File size: 14,018 Bytes
ee594f0 | 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 | --- 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
|