| import os
|
| import argparse
|
| import pickle
|
| import torch
|
| import numpy as np
|
| import random
|
| import networkx as nx
|
| import matplotlib.pyplot as plt
|
| import math
|
| from tqdm import tqdm
|
| from torch.nn.utils.rnn import pad_sequence
|
| from sklearn.decomposition import PCA
|
| from sklearn.metrics.pairwise import cosine_similarity
|
|
|
|
|
| from model.transformer import GPTConfig, GPT
|
| from cli_utils import parse_count, format_count
|
|
|
|
|
| def parse_args():
|
| parser = argparse.ArgumentParser(
|
| description='Visualize hidden states for multiple tasks clustered by current node using PCA.')
|
|
|
|
|
| parser.add_argument('--ckpt_iter', type=int, default=10000)
|
| parser.add_argument('--config', type=str, default='6_6_384')
|
| 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="5M")
|
| parser.add_argument('--tasks', type=str, default='A1C1', help='Tasks to visualize (e.g., A1E1, A1C1, A1B1, etc.). Format: Task1[1-9]Task2[1-9]...')
|
| 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='store_true', default=False)
|
|
|
|
|
| parser.add_argument('--vis_samples', type=int, default=50000,
|
| help='Number of prefix sequences to extract and process.')
|
| parser.add_argument('--batch_size', type=int, default=100)
|
| parser.add_argument('--num_plot_nodes', type=int, default=10,
|
| help='Number of distinct nodes to color and plot (to avoid visual clutter).')
|
|
|
| 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 extract_taskA_prefixes(lines, stoi, max_samples, no_task_tag, grid_n, num_nodes):
|
| """
|
| 专门提取 Task A 的数据,并穷举路径上的每一步。
|
| 返回列表,每个元素为: {'ids': tensor, 'node': current_node, 'task': 'A'}
|
| """
|
| labels_chars = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'}
|
| 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:
|
|
|
| is_task_A = not any(c in labels_chars or c in {'L', 'R', 'F', 'T'} for c in parts)
|
| if not is_task_A: continue
|
| try:
|
| source = int(parts[0])
|
| except:
|
| continue
|
| else:
|
| if parts[0] != 'A': continue
|
| try:
|
| source = int(parts[1])
|
| except:
|
| continue
|
|
|
| actions = parts[colon_idx + 1:]
|
| if not actions: continue
|
|
|
| try:
|
| token_ids = [stoi[t] for t in parts]
|
| except KeyError:
|
| continue
|
|
|
| curr = source
|
|
|
|
|
| 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
|
|
|
| prefix_ids = token_ids[:colon_idx + 2 + i]
|
| data.append({'ids': torch.tensor(prefix_ids, dtype=torch.long), 'node': curr, 'task': 'A'})
|
|
|
| if len(data) >= max_samples:
|
| break
|
|
|
| return data
|
|
|
|
|
| def extract_taskE_prefixes(lines, stoi, max_samples, no_task_tag, grid_n, num_nodes):
|
| """
|
| 专门提取 Task E 的数据,并穷举路径上的每一对 (dir, label)。
|
| 返回列表,每个元素为: {'ids': tensor, 'node': current_node, 'task': 'E'}
|
| """
|
| labels_chars = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'}
|
| 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:
|
|
|
| is_task_E = any(c in labels_chars for c in parts[colon_idx + 1:])
|
| if not is_task_E: continue
|
| try:
|
| source = int(parts[0])
|
| target = int(parts[1])
|
| except:
|
| continue
|
| else:
|
| if parts[0] != 'E': continue
|
| try:
|
| source = int(parts[1])
|
| target = int(parts[2])
|
| except:
|
| continue
|
|
|
| actions = parts[colon_idx + 1:]
|
| if len(actions) < 2: continue
|
|
|
| try:
|
| token_ids = [stoi[t] for t in parts]
|
| except KeyError:
|
| continue
|
|
|
|
|
| curr = source
|
| dirs_map = {'N': -grid_n, 'S': grid_n, 'E': 1, 'W': -1}
|
|
|
| for step in range(0, len(actions), 2):
|
| if step >= len(actions) - 1:
|
| break
|
|
|
| direction = actions[step]
|
| label = actions[step + 1]
|
|
|
| if direction not in dirs_map or label not in labels_chars:
|
| break
|
|
|
| curr += dirs_map[direction]
|
| if not (0 <= curr < num_nodes):
|
| break
|
|
|
|
|
| prefix_ids = token_ids[:colon_idx + 2 + step + 2]
|
| data.append({'ids': torch.tensor(prefix_ids, dtype=torch.long), 'node': curr, 'task': 'E'})
|
|
|
| if len(data) >= max_samples:
|
| break
|
|
|
| return data
|
|
|
|
|
| def extract_taskC_prefixes(lines, stoi, max_samples, no_task_tag, grid_n, num_nodes):
|
| """
|
| 专门提取 Task C 的数据,并穷举路径上的每一个相对转向操作。
|
| Task C:起始方向东方(E),每个操作(L/R/F/T)既转向又移动一步。
|
| 返回列表,每个元素为: {'ids': tensor, 'node': current_node, 'task': 'C'}
|
| """
|
| data = []
|
|
|
| lines = list(lines)
|
| random.shuffle(lines)
|
|
|
|
|
| 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}
|
|
|
| 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:
|
|
|
| actions_part = parts[colon_idx + 1:]
|
| is_task_C = any(c in {'L', 'R', 'F', 'T'} for c in actions_part)
|
| if not is_task_C: continue
|
| try:
|
| source = int(parts[0])
|
| target = int(parts[1])
|
| except:
|
| continue
|
| else:
|
| if parts[0] != 'C': continue
|
| try:
|
| source = int(parts[1])
|
| target = int(parts[2])
|
| except:
|
| continue
|
|
|
| actions = parts[colon_idx + 1:]
|
| if not actions: continue
|
|
|
| try:
|
| token_ids = [stoi[t] for t in parts]
|
| except KeyError:
|
| continue
|
|
|
|
|
| curr = source
|
| orientation = 'E'
|
|
|
|
|
| for i, action in enumerate(actions):
|
| if action not in {'L', 'R', 'F', 'T'}:
|
| 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
|
|
|
|
|
| prefix_ids = token_ids[:colon_idx + 2 + i]
|
| data.append({'ids': torch.tensor(prefix_ids, dtype=torch.long), 'node': curr, 'task': 'C'})
|
|
|
| if len(data) >= max_samples:
|
| break
|
|
|
| return data
|
|
|
|
|
| activations = {}
|
|
|
|
|
| def get_layer_hook(layer_idx):
|
| def hook(model, input, output):
|
| activations[layer_idx] = output.detach()
|
|
|
| return hook
|
|
|
|
|
| def main():
|
| args = parse_args()
|
| seed = 42
|
| 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"
|
|
|
| data_dir = f'data/maze/{args.num_nodes}'
|
| nt_suffix = '_NT' if args.no_task_tag else ''
|
| out_dir = f'out/transformer/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]
|
|
|
|
|
| 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_{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)
|
| conf = GPTConfig(**checkpoint['model_args'])
|
|
|
| if args.local: conf.use_flash = False
|
|
|
| model = GPT(conf)
|
| model.load_state_dict({k.replace('_orig_mod.', ''): v for k, v in checkpoint['model'].items()})
|
| model.to(args.device).eval()
|
| for p in model.parameters(): p.requires_grad = False
|
|
|
|
|
| for i in range(conf.n_layer):
|
| model.transformer.h[i].register_forward_hook(get_layer_hook(i))
|
|
|
|
|
| model.transformer.ln_f.register_forward_hook(get_layer_hook('ln_f'))
|
|
|
|
|
| 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')])
|
|
|
|
|
|
|
| tasks_to_extract = []
|
| task_str = args.tasks
|
| i = 0
|
| while i < len(task_str):
|
| if task_str[i].isalpha():
|
| task_type = task_str[i]
|
| if i + 1 < len(task_str) and task_str[i+1].isdigit():
|
| task_num = int(task_str[i+1])
|
| tasks_to_extract.append((task_type, task_num))
|
| i += 2
|
| else:
|
| i += 1
|
| else:
|
| i += 1
|
|
|
| print(f"Extracting tasks from: {train_txt}")
|
| print(f"Tasks to extract: {tasks_to_extract}")
|
|
|
| dataset = []
|
| dataset_counts = {}
|
| lines = load_lines(train_txt)
|
| samples_per_task = args.vis_samples // len(tasks_to_extract) if tasks_to_extract else 0
|
|
|
| for task_type, task_num in tasks_to_extract:
|
| if task_type == 'A':
|
| dataset_A = extract_taskA_prefixes(lines, stoi, samples_per_task,
|
| args.no_task_tag, grid_n, args.num_nodes)
|
| dataset.extend(dataset_A)
|
| dataset_counts['A'] = len(dataset_A)
|
| print(f"Successfully extracted {len(dataset_A)} Task A samples.")
|
| elif task_type == 'E':
|
| dataset_E = extract_taskE_prefixes(lines, stoi, samples_per_task,
|
| args.no_task_tag, grid_n, args.num_nodes)
|
| dataset.extend(dataset_E)
|
| dataset_counts['E'] = len(dataset_E)
|
| print(f"Successfully extracted {len(dataset_E)} Task E samples.")
|
| elif task_type == 'C':
|
| dataset_C = extract_taskC_prefixes(lines, stoi, samples_per_task,
|
| args.no_task_tag, grid_n, args.num_nodes)
|
| dataset.extend(dataset_C)
|
| dataset_counts['C'] = len(dataset_C)
|
| print(f"Successfully extracted {len(dataset_C)} Task C samples.")
|
|
|
| random.shuffle(dataset)
|
| print(f"Total: {len(dataset)} prefix samples.\n")
|
|
|
|
|
| all_feats = {i: [] for i in range(conf.n_layer)}
|
| all_feats['ln_f'] = []
|
| node_labels = []
|
| task_labels = []
|
|
|
| for i in tqdm(range(0, len(dataset), args.batch_size), desc="Running Inference"):
|
| batch = dataset[i: i + args.batch_size]
|
|
|
| x_padded = pad_sequence([item['ids'] for item in batch], batch_first=True, padding_value=0).to(args.device)
|
|
|
| with torch.no_grad():
|
| model(x_padded)
|
|
|
| for lk in all_feats.keys():
|
| if lk not in activations:
|
| continue
|
| out = activations[lk]
|
| for j, item in enumerate(batch):
|
|
|
| all_feats[lk].append(out[j, len(item['ids']) - 1, :].cpu().numpy())
|
|
|
| for item in batch:
|
| node_labels.append(item['node'])
|
| task_labels.append(item['task'])
|
|
|
| node_labels = np.array(node_labels)
|
| task_labels = np.array(task_labels)
|
|
|
|
|
|
|
| unique_nodes, counts = np.unique(node_labels, return_counts=True)
|
| top_indices = np.argsort(-counts)[:args.num_plot_nodes]
|
| target_nodes = unique_nodes[top_indices]
|
|
|
| print(f"\nSelected top {args.num_plot_nodes} nodes for visualization: {target_nodes}")
|
|
|
|
|
| mask = np.isin(node_labels, target_nodes)
|
| filtered_labels = node_labels[mask]
|
| filtered_tasks = task_labels[mask]
|
|
|
|
|
| cmap = plt.get_cmap('tab10') if args.num_plot_nodes <= 10 else plt.get_cmap('tab20')
|
| color_map = {node: cmap(i / len(target_nodes)) for i, node in enumerate(target_nodes)}
|
|
|
|
|
| task_markers = {'A': 'o', 'E': '^', 'C': 's', 'D': 'P', 'F': 'X', 'G': 'D'}
|
| unique_tasks = np.unique(task_labels)
|
|
|
|
|
| print(f"\nApplying PCA and Plotting...")
|
| cols = min(3, conf.n_layer + 1)
|
| rows = math.ceil((conf.n_layer + 1) / cols)
|
| fig, axes = plt.subplots(rows, cols, figsize=(5 * cols + 2, 4 * rows))
|
|
|
| if conf.n_layer + 1 == 1:
|
| axes = [axes]
|
| else:
|
| axes = axes.flatten()
|
|
|
| first_ax_handles = []
|
|
|
|
|
| for l in range(conf.n_layer):
|
| feats = np.array(all_feats[l])[mask]
|
|
|
|
|
| pca = PCA(n_components=2, random_state=42)
|
| feats_2d = pca.fit_transform(feats)
|
|
|
| ax = axes[l]
|
|
|
| for node in target_nodes:
|
| for task in unique_tasks:
|
| idx = (filtered_labels == node) & (filtered_tasks == task)
|
| if np.sum(idx) > 0:
|
| marker = task_markers.get(task, 'o')
|
| ax.scatter(feats_2d[idx, 0], feats_2d[idx, 1],
|
| marker=marker, color=color_map[node], alpha=0.7, s=20)
|
| if l == 0:
|
| first_ax_handles.append(plt.Line2D([0], [0], marker=marker, color='w',
|
| markerfacecolor=color_map[node], markersize=8))
|
|
|
| ax.set_title(f'Layer {l}')
|
| ax.set_xticks([])
|
| ax.set_yticks([])
|
|
|
|
|
| ax_norm = axes[conf.n_layer]
|
|
|
|
|
| feats_ln_f = np.array(all_feats['ln_f'])[mask]
|
|
|
| pca_norm = PCA(n_components=2, random_state=42)
|
| feats_2d_norm = pca_norm.fit_transform(feats_ln_f)
|
|
|
| for node in target_nodes:
|
| for task in unique_tasks:
|
| idx = (filtered_labels == node) & (filtered_tasks == task)
|
| if np.sum(idx) > 0:
|
| marker = task_markers.get(task, 'o')
|
| ax_norm.scatter(feats_2d_norm[idx, 0], feats_2d_norm[idx, 1],
|
| marker=marker, color=color_map[node], alpha=0.7, s=20)
|
|
|
| ax_norm.set_title(f'Layer Final (Norm)')
|
| ax_norm.set_xticks([])
|
| ax_norm.set_yticks([])
|
|
|
|
|
| legend_handles = []
|
| for node in target_nodes:
|
| for task in sorted(unique_tasks):
|
| marker = task_markers.get(task, 'o')
|
| legend_handles.append(plt.Line2D([0], [0], marker=marker, color='w',
|
| markerfacecolor=color_map[node], markersize=8, label=f'Node {node} (Task {task})'))
|
|
|
| fig.legend(handles=legend_handles, loc='center right', bbox_to_anchor=(1.02, 0.5), title="Current Node & Task")
|
| plt.subplots_adjust(right=0.85)
|
|
|
|
|
| for l in range(conf.n_layer + 1, len(axes)):
|
| fig.delaxes(axes[l])
|
|
|
|
|
| task_suffix = ''.join([t for t, _ in tasks_to_extract])
|
| output_png = os.path.join(out_dir, f"vis_{task_suffix}_nodes_iter{args.ckpt_iter}.png")
|
| fig.savefig(output_png, dpi=300, bbox_inches='tight')
|
| plt.close(fig)
|
|
|
| print(f"Visualization successfully saved to: {output_png}")
|
|
|
|
|
| print("\n" + "="*100)
|
| print("Similarity Statistics (Cosine Similarity)")
|
| print("="*100)
|
|
|
|
|
| n_total_samples = len(task_labels)
|
| sample_rate = 0.1
|
| n_samples_to_use = max(1, int(n_total_samples * sample_rate))
|
| sample_indices = np.random.choice(n_total_samples, size=n_samples_to_use, replace=False)
|
| print(f"Using {n_samples_to_use} out of {n_total_samples} samples ({sample_rate*100:.0f}%)")
|
|
|
|
|
| layer_keys = list(range(conf.n_layer)) + ['ln_f']
|
|
|
| for layer_key in layer_keys:
|
| if layer_key not in all_feats:
|
| continue
|
|
|
| feats_all = np.array(all_feats[layer_key])
|
| feats = feats_all[sample_indices]
|
| sampled_task_labels = [task_labels[i] for i in sample_indices]
|
| sampled_node_labels = [node_labels[i] for i in sample_indices]
|
|
|
| if layer_key == 'ln_f':
|
| layer_name = "Layer Final (Norm)"
|
| else:
|
| layer_name = f"Layer {layer_key}"
|
|
|
|
|
|
|
| stats = {}
|
|
|
|
|
| print(f" Computing similarity matrix for {layer_name}...")
|
| sim_matrix = cosine_similarity(feats)
|
|
|
|
|
| n_samples = len(feats)
|
| for i in range(n_samples):
|
| for j in range(i + 1, n_samples):
|
| sim = sim_matrix[i, j]
|
|
|
| task_i = sampled_task_labels[i]
|
| task_j = sampled_task_labels[j]
|
| node_i = sampled_node_labels[i]
|
| node_j = sampled_node_labels[j]
|
| same_node = bool(node_i == node_j)
|
|
|
|
|
| if task_i == task_j:
|
| task_pair = task_i
|
| else:
|
| task_pair = f"{task_i}_vs_{task_j}" if task_i < task_j else f"{task_j}_vs_{task_i}"
|
|
|
| kind = 'same' if same_node else 'diff'
|
| key = (task_pair, kind)
|
| if key not in stats:
|
| stats[key] = []
|
| stats[key].append(sim)
|
|
|
|
|
| print(f"\n{layer_name}:")
|
|
|
|
|
| single_pairs = sorted({tp for tp, _ in stats.keys() if '_vs_' not in tp})
|
| cross_pairs = sorted({tp for tp, _ in stats.keys() if '_vs_' in tp})
|
| task_pairs = single_pairs + cross_pairs
|
|
|
| for tp in task_pairs:
|
| same_vals = stats.get((tp, 'same'), [])
|
| diff_vals = stats.get((tp, 'diff'), [])
|
| mean_same = np.mean(same_vals) if same_vals else 0.0
|
| mean_diff = np.mean(diff_vals) if diff_vals else 0.0
|
| n_same = len(same_vals)
|
| n_diff = len(diff_vals)
|
|
|
|
|
| if '_vs_' in tp:
|
| t1, t2 = tp.split('_vs_')
|
| label = f"Task {t1} vs {t2}"
|
| else:
|
| label = f"Task {tp} "
|
|
|
| print(f" {label} - Same: {mean_same:7.4f} (n={n_same:7d}) | Diff: {mean_diff:7.4f} (n={n_diff:7d})")
|
|
|
| print("="*100)
|
|
|
|
|
| if __name__ == "__main__":
|
| main() |