import os import argparse import pickle import torch import torch.nn as nn import torch.optim as optim 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 # Import project modules from model.transformer import GPTConfig, GPT from cli_utils import parse_count, format_count def parse_args(): parser = argparse.ArgumentParser(description='Linear Probe Test: Node Representation Analysis.') # --- Model & Data Configuration --- parser.add_argument('--ckpt_iter', type=int, default=10000, help='Checkpoint iteration to load') parser.add_argument('--config', type=str, default='12_6_384', help='Model configuration string (e.g., 1_1_120)') parser.add_argument('--device', type=str, default='cuda:0', help='Device to use (e.g., cuda:0, cpu)') parser.add_argument('--num_nodes', type=int, default=100, help='Number of nodes in the maze grid') parser.add_argument('--num_of_paths', type=int, default=20, help='Number of paths used in single-task data naming') parser.add_argument('--multitasks', action=argparse.BooleanOptionalAction, default=True, help='Use multitask data logic (default: True)') parser.add_argument('--num_train_dataset', type=parse_count, default='10M', help='Number of multitask training entries (supports K/M/B)') parser.add_argument('--num_test_dataset', type=parse_count, default=10000, help='Number of multitask test entries (supports K/M/B)') parser.add_argument('--tasks', type=str, default='C1', help='Task specification for filename resolution (e.g., A1, A1E1)') parser.add_argument('--CL', action=argparse.BooleanOptionalAction, default=False, help='Task C turn-label mode flag') parser.add_argument('--path_type', type=str, default='RWs', choices=['RWc', 'RWa', 'RWs'], help='Path generation type: RWc (cyclic), RWa (acyclic), RWs (single source)') parser.add_argument('--no_task_tag', action='store_true', default=False, help='Data files do not contain task identifiers (A, B, etc.)') parser.add_argument('--local', action='store_true', default=False, help='Disable flash attention for local GPU compatibility') parser.add_argument('--NLS', action='store_true', default=False, help='Use NLS model checkpoint (adds _NLS suffix to checkpoint/output filenames)') # --- Probe Specific Configuration --- parser.add_argument('--probe_tasks', type=str, default='C', help='Which task identifier to probe (e.g., A, C or E)') parser.add_argument('--probe_target', type=str, default='current', choices=['current', 'source', 'target', 'rel_direction', 'dist_to_target', 'orientation', 'node_orientation', 'count_F', 'count_L', 'count_R', 'count_T', 'cum_disp_N', 'cum_disp_E', 'cum_disp_S', 'cum_disp_W', 'rot_sum', 'rot_sin', 'rot_cos']) parser.add_argument('--probe_train_samples', type=int, default=5000, help='Number of sequences (lines) to sample from training data for probe training') parser.add_argument('--probe_test_samples', type=int, default=1000, help='Number of sequences (lines) to sample from test data for probe evaluation') parser.add_argument('--probe_batch_size', type=int, default=64, help='Batch size for training the linear probe') parser.add_argument('--probe_epochs', type=int, default=5, help='Number of training epochs for the linear probe') parser.add_argument('--probe_lr', type=float, default=1e-2, help='Learning rate for the linear probe optimizer') parser.add_argument('--probe_eval_bootstrap_samples', type=int, default=100, help='Number of bootstrap samples for standard error estimation') parser.add_argument('--probe_eval_on', type=str, default='test', choices=['train', 'test'], help='Evaluate on training set ("train") or test set ("test") (default: test)') # --- Position-wise heatmap plot --- parser.add_argument('--probe_test_seq_len', type=int, default=None, help='Optional: calculate per-position accuracy for sequences of this specific step length') parser.add_argument('--plot_with_tokens', action='store_true', default=True, help='If True, randomly select a valid sequence and use its tokens as X-axis labels in the heatmap. ' 'The heatmap data will also be restricted to this single sequence.') # --- Accuracy-by-distance plot --- parser.add_argument('--plot_acc_by_dist', action=argparse.BooleanOptionalAction, default=False, help='If True, additionally plot probe accuracy as a function of graph shortest-path distance ' 'from the current node to the target node. Only meaningful for classification probes ' '(e.g. --probe_target target/current). One curve per layer.') parser.add_argument('--plot_acc_by_dist_metric', type=str, default='graph', choices=['graph', 'manhattan'], help='Distance metric used for --plot_acc_by_dist bucketing.') parser.add_argument('--plot_acc_by_dist_min_bucket', type=int, default=20, help='Minimum number of samples a distance bucket must contain to be plotted.') # --- Task C additions --- parser.add_argument('--probe_current_orientation', action=argparse.BooleanOptionalAction, default=False, help='Task C only: probe the agent\'s CURRENT absolute orientation (N/E/S/W) after each step. ' 'Overrides --probe_target when set. 4-class classification.') parser.add_argument('--probe_node_orientation', action=argparse.BooleanOptionalAction, default=True, help='Task C only: jointly probe (current_node, current_orientation). ' 'Overrides --probe_target when set. (num_nodes * 4)-class classification, ' 'label = node * 4 + ori_cls with ori_cls in {N:0, E:1, S:2, W:3}.') parser.add_argument('--probe_node_orientation_split', action=argparse.BooleanOptionalAction, default=False, help='Task C + --probe_node_orientation only: at evaluation time, split probe accuracy by ' '(prev_action, curr_action) buckets in {T, FLR} x {T, FLR} and also report Overall. ' 'Probe is still trained on the full (no-filter) pool; bucketing happens only during eval.') # --- 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.') # --- Probe MLP architecture --- parser.add_argument('--probe_num_layers', type=int, default=1, help='Number of layers in the probe MLP. 1 = single linear layer (default); ' '>=2 adds hidden layers with ReLU activations.') parser.add_argument('--probe_hidden_dim', type=int, default=None, help='Hidden dimension for the probe MLP when --probe_num_layers > 1. ' 'Defaults to the input embedding dimension.') # --- Non-linear (GELU) probe form --- parser.add_argument('--probe_gelu_mlp', action='store_true', default=False, help='Use a 2-layer non-linear probe of the form ' 'Linear -> GELU -> Linear (state -> hidden -> num_classes), then align ' 'directly to the one-hot label. Overrides --probe_num_layers (forced to 2) ' 'and --probe_activation (forced to gelu).') parser.add_argument('--probe_activation', type=str, default='relu', choices=['relu', 'gelu'], help='Activation used between probe MLP layers when --probe_num_layers > 1.') # --- Control baseline & residual-stream split --- parser.add_argument('--random_init', action='store_true', default=False, help='If set, use a randomly-initialized model (same architecture as the checkpoint) ' 'instead of loading the trained weights. Useful as a control baseline for probing.') parser.add_argument('--probe_sublayer_split', action=argparse.BooleanOptionalAction, default=False, help='If set, probe BOTH the post-attn residual stream AND the post-mlp residual stream ' 'inside every transformer block (instead of just the block output). ' 'Doubles the number of probe positions per layer.') return parser.parse_args() class LinearProbe(nn.Module): """Linear or MLP probe classifier/regressor.""" def __init__(self, input_dim, num_classes, num_layers=1, hidden_dim=None, activation='relu'): super().__init__() if num_layers < 1: raise ValueError(f"num_layers must be >= 1, got {num_layers}") def make_act(): if activation == 'gelu': return nn.GELU() elif activation == 'relu': return nn.ReLU() raise ValueError(f"Unknown activation: {activation}") if num_layers == 1: self.linear = nn.Linear(input_dim, num_classes) else: h = hidden_dim if hidden_dim is not None else input_dim layers = [nn.Linear(input_dim, h), make_act()] for _ in range(num_layers - 2): layers += [nn.Linear(h, h), make_act()] layers.append(nn.Linear(h, num_classes)) self.linear = nn.Sequential(*layers) def forward(self, x): return self.linear(x) 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 parse_line_for_probe(line, target_task, probe_target, stoi, no_task_tag, num_nodes, n, taskE_probe_type, maze_graph, model=None, device=None, itos=None): """Parses lines and tracks requested information using model predictions for alignment.""" parts = line.split() if ':' not in parts: return None colon_idx = parts.index(':') labels_chars = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'} turn_chars = {'L', 'R', 'F', 'T'} # Determine Task ID and source/target nodes try: if no_task_tag: action_tokens = parts[colon_idx + 1:] if any(c in turn_chars for c in action_tokens): task_id = 'C' elif len(parts) > colon_idx + 2 and parts[colon_idx + 2] in labels_chars: task_id = 'E' else: task_id = 'A' source_node = int(parts[0]) target_node = int(parts[1]) else: task_id = parts[0] if task_id not in ['A', 'E', 'C']: return None source_node = int(parts[1]) target_node = int(parts[2]) except (ValueError, IndexError): return None if task_id != target_task: return None try: token_ids = [stoi[t] for t in parts if t in stoi] if len(token_ids) < len(parts): return None labels = [] probe_indices = [] extra_info = [] # 用于存储额外信息,例如预测的 label current_nodes = [] # 新增:用于存储当前走到的节点 prev_acts = [] # Task C only: previous action token at each probe point ('F','L','R','T' or None for i==0) curr_acts = [] # Task C only: current (just-executed) action token at each probe point tgt_x = target_node % n tgt_y = target_node // n # Task C orientation -> class index (used when probe_target == 'orientation') ORIENT_TO_CLS = {'N': 0, 'E': 1, 'S': 2, 'W': 3} def get_label(c_node, orient=None, counts=None, cum_disp=None, rot_sum=None): if probe_target == 'current': return c_node elif probe_target == 'source': return source_node elif probe_target == 'target': return target_node elif probe_target == 'rel_direction': cur_x = c_node % n cur_y = c_node // n return [float(tgt_x - cur_x), float(tgt_y - cur_y)] elif probe_target == 'orientation': # Task C: absolute orientation o_i after the i-th step (4-class N/E/S/W) return ORIENT_TO_CLS[orient] if orient is not None else 0 elif probe_target == 'node_orientation': # Task C: joint (node, orientation) -> num_nodes * 4 classes ori_cls = ORIENT_TO_CLS[orient] if orient is not None else 0 return c_node * 4 + ori_cls elif probe_target in ('count_F', 'count_L', 'count_R', 'count_T'): key = probe_target.split('_')[1] return [float(counts.get(key, 0)) if counts is not None else 0.0] elif probe_target in ('cum_disp_N', 'cum_disp_E', 'cum_disp_S', 'cum_disp_W'): key = probe_target.split('_')[-1] return [float(cum_disp.get(key, 0)) if cum_disp is not None else 0.0] elif probe_target == 'rot_sum': # Task C: un-modded cumulative rotation sum (F=0, L=-1, R=+1, T=+2). # orientation_i = (1 + rot_sum_i) mod 4, so this is the pre-mod register. return [float(rot_sum) if rot_sum is not None else 0.0] elif probe_target == 'rot_sin': rs = float(rot_sum) if rot_sum is not None else 0.0 return [float(np.sin(np.pi / 2.0 * rs))] elif probe_target == 'rot_cos': rs = float(rot_sum) if rot_sum is not None else 0.0 return [float(np.cos(np.pi / 2.0 * rs))] else: # dist_to_target: Manhattan distance cur_x = c_node % n cur_y = c_node // n return [float(abs(tgt_x - cur_x) + abs(tgt_y - cur_y))] curr = source_node # --- 修改点:删除了原本在此处添加 colon_idx 的逻辑,强制从冒号后的动作开始截断 --- path_actions = parts[colon_idx + 1:] if len(path_actions) == 0: return None # 如果冒号后没有动作,直接舍弃该行 if task_id == 'A': for i, move in enumerate(path_actions): if move == 'N': curr -= n elif move == 'S': curr += n elif move == 'E': curr += 1 elif move == 'W': curr -= 1 if not (0 <= curr < num_nodes): return None labels.append(get_label(curr)) probe_indices.append(colon_idx + 1 + i) extra_info.append(None) current_nodes.append(curr) # 记录当前节点 prev_acts.append(None) curr_acts.append(None) elif task_id == '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': -n, 'S': n, 'E': 1, 'W': -1} orientation = 'E' def apply_turn(o, a): if a == 'F': return o if a == 'L': return left_of[o] if a == 'R': return right_of[o] if a == 'T': return opposite_of[o] return None # Cumulative action counts (Stage 1 inputs) and cumulative displacement counts (Stage 2 inputs) counts = {'F': 0, 'L': 0, 'R': 0, 'T': 0} cum_disp = {'N': 0, 'E': 0, 'S': 0, 'W': 0} # Un-modded cumulative rotation sum (F=0, L=-1, R=+1, T=+2). orientation_i = (1 + rot_sum) mod 4. rot_value = {'F': 0, 'L': -1, 'R': 1, 'T': 2} rot_sum = 0 for i, action in enumerate(path_actions): if action not in turn_chars: return None next_orientation = apply_turn(orientation, action) next_node = curr + delta[next_orientation] if not (0 <= next_node < num_nodes): return None orientation = next_orientation curr = next_node counts[action] += 1 cum_disp[orientation] += 1 rot_sum += rot_value[action] prev_a = path_actions[i - 1] if i > 0 else None labels.append(get_label(curr, orient=orientation, counts=counts, cum_disp=cum_disp, rot_sum=rot_sum)) probe_indices.append(colon_idx + 1 + i) extra_info.append(orientation) # 记录当前朝向,方便调试 current_nodes.append(curr) prev_acts.append(prev_a) curr_acts.append(action) elif task_id == 'E': skip_simulation = (probe_target in ['target', 'source']) inference_ready = (not skip_simulation and taskE_probe_type == 'dir' and model is not None and device is not None) for i in range(0, len(path_actions), 2): direction = path_actions[i] if i + 1 >= len(path_actions): break # 若仅需要 Target/Source, 可完全跳过模型推理和走步模拟以大幅加速 if skip_simulation: target_lab = path_actions[i + 1] if taskE_probe_type == 'dir': labels.append(get_label(curr)) probe_indices.append(colon_idx + 1 + i) extra_info.append(target_lab) current_nodes.append("N/A") prev_acts.append(None) curr_acts.append(None) elif taskE_probe_type == 'label': labels.append(get_label(curr)) probe_indices.append(colon_idx + 2 + i) extra_info.append(target_lab) current_nodes.append("N/A") prev_acts.append(None) curr_acts.append(None) continue # --- 确定目标标签 (Target Label) --- if inference_ready: current_seq_len = colon_idx + 1 + i + 1 input_seq = torch.tensor([token_ids[:current_seq_len]], dtype=torch.long, device=device) with torch.no_grad(): output = model(input_seq) if isinstance(output, tuple): logits = output[0] else: logits = output last_token_logits = logits[0, -1, :] pred_token_id = torch.argmax(last_token_logits).item() target_lab = itos.get(pred_token_id, '') else: target_lab = path_actions[i + 1] # --- 模拟行走 --- step_count = 0 temp_curr = curr found = False while True: if direction == 'N': temp_curr -= n elif direction == 'S': temp_curr += 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 node_label = maze_graph.nodes[str(temp_curr)]['label'] if node_label == target_lab: curr = temp_curr found = True break if not found: return None if taskE_probe_type == 'dir': labels.append(get_label(curr)) probe_indices.append(colon_idx + 1 + i) extra_info.append(target_lab) current_nodes.append(curr) # 记录当前节点 prev_acts.append(None) curr_acts.append(None) elif taskE_probe_type == 'label': labels.append(get_label(curr)) probe_indices.append(colon_idx + 2 + i) extra_info.append(target_lab) current_nodes.append(curr) # 记录当前节点 prev_acts.append(None) curr_acts.append(None) # 如果最终没有收集到任何有效的探测点,返回 None if not labels: return None return token_ids, labels, probe_indices, extra_info, current_nodes, prev_acts, curr_acts except (ValueError, IndexError): return None def get_probe_data(lines, target_task, probe_target, num_samples, stoi, no_task_tag, num_nodes, n, taskE_probe_type, device, maze_graph, model=None, itos=None): candidates = [] labels_chars = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'} indices = np.random.permutation(len(lines)) target_count = int(num_samples * 2) print(f"Selecting {num_samples} candidate lines for Task {target_task}...") for idx in indices: line = lines[idx] parts = line.split() if ':' not in parts: continue colon_idx = parts.index(':') try: if no_task_tag: action_tokens = parts[colon_idx + 1:] turn_chars = {'L', 'R', 'F', 'T'} 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' else: line_task = parts[0] if line_task == target_task: candidates.append(line) if len(candidates) >= target_count: break except: continue data = [] total_probe_points = 0 for line in tqdm(candidates, desc="Processing Candidates (Model Inference)", leave=False): if len(data) >= num_samples: break parsed = parse_line_for_probe(line, target_task, probe_target, stoi, no_task_tag, num_nodes, n, taskE_probe_type, maze_graph, model, device, itos) if parsed: ids, labels, probe_indices, extra_info, current_nodes, prev_acts, curr_acts = parsed total_probe_points += len(labels) # Re-parse target_node from the line for distance bucketing _parts = line.split() try: _colon = _parts.index(':') if no_task_tag: _tgt_node = int(_parts[1]) else: _tgt_node = int(_parts[2]) except (ValueError, IndexError): _tgt_node = None data.append({'ids': torch.tensor(ids, dtype=torch.long, device=device), 'labels': labels, 'probe_indices': probe_indices, 'extra_info': extra_info, 'current_nodes': current_nodes, 'prev_acts': prev_acts, 'curr_acts': curr_acts, 'target_node': _tgt_node}) print(f" [debug] sequences={len(data)} | total probe points={total_probe_points}") return data activations = {} def get_activation_hook(name): def hook(model, input, output): activations[name] = output.detach() return hook def get_input_activation_hook(name): """Forward pre-hook: capture the FIRST positional input to the module. Useful for grabbing the residual stream just BEFORE a sublayer normalization, which equals the post-(previous-sublayer) residual stream. """ def hook(model, inputs): activations[name] = inputs[0].detach() return hook def bootstrap_accuracy(preds, labels, n_bootstrap=100): n_samples = len(preds) accuracies = [] for _ in range(n_bootstrap): indices = np.random.choice(n_samples, n_samples, replace=True) acc = np.mean(preds[indices] == labels[indices]) accuracies.append(acc) return float(np.mean(accuracies)), float(np.std(accuracies)) def calculate_r2(y_pred, y_true): ss_res = np.sum((y_true - y_pred) ** 2) ss_tot = np.sum((y_true - np.mean(y_true, axis=0)) ** 2) if ss_tot == 0: return 1.0 if ss_res == 0 else 0.0 return 1 - (ss_res / ss_tot) def pick_first_existing(candidates): for path in candidates: if os.path.exists(path): return path return candidates[0] def main(): args = parse_args() torch.manual_seed(42) np.random.seed(42) random.seed(42) grid_n = int(args.num_nodes ** 0.5) # --- Resolve probe MLP form override --- if args.probe_gelu_mlp: args.probe_num_layers = 2 args.probe_activation = 'gelu' print("[probe_gelu_mlp] Probe form: Linear -> GELU -> Linear (2-layer MLP, GELU activation).") tasks_tag = f"{args.tasks}_CL" if args.CL else args.tasks path_type_tag = args.path_type tasks_tag = f"{tasks_tag}_{path_type_tag}" if args.no_task_tag: tasks_tag += "_NT" graph_tag = f"{args.tasks}_CL" if args.CL else args.tasks graph_tag = f"{graph_tag}_{path_type_tag}" if args.no_task_tag: graph_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) # --- Resolve Task C probe overrides BEFORE building filenames --- _c_overrides = sum([bool(args.probe_current_orientation), bool(args.probe_node_orientation)]) if _c_overrides > 1: raise ValueError("--probe_current_orientation / --probe_node_orientation " "are mutually exclusive.") if args.probe_current_orientation: if args.probe_tasks != 'C': raise ValueError("--probe_current_orientation is only defined for Task C " f"(got --probe_tasks={args.probe_tasks}).") args.probe_target = 'orientation' if args.probe_node_orientation: if args.probe_tasks != 'C': raise ValueError("--probe_node_orientation is only defined for Task C " f"(got --probe_tasks={args.probe_tasks}).") args.probe_target = 'node_orientation' if args.probe_node_orientation_split and not args.probe_node_orientation: raise ValueError("--probe_node_orientation_split requires --probe_node_orientation.") eval_on_str = f"_eval_{args.probe_eval_on}" excl_tag = "" rand_tag = "_rand" if args.random_init else "" summary_path = os.path.join(out_dir, f"probe_{args.probe_target}_{args.probe_tasks}{args.taskE_probe_type if args.probe_tasks == 'E' else ''}_{tasks_tag}_{args.ckpt_iter}{eval_on_str}{excl_tag}{rand_tag}.txt") detailed_path = os.path.join(out_dir, f"probe_data_{args.probe_target}_{args.probe_tasks}{args.taskE_probe_type if args.probe_tasks == 'E' else ''}_{tasks_tag}_{args.ckpt_iter}{eval_on_str}{excl_tag}{rand_tag}.txt") meta_path = pick_first_existing( [os.path.join(data_dir, f'meta_{tasks_tag}.pkl'), os.path.join(data_dir, f'meta_{args.tasks}.pkl'), os.path.join(data_dir, 'meta.pkl')]) with open(meta_path, 'rb') as f: meta = pickle.load(f) stoi, itos = meta['stoi'], meta['itos'] if args.multitasks: maze_graph_path = pick_first_existing([ f'{data_dir}/maze_graph_{graph_tag}.graphml', f'{data_dir}/maze_graph_{args.tasks}.graphml', f'{data_dir}/maze_graph.graphml', ]) else: maze_graph_path = f'{data_dir}/maze_graph.graphml' print(f"Loading Graph from: {maze_graph_path}") maze_graph = nx.read_graphml(maze_graph_path) train_label = format_count(args.num_train_dataset) ckpt_path = pick_first_existing([ 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 checkpoint from: {ckpt_path}") checkpoint = torch.load(ckpt_path, map_location=args.device, weights_only=False) conf = GPTConfig(**checkpoint['model_args']) if args.local: conf.use_flash = False model = GPT(conf) if args.random_init: print("[random_init] Skipping checkpoint weights; using randomly-initialized model as control.") else: 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 print("Model loaded for data generation & probing.") train_txt = pick_first_existing([os.path.join(data_dir, f"train_{tasks_tag}_{train_label}.txt"), os.path.join(data_dir, f'train_{args.num_of_paths}.txt')]) test_txt = pick_first_existing( [os.path.join(data_dir, f"test_{tasks_tag}_{format_count(args.num_test_dataset)}.txt"), os.path.join(data_dir, 'test.txt')]) print(f"Preparing Probe Data | Task: {args.probe_tasks} | Target: {args.probe_target}...") if args.probe_target == 'orientation': print(f" [override] --probe_current_orientation enabled -> probe_target='orientation' (4-class N/E/S/W)") elif args.probe_target == 'node_orientation': print(f" [override] --probe_node_orientation enabled -> probe_target='node_orientation' " f"({args.num_nodes * 4}-class, label = node * 4 + ori_cls)") probe_train_data = get_probe_data(load_lines(train_txt), args.probe_tasks, args.probe_target, args.probe_train_samples, stoi, args.no_task_tag, args.num_nodes, grid_n, args.taskE_probe_type, args.device, maze_graph, model=model, itos=itos) probe_test_data = get_probe_data(load_lines(test_txt), args.probe_tasks, args.probe_target, args.probe_test_samples, stoi, args.no_task_tag, args.num_nodes, grid_n, args.taskE_probe_type, args.device, maze_graph, model=model, itos=itos) eval_data = probe_test_data if args.probe_eval_on == 'test' else probe_train_data print(f"Evaluating on {args.probe_eval_on} set ({len(eval_data)} sequences)") # --- Pre-select target sequence if plot_with_tokens is enabled --- target_seq_id = None n_seq_matching_len = 0 if args.probe_test_seq_len is not None: for idx, item in enumerate(eval_data): item['global_idx'] = idx valid_ids = [idx for idx, item in enumerate(eval_data) if len(item['labels']) == args.probe_test_seq_len] n_seq_matching_len = len(valid_ids) if args.plot_with_tokens and valid_ids: target_seq_id = random.choice(valid_ids) # ----------------------------------------------------------------- print(f"\n--- Ground Truth Verification (10 samples from {args.probe_eval_on} set) ---") verification_indices = random.sample(range(len(eval_data)), min(10, len(eval_data))) for idx in verification_indices: item = eval_data[idx] tokens = [itos[t.item()] for t in item['ids']] pos_in_labels = random.randint(0, len(item['labels']) - 1) p_idx = item['probe_indices'][pos_in_labels] prefix_str = " ".join(tokens[:p_idx + 1]) if args.probe_tasks == 'E' and args.taskE_probe_type == 'dir': extra_val = item['extra_info'][pos_in_labels] if extra_val and extra_val != "init": prefix_str += f" ({extra_val})" gt_val = item['labels'][pos_in_labels] print(f"Prefix: [{prefix_str}] -> Target: {gt_val}") print("-----------------------------------------------\n") results_per_layer = [] bucket_results_per_layer = [] heatmap_data = [] _count_targets = ('count_F', 'count_L', 'count_R', 'count_T') _cum_disp_targets = ('cum_disp_N', 'cum_disp_E', 'cum_disp_S', 'cum_disp_W') is_regression = (args.probe_target in ['rel_direction', 'dist_to_target', 'rot_sum', 'rot_sin', 'rot_cos'] or args.probe_target in _count_targets or args.probe_target in _cum_disp_targets) # Non-linear (gelu/relu) probes: train classification targets as one-hot regression (MSE) # instead of cross-entropy. Evaluation still uses argmax over the output vector. onehot_mse = (not is_regression) and (args.probe_num_layers >= 2) if onehot_mse: print(f"[onehot_mse] num_layers={args.probe_num_layers} ({args.probe_activation}) -> " f"training classification probe with MSE-to-one-hot instead of cross-entropy.") # Integer-valued regression targets: train with MSE but report rounded-integer accuracy use_round_acc = (args.probe_target == 'rot_sum') if args.probe_target == 'rel_direction': probe_out_dim = 2 elif args.probe_target == 'dist_to_target': probe_out_dim = 1 elif args.probe_target == 'rot_sum': probe_out_dim = 1 elif args.probe_target in ('rot_sin', 'rot_cos'): probe_out_dim = 1 elif args.probe_target in _count_targets or args.probe_target in _cum_disp_targets: probe_out_dim = 1 elif args.probe_target == 'orientation': probe_out_dim = 4 # N/E/S/W elif args.probe_target == 'node_orientation': probe_out_dim = args.num_nodes * 4 # (node, orientation) joint else: probe_out_dim = args.num_nodes # --- Pre-compute per-probe-point distance from current node to target node --- # eval_dist[seq_idx] = list[int|None] aligned with eval_data[seq_idx]['labels'] eval_dist = None if args.plot_acc_by_dist: if is_regression: print(f"[plot_acc_by_dist] Skipped: probe_target '{args.probe_target}' is regression, not classification.") args.plot_acc_by_dist = False else: print(f"[plot_acc_by_dist] Computing distances ({args.plot_acc_by_dist_metric}) for each probe point...") dist_cache = {} def _dist(u, v): if u is None or v is None or u == "N/A" or v == "N/A": return None try: u = int(u); v = int(v) except (ValueError, TypeError): return None if args.plot_acc_by_dist_metric == 'manhattan': ux, uy = u % grid_n, u // grid_n vx, vy = v % grid_n, v // grid_n return abs(ux - vx) + abs(uy - vy) key = (u, v) if u <= v else (v, u) if key in dist_cache: return dist_cache[key] try: d = nx.shortest_path_length(maze_graph, str(u), str(v)) except (nx.NetworkXNoPath, nx.NodeNotFound): d = None dist_cache[key] = d return d eval_dist = [] for item in eval_data: tgt = item.get('target_node') ds = [_dist(cn, tgt) for cn in item['current_nodes']] eval_dist.append(ds) n_valid = sum(1 for ds in eval_dist for d in ds if d is not None) print(f"[plot_acc_by_dist] Valid probe points with computable distance: {n_valid}") # Per-layer per-distance accumulators: dist_correct[layer_idx][d] = [n_correct, n_total] dist_acc_per_layer = [{} for _ in range(0)] # filled below once n_total_layers is known # 构建要 probe 的层列表:各个 transformer block + 最后的 LayerNorm (ln_f) # 每个元素:(display_name, module, hook_kind) # hook_kind: 'output' -> register_forward_hook (captures module output) # 'input' -> register_forward_pre_hook (captures module input; # used to grab post-attn residual via ln_2's input) if args.probe_sublayer_split: layer_targets = [] for i in range(conf.n_layer): # Post-attn residual stream = input to ln_2 (block i) layer_targets.append( (f"Layer {i + 1} post-attn", model.transformer.h[i].ln_2, 'input')) # Post-mlp residual stream = output of block i layer_targets.append( (f"Layer {i + 1} post-mlp", model.transformer.h[i], 'output')) else: layer_targets = [(f"Layer {i + 1}", model.transformer.h[i], 'output') for i in range(conf.n_layer)] layer_targets.append(("Layer Final (Norm)", model.transformer.ln_f, 'output')) n_total_layers = len(layer_targets) # Now that n_total_layers is known, allocate the per-layer distance accumulators. if args.plot_acc_by_dist: dist_acc_per_layer = [{} for _ in range(n_total_layers)] else: dist_acc_per_layer = None for layer_idx, (layer_name, layer_module, hook_kind) in enumerate(layer_targets): if hook_kind == 'input': hook_handle = layer_module.register_forward_pre_hook( get_input_activation_hook('current_layer')) else: hook_handle = layer_module.register_forward_hook( get_activation_hook('current_layer')) probe = LinearProbe(conf.n_embd, probe_out_dim, num_layers=args.probe_num_layers, hidden_dim=args.probe_hidden_dim, activation=args.probe_activation).to(args.device) optimizer = optim.Adam(probe.parameters(), lr=args.probe_lr) criterion = nn.MSELoss() if (is_regression or onehot_mse) else nn.CrossEntropyLoss() for epoch in range(args.probe_epochs): probe.train() perm = np.random.permutation(len(probe_train_data)) for b_start in range(0, len(probe_train_data), args.probe_batch_size): batch_items = [probe_train_data[i] for i in perm[b_start: b_start + args.probe_batch_size]] batch_items.sort(key=lambda x: len(x['ids']), reverse=True) x_padded = pad_sequence([item['ids'] for item in batch_items], batch_first=True, padding_value=0) with torch.no_grad(): model(x_padded) h_states = activations['current_layer'] p_in, p_tgt = [], [] for i, item in enumerate(batch_items): valid_h = h_states[i, item['probe_indices'], :] p_in.append(valid_h) if onehot_mse: lab = torch.tensor(item['labels'], dtype=torch.long, device=args.device) p_tgt.append(torch.nn.functional.one_hot(lab, num_classes=probe_out_dim).float()) else: target_type = torch.float if is_regression else torch.long p_tgt.append(torch.tensor(item['labels'], dtype=target_type, device=args.device)) if not p_in: continue optimizer.zero_grad() loss = criterion(probe(torch.cat(p_in, 0)), torch.cat(p_tgt, 0)) loss.backward() optimizer.step() probe.eval() all_preds, all_labels, layer_log_lines = [], [], [] pos_wise_matches = [] # For --probe_node_orientation_split: collect per-position (prev_act, curr_act) aligned with preds/labels. all_prev_acts, all_curr_acts = [], [] with torch.no_grad(): for b_start in range(0, len(eval_data), args.probe_batch_size): batch_items = eval_data[b_start: b_start + args.probe_batch_size] x_padded = pad_sequence([item['ids'] for item in batch_items], batch_first=True, padding_value=0) model(x_padded) h_states = activations['current_layer'] for i, item in enumerate(batch_items): valid_h = h_states[i, item['probe_indices'], :] out = probe(valid_h) actuals_raw = item['labels'] if is_regression: preds = out.cpu().numpy() actuals = np.array(actuals_raw) else: preds = torch.argmax(out, dim=1).cpu().numpy() actuals = np.array(actuals_raw) all_preds.append(preds) all_labels.append(actuals) if args.probe_node_orientation_split: all_prev_acts.extend(item.get('prev_acts', [None] * len(preds))) all_curr_acts.extend(item.get('curr_acts', [None] * len(preds))) # --- Accumulate per-distance accuracy for this layer --- if args.plot_acc_by_dist and eval_dist is not None and not is_regression: seq_global_idx = b_start + i ds = eval_dist[seq_global_idx] bucket = dist_acc_per_layer[layer_idx] for step_idx, d in enumerate(ds): if d is None: continue if d not in bucket: bucket[d] = [0, 0] bucket[d][1] += 1 if preds[step_idx] == actuals[step_idx]: bucket[d][0] += 1 if args.probe_test_seq_len is not None and len(actuals) == args.probe_test_seq_len: # Modified to include `item` for token extraction later pos_wise_matches.append((preds, actuals, item)) full_tokens = [itos[t.item()] for t in item['ids']] for step_idx, p_idx in enumerate(item['probe_indices']): prefix_str = ' '.join(full_tokens[:p_idx + 1]) if args.probe_tasks == 'E' and args.taskE_probe_type == 'dir': extra_val = item['extra_info'][step_idx] if extra_val and extra_val != "init": prefix_str += f" ({extra_val})" p_val, a_val = preds[step_idx], actuals[step_idx] res = "OK" if np.allclose(p_val, a_val, atol=0.5) else f"ERR(Real:{a_val})" layer_log_lines.append(f"Prefix:[{prefix_str}] | Pred:{p_val} | {res}") with open(detailed_path, 'a') as f_det: f_det.write(f"--- {layer_name} ---\n") sampled_lines = random.sample(layer_log_lines, min(len(layer_log_lines), 1000)) for line in sampled_lines: f_det.write(line + "\n") f_det.write("\n") all_preds_cat = np.concatenate(all_preds, axis=0) all_labels_cat = np.concatenate(all_labels, axis=0) if is_regression: if use_round_acc: p_int = np.round(np.asarray(all_preds_cat).reshape(-1)).astype(np.int64) l_int = np.round(np.asarray(all_labels_cat).reshape(-1)).astype(np.int64) acc = float(np.mean(p_int == l_int)) results_per_layer.append(acc) print(f"{layer_name} Overall Accuracy ({args.probe_target}, rounded): {acc * 100:.2f}%") else: r2 = calculate_r2(all_preds_cat, all_labels_cat) results_per_layer.append(r2) print(f"{layer_name} Overall R^2 Score ({args.probe_target}): {r2:.4f}") else: mean_acc, std_acc = bootstrap_accuracy(all_preds_cat, all_labels_cat, args.probe_eval_bootstrap_samples) results_per_layer.append((mean_acc, std_acc)) print(f"{layer_name} Overall Accuracy ({args.probe_target}): {mean_acc * 100:.2f}% ± {std_acc * 100:.2f}%") # --- Optional (prev, curr) bucket evaluation for node_orientation --- if args.probe_node_orientation_split and not is_regression: prev_arr = np.array(all_prev_acts, dtype=object) curr_arr = np.array(all_curr_acts, dtype=object) bucket_specs = [('T', 'T'), ('T', 'FLR'), ('FLR', 'T'), ('FLR', 'FLR')] bucket_results = {} print(f" [{layer_name}] bucketed:", end='') for pv, cv in bucket_specs: mask = np.zeros(len(prev_arr), dtype=bool) for k in range(len(prev_arr)): pa, ca = prev_arr[k], curr_arr[k] if pa is None or ca is None: continue pa_v = 'T' if pa == 'T' else 'FLR' ca_v = 'T' if ca == 'T' else 'FLR' if pa_v == pv and ca_v == cv: mask[k] = True if mask.sum() == 0: bucket_results[(pv, cv)] = (0.0, 0.0, 0) continue sp = all_preds_cat[mask] sl = all_labels_cat[mask] m, s = bootstrap_accuracy(sp, sl, args.probe_eval_bootstrap_samples) bucket_results[(pv, cv)] = (m, s, int(mask.sum())) print(f" prev={pv},curr={cv}: {m*100:.2f}% (n={int(mask.sum())})", end='') print() if 'bucket_results_per_layer' not in locals(): bucket_results_per_layer = [] bucket_results_per_layer.append(bucket_results) if args.probe_test_seq_len is not None: # --- Ensure heatmap data is restricted to the chosen sequence if plot_with_tokens is True --- if args.plot_with_tokens and target_seq_id is not None: pos_wise_matches = [m for m in pos_wise_matches if m[2].get('global_idx') == target_seq_id] if layer_idx == 0: if args.plot_with_tokens: print( f"--- Generating heatmap for a single selected sequence with {args.probe_test_seq_len} steps ---") else: print( f"--- Found {len(pos_wise_matches)} sequences with exactly {args.probe_test_seq_len} steps ---") if len(pos_wise_matches) > 0: pos_metrics = [] for p_idx in range(args.probe_test_seq_len): p_at_pos = np.array([m[0][p_idx] for m in pos_wise_matches]) l_at_pos = np.array([m[1][p_idx] for m in pos_wise_matches]) if is_regression and not use_round_acc: m_val = calculate_r2(p_at_pos, l_at_pos) else: p_cmp = np.round(p_at_pos.reshape(-1)).astype(np.int64) if use_round_acc else p_at_pos l_cmp = np.round(l_at_pos.reshape(-1)).astype(np.int64) if use_round_acc else l_at_pos m_val = float(np.mean(p_cmp == l_cmp)) pos_metrics.append(m_val) heatmap_data.append(pos_metrics) hook_handle.remove() if args.probe_test_seq_len is not None and len(heatmap_data) == n_total_layers: heatmap_array = np.array(heatmap_data) fig, ax = plt.subplots(figsize=(max(12, args.probe_test_seq_len * 0.6), max(5, n_total_layers * 0.6))) _scalar_acc = (not is_regression) or use_round_acc im = ax.imshow(heatmap_array, cmap='coolwarm', aspect='equal', vmin=0 if _scalar_acc else None, vmax=1 if _scalar_acc else None) fig.colorbar(im, ax=ax, label='Accuracy' if _scalar_acc else 'R^2 Score') if args.plot_with_tokens and target_seq_id is not None: n_used = 1 title_seq_info = f'1 of {n_seq_matching_len} seq (single, with tokens)' else: n_used = len(pos_wise_matches) title_seq_info = f'avg over {n_used} seq' ax.set_title( f'Position-wise Probe Performance ({args.probe_target}) | Seq Len {args.probe_test_seq_len} | Eval on {args.probe_eval_on} | {title_seq_info}') ax.set_xlabel('Position in Sequence') ax.set_ylabel('Layer') ax.set_yticks(range(n_total_layers)) ax.set_yticklabels([t[0] for t in layer_targets]) ax.set_xticks(range(args.probe_test_seq_len)) # --- Logic for Dynamic Token X-Axis Labels --- x_labels = [f'{i}' for i in range(args.probe_test_seq_len)] # Default 0, 1, 2... rotation = 0 ha = 'center' if args.plot_with_tokens and len(pos_wise_matches) > 0: # Because pos_wise_matches is already filtered, [0] is exactly our target selected_sample = pos_wise_matches[0][2] tokens = [itos[t.item()] for t in selected_sample['ids']] probe_indices = selected_sample['probe_indices'] nodes_history = selected_sample['current_nodes'] # 获取节点历史 new_x_labels = [] last_idx = 0 # 使用 enumerate 获取索引以访问 nodes_history for k, p_idx in enumerate(probe_indices): # Get the chunk of tokens ending at the probe point chunk = tokens[last_idx:p_idx + 1] node_id = nodes_history[k] # 获取当前节点 # 格式化:Token 前缀 + 换行 + 节点ID label_str = f"{' '.join(chunk)}\n({node_id})" new_x_labels.append(label_str) last_idx = p_idx + 1 x_labels = new_x_labels rotation = 45 # Rotate slightly to prevent overlap of long tokens like "A 26 37 : E" ha = 'right' ax.set_xticklabels(x_labels, rotation=rotation, ha=ha) # --- Highlight labels with perfect accuracy (1.0) --- # We iterate through the x-axis labels and check the corresponding value in the last layer of heatmap for i, label in enumerate(ax.get_xticklabels()): if heatmap_array.shape[1] > i: val = heatmap_array[-1, i] # Value at last layer for position i # Check if accuracy/R2 is effectively 1.0 (using a small tolerance for float precision) if abs(val - 1.0) < 1e-4: label.set_color('red') # ----------------------------------------------- for i in range(n_total_layers): for j in range(args.probe_test_seq_len): ax.text(j, i, f"{heatmap_array[i, j]:.2f}", ha="center", va="center", color="white", fontsize=8) fig.tight_layout() # Add 'single' suffix to output filename if token plotting is enabled to differentiate single_suffix = "_single" if args.plot_with_tokens else "" plot_filename = os.path.join(out_dir, f"probe_heatmap_{args.probe_target}_{args.probe_tasks}{args.taskE_probe_type if args.probe_tasks == 'E' else ''}_{tasks_tag}_{args.ckpt_iter}_len{args.probe_test_seq_len}{eval_on_str}{single_suffix}{rand_tag}.png") fig.savefig(plot_filename, dpi=300) plt.close(fig) print(f"\nPosition-wise heatmap saved to: {plot_filename}") separator = "=" * 60 with open(summary_path, 'w') as f_sum: f_sum.write(f"{separator}\n") f_sum.write(f"Probing Test Results: {args.probe_target.upper()} | Task: {args.probe_tasks}\n") f_sum.write(f"{separator}\n") f_sum.write(f"Config: {args.config}\n") f_sum.write(f"Checkpoint iteration: {args.ckpt_iter}\n") f_sum.write(f"Number of nodes: {args.num_nodes}\n") f_sum.write(f"Probing target: {args.probe_target}\n") if args.probe_tasks == 'E': f_sum.write(f"Task E Probe Type: {args.taskE_probe_type}\n") if args.probe_test_seq_len is not None: f_sum.write( f"Position-wise test for seq length: {args.probe_test_seq_len}\n") f_sum.write(f"Evaluated on: {args.probe_eval_on} set\n") f_sum.write(f"{separator}\n\n") for l, val in enumerate(results_per_layer): _as_acc = (not is_regression) or use_round_acc metric_name = "Accuracy" if _as_acc else "R^2" if isinstance(val, tuple): mean_v, std_v = val metric_val = f"{mean_v * 100:.4f}% ± {std_v * 100:.4f}%" else: metric_val = f"{val * 100:.4f}%" if _as_acc else f"{val:.4f}" layer_display = layer_targets[l][0] if l < len(layer_targets) else f"Layer {l + 1}" f_sum.write(f"{layer_display}: {metric_name} = {metric_val}\n") f_sum.write(f"\n{separator}\n") if args.probe_node_orientation_split and bucket_results_per_layer: f_sum.write("\n--- (prev_action, curr_action) bucket accuracies ---\n") f_sum.write(f"{'Layer':<14} {'T,T':>20} {'T,FLR':>20} {'FLR,T':>20} {'FLR,FLR':>20} {'Overall':>20}\n") for l, br in enumerate(bucket_results_per_layer): layer_display = layer_targets[l][0] if l < len(layer_targets) else f"Layer {l + 1}" cells = [] for key in [('T', 'T'), ('T', 'FLR'), ('FLR', 'T'), ('FLR', 'FLR')]: m, s, n = br.get(key, (0.0, 0.0, 0)) cells.append(f"{m*100:.2f}±{s*100:.2f}(n={n})") overall = results_per_layer[l] if isinstance(overall, tuple): o_cell = f"{overall[0]*100:.2f}±{overall[1]*100:.2f}" else: o_cell = f"{overall*100:.2f}" f_sum.write(f"{layer_display:<14} {cells[0]:>20} {cells[1]:>20} {cells[2]:>20} {cells[3]:>20} {o_cell:>20}\n") f_sum.write(f"{separator}\n") print(f"\nDone. Summary saved to: {summary_path}") # --- Optional: plot probe accuracy vs distance-to-target --- if args.plot_acc_by_dist and dist_acc_per_layer is not None: min_n = args.plot_acc_by_dist_min_bucket # Union of all distances seen across layers (they should be the same set) all_dists = sorted({d for layer_buckets in dist_acc_per_layer for d in layer_buckets.keys()}) # Keep only distances whose total count (summed across layers / all == any layer's count) >= min_n valid_dists = [] for d in all_dists: # All layers share the same denominators because they're computed on the same probe points totals = [dist_acc_per_layer[l].get(d, [0, 0])[1] for l in range(n_total_layers)] if max(totals) >= min_n: valid_dists.append(d) if not valid_dists: print(f"[plot_acc_by_dist] No distance bucket has >= {min_n} samples; skipping plot.") else: fig, ax = plt.subplots(figsize=(max(8, len(valid_dists) * 0.5), 5)) cmap = plt.get_cmap('viridis', n_total_layers) for l in range(n_total_layers): xs, ys, ns = [], [], [] for d in valid_dists: n_corr, n_tot = dist_acc_per_layer[l].get(d, [0, 0]) if n_tot < min_n: continue xs.append(d) ys.append(n_corr / n_tot) ns.append(n_tot) if not xs: continue ax.plot(xs, ys, marker='o', color=cmap(l), label=layer_targets[l][0]) ax.set_xlabel(f"Distance from current node to target ({args.plot_acc_by_dist_metric})") ax.set_ylabel("Probe accuracy") ax.set_ylim(0, 1.02) ax.set_title( f"Probe Accuracy vs Distance-to-Target | target={args.probe_target} | " f"task={args.probe_tasks} | eval={args.probe_eval_on}" ) ax.grid(True, alpha=0.3) ax.legend(loc='best', fontsize=8) # Annotate bucket sizes on the bottom layer's curve (use last layer for clarity) last_bucket = dist_acc_per_layer[-1] for d in valid_dists: n_corr, n_tot = last_bucket.get(d, [0, 0]) if n_tot >= min_n: ax.annotate(f"n={n_tot}", xy=(d, 0.02), ha='center', va='bottom', fontsize=7, color='gray', rotation=90) fig.tight_layout() dist_plot_path = os.path.join( out_dir, f"probe_acc_by_dist_{args.probe_target}_{args.probe_tasks}" f"{args.taskE_probe_type if args.probe_tasks == 'E' else ''}_" f"{tasks_tag}_{args.ckpt_iter}{eval_on_str}{excl_tag}{rand_tag}_" f"{args.plot_acc_by_dist_metric}.png" ) fig.savefig(dist_plot_path, dpi=300) plt.close(fig) print(f"[plot_acc_by_dist] Saved plot to: {dist_plot_path}") # Also dump a CSV so the numbers are inspectable csv_path = dist_plot_path.replace('.png', '.csv') with open(csv_path, 'w') as f_csv: header = ['distance'] + [layer_targets[l][0] + '_acc' for l in range(n_total_layers)] + \ [layer_targets[l][0] + '_n' for l in range(n_total_layers)] f_csv.write(','.join(header) + '\n') for d in valid_dists: row = [str(d)] for l in range(n_total_layers): n_corr, n_tot = dist_acc_per_layer[l].get(d, [0, 0]) row.append(f"{(n_corr / n_tot):.6f}" if n_tot > 0 else "") for l in range(n_total_layers): n_corr, n_tot = dist_acc_per_layer[l].get(d, [0, 0]) row.append(str(n_tot)) f_csv.write(','.join(row) + '\n') print(f"[plot_acc_by_dist] Saved data to: {csv_path}") if __name__ == "__main__": main()