Download code/Train_CMTLNet_Step1.py from unknownBrain/survivalanalysis_checkpointing: direct link, hf CLI and curl.
- Browser
- Download file 29.8 kB
-
https://huggingface.co/datasets/unknownBrain/survivalanalysis_checkpointing/resolve/232c308b8fdb813d8a0332da1206d7ea2a13014f/code/Train_CMTLNet_Step1.py
- Command line
-
hf download hf://datasets/unknownBrain/survivalanalysis_checkpointing@232c308b8fdb813d8a0332da1206d7ea2a13014f/code/Train_CMTLNet_Step1.py
-
curl -L -o Train_CMTLNet_Step1.py https://huggingface.co/datasets/unknownBrain/survivalanalysis_checkpointing/resolve/232c308b8fdb813d8a0332da1206d7ea2a13014f/code/Train_CMTLNet_Step1.py
29.8 kB
| 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() |