Text-to-Image
Diffusers
Safetensors
recoilme commited on
Commit
23e187f
·
1 Parent(s): 9ce807a
Files changed (1) hide show
  1. train.py +45 -42
train.py CHANGED
@@ -57,7 +57,7 @@ torch_compile = False
57
  unet_gradient = True
58
  loss_normalize = False
59
  fixed_seed = False
60
- shuffle = False
61
  comet_ml_api_key = "Agctp26mbqnoYrrlvQuKSTk6r"
62
  comet_ml_workspace = "recoilme"
63
  torch.backends.cuda.matmul.allow_tf32 = True
@@ -247,68 +247,71 @@ if mean is not None and std is not None:
247
  class DistributedResolutionBatchSampler(Sampler):
248
  def __init__(self, dataset, batch_size, num_replicas, rank, drop_last=True, shuffle=False):
249
  self.dataset = dataset
250
- self.batch_size = max(1, batch_size // num_replicas)
251
  self.num_replicas = num_replicas
252
  self.rank = rank
253
  self.drop_last = drop_last
254
  self.shuffle = shuffle
255
  self.epoch = 0
256
-
 
 
 
 
257
  try:
258
  widths = np.array(dataset["width"])
259
  heights = np.array(dataset["height"])
260
  except KeyError:
261
  widths = np.zeros(len(dataset))
262
  heights = np.zeros(len(dataset))
263
-
264
- # Группируем индексы по размерам
265
- self.size_keys = np.unique(np.stack([widths, heights], axis=1), axis=0)
266
  self.size_groups = {}
267
- for w, h in self.size_keys:
268
- mask = (widths == w) & (heights == h)
269
- self.size_groups[(w, h)] = np.where(mask)[0]
270
-
271
- self.group_num_batches = {}
272
- total_batches = 0
273
- for size, indices in self.size_groups.items():
274
- num_full_batches = len(indices) // (self.batch_size * self.num_replicas)
275
- self.group_num_batches[size] = num_full_batches
276
- total_batches += num_full_batches
277
-
278
- self.num_batches = total_batches
279
-
280
  def __iter__(self):
281
- all_batches = []
282
  rng = np.random.RandomState(self.epoch)
283
-
284
- for size, indices in self.size_groups.items():
285
- indices = indices.copy()
 
 
 
286
  if self.shuffle:
287
- rng.shuffle(indices) # Перемешиваем внутри группы
288
-
289
- num_full_batches = self.group_num_batches[size]
290
- if num_full_batches == 0:
291
  continue
292
-
293
- # Берем только индексы, кратные полному размеру батча (batch_size * num_replicas)
294
- valid_indices = indices[:num_full_batches * self.batch_size * self.num_replicas]
295
- # Формируем сетку батчей
296
- batches = valid_indices.reshape(-1, self.batch_size * self.num_replicas)
297
-
298
- # Выбираем чанк для конкретного GPU
299
- start_idx = self.rank * self.batch_size
300
- gpu_batches = batches[:, start_idx : start_idx + self.batch_size]
301
- all_batches.extend(gpu_batches.tolist())
302
 
303
- # Перемешиваем батчи разных разрешений между собой
 
 
 
 
304
  if self.shuffle:
305
- rng.shuffle(all_batches)
306
 
307
- accelerator.wait_for_everyone()
308
- return iter(all_batches)
 
 
 
 
 
309
 
310
  def __len__(self):
311
- return self.num_batches
312
 
313
  def set_epoch(self, epoch):
314
  self.epoch = epoch
 
57
  unet_gradient = True
58
  loss_normalize = False
59
  fixed_seed = False
60
+ shuffle = True
61
  comet_ml_api_key = "Agctp26mbqnoYrrlvQuKSTk6r"
62
  comet_ml_workspace = "recoilme"
63
  torch.backends.cuda.matmul.allow_tf32 = True
 
247
  class DistributedResolutionBatchSampler(Sampler):
248
  def __init__(self, dataset, batch_size, num_replicas, rank, drop_last=True, shuffle=False):
249
  self.dataset = dataset
 
250
  self.num_replicas = num_replicas
251
  self.rank = rank
252
  self.drop_last = drop_last
253
  self.shuffle = shuffle
254
  self.epoch = 0
255
+
256
+ # локальный batch для одной GPU
257
+ self.batch_size = max(1, batch_size // num_replicas)
258
+ self.global_batch = self.batch_size * self.num_replicas
259
+
260
  try:
261
  widths = np.array(dataset["width"])
262
  heights = np.array(dataset["height"])
263
  except KeyError:
264
  widths = np.zeros(len(dataset))
265
  heights = np.zeros(len(dataset))
266
+
267
+ # группировка индексов по (width, height)
 
268
  self.size_groups = {}
269
+ for i, (w, h) in enumerate(zip(widths, heights)):
270
+ self.size_groups.setdefault((w, h), []).append(i)
271
+
272
+ # переводим в numpy для скорости
273
+ for k in self.size_groups:
274
+ self.size_groups[k] = np.array(self.size_groups[k], dtype=np.int64)
275
+
276
+ # считаем общее число батчей
277
+ self.num_batches = sum(
278
+ len(indices) // self.global_batch
279
+ for indices in self.size_groups.values()
280
+ )
281
+
282
  def __iter__(self):
 
283
  rng = np.random.RandomState(self.epoch)
284
+
285
+ global_batches = []
286
+
287
+ for indices in self.size_groups.values():
288
+ idx = indices.copy()
289
+
290
  if self.shuffle:
291
+ rng.shuffle(idx)
292
+
293
+ num_batches = len(idx) // self.global_batch
294
+ if num_batches == 0:
295
  continue
 
 
 
 
 
 
 
 
 
 
296
 
297
+ idx = idx[:num_batches * self.global_batch]
298
+ batches = idx.reshape(num_batches, self.global_batch)
299
+
300
+ global_batches.extend(batches)
301
+
302
  if self.shuffle:
303
+ rng.shuffle(global_batches)
304
 
305
+ # split батча по GPU
306
+ start = self.rank * self.batch_size
307
+ end = start + self.batch_size
308
+
309
+ result = [batch[start:end] for batch in global_batches]
310
+
311
+ return iter(result)
312
 
313
  def __len__(self):
314
+ return self.num_batches
315
 
316
  def set_epoch(self, epoch):
317
  self.epoch = epoch