-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathgradio_sensor_transformer_app.py
More file actions
4771 lines (3892 loc) · 191 KB
/
Copy pathgradio_sensor_transformer_app.py
File metadata and controls
4771 lines (3892 loc) · 191 KB
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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Enhanced Gradio Interface for Industrial Digital Twin with Residual Boost Training
Complete Residual Boost Training System - Enhanced Gradio Interface
Features:
1. Stage1 (SST) model training - Static Sensor Transformer for baseline predictions
2. Residual extraction - Extract prediction errors from Stage1 model
3. Stage2 residual model training - Train on residuals to correct Stage1 errors
4. Intelligent R² threshold selection - Automatically decide which signals need Stage2
5. Ensemble model generation - Optimal combination of Stage1 and Stage2 predictions
6. Comprehensive visualization - Individual prediction vs actual comparison for all signals
7. CSV export - Save detailed inference results with per-signal R² scores
"""
import os
import torch
import torch.nn as nn
import torch.optim as optim
from torch.cuda.amp import autocast, GradScaler
from typing import Dict, List, Tuple, Any, Optional
os.environ['KMP_DUPLICATE_LIB_OK'] = 'TRUE'
import sys
import warnings
import traceback
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from datetime import datetime
import json
import matplotlib
import platform
import pickle
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
# ============================================================================
# TFT model save function (added at top of file)
def save_tft_model_with_config(
model_name: str,
tft_model: nn.Module,
config: Dict[str, Any],
scalers: Dict[str, StandardScaler],
residual_data_key: str,
residual_info: Dict[str, Any],
history: Dict[str, List[float]]
) -> Tuple[str, str, str]:
"""
Save TFT model, config and scalers
Args:
model_name: TFTModel name
tft_model: Trained TFT model
config: Training config
scalers: Data scalers
residual_data_key: Residual data key
residual_info: Residual data info
history: Training history
Returns:
model_path: Model weight file path
scaler_path: ScalerFile path
inference_config_path: Inference configFile path
"""
model_dir = "saved_models/tft_models"
os.makedirs(model_dir, exist_ok=True)
# 1. Save model weights
model_path = os.path.join(model_dir, f"{model_name}.pth")
torch.save({
'model_state_dict': tft_model.state_dict(),
'model_config': {
'num_targets': tft_model.num_targets,
'num_external_factors': tft_model.num_external_factors,
'd_model': tft_model.d_model,
'use_grouping': tft_model.use_grouping,
'signal_groups': tft_model.signal_groups if hasattr(tft_model, 'signal_groups') else None
},
'training_config': config,
'training_history': history,
'residual_data_key': residual_data_key,
'created_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
}, model_path)
# 2. Save scalers
scaler_path = os.path.join(model_dir, f"{model_name}_scalers.pkl")
with open(scaler_path, 'wb') as f:
pickle.dump(scalers, f)
# 3. Save inference config JSON (most important)
inference_config_path = os.path.join(model_dir, f"{model_name}_inference.json")
inference_config = {
'model_name': model_name,
'model_type': 'ResidualTFT',
'model_path': model_path,
'scaler_path': scaler_path,
# TFT model architecture
'architecture': {
'd_model': config['d_model'],
'nhead': config['nhead'],
'num_encoder_layers': config['num_encoder_layers'],
'num_decoder_layers': config['num_decoder_layers'],
'dropout': config['dropout'],
'use_grouping': config.get('use_grouping', False),
'signal_groups': config.get('signal_groups', None)
},
# Data config
'data_config': {
'encoder_length': config['encoder_length'],
'future_horizon': residual_info['future_horizon'],
'residual_data_key': residual_data_key,
'base_model_name': residual_info['base_model_name'],
'num_targets': len(residual_info['target_signals']),
'num_external_factors': len(residual_info['boundary_signals'])
},
# Signal info
'signals': {
'boundary_signals': residual_info['boundary_signals'],
'target_signals': residual_info['target_signals'],
'residual_signals': residual_info['residual_signals']
},
# Training info
'training_info': {
'epochs_trained': len(history['train_losses']),
'best_val_loss': min(history['val_losses']),
'batch_size': config['batch_size'],
'learning_rate': config['lr']
},
'created_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
}
with open(inference_config_path, 'w', encoding='utf-8') as f:
json.dump(inference_config, f, indent=2, ensure_ascii=False)
print(f"✅ TFTModel saved:")
print(f" 📦 Model weights: {model_path}")
print(f" 📊 Scalers: {scaler_path}")
print(f" 📄 Inference config: {inference_config_path}")
return model_path, scaler_path, inference_config_path
# ============================================================================
# TFT model load function
def load_tft_model_from_config(config_file_path: str, device: torch.device) -> Tuple[str, str]:
"""
Load TFT model from inference config file
Args:
config_file_path: Inference configJSONFile path
device: PyTorch device
Returns:
model_name: Model name
status_msg: Load status message
"""
try:
# Read config
with open(config_file_path, 'r', encoding='utf-8') as f:
config = json.load(f)
model_name = config['model_name']
model_path = config['model_path']
scaler_path = config['scaler_path']
# Check if files exist
if not os.path.exists(model_path):
return None, f"❌ Model file does not exist: {model_path}"
if not os.path.exists(scaler_path):
return None, f"❌ Scaler file does not exist: {scaler_path}"
# Load model
checkpoint = torch.load(model_path, map_location=device, weights_only=False)
model_config = checkpoint['model_config']
# Rebuild TFT model
tft_model = GroupedMultiTargetTFT(
num_targets=model_config['num_targets'],
num_external_factors=model_config['num_external_factors'],
d_model=config['architecture']['d_model'],
nhead=config['architecture']['nhead'],
num_encoder_layers=config['architecture']['num_encoder_layers'],
num_decoder_layers=config['architecture']['num_decoder_layers'],
dropout=config['architecture']['dropout'],
use_grouping=config['architecture'].get('use_grouping', False),
signal_groups=config['architecture'].get('signal_groups', None)
)
tft_model.load_state_dict(checkpoint['model_state_dict'])
tft_model.to(device)
tft_model.eval()
# Load scalers
with open(scaler_path, 'rb') as f:
scalers = pickle.load(f)
# Save to global state
global_state['residual_models'][model_name] = {
'model': tft_model,
'config': config['architecture'],
'history': checkpoint.get('training_history', {'train_losses': [], 'val_losses': []}),
'residual_data_key': config['data_config']['residual_data_key'],
'info': {
'base_model_name': config['data_config']['base_model_name'],
'target_signals': config['signals']['target_signals'],
'boundary_signals': config['signals']['boundary_signals'],
'residual_signals': config['signals']['residual_signals'],
'model_type': 'StaticSensorTransformer', # Inherited from base model
'future_horizon': config['data_config']['future_horizon']
},
'encoder_length': config['data_config']['encoder_length'],
'future_horizon': config['data_config']['future_horizon']
}
global_state['residual_scalers'][model_name] = scalers
# BuildStatus message
status_msg = f"✅ TFT model loaded successfully!\n\n"
status_msg += f"📌 Model name: {model_name}\n"
status_msg += f"📊 Base model: {config['data_config']['base_model_name']}\n"
status_msg += f"🎯 Number of target signals: {config['data_config']['num_targets']}\n"
status_msg += f"📈 Number of boundary signals: {config['data_config']['num_external_factors']}\n"
status_msg += f"📏 Historical window length: {config['data_config']['encoder_length']}\n"
status_msg += f"🔮 Future prediction horizon: {config['data_config']['future_horizon']}\n"
status_msg += f"⚙️ Model dimensions: {config['architecture']['d_model']}\n"
status_msg += f"🕒 Created at: {config['created_time']}\n"
if 'training_info' in config:
ti = config['training_info']
status_msg += f"\n📚 Training info:\n"
status_msg += f" - Training epochs: {ti['epochs_trained']}\n"
status_msg += f" - Best validation loss: {ti['best_val_loss']:.6f}\n"
status_msg += f" - Batch size: {ti['batch_size']}\n"
status_msg += f" - Learning rate: {ti['learning_rate']}\n"
print(status_msg)
return model_name, status_msg
except Exception as e:
error_msg = f"❌ TFT model loading failed:\n{str(e)}\n\n{traceback.format_exc()}"
print(error_msg)
return None, error_msg
# ============================================================================
# Configure Chinese font
def configure_chinese_font():
"""Configure matplotlib for Chinese font display"""
import matplotlib
import platform
system = platform.system()
if system == 'Darwin': # macOS
matplotlib.rc('font', family='Arial Unicode MS')
elif system == 'Windows':
matplotlib.rc('font', family='SimHei')
else: # Linux
matplotlib.rc('font', family='DejaVu Sans')
matplotlib.rcParams['axes.unicode_minus'] = False
sns.set_style("whitegrid")
# ============================================================================
# Import modules
try:
import gradio as gr
print("✅ Gradio import successful")
except ImportError:
print("❌ Please install gradio: pip install gradio")
sys.exit(1)
# Trying to import local modules
try:
from models.static_transformer import StaticSensorTransformer
from models.residual_tft import (
GroupedMultiTargetTFT,
ResidualExtractor,
train_residual_tft,
prepare_residual_sequence_data,
compute_r2_safe,
compute_residuals_correctly,
batch_inference,
inference_with_boosting,
compute_per_signal_metrics,
clear_gpu_memory,
print_gpu_memory
)
from models.utils import apply_ifd_smoothing
print("✅ Local modules imported successfully")
except ImportError as e:
print(f"⚠️ Local modules import failed: {e}")
print("Trying to use relative imports...")
try:
from static_transformer import StaticSensorTransformer
from residual_tft import (
GroupedMultiTargetTFT,
ResidualExtractor,
train_residual_tft,
prepare_residual_sequence_data,
compute_r2_safe,
compute_residuals_correctly,
batch_inference,
inference_with_boosting,
compute_per_signal_metrics,
clear_gpu_memory,
print_gpu_memory
)
from utils import apply_ifd_smoothing
print("✅ Relative import successful")
except ImportError as e2:
print(f"❌ Relative import also failed: {e2}")
print("Will use inline definitions...")
# Setup device with enhanced GPU detection
def setup_device():
"""Setup computing device with GPU detection and configuration"""
configure_chinese_font()
if torch.cuda.is_available():
device = torch.device('cuda')
print(f"GPU detected successfully: {torch.cuda.get_device_name(0)}")
print(f" CUDA version: {torch.version.cuda}")
print(f" GPU memory: {torch.cuda.get_device_properties(0).total_memory / 1024 ** 3:.1f} GB")
torch.backends.cudnn.benchmark = True
torch.backends.cudnn.deterministic = False
return device
else:
device = torch.device('cpu')
print("GPU not available, using CPU training")
return device
device = setup_device()
def load_saved_models():
"""Load saved models from file system"""
model_dir = "saved_models"
if not os.path.exists(model_dir):
return
print(f"Loading saved models from {model_dir}...")
for filename in os.listdir(model_dir):
if filename.endswith('.pth') and not filename.endswith('_scalers.pkl'):
model_name = filename[:-4]
model_path = os.path.join(model_dir, filename)
scaler_path = os.path.join(model_dir, f"{model_name}_scalers.pkl")
try:
checkpoint = torch.load(model_path, map_location=device, weights_only=False)
model_config = checkpoint['model_config']
if model_config['type'] == 'StaticSensorTransformer':
model = StaticSensorTransformer(
num_boundary_sensors=len(model_config['boundary_signals']),
num_target_sensors=len(model_config['target_signals']),
d_model=model_config['config']['d_model'],
nhead=model_config['config']['nhead'],
num_layers=model_config['config']['num_layers'],
dropout=model_config['config']['dropout']
)
else:
continue
model.load_state_dict(checkpoint['model_state_dict'])
model.to(device)
model.eval()
scalers = {}
if os.path.exists(scaler_path):
with open(scaler_path, 'rb') as f:
scalers = pickle.load(f)
global_state['trained_models'][model_name] = {
'model': model,
'type': model_config['type'],
'boundary_signals': model_config['boundary_signals'],
'target_signals': model_config['target_signals'],
'config': model_config['config'],
'model_path': model_path,
'scaler_path': scaler_path
}
global_state['scalers'][model_name] = scalers
print(f" Loading model: {model_name}")
except Exception as e:
print(f" Model loading failed {model_name}: {e}")
continue
print(f"Model loading complete, loaded {len(global_state['trained_models'])} models")
# Global state management
global_state = {
'df': None,
'trained_models': {},
'scalers': {},
'residual_data': {},
'residual_models': {},
'residual_scalers': {},
'final_predictions': {},
'training_logs': {},
'model_configs': {},
'all_signals': [],
# New: Stage2 Boost model storage
'stage2_models': {}, # Stage2 residual model
'stage2_scalers': {}, # Stage2 Scalers
'ensemble_models': {}, # Ensemble inference model (SST + Stage2)
'sundial_models': {}, # Sundial time series prediction model
# Training control flags
'stop_training_tab2': False, # Flag to stop Tab2 training
'stop_training_tab4': False, # Flag to stop Tab4 training
}
# ============================================================================
# Colab Auto-load Support
# ============================================================================
def autoload_colab_data():
"""
Automatically load pre-defined data from Colab environment
This function checks for pre-saved CSV files and automatically loads them
into global_state, making them immediately available in Tab1.
Supports:
- Standard predefined paths
- Environment variable: COLAB_DATA_PATH
- Wildcard matching in data/ folder
- Google Drive mounted paths
"""
import glob
# Priority 1: Environment variable
env_path = os.environ.get('COLAB_DATA_PATH')
if env_path and os.path.exists(env_path):
preload_paths = [env_path]
else:
# Priority 2: Standard predefined paths
preload_paths = [
'data/colab_preloaded_data.csv',
'data/test_data.csv',
'/content/colab_data.csv',
# Add more common names
'data/leap_data.csv',
'data/sensor_data.csv',
'data/training_data.csv',
# Google Drive paths
'/content/drive/MyDrive/data.csv',
'/content/drive/MyDrive/colab_data.csv',
]
# Priority 3: Wildcard search in data/ folder
if os.path.exists('data'):
csv_files = glob.glob('data/*.csv')
if csv_files:
# Add all CSV files in data/ folder
preload_paths.extend(csv_files)
for preload_path in preload_paths:
if os.path.exists(preload_path):
try:
df_auto = pd.read_csv(preload_path)
# Validate: must have at least 2 columns
if df_auto.shape[1] < 2:
print(f"⚠️ [Colab Auto-load] Skipping {preload_path}: too few columns")
continue
# Validate: must have at least 10 rows
if df_auto.shape[0] < 10:
print(f"⚠️ [Colab Auto-load] Skipping {preload_path}: too few rows")
continue
global_state['df'] = df_auto
global_state['data_loaded'] = True
print("=" * 80)
print("✅✅✅ [Colab Auto-load] Data successfully loaded into Tab1! ✅✅✅")
print(f"📊 Data shape: {df_auto.shape}")
print(f"📋 Columns: {list(df_auto.columns)[:10]}") # Show first 10 columns
if df_auto.shape[1] > 10:
print(f" ... and {df_auto.shape[1] - 10} more columns")
print(f"📁 Source: {preload_path}")
print("=" * 80)
return df_auto
except Exception as e:
print(f"⚠️ [Colab Auto-load] Failed to load {preload_path}: {e}")
continue
return None
# Auto-load disabled - user can manually select files in Tab1
# To enable auto-load, uncomment the line below:
# autoload_colab_data()
load_saved_models()
plt.style.use('default')
sns.set_palette("husl")
print("=" * 80)
print("Industrial Digital Twin with Residual Boost - Enhanced Interface")
print("=" * 80)
print(f"Using device: {device}")
print(f"PyTorch version: {torch.__version__}")
print("=" * 80)
# ============================================================================
# Model loading and inference config management
def save_inference_config(model_name, model_type, model_path, scaler_path,
boundary_signals, target_signals, config_dict):
"""
Save inference config file - for direct model loading for inference later
Args:
model_name: Model name
model_type: Model type
model_path: Model weight file path
scaler_path: ScalerFile path
boundary_signals: Boundary signal list
target_signals: Target signal list
config_dict: Model architecture config
"""
inference_config = {
'model_name': model_name,
'model_type': model_type,
'model_path': model_path,
'scaler_path': scaler_path,
'boundary_signals': boundary_signals,
'target_signals': target_signals,
'architecture': config_dict,
'created_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
}
model_dir = os.path.dirname(model_path)
config_path = os.path.join(model_dir, f"{model_name}_inference.json")
with open(config_path, 'w', encoding='utf-8') as f:
json.dump(inference_config, f, indent=2, ensure_ascii=False)
print(f"✅ Inference configsaved: {config_path}")
return config_path
def load_model_from_inference_config(config_file_path, device):
"""
Load model from inference config file
Args:
config_file_path: Inference configJSONFile path
device: PyTorch device
Returns:
model_name: Model name
success_msg: Success message
"""
try:
with open(config_file_path, 'r', encoding='utf-8') as f:
config = json.load(f)
model_name = config['model_name']
model_type = config['model_type']
model_path = config['model_path']
scaler_path = config['scaler_path']
# Check if files exist
if not os.path.exists(model_path):
return None, f"❌ Model file does not exist: {model_path}"
if not os.path.exists(scaler_path):
return None, f"❌ Scaler file does not exist: {scaler_path}"
# Load model
checkpoint = torch.load(model_path, map_location=device, weights_only=False)
arch = config['architecture']
if model_type == 'StaticSensorTransformer':
model = StaticSensorTransformer(
num_boundary_sensors=len(config['boundary_signals']),
num_target_sensors=len(config['target_signals']),
d_model=arch['d_model'],
nhead=arch['nhead'],
num_layers=arch['num_layers'],
dropout=arch['dropout']
)
else:
return None, f"❌ Unsupported model type: {model_type}"
model.load_state_dict(checkpoint['model_state_dict'])
model.to(device)
model.eval()
# Load scalers
with open(scaler_path, 'rb') as f:
scalers = pickle.load(f)
# Save to global state
global_state['trained_models'][model_name] = {
'model': model,
'type': model_type,
'boundary_signals': config['boundary_signals'],
'target_signals': config['target_signals'],
'config': arch,
'model_path': model_path,
'scaler_path': scaler_path
}
global_state['scalers'][model_name] = scalers
success_msg = f"✅ Model loaded successfully!\n\n"
success_msg += f"📌 Model name: {model_name}\n"
success_msg += f"📊 Model type: {model_type}\n"
success_msg += f"🎯 Number of boundary signals: {len(config['boundary_signals'])}\n"
success_msg += f"📈 Number of target signals: {len(config['target_signals'])}\n"
success_msg += f"⚙️ Model parameters: d_model={arch['d_model']}, nhead={arch['nhead']}, layers={arch['num_layers']}\n"
success_msg += f"🕒 Created at: {config['created_time']}\n"
print(success_msg)
return model_name, success_msg
except Exception as e:
error_msg = f"❌ Model loading failed:\n{str(e)}\n\n{traceback.format_exc()}"
print(error_msg)
return None, error_msg
# ============================================================================
# Stage2 Boost model definition and training functions
def train_stage2_boost_model(
residual_data_key: str,
config: Dict[str, Any],
progress=None
) -> Tuple[str, Dict[str, Any]]:
"""
Train Stage2 Boost residual model
Args:
residual_data_key: Residual data key
config: Training config
progress: Gradio progress object for real-time updates
Returns:
status_msg: Training status message
results: Training result dictionary
"""
try:
if residual_data_key not in global_state['residual_data']:
return "❌ Residual data does not exist!", {}
log_msg = []
log_msg.append("=" * 80)
log_msg.append("🚀 Starting training Stage2 Boost residual model")
log_msg.append("=" * 80)
# Get residual data
residuals_df = global_state['residual_data'][residual_data_key]['data']
residual_info = global_state['residual_data'][residual_data_key]['info']
boundary_signals = residual_info['boundary_signals']
target_signals = residual_info['target_signals']
residual_signals = residual_info['residual_signals']
# Use Stage1's data split ratios (CRITICAL: ensures same test set as Stage1)
data_split_info = residual_info.get('data_split', {})
test_size = data_split_info.get('test_size', config.get('test_size', 0.15))
val_size = data_split_info.get('val_size', config.get('val_size', 0.15))
if 'data_split' in residual_info:
log_msg.append(f"\n✓ Using Stage1's data split ratios (test={test_size:.2f}, val={val_size:.2f})")
else:
log_msg.append(f"\n⚠️ Warning: Stage1 data split info not found, using config values")
log_msg.append(f"\n📊 Data info:")
log_msg.append(f" Residual data: {residual_data_key}")
log_msg.append(f" Number of boundary signals: {len(boundary_signals)}")
log_msg.append(f" Number of target signals: {len(target_signals)}")
log_msg.append(f" Data length: {len(residuals_df)}")
# Prepare training data
X = residuals_df[boundary_signals].values
y_residual = residuals_df[residual_signals].values
# Data split (using Stage1's ratios)
train_size = int(len(X) * (1 - test_size - val_size))
val_size_samples = int(len(X) * val_size)
X_train = X[:train_size]
X_val = X[train_size:train_size + val_size_samples]
X_test = X[train_size + val_size_samples:]
y_train = y_residual[:train_size]
y_val = y_residual[train_size:train_size + val_size_samples]
y_test = y_residual[train_size + val_size_samples:]
log_msg.append(f"\n🔀 Data split:")
log_msg.append(f" Training set: {len(X_train)} ({len(X_train) / len(X) * 100:.1f}%)")
log_msg.append(f" Validation set: {len(X_val)} ({len(X_val) / len(X) * 100:.1f}%)")
log_msg.append(f" Test set: {len(X_test)} ({len(X_test) / len(X) * 100:.1f}%)")
# Data standardization
scaler_X = StandardScaler()
scaler_y = StandardScaler()
X_train_scaled = scaler_X.fit_transform(X_train)
X_val_scaled = scaler_X.transform(X_val)
X_test_scaled = scaler_X.transform(X_test)
y_train_scaled = scaler_y.fit_transform(y_train)
y_val_scaled = scaler_y.transform(y_val)
y_test_scaled = scaler_y.transform(y_test)
# Create DataLoader
train_dataset = torch.utils.data.TensorDataset(
torch.FloatTensor(X_train_scaled),
torch.FloatTensor(y_train_scaled)
)
val_dataset = torch.utils.data.TensorDataset(
torch.FloatTensor(X_val_scaled),
torch.FloatTensor(y_val_scaled)
)
train_loader = torch.utils.data.DataLoader(
train_dataset,
batch_size=config['batch_size'],
shuffle=True
)
val_loader = torch.utils.data.DataLoader(
val_dataset,
batch_size=config['batch_size'],
shuffle=False
)
# Initialize Stage2 model (using SST architecture)
log_msg.append(f"\n🏗️ Initializing Stage2 residual model:")
log_msg.append(f" Architecture: StaticSensorTransformer")
log_msg.append(f" d_model: {config['d_model']}")
log_msg.append(f" nhead: {config['nhead']}")
log_msg.append(f" num_layers: {config['num_layers']}")
stage2_model = StaticSensorTransformer(
num_boundary_sensors=len(boundary_signals),
num_target_sensors=len(target_signals),
d_model=config['d_model'],
nhead=config['nhead'],
num_layers=config['num_layers'],
dropout=config['dropout']
).to(device)
# Optimizer and scheduler
optimizer = torch.optim.AdamW(
stage2_model.parameters(),
lr=config['lr'],
weight_decay=config.get('weight_decay', 1e-5)
)
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(
optimizer,
mode='min',
factor=config.get('scheduler_factor', 0.7),
patience=config.get('scheduler_patience', 15)
)
log_msg.append(f"📊 Learning rate scheduler: ReduceLROnPlateau (factor={config.get('scheduler_factor', 0.7)}, patience={config.get('scheduler_patience', 15)})")
criterion = nn.MSELoss()
# Mixed precision training
scaler = GradScaler()
# Training loop
log_msg.append(f"\n🎯 Starting training (mixed precision, total epochs: {config['epochs']})")
history = {
'train_losses': [],
'val_losses': [],
'train_r2': [],
'val_r2': [],
'train_mae': [],
'val_mae': []
}
best_val_loss = float('inf')
patience_counter = 0
early_stop_patience = config.get('early_stop_patience', 25)
for epoch in range(config['epochs']):
# Training phase with mixed precision
stage2_model.train()
train_loss = 0.0
train_preds = []
train_targets = []
for batch_X, batch_y in train_loader:
batch_X, batch_y = batch_X.to(device), batch_y.to(device)
optimizer.zero_grad()
# Mixed precision forward pass
with autocast():
outputs = stage2_model(batch_X)
loss = criterion(outputs, batch_y)
# Mixed precision backward pass
scaler.scale(loss).backward()
scaler.unscale_(optimizer)
# Gradient clipping
if config.get('grad_clip', 0) > 0:
torch.nn.utils.clip_grad_norm_(stage2_model.parameters(), config['grad_clip'])
scaler.step(optimizer)
scaler.update()
train_loss += loss.item()
train_preds.append(outputs.detach().cpu().numpy())
train_targets.append(batch_y.detach().cpu().numpy())
train_loss /= len(train_loader)
train_preds = np.vstack(train_preds)
train_targets = np.vstack(train_targets)
train_r2, _ = compute_r2_safe(train_targets, train_preds, method='per_output_mean')
train_mae = mean_absolute_error(train_targets, train_preds)
# Validation phase with mixed precision
stage2_model.eval()
val_loss = 0.0
val_preds = []
val_targets = []
with torch.no_grad():
for batch_X, batch_y in val_loader:
batch_X, batch_y = batch_X.to(device), batch_y.to(device)
with autocast():
outputs = stage2_model(batch_X)
loss = criterion(outputs, batch_y)
val_loss += loss.item()
val_preds.append(outputs.cpu().numpy())
val_targets.append(batch_y.cpu().numpy())
val_loss /= len(val_loader)
val_preds = np.vstack(val_preds)
val_targets = np.vstack(val_targets)
val_r2, _ = compute_r2_safe(val_targets, val_preds, method='per_output_mean')
val_mae = mean_absolute_error(val_targets, val_preds)
# Record history
history['train_losses'].append(train_loss)
history['val_losses'].append(val_loss)
history['train_r2'].append(train_r2)
history['val_r2'].append(val_r2)
history['train_mae'].append(train_mae)
history['val_mae'].append(val_mae)
# Learning rate scheduling
scheduler.step(val_loss)
# Early stopping check
if val_loss < best_val_loss:
best_val_loss = val_loss
patience_counter = 0
# Save best model
best_model_state = stage2_model.state_dict().copy()
else:
patience_counter += 1
# Progress output (enhanced version)
if (epoch + 1) % max(1, config['epochs'] // 20) == 0 or epoch == 0 or epoch == config['epochs'] - 1:
# Get current learning rate
current_lr = optimizer.param_groups[0]['lr']
# Calculate RMSE
train_rmse = np.sqrt(train_loss)
val_rmse = np.sqrt(val_loss)
msg = f"\nEpoch {epoch + 1}/{config['epochs']}"
msg += f"\n 📉 Train: Loss={train_loss:.4f}, RMSE={train_rmse:.4f}, MAE={train_mae:.4f}, R²={train_r2:.4f}"
msg += f"\n 📊 Val: Loss={val_loss:.4f}, RMSE={val_rmse:.4f}, MAE={val_mae:.4f}, R²={val_r2:.4f}"
msg += f"\n 🎯 Val/Train Ratio: {val_loss/train_loss:.2f}x"
msg += f"\n 📚 LR: {current_lr:.2e}"
log_msg.append(msg)
# Update progress bar with current status
if progress:
progress((epoch + 1) / config['epochs'], desc=f"Epoch {epoch+1}/{config['epochs']} - Val R²: {val_r2:.4f}")
# Early stopping
if patience_counter >= early_stop_patience:
log_msg.append(f"\n⏸️ Early stopping triggered (Epoch {epoch + 1})")
break
# Load best model
stage2_model.load_state_dict(best_model_state)
# Test set evaluation with batch inference
y_test_pred = batch_inference(
stage2_model, X_test, scaler_X, scaler_y, device,
batch_size=config['batch_size'], model_name="Stage2"
)
test_mae = mean_absolute_error(y_test, y_test_pred)
test_rmse = np.sqrt(mean_squared_error(y_test, y_test_pred))
test_r2, _ = compute_r2_safe(y_test, y_test_pred, method='per_output_mean')
# Training history summary
log_msg.append(f"\n📈 Training history summary ({len(history['train_losses'])} epochs):")
log_msg.append(f" Best validation loss: {best_val_loss:.4f} (Epoch {np.argmin(history['val_losses']) + 1})")
log_msg.append(f" Best validation R²: {max(history['val_r2']):.4f} (Epoch {np.argmax(history['val_r2']) + 1})")
log_msg.append(f" Best validation MAE: {min(history['val_mae']):.4f} (Epoch {np.argmin(history['val_mae']) + 1})")
log_msg.append(f" Final training loss: {history['train_losses'][-1]:.4f}")
log_msg.append(f" Final validation loss: {history['val_losses'][-1]:.4f}")
log_msg.append(f"\n📊 Test set performance:")
log_msg.append(f" MAE: {test_mae:.6f}")
log_msg.append(f" RMSE: {test_rmse:.6f}")
log_msg.append(f" R²: {test_r2:.4f}")
# Save model
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
model_name = f"Stage2_Boost_{residual_data_key}_{timestamp}"
model_dir = "saved_models/stage2_boost"
os.makedirs(model_dir, exist_ok=True)
model_path = os.path.join(model_dir, f"{model_name}.pth")
torch.save({
'model_state_dict': stage2_model.state_dict(),
'config': config,
'history': history,
'residual_data_key': residual_data_key,
'boundary_signals': boundary_signals,
'target_signals': target_signals,
'residual_signals': residual_signals,
'test_metrics': {
'mae': test_mae,
'rmse': test_rmse,
'r2': test_r2
}
}, model_path)
# Save scalers
scaler_path = os.path.join(model_dir, f"{model_name}_scalers.pkl")
with open(scaler_path, 'wb') as f:
pickle.dump({'X': scaler_X, 'y': scaler_y}, f)
# Save to global state
global_state['stage2_models'][model_name] = {
'model': stage2_model,
'config': config,
'history': history,
'residual_data_key': residual_data_key,
'boundary_signals': boundary_signals,
'target_signals': target_signals,
'residual_signals': residual_signals,
'model_path': model_path,
'scaler_path': scaler_path,
'test_metrics': {
'mae': test_mae,
'rmse': test_rmse,
'r2': test_r2
}
}
global_state['stage2_scalers'][model_name] = {'X': scaler_X, 'y': scaler_y}
log_msg.append(f"\n✅ Stage2 model training completed and saved:")
log_msg.append(f" Model name: {model_name}")
log_msg.append(f" Model path: {model_path}")
log_msg.append(f" Scaler path: {scaler_path}")
results = {
'model_name': model_name,
'history': history,
'test_metrics': {
'mae': test_mae,
'rmse': test_rmse,
'r2': test_r2
}
}