-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatasets.py
1786 lines (1436 loc) · 55.2 KB
/
datasets.py
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
from torch.utils.data import Dataset
from torchvision import datasets
import torchvision.transforms as transforms
import numpy as np
import torch
import math
import random
from PIL import Image
import os
import glob
import einops
import torchvision.transforms.functional as F
import h5py
from lfm_dataset.ffhq_from1024 import FFHQ_From1024
from lfm_dataset.real_img import Real_IMG
from pathlib import Path
from tqdm import tqdm
import os
import webdataset as wds
os.environ["WDS_VERBOSE_CACHE"] = "1"
class UnlabeledDataset(Dataset):
def __init__(self, dataset):
self.dataset = dataset
def __len__(self):
return len(self.dataset)
def __getitem__(self, item):
data = tuple(self.dataset[item][:-1]) # remove label
if len(data) == 1:
data = data[0]
return data
class LabeledDataset(Dataset):
def __init__(self, dataset, labels):
self.dataset = dataset
self.labels = labels
def __len__(self):
return len(self.dataset)
def __getitem__(self, item):
return self.dataset[item], self.labels[item]
class CFGDataset(Dataset): # for classifier free guidance
def __init__(self, dataset, p_uncond, empty_token):
self.dataset = dataset
self.p_uncond = p_uncond
self.empty_token = empty_token
def __len__(self):
return len(self.dataset)
def __getitem__(self, item):
x, y = self.dataset[item]
if random.random() < self.p_uncond:
y = self.empty_token
assert x is not None
assert y is not None
return x, y
class DatasetFactory(object):
def __init__(self):
self.train = None
self.test = None
def get_split(self, split, labeled=False):
if split == "train":
dataset = self.train
elif split == "test":
dataset = self.test
else:
raise ValueError
if self.has_label:
return dataset if labeled else UnlabeledDataset(dataset)
else:
assert not labeled
return dataset
def unpreprocess(self, v): # to B C H W and [0, 1]
v = 0.5 * (v + 1.0)
v.clamp_(0.0, 1.0)
return v
@property
def has_label(self):
return True
@property
def data_shape(self):
raise NotImplementedError
@property
def data_dim(self):
return int(np.prod(self.data_shape))
@property
def fid_stat(self):
return None
def sample_label(self, n_samples, device):
raise NotImplementedError
def label_prob(self, k):
raise NotImplementedError
# CIFAR10
class CIFAR10(DatasetFactory):
r"""CIFAR10 dataset
Information of the raw dataset:
train: 50,000
test: 10,000
shape: 3 * 32 * 32
"""
def __init__(self, path, random_flip=False, cfg=False, p_uncond=None):
super().__init__()
transform_train = [transforms.ToTensor(), transforms.Normalize(0.5, 0.5)]
transform_test = [transforms.ToTensor(), transforms.Normalize(0.5, 0.5)]
if random_flip: # only for train
transform_train.append(transforms.RandomHorizontalFlip())
transform_train = transforms.Compose(transform_train)
transform_test = transforms.Compose(transform_test)
self.train = datasets.CIFAR10(
path, train=True, transform=transform_train, download=True
)
self.test = datasets.CIFAR10(
path, train=False, transform=transform_test, download=True
)
assert len(self.train.targets) == 50000
self.K = max(self.train.targets) + 1
self.cnt = torch.tensor(
[len(np.where(np.array(self.train.targets) == k)[0]) for k in range(self.K)]
).float()
self.frac = [self.cnt[k] / 50000 for k in range(self.K)]
print(f"{self.K} classes")
print(f"cnt: {self.cnt}")
print(f"frac: {self.frac}")
if cfg: # classifier free guidance
assert p_uncond is not None
print(
f"prepare the dataset for classifier free guidance with p_uncond={p_uncond}"
)
self.train = CFGDataset(self.train, p_uncond, self.K)
@property
def data_shape(self):
return 3, 32, 32
@property
def fid_stat(self):
return "assets/fid_stats/fid_stats_cifar10_train_pytorch.npz"
def sample_label(self, n_samples, device):
return torch.multinomial(self.cnt, n_samples, replacement=True).to(device)
def label_prob(self, k):
return self.frac[k]
# ImageNet
class FeatureDataset_256_NPY(Dataset): # used for h5_extract_npy_h5
def __init__(self, path, debug=False):
super().__init__()
self.path = path
# names = sorted(os.listdir(path))
# self.files = [os.path.join(path, name) for name in names]
self.debug = debug
# test
path = os.path.join(self.path, f"0.npy")
z, label = np.load(path, allow_pickle=True)
print(z.shape, z.dtype, label.shape, label.dtype)
def __len__(self):
if self.debug:
return 220_000
else:
return 1_281_167 * 2 # consider the random flip
def __getitem__(self, idx):
path = os.path.join(self.path, f"{idx}.npy")
z, label = np.load(path, allow_pickle=True)
return z, label
class FeatureDataset_IN_Cluster_H5(Dataset):
def __init__(self, path, path_cluster, debug=False):
super().__init__()
self.path = path
self.path_cluster = path_cluster
# names = sorted(os.listdir(path))
# self.files = [os.path.join(path, name) for name in names]
self.debug = debug
print("Loading images from %s into memory..." % self.path_cluster)
with h5py.File(self.path_cluster, "r") as f:
if debug:
self.cluster_assignment = f["cluster_assignment"][:10_000] # [N, 1]
else:
self.cluster_assignment = f["cluster_assignment"][:] # [N, 1
print(
"cluster_assignment",
self.cluster_assignment.shape,
self.cluster_assignment.dtype,
)
with h5py.File(self.path, "r") as f:
if debug:
self.train_feat = f["train_feat"][:10_000] # [N, 1]
self.train_label = f["train_label"][:10_000] # [N, 1]
else:
self.train_feat = f["train_feat"][:]
self.train_label = f["train_label"][:]
assert len(self.train_feat) == len(self.train_label)
self.len = len(self.train_feat)
def __len__(self):
if self.debug:
return 2000
else:
return self.len - 10
# return 253379 - 10 # consider the random flip
def __getitem__(self, idx):
z = self.train_feat[idx]
cluster_id = self.cluster_assignment[idx]
return z, cluster_id
class FeatureDataset_IN_Cluster_H5_lazyload(Dataset): # a right writing for 70Gsize
def __init__(self, path, path_cluster, debug=False):
super().__init__()
self.path = path
self.path_cluster = path_cluster
# names = sorted(os.listdir(path))
# self.files = [os.path.join(path, name) for name in names]
self.debug = debug
print("Loading images from %s, lazy mode!!..." % self.path_cluster)
with h5py.File(self.path_cluster, "r") as f:
if debug:
self.cluster_assignment = f["cluster_assignment"][:10_000] # [N, 1]
else:
self.cluster_assignment = f["cluster_assignment"][:] # [N, 1
print(
"cluster_assignment",
self.cluster_assignment.shape,
self.cluster_assignment.dtype,
)
with h5py.File(self.path, "r") as f:
self.len = len(f["train_feat"])
print("train_feat", f["train_feat"].shape, f["train_label"].shape)
assert len(f["train_feat"]) == len(f["train_label"])
def __len__(self):
if self.debug:
return 2000
else:
return self.len - 10
# return 253379 - 10 # consider the random flip
def _open_hdf5(self):
self._hf = h5py.File(self.path, "r")
def __getitem__(self, idx):
if not hasattr(self, "_hf"):
self._open_hdf5()
_feat = np.array(self._hf["train_feat"][idx])
# _label = int(self._hf["train_label"][idx])
cluster_id = self.cluster_assignment[idx]
return _feat, cluster_id
class FeatureDataset_Cluster_IN256(Dataset):
def __init__(self, path, path_cluster, load_in_mem, debug=False):
super().__init__()
self.path = path
self.path_cluster = path_cluster
# names = sorted(os.listdir(path))
# self.files = [os.path.join(path, name) for name in names]
self.debug = debug
print("Loading images from %s into memory..." % self.path_cluster)
with h5py.File(self.path_cluster, "r") as f:
if debug:
self.cluster_assignment = f["cluster_assignment"][:10_000] # [N, 1]
else:
self.cluster_assignment = f["cluster_assignment"][:] # [N, 1]
with h5py.File(self.path_cluster, "r") as f:
if debug:
self.cluster_assignment = f["cluster_assignment"][:10_000] # [N, 1]
else:
self.cluster_assignment = f["cluster_assignment"][:] # [N, 1]
print(
"cluster_assignment",
self.cluster_assignment.shape,
self.cluster_assignment.dtype,
)
def __len__(self):
if self.debug:
return 10_000
else:
return 1_281_167 * 2 # consider the random flip
def __getitem__(self, idx):
path = os.path.join(self.path, f"{str(idx).zfill(9)}.npy")
if not os.path.isfile(path):
path = os.path.join(self.path, f"{idx}.npy")
try:
z, _ = np.load(path, allow_pickle=True)
except:
z = np.load(path, allow_pickle=True)
cluster_id = self.cluster_assignment[idx]
# print(z.shape, z.dtype, cluster_id.shape, cluster_id.dtype)
return z, cluster_id
class ChurchesFeatureDataset_H5(Dataset):
def __init__(
self,
path,
):
super().__init__()
self.path = path
print(f"loading, path: {path}")
with h5py.File(self.path, "r") as f:
self.len = len(f["train_feat"])
print("dataset length", self.len)
def __len__(self):
return self.len
def _open_hdf5(self):
self._hf = h5py.File(self.path, "r")
def __getitem__(self, idx):
if not hasattr(self, "_hf"):
self._open_hdf5()
_feat = np.array(self._hf["train_feat"][idx])
return _feat
class ChurchesFeatureDataset_Cluster_H5(ChurchesFeatureDataset_H5):
def __init__(self, path, path_cluster, load_in_mem=None, debug=False):
super().__init__(path)
self.path_cluster = path_cluster
self.debug = debug
print("Loading images from %s into memory..." % self.path_cluster)
with h5py.File(self.path_cluster, "r") as f:
self.cluster_assignment = f["cluster_assignment"][:] # [N, 1]
print(
"cluster_assignment",
self.cluster_assignment.shape,
self.cluster_assignment.dtype,
)
def __getitem__(self, idx):
if not hasattr(self, "_hf"):
self._open_hdf5()
_feat = np.array(self._hf["train_feat"][idx])
cluster_id = self.cluster_assignment[idx]
return _feat, cluster_id
class ImageNetFeatures_H5(
DatasetFactory
): # the moments calculated by Stable Diffusion image encoder
def __init__(self, path, cfg=False, K=100, p_uncond=None, debug=False):
super().__init__()
print("Prepare dataset...")
if path.endswith(".h5"):
print("using h5 dataset")
self.train = ImageNetFeatureDataset_H5(
path=path, load_in_mem=True, debug=debug
)
else:
raise
print("Prepare dataset ok")
self.K = K
if cfg: # classifier free guidance
assert p_uncond is not None
print(
f"prepare the dataset for classifier free guidance with p_uncond={p_uncond}"
)
self.train = CFGDataset(self.train, p_uncond, self.K)
@property
def data_shape(self):
return 4, 32, 32
@property
def fid_stat(self):
return f"assets/fid_stats/fid_stats_imagenet256_guided_diffusion.npz"
def sample_label(self, n_samples, device):
return torch.randint(0, self.K, (n_samples,), device=device)
class ImageNet256Features(
DatasetFactory
): # the moments calculated by Stable Diffusion image encoder
def __init__(self, path, cfg=False, p_uncond=None, debug=False):
super().__init__()
print("Prepare dataset...")
if path.endswith(".h5"):
print("using h5 dataset")
self.train = ImageNetFeatureDataset_H5(
path=path, load_in_mem=True, debug=debug
)
else:
raise NotImplementedError("should not use it any more ")
print("using npy dataset")
self.train = FeatureDataset_IN100(path=path, debug=debug)
print("Prepare dataset ok")
self.K = 1000
if cfg: # classifier free guidance
assert p_uncond is not None
print(
f"prepare the dataset for classifier free guidance with p_uncond={p_uncond}"
)
self.train = CFGDataset(self.train, p_uncond, self.K)
@property
def data_shape(self):
return 4, 32, 32
@property
def fid_stat(self):
return f"assets/fid_stats/fid_stats_imagenet256_guided_diffusion.npz"
def sample_label(self, n_samples, device):
return torch.randint(0, 1000, (n_samples,), device=device)
class IN_Features_EMA_H5(
DatasetFactory
): # the moments calculated by Stable Diffusion image encoder
def __init__(self, path, K=100, cfg=False, p_uncond=None, debug=False):
super().__init__()
print("Prepare dataset...")
if path.endswith(".h5"):
print("using h5 dataset")
self.train = ImageNetFeatureDataset_H5(
path=path, load_in_mem=True, debug=debug
)
else:
raise NotImplementedError("should not use it any more ")
print("using npy dataset")
self.train = FeatureDataset_IN100(path=path, debug=debug)
print("Prepare dataset ok")
self.K = K
@property
def data_shape(self):
return 4, 32, 32
@property
def fid_stat(self):
return f"assets/fid_stats/fid_stats_imagenet256_guided_diffusion.npz"
def sample_label(self, n_samples, device):
return torch.randint(0, self.K, (n_samples,), device=device)
class ImageNet256Features(
DatasetFactory
): # the moments calculated by Stable Diffusion image encoder
def __init__(self, path, cfg=False, p_uncond=None, debug=False):
super().__init__()
print("Prepare dataset...")
self.train = FeatureDataset_IN100(path, debug=debug)
print("Prepare dataset ok")
self.K = 1000
if cfg: # classifier free guidance
assert p_uncond is not None
print(
f"prepare the dataset for classifier free guidance with p_uncond={p_uncond}"
)
self.train = CFGDataset(self.train, p_uncond, self.K)
@property
def data_shape(self):
return 4, 32, 32
@property
def fid_stat(self):
return f"assets/fid_stats/fid_stats_imagenet256_guided_diffusion.npz"
@property
def fid_stat_dir(self):
return f"assets/fid_stats/imagenet256_50k"
def sample_label(self, n_samples, device):
return torch.randint(0, self.K, (n_samples,), device=device)
class ImageNet256Features_Online_aaaa(
DatasetFactory
): # the moments calculated by Stable Diffusion image encoder
def __init__(self, path, cfg=False, p_uncond=None, debug=False):
super().__init__()
print("Prepare dataset...")
self.train = FeatureDataset_Online(path, debug=debug)
print("Prepare dataset ok")
self.K = 1000
if cfg: # classifier free guidance
assert p_uncond is not None
print(
f"prepare the dataset for classifier free guidance with p_uncond={p_uncond}"
)
self.train = CFGDataset(self.train, p_uncond, self.K)
@property
def data_shape(self):
return 4, 32, 32
@property
def fid_stat(self):
return f"assets/fid_stats/fid_stats_imagenet256_guided_diffusion.npz"
@property
def fid_stat_dir(self):
return f"assets/fid_stats/imagenet256_50k"
def sample_label(self, n_samples, device):
return torch.randint(0, 1000, (n_samples,), device=device)
@property
def has_label(self):
return True
class Churches256Features_Cluster(DatasetFactory):
def __init__(
self,
path,
path_cluster,
cluster_k,
cfg=False,
p_uncond=None,
load_in_mem=True,
debug=False,
):
super().__init__()
print("Prepare dataset...")
if True:
self.train = ChurchesFeatureDataset_Cluster_H5(
path, path_cluster=path_cluster, load_in_mem=load_in_mem, debug=debug
)
else:
raise
print("Prepare dataset ok")
self.K = self.cluster_k = cluster_k
print("********* cfg", cfg)
if cfg: # classifier free guidance
assert p_uncond is not None
print(
f"prepare the dataset for classifier free guidance with p_uncond={p_uncond}"
)
self.train = CFGDataset(self.train, p_uncond, self.K)
@property
def data_shape(self):
return 4, 32, 32
@property
def fid_stat(self):
return f"assets/fid_stats/churches256_10k.npz"
@property
def fid_stat_dir(self):
return f"assets/fid_stats/churches256_10k"
def sample_label(self, n_samples, device):
return torch.randint(0, self.cluster_k, (n_samples,), device=device)
class ImageNet256Features_Cluster(
DatasetFactory
): # the moments calculated by Stable Diffusion image encoder
def __init__(
self,
path,
path_cluster,
cluster_k,
cfg=False,
p_uncond=None,
load_in_mem=True,
debug=False,
):
super().__init__()
print("Prepare dataset...")
if True:
self.train = FeatureDataset_Cluster_IN256(
path, path_cluster=path_cluster, load_in_mem=load_in_mem, debug=debug
)
else:
self.train = ImageNetFeatureDataset_H5(path, load_in_mem=False)
print("Prepare dataset ok")
self.K = self.cluster_k = cluster_k
if cfg: # classifier free guidance
assert p_uncond is not None
print(
f"prepare the dataset for classifier free guidance with p_uncond={p_uncond}"
)
self.train = CFGDataset(self.train, p_uncond, self.K)
@property
def data_shape(self):
return 4, 32, 32
@property
def fid_stat(self):
return f"assets/fid_stats/fid_stats_imagenet256_guided_diffusion.npz"
@property
def fid_stat_dir(self):
return f"assets/fid_stats/imagenet256_50k"
def sample_label(self, n_samples, device):
return torch.randint(0, self.cluster_k, (n_samples,), device=device)
class IN_Features_Cluster_H5(
DatasetFactory
): # the moments calculated by Stable Diffusion image encoder
def __init__(
self,
path,
path_cluster,
cluster_k,
cfg=False,
p_uncond=None,
debug=False,
):
super().__init__()
print("Prepare dataset...")
self.train = FeatureDataset_IN_Cluster_H5_lazyload(
path, path_cluster=path_cluster, debug=debug
)
print("Prepare dataset ok")
self.K = self.cluster_k = cluster_k
if cfg: # classifier free guidance
assert p_uncond is not None
print(
f"prepare the dataset for classifier free guidance with p_uncond={p_uncond}"
)
self.train = CFGDataset(self.train, p_uncond, self.K)
@property
def data_shape(self):
return 4, 32, 32
@property
def fid_stat(self):
return f"assets/fid_stats/fid_stats_imagenet256_guided_diffusion.npz"
@property
def fid_stat_dir(self):
return f"assets/fid_stats/imagenet256_50k"
def sample_label(self, n_samples, device):
return torch.randint(0, self.cluster_k, (n_samples,), device=device)
class ImageNet256Features_H5(
DatasetFactory
): # the moments calculated by Stable Diffusion image encoder
def __init__(self, path_h5, cfg=False, p_uncond=None, debug=False):
super().__init__()
print("Prepare dataset...")
if False:
self.train = FeatureDataset(path_h5)
else:
self.train = ImageNetFeatureDataset_H5(
path_h5, load_in_mem=False, debug=debug
)
print("Prepare dataset ok")
self.K = 1000
if cfg: # classifier free guidance
assert p_uncond is not None
print(
f"prepare the dataset for classifier free guidance with p_uncond={p_uncond}"
)
self.train = CFGDataset(self.train, p_uncond, self.K)
@property
def data_shape(self):
return 4, 32, 32
@property
def fid_stat(self):
return f"assets/fid_stats/fid_stats_imagenet256_guided_diffusion.npz"
def sample_label(self, n_samples, device):
return torch.randint(0, 1000, (n_samples,), device=device)
class ImageNet512Features(
DatasetFactory
): # the moments calculated by Stable Diffusion image encoder
def __init__(self, path, cfg=False, p_uncond=None):
super().__init__()
print("Prepare dataset...")
self.train = FeatureDataset(path)
print("Prepare dataset ok")
self.K = 1000
if cfg: # classifier free guidance
assert p_uncond is not None
print(
f"prepare the dataset for classifier free guidance with p_uncond={p_uncond}"
)
self.train = CFGDataset(self.train, p_uncond, self.K)
@property
def data_shape(self):
return 4, 64, 64
@property
def fid_stat(self):
return f"assets/fid_stats/fid_stats_imagenet512_guided_diffusion.npz"
def sample_label(self, n_samples, device):
return torch.randint(0, 1000, (n_samples,), device=device)
class ImageNet100(DatasetFactory):
def __init__(
self, path, in100_list, resolution, random_crop=False, random_flip=True
):
super().__init__()
self.in100_list = in100_list
with open(self.in100_list, "r") as f:
self.in100_list = [_.strip() for _ in f.readlines()]
if False:
print(f"Counting ImageNet files from {path}")
train_files = _list_image_files_recursively(os.path.join(path, "train"))
class_names = [os.path.basename(path).split("_")[0] for path in train_files]
else:
print(f"Counting ImageNet files from {path}")
train_files = _list_image_files_recursively(os.path.join(path, "train"))
class_names = [os.path.basename(path).split("_")[0] for path in train_files]
train_files_new, class_names_new = [], []
for tf, cn in zip(train_files, class_names):
if cn in self.in100_list:
train_files_new.append(tf)
class_names_new.append(cn)
train_files, class_names = train_files_new, class_names_new
print("FFFFinish counting ImageNet files")
print(len(train_files), len(class_names))
sorted_classes = {x: i for i, x in enumerate(sorted(set(class_names)))}
train_labels = [sorted_classes[x] for x in class_names]
print("Finish counting ImageNet files")
self.train = ImageDataset(
resolution,
train_files,
labels=train_labels,
random_crop=random_crop,
random_flip=random_flip,
)
self.resolution = resolution
if len(self.train) != 1_281_167:
print(f"Missing train samples: {len(self.train)} < 1281167")
self.K = max(self.train.labels) + 1
cnt = dict(zip(*np.unique(self.train.labels, return_counts=True)))
self.cnt = torch.tensor([cnt[k] for k in range(self.K)]).float()
self.frac = [self.cnt[k] / len(self.train.labels) for k in range(self.K)]
print(f"{self.K} classes")
print(f"cnt[:10]: {self.cnt[:10]}")
print(f"frac[:10]: {self.frac[:10]}")
@property
def data_shape(self):
return 3, self.resolution, self.resolution
@property
def fid_stat(self):
return (
f"assets/fid_stats/fid_stats_imagenet{self.resolution}_guided_diffusion.npz"
)
def sample_label(self, n_samples, device):
return torch.multinomial(self.cnt, n_samples, replacement=True).to(device)
def label_prob(self, k):
return self.frac[k]
class ImageNet(DatasetFactory):
def __init__(self, path, resolution, random_crop=False, random_flip=True):
super().__init__()
print(f"Counting ImageNet files from {path}")
train_files = _list_image_files_recursively(os.path.join(path, "train"))
class_names = [os.path.basename(path).split("_")[0] for path in train_files]
sorted_classes = {x: i for i, x in enumerate(sorted(set(class_names)))}
train_labels = [sorted_classes[x] for x in class_names]
print("Finish counting ImageNet files")
self.train = ImageDataset(
resolution,
train_files,
labels=train_labels,
random_crop=random_crop,
random_flip=random_flip,
)
self.resolution = resolution
if len(self.train) != 1_281_167:
print(f"Missing train samples: {len(self.train)} < 1281167")
self.K = max(self.train.labels) + 1
cnt = dict(zip(*np.unique(self.train.labels, return_counts=True)))
self.cnt = torch.tensor([cnt[k] for k in range(self.K)]).float()
self.frac = [self.cnt[k] / len(self.train.labels) for k in range(self.K)]
print(f"{self.K} classes")
print(f"cnt[:10]: {self.cnt[:10]}")
print(f"frac[:10]: {self.frac[:10]}")
@property
def data_shape(self):
return 3, self.resolution, self.resolution
@property
def fid_stat(self):
return (
f"assets/fid_stats/fid_stats_imagenet{self.resolution}_guided_diffusion.npz"
)
def sample_label(self, n_samples, device):
return torch.multinomial(self.cnt, n_samples, replacement=True).to(device)
def label_prob(self, k):
return self.frac[k]
def _list_image_files_recursively(data_dir):
results = []
for entry in sorted(os.listdir(data_dir)):
full_path = os.path.join(data_dir, entry)
ext = entry.split(".")[-1]
if "." in entry and ext.lower() in ["jpg", "jpeg", "png", "gif"]:
results.append(full_path)
elif os.listdir(full_path):
results.extend(_list_image_files_recursively(full_path))
return results
class ImageDataset(Dataset):
def __init__(
self,
resolution,
image_paths,
labels,
random_crop=False,
random_flip=True,
):
super().__init__()
self.resolution = resolution
self.image_paths = image_paths
self.labels = labels
self.random_crop = random_crop
self.random_flip = random_flip
def __len__(self):
return len(self.image_paths)
def __getitem__(self, idx):
path = self.image_paths[idx]
pil_image = Image.open(path)
pil_image.load()
pil_image = pil_image.convert("RGB")
if self.random_crop:
arr = random_crop_arr(pil_image, self.resolution)
else:
arr = center_crop_arr(pil_image, self.resolution)
if self.random_flip and random.random() < 0.5:
arr = arr[:, ::-1]
arr = arr.astype(np.float32) / 127.5 - 1
label = np.array(self.labels[idx], dtype=np.int64)
return np.transpose(arr, [2, 0, 1]), label
def center_crop_arr(pil_image, image_size):
# We are not on a new enough PIL to support the `reducing_gap`
# argument, which uses BOX downsampling at powers of two first.
# Thus, we do it by hand to improve downsample quality.
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 arr[crop_y : crop_y + image_size, crop_x : crop_x + image_size]
def random_crop_arr(pil_image, image_size, min_crop_frac=0.8, max_crop_frac=1.0):
min_smaller_dim_size = math.ceil(image_size / max_crop_frac)
max_smaller_dim_size = math.ceil(image_size / min_crop_frac)
smaller_dim_size = random.randrange(min_smaller_dim_size, max_smaller_dim_size + 1)
# We are not on a new enough PIL to support the `reducing_gap`
# argument, which uses BOX downsampling at powers of two first.
# Thus, we do it by hand to improve downsample quality.
while min(*pil_image.size) >= 2 * smaller_dim_size:
pil_image = pil_image.resize(
tuple(x // 2 for x in pil_image.size), resample=Image.BOX
)
scale = smaller_dim_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 = random.randrange(arr.shape[0] - image_size + 1)
crop_x = random.randrange(arr.shape[1] - image_size + 1)
return arr[crop_y : crop_y + image_size, crop_x : crop_x + image_size]
# CelebA
class Crop(object):
def __init__(self, x1, x2, y1, y2):
self.x1 = x1
self.x2 = x2
self.y1 = y1
self.y2 = y2
def __call__(self, img):
return F.crop(img, self.x1, self.y1, self.x2 - self.x1, self.y2 - self.y1)
def __repr__(self):
return self.__class__.__name__ + "(x1={}, x2={}, y1={}, y2={})".format(
self.x1, self.x2, self.y1, self.y2
)
class ImageNetFeatureDataset_H5(Dataset):
def __init__(self, path, load_in_mem=True, debug=False):
super().__init__()
self.path = path
print(f"loading, path: {path}")
with h5py.File(self.path, "r") as f:
self.len = len(f["train_feat"])
print("dataset length", self.len)
print("train_feat", f["train_feat"].shape, f["train_label"].shape)
assert len(f["train_feat"]) == len(f["train_label"])