unknownBrain's picture
Upload all remaining preprocessing, standalone, test and utility files
ee594f0 verified
Raw History Blame Contribute Delete
14 kB
--- Train_CMTLNet_Step2_backup.py 2026-09-22 12:39:24.191187225 +0530
+++ Train_CMTLNet_Step2.py 2026-09-22 12:41:51.246139213 +0530
@@ -1,4 +1,9 @@
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
@@ -289,6 +294,33 @@
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)
+
+ # 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
log_1p19q = pd.DataFrame(columns=[
@@ -324,7 +356,7 @@
iter_IDH = iter(train_loader_IDH)
iter_LHG = iter(train_loader_LHG)
- for epoch in range(config.epochs_s2):
+ for epoch in range(start_epoch, config.epochs_s2):
if epoch == config.save_epoch:
best_score = -1 # Reset best score at a specific epoch
@@ -364,42 +396,38 @@
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 (now receives risk_scores)
- (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 ---
- # Mask out patients who don't have survival data (time == 0)
- valid_mask = combined_times > 0
- if valid_mask.sum() >= 2: # Cox loss needs at least a pair to rank
- loss_surv = cox_ph_loss(risk_scores[valid_mask], combined_times[valid_mask], combined_events[valid_mask])
- else:
- loss_surv = torch.tensor(0.0, device=risk_scores.device, requires_grad=True)
-
- # Classification losses
- 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])
+ # 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:
+ loss_surv = cox_ph_loss(risk_scores[valid_mask], 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 (weighing survival by 0.5 so it doesn't overpower classification)
- total_loss = loss_cls_U1 + loss_cls_U2 + loss_cls_U3 + loss_cls_1 + loss_cls_2 + loss_cls_3 + (0.5 * loss_surv)
+ 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
+ # Backward pass with AMP
optimizer.zero_grad()
- total_loss.backward()
- optimizer.step()
+ scaler.scale(total_loss).backward()
+ scaler.step(optimizer)
+ scaler.update()
# 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(
@@ -439,16 +467,16 @@
log_entry_mean = get_pandas_series(epoch, metrics_train_mean, metrics_test_mean)
# Append logs to DataFrames and save to CSV
- log_1p19q = log_1p19q.append(log_entry_1p19q, ignore_index=True)
+ 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 = log_IDH.append(log_entry_IDH, ignore_index=True)
+ 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 = log_LHG.append(log_entry_LHG, ignore_index=True)
+ 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 = log_mean.append(log_entry_mean, ignore_index=True)
+ 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
@@ -464,6 +492,37 @@
'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="jainamdedhia/cmtlnet-training",
+ 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
@@ -472,6 +531,64 @@
# 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="jainamdedhia/cmtlnet-training",
+ 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__':
@@ -495,19 +612,40 @@
'./LHG.pkl'
]
- Base_CEF_model_paths = [
- './Fold_0/CFE.pkl',
- './Fold_1/CFE.pkl',
- './Fold_2/CFE.pkl',
- './Fold_3/CFE.pkl',
- './Fold_4/CFE.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 cfe_files:
+ latest_cfe = max(cfe_files, key=os.path.getmtime)
+ print(f"✅ Loading CFE model for Fold {fold}: {latest_cfe}")
+ else:
+ raise FileNotFoundError(f"No CFE checkpoint found for Fold {fold} in {cfe_pattern}")
+
model = CMTLNet(in_channels=3, num_classes=2, Arcm=0.5, multi=3) # Initialize the model
- model_basic_CFE = torch.load(Base_CEF_model_paths[fold], weights_only=False)
- model.ShareTask.load_state_dict(model_basic_CFE.state_dict())
- save_name = model.name # Get the model's name
+ model = model.to(config.device if hasattr(config, 'device') else 'cuda')
+ model_basic_CFE = torch.load(latest_cfe, weights_only=False)
+ model.ShareTask.load_state_dict(model_basic_CFE.get('model_state_dict', model_basic_CFE.state_dict()) if isinstance(model_basic_CFE, dict) else model_basic_CFE.state_dict())
+
+ save_name = getattr(model, 'name', 'UFE_UCFC')
print(f"{save_name}_Fold_{fold}")
- train(fold, pkl_paths) # Start training
\ No newline at end of file
+
+ # 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()
\ No newline at end of file