File size: 27,759 Bytes
1ef5ba8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""CTA Ablation Study Module.

All ablation variants are controlled by a single ``ablation_variant`` string
in the config, so we only need ONE extra method file and ONE extra config file.

Supported variants
------------------
Full ablation table (8 dimensions × multiple settings):

[A] Detection signal (classifier input features)
  A1  full              -- Full CTA (baseline, all features)
  A2  no_asym           -- Remove asymmetry score from classifier input
  A3  no_ltotal         -- Remove L_total from classifier input
  A4  asym_only         -- Classifier input = [asym] only
  A5  pooled_only       -- Classifier input = [v_pooled, a_pooled] only (no predictor signals)
  A6  flip_sign         -- asym := L_AV − L_VA (opposite sign of default). Also flips
                           the margin ranking loss so it still pushes fakes AWAY from
                           reals in the new sign convention.
  A7  abs_asym          -- asym := |L_VA − L_AV|. Loses directional forensic signature
                           but tests whether magnitude alone is sufficient.

[B] Predictor training strategy
  B1  real_only         -- Predictors trained on real samples only (default)
  B2  all_samples       -- Predictors trained on ALL samples (real + fake)
  B3  no_predictor      -- Predictors frozen at random init (test if learned physics matter)

[C] Loss function ablation
  C1  no_loss_asym      -- Remove margin ranking loss (loss_asym = 0)
  C2  no_loss_aux       -- Remove cross-generator consistency loss (loss_aux = 0)
  C3  no_loss_av        -- Remove A->V predictor loss (only train V->A)
  C4  no_loss_va        -- Remove V->A predictor loss (only train A->V)
  C5  no_detach         -- Do NOT detach l_av/l_va before classifier (allow gradient flow)

[D] Predictor architecture
  D1  depth_1           -- Predictor depth = 1 (shallow)
  D2  depth_4           -- Predictor depth = 4 (default)
  D3  depth_8           -- Predictor depth = 8 (deep)
  D4  mlp_predictor     -- Replace Transformer Decoder with MLP predictor
  D5  shared_predictor  -- A->V and V->A share the same predictor weights

[E] Backbone freeze ratio (video)
  E1  video_freeze_0    -- Video backbone fully unfrozen (freeze_ratio=0.0)
  E2  video_freeze_07   -- Video backbone freeze_ratio=0.7 (default)
  E3  video_freeze_10   -- Video backbone fully frozen (freeze_ratio=1.0)

[F] Backbone freeze ratio (audio)
  F1  audio_freeze_0    -- Audio backbone fully unfrozen (freeze_ratio=0.0)
  F2  audio_freeze_08   -- Audio backbone freeze_ratio=0.8 (default)

[G] Data strategy
  G1  aligned_crop      -- Force video frames and audio to be time-aligned
  G2  random_crop       -- Independent random crop (default)

[M] Modality / Cross-modal role ablation
  M1  video_only            -- Single-modality baseline: video features only, no predictor.
  M2  audio_only            -- Single-modality baseline: audio features only, no predictor.
  M3  intra_modal           -- Replace cross-modal preds with V->V and A->A self-reconstruction.
                               Tests whether the asymmetry signal is *cross-modal*-specific.
  M4  noise_target          -- Replace target tokens with Gaussian noise inside the predictor
                               loss; predictor cannot learn anything meaningful. Tests whether
                               the asymmetry signal is genuine causal-direction information.
  M5  shuffle_pair          -- In-batch shuffle of audio so each video is paired with someone
                               else's audio. Breaks sample correspondence but keeps modalities.
                               Tests whether *correspondence* matters (vs. raw modality stats).
  M6  drop_audio_infer      -- Train as full CTA; at inference, zero-out audio features.
                               Reveals how much the predictor signal depends on audio at test.
  M7  drop_video_infer      -- Train as full CTA; at inference, zero-out video features.
                               Reveals how much the predictor signal depends on video at test.
"""
from __future__ import annotations

import random
from typing import Any, Dict

import torch
import torch.nn as nn
import torch.nn.functional as F

from ..models.backbones import VideoBackbone, AudioBackbone, CrossModalPredictor
from .base import BaseMethod


# Variant groups for quick lookup
_GROUP_M_SET = {
    "M1_video_only", "M2_audio_only", "M3_intra_modal",
    "M4_noise_target", "M5_shuffle_pair",
    "M6_drop_audio_infer", "M7_drop_video_infer",
}


# ---------------------------------------------------------------------------
# Direction-convention helper (used by A6_flip_sign / A7_abs_asym)
# ---------------------------------------------------------------------------
def _compute_asym(variant: str, l_av: torch.Tensor, l_va: torch.Tensor) -> torch.Tensor:
    """Return per-sample asymmetry score in the sign convention required by variant.

    Default: s_asym = L_VA − L_AV.  With this convention fakes score negatively
    and the margin loss pushes  asym_fake < asym_real.

    A6_flip_sign: s_asym = L_AV − L_VA.  Sign is opposite; margin loss must be
    flipped so it still pushes fakes AWAY from reals (see loss code below).

    A7_abs_asym: s_asym = |L_VA − L_AV|.  Directional information erased.
    """
    if variant == "A6_flip_sign":
        return l_av - l_va
    if variant == "A7_abs_asym":
        return (l_va - l_av).abs()
    return l_va - l_av


# ---------------------------------------------------------------------------
# MLP predictor (for variant D4)
# ---------------------------------------------------------------------------
class MLPPredictor(nn.Module):
    """Simple MLP cross-modal predictor: pools source tokens, then projects
    to target dimension. No cross-attention, no sequence modeling."""

    def __init__(self, src_dim: int, tgt_dim: int, hidden_dim: int = 512, dropout: float = 0.1):
        super().__init__()
        self.net = nn.Sequential(
            nn.Linear(src_dim, hidden_dim),
            nn.GELU(),
            nn.Dropout(dropout),
            nn.Linear(hidden_dim, hidden_dim),
            nn.GELU(),
            nn.Dropout(dropout),
        )
        self.out = nn.Linear(hidden_dim, tgt_dim)

    def forward(self, src_tokens: torch.Tensor, tgt_query: torch.Tensor) -> torch.Tensor:
        # src_tokens: (B, T_s, D_s) -> pool -> (B, D_s)
        src_pooled = src_tokens.mean(dim=1)          # (B, D_s)
        h = self.net(src_pooled)                     # (B, hidden)
        pred_pooled = self.out(h)                    # (B, D_t)
        # Broadcast to match tgt_query shape (B, T_t, D_t)
        return pred_pooled.unsqueeze(1).expand_as(tgt_query)


# ---------------------------------------------------------------------------
# Core model
# ---------------------------------------------------------------------------
class CTAAblationModel(nn.Module):
    def __init__(self, method_cfg, backbone_cfg):
        super().__init__()
        variant = method_cfg.ablation_variant

        # ---- video backbone ------------------------------------------------
        # Variants E1/E2/E3 override freeze_ratio. M2 (audio-only) skips video.
        video_freeze = backbone_cfg.freeze_ratio
        if variant == "E1_video_freeze_0":
            video_freeze = 0.0
        elif variant == "E3_video_freeze_10":
            video_freeze = 1.0
        # E2 uses default from backbone_cfg

        # M1 only needs video; M2 only needs audio. Other M variants need both.
        # We always build BOTH backbones for code simplicity, except M2 skips
        # video and M1 skips audio (saves memory in single-modality runs).
        self.has_video = variant != "M2_audio_only"
        self.has_audio = variant != "M1_video_only"

        if self.has_video:
            self.video = VideoBackbone(
                hf_id=backbone_cfg.hf_id,
                freeze_ratio=video_freeze,
            )
            vD = self.video.feature_dim
        else:
            self.video = None
            vD = backbone_cfg.get("feature_dim", 768)  # placeholder

        # ---- audio backbone ------------------------------------------------
        audio_freeze = method_cfg.audio_backbone.freeze_ratio
        if variant == "F1_audio_freeze_0":
            audio_freeze = 0.0
        # F2 uses default

        if self.has_audio:
            self.audio = AudioBackbone(
                hf_id=method_cfg.audio_backbone.hf_id,
                freeze_ratio=audio_freeze,
            )
            aD = self.audio.feature_dim
        else:
            self.audio = None
            aD = method_cfg.audio_backbone.feature_dim  # 768

        # ---- predictor depth override (D1/D2/D3) ---------------------------
        pred_depth = method_cfg.av_predictor.depth
        if variant == "D1_depth_1":
            pred_depth = 1
        elif variant == "D3_depth_8":
            pred_depth = 8
        # D2 uses default depth from config

        # ---- build predictors ----------------------------------------------
        # M1/M2: no predictor at all (single-modality baseline).
        # M3: V->V and A->A self-reconstruction (same shape, but src_dim==tgt_dim).
        # M4/M5/M6/M7: same shape as default cross-modal (A->V, V->A).
        if variant in ("M1_video_only", "M2_audio_only"):
            self.av_pred = None
            self.va_pred = None
        elif variant == "M3_intra_modal":
            # Self-reconstruction predictors. We rebind:
            #   self.av_pred  = V->V  (was A->V)
            #   self.va_pred  = A->A  (was V->A)
            self.av_pred = CrossModalPredictor(
                src_dim=vD, tgt_dim=vD,
                hidden_dim=method_cfg.av_predictor.hidden_dim,
                depth=pred_depth,
                heads=method_cfg.av_predictor.heads,
                dropout=method_cfg.av_predictor.dropout,
            )
            self.va_pred = CrossModalPredictor(
                src_dim=aD, tgt_dim=aD,
                hidden_dim=method_cfg.va_predictor.hidden_dim,
                depth=pred_depth,
                heads=method_cfg.va_predictor.heads,
                dropout=method_cfg.va_predictor.dropout,
            )
        elif variant == "D4_mlp_predictor":
            self.av_pred = MLPPredictor(
                src_dim=aD, tgt_dim=vD,
                hidden_dim=method_cfg.av_predictor.hidden_dim,
                dropout=method_cfg.av_predictor.dropout,
            )
            self.va_pred = MLPPredictor(
                src_dim=vD, tgt_dim=aD,
                hidden_dim=method_cfg.va_predictor.hidden_dim,
                dropout=method_cfg.va_predictor.dropout,
            )
        elif variant == "D5_shared_predictor":
            # Shared predictor: both directions use the same weights.
            # Since src/tgt dims are both 768, this is valid.
            shared = CrossModalPredictor(
                src_dim=vD, tgt_dim=aD,
                hidden_dim=method_cfg.av_predictor.hidden_dim,
                depth=pred_depth,
                heads=method_cfg.av_predictor.heads,
                dropout=method_cfg.av_predictor.dropout,
            )
            self.av_pred = shared
            self.va_pred = shared
        else:
            self.av_pred = CrossModalPredictor(
                src_dim=aD, tgt_dim=vD,
                hidden_dim=method_cfg.av_predictor.hidden_dim,
                depth=pred_depth,
                heads=method_cfg.av_predictor.heads,
                dropout=method_cfg.av_predictor.dropout,
            )
            self.va_pred = CrossModalPredictor(
                src_dim=vD, tgt_dim=aD,
                hidden_dim=method_cfg.va_predictor.hidden_dim,
                depth=pred_depth,
                heads=method_cfg.va_predictor.heads,
                dropout=method_cfg.va_predictor.dropout,
            )

        # Variant B3: freeze predictors at random init
        if variant == "B3_no_predictor":
            for p in self.av_pred.parameters():
                p.requires_grad_(False)
            for p in self.va_pred.parameters():
                p.requires_grad_(False)

        # ---- classifier head -----------------------------------------------
        # Input dim depends on variant
        if variant == "M1_video_only":
            cls_in_dim = vD                               # only pooled video
        elif variant == "M2_audio_only":
            cls_in_dim = aD                               # only pooled audio
        elif variant == "A4_asym_only":
            cls_in_dim = 1
        elif variant == "A5_pooled_only":
            cls_in_dim = vD + aD
        elif variant == "A2_no_asym":
            cls_in_dim = vD + aD + 1                      # pooled_v + pooled_a + L_total
        elif variant == "A3_no_ltotal":
            cls_in_dim = vD + aD + 1                      # pooled_v + pooled_a + asym
        else:
            # Full / B / C / D / E / F / G / M3 / M4 / M5 / M6 / M7
            cls_in_dim = vD + aD + 2                      # pooled_v + pooled_a + asym + L_total

        self.cls = nn.Sequential(
            nn.Linear(cls_in_dim, method_cfg.classifier.hidden),
            nn.GELU(),
            nn.Dropout(method_cfg.classifier.dropout),
            nn.Linear(method_cfg.classifier.hidden, 1),
        )

        self.variant = variant
        self.vD = vD
        self.aD = aD

    # -----------------------------------------------------------------------
    def predict_pairs(self, video: torch.Tensor, audio: torch.Tensor, training: bool = True):
        """Compute predictor outputs and per-sample asymmetry score.

        For Group M variants:
          M1/M2 -> not called (training_step / score handle them directly).
          M3    -> intra-modal self-reconstruction. l_av := L_VV, l_va := L_AA.
                   asym := L_AA - L_VV (still "harder direction minus easier").
          M4    -> target tokens replaced by Gaussian noise (same shape).
          M5    -> in-batch shuffle of audio so video[i] is paired with audio[perm[i]].
                   Only applied during training; at inference we keep the natural pairing
                   so that asym reflects what the model learned about MISALIGNED pairs.
          M6/M7 -> same forward as full; the dropout is applied in `score()` or in
                   `training_step()` separately for clarity.
        """
        variant = self.variant

        v = self.video(video)
        a = self.audio(audio)

        if variant == "M3_intra_modal":
            # Intra-modal self-reconstruction.
            # av_pred: V->V (input=v tokens, target=v tokens)
            # va_pred: A->A (input=a tokens, target=a tokens)
            v_pred = self.av_pred(src_tokens=v["tokens"], tgt_query=v["tokens"])
            a_pred = self.va_pred(src_tokens=a["tokens"], tgt_query=a["tokens"])

            l_av = F.mse_loss(v_pred, v["tokens"], reduction="none").mean(dim=[1, 2])
            l_va = F.mse_loss(a_pred, a["tokens"], reduction="none").mean(dim=[1, 2])
            asym = _compute_asym(variant, l_av, l_va)
            return v, a, l_av, l_va, asym

        if variant == "M5_shuffle_pair" and training:
            # In-batch shuffle of audio so video[i] is paired with audio[perm[i]].
            B = a["tokens"].size(0)
            if B > 1:
                # Random non-identity permutation.
                perm = torch.randperm(B, device=a["tokens"].device)
                a_tokens = a["tokens"][perm]
                a_pooled_shuf = a["pooled"][perm]
            else:
                a_tokens = a["tokens"]
                a_pooled_shuf = a["pooled"]
            v_pred = self.av_pred(src_tokens=a_tokens, tgt_query=v["tokens"])
            a_pred = self.va_pred(src_tokens=v["tokens"], tgt_query=a_tokens)
            l_av = F.mse_loss(v_pred, v["tokens"], reduction="none").mean(dim=[1, 2])
            l_va = F.mse_loss(a_pred, a_tokens, reduction="none").mean(dim=[1, 2])
            asym = _compute_asym(variant, l_av, l_va)
            # Replace a["pooled"] with the shuffled one so the classifier sees the
            # exact pair we trained on this step.
            a = {"pooled": a_pooled_shuf, "tokens": a_tokens}
            return v, a, l_av, l_va, asym

        # Default cross-modal forward
        v_pred = self.av_pred(src_tokens=a["tokens"], tgt_query=v["tokens"])
        a_pred = self.va_pred(src_tokens=v["tokens"], tgt_query=a["tokens"])

        if variant == "M4_noise_target":
            # Replace target tokens with Gaussian noise of matching shape/scale.
            # The predictor is forced to match noise; signal collapses.
            v_target = torch.randn_like(v["tokens"])
            a_target = torch.randn_like(a["tokens"])
        else:
            v_target = v["tokens"]
            a_target = a["tokens"]

        l_av = F.mse_loss(v_pred, v_target, reduction="none").mean(dim=[1, 2])  # (B,)
        l_va = F.mse_loss(a_pred, a_target, reduction="none").mean(dim=[1, 2])  # (B,)

        asym = _compute_asym(variant, l_av, l_va)
        return v, a, l_av, l_va, asym

    # -----------------------------------------------------------------------
    def classify(self, v_pooled, a_pooled, l_av, l_va):
        asym = _compute_asym(self.variant, l_av, l_va)
        variant = self.variant

        if variant == "M1_video_only":
            feat = v_pooled
        elif variant == "M2_audio_only":
            feat = a_pooled
        elif variant == "A4_asym_only":
            feat = asym.unsqueeze(-1)
        elif variant == "A5_pooled_only":
            feat = torch.cat([v_pooled, a_pooled], dim=-1)
        elif variant == "A2_no_asym":
            feat = torch.cat([v_pooled, a_pooled, (l_av + l_va).unsqueeze(-1)], dim=-1)
        elif variant == "A3_no_ltotal":
            feat = torch.cat([v_pooled, a_pooled, asym.unsqueeze(-1)], dim=-1)
        else:
            # Full / all other variants: use complete feature set
            feat = torch.cat([
                v_pooled,
                a_pooled,
                asym.unsqueeze(-1),
                (l_av + l_va).unsqueeze(-1),
            ], dim=-1)

        return self.cls(feat)   # (B, 1) logits


# ---------------------------------------------------------------------------
# Lightning Module
# ---------------------------------------------------------------------------
class CTAAblationLitModule(BaseMethod):
    def __init__(self, method_cfg, backbone_cfg, data_cfg):
        super().__init__(method_cfg=method_cfg, backbone_cfg=backbone_cfg, data_cfg=data_cfg)
        self.model = CTAAblationModel(method_cfg, backbone_cfg)
        self.variant = method_cfg.ablation_variant

    # -----------------------------------------------------------------------
    def _training_step_single_modality(self, batch):
        """Path for M1_video_only and M2_audio_only.

        These variants do NOT use a predictor, so there is no l_av / l_va /
        asym / loss_aux. We only optimize the classifier on a pooled feature.
        """
        labels = batch["label"].long()

        if self.variant == "M1_video_only":
            v = self.model.video(batch["video"])
            v_pooled = v["pooled"]
            # Build a zero "audio" so classify() shape logic still works for callers,
            # but classify() detects M1 and only uses v_pooled.
            a_pooled = torch.zeros(
                v_pooled.size(0), self.model.aD,
                device=v_pooled.device, dtype=v_pooled.dtype,
            )
        else:  # M2_audio_only
            a = self.model.audio(batch["audio"])
            a_pooled = a["pooled"]
            v_pooled = torch.zeros(
                a_pooled.size(0), self.model.vD,
                device=a_pooled.device, dtype=a_pooled.dtype,
            )

        # Dummy l_av / l_va; classify() will not use them for M1/M2.
        zero = torch.zeros(v_pooled.size(0), device=v_pooled.device, dtype=v_pooled.dtype)
        logits = self.model.classify(v_pooled, a_pooled, zero, zero)
        loss_cls = F.binary_cross_entropy_with_logits(logits.squeeze(-1), labels.float())

        loss = self.method_cfg.loss.cls_weight * loss_cls

        self.log_dict({
            "train/loss": loss,
            "train/loss_cls": loss_cls,
        }, prog_bar=False, on_step=True, on_epoch=True, sync_dist=True)

        return loss

    # -----------------------------------------------------------------------
    def training_step(self, batch, batch_idx):
        if batch is None:
            return None

        variant = self.variant

        # Single-modality baselines have a separate, simpler path.
        if variant in ("M1_video_only", "M2_audio_only"):
            return self._training_step_single_modality(batch)

        video = batch["video"]
        audio = batch["audio"]
        labels = batch["label"].long()

        # ---- M6/M7: zero-out one modality during training so the model learns
        #           a single-modality decision rule but still has all the
        #           predictor scaffolding. This makes the comparison clean.
        if variant == "M6_drop_audio_infer":
            audio = torch.zeros_like(audio)
        elif variant == "M7_drop_video_infer":
            video = torch.zeros_like(video)

        # ---- forward -------------------------------------------------------
        v, a, l_av, l_va, asym = self.model.predict_pairs(video, audio, training=True)

        is_real = (labels == 0).float()
        denom_r = is_real.sum().clamp(min=1.0)

        # ---- loss_av / loss_va (predictor losses) --------------------------
        # Variant B2: train predictors on ALL samples
        # Variant B3: predictors frozen, no predictor loss
        # Variant C3: skip loss_av (only train V->A)
        # Variant C4: skip loss_va (only train A->V)
        # Variant M4: target is noise; we still compute loss_av/loss_va so the
        #             optimizer is well-defined, but on real samples only.
        # Variant M5: misaligned pair; loss is on (v[i], a[perm[i]]) — this
        #             is valid because we're testing whether the predictor can
        #             still extract a useful asym signal under shuffled pairs.
        if variant == "B3_no_predictor":
            loss_av = l_av.new_zeros([])
            loss_va = l_va.new_zeros([])
        elif variant == "B2_all_samples":
            loss_av = l_av.mean()
            loss_va = l_va.mean()
        elif variant == "C3_no_loss_av":
            loss_av = l_av.new_zeros([])
            loss_va = (l_va * is_real).sum() / denom_r
        elif variant == "C4_no_loss_va":
            loss_av = (l_av * is_real).sum() / denom_r
            loss_va = l_va.new_zeros([])
        else:
            # Default (real_only): B1 / A* / C1 / C2 / C5 / D* / E* / F* / G* / M3-M7
            loss_av = (l_av * is_real).sum() / denom_r
            loss_va = (l_va * is_real).sum() / denom_r

        # ---- loss_asym (margin ranking) ------------------------------------
        asym_r = asym[labels == 0]
        asym_f = asym[labels == 1]
        if variant == "C1_no_loss_asym":
            loss_asym = asym.new_zeros([])
        elif asym_r.numel() > 0 and asym_f.numel() > 0:
            if variant in {"A6_flip_sign", "A7_abs_asym"}:
                # Under these variants, the empirically expected direction is
                # asym_fake > asym_real (opposite of default). Flip the ranking
                # loss so it stays dormant when the direction is correct and
                # kicks in only when the model reverses it.
                loss_asym = F.relu(asym_r.mean() - asym_f.mean())
            else:
                loss_asym = F.relu(asym_f.mean() - asym_r.mean())
        else:
            loss_asym = asym.new_zeros([])

        # ---- classifier loss -----------------------------------------------
        # Variant C5: do NOT detach l_av/l_va (allow gradient to flow back)
        if variant == "C5_no_detach":
            logits = self.model.classify(v["pooled"], a["pooled"], l_av, l_va)
        else:
            logits = self.model.classify(v["pooled"], a["pooled"], l_av.detach(), l_va.detach())

        loss_cls = F.binary_cross_entropy_with_logits(logits.squeeze(-1), labels.float())

        # ---- cross-generator auxiliary loss --------------------------------
        loss_aux = asym.new_zeros([])
        if variant != "C2_no_loss_aux":
            if self.method_cfg.aux_crossgen.enabled and "alt_video" in batch:
                alt_v_in = batch["alt_video"]
                alt_a_in = batch["alt_audio"]
                if variant == "M6_drop_audio_infer":
                    alt_a_in = torch.zeros_like(alt_a_in)
                elif variant == "M7_drop_video_infer":
                    alt_v_in = torch.zeros_like(alt_v_in)
                _, _, l_av2, l_va2, asym2 = self.model.predict_pairs(
                    alt_v_in, alt_a_in, training=True,
                )
                loss_aux = F.mse_loss(asym, asym2)

        # ---- total loss ----------------------------------------------------
        loss = (
            self.method_cfg.loss.av_weight * loss_av
            + self.method_cfg.loss.va_weight * loss_va
            + self.method_cfg.loss.asym_weight * loss_asym
            + self.method_cfg.loss.cls_weight * loss_cls
            + self.method_cfg.aux_crossgen.weight * loss_aux
        )

        self.log_dict({
            "train/loss": loss,
            "train/loss_av": loss_av,
            "train/loss_va": loss_va,
            "train/loss_asym": loss_asym,
            "train/loss_cls": loss_cls,
            "train/loss_aux": loss_aux,
            "train/asym_mean_real": asym_r.mean() if asym_r.numel() > 0 else torch.zeros_like(loss),
            "train/asym_mean_fake": asym_f.mean() if asym_f.numel() > 0 else torch.zeros_like(loss),
        }, prog_bar=False, on_step=True, on_epoch=True, sync_dist=True)

        return loss

    # -----------------------------------------------------------------------
    @torch.no_grad()
    def score(self, batch: Dict[str, Any]) -> torch.Tensor:
        variant = self.variant

        # ---- M1/M2: single-modality inference ------------------------------
        if variant == "M1_video_only":
            v = self.model.video(batch["video"])
            v_pooled = v["pooled"]
            a_pooled = torch.zeros(
                v_pooled.size(0), self.model.aD,
                device=v_pooled.device, dtype=v_pooled.dtype,
            )
            zero = torch.zeros(v_pooled.size(0), device=v_pooled.device, dtype=v_pooled.dtype)
            logits = self.model.classify(v_pooled, a_pooled, zero, zero)
            return torch.sigmoid(logits.squeeze(-1))

        if variant == "M2_audio_only":
            a = self.model.audio(batch["audio"])
            a_pooled = a["pooled"]
            v_pooled = torch.zeros(
                a_pooled.size(0), self.model.vD,
                device=a_pooled.device, dtype=a_pooled.dtype,
            )
            zero = torch.zeros(a_pooled.size(0), device=a_pooled.device, dtype=a_pooled.dtype)
            logits = self.model.classify(v_pooled, a_pooled, zero, zero)
            return torch.sigmoid(logits.squeeze(-1))

        video = batch["video"]
        audio = batch["audio"]

        # ---- M6/M7: inference-time modality dropout ------------------------
        if variant == "M6_drop_audio_infer":
            audio = torch.zeros_like(audio)
        elif variant == "M7_drop_video_infer":
            video = torch.zeros_like(video)

        v, a, l_av, l_va, asym = self.model.predict_pairs(video, audio, training=False)
        logits = self.model.classify(v["pooled"], a["pooled"], l_av, l_va)
        return torch.sigmoid(logits.squeeze(-1))