| 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
|
|
|
|
|
| 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).')
|
|
|
|
|
| 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)')
|
|
|
|
|
| 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)')
|
|
|
|
|
| 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.')
|
|
|
|
|
| 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.')
|
|
|
|
|
| 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.')
|
|
|
|
|
| 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':
|
|
|
| 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:
|
| 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)
|
|
|
| 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':
|
|
|
| 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:
|
|
|
| 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'):
|
|
|
|
|
|
|
| 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'
|
|
|
| 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_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
|
| conf = MambaConfig(**margs); model = Mamba(conf)
|
| elif ckpt_model_type == 'mamba2':
|
| if local and 'use_cuda' in margs:
|
| margs['use_cuda'] = False
|
| 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()
|
|
|
|
|
| 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'
|
|
|
|
|
| if args.cluster_by == 'taskE_token_type':
|
| args.probe_tasks = 'E'
|
|
|
| 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"
|
|
|
| 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)
|
|
|
| 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'])
|
|
|
| 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]
|
|
|
| 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_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()
|
|
|
|
|
| is_node_mode = (args.cluster_by == 'node')
|
| use_random_nodes = False
|
| selected_nodes = None
|
| node_mask_for_vis = None
|
| node_to_wall_types = None
|
|
|
| if is_node_mode and args.vis_num_nodes > 0:
|
| unique_nodes = np.unique(filtered_labels)
|
| if len(unique_nodes) > args.vis_num_nodes:
|
|
|
| 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]
|
|
|
|
|
| feats_all = np.array(all_feats[l])[mask]
|
|
|
| if use_random_nodes and args.pca_full_data:
|
|
|
|
|
| if feats_all.shape[0] > 2000:
|
|
|
| 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)
|
|
|
| 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:
|
|
|
| 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
|
|
|
|
|
| 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:
|
|
|
|
|
| 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():
|
|
|
| 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() |