File size: 5,839 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
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.")