File size: 29,815 Bytes
232c308
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True" # <--- ADD THIS
import torch
import config
import monai
import warnings
import numpy as np
import pandas as pd
import psutil  # <--- ADDED FOR MEMORY MONITORING
import wandb

# --- ADDED FOR HUGGING FACE ---
try:
    import huggingface_hub
except ImportError:
    print("⚠️ huggingface_hub not installed. Please run: pip install huggingface-hub")

HF_TOKEN = os.environ.get("HF_TOKEN")
if HF_TOKEN:
    print("✅ Hugging Face token found — will upload checkpoints to cloud")
else:
    print("⚠️ HF_TOKEN not set — checkpoints will only be saved locally")
# ------------------------------

from model.CMTLNet import CFE

from torch.nn import CrossEntropyLoss
from torch.utils.data import DataLoader
from torch.optim.lr_scheduler import ReduceLROnPlateau
from dataLoder.loader_S1 import TrainDataLoader_balance as TrainDataLoader
from dataLoder.loader_S1 import TestDataLoader
from utiles import save_model, get_learning_rate, calculate_classification_metrics, move_tensor_to_device, AverageMeter
from torch.cuda.amp import autocast, GradScaler  # <--- ADDED AMP IMPORT

def validate(data_loader, model, mode_flag, ssl_index, class_name):
    """
    Validates the model on a given dataset and computes loss and classification metrics.

    Parameters:
        data_loader (DataLoader): DataLoader for the dataset to validate.
        model (torch.nn.Module): The model to validate.
        mode_flag (str): Indicates whether the dataset is 'Train' or 'Test'.
        ssl_index (int): SSL index used for model prediction.
        class_name (str): Name of the class/category being validated.

    Returns:
        tuple: Contains average loss, accuracy, F1 score, precision, and recall.
    """
    model.eval()  # Set model to evaluation mode
    cross_entropy_loss = CrossEntropyLoss(reduction='mean')  # Define cross-entropy loss
    all_targets, all_predictions = [], []  # Lists to store all true labels and predictions
    loss_meter = AverageMeter()  # Utility to track average loss

    for batch_data in data_loader:
        images, labels = batch_data
        images = move_tensor_to_device(images, use_gpu=config.use_cuda)  # Move images to GPU if available
        labels = move_tensor_to_device(labels, use_gpu=config.use_cuda)  # Move labels to GPU if available

        with torch.no_grad():  # Disable gradient computation
            outputs = model.predict(images, ssl_index)  # Get model predictions
            loss = cross_entropy_loss(outputs, labels)  # Compute loss
            loss_meter.update(loss.item(), 1)  # Update loss meter
            probabilities = torch.nn.functional.softmax(outputs, dim=1)  # Compute probabilities
            predicted_classes = torch.argmax(probabilities, dim=1).cpu().numpy()  # Get predicted classes
            true_labels = labels.cpu().detach().numpy()  # Get true labels
            all_predictions.extend(predicted_classes)  # Collect predictions
            all_targets.extend(true_labels)  # Collect true labels

    average_loss = loss_meter.average  # Calculate average loss
    all_predictions = np.array(all_predictions, dtype=np.int32)
    all_targets = np.array(all_targets, dtype=np.int32)
    # Compute classification metrics: Accuracy, F1, Precision, Recall, and Confusion Matrix
    accuracy, f1, precision, recall, confusion_matrix = calculate_classification_metrics(
        predictions=all_predictions,
        targets=all_targets,
        average_method="macro"
    )
    print(confusion_matrix)  # Print confusion matrix

    # Print metrics based on whether it's training or testing
    if mode_flag == 'Test':
        print(f'Test set {class_name} | Accuracy {accuracy:.4f} | F1 {f1:.4f} | Precision {precision:.4f} | Recall {recall:.4f} |')
    else:
        print(f'Train set {class_name} | Accuracy {accuracy:.4f} | F1 {f1:.4f} | Precision {precision:.4f} | Recall {recall:.4f} |')

    model.train()  # Set model back to training mode

    return average_loss, accuracy, f1, precision, recall


def valid_metrics_by_class(model, train_loader, test_loader, ssl_index, class_name):
    """
    Computes validation metrics for a specific class on both training and testing datasets.

    Parameters:
        model (torch.nn.Module): The model to validate.
        train_loader (DataLoader): DataLoader for the training dataset.
        test_loader (DataLoader): DataLoader for the testing dataset.
        ssl_index (int): SSL index used for model prediction.
        class_name (str): Name of the class/category being validated.

    Returns:
        tuple: Contains training metrics and testing metrics.
    """
    # Validate on training data
    train_loss, train_accuracy, train_f1, train_precision, train_recall = validate(
        data_loader=train_loader,
        model=model,
        mode_flag='Train',
        ssl_index=ssl_index,
        class_name=class_name
    )

    # Validate on testing data
    test_loss, test_accuracy, test_f1, test_precision, test_recall = validate(
        data_loader=test_loader,
        model=model,
        mode_flag='Test',
        ssl_index=ssl_index,
        class_name=class_name
    )

    # Collect training and testing metrics
    metrics_train = [train_loss, train_accuracy, train_f1, train_precision, train_recall]
    metrics_test = [test_loss, test_accuracy, test_f1, test_precision, test_recall]
    return metrics_train, metrics_test


def get_pandas_series(epoch, train_metrics, test_metrics):
    """
    Creates a Pandas Series for logging metrics.

    Parameters:
        epoch (int): Current epoch number.
        train_metrics (list): List of training metrics.
        test_metrics (list): List of testing metrics.

    Returns:
        pd.Series: Series containing epoch and corresponding metrics.
    """
    series = pd.Series([
        epoch,
        train_metrics[0],  # Training loss
        train_metrics[1],  # Training accuracy
        train_metrics[2],  # Training F1 score
        test_metrics[0],   # Testing loss
        test_metrics[1],   # Testing accuracy
        test_metrics[2],   # Testing F1 score
    ], index=[
        'epoch',
        'Train_loss', 'Train_Accuracy', 'Train_F1',
        'Val_loss', 'Val_Accuracy', 'Val_F1'
    ])
    return series


def get_class_loaders(TrainDataset, TestDataset, transforms, fold, loader_id, pkl_path):
    """
    Creates DataLoaders for training and validation datasets for a specific class.

    Parameters:
        TrainDataset (Dataset): Training dataset class.
        TestDataset (Dataset): Testing dataset class.
        transforms (Compose): Data transformation pipeline.
        fold (int): Current fold number for cross-validation.
        loader_id (str): Identifier for the class.
        pkl_path (str): Path to the pickle file containing dataset information.

    Returns:
        tuple: Contains training DataLoader, validation training DataLoader, and validation testing DataLoader.
    """
    # Create training dataset
    train_dataset = TrainDataset(
        mode='train',
        fold=fold,
        transform=transforms,
        random_flag=config.random_flag,
        pickle_path=pkl_path
    )

    # Create training DataLoader
    train_loader = DataLoader(
        train_dataset,
        batch_size=config.batch_size,
        shuffle=True,
        drop_last=True,
        num_workers=config.n_threads,
        pin_memory=True,  # Changed to True for Linux Server
        prefetch_factor=4,
        persistent_workers=True
    )
    print(f"Number of train_loader {loader_id} examples {len(train_dataset)}")

    # Create validation training dataset
    val_train_dataset = TestDataset(
        mode='train',
        fold=fold,
        transform=transforms,
        pickle_path=pkl_path
    )

    # Create validation training DataLoader
    val_train_loader = DataLoader(
        val_train_dataset,
        batch_size=1,
        shuffle=False,
        drop_last=False,
        num_workers=12,
        pin_memory=True,
        prefetch_factor=2,
        persistent_workers=False
    )
    print(f"Number of val_train_loader {loader_id} examples {len(val_train_dataset)}")

    # Create validation testing dataset
    val_test_dataset = TestDataset(
        mode='test',
        fold=fold,
        transform=transforms,
        pickle_path=pkl_path
    )

    # Create validation testing DataLoader
    val_loader = DataLoader(
        val_test_dataset,
        batch_size=1,
        shuffle=False,
        drop_last=False,
        num_workers=12,
        pin_memory=True,
        prefetch_factor=2,
        persistent_workers=False
    )
    print(f"Number of val_loader {loader_id} examples {len(val_test_dataset)}")
    return train_loader, val_train_loader, val_loader

def reshape_input_data(data):
    """
    Reshapes input data and moves it to the appropriate device (GPU or CPU).

    Parameters:
        data (tuple): Tuple containing images, tumour-related labels, and classification labels.

    Returns:
        tuple: Reshaped images, tumour-related labels, and classification labels.
    """
    images, label_NT, labels = data
    # Reshape images
    images = images.view(
        images.size(0) * images.size(1),
        images.size(2),
        images.size(3),
        images.size(4),
        images.size(5)
    )
    # Reshape non-target labels and target labels
    label_NT = label_NT.view(-1)
    labels = labels.view(-1)

    # --- FORCE GPU OVERRIDE (Bypass Config completely) ---
    images = images.to('cuda')
    label_NT = label_NT.to('cuda')
    labels = labels.to('cuda')
    return images, label_NT, labels


def train(fold, pkl_paths, model):  # Added model as parameter
    """
    Main training function responsible for the entire training process, including data loading, model training,
    validation, logging, and model saving.

    Parameters:
        fold (int): Current fold number for cross-validation.
        pkl_paths (list): List of paths to pickle files for each class.
        model (torch.nn.Module): The model to train.
    """
    # Define data transformations
    val_transforms = monai.transforms.Compose([
        monai.transforms.ToTensor(),
    ])

    # Get DataLoaders for each class
    train_loader_1p19q, val_train_loader_1p19q, val_loader_1p19q = get_class_loaders(
        TrainDataset=TrainDataLoader,
        TestDataset=TestDataLoader,
        transforms=val_transforms,
        fold=fold,
        loader_id='1p19q',
        pkl_path=pkl_paths[0]
    )
    train_loader_IDH, val_train_loader_IDH, val_loader_IDH = get_class_loaders(
        TrainDataset=TrainDataLoader,
        TestDataset=TestDataLoader,
        transforms=val_transforms,
        fold=fold,
        loader_id='IDH',
        pkl_path=pkl_paths[1]
    )
    train_loader_LHG, val_train_loader_LHG, val_loader_LHG = get_class_loaders(
        TrainDataset=TrainDataLoader,
        TestDataset=TestDataLoader,
        transforms=val_transforms,
        fold=fold,
        loader_id='LHG',
        pkl_path=pkl_paths[2]
    )

    cross_entropy_loss = CrossEntropyLoss(reduction='mean')  # Define cross-entropy loss

    # Only optimize parameters that require gradients
    optim_parameters = filter(lambda p: p.requires_grad, model.parameters())
    optimizer = torch.optim.Adam(
        optim_parameters,
        lr=config.lr_self,
        weight_decay=config.weight_decay
    )  # Using Adam optimizer
    
    scaler = GradScaler()  # <--- INITIALIZE MIXED PRECISION SCALER

    # Learning rate scheduler
    scheduler = ReduceLROnPlateau(
        optimizer=optimizer,
        factor=config.lr_reduce_factor,
        patience=config.lr_reduce_patience,
        mode='max',
        min_lr=config.min_lr
    )

    global_step = 0  # Initialize global step
    best_score = -1  # Initialize best score
    start_epoch = 0

    save_name = getattr(model, 'name', 'CFE')
    save_path = os.path.join(config.data_dir, 'results', str(save_name), f'Fold_{fold}')
    if not os.path.exists(save_path):
        os.makedirs(save_path, exist_ok=True)

    # Check if this fold is already fully completed
    mean_log_file = os.path.join(save_path, 'log_mean.csv')
    if os.path.exists(mean_log_file):
        try:
            df_existing = pd.read_csv(mean_log_file)
            if len(df_existing) >= config.epochs_s1 and df_existing['epoch'].max() >= config.epochs_s1 - 1:
                print(f"🎉 Fold {fold} is already fully completed ({len(df_existing)}/{config.epochs_s1} epochs). Skipping!")
                return
        except Exception as e:
            print(f"Warning checking fold completion: {e}")

    # Find the latest checkpoint for this fold automatically
    import glob
    latest_checkpoint = None
    checkpoints = glob.glob(f'checkpoint_fold{fold}_epoch*.pkl')
    if checkpoints:
        # Extract epoch numbers and sort to find the latest
        latest_checkpoint = max(checkpoints, key=lambda x: int(x.split('epoch')[1].split('.pkl')[0]))
    
    resume_path = latest_checkpoint if latest_checkpoint else config.resume_checkpoint

    if resume_path and os.path.exists(resume_path):
        print(f"Resuming from checkpoint: {resume_path}")
        checkpoint = torch.load(resume_path, weights_only=False)
        model.load_state_dict(checkpoint['model_state_dict'])
        
        if 'optimizer_state_dict' in checkpoint:
            optimizer.load_state_dict(checkpoint['optimizer_state_dict'])
        if 'scheduler_state_dict' in checkpoint:
            scheduler.load_state_dict(checkpoint['scheduler_state_dict'])
        if 'scaler_state_dict' in checkpoint:
            scaler.load_state_dict(checkpoint['scaler_state_dict'])
        if 'global_step' in checkpoint:
            global_step = checkpoint['global_step']
        if 'best_f1' in checkpoint:
            best_score = checkpoint['best_f1']
        if 'epoch' in checkpoint:
            start_epoch = checkpoint['epoch'] + 1

    # Initialize DataFrames for logging, preserving prior epochs if resuming
    def load_or_init_log(filename):
        csv_p = os.path.join(save_path, filename)
        if start_epoch > 0 and os.path.exists(csv_p):
            try:
                df = pd.read_csv(csv_p)
                df = df[df['epoch'] < start_epoch]
                print(f"Preserved {len(df)} previous epochs from {filename}")
                return df
            except Exception as e:
                print(f"Warning reading existing {csv_p}: {e}")
        return pd.DataFrame(columns=[
            'epoch',
            'Train_loss', 'Train_Accuracy', 'Train_F1',
            'Val_loss', 'Val_Accuracy', 'Val_F1'
        ])

    log_1p19q = load_or_init_log('log_1p19q.csv')
    log_IDH = load_or_init_log('log_IDH.csv')
    log_LHG = load_or_init_log('log_LHG.csv')
    log_mean = load_or_init_log('log_mean.csv')

    model.train()  # Set model to training mode

    # Initialize iterator indices
    iter_index_IDH = 0
    iter_index_LHG = 0

    iter_IDH = iter(train_loader_IDH)
    iter_LHG = iter(train_loader_LHG)

    for epoch in range(start_epoch, config.epochs_s1):
        print(f"\n--- STARTING EPOCH {epoch} ---")  # Added to track epoch progress
        if epoch == config.save_epoch:
            best_score = -1  # Reset best score at a specific epoch

        iter_1p19q = iter(train_loader_1p19q)  # Get iterator for 1p19q class
        
        # --- START PROGRESS BAR HERE ---
        for batch_idx in range(len(train_loader_1p19q)):
            # --- AGGRESSIVE PRE-LOAD CLEANUP ---
            import gc
            gc.collect() 
            # -----------------------------------
            
            # --- MEMORY WATCHDOG ---
            process = psutil.Process(os.getpid())
            mem_gb = process.memory_info().rss / (1024 ** 3)
            
            # -----------------------
            
            iter_index_IDH += 1
            iter_index_LHG += 1

            # Reset iterators if they exceed dataset length
            if iter_index_IDH >= len(train_loader_IDH):
                iter_IDH = iter(train_loader_IDH)
                iter_index_IDH = 0

            if iter_index_LHG >= len(train_loader_LHG):
                iter_LHG = iter(train_loader_LHG)
                iter_index_LHG = 0

            # Loading 1p19q data volume...
            try:
                data_1p19q = next(iter_1p19q)
            except Exception as e:
                print(f"CRITICAL ERROR LOADING 1p19q DATA: {e}")
                raise e
            imgs_1p19q, label_NT_1p19q, label_1p19q = reshape_input_data(data_1p19q)
            del data_1p19q 
            gc.collect()

            # Loading IDH data volume...
            data_IDH = next(iter_IDH)
            imgs_IDH, label_NT_IDH, label_IDH = reshape_input_data(data_IDH)
            del data_IDH  
            gc.collect()

            # Loading LHG data volume...
            data_LHG = next(iter_LHG)
            imgs_LHG, label_NT_LHG, label_LHG = reshape_input_data(data_LHG)
            del data_LHG  
            gc.collect()

            # Packaging multi-task tensors...
            label_list = [label_1p19q, label_IDH, label_LHG]
            combined_input = torch.cat((imgs_1p19q, imgs_IDH, imgs_LHG), dim=0)
            labels_NG_list = [label_NT_1p19q, label_NT_IDH, label_NT_LHG]

            # Commencing forward model execution on GPU...
            
            # --- START 50% MEMORY SAVINGS W/ MIXED PRECISION ---
            with autocast():
                (logits_NG, labels_NG_all, out_cls_list_NG,
                 out_cls_list, out_cls_labels) = model(combined_input, labels_NG_list, label_list)

                # Compute losses
                loss_NG = cross_entropy_loss(logits_NG, labels_NG_all)
                loss_cls_N1 = cross_entropy_loss(out_cls_list_NG[0], label_list[0])
                loss_cls_N2 = cross_entropy_loss(out_cls_list_NG[1], label_list[1])
                loss_cls_N3 = cross_entropy_loss(out_cls_list_NG[2], label_list[2])
                loss_cls_1 = cross_entropy_loss(out_cls_list[0], out_cls_labels[0])
                loss_cls_2 = cross_entropy_loss(out_cls_list[1], out_cls_labels[1])
                loss_cls_3 = cross_entropy_loss(out_cls_list[2], out_cls_labels[2])

                total_cls_loss = loss_cls_1 + loss_cls_2 + loss_cls_3 + loss_cls_N1 + loss_cls_N2 + loss_cls_N3
                total_loss = loss_NG + total_cls_loss
            # --- END MIXED PRECISION ---

            optimizer.zero_grad(set_to_none=True)
            
            # --- SCALE GRADIENTS FOR HALF-PRECISION MEMORY ---
            scaler.scale(total_loss).backward()
            scaler.step(optimizer)
            scaler.update()
            # --------------------------------------------------
            
            if batch_idx % 10 == 0:
                print(f"   [Epoch {epoch}] Batch {batch_idx}/{len(train_loader_1p19q)} | Loss: {total_loss.item():.4f} | RAM: {mem_gb:.2f} GB")

            # --- MASSIVE RAM & GPU CLEANUP AFTER EACH BATCH ---
            del imgs_1p19q, imgs_IDH, imgs_LHG, combined_input
            del logits_NG, labels_NG_all, out_cls_list_NG, out_cls_list, out_cls_labels
            del total_loss, total_cls_loss, loss_NG
            # REMOVED torch.cuda.empty_cache() to prevent VRAM fragmentation
            gc.collect()
            # --------------------------------------------------

            global_step += 1

        # Get current learning rate
        current_lr = get_learning_rate(optimizer)
        print(f'Global_Step {global_step} | Train Epoch: {epoch} | lr {current_lr:.2e} |')

        # Define save path
        save_path = os.path.join(config.data_dir, 'results', str(save_name), f'Fold_{fold}')
        if not os.path.exists(save_path):
            os.makedirs(save_path)

        # Compute metrics for each class
        metrics_train_1p19q, metrics_test_1p19q = valid_metrics_by_class(
            model=model,
            train_loader=val_train_loader_1p19q,
            test_loader=val_loader_1p19q,
            ssl_index=0,
            class_name='1p19q'
        )

        metrics_train_IDH, metrics_test_IDH = valid_metrics_by_class(
            model=model,
            train_loader=val_train_loader_IDH,
            test_loader=val_loader_IDH,
            ssl_index=1,
            class_name='IDH'
        )

        metrics_train_LHG, metrics_test_LHG = valid_metrics_by_class(
            model=model,
            train_loader=val_train_loader_LHG,
            test_loader=val_loader_LHG,
            ssl_index=2,
            class_name='LHG'
        )

        # Calculate mean metrics across classes
        metrics_train_mean = (np.array(metrics_train_1p19q) + np.array(metrics_train_IDH) +
                              np.array(metrics_train_LHG)) / 3.0
        metrics_test_mean = (np.array(metrics_test_1p19q) + np.array(metrics_test_IDH) +
                             np.array(metrics_test_LHG)) / 3.0

        # Create log entries
        log_entry_1p19q = get_pandas_series(epoch, metrics_train_1p19q, metrics_test_1p19q)
        log_entry_IDH = get_pandas_series(epoch, metrics_train_IDH, metrics_test_IDH)
        log_entry_LHG = get_pandas_series(epoch, metrics_train_LHG, metrics_test_LHG)
        log_entry_mean = get_pandas_series(epoch, metrics_train_mean, metrics_test_mean)

        # Append logs to DataFrames and save to CSV (Updated for modern Pandas)
        log_1p19q = pd.concat([log_1p19q, log_entry_1p19q.to_frame().T], ignore_index=True)
        log_1p19q.to_csv(os.path.join(save_path, 'log_1p19q.csv'), index=False)

        log_IDH = pd.concat([log_IDH, log_entry_IDH.to_frame().T], ignore_index=True)
        log_IDH.to_csv(os.path.join(save_path, 'log_IDH.csv'), index=False)

        log_LHG = pd.concat([log_LHG, log_entry_LHG.to_frame().T], ignore_index=True)
        log_LHG.to_csv(os.path.join(save_path, 'log_LHG.csv'), index=False)

        log_mean = pd.concat([log_mean, log_entry_mean.to_frame().T], ignore_index=True)
        log_mean.to_csv(os.path.join(save_path, 'log_mean.csv'), index=False)

        # Use the mean F1 score from the test set as the evaluation metric
        current_f1 = metrics_test_mean[2]

        # Save the best model based on F1 score
        if epoch >= config.save_epoch:
            if current_f1 > best_score:
                save_config = {
                    'name': save_name,
                    'save_dir': save_path,
                    'global_step': global_step,
                    'Test_F1': current_f1
                }
                save_model(model=model, config=save_config)
                
                # Reconstruct path generated by save_model to upload it
                f1_percentage = current_f1 * 100
                best_path = os.path.join(save_path, f"{save_name}_F1_{f1_percentage:.2f}_step_{global_step}.pkl")
                
                # Upload best model to Hugging Face
                hf_token = os.environ.get("HF_TOKEN")
                if hf_token and os.path.exists(best_path):
                    try:
                        from huggingface_hub import upload_file
                        filename_only = os.path.basename(best_path)
                        upload_file(
                            path_or_fileobj=best_path,
                            path_in_repo=f"best_models/fixedone/Fold_{fold}/{filename_only}",
                            repo_id="unknownBrain/survivalanalysis_checkpointing",
                            repo_type="dataset",
                            token=hf_token,
                        )
                        print(f"☁️ Best model uploaded to Hugging Face: {filename_only}")
                    except Exception as e:
                        print(f"⚠️ Hugging Face best model upload failed: {e}")
                
                best_score = current_f1

        # Update the best score if current F1 is better
        if current_f1 > best_score:
            best_score = current_f1

        # Step the scheduler based on the best score
        scheduler.step(best_score)
        
        # ===== LIGHT CHECKPOINT EVERY 5 EPOCHS OR FINAL EPOCH =====
        if (epoch % 5 == 0 and epoch > 0) or (epoch == config.epochs_s1 - 1):
            light_checkpoint_path = f'checkpoint_fold{fold}_epoch{epoch}.pkl'
            torch.save({
                'epoch': epoch,
                'fold': fold,
                'model_state_dict': model.state_dict(),
                'optimizer_state_dict': optimizer.state_dict(),
                'scheduler_state_dict': scheduler.state_dict(),
                'scaler_state_dict': scaler.state_dict(),
                'best_f1': best_score,
                'global_step': global_step
            }, light_checkpoint_path)
            print(f"✅ Light checkpoint saved locally: {light_checkpoint_path}")
            
            # Prune older intermediate checkpoints (keep latest 2) to preserve disk space
            older_epoch = epoch - 10
            older_checkpoint = f'checkpoint_fold{fold}_epoch{older_epoch}.pkl'
            if os.path.exists(older_checkpoint):
                try:
                    os.remove(older_checkpoint)
                    print(f"🧹 Removed older checkpoint to preserve disk: {older_checkpoint}")
                except Exception as e:
                    pass

            # Upload to W&B
            if wandb.run is not None:
                wandb.save(light_checkpoint_path)
                print(f"☁️ Uploaded to W&B: {light_checkpoint_path}")
            
            # Upload to Hugging Face
            hf_token = os.environ.get("HF_TOKEN")
            if hf_token:
                try:
                    from huggingface_hub import upload_file
                    upload_file(
                        path_or_fileobj=light_checkpoint_path,
                        path_in_repo=f"checkpoints/fixedone/{light_checkpoint_path}",
                        repo_id="unknownBrain/survivalanalysis_checkpointing",
                        repo_type="dataset",
                        token=hf_token,
                    )
                    print(f"☁️ Uploaded to Hugging Face: {light_checkpoint_path}")
                except Exception as e:
                    print(f"⚠️ Hugging Face upload failed: {e}")
            else:
                print("ℹ️ HF_TOKEN not set. Skipping Hugging Face upload.")
        # ===== END LIGHT CHECKPOINT =====
        
        # Log to W&B
        if wandb.run is not None:
            wandb.log({
                "Train/Mean_Loss": metrics_train_mean[0], 
                "Train/Mean_Accuracy": metrics_train_mean[1],
                "Train/Mean_F1": metrics_train_mean[2],
                "Test/Mean_Loss": metrics_test_mean[0], 
                "Test/Mean_Accuracy": metrics_test_mean[1],
                "Test/Mean_F1": metrics_test_mean[2],
                "Epoch": epoch, 
                "Learning_Rate": current_lr,
                "Global_Step": global_step
            })
            
        # Safely empty cache at the end of the epoch
        torch.cuda.empty_cache()


if __name__ == '__main__':
    # Ignore all warnings
    warnings.filterwarnings("ignore")

    # Set random seeds for reproducibility
    seed = config.random_seed
    np.random.seed(seed)  # Python's random seed
    os.environ['PYTHONHASHSEED'] = str(seed)  # Disable Python hash randomization
    torch.manual_seed(seed)  # Torch CPU random seed
    torch.cuda.manual_seed(seed)  # Torch GPU random seed
    torch.cuda.manual_seed_all(seed)  # Torch multi-GPU random seed
    
    # --- FIX PYTORCH 3D TENSOR RAM LEAK ---
    torch.backends.cudnn.benchmark = True
    torch.backends.cudnn.deterministic = True

    # Define paths to pickle files for each class
    pkl_paths = [
        './1p19q.pkl',
        './IDH.pkl',
        './LHG.pkl'
    ]

    # Perform 5-fold cross-validation training
    for fold in range(5):
        # Quick check if fold is already completed before allocating model and wandb
        save_path = os.path.join(config.data_dir, 'results', 'CFE', f'Fold_{fold}')
        mean_log_file = os.path.join(save_path, 'log_mean.csv')
        if os.path.exists(mean_log_file):
            try:
                df_existing = pd.read_csv(mean_log_file)
                if len(df_existing) >= config.epochs_s1 and df_existing['epoch'].max() >= config.epochs_s1 - 1:
                    print(f"\n{'='*50}")
                    print(f"🎉 Fold {fold} is already fully completed ({len(df_existing)}/{config.epochs_s1} epochs). Skipping to next fold!")
                    print(f"{'='*50}\n")
                    continue
            except Exception as e:
                pass

        torch.set_float32_matmul_precision('high') # Leverage Tensor Cores
        model = CFE(in_channels=3, num_classes=2, Arcm=0.5, multi=3)  # Initialize the model
        model = model.to('cuda')  # Move model to GPU
        save_name = getattr(model, 'name', 'CFE') # Access before compile
        
        # Compile model for speedup if using PyTorch 2.0+
        if hasattr(torch, 'compile'):
            model = torch.compile(model)
        
        print(f"{save_name}_Fold_{fold}")
        
        wandb.init(
            project=config.wandb_project,
            entity=config.wandb_entity,
            name=f"{save_name}_Fold_{fold}",
            config={
                'epochs': config.epochs_s1,
                'batch_size': config.batch_size,
                'learning_rate': config.lr_self,
                'num_workers': config.n_threads,
                'save_epoch': config.save_epoch,
            },
            reinit=True
        )
        
        train(fold, pkl_paths, model)
        wandb.finish()