File size: 5,253 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
"""Plot per-layer probe accuracy for the architectures on one figure.

Data is loaded automatically from the kdetour result files saved by
maze_kstep_detour_test.py (out/maze_kdetour/kdetour_*.npz, key
'layer_probe_acc'). You only need to set TASK / DATASET / configs below.

Horizontal axis = absolute layer number. Because the RNN/SSM models here have
twice as many layers as the transformers, one transformer layer is aligned to
two Mamba/GRU layers: transformer layer i is drawn at x = 2*i. The bottom of
the plot uses two rows of tick labels -- top row = Mamba/GRU layer number,
bottom row = Transformer layer number.
"""
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'


def parse_args():
    p = argparse.ArgumentParser(description='Plot per-layer probe accuracy 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()


# (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']


def load_layer_probe_acc(args, model_key, config):
    """Return (layer_probe_acc array, best_layer int) from the kdetour npz, or
    (None, None) if the file is missing / has no layer_probe_acc."""
    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 'layer_probe_acc' not in d:
        print(f"[no layer_probe_acc] {path}")
        return None, None
    vals = np.asarray(d['layer_probe_acc'], dtype=float)
    best = int(d['best_layer']) if 'best_layer' in d else int(np.argmax(vals) + 1)
    return vals, best


def main():
    args = parse_args()
    os.makedirs(args.out_dir, exist_ok=True)
    out = os.path.join(
        args.out_dir,
        f'layer_probe_acc_{args.task}_{args.dataset}_{args.tf_config}_{args.rnn_config}.png')
    plt.figure(figsize=(10, 5.5))
    # Transformer family = is_tf True; 1 transformer layer spans 2 RNN layers,
    # so transformer layer i is placed at x = 2*i to align with Mamba/GRU.
    parsed = []
    maxx = 1
    for (name, key, is_tf), marker in zip(MODEL_SPECS, MARKERS):
        config = args.tf_config if is_tf else args.rnn_config
        vals, best = load_layer_probe_acc(args, key, config)
        if vals is None or len(vals) == 0:
            parsed.append(None)
            continue
        n = len(vals)
        x = [2 * i for i in range(1, n + 1)] if is_tf else list(range(1, n + 1))
        label = f'{name} ({config})'
        parsed.append((label, x, vals, marker, best))
        maxx = max(maxx, max(x))

    plotted = 0
    for item in parsed:
        if item is None:
            continue
        label, x, vals, marker, best = item
        plt.plot(x, vals, marker=marker, markersize=6, linewidth=2, label=label)
        print(f"{label}: {len(vals)} layers, best = L{best} ({vals[best - 1]:.1f}%)")
        plotted += 1

    if plotted == 0:
        print("Nothing to plot: no kdetour npz files found for these settings.")
        return

    # Two-row tick labels: top row = Mamba/GRU layer, bottom row = Transformer layer.
    ticks = list(range(1, maxx + 1))
    labels = []
    for t in ticks:
        tf = str(t // 2) if t % 2 == 0 else ''
        labels.append(f"{t}\n{tf}")
    plt.xticks(ticks, labels, fontsize=8)

    plt.xlabel('layer  (top: Mamba/GRU layer,  bottom: Transformer layer)', fontsize=11)
    plt.ylabel('probe accuracy (%)', fontsize=12)
    plt.title(f'Per-layer probe accuracy (Task {args.task}, {args.dataset})', fontsize=13)
    plt.ylim(-2, 105)
    plt.grid(True, alpha=0.3)
    plt.legend(fontsize=10, framealpha=0.9)
    plt.tight_layout()
    plt.savefig(out, dpi=150)
    plt.close()
    print(f"Saved figure to {out}")


if __name__ == '__main__':
    main()