File size: 2,641 Bytes
21419ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""2D/3D MDT teachers with shared/specific encoders and reconstruction heads."""
import torch
from torch import nn
from torch.nn import functional as F
from .backbones import SimpleLightCNNBackbone, SimpleLight3DCNNBackbone

class MDTTeacher(nn.Module):
    """2D modality-disentangling teacher; tuple format matches MDTLoss."""

    def __init__(self, hidden_dim: int=128, z_dim: int=64, num_classes: int=2):
        super().__init__()
        self.extractor_aia = SimpleLightCNNBackbone(3)
        self.extractor_hmi = SimpleLightCNNBackbone(1)
        self.proj_aia = nn.Sequential(nn.Linear(512, hidden_dim), nn.LeakyReLU(0.2), nn.LayerNorm(hidden_dim))
        self.proj_hmi = nn.Sequential(nn.Linear(512, hidden_dim), nn.LeakyReLU(0.2), nn.LayerNorm(hidden_dim))
        self.encoder_specific_aia = self._encoder(hidden_dim, z_dim)
        self.encoder_specific_hmi = self._encoder(hidden_dim, z_dim)
        self.encoder_common_aia = self._encoder(hidden_dim, z_dim)
        self.encoder_common_hmi = self._encoder(hidden_dim, z_dim)
        self.decoder_aia = self._decoder(z_dim, hidden_dim)
        self.decoder_hmi = self._decoder(z_dim, hidden_dim)
        self.classifier = nn.Linear(z_dim, num_classes)

    @staticmethod
    def _encoder(in_dim: int, out_dim: int) -> nn.Sequential:
        return nn.Sequential(nn.Linear(in_dim, out_dim), nn.LayerNorm(out_dim), nn.Sigmoid(), nn.Linear(out_dim, out_dim))

    @staticmethod
    def _decoder(in_dim: int, out_dim: int) -> nn.Sequential:
        return nn.Sequential(nn.Linear(in_dim, out_dim), nn.Sigmoid(), nn.LayerNorm(out_dim), nn.Linear(out_dim, out_dim))

    def forward(self, aia: torch.Tensor, hmi: torch.Tensor):
        h_aia = self.proj_aia(self.extractor_aia(aia))
        h_hmi = self.proj_hmi(self.extractor_hmi(hmi))
        z_sa = F.normalize(self.encoder_specific_aia(h_aia), p=2, dim=1)
        z_sb = F.normalize(self.encoder_specific_hmi(h_hmi), p=2, dim=1)
        z_ca = F.normalize(self.encoder_common_aia(h_aia), p=2, dim=1)
        z_cb = F.normalize(self.encoder_common_hmi(h_hmi), p=2, dim=1)
        h_aia_recon = self.decoder_aia(z_ca + z_sa)
        h_hmi_recon = self.decoder_hmi(z_cb + z_sb)
        logits = self.classifier(z_ca + z_cb)
        return (logits, (h_aia, h_hmi, h_aia_recon, h_hmi_recon), (z_ca, z_cb, z_sa, z_sb))

class MDTTeacher3D(MDTTeacher):

    def __init__(self, hidden_dim: int=128, z_dim: int=64, num_classes: int=2):
        super().__init__(hidden_dim=hidden_dim, z_dim=z_dim, num_classes=num_classes)
        self.extractor_aia = SimpleLight3DCNNBackbone(3)
        self.extractor_hmi = SimpleLight3DCNNBackbone(1)