WorldModelForMaze / maze_kstep_detour_test.py
Kalso42's picture
Upload folder using huggingface_hub
34e468d verified
Raw
History Blame Contribute Delete
53.9 kB
# 该实验测试 GPT 在 Task C 迷宫导航中,对 k 步「最低概率合法 token」detour 的泛化能力。
#
# 前缀完全截到冒号结束(即 prompt = "C source target :",不含任何动作 token),
# 然后从 source 开始连续注入 detour(每步选择「预测概率最低但合法」的相对转向),
# 一次性给出 k = 10,20,...,70 步 detour 的结果。
#
# 探针:与 maze_probe_test.py 相同的方式训练(默认 5000 条训练序列、预测当前节点),
# 只取「最后一层 block 的输出」做探针(hook 用 get_block_list,GPT/Mamba 通用)。
#
# 报告五个指标(每个 k 一行),全部架构无关(只看 block 输出 + 输出分布):
# 1. probe_acc —— 表征保真:探针解出的当前 (node, facing) 是否等于真实状态(↑)
# 2. illegal_mass —— 行为读出(Stage 2):模型把多少概率质量分给「非法转向」(↓)
# 3. c_illegal_mass —— 在探针分类正确时的 illegal_mass(条件,↓)
# 4. matched_jsd —— 历史不变性:到达同一真实状态 (node,facing) 时,detour 路径与
# 干净路径的下一步分布之差(对干净参照表做 JSD,↓)
# 5. c_matched_jsd —— 在探针分类正确时的 matched_jsd(条件,↓)
#
# 若条件指标(3/5)仍明显劣化,说明探针解码出的状态不是模型行为的充分统计量
# (表征与行为脱钩,探针准确率会高估模型可靠性)。
import os
import math
import pickle
import argparse
import random
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import networkx as nx
from tqdm import tqdm
from torch.nn.utils.rnn import pad_sequence
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
from maze_detour_test import (
get_legal_dirs, abs_to_turn, turn_to_abs, step_node, load_lines,
)
INF = float('inf')
# Absolute facing directions -> index, for the joint (node, facing) probe target.
FACING_ORDER = ['N', 'E', 'S', 'W']
FACING_IDX = {d: i for i, d in enumerate(FACING_ORDER)}
def make_task_ops(task_type, stoi, G):
"""Build task-specific operations for the detour test.
Task C: relative turns {F,L,R,T}; state = (node, facing); 1 token / move.
Task A: absolute dirs {N,S,E,W}; state = node; 1 token / move.
Task I: clockwise-index {1,2,3,4} into feasible edges from a FIXED North
reference (no facing tracking); state = node; 1 token / move. Legal
indices at a state are {1..f} (f = #feasible edges), so an index > f is
illegal.
Task H: clockwise-index {1,2,3,4} into feasible edges; state = (node, facing);
1 token / move. Legal indices at a state are {1..f} (f = #feasible edges),
so an index > f is illegal.
Task E: ``[direction label]`` pairs; state = node; 2 tokens / move, where the
label observation is the label of the node reached by the move.
Task E note: the training data is segment-compressed (a straight run emits one
``(dir, end_label)`` pair per node whose label matches the run's end label), so
the token stream is not a faithful per-step trajectory in general. We therefore
(a) parse real data with self-validation -- only accept a position while the
emitted label equals the graph label of the reconstructed node, which keeps the
"one pair = one move" reading exact -- and (b) inject detours as length-1 runs
``(dir, label-of-new-node)``, which is on-distribution and exactly trackable.
"""
tt = str(task_type).upper()
DIRS = ('N', 'S', 'E', 'W')
if tt.startswith('C'):
action_order = ['F', 'L', 'R', 'T']
def init_state(src):
return {'node': src, 'facing': 'E'}
def legal_actions(_G, st, grid_n):
legal_abs = get_legal_dirs(_G, st['node'], grid_n)
return [t for t in (abs_to_turn(d, st['facing']) for d in legal_abs) if t is not None]
def advance(st, action, grid_n):
d = turn_to_abs(action, st['facing'])
st['node'] = step_node(st['node'], d, grid_n)
st['facing'] = d
return st['node']
def label(st):
return st['node'] * len(FACING_ORDER) + FACING_IDX[st['facing']]
def ref_key(st):
return (st['node'], st['facing'])
def parse_probe(parts, colon_idx, src, grid_n, num_nodes):
actions = parts[colon_idx + 1:]
st = init_state(src)
indices, labels = [], []
for j, act in enumerate(actions):
if act not in ('F', 'L', 'R', 'T'):
break
node = advance(st, act, grid_n)
if not (0 <= node < num_nodes):
break
indices.append(colon_idx + 1 + j)
labels.append(label(st))
return indices, labels
def parse_reference(parts, colon_idx, src, grid_n, num_nodes):
actions = parts[colon_idx + 1:]
st = init_state(src)
positions, states = [], []
for j, act in enumerate(actions):
if act not in ('F', 'L', 'R', 'T'):
break
positions.append(colon_idx + j)
states.append(ref_key(st))
node = advance(st, act, grid_n)
if not (0 <= node < num_nodes):
positions.pop()
states.pop()
break
return positions, states
ops = dict(label_factor=len(FACING_ORDER), state_name='node+facing', group_size=1)
elif tt.startswith('H'):
# Relative clockwise-index encoding. Each token is the 1-based index of the
# chosen edge among feasible edges, enumerated clockwise from the current
# facing; after moving, facing := chosen direction. State = (node, facing),
# 1 token / move (like Task C). Unlike C, the legal index set is {1..f} where
# f = #feasible edges at the current node, so "illegal" = index > f.
action_order = ['1', '2', '3', '4']
CLOCKWISE_SCAN = {
'N': ['N', 'E', 'S', 'W'],
'E': ['E', 'S', 'W', 'N'],
'S': ['S', 'W', 'N', 'E'],
'W': ['W', 'N', 'E', 'S'],
}
def init_state(src):
return {'node': src, 'facing': 'E'}
def feasible_dirs(st, grid_n):
legal_abs = set(get_legal_dirs(G, st['node'], grid_n))
return [d for d in CLOCKWISE_SCAN[st['facing']] if d in legal_abs]
def legal_actions(_G, st, grid_n):
return [str(i) for i in range(1, len(feasible_dirs(st, grid_n)) + 1)]
def advance(st, action, grid_n):
feasible = feasible_dirs(st, grid_n)
d = feasible[int(action) - 1]
st['node'] = step_node(st['node'], d, grid_n)
st['facing'] = d
return st['node']
def label(st):
return st['node'] * len(FACING_ORDER) + FACING_IDX[st['facing']]
def ref_key(st):
return (st['node'], st['facing'])
def parse_probe(parts, colon_idx, src, grid_n, num_nodes):
actions = parts[colon_idx + 1:]
st = init_state(src)
indices, labels = [], []
for j, act in enumerate(actions):
if act not in ('1', '2', '3', '4'):
break
feasible = feasible_dirs(st, grid_n)
if int(act) < 1 or int(act) > len(feasible): # index exceeds feasible edges
break
node = advance(st, act, grid_n)
if not (0 <= node < num_nodes):
break
indices.append(colon_idx + 1 + j)
labels.append(label(st))
return indices, labels
def parse_reference(parts, colon_idx, src, grid_n, num_nodes):
actions = parts[colon_idx + 1:]
st = init_state(src)
positions, states = [], []
for j, act in enumerate(actions):
if act not in ('1', '2', '3', '4'):
break
feasible = feasible_dirs(st, grid_n)
if int(act) < 1 or int(act) > len(feasible):
break
positions.append(colon_idx + j)
states.append(ref_key(st))
node = advance(st, act, grid_n)
if not (0 <= node < num_nodes):
positions.pop()
states.pop()
break
return positions, states
ops = dict(label_factor=len(FACING_ORDER), state_name='node+facing', group_size=1)
elif tt.startswith('I'):
# Absolute clockwise-index encoding. Each token is the 1-based index of the
# chosen edge among feasible edges, enumerated clockwise from a FIXED North
# reference (N, E, S, W); the walker does NOT track facing. State = node,
# 1 token / move (like Task A). The legal index set is {1..f} where f =
# #feasible edges at the current node, so "illegal" = index > f.
action_order = ['1', '2', '3', '4']
FIXED_SCAN = ['N', 'E', 'S', 'W']
def init_state(src):
return {'node': src}
def feasible_dirs(st, grid_n):
legal_abs = set(get_legal_dirs(G, st['node'], grid_n))
return [d for d in FIXED_SCAN if d in legal_abs]
def legal_actions(_G, st, grid_n):
return [str(i) for i in range(1, len(feasible_dirs(st, grid_n)) + 1)]
def advance(st, action, grid_n):
feasible = feasible_dirs(st, grid_n)
d = feasible[int(action) - 1]
st['node'] = step_node(st['node'], d, grid_n)
return st['node']
def label(st):
return st['node']
def ref_key(st):
return st['node']
def parse_probe(parts, colon_idx, src, grid_n, num_nodes):
actions = parts[colon_idx + 1:]
st = init_state(src)
indices, labels = [], []
for j, act in enumerate(actions):
if act not in ('1', '2', '3', '4'):
break
feasible = feasible_dirs(st, grid_n)
if int(act) < 1 or int(act) > len(feasible): # index exceeds feasible edges
break
node = advance(st, act, grid_n)
if not (0 <= node < num_nodes):
break
indices.append(colon_idx + 1 + j)
labels.append(label(st))
return indices, labels
def parse_reference(parts, colon_idx, src, grid_n, num_nodes):
actions = parts[colon_idx + 1:]
st = init_state(src)
positions, states = [], []
for j, act in enumerate(actions):
if act not in ('1', '2', '3', '4'):
break
feasible = feasible_dirs(st, grid_n)
if int(act) < 1 or int(act) > len(feasible):
break
positions.append(colon_idx + j)
states.append(ref_key(st))
node = advance(st, act, grid_n)
if not (0 <= node < num_nodes):
positions.pop()
states.pop()
break
return positions, states
ops = dict(label_factor=1, state_name='node', group_size=1)
elif tt.startswith('E'):
action_order = ['N', 'S', 'E', 'W']
def init_state(src):
return {'node': src, 'prev_dir': None}
def legal_actions(_G, st, grid_n):
return get_legal_dirs(_G, st['node'], grid_n)
def advance(st, action, grid_n):
st['node'] = step_node(st['node'], action, grid_n)
return st['node']
def label(st):
return st['node']
def ref_key(st):
return st['node']
def node_label_id(st):
return stoi[str(G.nodes[str(st['node'])]['label'])]
def parse_probe(parts, colon_idx, src, grid_n, num_nodes):
actions = parts[colon_idx + 1:]
st = init_state(src)
indices, labels = [], []
i, m = 0, len(actions) // 2
while i < m:
d, lab = actions[2 * i], actions[2 * i + 1]
if d not in DIRS:
break
node = advance(st, d, grid_n)
if not (0 <= node < num_nodes):
break
if str(G.nodes[str(node)]['label']) != lab: # compression ambiguity -> stop
break
indices.append(colon_idx + 1 + 2 * i + 1) # label-token position
labels.append(node)
i += 1
return indices, labels
def parse_reference(parts, colon_idx, src, grid_n, num_nodes):
actions = parts[colon_idx + 1:]
st = init_state(src)
positions, states = [], []
pred_pos = colon_idx # ':' predicts move 0's direction
i, m = 0, len(actions) // 2
while i < m:
d, lab = actions[2 * i], actions[2 * i + 1]
if d not in DIRS:
break
positions.append(pred_pos)
states.append(ref_key(st))
node = advance(st, d, grid_n)
if not (0 <= node < num_nodes) or str(G.nodes[str(node)]['label']) != lab:
positions.pop()
states.pop()
break
pred_pos = colon_idx + 1 + 2 * i + 1 # this label predicts the next direction
i += 1
return positions, states
ops = dict(label_factor=1, state_name='node', group_size=2,
node_label_id=node_label_id, avoid_prev=True)
else: # Task A (and other absolute-direction tasks)
action_order = ['N', 'S', 'E', 'W']
def init_state(src):
return {'node': src}
def legal_actions(_G, st, grid_n):
return get_legal_dirs(_G, st['node'], grid_n)
def advance(st, action, grid_n):
st['node'] = step_node(st['node'], action, grid_n)
return st['node']
def label(st):
return st['node']
def ref_key(st):
return st['node']
def parse_probe(parts, colon_idx, src, grid_n, num_nodes):
actions = parts[colon_idx + 1:]
st = init_state(src)
indices, labels = [], []
for j, act in enumerate(actions):
if act not in DIRS:
break
node = advance(st, act, grid_n)
if not (0 <= node < num_nodes):
break
indices.append(colon_idx + 1 + j)
labels.append(label(st))
return indices, labels
def parse_reference(parts, colon_idx, src, grid_n, num_nodes):
actions = parts[colon_idx + 1:]
st = init_state(src)
positions, states = [], []
for j, act in enumerate(actions):
if act not in DIRS:
break
positions.append(colon_idx + j)
states.append(ref_key(st))
node = advance(st, act, grid_n)
if not (0 <= node < num_nodes):
positions.pop()
states.pop()
break
return positions, states
ops = dict(label_factor=1, state_name='node', group_size=1)
ops.update({
'action_order': action_order,
'action_ids': {a: stoi[a] for a in action_order},
'init_state': init_state,
'legal_actions': legal_actions,
'advance': advance,
'label': label,
'ref_key': ref_key,
'parse_probe': parse_probe,
'parse_reference': parse_reference,
})
ops.setdefault('avoid_prev', False)
ops.setdefault('node_label_id', None)
return ops
def parse_args():
p = argparse.ArgumentParser(
description='k-step detour test (Task A/C/E/H/I): probe fidelity vs. next-step behaviour.')
# --- Model & data ---
p.add_argument('--ckpt_iter', type=int, default=10000)
p.add_argument('--model', type=str, default='mamba2', choices=['transformer', 'transformer-rope', 'transformer-nextlat', 'mamba', 'mamba2', 'gated-deltanet', 'gru'],
help='Model architecture; selects out/<model>/ and how the checkpoint is built.')
p.add_argument('--config', type=str, default='24_576',)
p.add_argument('--device', type=str, default='cuda:0')
p.add_argument('--num_nodes', type=int, default=100)
p.add_argument('--num_train_dataset', type=parse_count, default='10M')
p.add_argument('--num_test_dataset', type=parse_count, default='10K')
p.add_argument('--tasks', type=str, default='H1')
p.add_argument('--path_type', type=str, default='RWs', choices=['RWc', 'RWa', 'RWs'])
p.add_argument('--temperature', type=float, default=1.0,
help='Sampling temperature for reach_acc completion. >0 samples; <=0 is greedy argmax. Default 1.0.')
p.add_argument('--no_task_tag', action='store_true', default=False)
p.add_argument('--NLS', action='store_true', default=False)
# --- Experiment ---
p.add_argument('--num_trials', type=int, default=1000,
help='Number of test sequences (prompts) to run detour on.')
p.add_argument('--k_list', type=str, default='10,20,30,40,50,60,70,80,90,100,110,120,130,140,150',
help='Comma-separated detour lengths to evaluate.')
p.add_argument('--batch_size', type=int, default=128,
help='Trials per batch (all share the same length, no padding).')
# --- Probe ---
p.add_argument('--probe_train_samples', type=int, default=5000,
help='Number of training sequences used to train the probe.')
p.add_argument('--ref_samples', type=int, default=5000,
help='Number of clean training sequences used to build the next-step reference table.')
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('--out_dir', type=str, default='out/maze_kdetour',
help='Directory to save the per-k results table (CSV + NPZ).')
return p.parse_args()
class LinearProbe(nn.Module):
def __init__(self, input_dim, num_classes):
super().__init__()
self.linear = nn.Linear(input_dim, num_classes)
def forward(self, x):
return self.linear(x)
_acts = {}
def _hook(name):
def fn(_m, _inp, out):
_acts[name] = out.detach()
return fn
def get_block_list(model):
"""Return the per-layer block ModuleList (transformer: .transformer.h, mamba: .layers)."""
if hasattr(model, 'transformer'):
return model.transformer.h
return model.layers
def build_model_from_checkpoint(checkpoint, model_type, device):
"""Reconstruct the right architecture from a checkpoint, honoring its stored model_type."""
ckpt_model_type = checkpoint.get('model_type', model_type)
if ckpt_model_type == 'mamba':
conf = MambaConfig(**checkpoint['model_args'])
model = Mamba(conf).to(device)
elif ckpt_model_type == 'mamba2':
conf = Mamba2Config(**checkpoint['model_args'])
model = Mamba2(conf).to(device)
elif ckpt_model_type == 'gated-deltanet':
conf = GatedDeltaNetConfig(**checkpoint['model_args'])
model = GatedDeltaNet(conf).to(device)
elif ckpt_model_type == 'gru':
conf = GRUConfig(**checkpoint['model_args'])
model = GRU(conf).to(device)
elif ckpt_model_type == 'transformer-nextlat':
conf = TransformerNextLatConfig(**checkpoint['model_args'])
model = TransformerNextLat(conf).to(device)
elif ckpt_model_type == 'transformer-rope':
conf = GPTRoPEConfig(**checkpoint['model_args'])
model = GPTRoPE(conf).to(device)
else:
conf = GPTConfig(**checkpoint['model_args'])
model = GPT(conf).to(device)
model.load_state_dict({k.replace('_orig_mod.', ''): v for k, v in checkpoint['model'].items()})
model.eval()
return model, conf
# ----------------------------------------------------------------------------
# Probe training (last Transformer layer only, target = current node)
# ----------------------------------------------------------------------------
def collect_probe_data(lines, stoi, no_task_tag, num_nodes, grid_n, device, max_samples, task_ops):
"""Collect (token_ids, probe positions, current-state labels) from clean paths.
Works for Task C (turns -> node+facing), Task A (directions -> node) and Task E
(direction/label pairs -> node). Parsing is delegated to ``task_ops['parse_probe']``."""
data = []
for line in lines:
if len(data) >= max_samples:
break
parts = line.split()
if ':' not in parts:
continue
colon_idx = parts.index(':')
try:
src = int(parts[0]) if no_task_tag else int(parts[1])
ids = [stoi[t] for t in parts]
except (KeyError, ValueError, IndexError):
continue
indices, labels = task_ops['parse_probe'](parts, colon_idx, src, grid_n, num_nodes)
if labels:
data.append({
'ids': torch.tensor(ids, dtype=torch.long, device=device),
'probe_indices': indices,
'labels': labels,
})
return data
def train_last_layer_probe(model, probe_data, last_layer, n_embd, num_classes, device,
epochs, lr, batch_size):
hook = get_block_list(model)[last_layer].register_forward_hook(_hook('probe'))
probe = LinearProbe(n_embd, num_classes).to(device)
optimizer = optim.Adam(probe.parameters(), lr=lr)
criterion = nn.CrossEntropyLoss()
for _ in range(epochs):
probe.train()
perm = np.random.permutation(len(probe_data))
for b in range(0, len(probe_data), batch_size):
batch = [probe_data[i] for i in perm[b:b + batch_size]]
batch.sort(key=lambda x: len(x['ids']), reverse=True)
x = pad_sequence([it['ids'] for it in batch], batch_first=True, padding_value=0)
with torch.no_grad():
model(x)
h = _acts['probe']
p_in, p_tgt = [], []
for i, it in enumerate(batch):
p_in.append(h[i, it['probe_indices'], :])
p_tgt.append(torch.tensor(it['labels'], dtype=torch.long, device=device))
optimizer.zero_grad()
loss = criterion(probe(torch.cat(p_in)), torch.cat(p_tgt))
loss.backward()
optimizer.step()
# Training accuracy (sanity check)
probe.eval()
correct = total = 0
with torch.no_grad():
for b in range(0, min(len(probe_data), 200), batch_size):
batch = sorted(probe_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['probe']
for i, it in enumerate(batch):
preds = probe(h[i, it['probe_indices'], :]).argmax(dim=1)
lab = torch.tensor(it['labels'], dtype=torch.long, device=device)
correct += (preds == lab).sum().item()
total += len(it['labels'])
hook.remove()
print(f" Last-layer probe train acc = {correct / total * 100:.1f}%" if total else " (no train data)")
return probe
def train_all_layer_probes(model, probe_data, n_layers, n_embd, num_classes, device,
epochs, lr, batch_size):
"""Train a separate linear probe on every layer, then pick the layer whose probe
reaches the highest train accuracy. Features at the probe positions are cached with
a single forward pass per batch (hooks on all layers), so the per-layer probes are
trained on cached activations without extra model forwards.
Returns (best_layer, best_probe, accs) where best_layer is 0-indexed and accs is the
per-layer train-accuracy list."""
block_list = get_block_list(model)
# Register a hook on every layer to capture its output for the current batch.
layer_acts = {}
def make_hook(idx):
def fn(_m, _i, o):
layer_acts[idx] = o.detach()
return fn
hooks = [block_list[li].register_forward_hook(make_hook(li)) for li in range(n_layers)]
# Cache per-layer features at the probe positions (single forward pass per batch).
feats = {li: [] for li in range(n_layers)}
labels_all = []
with torch.no_grad():
for b in range(0, len(probe_data), batch_size):
batch = sorted(probe_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)
for i, it in enumerate(batch):
idxs = it['probe_indices']
for li in range(n_layers):
feats[li].append(layer_acts[li][i, idxs, :].float())
labels_all.append(torch.tensor(it['labels'], dtype=torch.long, device=device))
for hk in hooks:
hk.remove()
if not labels_all:
raise RuntimeError("No probe-training data collected.")
Y = torch.cat(labels_all)
feats = {li: torch.cat(feats[li]) for li in range(n_layers)}
N = Y.size(0)
best_layer, best_probe, best_acc, accs = 0, None, -1.0, []
for li in range(n_layers):
X = feats[li]
probe = LinearProbe(n_embd, num_classes).to(device)
optimizer = optim.Adam(probe.parameters(), lr=lr)
criterion = nn.CrossEntropyLoss()
for _ in range(epochs):
probe.train()
perm = torch.randperm(N, device=device)
for s in range(0, N, 4096):
sel = perm[s:s + 4096]
optimizer.zero_grad()
loss = criterion(probe(X[sel]), Y[sel])
loss.backward()
optimizer.step()
probe.eval()
with torch.no_grad():
acc = (probe(X).argmax(dim=1) == Y).float().mean().item()
accs.append(acc)
print(f" L{li + 1:>2} probe train acc = {acc * 100:.1f}%")
if acc > best_acc:
best_acc, best_layer, best_probe = acc, li, probe
# free this layer's cached features once its probe is trained
feats[li] = None
print(f" >> best probe layer = L{best_layer + 1} (train acc {best_acc * 100:.1f}%)")
return best_layer, best_probe, accs
TURN_ORDER = ['F', 'L', 'R', 'T']
def js_divergence(p, q, eps=1e-12):
"""Jensen-Shannon divergence (base-2, in [0,1]) between two discrete distributions."""
p = np.asarray(p, dtype=np.float64) + eps
q = np.asarray(q, dtype=np.float64) + eps
p /= p.sum()
q /= q.sum()
m = 0.5 * (p + q)
kl = lambda a, b: float(np.sum(a * np.log2(a / b)))
return 0.5 * kl(p, m) + 0.5 * kl(q, m)
# ----------------------------------------------------------------------------
# Clean next-step reference table: (node, facing) -> avg distribution over {F,L,R,T}
# ----------------------------------------------------------------------------
def build_reference_table(model, lines, stoi, no_task_tag, num_nodes, grid_n, device,
max_samples, task_ops, batch_size=64):
"""Forward clean paths and average the model's next-step action distribution at every
visited state. The distribution is the full-vocab softmax restricted to the task's
action set and renormalized. Keyed by state (Task C: (node,facing); Task A: node)."""
action_order = task_ops['action_order']
tids = [task_ops['action_ids'][a] for a in action_order]
n_act = len(action_order)
seqs = []
for line in lines:
if len(seqs) >= max_samples:
break
parts = line.split()
if ':' not in parts:
continue
colon_idx = parts.index(':')
try:
src = int(parts[0]) if no_task_tag else int(parts[1])
ids = [stoi[t] for t in parts]
except (KeyError, ValueError, IndexError):
continue
positions, states = task_ops['parse_reference'](parts, colon_idx, src, grid_n, num_nodes)
if positions:
seqs.append({'ids': torch.tensor(ids, dtype=torch.long, device=device),
'positions': positions, 'states': states})
acc, cnt = {}, {}
for b in range(0, len(seqs), batch_size):
batch = sorted(seqs[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)
with torch.no_grad():
# Pass dummy targets so the model returns logits at ALL positions
# (with targets=None, GPT only returns the last position's logits).
logits, _ = model(x, x)
full = F.softmax(logits, dim=-1)
for i, it in enumerate(batch):
pall = full[i, it['positions'], :][:, tids].cpu().numpy()
for row, st in zip(pall, it['states']):
s = row.sum()
if s <= 0:
continue
row = row / s
if st not in acc:
acc[st] = np.zeros(n_act, dtype=np.float64)
cnt[st] = 0
acc[st] += row
cnt[st] += 1
ref = {st: acc[st] / cnt[st] for st in acc}
print(f" Reference table covers {len(ref)} distinct {task_ops['state_name']} states.")
return ref
# ----------------------------------------------------------------------------
# Post-detour completion: greedily walk to the target, measure reach accuracy
# ----------------------------------------------------------------------------
def run_completion(model, seq, states, targets, task_ops, G, grid_n, num_nodes,
max_steps, max_ctx, device, temperature=1.0):
"""From the detour-prefixed sequence, let the model autoregressively generate the rest
of the path and advance the true state. With temperature>0 the next token is sampled
(temperature=1.0 matches the training distribution); with temperature<=0 it is greedy
argmax. Returns list[bool] per trial. The test protocol is the SAME for every task: the
model generates until it ENDS the path on its own (emits a non-move / EOS token), and a
trial counts as solved ONLY if it terminates while standing on the target -- i.e. the
generated path must END AT the target (结束在终点). Merely stepping onto / passing
through the target mid-path does NOT count. Per-trial outcome in
{'reached', 'illegal', 'not_on_target', 'no_end'}:
- 'reached' : model emitted an end token while on the target (正确结束在终点)
- 'illegal' : emitted a move that walks into a wall (走了非法路径)
- 'not_on_target' : emitted a non-move token (ended) while not on the target (结束但不在目标)
- 'no_end' : never emitted an end / ran out of max_steps (没有输出结束)
Task E note: the encoding is label-compressed -- one emitted ``(dir, label)`` pair
means "advance in `dir` until reaching the next node whose label == `label`"
(intermediate non-matching nodes are skipped, exactly as the training data is
generated). So for Task E we let the model emit BOTH the direction and the label and
then walk multiple grid cells until that label is hit (or a wall -> illegal). Decoding
each pair as a single grid step would systematically derail the walk and cap reach_acc
far below the model's true ability. Other tasks (group_size==1) keep the single-step
decode."""
B = seq.size(0)
action_ids = task_ops['action_ids']
id2action = {v: k for k, v in action_ids.items()}
gs = task_ops['group_size']
node_label_id = task_ops.get('node_label_id')
dummy_tok = action_ids[task_ops['action_order'][0]]
cur = [dict(s) for s in states]
done = [False] * B
success = [False] * B
reason = [None] * B
for i in range(B):
if cur[i]['node'] == targets[i]:
success[i] = done[i] = True
reason[i] = 'reached'
work = seq.clone()
def sample_next(ctx_tokens):
# NOTE: do NOT break when work exceeds max_ctx. For long detours (k >= block_size)
# the prefix already exceeds the context window; we just slide the window
# (ctx = work[:, -max_ctx:]) like the probe-eval loop in main().
cc = ctx_tokens if max_ctx is None else ctx_tokens[:, -max_ctx:]
with torch.no_grad():
lg, _ = model(cc)
if temperature <= 0:
return lg[:, -1, :].argmax(dim=1)
pr = torch.softmax(lg[:, -1, :] / temperature, dim=1)
return torch.multinomial(pr, num_samples=1).squeeze(1)
if gs == 2:
# ---- Task E: run-level (label-compressed) decoding ----
def label_tok_of(node):
return node_label_id({'node': node})
for _ in range(max_steps):
if all(done):
break
nxt_d = sample_next(work)
d_str = [None] * B
d_col = []
for i in range(B):
if done[i]:
d_col.append(dummy_tok)
continue
tok = int(nxt_d[i].item())
action = id2action.get(tok)
if action is None: # non-move token => the model ENDED the path
done[i] = True
if cur[i]['node'] == targets[i]:
success[i] = True
reason[i] = 'reached' # ended exactly on the target (结束在终点)
else:
reason[i] = 'not_on_target'
d_col.append(tok)
continue
d_str[i] = action
d_col.append(tok)
# Forward once more with the direction appended to read the model's label token.
work_d = torch.cat(
[work, torch.tensor(d_col, dtype=torch.long, device=device).unsqueeze(1)], dim=1)
nxt_l = sample_next(work_d)
rows = []
for i in range(B):
if d_str[i] is None: # done before / just ended this step
rows.append([d_col[i], dummy_tok])
continue
l_tok = int(nxt_l[i].item())
d = d_str[i]
node = cur[i]['node']
illegal = False
cnt = 0
while True: # walk in d until the emitted label is hit
if d not in get_legal_dirs(G, node, grid_n):
illegal = True
break
node = step_node(node, d, grid_n)
cnt += 1
if label_tok_of(node) == l_tok:
break # arrived at the pair's endpoint (labelled node)
if cnt >= grid_n: # safety: corridor longer than the grid
illegal = True
break
cur[i]['node'] = node
rows.append([d_col[i], l_tok])
# Reach is only granted when the model itself ENDS the path (emits a non-move /
# EOS token) while standing on the target -- handled in the direction loop above.
# Merely stepping onto / passing through the target does NOT count. Here we only
# advance the true state and flag walls.
if illegal:
done[i] = True
reason[i] = 'illegal'
work = torch.cat(
[work, torch.tensor(rows, dtype=torch.long, device=device)], dim=1)
for i in range(B):
if reason[i] is None:
reason[i] = 'no_end'
return success, reason
# ---- Task A/C/H: single-step decoding ----
for _ in range(max_steps):
if all(done):
break
nxt = sample_next(work)
rows = []
for i in range(B):
if done[i]:
rows.append([dummy_tok] * gs)
continue
tok = int(nxt[i].item())
action = id2action.get(tok)
if action is None: # non-move token => the model ENDED the path
done[i] = True
if cur[i]['node'] == targets[i]:
success[i] = True
reason[i] = 'reached' # ended exactly on the target (结束在终点)
else:
reason[i] = 'not_on_target' # ended, but not on the target
rows.append([tok] + [dummy_tok] * (gs - 1))
continue
legal = task_ops['legal_actions'](G, cur[i], grid_n)
if action not in legal: # illegal move -> walked into a wall
done[i] = True
reason[i] = 'illegal'
rows.append([tok] + [dummy_tok] * (gs - 1))
continue
task_ops['advance'](cur[i], action, grid_n)
rows.append([tok])
# Reach is only granted when the model itself ENDS the path on the target (handled
# above). Stepping onto the target mid-path does NOT auto-succeed.
work = torch.cat(
[work, torch.tensor(rows, dtype=torch.long, device=device)], dim=1)
for i in range(B):
if reason[i] is None: # never ended within max_steps
reason[i] = 'no_end'
return success, reason
def main():
args = parse_args()
grid_n = int(math.sqrt(args.num_nodes))
k_list = sorted(int(x) for x in args.k_list.split(','))
tasks_tag = f"{args.tasks}_{args.path_type}" + ("_NT" if args.no_task_tag else "")
# transformer-nextlat checkpoints carry the _NL suffix (encapsulated NextLat).
ckpt_tag = tasks_tag
if args.model == 'transformer-nextlat':
ckpt_tag = f"{ckpt_tag}_NL"
if args.NLS:
ckpt_tag = f"{ckpt_tag}_NLS"
data_dir = f'data/maze/{args.num_nodes}'
out_dir = f'out/{args.model.replace("-", "_")}/maze_{args.config}_{args.num_nodes}{"_NT" if args.no_task_tag else ""}/'
# --- Load meta / graph / model ---
meta = pickle.load(open(f'{data_dir}/meta_{tasks_tag}.pkl', 'rb'))
stoi, itos = meta['stoi'], meta['itos']
G = nx.read_graphml(f'{data_dir}/maze_graph_{tasks_tag}.graphml')
ckpt_path = f'{out_dir}/{args.ckpt_iter}_ckpt_maze_{ckpt_tag}_{format_count(args.num_train_dataset)}.pt'
checkpoint = torch.load(ckpt_path, map_location=args.device, weights_only=False)
model, conf = build_model_from_checkpoint(checkpoint, args.model, args.device)
last_layer = conf.n_layer - 1
task_ops = make_task_ops(args.tasks, stoi, G)
action_order = task_ops['action_order']
action_ids = task_ops['action_ids']
num_classes = args.num_nodes * task_ops['label_factor']
# k_list is interpreted in MOVE units (number of injected detour moves), consistent
# across all tasks. Each move emits group_size tokens (Task E: 2 tokens = a (dir,
# label) pair; other tasks: 1 token), so a detour of k moves appends k * group_size
# tokens to the sequence (e.g. Task E k=150 -> 300 tokens; other tasks k=150 -> 150).
gs = task_ops['group_size']
move_set = set(k_list)
max_move = max(k_list)
# --- Train probe on ALL layers; keep the best layer (current state) ---
train_lines = load_lines(f"{data_dir}/train_{tasks_tag}_{format_count(args.num_train_dataset)}.txt")
random.shuffle(train_lines)
print(f"--- Training per-layer probes ({task_ops['state_name']}) on {args.probe_train_samples} sequences ---")
probe_data = collect_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)} probe-training sequences.")
best_layer, probe, layer_accs = train_all_layer_probes(
model, probe_data, conf.n_layer, conf.n_embd,
num_classes,
args.device, args.probe_epochs, args.probe_lr, args.probe_batch_size)
probe.eval()
# --- Build clean next-step reference table (for matched_jsd) ---
print(f"--- Building clean next-step reference table on {args.ref_samples} sequences ---")
ref_table = build_reference_table(model, train_lines, stoi, args.no_task_tag, args.num_nodes,
grid_n, args.device, args.ref_samples, task_ops)
# --- Build trials: prefix = prompt up to and including ':' ---
test_lines = load_lines(f"{data_dir}/test_{tasks_tag}_{format_count(args.num_test_dataset)}.txt")
random.shuffle(test_lines)
trials = []
for line in test_lines:
if len(trials) >= args.num_trials:
break
parts = line.split()
if ':' not in parts:
continue
colon_idx = parts.index(':')
try:
source = int(parts[0]) if args.no_task_tag else int(parts[1])
target = int(parts[1]) if args.no_task_tag else int(parts[2])
prompt_ids = [stoi[t] for t in parts[:colon_idx + 1]]
except (KeyError, ValueError, IndexError):
continue
trials.append({'prompt_ids': prompt_ids, 'source': source, 'target': target})
print(f"Built {len(trials)} trials. Detour lengths k = {k_list} "
f"(moves; {gs} token(s)/move => +{gs}*k tokens appended to the sequence)\n")
# --- Accumulators per k ---
probe_correct = {k: 0 for k in k_list}
probe_total = {k: 0 for k in k_list}
illegal_mass_sum = {k: 0.0 for k in k_list} # prob mass on illegal turns
illegal_total = {k: 0 for k in k_list}
illegal_mass_cond_sum = {k: 0.0 for k in k_list} # conditioned on probe correct
illegal_cond_total = {k: 0 for k in k_list}
matched_jsd_sum = {k: 0.0 for k in k_list} # JSD vs clean reference at same state
matched_total = {k: 0 for k in k_list}
matched_jsd_cond_sum = {k: 0.0 for k in k_list} # conditioned on probe correct
matched_cond_total = {k: 0 for k in k_list}
complete_success = {k: 0 for k in k_list} # reached target after detour
complete_total = {k: 0 for k in k_list}
fail_illegal = {k: 0 for k in k_list} # 走了非法路径 (walked into a wall)
fail_not_on_target = {k: 0 for k in k_list} # 没有结束在目标上 (ended off-target)
fail_no_end = {k: 0 for k in k_list} # 没有输出结束 (never ended)
max_ctx = getattr(conf, 'block_size', None)
completion_max_steps = args.num_nodes # cap on post-detour greedy walk
# Group trials by prompt length so each batch is uniform (no padding).
groups = {}
for tr in trials:
groups.setdefault(len(tr['prompt_ids']), []).append(tr)
device = args.device
for L0, group in groups.items():
for cs in tqdm(range(0, len(group), args.batch_size),
desc=f"detour (prompt_len={L0})"):
chunk = group[cs:cs + args.batch_size]
seq = torch.tensor([tr['prompt_ids'] for tr in chunk], dtype=torch.long, device=device)
states = [task_ops['init_state'](tr['source']) for tr in chunk]
hook = get_block_list(model)[best_layer].register_forward_hook(_hook('eval'))
for step in range(max_move + 1): # step == #detour moves in seq (1 move = gs tokens)
ctx_eval = seq if max_ctx is None else seq[:, -max_ctx:]
with torch.no_grad():
logits, _ = model(ctx_eval)
last_logits = logits[:, -1, :]
probs = F.softmax(last_logits, dim=-1)
act_last = _acts['eval'][:, -1, :] # last-layer output at final position
if step in move_set:
kk = step # move-count key for the accumulators
preds = probe(act_last).argmax(dim=1)
for si in range(len(chunk)):
st = states[si]
# (1) probe accuracy
pc = int(preds[si].item() == task_ops['label'](st))
probe_correct[kk] += pc
probe_total[kk] += 1
# legal / illegal actions at the true state
legal_acts = set(task_ops['legal_actions'](G, st, grid_n))
illegal_acts = [a for a in action_order if a not in legal_acts]
# (2)/(3) illegal probability mass
ill = sum(probs[si, action_ids[a]].item() for a in illegal_acts)
illegal_mass_sum[kk] += ill
illegal_total[kk] += 1
if pc:
illegal_mass_cond_sum[kk] += ill
illegal_cond_total[kk] += 1
# (4)/(5) matched-state next-step JSD vs clean reference
ref = ref_table.get(task_ops['ref_key'](st))
if ref is not None:
p4 = np.array([probs[si, action_ids[a]].item() for a in action_order],
dtype=np.float64)
ssum = p4.sum()
if ssum > 0:
jsd = js_divergence(p4 / ssum, ref)
matched_jsd_sum[kk] += jsd
matched_total[kk] += 1
if pc:
matched_jsd_cond_sum[kk] += jsd
matched_cond_total[kk] += 1
# (6) reach-target accuracy: let the model walk to completion
targets_b = [tr['target'] for tr in chunk]
succ, reasons = run_completion(model, seq, states, targets_b, task_ops, G,
grid_n, args.num_nodes, completion_max_steps,
max_ctx, device, temperature=args.temperature)
for s, r in zip(succ, reasons):
complete_total[kk] += 1
complete_success[kk] += int(s)
if r == 'illegal':
fail_illegal[kk] += 1
elif r == 'not_on_target':
fail_not_on_target[kk] += 1
elif r == 'no_end':
fail_no_end[kk] += 1
if step == max_move:
break
# Pick lowest-probability legal action; append the move and advance the
# true state. Task A/C: one token. Task E: a (dir, label) pair, where the
# direction prefers to differ from the previous one so each injected run
# has length 1 -> the (dir, label-of-new-node) pair stays on-distribution.
gs = task_ops['group_size']
node_label_id = task_ops.get('node_label_id')
rows = []
for si, st in enumerate(states):
legal_acts = task_ops['legal_actions'](G, st, grid_n)
if not legal_acts:
row = [action_ids[action_order[0]]]
if gs == 2:
row.append(node_label_id(st))
rows.append(row)
continue
pool = legal_acts
if task_ops['avoid_prev'] and st.get('prev_dir') is not None:
alt = [a for a in legal_acts if a != st['prev_dir']]
if alt:
pool = alt
move = min(pool, key=lambda m: probs[si, action_ids[m]].item())
task_ops['advance'](st, move, grid_n)
if task_ops['avoid_prev']:
st['prev_dir'] = move
row = [action_ids[move]]
if gs == 2:
row.append(node_label_id(st))
rows.append(row)
seq = torch.cat(
[seq, torch.tensor(rows, dtype=torch.long, device=device)], dim=1)
hook.remove()
# --- Report ---
width = 132
print("\n" + "=" * width)
print(f"k-step detour results | task={args.tasks} | ckpt={args.ckpt_iter} | best probe layer (L{best_layer + 1} of {conf.n_layer})")
print("=" * width)
print(f" probe_acc : k 步 detour 探针准确率(解 {task_ops['state_name']},取最佳层 L{best_layer + 1},表征保真,↑)")
print(" illegal_m : 模型分给「非法转向」的概率质量(行为读出,↓)")
print(" c_illegal_m : 探针正确时的 illegal_m(条件,↓)")
print(" matched_jsd : 同状态下 detour vs 干净路径下一步分布 JSD(历史不变性,↓)")
print(" c_match_jsd : 探针正确时的 matched_jsd(条件,↓)")
print(f" reach_acc : detour 后采样自回归生成(temp={args.temperature})、模型自行结束且正好停在 target 的比例(结束在终点,↑)")
print(" illegal : reach 失败-走了非法路径(撞墙,占全部 trial 比例,↓)")
print(" not_on_tgt : reach 失败-输出非转向 token 结束但不在 target(占全部 trial 比例,↓)")
print("-" * width)
header = (f"{'k':>4} | {'probe_acc':>10} | {'illegal_m':>10} | {'c_illegal_m':>12} | "
f"{'matched_jsd':>12} | {'c_match_jsd':>12} | {'reach_acc':>10} | "
f"{'illegal':>9} | {'not_on_tgt':>11}")
print(header)
print("-" * width)
for k in k_list:
pa = probe_correct[k] / probe_total[k] * 100 if probe_total[k] else 0.0
im = illegal_mass_sum[k] / illegal_total[k] * 100 if illegal_total[k] else 0.0
c_im = illegal_mass_cond_sum[k] / illegal_cond_total[k] * 100 if illegal_cond_total[k] else 0.0
mj = matched_jsd_sum[k] / matched_total[k] if matched_total[k] else float('nan')
c_mj = matched_jsd_cond_sum[k] / matched_cond_total[k] if matched_cond_total[k] else float('nan')
tot = complete_total[k]
ra = complete_success[k] / tot * 100 if tot else 0.0
fi = fail_illegal[k] / tot * 100 if tot else 0.0
fn = fail_not_on_target[k] / tot * 100 if tot else 0.0
print(f"{k:>4} | {pa:>9.2f}% | {im:>9.2f}% | {c_im:>11.2f}% | {mj:>12.4f} | {c_mj:>12.4f} | "
f"{ra:>9.2f}% | {fi:>8.2f}% | {fn:>10.2f}%")
print("-" * width)
print("若 c_illegal_m / c_match_jsd 仍明显劣化:探针解码的状态不是模型行为的充分统计量,")
print("表征与行为脱钩,探针准确率会高估模型的可靠性。")
print("注:reach_acc + illegal + not_on_tgt 之外的剩余 = 走满 max_steps 仍未结束(f_no_end,通常≈0)。")
# --- Save results (CSV + NPZ) ---
os.makedirs(args.out_dir, exist_ok=True)
train_label = format_count(args.num_train_dataset)
tag = (f"{args.tasks}_{args.path_type}_{args.ckpt_iter}_{train_label}_"
f"{args.model.replace('-', '_')}_{args.config}")
cols = ['k', 'probe_acc', 'illegal_m', 'c_illegal_m', 'matched_jsd',
'c_match_jsd', 'reach_acc', 'illegal', 'not_on_tgt']
table = []
for k in k_list:
pa = probe_correct[k] / probe_total[k] * 100 if probe_total[k] else 0.0
im = illegal_mass_sum[k] / illegal_total[k] * 100 if illegal_total[k] else 0.0
c_im = illegal_mass_cond_sum[k] / illegal_cond_total[k] * 100 if illegal_cond_total[k] else 0.0
mj = matched_jsd_sum[k] / matched_total[k] if matched_total[k] else float('nan')
c_mj = matched_jsd_cond_sum[k] / matched_cond_total[k] if matched_cond_total[k] else float('nan')
tot = complete_total[k]
ra = complete_success[k] / tot * 100 if tot else 0.0
fi = fail_illegal[k] / tot * 100 if tot else 0.0
fn = fail_not_on_target[k] / tot * 100 if tot else 0.0
table.append([k, pa, im, c_im, mj, c_mj, ra, fi, fn])
table = np.array(table, dtype=float)
csv_path = os.path.join(args.out_dir, f'kdetour_{tag}.csv')
with open(csv_path, 'w') as f:
f.write(','.join(cols) + '\n')
for r in table:
f.write(f"{int(r[0])}," + ','.join(f"{v:.6f}" for v in r[1:]) + '\n')
npz_path = os.path.join(args.out_dir, f'kdetour_{tag}.npz')
np.savez(npz_path, table=table, columns=np.array(cols),
k=table[:, 0], best_layer=best_layer + 1, n_layer=conf.n_layer,
layer_probe_acc=np.array(layer_accs, dtype=float) * 100)
print(f"Wrote {csv_path}")
print(f"Wrote {npz_path}")
if __name__ == "__main__":
main()