-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathts_model_w_cot_sft.py
More file actions
1829 lines (1549 loc) · 75.1 KB
/
ts_model_w_cot_sft.py
File metadata and controls
1829 lines (1549 loc) · 75.1 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
"""
SFT Training for Qwen3TS with CoT and Tools
Adapted from qwen3_ts_model_w_cot.py for the new Qwen3TS architecture
Uses <ts><ts/> placeholders with processor-based encoding
"""
# --- make the `artist` library package importable via flat module names ---
import os as _os, sys as _sys
_sys.path.insert(0, _os.path.join(_os.path.dirname(_os.path.abspath(__file__)), "artist"))
# ---------------------------------------------------------------------------
import os
import torch
import pytorch_lightning as pl
from pytorch_lightning.callbacks import ModelCheckpoint, EarlyStopping, LearningRateMonitor, Callback
from torch.utils.data import DataLoader
import numpy as np
import json
from typing import List, Dict, Optional
from datetime import datetime
import copy
import re
import random
import json
from datetime import datetime
# Import Qwen3TS components
from bases import MultimodalModel
from transformers import AutoTokenizer
from transformers import AutoModelForCausalLM
from peft import LoraConfig, get_peft_model, TaskType
from peft import PeftModel
# Import existing dataset classes
from multimodal import MultimodalMCQDataset, MultimodalOpenDataset
from utils_general import read_jsonl
from ts_model_w_cot_sft import mask_non_assistant, post_process_conversation, get_first_user_message, extract_ts_segments, merge_consecutive_thinks, merge_consecutive_thinks_new
from qwen_utils import (
extract_answer,
extract_answer_letter,
extract_answer_letter_from_text,
parse_tool_segs,
)
import math
import gc
from transformers import StoppingCriteria, StoppingCriteriaList
class StopOnAny(StoppingCriteria):
def __init__(self, tokenizer, stops, initial_length):
self.tokenizer = tokenizer
self.stops = stops
self.initial_length = initial_length # Length of prompt
def __call__(self, input_ids, scores, **kwargs):
# Only decode tokens generated AFTER the initial prompt
if input_ids.shape[1] <= self.initial_length:
return False
# Decode only the newly generated tokens
new_tokens = input_ids[0, self.initial_length:]
text = self.tokenizer.decode(new_tokens, skip_special_tokens=False)
for stop in self.stops:
if stop in text:
# print(f"STOPPING: Found '{stop}' in generated text")
return True
return False
# Tool definition for Qwen3TS
TOOLS = [{
"type": "function",
"function": {
"name": "timeseries_zoom_in_tool",
"description": "Zoom in on a TS segment [x1, y1].",
"parameters": {
"type": "object",
"properties": {
"ts_seg": {
"type": "array",
"items": {"type": "integer"},
"minItems": 2,
"maxItems": 2
}
},
"required": ["ts_seg"]
}
}
}]
class Qwen3TSDataModule(pl.LightningDataModule):
"""DataModule for Qwen3TS SFT using existing dataset classes"""
def __init__(
self,
train_data_path: str,
val_data_path: Optional[str] = None,
task_type: str = "1TS",
batch_size: int = 4,
num_workers: int = 4,
w_cot: bool = False,
training_stage: str = "mcq",
tokenizer = None,
**dataset_kwargs
):
super().__init__()
self.train_data_path = train_data_path
self.val_data_path = val_data_path
self.task_type = task_type
self.batch_size = batch_size
self.num_workers = num_workers
self.w_cot = w_cot
self.training_stage = training_stage
self.tokenizer = tokenizer
self.dataset_kwargs = dataset_kwargs
def _load_data(self, data_path: str):
"""Load data from JSON/JSONL file"""
return read_jsonl(data_path)
def setup(self, stage: Optional[str] = None):
if stage == "fit" or stage is None:
train_data = self._load_data(self.train_data_path)
# Use MultimodalMCQDataset for MCQ tasks
if self.training_stage == "mcq" or self.training_stage == "reasoning":
self.train_dataset = MultimodalMCQDataset(
train_data,
tokenizer=self.tokenizer,
task_name=self.task_type,
w_cot=self.w_cot,
partition="train",
**self.dataset_kwargs
)
else: # alignment stage
self.train_dataset = MultimodalOpenDataset(
train_data,
tokenizer=self.tokenizer,
task_name=self.task_type,
w_cot=self.w_cot,
partition="train",
**self.dataset_kwargs
)
if self.val_data_path:
val_data = self._load_data(self.val_data_path)
if self.training_stage == "mcq" or self.training_stage == "reasoning":
self.val_dataset = MultimodalMCQDataset(
val_data,
tokenizer=self.tokenizer,
task_name=self.task_type,
w_cot=self.w_cot,
partition="val",
**self.dataset_kwargs
)
else:
self.val_dataset = MultimodalOpenDataset(
val_data,
tokenizer=self.tokenizer,
task_name=self.task_type,
w_cot=self.w_cot,
partition="val",
**self.dataset_kwargs
)
else:
self.val_dataset = None
def train_dataloader(self):
return DataLoader(
self.train_dataset,
batch_size=self.batch_size,
shuffle=True,
num_workers=self.num_workers,
collate_fn=self._simple_collate
)
def val_dataloader(self):
if self.val_dataset is None:
return None
return DataLoader(
self.val_dataset,
batch_size=self.batch_size,
shuffle=False,
num_workers=self.num_workers,
collate_fn=self._simple_collate
)
def _simple_collate(self, batch):
"""Simple collate that preserves the structure from MultimodalMCQDataset"""
# Batch is a list of dicts with keys: context, ts, label, cot_in_format, etc.
collated = {
'context': [item['context'] for item in batch],
'ts': [item['ts'] for item in batch],
'label': [item['label'] for item in batch],
}
# Add cot_in_format if present
if 'cot_in_format' in batch[0]:
collated['cot_in_format'] = [item.get('cot_in_format', None) for item in batch]
return collated
class Qwen3TSLightning(MultimodalModel):
"""Lightning module for Qwen3TS with CoT and tool support"""
def __init__(
self,
model_path: str = "Qwen/Qwen2.5-3B",
ts_config: dict = None,
learning_rate: float = 2e-5,
weight_decay: float = 0.01,
warmup_steps: int = 100,
batch_size: int = 4,
w_cot: bool = False,
training_stage: str = "mcq",
task: str = "1TS", # Match CLI's task parameter name
# LoRA parameters
use_lora: bool = False,
lora_r: int = 16,
lora_alpha: int = 32,
lora_dropout: float = 0.1,
lora_target_modules: list = None,
freeze_ts_encoder: bool = False,
lora_weights_path: str = None,
# Additional parameters for CLI compatibility
random_segment_selection: bool = False,
total_ts: bool = False,
regular_sft: bool = False,
eval_passk: bool = False,
num_samples_per_question: int = 1,
passk: str = "1,2,4,8",
max_eval_samples: int = -1,
adapter_type: str = "itformer",
cot_no_tools: bool = False,
**kwargs
):
MultimodalModel.__init__(self, **kwargs)
self.learning_rate = learning_rate
self.weight_decay = weight_decay
self.warmup_steps = warmup_steps
self.batch_size = batch_size
self.w_cot = w_cot
self.training_stage = training_stage
self.task = task # Use 'task' to match CLI
self.freeze_ts_encoder = freeze_ts_encoder
# LoRA settings
self.use_lora = use_lora
self.lora_r = lora_r
self.lora_alpha = lora_alpha
self.lora_dropout = lora_dropout
self.lora_target_modules = lora_target_modules or ["q_proj", "v_proj", "k_proj", "o_proj", "gate_proj", "up_proj", "down_proj"]
# Additional parameters for CLI compatibility
self.random_segment_selection = random_segment_selection
self.total_ts = total_ts
self.regular_sft = regular_sft
self.eval_passk = eval_passk
self.num_samples_per_question = num_samples_per_question
self.passk = passk
self.max_eval_samples = max_eval_samples
self.lora_weights_path = lora_weights_path
self.cot_no_tools = cot_no_tools
# Load tokenizer and processor
print(f"Loading tokenizer from: {model_path}")
self.tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
# self.processor = Qwen3TSProcessor(tokenizer=self.tokenizer)
# Load model
print(f"Loading Qwen3TS model from: {model_path}")
self.model = AutoModelForCausalLM.from_pretrained(
model_path,
trust_remote_code=True,
torch_dtype=torch.bfloat16,
use_safetensors=False
)
# Override TS config if provided
if ts_config:
print(f"Overriding TS config with: {ts_config}")
for key, value in ts_config.items():
setattr(self.model.config.ts, key, value)
# Freeze all parameters first
for param in self.model.parameters():
param.requires_grad = False
# Apply LoRA if requested
if self.use_lora:
self._apply_lora()
# Load LoRA weights if path provided
if self.lora_weights_path:
# Check if it's a .ckpt file (full checkpoint) or a directory (LoRA weights)
if self.lora_weights_path.endswith('.ckpt'):
print(f"Loading full checkpoint from: {self.lora_weights_path}")
checkpoint = torch.load(self.lora_weights_path, map_location='cpu')
self.load_state_dict(checkpoint['state_dict'], strict=False)
print("Loaded full checkpoint successfully")
else:
# It's a LoRA weights directory
if not self.use_lora:
self.use_lora = True
self._apply_lora()
self._load_lora_weights()
# Load custom weights if path provided (and no LoRA weights)
# if self.custom_weights_path and not self.lora_weights_path:
# self._load_custom_weights(self.custom_weights_path)
# Unfreeze TS encoder (always trainable)
if not self.freeze_ts_encoder:
print("TS encoder will be trained")
for param in self.model.ts_encoder.parameters():
param.requires_grad = True
else:
print("TS encoder is frozen")
self.save_hyperparameters()
self._print_trainable_summary()
def _print_trainable_summary(self):
trainable = sum(p.numel() for p in self.model.parameters() if p.requires_grad)
total = sum(p.numel() for p in self.model.parameters())
print("\n=== TRAINABLE PARAMETERS ===")
print(f"Trainable: {trainable:,}")
print(f"Total: {total:,}")
print(f"Percentage: {100 * trainable / total:.2f}%")
if self.use_lora:
lora_params = sum(p.numel() for n, p in self.model.named_parameters()
if 'lora' in n.lower() and p.requires_grad)
print(f"LoRA parameters: {lora_params:,}")
print("=" * 40)
def _apply_lora(self):
"""Apply LoRA to the language model"""
print(f"Applying LoRA with r={self.lora_r}, alpha={self.lora_alpha}")
print(f"Target modules: {self.lora_target_modules}")
lora_config = LoraConfig(
task_type=TaskType.CAUSAL_LM,
r=self.lora_r,
lora_alpha=self.lora_alpha,
lora_dropout=self.lora_dropout,
target_modules=self.lora_target_modules,
bias="none",
)
self.model = get_peft_model(self.model, lora_config)
print(f"LoRA applied successfully")
def save_weights(self, output_dir: str):
"""Save LoRA weights and TS encoder weights"""
os.makedirs(output_dir, exist_ok=True)
if self.use_lora:
# Save LoRA weights
self.model.save_pretrained(output_dir)
print(f"Saved LoRA weights to {output_dir}")
# Get base model (unwrap LoRA if present)
if hasattr(self.model, 'get_base_model'):
base_model = self.model.get_base_model()
else:
base_model = self.model
# Save TS encoder weights
if not self.freeze_ts_encoder:
ts_encoder_path = os.path.join(output_dir, 'ts_encoder.bin')
torch.save(base_model.ts_encoder.state_dict(), ts_encoder_path)
print(f"Saved TS encoder weights to {ts_encoder_path}")
else:
print("TS encoder is frozen, not saving encoder weights")
def _print_trainable_summary(self):
trainable = sum(p.numel() for p in self.model.parameters() if p.requires_grad)
total = sum(p.numel() for p in self.model.parameters())
print("\n=== TRAINABLE PARAMETERS ===")
print(f"Trainable: {trainable:,}")
print(f"Total: {total:,}")
print(f"Percentage: {100 * trainable / total:.2f}%")
print("=" * 40)
def _load_lora_weights(self):
"""Load LoRA weights from saved path"""
if not os.path.exists(self.lora_weights_path):
raise FileNotFoundError(f"LoRA weights path not found: {self.lora_weights_path}")
print(f"Loading LoRA weights from {self.lora_weights_path}")
if isinstance(self.model, PeftModel):
base_model = self.model.get_base_model()
else:
base_model = self.model
peft_model = PeftModel.from_pretrained(base_model, self.lora_weights_path)
self.model = peft_model
# Get the base model for loading additional weights
model_for_loading = self.model.get_base_model() if hasattr(self.model, 'get_base_model') else self.model
# Load TS encoder weights if they exist
ts_encoder_path = os.path.join(self.lora_weights_path, 'ts_encoder.bin')
if os.path.exists(ts_encoder_path):
ts_encoder_weights = torch.load(ts_encoder_path, map_location='cpu')
if hasattr(model_for_loading, 'ts_encoder'):
model_for_loading.ts_encoder.load_state_dict(ts_encoder_weights)
print("Loaded TS encoder weights")
print("LoRA weights loaded successfully")
def _load_custom_weights(self, checkpoint_dir: str):
"""Load custom components (TS encoder) without LoRA"""
if not os.path.exists(checkpoint_dir):
raise FileNotFoundError(f"Custom weights path not found: {checkpoint_dir}")
print(f"Loading custom weights from {checkpoint_dir}")
# For non-LoRA models, use the model directly
model_for_loading = self.model
# Load TS encoder weights if they exist
ts_encoder_path = os.path.join(checkpoint_dir, 'ts_encoder.bin')
if os.path.exists(ts_encoder_path):
ts_encoder_weights = torch.load(ts_encoder_path, map_location='cpu')
if hasattr(model_for_loading, 'ts_encoder'):
model_for_loading.ts_encoder.load_state_dict(ts_encoder_weights)
print(f"Loaded TS encoder weights")
print("Custom weights loaded successfully")
def _detect_trailing_padding(self, segment: torch.Tensor) -> int:
"""
Detect how many consecutive zeros are at the end of the segment (padding).
Args:
segment: [seg_len] time series segment
Returns:
num_padding: Number of trailing zeros (padding length)
"""
seg_len = segment.shape[0]
# Count consecutive zeros from the end
num_padding = 0
for i in range(seg_len - 1, -1, -1):
if segment[i] == 0:
num_padding += 1
else:
break
return num_padding
def _get_instruction_for_stage(self, training_stage: str) -> str:
"""Get instruction text based on training stage and task type"""
if training_stage == "mcq":
if self.task == "ETI":
return "The following is a multiple-choice question. Please select and provide the correct answer from options 'A', 'B', 'C', 'D'. Only return the correct answer letter."
elif self.task == "1TS":
return "The following is a multiple-choice question about time series data. Please select and provide the correct answer from options 'A', 'B', 'C', 'D'. Only return the correct answer letter."
elif self.task == "2TS":
return "The following is a multiple-choice question about two time series. Please select and provide the correct answer from options available. Only return the correct answer letter."
else:
return "The following is a multiple-choice question. Please select and provide the correct answer. Only return the correct answer letter."
elif training_stage == "alignment":
return "You are provided with a time series data and a question about it. Please analyze the time series data and provide a detailed answer to the following question."
elif training_stage == "reasoning":
if self.task == "1TS":
return "Please analyze the time series data step by step, explaining your reasoning, then provide your final answer to the following question."
elif self.task == "2TS":
return "Please analyze the two time series step by step, explaining your reasoning, then provide your final answer to the following question."
else:
return "Please analyze the data step by step, explaining your reasoning, then provide your final answer."
else:
raise ValueError(f"Unknown training_stage: {training_stage}")
def create_prompt(self, context: str, ts_length: int) -> str:
"""Create formatted prompt for Qwen3TS"""
return f"""
You are a time series expert. Analyze ONLY the given time series data and answer the question.
# Output Schema (STRICT)
<think>One–two sentences describing your reasoning and how you came to the answer.</think>
<answer>
[Direct answer ONLY - the first line must be exactly one letter from the set of available options.]
</answer>
# Rules (MANDATORY)
- No text outside <think> and <answer>.
- In <think>, explain your reasoning and reference the time series.
- In <answer>, the first line must be exactly one letter from the set of available options.
# Time Series
### Segment 0: Timesteps [0, {ts_length}]
<ts><ts/>
# Question
{context}
""".strip()
def replace_answer(self, s: str, actual: str) -> str:
"""Replace answer in CoT content"""
pattern = r'<answer>.*?</answer>'
if re.search(pattern, s):
return re.sub(pattern, f'<answer>{actual}</answer>', s, count=1)
else:
return s + f'\n<answer>{actual}</answer>'
def _prepare_ts_segments_for_model(self, ts_tensor: torch.Tensor, ts_segs: List) -> torch.Tensor:
"""
Prepare time series segments with mask channel for model input.
The model expects: [batch_size, max_num_segments, max_seg_len, 2]
where channel 0 = values, channel 1 = mask (1=valid, 0=padding)
Args:
ts_tensor: [batch, full_seq_len] original time series
ts_segs: List of lists with (start, end) tuples per sample
Returns:
ts_for_model: [batch_size, max_num_segments, max_seg_len, 2] with values and mask
"""
# print(f"DEBUG _prepare_ts_segments_for_model:")
# print(f" ts_tensor.shape: {ts_tensor.shape}")
# print(f" len(ts_segs): {len(ts_segs)}")
# print(f" ts_segs: {ts_segs}")
if ts_segs is None or len(ts_segs) == 0:
return None
batch_size = len(ts_segs)
# First pass: collect all segments and find max dimensions
all_batch_segments = []
max_num_segments = 0
max_seg_len = 0
for batch_idx, segments in enumerate(ts_segs):
batch_segments = []
if segments is None or len(segments) == 0:
all_batch_segments.append([])
print("no segments found")
continue
if ts_tensor.dim() == 4:
ts_sample = ts_tensor[batch_idx][0] # [seq_len]
else: # dim == 3
ts_sample = ts_tensor[batch_idx] # [seq_len]
for start, end in segments:
# Extract segment
segment = ts_sample[start:end] # [seg_len]
batch_segments.append(segment)
max_seg_len = max(max_seg_len, segment.shape[0])
max_num_segments = max(max_num_segments, len(batch_segments))
all_batch_segments.append(batch_segments)
if max_num_segments == 0 or max_seg_len == 0:
print("no segments found")
raise ValueError("no segments found")
# Second pass: create padded tensor
# Shape: [batch_size, max_num_segments, max_seg_len, 2]
total_num_segments = sum(len(segs) for segs in all_batch_segments)
ts_for_model = torch.zeros(
total_num_segments,
max_seg_len,
2, # [values, mask]
dtype=ts_tensor[0].dtype,
device=ts_tensor[0].device
)
seg_list_padded = []
mask_list = []
seg_counter = 0
for batch_idx, batch_segments in enumerate(all_batch_segments):
for seg_idx, segment in enumerate(batch_segments):
seg_len = segment.shape[0]
if segment.dim() == 2:
segment = segment.squeeze(-1)
# Pad segment to max_seg_len
if seg_len < max_seg_len:
# Pad with last value
# padding = segment[-1].repeat(max_seg_len - seg_len)
padding = torch.zeros(max_seg_len - seg_len, dtype=ts_tensor[0].dtype, device=ts_tensor[0].device)
padded_segment = torch.cat([segment, padding])
else:
padded_segment = segment
# Create mask (1 for valid, 0 for padding)
# num_padding = self._detect_trailing_padding(padded_segment)
# if num_padding > 0:
# seg_len = seg_len - num_padding
# mask = torch.zeros(max_seg_len, dtype=ts_tensor[0].dtype, device=ts_tensor[0].device)
# mask[:seg_len] = 1.0
if self.task in ["TSQA", "TRQA", "ETI"]:
mask = torch.zeros(max_seg_len, dtype=ts_tensor[0].dtype, device=ts_tensor[0].device)
mask[:seg_len] = 1.0
else: # you just ran rcw wo it, so remember this in the inference
num_padding = self._detect_trailing_padding(padded_segment)
if num_padding > 0:
seg_len = seg_len - num_padding
mask = torch.zeros(max_seg_len, dtype=ts_tensor[0].dtype, device=ts_tensor[0].device)
mask[:seg_len] = 1.0
# Fill in the tensor
ts_for_model[seg_counter, :, 0] = padded_segment # values
ts_for_model[seg_counter, :, 1] = mask # mask
seg_counter += 1
return ts_for_model
def _prepare_ts(self, ts_batch):
"""Prepare time series data for Qwen3TS"""
if self.task == "2TS":
# 2TS: stack each sample's two arrays into [2, seq_len, n_vars]
ts_tensor_pairs = []
for pair in ts_batch:
pair_tensors = []
for t in pair:
ts_tensor = torch.from_numpy(t).float() if isinstance(t, np.ndarray) else torch.tensor(t, dtype=torch.float32)
if ts_tensor.dim() == 1:
ts_tensor = ts_tensor.unsqueeze(-1)
pair_tensors.append(ts_tensor)
ts_tensor_pairs.append(torch.stack(pair_tensors, dim=0))
ts_batch_tensor = torch.stack(ts_tensor_pairs, dim=0).to(self.device)
else:
# 1TS
ts_tensors = []
for t in ts_batch:
ts_tensor = torch.from_numpy(t).float() if isinstance(t, np.ndarray) else torch.tensor(t, dtype=torch.float32)
if ts_tensor.dim() == 1:
ts_tensor = ts_tensor.unsqueeze(-1)
ts_tensors.append(ts_tensor)
ts_batch_tensor = torch.stack(ts_tensors, dim=0).to(self.device)
return ts_batch_tensor
def qwen_preprocess(
self,
sources,
ts_tensor: torch.Tensor,
tokenizer,
partition: str = 'train',
enable_thinking: bool = True,
regular_sft: bool = False,
) -> Dict:
# System message
system_message = {
'role': 'system',
'content':'you are a helpful assistant that can answer questions about time series data.'
}
conversations = []
questions = []
ts_segments_list = []
segs_names_list = []
for i, source in enumerate(sources):
# Build message list
messages = [system_message]
# Extract segments to get accurate count of valid tool calls
if not self.cot_no_tools:
ts_segs, invalid_segments_count, msg_w_tool_idx = extract_ts_segments(source, ts_tensor[i])
else:
ts_segs = [[0, len(ts_tensor[i])]]
invalid_segments_count = 0
msg_w_tool_idx = {}
# Add after-tool messages based on actual valid segments
j = 1 # tool call index starts from 1
for i, msg in enumerate(source):
messages.append(msg)
if not self.cot_no_tools:
if i in msg_w_tool_idx.keys():
content_str = ""
for seg in msg_w_tool_idx[i]:
content_str += f"Segment ({seg[0]},{seg[1]}) of time series: <ts><ts/>\n"
messages.append({
"role": "user",
"content": f"{content_str}Think in the mind first, and then decide whether to call tools one or more times OR provide final answer. "
})
# Process messages
messages = merge_consecutive_thinks(messages)
# Step 2: Extract TS segments if training/validation
if partition != 'test':
ts_segments_list.append(ts_segs)
# Step 3: Extract question for encoding
first_user_message = get_first_user_message(messages)
question = first_user_message.replace("<ts><ts/>", "").strip() #next((m for m in messages if m.get("role") == "user" and TS_PLACEHOLDER in m.get("content", "")), None)
if question:
question_ids = tokenizer.encode(question, add_special_tokens=False)
else:
question_ids = []
questions.append(question_ids)
# Step 4: Normalize messages for Qwen format
# messages = normalize_for_qwen(messages)
# Step 5: Apply chat template
add_generation_prompt = (partition == 'test')
if enable_thinking and not self.cot_no_tools:
conversation = tokenizer.apply_chat_template(
messages,
tokenize=False,
tools=TOOLS,
add_generation_prompt=add_generation_prompt,
enable_thinking=enable_thinking
)
elif regular_sft or self.cot_no_tools:
conversation = tokenizer.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=add_generation_prompt,
enable_thinking=enable_thinking
)
else:
conversation = tokenizer.apply_chat_template(
messages,
tokenize=False,
)
conversation1 = post_process_conversation(conversation)
conversations.append(conversation1)
# Tokenize all conversations
tokenized = tokenizer(
conversations,
return_tensors="pt",
padding="longest",
max_length=tokenizer.model_max_length,
truncation=True,
)
input_ids = tokenized.input_ids
attention_mask = tokenized.attention_mask
# Create labels
targets = input_ids.clone()
targets[attention_mask == 0] = -100 # Mask padding
# Mask non-assistant tokens for training
if partition != 'test':
targets = mask_non_assistant(conversations, tokenizer, targets)
return {
"input_ids": input_ids,
"labels": targets,
"attention_mask": attention_mask,
"ts_segs": ts_segments_list if partition != 'test' else None,
"question_ids": questions,
"invalid_segments_count": invalid_segments_count,
"segs_names": segs_names_list if partition != 'test' else None
}
def prepare_inputs(self, batch, partition='train'):
"""Prepare inputs for Qwen3TS - matches your prepare_inputs style"""
contexts = batch['context']
labels = batch['label']
ts_data = batch['ts']
cot_data = batch.get('cot_in_format', [None] * len(contexts))
# Get instruction based on training stage
instruction = self._get_instruction_for_stage(self.training_stage)
# Format contexts
if self.task == "2TS":
formatted_contexts = [f"Given two time series (original and modified), {x}" for x in contexts]
else:
formatted_contexts = contexts
# Add instruction
formatted_contexts = [instruction + "\n" + x for x in formatted_contexts]
ts_tensor = self._prepare_ts(ts_data)
# Build conversation sources
if self.w_cot:
sources = []
all_timeseries = []
for i, (context, lbl, ts, cot_item) in enumerate(zip(formatted_contexts, labels, ts_data, cot_data)):
all_conv = []
prompt = self.create_prompt(context, ts_tensor[i].shape[0])
all_conv.append({"role": "user", "content": prompt})
# Add CoT if available
if cot_item is not None:
cot_copy = copy.deepcopy(cot_item)
# Fix answer in last message
last_content = cot_copy[-1]['content']
correct_content = self.replace_answer(last_content, lbl)
cot_copy[-1]['content'] = correct_content
all_conv.extend(cot_copy)
sources.append(all_conv)
# all_timeseries.append(ts_np)
else:
sources = []
all_timeseries = []
for context, lbl, ts in zip(formatted_contexts, labels, ts_data):
all_conv = []
# Convert ts to numpy
if isinstance(ts, torch.Tensor):
ts_np = ts.cpu().numpy()
else:
ts_np = np.array(ts, dtype=np.float32)
# Simple format
prompt = f"<ts><ts/>\n{context}"
all_conv.append({"role": "user", "content": prompt})
all_conv.append({"role": "assistant", "content": f"<answer>{lbl}</answer>"})
sources.append(all_conv)
# all_timeseries.append(ts_np)
data_dicts = self.qwen_preprocess(sources, ts_tensor, self.tokenizer, partition=partition, enable_thinking=self.w_cot, regular_sft=self.regular_sft)
input_ids = data_dicts["input_ids"].to(self.device)
attention_mask = data_dicts["attention_mask"].to(self.device)
labels_tensor = data_dicts["labels"].to(self.device)
ts_segs = data_dicts["ts_segs"] # Extract the segments from tool calls
ts_for_model = self._prepare_ts_segments_for_model(ts_tensor, ts_segs)
if ts_for_model is not None:
ts_for_model = ts_for_model.to(self.device)
return input_ids, attention_mask, ts_for_model, labels_tensor
def forward(self, batch, partition='train'):
input_ids, attention_mask, timeseries, labels = self.prepare_inputs(batch, partition)
outputs = self.model(
input_ids=input_ids,
timeseries=timeseries,
attention_mask=attention_mask,
labels=labels
)
return outputs.loss, outputs.logits
def training_step(self, batch, batch_idx):
loss, _ = self.forward(batch, partition='train')
self.log('train/loss', loss, on_step=True, on_epoch=True,
prog_bar=True, batch_size=self.batch_size)
return loss
def validation_step(self, batch, batch_idx):
loss, _ = self.forward(batch, partition='val')
self.log('val/loss', loss, on_step=True, on_epoch=True,
prog_bar=True, batch_size=self.batch_size, sync_dist=True)
return loss
def configure_optimizers(self):
optimizer = torch.optim.AdamW(
filter(lambda p: p.requires_grad, self.model.parameters()),
lr=self.learning_rate,
weight_decay=self.weight_decay
)
scheduler = torch.optim.lr_scheduler.LinearLR(
optimizer,
start_factor=0.1,
total_iters=self.warmup_steps
)
return {
'optimizer': optimizer,
'lr_scheduler': {
'scheduler': scheduler,
'interval': 'step',
'frequency': 1
}
}
def generate(self, context: List[str], label: List[str], ts: List[np.ndarray], cot: List[str] = None, **kwargs):
"""
Tool-aware generation for Qwen3TS that handles embedding injection for tool calls.
Adapted from QwenTS generate method.
"""
device = self.device
tok = self.tokenizer
ts_placeholder_id = tok.encode("<ts><ts/>", add_special_tokens=False)[0]
ts_tensors = self._prepare_ts(ts)
if self.task == "2TS":
formatted_context = [f"Given two time series (original and modified), {x}" for x in context]
else:
formatted_context = context
# Get instruction based on training stage
instruction = self._get_instruction_for_stage(self.training_stage)
formatted_context = [instruction + "\n" + x for x in formatted_context]
# System prompt and tools definition
sys_content = 'you are a helpful assistant that can answer questions about time series data.'
# Generation params
gen_params = {
'max_new_tokens': kwargs.get("gen_tokens", 2048),
'do_sample': True,
'temperature': kwargs.get("temperature", 0.7),
'top_p': kwargs.get("top_p", 1.0),
'eos_token_id': tok.eos_token_id,
'pad_token_id': tok.pad_token_id
}
results = []
# === NON-COT MODE: Simple generation without tools ===
if not self.w_cot:
stopper = StopOnAny(tok, ["</answer>", "<|im_end|>"])
for question_text, gold, ts_tensor in zip(formatted_context, label, ts_tensors):
L = ts_tensor.shape[1]
context_text = self.create_prompt(question_text, L)
# Initialize conversation
initial_messages = [
{"role": "system", "content": sys_content},
{"role": "user", "content": context_text}
]
conv = tok.apply_chat_template(initial_messages, tokenize=False,
add_generation_prompt=True, enable_thinking=False)
initial_tokens = tok(conv, return_tensors="pt", padding=False, truncation=True,
max_length=tok.model_max_length).to(device)
# Prepare timeseries input with full segment
ts_segs = [[0, L]]
ts_for_model = self._prepare_ts_segments_for_model(ts_tensor.unsqueeze(0), [ts_segs])
if ts_for_model is not None:
ts_for_model = ts_for_model.to(device)
input_len = initial_tokens.input_ids.size(1)
# Single generation call
out = self.model.generate(
input_ids=initial_tokens.input_ids,
attention_mask=initial_tokens.attention_mask,
timeseries=ts_for_model,
stopping_criteria=[stopper] if stopper else None,
**gen_params
)
new_tokens = out[0, input_len:]
generated_text = tok.decode(new_tokens, skip_special_tokens=False)
# Extract answer
answer = extract_answer(generated_text)
if answer is None:
answer = extract_answer_letter_from_text(generated_text) or generated_text.strip()
# MCQ post-processing
if self.training_stage == "mcq":
answer = extract_answer_letter(answer)
results.append({
"context": f"<ts><ts/>\n{question_text}",
"result": answer,
"raw_result": generated_text,
"label": gold,
"ts": ts_tensor.cpu().numpy()
})
torch.cuda.empty_cache()
gc.collect()
return results
elif self.cot_no_tools:
stopper = StopOnAny(tok, ["</answer>", "<|im_end|>"], 0)
for question_text, gold, ts_tensor in zip(formatted_context, label, ts_tensors):
L = ts_tensor.shape[0] if ts_tensor.dim() == 1 else ts_tensor.shape[1]
context_text = self.create_prompt(question_text, L)
# Initialize conversation WITHOUT tools but WITH thinking enabled
initial_messages = [
{"role": "system", "content": sys_content},
{"role": "user", "content": context_text}
]
# Apply template WITHOUT tools but WITH thinking enabled
conv = tok.apply_chat_template(
initial_messages,
tokenize=False,
add_generation_prompt=True,
enable_thinking=True # Enable <think> tags
# NOTE: No tools parameter - this is the key difference
)