Repository navigation
Expand file tree
/
Copy pathtrain.py
More file actions
3474 lines (3047 loc) · 143 KB
/
Copy pathtrain.py
File metadata and controls
3474 lines (3047 loc) · 143 KB
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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
"""
A minimal training script for DiT using PyTorch DDP.
"""
import torch
# the first flag below was False when we tested this script but True makes A100 training a lot faster:
torch.backends.cuda.matmul.allow_tf32 = True
torch.backends.cudnn.allow_tf32 = True
import torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel as DDP
from torch.utils.data import DataLoader, Dataset, Sampler
from torch.utils.data.dataloader import default_collate
from torch.utils.data.distributed import DistributedSampler
from torch.utils.tensorboard import SummaryWriter
from torchvision.datasets import ImageFolder
from torchvision import transforms
import torch.nn.functional as F
import numpy as np
from collections import OrderedDict, Counter
from PIL import Image
from copy import deepcopy
from glob import glob
from time import time
import argparse
import logging
import os
import sys
import json
import csv
import hashlib
import heapq
import math
from models import DiT_models
from diffusion import create_diffusion
from diffusion.gaussian_diffusion import _extract_into_tensor
from diffusers.models import AutoencoderKL
from torchvision.utils import make_grid, save_image
from ldm.modules.adapter import MultiModalAdapterManager
try:
from skimage.metrics import structural_similarity
SKIMAGE_AVAILABLE = True
except Exception:
SKIMAGE_AVAILABLE = False
#################################################################################
# Training Helper Functions #
#################################################################################
@torch.no_grad()
def update_ema(ema_model, model, decay=0.9999):
"""
Step the EMA model towards the current model.
"""
ema_params = OrderedDict(ema_model.named_parameters())
model_params = OrderedDict(model.named_parameters())
for name, param in model_params.items():
# TODO: Consider applying only to params that require_grad to avoid small numerical changes of pos_embed
ema_params[name].mul_(decay).add_(param.data, alpha=1 - decay)
def requires_grad(model, flag=True):
"""
Set requires_grad flag for all parameters in a model.
"""
for p in model.parameters():
p.requires_grad = flag
def cleanup():
"""
End DDP training.
"""
dist.destroy_process_group()
def create_logger(logging_dir):
"""
Create a logger that writes to a log file and stdout.
"""
if dist.get_rank() == 0: # real logger
logging.basicConfig(
level=logging.INFO,
format='[\033[34m%(asctime)s\033[0m] %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
handlers=[logging.StreamHandler(), logging.FileHandler(f"{logging_dir}/log.txt")]
)
logger = logging.getLogger(__name__)
else: # dummy logger (does nothing)
logger = logging.getLogger(__name__)
logger.addHandler(logging.NullHandler())
return logger
def _count_params(m, only_trainable=False):
if m is None:
return 0
if hasattr(m, "module"):
m = m.module
total = 0
for p in m.parameters():
if only_trainable and (not bool(getattr(p, "requires_grad", False))):
continue
total += int(p.numel())
return int(total)
def _log_config_summary(
*,
args,
logger,
rank,
device,
world_size,
use_manifest,
resumed,
train_steps,
dataset,
loader,
ae_models_by_id,
ae_info_by_modality,
pair_weight_table,
model,
ema,
eval_loaders,
):
if int(rank) != 0:
return
def _yn(v):
return if bool(v) else
def _on(v):
return if bool(v) else
per_gpu_batch = int(args.global_batch_size // max(1, int(world_size)))
mods = [str(m).lower() for m in (getattr(args, "modalities", []) or [])]
main_target = "x0" if bool(getattr(args, "predict_xstart", False)) else "eps"
main_snr_gamma = getattr(args, "x0_loss_snr_gamma", None)
main_snr_gamma = None if main_snr_gamma is None else float(main_snr_gamma)
wmin = None
wmax = None
if pair_weight_table is not None:
try:
wmin = float(pair_weight_table.min().item())
wmax = float(pair_weight_table.max().item())
except Exception:
wmin = None
wmax = None
ae_lines = []
if isinstance(ae_info_by_modality, dict) and ae_info_by_modality:
for m in mods:
meta = ae_info_by_modality.get(m, None)
if isinstance(meta, dict):
ck = meta.get("ckpt_resolved", None)
used = meta.get("used_override", None)
eval_lines = []
if isinstance(eval_loaders, dict) and eval_loaders:
items = []
for _, it in eval_loaders.items():
try:
split = str(it.get("split", ""))
pair_tag = str(it.get("pair_tag", ""))
ld = it.get("loader")
n = "?" if ld is None else str(len(getattr(ld, "dataset", [])))
items.append(f"{split}:{pair_tag}(n={n})")
except Exception:
continue
if items:
s = ", ".join(items[:12])
if len(items) > 12:
eval_lines.append(f"- : {s}")
dit_total = int(_count_params(model, only_trainable=False))
dit_train = int(_count_params(model, only_trainable=True))
ema_total = int(_count_params(ema, only_trainable=False))
ema_train = int(_count_params(ema, only_trainable=True))
ae_total = 0
ae_train = 0
if isinstance(ae_models_by_id, dict):
for _, ae in ae_models_by_id.items():
ae_total += int(_count_params(ae, only_trainable=False))
ae_train += int(_count_params(ae, only_trainable=True))
lines = []
lines.append("=" * 80)
if bool(use_manifest):
lines.append(f" - manifest={str(getattr(args, 'manifest_file', ''))}")
lines.append(f" - base_dir={str(getattr(args, 'manifest_base_dir', None))}")
lines.append(f"- : {mod_map}")
lsf = getattr(args, "latent_scale_factors_resolved", None)
if isinstance(lsf, dict) and lsf:
lines.append(
)
else:
else:
gamma_str = if main_snr_gamma is None else str(main_snr_gamma)
if bool(use_manifest) and bool(getattr(args, "pair_loss_reweight", True)):
extra = ""
if (wmin is not None) and (wmax is not None):
lines.append(
% (
float(getattr(args, "pair_loss_reweight_alpha", 0.5)),
float(getattr(args, "pair_loss_reweight_min", 0.25)),
float(getattr(args, "pair_loss_reweight_max", 4.0)),
extra,
)
)
else:
lines.append("- : ")
lines.append(
% (int(dit_total), int(dit_train), int(ema_total), int(ema_train), int(ae_total), int(ae_train))
)
lines.append(
% (
_yn(getattr(args, "run_eval", True)),
_yn(getattr(args, "eval_preflight", True)),
_yn(getattr(args, "eval_distributed", False)),
int(getattr(args, "eval_batch_size", 0)),
str(getattr(args, "eval_num_samples", None)),
int(getattr(args, "eval_vis_samples", 0)),
str(getattr(args, "eval_sampler", "ddim")),
int(getattr(args, "eval_num_sampling_steps", 0)),
float(getattr(args, "eval_cfg_scale", 1.0)),
_yn(getattr(args, "eval_use_ema", True)),
)
)
lines.append(
% (
_yn(getattr(args, "eval_enable_fid", False)),
_yn(getattr(args, "eval_enable_lpips", False)),
_yn(getattr(args, "eval_allow_download", True)),
)
)
if ae_lines:
lines.append("- AE:")
lines.extend(ae_lines)
if eval_lines:
lines.extend(eval_lines)
lines.append("=" * 80)
logger.info("\n".join(lines))
def center_crop_arr(pil_image, image_size):
"""
Center cropping implementation from ADM.
https://github.com/openai/guided-diffusion/blob/8fb3ad9197f16bbc40620447b2742e13458d2831/guided_diffusion/image_datasets.py#L126
"""
while min(*pil_image.size) >= 2 * image_size:
pil_image = pil_image.resize(
tuple(x // 2 for x in pil_image.size), resample=Image.BOX
)
scale = image_size / min(*pil_image.size)
pil_image = pil_image.resize(
tuple(round(x * scale) for x in pil_image.size), resample=Image.BICUBIC
)
arr = np.array(pil_image)
crop_y = (arr.shape[0] - image_size) // 2
crop_x = (arr.shape[1] - image_size) // 2
return Image.fromarray(arr[crop_y: crop_y + image_size, crop_x: crop_x + image_size])
def _add_unitransfer_to_path(uni_root):
uni_root = os.path.abspath(uni_root)
if uni_root not in sys.path:
sys.path.append(uni_root)
taming_root = os.path.join(uni_root, "taming-transformers")
if os.path.isdir(taming_root) and taming_root not in sys.path:
sys.path.append(taming_root)
def _parse_kv_list(kvs):
if kvs is None:
return {}
out = {}
for item in kvs:
if "=" not in item:
raise ValueError(f"Expected key=value, got: {item}")
k, v = item.split("=", 1)
out[str(k).strip().lower()] = str(v).strip()
return out
def _parse_latent_scale_factors(latent_scale_factors, modalities, default_scale_factor):
mods = [str(m).strip().lower() for m in (modalities or [])]
base = {m: float(default_scale_factor) for m in mods}
kv = _parse_kv_list(latent_scale_factors)
provided = set()
for k, v in kv.items():
kk = "opt" if str(k).strip().lower() == "rgb" else str(k).strip().lower()
if kk not in base:
raise ValueError(f"Unknown modality in --latent-scale-factors: {k} (known={mods})")
if kk in provided:
raise ValueError(f"Duplicate modality in --latent-scale-factors: {k} (normalized={kk})")
provided.add(kk)
base[kk] = float(v)
if latent_scale_factors is not None:
if len(provided) == 0:
raise ValueError(
"--latent-scale-factors was provided but no valid entries were parsed. "
"Expected format like: sar=0.42 opt=0.38 ms=0.48 nir=0.56 pan=0.44"
)
missing = [m for m in mods if m not in provided]
if missing:
raise ValueError(
f"Strict mode: --latent-scale-factors must cover all --modalities. Missing: {missing}. "
f"Provided(normalized): {sorted(provided)}. Expected: {mods}"
)
return base
def _str2bool(v):
if isinstance(v, bool):
return v
if v is None:
raise argparse.ArgumentTypeError("Expected a boolean")
s = str(v).strip().lower()
if s in ("true", "1", "yes", "y", "t"):
return True
if s in ("false", "0", "no", "n", "f"):
return False
raise argparse.ArgumentTypeError(f"Expected a boolean, got: {v}")
def _resolve_manifest_path(path, base_dir):
if path is None:
return path
p = str(path)
if os.path.isabs(p) or (len(p) >= 2 and p[1] == ":"):
return p
if base_dir is None:
return p
b = os.path.abspath(str(base_dir))
p = p.lstrip("/").lstrip("\\")
return os.path.normpath(os.path.join(b, p))
def _infer_manifest_dataset_name(path):
if path is None:
return None
s = str(path).replace("\\", "/")
parts = [p for p in s.split("/") if p]
try:
i = parts.index("Images")
except ValueError:
return None
if i + 1 >= len(parts):
return None
root = str(parts[i + 1])
if root.lower() == "spacenet" and i + 2 < len(parts):
return str(parts[i + 2])
return root
class BalancedDistributedSampler(Sampler):
def __init__(
self,
dataset,
group_keys,
num_replicas=None,
rank=None,
shuffle=True,
seed=0,
drop_last=False,
batch_size=None,
cover_all=False,
):
if num_replicas is None:
num_replicas = dist.get_world_size() if dist.is_available() and dist.is_initialized() else 1
if rank is None:
rank = dist.get_rank() if dist.is_available() and dist.is_initialized() else 0
self.dataset = dataset
self.group_keys = list(group_keys) if group_keys is not None else []
self.num_replicas = int(num_replicas)
self.rank = int(rank)
self.shuffle = bool(shuffle)
self.seed = int(seed)
self.drop_last = bool(drop_last)
self.batch_size = None if batch_size is None else int(batch_size)
self.cover_all = bool(cover_all)
self.epoch = 0
self._last_full_indices = None
if len(self.group_keys) != len(self.dataset):
raise ValueError(f"group_keys length must match dataset length: {len(self.group_keys)} vs {len(self.dataset)}")
self.group_to_indices = {}
for i, k in enumerate(self.group_keys):
kk = "unknown" if k is None else str(k)
self.group_to_indices.setdefault(kk, []).append(int(i))
if not self.group_to_indices:
self.group_to_indices = {"unknown": list(range(len(self.dataset)))}
if self.cover_all and self.group_to_indices:
max_len = max(int(len(v)) for v in self.group_to_indices.values())
desired_total = int(max_len * max(1, len(self.group_to_indices)))
self.num_samples = int(math.ceil(desired_total / float(self.num_replicas)))
else:
if self.drop_last:
self.num_samples = int(math.floor(len(self.dataset) / self.num_replicas))
else:
self.num_samples = int(math.ceil(len(self.dataset) / self.num_replicas))
if self.batch_size is not None and self.batch_size > 0:
self.num_samples = int(math.ceil(self.num_samples / float(self.batch_size)) * self.batch_size)
self.total_size = int(self.num_samples * self.num_replicas)
def __iter__(self):
g = torch.Generator()
g.manual_seed(self.seed + self.epoch)
groups = list(self.group_to_indices.keys())
if self.shuffle and len(groups) > 1:
p = torch.randperm(len(groups), generator=g).tolist()
groups = [groups[i] for i in p]
pools = {}
ptr = {}
for k in groups:
idx = list(self.group_to_indices.get(k, []))
if not idx:
continue
if self.shuffle and len(idx) > 1:
p = torch.randperm(len(idx), generator=g).tolist()
idx = [idx[i] for i in p]
pools[k] = idx
ptr[k] = 0
if not pools:
indices = list(range(len(self.dataset)))
else:
indices = []
group_list = list(pools.keys())
n_groups = len(group_list)
for i in range(int(self.total_size)):
k = group_list[i % n_groups]
p = int(ptr[k])
if p < len(pools[k]):
indices.append(int(pools[k][p]))
ptr[k] = p + 1
else:
base = self.group_to_indices.get(k, [])
if not base:
indices.append(int(torch.randint(0, len(self.dataset), (1,), generator=g).item()))
else:
j = int(torch.randint(0, len(base), (1,), generator=g).item())
indices.append(int(base[j]))
if len(indices) < self.total_size:
indices += indices[: int(self.total_size - len(indices))]
indices = indices[: int(self.total_size)]
self._last_full_indices = list(indices)
start = int(self.rank * self.num_samples)
end = int(start + self.num_samples)
return iter(indices[start:end])
def __len__(self):
return int(self.num_samples)
def set_epoch(self, epoch):
self.epoch = int(epoch)
def get_last_full_indices(self):
if self._last_full_indices is None:
return None
return list(self._last_full_indices)
def _fid_from_features(fp, fg):
fp = fp.double()
fg = fg.double()
mu1 = fp.mean(dim=0)
mu2 = fg.mean(dim=0)
xc1 = fp - mu1
xc2 = fg - mu2
cov1 = (xc1.t() @ xc1) / max(1, fp.shape[0] - 1)
cov2 = (xc2.t() @ xc2) / max(1, fg.shape[0] - 1)
eps = 1e-6
cov1 = cov1 + torch.eye(cov1.shape[0], dtype=cov1.dtype) * eps
cov2 = cov2 + torch.eye(cov2.shape[0], dtype=cov2.dtype) * eps
e1, v1 = torch.linalg.eigh(cov1)
e1 = torch.clamp(e1, min=0)
s1 = (v1 * torch.sqrt(e1).unsqueeze(0)) @ v1.t()
a = s1 @ cov2 @ s1
ea = torch.linalg.eigvalsh(a)
ea = torch.clamp(ea, min=0)
tr_covmean = torch.sum(torch.sqrt(ea))
return float(((mu1 - mu2).pow(2).sum() + torch.trace(cov1) + torch.trace(cov2) - 2.0 * tr_covmean).item())
def _default_ae_config_path(uni_root, latent_size, latent_channels, modality_lower):
name = f"autoencoder_kl_{latent_size}x{latent_size}x{latent_channels}_local_{modality_lower}.yaml"
return os.path.join(uni_root, "configs", "autoencoder", name)
def _load_unitransfer_ae_and_norm(uni_root, config_path, device, ckpt_override=None):
from omegaconf import OmegaConf
from ldm.util import instantiate_from_config
config_path = os.path.abspath(str(config_path))
cfg = OmegaConf.load(config_path)
model_cfg = cfg["model"]
model_dict = OmegaConf.to_container(model_cfg, resolve=True)
params = dict(model_dict.get("params", {}))
ckpt_from_config = params.get("ckpt_path", None)
ckpt_from_config = None if ckpt_from_config is None else str(ckpt_from_config)
ckpt_override = None if ckpt_override is None else str(ckpt_override)
used_override = ckpt_override is not None
ckpt_chosen = ckpt_override if used_override else ckpt_from_config
ckpt_resolved = None
if ckpt_chosen is not None:
ckpt_resolved = str(ckpt_chosen)
if not os.path.isabs(ckpt_resolved):
ckpt_resolved = os.path.join(uni_root, ckpt_resolved)
ckpt_resolved = os.path.abspath(ckpt_resolved)
if not os.path.isfile(ckpt_resolved):
raise FileNotFoundError(
f"AE checkpoint not found: {ckpt_resolved} (config={config_path}, override={ckpt_override}, config_ckpt={ckpt_from_config})"
)
params["ckpt_path"] = ckpt_resolved
params["lossconfig"] = {"target": "torch.nn.Identity"}
model = instantiate_from_config({"target": model_dict["target"], "params": params})
model = model.to(device)
model.eval()
requires_grad(model, False)
data_train_params = {}
try:
data_train_params = OmegaConf.to_container(cfg["data"]["params"]["train"]["params"], resolve=True)
except Exception:
data_train_params = {}
norm_cfg = {
"normalization": data_train_params.get("normalization", "uint8"),
"data_min": data_train_params.get("data_min", None),
"data_max": data_train_params.get("data_max", None),
"normalize_per_channel": data_train_params.get("normalize_per_channel", False),
"stats_file": data_train_params.get("stats_file", None),
"raw_size": data_train_params.get("size", None),
}
stats_file = norm_cfg.get("stats_file", None)
if stats_file is not None and not os.path.isabs(str(stats_file)):
norm_cfg["stats_file"] = os.path.join(uni_root, str(stats_file))
meta = {
"config_path": config_path,
"ckpt_from_config": ckpt_from_config,
"ckpt_override": ckpt_override,
"ckpt_resolved": ckpt_resolved,
"used_override": bool(used_override),
}
return model, norm_cfg, meta
@torch.no_grad()
def _encode_raw_list_to_latents(
raw_list,
mod_ids_cpu,
ae_models_by_id,
latent_size,
latent_channels,
latent_scale_factor,
device,
strict_no_resize=False,
):
b = len(raw_list)
out = torch.zeros(b, latent_channels, latent_size, latent_size, device=device)
for mod_id, ae in ae_models_by_id.items():
idx_all = (mod_ids_cpu == int(mod_id)).nonzero(as_tuple=False).flatten().tolist()
idx = [i for i in idx_all if raw_list[i] is not None]
if len(idx) == 0:
continue
xs = torch.stack([raw_list[i] for i in idx], dim=0).to(device, non_blocking=True)
posterior = ae.encode(xs)
z = posterior.sample()
if z.shape[-1] != latent_size or z.shape[-2] != latent_size:
if bool(strict_no_resize):
raise ValueError(
f"VAE latent spatial size mismatch for mod_id={int(mod_id)}: got {tuple(z.shape[-2:])}, expected {(int(latent_size), int(latent_size))}. "
f"This run forbids any resize; fix the input raw resolution or the AE config downsampling."
)
z = F.interpolate(z, size=(latent_size, latent_size), mode="bilinear", align_corners=False)
sf = latent_scale_factor
if isinstance(latent_scale_factor, dict):
sf = latent_scale_factor.get(int(mod_id), 1.0)
sf = float(sf)
if sf != 1.0:
z = z * sf
out[idx] = z
return out
class ManifestLatentPairDataset(Dataset):
def __init__(
self,
manifest_file,
modalities,
conditioning_mode,
enable_any_to_all=True,
allowed_pairs=None,
augment=True,
latent_size=None,
latent_scale_factor=1.0,
latent_scale_factors=None,
base_dir=None,
):
self.modalities = [m.lower() for m in modalities]
self.mod2id = {m: i for i, m in enumerate(self.modalities)}
self.conditioning_mode = conditioning_mode
self.enable_any_to_all = bool(enable_any_to_all)
self.augment = bool(augment)
self.latent_size = None if latent_size is None else int(latent_size)
self.latent_scale_factor = float(latent_scale_factor)
self.latent_scale_factors = None
if latent_scale_factors is not None:
self.latent_scale_factors = {str(k).strip().lower(): float(v) for k, v in dict(latent_scale_factors).items()}
self.base_dir = None if base_dir is None else str(base_dir)
if allowed_pairs is None:
self.allowed_pairs_set = None
else:
pairs_set = set()
for p in allowed_pairs:
if isinstance(p, str) and "->" in p:
s, t = p.split("->", 1)
pairs_set.add((s.strip().lower(), t.strip().lower()))
elif isinstance(p, (tuple, list)) and len(p) == 2:
pairs_set.add((str(p[0]).strip().lower(), str(p[1]).strip().lower()))
else:
raise ValueError(f"Unsupported allowed_pairs entry: {p}")
self.allowed_pairs_set = pairs_set
with open(manifest_file, "r") as f:
manifest = json.load(f)
self.samples = list(manifest.values()) if isinstance(manifest, dict) else list(manifest)
self.pair_group_keys = []
self.pairs = []
if self.conditioning_mode == "none":
for idx, sample in enumerate(self.samples):
available = [
m
for m in self.modalities
if any(
(str(k).lower() == m) or (m == "opt" and str(k).lower() == "rgb")
for k in sample.keys()
)
]
for tgt_mod in available:
self.pairs.append({"sample_idx": idx, "src_mod": None, "tgt_mod": tgt_mod})
self.pair_group_keys.append(f"{tgt_mod}->{tgt_mod}")
else:
for idx, sample in enumerate(self.samples):
available = [
m
for m in self.modalities
if any(
(str(k).lower() == m) or (m == "opt" and str(k).lower() == "rgb")
for k in sample.keys()
)
]
if len(available) < 2:
continue
if self.enable_any_to_all:
for src_mod in available:
for tgt_mod in available:
if src_mod == tgt_mod:
continue
if self.allowed_pairs_set is not None and (src_mod, tgt_mod) not in self.allowed_pairs_set:
continue
self.pairs.append({"sample_idx": idx, "src_mod": src_mod, "tgt_mod": tgt_mod})
self.pair_group_keys.append(f"{src_mod}->{tgt_mod}")
else:
for i, src_mod in enumerate(available):
for tgt_mod in available[i + 1 :]:
if self.allowed_pairs_set is None or (src_mod, tgt_mod) in self.allowed_pairs_set:
self.pairs.append({"sample_idx": idx, "src_mod": src_mod, "tgt_mod": tgt_mod})
self.pair_group_keys.append(f"{src_mod}->{tgt_mod}")
if self.allowed_pairs_set is None or (tgt_mod, src_mod) in self.allowed_pairs_set:
self.pairs.append({"sample_idx": idx, "src_mod": tgt_mod, "tgt_mod": src_mod})
self.pair_group_keys.append(f"{tgt_mod}->{src_mod}")
def __len__(self):
return len(self.pairs)
def _get_path(self, sample, modality_lower):
for k, v in sample.items():
kl = str(k).lower()
if kl == modality_lower:
return _resolve_manifest_path(v, self.base_dir)
if modality_lower == "opt" and kl == "rgb":
return _resolve_manifest_path(v, self.base_dir)
raise KeyError(modality_lower)
def _load_latent(self, path, modality_lower):
arr = np.load(path)
if arr.ndim == 2:
arr = arr[None, :, :]
elif arr.ndim == 3:
if arr.shape[0] <= 16:
pass
elif arr.shape[2] <= 16:
arr = arr.transpose(2, 0, 1)
else:
pass
else:
raise ValueError(f"Unsupported latent shape: {arr.shape} from {path}")
x = torch.from_numpy(arr).float()
if self.latent_size is not None and (x.shape[1] != self.latent_size or x.shape[2] != self.latent_size):
x = F.interpolate(x.unsqueeze(0), size=(self.latent_size, self.latent_size), mode="bilinear", align_corners=False).squeeze(0)
sf = float(self.latent_scale_factor)
if self.latent_scale_factors is not None:
sf = float(self.latent_scale_factors.get(str(modality_lower).strip().lower(), sf))
if sf != 1.0:
x = x * sf
return x
def __getitem__(self, idx):
pair = self.pairs[idx]
sample = self.samples[pair["sample_idx"]]
tgt_mod = pair["tgt_mod"]
tgt_path = self._get_path(sample, tgt_mod)
x = self._load_latent(tgt_path, tgt_mod)
if pair["src_mod"] is None:
cond = torch.zeros_like(x)
src_mod = tgt_mod
else:
src_mod = pair["src_mod"]
src_path = self._get_path(sample, src_mod)
cond = self._load_latent(src_path, src_mod)
if self.augment:
if torch.rand(()) < 0.5:
x = torch.flip(x, dims=[2])
cond = torch.flip(cond, dims=[2])
if torch.rand(()) < 0.5:
x = torch.flip(x, dims=[1])
cond = torch.flip(cond, dims=[1])
return {
"x": x,
"cond": cond,
"src_mod": torch.tensor(self.mod2id[src_mod], dtype=torch.long),
"tgt_mod": torch.tensor(self.mod2id[tgt_mod], dtype=torch.long),
}
class ManifestRawPairDataset(Dataset):
def __init__(
self,
manifest_file,
modalities,
conditioning_mode,
enable_any_to_all=True,
allowed_pairs=None,
augment=True,
size=None,
normalization_configs=None,
no_resize=False,
base_dir=None,
balance_key=None,
):
self.modalities = [m.lower() for m in modalities]
self.mod2id = {m: i for i, m in enumerate(self.modalities)}
self.conditioning_mode = str(conditioning_mode)
self.enable_any_to_all = bool(enable_any_to_all)
self.augment = bool(augment)
self.size = None if size is None else int(size)
self.base_dir = None if base_dir is None else str(base_dir)
self.balance_key = None if balance_key is None else str(balance_key)
if allowed_pairs is None:
self.allowed_pairs_set = None
else:
pairs_set = set()
for p in allowed_pairs:
if isinstance(p, str) and "->" in p:
s, t = p.split("->", 1)
pairs_set.add((s.strip().lower(), t.strip().lower()))
elif isinstance(p, (tuple, list)) and len(p) == 2:
pairs_set.add((str(p[0]).strip().lower(), str(p[1]).strip().lower()))
else:
raise ValueError(f"Unsupported allowed_pairs entry: {p}")
self.allowed_pairs_set = pairs_set
with open(manifest_file, "r") as f:
manifest = json.load(f)
self.samples = list(manifest.values()) if isinstance(manifest, dict) else list(manifest)
self.sample_group_keys = []
bk = "modality_set" if self.balance_key is None else str(self.balance_key).strip().lower()
for sample in self.samples:
key = None
if isinstance(sample, dict) and bk == "modality_set":
present = set()
for k in sample.keys():
kl = str(k).strip().lower()
if kl == "rgb":
kl = "opt"
if kl in self.modalities:
present.add(kl)
if present:
key = "+".join(sorted(present))
elif isinstance(sample, dict) and bk not in ["infer", ""]:
for k, v in sample.items():
if str(k).strip().lower() == bk:
key = v
break
if key is None and isinstance(sample, dict):
p = None
for _, v in sample.items():
if isinstance(v, str) and v:
p = v
break
key = _infer_manifest_dataset_name(p)
self.sample_group_keys.append("unknown" if key is None else str(key))
self.pair_group_keys = []
from ldm.util.normalization import NormalizationManager
self.no_resize = bool(no_resize)
if normalization_configs is None:
normalization_configs = {}
self.norm_managers = {}
self.modality_raw_sizes = {}
for m in self.modalities:
cfg = normalization_configs.get(m, {})
self.norm_managers[m] = NormalizationManager(
normalization=cfg.get("normalization", "uint8"),
data_min=cfg.get("data_min", None),
data_max=cfg.get("data_max", None),
normalize_per_channel=cfg.get("normalize_per_channel", False),
stats_file=cfg.get("stats_file", None),
)
self.modality_raw_sizes[m] = cfg.get("raw_size", None)
self.pairs = []
if self.conditioning_mode == "none":
for idx, sample in enumerate(self.samples):
available = [
m
for m in self.modalities
if any(
(str(k).lower() == m) or (m == "opt" and str(k).lower() == "rgb")
for k in sample.keys()
)
]
for tgt_mod in available:
self.pairs.append({"sample_idx": idx, "src_mod": None, "tgt_mod": tgt_mod})
if bk == "pair":
self.pair_group_keys.append(f"{tgt_mod}->{tgt_mod}")
else:
self.pair_group_keys.append(self.sample_group_keys[idx])
else:
for idx, sample in enumerate(self.samples):
available = [
m
for m in self.modalities
if any(
(str(k).lower() == m) or (m == "opt" and str(k).lower() == "rgb")
for k in sample.keys()
)
]
if len(available) < 2:
continue
if self.enable_any_to_all:
for src_mod in available:
for tgt_mod in available:
if src_mod == tgt_mod:
continue
if self.allowed_pairs_set is not None and (src_mod, tgt_mod) not in self.allowed_pairs_set:
continue
self.pairs.append({"sample_idx": idx, "src_mod": src_mod, "tgt_mod": tgt_mod})
if bk == "pair":
self.pair_group_keys.append(f"{src_mod}->{tgt_mod}")
else:
self.pair_group_keys.append(self.sample_group_keys[idx])
else:
for i, src_mod in enumerate(available):
for tgt_mod in available[i + 1 :]:
if self.allowed_pairs_set is None or (src_mod, tgt_mod) in self.allowed_pairs_set:
self.pairs.append({"sample_idx": idx, "src_mod": src_mod, "tgt_mod": tgt_mod})
if bk == "pair":
self.pair_group_keys.append(f"{src_mod}->{tgt_mod}")
else:
self.pair_group_keys.append(self.sample_group_keys[idx])
if self.allowed_pairs_set is None or (tgt_mod, src_mod) in self.allowed_pairs_set:
self.pairs.append({"sample_idx": idx, "src_mod": tgt_mod, "tgt_mod": src_mod})
if bk == "pair":
self.pair_group_keys.append(f"{tgt_mod}->{src_mod}")
else:
self.pair_group_keys.append(self.sample_group_keys[idx])
def __len__(self):
return len(self.pairs)
def _get_path(self, sample, modality_lower):
for k, v in sample.items():
kl = str(k).lower()
if kl == modality_lower:
return _resolve_manifest_path(v, self.base_dir)
if modality_lower == "opt" and kl == "rgb":
return _resolve_manifest_path(v, self.base_dir)
raise KeyError(modality_lower)
def _process_image_shape(self, arr):
if arr.ndim == 2:
return arr[None, :, :]
if arr.ndim == 3:
if arr.shape[0] <= 16:
return arr
if arr.shape[2] <= 16:
return arr.transpose(2, 0, 1)
return arr
raise ValueError(f"Unsupported array shape: {arr.shape}")
def _load_image(self, path, modality_lower):
arr = np.load(path)
arr = self._process_image_shape(arr)
arr = self.norm_managers[modality_lower].normalize(arr)
x = torch.from_numpy(arr).float()
expected = self.size
mod_expected = self.modality_raw_sizes.get(modality_lower, None)
if mod_expected is not None:
try:
mod_expected = int(mod_expected)
except Exception:
mod_expected = None
if expected is None and mod_expected is not None:
expected = mod_expected
if expected is not None and (x.shape[1] != int(expected) or x.shape[2] != int(expected)):
if self.no_resize:
raise ValueError(
f"Raw size mismatch for modality '{modality_lower}': got {(int(x.shape[1]), int(x.shape[2]))}, expected {(int(expected), int(expected))}. "
f"This run forbids any resize; fix the .npy shapes or the AE config 'data.params.train.params.size'."
)
x = F.interpolate(x.unsqueeze(0), size=(int(expected), int(expected)), mode="bilinear", align_corners=False).squeeze(0)
return x
def __getitem__(self, idx):
pair = self.pairs[idx]
sample = self.samples[pair["sample_idx"]]
tgt_mod = pair["tgt_mod"]
tgt_path = self._get_path(sample, tgt_mod)
x_raw = self._load_image(tgt_path, tgt_mod)
if pair["src_mod"] is None:
cond_raw = None
src_mod = tgt_mod
else:
src_mod = pair["src_mod"]
src_path = self._get_path(sample, src_mod)
cond_raw = self._load_image(src_path, src_mod)