survivalanalysis_checkpointing / code /fix_step2_part4.py
unknownBrain's picture
Upload all remaining preprocessing, standalone, test and utility files
ee594f0 verified
Raw History Blame Contribute Delete
5.84 kB
import re
import os
with open('Train_CMTLNet_Step2.py', 'r') as f:
code = f.read()
target = """ # 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)
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)"""
replacement = """ # 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="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
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="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 target in code:
code = code.replace(target, replacement)
else:
print("Target 5 not found.")
with open('Train_CMTLNet_Step2.py', 'w') as f:
f.write(code)
print("Part 4 replacements done.")