File size: 49,388 Bytes
619344d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
# Copyright (c) 2025 Hansheng Chen

import os
import sys
import logging
import pickle
import warnings
import numpy as np
import torch
import torch.distributed as dist
import torch.nn.functional as F
import mmcv
import hashlib

from copy import deepcopy
from contextlib import contextmanager, redirect_stdout, nullcontext
from scipy import linalg
from scipy.stats import entropy
from torchvision import models
from mmcv.runner import get_dist_info, load_checkpoint
from mmgen.utils import get_root_logger
from mmgen.core.registry import METRICS
from mmgen.core.evaluation.metrics import (
    Metric, TERO_INCEPTION_URL, _load_inception_torch, MMGEN_CACHE_DIR)
from mmgen.core.evaluation.metrics import FID as _FID
from mmgen.core.evaluation.metrics import PR as _PR
from open_clip import get_tokenizer, create_model
from lakonlab.utils.io_utils import download_from_huggingface, download_from_url


# Global caches for model loading
_inception_cache = {}
_hpsv2_cache = {}
_clip_cache = {}


def _argv_ctx(argv):
    class _Argv:

        def __enter__(self):
            self._old = sys.argv
            sys.argv = argv

        def __exit__(self, exc_type, exc, tb):
            sys.argv = self._old

    return _Argv()


def _redirect_stdout(to_buf):
    return redirect_stdout(to_buf) if to_buf is not None else nullcontext()


@contextmanager
def _quarantine_openclip_logging():
    """
    Guard against open_clip (and friends) mutating global logging.
    Snapshots root handlers/level, runs the block, then removes any
    NEW handlers and restores the level. Also disables propagation
    for the open_clip logger so logs don’t bubble to root.
    """
    root = logging.getLogger()
    before_handlers = tuple(root.handlers)   # snapshot by identity
    before_ids = {id(h) for h in before_handlers}
    before_level = root.level

    try:
        yield
    finally:
        # Remove only handlers that were added during the block
        for h in list(root.handlers):
            if id(h) not in before_ids:
                root.removeHandler(h)
                try:
                    h.close()
                except Exception:
                    pass
        root.setLevel(before_level)

        # Clamp open_clip logger so it won’t re-emit to root
        oc = logging.getLogger("open_clip")
        oc.propagate = False
        oc.handlers.clear()


def _load_inception_from_path(inception_path, map_location=None):
    mmcv.print_log(
        'Try to load Tero\'s Inception Model from '
        f'\'{inception_path}\'.', 'mmgen')
    try:
        model = torch.jit.load(inception_path, map_location=map_location)
        mmcv.print_log('Load Tero\'s Inception Model successfully.', 'mmgen')
    except Exception as e:
        model = None
        mmcv.print_log(
            'Load Tero\'s Inception Model failed. '
            f'\'{e}\' occurs.', 'mmgen')
    return model


def _load_inception_from_url(inception_url, map_location=None):
    """
    Fix multi-node downloading issue in MMGen.
    """
    inception_url = inception_url if inception_url else TERO_INCEPTION_URL
    mmcv.print_log(f'Try to download Inception Model from {inception_url}...',
                   'mmgen')
    try:
        path = download_from_url(inception_url, dest_dir=MMGEN_CACHE_DIR)
        mmcv.print_log('Download Finished.')
        return _load_inception_from_path(path, map_location=map_location)
    except Exception as e:
        mmcv.print_log(f'Download Failed. {e} occurs.')
        return None


def load_inception(inception_args, metric, map_location=None):
    """
    Fix multi-node downloading issue in MMGen.
    """
    if not isinstance(inception_args, dict):
        raise TypeError('Receive invalid \'inception_args\': '
                        f'\'{inception_args}\'')

    # Create cache key from arguments
    cache_key = hashlib.md5(str(sorted(inception_args.items())).encode()).hexdigest()
    cache_key += f"_{metric}"
    
    # Check if model is already cached
    if cache_key in _inception_cache:
        return _inception_cache[cache_key]

    _inception_args = deepcopy(inception_args)
    inceptoin_type = _inception_args.pop('type', None)

    if torch.__version__ < '1.6.0':
        mmcv.print_log(
            'Current Pytorch Version not support script module, load '
            'Inception Model from torch model zoo. If you want to use '
            'Tero\' script model, please update your Pytorch higher '
            f'than \'1.6\' (now is {torch.__version__})', 'mmgen')
        result = _load_inception_torch(_inception_args, metric), 'pytorch'
        _inception_cache[cache_key] = result
        return result

    # load pytorch version is specific
    if inceptoin_type != 'StyleGAN':
        result = _load_inception_torch(_inception_args, metric), 'pytorch'
        _inception_cache[cache_key] = result
        return result

    # try to load Tero's version
    path = _inception_args.get('inception_path', TERO_INCEPTION_URL)

    # try to parse `path` as web url and download
    if 'http' not in path:
        model = _load_inception_from_path(path, map_location=map_location)
        if isinstance(model, torch.nn.Module):
            result = model, 'StyleGAN'
            _inception_cache[cache_key] = result
            return result

    # try to parse `path` as path on disk
    model = _load_inception_from_url(path, map_location=map_location)
    if isinstance(model, torch.nn.Module):
        result = model, 'StyleGAN'
        _inception_cache[cache_key] = result
        return result

    raise RuntimeError('Cannot Load Inception Model, please check the input '
                       f'`inception_args`: {inception_args}')


def load_hpsv2(hps_version, device='cpu', precision='fp16'):
    assert hps_version in ['v2', 'v2.1']
    
    # Create cache key from arguments
    cache_key = f"{hps_version}_{device}_{precision}"
    
    # Check if model is already cached
    if cache_key in _hpsv2_cache:
        return _hpsv2_cache[cache_key]

    with _quarantine_openclip_logging():
        model = create_model(
            'ViT-H-14-quickgelu',
            precision=precision,
            device=device,
            output_dict=True)
        model.requires_grad_(False)
        tokenizer = get_tokenizer('ViT-H-14')
    load_checkpoint(
        model,
        f'huggingface://xswu/HPSv2/HPS_{hps_version}_compressed.pt',
        map_location='cpu', strict=True)

    result = model, tokenizer
    _hpsv2_cache[cache_key] = result
    return result


def load_openclip(
        model_name='ViT-L-14-336-quickgelu',
        pretrained='openai',
        device='cpu',
        precision='fp16'):
    cache_key = f'{model_name}_{pretrained}_{device}_{precision}'
    if cache_key in _clip_cache:
        return _clip_cache[cache_key]

    with _quarantine_openclip_logging():
        model = create_model(
            model_name,
            pretrained=pretrained,
            precision=precision,
            device=device,
            output_dict=True)
        model.requires_grad_(False)
        tokenizer = get_tokenizer(model_name)
    _clip_cache[cache_key] = (model, tokenizer)
    return _clip_cache[cache_key]


def compute_pr_distances(row_features,
                         col_features,
                         col_batch_size=10000):
    dist_batches = []
    for col_batch in col_features.split(col_batch_size):
        dist_batch = torch.cdist(
            row_features.unsqueeze(0), col_batch.unsqueeze(0))[0]
        dist_batches.append(dist_batch.cpu())
    return torch.cat(dist_batches, dim=1)


@METRICS.register_module(force=True)
class PR(_PR):

    def __init__(
            self,
            num_images=None,
            image_shape=None,
            feats_pkl=None,
            k=3,
            bgr2rgb=True,
            vgg16_script=None,
            inception_args=None,
            row_batch_size=10000,
            col_batch_size=10000):
        super(_PR, self).__init__(num_images, image_shape)

        self.feats_pkl = feats_pkl

        self.vgg16 = self.inception_net = None
        self.device = 'cpu'

        if vgg16_script is not None:
            mmcv.print_log('loading vgg16 for improved precision and recall...',
                           'mmgen')
            if os.path.isfile(vgg16_script):
                self.vgg16 = torch.jit.load('work_dirs/cache/vgg16.pt', map_location=self.device).eval()
                self.use_tero_scirpt = True
            else:
                mmcv.print_log(
                    'Cannot load Tero\'s script module. Use official '
                    'vgg16 instead', 'mmgen')
                self.vgg16 = models.vgg16(pretrained=True).eval()
                self.use_tero_scirpt = False
        elif inception_args is not None:
            self.inception_net, self.inception_style = load_inception(
                inception_args, 'FID')
        else:
            raise ValueError('Please provide either vgg16_script or inception_args')

        self.k = k
        self.bgr2rgb = bgr2rgb
        self.row_batch_size = row_batch_size
        self.col_batch_size = col_batch_size

    def prepare(self):
        self.features_of_reals = []
        self.features_of_fakes = []
        if self.feats_pkl is not None:
            assert mmcv.is_filepath(self.feats_pkl)
            with open(self.feats_pkl, 'rb') as f:
                reference = pickle.load(f)
                self.features_of_reals = [torch.from_numpy(feat) for feat in reference['features_of_reals']]
                self.num_real_feeded = reference['num_real_feeded']
                mmcv.print_log(
                    f'Load reference inception pkl from {self.feats_pkl}',
                    'mmgen')

    def extract_features(self, batch):
        if self.vgg16 is not None:
            if self.use_tero_scirpt:
                batch = (batch * 127.5 + 128).clamp(0, 255).to(torch.uint8)
                feat = self.vgg16(batch, return_features=True)
            else:
                batch = F.interpolate(batch, size=(224, 224))
                before_fc = self.vgg16.features(batch)
                before_fc = before_fc.view(-1, 7 * 7 * 512)
                feat = self.vgg16.classifier[:4](before_fc)
        else:
            if self.inception_style == 'StyleGAN':
                batch = (batch * 127.5 + 128).clamp(0, 255).to(torch.uint8)
                feat = self.inception_net(batch, return_features=True)
            else:
                feat = self.inception_net(batch)[0].view(batch.shape[0], -1)
        return feat

    @torch.no_grad()
    def feed_op(self, batch, mode):
        batch = batch.to(self.device)
        if self.bgr2rgb:
            batch = batch[:, [2, 1, 0]]

        feat = self.extract_features(batch)

        if dist.is_initialized():
            ws = dist.get_world_size()
            placeholder = [torch.zeros_like(feat) for _ in range(ws)]
            dist.all_gather(placeholder, feat)
            feat = torch.stack(placeholder, dim=1).reshape(feat.size(0) * ws, *feat.shape[1:])

        if (dist.is_initialized() and dist.get_rank() == 0) or not dist.is_initialized():
            if mode == 'reals':
                self.features_of_reals.append(feat)
            elif mode == 'fakes':
                self.features_of_fakes.append(feat)
            else:
                raise ValueError(f'{mode} is not a implemented feed mode.')

    def feed(self, batch, mode):
        if self.num_images is not None:
            return super().feed(batch, mode)
        else:
            self.feed_op(batch, mode)

    @torch.no_grad()
    def summary(self):
        gen_features = torch.cat(self.features_of_fakes)
        real_features = torch.cat(self.features_of_reals).to(device=gen_features.device)
        if self.num_images is not None:
            assert gen_features.shape[0] >= self.num_images
            gen_features = gen_features[:self.num_images]
            if self.feats_pkl is None:  # real feats not pre-calculated
                assert real_features.shape[0] >= self.num_images
                real_features = real_features[:self.num_images]

        self._result_dict = {}

        for name, manifold, probes in [
            ('precision', real_features, gen_features),
            ('recall', gen_features, real_features)
        ]:
            kth = []
            for manifold_batch in manifold.split(self.row_batch_size):
                distance = compute_pr_distances(
                    row_features=manifold_batch,
                    col_features=manifold,
                    col_batch_size=self.col_batch_size)
                kth.append(
                    distance.to(torch.float32).kthvalue(self.k + 1).values.to(torch.float16))
            kth = torch.cat(kth)
            pred = []
            for probes_batch in probes.split(self.row_batch_size):
                distance = compute_pr_distances(
                    row_features=probes_batch,
                    col_features=manifold,
                    col_batch_size=self.col_batch_size)
                pred.append((distance <= kth).any(dim=1))
            self._result_dict[name] = float(torch.cat(pred).to(torch.float32).mean())

        precision = self._result_dict['precision']
        recall = self._result_dict['recall']
        self._result_str = f'precision: {precision}, recall:{recall}'
        return self._result_dict

    def clear_fake_data(self):
        self.features_of_fakes = []
        self.num_fake_feeded = 0

    def clear(self, clear_reals=False):
        self.clear_fake_data()
        if clear_reals:
            self.features_of_reals = []
            self.num_real_feeded = 0

    def load_to_gpu(self):
        """Move models to GPU."""
        if torch.cuda.is_available():
            if self.vgg16 is not None:
                self.vgg16 = self.vgg16.cuda()
            elif self.inception_net is not None:
                self.inception_net.cuda()
            self.device = 'cuda'

    def offload_to_cpu(self):
        """Move models to CPU."""
        if self.vgg16 is not None:
            self.vgg16 = self.vgg16.cpu()
        elif self.inception_net is not None:
            self.inception_net.cpu()
        self.device = 'cpu'


@METRICS.register_module(force=True)
class FID(_FID):

    def __init__(self,
                 num_images=None,
                 image_shape=None,
                 inception_pkl=None,
                 bgr2rgb=True,
                 inception_args=dict(normalize_input=False)):
        super().__init__(
            num_images,
            image_shape=image_shape,
            inception_pkl=inception_pkl,
            bgr2rgb=bgr2rgb,
            inception_args=inception_args)

    def prepare(self):
        if self.inception_pkl is not None:
            assert mmcv.is_filepath(self.inception_pkl)
            if self.inception_pkl.startswith('huggingface://'):
                self.inception_pkl = download_from_huggingface(self.inception_pkl)
            elif self.inception_pkl.startswith(('http://', 'https://')):
                self.inception_pkl = download_from_url(self.inception_pkl)
            with open(self.inception_pkl, 'rb') as f:
                reference = pickle.load(f)
                self.real_mean = reference['mean']
                self.real_cov = reference['cov']
                mmcv.print_log(
                    f'Load reference inception pkl from {self.inception_pkl}',
                    'mmgen')
            self.num_real_feeded = self.num_images

    @torch.no_grad()
    def summary(self):
        # calculate reference inception stat
        if self.real_mean is None:
            feats = torch.cat(self.real_feats, dim=0)
            if self.num_images is not None:
                assert feats.shape[0] >= self.num_images
                feats = feats[:self.num_images]
            feats_np = feats.numpy()
            self.real_mean = np.mean(feats_np, 0)
            self.real_cov = np.cov(feats_np, rowvar=False)

        # calculate fake inception stat
        fake_feats = torch.cat(self.fake_feats, dim=0)
        if self.num_images is not None:
            assert fake_feats.shape[0] >= self.num_images
            fake_feats = fake_feats[:self.num_images]
        fake_feats_np = fake_feats.numpy()
        fake_mean = np.mean(fake_feats_np, 0)
        fake_cov = np.cov(fake_feats_np, rowvar=False)

        # calculate distance between real and fake statistics
        fid, mean, cov = self._calc_fid(fake_mean, fake_cov, self.real_mean, self.real_cov)

        # results for print/table
        self._result_str = (f'{fid:.4f} ({mean:.5f}/{cov:.5f})')
        # results for log_buffer
        self._result_dict = dict(fid=fid, fid_mean=mean, fid_cov=cov)

        return fid, mean, cov

    def feed(self, batch, mode):
        if self.num_images is not None:
            return super().feed(batch, mode)
        else:
            self.feed_op(batch, mode)


@METRICS.register_module()
class FIDKID(FID):
    name = 'FIDKID'

    def __init__(self,
                 num_images=None,
                 num_subsets=100,
                 max_subset_size=1000,
                 **kwargs):
        super().__init__(num_images=num_images, **kwargs)
        self.num_subsets = num_subsets
        self.max_subset_size = max_subset_size
        self.real_feats_np = None

    def prepare(self):
        if self.inception_pkl is not None:
            assert mmcv.is_filepath(self.inception_pkl)
            with open(self.inception_pkl, 'rb') as f:
                reference = pickle.load(f)
                self.real_mean = reference['mean']
                self.real_cov = reference['cov']
                self.real_feats_np = reference['feats_np']
                mmcv.print_log(
                    f'Load reference inception pkl from {self.inception_pkl}',
                    'mmgen')
            self.num_real_feeded = self.num_images

    @staticmethod
    def _calc_kid(real_feat, fake_feat, num_subsets, max_subset_size):
        """Refer to the implementation from:
        https://github.com/NVlabs/stylegan2-ada-pytorch/blob/main/metrics/kernel_inception_distance.py#L18  # noqa
        Args:
            real_feat (np.array): Features of the real samples.
            fake_feat (np.array): Features of the fake samples.
            num_subsets (int): Number of subsets to calculate KID.
            max_subset_size (int): The max size of each subset.
        Returns:
            float: The calculated kid metric.
        """
        n = real_feat.shape[1]
        m = min(min(real_feat.shape[0], fake_feat.shape[0]), max_subset_size)
        t = 0
        for _ in range(num_subsets):
            x = fake_feat[np.random.choice(
                fake_feat.shape[0], m, replace=False)]
            y = real_feat[np.random.choice(
                real_feat.shape[0], m, replace=False)]
            a = (x @ x.T / n + 1)**3 + (y @ y.T / n + 1)**3
            b = (x @ y.T / n + 1)**3
            t += (a.sum() - np.diag(a).sum()) / (m - 1) - b.sum() * 2 / m

        kid = t / num_subsets / m
        return float(kid)

    @torch.no_grad()
    def summary(self):
        if self.real_feats_np is None:
            feats = torch.cat(self.real_feats, dim=0)
            if self.num_images is not None:
                assert feats.shape[0] >= self.num_images
                feats = feats[:self.num_images]
            feats_np = feats.numpy()
            self.real_feats_np = feats_np
            self.real_mean = np.mean(feats_np, 0)
            self.real_cov = np.cov(feats_np, rowvar=False)

        fake_feats = torch.cat(self.fake_feats, dim=0)
        if self.num_images is not None:
            assert fake_feats.shape[0] >= self.num_images
            fake_feats = fake_feats[:self.num_images]
        fake_feats_np = fake_feats.numpy()
        fake_mean = np.mean(fake_feats_np, 0)
        fake_cov = np.cov(fake_feats_np, rowvar=False)

        fid, mean, cov = self._calc_fid(fake_mean, fake_cov, self.real_mean,
                                        self.real_cov)
        kid = self._calc_kid(self.real_feats_np, fake_feats_np, self.num_subsets,
                             self.max_subset_size) * 1000

        self._result_str = f'{fid:.4f} ({mean:.5f}/{cov:.5f}), {kid:.4f}'
        self._result_dict = dict(fid=fid, fid_mean=mean, fid_cov=cov, kid=kid)

        return fid, mean, cov, kid


@METRICS.register_module()
class InceptionMetrics(Metric):
    name = 'InceptionMetrics'

    def __init__(self,
                 num_images=None,
                 reference_pkl=None,
                 bgr2rgb=False,
                 center_crop=False,  # SDXL-Lightning patch FID
                 resize=True,
                 inception_args=dict(
                    type='StyleGAN',
                    inception_path=TERO_INCEPTION_URL),
                 use_kid=False,
                 use_pr=True,
                 use_is=True,
                 kid_num_subsets=100,
                 kid_max_subset_size=1000,
                 pr_k=3,
                 pr_row_batch_size=10000,
                 pr_col_batch_size=10000,
                 is_splits=10,
                 prefix=''):
        super().__init__(num_images)
        self.reference_pkl = reference_pkl
        self.real_feats = []
        self.fake_feats = []
        self.preds = []
        self.real_mean = None
        self.real_cov = None
        self.bgr2rgb = bgr2rgb
        self.center_crop = center_crop
        self.resize = resize
        self.device = 'cpu'

        if self.center_crop and self.resize:
            warnings.warn('`center_crop` is set to True, `resize` will be ignored.')

        logger = get_root_logger()
        ori_level = logger.level
        logger.setLevel('ERROR')
        self.inception_net, self.inception_style = load_inception(
            inception_args, 'FID', map_location=self.device)
        logger.setLevel(ori_level)

        self.inception_net.eval()

        self.use_kid = use_kid
        self.use_pr = use_pr
        self.use_is = use_is
        self.kid_num_subsets = kid_num_subsets
        self.kid_max_subset_size = kid_max_subset_size
        self.real_feats_np = None

        self.pr_k = pr_k
        self.pr_row_batch_size = pr_row_batch_size
        self.pr_col_batch_size = pr_col_batch_size

        self.is_splits = is_splits
        self.prefix = prefix

    def prepare(self):
        self.real_feats = []
        self.real_feats_np = None
        self.fake_feats = []
        self.preds = []
        if self.reference_pkl is not None:
            assert mmcv.is_filepath(self.reference_pkl)
            if self.reference_pkl.startswith('huggingface://'):
                self.reference_pkl = download_from_huggingface(self.reference_pkl)
            elif self.reference_pkl.startswith(('http://', 'https://')):
                self.reference_pkl = download_from_url(self.reference_pkl)
            with open(self.reference_pkl, 'rb') as f:
                reference = pickle.load(f)
                self.real_mean = reference['mean']
                self.real_cov = reference['cov']
                self.real_feats_np = reference['real_feats_np']
                self.real_feats = [torch.from_numpy(reference['real_feats_np'])]
                self.num_real_feeded = reference['num_real_feeded']

    @staticmethod
    def _calc_fid(sample_mean, sample_cov, real_mean, real_cov, eps=1e-6):
        """Refer to the implementation from:

        https://github.com/rosinality/stylegan2-pytorch/blob/master/fid.py#L34
        """
        cov_sqrt, _ = linalg.sqrtm(sample_cov @ real_cov, disp=False)

        if not np.isfinite(cov_sqrt).all():
            print('product of cov matrices is singular')
            offset = np.eye(sample_cov.shape[0]) * eps
            cov_sqrt = linalg.sqrtm(
                (sample_cov + offset) @ (real_cov + offset))

        if np.iscomplexobj(cov_sqrt):
            if not np.allclose(np.diagonal(cov_sqrt).imag, 0, atol=1e-3):
                m = np.max(np.abs(cov_sqrt.imag))

                raise ValueError(f'Imaginary component {m}')

            cov_sqrt = cov_sqrt.real

        mean_diff = sample_mean - real_mean
        mean_norm = mean_diff @ mean_diff

        trace = np.trace(sample_cov) + np.trace(
            real_cov) - 2 * np.trace(cov_sqrt)

        fid = mean_norm + trace

        return fid, mean_norm, trace

    @staticmethod
    def _calc_kid(real_feat, fake_feat, num_subsets, max_subset_size):
        """Refer to the implementation from:
        https://github.com/NVlabs/stylegan2-ada-pytorch/blob/main/metrics/kernel_inception_distance.py#L18  # noqa
        Args:
            real_feat (np.array): Features of the real samples.
            fake_feat (np.array): Features of the fake samples.
            num_subsets (int): Number of subsets to calculate KID.
            max_subset_size (int): The max size of each subset.
        Returns:
            float: The calculated kid metric.
        """
        n = real_feat.shape[1]
        m = min(min(real_feat.shape[0], fake_feat.shape[0]), max_subset_size)
        t = 0
        for _ in range(num_subsets):
            x = fake_feat[np.random.choice(
                fake_feat.shape[0], m, replace=False)]
            y = real_feat[np.random.choice(
                real_feat.shape[0], m, replace=False)]
            a = (x @ x.T / n + 1)**3 + (y @ y.T / n + 1)**3
            b = (x @ y.T / n + 1)**3
            t += (a.sum() - np.diag(a).sum()) / (m - 1) - b.sum() * 2 / m

        kid = t / num_subsets / m
        return float(kid)

    def extract_features(self, batch):
        if self.center_crop:
            crop_size = 299
            h, w = batch.shape[2], batch.shape[3]
            assert h >= crop_size and w >= crop_size
            h_offset = (h - crop_size) // 2
            w_offset = (w - crop_size) // 2
            batch = batch[:, :, h_offset:h_offset + crop_size, w_offset:w_offset + crop_size]
        elif self.resize:
            batch = F.interpolate(
                batch, size=(299, 299), mode='bicubic', align_corners=False, antialias=True).clamp(min=-1, max=1)
        assert self.inception_style == 'StyleGAN'
        batch = (batch * 127.5 + 128).clamp(0, 255).to(torch.uint8)
        feat = self.inception_net(batch, return_features=True)
        pred = F.linear(feat, self.inception_net.output.weight).softmax(dim=1)
        return feat, pred

    @torch.no_grad()
    def feed_op(self, batch, mode):
        if self.bgr2rgb:
            batch = batch[:, [2, 1, 0]]
        batch = batch.to(self.device)

        feat, pred = self.extract_features(batch)

        if dist.is_initialized():
            ws = dist.get_world_size()
            placeholder = [torch.zeros_like(feat) for _ in range(ws)]
            dist.all_gather(placeholder, feat)
            feat = torch.stack(placeholder, dim=1).reshape(feat.size(0) * ws, *feat.shape[1:])
            if mode == 'fakes':
                placeholder = [torch.zeros_like(pred) for _ in range(ws)]
                dist.all_gather(placeholder, pred)
                pred = torch.stack(placeholder, dim=1).reshape(pred.size(0) * ws, *pred.shape[1:])

        # in distributed training, we only collect features at rank-0.
        if (dist.is_initialized() and dist.get_rank() == 0) or not dist.is_initialized():
            if mode == 'reals':
                self.real_feats.append(feat.cpu())
            elif mode == 'fakes':
                self.fake_feats.append(feat.cpu())
                self.preds.append(pred.cpu().numpy())
            else:
                raise ValueError(
                    f"The expected mode should be set to 'reals' or 'fakes,\
                    but got '{mode}'")

    def feed(self, batch, mode):
        if self.num_images is None:
            self.feed_op(batch, mode)

        else:
            _, ws = get_dist_info()
            if mode == 'reals':
                if self.num_real_feeded == self.num_real_need:
                    return 0

                if isinstance(batch, dict):
                    batch_size = len(list(batch.values())[0])
                    end = min(batch_size, self.num_real_need - self.num_real_feeded)
                    batch_to_feed = {k: v[:end] for k, v in batch.items()}
                else:
                    batch_size = batch.shape[0]
                    end = min(batch_size, self.num_real_need - self.num_real_feeded)
                    batch_to_feed = batch[:end]

                global_end = min(batch_size * ws,
                                 self.num_real_need - self.num_real_feeded)
                self.feed_op(batch_to_feed, mode)
                self.num_real_feeded += global_end
                return end

            elif mode == 'fakes':
                if self.num_fake_feeded == self.num_fake_need:
                    return 0

                if isinstance(batch, dict):
                    batch_size = len(list(batch.values())[0])
                    end = min(batch_size, self.num_fake_need - self.num_fake_feeded)
                    batch_to_feed = {k: v[:end] for k, v in batch.items()}
                else:
                    batch_size = batch.shape[0]
                    end = min(batch_size, self.num_fake_need - self.num_fake_feeded)
                    batch_to_feed = batch[:end]

                global_end = min(batch_size * ws,
                                 self.num_fake_need - self.num_fake_feeded)
                self.feed_op(batch_to_feed, mode)
                self.num_fake_feeded += global_end
                return end
            else:
                raise ValueError(
                    'The expected mode should be set to \'reals\' or \'fakes\','
                    f'but got \'{mode}\'')

    @torch.no_grad()
    def summary(self):
        real_feats = torch.cat(self.real_feats, dim=0)
        fake_feats = torch.cat(self.fake_feats, dim=0)
        if self.num_images is not None:
            assert fake_feats.shape[0] >= self.num_images
            fake_feats = fake_feats[:self.num_images]
            if self.reference_pkl is None:  # real feats not pre-calculated
                assert real_feats.shape[0] >= self.num_images
                real_feats = real_feats[:self.num_images]

        if self.real_feats_np is None:
            real_feats_np = real_feats.numpy()
            self.real_feats_np = real_feats_np
            self.real_mean = np.mean(real_feats_np, 0)
            self.real_cov = np.cov(real_feats_np, rowvar=False)

        self._result_dict = dict()

        prefix = self.prefix + '_' if len(self.prefix) > 0 else ''

        # FID
        fake_feats_np = fake_feats.numpy()
        fake_mean = np.mean(fake_feats_np, 0)
        fake_cov = np.cov(fake_feats_np, rowvar=False)
        fid, mean, cov = self._calc_fid(fake_mean, fake_cov, self.real_mean,
                                        self.real_cov)
        self._result_dict.update({f'{prefix}fid': fid})
        _result_str = f'{prefix}FID: {fid:.4f} ({mean:.4f}/{cov:.4f})'

        # KID
        if self.use_kid:
            kid = self._calc_kid(self.real_feats_np, fake_feats_np, self.kid_num_subsets,
                                 self.kid_max_subset_size) * 1000
            self._result_dict.update({f'{prefix}kid': kid})
            _result_str += f', {prefix}KID: {kid:.4f}'
        else:
            kid = None

        # PR
        if self.use_pr:
            for name, manifold, probes in [
                (f'{prefix}precision', real_feats, fake_feats),
                (f'{prefix}recall', fake_feats, real_feats)
            ]:
                kth = []
                for manifold_batch in manifold.split(self.pr_row_batch_size):
                    distance = compute_pr_distances(
                        row_features=manifold_batch,
                        col_features=manifold,
                        col_batch_size=self.pr_col_batch_size)
                    kth.append(
                        distance.to(torch.float32).kthvalue(self.pr_k + 1).values.to(torch.float16))
                kth = torch.cat(kth)
                pred = []
                for probes_batch in probes.split(self.pr_row_batch_size):
                    distance = compute_pr_distances(
                        row_features=probes_batch,
                        col_features=manifold,
                        col_batch_size=self.pr_col_batch_size)
                    pred.append((distance <= kth).any(dim=1))
                self._result_dict[name] = float(torch.cat(pred).to(torch.float32).mean())
            precision = self._result_dict[f'{prefix}precision']
            recall = self._result_dict[f'{prefix}recall']
            _result_str += f', {prefix}Precision: {precision:.5f}, {prefix}Recall:{recall:.5f}'
        else:
            precision = recall = None

        # IS
        if self.use_is:
            split_scores = []
            self.preds = np.concatenate(self.preds, axis=0)
            if self.num_images is not None:
                assert self.preds.shape[0] >= self.num_images
                self.preds = self.preds[:self.num_images]
            num_preds = self.preds.shape[0]
            for k in range(self.is_splits):
                part = self.preds[k * (num_preds // self.is_splits):(k + 1) * (num_preds // self.is_splits), :]
                py = np.mean(part, axis=0)
                scores = []
                for i in range(part.shape[0]):
                    pyx = part[i, :]
                    scores.append(entropy(pyx, py))
                split_scores.append(np.exp(np.mean(scores)))
            is_mean = np.mean(split_scores)
            self._result_dict.update({f'{prefix}is': is_mean})
            _result_str += f', {prefix}IS: {is_mean:.2f}'
        else:
            is_mean = None

        self._result_str = _result_str

        return fid, kid, precision, recall, is_mean

    def clear_fake_data(self):
        self.fake_feats = []
        self.preds = []
        self.num_fake_feeded = 0

    def clear(self, clear_reals=False):
        self.clear_fake_data()
        if clear_reals:
            self.real_feats = []
            self.real_feats_np = None
            self.num_real_feeded = 0

    def load_to_gpu(self):
        """Move models to GPU."""
        if torch.cuda.is_available():
            self.inception_net.cuda()
            self.device = 'cuda'

    def offload_to_cpu(self):
        """Move models to CPU."""
        self.inception_net.cpu()
        self.device = 'cpu'


@METRICS.register_module()
class ColorStats(Metric):
    name = 'ColorStats'

    def __init__(self,
                 num_images=None):
        super().__init__(num_images)

    def prepare(self):
        self.stats = []

    @staticmethod
    def srgb_to_linear(c):
        threshold = 0.04045
        below = c <= threshold
        out = torch.where(
            below, c / 12.92, ((c + 0.055) / 1.055) ** 2.4)
        return out

    @staticmethod
    def linear_to_srgb(c):
        threshold = 0.0031308
        below = c <= threshold
        out = torch.where(
            below, 12.92 * c, 1.055 * c ** (1.0 / 2.4) - 0.055)
        return out

    def rgb_to_grayscale_srgb(self, img_srgb):
        img_lin = self.srgb_to_linear(img_srgb)
        R_lin, G_lin, B_lin = img_lin.unbind(dim=1)
        Y_lin = 0.2126 * R_lin + 0.7152 * G_lin + 0.0722 * B_lin
        gray_srgb = self.linear_to_srgb(Y_lin)
        return gray_srgb

    @staticmethod
    def srgb_to_hsv_saturation(img_srgb):
        c_max = torch.amax(img_srgb, dim=1)
        c_min = torch.amin(img_srgb, dim=1)
        delta = c_max - c_min
        sat = delta / c_max.clamp(min=1e-5)
        return sat

    def compute_stats(self, batch):
        batch = (batch / 2 + 0.5).clamp(0, 1)
        gray = self.rgb_to_grayscale_srgb(batch).flatten(1)
        contrast, brightness = torch.std_mean(gray, dim=1)
        saturation = self.srgb_to_hsv_saturation(batch).flatten(1).mean(dim=1)
        return torch.stack([brightness, contrast, saturation], dim=-1)

    @torch.no_grad()
    def feed_op(self, batch, mode):
        stats = self.compute_stats(batch)

        if dist.is_initialized():
            ws = dist.get_world_size()
            placeholder = [torch.zeros_like(stats) for _ in range(ws)]
            dist.all_gather(placeholder, stats)
            stats = torch.stack(placeholder, dim=1).reshape(stats.size(0) * ws, *stats.shape[1:])

        # in distributed training, we only collect features at rank-0.
        if (dist.is_initialized() and dist.get_rank() == 0) or not dist.is_initialized():
            self.stats.append(stats.cpu())

    def feed(self, batch, mode):
        if mode == 'reals':
            return 0

        if self.num_images is None:
            self.feed_op(batch, mode)

        else:
            _, ws = get_dist_info()

            if self.num_fake_feeded == self.num_fake_need:
                return 0

            if isinstance(batch, dict):
                batch_size = len(list(batch.values())[0])
                end = min(batch_size, self.num_fake_need - self.num_fake_feeded)
                batch_to_feed = {k: v[:end] for k, v in batch.items()}
            else:
                batch_size = batch.shape[0]
                end = min(batch_size, self.num_fake_need - self.num_fake_feeded)
                batch_to_feed = batch[:end]

            global_end = min(batch_size * ws,
                             self.num_fake_need - self.num_fake_feeded)
            self.feed_op(batch_to_feed, mode)
            self.num_fake_feeded += global_end
            return end

    @torch.no_grad()
    def summary(self):
        stats = torch.cat(self.stats, dim=0)
        if self.num_images is not None:
            assert stats.shape[0] >= self.num_images
            stats = stats[:self.num_images]
        stats = stats.mean(dim=0)
        brightness, contrast, saturation = stats.tolist()
        self._result_dict = dict(
            brightness=brightness, contrast=contrast, saturation=saturation)
        self._result_str = f'Brightness: {brightness:.4f}, Contrast: {contrast:.4f}, Saturation: {saturation:.4f}'
        return brightness, contrast, saturation

    def clear_fake_data(self):
        self.stats = []
        self.num_fake_feeded = 0

    def clear(self, clear_reals=False):
        self.clear_fake_data()


@METRICS.register_module()
class HPSv2(Metric):
    name = 'HPSv2'
    requires_prompt = True

    def __init__(self,
                 num_images=None,
                 hps_version='v2.1'):
        super().__init__(num_images)
        self.hps_version = hps_version
        self.device = 'cpu'  # Initialize on CPU
        self.dtype = torch.float16
        self.model, self.tokenizer = load_hpsv2(hps_version, device=self.device, precision='fp16')
        self.model.eval()
        image_size = self.model.visual.image_size
        if isinstance(image_size, tuple):
            assert len(image_size) == 2 and image_size[0] == image_size[1]
            image_size = image_size[0]
        self.image_size = image_size
        self.image_mean = torch.tensor(self.model.visual.image_mean, device=self.device).view(3, 1, 1)
        self.image_std = torch.tensor(self.model.visual.image_std, device=self.device).view(3, 1, 1)

    def prepare(self):
        self.scores = []

    def resize(self, imgs):
        h, w = imgs.shape[2:]
        scale = self.image_size / float(max(h, w))
        if scale != 1.0:
            h = int(round(h * scale))
            w = int(round(w * scale))
            imgs = F.interpolate(imgs, size=(h, w), mode='bicubic', align_corners=False, antialias=True).clamp(0, 1)
        if h != w:
            pad_h = self.image_size - h
            pad_w = self.image_size - w
            imgs = F.pad(
                imgs, (pad_w // 2, pad_w - pad_w // 2, pad_h // 2, pad_h - pad_h // 2), mode='constant', value=0)
        return imgs

    @torch.no_grad()
    def feed_op(self, batch, mode):
        imgs = batch['imgs']
        prompts = batch['prompts']

        imgs = (imgs.to(device=self.device, dtype=torch.float32) / 2 + 0.5).clamp(0, 1)
        imgs = ((self.resize(imgs) - self.image_mean) / self.image_std).to(dtype=self.dtype)
        prompts = self.tokenizer(prompts).to(device=self.device)

        outputs = self.model(imgs, prompts)
        image_features, text_features = outputs['image_features'], outputs['text_features']
        hps_scores = (image_features * text_features).sum(dim=-1)  # (bs, )

        if dist.is_initialized():
            ws = dist.get_world_size()
            placeholder = [torch.empty_like(hps_scores) for _ in range(ws)]
            dist.all_gather(placeholder, hps_scores)
            hps_scores = torch.stack(placeholder, dim=1).reshape(hps_scores.size(0) * ws)

        if (dist.is_initialized() and dist.get_rank() == 0) or not dist.is_initialized():
            self.scores.append(hps_scores.float().cpu())

    def feed(self, batch, mode):
        if mode == 'reals':
            return 0

        if self.num_images is None:
            self.feed_op(batch, mode)

        else:
            _, ws = get_dist_info()

            if self.num_fake_feeded == self.num_fake_need:
                return 0

            if isinstance(batch, dict):
                batch_size = len(list(batch.values())[0])
                end = min(batch_size, self.num_fake_need - self.num_fake_feeded)
                batch_to_feed = {k: v[:end] for k, v in batch.items()}
            else:
                batch_size = batch.shape[0]
                end = min(batch_size, self.num_fake_need - self.num_fake_feeded)
                batch_to_feed = batch[:end]

            global_end = min(batch_size * ws,
                             self.num_fake_need - self.num_fake_feeded)
            self.feed_op(batch_to_feed, mode)
            self.num_fake_feeded += global_end
            return end

    @torch.no_grad()
    def summary(self):
        scores = torch.cat(self.scores, dim=0)
        if self.num_images is not None:
            assert scores.shape[0] >= self.num_images
            scores = scores[:self.num_images]
        mean_score = scores.mean().item()
        self._result_dict = dict(hpsv2=mean_score)
        self._result_str = f'HPSv2: {mean_score:.4f}'
        return mean_score

    def clear_fake_data(self):
        self.scores = []
        self.num_fake_feeded = 0

    def clear(self, clear_reals=False):
        self.clear_fake_data()

    def load_to_gpu(self):
        if torch.cuda.is_available():
            self.model.cuda()
            self.image_mean = self.image_mean.cuda()
            self.image_std = self.image_std.cuda()
            self.device = 'cuda'

    def offload_to_cpu(self):
        self.model.cpu()
        self.image_mean = self.image_mean.cpu()
        self.image_std = self.image_std.cpu()
        self.device = 'cpu'


@METRICS.register_module()
class CLIPSimilarity(Metric):
    """
    Average image–text CLIP cosine similarity (↑ better).
    Preprocess emulates OpenAI CLIP for ViT-L/14@336:
      - Resize so min(H, W) = 336 (bicubic, antialias), keep aspect ratio
      - Center crop to 336x336
      - Normalize with model.visual.image_mean/std
    Expects batch = {'imgs': (B,3,H,W) in [-1,1], 'prompts': List[str]}
    """
    name = 'CLIPSimilarity'
    requires_prompt = True

    def __init__(
        self,
        num_images=None,
        model_name='ViT-L-14-336-quickgelu',
        pretrained='openai',
        precision='fp16',   # 'fp16' | 'fp32' | 'bf16'
    ):
        super().__init__(num_images)
        self.model_name = model_name
        self.pretrained = pretrained
        self.precision = precision

        self.device = 'cpu'
        self.dtype = {
            'fp16': torch.float16,
            'bf16': torch.bfloat16,
            'fp32': torch.float32
        }.get(precision, torch.float16)

        self.model, self.tokenizer = load_openclip(
            model_name=model_name,
            pretrained=pretrained,
            device=self.device,
            precision=precision,
        )
        self.model.eval()

        # OpenAI ViT-L/14@336 uses square 336 input
        image_size = self.model.visual.image_size
        if isinstance(image_size, tuple):
            assert len(image_size) == 2 and image_size[0] == image_size[1]
            image_size = image_size[0]
        self.image_size = int(image_size)  # 336

        # Use the model's own stats for normalization
        self.image_mean = torch.tensor(self.model.visual.image_mean, device=self.device).view(3, 1, 1)
        self.image_std = torch.tensor(self.model.visual.image_std, device=self.device).view(3, 1, 1)

    def prepare(self):
        self.scores = []

    def _resize_min_side_then_center_crop(self, imgs):
        """
        imgs: (B,3,H,W) in [0,1], float32, on self.device
        1) Resize so min(H,W) == self.image_size, preserve AR (bicubic, antialias)
        2) Center-crop to (self.image_size, self.image_size)
        3) Normalize with model mean/std
        4) Cast to self.dtype
        """
        _, _, H, W = imgs.shape
        target = self.image_size

        # Scale factor so that the shorter side becomes 'target'
        short, long = (H, W) if H < W else (W, H)
        if short == 0:
            raise ValueError("Invalid image with zero dimension.")
        scale = target / float(short)

        new_h = max(1, int(round(H * scale)))
        new_w = max(1, int(round(W * scale)))
        if new_h != H or new_w != W:
            imgs = F.interpolate(
                imgs, size=(new_h, new_w),
                mode='bicubic', align_corners=False, antialias=True
            ).clamp(0, 1)

        # Center crop to target x target
        top = max(0, (new_h - target) // 2)
        left = max(0, (new_w - target) // 2)
        imgs = imgs[:, :, top:top + target, left:left + target]

        imgs = (imgs - self.image_mean) / self.image_std
        return imgs.to(dtype=self.dtype)

    @torch.no_grad()
    def feed_op(self, batch, mode):
        if mode == 'reals':
            return 0

        imgs = batch['imgs']
        prompts = batch['prompts']

        # [-1,1] -> [0,1]
        imgs = (imgs.to(device=self.device, dtype=torch.float32) / 2 + 0.5).clamp(0, 1)
        imgs = self._resize_min_side_then_center_crop(imgs)

        # Tokenize on device
        text = self.tokenizer(prompts).to(device=self.device)

        # Forward (create_model(..., output_dict=True)) => dict w/ features
        out = self.model(imgs, text)
        if isinstance(out, dict) and ('image_features' in out and 'text_features' in out):
            img_feat = out['image_features']
            txt_feat = out['text_features']
        else:
            img_feat = self.model.encode_image(imgs)
            txt_feat = self.model.encode_text(text)

        # Cosine similarity per pair
        img_feat = F.normalize(img_feat, dim=-1)
        txt_feat = F.normalize(txt_feat, dim=-1)
        sim = (img_feat * txt_feat).sum(dim=-1).to(torch.float32)  # (B,)

        # DDP gather
        if dist.is_initialized():
            ws = dist.get_world_size()
            bucket = [torch.empty_like(sim) for _ in range(ws)]
            dist.all_gather(bucket, sim)
            sim = torch.stack(bucket, dim=1).reshape(sim.size(0) * ws)

        if (dist.is_initialized() and dist.get_rank() == 0) or not dist.is_initialized():
            self.scores.append(sim.cpu())

    def feed(self, batch, mode):
        if mode == 'reals':
            return 0

        if self.num_images is None:
            self.feed_op(batch, mode)

        else:
            _, ws = get_dist_info()

            if self.num_fake_feeded == self.num_fake_need:
                return 0

            if isinstance(batch, dict):
                batch_size = len(list(batch.values())[0])
                end = min(batch_size, self.num_fake_need - self.num_fake_feeded)
                batch_to_feed = {k: v[:end] for k, v in batch.items()}
            else:
                batch_size = batch.shape[0]
                end = min(batch_size, self.num_fake_need - self.num_fake_feeded)
                batch_to_feed = batch[:end]

            global_end = min(batch_size * ws, self.num_fake_need - self.num_fake_feeded)
            self.feed_op(batch_to_feed, mode)
            self.num_fake_feeded += global_end
            return end

    @torch.no_grad()
    def summary(self):
        sims = torch.cat(self.scores, dim=0)
        if self.num_images is not None:
            assert sims.shape[0] >= self.num_images
            sims = sims[:self.num_images]
        mean_sim = sims.mean().item()

        self._result_dict = dict(clipsim=mean_sim)  # raw cosine in [-1,1]
        self._result_str = f'CLIPSim: {mean_sim:.4f}'
        return mean_sim

    def clear_fake_data(self):
        self.scores = []
        self.num_fake_feeded = 0

    def clear(self, clear_reals=False):
        self.clear_fake_data()

    def load_to_gpu(self):
        if torch.cuda.is_available():
            self.model.cuda()
            self.image_mean = self.image_mean.cuda()
            self.image_std = self.image_std.cuda()
            self.device = 'cuda'

    def offload_to_cpu(self):
        self.model.cpu()
        self.image_mean = self.image_mean.cpu()
        self.image_std = self.image_std.cpu()
        self.device = 'cpu'