-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLearner.py
More file actions
executable file
·4425 lines (4172 loc) · 213 KB
/
Learner.py
File metadata and controls
executable file
·4425 lines (4172 loc) · 213 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
import lz
from lz import *
from models import Backbone, MobileFaceNet, CSMobileFaceNet, l2_norm, Arcface, MySoftmax, TripletLoss
import models
import numpy as np
from verifacation import evaluate
from torch import optim
from tensorboardX import SummaryWriter
from utils import get_time, gen_plot, hflip_batch, separate_bn_paras, hflip
from torchvision import transforms as trans
import os, random, logging, numbers, math
from pathlib import Path
from torch.utils.data import DataLoader
from config import conf
import torch.autograd
from torch import nn
import torch.multiprocessing as mp
from torch.utils.data.sampler import Sampler
from torch.nn import functional as F
try:
import mxnet as mx
from mxnet import ndarray as nd
from mxnet import recordio
except ImportError:
logging.warning('if want to train, install mxnet for read rec data')
conf.training = False
try:
import mox_patch_0603_v4
import moxing.pytorch as mox
except:
logging.warning('not in the cloud')
conf.cloud = False
if conf.fp16:
try:
# from apex.parallel import DistributedDataParallel as DDP
# from apex.fp16_utils import *
from apex import amp
# amp.register_half_function(torch.nn, 'PReLU')
# amp.register_half_function(torch.nn.functional, 'prelu')
except ImportError:
logging.warning(
"if want to use fp16, install apex from https://www.github.com/nvidia/apex to run this example.")
conf.fp16 = False
def unpack_f64(s):
from mxnet.recordio import IRHeader, _IR_FORMAT, _IR_SIZE, struct
header = IRHeader(*struct.unpack(_IR_FORMAT, s[:_IR_SIZE]))
s = s[_IR_SIZE:]
if header.flag > 0:
header = header._replace(label=np.frombuffer(s, np.float64, header.flag))
s = s[header.flag * 8:]
return header, s
def unpack_f32(s):
from mxnet.recordio import IRHeader, _IR_FORMAT, _IR_SIZE, struct
header = IRHeader(*struct.unpack(_IR_FORMAT, s[:_IR_SIZE]))
s = s[_IR_SIZE:]
if header.flag > 0:
header = header._replace(label=np.frombuffer(s, np.float32, header.flag))
s = s[header.flag * 4:]
return header, s
def unpack_auto(s, fp): # todo maybe just use conf.dataset_name 'dataset_name': 'alpha_f64'
if 'f64' in fp or 'alpha' in fp or conf.cloud: # TODO cloud must train alpha_f64 or alpha_jk!
return unpack_f64(s)
else:
return unpack_f32(s)
# todo merge this
class Obj():
pass
def get_rec(p='/data2/share/faces_emore/train.idx'):
self = Obj()
self.imgrecs = []
path_imgidx = p
path_imgrec = path_imgidx.replace('.idx', '.rec')
self.imgrecs.append(
recordio.MXIndexedRecordIO(
path_imgidx, path_imgrec,
'r')
)
self.lock = mp.Lock()
self.imgrec = self.imgrecs[0]
s = self.imgrec.read_idx(0)
header, _ = recordio.unpack(s)
assert header.flag > 0, 'ms1m or glint ...'
print('header0 label', header.label)
self.header0 = (int(header.label[0]), int(header.label[1]))
self.id2range = {}
self.imgidx = []
self.ids = []
ids_shif = int(header.label[0])
for identity in list(range(int(header.label[0]), int(header.label[1]))):
s = self.imgrecs[0].read_idx(identity)
header, _ = recordio.unpack(s)
a, b = int(header.label[0]), int(header.label[1])
if b - a > conf.cutoff:
self.id2range[identity] = (a, b)
self.ids.append(identity)
self.imgidx += list(range(a, b))
self.ids = np.asarray(self.ids)
self.num_classes = len(self.ids)
# self.ids_map = {identity - ids_shif: id2 for identity, id2 in zip(self.ids, range(self.num_classes))}
ids_map_tmp = {identity: id2 for identity, id2 in zip(self.ids, range(self.num_classes))}
self.ids = [ids_map_tmp[id_] for id_ in self.ids]
self.ids = np.asarray(self.ids)
self.id2range = {ids_map_tmp[id_]: range_ for id_, range_ in self.id2range.items()}
return self
class DatasetCasia(torch.utils.data.Dataset):
def __init__(self, path=None):
self.file = '/data2/share/casia_landmark.txt'
self.lines = open(self.file).readlines()
df = pd.read_csv(self.file, sep='\t', header=None)
self.num_classes = np.unique(df.iloc[:, 1]).shape[0]
self.root_path = Path('/data2/share/faces_emore/')
self.cache = {}
def __len__(self):
return len(self.lines)
def __getitem__(self, item):
line = self.lines[item].split()
path = '/data2/share/casia/' + line[0]
if item in self.cache:
img = self.cache[item]
else:
img = open(path, 'rb').read()
self.cache[item] = img
fbs = np.asarray(bytearray(img), dtype=np.uint8)
img = cv2.imdecode(fbs, 1)
cid = int(line[1])
kpts = line[2:]
kpts = np.asarray(kpts, int).reshape(-1, 2)
warp = lz.preprocess(img, kpts, )
warp = cvb.bgr2rgb(warp)
if random.randint(0, 1) == 1:
warp = warp[:, ::-1, :] # for 112,112,3 second 112 is left right
# plt_imshow(img, inp_mode='bgr'); plt.show()
# plt_imshow(warp, inp_mode = 'bgr'); plt.show()
warp = warp / 255.
warp -= 0.5
warp /= 0.5
warp = np.array(warp, dtype=np.float32)
warp = warp.transpose((2, 0, 1))
return {'imgs': warp, 'labels': int(cid), 'indexes': item + 1,
'ind_inds': -1, 'is_trains': False}
class DatasetIJBC2(torch.utils.data.Dataset):
def __init__(self, ):
self.test_transform = trans.Compose([
trans.ToTensor(),
trans.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])
])
IJBC_path = '/data1/share/IJB_release/' if 'amax' in lz.hostname() else '/home/zl/zl_data/IJB_release/'
img_list_path = IJBC_path + './IJBC/meta/ijbc_name_5pts_score.txt'
img_list = open(img_list_path)
files = img_list.readlines()
img_path = '/share/data/loose_crop'
if not osp.exists(img_path):
img_path = IJBC_path + './IJBC/loose_crop'
self.img_path = img_path
self.IJBC_path = IJBC_path
self.files = files
def __len__(self):
return len(self.files)
def __getitem__(self, item):
import cvbase as cvb
from PIL import Image
img_index = item
each_line = self.files[img_index]
name_lmk_score = each_line.strip().split(' ')
img_name = os.path.join(self.img_path, name_lmk_score[0])
img = cvb.read_img(img_name)
img = cvb.bgr2rgb(img) # this is RGB
assert img is not None, img_name
lmk = np.array([float(x) for x in name_lmk_score[1:-1]], dtype=np.float32)
lmk = lmk.reshape((5, 2))
warp_img = lz.preprocess(img, landmark=lmk)
warp_img = Image.fromarray(warp_img)
img = self.test_transform(warp_img)
return img
class MegaFaceDisDS(torch.utils.data.Dataset):
def __init__(self):
megaface_path = '/data1/share/megaface/'
# files_scrub = open(f'{megaface_path}/facescrub_lst') .readlines()
# files_scrub = [f'{megaface_path}/facescrub_images/{f}' for f in files_scrub]
files_scrub = []
files_dis = open('f{megaface_path}/megaface_lst').readlines()
files_dis = [f'{megaface_path}/facescrub_images/{f}' for f in files_dis]
self.files = files_dis + files_scrub
self.test_transform = trans.Compose([
trans.ToTensor(),
trans.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])
])
def __len__(self):
return len(self.files)
def __getitem__(self, item):
import cvbase as cvb
img = cvb.read_img(self.files[item])
img = cvb.bgr2rgb(img) # this is RGB
img = self.test_transform(img)
return img
class DatasetCfpFp(torch.utils.data.Dataset):
def __init__(self):
from data.data_pipe import get_val_pair
carray, issame = get_val_pair('/data2/share/faces_emore', 'cfp_fp')
carray = np.array(carray, np.float32)
carray = carray[:, ::-1, :, :].copy() # to rgb
self.carray = carray
def __len__(self):
return len(self.carray)
def __getitem__(self, item):
img = self.carray[item]
if random.randint(0, 1) == 1:
img = img[:, :, ::-1].copy()
return img
class TestDataset(object):
def __init__(self):
assert conf.use_test
if conf.use_test == 'ijbc':
self.rec_test = DatasetIJBC2()
self.imglen = len(self.rec_test)
elif conf.use_test == 'glint':
self.rec_test = get_rec('/data2/share/glint_test/train.idx')
self.imglen = max(self.rec_test.imgidx) + 1
elif conf.use_test == 'cfp_fp':
self.rec_test = DatasetCfpFp()
self.imglen = len(self.rec_test)
else:
raise ValueError(f'{conf.use_test}')
def _get_single_item(self, index):
if conf.use_test == 'ijbc':
imgs = self.rec_test[index]
elif conf.use_test == 'cfp_fp':
imgs = self.rec_test[index]
elif conf.use_test == 'glint':
self.rec_test.lock.acquire()
s = self.rec_test.imgrec.read_idx(index)
self.rec_test.lock.release()
header, img = unpack_auto(s, 'glint_test')
imgs = self.imdecode(img)
imgs = self.preprocess_img(imgs)
else:
raise ValueError(f'{conf.use_test}')
return {'imgs': np.array(imgs, dtype=np.float32), 'labels': -1, 'indexes': index,
'ind_inds': -1, 'is_trains': False}
def __len__(self):
return self.imglen
def __getitem__(self, indices, ):
res = self._get_single_item(indices)
return res
rec_cache = {}
class TorchDataset(object):
def __init__(self,
path_ms1m,
):
self.flip = conf.flip
self.path_ms1m = path_ms1m
self.root_path = Path(path_ms1m)
path_imgrec = str(path_ms1m) + '/train.rec'
path_imgidx = path_imgrec[0:-4] + ".idx"
assert os.path.exists(path_imgidx), path_imgidx
self.path_imgidx = path_imgidx
self.path_imgrec = path_imgrec
self.imgrecs = []
self.locks = []
lz.timer.since_last_check('start timer for imgrec')
for num_rec in range(conf.num_recs):
self.imgrecs.append(
recordio.MXIndexedRecordIO(
path_imgidx, path_imgrec,
'r')
)
self.locks.append(mp.Lock())
lz.timer.since_last_check(f'{conf.num_recs} imgrec readers init')
lz.timer.since_last_check('start cal dataset info')
with self.locks[0]:
s = self.imgrecs[0].read_idx(0)
header, _ = unpack_auto(s, self.path_imgidx)
assert header.flag > 0, 'ms1m or glint ...'
logging.info(f'header0 label {header.label}')
self.header0 = (int(header.label[0]), int(header.label[1]))
self.id2range = {}
self.idx2id = {}
self.imgidx = []
self.ids = []
ids_shif = int(header.label[0])
for identity in list(range(int(header.label[0]), int(header.label[1]))):
s = self.imgrecs[0].read_idx(identity)
header, _ = unpack_auto(s, self.path_imgidx)
a, b = int(header.label[0]), int(header.label[1])
if b - a > conf.cutoff:
self.id2range[identity] = (a, b)
self.ids.append(identity)
self.imgidx += list(range(a, b))
self.ids = np.asarray(self.ids)
self.num_classes = len(self.ids)
self.ids_map = {identity - ids_shif: id2 for identity, id2 in
zip(self.ids, range(self.num_classes))} # if cutoff==0, this is identitical
ids_map_tmp = {identity: id2 for identity, id2 in zip(self.ids, range(self.num_classes))}
self.ids = np.asarray([ids_map_tmp[id_] for id_ in self.ids])
self.id2range = {ids_map_tmp[id_]: range_ for id_, range_ in self.id2range.items()}
for id_, range_ in self.id2range.items():
for idx_ in range(range_[0], range_[1]):
self.idx2id[idx_] = id_
# lz.msgpack_dump([self.imgidx, self.ids, self.id2range], str(path_ms1m) + f'/info.{conf.cutoff}.pk')
conf.num_clss = self.num_classes
conf.explored = np.zeros(self.ids.max() + 1, dtype=int)
if conf.dop is None:
if conf.mining == 'dop':
conf.dop = np.ones(self.ids.max() + 1, dtype=int) * conf.mining_init # dop: -1 ... -1
conf.id2range_dop = {str(id_):
np.ones((range_[1] - range_[0],)) *
conf.mining_init for id_, range_ in
self.id2range.items()}
elif conf.mining == 'imp' or conf.mining == 'rand.id':
conf.id2range_dop = {str(id_):
np.ones((range_[1] - range_[0],)) *
conf.mining_init for id_, range_ in
self.id2range.items()}
conf.dop = np.asarray([v.sum() for v in conf.id2range_dop.values()]) # Note: different with dop
logging.info(f'update num_clss {conf.num_clss} ')
self.cur = 0
lz.timer.since_last_check('finish cal dataset info')
if conf.kd and conf.sftlbl_from_file:
self.teacher_embedding_db = lz.Database('work_space/r100.retina.2.h5', 'r')['feas'][...][:5179510,
...].astype('float16')
if conf.clean_ids:
assert conf.cutoff is None, 'not all option combination is implemented'
id2nimgs = collections.defaultdict(int)
for id_ in conf.clean_ids:
id2nimgs[id_] += 1
abadon_ids = np.where(np.array(list(id2nimgs.values())) <= 10)[0]
ids_remap = {}
new_id = -1
for id_ in np.unique(conf.clean_ids):
if id_ in abadon_ids:
ids_remap[id_] = -1
else:
ids_remap[id_] = new_id
new_id += 1
new_ids = []
for id_ in conf.clean_ids:
new_ids.append(ids_remap[id_])
new_ids = np.array(new_ids)
conf.clean_ids = new_ids
if conf.clean_ids:
try:
conf.num_clss = self.num_classes = np.unique(conf.clean_ids).shape[0] - 1
except:
pass
global rec_cache
self.rec_cache = rec_cache
if conf.fill_cache:
self.fill_cache()
if not conf.sftlbl_from_file and conf.teacher_head_in_dloader:
save_path = Path('work_space/r100.128.retina.clean.arc/save/')
fixed_str = [t.name for t in save_path.glob('model*_*.pth')][0]
self.teacher_head = Arcface(embedding_size=512, classnum=conf.num_clss).to(
conf.teacher_head_dev)
self.teacher_head.update_mrg()
head_state_dict = torch.load(save_path / 'head_{}'.format(fixed_str.replace('model_', '')))
self.teacher_head.load_state_dict(head_state_dict)
def fill_cache(self):
start, stop = min(self.imgidx), max(self.imgidx) + 1
if isinstance(conf.fill_cache, float):
stop = start + (stop - start) * conf.fill_cache
stop = int(stop)
for index in range(start, stop):
if index % 9999 == 1:
logging.info(f'loading {index} ')
self.rec_cache[index] = self.imgrecs[0].read_idx(index)
def __len__(self):
if conf.local_rank is not None:
return len(self.imgidx) // torch.distributed.get_world_size()
else:
return len(self.imgidx) // conf.epoch_less_iter
def __getitem__(self, indices, ):
res = self._get_single_item(indices)
return res
def imdecode(self, s):
"""Decodes a string or byte string to an NDArray.
See mx.img.imdecode for more details."""
img = mx.image.imdecode(s) # mx.ndarray
return img
def postprocess_data(self, datum):
"""Final postprocessing step before image is loaded into the batch."""
return nd.transpose(datum, axes=(2, 0, 1))
def preprocess_img(self, imgs):
if isinstance(imgs, np.ndarray):
imgs = mx.nd.array(imgs)
if self.flip and random.randint(0, 1) == 1:
imgs = mx.ndarray.flip(data=imgs, axis=1)
imgs = imgs.asnumpy()
if not conf.fast_load:
imgs = imgs / 255.
imgs -= 0.5 # simply use 0.5 as mean
imgs /= 0.5
imgs = np.array(imgs, dtype=np.float32)
imgs = imgs.transpose((2, 0, 1))
return imgs
def _get_single_item(self, index):
# global rec_cache
if isinstance(index, tuple):
# assert not isinstance(index, tuple)
index, pid, ind_ind = index
index -= 1
if conf.clean_ids is not None:
lbl = conf.clean_ids[index]
if isinstance(lbl, tuple):
imgp, lbl_t = lbl
imgs_t = cvb.read_img(imgp)
imgs_t = cvb.bgr2rgb(imgs_t)
imgs_t = self.preprocess_img(imgs_t)
elif lbl == -1:
return self._get_single_item(np.random.randint(low=0, high=len(self)))
index += 1 # 1 based!
if index in self.rec_cache:
s = self.rec_cache[index]
else:
with self.locks[0]:
s = self.imgrecs[0].read_idx(index) # from [ 1 to 3804846 ]
# rec_cache[index] = s
header, img = unpack_auto(s, self.path_imgidx) # this is RGB format
imgs = self.imdecode(img)
assert imgs is not None
label = header.label
if not isinstance(label, numbers.Number):
assert label[-1] == 0. or label[-1] == 1., f'{label} {index} {imgs.shape}'
label = label[0]
label = int(label)
imgs = self.preprocess_img(imgs)
# assert label == int(self.idx2id[index]), f'{label} {self.idx2id[index]}'
assert label in self.ids_map
label = self.ids_map[label]
label = int(label)
if conf.clean_ids is not None:
if isinstance(lbl, tuple):
imgs = imgs_t
label = lbl_t
else:
label = lbl
res = {'imgs': imgs, 'labels': label,
'indexes': index, 'ind_inds': -1,
}
if conf.kd and conf.sftlbl_from_file:
teachers_embedding = self.teacher_embedding_db[index - 1]
if conf.teacher_head_in_dloader:
teachers_embedding = to_torch(teachers_embedding).to(conf.teacher_head_dev).float().unsqueeze(0)
labels = to_torch(np.array([label])).to(conf.teacher_head_dev)
teachers_embedding = self.teacher_head(teachers_embedding, labels).cuda()
res['teacher_embedding'] = teachers_embedding
return res
class MxnetLoader(object):
def __init__(self, path_ms1m, shuffle=True):
# os.environ['MXNET_CPU_WORKER_NTHREADS'] = '32'
# os.environ['MXNET_ENGINE_TYPE'] = 'ThreadedEnginePerDevice'
path_imgrec = str(path_ms1m) + '/train.rec'
path_imgidx = path_imgrec[0:-4] + ".idx"
assert os.path.exists(path_imgidx), path_imgidx
from data.image_iter import FaceImageIter
train_dataiter = FaceImageIter(
batch_size=conf.batch_size,
data_shape=(3, 112, 112),
path_imgrec=path_imgrec,
shuffle=shuffle,
rand_mirror=True,
mean=None,
cutoff=conf.cutoff,
color_jittering=0,
images_filter=0,
)
self.train_dataiter_ori = train_dataiter
self.train_dataiter = mx.io.PrefetchingIter(train_dataiter)
if conf.kd and conf.sftlbl_from_file:
self.teacher_embedding_db = lz.Database(lz.root_path + 'work_space/r100.retina.2.h5', 'r')['feas'][...][
:5179510,
...].astype('float16')
self.num_classes = self.train_dataiter_ori.num_classes
def __len__(self):
return len(self.train_dataiter_ori)
def __iter__(self):
diter = iter(self.train_dataiter)
try:
for ind, batch in enumerate(diter):
data, label, index = batch.data[0], batch.label[0], batch.index
imgs = data.asnumpy()
imgs -= 127.5
imgs /= 127.5
imgs = to_torch(imgs).cuda()
label = label.asnumpy().astype(int)
label = to_torch(label).cuda()
index = index.asnumpy().astype(int)
res = {'imgs': imgs, 'labels': label, 'indexes': index, }
if conf.kd and conf.sftlbl_from_file:
teacher_embedding = self.teacher_embedding_db[index - 1]
teacher_embedding = to_torch(teacher_embedding).cuda()
res['teacher_embedding'] = teacher_embedding
yield res
except Exception as e:
logging.info(f'!! chk er os {e}')
self.train_dataiter.reset()
class Dataset_val(torch.utils.data.Dataset):
def __init__(self, path, name, transform=None):
from data.data_pipe import get_val_pair
self.carray, self.issame = get_val_pair(path, name)
self.carray = self.carray[:, ::-1, :, :] # BGR 2 RGB!
self.transform = transform
def __getitem__(self, index):
if self.transform:
fliped_carray = self.transform(torch.tensor(self.carray[index]))
return {'carray': self.carray[index], 'issame': 1.0 * self.issame[index], 'fliped_carray': fliped_carray}
else:
return {'carray': self.carray[index], 'issame': 1.0 * self.issame[index]}
def __len__(self):
return len(self.issame)
class RandomIdSampler(Sampler):
def __init__(self, imgidx, ids, id2range):
path_ms1m = conf.use_data_folder
self.imgidx, self.ids, self.id2range = imgidx, ids, id2range
# above is the imgidx of .rec file
# remember -1 to convert to pytorch imgidx
self.num_instances = conf.instances
self.batch_size = conf.batch_size
if conf.tri_wei != 0:
assert self.batch_size % self.num_instances == 0
self.num_pids_per_batch = self.batch_size // self.num_instances
self.index_dic = {id: (np.asarray(list(range(idxs[0], idxs[1])))).tolist()
for id, idxs in self.id2range.items()} # it index based on 1
self.ids = list(self.ids)
self.nimgs = np.asarray([
range_[1] - range_[0] for id_, range_ in self.id2range.items()
])
self.nimgs_normed = self.nimgs / self.nimgs.sum()
# estimate number of examples in an epoch
self.length = 0
for pid in self.ids:
idxs = self.index_dic[pid]
num = len(idxs)
if num < self.num_instances:
num = self.num_instances
self.length += num - num % self.num_instances
def __len__(self):
if conf.local_rank is not None:
return self.length // torch.distributed.get_world_size()
else:
return self.length
def get_batch_ids(self):
pids = []
dop = conf.dop
if conf.mining == 'imp' or conf.mining == 'rand.id':
# lz.logging.info(f'dop smapler {np.count_nonzero( dop == conf.mining_init)} {dop}')
pids = np.random.choice(self.ids,
size=int(self.num_pids_per_batch),
p=conf.dop / conf.dop.sum(),
# comment, diff smpl diff wei; the smpl in few-smpl cls will more likely to smpled
# not comment, diff smpl same wei;
replace=False
)
# todo dop with no replacement
elif conf.mining == 'dop':
# lz.logging.info(f'dop smapler {np.count_nonzero( dop ==-1)} {dop}')
nrand_ids = int(self.num_pids_per_batch * conf.rand_ratio)
pids_now = np.random.choice(self.ids,
size=nrand_ids,
replace=False)
pids.append(pids_now)
for _ in range(int(1 / conf.rand_ratio) - 1): # -1 is important
pids_next = dop[pids_now]
pids_next[pids_next == -1] = np.random.choice(self.ids,
size=len(pids_next[pids_next == -1]),
replace=False)
pids.append(pids_next)
pids_now = pids_next
pids = np.concatenate(pids)
pids = np.unique(pids)
np.random.shuffle(pids) # just for safety
if len(pids) < self.num_pids_per_batch:
pids_now = np.random.choice(np.setdiff1d(self.ids, pids),
size=self.num_pids_per_batch - len(pids),
replace=False)
pids = np.concatenate((pids, pids_now))
else:
pids = pids[: self.num_pids_per_batch]
# assert len(pids) == np.unique(pids).shape[0]
return pids
def get_batch_idxs(self):
pids = self.get_batch_ids()
cnt = 0
for pid in pids:
if len(self.index_dic[pid]) < self.num_instances:
replace = True
else:
replace = False
if conf.mining == 'imp':
assert len(self.index_dic[pid]) == conf.id2range_dop[str(pid)].shape[0]
ind_inds = np.random.choice(
len(self.index_dic[pid]),
size=(self.num_instances,), replace=replace,
p=conf.id2range_dop[str(pid)] / conf.id2range_dop[str(pid)].sum()
)
else:
ind_inds = np.random.choice(
len(self.index_dic[pid]),
size=(self.num_instances,), replace=replace, )
if conf.chs_first:
if conf.dataset_name == 'alpha_jk':
ind_inds = np.concatenate(([0], ind_inds))
ind_inds = np.unique(ind_inds)[:self.num_instances] # 0 must be chsn
elif conf.dataset_name == 'alpha_f64':
if pid >= 112145: # 112145 开始是证件-监控 zjjk
ind_inds = np.concatenate(([0], ind_inds))
ind_inds = np.unique(ind_inds)[:self.num_instances] # 0 must be chsn
for ind_ind in ind_inds:
ind = self.index_dic[pid][ind_ind]
yield ind, pid, ind_ind
cnt += 1
if cnt == self.batch_size:
break
if cnt == self.batch_size:
break
def __iter__(self):
if conf.mining == 'rand.img': # quite slow
for _ in range(len(self)):
# lz.timer.since_last_check('s next id iter')
pid = np.random.choice(
self.ids, p=self.nimgs_normed,
)
ind_ind = np.random.choice(
range(len(self.index_dic[pid])),
)
ind = self.index_dic[pid][ind_ind]
# lz.timer.since_last_check('f next id iter')
yield ind, pid, ind_ind
else:
cnt = 0
while cnt < len(self):
# logging.info(f'cnt {cnt}')
for ind, pid, ind_ind in self.get_batch_idxs():
cnt += 1
yield (ind, pid, ind_ind)
# todo this seq can only be used to initial head!
class SeqSampler(Sampler):
def __init__(self, id2range):
self.id2range = id2range
self.index_dic = {id: (np.asarray(list(range(idxs[0], idxs[1])))).tolist()
for id, idxs in self.id2range.items()} # it index based on 1
if conf.head_init == 'all':
self.nimgs = np.asarray([
range_[1] - range_[0] for id_, range_ in self.id2range.items()
])
else:
self.nimgs = np.asarray([
min(range_[1] - range_[0], int(conf.head_init)) for id_, range_ in self.id2range.items()
])
self.length = sum(self.nimgs)
def __len__(self):
return self.length
def __iter__(self):
for pid in self.id2range:
max_nimgs = len(self.index_dic[pid])
if conf.head_init != 'all':
max_nimgs = min(max_nimgs, int(conf.head_init))
for ind_ind in range(max_nimgs):
ind = self.index_dic[pid][ind_ind]
yield ind, pid, ind_ind
def update_dop_cls(thetas, labels, dop):
with torch.no_grad():
bs = thetas.shape[0]
# logging.info(f'min is {thetas.min()}')
thetas[torch.arange(0, bs, dtype=torch.long), labels] = -1e4
dop[labels.cpu().numpy()] = torch.argmax(thetas, dim=1).cpu().numpy()
class FaceInfer():
def __init__(self, conf=conf, gpuid=(0,)):
if conf.net_mode == 'mobilefacenet':
self.model = MobileFaceNet(conf.embedding_size)
print('MobileFaceNet model generated')
elif conf.net_mode == 'ir_se' or conf.net_mode == 'ir':
self.model = Backbone(conf.net_depth, conf.drop_ratio, conf.net_mode)
elif conf.net_mode == 'mbv3':
self.model = models.mobilenetv3(mode=conf.mb_mode, width_mult=conf.mb_mult)
elif conf.net_mode == 'hrnet':
self.model = models.get_cls_net()
elif conf.net_mode == 'effnet':
name = conf.eff_name
self.model = models.EfficientNet.from_name(name)
imgsize = models.EfficientNet.get_image_size(name)
assert conf.input_size == imgsize, imgsize
else:
raise ValueError(conf.net_mode)
self.model = self.model.eval()
self.model = torch.nn.DataParallel(self.model,
device_ids=list(gpuid), output_device=gpuid[0]).to(gpuid[0])
self.model = self.model.eval()
def load_model_only(self, fpath):
model_state_dict = torch.load(fpath, map_location=lambda storage, loc: storage)
model_state_dict = {k: v for k, v in model_state_dict.items() if 'num_batches_tracked' not in k}
if list(model_state_dict.keys())[0].startswith('module'):
self.model.load_state_dict(model_state_dict, strict=True, )
else:
self.model.module.load_state_dict(model_state_dict, strict=True, )
def load_state(self, fixed_str=None,
resume_path=None, latest=True, strict=True,
):
from pathlib import Path
save_path = Path(resume_path)
modelp = save_path / '{}'.format(fixed_str)
if not modelp.exists() or not modelp.is_file():
modelp = save_path / 'model_{}'.format(fixed_str)
if not (modelp).exists() or not modelp.is_file():
fixed_strs = [t.name for t in save_path.glob('model*_*.pth')]
if latest:
step = [fixed_str.split('_')[-2].split(':')[-1] for fixed_str in fixed_strs]
else: # best
step = [fixed_str.split('_')[-3].split(':')[-1] for fixed_str in fixed_strs]
step = np.asarray(step, dtype=float)
assert step.shape[0] > 0, f"{resume_path} chk!"
step_ind = step.argmax()
fixed_str = fixed_strs[step_ind].replace('model_', '').replace('model2_', '')
modelp = save_path / 'model_{}'.format(fixed_str)
logging.info(f'you are using gpu, load model, {modelp}')
model_state_dict = torch.load(str(modelp), map_location=lambda storage, loc: storage)
# model_state_dict = {k: v for k, v in model_state_dict.items() if 'num_batches_tracked' not in k} # for spec norm, not wipe meta data!
if conf.cvt_ipabn:
import copy
model_state_dict2 = copy.deepcopy(model_state_dict)
for k in model_state_dict2.keys():
if 'running_mean' in k:
name = k.replace('running_mean', 'weight')
model_state_dict2[name] = torch.abs(model_state_dict[name])
model_state_dict = model_state_dict2
if list(model_state_dict.keys())[0].startswith('module'):
self.model.load_state_dict(model_state_dict, strict=strict, )
else:
self.model.module.load_state_dict(model_state_dict, strict=strict, )
if conf.fast_load:
class data_prefetcher():
def __init__(self, loader):
self.loader = iter(loader)
self.stream = torch.cuda.Stream()
self.mean = torch.tensor([.5 * 255, .5 * 255, .5 * 255]).cuda().view(1, 3, 1, 1)
self.std = torch.tensor([.5 * 255, .5 * 255, .5 * 255]).cuda().view(1, 3, 1, 1)
# With Amp, it isn't necessary to manually convert data to half.
# Type conversions are done internally on the fly within patched torch functions.
if conf.fp16:
self.mean = self.mean.half()
self.std = self.std.half()
self.buffer = []
self.preload()
def preload(self):
try:
ind_loader, data_loader = next(self.loader)
with torch.cuda.stream(self.stream):
data_loader['imgs'] = data_loader['imgs'].cuda()
data_loader['labels_cpu'] = data_loader['labels']
data_loader['labels'] = data_loader['labels'].cuda()
if conf.fp16:
data_loader['imgs'] = data_loader['imgs'].half()
else:
data_loader['imgs'] = data_loader['imgs'].float()
data_loader['imgs'] = data_loader['imgs'].sub_(self.mean).div_(self.std)
self.buffer.append((ind_loader, data_loader))
except StopIteration:
self.buffer.append((None, None))
return
def next(self):
torch.cuda.current_stream().wait_stream(self.stream)
self.preload()
res = self.buffer.pop(0)
return res
__next__ = next
def __iter__(self):
while True:
ind, data = self.next()
if ind is None:
raise StopIteration
yield ind, data
else:
data_prefetcher = lambda x: x
def fast_collate(batch):
imgs = [img['imgs'] for img in batch]
targets = torch.tensor([target['labels'] for target in batch], dtype=torch.int64)
ind_inds = torch.tensor([target['ind_inds'] for target in batch], dtype=torch.int64)
indexes = torch.tensor([target['indexes'] for target in batch], dtype=torch.int64)
is_trains = torch.tensor([target['is_trains'] for target in batch], dtype=torch.int64)
w = imgs[0].shape[1]
h = imgs[0].shape[2]
tensor = torch.zeros((len(imgs), 3, h, w), dtype=torch.uint8)
for i, img in enumerate(imgs):
nump_array = np.asarray(img, dtype=np.uint8)
if nump_array.ndim < 3:
nump_array = np.expand_dims(nump_array, axis=-1)
# nump_array = np.rollaxis(nump_array, 2)
tensor[i] += torch.from_numpy(nump_array)
return {'imgs': tensor, 'labels': targets,
'ind_inds': ind_inds, 'indexes': indexes,
'is_trains': is_trains}
class face_learner(object):
def __init__(self, conf=conf, ):
self.milestones = np.asarray(conf.milestones)
self.val_loader_cache = {}
if conf.use_loader == 'mxnet':
self.loader = MxnetLoader(conf.use_data_folder)
self.class_num = self.loader.num_classes
elif conf.use_loader == 'dali':
from tools.dali import fdali_iter, plmxds
self.loader = fdali_iter
self.class_num = plmxds.num_classes
elif conf.dataset_name == 'webface' or conf.dataset_name == 'casia':
file = '/data2/share/casia_landmark.txt'
df = pd.read_csv(file, sep='\t', header=None)
id2nimgs = {}
for key, frame in df.groupby(1):
id2nimgs[key] = frame.shape[0]
nimgs = list(id2nimgs.values())
nimgs = np.array(nimgs)
nimgs = nimgs.sum() / nimgs
id2wei = {ind: wei for ind, wei in enumerate(nimgs)}
weis = [id2wei[id_] for id_ in np.array(df.iloc[:, 1])]
weis = np.asarray(weis)
weis = np.ones((weis.shape[0])) # todo
self.dataset = DatasetCasia(conf.use_data_folder, )
self.loader = DataLoader(self.dataset, batch_size=conf.batch_size,
num_workers=conf.num_workers,
# sampler=torch.utils.data.sampler.WeightedRandomSampler(
# weis, weis.shape[0],
# replacement=True
# ),
shuffle=True,
# todo if no-replacement, suddenly large loss on new epoch
# todo whether rebalance
drop_last=True, pin_memory=True, )
self.class_num = conf.num_clss = self.dataset.num_classes
else:
self.dataset = TorchDataset(conf.use_data_folder)
self.loader = DataLoader(
self.dataset, batch_size=conf.batch_size,
num_workers=conf.num_workers,
sampler=RandomIdSampler(self.dataset.imgidx,
self.dataset.ids, self.dataset.id2range),
# shuffle=True,
drop_last=True, pin_memory=conf.pin_memory,
collate_fn=torch.utils.data.dataloader.default_collate if not conf.fast_load else fast_collate
)
self.class_num = self.dataset.num_classes
logging.info(f'{self.class_num} classes, load ok ')
if conf.dop is None:
conf.explored = np.zeros(self.class_num, dtype=int)
conf.dop = np.ones(self.class_num, dtype=int) * conf.mining_init
if conf.need_log:
if torch.distributed.is_initialized():
lz.set_file_logger(str(conf.log_path) + f'/proc{torch.distributed.get_rank()}')
lz.set_file_logger_prt(str(conf.log_path) + f'/proc{torch.distributed.get_rank()}')
lz.mkdir_p(conf.log_path, delete=False)
else:
lz.mkdir_p(conf.log_path, delete=False)
lz.mkdir_p(lz.cloud_normpath(conf.log_path), delete=False)
lz.set_file_logger(str(conf.log_path))
lz.set_file_logger_prt(str(conf.log_path))
if conf.need_tb and (not torch.distributed.is_initialized() or torch.distributed.get_rank() == 0):
self.writer = SummaryWriter(str(conf.log_path))
conf.writer = self.writer
self.writer.add_text('conf', f'{simplify_conf(conf)}', 0) # todo to markdown
else:
self.writer = None
self.step = 0
if conf.net_mode == 'mobilefacenet':
logging.info('MobileFaceNet model generating ... ')
self.model = MobileFaceNet(conf.embedding_size)
elif conf.net_mode == 'effnet':
name = conf.eff_name
self.model = models.EfficientNet.from_name(name)
imgsize = models.EfficientNet.get_image_size(name)
assert conf.input_size == imgsize, imgsize
elif conf.net_mode == 'mbfc':
self.model = models.mbfc()
elif conf.net_mode == 'sglpth':
self.model = models.singlepath(build_from_decs=conf.decs)
elif conf.net_mode == 'mbv3':
self.model = models.mobilenetv3(mode=conf.mb_mode, width_mult=conf.mb_mult)
elif conf.net_mode == 'hrnet':
self.model = models.get_cls_net()
elif conf.net_mode == 'nasnetamobile':
self.model = models.nasnetamobile(512)
elif conf.net_mode == 'resnext':
self.model = models.ResNeXt(**models.resnext._NETS[str(conf.net_depth)])
elif conf.net_mode == 'csmobilefacenet':
self.model = CSMobileFaceNet()
logging.info('CSMobileFaceNet model generated')
elif conf.net_mode == 'densenet':
self.model = models.DenseNet(**models.densenet._NETS[str(conf.net_depth)])
elif conf.net_mode == 'widerresnet':
self.model = models.WiderResNet(**models.wider_resnet._NETS[str(conf.net_depth)])
# self.model = models.WiderResNetA2(**models.wider_resnet._NETS[str(conf.net_depth)])
# elif conf.net_mode == 'seresnext50':
# self.model = se_resnext50_32x4d(512, )
# elif conf.net_mode == 'seresnext101':
# self.model = se_resnext101_32x4d(512)
elif conf.net_mode == 'ir_se' or conf.net_mode == 'ir':
self.model = Backbone(conf.net_depth, conf.drop_ratio, conf.net_mode)
logging.info('{}_{} model generated'.format(conf.net_mode, conf.net_depth))
else:
raise ValueError(conf.net_mode)
if conf.kd and not conf.teacher_head_in_dloader:
save_path = Path('work_space/r100.128.retina.clean.arc/save/')
fixed_str = [t.name for t in save_path.glob('model*_*.pth')][0]
if not conf.sftlbl_from_file:
self.teacher_model = Backbone(152, conf.drop_ratio, 'ir_se')
self.teacher_model = torch.nn.DataParallel(self.teacher_model).cuda()
modelp = save_path / fixed_str
model_state_dict = torch.load(modelp, map_location=lambda storage, loc: storage)
model_state_dict = {k: v for k, v in model_state_dict.items() if 'num_batches_tracked' not in k}
if list(model_state_dict.keys())[0].startswith('module'):
self.teacher_model.load_state_dict(model_state_dict, strict=True)
else:
self.teacher_model.module.load_state_dict(model_state_dict, strict=True)
self.teacher_model.eval()
self.teacher_head = Arcface(embedding_size=512, classnum=self.class_num).to(conf.teacher_head_dev)
self.teacher_head.update_mrg()
head_state_dict = torch.load(save_path / 'head_{}'.format(fixed_str.replace('model_', '')))
self.teacher_head.load_state_dict(head_state_dict)
if conf.loss == 'arcface':
self.head = Arcface(embedding_size=conf.embedding_size, classnum=self.class_num)
elif conf.loss == 'softmax':
self.head = MySoftmax(embedding_size=conf.embedding_size, classnum=self.class_num)