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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
import os
import argparse
import pickle
import torch
import numpy as np
import networkx as nx
import random
import matplotlib.pyplot as plt
from tqdm import tqdm
from torch.nn.utils.rnn import pad_sequence
from collections import defaultdict
from sklearn.decomposition import PCA

# Import project modules
from model.transformer import GPTConfig, GPT
from model.transformer_rope import GPTRoPEConfig, GPTRoPE
from model.transformer_nextlat import TransformerNextLatConfig, TransformerNextLat
from model.mamba import MambaConfig, Mamba
from model.mamba2 import Mamba2Config, Mamba2
from model.gated_deltanet import GatedDeltaNetConfig, GatedDeltaNet
from model.gru import GRUConfig, GRU
from cli_utils import parse_count, format_count


def parse_args():
    parser = argparse.ArgumentParser(
        description='Analyze hidden state clustering by wall structure (legal moves).')

    # --- Model & Data Configuration ---
    parser.add_argument('--model', type=str, default='transformer',
                        choices=['transformer', 'transformer-rope', 'transformer-nextlat',
                                 'mamba', 'mamba2', 'gated-deltanet', 'gru'],
                        help='Model architecture (matches out/<model>/ dir). Default: transformer')
    parser.add_argument('--ckpt_iter', type=int, default=10000)
    parser.add_argument('--config', type=str, default='12_12_576')
    parser.add_argument('--device', type=str, default='cuda:0')
    parser.add_argument('--num_nodes', type=int, default=100)
    parser.add_argument('--num_of_paths', type=int, default=20)
    parser.add_argument('--multitasks', action=argparse.BooleanOptionalAction, default=True)
    parser.add_argument('--num_train_dataset', type=parse_count, default="10M")
    parser.add_argument('--tasks', type=str, default='C1')
    parser.add_argument('--CL', action=argparse.BooleanOptionalAction, default=False)
    parser.add_argument('--path_type', type=str, default='RWs', choices=['RWc', 'RWa', 'RWs'])
    parser.add_argument('--no_task_tag', action='store_true', default=False)
    parser.add_argument('--local', action=argparse.BooleanOptionalAction, default=False)
    parser.add_argument('--NLS', action='store_true', default=False,
                        help='Use NLS model checkpoint (adds _NLS suffix to filenames)')

    # --- Clustering Specific ---
    parser.add_argument('--num_samples', type=int, default=5000,
                        help='Number of prefix sequences to sample.')
    parser.add_argument('--batch_size', type=int, default=128)
    parser.add_argument('--min_samples_per_class', type=int, default=30,
                        help='Minimum number of samples required to keep a class.')
    parser.add_argument('--cluster_by', type=str, default='current_token',
                        choices=['node', 'wall_type', 'predicted_token', 'current_token'],
                        help='Clustering criteria: node, wall_type, predicted_token, or current_token '
                             '(the last/probed token of the prefix). '
                             '(For Task-specific criteria see --cluster_by_orientation / --cluster_by_taskE_token_type.)')
    parser.add_argument('--probe_tasks', type=str, default='C',
                        help='Which task identifier to probe (e.g., A, C, E, H, or I)')

    # --- Task C additions ---
    parser.add_argument('--rel_wall_type', action=argparse.BooleanOptionalAction, default=False,
                        help='Task C only: cluster by legal moves expressed as L/R/F/T relative to current orientation. Overrides --cluster_by when set.')
    parser.add_argument('--cluster_by_orientation', action=argparse.BooleanOptionalAction, default=False,
                        help='Task C only: cluster by current orientation (N/S/E/W) instead of --cluster_by. Overrides --cluster_by when set.')

    # --- Task E additions ---
    parser.add_argument('--taskE_probe_type', type=str, default='label', choices=['dir', 'label'],
                        help='For Task E, probe at the "dir" token or the "label" token position.')
    parser.add_argument('--cluster_by_taskE_token_type', action=argparse.BooleanOptionalAction, default=False,
                        help='Task E only: cluster by the taskE token type (dir vs label) instead of --cluster_by. Overrides --cluster_by when set.')

    # --- Task I additions ---
    parser.add_argument('--cluster_by_legal_next', action=argparse.BooleanOptionalAction, default=False,
                        help='Task I only: cluster by the set of legal next steps expressed as open fixed-scan '
                             'slot indices (0=N,1=E,2=S,3=W), e.g. "0,2,3". Overrides --cluster_by when set.')

    # --- Visualization ---
    parser.add_argument('--vis_num_nodes', type=int, default=0,
                        help='When clustering by node, randomly show at most this many node classes with distinct colors. '
                             'Set to 0 or negative to show all nodes (continuous colormap).')
    parser.add_argument('--pca_full_data', action='store_true', default=True,
                        help='When clustering by node and using --vis_num_nodes > 0, perform PCA on all samples (not just the subset) '
                             'and then display only the subset. This preserves the global PCA structure.')

    return parser.parse_args()


def load_lines(path):
    if not os.path.exists(path):
        return []
    try:
        with open(path, 'r', encoding='gbk') as f:
            return [line.strip() for line in f if line.strip()]
    except:
        with open(path, 'r', encoding='utf-8') as f:
            return [line.strip() for line in f if line.strip()]


def get_legal_dirs(G, node, grid_n):
    legal = []
    for nb_str in G.neighbors(str(node)):
        nb = int(nb_str)
        if nb == node - grid_n:
            legal.append('N')
        elif nb == node + grid_n:
            legal.append('S')
        elif nb == node + 1:
            legal.append('E')
        elif nb == node - 1:
            legal.append('W')
    return sorted(legal)


def extract_data_for_clustering(lines, stoi, max_samples, no_task_tag, grid_n, num_nodes, maze_graph, probe_tasks,

                                taskE_probe_type, cluster_by):
    labels_chars = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'}
    turn_chars = {'L', 'R', 'F', 'T'}
    data = []

    lines = list(lines)
    random.shuffle(lines)

    for line in lines:
        if len(data) >= max_samples:
            break

        parts = line.split()
        if ':' not in parts:
            continue
        colon_idx = parts.index(':')

        if no_task_tag:
            action_tokens = parts[colon_idx + 1:]
            if any(c in turn_chars for c in action_tokens):
                line_task = 'C'
            elif len(parts) > colon_idx + 2 and parts[colon_idx + 2] in labels_chars:
                line_task = 'E'
            else:
                line_task = 'A'
            try:
                source = int(parts[0])
            except:
                continue
        else:
            line_task = parts[0]
            if line_task not in ['A', 'E', 'C', 'H', 'I']:
                continue
            try:
                source = int(parts[1])
            except:
                continue

        if line_task != probe_tasks:
            continue

        actions = parts[colon_idx + 1:]
        if not actions:
            continue

        try:
            token_ids = [stoi[t] for t in parts]
        except KeyError:
            continue

        curr = source

        if probe_tasks == 'A':
            for i, move in enumerate(actions):
                if move == 'N':
                    curr -= grid_n
                elif move == 'S':
                    curr += grid_n
                elif move == 'E':
                    curr += 1
                elif move == 'W':
                    curr -= 1

                if not (0 <= curr < num_nodes):
                    break

                legal = get_legal_dirs(maze_graph, curr, grid_n)
                wall_type = ','.join(legal)

                prefix_ids = token_ids[:colon_idx + 2 + i]
                data.append({
                    'ids': torch.tensor(prefix_ids, dtype=torch.long),
                    'node': curr,
                    'wall_type': wall_type,
                    'current_token': move
                })

                if len(data) >= max_samples:
                    break

        elif probe_tasks == 'C':
            # Task C:相对转向,起始朝东 (E),每个 action 先转向再前进一步
            left_of = {'N': 'W', 'W': 'S', 'S': 'E', 'E': 'N'}
            right_of = {v: k for k, v in left_of.items()}
            opposite_of = {'N': 'S', 'S': 'N', 'E': 'W', 'W': 'E'}
            delta = {'N': -grid_n, 'S': grid_n, 'E': 1, 'W': -1}
            orientation = 'E'

            for i, action in enumerate(actions):
                if action not in turn_chars:
                    break

                if action == 'F':
                    next_orientation = orientation
                elif action == 'L':
                    next_orientation = left_of[orientation]
                elif action == 'R':
                    next_orientation = right_of[orientation]
                else:  # 'T'
                    next_orientation = opposite_of[orientation]

                next_node = curr + delta[next_orientation]
                if not (0 <= next_node < num_nodes):
                    break

                orientation = next_orientation
                curr = next_node

                legal = get_legal_dirs(maze_graph, curr, grid_n)
                # 同时记录绝对方向和相对方向的 wall_type
                abs_wall_type = ','.join(legal)
                abs_to_rel = {
                    orientation: 'F',
                    left_of[orientation]: 'L',
                    right_of[orientation]: 'R',
                    opposite_of[orientation]: 'T',
                }
                rel_legal = sorted({abs_to_rel[d] for d in legal})
                rel_wall_type_str = ','.join(rel_legal)

                prefix_ids = token_ids[:colon_idx + 2 + i]
                data.append({
                    'ids': torch.tensor(prefix_ids, dtype=torch.long),
                    'node': curr,
                    'wall_type': abs_wall_type,
                    'rel_wall_type': rel_wall_type_str,
                    'orientation': orientation,
                    'current_token': action
                })

                if len(data) >= max_samples:
                    break

        elif probe_tasks == 'E':
            for i in range(0, len(actions), 2):
                direction = actions[i]
                if i + 1 >= len(actions):
                    break
                target_lab = actions[i + 1]

                step_count = 0
                temp_curr = curr
                found = False

                while True:
                    if direction == 'N':
                        temp_curr -= grid_n
                    elif direction == 'S':
                        temp_curr += grid_n
                    elif direction == 'E':
                        temp_curr += 1
                    elif direction == 'W':
                        temp_curr -= 1

                    if not (0 <= temp_curr < num_nodes):
                        break
                    step_count += 1
                    if step_count > num_nodes + 5:
                        break

                    if maze_graph.nodes[str(temp_curr)]['label'] == target_lab:
                        curr = temp_curr
                        found = True
                        break

                if not found:
                    break

                legal = get_legal_dirs(maze_graph, curr, grid_n)
                wall_type = ','.join(legal)

                if cluster_by == 'taskE_token_type':
                    # Extract BOTH 'dir' and 'label' positions
                    prefix_ids_dir = token_ids[:colon_idx + 2 + i]
                    data.append({
                        'ids': torch.tensor(prefix_ids_dir, dtype=torch.long),
                        'node': curr,
                        'wall_type': wall_type,
                        'taskE_token_type': 'dir',
                        'current_token': direction
                    })

                    prefix_ids_lab = token_ids[:colon_idx + 3 + i]
                    data.append({
                        'ids': torch.tensor(prefix_ids_lab, dtype=torch.long),
                        'node': curr,
                        'wall_type': wall_type,
                        'taskE_token_type': 'label',
                        'current_token': target_lab
                    })
                else:
                    # Extract only the specified one
                    if taskE_probe_type == 'dir':
                        prefix_ids = token_ids[:colon_idx + 2 + i]
                        cur_tok = direction
                    else:
                        prefix_ids = token_ids[:colon_idx + 3 + i]
                        cur_tok = target_lab

                if len(data) >= max_samples:
                    break

        elif probe_tasks in ('H', 'I'):
            # Index-token tasks: replay (node[, facing]) state from 1-based scan indices.
            # Task H: clockwise scan starting from current facing (state = node + facing).
            # Task I: fixed North->E->S->W scan, no facing tracking (state = node only).
            CLOCKWISE_SCAN = {
                'N': ['N', 'E', 'S', 'W'],
                'E': ['E', 'S', 'W', 'N'],
                'S': ['S', 'W', 'N', 'E'],
                'W': ['W', 'N', 'E', 'S'],
            }
            FIXED_SCAN = ['N', 'E', 'S', 'W']
            delta = {'N': -grid_n, 'S': grid_n, 'E': 1, 'W': -1}
            facing = 'E'  # Task H starts facing East; unused for Task I

            for i, idx_tok in enumerate(actions):
                try:
                    choice = int(idx_tok)
                except ValueError:
                    break

                scan_order = CLOCKWISE_SCAN[facing] if probe_tasks == 'H' else FIXED_SCAN
                feasible = []
                for d in scan_order:
                    nb = curr + delta[d]
                    if 0 <= nb < num_nodes and maze_graph.has_edge(str(curr), str(nb)):
                        feasible.append(d)

                if not (1 <= choice <= len(feasible)):
                    break

                move = feasible[choice - 1]
                curr = curr + delta[move]
                if probe_tasks == 'H':
                    facing = move

                legal = get_legal_dirs(maze_graph, curr, grid_n)
                wall_type = ','.join(legal)

                prefix_ids = token_ids[:colon_idx + 2 + i]
                item = {
                    'ids': torch.tensor(prefix_ids, dtype=torch.long),
                    'node': curr,
                    'wall_type': wall_type,
                    'current_token': idx_tok,
                }
                if probe_tasks == 'H':
                    item['orientation'] = facing
                if probe_tasks == 'I':
                    # Legal next steps as open fixed-scan slot indices (0=N,1=E,2=S,3=W),
                    # matching the index tokens the model emits for Task I.
                    legal_set = set(legal)
                    item['legal_next'] = ','.join(str(j) for j, d in enumerate(FIXED_SCAN) if d in legal_set)
                data.append(item)

                if len(data) >= max_samples:
                    break

    return data[:max_samples]


activations = {}


def get_layer_hook(layer_idx):
    def hook(model, input, output):
        activations[layer_idx] = output.detach()

    return hook


def get_block_list(model):
    """Per-layer block ModuleList (transformer: .transformer.h, recurrent: .layers)."""
    if hasattr(model, 'transformer'):
        return model.transformer.h
    return model.layers


def get_final_norm(model):
    """Final pre-head norm (transformer: .transformer.ln_f, recurrent: .out_norm)."""
    if hasattr(model, 'transformer') and hasattr(model.transformer, 'ln_f'):
        return model.transformer.ln_f
    return model.out_norm


def get_lm_head(model):
    """Output projection head. Most models expose .lm_head; TransformerNextLat

    wraps the backbone, so its head lives at .gpt.lm_head."""
    if hasattr(model, 'lm_head'):
        return model.lm_head
    if hasattr(model, 'gpt') and hasattr(model.gpt, 'lm_head'):
        return model.gpt.lm_head
    raise AttributeError(f"{type(model).__name__} has no lm_head")


def build_model_from_checkpoint(checkpoint, model_type, local=False):
    """Reconstruct the right architecture from a checkpoint, honoring its stored model_type."""
    ckpt_model_type = checkpoint.get('model_type', model_type)
    margs = checkpoint['model_args']
    if ckpt_model_type == 'mamba':
        if local and 'use_cuda' in margs:
            margs['use_cuda'] = False  # fall back to pure-PyTorch parallel scan
        conf = MambaConfig(**margs); model = Mamba(conf)
    elif ckpt_model_type == 'mamba2':
        if local and 'use_cuda' in margs:
            margs['use_cuda'] = False  # fall back to pure-PyTorch chunked SSD
        conf = Mamba2Config(**margs); model = Mamba2(conf)
    elif ckpt_model_type == 'gated-deltanet':
        conf = GatedDeltaNetConfig(**margs); model = GatedDeltaNet(conf)
    elif ckpt_model_type == 'gru':
        conf = GRUConfig(**margs); model = GRU(conf)
    elif ckpt_model_type == 'transformer-nextlat':
        if local and 'use_flash' in margs:
            margs['use_flash'] = False
        conf = TransformerNextLatConfig(**margs); model = TransformerNextLat(conf)
    elif ckpt_model_type == 'transformer-rope':
        conf = GPTRoPEConfig(**margs)
        if local:
            conf.use_flash = False
        model = GPTRoPE(conf)
    else:
        conf = GPTConfig(**margs)
        if local:
            conf.use_flash = False
        model = GPT(conf)
    model.load_state_dict({k.replace('_orig_mod.', ''): v for k, v in checkpoint['model'].items()})
    return model, conf


def normalize_features(feats):
    norms = np.linalg.norm(feats, axis=1, keepdims=True)
    norms[norms == 0] = 1e-12
    return feats / norms


def compute_intra_inter_distances(feats, labels, unique_labels):
    centroids = {}
    for lab in unique_labels:
        mask = (labels == lab)
        if np.sum(mask) == 0:
            continue
        centroids[lab] = np.mean(feats[mask], axis=0)
        centroids[lab] = centroids[lab] / (np.linalg.norm(centroids[lab]) + 1e-12)

    intra_dists = []
    for lab in unique_labels:
        mask = (labels == lab)
        if np.sum(mask) == 0:
            continue
        centroid = centroids[lab]
        sim = np.dot(feats[mask], centroid)
        dists = 1 - sim
        intra_dists.append(np.mean(dists))
    intra_avg = np.mean(intra_dists) if intra_dists else 0.0

    inter_dists = []
    centroids_list = list(centroids.values())
    for i in range(len(centroids_list)):
        for j in range(i + 1, len(centroids_list)):
            sim = np.dot(centroids_list[i], centroids_list[j])
            dist = 1 - sim
            inter_dists.append(dist)
    inter_avg = np.mean(inter_dists) if inter_dists else 0.0

    return intra_avg, inter_avg


def main():
    args = parse_args()

    # 解析任务专用的 cluster_by 覆盖选项
    overrides_set = sum([args.cluster_by_orientation, args.cluster_by_taskE_token_type,
                         args.rel_wall_type, args.cluster_by_legal_next])
    if overrides_set > 1:
        print("[Warning] --cluster_by_orientation / --cluster_by_taskE_token_type / --rel_wall_type / "
              "--cluster_by_legal_next are mutually exclusive; "
              "preferring --cluster_by_orientation > --rel_wall_type > --cluster_by_legal_next > --cluster_by_taskE_token_type.")
        if args.cluster_by_orientation:
            args.rel_wall_type = False
            args.cluster_by_legal_next = False
            args.cluster_by_taskE_token_type = False
        elif args.rel_wall_type:
            args.cluster_by_legal_next = False
            args.cluster_by_taskE_token_type = False
        elif args.cluster_by_legal_next:
            args.cluster_by_taskE_token_type = False
    if args.cluster_by_orientation:
        args.cluster_by = 'orientation'
    elif args.rel_wall_type:
        args.cluster_by = 'rel_wall_type'
    elif args.cluster_by_legal_next:
        args.cluster_by = 'legal_next'
    elif args.cluster_by_taskE_token_type:
        args.cluster_by = 'taskE_token_type'

    # 强制修正:如果是 taskE_token_type,则必须提取 Task E
    if args.cluster_by == 'taskE_token_type':
        args.probe_tasks = 'E'
    # 'rel_wall_type' 仅对 Task C 有意义;'orientation' 对 Task C / H 有意义
    if args.cluster_by == 'rel_wall_type' and args.probe_tasks != 'C':
        print(f"[Warning] cluster_by='rel_wall_type' is only meaningful for Task C; forcing probe_tasks='C'.")
        args.probe_tasks = 'C'
    elif args.cluster_by == 'orientation' and args.probe_tasks not in ('C', 'H'):
        print(f"[Warning] cluster_by='orientation' is only meaningful for Task C/H; forcing probe_tasks='C'.")
        args.probe_tasks = 'C'
    elif args.cluster_by == 'legal_next' and args.probe_tasks != 'I':
        print(f"[Warning] cluster_by='legal_next' is only meaningful for Task I; forcing probe_tasks='I'.")
        args.probe_tasks = 'I'

    seed = 44
    torch.manual_seed(seed)
    np.random.seed(seed)
    random.seed(seed)
    grid_n = int(args.num_nodes ** 0.5)

    tasks_tag = f"{args.tasks}_CL" if args.CL else args.tasks
    tasks_tag = f"{tasks_tag}_{args.path_type}"
    if args.no_task_tag:
        tasks_tag += "_NT"
    # NLS only affects checkpoint naming (per train_maze.py)
    ckpt_tasks_tag = tasks_tag
    if args.model == 'transformer-nextlat':
        ckpt_tasks_tag = f"{ckpt_tasks_tag}_NL"
    if args.NLS:
        ckpt_tasks_tag = f"{ckpt_tasks_tag}_NLS"

    data_dir = f'data/maze/{args.num_nodes}'
    nt_suffix = '_NT' if args.no_task_tag else ''
    model_dir = args.model.replace('-', '_')
    out_dir = f'out/{model_dir}/maze_{args.config}_{args.num_nodes}{nt_suffix}/'
    os.makedirs(out_dir, exist_ok=True)

    def pick_file(candidates):
        for path in candidates:
            if os.path.exists(path):
                return path
        return candidates[0]

    maze_graph_path = pick_file([f'{data_dir}/maze_graph_{tasks_tag}.graphml',
                                 f'{data_dir}/maze_graph.graphml'])
    print(f"Loading Graph from: {maze_graph_path}")
    maze_graph = nx.read_graphml(maze_graph_path)

    meta = pickle.load(open(pick_file([f'{data_dir}/meta_{tasks_tag}.pkl',
                                       f'{data_dir}/meta.pkl']), 'rb'))
    stoi, itos = meta['stoi'], meta['itos']

    train_label = format_count(args.num_train_dataset)
    ckpt_path = pick_file([os.path.join(out_dir, f'{args.ckpt_iter}_ckpt_maze_{ckpt_tasks_tag}_{train_label}.pt'),
                           os.path.join(out_dir, f'{args.ckpt_iter}_ckpt_maze_{tasks_tag}_{train_label}.pt'),
                           os.path.join(out_dir, f'{args.ckpt_iter}_ckpt_maze_{args.num_of_paths}.pt')])
    print(f"Loading Model from: {ckpt_path}")
    checkpoint = torch.load(ckpt_path, map_location=args.device, weights_only=False)
    model, conf = build_model_from_checkpoint(checkpoint, args.model, local=args.local)
    model.to(args.device).eval()
    for p in model.parameters():
        p.requires_grad = False

    block_list = get_block_list(model)
    for i in range(conf.n_layer):
        block_list[i].register_forward_hook(get_layer_hook(i))

    train_txt = pick_file([os.path.join(data_dir, f"train_{tasks_tag}_{train_label}.txt"),
                           os.path.join(data_dir, f'train_{args.num_of_paths}.txt')])
    print(f"Extracting samples for clustering...")
    dataset = extract_data_for_clustering(load_lines(train_txt), stoi, args.num_samples,
                                          args.no_task_tag, grid_n, args.num_nodes, maze_graph,
                                          args.probe_tasks, args.taskE_probe_type, args.cluster_by)
    print(f"Extracted {len(dataset)} samples.")

    print("\n" + "=" * 60)
    print(f"SAMPLE DATA EXAMPLES (Cluster by: {args.cluster_by})")
    print("=" * 60)
    for i in range(min(5, len(dataset))):
        item = dataset[i]
        ids = item['ids'].tolist()
        tokens = [itos[idx] for idx in ids]
        prefix_str = " ".join(tokens)
        label_val = item.get(args.cluster_by,
                             "N/A (needs model inference)") if args.cluster_by != 'predicted_token' else "N/A (needs model inference)"

        print(f"Example {i + 1}:")
        print(f"  Current Node : {item['node']}")
        print(f"  Wall Type    : {item['wall_type']}")
        print(f"  Selected Label: {label_val}")
        print(f"  Prefix       : {prefix_str}")
        print("-" * 60)

    all_feats = {i: [] for i in range(conf.n_layer + 1)}
    cluster_labels = []
    all_wall_types = []   # 记录每个样本的墙壁类型(用于节点模式图例标注)

    for b_start in tqdm(range(0, len(dataset), args.batch_size), desc="Inference"):
        batch = dataset[b_start:b_start + args.batch_size]
        x_padded = pad_sequence([item['ids'] for item in batch], batch_first=True, padding_value=0).to(args.device)
        seq_lengths = [len(item['ids']) for item in batch]

        current_batch_size = len(batch)

        with torch.no_grad():
            _ = model(x_padded)

            batch_indices = torch.arange(current_batch_size, device=args.device)
            last_token_idx = torch.tensor(seq_lengths, device=args.device) - 1

            h_final = activations[conf.n_layer - 1]
            if h_final.shape[0] != current_batch_size and h_final.shape[1] == current_batch_size:
                h_final = h_final.transpose(0, 1)

            h_last = h_final[batch_indices, last_token_idx, :]

            h_norm = get_final_norm(model)(h_last)
            logits = get_lm_head(model)(h_norm)

            if args.cluster_by == 'predicted_token':
                pred_ids = torch.argmax(logits, dim=-1).cpu().numpy()
                batch_labels = [itos[idx] for idx in pred_ids]
                cluster_labels.extend(batch_labels)
                # 填充 all_wall_types,保持长度一致
                for item in batch:
                    all_wall_types.append(item['wall_type'])

            for l in range(conf.n_layer):
                h = activations[l]
                if h.shape[0] != current_batch_size and h.shape[1] == current_batch_size:
                    h = h.transpose(0, 1)

                h_last_layer = h[batch_indices, last_token_idx, :].cpu().numpy()
                all_feats[l].extend(h_last_layer)

            h_norm_np = h_norm.cpu().numpy()
            all_feats[conf.n_layer].extend(h_norm_np)

        if args.cluster_by != 'predicted_token':
            for item in batch:
                if args.cluster_by == 'node':
                    cluster_labels.append(str(item['node']))
                elif args.cluster_by == 'wall_type':
                    cluster_labels.append(item['wall_type'])
                elif args.cluster_by == 'taskE_token_type':
                    cluster_labels.append(item['taskE_token_type'])
                elif args.cluster_by == 'orientation':
                    cluster_labels.append(item['orientation'])
                elif args.cluster_by == 'rel_wall_type':
                    cluster_labels.append(item['rel_wall_type'])
                elif args.cluster_by == 'legal_next':
                    cluster_labels.append(item['legal_next'])
                elif args.cluster_by == 'current_token':
                    cluster_labels.append(item['current_token'])
                # 无论哪种模式,只要后续需要显示墙壁类型(仅用于 node 模式),都记录 wall_type
                all_wall_types.append(item['wall_type'])

    cluster_labels = np.array(cluster_labels)
    all_wall_types = np.array(all_wall_types)

    unique, counts = np.unique(cluster_labels, return_counts=True)
    valid_classes = [u for u, c in zip(unique, counts) if c >= args.min_samples_per_class]
    print(f"Retained {len(valid_classes)} classes with >= {args.min_samples_per_class} samples.")
    if len(valid_classes) < 2:
        print("Not enough classes for inter-class distance. Exiting.")
        return

    mask = np.isin(cluster_labels, valid_classes)
    filtered_labels = cluster_labels[mask]
    # 仅在 node 模式下才需要墙壁类型信息(用于图例标注)
    if args.cluster_by == 'node':
        filtered_wall_types = all_wall_types[mask]
    else:
        filtered_wall_types = None  # 其他模式下不使用
    print(f"Total samples after filtering: {np.sum(mask)}")

    intra_distances = []
    inter_distances = []

    for l in range(conf.n_layer + 1):
        feats = np.array(all_feats[l])[mask]
        feats_norm = normalize_features(feats)

        intra, inter = compute_intra_inter_distances(feats_norm, filtered_labels, valid_classes)
        intra_distances.append(intra)
        inter_distances.append(inter)

    print("\n" + "=" * 60)
    print(f"CLUSTERING BY {args.cluster_by.upper()} (cosine distance)")
    print("=" * 60)
    print(f"{'Layer':<6} | {'Intra-class Dist':<18} | {'Inter-class Dist':<18}")
    print("-" * 60)
    for l, (intra, inter) in enumerate(zip(intra_distances, inter_distances)):
        layer_name = f"L_{l + 1}" if l < conf.n_layer else "L_Norm"
        print(f"{layer_name:<6} | {intra:>16.4f} | {inter:>16.4f}")
    print("=" * 60)

    if args.cluster_by == 'taskE_token_type':
        task_suffix = f"{args.probe_tasks}_both"
    elif args.probe_tasks == 'E':
        task_suffix = f"{args.probe_tasks}{args.taskE_probe_type}"
    else:
        task_suffix = f"{args.probe_tasks}"

    # cluster_by 直接作为文件名后缀('rel_wall_type' / 'orientation' / 'taskE_token_type' 等都是覆盖后的值)
    cluster_by_suffix = args.cluster_by
    nls_suffix = '_NLS' if args.NLS else ''

    out_txt = os.path.join(out_dir, f"clustering_{task_suffix}_{cluster_by_suffix}_{args.ckpt_iter}{nls_suffix}.txt")
    with open(out_txt, 'w') as f:
        f.write(f"CLUSTERING BY {args.cluster_by.upper()} (cosine distance)\n")
        f.write("=" * 60 + "\n")
        f.write(f"{'Layer':<6} | {'Intra-class Dist':<18} | {'Inter-class Dist':<18}\n")
        f.write("-" * 60 + "\n")
        for l, (intra, inter) in enumerate(zip(intra_distances, inter_distances)):
            layer_name = f"L_{l + 1}" if l < conf.n_layer else "L_Norm"
            f.write(f"{layer_name:<6} | {intra:>16.4f} | {inter:>16.4f}\n")
    print(f"Results saved to {out_txt}")

    print("\nGenerating 2D visualization using PCA...")

    n_layers = conf.n_layer + 1
    cols = min(3, n_layers)
    rows = (n_layers + cols - 1) // cols

    fig, axes = plt.subplots(rows, cols, figsize=(6 * cols, 5 * rows))
    if n_layers == 1:
        axes = [axes]
    else:
        axes = axes.flatten()

    # Decide how to visualize node classes
    is_node_mode = (args.cluster_by == 'node')
    use_random_nodes = False
    selected_nodes = None
    node_mask_for_vis = None
    node_to_wall_types = None   # 节点ID -> 墙壁类型集合

    if is_node_mode and args.vis_num_nodes > 0:
        unique_nodes = np.unique(filtered_labels)
        if len(unique_nodes) > args.vis_num_nodes:
            # Randomly select a subset of nodes for visualization
            rng = np.random.RandomState(seed)
            selected_nodes = rng.choice(unique_nodes, size=args.vis_num_nodes, replace=False)
            use_random_nodes = True
            node_mask_for_vis = np.isin(filtered_labels, selected_nodes)
            print(f"Randomly selected {args.vis_num_nodes} nodes out of {len(unique_nodes)} for visualization: {sorted(selected_nodes)}")

            # 预计算每个选中节点的墙壁类型集合
            node_to_wall_types = {}
            for node in selected_nodes:
                node_mask = (filtered_labels == node)
                wall_types_for_node = filtered_wall_types[node_mask]
                unique_wall_types = sorted(set(wall_types_for_node))
                node_to_wall_types[node] = unique_wall_types
        else:
            print(f"Total unique nodes ({len(unique_nodes)}) <= vis_num_nodes, showing all nodes.")
    elif is_node_mode:
        print("Showing all nodes (continuous colormap).")

    # 用于存储全局图例的句柄和标签
    legend_handles = []
    legend_labels = []

    for l in range(n_layers):
        ax = axes[l]

        # 获取该层所有样本的特征(已通过 mask 过滤)
        feats_all = np.array(all_feats[l])[mask]   # shape (N, D)

        if use_random_nodes and args.pca_full_data:
            # 情况:使用全部样本进行 PCA 拟合,然后只绘制选中节点的投影点
            # 可选子采样以提高速度(仅用于拟合,不影响投影)
            if feats_all.shape[0] > 2000:
                # 随机采样 2000 个点用于拟合 PCA
                idx_sample = np.random.choice(feats_all.shape[0], 2000, replace=False)
                pca = PCA(n_components=2)
                pca.fit(feats_all[idx_sample])
            else:
                pca = PCA(n_components=2)
                pca.fit(feats_all)

            # 对所有样本进行投影
            feats_2d_all = pca.transform(feats_all)   # shape (N, 2)
            # 提取选中节点的投影结果
            feats_vis = feats_2d_all[node_mask_for_vis]
            labels_vis = filtered_labels[node_mask_for_vis]
            if is_node_mode:
                wall_types_vis = filtered_wall_types[node_mask_for_vis]
            else:
                wall_types_vis = None
        else:
            # 原有逻辑:仅使用用于绘制的样本进行 PCA(可能是全部样本,也可能是子集)
            if use_random_nodes:
                # 只使用选中节点的特征
                feats_vis_subset = feats_all[node_mask_for_vis]
                labels_vis = filtered_labels[node_mask_for_vis]
                if is_node_mode:
                    wall_types_vis = filtered_wall_types[node_mask_for_vis]
                else:
                    wall_types_vis = None
            else:
                # 使用全部有效样本
                feats_vis_subset = feats_all
                labels_vis = filtered_labels
                if is_node_mode:
                    wall_types_vis = filtered_wall_types
                else:
                    wall_types_vis = None

            # 可选子采样
            if feats_vis_subset.shape[0] > 2000:
                idx = np.random.choice(feats_vis_subset.shape[0], 2000, replace=False)
                feats_vis_subset = feats_vis_subset[idx]
                labels_vis = labels_vis[idx]
                if is_node_mode and wall_types_vis is not None:
                    wall_types_vis = wall_types_vis[idx]

            pca = PCA(n_components=2)
            feats_2d = pca.fit_transform(feats_vis_subset)
            feats_vis = feats_2d   # 此时 feats_vis 就是投影后的坐标

        # 绘图部分,根据 is_node_mode 和 use_random_nodes 选择颜色映射和标记
        if is_node_mode:
            if use_random_nodes:
                # 为每个选中的节点分配固定颜色
                unique_selected = np.unique(labels_vis)
                # 如果全局图例尚未生成,则创建颜色映射
                if not legend_handles:
                    cmap = plt.cm.tab20
                    color_map = {}
                    for i, node in enumerate(unique_selected):
                        color_map[node] = cmap(i % 20)
                    # 为每个节点生成图例句柄和标签
                    for node in unique_selected:
                        wall_types_str = ','.join(node_to_wall_types[node]) if node in node_to_wall_types else ''
                        label_text = f"{node} ({wall_types_str})" if wall_types_str else str(node)
                        handle = plt.Line2D([0], [0], marker='o', color='w', markerfacecolor=color_map[node],
                                            markersize=8, label=label_text)
                        legend_handles.append(handle)
                        legend_labels.append(label_text)
                else:
                    # 复用颜色映射(但需要从已存储的 handle 中获取颜色)
                    # 简单起见,重新生成 color_map(因为 unique_selected 顺序可能一致)
                    cmap = plt.cm.tab20
                    color_map = {}
                    for i, node in enumerate(unique_selected):
                        color_map[node] = cmap(i % 20)

                # 绘制每个节点
                for node in unique_selected:
                    node_mask_plot = (labels_vis == node)
                    ax.scatter(feats_vis[node_mask_plot, 0], feats_vis[node_mask_plot, 1],
                               c=[color_map[node]], s=10, alpha=0.7)
            else:
                # 连续色图:不添加图例,只绘制
                int_labels_vis = np.array([int(lab) for lab in labels_vis])
                sc = ax.scatter(feats_vis[:, 0], feats_vis[:, 1],
                                c=int_labels_vis, cmap='viridis', s=10, alpha=0.7)
        else:
            # 其他聚类模式:为每个有效类别分配固定颜色
            if not legend_handles:
                colors = plt.cm.tab20(np.linspace(0, 1, len(valid_classes)))
                for i, cls_type in enumerate(valid_classes):
                    handle = plt.Line2D([0], [0], marker='o', color='w', markerfacecolor=colors[i],
                                        markersize=8, label=cls_type)
                    legend_handles.append(handle)
                    legend_labels.append(cls_type)
            else:
                # 复用颜色
                colors = [h.get_markerfacecolor() for h in legend_handles]
            # 绘制每个类别
            for i, cls_type in enumerate(valid_classes):
                type_mask = (labels_vis == cls_type)
                if np.sum(type_mask) > 0:
                    ax.scatter(feats_vis[type_mask, 0], feats_vis[type_mask, 1],
                               c=[colors[i]], s=10, alpha=0.7)

        title = f'Layer {l + 1}' if l < conf.n_layer else 'Layer Final (Norm)'
        ax.set_title(title)
        ax.set_xlabel('Principal Component 1')
        ax.set_ylabel('Principal Component 2')
        ax.grid(True, linestyle='--', alpha=0.3)

    # 删除多余的子图
    for i in range(n_layers, len(axes)):
        fig.delaxes(axes[i])

    # 添加全局图例(如果需要)
    if legend_handles:
        fig.legend(handles=legend_handles, labels=legend_labels, loc='lower right',
                   fontsize='small', title=('Node ID (wall types)' if is_node_mode and use_random_nodes else args.cluster_by),
                   bbox_to_anchor=(0.98, 0.02))  # 右下角位置
    elif is_node_mode and not use_random_nodes and 'sc' in locals():
        # 连续色图模式添加 colorbar
        active_axes = axes[:n_layers]
        fig.colorbar(sc, ax=active_axes, orientation='vertical', fraction=0.02, pad=0.04, label='Node ID')

    out_png = os.path.join(out_dir, f"clustering_{task_suffix}_{cluster_by_suffix}_{args.ckpt_iter}{nls_suffix}.png")
    plt.savefig(out_png, dpi=300, bbox_inches='tight')
    plt.close()
    print(f"Plot saved to {out_png}")


if __name__ == "__main__":
    main()