File size: 11,077 Bytes
d5cfa8f
 
 
 
 
 
 
 
 
 
 
 
 
b40a476
d5cfa8f
 
b40a476
 
d5cfa8f
 
 
 
 
 
 
b40a476
d5cfa8f
 
b40a476
d5cfa8f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b40a476
 
d5cfa8f
b40a476
 
 
d5cfa8f
b40a476
b92e396
b40a476
d5cfa8f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b40a476
d5cfa8f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b40a476
d5cfa8f
 
b40a476
d5cfa8f
 
 
 
 
 
 
 
b40a476
 
d5cfa8f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os

import einops
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision.transforms import Resize
from transformers import ViTImageProcessor, ViTModel, BertModel, ViTConfig, BertConfig

from .configuration_aurora import AuroraConfig


class VisionEncoder(nn.Module):
    config_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'vit_config')
    def __init__(self, config: AuroraConfig):
        super().__init__()
        self.processor = UnifiedImageProcessor(config)
        self.model = ViTModel(ViTConfig.from_json_file(os.path.join(self.config_path, 'config.json')))
        for param in self.model.parameters():
            param.requires_grad = False
        self.hidden_size = self.model.config.hidden_size
        self.output_dim = config.hidden_size
        self.num_distill = config.num_distill

        self.projection = nn.Linear(self.hidden_size, self.output_dim)

        self.target_vision_tokens = nn.Parameter(torch.randn(self.num_distill, self.output_dim))

        # Cross-attention layer
        self.cross_vision = nn.TransformerDecoder(
            nn.TransformerDecoderLayer(
                d_model=config.hidden_size,
                nhead=config.num_attention_heads,
                dim_feedforward=config.intermediate_size,
                dropout=config.dropout_rate,
                batch_first=True,
            ),
            norm=nn.LayerNorm(config.hidden_size),
            num_layers=config.num_vision_cross_layers,
        )

    def extract_vit_features(self, image_tensor):
        """
        Extract image features using ViT
        Args:
            image_tensor: Preprocessed image tensor with shape [batch_size, 3, H, W]
        Returns:
            cls_feature: [CLS] token feature with shape [batch_size, hidden_size]
            patch_features: Features of all patches with shape [batch_size, num_patches, hidden_size]
        """
        outputs = self.model(pixel_values=image_tensor)

        last_hidden_state = outputs.last_hidden_state

        cls_feature = last_hidden_state[:, 0, :]  # [batch_size, hidden_size]

        patch_features = last_hidden_state[:, 1:, :]  # [batch_size, num_patches, hidden_size]

        return cls_feature, patch_features

    def forward(self, x, type='pseudo'):
        x = self.processor(x, type=type)
        _, patch_features = self.extract_vit_features(x)
        patch_features = self.projection(patch_features)
        target_vision_tokens = self.target_vision_tokens.unsqueeze(0).repeat(patch_features.shape[0], 1, 1)
        output_tokens = self.cross_vision(target_vision_tokens, patch_features)
        return output_tokens  # [batch_size, num_patches, hidden_size]


class UnifiedImageProcessor(nn.Module):
    config_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'vit_config')
    def __init__(self, config: AuroraConfig):
        super().__init__()
        # Load ViT preprocessor to get pretrained normalization parameters and target size
        self.vit_processor = ViTImageProcessor.from_json_file(os.path.join(self.config_path, 'preprocessor_config.json'))
        self.target_size = self.vit_processor.size["height"]  # e.g., 224 (default ViT input size)

        # Define resizer for pseudo-images (matches real image target size)
        self.pseudo_resizer = Resize((self.target_size, self.target_size))

        self.token_len = config.token_len

    def process_real_image(self, images):
        """Process real images: automatic resizing, cropping, and normalization"""
        # Directly use ViTImageProcessor to ensure consistency with pretraining pipeline
        inputs = self.vit_processor(images=images, return_tensors="pt")
        return inputs["pixel_values"]  # Shape: [batch_size, 3, H, W]

    def _period_search(self, x):
        xf = torch.fft.rfft(x, dim=-1)
        # find period by amplitudes
        frequency_list = abs(xf).mean(0)
        frequency_list[0] = 0
        _, top_list = torch.topk(frequency_list, 1)
        top_list = top_list.detach().cpu().numpy()
        period = x.shape[1] // top_list
        return period

    def process_pseudo_image(self, x):
        """Process pseudo-images (converted from time series): ensure consistent normalization with real images"""

        # Segmentation
        input_length = x.shape[-1]
        period = list(self._period_search(x))[0]
        period = period if 0 < period < input_length else self.token_len
        if period > input_length:
            period = input_length

        padding_length = (period - (input_length %
                                            period)) % period
        x_pad = F.pad(x, (padding_length, 0))
        x_2d = einops.rearrange(x_pad, 'b (p f) -> b 1 f p', f=period)

        # 3. Render & Alignment
        x_resize = self.pseudo_resizer(x_2d)
        image_input = einops.repeat(x_resize, 'b 1 h w -> b c h w', c=3)
        return image_input

    def forward(self, x, type='pseudo'):
        if type == 'pseudo':
            return self.process_pseudo_image(x)
        else:
            return self.process_real_image(x)


class TextEncoder(nn.Module):
    config_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'bert_config')
    def __init__(self, config: AuroraConfig):
        super().__init__()
        self.model = BertModel(BertConfig.from_json_file(os.path.join(self.config_path, 'config.json')))
        for param in self.model.parameters():
            param.requires_grad = False
        self.hidden_size = self.model.config.hidden_size
        self.output_dim = config.hidden_size
        self.num_distill = config.num_distill
        self.max_length = 125

        self.projection = nn.Linear(self.hidden_size, self.output_dim)

        # Define learnable target tokens (shape: [num_distill_tokens, hidden_size])
        self.target_text_tokens = nn.Parameter(torch.randn(self.num_distill, self.output_dim))

        self.cross_text = nn.TransformerDecoder(
            nn.TransformerDecoderLayer(
                d_model=config.hidden_size,
                nhead=config.num_attention_heads,
                dim_feedforward=config.intermediate_size,
                dropout=config.dropout_rate,
                batch_first=True,
            ),
            norm=nn.LayerNorm(config.hidden_size),
            num_layers=config.num_text_cross_layers,
        )

    def extract_bert_features(self, input_dict):
        """Extract and clean BERT features with fixed output shape"""
        outputs = self.model(**input_dict)

        last_hidden_state = outputs.last_hidden_state  # [batch_size, seq_len, hidden_size]
        cls_feature = last_hidden_state[:, 0, :]  # [batch_size, hidden_size]
        token_features = last_hidden_state

        # Create mask to exclude [CLS], [SEP], and padding tokens
        attention_mask = input_dict["attention_mask"]  # [batch_size, seq_len]
        batch_size, seq_len = attention_mask.shape
        valid_mask = torch.ones_like(attention_mask)
        valid_mask[:, 0] = 0  # Exclude [CLS]

        for i in range(batch_size):
            sep_pos = torch.where(attention_mask[i] == 1)[0][-1]
            valid_mask[i, sep_pos] = 0  # Exclude [SEP]

        # Apply mask and get valid tokens
        valid_token_mask = valid_mask.unsqueeze(-1).expand(-1, -1, self.hidden_size)
        clean_token_features = token_features * valid_token_mask

        # Convert to fixed shape [batch_size, max_valid_tokens, hidden_size]
        fixed_features = torch.zeros(batch_size, self.max_length, self.hidden_size,
                                     device=clean_token_features.device)
        valid_counts = []

        for i in range(batch_size):
            # Get valid tokens (excluding zeros)
            valid_tokens = clean_token_features[i][clean_token_features[i].sum(dim=1) != 0]
            valid_count = valid_tokens.shape[0]
            valid_counts.append(valid_count)

            # Truncate if longer than max_length, else pad with zeros
            if valid_count > self.max_length:
                fixed_features[i] = valid_tokens[:self.max_length]
            else:
                fixed_features[i, :valid_count] = valid_tokens

        return cls_feature, token_features, fixed_features, valid_counts

    def forward(self, texts):
        """Return fixed-shape token features [batch_size, max_valid_tokens, hidden_size]"""
        _, _, fixed_features, _ = self.extract_bert_features(texts)
        fixed_features = self.projection(fixed_features)

        target_text_tokens = self.target_text_tokens.unsqueeze(0).repeat(fixed_features.shape[0], 1, 1)

        output_tokens = self.cross_text(target_text_tokens, fixed_features)
        return output_tokens


class ModalityConnector(nn.Module):
    def __init__(self, config: AuroraConfig):
        """
        Args:
            hidden_size: Feature dimension (must match text/vision feature dimensions)
            num_distill_tokens: Unified token count (constant N)
        """
        super().__init__()
        self.hidden_size = config.hidden_size

        # Define learnable target tokens (shape: [num_distill_tokens, hidden_size])
        self.connect_text = nn.TransformerDecoder(
            nn.TransformerDecoderLayer(
                d_model=config.hidden_size,
                nhead=config.num_attention_heads,
                dim_feedforward=config.intermediate_size,
                dropout=config.dropout_rate,
                batch_first=True,
            ),
            norm=nn.LayerNorm(config.hidden_size),
            num_layers=config.num_text_connect_layers,
        )

        self.connect_vision = nn.TransformerDecoder(
            nn.TransformerDecoderLayer(
                d_model=config.hidden_size,
                nhead=config.num_attention_heads,
                dim_feedforward=config.intermediate_size,
                dropout=config.dropout_rate,
                batch_first=True,
            ),
            norm=nn.LayerNorm(config.hidden_size),
            num_layers=config.num_vision_connect_layers,
        )

    def forward(self, x, text_features, vision_features):
        """
        Distill text and vision tokens to the same count N
        Args:
            x: Time Series with shape [batch_size, n, hidden_size] (n is time series token count)
            text_features: Text features with shape [batch_size, T, hidden_size] (T is text token count)
            vision_features: Vision features with shape [batch_size, V, hidden_size] (V is vision token count)
        Returns:
            text_distilled: Distilled text tokens with shape [batch_size, N, hidden_size]
            vision_distilled: Distilled vision tokens with shape [batch_size, N, hidden_size]
        """
        if text_features is not None:
            from_text = self.connect_text(
                x,
                text_features
            )
        else:
            from_text = None

        from_vision = self.connect_vision(
            x,
            vision_features
        )

        return from_text, from_vision