forked from OpenTSLM/OpenTSLM
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcurriculum_learning.py
More file actions
1818 lines (1622 loc) · 72.5 KB
/
Copy pathcurriculum_learning.py
File metadata and controls
1818 lines (1622 loc) · 72.5 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
# SPDX-FileCopyrightText: 2025 Stanford University, ETH Zurich, and the project authors (see CONTRIBUTORS.md)
# SPDX-FileCopyrightText: 2025 This source file is part of the OpenTSLM open-source project.
#
# SPDX-License-Identifier: MIT
import os
import json
import os as _os
import argparse
from typing import List, Optional, Dict, Any, Callable
from opentslm.time_series_datasets.TSQADataset import TSQADataset
from opentslm.time_series_datasets.m4.M4QADataset import M4QADataset
from opentslm.time_series_datasets.sleep.SleepEDFCoTQADataset import SleepEDFCoTQADataset
from opentslm.time_series_datasets.har_cot.HARCoTQADataset import HARCoTQADataset
from opentslm.time_series_datasets.ecg_qa.ECGQACoTQADataset import ECGQACoTQADataset
from opentslm.time_series_datasets.util import (
extend_time_series_to_match_patch_size_and_aggregate,
)
import torch
import torch.distributed as dist
from torch.optim import AdamW
from torch.nn.utils import clip_grad_norm_
from torch.utils.data import ConcatDataset, DataLoader, Dataset
from torch.utils.data.distributed import DistributedSampler
from torch.nn.parallel import DistributedDataParallel as DDP
from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
from torch.distributed.fsdp import (
CPUOffload,
MixedPrecision,
ShardingStrategy,
BackwardPrefetch,
FullStateDictConfig,
StateDictType,
)
from tqdm.auto import tqdm
from transformers import get_linear_schedule_with_warmup
from opentslm.model.encoder.TransformerCNNEncoder import TransformerCNNEncoder
from opentslm.model.llm.OpenTSLMFlamingo import OpenTSLMFlamingo
from opentslm.model.llm.OpenTSLMSP import OpenTSLMSP
from opentslm.model.projector.MLPProjector import MLPProjector
import datetime
from opentslm.logger import get_logger, set_global_verbose
from opentslm.model_config import (
BATCH_SIZE,
EARLY_STOP_PAT,
GRAD_CLIP_NORM,
LR_ENCODER,
LR_PROJECTOR,
NUM_EPOCHS,
PATCH_SIZE,
WARMUP_FRAC,
WEIGHT_DECAY,
)
# Global stage configuration - users can modify this to mix and match stages
CURRICULUM_STAGES = [
"stage1_mcq",
"stage2_captioning",
"stage3_cot",
"stage4_sleep_cot",
"stage5_ecg_cot",
]
class CurriculumTrainer:
"""
Curriculum learning trainer for OpenTSLM models.
Trains models stage by stage with shared training logic.
While this may look like a lot of code, it's actually quite modular.
We simply train either OpenTSLMSP or OpenTSLMFlamingo, both using the same training loop.
We train across different stages:
- stage1_mcq: Trains the model on a time-series MCQ dataset (TSQA)
- stage2_captioning: Trains the model on a time-series captioning dataset (M4 time series captioning)
- stage3_cot: Trains the model on a chain-of-thought reasoning dataset (HAR CoT)
- stage4_sleep_cot: Trains the model on sleep stage classification with chain-of-thought reasoning
- stage5_ecg_cot: Trains the model on ECG QA with chain-of-thought reasoning
Features:
- Automatic loss history tracking saved to loss_history.txt in each stage's checkpoints directory
- Loss history is appended to when resuming training, preserving all previous epochs
- Displays previous loss history when resuming training
If you run this script, you should be able to reproduce our results from the paper.
All datasets are automatically downloaded and processed.
"""
def _sanitize_llm_id(self, llm_id: str) -> str:
"""Sanitize llm_id for use in directory names (e.g., meta-llama/Llama-3.2-1B -> Llama3_2_1B)"""
if not llm_id:
return "unknown_llm"
# Take last part after /, replace . and - with _
name = llm_id.split("/")[-1]
name = name.replace(".", "_").replace("-", "_")
# Optionally, remove duplicate underscores
while "__" in name:
name = name.replace("__", "_")
return name
def __init__(
self,
model_type: str,
device: str = None,
gradient_checkpointing: bool = False,
dist_url: str = "env://",
dist_backend: str = "nccl",
local_rank: int = int(os.environ.get("LOCAL_RANK", 0)),
llm_id: str = None,
):
"""
Initialize the curriculum trainer.
Args:
model_type: Either 'OpenTSLMSP' or 'OpenTSLMFlamingo'
device: Device to use for training ('cuda', 'mps', or 'cpu')
gradient_checkpointing: Enable gradient checkpointing
dist_url: URL used to set up distributed training
dist_backend: Distributed backend
local_rank: Local GPU rank
llm_id: LLM model ID (e.g., 'google/medgemma-2b', 'meta-llama/Llama-3.2-1B')
"""
self.model_type = model_type
self.device = device or self._get_device()
if self.device == "mps":
print(
"🚨 Warning: Using MPS, might not be fully compatible with the model. Use CUDA for best results."
)
self.llm_id = llm_id
self.llm_id_safe = self._sanitize_llm_id(llm_id)
# Distributed training parameters
self.gradient_checkpointing = gradient_checkpointing
self.dist_url = dist_url
self.dist_backend = dist_backend
self.local_rank = local_rank
# Initialize distributed training if needed
self.rank = 0
self.world_size = 1
if self._should_use_distributed():
self._init_distributed()
self.model = self._initialize_model()
self.results_dir = os.path.join("results", self.llm_id_safe, self.model_type)
self._create_results_dir()
def _get_device(self) -> str:
"""Get the best available device."""
if torch.cuda.is_available():
return "cuda"
elif torch.backends.mps.is_available():
return "mps"
else:
return "cpu"
def _initialize_model(self):
"""Initialize the specified model type."""
if self.model_type == "OpenTSLMSP":
model = OpenTSLMSP(llm_id=self.llm_id, device=self.device).to(self.device)
elif self.model_type == "OpenTSLMFlamingo":
model = OpenTSLMFlamingo(
cross_attn_every_n_layers=1,
gradient_checkpointing=self.gradient_checkpointing,
llm_id=self.llm_id,
device=self.device,
).to(self.device)
else:
raise ValueError(f"Unknown model type: {self.model_type}")
# Use DDP for multi-GPU training (simpler and than FSDP)
if self.world_size > 1:
model = DDP(
model,
device_ids=[self.local_rank] if torch.cuda.is_available() else None,
)
if self.rank == 0:
print(f"Wrapped {self.model_type} with DDP for distributed training")
return model
def _get_cast_dtype(self, precision: str):
"""Get cast dtype for mixed precision."""
if precision == "bf16":
return torch.bfloat16
elif precision == "fp16":
return torch.float16
else:
return None
def _create_results_dir(self):
"""Create the results directory structure."""
os.makedirs(self.results_dir, exist_ok=True)
# model_dir now includes llm_id_safe
model_dir = self.results_dir
os.makedirs(model_dir, exist_ok=True)
# Create stage directories based on global configuration
for stage in CURRICULUM_STAGES:
stage_dir = os.path.join(model_dir, stage)
os.makedirs(stage_dir, exist_ok=True)
os.makedirs(os.path.join(stage_dir, "checkpoints"), exist_ok=True)
os.makedirs(os.path.join(stage_dir, "results"), exist_ok=True)
def _get_optimizer(
self,
batch_size: int = None,
lr_encoder: float = None,
lr_projector: float = None,
lr_base: float = None,
):
"""Get optimizer for the model with configurable learning rates."""
# Get the underlying model (handles DDP wrapping)
model = self._get_model()
if self.model_type == "OpenTSLMSP":
# Parameter groups with different learning rates for SP
enc_params = list(model.encoder.parameters())
proj_params = list(model.projector.projector.parameters())
# Use provided learning rates or defaults
encoder_lr = lr_encoder if lr_encoder is not None else LR_ENCODER
projector_lr = lr_projector if lr_projector is not None else LR_PROJECTOR
param_groups = [
{"params": enc_params, "lr": encoder_lr, "weight_decay": WEIGHT_DECAY},
{
"params": proj_params,
"lr": projector_lr,
"weight_decay": WEIGHT_DECAY,
},
]
# Add LoRA parameters if enabled
if hasattr(model, "lora_enabled") and model.lora_enabled:
lora_params = model.get_lora_parameters()
if lora_params:
# Use projector LR for LoRA parameters (similar fine-tuning nature)
param_groups.append(
{
"params": lora_params,
"lr": projector_lr,
"weight_decay": WEIGHT_DECAY,
}
)
if self.rank == 0:
print(f"📊 Learning rates for {self.model_type} (with LoRA):")
print(f" Encoder LR: {encoder_lr:.2e}")
print(f" Projector LR: {projector_lr:.2e}")
print(
f" LoRA LR: {projector_lr:.2e} ({len(lora_params)} parameters)"
)
else:
raise RuntimeError(
"LoRA is enabled but no trainable LoRA parameters found. This indicates a LoRA configuration issue."
)
else:
if self.rank == 0:
print(f"📊 Learning rates for {self.model_type}:")
print(f" Encoder LR: {encoder_lr:.2e}")
print(f" Projector LR: {projector_lr:.2e}")
return AdamW(param_groups)
else:
# For Flamingo, use grouped parameters
params_to_optimize = model.named_parameters()
params_to_optimize = list(
filter(
lambda x: x[1].requires_grad
and not getattr(x[1], "exclude_from_optimizer", False),
params_to_optimize,
)
)
# Group parameters for weight decay
params_with_wd, params_without_wd = [], []
for n, p in params_to_optimize:
if "gated_cross_attn" in n:
params_with_wd.append(p)
else:
params_without_wd.append(p)
# Use provided base learning rate or default
base_lr = lr_base if lr_base is not None else 2e-4
if self.rank == 0:
print(f"📊 Learning rate for {self.model_type}:")
print(f" Base LR: {base_lr:.2e}")
return torch.optim.AdamW(
[
{"params": params_with_wd, "weight_decay": 0.1},
{"params": params_without_wd, "weight_decay": 0.0},
],
lr=base_lr,
)
def _merge_data_loaders(
self,
datasets: List[Dataset],
shuffle: bool,
batch_size: int,
patch_size: int,
distribute_data: bool = False,
) -> DataLoader:
"""Create a merged data loader from multiple datasets."""
merged_ds = ConcatDataset(datasets)
# Use distributed sampler if distributed training is enabled
if distribute_data and dist.is_initialized():
sampler = DistributedSampler(
merged_ds, num_replicas=self.world_size, rank=self.rank, shuffle=shuffle
)
return DataLoader(
merged_ds,
sampler=sampler,
batch_size=batch_size,
collate_fn=lambda batch: extend_time_series_to_match_patch_size_and_aggregate(
batch, patch_size=patch_size
),
)
else:
return DataLoader(
merged_ds,
shuffle=shuffle,
batch_size=batch_size,
collate_fn=lambda batch: extend_time_series_to_match_patch_size_and_aggregate(
batch, patch_size=patch_size
),
)
def _save_checkpoint(
self, stage: str, epoch: int, val_loss: float, optimizer, scheduler
):
"""Save model checkpoint for a specific stage."""
checkpoint_dir = os.path.join(self.results_dir, stage, "checkpoints")
# Only save on rank 0 for distributed training
if dist.is_initialized() and self.rank != 0:
return
# Get the underlying model (handles DDP wrapping)
model = self._get_model()
if self.model_type == "OpenTSLMSP":
checkpoint = {
"encoder_state": model.encoder.state_dict(),
"projector_state": model.projector.state_dict(),
"optimizer_state": optimizer.state_dict(),
"scheduler_state": scheduler.state_dict(),
"val_loss": val_loss,
"epoch": epoch,
}
# Add LoRA state to checkpoint
model.save_lora_state_to_checkpoint(checkpoint)
else:
# Handle DDP or single GPU case for OpenTSLMFlamingo
model_state = model.state_dict()
if hasattr(self.model, "module"):
# Remove 'module.' prefix for DDP
model_state = {
k.replace("module.", ""): v for k, v in model_state.items()
}
checkpoint = {
"model_state": model_state,
"optimizer_state": optimizer.state_dict(),
"scheduler_state": scheduler.state_dict(),
"val_loss": val_loss,
"epoch": epoch,
}
checkpoint_path = os.path.join(checkpoint_dir, "best_model.pt")
# Check disk space before saving
if self.rank == 0:
import shutil
total, used, free = shutil.disk_usage(checkpoint_dir)
free_gb = free / (1024**3)
print(f"💾 Disk space: {free_gb:.2f} GB free in {checkpoint_dir}")
# Estimate checkpoint size (rough estimate)
estimated_size_gb = sum(
p.numel() * p.element_size() for p in self._get_model().parameters()
) / (1024**3)
if (
free_gb < estimated_size_gb * 2
): # Need at least 2x the size for safe writing
print(
f"⚠️ Warning: Low disk space. Need ~{estimated_size_gb:.2f} GB, have {free_gb:.2f} GB free"
)
# Try to save with error handling
try:
torch.save(checkpoint, checkpoint_path)
except Exception as e:
if self.rank == 0:
print(f"❌ Failed to save checkpoint: {e}")
print(f" Checkpoint path: {checkpoint_path}")
print(
f" Checkpoint size: {sum(p.numel() * p.element_size() for p in self._get_model().parameters()) / 1024**3:.2f} GB"
)
raise RuntimeError(f"Failed to save checkpoint: {e}")
def _save_loss_history(
self, stage: str, epoch: int, train_loss: float, val_loss: float
):
"""Save loss history to a file for tracking training progress."""
if dist.is_initialized() and self.rank != 0:
return # Only save on rank 0 for distributed training
checkpoint_dir = os.path.join(self.results_dir, stage, "checkpoints")
loss_history_file = os.path.join(checkpoint_dir, "loss_history.txt")
# Ensure the directory exists
os.makedirs(checkpoint_dir, exist_ok=True)
# Create the file with header if it doesn't exist
if not os.path.exists(loss_history_file):
with open(loss_history_file, "w") as f:
f.write("Epoch\tTrain_Loss\tVal_Loss\n")
f.write("-" * 30 + "\n")
# Append the current epoch's losses
with open(loss_history_file, "a") as f:
f.write(f"{epoch}\t{train_loss:.6f}\t{val_loss:.6f}\n")
def _display_loss_history(self, stage: str):
"""Display the loss history for a stage if available."""
if dist.is_initialized() and self.rank != 0:
return # Only display on rank 0 for distributed training
checkpoint_dir = os.path.join(self.results_dir, stage, "checkpoints")
loss_history_file = os.path.join(checkpoint_dir, "loss_history.txt")
if os.path.exists(loss_history_file):
try:
with open(loss_history_file, "r") as f:
lines = f.readlines()
if len(lines) > 2: # More than just header
print(f"📊 Previous loss history for {stage}:")
print(" Epoch\tTrain_Loss\tVal_Loss")
print(" " + "-" * 30)
# Show last 5 epochs (or all if less than 5)
start_idx = max(2, len(lines) - 5) # Skip header lines
for line in lines[start_idx:]:
if line.strip() and not line.startswith("-"):
parts = line.strip().split("\t")
if len(parts) == 3:
epoch, train_loss, val_loss = parts
print(f" {epoch}\t{train_loss}\t{val_loss}")
if len(lines) > 7: # More than 5 epochs
print(f" ... and {len(lines) - 7} more epochs")
print()
except Exception as e:
print(f"⚠️ Could not read loss history: {e}")
def _load_checkpoint(
self, stage: str, optimizer, scheduler, eval_only: bool = False
):
"""Load model checkpoint for a specific stage."""
checkpoint_path = os.path.join(
self.results_dir, stage, "checkpoints", "best_model.pt"
)
if os.path.exists(checkpoint_path):
# Always load checkpoint to CPU first to avoid GPU OOM spikes
checkpoint = torch.load(
checkpoint_path, map_location="cpu", weights_only=False
)
# Get the underlying model (handles DDP wrapping)
model = self._get_model()
if self.model_type == "OpenTSLMSP":
model.encoder.load_state_dict(checkpoint["encoder_state"])
model.projector.load_state_dict(checkpoint["projector_state"])
# Load LoRA state using the OpenTSLMSP method (allow missing for backward compatibility)
try:
model.load_lora_state_from_checkpoint(
checkpoint, allow_missing=True
)
except RuntimeError as e:
if self.rank == 0:
print(f"❌ Failed to load LoRA state from checkpoint: {e}")
raise
# Only load optimizer state when training
if (
not eval_only
and optimizer is not None
and "optimizer_state" in checkpoint
):
optimizer.load_state_dict(checkpoint["optimizer_state"])
else:
# Handle DDP or single GPU case for OpenTSLMFlamingo
model_state = checkpoint["model_state"]
if hasattr(self.model, "module"):
# Add 'module.' prefix for DDP
model_state = {f"module.{k}": v for k, v in model_state.items()}
# Load state dict with strict=False to handle missing keys
try:
missing_keys, unexpected_keys = self.model.load_state_dict(
model_state, strict=False
)
if missing_keys and self.rank == 0:
print(
f"⚠️ Warning: Missing keys when loading checkpoint for {stage}:"
)
for key in missing_keys[:10]: # Show first 10 missing keys
print(f" - {key}")
if len(missing_keys) > 10:
print(f" ... and {len(missing_keys) - 10} more keys")
if unexpected_keys and self.rank == 0:
print(
f"⚠️ Warning: Unexpected keys when loading checkpoint for {stage}:"
)
for key in unexpected_keys[
:10
]: # Show first 10 unexpected keys
print(f" - {key}")
if len(unexpected_keys) > 10:
print(f" ... and {len(unexpected_keys) - 10} more keys")
except Exception as e:
raise RuntimeError(
f"Failed to load model state from checkpoint for {stage}: {e}"
)
# Only load optimizer state when training
if (
not eval_only
and optimizer is not None
and "optimizer_state" in checkpoint
):
optimizer.load_state_dict(checkpoint["optimizer_state"])
# Only load scheduler state when training
if (
not eval_only
and scheduler is not None
and "scheduler_state" in checkpoint
):
scheduler.load_state_dict(checkpoint["scheduler_state"])
return checkpoint.get("epoch", "?"), checkpoint.get(
"val_loss", float("inf")
)
return None, float("inf")
def _load_previous_stage_model(
self, current_stage: str
) -> Optional[Dict[str, Any]]:
"""Load the best model from the previous stage and return its metrics."""
try:
current_idx = CURRICULUM_STAGES.index(current_stage)
if current_idx == 0:
# First stage, no previous model to load
return None
previous_stage = CURRICULUM_STAGES[current_idx - 1]
metrics_file = os.path.join(
self.results_dir, previous_stage, "results", "metrics.json"
)
if not os.path.exists(metrics_file):
# PATCH: If running stage2_captioning and previous stage metrics are missing, skip loading
if current_stage == "stage2_captioning":
if self.rank == 0:
print(
f"⚠️ Skipping previous stage {previous_stage} because metrics file not found: {metrics_file}"
)
return None
raise RuntimeError(
f"Previous stage {previous_stage} metrics file not found: {metrics_file}"
)
# Be robust to malformed JSON (e.g., concurrent writes or concatenated JSON)
try:
with open(metrics_file, "r") as f:
metrics = json.load(f)
except Exception as e:
if self.rank == 0:
print(
f"⚠️ Warning: Could not parse metrics file for {previous_stage} ({metrics_file}): {e}"
)
print(" Proceeding without previous metrics.")
metrics = {}
# Load the model weights from previous stage
checkpoint_path = os.path.join(
self.results_dir, previous_stage, "checkpoints", "best_model.pt"
)
if not os.path.exists(checkpoint_path):
# PATCH: If running stage2_captioning and previous stage checkpoint is missing, skip loading
if current_stage == "stage2_captioning":
if self.rank == 0:
print(
f"⚠️ Skipping previous stage {previous_stage} because checkpoint not found: {checkpoint_path}"
)
return None
raise RuntimeError(
f"Previous stage {previous_stage} checkpoint not found: {checkpoint_path}"
)
print(
"Loading checkpoint from previous stage: ",
checkpoint_path,
"and model type: ",
self.model_type,
"and llm_id: ",
self.llm_id,
)
print("This might take a while")
checkpoint = torch.load(
checkpoint_path, map_location="cpu", weights_only=False
)
# Get the underlying model (handles DDP wrapping)
model = self._get_model()
if self.model_type == "OpenTSLMSP":
model.encoder.load_state_dict(checkpoint["encoder_state"])
model.projector.load_state_dict(checkpoint["projector_state"])
# Load LoRA state from previous stage (allow missing for stage transitions)
try:
loaded_count = model.load_lora_state_from_checkpoint(
checkpoint, allow_missing=True
)
if loaded_count > 0 and self.rank == 0:
print(
f"📥 Loaded LoRA adapters from previous stage: {loaded_count} parameters"
)
except RuntimeError as e:
if self.rank == 0:
print(f"❌ Failed to load LoRA state from previous stage: {e}")
# For previous stage loading, we can be more tolerant of LoRA mismatches
# as stages might have different LoRA configurations
else:
# Handle OpenTSLMFlamingo with graceful loading
model_state = checkpoint["model_state"]
if hasattr(self.model, "module"):
# Add 'module.' prefix for DDP
model_state = {f"module.{k}": v for k, v in model_state.items()}
# Load state dict with strict=False to handle missing keys
try:
missing_keys, unexpected_keys = self.model.load_state_dict(
model_state, strict=False
)
if missing_keys and self.rank == 0:
print(
f"⚠️ Warning: Missing keys when loading previous stage {previous_stage}:"
)
for key in missing_keys[:5]: # Show first 5 missing keys
print(f" - {key}")
if len(missing_keys) > 5:
print(f" ... and {len(missing_keys) - 5} more keys")
print(
f" This is normal when transitioning between stages with different model configurations."
)
if unexpected_keys and self.rank == 0:
print(
f"⚠️ Warning: Unexpected keys when loading previous stage {previous_stage}:"
)
for key in unexpected_keys[:5]: # Show first 5 unexpected keys
print(f" - {key}")
if len(unexpected_keys) > 5:
print(f" ... and {len(unexpected_keys) - 5} more keys")
except Exception as e:
raise RuntimeError(
f"Failed to load model state from previous stage {previous_stage}: {e}"
)
return {
"stage": previous_stage,
"metrics": metrics,
"epoch": checkpoint.get("epoch", "?"),
"val_loss": checkpoint.get("val_loss", "?"),
}
except Exception as e:
raise RuntimeError(f"Failed to load previous stage model: {e}")
def _calculate_accuracy(
self, predictions: List[str], gold_answers: List[str]
) -> float:
"""Calculate accuracy for MCQ tasks."""
correct = 0
total = len(predictions)
for pred, gold in zip(predictions, gold_answers):
# Clean up predictions and gold answers
pred_clean = pred.strip()
gold_clean = gold.strip()
# Check if gold starts with the cleaned prediction (more robust matching)
if gold_clean.startswith(pred_clean) or pred_clean == gold_clean:
correct += 1
return correct / total if total > 0 else 0.0
def _evaluate_stage(
self,
stage: str,
test_loader: DataLoader,
stage_name: str,
metric_func: Callable = None,
epoch: int = None,
) -> Dict[str, Any]:
"""Evaluate model on test set for a specific stage."""
# Enable eval mode for all ranks
self.model.eval()
results = []
test_loss = 0.0
# Set higher max_tokens for generation during evaluation
max_new_tokens = 2000
# Prepare per-rank streaming writer for test predictions
results_file_rank = os.path.join(
self.results_dir,
stage_name,
"results",
f"test_predictions_rank_{self.rank if dist.is_initialized() else 0}.jsonl",
)
final_results_file = os.path.join(
self.results_dir, stage_name, "results", "test_predictions.jsonl"
)
results_fp = None
# Ensure directory exists (defensive)
os.makedirs(os.path.dirname(results_file_rank), exist_ok=True)
if self.rank == 0:
print(f"[Eval] rank={self.rank}, world_size={self.world_size}")
print(f"Saving per-rank test predictions to: {results_file_rank}")
if dist.is_initialized():
print(
f"Final merged predictions will be saved to: {final_results_file}"
)
# Open per-rank file in write mode to start fresh, then append per-sample
results_fp = open(results_file_rank, "w", encoding="utf-8")
if not results_fp:
raise RuntimeError(
f"Failed to open per-rank results file: {results_file_rank}"
)
try:
with torch.no_grad():
for batch in tqdm(
test_loader, desc=f"Evaluating {stage_name}", disable=self.rank != 0
):
# Generate predictions with higher max_tokens (skip separate loss computation)
predictions = self._get_model().generate(
batch, max_new_tokens=max_new_tokens
)
# Collect results
for sample, pred in zip(batch, predictions):
result = {
"pre_prompt": sample["pre_prompt"],
"time_series_text": sample["time_series_text"],
"post_prompt": sample["post_prompt"],
"generated": pred,
"gold": sample["answer"],
}
# Add time series ID for stage2 captioning
if stage == "stage2_captioning" and "id" in sample:
result["time_series_id"] = sample["id"]
# Add template_id and ecg_id for stage5_ecg_cot
if stage == "stage5_ecg_cot":
if "template_id" in sample:
result["template_id"] = sample["template_id"]
if "ecg_id" in sample:
result["ecg_id"] = sample["ecg_id"]
if "correct_answer" in sample:
result["correct_answer"] = sample["correct_answer"]
results.append(result)
# Stream write each result immediately to per-rank file
results_fp.write(json.dumps(result, ensure_ascii=False) + "\n")
results_fp.flush()
try:
os.fsync(results_fp.fileno())
except Exception:
pass
finally:
if results_fp is not None:
results_fp.close()
# Synchronize all ranks before merging
if dist.is_initialized():
dist.barrier()
# Rank 0 merges per-rank files into final results file
if (not dist.is_initialized()) or (self.rank == 0):
try:
# Overwrite final file each evaluation
with open(final_results_file, "w", encoding="utf-8") as merged_fp:
if dist.is_initialized():
num_ranks = self.world_size
else:
num_ranks = 1
for r in range(num_ranks):
part_file = os.path.join(
self.results_dir,
stage_name,
"results",
f"test_predictions_rank_{r}.jsonl",
)
if os.path.exists(part_file):
with open(part_file, "r", encoding="utf-8") as pf:
for line in pf:
merged_fp.write(line)
if self.rank == 0:
print(f"Merged per-rank predictions into: {final_results_file}")
finally:
pass
avg_test_loss = float("nan")
# Calculate stage-specific metrics
metrics = {"test_loss": avg_test_loss}
if epoch is not None:
metrics["epoch"] = epoch
if metric_func:
# Compute metrics on rank 0 after merging, else minimal metrics
if (not dist.is_initialized()) or (self.rank == 0):
predictions = []
gold_answers = []
# Read from final merged file
merged_path = final_results_file
with open(merged_path, "r", encoding="utf-8") as f:
for line in f:
try:
obj = json.loads(line)
predictions.append(obj.get("generated", ""))
gold_answers.append(obj.get("gold", ""))
except Exception:
continue
additional_metrics = metric_func(predictions, gold_answers)
metrics.update(additional_metrics)
# Save results only on rank 0 (or when not distributed)
if (not dist.is_initialized()) or (self.rank == 0):
# Save metrics
metrics_file = os.path.join(
self.results_dir, stage_name, "results", "metrics.json"
)
with open(metrics_file, "w") as f:
json.dump(metrics, f, indent=2)
print(f"✅ {stage_name} evaluation complete:")
print(f" Test predictions saved to: {final_results_file}")
print(f" Metrics saved to: {metrics_file}")
print(f" Max tokens used for generation: {max_new_tokens}")
for metric, value in metrics.items():
if isinstance(value, (int, float)):
print(f" {metric}: {value:.4f}")
else:
print(f" {metric}: {value}")
# Signal other ranks that evaluation is complete
if dist.is_initialized():
dist.barrier()
return metrics
def _is_evaluation_completed(self, stage: str) -> bool:
"""Check if evaluation was completed for a stage by looking for test predictions file."""
test_predictions_file = os.path.join(
self.results_dir, stage, "results", "test_predictions.jsonl"
)
metrics_file = os.path.join(self.results_dir, stage, "results", "metrics.json")
# Check if both files exist
if not os.path.exists(test_predictions_file) or not os.path.exists(
metrics_file
):
return False
# Also check if metrics file has evaluation results
try:
with open(metrics_file, "r") as f:
metrics = json.load(f)
return "test_loss" in metrics
except:
return False
def _train_stage(
self,
stage_name: str,
dataset_class,
num_epochs: int,
lr_encoder: float,
lr_projector: float,
lr_base: float,
metric_func: Callable = None,
batch_size: int = None,
eval_only: bool = False,
sampler=None,
) -> Dict[str, Any]:
"""Generic training function for any stage."""
epoch = None
# Use provided batch_size or default to global BATCH_SIZE
if batch_size is None:
batch_size = BATCH_SIZE
if self.rank == 0:
print(f"\n🚀 Starting {stage_name} Training with {self.model_type}")
if eval_only:
print("🔍 EVAL-ONLY MODE: Skipping training, only running evaluation")
print("=" * 60)
print(f"📊 Stage Configuration:")
print(f" Epochs: {num_epochs}")
if self.model_type == "OpenTSLMSP":
print(f" Encoder LR: {lr_encoder:.2e}")
print(f" Projector LR: {lr_projector:.2e}")
else:
print(f" Base LR: {lr_base:.2e}")
print(f" Batch size per GPU: {batch_size}")
if self.world_size > 1:
print(f" Effective batch size: {batch_size * self.world_size}")
print()
# Check if checkpoint exists when in eval_only mode
if eval_only and not self._checkpoint_exists(stage_name):
raise RuntimeError(
f"Eval-only mode requires a checkpoint for {stage_name}, but none found at {os.path.join(self.results_dir, stage_name, 'checkpoints', 'best_model.pt')}"
)
# Load previous stage model and display metrics
try:
previous_stage_info = self._load_previous_stage_model(stage_name)
if previous_stage_info:
if self.rank == 0:
print(f"📂 Loading best model from {previous_stage_info['stage']}:")
print(f" Achieved at epoch: {previous_stage_info['epoch']}")
val_loss = previous_stage_info["val_loss"]
if isinstance(val_loss, (int, float)):
print(f" Validation loss: {val_loss:.4f}")
else:
print(f" Validation loss: {val_loss}")
for metric, value in previous_stage_info["metrics"].items():
if isinstance(value, (int, float)):
print(f" {metric}: {value:.4f}")
else:
print(f" {metric}: {value}")
print()
else:
# Only allow fresh model for first stage
if stage_name != CURRICULUM_STAGES[0]:
raise RuntimeError(
f"Cannot start {stage_name} with fresh model. Previous stage {CURRICULUM_STAGES[CURRICULUM_STAGES.index(stage_name) - 1]} must be completed first."
)
if self.rank == 0:
print("🆕 Starting with fresh model (first stage)")
print()
except Exception as e:
if self.rank == 0:
print(f"❌ Error loading previous stage: {e}")
raise Exception(f"Error loading previous stage: {e}")
# Check if evaluation was already completed
evaluation_completed = self._is_evaluation_completed(stage_name)
if evaluation_completed and self.rank == 0:
print(
f"✅ Evaluation already completed for {stage_name}, skipping training and evaluation"
)
print(f"📂 Loading existing metrics...")
# Load and return existing metrics
metrics_file = os.path.join(
self.results_dir, stage_name, "results", "metrics.json"
)
with open(metrics_file, "r") as f:
metrics = json.load(f)
print(f"📊 Existing results for {stage_name}:")
for metric, value in metrics.items():
if isinstance(value, (int, float)):
print(f" {metric}: {value:.4f}")
else:
print(f" {metric}: {value}")
return metrics
# Enable LoRA if needed for this stage
self._enable_lora_if_needed(stage_name)
# Initialize optimizer and scheduler
optimizer = self._get_optimizer(batch_size, lr_encoder, lr_projector, lr_base)
# Create data loaders
if sampler is not None:
if self.world_size > 1:
get_logger().warning(
"BalancedBatchSampler was provided, but distributed training (DDP) is enabled. BalancedBatchSampler will NOT be used. Data will be sharded using DistributedSampler instead. Typically for stage3_cot it is better to use BalancedBatchSampler, if dataset is imbalanced."
)
train_loader = self._merge_data_loaders(
[
dataset_class(
"train", EOS_TOKEN=self._get_model().get_eos_token()