Download code/Train_CMTLNet_Step2.py from unknownBrain/survivalanalysis_checkpointing: direct link, hf CLI and curl.
- Browser
- Download file 29.3 kB
-
https://huggingface.co/datasets/unknownBrain/survivalanalysis_checkpointing/resolve/main/code/Train_CMTLNet_Step2.py
- Command line
-
hf download hf://datasets/unknownBrain/survivalanalysis_checkpointing/code/Train_CMTLNet_Step2.py
-
curl -L -o Train_CMTLNet_Step2.py https://huggingface.co/datasets/unknownBrain/survivalanalysis_checkpointing/resolve/main/code/Train_CMTLNet_Step2.py
29.3 kB
| import os | |
| import glob | |
| import gc | |
| import wandb | |
| from torch.cuda.amp import autocast, GradScaler | |
| from huggingface_hub import upload_file | |
| os.environ["CUDA_VISIBLE_DEVICES"] = "0" | |
| import torch | |
| import config | |
| import monai | |
| import warnings | |
| import numpy as np | |
| import pandas as pd | |
| from model.CMTLNet import CMTLNet | |
| from torch.nn import CrossEntropyLoss | |
| from torch.utils.data import DataLoader | |
| from torch.optim.lr_scheduler import ReduceLROnPlateau | |
| from dataLoder.loader_S2 import TrainDataLoader_balance as TrainDataLoader | |
| from dataLoder.loader_S2 import TestDataLoader | |
| from utiles import save_model, get_learning_rate, calculate_classification_metrics, move_tensor_to_device, AverageMeter | |
| from survivalstandalone.losses import cox_ph_loss | |
| 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, | |
| 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=config.use_cuda | |
| ) | |
| 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=config.n_threads, | |
| pin_memory=config.use_cuda | |
| ) | |
| 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=config.n_threads, | |
| pin_memory=config.use_cuda | |
| ) | |
| 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): | |
| images, labels, times, events = data | |
| images = images.view(images.size(0) * images.size(1), images.size(2), images.size(3), images.size(4), images.size(5)) | |
| labels = labels.view(-1) | |
| times = times.view(-1) | |
| events = events.view(-1) | |
| images = move_tensor_to_device(images, use_gpu=config.use_cuda) | |
| labels = move_tensor_to_device(labels, use_gpu=config.use_cuda) | |
| times = move_tensor_to_device(times, use_gpu=config.use_cuda) | |
| events = move_tensor_to_device(events, use_gpu=config.use_cuda) | |
| return images, labels, times, events | |
| def train(fold, pkl_paths): | |
| """ | |
| 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. | |
| """ | |
| # 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] | |
| ) | |
| # Move model to GPU if available | |
| if config.use_cuda: | |
| model.cuda() | |
| 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 | |
| # 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 | |
| scaler = GradScaler() | |
| save_name = getattr(model, 'name', 'UFE_UCFC') | |
| save_path = os.path.join(config.data_dir, 'results', 'UFE_UCFC', f'Fold_{fold}') | |
| if not os.path.exists(save_path): | |
| os.makedirs(save_path, exist_ok=True) | |
| # Check if 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_s2 and df_existing['epoch'].max() >= config.epochs_s2 - 1: | |
| print(f"🎉 Step 2 Fold {fold} is already fully completed ({len(df_existing)}/{config.epochs_s2} epochs). Skipping!") | |
| return | |
| except Exception as e: | |
| print(f"Warning checking fold completion: {e}") | |
| # Resume logic | |
| import glob | |
| checkpoints = glob.glob(os.path.join(save_path, f'checkpoint_fold{fold}_epoch*.pkl')) | |
| if checkpoints: | |
| latest_checkpoint = max(checkpoints, key=lambda x: int(x.split('epoch')[1].split('.pkl')[0])) | |
| print(f"Resuming from checkpoint: {latest_checkpoint}") | |
| checkpoint = torch.load(latest_checkpoint, 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_s2): | |
| print(f"\n{'='*40}") | |
| print(f"🚀 STARTING EPOCH {epoch} (Fold {fold})") | |
| print(f"{'='*40}") | |
| 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 | |
| import psutil | |
| import gc | |
| for batch_idx in range(len(train_loader_1p19q)): | |
| 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 | |
| # Get data for each class | |
| data_1p19q = next(iter_1p19q) | |
| data_IDH = next(iter_IDH) | |
| data_LHG = next(iter_LHG) | |
| # Reshape input data | |
| # Reshape input data | |
| imgs_1p19q, label_1p19q, time_1p19q, event_1p19q = reshape_input_data(data_1p19q) | |
| imgs_IDH, label_IDH, time_IDH, event_IDH = reshape_input_data(data_IDH) | |
| imgs_LHG, label_LHG, time_LHG, event_LHG = reshape_input_data(data_LHG) | |
| # Combine inputs and targets | |
| label_list = [label_1p19q, label_IDH, label_LHG] | |
| combined_input = torch.cat((imgs_1p19q, imgs_IDH, imgs_LHG), dim=0) | |
| combined_times = torch.cat((time_1p19q, time_IDH, time_LHG), dim=0) | |
| combined_events = torch.cat((event_1p19q, event_IDH, event_LHG), dim=0) | |
| condition_1p19q = torch.tensor(0, dtype=torch.long, device=label_1p19q.device).repeat(1, label_1p19q.size(0))[0] | |
| condition_IDH = torch.tensor(1, dtype=torch.long, device=label_IDH.device).repeat(1, label_IDH.size(0))[0] | |
| condition_LHG = torch.tensor(2, dtype=torch.long, device=label_LHG.device).repeat(1, label_LHG.size(0))[0] | |
| condition = torch.cat([condition_1p19q, condition_IDH, condition_LHG], dim=0) | |
| # Forward pass with AMP | |
| with autocast(): | |
| (out_cls_list_UFE, out_cls_labels_UFE, | |
| out_cls_list_UCFC, out_cls_labels_UCFC, risk_scores) = model(combined_input, label_list, condition) | |
| # --- CALCULATE COX LOSS --- | |
| valid_mask = combined_times > 0 | |
| if valid_mask.sum() >= 2: | |
| # Squeeze risk_scores to 1D to match combined_times and combined_events | |
| # Otherwise, diff (N, 1) * event (N) creates an N x N matrix and explodes the loss! | |
| risk_1d = risk_scores[valid_mask].squeeze() | |
| loss_surv = cox_ph_loss(risk_1d, combined_times[valid_mask], combined_events[valid_mask]) | |
| else: | |
| loss_surv = torch.tensor(0.0, device=risk_scores.device, requires_grad=True) | |
| loss_cls_U1 = cross_entropy_loss(out_cls_list_UFE[0], out_cls_labels_UFE[0]) | |
| loss_cls_U2 = cross_entropy_loss(out_cls_list_UFE[1], out_cls_labels_UFE[1]) | |
| loss_cls_U3 = cross_entropy_loss(out_cls_list_UFE[2], out_cls_labels_UFE[2]) | |
| loss_cls_1 = cross_entropy_loss(out_cls_list_UCFC[0], out_cls_labels_UCFC[0]) | |
| loss_cls_2 = cross_entropy_loss(out_cls_list_UCFC[1], out_cls_labels_UCFC[1]) | |
| loss_cls_3 = cross_entropy_loss(out_cls_list_UCFC[2], out_cls_labels_UCFC[2]) | |
| total_loss = loss_cls_U1 + loss_cls_U2 + loss_cls_U3 + loss_cls_1 + loss_cls_2 + loss_cls_3 + (0.5 * loss_surv) | |
| # Backward pass with AMP | |
| optimizer.zero_grad() | |
| scaler.scale(total_loss).backward() | |
| scaler.step(optimizer) | |
| scaler.update() | |
| global_step += 1 | |
| if batch_idx % 10 == 0: | |
| process = psutil.Process(os.getpid()) | |
| mem_gb = process.memory_info().rss / (1024 ** 3) | |
| print(f" [Epoch {epoch}] Batch {batch_idx}/{len(train_loader_1p19q)} | Loss: {total_loss.item():.4f} | RAM: {mem_gb:.2f} GB") | |
| print(f" -> UFE: {loss_cls_U1.item():.2f}, {loss_cls_U2.item():.2f}, {loss_cls_U3.item():.2f} | UCFC: {loss_cls_1.item():.2f}, {loss_cls_2.item():.2f}, {loss_cls_3.item():.2f} | Surv: {loss_surv.item():.2f}") | |
| # Get current learning rate | |
| current_lr = get_learning_rate(optimizer) | |
| print(f'Global_Step {global_step} | Train Epoch: {epoch} | lr {current_lr:.2e} |') | |
| # 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 | |
| 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") | |
| best_model_name = f'best_model_fold{fold}.pkl' | |
| best_model_path = os.path.join(save_path, best_model_name) | |
| import shutil | |
| if os.path.exists(best_path): | |
| shutil.copy(best_path, best_model_path) | |
| # Upload best model to W&B | |
| if wandb.run is not None: | |
| wandb.save(best_model_path) | |
| # Upload best model to Hugging Face | |
| hf_token = os.environ.get("HF_TOKEN") | |
| if hf_token and os.path.exists(best_model_path): | |
| try: | |
| from huggingface_hub import upload_file | |
| upload_file( | |
| path_or_fileobj=best_model_path, | |
| path_in_repo=f"best_models/Fold_{fold}/{best_model_name}", | |
| repo_id="unknownBrain/survivalanalysis_checkpointing", | |
| repo_type="dataset", | |
| token=hf_token, | |
| ) | |
| print(f"☁️ Best model uploaded to Hugging Face: {best_model_name}") | |
| 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 ===== | |
| if epoch % 5 == 0 and epoch > 0: | |
| light_checkpoint_path = os.path.join(save_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}") | |
| # 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 | |
| filename_only = os.path.basename(light_checkpoint_path) | |
| upload_file( | |
| path_or_fileobj=light_checkpoint_path, | |
| path_in_repo=f"checkpoints/{filename_only}", | |
| 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 | |
| gc.collect() | |
| 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 | |
| torch.backends.cudnn.benchmark = False # Disable cuDNN benchmark | |
| torch.backends.cudnn.deterministic = True # Enable deterministic algorithms | |
| # 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): | |
| import glob | |
| import wandb | |
| cfe_pattern = f'results/CFE/Fold_{fold}/CFE_F1_*.pkl' | |
| cfe_files = glob.glob(cfe_pattern) | |
| if not cfe_files: | |
| cfe_files = glob.glob(f'best_models/fixedone/Fold_{fold}/CFE_F1_*.pkl') | |
| if not cfe_files: | |
| cfe_files = glob.glob(f'../results/CFE/Fold_{fold}/CFE_F1_*.pkl') | |
| if not cfe_files: | |
| cfe_files = glob.glob(f'../best_models/fixedone/Fold_{fold}/CFE_F1_*.pkl') | |
| if not cfe_files: | |
| cfe_files = glob.glob(f'../../best_models/fixedone/Fold_{fold}/CFE_F1_*.pkl') | |
| if not cfe_files: | |
| cfe_files = glob.glob(f'../../results/CFE/Fold_{fold}/CFE_F1_*.pkl') | |
| if cfe_files: | |
| latest_cfe = max(cfe_files, key=os.path.getmtime) | |
| print(f"✅ Loading CFE model for Fold {fold}: {latest_cfe}") | |
| else: | |
| print(f"⚠️ No Step 1 (CFE) checkpoint found for Fold {fold}. Step 1 must complete Fold {fold} first. Skipping Fold {fold}.") | |
| continue | |
| model = CMTLNet(in_channels=3, num_classes=2, Arcm=0.5, multi=3) # Initialize the model | |
| model = model.to(config.device if hasattr(config, 'device') else 'cuda') | |
| model_basic_CFE = torch.load(latest_cfe, weights_only=False) | |
| if isinstance(model_basic_CFE, dict): | |
| state_dict = model_basic_CFE.get('model_state_dict', model_basic_CFE) | |
| else: | |
| state_dict = model_basic_CFE.state_dict() | |
| # Strip '_orig_mod.' prefix added by torch.compile() in Step 1 | |
| cleaned_state_dict = {} | |
| for k, v in state_dict.items(): | |
| new_key = k.replace('_orig_mod.', '', 1) | |
| cleaned_state_dict[new_key] = v | |
| missing, unexpected = model.ShareTask.load_state_dict(cleaned_state_dict, strict=False) | |
| if missing: | |
| print(f"⚠️ Missing keys in ShareTask: {len(missing)} keys") | |
| if unexpected: | |
| print(f"⚠️ Unexpected keys in ShareTask: {len(unexpected)} keys") | |
| print(f"✅ ShareTask weights loaded successfully for Fold {fold}") | |
| save_name = getattr(model, 'name', 'UFE_UCFC') | |
| print(f"{save_name}_Fold_{fold}") | |
| # Initialize wandb | |
| wandb.init( | |
| project="CMTLNet-Training", | |
| name=f"Step2-Fold-{fold}", | |
| config={ | |
| 'epochs': config.epochs_s2, | |
| 'batch_size': config.batch_size, | |
| 'learning_rate': config.lr_self, | |
| 'num_workers': config.n_threads, | |
| }, | |
| reinit=True | |
| ) | |
| train(fold, pkl_paths) # Start training | |
| wandb.finish() |