-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodel.py
More file actions
1612 lines (1350 loc) · 57.8 KB
/
Copy pathmodel.py
File metadata and controls
1612 lines (1350 loc) · 57.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Model definitions for AS-TIME.
The proposed model is ``ASTIME`` (time-conditioned multimodal fusion:
MIL -> delta_t-conditioned gated fusion -> delta_t-guided MoE). The
remaining classes are the Table 1 comparison baselines. Use the
``ASTimeModel`` factory at the bottom of this file to instantiate a model
from a set of modality / fusion flags.
"""
from typing import Dict, Any, List, Optional, Tuple
import math
import torch
from torch import nn
from torch.nn import functional as F
from time_embedding import TimePosConfig, PosEmbedding, build_time_features
def _to_device_if_needed(tensor: torch.Tensor, device: torch.device) -> torch.Tensor:
if tensor.device == device:
return tensor
return tensor.to(device, non_blocking=True)
# ===========================================================================
# Baselines (Table 1 comparison methods)
# ===========================================================================
class TransformerAggregator(nn.Module):
"""
Aggregator with attention export.
- returns CLS embedding
- optionally returns attention from CLS to input tokens (avg over heads)
"""
def __init__(self, dim: int, n_heads: int = 4, dropout: float = 0.3):
super().__init__()
self.cls_token = nn.Parameter(torch.zeros(1, 1, dim))
self.attn = nn.MultiheadAttention(embed_dim=dim, num_heads=n_heads,
dropout=dropout, batch_first=True)
self.ln1 = nn.LayerNorm(dim)
self.ff = nn.Sequential(
nn.Linear(dim, 4 * dim),
nn.ReLU(),
nn.Dropout(dropout),
nn.Linear(4 * dim, dim),
)
self.ln2 = nn.LayerNorm(dim)
def forward(self, x: torch.Tensor, return_attn: bool = False):
"""
x: [N, D] or [B, N, D]
return_attn:
- if True: returns (cls_emb, attn_cls) where attn_cls is [B, N]
(attention weights from CLS to each input token, averaged over heads)
"""
squeeze_back = False
if x.ndim == 2:
x = x.unsqueeze(0) # [1, N, D]
squeeze_back = True
B, N, D = x.shape
cls = self.cls_token.expand(B, 1, D) # [B,1,D]
x = torch.cat([cls, x], dim=1) # [B,1+N,D]
# Self-attn
attn_out, attn_w = self.attn(x, x, x, need_weights=True, average_attn_weights=False)
# attn_w: [B, num_heads, (1+N), (1+N)]
x = self.ln1(x + attn_out)
x = self.ln2(x + self.ff(x))
cls_out = x[:, 0, :] # [B,D]
if squeeze_back:
cls_out = cls_out.squeeze(0) # [D]
if not return_attn:
return cls_out
# CLS attending to input tokens only (exclude CLS itself)
# attn_w[:, :, 0, 1:] -> [B, heads, N]
attn_cls = attn_w[:, :, 0, 1:].mean(dim=1) # [B, N]
if squeeze_back:
attn_cls = attn_cls.squeeze(0) # [N]
return cls_out, attn_cls
class ASVideoOnlyModel(nn.Module):
"""
Video-only AS-time model.
- Input: per-video embeddings (each video = 1 token)
- No reports, no time
- Pipeline: video_proj -> TransformerAggregator -> classifier
Forward is kept compatible:
forward(video_0, view_0, report0_cls, delta_t) -> logits [B, num_classes]
Only video_0 is used.
"""
def __init__(
self,
video_dim: int = 512,
d_model: int = 256,
num_classes: int = 4,
dropout: float = 0.3,
n_heads: int = 4,
):
super().__init__()
self.d_model = d_model
self.num_classes = num_classes
# Project raw EchoPrime video embeddings -> latent space
self.video_proj = nn.Linear(video_dim, d_model)
# Aggregate across all videos for the study
self.video_aggregator = TransformerAggregator(dim=d_model, n_heads=n_heads, dropout=dropout)
# Simple MLP classifier on the study-level video embedding
hidden_dim = d_model * 2
self.classifier = nn.Sequential(
nn.LayerNorm(d_model),
nn.Linear(d_model, hidden_dim),
nn.ReLU(),
nn.Dropout(dropout),
nn.Linear(hidden_dim, num_classes),
)
# def encode_study_videos(self, videos: torch.Tensor, return_attn: bool = False) -> torch.Tensor:
# """
# videos: [N_videos, video_dim]
# returns: [d_model] study-level video embedding
# """
# if videos is None or videos.numel() == 0:
# raise ValueError("encode_video_tokens: videos is None")
# if torch.isnan(videos).any() or torch.isinf(videos).any():
# raise ValueError(f"videos contain NaN or Inf values: {videos}")
# v = self.video_proj(videos) # [N_v, d_model]
# v_emb = self.video_aggregator(v, return_attn=return_attn) # [d_model] - get the cls tokens summarizing all video embeddings
# return v_emb
def encode_study_videos(self, videos: torch.Tensor, return_attn: bool = False):
v = self.video_proj(videos) # [N_v, d_model]
if return_attn:
cls_emb, attn = self.video_aggregator(v, return_attn=True) # attn: [N_v]
return cls_emb, attn
else:
cls_emb = self.video_aggregator(v, return_attn=False)
return cls_emb
def forward(
self,
video_0: List[torch.Tensor], # list of [N0_i, video_dim]
view_0: List[torch.Tensor], # unused
report0_cls: List[torch.Tensor], # unused
delta_t: torch.Tensor, # unused
) -> torch.Tensor:
"""
Returns logits: [B, num_classes]
"""
device = next(self.parameters()).device
B = len(video_0)
vid_emb_list = []
for i in range(B):
v0 = video_0[i].to(device) # [N0_i, video_dim]
vid_emb = self.encode_study_videos(v0, return_attn=False) # [d_model]
vid_emb_list.append(vid_emb)
vid_batch = torch.stack(vid_emb_list, dim=0) # [B, d_model]
logits = self.classifier(vid_batch) # [B, num_classes]
return logits
class ASReportOnlyModel(nn.Module):
"""
Report-only AS-time model.
- Input: per-sentence CLS embeddings for study 0 (report0_cls)
- No videos, no time
- Pipeline: report_proj -> TransformerAggregator -> classifier
Forward signature kept compatible with your training loop.
Only report0_cls is used.
"""
def __init__(
self,
report_dim: int = 768,
d_model: int = 256,
num_classes: int = 4,
dropout: float = 0.3,
n_heads: int = 4,
):
super().__init__()
self.d_model = d_model
self.num_classes = num_classes
self.report_proj = nn.Linear(report_dim, d_model)
self.report_aggregator = TransformerAggregator(dim=d_model, n_heads=n_heads, dropout=dropout)
hidden_dim = d_model * 2
self.classifier = nn.Sequential(
nn.LayerNorm(d_model),
nn.Linear(d_model, hidden_dim),
nn.ReLU(),
nn.Dropout(dropout),
nn.Linear(hidden_dim, num_classes),
)
# def encode_study_report(self, report_cls: torch.Tensor) -> torch.Tensor:
# """
# report_cls: [N_sentences, report_dim]
# returns: [d_model] study-level report embedding
# """
# if report_cls is None or report_cls.numel() == 0:
# raise ValueError("encode_study_tokens: report is None")
# if torch.isnan(report_cls).any() or torch.isinf(report_cls).any():
# raise ValueError(f"report_cls contains NaN or Inf values: {report_cls}")
# rep = self.report_proj(report_cls) # [N_s, d_model]
# rep_emb = self.report_aggregator(rep) # [d_model]
# return rep_emb
def encode_study_report(self, report_cls: torch.Tensor, return_attn: bool = False):
rep = self.report_proj(report_cls) # [N_s, d_model]
if return_attn:
cls_emb, attn = self.report_aggregator(rep, return_attn=True) # attn: [N_s]
return cls_emb, attn
else:
cls_emb = self.report_aggregator(rep, return_attn=False)
return cls_emb
def forward(
self,
video_0: List[torch.Tensor], # unused
view_0: List[torch.Tensor], # unused
report0_cls: List[torch.Tensor], # list of [M0_i, report_dim]
delta_t: torch.Tensor, # unused
) -> torch.Tensor:
"""
Returns logits: [B, num_classes]
"""
device = next(self.parameters()).device
B = len(report0_cls)
rep_emb_list = []
for i in range(B):
r0 = report0_cls[i].to(device) # [M0_i, report_dim]
rep_emb = self.encode_study_report(r0) # [d_model]
rep_emb_list.append(rep_emb)
rep_batch = torch.stack(rep_emb_list, dim=0) # [B, d_model]
logits = self.classifier(rep_batch) # [B, num_classes]
return logits
class ASTimeOnlyModel(nn.Module):
"""
Time-only AS-time model.
- Input: scalar delta_t for each pair (days)
- No videos, no reports
- Pipeline: build_time_features(delta_t) -> PosEmbedding -> classifier
Forward signature kept compatible; only delta_t is used.
"""
def __init__(
self,
d_model: int = 256,
num_classes: int = 4,
dropout: float = 0.3,
):
super().__init__()
self.d_model = d_model
self.num_classes = num_classes
# Time encoder config
self.time_cfg = TimePosConfig(
emb_dim=d_model,
seq_length=1,
pos_emb="temporal",
n_time_features=1,
temperature=10000.0,
)
self.time_pos = PosEmbedding(self.time_cfg, emb_dim=d_model)
self.use_log_standardize = True
self.register_buffer("mean_log", torch.zeros(1))
self.register_buffer("std_log", torch.ones(1))
hidden_dim = d_model * 2
self.classifier = nn.Sequential(
nn.LayerNorm(d_model),
nn.Linear(d_model, hidden_dim),
nn.ReLU(),
nn.Dropout(dropout),
nn.Linear(hidden_dim, num_classes),
)
self.scalar_proj = nn.Linear(1, d_model)
# def encode_time_batch(self, delta_t: torch.Tensor) -> torch.Tensor:
# """
# delta_t: [B] tensor of scalars
# returns: [B, d_model] time embeddings
# """
# if delta_t is None or delta_t.numel() == 0:
# raise ValueError("No delta_t values provided.")
# if torch.isnan(delta_t).any() or torch.isinf(delta_t).any():
# raise ValueError(f"delta_t contains NaN or Inf values: {delta_t}")
# if delta_t.ndim > 1:
# delta_t = delta_t.view(-1) # [B]
# time_feats = build_time_features(delta_t) # [B, 1, n_time_features]
# t_emb = self.time_pos(time_feats) # [B, 1, d_model]
# t_emb = t_emb.squeeze(1) # [B, d_model]
# return t_emb
@torch.no_grad()
def set_time_stats(self, mean_log: float, std_log: float):
self.mean_log.fill_(float(mean_log))
self.std_log.fill_(float(std_log))
# return
def encode_time_batch(self, delta_t: torch.Tensor) -> torch.Tensor:
if delta_t is None or delta_t.numel() == 0:
raise ValueError("No delta_t values provided.")
if torch.isnan(delta_t).any() or torch.isinf(delta_t).any():
raise ValueError(f"delta_t contains NaN or Inf values: {delta_t}")
if delta_t.ndim > 1:
delta_t = delta_t.view(-1) # [B]
if self.use_log_standardize:
delta_t = torch.log1p(delta_t)
delta_t = (delta_t - self.mean_log) / (self.std_log + 1e-8)
time_feats = build_time_features(delta_t) # [B, 1, 1]
t_emb = self.time_pos(time_feats) # [B, 1, d_model]
return t_emb.squeeze(1) # [B, d_model]
# def encode_time_batch(self, delta_t: torch.Tensor) -> torch.Tensor:
# if delta_t is None or delta_t.numel() == 0:
# raise ValueError("No delta_t values provided.")
# if torch.isnan(delta_t).any() or torch.isinf(delta_t).any():
# raise ValueError(f"delta_t contains NaN or Inf values: {delta_t}")
# if delta_t.ndim > 1:
# delta_t = delta_t.view(-1) # [B]
# # OPTIONAL: keep log+standardization for fairness
# if self.use_log_standardize:
# delta_t = torch.log1p(delta_t)
# delta_t = (delta_t - self.mean_log) / (self.std_log + 1e-8)
# # ---- NEW PART ----
# delta_t = delta_t.unsqueeze(-1) # [B, 1]
# return self.scalar_proj(delta_t)
def forward(
self,
video_0: List[torch.Tensor], # unused
view_0: List[torch.Tensor], # unused
report0_cls: List[torch.Tensor], # unused
delta_t: torch.Tensor, # [B]
) -> torch.Tensor:
"""
Returns logits: [B, num_classes]
"""
device = next(self.parameters()).device
delta_t = delta_t.to(device) # [B]
t_emb = self.encode_time_batch(delta_t)
logits = self.classifier(t_emb)
return logits
class ASMLP(nn.Module):
"""
Multi-modal AS-time model (MLP fusion).
- Supports any 2 or 3 of: video, report, time.
- For each used modality, we get a [B, d_model] study-level embedding,
then concatenate -> [B, M * d_model] (M = #modalities) and feed to an MLP classifier.
Forward signature is kept compatible with your training loop:
forward(video_0, view_0, report0_cls, delta_t) -> logits [B, num_classes]
"""
def __init__(
self,
video_dim: int = 512,
report_dim: int = 768,
d_model: int = 256,
num_classes: int = 4,
dropout: float = 0.3,
n_heads: int = 4,
use_video: bool = False,
use_report: bool = False,
use_time: bool = False,
):
super().__init__()
# ---- which modalities are used ----
self.use_video = use_video
self.use_report = use_report
self.use_time = use_time
active_count = int(use_video) + int(use_report) + int(use_time)
self.active_modalities = active_count
# if (use_video + use_report + use_time) != 2:
# raise ValueError(
# "ASBiModalMLP expects EXACTLY two of "
# "use_video/use_report/use_time to be True."
# )
self.d_model = d_model
self.num_classes = num_classes
# ---- video branch (if used) ----
if self.use_video:
self.video_proj = nn.Linear(video_dim, d_model)
self.video_aggregator = TransformerAggregator(
dim=d_model,
n_heads=n_heads,
dropout=dropout,
)
# ---- report branch (if used) ----
if self.use_report:
self.report_proj = nn.Linear(report_dim, d_model)
self.report_aggregator = TransformerAggregator(
dim=d_model,
n_heads=n_heads,
dropout=dropout,
)
# ---- time branch (if used) ----
if self.use_time:
# # Simple scalar -> d_model projection, same flavour as ASTimeOnlyModel
# self.scalar_proj = nn.Linear(1, d_model)
# Time encoder config
self.time_cfg = TimePosConfig(
emb_dim=d_model,
seq_length=1,
pos_emb="temporal",
n_time_features=1,
temperature=10000.0,
)
self.time_pos = PosEmbedding(self.time_cfg, emb_dim=d_model)
self.use_log_standardize = True
self.register_buffer("mean_log", torch.zeros(1))
self.register_buffer("std_log", torch.ones(1))
# ---- classifier: (M * d_model) -> num_classes ----
fused_dim = self.active_modalities * d_model
hidden_dim = fused_dim * 2
self.classifier = nn.Sequential(
nn.LayerNorm(fused_dim),
nn.Linear(fused_dim, hidden_dim),
nn.ReLU(),
nn.Dropout(dropout),
nn.Linear(hidden_dim, num_classes),
)
# --------- helpers: encoders per modality ---------
def encode_study_videos(self, videos: torch.Tensor) -> torch.Tensor:
"""
videos: [N_v, video_dim]
returns: [d_model] study-level video embedding
"""
v = self.video_proj(videos) # [N_v, d_model]
cls_emb = self.video_aggregator(v, return_attn=False) # [d_model]
return cls_emb
def encode_study_report(self, report_cls: torch.Tensor) -> torch.Tensor:
"""
report_cls: [N_s, report_dim]
returns: [d_model] study-level report embedding
"""
rep = self.report_proj(report_cls) # [N_s, d_model]
cls_emb = self.report_aggregator(rep, return_attn=False) # [d_model]
return cls_emb
# def encode_time_batch(self, delta_t: torch.Tensor) -> torch.Tensor:
# """
# delta_t: [B] raw (or preprocessed) time gaps in days.
# returns: [B, d_model]
# """
# if delta_t is None or delta_t.numel() == 0:
# raise ValueError("No delta_t values provided.")
# if torch.isnan(delta_t).any() or torch.isinf(delta_t).any():
# raise ValueError(f"delta_t contains NaN or Inf values: {delta_t}")
# if delta_t.ndim > 1:
# delta_t = delta_t.view(-1) # [B]
# delta_t = delta_t.unsqueeze(-1) # [B, 1]
# return self.scalar_proj(delta_t) # [B, d_model]
# @torch.no_grad()
# def set_time_stats(self, *args, **kwargs):
# """
# Kept for API compatibility with time-standardized models.
# No-op here (we're using raw/scalar-projected time).
# """
# return
@torch.no_grad()
def set_time_stats(self, mean_log: float, std_log: float):
self.mean_log.fill_(float(mean_log))
self.std_log.fill_(float(std_log))
# return
def encode_time_batch(self, delta_t: torch.Tensor) -> torch.Tensor:
if delta_t is None or delta_t.numel() == 0:
raise ValueError("No delta_t values provided.")
if torch.isnan(delta_t).any() or torch.isinf(delta_t).any():
raise ValueError(f"delta_t contains NaN or Inf values: {delta_t}")
if delta_t.ndim > 1:
delta_t = delta_t.view(-1) # [B]
if self.use_log_standardize:
delta_t = torch.log1p(delta_t)
delta_t = (delta_t - self.mean_log) / (self.std_log + 1e-8)
time_feats = build_time_features(delta_t) # [B, 1, 1]
t_emb = self.time_pos(time_feats) # [B, 1, d_model]
return t_emb.squeeze(1) # [B, d_model]
# --------- forward ---------
def forward(
self,
video_0: List[torch.Tensor], # list of [N_v_i, video_dim]
view_0: List[torch.Tensor], # unused, for API compatibility
report0_cls: List[torch.Tensor], # list of [N_s_i, report_dim]
delta_t: torch.Tensor, # [B]
) -> torch.Tensor:
"""
Returns logits: [B, num_classes]
"""
device = next(self.parameters()).device
# Infer batch size safely from available inputs
B_candidates = []
if self.use_video:
B_candidates.append(len(video_0))
if self.use_report:
B_candidates.append(len(report0_cls))
if self.use_time:
B_candidates.append(delta_t.size(0))
B = B_candidates[0] if B_candidates else 0
if B == 0:
raise ValueError("Empty batch passed to ASMLP")
# ---- encode each used modality to [B, d_model] ----
modal_embs = []
if self.use_video:
vid_emb_list = []
for i in range(B):
v0 = video_0[i].to(device) # [N_v_i, video_dim]
vid_emb = self.encode_study_videos(v0) # [d_model]
vid_emb_list.append(vid_emb)
vid_emb = torch.stack(vid_emb_list, dim=0) # [B, d_model]
modal_embs.append(vid_emb)
if self.use_report:
rep_emb_list = []
for i in range(B):
r0 = report0_cls[i].to(device) # [N_s_i, report_dim]
rep_emb = self.encode_study_report(r0) # [d_model]
rep_emb_list.append(rep_emb)
rep_emb = torch.stack(rep_emb_list, dim=0) # [B, d_model]
modal_embs.append(rep_emb)
if self.use_time:
t_emb = self.encode_time_batch(delta_t.to(device)) # [B, d_model]
modal_embs.append(t_emb)
# # We asserted exactly two modalities are True → modal_embs has length 2
# if len(modal_embs) != 2:
# raise RuntimeError("ASBiModalMLP internal error: expected 2 modality embeddings.")
fused = torch.cat(modal_embs, dim=-1) # [B, 2 * d_model]
logits = self.classifier(fused) # [B, num_classes]
return logits
class ASTimeModel_CrossAttn(nn.Module):
"""
AS-time model with report/time-guided video interpretation via cross-attention.
- Video: per-video embeddings (each video = 1 token; all videos kept)
- Report: per-sentence CLS embeddings -> TransformerAggregator -> 1 report token
- Time: scalar delta_t -> 1 time token via temporal positional embedding
- Cross-attn: (report + time) tokens query the video tokens (K/V)
- Summaries: video / report / time -> concat -> classifier
Forward signature:
forward(video_0, view_0, report0_cls, delta_t) -> logits [B, num_classes]
"""
def __init__(
self,
video_dim: int = 512,
report_dim: int = 768,
d_model: int = 256,
num_classes: int = 2, # early/significant
dropout: float = 0.3,
n_heads: int = 4,
use_video: bool = True,
use_report: bool = True,
use_time: bool = True,
):
super().__init__()
self.d_model = d_model
self.num_classes = num_classes
self.use_video = use_video
self.use_report = use_report
self.use_time = use_time
# Project raw embeddings into shared latent space
self.video_proj = nn.Linear(video_dim, d_model)
self.report_proj = nn.Linear(report_dim, d_model)
# Aggregate all report CLS tokens into a single token (like original script style)
self.report_aggregator = TransformerAggregator(dim=d_model, n_heads=n_heads, dropout=dropout)
# Time encoding (delta_t -> temporal position embedding)
self.time_cfg = TimePosConfig(
emb_dim=d_model,
seq_length=1,
pos_emb="temporal",
n_time_features=1,
temperature=10000.0,
)
self.time_pos = PosEmbedding(self.time_cfg, emb_dim=d_model)
self.use_log_standardize = True
self.register_buffer("mean_log", torch.zeros(1))
self.register_buffer("std_log", torch.ones(1))
# Cross-attention: Q = [report_token, time_token], K/V = video_tokens
self.cross_attn = nn.MultiheadAttention(
embed_dim=d_model,
num_heads=n_heads,
dropout=dropout,
batch_first=True,
)
# Lightweight FFN on the cross-attn output
self.cross_ffn = nn.Sequential(
nn.LayerNorm(d_model),
nn.Linear(d_model, d_model),
nn.ReLU(),
nn.Dropout(dropout),
)
# Final fusion: video + report + time
fusion_dim = d_model * 3
hidden_dim = d_model * 2
self.classifier = nn.Sequential(
nn.Linear(fusion_dim, hidden_dim),
nn.ReLU(),
nn.Dropout(dropout),
nn.Linear(hidden_dim, num_classes),
)
@torch.no_grad()
def set_time_stats(self, mean_log: float, std_log: float):
self.mean_log.fill_(float(mean_log))
self.std_log.fill_(float(std_log))
def encode_video_tokens(self, videos: torch.Tensor) -> torch.Tensor:
"""
videos: [N_videos, video_dim]
returns: [N_videos, d_model]
"""
if not self.use_video:
raise ValueError("ASTimeModel_CrossAttn requires use_video=True for cross-attention.")
if videos is None or videos.numel() == 0:
raise ValueError("No video embeddings available for this study.")
if torch.isnan(videos).any() or torch.isinf(videos).any():
raise ValueError(f"videos contain NaN or Inf values: {videos}")
return self.video_proj(videos) # [N_v, d_model]
def encode_report_tokens(self, report_cls: torch.Tensor) -> torch.Tensor:
"""
Turn report CLS embeddings into a single d_model token via TransformerAggregator.
report_cls: [N_sentences, report_dim]
returns:
[1, d_model] if we have a report and use_report=True
[0, d_model] (empty) if reports are disabled or missing
"""
if not self.use_report:
device = report_cls.device if isinstance(report_cls, torch.Tensor) else "cpu"
return torch.empty(0, self.d_model, device=device)
if report_cls is None or report_cls.numel() == 0:
device = report_cls.device if isinstance(report_cls, torch.Tensor) else "cpu"
return torch.empty(0, self.d_model, device=device)
if torch.isnan(report_cls).any() or torch.isinf(report_cls).any():
raise ValueError(f"report_cls contains NaN or Inf values: {report_cls}")
rep = self.report_proj(report_cls) # [M, d_model]
rep_agg = self.report_aggregator(rep) # [d_model]
return rep_agg.unsqueeze(0) # [1, d_model] (single token)
def encode_time_token(self, delta_t: torch.Tensor) -> torch.Tensor:
"""
delta_t: scalar tensor (single value for this pair)
returns: [1, d_model] time token
"""
if not self.use_time:
raise ValueError("encode_time_token called but use_time=False.")
if delta_t is None or delta_t.numel() == 0:
raise ValueError("No time value available for this study.")
if torch.isnan(delta_t).any() or torch.isinf(delta_t).any():
raise ValueError(f"delta_t contains NaN or Inf values: {delta_t}")
if delta_t.ndim == 0:
delta_t = delta_t.unsqueeze(0)
elif delta_t.ndim > 1:
delta_t = delta_t.view(-1)
if delta_t.numel() != 1:
raise ValueError(
f"encode_time_token expects scalar delta_t, got shape {delta_t.shape}"
)
if self.use_log_standardize:
delta_t = torch.log1p(delta_t)
delta_t = (delta_t - self.mean_log) / (self.std_log + 1e-8)
time_feats = build_time_features(delta_t) # [1, 1, n_time_features]
t_emb = self.time_pos(time_feats) # [1, 1, d_model]
return t_emb.squeeze(0) # [1, d_model]
def forward(
self,
video_0: List[torch.Tensor], # list of [N0_i, video_dim]
view_0: List[torch.Tensor], # list of [N0_i], unused but kept for API compatibility
report0_cls: List[torch.Tensor], # list of [M0_i, report_dim]
delta_t: torch.Tensor, # [B]
) -> torch.Tensor:
"""
All inputs come directly from your current dataloader + collate_fn.
Returns:
logits: [B, num_classes]
"""
B = len(video_0)
device = next(self.parameters()).device
fusion_list = []
for i in range(B):
v0 = video_0[i].to(device) # [N_v_i, video_dim]
video_tokens = self.encode_video_tokens(v0) # [N_v_i, d_model]
r0 = report0_cls[i].to(device)
report_token = self.encode_report_tokens(r0) # [1, d_model] or [0, d_model]
has_report = (report_token.size(0) > 0 and self.use_report)
if self.use_time:
t_i = delta_t[i].to(device) # scalar
time_token = self.encode_time_token(t_i) # [1, d_model]
has_time = True
else:
time_token = None
has_time = False
# building Q
q_pieces = []
if has_report:
q_pieces.append(report_token) # [1, d_model]
if has_time:
q_pieces.append(time_token) # [1, d_model]
if len(q_pieces) == 0:
raise ValueError("No Q available.")
else:
q = torch.cat(q_pieces, dim=0).unsqueeze(0) # [1, Lq<=2, d_model]
k = video_tokens.unsqueeze(0) # [1, N_v_i, d_model]
v = video_tokens.unsqueeze(0) # [1, N_v_i, d_model]
attn_out, _ = self.cross_attn(q, k, v) # [1, Lq<=2, d_model]
attn_out = self.cross_ffn(attn_out) # [1, Lq<=2, d_model]
video_summary = attn_out.mean(dim=1).squeeze(0) # [d_model]
# Split back into report/time summaries
if has_report and has_time:
# order: [report_token, time_token]
rep_out = attn_out[:, 0:1, :] # [1, 1, d_model]
time_out = attn_out[:, 1:2, :] # [1, 1, d_model]
report_summary = rep_out.squeeze(0).squeeze(0) # [d_model]
time_summary = time_out.squeeze(0).squeeze(0) # [d_model]
elif has_report and not has_time:
rep_out = attn_out # [1, 1, d_model]
report_summary = rep_out.squeeze(0).squeeze(0)
time_summary = torch.zeros(self.d_model, device=device)
elif not has_report and has_time:
time_out = attn_out # [1, 1, d_model]
time_summary = time_out.squeeze(0).squeeze(0)
report_summary = torch.zeros(self.d_model, device=device)
else:
# logically unreachable due to len(q_pieces) check
report_summary = torch.zeros(self.d_model, device=device)
time_summary = torch.zeros(self.d_model, device=device)
fused = torch.cat([video_summary, report_summary, time_summary], dim=-1,) # [3 * d_model]
fusion_list.append(fused)
fusion_batch = torch.stack(fusion_list, dim=0) # [B, 3 * d_model]
logits = self.classifier(fusion_batch) # [B, num_classes]
return logits
class CrossAttnFusionBlock(nn.Module):
def __init__(self, d_model: int, n_heads: int, dropout: float):
super().__init__()
self.cross_attn = nn.MultiheadAttention(
embed_dim=d_model,
num_heads=n_heads,
dropout=dropout,
batch_first=True,
)
self.ln1 = nn.LayerNorm(d_model)
self.ffn = nn.Sequential(
nn.Linear(d_model, 4 * d_model),
nn.GELU(),
nn.Dropout(dropout),
nn.Linear(4 * d_model, d_model),
nn.Dropout(dropout),
)
self.ln2 = nn.LayerNorm(d_model)
def forward(
self,
q_tokens: torch.Tensor,
kv_tokens: torch.Tensor,
key_padding_mask: torch.Tensor,
return_attn: bool = False,
):
attn_out, attn_w = self.cross_attn(
q_tokens,
kv_tokens,
kv_tokens,
key_padding_mask=key_padding_mask,
need_weights=return_attn,
average_attn_weights=False,
)
x = self.ln1(q_tokens + attn_out)
x = self.ln2(x + self.ffn(x))
if return_attn:
return x, attn_w
return x
class ASTimeModel_CrossAttnV2(nn.Module):
"""
Latest batched cross-attention architecture.
Keeps legacy ASTimeModel_CrossAttn intact for backward compatibility.
"""
def __init__(
self,
video_dim: int = 512,
report_dim: int = 768,
d_model: int = 256,
num_classes: int = 2,
dropout: float = 0.3,
n_heads: int = 4,
n_cross_layers: int = 2,
use_video: bool = True,
use_report: bool = True,
use_time: bool = True,
):
super().__init__()
self.d_model = d_model
self.num_classes = num_classes
self.use_video = use_video
self.use_report = use_report
self.use_time = use_time
if not self.use_video:
raise ValueError("ASTimeModel_CrossAttnV2 requires use_video=True")
self.video_proj = nn.Linear(video_dim, d_model)
self.report_proj = nn.Linear(report_dim, d_model)
self.report_aggregator = TransformerAggregator(dim=d_model, n_heads=n_heads, dropout=dropout)
self.time_cfg = TimePosConfig(
emb_dim=d_model,
seq_length=1,
pos_emb="temporal",
n_time_features=1,
temperature=10000.0,
)
self.time_pos = PosEmbedding(self.time_cfg, emb_dim=d_model)
self.use_log_standardize = True
self.register_buffer("mean_log", torch.zeros(1))
self.register_buffer("std_log", torch.ones(1))
self.null_report_token = nn.Parameter(torch.zeros(1, 1, d_model))
self.null_time_token = nn.Parameter(torch.zeros(1, 1, d_model))
self.cross_blocks = nn.ModuleList(
[
CrossAttnFusionBlock(d_model=d_model, n_heads=n_heads, dropout=dropout)
for _ in range(n_cross_layers)
]
)
# classifier dims depend on whether time is used
if self.use_time:
fusion_dim = d_model * 3 # [video, report, time]
else:
fusion_dim = d_model * 2 # [video, report] only
hidden_dim = d_model * 2
self.classifier = nn.Sequential(
nn.LayerNorm(fusion_dim),
nn.Linear(fusion_dim, hidden_dim),
nn.GELU(),
nn.Dropout(dropout),
nn.Linear(hidden_dim, num_classes),
)
@torch.no_grad()
def set_time_stats(self, mean_log: float, std_log: float):
self.mean_log.fill_(float(mean_log))
self.std_log.fill_(float(std_log))
def encode_time_token(self, delta_t: torch.Tensor) -> torch.Tensor:
if delta_t.ndim == 0:
delta_t = delta_t.unsqueeze(0)
elif delta_t.ndim > 1:
delta_t = delta_t.view(-1)
if delta_t.numel() != 1:
raise ValueError(f"encode_time_token expects scalar delta_t, got shape {delta_t.shape}")
if self.use_log_standardize:
delta_t = torch.log1p(delta_t)
delta_t = (delta_t - self.mean_log) / (self.std_log + 1e-8)
time_feats = build_time_features(delta_t)
t_emb = self.time_pos(time_feats)
return t_emb.squeeze(0)
def _masked_mean(self, x: torch.Tensor, valid_mask: torch.Tensor) -> torch.Tensor:
valid = valid_mask.unsqueeze(-1).to(dtype=x.dtype)
summed = (x * valid).sum(dim=1)
denom = valid.sum(dim=1).clamp(min=1.0)
return summed / denom
def forward(
self,
video_0: List[torch.Tensor],
view_0: List[torch.Tensor],
report0_cls: List[torch.Tensor],
delta_t: torch.Tensor,
) -> torch.Tensor:
B = len(video_0)