| import os
|
| import argparse
|
| import pickle
|
| import torch
|
| import math
|
| import numpy as np
|
| import random
|
| from tqdm import tqdm
|
| from torch.nn.utils.rnn import pad_sequence
|
| import matplotlib.pyplot as plt
|
|
|
|
|
| from model.transformer import GPTConfig, GPT
|
| from cli_utils import parse_count, format_count
|
|
|
|
|
| def parse_args():
|
| parser = argparse.ArgumentParser(description='Probe Attention Weights towards the Target Token.')
|
|
|
|
|
| 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=50)
|
| parser.add_argument('--num_train_dataset', type=parse_count, default="9M")
|
| parser.add_argument('--tasks', type=str, default='C1', help='Tasks used for filename generation.')
|
| 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('--NLS', action='store_true', default=False,
|
| help='Use NLS model checkpoint (adds _NLS suffix to checkpoint/output filenames)')
|
|
|
|
|
| parser.add_argument('--target_task', type=str, default='C', help='Which task to analyze (e.g., A, C, E).')
|
| parser.add_argument('--num_samples', type=int, default=1000, help='Number of sequences to sample.')
|
| parser.add_argument('--seq_len', type=int, default=30, help='Exact length of sequences to analyze.')
|
| parser.add_argument('--batch_size', type=int, default=100)
|
|
|
| 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_fixed_length_data(lines, stoi, num_samples, seq_len, no_task_tag, target_task):
|
| valid_seqs = []
|
|
|
| target_idx = 1 if no_task_tag else 2
|
| labels_chars = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'}
|
|
|
| for line in lines:
|
| parts = line.split()
|
| if len(parts) < seq_len:
|
| continue
|
|
|
|
|
| if target_idx + 1 >= len(parts) or parts[target_idx + 1] != ':':
|
| continue
|
|
|
| colon_idx = target_idx + 1
|
|
|
|
|
| if not no_task_tag:
|
| if parts[0] != target_task:
|
| continue
|
| else:
|
|
|
| is_task_e = len(parts) > colon_idx + 2 and parts[colon_idx + 2] in labels_chars
|
| if target_task == 'E' and not is_task_e:
|
| continue
|
| if target_task == 'A' and is_task_e:
|
| continue
|
|
|
| try:
|
| tokens = [stoi[p] for p in parts[:seq_len]]
|
| valid_seqs.append(tokens)
|
| except KeyError:
|
| continue
|
|
|
| if len(valid_seqs) < num_samples:
|
| print(f"Warning: Only found {len(valid_seqs)} valid Task {target_task} sequences. Using all of them.")
|
| sampled = valid_seqs
|
| else:
|
| sampled = random.sample(valid_seqs, num_samples)
|
|
|
| return [torch.tensor(s, dtype=torch.long) for s in sampled], target_idx
|
|
|
|
|
|
|
| activations = {}
|
|
|
|
|
| def get_attention_hook(layer_idx, n_head):
|
| """
|
| 挂载在 c_attn 层上的 Hook:
|
| c_attn 输出 shape 为 (B, T, 3 * C),包含 Q, K, V。
|
| 修改:保留所有 Head 的维度,不再取平均。
|
| """
|
|
|
| def hook(module, input, output):
|
| B, T, C3 = output.size()
|
| C = C3 // 3
|
| hs = C // n_head
|
|
|
|
|
| q, k, v = output.split(C, dim=2)
|
|
|
|
|
| k = k.view(B, T, n_head, hs).transpose(1, 2)
|
| q = q.view(B, T, n_head, hs).transpose(1, 2)
|
|
|
|
|
| att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(hs))
|
|
|
|
|
| mask = torch.tril(torch.ones(T, T, device=output.device)).view(1, 1, T, T)
|
| att = att.masked_fill(mask == 0, float('-inf'))
|
|
|
|
|
| att = torch.nn.functional.softmax(att, dim=-1)
|
|
|
|
|
| att_full = att.detach().cpu()
|
|
|
| if layer_idx not in activations:
|
| activations[layer_idx] = []
|
| activations[layer_idx].append(att_full)
|
|
|
| return hook
|
|
|
|
|
| def main():
|
| args = parse_args()
|
| seed = 42
|
| torch.manual_seed(seed)
|
| np.random.seed(seed)
|
| random.seed(seed)
|
|
|
| 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 = f"{tasks_tag}_NLS" if args.NLS else tasks_tag
|
| nls_suffix = '_NLS' if args.NLS else ''
|
|
|
| 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_first_existing(candidates):
|
| for path in candidates:
|
| if os.path.exists(path): return path
|
| return candidates[0]
|
|
|
|
|
| meta = pickle.load(open(pick_first_existing([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_first_existing([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')])
|
| checkpoint = torch.load(ckpt_path, map_location=args.device)
|
| conf = GPTConfig(**checkpoint['model_args'])
|
|
|
|
|
| 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 i in range(conf.n_layer):
|
| model.transformer.h[i].attn.c_attn.register_forward_hook(get_attention_hook(i, conf.n_head))
|
|
|
|
|
| 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')])
|
|
|
| print(f"Loading data from: {train_txt}")
|
| lines = load_lines(train_txt)
|
| dataset, target_idx = extract_fixed_length_data(lines, stoi, args.num_samples, args.seq_len, args.no_task_tag, args.target_task)
|
| print(f"Successfully extracted {len(dataset)} Task {args.target_task} sequences of length {args.seq_len}.")
|
| print(f"Target token index determined as: {target_idx} (0-indexed)")
|
|
|
|
|
| print(f"\n--- Task {args.target_task} Sequence Samples ---")
|
| for s in dataset[:3]:
|
| print(" ".join([itos[x.item()] for x in s]))
|
| print("------------------------\n")
|
|
|
|
|
| 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(batch, batch_first=True, padding_value=0).to(args.device)
|
| with torch.no_grad():
|
| model(x_padded)
|
|
|
|
|
|
|
| print(f"\n--- Attention Weights towards Target Token (Index: {target_idx}) ---")
|
| results_text = f"Attention Probe Results - Task {args.target_task} (Seq Len: {args.seq_len}, Samples: {len(dataset)})\n"
|
| results_text += f"Target Token Index: {target_idx}\n"
|
| results_text += "Note: Stats below are averaged over all heads for each layer.\n\n"
|
|
|
| for l in range(conf.n_layer):
|
|
|
| layer_att = torch.cat(activations[l], dim=0)
|
|
|
|
|
| layer_att_mean_heads = layer_att.mean(dim=1)
|
|
|
| layer_header = f"=== Layer {l:02d} ==="
|
| print(layer_header)
|
| results_text += layer_header + "\n"
|
|
|
|
|
| for pos in range(args.seq_len):
|
| if pos < target_idx:
|
| line = f" Pos {pos:02d} : 0.0000 ± 0.0000 (Masked)"
|
| else:
|
|
|
| weights = layer_att_mean_heads[:, pos, target_idx].numpy()
|
| mean_w = np.mean(weights)
|
| std_w = np.std(weights)
|
| line = f" Pos {pos:02d} : {mean_w:.4f} ± {std_w:.4f}"
|
|
|
| print(line)
|
| results_text += line + "\n"
|
| print()
|
| results_text += "\n"
|
|
|
|
|
| output_txt = os.path.join(out_dir, f"attention_probe_Task{args.target_task}_L{args.seq_len}_iter{args.ckpt_iter}{nls_suffix}.txt")
|
| with open(output_txt, 'w') as f:
|
| f.write(results_text)
|
| print(f"Done! Attention stats saved to: {output_txt}")
|
|
|
|
|
| print("\n--- Generating Attention Matrix Visualization (Per Head) ---")
|
|
|
|
|
|
|
|
|
| if conf.n_head > 1:
|
| rows = conf.n_layer
|
| cols = conf.n_head
|
| layout_by_layer_rows = True
|
| else:
|
| rows = 1
|
| cols = conf.n_layer
|
| layout_by_layer_rows = False
|
|
|
| fig, axes = plt.subplots(rows, cols, figsize=(3 * cols, 3 * rows), squeeze=False)
|
|
|
| for l in range(conf.n_layer):
|
|
|
| layer_att = torch.cat(activations[l], dim=0)
|
|
|
| for h in range(conf.n_head):
|
|
|
| mean_att_matrix = layer_att[:, h, :, :].mean(dim=0).numpy()
|
|
|
| if layout_by_layer_rows:
|
| row_idx, col_idx = l, h
|
| else:
|
| row_idx, col_idx = 0, l
|
|
|
| ax = axes[row_idx, col_idx]
|
|
|
| im = ax.imshow(mean_att_matrix, cmap='viridis', aspect='equal', vmin=0, vmax=1)
|
|
|
|
|
| ax.set_title(f'L{l} H{h}', fontsize=10)
|
|
|
|
|
| if col_idx == 0:
|
| ax.set_ylabel(f'L{l} Query Pos' if layout_by_layer_rows else 'Query Pos')
|
|
|
| if row_idx == rows - 1:
|
| ax.set_xlabel('Key Pos')
|
|
|
|
|
| ax.axvline(x=target_idx, color='red', linestyle='--', alpha=0.5, linewidth=1)
|
|
|
|
|
| fig.subplots_adjust(right=0.82)
|
| cbar_ax = fig.add_axes([0.86, 0.15, 0.02, 0.7])
|
| fig.colorbar(im, cax=cbar_ax, label='Attention Weight')
|
|
|
| plt.suptitle(f'Attention Matrices per Head - Task {args.target_task} (Target Idx: {target_idx})', fontsize=16)
|
|
|
| output_png = os.path.join(out_dir, f"attention_matrix_Task{args.target_task}_L{args.seq_len}_iter{args.ckpt_iter}{nls_suffix}.png")
|
| plt.savefig(output_png, dpi=300, bbox_inches='tight')
|
| plt.close()
|
|
|
| print(f"Done! Attention visualization saved to: {output_png}")
|
|
|
|
|
| if __name__ == "__main__":
|
| main() |