Repository navigation
Expand file tree
/
Copy pathtrain.py
More file actions
2060 lines (1753 loc) · 96.6 KB
/
Copy pathtrain.py
File metadata and controls
2060 lines (1753 loc) · 96.6 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
import torch
import torch.nn.functional as F
import torch.nn as nn
from torch import optim
from torch.cuda.amp import autocast, GradScaler
from tqdm import tqdm
import numpy as np
import argparse
import time
import os
import random
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.manifold import TSNE
from sklearn.decomposition import PCA
from torch.utils.data import DataLoader
from models.TimeCMA import Dual
from utils.metrics import MSE, MAE, metric
from data_provider.data_loader_emb import Dataset_ETT_hour, Dataset_ETT_minute, Dataset_Custom
import faulthandler
faulthandler.enable()
torch.cuda.empty_cache()
torch.cuda.ipc_collect()
os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "max_split_size_mb:150"
# -------------------------------
# Args
# -------------------------------
def parse_args():
p = argparse.ArgumentParser()
p.add_argument("--device", type=str, default="cuda")
p.add_argument("--gpu_id", type=int, default=0, help="GPU device ID to use (default: 0)")
p.add_argument("--root_path", type=str, default="./dataset")
p.add_argument("--data_path", type=str, default="ETTm1")
p.add_argument("--channel", type=int, default=32)
p.add_argument("--num_nodes", type=int, default=7)
p.add_argument("--seq_len", type=int, default=96)
p.add_argument("--pred_len", type=int, default=96)
p.add_argument("--batch_size", type=int, default=128)
p.add_argument("--learning_rate", type=float, default=1e-4)
p.add_argument("--dropout_n", type=float, default=0.2)
p.add_argument("--d_llm", type=int, default=768)
p.add_argument("--e_layer", type=int, default=1)
p.add_argument("--d_layer", type=int, default=1)
p.add_argument("--head", type=int, default=8)
p.add_argument("--weight_decay", type=float, default=1e-3)
p.add_argument("--num_workers", type=int, default=None, help="Number of data loading workers (default: auto-detect based on CPU cores)")
p.add_argument("--model_name", type=str, default="gpt2")
p.add_argument("--epochs", type=int, default=100)
p.add_argument("--seed", type=int, default=42)
p.add_argument("--es_patience", type=int, default=50)
p.add_argument("--save", type=str, default="./logs/" + time.strftime("%Y-%m-%d-%H:%M:%S") + "-")
# 정렬 관련
p.add_argument("--align_weight", type=float, default=0.1, help="weight for cosine alignment loss")
p.add_argument("--align_weight_time", type=float, default=0.3, help = "weight for per-time alignment loss")
p.add_argument("--common_dim", type=int, default=64, help="shared space dimension D")
# 시점별 대조학습 관련 파라미터
p.add_argument("--time_window", type=int, default=3, help="Time window for positive pairs (nearby time steps are treated as positive)")
p.add_argument("--contrastive_temperature", type=float, default=0.07, help="Temperature for contrastive learning")
p.add_argument("--hard_negative_ratio", type=float, default=0.5, help="Ratio of hard negatives in negative sampling")
p.add_argument("--use_contrastive_time", action="store_true", default=False, help="Use contrastive learning for time-wise alignment")
p.add_argument("--print_every", type=int, default=50)
# 성능 최적화 관련 파라미터
p.add_argument("--use_amp", action="store_true", default=True, help="Use Automatic Mixed Precision")
p.add_argument("--gradient_accumulation_steps", type=int, default=1, help="Number of gradient accumulation steps")
p.add_argument("--pin_memory", action="store_true", default=True, help="Pin memory for faster GPU transfer")
p.add_argument("--persistent_workers", action="store_true", default=True, help="Use persistent workers")
p.add_argument("--prefetch_factor", type=int, default=4, help="Prefetch factor for data loading (higher = more prefetching, default: 4)")
p.add_argument("--compile_model", action="store_true", default=False, help="Use torch.compile for model optimization")
p.add_argument("--stride", type=int, default=1, help="Sliding window stride for data sampling")
return p.parse_args()
# -------------------------------
# Utils
# -------------------------------
def seed_it(seed):
random.seed(seed)
np.random.seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.enabled = True
def to_tensor(x):
if torch.is_tensor(x):
return x
return torch.as_tensor(x)
def pad_prompt_embeddings(fps):
"""
fps_list: 각 원소가 [T_i, d_llm, N] 또는 [K, T_i, d_llm, N] (K개 뷰)의 텐서/넘파이
return: [B, T_max, d_llm, N]
"""
# fps: list of [T_i, d_llm, N] (혹은 [K, T_i, d_llm, N]이면 K 평균)
_norm = []
for t in fps:
t = torch.as_tensor(t)
if t.dim() == 4:
# [K, T_i, d_llm, N] -> K 평균 → [T_i, d_llm, N]
t = t.mean(dim=0)
elif t.dim() != 3:
raise ValueError(f"full_prompt_emb must be 3D [T_i, d_llm, N], got {tuple(t.shape)}")
_norm.append(t)
T_max = max(t.size(0) for t in _norm)
d_llm = _norm[0].size(1)
N = _norm[0].size(2)
padded = []
for t in _norm:
Ti = t.size(0)
if Ti < T_max:
last = t[-1:].expand(T_max - Ti, d_llm, N) # 마지막 토큰 복제 패딩
t = torch.cat([t, last], dim=0)
padded.append(t)
return torch.stack(padded, dim=0) # [B, T_max, d_llm, N]
def _norm_last_emb(le):
# le: last_emb sample → [d_llm, N]로 강제
le = torch.as_tensor(le)
if le.is_sparse:
le = le.to_dense()
# 과차원 있다면 앞축 평균
while le.dim() > 2:
le = le.mean(dim=0)
if le.dim() == 1:
# [d_llm]가 들어오면 N=1로 가정(권장하진 않음; 가능하면 Dataset에서 고쳐주세요)
le = le.unsqueeze(-1)
if le.dim() != 2:
raise ValueError(f"last_emb must be 2D [d_llm, N], got {tuple(le.shape)}")
return le # [d_llm, N]
def _norm_anchor(anc):
# anc: anchor_avg sample → [N, d_llm]로 강제
anc = torch.as_tensor(anc)
if anc.dim() == 4:
# [K, N, d_llm] 앞에 뭔가 더 있으면 평균
anc = anc.mean(dim=0)
if anc.dim() == 3:
# [K, N, d_llm] -> K 평균
anc = anc.mean(dim=0)
elif anc.dim() == 2:
pass
else:
raise ValueError(f"anchor_avg bad shape: {tuple(anc.shape)} (need [N,d_llm] or [K,N,d_llm])")
# 혹시 [d_llm, N] 순서면 전치
if anc.size(0) != anc.size(-1) and anc.size(0) != anc.size(1):
# 모양이 확실치 않으면 그대로 두되, 필요시 Dataset에서 고치세요.
pass
# [d_llm, N] → [N, d_llm]
if anc.size(0) != anc.size(1) and anc.size(0) != anc.size(0):
pass
if anc.size(0) != anc.size(1) and anc.size(0) == anc.size(-1):
anc = anc.permute(1, 0) # [d_llm, N] → [N, d_llm]
if anc.size(0) < anc.size(1): # [d_llm, N] 형태일 때
anc = anc.permute(1, 0) # → [N, d_llm]
return anc # [N, d_llm]
def custom_collate(batch):
"""
batch item: (x, y, x_mark, y_mark, last_emb, full_prompt, anchor_avg, num_token_idx)
x: [L, N], last_emb: [d_llm, N] (변형될 수 있으므로 정규화), full_prompt: [T_i, d_llm, N] or [K, T_i, d_llm, N]
anchor_avg: [N, d_llm] or [K, N, d_llm]
- num_token_idx: 파이썬 리스트 (B 길이)로 유지 (각 요소는 [L][N] 구조의 리스트)
"""
xs, ys, xms, yms, lasts, fps, anchors, tokidx = zip(*batch)
x = torch.stack([torch.as_tensor(t) for t in xs], dim=0)
y = torch.stack([torch.as_tensor(t) for t in ys], dim=0)
x_mark = torch.stack([torch.as_tensor(t) for t in xms], dim=0)
y_mark = torch.stack([torch.as_tensor(t) for t in yms], dim=0)
# last_emb: 각 샘플을 [d_llm, N]로 통일 후 [B, d_llm, N]로 stack
last_list = [_norm_last_emb(le) for le in lasts]
# 여기서 모든 샘플이 같은 (d_llm, N)인지 확인
d_llm, N = last_list[0].shape
for t in last_list:
if t.shape != (d_llm, N):
raise ValueError(f"last_emb shapes differ inside batch: {tuple(t.shape)} vs {(d_llm, N)}")
last = torch.stack(last_list, dim=0) # [B, d_llm, N]
# full_prompt: [B, T_max, d_llm, N]
full_prompt = pad_prompt_embeddings(fps)
# anchor_avg: 각 샘플을 [N, d_llm]로 통일 후 [B, N, d_llm]로 stack
anc_list = [_norm_anchor(a) for a in anchors]
N2, d2 = anc_list[0].shape
for t in anc_list:
if t.shape != (N2, d2):
raise ValueError(f"anchor_avg shapes differ inside batch: {tuple(t.shape)} vs {(N2, d2)}")
anchor = torch.stack(anc_list, dim=0) # [B, N, d_llm]
# num_token_idx: list 그대로 (길이 B)
num_token_idx_batch = list(tokidx)
return x, y, x_mark, y_mark, last, full_prompt, anchor, num_token_idx_batch
def load_data(args):
import multiprocessing
data_map = {
'ETTh1': Dataset_ETT_hour,
'ETTh2': Dataset_ETT_hour,
'ETTm1': Dataset_ETT_minute,
'ETTm2': Dataset_ETT_minute
}
data_class = data_map.get(args.data_path, Dataset_Custom)
train_set = data_class(flag='train', scale=True, size=[args.seq_len, 0, args.pred_len], data_path=args.data_path, stride=args.stride)
val_set = data_class(flag='val', scale=True, size=[args.seq_len, 0, args.pred_len], data_path=args.data_path, stride=args.stride)
test_set = data_class(flag='test', scale=True, size=[args.seq_len, 0, args.pred_len], data_path=args.data_path, stride=args.stride)
scaler = train_set.scaler
# num_workers 자동 설정 (기본값이 None인 경우)
if args.num_workers is None:
# CPU 코어 수의 75%를 사용하되, 최소 4개, 최대 16개
cpu_count = multiprocessing.cpu_count()
num_workers = max(4, min(16, int(cpu_count * 0.75)))
print(f"🔧 Auto-detected num_workers: {num_workers} (CPU cores: {cpu_count})")
else:
num_workers = args.num_workers
# 최적화된 DataLoader 설정
dataloader_kwargs = {
'batch_size': args.batch_size,
'shuffle': False,
'drop_last': True,
'num_workers': num_workers,
'collate_fn': custom_collate,
'pin_memory': args.pin_memory if torch.cuda.is_available() else False,
'persistent_workers': args.persistent_workers and num_workers > 0,
'prefetch_factor': args.prefetch_factor if num_workers > 0 else 2
}
print(f"📊 DataLoader settings: num_workers={num_workers}, prefetch_factor={dataloader_kwargs['prefetch_factor']}, pin_memory={dataloader_kwargs['pin_memory']}")
train_loader = DataLoader(train_set, **dataloader_kwargs)
val_loader = DataLoader(val_set, **dataloader_kwargs)
test_loader = DataLoader(test_set, **dataloader_kwargs)
return train_set, val_set, test_set, train_loader, val_loader, test_loader, scaler
def get_first_batch_embeddings(loader, model, device):
model.eval()
with torch.no_grad():
batch = next(iter(loader))
x, _y, x_mark, _y_mark, last_emb, full_prompt_emb, _anchor_avg, _num_token_idx = batch
x = x.to(device); x_mark = x_mark.to(device)
last_emb = last_emb.to(device)
full_prompt_emb = full_prompt_emb.to(device)
enc, pr, cr = model.get_embeddings(x, x_mark, last_emb, full_prompt_emb)
return enc, pr, cr, full_prompt_emb
def time_step_alignment_loss_vectorized(
ts_time_feats, # [B, L, N, C] 시점을 보존한 TS 임베딩
full_prompt, # [B, T_max, d_llm, N] 프롬프트 전체 토큰 임베딩
num_token_idx, # python list: num_token_idx[b][n][t] -> [idx, idx, ...]
ts_head, # TS -> D
txt_head, # LLM -> D
*, detach_text=True, reduce="mean"
):
"""
벡터화된 시점 정렬 손실 계산 - 완전 벡터화 버전 (성능 최적화)
"""
device = ts_time_feats.device
B, L, N, C = ts_time_feats.shape
_, T_max, d_llm, N2 = full_prompt.shape
assert N == N2, f"Channel mismatch: N={N}, full_prompt N={N2}"
# ✅ Step 1: num_token_idx를 텐서로 변환
# 최대 토큰 수 동적 계산 (로직 변화 없이 모든 토큰 포함)
max_tokens = 0
for b in range(B):
for n in range(N):
for t in range(L):
if t < len(num_token_idx[b][n]):
tok_ids = num_token_idx[b][n][t]
if isinstance(tok_ids, list) and len(tok_ids) > 0:
# 평탄화
if isinstance(tok_ids[0], list):
tok_ids = [item for sublist in tok_ids for item in sublist]
# 필터링
valid_ids = [idx for idx in tok_ids
if isinstance(idx, (int, float)) and 0 <= idx < T_max]
max_tokens = max(max_tokens, len(valid_ids))
max_tokens = max(max_tokens, 1) # 최소 1 (빈 텐서 방지)
# 텐서 생성: [B, N, L, max_tokens]
token_idx_tensor = torch.full((B, N, L, max_tokens), -1, dtype=torch.long, device=device)
token_count = torch.zeros((B, N, L), dtype=torch.long, device=device)
# num_token_idx를 텐서로 변환 (한 번만 루프 - 텐서 변환용)
for b in range(B):
for n in range(N):
for t in range(L):
if t < len(num_token_idx[b][n]):
tok_ids = num_token_idx[b][n][t]
if isinstance(tok_ids, list) and len(tok_ids) > 0:
# 평탄화
if isinstance(tok_ids[0], list):
tok_ids = [item for sublist in tok_ids for item in sublist]
# 필터링
valid_ids = [idx for idx in tok_ids
if isinstance(idx, (int, float)) and 0 <= idx < T_max]
if valid_ids:
k = len(valid_ids) # 모든 토큰 사용 (max_tokens로 제한하지 않음)
token_idx_tensor[b, n, t, :k] = torch.tensor(valid_ids[:k], device=device, dtype=torch.long)
token_count[b, n, t] = k
# 유효한 위치가 없으면 0 반환
if token_count.sum() == 0:
return ts_time_feats.new_tensor(0.0)
# ✅ Step 2: full_prompt를 [B, N, T_max, d_llm]로 재구성
if detach_text:
fp_reshaped = full_prompt.detach().permute(0, 3, 1, 2) # [B, N, T_max, d_llm]
else:
fp_reshaped = full_prompt.permute(0, 3, 1, 2) # [B, N, T_max, d_llm]
# ✅ Step 3: 벡터화된 인덱싱으로 토큰 임베딩 추출
# 배치/채널/시간 인덱스 생성
b_idx = torch.arange(B, device=device).unsqueeze(1).unsqueeze(2).unsqueeze(3).expand(-1, N, L, max_tokens)
n_idx = torch.arange(N, device=device).unsqueeze(0).unsqueeze(2).unsqueeze(3).expand(B, -1, L, max_tokens)
# 유효한 토큰 마스크
valid_mask = (token_idx_tensor >= 0) & (token_idx_tensor < T_max) # [B, N, L, max_tokens]
# 토큰 인덱스를 안전하게 클리핑
token_idx_clipped = torch.clamp(token_idx_tensor, 0, T_max - 1)
# 토큰 임베딩 추출: [B, N, L, max_tokens, d_llm]
# advanced indexing 사용
token_embeddings = fp_reshaped[b_idx, n_idx, token_idx_clipped] # [B, N, L, max_tokens, d_llm]
# 마스크 적용 (유효하지 않은 토큰은 0으로)
token_embeddings = token_embeddings * valid_mask.unsqueeze(-1).float() # [B, N, L, max_tokens, d_llm]
# 평균 계산: [B, N, L, d_llm]
token_sum = token_embeddings.sum(dim=3) # [B, N, L, d_llm]
token_count_expanded = token_count.unsqueeze(-1).float() # [B, N, L, 1]
token_avg = token_sum / (token_count_expanded + 1e-8) # [B, N, L, d_llm]
# ✅ Step 4: TS 임베딩을 공통 공간으로 매핑
ts_time = ts_time_feats.reshape(B*L*N, C) # [B*L*N, C]
ts_z_raw = ts_head(ts_time) # [B*L*N, D]
# NaN/Inf 체크
if torch.isnan(ts_z_raw).any() or torch.isinf(ts_z_raw).any():
ts_z_raw = torch.nan_to_num(ts_z_raw, nan=0.0, posinf=1.0, neginf=-1.0)
ts_z_norm = torch.norm(ts_z_raw, dim=-1, keepdim=True)
ts_z = ts_z_raw / (ts_z_norm + 1e-8) # [B*L*N, D]
ts_z_reshaped = ts_z.reshape(B, L, N, -1) # [B, L, N, D]
# ✅ Step 5: 텍스트 임베딩을 공통 공간으로 매핑
# token_avg는 [B, N, L, d_llm] 순서, ts_z_reshaped는 [B, L, N, D] 순서
# 인덱스 매칭을 위해 token_avg를 [B, L, N, d_llm] 순서로 변환
token_avg_reshaped = token_avg.permute(0, 2, 1, 3) # [B, L, N, d_llm]
token_avg_flat = token_avg_reshaped.reshape(B*L*N, d_llm) # [B*L*N, d_llm]
txt_z_raw = txt_head(token_avg_flat) # [B*L*N, D]
# NaN/Inf 체크
if torch.isnan(txt_z_raw).any() or torch.isinf(txt_z_raw).any():
txt_z_raw = torch.nan_to_num(txt_z_raw, nan=0.0, posinf=1.0, neginf=-1.0)
txt_z_norm = torch.norm(txt_z_raw, dim=-1, keepdim=True)
txt_z = txt_z_raw / (txt_z_norm + 1e-8) # [B*L*N, D]
txt_z_reshaped = txt_z.reshape(B, L, N, -1) # [B, L, N, D]
# ✅ Step 6: 유효한 위치만 선택하여 코사인 유사도 계산
# token_count는 [B, N, L] 순서, ts_z_reshaped는 [B, L, N, D] 순서
# 기존 로직: (b*L*N) + (t*N) + n → ts_z_reshaped[b, t, n]
# 따라서 valid_positions도 [B, L, N] 순서로 맞춰야 함
valid_positions = (token_count > 0) # [B, N, L]
valid_positions_reshaped = valid_positions.permute(0, 2, 1) # [B, L, N]로 변환 (b, t, n 순서)
ts_z_valid = ts_z_reshaped[valid_positions_reshaped] # [M, D]
txt_z_valid = txt_z_reshaped[valid_positions_reshaped] # [M, D]
if ts_z_valid.shape[0] == 0:
return ts_time_feats.new_tensor(0.0)
# 코사인 유사도 계산
cos_sim = F.cosine_similarity(ts_z_valid, txt_z_valid, dim=-1) # [M]
# NaN 체크
if torch.isnan(cos_sim).any():
print(f"[WARNING] NaN detected in cosine_similarity, replacing with 0.0")
cos_sim = torch.nan_to_num(cos_sim, nan=0.0)
losses = 1.0 - cos_sim # [M]
# NaN 체크
if torch.isnan(losses).any():
print(f"[WARNING] NaN detected in losses, replacing with 0.0")
losses = torch.nan_to_num(losses, nan=0.0)
result = losses.mean() if reduce == "mean" else losses.sum()
# 최종 NaN 체크
if torch.isnan(result):
print(f"[WARNING] Final result is NaN, returning 0.0")
return ts_time_feats.new_tensor(0.0)
return result
def time_step_alignment_loss_contrastive(
ts_time_feats, # [B, L, N, C] 시점을 보존한 TS 임베딩
full_prompt, # [B, T_max, d_llm, N] 프롬프트 전체 토큰 임베딩
num_token_idx, # python list: num_token_idx[b][n][t] -> [idx, idx, ...]
ts_head, # TS -> D
txt_head, # LLM -> D
*,
detach_text=True,
reduce="mean",
time_window=3,
temperature=0.07,
hard_negative_ratio=0.5
):
"""
시점별 대조학습 기반 정렬 손실
Positive 쌍: 같은 배치, 같은 채널, 같은 시점 (또는 time_window 내 인근 시점)
Negative 쌍: 다른 배치, 다른 채널, 또는 다른 시점
"""
device = ts_time_feats.device
B, L, N, C = ts_time_feats.shape
_, T_max, d_llm, N2 = full_prompt.shape
assert N == N2, f"Channel mismatch: N={N}, full_prompt N={N2}"
# ✅ Step 1: num_token_idx를 텐서로 변환 (기존 로직 재사용)
max_tokens = 0
for b in range(B):
for n in range(N):
for t in range(L):
if t < len(num_token_idx[b][n]):
tok_ids = num_token_idx[b][n][t]
if isinstance(tok_ids, list) and len(tok_ids) > 0:
if isinstance(tok_ids[0], list):
tok_ids = [item for sublist in tok_ids for item in sublist]
valid_ids = [idx for idx in tok_ids
if isinstance(idx, (int, float)) and 0 <= idx < T_max]
max_tokens = max(max_tokens, len(valid_ids))
max_tokens = max(max_tokens, 1)
token_idx_tensor = torch.full((B, N, L, max_tokens), -1, dtype=torch.long, device=device)
token_count = torch.zeros((B, N, L), dtype=torch.long, device=device)
for b in range(B):
for n in range(N):
for t in range(L):
if t < len(num_token_idx[b][n]):
tok_ids = num_token_idx[b][n][t]
if isinstance(tok_ids, list) and len(tok_ids) > 0:
if isinstance(tok_ids[0], list):
tok_ids = [item for sublist in tok_ids for item in sublist]
valid_ids = [idx for idx in tok_ids
if isinstance(idx, (int, float)) and 0 <= idx < T_max]
if valid_ids:
k = len(valid_ids)
token_idx_tensor[b, n, t, :k] = torch.tensor(valid_ids[:k], device=device, dtype=torch.long)
token_count[b, n, t] = k
if token_count.sum() == 0:
return ts_time_feats.new_tensor(0.0)
# ✅ Step 2: 텍스트 토큰 임베딩 추출 및 평균
if detach_text:
fp_reshaped = full_prompt.detach().permute(0, 3, 1, 2) # [B, N, T_max, d_llm]
else:
fp_reshaped = full_prompt.permute(0, 3, 1, 2) # [B, N, T_max, d_llm]
b_idx = torch.arange(B, device=device).unsqueeze(1).unsqueeze(2).unsqueeze(3).expand(-1, N, L, max_tokens)
n_idx = torch.arange(N, device=device).unsqueeze(0).unsqueeze(2).unsqueeze(3).expand(B, -1, L, max_tokens)
valid_mask = (token_idx_tensor >= 0) & (token_idx_tensor < T_max)
token_idx_clipped = torch.clamp(token_idx_tensor, 0, T_max - 1)
token_embeddings = fp_reshaped[b_idx, n_idx, token_idx_clipped] # [B, N, L, max_tokens, d_llm]
token_embeddings = token_embeddings * valid_mask.unsqueeze(-1).float()
token_sum = token_embeddings.sum(dim=3) # [B, N, L, d_llm]
token_count_expanded = token_count.unsqueeze(-1).float()
token_avg = token_sum / (token_count_expanded + 1e-8) # [B, N, L, d_llm]
# ✅ Step 3: TS 및 텍스트 임베딩을 공통 공간으로 매핑
ts_time = ts_time_feats.reshape(B*L*N, C) # [B*L*N, C]
ts_z_raw = ts_head(ts_time)
if torch.isnan(ts_z_raw).any() or torch.isinf(ts_z_raw).any():
ts_z_raw = torch.nan_to_num(ts_z_raw, nan=0.0, posinf=1.0, neginf=-1.0)
ts_z_norm = torch.norm(ts_z_raw, dim=-1, keepdim=True)
ts_z = ts_z_raw / (ts_z_norm + 1e-8) # [B*L*N, D]
ts_z_reshaped = ts_z.reshape(B, L, N, -1) # [B, L, N, D]
token_avg_reshaped = token_avg.permute(0, 2, 1, 3) # [B, L, N, d_llm]
token_avg_flat = token_avg_reshaped.reshape(B*L*N, d_llm)
txt_z_raw = txt_head(token_avg_flat)
if torch.isnan(txt_z_raw).any() or torch.isinf(txt_z_raw).any():
txt_z_raw = torch.nan_to_num(txt_z_raw, nan=0.0, posinf=1.0, neginf=-1.0)
txt_z_norm = torch.norm(txt_z_raw, dim=-1, keepdim=True)
txt_z = txt_z_raw / (txt_z_norm + 1e-8) # [B*L*N, D]
txt_z_reshaped = txt_z.reshape(B, L, N, -1) # [B, L, N, D]
# ✅ Step 4: 유효한 위치만 선택
valid_positions = (token_count > 0) # [B, N, L]
valid_positions_reshaped = valid_positions.permute(0, 2, 1) # [B, L, N]
# 유효한 위치의 인덱스 수집
valid_indices = torch.nonzero(valid_positions_reshaped, as_tuple=False) # [M, 3] (b, t, n)
M = valid_indices.shape[0]
if M == 0:
return ts_time_feats.new_tensor(0.0)
# 유효한 TS 및 텍스트 임베딩 추출
ts_z_valid = ts_z_reshaped[valid_indices[:, 0], valid_indices[:, 1], valid_indices[:, 2]] # [M, D]
txt_z_valid = txt_z_reshaped[valid_indices[:, 0], valid_indices[:, 1], valid_indices[:, 2]] # [M, D]
# ✅ Step 5: Positive/Negative 마스크 생성
# 각 샘플에 대해 (b, t, n) 정보를 사용하여 마스크 생성
batch_ids = valid_indices[:, 0] # [M]
time_ids = valid_indices[:, 1] # [M]
channel_ids = valid_indices[:, 2] # [M]
# Positive 마스크: 같은 배치, 같은 채널, 같은 시점 또는 time_window 내 인근 시점
batch_match = batch_ids.unsqueeze(1) == batch_ids.unsqueeze(0) # [M, M]
channel_match = channel_ids.unsqueeze(1) == channel_ids.unsqueeze(0) # [M, M]
time_diff = torch.abs(time_ids.unsqueeze(1) - time_ids.unsqueeze(0)) # [M, M]
time_match = time_diff <= time_window # [M, M]
positive_mask = batch_match & channel_match & time_match # [M, M]
# 자기 자신은 제외 (대각선 제거)
positive_mask.fill_diagonal_(False)
# Negative 마스크: 다른 배치, 다른 채널, 또는 다른 시점
negative_mask = ~(batch_match & channel_match & time_match) # [M, M]
negative_mask.fill_diagonal_(False) # 자기 자신 제외
# ✅ Step 6: 유사도 행렬 계산
similarity_matrix = torch.matmul(ts_z_valid, txt_z_valid.T) / temperature # [M, M]
# ✅ Step 7: Hard Negative 샘플링 (선택적) - 벡터화 최적화
if hard_negative_ratio > 0 and hard_negative_ratio < 1.0:
# 유사도가 높지만 negative인 샘플들을 hard negative로 선택
hard_negative_scores = similarity_matrix.clone()
hard_negative_scores[positive_mask] = float('-inf')
hard_negative_scores.fill_diagonal_(float('-inf'))
num_hard_negatives = int(M * hard_negative_ratio)
if num_hard_negatives > 0:
# 각 행에 대해 상위 hard negative 선택
k = min(num_hard_negatives, M-1)
_, top_hard_indices = torch.topk(hard_negative_scores, k=k, dim=1) # [M, k]
# Hard negative 마스크 생성 - 벡터화
hard_negative_mask = torch.zeros_like(negative_mask, dtype=torch.bool)
row_indices = torch.arange(M, device=device).unsqueeze(1).expand(-1, k) # [M, k]
hard_negative_mask[row_indices, top_hard_indices] = True
# Hard negative만 사용하도록 negative_mask 업데이트
negative_mask = hard_negative_mask
# ✅ Step 8: InfoNCE 손실 계산 - 벡터화 최적화
# 유사도 행렬을 exp로 변환
exp_sim = torch.exp(similarity_matrix) # [M, M]
# 자기 자신과의 유사도 (대각선)
self_exp = exp_sim.diagonal() # [M]
# Positive 쌍들의 exp 합 (각 행별로)
pos_exp_sum = (exp_sim * positive_mask).sum(dim=1) # [M]
# Negative 쌍들의 exp 합 (각 행별로)
neg_exp_sum = (exp_sim * negative_mask).sum(dim=1) # [M]
# 분자: 자기 자신 + positive 쌍들
numerator = self_exp + pos_exp_sum # [M]
# 분모: 분자 + negative 쌍들
denominator = numerator + neg_exp_sum + 1e-8 # [M]
# InfoNCE 손실: -log(exp(pos) / (exp(pos) + exp(neg)))
losses = -torch.log(numerator / denominator) # [M]
# NaN 체크
if torch.isnan(losses).any():
print(f"[WARNING] NaN detected in contrastive losses, replacing with 0.0")
losses = torch.nan_to_num(losses, nan=0.0)
result = losses.mean() if reduce == "mean" else losses.sum()
if torch.isnan(result):
print(f"[WARNING] Final contrastive result is NaN, returning 0.0")
return ts_time_feats.new_tensor(0.0)
return result
def time_step_alignment_loss(
ts_time_feats, # [B, L, N, C] 시점을 보존한 TS 임베딩 (또는 value_embed(x) 등)
full_prompt, # [B, T_max, d_llm, N] 프롬프트 전체 토큰 임베딩
num_token_idx, # python list: num_token_idx[b][n][t] -> [idx, idx, ...]
ts_head, # TS -> D
txt_head, # LLM -> D
*,
detach_text=True,
reduce="mean",
use_contrastive=True,
time_window=3,
temperature=0.07,
hard_negative_ratio=0.5
):
"""
시점 정렬 손실 - 대조학습 버전 또는 기존 벡터화 버전 선택
"""
if use_contrastive:
return time_step_alignment_loss_contrastive(
ts_time_feats, full_prompt, num_token_idx, ts_head, txt_head,
detach_text=detach_text, reduce=reduce,
time_window=time_window, temperature=temperature, hard_negative_ratio=hard_negative_ratio
)
else:
return time_step_alignment_loss_vectorized(
ts_time_feats, full_prompt, num_token_idx, ts_head, txt_head,
detach_text=detach_text, reduce=reduce
)
# ----------------------------
# Similarity / Heatmap helpers
# -------------------------------
@torch.no_grad()
def visualize_common_space_all_per_channel(
enc_out, cross_out, prompt_last, full_prompt_emb,
ts_head, txt_head,
*,
method="tsne",
token_sample_per_channel=50,
color_map=None, # {"ENC":"#..", "CROSS":"#..", "LAST":"#..", "TOK":"#.."}
save_path="common_space_all.png"
):
"""
- ENC / CROSS / LAST: [B,N,D] → (B*N,D)로 모두 찍음 (배치×채널 개별 포인트)
- TOK: 채널별로 token_sample_per_channel 만큼 샘플링해서 같은 채널 마커로 찍음
- 같은 채널이면 같은 마커, 종류(ENC/CROSS/LAST/TOK)는 색만 다르게
"""
device = next(ts_head.parameters()).device
# ---------- shape normalize ----------
def _enc_bnC(x): # [B,C,N] -> [B,N,C]
if x.dim() == 2: x = x.unsqueeze(0)
return x.contiguous()
def _last_bnE(x): # [B,d_llm,N] -> [B,N,d_llm]
if x.dim() == 2: x = x.unsqueeze(0)
return x.contiguous()
print(enc_out.shape)
print(cross_out.shape)
print(prompt_last.shape)
enc_bnC = _enc_bnC(enc_out).to(device) # [B,N,C]
cross_bnC = (cross_out if cross_out.dim()==3 else cross_out.unsqueeze(0)).to(device) # [B,N,C]
last_bnE = _last_bnE(prompt_last).to(device) # [B,N,E]
B, N, C = enc_bnC.shape
D = ts_head[-1].out_features if hasattr(ts_head[-1], "out_features") else ts_head(enc_bnC[:1]).shape[-1]
# ---------- project to common space ----------
enc_proj = F.normalize(ts_head(enc_bnC), dim=-1) # [B,N,D]
cross_proj = F.normalize(ts_head(cross_bnC), dim=-1) # [B,N,D]
last_proj = F.normalize(txt_head(last_bnE), dim=-1) # [B,N,D]
# ---------- full prompt tokens ----------
if full_prompt_emb.dim() == 3: # [T,E,N] -> [1,T,E,N]
full_prompt_emb = full_prompt_emb.unsqueeze(0)
B_fp, T, E, N_fp = full_prompt_emb.shape
assert N_fp == N, f"N mismatch: full_prompt N={N_fp} vs N={N}"
# [B,N,T,E] - 안전한 permute 처리
if full_prompt_emb.dim() == 4:
fp_bnte = full_prompt_emb.permute(0, 3, 1, 2).contiguous()
else:
print(f"⚠️ Unexpected full_prompt_emb dimensions: {full_prompt_emb.shape}")
# 3차원인 경우 처리
if full_prompt_emb.dim() == 3:
# [T, E, N] -> [1, N, T, E]
fp_bnte = full_prompt_emb.permute(2, 0, 1).unsqueeze(0).contiguous()
else:
print(f"❌ Cannot handle full_prompt_emb with {full_prompt_emb.dim()} dimensions")
return
tok_list = []
tok_ch_list = []
for b in range(B_fp):
for n in range(N):
tok_e = fp_bnte[b, n] # [T,E]
k = min(T, token_sample_per_channel)
if k <= 0:
continue
idx = torch.randperm(T, device=device)[:k]
sel = tok_e.index_select(0, idx) # [k,E]
# [k,E] -> [k,D] (txt_head는 [B,N,E] 기대라서 배치축 임시 추가)
sel_d = F.normalize(txt_head(sel.unsqueeze(0)), dim=-1).squeeze(0) # [k,D]
tok_list.append(sel_d)
tok_ch_list.append(torch.full((k,), n, device=device, dtype=torch.long))
tok_proj = torch.cat(tok_list, dim=0) if len(tok_list) else torch.empty(0, D, device=device)
tok_ch = torch.cat(tok_ch_list, dim=0) if len(tok_ch_list) else torch.empty(0, dtype=torch.long, device=device)
# ---------- flatten (B,N,D) -> (B*N,D) & channel index ----------
def _flatten_with_channel(z): # z: [B,N,D]
zf = z.reshape(-1, z.size(-1)) # [B*N,D]
ch = torch.arange(N, device=z.device).repeat(B) # [B*N] : 0..N-1, 0..N-1, ...
return zf, ch
enc_flat, enc_ch = _flatten_with_channel(enc_proj)
cross_flat, cross_ch = _flatten_with_channel(cross_proj)
last_flat, last_ch = _flatten_with_channel(last_proj)
# tok_proj, tok_ch already prepared
arrays = [enc_flat.cpu().numpy(), cross_flat.cpu().numpy(), last_flat.cpu().numpy(), tok_proj.cpu().numpy()]
names = ["ENC", "CROSS", "LAST", "TOK"]
chs = [enc_ch.cpu().numpy(), cross_ch.cpu().numpy(), last_ch.cpu().numpy(), tok_ch.cpu().numpy()]
# concat for joint 2D projection
X = np.concatenate(arrays, axis=0) # [(sum K), D]
if X.shape[0] < 3:
print("Not enough points to visualize.")
return
if method.lower() == "pca":
reducer = PCA(n_components=2)
X2 = reducer.fit_transform(X)
else:
# TSNE perplexity는 데이터 수에 맞게 안전하게
perp = max(2, min(30, X.shape[0] // 3))
reducer = TSNE(n_components=2, init="pca", perplexity=perp)
X2 = reducer.fit_transform(X)
sizes = [a.shape[0] for a in arrays]
splits = np.cumsum(sizes)[:-1]
Xparts = np.split(X2, splits, axis=0)
CHparts = np.split(np.concatenate(chs, axis=0), splits, axis=0)
# ---------- plot ----------
plt.figure(figsize=(9, 7))
# 색상: 종류별(ENC/CROSS/LAST/TOK), 마커: 채널별
default_colors = {"ENC": "#1f77b4", "CROSS": "#2ca02c", "LAST": "#ff7f0e", "TOK": "#d62728"}
if color_map is not None:
default_colors.update(color_map)
# 채널 마커 세트 (N=7 가정, 더 많으면 반복)
channel_markers = ['o', 's', '^', 'D', 'P', 'X', '*', 'v', '<', '>']
# 범례 표시를 위해 채널별 첫 호출 여부 관리
channel_legend_done = [False] * N
type_legend_done = {k: False for k in default_colors.keys()}
for name, pts, ch_idx in zip(names, Xparts, CHparts):
color = default_colors.get(name, None)
for n in range(N):
mask = (ch_idx == n)
if not np.any(mask):
continue
mk = channel_markers[n % len(channel_markers)]
# 첫 등장엔 채널 범례 + 타입 범례를 같이 표기
label = None
if not channel_legend_done[n] and not type_legend_done.get(name, False):
label = f"{name} (ch{n})"
channel_legend_done[n] = True
type_legend_done[name] = True
elif not channel_legend_done[n]:
label = f"ch{n}"
channel_legend_done[n] = True
elif not type_legend_done.get(name, False):
label = f"{name}"
type_legend_done[name] = True
plt.scatter(pts[mask, 0], pts[mask, 1],
s=24, alpha=0.85, marker=mk, color=color,
label=label)
plt.title(f"Common-space (per-channel markers, {method.upper()})")
plt.tight_layout()
plt.legend(ncol=2, fontsize=9)
plt.savefig(save_path, dpi=150)
plt.close()
print(f"✅ Saved common-space plot to {save_path}")
def compute_cosine_similarity(prompt_last: torch.Tensor,
cross_out: torch.Tensor,
projector: nn.Module = None) -> torch.Tensor:
"""
Compute cosine similarity between prompt_last and cross_out embeddings per channel.
Args:
prompt_last (Tensor): [d_llm, N] or [B, d_llm, N]
cross_out (Tensor): [N, C] or [B, N, C]
projector (nn.Module, optional): Optional linear layer for dimension alignment.
Returns:
Tensor: Cosine similarity per channel: [N] or [B, N]
"""
if prompt_last.dim() == 2:
prompt_last = prompt_last.unsqueeze(0) # [1, d_llm, N]
if cross_out.dim() == 2:
cross_out = cross_out.unsqueeze(0) # [1, N, C]
B, d_llm, N = prompt_last.shape
_, N2, C = cross_out.shape
assert N == N2, f"Mismatch in channels: {N} vs {N2}"
prompt_last = prompt_last.permute(0, 2, 1) # [B, N, d_llm]
# Optional projection if needed
if d_llm != C:
if projector is None:
projector = nn.Linear(d_llm, C).to(prompt_last.device)
prompt_last = projector(prompt_last)
sim = F.cosine_similarity(prompt_last, cross_out, dim=-1) # [B, N]
return sim.squeeze(0) if sim.size(0) == 1 else sim
def plot_similarity_distributions(pre_sim, post_sim, save_path='sim_distribution.png'):
pre_sim = pre_sim.detach().cpu().numpy().flatten()
post_sim = post_sim.detach().cpu().numpy().flatten()
plt.figure(figsize=(8,6))
sns.histplot(pre_sim, color='blue', label='Pre-training', kde=True, stat="density", bins=20, alpha=0.6)
sns.histplot(post_sim, color='red', label='Post-training', kde=True, stat="density", bins=20, alpha=0.6)
plt.title("Cosine Similarity Distribution\n(prompt_last vs cross_out)")
plt.xlabel("Cosine Similarity")
plt.ylabel("Density")
plt.legend()
plt.grid(True)
plt.tight_layout()
plt.savefig(save_path)
print(f"✅ Saved similarity distribution to {save_path}")
def compute_pairwise_distance_mse(X: torch.Tensor, Y: torch.Tensor) -> float:
"""
Compute the MSE between pairwise distance matrices of X and Y.
Args:
X: [N, D1]
Y: [N, D2]
Returns:
float: Mean squared error between pairwise distances
"""
# Compute pairwise distances
D1 = torch.cdist(X, X, p=2) # [N, N]
D2 = torch.cdist(Y, Y, p=2) # [N, N]
# Normalize (optional): min-max to [0,1] range for stability
D1 = (D1 - D1.min()) / (D1.max() - D1.min() + 1e-8)
D2 = (D2 - D2.min()) / (D2.max() - D2.min() + 1e-8)
# MSE between distance matrices
return F.mse_loss(D1, D2).item()
def visualize_combined_embeddings(ts_embeddings, txt_embeddings, save_path="combined_embeddings.png"):
"""시계열과 텍스트 임베딩을 함께 시각화합니다."""
# 입력 검증
if not ts_embeddings or not txt_embeddings:
print("❌ No embeddings data provided for visualization")
return
try:
# Feature별 색상 설정
feature_colors = plt.cm.tab10(np.linspace(0, 1, 7))
feature_names = ['HUFL', 'HULL', 'MUFL', 'MULL', 'LUFL', 'LULL', 'OT']
feature_markers = ['o', 's', '^', 'D', 'P', 'X', '*']
# 모든 임베딩 결합
all_embeddings = []
all_labels = []
all_types = []
for item in ts_embeddings:
all_embeddings.append(item['embedding'])
all_labels.append(f"TS_{item['feature_name']}_{item['time_position']}")
all_types.append('Time Series')
for item in txt_embeddings:
all_embeddings.append(item['embedding'])
all_labels.append(f"TXT_{item['feature_name']}_{item['time_position']}")
all_types.append('Text (Prompt)')
if not all_embeddings:
print("❌ No valid embeddings found")
return
# t-SNE 적용
embeddings = np.array(all_embeddings)
if len(embeddings) < 3:
print("❌ Not enough embeddings for t-SNE")
return
tsne = TSNE(n_components=2, random_state=42, perplexity=min(30, len(embeddings) // 3))
embeddings_2d = tsne.fit_transform(embeddings)
except Exception as e:
print(f"❌ Error in visualization: {e}")
return
try:
# 시각화
fig, ax = plt.subplots(1, 1, figsize=(15, 10))
# 각 타입별로 시각화
type_colors = {'Time Series': 'blue', 'Text (Prompt)': 'red'}
type_markers = {'Time Series': 'o', 'Text (Prompt)': 's'}
# 각 feature와 타입별로 시간 순서대로 그룹화
for feature_idx, feature_name in enumerate(feature_names):
for embed_type in type_colors.keys():
# 해당 feature와 타입의 데이터만 필터링
feature_type_data = []
for i, (embedding_2d, label, etype) in enumerate(zip(embeddings_2d, all_labels, all_types)):
if etype == embed_type and label.split('_')[1] == feature_name:
time_pos = int(label.split('_')[2])
feature_type_data.append((embedding_2d, time_pos))
# 시간 순서대로 정렬
feature_type_data.sort(key=lambda x: x[1])
if len(feature_type_data) > 0:
# 점들 그리기
for embedding_2d, time_pos in feature_type_data:
ax.scatter(embedding_2d[0], embedding_2d[1],
c=feature_colors[feature_idx],
marker=type_markers[embed_type],
s=30 + time_pos * 8,
alpha=0.7,
edgecolors='black',
linewidth=0.5)
# 시간 순서대로 선 연결
if len(feature_type_data) > 1:
x_coords = [data[0][0] for data in feature_type_data]
y_coords = [data[0][1] for data in feature_type_data]
# 선 그리기
ax.plot(x_coords, y_coords,
color=feature_colors[feature_idx],
alpha=0.4,
linewidth=1.5,
linestyle='-')
# 화살표로 시간 방향 표시
for j in range(len(x_coords) - 1):
ax.annotate('', xy=(x_coords[j+1], y_coords[j+1]),
xytext=(x_coords[j], y_coords[j]),
arrowprops=dict(arrowstyle='->',
color=feature_colors[feature_idx],
alpha=0.6,
lw=1.5))
# 범례 생성
legend_elements = []
for i, feature in enumerate(feature_names):
legend_elements.append(plt.Line2D([0], [0], marker=feature_markers[i], color='w',
markerfacecolor=feature_colors[i], markersize=10, label=feature))
for embed_type, color in type_colors.items():
legend_elements.append(plt.Line2D([0], [0], marker=type_markers[embed_type], color='w',
markerfacecolor=color, markersize=10, label=embed_type))
ax.set_title('Combined Time Series and Prompt Text Embeddings (t-SNE)', fontsize=16, fontweight='bold')
ax.set_xlabel('t-SNE 1')
ax.set_ylabel('t-SNE 2')
ax.grid(True, alpha=0.3)
ax.legend(handles=legend_elements, loc='upper right', bbox_to_anchor=(1.0, 1.0), fontsize=8)
plt.tight_layout()
plt.savefig(save_path, dpi=300, bbox_inches='tight')
plt.close()
print(f"✅ Saved combined embeddings visualization to {save_path}")
except Exception as e:
print(f"❌ Error saving visualization: {e}")
plt.close()
def get_embeddings_for_visualization(model, ts_head, txt_head, dataset, args, device, num_segments=20):
"""시각화를 위한 임베딩 데이터를 추출합니다."""
print(f"🔄 Extracting embeddings for visualization ({num_segments} segments)...")
model.eval()
ts_head.eval()
txt_head.eval()
# 첫 번째 배치 데이터 가져오기
try:
batch = next(iter(dataset))
x, y, x_mark, y_mark, last_emb, full_prompt, anchor_avg, num_token_idx = batch
except Exception as e:
print(f"❌ Error loading batch: {e}")
return [], []
# 데이터 타입 확인 및 변환
if isinstance(x, np.ndarray):
x = torch.from_numpy(x).unsqueeze(0).to(device)
else: