WorldModelForMaze / maze_vis_probe_target.py
Kalso42's picture
Upload folder using huggingface_hub
34e468d verified
Raw
History Blame Contribute Delete
13.9 kB
"""Target-node probe accuracy vs. distance-to-target for the six architectures.
For every model we load the checkpoint and train a separate linear probe on each
layer to read the GOAL (target) node out of the hidden state at every readout
position along the path. We pick, per model, the layer whose probe is most
accurate, then evaluate that layer's probe on a held-out test set -- the same
train-probe / test-eval split maze_kstep_detour_test.py uses.
The figure is a line plot: x = graph shortest-path distance from the current
node to the target, y = target-node probe accuracy at that distance, one line
per architecture (legend annotated with the winning layer, e.g. "Mamba-2 (L4)").
This shows how goal decodability decays as the agent moves away from the target.
Reuses the probe / model machinery from maze_kstep_detour_test.py so no logic is
duplicated; only the probe *target* differs (goal node instead of current node).
"""
import os
import math
import pickle
import random
import argparse
from collections import defaultdict
import numpy as np
import torch
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import networkx as nx
from torch.nn.utils.rnn import pad_sequence
from cli_utils import format_count, parse_count
from maze_detour_test import load_lines
from maze_kstep_detour_test import (
make_task_ops,
build_model_from_checkpoint,
train_all_layer_probes,
get_block_list,
)
# (display name, out/<dir_key>/ folder, is_transformer_family, needs _NL ckpt suffix)
MODEL_SPECS = [
('Transformer', 'transformer', True, False),
('Transformer-NextLat', 'transformer_nextlat', True, True),
('Mamba', 'mamba', False, False),
('Mamba-2', 'mamba2', False, False),
('Gated-DeltaNet', 'gated_deltanet', False, False),
('GRU', 'gru', False, False),
]
def parse_args():
p = argparse.ArgumentParser(
description='Target-node probe accuracy vs. distance-to-target across the six architectures.')
p.add_argument('--tasks', default='I1', help='Task spec for filename resolution (e.g. A1, C1, I1).')
p.add_argument('--dataset', default='10M', help='Dataset label shown in the output filename.')
p.add_argument('--tf_config', default='6_6_384', help='Config string for the transformer family.')
p.add_argument('--rec_config', default='12_384', help='Config string for the RNN/SSM family.')
p.add_argument('--num_train', type=parse_count, default='10M',
help='Number of training entries (supports K/M/B); selects the checkpoint + data file.')
p.add_argument('--num_test', type=parse_count, default='10K',
help='Number of test entries (supports K/M/B); selects the held-out eval file.')
p.add_argument('--ckpt_iter', type=int, default=10000)
p.add_argument('--path_type', default='RWs', choices=['RWc', 'RWa', 'RWs'])
p.add_argument('--no_task_tag', action='store_true', default=False)
p.add_argument('--NLS', action='store_true', default=False)
p.add_argument('--num_nodes', type=int, default=100)
p.add_argument('--device', default='cuda:0')
# Probe hyper-parameters (mirror maze_kstep_detour_test.py defaults).
p.add_argument('--probe_train_samples', type=int, default=5000)
p.add_argument('--probe_eval_samples', type=int, default=2000,
help='Number of held-out test sequences used to evaluate the best-layer probe.')
p.add_argument('--probe_epochs', type=int, default=5)
p.add_argument('--probe_lr', type=float, default=1e-2)
p.add_argument('--probe_batch_size', type=int, default=64)
p.add_argument('--min_count', type=int, default=30,
help='Drop distance bins with fewer than this many test positions.')
p.add_argument('--out_dir', default='out/plot')
return p.parse_args()
def collect_target_probe_data(lines, stoi, no_task_tag, num_nodes, grid_n, device,
max_samples, task_ops, dist_lookup=None):
"""Collect (token_ids, readout positions, target-node label[, distance]) from clean paths.
The readout positions are the same per-move positions the current-node probe uses
(delegated to ``task_ops['parse_probe']``); only the probe label changes -- every
position is labelled with the sequence's fixed GOAL (target) node. When ``dist_lookup``
is given we also record, per position, the graph shortest-path distance from the
CURRENT node (recovered from the state label) to the target; positions with no path
are dropped."""
label_factor = task_ops['label_factor']
data = []
for line in lines:
if len(data) >= max_samples:
break
parts = line.split()
if ':' not in parts:
continue
colon_idx = parts.index(':')
try:
if no_task_tag:
src, target = int(parts[0]), int(parts[1])
else:
src, target = int(parts[1]), int(parts[2])
ids = [stoi[t] for t in parts]
except (KeyError, ValueError, IndexError):
continue
if not (0 <= target < num_nodes):
continue
indices, state_labels = task_ops['parse_probe'](parts, colon_idx, src, grid_n, num_nodes)
if not indices:
continue
if dist_lookup is None:
keep_idx, dists = indices, None
else:
tstr = str(target)
keep_idx, dists = [], []
for pos, slab in zip(indices, state_labels):
cur = slab // label_factor
d = dist_lookup.get(str(cur), {}).get(tstr)
if d is None:
continue
keep_idx.append(pos)
dists.append(d)
if not keep_idx:
continue
item = {
'ids': torch.tensor(ids, dtype=torch.long, device=device),
'probe_indices': keep_idx,
'labels': [target] * len(keep_idx),
}
if dists is not None:
item['dists'] = dists
data.append(item)
return data
def eval_probe_by_distance(model, probe, layer, data, device, batch_size=64):
"""Run ``probe`` on layer ``layer`` outputs and tally correct/total per distance bin.
Returns dict: distance -> [correct, total]."""
acts = {}
def hook(_m, _i, o):
acts['h'] = o.detach()
handle = get_block_list(model)[layer].register_forward_hook(hook)
probe.eval()
agg = defaultdict(lambda: [0, 0])
with torch.no_grad():
for b in range(0, len(data), batch_size):
batch = sorted(data[b:b + batch_size], key=lambda x: len(x['ids']), reverse=True)
x = pad_sequence([it['ids'] for it in batch], batch_first=True, padding_value=0)
model(x)
h = acts['h']
for i, it in enumerate(batch):
preds = probe(h[i, it['probe_indices'], :].float()).argmax(dim=1)
lab = torch.tensor(it['labels'], dtype=torch.long, device=device)
correct = (preds == lab).cpu().numpy()
for c, d in zip(correct, it['dists']):
agg[d][1] += 1
if c:
agg[d][0] += 1
handle.remove()
return agg
def run_one_model(args, dir_key, is_tf, needs_nl, stoi, G, grid_n, train_lines, test_lines,
dist_lookup):
"""Load one architecture's checkpoint, train per-layer target probes, pick the best
layer by train accuracy, and evaluate that layer's probe on the held-out test set,
binned by distance-to-target. Returns dict(best_layer, dist_agg, n_layer, config) or
None if the checkpoint is missing."""
config = args.tf_config if is_tf else args.rec_config
tasks_tag = f"{args.tasks}_{args.path_type}" + ("_NT" if args.no_task_tag else "")
ckpt_tag = tasks_tag + ("_NL" if needs_nl else "") + ("_NLS" if args.NLS else "")
out_dir = (f'out/{dir_key}/maze_{config}_{args.num_nodes}'
f'{"_NT" if args.no_task_tag else ""}/')
ckpt_path = f'{out_dir}/{args.ckpt_iter}_ckpt_maze_{ckpt_tag}_{format_count(args.num_train)}.pt'
if not os.path.exists(ckpt_path):
print(f"[missing] {ckpt_path}")
return None
checkpoint = torch.load(ckpt_path, map_location=args.device, weights_only=False)
# Inference only: fall back to the pure-PyTorch scan so we don't require the
# mamba_ssm CUDA kernel (identical outputs, runs in any environment).
margs = checkpoint.get('model_args', {})
if 'use_cuda' in margs:
margs['use_cuda'] = False
model, conf = build_model_from_checkpoint(checkpoint, dir_key.replace('_', '-'), args.device)
task_ops = make_task_ops(args.tasks, stoi, G)
probe_data = collect_target_probe_data(
train_lines, stoi, args.no_task_tag, args.num_nodes, grid_n,
args.device, args.probe_train_samples, task_ops)
print(f" collected {len(probe_data)} train target-probe sequences "
f"({conf.n_layer} layers, n_embd={conf.n_embd})")
if not probe_data:
return None
# Train a probe on every layer; keep the layer with the highest train accuracy.
best_layer, best_probe, _ = train_all_layer_probes(
model, probe_data, conf.n_layer, conf.n_embd, args.num_nodes,
args.device, args.probe_epochs, args.probe_lr, args.probe_batch_size)
# Evaluate that best layer's probe on held-out test sequences, binned by distance.
test_data = collect_target_probe_data(
test_lines, stoi, args.no_task_tag, args.num_nodes, grid_n,
args.device, args.probe_eval_samples, task_ops, dist_lookup=dist_lookup)
dist_agg = eval_probe_by_distance(model, best_probe, best_layer, test_data,
args.device, args.probe_batch_size) if test_data else {}
tot_c = sum(v[0] for v in dist_agg.values())
tot_n = sum(v[1] for v in dist_agg.values())
overall = tot_c / tot_n * 100.0 if tot_n else float('nan')
print(f" best layer = L{best_layer + 1}, overall test acc = {overall:.1f}% "
f"(on {len(test_data)} test sequences, {tot_n} positions)")
del model
if args.device.startswith('cuda'):
torch.cuda.empty_cache()
return {'best_layer': best_layer + 1, 'dist_agg': dict(dist_agg),
'n_layer': conf.n_layer, 'config': config}
def main():
args = parse_args()
os.makedirs(args.out_dir, exist_ok=True)
grid_n = int(math.sqrt(args.num_nodes))
tasks_tag = f"{args.tasks}_{args.path_type}" + ("_NT" if args.no_task_tag else "")
data_dir = f'data/maze/{args.num_nodes}'
meta = pickle.load(open(f'{data_dir}/meta_{tasks_tag}.pkl', 'rb'))
stoi = meta['stoi']
G = nx.read_graphml(f'{data_dir}/maze_graph_{tasks_tag}.graphml')
# All-pairs shortest-path distances (cheap for ~100 nodes); keys are node strings.
dist_lookup = {s: dict(d) for s, d in nx.all_pairs_shortest_path_length(G)}
train_lines = load_lines(f"{data_dir}/train_{tasks_tag}_{format_count(args.num_train)}.txt")
random.shuffle(train_lines)
test_lines = load_lines(f"{data_dir}/test_{tasks_tag}_{format_count(args.num_test)}.txt")
random.shuffle(test_lines)
results = {} # display name -> dict(best_layer, dist_agg, n_layer, config)
for name, dir_key, is_tf, needs_nl in MODEL_SPECS:
print(f"--- {name} ---")
try:
res = run_one_model(args, dir_key, is_tf, needs_nl, stoi, G, grid_n,
train_lines, test_lines, dist_lookup)
except Exception as e: # missing optional backend (e.g. fla for Gated-DeltaNet)
print(f"[skip {name}] {type(e).__name__}: {e}")
res = None
if res is not None:
results[name] = res
if not results:
print("Nothing to plot: no checkpoints found for these settings.")
return
# --- Line plot: target-probe accuracy vs distance-to-target, one line per model ---
colors = plt.cm.tab10(np.linspace(0, 1, len(MODEL_SPECS)))
color_map = {name: colors[i] for i, (name, *_) in enumerate(MODEL_SPECS)}
markers = ['o', 's', '^', 'D', 'P', 'v']
marker_map = {name: markers[i] for i, (name, *_) in enumerate(MODEL_SPECS)}
plt.figure(figsize=(9, 5.5))
npz = {}
for name, *_ in MODEL_SPECS:
if name not in results:
continue
agg = results[name]['dist_agg']
dists = sorted(d for d, (c, n) in agg.items() if n >= args.min_count)
if not dists:
continue
accs = [agg[d][0] / agg[d][1] * 100.0 for d in dists]
best = results[name]['best_layer']
plt.plot(dists, accs, marker=marker_map[name], markersize=5, linewidth=2,
color=color_map[name], label=f'{name} (L{best})')
npz[f'{name}_dist'] = np.array(dists)
npz[f'{name}_acc'] = np.array(accs)
print(f"{name}: best=L{best}, distances {dists[0]}..{dists[-1]}")
plt.xlabel('distance to target (graph shortest-path steps)', fontsize=12)
plt.ylabel('target-node probe accuracy (%)', fontsize=12)
plt.title(f'Target-node decodability vs distance to target (Task {args.tasks}, {args.dataset})',
fontsize=13)
plt.ylim(-2, 105)
plt.grid(True, alpha=0.3)
plt.legend(fontsize=10, framealpha=0.9)
plt.tight_layout()
stem = f'probe_target_dist_{args.tasks}_{args.dataset}_{args.tf_config}_{args.rec_config}'
out_png = os.path.join(args.out_dir, f'{stem}.png')
plt.savefig(out_png, dpi=150)
np.savez(os.path.join(args.out_dir, f'{stem}.npz'), **npz)
print(f"\nSaved figure -> {out_png}")
print(f"Saved data -> {os.path.join(args.out_dir, stem + '.npz')}")
if __name__ == '__main__':
main()