File size: 21,452 Bytes
3cecacc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import torch
import torch.nn as nn
import torch.nn.functional as F
import pytorch_lightning as pl
from torch.utils.data import Dataset, DataLoader
from typing import List, Tuple, Optional
import numpy as np
from pathlib import Path
from deepspeed.ops.adam import FusedAdam

class MusicClassifier(pl.LightningModule):
    def __init__(self,
                input_dim: int,
                hidden_dim: int = 256,
                learning_rate: float = 1e-4,
                emb_model: Optional[nn.Module] = None,
                is_emb: bool = False):
        super().__init__()
        self.save_hyperparameters()
        
        self.model = SegmentTransformer(
            input_dim=input_dim,
            hidden_dim=hidden_dim
        )
        self.emb_model = emb_model
        self.learning_rate = learning_rate
        self.is_emb = is_emb
    
    def forward(self, x: torch.Tensor, mask: Optional[torch.Tensor] = None) -> torch.Tensor:
        return self.model(x, mask)
    
    def training_step(self, batch: Tuple[torch.Tensor, torch.Tensor, torch.Tensor], batch_idx: int) -> torch.Tensor:
        x, y, mask = batch
        if self.is_emb == False:
            _,x = self.emb_model(x)
        y_hat = self(x, mask)
        loss = F.binary_cross_entropy_with_logits(y_hat.squeeze(), y.float())
        
        # Log metrics
        self.log('train_loss', loss,on_epoch=True, prog_bar=True)
        preds = (torch.sigmoid(y_hat.squeeze()) > 0.5).float()
        acc = (preds == y.float()).float().mean()
        self.log('train_acc', acc,on_epoch=True, prog_bar=True)
        
        return loss
    
    def validation_step(self, batch: Tuple[torch.Tensor, torch.Tensor, torch.Tensor], batch_idx: int) -> None:
        x, y, mask = batch
        if self.is_emb == False:
            _,x = self.emb_model(x)
        y_hat = self(x, mask)
        loss = F.binary_cross_entropy_with_logits(y_hat.squeeze(), y.float())
        
        # Calculate accuracy
        preds = (torch.sigmoid(y_hat.squeeze()) > 0.5).float()
        acc = (preds == y.float()).float().mean()
        
        self.log('val_loss', loss, prog_bar=True)
        self.log('val_acc', acc, prog_bar=True)
    
    def configure_optimizers(self):
        optimizer = torch.optim.AdamW(
            self.parameters(),
            lr=self.learning_rate,
            weight_decay=0.01
        )
        scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(
            optimizer,
            T_max=100,  # Adjust based on your training epochs
            eta_min=1e-6
        )
        return {
            'optimizer': optimizer,
            'lr_scheduler': scheduler,
            'monitor': 'val_loss'
        }

class MusicAudioClassifier(pl.LightningModule):
    def __init__(self,
                input_dim: int,
                hidden_dim: int = 256,
                learning_rate: float = 1e-4,
                emb_model: Optional[nn.Module] = None,
                is_emb: bool = False,
                mode: str = 'only_emb',
                share_parameter: bool = False):
        super().__init__()
        self.save_hyperparameters()
        
        self.model = SegmentTransformer(
            input_dim=input_dim,
            hidden_dim=hidden_dim,
            mode = mode,
            share_parameter = share_parameter
        )
        self.emb_model = emb_model
        self.learning_rate = learning_rate
        self.is_emb = is_emb
    
    def _process_audio_batch(self, x: torch.Tensor) -> torch.Tensor:

        B, S = x.shape[:2]  # [B, S, C, M, T] or [B, S, C, T] for wav, [B, S, 1?, embsize] for emb
        x = x.view(B*S, *x.shape[2:])  # [B*S, C, M, T] 
        if self.is_emb == False:
            _, embeddings = self.emb_model(x)  # [B*S, emb_dim]
        else:
            embeddings = x
        if embeddings.dim() == 3:
            pooled_features = embeddings.mean(dim=1) # transformer
        else:
            pooled_features = embeddings # CCV..? no need to pooling
        return pooled_features.view(B, S, -1)  # [B, S, emb_dim]
    
    def forward(self, x: torch.Tensor, mask: Optional[torch.Tensor] = None) -> torch.Tensor:
        x = self._process_audio_batch(x) # ์ด๊ฑธ freezeํ•˜๊ณ  ์“ฐ๋Š”๊ฒŒ ์‚ฌ์‹ค์ƒ ์œ—๋ฒ„์ „์ž„
        x = x.half()
        return self.model(x, mask)
    
    def training_step(self, batch: Tuple[torch.Tensor, torch.Tensor, torch.Tensor], batch_idx: int) -> torch.Tensor:
        x, y, mask = batch
        x = x.half()
        y_hat = self(x, mask)
        
        # ๋ฐฐ์น˜ ํฌ๊ธฐ๊ฐ€ 1์ธ ๊ฒฝ์šฐ ์˜ˆ์™ธ์ฒ˜๋ฆฌ
        if y_hat.size(0) == 1:
            loss = F.binary_cross_entropy_with_logits(y_hat.flatten(), y.float().flatten())
            probs = torch.sigmoid(y_hat.flatten())
            y_true = y.float().flatten()
        else:
            loss = F.binary_cross_entropy_with_logits(y_hat.squeeze(), y.float())
            probs = torch.sigmoid(y_hat.squeeze())
            y_true = y.float()
        
        # ๊ฐ„๋‹จํ•œ ๋ฐฐ์น˜ ์†์‹ค๋งŒ ๋กœ๊น… (step ์ˆ˜์ค€)
        self.log('train_loss', loss, on_step=True, on_epoch=True, prog_bar=True, sync_dist=True)
        
        # ์ „์ฒด ์—ํญ์— ๋Œ€ํ•œ ๋ฉ”ํŠธ๋ฆญ ๊ณ„์‚ฐ์„ ์œ„ํ•ด ์˜ˆ์ธก๊ณผ ์‹ค์ œ๊ฐ’ ์ €์žฅ
        self.training_step_outputs.append({'preds': probs, 'targets': y_true})
        
        return loss

    def validation_step(self, batch: Tuple[torch.Tensor, torch.Tensor, torch.Tensor], batch_idx: int) -> None:
        x, y, mask = batch
        x = x.half()
        y_hat = self(x, mask)
        
        # ๋ฐฐ์น˜ ํฌ๊ธฐ๊ฐ€ 1์ธ ๊ฒฝ์šฐ ์˜ˆ์™ธ์ฒ˜๋ฆฌ
        if y_hat.size(0) == 1:
            loss = F.binary_cross_entropy_with_logits(y_hat.flatten(), y.float().flatten())
            probs = torch.sigmoid(y_hat.flatten())
            y_true = y.float().flatten()
        else:
            loss = F.binary_cross_entropy_with_logits(y_hat.squeeze(), y.float())
            probs = torch.sigmoid(y_hat.squeeze())
            y_true = y.float()
        
        # ๊ฐ„๋‹จํ•œ ๋ฐฐ์น˜ ์†์‹ค๋งŒ ๋กœ๊น… (step ์ˆ˜์ค€)
        self.log('val_loss', loss, on_step=True, on_epoch=True, prog_bar=True, sync_dist=True)
        
        # ์ „์ฒด ์—ํญ์— ๋Œ€ํ•œ ๋ฉ”ํŠธ๋ฆญ ๊ณ„์‚ฐ์„ ์œ„ํ•ด ์˜ˆ์ธก๊ณผ ์‹ค์ œ๊ฐ’ ์ €์žฅ
        self.validation_step_outputs.append({'preds': probs, 'targets': y_true})

    def test_step(self, batch: Tuple[torch.Tensor, torch.Tensor, torch.Tensor], batch_idx: int) -> None:
        x, y, mask = batch
        x = x.half()
        y_hat = self(x, mask)
        
        # ๋ฐฐ์น˜ ํฌ๊ธฐ๊ฐ€ 1์ธ ๊ฒฝ์šฐ ์˜ˆ์™ธ์ฒ˜๋ฆฌ
        if y_hat.size(0) == 1:
            loss = F.binary_cross_entropy_with_logits(y_hat.flatten(), y.float().flatten())
            probs = torch.sigmoid(y_hat.flatten())
            y_true = y.float().flatten()
        else:
            loss = F.binary_cross_entropy_with_logits(y_hat.squeeze(), y.float())
            probs = torch.sigmoid(y_hat.squeeze())
            y_true = y.float()
        
        # ๊ฐ„๋‹จํ•œ ๋ฐฐ์น˜ ์†์‹ค๋งŒ ๋กœ๊น… (step ์ˆ˜์ค€)
        self.log('test_loss', loss, on_epoch=True, prog_bar=True)
        
        # ์ „์ฒด ์—ํญ์— ๋Œ€ํ•œ ๋ฉ”ํŠธ๋ฆญ ๊ณ„์‚ฐ์„ ์œ„ํ•ด ์˜ˆ์ธก๊ณผ ์‹ค์ œ๊ฐ’ ์ €์žฅ
        self.test_step_outputs.append({'preds': probs, 'targets': y_true})

    def on_train_epoch_start(self):
        # ์—ํญ ์‹œ์ž‘ ์‹œ ๊ฒฐ๊ณผ ์ €์žฅ์šฉ ๋ฆฌ์ŠคํŠธ ์ดˆ๊ธฐํ™”
        self.training_step_outputs = []

    def on_validation_epoch_start(self):
        # ์—ํญ ์‹œ์ž‘ ์‹œ ๊ฒฐ๊ณผ ์ €์žฅ์šฉ ๋ฆฌ์ŠคํŠธ ์ดˆ๊ธฐํ™”
        self.validation_step_outputs = []

    def on_test_epoch_start(self):
        # ์—ํญ ์‹œ์ž‘ ์‹œ ๊ฒฐ๊ณผ ์ €์žฅ์šฉ ๋ฆฌ์ŠคํŠธ ์ดˆ๊ธฐํ™”
        self.test_step_outputs = []

    def on_train_epoch_end(self):
        # ์—ํญ์ด ๋๋‚  ๋•Œ ์ „์ฒด ๋ฐ์ดํ„ฐ์— ๋Œ€ํ•œ ๋ฉ”ํŠธ๋ฆญ ๊ณ„์‚ฐ
        if not hasattr(self, 'training_step_outputs') or not self.training_step_outputs:
            return
            
        all_preds = torch.cat([x['preds'] for x in self.training_step_outputs])
        all_targets = torch.cat([x['targets'] for x in self.training_step_outputs])
        
        # ์ „์ฒด ๋ฐ์ดํ„ฐ์— ๋Œ€ํ•œ ๋ฉ”ํŠธ๋ฆญ ๊ณ„์‚ฐ
        binary_preds = (all_preds > 0.5).float()
        
        # ์ •ํ™•๋„ ๊ณ„์‚ฐ
        acc = (binary_preds == all_targets).float().mean()
        
        # ํ˜ผ๋™ ํ–‰๋ ฌ ์š”์†Œ ๊ณ„์‚ฐ
        tp = torch.sum((binary_preds == 1) & (all_targets == 1)).float()
        fp = torch.sum((binary_preds == 1) & (all_targets == 0)).float()
        tn = torch.sum((binary_preds == 0) & (all_targets == 0)).float()
        fn = torch.sum((binary_preds == 0) & (all_targets == 1)).float()
        
        # ๋ฉ”ํŠธ๋ฆญ ๊ณ„์‚ฐ
        precision = tp / (tp + fp) if (tp + fp) > 0 else torch.tensor(0.0).to(tp.device)
        recall = tp / (tp + fn) if (tp + fn) > 0 else torch.tensor(0.0).to(tp.device)
        f1 = 2 * precision * recall / (precision + recall) if (precision + recall) > 0 else torch.tensor(0.0).to(tp.device)
        specificity = tn / (tn + fp) if (tn + fp) > 0 else torch.tensor(0.0).to(tn.device)
        
        # ๋กœ๊น… - ์ผ๊ด€๋œ ์ด๋ฆ„ ์‚ฌ์šฉ
        self.log('train_acc', acc, on_epoch=True, prog_bar=True, sync_dist=True)
        self.log('train_precision', precision, on_epoch=True, sync_dist=True)
        self.log('train_recall', recall, on_epoch=True, sync_dist=True)
        self.log('train_f1', f1, on_epoch=True, prog_bar=True, sync_dist=True)
        self.log('train_specificity', specificity, on_epoch=True, sync_dist=True)

    def on_validation_epoch_end(self):
        # ์—ํญ์ด ๋๋‚  ๋•Œ ์ „์ฒด ๋ฐ์ดํ„ฐ์— ๋Œ€ํ•œ ๋ฉ”ํŠธ๋ฆญ ๊ณ„์‚ฐ
        if not hasattr(self, 'validation_step_outputs') or not self.validation_step_outputs:
            return
            
        all_preds = torch.cat([x['preds'] for x in self.validation_step_outputs])
        all_targets = torch.cat([x['targets'] for x in self.validation_step_outputs])
        
        # ROC-AUC ๊ณ„์‚ฐ (๊ฐ„๋‹จํ•œ ๊ทผ์‚ฌ)
        sorted_indices = torch.argsort(all_preds, descending=True)
        sorted_targets = all_targets[sorted_indices]
        
        n_pos = torch.sum(all_targets)
        n_neg = len(all_targets) - n_pos
        
        if n_pos > 0 and n_neg > 0:
            # TPR๊ณผ FPR์„ ๋ˆ„์ ํ•ฉ์œผ๋กœ ๊ณ„์‚ฐ
            tpr_curve = torch.cumsum(sorted_targets, dim=0) / n_pos
            fpr_curve = torch.cumsum(1 - sorted_targets, dim=0) / n_neg
            
            # AUC ๊ณ„์‚ฐ (์‚ฌ๋‹ค๋ฆฌ๊ผด ๋ฒ•์น™)
            width = fpr_curve[1:] - fpr_curve[:-1]
            height = (tpr_curve[1:] + tpr_curve[:-1]) / 2
            auc_approx = torch.sum(width * height)
            
            self.log('val_auc', auc_approx, on_epoch=True)
        
        # ์ „์ฒด ๋ฐ์ดํ„ฐ์— ๋Œ€ํ•œ ๋ฉ”ํŠธ๋ฆญ ๊ณ„์‚ฐ
        binary_preds = (all_preds > 0.5).float()
        
        # ์ •ํ™•๋„ ๊ณ„์‚ฐ
        acc = (binary_preds == all_targets).float().mean()
        
        # ํ˜ผ๋™ ํ–‰๋ ฌ ์š”์†Œ ๊ณ„์‚ฐ
        tp = torch.sum((binary_preds == 1) & (all_targets == 1)).float()
        fp = torch.sum((binary_preds == 1) & (all_targets == 0)).float()
        tn = torch.sum((binary_preds == 0) & (all_targets == 0)).float()
        fn = torch.sum((binary_preds == 0) & (all_targets == 1)).float()
        
        # ๋ฉ”ํŠธ๋ฆญ ๊ณ„์‚ฐ
        precision = tp / (tp + fp) if (tp + fp) > 0 else torch.tensor(0.0).to(tp.device)
        recall = tp / (tp + fn) if (tp + fn) > 0 else torch.tensor(0.0).to(tp.device)
        f1 = 2 * precision * recall / (precision + recall) if (precision + recall) > 0 else torch.tensor(0.0).to(tp.device)
        specificity = tn / (tn + fp) if (tn + fp) > 0 else torch.tensor(0.0).to(tn.device)
        
        # ๋กœ๊น… - ์ผ๊ด€๋œ ์ด๋ฆ„ ์‚ฌ์šฉ (val_epoch_f1 ๋Œ€์‹  val_f1 ์‚ฌ์šฉ)
        self.log('val_acc', acc, on_epoch=True, prog_bar=True, sync_dist=True)
        self.log('val_precision', precision, on_epoch=True, sync_dist=True)
        self.log('val_recall', recall, on_epoch=True, sync_dist=True)
        self.log('val_f1', f1, on_epoch=True, prog_bar=True, sync_dist=True)
        self.log('val_specificity', specificity, on_epoch=True, sync_dist=True)

    def on_test_epoch_end(self):
        # ์—ํญ์ด ๋๋‚  ๋•Œ ์ „์ฒด ํ…Œ์ŠคํŠธ ๋ฐ์ดํ„ฐ์— ๋Œ€ํ•œ ๋ฉ”ํŠธ๋ฆญ ๊ณ„์‚ฐ
        if not hasattr(self, 'test_step_outputs') or not self.test_step_outputs:
            return
            
        all_preds = torch.cat([x['preds'] for x in self.test_step_outputs])
        all_targets = torch.cat([x['targets'] for x in self.test_step_outputs])
        
        # ROC-AUC ๊ณ„์‚ฐ (๊ฐ„๋‹จํ•œ ๊ทผ์‚ฌ)
        sorted_indices = torch.argsort(all_preds, descending=True)
        sorted_targets = all_targets[sorted_indices]
        
        n_pos = torch.sum(all_targets)
        n_neg = len(all_targets) - n_pos
        
        if n_pos > 0 and n_neg > 0:
            # TPR๊ณผ FPR์„ ๋ˆ„์ ํ•ฉ์œผ๋กœ ๊ณ„์‚ฐ
            tpr_curve = torch.cumsum(sorted_targets, dim=0) / n_pos
            fpr_curve = torch.cumsum(1 - sorted_targets, dim=0) / n_neg
            
            # AUC ๊ณ„์‚ฐ (์‚ฌ๋‹ค๋ฆฌ๊ผด ๋ฒ•์น™)
            width = fpr_curve[1:] - fpr_curve[:-1]
            height = (tpr_curve[1:] + tpr_curve[:-1]) / 2
            auc_approx = torch.sum(width * height)
            
            self.log('test_auc', auc_approx, on_epoch=True, sync_dist=True)
        
        # ์ „์ฒด ๋ฐ์ดํ„ฐ์— ๋Œ€ํ•œ ๋ฉ”ํŠธ๋ฆญ ๊ณ„์‚ฐ
        binary_preds = (all_preds > 0.5).float()
        
        # ์ •ํ™•๋„ ๊ณ„์‚ฐ
        acc = (binary_preds == all_targets).float().mean()
        
        # ํ˜ผ๋™ ํ–‰๋ ฌ ์š”์†Œ ๊ณ„์‚ฐ
        tp = torch.sum((binary_preds == 1) & (all_targets == 1)).float()
        fp = torch.sum((binary_preds == 1) & (all_targets == 0)).float()
        tn = torch.sum((binary_preds == 0) & (all_targets == 0)).float()
        fn = torch.sum((binary_preds == 0) & (all_targets == 1)).float()
        
        # ๋ฉ”ํŠธ๋ฆญ ๊ณ„์‚ฐ
        precision = tp / (tp + fp) if (tp + fp) > 0 else torch.tensor(0.0).to(tp.device)
        recall = tp / (tp + fn) if (tp + fn) > 0 else torch.tensor(0.0).to(tp.device)
        f1 = 2 * precision * recall / (precision + recall) if (precision + recall) > 0 else torch.tensor(0.0).to(tp.device)
        specificity = tn / (tn + fp) if (tn + fp) > 0 else torch.tensor(0.0).to(tn.device)
        balanced_acc = (recall + specificity) / 2
        
        # ๋กœ๊น… - ์ผ๊ด€๋œ ์ด๋ฆ„ ์‚ฌ์šฉ
        self.log('test_acc', acc, on_epoch=True, prog_bar=True)
        self.log('test_precision', precision, on_epoch=True)
        self.log('test_recall', recall, on_epoch=True)
        self.log('test_f1', f1, on_epoch=True, prog_bar=True)
        self.log('test_specificity', specificity, on_epoch=True)
        self.log('test_balanced_acc', balanced_acc, on_epoch=True)

    def configure_optimizers(self):
        optimizer = FusedAdam(self.parameters(),lr=self.learning_rate,
            weight_decay=0.01)
        scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(
            optimizer,
            T_max=100,  # Adjust based on your training epochs
            eta_min=1e-6
        )

        return {
            'optimizer': optimizer,
            'lr_scheduler': scheduler,
            'monitor': 'val_loss',
        }


def pad_sequence_with_mask(batch: List[Tuple[torch.Tensor, int]]) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
    """Collate function for DataLoader that creates padded sequences and attention masks with fixed length (48)."""
    embeddings, labels = zip(*batch)
    fixed_len = 48  # ๊ณ ์ • ๊ธธ์ด

    batch_size = len(embeddings)
    feat_dim = embeddings[0].shape[-1]
    
    padded = torch.zeros((batch_size, fixed_len, feat_dim))  # ๊ณ ์ • ๊ธธ์ด๋กœ ํŒจ๋”ฉ๋œ ํ…์„œ
    mask = torch.ones((batch_size, fixed_len), dtype=torch.bool)  # True๋Š” padding์„ ์˜๋ฏธ
    
    for i, emb in enumerate(embeddings):
        length = emb.shape[0]
        
        # ๊ธธ์ด๊ฐ€ ๊ณ ์ • ๊ธธ์ด๋ณด๋‹ค ๊ธธ๋ฉด ์ž๋ฅด๊ณ , ์งง์œผ๋ฉด ํŒจ๋”ฉ
        if length > fixed_len:
            padded[i, :] = emb[:fixed_len]  # fixed_len๋ณด๋‹ค ๊ธด ๋ถ€๋ถ„์„ ์ž˜๋ผ์„œ ์ฑ„์šด๋‹ค.
            mask[i, :] = False
        else:
            padded[i, :length] = emb  # ์‹ค์ œ ๋ฐ์ดํ„ฐ ๊ธธ์ด์— ๋งž๊ฒŒ ์ฑ„์šด๋‹ค.
            mask[i, :length] = False  # ํŒจ๋”ฉ์ด ์•„๋‹Œ ๋ถ€๋ถ„์€ False๋กœ ์„ค์ •
    
    return padded, torch.tensor(labels), mask


class SegmentTransformer(nn.Module):
    def __init__(self, 
                 input_dim: int,
                 hidden_dim: int = 256,
                 num_heads: int = 8,
                 num_layers: int = 4,
                 dropout: float = 0.1,
                 max_sequence_length: int = 1000,
                 mode: str = 'only_emb',
                 share_parameter: bool = False):
        super().__init__()
        
        # Original sequence processing
        self.input_projection = nn.Linear(input_dim, hidden_dim)
        self.mode = mode
        self.share_parameter = share_parameter
        # Positional encoding
        position = torch.arange(max_sequence_length).unsqueeze(1)
        div_term = torch.exp(torch.arange(0, hidden_dim, 2) * (-np.log(10000.0) / hidden_dim))
        pos_encoding = torch.zeros(max_sequence_length, hidden_dim)
        pos_encoding[:, 0::2] = torch.sin(position * div_term)
        pos_encoding[:, 1::2] = torch.cos(position * div_term)
        self.register_buffer('pos_encoding', pos_encoding)
        
        # Transformer for original sequence
        encoder_layer = nn.TransformerEncoderLayer(
            d_model=hidden_dim,
            nhead=num_heads,
            dim_feedforward=hidden_dim * 4,
            dropout=dropout,
            batch_first=True
        )
        self.transformer = nn.TransformerEncoder(encoder_layer, num_layers=num_layers)
        self.sim_transformer = nn.TransformerEncoder(encoder_layer, num_layers=num_layers)
        
        # Self-similarity stream processing
        self.similarity_projection = nn.Sequential(
            nn.Conv1d(1, hidden_dim // 2, kernel_size=3, padding=1),
            nn.ReLU(),
            nn.Conv1d(hidden_dim // 2, hidden_dim, kernel_size=3, padding=1),
            nn.ReLU(),
            nn.Dropout(dropout)
        )
        
        # Transformer for similarity stream
        self.similarity_transformer = nn.TransformerEncoder(encoder_layer, num_layers=num_layers)
        
        # Final classification head
        self.classification_head_dim = hidden_dim * 2 if mode == 'both' else hidden_dim
        self.classification_head = nn.Sequential(
            nn.Linear(self.classification_head_dim, hidden_dim),
            nn.LayerNorm(hidden_dim),
            nn.ReLU(),
            nn.Dropout(dropout),
            nn.Linear(hidden_dim, hidden_dim // 2),
            nn.LayerNorm(hidden_dim // 2),
            nn.ReLU(),
            nn.Dropout(dropout),
            nn.Linear(hidden_dim // 2, 1)
        )
        
    def forward(self, x: torch.Tensor, padding_mask: Optional[torch.Tensor] = None) -> torch.Tensor:
        batch_size, seq_len, _ = x.shape
        
        # 1. Process original sequence
        x1 = self.input_projection(x)
        x1 = x1 + self.pos_encoding[:seq_len].unsqueeze(0)
        x1 = self.transformer(x1, src_key_padding_mask=padding_mask)  # padding_mask ์‚ฌ์šฉ

        # 2. Calculate and process self-similarity
        x_expanded = x.unsqueeze(2)
        x_transposed = x.unsqueeze(1)
        distances = torch.mean((x_expanded - x_transposed) ** 2, dim=-1)
        similarity_matrix = torch.exp(-distances)  # (batch_size, seq_len, seq_len)
        
        # ์ž๊ธฐ ์œ ์‚ฌ๋„ ๋งˆ์Šคํฌ ์ƒ์„ฑ ๋ฐ ์ ์šฉ (๊ฐ ์‹œ์ ์— ๋Œ€ํ•œ ๋งˆ์Šคํฌ ๊ฐœ๋ณ„ ์ ์šฉ)
        if padding_mask is not None:
            similarity_mask = padding_mask.unsqueeze(1) | padding_mask.unsqueeze(2)  # (batch_size, seq_len, seq_len)
            similarity_matrix = similarity_matrix.masked_fill(similarity_mask, 0.0)

        # Process similarity matrix row by row using Conv1d
        x2 = similarity_matrix.unsqueeze(1)  # (batch_size, 1, seq_len, seq_len)
        x2 = x2.view(batch_size * seq_len, 1, seq_len)  # Reshape for Conv1d
        x2 = self.similarity_projection(x2)  # (batch_size * seq_len, hidden_dim, seq_len)
        x2 = x2.mean(dim=2)  # Pool across sequence dimension
        x2 = x2.view(batch_size, seq_len, -1)  # Reshape back

        x2 = x2 + self.pos_encoding[:seq_len].unsqueeze(0)
        if self.share_parameter:
            x2 = self.transformer(x2, src_key_padding_mask=padding_mask)
        else:
            x2 = self.sim_transformer(x2, src_key_padding_mask=padding_mask)  # padding_mask ์‚ฌ์šฉ

        # 3. Global average pooling for both streams
        if padding_mask is not None:
            mask_expanded = (~padding_mask).float().unsqueeze(-1)
            x1 = (x1 * mask_expanded).sum(dim=1) / mask_expanded.sum(dim=1)
            x2 = (x2 * mask_expanded).sum(dim=1) / mask_expanded.sum(dim=1)
        else:
            x1 = x1.mean(dim=1)
            x2 = x2.mean(dim=1)
        
        # 4. Combine both streams and classify
        #x = x1 # only emb
        #x = x2 # only structure
        #x = torch.cat([x1, x2], dim=-1) 
        if self.mode == 'only_emb':
            x = x1
        elif self.mode == 'only_structure':
            x = x2
        elif self.mode == 'both':
            x = torch.cat([x1, x2], dim=-1)
        x = x.half()
        return self.classification_head(x)