File size: 52,788 Bytes
cb5f642
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
"""
Evaluate a single VLM on the 238 active (hard) cases.

Usage:
  python eval_active_cases.py \
      --model-name qwen3vl_finetuned \
      --frames-dir /mlx/users/jiashuo.fan/playground/inference/active_cases/frames_cache \
      --output-dir /mnt/bn/bohanzhainas1/jiashuo/exp/active_cases_eval

  # Override model path:
  python eval_active_cases.py --model-name internvl3_8b --model-path /some/other/path ...

Model types supported:
  qwen3vl   - Qwen3-VL (uses Qwen3VLForConditionalGeneration + qwen_vl_utils)
  qwen25vl  - Qwen2.5-VL / Qwen2-VL (uses Qwen2VLForConditionalGeneration + qwen_vl_utils)
  internvl  - InternVL (uses InternVLChatModel with trust_remote_code)
  llava     - LLaVA-OneVision (LlavaQwenForCausalLM)
  generic   - AutoModelForCausalLM with AutoProcessor / AutoTokenizer
"""

import argparse
import base64
import glob
import io
import json
import os
import re
import sys
import time
import traceback
import types
from pathlib import Path

# Stub xformers so models that optionally import it (e.g. CogVLM2) can still
# load without having xformers installed.  Replace memory_efficient_attention
# with PyTorch's scaled_dot_product_attention.
if "xformers" not in sys.modules:
    import torch as _torch
    _xops = types.ModuleType("xformers.ops")
    def _mem_eff_attn(query, key, value, attn_bias=None, scale=None, **kw):
        # xformers layout: (B, S, H, D); torch SDPA layout: (B, H, S, D)
        q = query.transpose(1, 2)
        k = key.transpose(1, 2)
        v = value.transpose(1, 2)
        out = _torch.nn.functional.scaled_dot_product_attention(
            q, k, v, attn_mask=attn_bias, scale=scale,
        )
        return out.transpose(1, 2)  # back to (B, S, H, D)
    _xops.memory_efficient_attention = _mem_eff_attn
    _xformers = types.ModuleType("xformers")
    _xformers.ops = _xops
    sys.modules["xformers"] = _xformers
    sys.modules["xformers.ops"] = _xops

from PIL import Image

# ── defaults ──────────────────────────────────────────────────────────────────

FRAMES_DIR  = Path("/mlx/users/jiashuo.fan/playground/inference/active_cases/frames_cache")
OUTPUT_DIR  = Path("/mnt/bn/bohanzhainas1/jiashuo/exp/active_cases_eval")
FRAMES_PER_VIDEO = 8     # subsample from the 16 stored frames
MAX_PIXELS       = 336 * 336
MAX_NEW_TOKENS   = 128
SAVE_INTERVAL    = 20

# ── SYSTEM prompt for non-fine-tuned models ───────────────────────────────────

BASE_SYSTEM_PROMPT = """You are an expert at analyzing pairs of TikTok videos for a "Proactive Publish" attribution task. Given two videos, you must determine whether watching Video 1 (consumption video) CAUSED or INSPIRED the user to create Video 2 (publish video).

label=1 means the videos are causally related (e.g., same meme/challenge/song, same viral format, same template).
label=0 means they are NOT causally related (they may be in the same broad category but lack direct inspiration).

You MUST respond with a JSON object and nothing else."""

BASE_USER_TEMPLATE = """Analyze these two TikTok videos:

Video 1 (consumption video - what the user watched):
{view_frames_placeholder}

Video 2 (publish video - what the user then created):
{pub_frames_placeholder}

Category: {class_name}

Did watching Video 1 CAUSE or INSPIRE the creation of Video 2?

Respond with JSON only:
{{"reasoning": "<brief explanation>", "label": 0 or 1}}"""

# ── helpers ───────────────────────────────────────────────────────────────────

def load_sample_files(frames_dir: Path) -> list[dict]:
    files = sorted(frames_dir.glob("*.json"))
    samples = []
    for f in files:
        try:
            data = json.loads(f.read_text())
            if data.get("source") == "failed" or not data.get("messages"):
                print(f"  [SKIP] {f.stem} (no frames / failed extraction)", flush=True)
                continue
            samples.append(data)
        except Exception as e:
            print(f"  [SKIP] {f.name}: {e}", flush=True)
    return samples


def b64_to_pil(b64_str: str) -> Image.Image:
    img = Image.open(io.BytesIO(base64.b64decode(b64_str))).convert("RGB")
    w, h = img.size
    if w * h > MAX_PIXELS:
        scale = (MAX_PIXELS / (w * h)) ** 0.5
        img = img.resize((int(w * scale), int(h * scale)), Image.BILINEAR)
    return img


def subsample_frames(frames: list[str], n: int = FRAMES_PER_VIDEO) -> list[str]:
    """Pick n evenly-spaced frames from a list of base64 frames."""
    if len(frames) <= n:
        return frames
    step = len(frames) / n
    return [frames[int(i * step)] for i in range(n)]


def parse_sample_for_finetuned(sample: dict) -> tuple[list, int]:
    """
    Parse sample in training format: return (content_items, gt_label).
    content_items match the format used during training.
    """
    msgs = sample["messages"]
    user_content = msgs[0]["content"]
    gt_text = msgs[1]["content"][0]["text"] if len(msgs) > 1 else '{"label": 1}'
    gt_label = extract_label(gt_text)

    content_items = []
    for item in user_content:
        if item["type"] == "video":
            frames = subsample_frames(item["video"], FRAMES_PER_VIDEO)
            for b64 in frames:
                content_items.append({"type": "image", "image": b64_to_pil(b64)})
        elif item["type"] == "text":
            content_items.append({"type": "text", "text": item["text"]})
        elif item["type"] == "image":
            content_items.append({"type": "image", "image": b64_to_pil(item["image"])})

    return content_items, gt_label


def parse_sample_for_base(sample: dict) -> tuple[list, int]:
    """
    Parse sample for non-fine-tuned models: build a natural language prompt
    with PIL images interleaved with text.
    """
    msgs = sample["messages"]
    user_content = msgs[0]["content"]
    gt_text = msgs[1]["content"][0]["text"] if len(msgs) > 1 else '{"label": 1}'
    gt_label = extract_label(gt_text)

    class_name = sample.get("class_name", "")

    # Collect video frame lists
    video_lists = []
    for item in user_content:
        if item["type"] == "video":
            video_lists.append(item["video"])

    view_frames_b64 = subsample_frames(video_lists[0], FRAMES_PER_VIDEO) if len(video_lists) > 0 else []
    pub_frames_b64  = subsample_frames(video_lists[1], FRAMES_PER_VIDEO) if len(video_lists) > 1 else []

    view_pil = [b64_to_pil(b) for b in view_frames_b64]
    pub_pil  = [b64_to_pil(b) for b in pub_frames_b64]

    return view_pil, pub_pil, class_name, gt_label


def extract_label(text: str) -> int | None:
    try:
        stripped = text.strip()
        if "```" in stripped:
            m = re.search(r"```(?:json)?\s*([\s\S]+?)```", stripped)
            if m:
                stripped = m.group(1).strip()
        return int(json.loads(stripped)["label"])
    except Exception:
        m = re.search(r'"label"\s*:\s*([01])', text)
        return int(m.group(1)) if m else None


def compute_stats(results: list[dict]) -> dict:
    from collections import defaultdict
    label_stats = defaultdict(lambda: {"tp": 0, "fp": 0, "fn": 0, "tn": 0})
    correct = evaluated = parse_fail = 0

    for r in results:
        if "error" in r:
            continue
        if r.get("pred_label") is None:
            parse_fail += 1
            continue
        gt, pred = r.get("gt_label"), r["pred_label"]
        if gt is None:
            continue
        evaluated += 1
        if gt == pred:
            correct += 1
        for label in [0, 1]:
            if gt == label and pred == label:
                label_stats[label]["tp"] += 1
            elif gt != label and pred == label:
                label_stats[label]["fp"] += 1
            elif gt == label and pred != label:
                label_stats[label]["fn"] += 1
            else:
                label_stats[label]["tn"] += 1

    per_class = {}
    for label, s in label_stats.items():
        tp, fp, fn = s["tp"], s["fp"], s["fn"]
        prec = tp / (tp + fp) if (tp + fp) > 0 else 0.0
        rec  = tp / (tp + fn) if (tp + fn) > 0 else 0.0
        f1   = 2 * prec * rec / (prec + rec) if (prec + rec) > 0 else 0.0
        per_class[str(label)] = {
            "precision": round(prec, 4),
            "recall":    round(rec, 4),
            "f1":        round(f1, 4),
            "support":   tp + fn,
        }

    return {
        "accuracy":       round(correct / evaluated, 4) if evaluated else 0.0,
        "correct":        correct,
        "evaluated":      evaluated,
        "parse_failures": parse_fail,
        "per_class":      per_class,
    }


def save_results(out_path: Path, model_name: str, model_path: str,
                 results: list, stats: dict):
    out_path.write_text(json.dumps({
        "model_name":     model_name,
        "model_path":     model_path,
        "frames_per_video": FRAMES_PER_VIDEO,
        "max_pixels":     MAX_PIXELS,
        "total_samples":  len(results),
        **stats,
        "results": results,
    }, ensure_ascii=False, indent=2))


# ══════════════════════════════════════════════════════════════════════════════
# Model loaders
# ══════════════════════════════════════════════════════════════════════════════

def load_qwen3vl(model_path: str):
    import torch
    from transformers import Qwen3VLForConditionalGeneration, AutoProcessor

    print(f"Loading Qwen3-VL from {model_path}", flush=True)
    model = Qwen3VLForConditionalGeneration.from_pretrained(
        model_path,
        torch_dtype=torch.bfloat16,
        attn_implementation="flash_attention_2",
        device_map="cuda:0",
        trust_remote_code=True,
    )
    model.eval()
    processor = AutoProcessor.from_pretrained(model_path, trust_remote_code=True)
    return model, processor


def load_qwen25vl(model_path: str):
    import torch
    from transformers import AutoProcessor

    print(f"Loading Qwen2-VL / Qwen2.5-VL from {model_path}", flush=True)
    # Qwen2.5-VL uses Qwen2_5_VLForConditionalGeneration; Qwen2-VL uses Qwen2VLForConditionalGeneration
    try:
        from transformers import Qwen2_5_VLForConditionalGeneration
        model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
            model_path,
            torch_dtype=torch.bfloat16,
            attn_implementation="flash_attention_2",
            device_map="cuda:0",
            trust_remote_code=True,
        )
        print("Loaded as Qwen2_5_VL", flush=True)
    except Exception:
        from transformers import Qwen2VLForConditionalGeneration
        model = Qwen2VLForConditionalGeneration.from_pretrained(
            model_path,
            torch_dtype=torch.bfloat16,
            attn_implementation="flash_attention_2",
            device_map="cuda:0",
            trust_remote_code=True,
        )
        print("Loaded as Qwen2VL (fallback)", flush=True)
    model.eval()
    processor = AutoProcessor.from_pretrained(model_path, trust_remote_code=True)
    return model, processor


def load_internvl(model_path: str):
    import torch
    from transformers import AutoModel, AutoTokenizer

    print(f"Loading InternVL from {model_path}", flush=True)
    model = AutoModel.from_pretrained(
        model_path,
        torch_dtype=torch.bfloat16,
        attn_implementation="flash_attention_2",
        device_map="cuda:0",
        trust_remote_code=True,
    )
    model.eval()
    tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
    return model, tokenizer


def load_llava(model_path: str):
    import torch
    from transformers import AutoProcessor, AutoModelForVision2Seq

    print(f"Loading LLaVA from {model_path}", flush=True)
    model = AutoModelForVision2Seq.from_pretrained(
        model_path,
        torch_dtype=torch.bfloat16,
        device_map="cuda:0",
        trust_remote_code=True,
    )
    model.eval()
    processor = AutoProcessor.from_pretrained(model_path, trust_remote_code=True)
    return model, processor


def load_llama32_vision(model_path: str):
    import torch
    from transformers import MllamaForConditionalGeneration, AutoProcessor

    print(f"Loading Llama-3.2-Vision from {model_path}", flush=True)
    model = MllamaForConditionalGeneration.from_pretrained(
        model_path,
        torch_dtype=torch.bfloat16,
        device_map="cuda:0",
    )
    model.eval()
    processor = AutoProcessor.from_pretrained(model_path)
    return model, processor


def load_phi3_vision(model_path: str):
    import torch
    from transformers import AutoModelForCausalLM, AutoProcessor

    print(f"Loading Phi-3.5-vision from {model_path}", flush=True)
    model = AutoModelForCausalLM.from_pretrained(
        model_path,
        torch_dtype=torch.bfloat16,
        device_map="cuda:0",
        trust_remote_code=True,
        _attn_implementation="flash_attention_2",
    )
    model.eval()
    processor = AutoProcessor.from_pretrained(model_path, trust_remote_code=True, num_crops=4)
    return model, processor


def load_minicpm_v(model_path: str):
    import torch
    from transformers import AutoModel, AutoTokenizer

    print(f"Loading MiniCPM-V from {model_path}", flush=True)
    model = AutoModel.from_pretrained(
        model_path,
        torch_dtype=torch.bfloat16,
        device_map="cuda:0",
        trust_remote_code=True,
    )
    model.eval()
    tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
    return model, tokenizer


def load_pixtral(model_path: str):
    import torch
    from transformers import LlavaForConditionalGeneration, AutoProcessor

    print(f"Loading Pixtral from {model_path}", flush=True)
    model = LlavaForConditionalGeneration.from_pretrained(
        model_path,
        torch_dtype=torch.bfloat16,
        device_map="cuda:0",
    )
    model.eval()
    processor = AutoProcessor.from_pretrained(model_path)
    return model, processor


def load_janus(model_path: str):
    import torch
    from transformers import AutoModelForCausalLM, AutoProcessor

    print(f"Loading Janus-Pro from {model_path}", flush=True)
    model = AutoModelForCausalLM.from_pretrained(
        model_path,
        torch_dtype=torch.bfloat16,
        device_map="cuda:0",
        trust_remote_code=True,
    )
    model.eval()
    processor = AutoProcessor.from_pretrained(model_path, trust_remote_code=True)
    return model, processor


def load_cogvlm2(model_path: str):
    import torch
    from transformers import AutoTokenizer, AutoModelForCausalLM
    print(f"Loading CogVLM2 from {model_path}", flush=True)
    tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
    model = AutoModelForCausalLM.from_pretrained(
        model_path,
        torch_dtype=torch.bfloat16,
        device_map="cuda:0",
        trust_remote_code=True,
    )
    model.eval()
    return model, tokenizer


def run_cogvlm2(model, tokenizer, view_pil: list, pub_pil: list, class_name: str) -> str:
    """Inference for CogVLM2 (requires build_conversation_input_ids)."""
    import torch
    from PIL import Image

    # CogVLM2 supports only a single image; create a 4x2 grid:
    #   top row: 4 frames from video 1, bottom row: 4 frames from video 2
    n = min(4, len(view_pil))
    m = min(4, len(pub_pil))
    frames = view_pil[:n] + pub_pil[:m]
    cell_w, cell_h = 224, 224
    cols = 4
    rows = (len(frames) + cols - 1) // cols
    grid = Image.new("RGB", (cols * cell_w, rows * cell_h), (0, 0, 0))
    for idx, fr in enumerate(frames):
        fr_r = fr.resize((cell_w, cell_h))
        grid.paste(fr_r, ((idx % cols) * cell_w, (idx // cols) * cell_h))

    query = (
        f"The image shows a grid of video frames: "
        f"top row has {n} frames from Video 1 (consumption), "
        f"bottom row has {m} frames from Video 2 (publish). "
        f"Category: {class_name}. "
        "Did watching Video 1 CAUSE or INSPIRE the creation of Video 2? "
        "label=1: causally related, label=0: not causally related. "
        'JSON only: {"reasoning": "...", "label": 0 or 1}'
    )

    input_by_model = model.build_conversation_input_ids(
        tokenizer,
        query=query,
        history=[],
        images=[grid],
        template_version="chat",
    )
    device = next(model.parameters()).device
    inputs = {
        "input_ids":      input_by_model["input_ids"].unsqueeze(0).to(device),
        "token_type_ids": input_by_model["token_type_ids"].unsqueeze(0).to(device),
        "attention_mask": input_by_model["attention_mask"].unsqueeze(0).to(device),
        "images":         [[img.to(device).to(torch.bfloat16)
                            for img in input_by_model["images"]]],
    }
    # Patch methods removed from transformers >= 4.46 that CogVLM2 relies on.
    if not hasattr(model, "_extract_past_from_model_output"):
        def _extract_past(model_output, standardize_cache_format=False):
            return getattr(model_output, "past_key_values", None)
        model._extract_past_from_model_output = _extract_past

    # Patch llm_forward to handle ((None,None),...) past_key_values from newer transformers
    _orig_llm_forward = model.model.llm_forward
    def _patched_llm_forward(self_or_first, *args, **kwargs):
        # Detect if called as bound method (self is model.model) or unbound
        if callable(_orig_llm_forward):
            # get past_key_values from kwargs or args
            pkv = kwargs.get("past_key_values", None)
            if pkv is not None and hasattr(pkv, "__len__"):
                # If all layers are None, treat as None
                if all((layer is None or (hasattr(layer, "__len__") and all(t is None for t in layer)))
                       for layer in pkv):
                    kwargs["past_key_values"] = None
        return _orig_llm_forward(*args, **kwargs) if args else _orig_llm_forward(**kwargs)
    # simpler: just patch at the module level
    import types as _types
    def _safe_llm_forward(self, *args, **kwargs):
        pkv = kwargs.get("past_key_values", None)
        if pkv is not None and hasattr(pkv, "__len__"):
            if all((layer is None or (hasattr(layer, "__len__") and all(t is None for t in layer)))
                   for layer in pkv):
                kwargs["past_key_values"] = None
        return _orig_llm_forward(*args, **kwargs)
    model.model.llm_forward = _types.MethodType(_safe_llm_forward, model.model)

    gen_kwargs = {
        "max_new_tokens": MAX_NEW_TOKENS,
        "pad_token_id":   tokenizer.eos_token_id,
        "do_sample":      False,
    }
    with torch.no_grad():
        outputs = model.generate(**inputs, **gen_kwargs)
        outputs = outputs[:, inputs["input_ids"].shape[1]:]
    return tokenizer.decode(outputs[0], skip_special_tokens=True)


def load_molmo(model_path: str):
    import sys, torch
    from transformers import AutoModelForCausalLM, AutoProcessor

    # Molmo's image_preprocessing_molmo.py has a conditional `import tensorflow` that
    # causes check_imports to fail if tensorflow is not installed.  Stub it out.
    if "tensorflow" not in sys.modules:
        # Create a permissive tensorflow stub: any attribute access returns a
        # no-op callable/class so Molmo's check_imports and processor don't crash.
        class _TFStub(types.ModuleType):
            def __getattr__(self, name):
                if name.startswith("_"):
                    raise AttributeError(name)
                # Return a dummy class / callable for unknown attrs
                dummy = type(name, (), {"__call__": lambda self, *a, **kw: False})()
                setattr(self, name, dummy)
                return dummy
        tf_stub = _TFStub("tensorflow")
        tf_stub.Tensor = type("Tensor", (), {})
        tf_stub.Variable = type("Variable", (), {})
        tf_stub.is_tensor = lambda x: False
        tf_stub.string = str
        tf_stub.float32 = "float32"
        tf_stub.int32 = "int32"
        _keras = _TFStub("tensorflow.keras")
        _keras_backend = _TFStub("tensorflow.keras.backend")
        _keras_backend.image_data_format = lambda: "channels_last"
        _keras.backend = _keras_backend
        tf_stub.keras = _keras
        tf_stub.io = _TFStub("tensorflow.io")
        sys.modules["tensorflow"] = tf_stub
        sys.modules["tensorflow.io"] = tf_stub.io
        sys.modules["tensorflow.keras"] = _keras
        sys.modules["tensorflow.keras.backend"] = _keras_backend

    print(f"Loading Molmo from {model_path}", flush=True)
    processor = AutoProcessor.from_pretrained(
        model_path, trust_remote_code=True,
        torch_dtype=torch.bfloat16,
    )
    model = AutoModelForCausalLM.from_pretrained(
        model_path,
        torch_dtype=torch.bfloat16,
        device_map="cuda:0",
        trust_remote_code=True,
    )
    model.eval()
    return model, processor


def load_moondream(model_path: str):
    import shutil, torch
    from pathlib import Path
    from transformers import AutoModelForCausalLM, AutoTokenizer

    # Pre-populate HF modules cache with ALL .py files from the local model dir
    # so that transformers' dynamic_module_utils can resolve all relative imports.
    model_name = Path(model_path).name
    cache_dir = Path.home() / ".cache" / "huggingface" / "modules" / "transformers_modules" / model_name
    if cache_dir.exists():
        shutil.rmtree(cache_dir)
    cache_dir.mkdir(parents=True, exist_ok=True)
    for py_file in Path(model_path).glob("*.py"):
        shutil.copy2(py_file, cache_dir / py_file.name)
    print(f"Pre-populated cache with {len(list(cache_dir.glob('*.py')))} .py files", flush=True)

    print(f"Loading Moondream from {model_path}", flush=True)
    model = AutoModelForCausalLM.from_pretrained(
        model_path,
        torch_dtype=torch.bfloat16,
        device_map="cuda:0",
        trust_remote_code=True,
    )
    model.eval()
    tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
    return model, tokenizer


def load_generic(model_path: str):
    """Generic loader: try AutoModelForCausalLM, fallback to AutoModelForVision2Seq, then AutoModel."""
    import torch
    from transformers import AutoModelForCausalLM, AutoModelForVision2Seq, AutoModel, AutoProcessor, AutoTokenizer

    print(f"Loading generic model from {model_path}", flush=True)
    try:
        processor = AutoProcessor.from_pretrained(model_path, trust_remote_code=True)
    except Exception:
        processor = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)

    load_kwargs = dict(torch_dtype=torch.bfloat16, device_map="cuda:0", trust_remote_code=True)
    model = None
    for cls in (AutoModelForCausalLM, AutoModelForVision2Seq, AutoModel):
        try:
            model = cls.from_pretrained(model_path, **load_kwargs)
            print(f"Loaded with {cls.__name__}", flush=True)
            break
        except Exception as e:
            print(f"  {cls.__name__} failed: {e}", flush=True)
    if model is None:
        raise RuntimeError(f"Could not load model from {model_path} with any loader")
    model.eval()
    return model, processor


# ══════════════════════════════════════════════════════════════════════════════
# Inference functions
# ══════════════════════════════════════════════════════════════════════════════

def run_qwenvl_finetuned(model, processor, content_items: list) -> str:
    """Inference for fine-tuned Qwen3-VL / Qwen2.5-VL (uses training message format)."""
    import torch
    from qwen_vl_utils import process_vision_info

    messages = [{"role": "user", "content": content_items}]
    text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
    image_inputs, _ = process_vision_info(messages)

    inputs = processor(
        text=[text],
        images=image_inputs,
        return_tensors="pt",
    ).to("cuda:0")

    with torch.no_grad():
        output_ids = model.generate(
            **inputs,
            max_new_tokens=MAX_NEW_TOKENS,
            do_sample=False,
            pad_token_id=processor.tokenizer.eos_token_id,
        )

    prompt_len = inputs["input_ids"].shape[1]
    return processor.decode(output_ids[0, prompt_len:], skip_special_tokens=True)


def run_qwenvl_base(model, processor, view_pil: list, pub_pil: list, class_name: str) -> str:
    """Inference for base/instruct Qwen3-VL / Qwen2.5-VL (natural language prompt)."""
    import torch
    from qwen_vl_utils import process_vision_info

    # Build content: system + interleaved images + text
    content = []

    content.append({"type": "text", "text": "Video 1 (consumption video):"})
    for img in view_pil:
        content.append({"type": "image", "image": img})

    content.append({"type": "text", "text": "\nVideo 2 (publish video):"})
    for img in pub_pil:
        content.append({"type": "image", "image": img})

    content.append({
        "type": "text",
        "text": (
            f"\nCategory: {class_name}\n\n"
            "Did watching Video 1 CAUSE or INSPIRE the creation of Video 2?\n"
            "label=1: causally related (same meme/challenge/song/template)\n"
            "label=0: not causally related\n\n"
            'Respond with JSON only: {"reasoning": "...", "label": 0 or 1}'
        ),
    })

    messages = [
        {"role": "system", "content": BASE_SYSTEM_PROMPT},
        {"role": "user",   "content": content},
    ]
    text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
    image_inputs, _ = process_vision_info(messages)

    inputs = processor(
        text=[text],
        images=image_inputs,
        return_tensors="pt",
    ).to("cuda:0")

    with torch.no_grad():
        output_ids = model.generate(
            **inputs,
            max_new_tokens=MAX_NEW_TOKENS,
            do_sample=False,
            pad_token_id=processor.tokenizer.eos_token_id,
        )

    prompt_len = inputs["input_ids"].shape[1]
    return processor.decode(output_ids[0, prompt_len:], skip_special_tokens=True)


def run_internvl(model, tokenizer, view_pil: list, pub_pil: list, class_name: str) -> str:
    """Inference for InternVL models."""
    import torch
    import torchvision.transforms as T
    from torchvision.transforms.functional import InterpolationMode

    IMAGENET_MEAN = (0.485, 0.456, 0.406)
    IMAGENET_STD  = (0.229, 0.224, 0.225)

    # Use 448 with downsample; each image β†’ 1 tile β†’ 256 tokens after pixel shuffle
    def build_transform(input_size=448):
        return T.Compose([
            T.Lambda(lambda img: img.convert("RGB")),
            T.Resize((input_size, input_size), interpolation=InterpolationMode.BICUBIC),
            T.ToTensor(),
            T.Normalize(mean=IMAGENET_MEAN, std=IMAGENET_STD),
        ])

    transform = build_transform(448)
    all_images = view_pil + pub_pil
    pixel_values = torch.stack([transform(img) for img in all_images]).to(torch.bfloat16).cuda()

    n_view = len(view_pil)
    n_pub  = len(pub_pil)

    # InternVL uses plain <image>\n tokens β€” one per image
    view_img_tokens = "<image>\n" * n_view
    pub_img_tokens  = "<image>\n" * n_pub

    question = (
        f"Video 1 (consumption video) - {n_view} frames:\n{view_img_tokens}"
        f"Video 2 (publish video) - {n_pub} frames:\n{pub_img_tokens}"
        f"Category: {class_name}\n\n"
        "Did watching Video 1 CAUSE or INSPIRE the creation of Video 2?\n"
        "label=1: causally related, label=0: not causally related\n\n"
        'Respond with JSON only: {"reasoning": "...", "label": 0 or 1}'
    )

    # num_patches_list: one tile per image
    num_patches_list = [1] * len(all_images)
    generation_config = dict(max_new_tokens=MAX_NEW_TOKENS, do_sample=False)

    response = model.chat(
        tokenizer,
        pixel_values,
        question,
        generation_config,
        num_patches_list=num_patches_list,
        history=None,
        return_history=False,
    )
    return response


def run_llava(model, processor, view_pil: list, pub_pil: list, class_name: str) -> str:
    """Inference for LLaVA-OneVision."""
    import torch

    # Build conversation with image tokens
    n_view = len(view_pil)
    n_pub  = len(pub_pil)

    view_img_str = "\n".join(["<image>"] * n_view)
    pub_img_str  = "\n".join(["<image>"] * n_pub)

    text_prompt = (
        f"Video 1 (consumption video):\n{view_img_str}\n\n"
        f"Video 2 (publish video):\n{pub_img_str}\n\n"
        f"Category: {class_name}\n\n"
        "Did watching Video 1 CAUSE or INSPIRE the creation of Video 2?\n"
        "label=1: causally related, label=0: not causally related\n\n"
        'Respond with JSON only: {"reasoning": "...", "label": 0 or 1}'
    )

    conversation = [
        {"role": "system", "content": BASE_SYSTEM_PROMPT},
        {"role": "user",   "content": text_prompt},
    ]

    all_images = view_pil + pub_pil
    prompt = processor.apply_chat_template(
        conversation, tokenize=False, add_generation_prompt=True
    )
    inputs = processor(
        images=all_images,
        text=prompt,
        return_tensors="pt",
    ).to("cuda:0")
    inputs = {k: v.to(torch.bfloat16) if v.dtype == torch.float32 else v
              for k, v in inputs.items()}

    with torch.no_grad():
        output_ids = model.generate(
            **inputs,
            max_new_tokens=MAX_NEW_TOKENS,
            do_sample=False,
        )

    prompt_len = inputs["input_ids"].shape[1]
    return processor.decode(output_ids[0, prompt_len:], skip_special_tokens=True)


def run_llama32_vision(model, processor, view_pil: list, pub_pil: list, class_name: str) -> str:
    """Inference for Llama-3.2-Vision."""
    import torch

    all_images = view_pil + pub_pil
    n_view = len(view_pil)
    n_pub  = len(pub_pil)

    view_img_str = "".join([f"<|image|>" for _ in view_pil])
    pub_img_str  = "".join([f"<|image|>" for _ in pub_pil])

    messages = [
        {"role": "user", "content": [
            {"type": "text", "text": (
                f"Video 1 (consumption video) - {n_view} frames:\n"
            )},
            *[{"type": "image"} for _ in view_pil],
            {"type": "text", "text": (
                f"\nVideo 2 (publish video) - {n_pub} frames:\n"
            )},
            *[{"type": "image"} for _ in pub_pil],
            {"type": "text", "text": (
                f"\nCategory: {class_name}\n\n"
                "Did watching Video 1 CAUSE or INSPIRE the creation of Video 2?\n"
                "label=1: causally related, label=0: not causally related\n\n"
                'Respond with JSON only: {"reasoning": "...", "label": 0 or 1}'
            )},
        ]},
    ]

    text = processor.apply_chat_template(messages, add_generation_prompt=True)
    inputs = processor(
        images=all_images,
        text=text,
        return_tensors="pt",
    ).to("cuda:0")

    with torch.no_grad():
        output_ids = model.generate(
            **inputs,
            max_new_tokens=MAX_NEW_TOKENS,
            do_sample=False,
        )

    prompt_len = inputs["input_ids"].shape[1]
    return processor.decode(output_ids[0, prompt_len:], skip_special_tokens=True)


def run_phi3_vision(model, processor, view_pil: list, pub_pil: list, class_name: str) -> str:
    """Inference for Phi-3.5-vision."""
    import torch

    # Phi-3.5 uses seen_tokens / get_usable_length on DynamicCache; patch if missing
    try:
        from transformers.cache_utils import DynamicCache
        if not hasattr(DynamicCache, "seen_tokens"):
            DynamicCache.seen_tokens = property(lambda self: self.get_seq_length())
        if not hasattr(DynamicCache, "get_usable_length"):
            def _get_usable_length(self, new_seq_length, layer_idx=0):
                return self.get_seq_length(layer_idx)
            DynamicCache.get_usable_length = _get_usable_length
    except Exception:
        pass

    all_images = view_pil + pub_pil
    n_view = len(view_pil)
    n_pub  = len(pub_pil)

    view_img_tags = "".join([f"<|image_{i+1}|>\n" for i in range(n_view)])
    pub_img_tags  = "".join([f"<|image_{n_view+i+1}|>\n" for i in range(n_pub)])

    messages = [
        {"role": "user", "content": (
            f"Video 1 (consumption video):\n{view_img_tags}"
            f"Video 2 (publish video):\n{pub_img_tags}"
            f"Category: {class_name}\n\n"
            "Did watching Video 1 CAUSE or INSPIRE the creation of Video 2?\n"
            "label=1: causally related, label=0: not causally related\n\n"
            'Respond with JSON only: {"reasoning": "...", "label": 0 or 1}'
        )},
    ]

    prompt = processor.tokenizer.apply_chat_template(
        messages, tokenize=False, add_generation_prompt=True
    )
    inputs = processor(prompt, all_images, return_tensors="pt").to("cuda:0")

    with torch.no_grad():
        output_ids = model.generate(
            **inputs,
            max_new_tokens=MAX_NEW_TOKENS,
            do_sample=False,
            eos_token_id=processor.tokenizer.eos_token_id,
        )

    prompt_len = inputs["input_ids"].shape[1]
    return processor.tokenizer.decode(output_ids[0, prompt_len:], skip_special_tokens=True)


def run_minicpm_v(model, tokenizer, view_pil: list, pub_pil: list, class_name: str) -> str:
    """Inference for MiniCPM-V."""
    import torch

    all_images = view_pil + pub_pil

    question = (
        f"Video 1 (consumption video) - {len(view_pil)} frames (shown above)\n"
        f"Video 2 (publish video) - {len(pub_pil)} frames (shown above)\n\n"
        f"Category: {class_name}\n\n"
        "Did watching Video 1 CAUSE or INSPIRE the creation of Video 2?\n"
        "label=1: causally related, label=0: not causally related\n\n"
        'Respond with JSON only: {"reasoning": "...", "label": 0 or 1}'
    )

    msgs = [{"role": "user", "content": all_images + [question]}]

    res = model.chat(
        image=None,
        msgs=msgs,
        tokenizer=tokenizer,
        sampling=False,
        max_new_tokens=MAX_NEW_TOKENS,
    )
    return res


def run_pixtral(model, processor, view_pil: list, pub_pil: list, class_name: str) -> str:
    """Inference for Pixtral-12B."""
    import torch

    all_images = view_pil + pub_pil
    n_view = len(view_pil)
    n_pub  = len(pub_pil)

    content = []
    content.append({"type": "text", "text": f"Video 1 (consumption video) - {n_view} frames:"})
    for _ in view_pil:
        content.append({"type": "image"})
    content.append({"type": "text", "text": f"\nVideo 2 (publish video) - {n_pub} frames:"})
    for _ in pub_pil:
        content.append({"type": "image"})
    content.append({"type": "text", "text": (
        f"\nCategory: {class_name}\n\n"
        "Did watching Video 1 CAUSE or INSPIRE the creation of Video 2?\n"
        "label=1: causally related, label=0: not causally related\n\n"
        'Respond with JSON only: {"reasoning": "...", "label": 0 or 1}'
    )})

    messages = [{"role": "user", "content": content}]

    text = processor.apply_chat_template(messages, add_generation_prompt=True)
    inputs = processor(
        images=all_images,
        text=text,
        return_tensors="pt",
    ).to("cuda:0")

    with torch.no_grad():
        output_ids = model.generate(
            **inputs,
            max_new_tokens=MAX_NEW_TOKENS,
            do_sample=False,
        )

    prompt_len = inputs["input_ids"].shape[1]
    return processor.decode(output_ids[0, prompt_len:], skip_special_tokens=True)


def run_janus(model, processor, view_pil: list, pub_pil: list, class_name: str) -> str:
    """Inference for Janus-Pro (DeepSeek multi-modal understanding)."""
    import torch

    all_images = view_pil + pub_pil
    n_view, n_pub = len(view_pil), len(pub_pil)

    # Janus uses image tokens in conversation format
    img_tags_view = "<image_placeholder>" * n_view
    img_tags_pub  = "<image_placeholder>" * n_pub

    conversation = [
        {"role": "User", "content": (
            f"Video 1 (consumption video) - {n_view} frames:\n{img_tags_view}\n"
            f"Video 2 (publish video) - {n_pub} frames:\n{img_tags_pub}\n\n"
            f"Category: {class_name}\n\n"
            "Did watching Video 1 CAUSE or INSPIRE the creation of Video 2?\n"
            "label=1: causally related, label=0: not causally related\n\n"
            'Respond with JSON only: {"reasoning": "...", "label": 0 or 1}'
        )},
        {"role": "Assistant", "content": ""},
    ]

    prepare = processor(
        conversations=conversation,
        images=all_images,
        force_batchify=True,
    ).to("cuda:0")

    inputs_embeds = model.prepare_inputs_embeds(**prepare)
    with torch.no_grad():
        output_ids = model.language_model.generate(
            inputs_embeds=inputs_embeds,
            attention_mask=prepare.attention_mask,
            pad_token_id=processor.tokenizer.eos_token_id,
            bos_token_id=processor.tokenizer.bos_token_id,
            eos_token_id=processor.tokenizer.eos_token_id,
            max_new_tokens=MAX_NEW_TOKENS,
            do_sample=False,
        )
    return processor.tokenizer.decode(output_ids[0].cpu(), skip_special_tokens=True)


def run_molmo(model, processor, view_pil: list, pub_pil: list, class_name: str) -> str:
    """Inference for Molmo (AllenAI)."""
    import torch

    all_images = view_pil + pub_pil

    prompt = (
        f"Video 1 (consumption video) - {len(view_pil)} frames and "
        f"Video 2 (publish video) - {len(pub_pil)} frames are shown above.\n"
        f"Category: {class_name}\n\n"
        "Did watching Video 1 CAUSE or INSPIRE the creation of Video 2?\n"
        "label=1: causally related, label=0: not causally related\n\n"
        'Respond with JSON only: {"reasoning": "...", "label": 0 or 1}'
    )

    inputs = processor.process(
        images=all_images,
        text=prompt,
    )
    inputs = {k: v.to("cuda:0").unsqueeze(0) if hasattr(v, "to") else v
              for k, v in inputs.items()}

    from transformers import GenerationConfig
    gen_cfg = getattr(model.config, "generation_config", None) or GenerationConfig(
        max_new_tokens=MAX_NEW_TOKENS, do_sample=False,
    )
    with torch.no_grad():
        output = model.generate_from_batch(
            inputs,
            generation_config=gen_cfg,
            max_new_tokens=MAX_NEW_TOKENS,
            do_sample=False,
        )
    generated = output[0, inputs["input_ids"].size(1):]
    return processor.tokenizer.decode(generated, skip_special_tokens=True)


def run_moondream(model, tokenizer, view_pil: list, pub_pil: list, class_name: str) -> str:
    """Inference for Moondream2."""
    # Moondream encodes each image independently, then does text generation
    question = (
        f"These are frames from two TikTok videos. "
        f"Video 1 ({len(view_pil)} frames) then Video 2 ({len(pub_pil)} frames). "
        f"Category: {class_name}. "
        "Did Video 1 CAUSE or INSPIRE the creation of Video 2? "
        "label=1: yes, label=0: no. "
        'JSON only: {"reasoning": "...", "label": 0 or 1}'
    )

    all_images = view_pil + pub_pil
    enc_images = [model.encode_image(img) for img in all_images]

    # Use first encoded image as primary, append others in question context
    answer = model.answer_question(
        enc_images[0],
        question,
        tokenizer,
        max_new_tokens=MAX_NEW_TOKENS,
    )
    return answer


def run_generic(model, processor, view_pil: list, pub_pil: list, class_name: str) -> str:
    """Inference for generic AutoModel (best-effort)."""
    import torch

    # Patch config.num_hidden_layers if missing (e.g. ChatGLM uses num_layers)
    cfg = getattr(model, "config", None)
    if cfg is not None and not hasattr(cfg, "num_hidden_layers"):
        for alt in ("num_layers", "n_layer", "n_layers"):
            if hasattr(cfg, alt):
                cfg.num_hidden_layers = getattr(cfg, alt)
                break

    all_images = view_pil + pub_pil
    n_view = len(view_pil)
    n_pub  = len(pub_pil)

    text_question = (
        f"Category: {class_name}\n\n"
        "Did watching Video 1 CAUSE or INSPIRE the creation of Video 2?\n"
        "label=1: causally related, label=0: not causally related\n\n"
        'Respond with JSON only: {"reasoning": "...", "label": 0 or 1}'
    )

    # Build messages using dict content (works for Idefics3 and most VLMs)
    # String content with <image> tokens gets stripped by some chat templates.
    user_content = (
        [{"type": "text", "text": "Video 1 (consumption video):"}]
        + [{"type": "image"} for _ in view_pil]
        + [{"type": "text", "text": "\nVideo 2 (publish video):"}]
        + [{"type": "image"} for _ in pub_pil]
        + [{"type": "text", "text": f"\n{text_question}"}]
    )
    messages = [
        {"role": "system", "content": BASE_SYSTEM_PROMPT},
        {"role": "user", "content": user_content},
    ]

    # Try dict-content template first; fall back to string-content template
    prompt = None
    if hasattr(processor, "apply_chat_template"):
        try:
            prompt = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
            # Verify image tokens are present
            img_token = getattr(processor, "image_token", "<image>")
            if img_token not in prompt and "<image" not in prompt:
                raise ValueError("no image tokens in template output")
        except Exception:
            # Fall back: string content with <image> placeholders
            view_img_str = "\n".join(["<image>"] * n_view)
            pub_img_str  = "\n".join(["<image>"] * n_pub)
            messages_str = [
                {"role": "system", "content": BASE_SYSTEM_PROMPT},
                {"role": "user", "content": (
                    f"Video 1 (consumption video):\n{view_img_str}\n\n"
                    f"Video 2 (publish video):\n{pub_img_str}\n\n{text_question}"
                )},
            ]
            try:
                prompt = processor.apply_chat_template(messages_str, tokenize=False, add_generation_prompt=True)
            except Exception:
                prompt = messages_str[-1]["content"]
    if prompt is None:
        view_img_str = "\n".join(["<image>"] * n_view)
        pub_img_str  = "\n".join(["<image>"] * n_pub)
        prompt = (f"Video 1:\n{view_img_str}\nVideo 2:\n{pub_img_str}\n{text_question}")

    try:
        if hasattr(processor, "image_processor") or hasattr(processor, "feature_extractor"):
            # Idefics3/SmolVLM requires images as List[List[PIL.Image]] (batch of samples)
            proc_cls = type(processor).__name__
            if "Idefics" in proc_cls or "SmolVLM" in proc_cls or hasattr(processor, "image_seq_len"):
                images_arg = [all_images]
            else:
                images_arg = all_images
            inputs = processor(
                images=images_arg,
                text=prompt,
                return_tensors="pt",
            ).to("cuda:0")
        else:
            inputs = processor(prompt, return_tensors="pt").to("cuda:0")
    except Exception:
        inputs = processor(prompt, return_tensors="pt").to("cuda:0")

    with torch.no_grad():
        output_ids = model.generate(
            **inputs,
            max_new_tokens=MAX_NEW_TOKENS,
            do_sample=False,
        )

    if hasattr(processor, "decode"):
        prompt_len = inputs["input_ids"].shape[1]
        return processor.decode(output_ids[0, prompt_len:], skip_special_tokens=True)
    else:
        return processor.batch_decode(output_ids, skip_special_tokens=True)[0]


# ══════════════════════════════════════════════════════════════════════════════
# Main
# ══════════════════════════════════════════════════════════════════════════════

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--model-name",   required=True,
                        help="Model name from models.py registry (e.g. qwen3vl_finetuned)")
    parser.add_argument("--model-path",   default=None,
                        help="Override model path (otherwise uses registry)")
    parser.add_argument("--model-type",   default=None,
                        help="Override model type: qwen3vl|qwen25vl|internvl|llava|generic")
    parser.add_argument("--finetuned",    action="store_true",
                        help="Use training-format prompt (for fine-tuned models)")
    parser.add_argument("--frames-dir",      default=str(FRAMES_DIR))
    parser.add_argument("--output-dir",      default=str(OUTPUT_DIR))
    parser.add_argument("--gpu-id",          type=int, default=0)
    parser.add_argument("--frames-per-video", type=int, default=None,
                        help="Override FRAMES_PER_VIDEO (default: 8)")
    args = parser.parse_args()

    if args.frames_per_video is not None:
        global FRAMES_PER_VIDEO
        FRAMES_PER_VIDEO = args.frames_per_video

    os.environ["CUDA_VISIBLE_DEVICES"] = str(args.gpu_id)

    # Resolve model config from registry
    sys.path.insert(0, str(Path(__file__).parent))
    from models import MODELS_BY_NAME

    registry = MODELS_BY_NAME.get(args.model_name, {})
    model_path = args.model_path or registry.get("model_path", args.model_name)
    model_type = args.model_type or registry.get("model_type", "generic")

    # Fine-tuned flag: auto-detect if model name is qwen3vl_finetuned, else use --finetuned flag
    is_finetuned = args.finetuned or (args.model_name == "qwen3vl_finetuned")

    print(f"Model:      {args.model_name}", flush=True)
    print(f"Model path: {model_path}", flush=True)
    print(f"Model type: {model_type}", flush=True)
    print(f"Fine-tuned: {is_finetuned}", flush=True)

    # Output
    out_dir  = Path(args.output_dir)
    out_dir.mkdir(parents=True, exist_ok=True)
    out_path = out_dir / f"{args.model_name}.json"

    # Load existing results (resume)
    done_keys: set[str] = set()
    results: list[dict] = []
    if out_path.exists():
        try:
            saved = json.loads(out_path.read_text())
            results = saved.get("results", [])
            done_keys = {r["key"] for r in results if "key" in r}
            print(f"Resuming: {len(done_keys)} already done", flush=True)
        except Exception:
            pass

    # Load samples
    frames_dir = Path(args.frames_dir)
    samples = load_sample_files(frames_dir)
    print(f"Loaded {len(samples)} samples from {frames_dir}", flush=True)

    pending = [s for s in samples
               if f"{s['view_gid']}_{s['pub_gid']}" not in done_keys]
    print(f"Pending: {len(pending)}", flush=True)

    if not pending:
        print("Nothing to evaluate!", flush=True)
        return

    # Load model
    loader_map = {
        "qwen3vl":         load_qwen3vl,
        "qwen25vl":        load_qwen25vl,
        "internvl":        load_internvl,
        "llava":           load_llava,
        "llama32_vision":  load_llama32_vision,
        "phi3_vision":     load_phi3_vision,
        "minicpm_v":       load_minicpm_v,
        "pixtral":         load_pixtral,
        "janus":           load_janus,
        "molmo":           load_molmo,
        "moondream":       load_moondream,
        "cogvlm2":         load_cogvlm2,
        "generic":         load_generic,
    }
    loader = loader_map.get(model_type, load_generic)
    model, processor = loader(model_path)

    # Inference loop
    t0 = time.time()
    for i, sample in enumerate(pending):
        key = f"{sample['view_gid']}_{sample['pub_gid']}"
        result = {
            "key":        key,
            "view_gid":   sample["view_gid"],
            "pub_gid":    sample["pub_gid"],
            "class_name": sample.get("class_name", ""),
        }

        try:
            if is_finetuned and model_type in ("qwen3vl", "qwen25vl"):
                content_items, gt_label = parse_sample_for_finetuned(sample)
                pred_text = run_qwenvl_finetuned(model, processor, content_items)
            else:
                view_pil, pub_pil, class_name, gt_label = parse_sample_for_base(sample)

                if model_type in ("qwen3vl", "qwen25vl"):
                    pred_text = run_qwenvl_base(model, processor, view_pil, pub_pil, class_name)
                elif model_type == "internvl":
                    pred_text = run_internvl(model, processor, view_pil, pub_pil, class_name)
                elif model_type == "llava":
                    pred_text = run_llava(model, processor, view_pil, pub_pil, class_name)
                elif model_type == "llama32_vision":
                    pred_text = run_llama32_vision(model, processor, view_pil, pub_pil, class_name)
                elif model_type == "phi3_vision":
                    pred_text = run_phi3_vision(model, processor, view_pil, pub_pil, class_name)
                elif model_type == "minicpm_v":
                    pred_text = run_minicpm_v(model, processor, view_pil, pub_pil, class_name)
                elif model_type == "pixtral":
                    pred_text = run_pixtral(model, processor, view_pil, pub_pil, class_name)
                elif model_type == "janus":
                    pred_text = run_janus(model, processor, view_pil, pub_pil, class_name)
                elif model_type == "molmo":
                    pred_text = run_molmo(model, processor, view_pil, pub_pil, class_name)
                elif model_type == "moondream":
                    pred_text = run_moondream(model, processor, view_pil, pub_pil, class_name)
                elif model_type == "cogvlm2":
                    pred_text = run_cogvlm2(model, processor, view_pil, pub_pil, class_name)
                else:
                    pred_text = run_generic(model, processor, view_pil, pub_pil, class_name)

            pred_label = extract_label(pred_text)
            result.update({
                "gt_label":   gt_label,
                "pred_label": pred_label,
                "match":      (pred_label == gt_label) if (pred_label is not None and gt_label is not None) else None,
                "prediction": pred_text,
            })
        except Exception as e:
            result["error"] = str(e)
            result["traceback"] = traceback.format_exc()[:500]
            print(f"  ERROR on {key}: {e}", flush=True)

        results.append(result)
        done_keys.add(key)

        # Progress
        elapsed = time.time() - t0
        speed = (i + 1) / elapsed
        total_done = len(done_keys)
        stats = compute_stats(results)
        print(
            f"[{total_done}/{len(samples)}] {key} | "
            f"acc={stats['accuracy']:.3f} "
            f"(correct={stats['correct']}/{stats['evaluated']}) "
            f"| {speed:.2f} samp/s",
            flush=True,
        )

        # Save periodically
        if (i + 1) % SAVE_INTERVAL == 0:
            stats = compute_stats(results)
            save_results(out_path, args.model_name, model_path, results, stats)

    # Final save
    stats = compute_stats(results)
    save_results(out_path, args.model_name, model_path, results, stats)

    elapsed = time.time() - t0
    print(f"\n{'='*60}", flush=True)
    print(f"DONE  model={args.model_name}", flush=True)
    print(f"  accuracy:  {stats['accuracy']:.4f} ({stats['correct']}/{stats['evaluated']})", flush=True)
    print(f"  per-class: {json.dumps(stats['per_class'], indent=4)}", flush=True)
    print(f"  parse_failures: {stats['parse_failures']}", flush=True)
    print(f"  time: {elapsed:.1f}s  ({len(results)/elapsed:.2f} samp/s)", flush=True)
    print(f"  saved -> {out_path}", flush=True)


if __name__ == "__main__":
    main()