File size: 5,011 Bytes
0c0ff0e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 | """Plot k-step detour metrics vs k for the architectures on one figure per metric.
Data is loaded automatically from the kdetour result files saved by
maze_kstep_detour_test.py (out/maze_kdetour/kdetour_*.npz, key 'table' with
column names in 'columns'). You only need to set TASK / DATASET / configs
(via the command line, see --help). One PNG is produced per metric in
METRICS, written to out/plot/.
"""
import os
import argparse
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
# ---------------------------------------------------------------------------
# Defaults (overridable on the command line, see --help).
# ---------------------------------------------------------------------------
TASK = 'I1'
DATASET = '10M'
# Model configs: transformer-family uses TF_CONFIG, RNN/SSM-family uses RNN_CONFIG.
TF_CONFIG = '6_6_384'
RNN_CONFIG = '12_384'
# kdetour result settings (match how the .npz files were produced).
CKPT_ITER = 10000
PATH_TYPE = 'RWs'
KDETOUR_DIR = 'out/maze_kdetour'
OUT_DIR = 'out/plot'
# (display name, file model key, is_transformer_family). Configs come from args.
MODEL_SPECS = [
('Transformer', 'transformer', True),
('Transformer-NextLat', 'transformer_nextlat', True),
('Mamba', 'mamba', False),
('Mamba-2', 'mamba2', False),
('Gated-DeltaNet', 'gated_deltanet', False),
('GRU', 'gru', False),
]
MARKERS = ['o', 's', '^', 'D', 'P', 'v']
# Each metric maps to a column name in the kdetour table.
# ylim=None means autoscale (used for JSD which is not a percentage).
METRICS = [
('probe_acc', 'probe accuracy (%)', (-2, 105)),
('c_match_jsd', 'c_match_jsd', None),
('reach_acc', 'reach accuracy (%)', (-2, 105)),
]
def parse_args():
p = argparse.ArgumentParser(description='Plot k-step detour metrics from kdetour npz files.')
p.add_argument('--task', default=TASK)
p.add_argument('--dataset', default=DATASET)
p.add_argument('--tf_config', default=TF_CONFIG)
p.add_argument('--rnn_config', default=RNN_CONFIG)
p.add_argument('--ckpt_iter', type=int, default=CKPT_ITER)
p.add_argument('--path_type', default=PATH_TYPE)
p.add_argument('--kdetour_dir', default=KDETOUR_DIR)
p.add_argument('--out_dir', default=OUT_DIR)
return p.parse_args()
def load_table(args, model_key, config):
"""Return (k array, {col_name: values}) from the kdetour npz, or (None, None)."""
fname = f'kdetour_{args.task}_{args.path_type}_{args.ckpt_iter}_{args.dataset}_{model_key}_{config}.npz'
path = os.path.join(args.kdetour_dir, fname)
if not os.path.exists(path):
print(f"[missing] {path}")
return None, None
d = np.load(path, allow_pickle=True)
if 'table' not in d or 'columns' not in d:
print(f"[no table] {path}")
return None, None
table = np.asarray(d['table'], dtype=float)
cols = [str(c) for c in d['columns']]
by_col = {c: table[:, i] for i, c in enumerate(cols)}
k = by_col.get('k')
return k, by_col
def plot_metric(args, loaded, metric, ylabel, ylim):
plt.figure(figsize=(9, 5.5))
all_k = None
plotted = 0
for (name, key, is_tf), marker in zip(MODEL_SPECS, MARKERS):
k, by_col = loaded[key]
if k is None or metric not in by_col:
continue
config = args.tf_config if is_tf else args.rnn_config
plt.plot(k, by_col[metric], marker=marker, markersize=6, linewidth=2,
label=f'{name} ({config})')
if all_k is None or len(k) > len(all_k):
all_k = k
plotted += 1
if plotted == 0:
print(f"[{metric}] nothing to plot: no kdetour npz files found.")
plt.close()
return
plt.xlabel('detour length k (steps)', fontsize=12)
plt.ylabel(ylabel, fontsize=12)
plt.title(f'k-step detour {metric} (Task {args.task}, {args.dataset})', fontsize=13)
ax = plt.gca()
ticks = [int(x) for x in all_k]
ax.set_xticks(ticks)
ax.set_xticklabels([str(t) for t in ticks])
for t, lbl in zip(ticks, ax.get_xticklabels()):
if t >= 100:
lbl.set_color('red')
if ylim is not None:
plt.ylim(*ylim)
plt.grid(True, alpha=0.3)
plt.legend(fontsize=10, framealpha=0.9)
plt.tight_layout()
out = os.path.join(
args.out_dir,
f'kstep_{metric}_{args.task}_{args.dataset}_{args.tf_config}_{args.rnn_config}.png')
plt.savefig(out, dpi=150)
plt.close()
print(f"Saved figure to {out}")
def main():
args = parse_args()
os.makedirs(args.out_dir, exist_ok=True)
loaded = {}
for name, key, is_tf in MODEL_SPECS:
config = args.tf_config if is_tf else args.rnn_config
loaded[key] = load_table(args, key, config)
for metric, ylabel, ylim in METRICS:
plot_metric(args, loaded, metric, ylabel, ylim)
if __name__ == '__main__':
main()
|