File size: 4,189 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 | import re
import os
with open('Train_CMTLNet_Step2.py', 'r') as f:
code = f.read()
# Fix 10: Imports
if 'import wandb' not in code:
code = code.replace('import os\n', 'import os\nimport glob\nimport gc\nimport wandb\nfrom torch.cuda.amp import autocast, GradScaler\nfrom huggingface_hub import upload_file\n')
# Fix 5: torch.load with weights_only=False
code = code.replace('torch.load(resume_path)', 'torch.load(resume_path, weights_only=False)')
code = code.replace('torch.load(Base_CEF_model_paths[fold])', 'torch.load(Base_CEF_model_paths[fold], weights_only=False)')
code = code.replace('torch.load(latest_cfe)', 'torch.load(latest_cfe, weights_only=False)')
code = code.replace('torch.load(latest_checkpoint)', 'torch.load(latest_checkpoint, weights_only=False)')
# Fix 1, 6: Update the main loop
old_loop = """ # Perform 5-fold cross-validation training
for fold in range(5):
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
print(f"{save_name}_Fold_{fold}")
train(fold, pkl_paths) # Start training"""
new_loop = """ # 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 = 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}")
# 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()"""
if old_loop in code:
code = code.replace(old_loop, new_loop)
else:
# Try regex if slight formatting difference
pattern = re.compile(r'# Perform 5-fold cross-validation training.*?train\(fold, pkl_paths\).*?# Start training', re.DOTALL)
if pattern.search(code):
code = pattern.sub(new_loop, code)
# Remove the old hardcoded paths block if it exists
old_paths = """ Base_CEF_model_paths = [
'./Fold_0/CFE.pkl',
'./Fold_1/CFE.pkl',
'./Fold_2/CFE.pkl',
'./Fold_3/CFE.pkl',
'./Fold_4/CFE.pkl'
]"""
if old_paths in code:
code = code.replace(old_paths, "")
# Fix Pandas deprecation warning if present
code = code.replace('log_1p19q.append(log_entry_1p19q, ignore_index=True)', 'pd.concat([log_1p19q, log_entry_1p19q.to_frame().T], ignore_index=True)')
code = code.replace('log_IDH.append(log_entry_IDH, ignore_index=True)', 'pd.concat([log_IDH, log_entry_IDH.to_frame().T], ignore_index=True)')
code = code.replace('log_LHG.append(log_entry_LHG, ignore_index=True)', 'pd.concat([log_LHG, log_entry_LHG.to_frame().T], ignore_index=True)')
code = code.replace('log_mean.append(log_entry_mean, ignore_index=True)', 'pd.concat([log_mean, log_entry_mean.to_frame().T], ignore_index=True)')
with open('Train_CMTLNet_Step2.py', 'w') as f:
f.write(code)
print("Initial replacements done.")
|