-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcnn_model.py
More file actions
2110 lines (1748 loc) · 77.3 KB
/
cnn_model.py
File metadata and controls
2110 lines (1748 loc) · 77.3 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
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import Dataset, DataLoader
import numpy as np
import pandas as pd
import os
import platform
from sklearn.model_selection import StratifiedKFold
from sklearn.metrics import f1_score
from tqdm import tqdm
import copy
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import RBF, WhiteKernel
from typing import Dict, Tuple, Optional, Union, List
import warnings
warnings.filterwarnings('ignore')
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import DataLoader
import numpy as np
from tqdm import tqdm
from sklearn.metrics import f1_score
# ============================================================
# PERFORMANCE FIX: Enable cuDNN benchmarking
# ============================================================
torch.backends.cudnn.benchmark = True
torch.backends.cudnn.enabled = True
# ============================================================
# TIER 5: FOCAL LOSS FOR CLASS IMBALANCE
# ============================================================
class FocalLoss(nn.Module):
"""
Focal Loss for extremely imbalanced classification.
Down-weights easy examples, focuses on hard-to-classify samples.
Args:
gamma: Focusing parameter (default: 2.0)
alpha: Balancing parameter (default: 0.75)
label_smoothing: Label smoothing factor (default: 0.0)
reduction: 'mean', 'sum', or 'none'
"""
def __init__(self, gamma=2.0, alpha=0.75, label_smoothing=0.0, reduction='mean'):
super().__init__()
self.gamma = gamma
self.alpha = alpha
self.label_smoothing = label_smoothing
self.reduction = reduction
def forward(self, inputs, targets):
probs = torch.sigmoid(inputs)
targets_smooth = targets * (1 - self.label_smoothing) + 0.5 * self.label_smoothing
ce_loss = F.binary_cross_entropy_with_logits(inputs, targets_smooth, reduction='none')
p_t = probs * targets + (1 - probs) * (1 - targets)
focal_weight = (1 - p_t) ** self.gamma
alpha_weight = self.alpha * targets + (1 - self.alpha) * (1 - targets)
focal_loss = alpha_weight * focal_weight * ce_loss
if self.reduction == 'mean':
return focal_loss.mean()
elif self.reduction == 'sum':
return focal_loss.sum()
return focal_loss
# ============================================================
# TIER 5: LIGHTCURVE AUGMENTATION
# ============================================================
class LightCurveAugmenter:
"""Time-series augmentation for astronomical lightcurves."""
def __init__(self, noise_std=0.05, time_jitter=0.02, flux_scale_range=(0.9, 1.1), p=0.5):
self.noise_std = noise_std
self.time_jitter = time_jitter
self.flux_scale_range = flux_scale_range
self.p = p
def __call__(self, x):
if np.random.random() > self.p:
return x
x = x.clone()
# Add Gaussian noise to flux values
noise = torch.randn_like(x) * self.noise_std
x = x + noise
# Apply random flux scaling
scale = np.random.uniform(*self.flux_scale_range)
x = x * scale
return x
class ContrastiveAugmenter:
"""
Augmentation pipeline for SimCLR pre-training.
Returns two augmented views of the same lightcurve.
"""
def __init__(self, seq_len=100):
self.seq_len = seq_len
self.base_augmenter = LightCurveAugmenter(p=1.0) # Always augment
def __call__(self, x):
"""
x: [Channels=6, SeqLen]
Returns (x_i, x_j)
"""
x_i = self.augment(x.clone())
x_j = self.augment(x.clone())
return x_i, x_j
def augment(self, x):
# 1. Base Augmentation (Flux scale, noise)
x = self.base_augmenter(x)
# 2. Random masking (Cutout) - simulate observational gaps
if np.random.random() < 0.5:
mask_len = int(0.2 * self.seq_len)
start = np.random.randint(0, max(1, self.seq_len - mask_len))
x[:, start:start+mask_len] = 0.0
# 3. Channel Dropout (simulate missing band)
if np.random.random() < 0.3 and x.shape[0] >= 6:
band_idx = np.random.randint(0, min(6, x.shape[0]))
x[band_idx, :] = 0.0
# 4. Photometric redshift perturbation
if np.random.random() < 0.3:
z_err = np.random.normal(0, 0.1)
factor = 1.0 + z_err
x = x / (factor**2) # Flux ~ 1/d_L^2
return x
# Config
SEQ_LEN = 100
CHANNELS = 2 # Flux, Flux_err
# ============================================================
# DATASET - PERFORMANCE OPTIMIZED
# ============================================================
class LightCurveDataset(Dataset):
"""
Dataset for lightcurve data with optional tabular features.
OPTIMIZED: Disabled GP by default, uses fast linear interpolation.
"""
def __init__(self, splits, object_ids, split_map, labels=None, seq_len=100,
tabular_features=None, use_gp=False): # CHANGED: GP disabled by default
self.splits = splits
self.object_ids = object_ids if isinstance(object_ids, (list, np.ndarray)) else object_ids.values
self.split_map = split_map
self.labels = labels
self.seq_len = seq_len
self.tabular_features = tabular_features
self.use_gp = use_gp
self.band_map = {'u': 0, 'g': 1, 'r': 2, 'i': 3, 'z': 4, 'Y': 5}
self.filters = ['u', 'g', 'r', 'i', 'z', 'Y']
def __len__(self):
return len(self.object_ids)
def __getitem__(self, idx):
oid = self.object_ids[idx]
# Determine split and get DF
split_name = self.split_map.get(oid)
if split_name and split_name in self.splits:
full_df = self.splits[split_name]
df = full_df[full_df['object_id'] == oid]
else:
df = self.splits.get(oid, pd.DataFrame())
# Prepare 6-channel input: [6 Bands, Seq_Len]
tensor = np.zeros((6, self.seq_len), dtype=np.float32)
if not df.empty:
# Normalize column names
col_map = {
'Filter': 'passband', 'band': 'passband',
'Flux': 'flux', 'flux': 'flux',
'Flux_err': 'flux_err', 'flux_err': 'flux_err',
'Time (MJD)': 'mjd', 'mjd': 'mjd', 'Time': 'mjd'
}
df = df.rename(columns=col_map)
# Global Time Normalization for this object
t_min = df['mjd'].min()
t_max = df['mjd'].max()
duration = t_max - t_min
if duration == 0:
duration = 1.0
# Define target uniform time grid
t_grid = np.linspace(t_min, t_max, self.seq_len)
for band_name, grp in df.groupby('passband'):
if band_name not in self.band_map:
continue
b_idx = self.band_map[band_name]
if len(grp) < 2: # Need at least 2 points for interpolation
continue
t = grp['mjd'].values
f = grp['flux'].values
e = grp['flux_err'].values
# Normalize Flux (Critical for NN)
f_mean = np.nanmean(f)
f_std = np.nanstd(f) + 1e-6
# Nan check for scalar stats
if np.isnan(f_mean) or np.isnan(f_std):
f_mean = 0.0
f_std = 1.0
f_norm = (f - f_mean) / f_std
e_norm = e / f_std
# Clean potential NaNs in normalized arrays
f_norm = np.nan_to_num(f_norm, nan=0.0)
e_norm = np.nan_to_num(e_norm, nan=0.0)
# PERFORMANCE FIX: Use linear interpolation by default
# GP is 100x slower and often not worth it
if self.use_gp and len(grp) >= 3:
try:
# GP Regression (SLOW - only use if explicitly requested)
kernel = 1.0 * RBF(length_scale=20.0, length_scale_bounds=(1e-1, 100.0)) + \
WhiteKernel(noise_level=1.0, noise_level_bounds=(1e-2, 10.0))
alpha = e_norm**2 + 1e-6
gp = GaussianProcessRegressor(
kernel=kernel,
alpha=alpha,
normalize_y=False,
n_restarts_optimizer=0
)
gp.fit(t.reshape(-1, 1), f_norm)
f_pred = gp.predict(t_grid.reshape(-1, 1))
tensor[b_idx, :] = f_pred
except Exception:
# Fallback to linear interpolation
f_pred = np.interp(t_grid, t, f_norm)
tensor[b_idx, :] = f_pred
else:
# Fast Linear Interpolation (DEFAULT)
f_pred = np.interp(t_grid, t, f_norm)
tensor[b_idx, :] = f_pred
x = torch.tensor(tensor, dtype=torch.float32)
# Handle tabular features if present
if self.tabular_features is not None:
if isinstance(self.tabular_features, pd.DataFrame):
try:
tab_vec = self.tabular_features.loc[oid].values.astype(np.float32)
except (KeyError, AttributeError):
tab_vec = np.zeros(300, dtype=np.float32)
else:
# Assume it's a dict {oid: array}
tab_vec = self.tabular_features.get(oid, np.zeros(300, dtype=np.float32))
tab_tensor = torch.tensor(tab_vec, dtype=torch.float32)
if self.labels is not None:
y = torch.tensor(self.labels[idx], dtype=torch.float32)
return (x, tab_tensor), y
return (x, tab_tensor)
if self.labels is not None:
y = torch.tensor(self.labels[idx], dtype=torch.float32)
return x, y
return x
def normalize_split_name(s):
"""Normalize split names to consistent format."""
if '_' in s:
p1, p2 = s.split('_')
return f"Split_{int(p2):02d}"
return s
# ============================================================
# MODELS
# ============================================================
class TemporalPositionalEncoding(nn.Module):
"""
Time-aware positional encoding for irregular time series.
Unlike standard positional encoding which assumes uniform spacing,
this encodes the actual time values, making it suitable for
astronomical light curves with irregular cadence.
"""
def __init__(self, d_model, max_len=200):
super().__init__()
self.d_model = d_model
# Learnable time embedding
self.time_embed = nn.Sequential(
nn.Linear(1, d_model // 2),
nn.SiLU(),
nn.Linear(d_model // 2, d_model)
)
def forward(self, x, time_values):
"""
x: [batch, seq_len, d_model]
time_values: [batch, seq_len] - actual MJD values
"""
# Normalize time to [0, 1] range per sample
t_min = time_values.min(dim=1, keepdim=True)[0]
t_max = time_values.max(dim=1, keepdim=True)[0]
t_norm = (time_values - t_min) / (t_max - t_min + 1e-8)
# Encode time
time_enc = self.time_embed(t_norm.unsqueeze(-1)) # [batch, seq, d_model]
return x + time_enc
class InceptionBlock(nn.Module):
"""
Inception block for multi-scale feature extraction.
Uses parallel convolutions with different kernel sizes to capture
both short-term and long-term patterns in lightcurves.
Based on InceptionTime architecture which achieves SOTA on UCR archive.
"""
def __init__(self, in_channels, n_filters=32, bottleneck_size=32):
super().__init__()
# Bottleneck for dimensionality reduction
self.bottleneck = nn.Conv1d(in_channels, bottleneck_size, kernel_size=1, bias=False)
# Multi-scale convolutions (kernel sizes: 9, 19, 39)
self.conv_small = nn.Conv1d(bottleneck_size, n_filters, kernel_size=9, padding=4, bias=False)
self.conv_medium = nn.Conv1d(bottleneck_size, n_filters, kernel_size=19, padding=9, bias=False)
self.conv_large = nn.Conv1d(bottleneck_size, n_filters, kernel_size=39, padding=19, bias=False)
# MaxPool path for residual-like connection
self.maxpool = nn.MaxPool1d(kernel_size=3, stride=1, padding=1)
self.conv_maxpool = nn.Conv1d(in_channels, n_filters, kernel_size=1, bias=False)
# Batch norm for concatenated output (4 paths * n_filters)
self.bn = nn.BatchNorm1d(n_filters * 4)
def forward(self, x):
# Bottleneck
bottleneck = self.bottleneck(x)
# Multi-scale convolutions
conv_small = self.conv_small(bottleneck)
conv_medium = self.conv_medium(bottleneck)
conv_large = self.conv_large(bottleneck)
# MaxPool path
maxpool = self.maxpool(x)
maxpool = self.conv_maxpool(maxpool)
# Concatenate all paths
out = torch.cat([conv_small, conv_medium, conv_large, maxpool], dim=1)
out = self.bn(out)
out = F.relu(out)
return out
class InceptionTime(nn.Module):
"""
InceptionTime: State-of-the-art deep learning for time series classification.
Architecture features:
- Multiple Inception blocks for multi-scale pattern extraction
- Residual connections for deep network training
- Global Average Pooling for sequence aggregation
Achieves "on par with the state-of-art" on UCR archive while being scalable.
Reference: Ismail Fawaz et al., 2019
"""
def __init__(self, input_channels=6, n_classes=1, n_filters=32, n_blocks=3,
bottleneck_size=32, embedding_dim=128, dropout=0.3):
super().__init__()
self.embedding_dim = embedding_dim
# Initial Inception block
self.inception1 = InceptionBlock(input_channels, n_filters, bottleneck_size)
# Additional Inception blocks with residual connections
self.inception_blocks = nn.ModuleList()
self.residual_convs = nn.ModuleList()
current_channels = n_filters * 4 # 4 paths in inception block
for i in range(n_blocks - 1):
self.inception_blocks.append(
InceptionBlock(current_channels, n_filters, bottleneck_size)
)
# Residual connection (optional skip)
if i % 2 == 1:
self.residual_convs.append(
nn.Sequential(
nn.Conv1d(current_channels, n_filters * 4, kernel_size=1, bias=False),
nn.BatchNorm1d(n_filters * 4)
)
)
else:
self.residual_convs.append(None)
# Global Average Pooling
self.gap = nn.AdaptiveAvgPool1d(1)
# Embedding head
self.embedding_head = nn.Sequential(
nn.Linear(n_filters * 4, embedding_dim),
nn.BatchNorm1d(embedding_dim),
nn.SiLU(),
nn.Dropout(dropout)
)
# Classification head
self.classifier = nn.Linear(embedding_dim, n_classes)
def forward(self, x):
"""
x: [batch, channels=6, seq_len=100]
"""
# Initial inception
out = self.inception1(x)
identity = out
# Additional inception blocks with residual
for i, (inception, residual) in enumerate(zip(self.inception_blocks, self.residual_convs)):
out = inception(out)
if residual is not None:
out = out + residual(identity)
identity = out
# Global average pooling
out = self.gap(out) # [batch, channels, 1]
out = out.squeeze(-1) # [batch, channels]
# Embedding
emb = self.embedding_head(out)
# Classification
logits = self.classifier(emb)
return logits, emb
class TDE_Transformer(nn.Module):
"""
Tier 3: Transformer-based TDE Classifier (T2 Architecture).
Ref: "Time-Series Transformer Implementation (HIGH IMPACT)"
Architecture:
1. Input Embedding: 1D Conv per band (captures local patterns)
2. Positional Encoding: Temporal ordering
3. Transformer Encoder: 3-6 layers, 4-8 heads
4. GAP + Classification
"""
def __init__(self, input_bands=6, seq_len=100, embedding_dim=128, n_heads=8, n_layers=4, dropout=0.2):
super().__init__()
self.embedding_dim = embedding_dim
# Input embedding using 1D convolution
self.input_conv = nn.Conv1d(input_bands, embedding_dim, kernel_size=3, padding=1)
# Position encoding
self.pos_encoder = nn.Parameter(torch.randn(1, embedding_dim, seq_len) * 0.02)
# Transformer Encoder
encoder_layer = nn.TransformerEncoderLayer(
d_model=embedding_dim,
nhead=n_heads,
dim_feedforward=embedding_dim * 4,
dropout=dropout,
activation='gelu',
batch_first=True
)
self.transformer = nn.TransformerEncoder(encoder_layer, num_layers=n_layers)
# Global pooling + Head
self.gap = nn.AdaptiveAvgPool1d(1)
self.classifier = nn.Sequential(
nn.Linear(embedding_dim, embedding_dim // 2),
nn.GELU(),
nn.Dropout(dropout),
nn.Linear(embedding_dim // 2, 1)
)
def forward(self, x):
"""
x: [batch, bands=6, seq_len=100]
"""
# Embedding: [Batch, 6, L] -> [Batch, D, L]
x = self.input_conv(x)
# Add Positional Encoding
x = x + self.pos_encoder[:, :, :x.shape[2]]
# Permute for Transformer: [Batch, L, D] (since batch_first=True)
x = x.permute(0, 2, 1)
# Transformer
x = self.transformer(x)
# GAP: [Batch, L, D] -> [Batch, D, L] -> [Batch, D, 1]
x = x.permute(0, 2, 1)
x = self.gap(x).squeeze(-1)
# Classification
out = self.classifier(x)
return out, x
class TabularTransformer(nn.Module):
"""
Transformer branch for Tabular Metadata (ATAT-style).
Instead of a simple MLP, we project features into a sequence of embeddings
to allow the Transformer to learn complex feature interactions via self-attention.
Ref: "ATAT: processes metadata (redshift, extinction, derived features)"
"""
def __init__(self, input_dim, d_model=32, n_heads=4, n_layers=3, dropout=0.1):
super().__init__()
# Project input into sequence of tokens
self.n_tokens = 8
self.tokenizer = nn.Linear(input_dim, self.n_tokens * d_model)
self.pos_encoder = nn.Parameter(torch.randn(1, self.n_tokens, d_model) * 0.02)
encoder_layer = nn.TransformerEncoderLayer(
d_model=d_model,
nhead=n_heads,
dim_feedforward=d_model * 4,
dropout=dropout,
activation='gelu',
batch_first=True
)
self.transformer = nn.TransformerEncoder(encoder_layer, num_layers=n_layers)
# Output aggregation
self.gap = nn.AdaptiveAvgPool1d(1)
def forward(self, x):
"""
x: [Batch, n_features] (e.g. 300)
"""
bs = x.shape[0]
# Tokenize: [Batch, n_features] -> [Batch, n_tokens * d_model]
tokens = self.tokenizer(x)
# Reshape: [Batch, n_tokens, d_model]
tokens = tokens.view(bs, self.n_tokens, -1)
# Positional Encoding
tokens = tokens + self.pos_encoder
# Transformer
out = self.transformer(tokens)
# Aggregate: [Batch, n_tokens, d_model] -> [Batch, d_model]
out = out.permute(0, 2, 1)
emb = self.gap(out).squeeze(-1)
return emb
class ATAT_Model(nn.Module):
"""
ATAT: Astronomical Transformer (Dual Branch).
Combines Lightcurve Transformer (Tlc) and Tabular Transformer (Ttab).
Ref: "Concatenate outputs from both transformers... Final classification through 2-layer MLP"
"""
def __init__(self,
lc_input_bands=6, lc_seq_len=100, lc_embed=128,
tab_input_dim=300, tab_embed=32,
n_heads=4, n_layers=3, dropout=0.2):
super().__init__()
# Branch 1: Lightcurve Transformer (Tlc)
self.tlc = TDE_Transformer(
input_bands=lc_input_bands,
seq_len=lc_seq_len,
embedding_dim=lc_embed,
n_heads=n_heads,
n_layers=n_layers,
dropout=dropout
)
# Remove classifier to get embedding directly
self.tlc.classifier = nn.Identity()
# Branch 2: Tabular Transformer (Ttab)
self.ttab = TabularTransformer(
input_dim=tab_input_dim,
d_model=tab_embed,
n_heads=4,
n_layers=3,
dropout=dropout
)
# Fusion Head
fusion_dim = lc_embed + tab_embed
self.head = nn.Sequential(
nn.Linear(fusion_dim, fusion_dim // 2),
nn.GELU(),
nn.Dropout(dropout),
nn.Linear(fusion_dim // 2, 1)
)
def forward(self, lc_data, tab_data):
"""
lc_data: [Batch, 6, 100]
tab_data: [Batch, n_features]
"""
# Get embeddings
_, lc_emb = self.tlc(lc_data)
tab_emb = self.ttab(tab_data)
# Concatenate
combined = torch.cat([lc_emb, tab_emb], dim=1)
# Final classification
logits = self.head(combined)
return logits, combined
class TDE_CNN1D(nn.Module):
"""Legacy 1D CNN - kept for compatibility. Consider using TDE_Transformer instead."""
def __init__(self, input_channels=6, embedding_dim=64):
super().__init__()
self.features = nn.Sequential(
# Block 1
nn.Conv1d(input_channels, 32, kernel_size=3, padding=1),
nn.BatchNorm1d(32),
nn.ReLU(),
nn.MaxPool1d(2),
# Block 2 (Dilated)
nn.Conv1d(32, 64, kernel_size=3, padding=2, dilation=2),
nn.BatchNorm1d(64),
nn.ReLU(),
nn.MaxPool1d(2),
# Block 3 (Dilated)
nn.Conv1d(64, 128, kernel_size=3, padding=4, dilation=4),
nn.BatchNorm1d(128),
nn.ReLU(),
nn.MaxPool1d(2),
nn.Flatten()
)
self.embedding_head = nn.Sequential(
nn.Linear(1536, embedding_dim),
nn.ReLU(),
nn.Dropout(0.3)
)
self.classifier = nn.Linear(embedding_dim, 1)
def forward(self, x):
x = self.features(x)
emb = self.embedding_head(x)
out = self.classifier(emb)
return out, emb
# ============================================================
# CONTRASTIVE & METRIC LEARNING - NaN FIXES
# ============================================================
class SimCLR(nn.Module):
"""
SimCLR Framework for Self-Supervised Learning.
Encoder: Base Transformer (Tlc or ATAT)
Projector: MLP to embedding space
"""
def __init__(self, encoder, input_dim=128, projection_dim=128):
super().__init__()
self.encoder = encoder
self.projector = nn.Sequential(
nn.Linear(input_dim, input_dim),
nn.ReLU(),
nn.Linear(input_dim, projection_dim)
)
def forward(self, x):
# x is a batch of lightcurves OR tuple (lc, tab) for ATAT
if isinstance(x, (list, tuple)):
# ATAT expects (lc, tab) as separate arguments
lc, tab = x
_, h = self.encoder(lc, tab)
else:
_, h = self.encoder(x)
z = self.projector(h)
return h, z
class SupConLoss(nn.Module):
"""
Supervised Contrastive Learning Loss - NaN FIXED VERSION.
FIX 1: Increased default temperature from 0.1 to 0.2 for numerical stability
FIX 2: Added gradient clipping in normalization
FIX 3: Better handling of edge cases
"""
def __init__(self, temperature=0.2, base_temperature=0.07): # CHANGED: temperature 0.1 -> 0.2
super().__init__()
self.temperature = temperature
self.base_temperature = base_temperature
def forward(self, features, labels):
"""
features: [Batch, Dim] (normalized)
labels: [Batch]
"""
device = features.device
batch_size = features.shape[0]
# FIX: Check for NaN in inputs
if torch.isnan(features).any():
print("WARNING: NaN detected in features input to SupConLoss")
features = torch.nan_to_num(features, nan=0.0)
# Labels reshape
labels = labels.contiguous().view(-1, 1)
if labels.shape[0] != batch_size:
raise ValueError('Num labels must match num features')
# Mask of same-class samples (positives)
mask = torch.eq(labels, labels.T).float().to(device)
# FIX: L2 normalize with explicit eps to prevent division by zero
features = F.normalize(features, p=2, dim=1, eps=1e-8)
# Compute logits (cosine similarity)
anchor_dot_contrast = torch.div(
torch.matmul(features, features.T),
self.temperature
)
# FIX: Clip logits to prevent overflow
anchor_dot_contrast = torch.clamp(anchor_dot_contrast, min=-50, max=50)
# Numerical stability
logits_max, _ = torch.max(anchor_dot_contrast, dim=1, keepdim=True)
logits = anchor_dot_contrast - logits_max.detach()
# Mask-out self-contrast cases
logits_mask = torch.scatter(
torch.ones_like(mask),
1,
torch.arange(batch_size).view(-1, 1).to(device),
0
)
mask = mask * logits_mask
# FIX: Check if mask has any positives
mask_sum = mask.sum(1)
if (mask_sum == 0).any():
# Some samples have no positives - add small epsilon
mask_sum = torch.clamp(mask_sum, min=1e-7)
# Compute log_prob
exp_logits = torch.exp(logits) * logits_mask
log_prob = logits - torch.log(exp_logits.sum(1, keepdim=True) + 1e-7)
# Mean log-likelihood for positive pairs
mean_log_prob_pos = (mask * log_prob).sum(1) / (mask_sum + 1e-7)
# FIX: Check for NaN before loss computation
if torch.isnan(mean_log_prob_pos).any():
print("WARNING: NaN in mean_log_prob_pos, replacing with zeros")
mean_log_prob_pos = torch.nan_to_num(mean_log_prob_pos, nan=0.0)
# Loss
loss = - (self.temperature / self.base_temperature) * mean_log_prob_pos
loss = loss.view(1, batch_size).mean()
# FIX: Final NaN check
if torch.isnan(loss):
print("WARNING: NaN loss detected, returning zero loss")
return torch.tensor(0.0, device=device, requires_grad=True)
return loss
class ImbalancedArcFaceLoss(nn.Module):
"""
ArcFace with Class-Specific Margins for Rare Classes.
Margin TDE >> Margin Non-TDE.
"""
def __init__(self, in_features, out_features, s=30.0, margin_tde=0.7, margin_non_tde=0.3):
super().__init__()
self.in_features = in_features
self.out_features = out_features
self.s = s
self.margins = {1: margin_tde, 0: margin_non_tde}
self.weight = nn.Parameter(torch.FloatTensor(out_features, in_features))
nn.init.xavier_uniform_(self.weight)
def forward(self, input, label):
# input: [Batch, features]
# label: [Batch] (long)
# Ensure weight is on same device as input
weight = self.weight.to(input.device)
# Normalize weights and features
cosine = F.linear(F.normalize(input), F.normalize(weight))
# Get dynamic margins based on label
m_vec = torch.tensor([self.margins[int(y)] for y in label.cpu().numpy()], device=input.device)
# One-hot
one_hot = torch.zeros(cosine.size(), device=input.device)
one_hot.scatter_(1, label.view(-1, 1).long(), 1)
# Add angular margin: theta + m
theta = torch.acos(torch.clamp(cosine, -1.0 + 1e-7, 1.0 - 1e-7))
target_logits = torch.cos(theta + m_vec.view(-1, 1))
# Scale
output = one_hot * target_logits + (1.0 - one_hot) * cosine
output *= self.s
return output
# ============================================================
# BALANCED BATCH SAMPLER
# ============================================================
class BalancedBatchSampler:
"""
Ensures each batch has a minimum number of positive samples.
Critical for extreme class imbalance (4.8% positive).
"""
def __init__(self, labels, batch_size, min_positives=4):
self.labels = labels
self.batch_size = batch_size
self.min_positives = min_positives
self.pos_indices = np.where(labels == 1)[0]
self.neg_indices = np.where(labels == 0)[0]
self.n_batches = len(labels) // batch_size
def __iter__(self):
for _ in range(self.n_batches):
# Sample positives
pos_sample = np.random.choice(
self.pos_indices,
size=min(self.min_positives, len(self.pos_indices)),
replace=False
)
# Sample negatives to fill batch
n_neg = self.batch_size - len(pos_sample)
neg_sample = np.random.choice(
self.neg_indices,
size=n_neg,
replace=False
)
# Combine and shuffle
batch = np.concatenate([pos_sample, neg_sample])
np.random.shuffle(batch)
yield batch.tolist()
def __len__(self):
return self.n_batches
# ============================================================
# TRAINING FUNCTIONS - PERFORMANCE OPTIMIZED
# ============================================================
def train_transformer_fold(
train_ids, val_ids, y_train, y_val,
processed_splits,
X_train_tab=None, X_val_tab=None,
n_epochs=30, # INCREASED from 15
batch_size=64, # DECREASED from 128 for stability
device='cuda',
use_atat=True,
pretrained_weights=None,
use_arcface=False,
num_workers=2,
# Architecture Params
n_heads=4,
n_layers=3,
embedding_dim=128,
dropout=0.3,
patience=8 # Default patience
):
"""
FIXED VERSION with:
1. Gradient clipping (CRITICAL)
2. Better learning rate schedule
3. Class balancing via sampler
4. Early stopping with patience
5. Warmup phase
6. Focal Loss instead of BCE
"""
# Imports removed: classes are defined in this file
# ============================================================
# FIX 1: CREATE BALANCED SAMPLER
# ============================================================
tab_map_train = None
tab_map_val = None
if use_atat and X_train_tab is not None:
tab_map_train = {oid: row for oid, row in zip(train_ids, X_train_tab)}
tab_map_val = {oid: row for oid, row in zip(val_ids, X_val_tab)}
train_ds = LightCurveDataset(
processed_splits, train_ids, {}, y_train,
tabular_features=tab_map_train,
use_gp=False
)
val_ds = LightCurveDataset(
processed_splits, val_ids, {}, y_val,
tabular_features=tab_map_val,
use_gp=False
)
# CRITICAL: Use BalancedBatchSampler for extreme imbalance
balanced_sampler = BalancedBatchSampler(
labels=y_train,
batch_size=batch_size,
min_positives=max(4, int(batch_size * 0.1)) # At least 10% positive per batch
)
train_loader = DataLoader(
train_ds,
batch_sampler=balanced_sampler, # Use balanced sampler instead of shuffle
num_workers=num_workers,
pin_memory=True,
persistent_workers=True if num_workers > 0 else False
)
val_loader = DataLoader(
val_ds,
batch_size=batch_size,
shuffle=False,
num_workers=num_workers,
pin_memory=True
)
# ============================================================
# FIX 2: MODEL WITH BETTER INITIALIZATION
# ============================================================
embedding_dim = 128
if use_atat and X_train_tab is not None:
model = ATAT_Model(
tab_input_dim=X_train_tab.shape[1],
tab_embed=32,
dropout=0.3 # INCREASED dropout
).to(device)
else:
model = TDE_Transformer(
input_bands=6,
seq_len=100,
embedding_dim=embedding_dim,
n_heads=n_heads,