File size: 17,504 Bytes
34e468d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
"""
Cross-architecture "memory length" figure.

Hold the readout fixed: for every sequence we always look at the SAME prediction
-- the distribution that predicts the token at --readout_pos. Then we perturb ONE
earlier path-step token at a time (positions from --flip_start up to readout_pos-1,
one position per trial) and measure KL(clean || perturbed) on that single fixed
readout.

Because the readout position (hence the context length) never changes, every
perturbation is measured under the same length, avoiding the 1/length dilution of
the older "flip-once read-everywhere" test (a flip in a length-20 context counts
~1/20, in length-80 ~1/80). A model that keeps a far token alive shows a high, flat
curve; a recent-steps shortcut decays fast.

The x-axis is the distance back from the readout, j = readout_pos - flipped position.

One run draws all six architectures together:
    Transformer, Nextlat (transformer-nextlat), Mamba, Mamba-2, Gated-Delta, GRU

Per-architecture configs are set manually via --tf_config (transformer family) and
--rec_config (recurrent / SSM family). Supports Task A/C/E/H/I.

Gated-Delta needs the dedicated `fla` conda env (flash-linear-attention + triton).
To include it, run this whole script in that env, e.g.:
    PYTHONNOUSERSITE=1 conda run -n fla python maze_vis_memory.py ...
Any model whose checkpoint is missing or fails to load is skipped with a warning.

Example (Task A):
    conda run -n fla python maze_vis_memory.py --tasks A1 \
        --tf_config 3_1_256 --rec_config 6_256 --num_train 500K \
        --ckpt_iter 10000 --flip_start 10 --readout_pos 90
"""

import os
import sys
import glob
import pickle
import argparse
import importlib

import numpy as np
import torch
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

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


def _ensure_numpy_core_alias():
    """Alias numpy.core <-> numpy._core so pickled checkpoints load regardless of
    the NumPy major version they were saved with. NumPy 2.0 renamed the private
    ``numpy.core`` package to ``numpy._core``; old pickles reference one name and
    new ones the other, so we register whichever is missing."""
    for src, dst in (('numpy._core', 'numpy.core'), ('numpy.core', 'numpy._core')):
        try:
            mod = importlib.import_module(src)
        except Exception:
            continue
        sys.modules.setdefault(dst, mod)
        for sub in ('multiarray', 'numeric', '_multiarray_umath', 'umath'):
            try:
                m = importlib.import_module(f'{src}.{sub}')
            except Exception:
                continue
            sys.modules.setdefault(f'{dst}.{sub}', m)


def build_model(model_type, model_args):
    """Instantiate the architecture named by ``model_type`` from a model_args dict.
    The model is returned on CPU; callers move it to the target device."""
    if model_type == 'mamba':
        return Mamba(MambaConfig(**model_args))
    if model_type == 'mamba2':
        return Mamba2(Mamba2Config(**model_args))
    if model_type == 'gated-deltanet':
        return GatedDeltaNet(GatedDeltaNetConfig(**model_args))
    if model_type == 'gru':
        return GRU(GRUConfig(**model_args))
    if model_type == 'transformer-nextlat':
        return TransformerNextLat(TransformerNextLatConfig(**model_args))
    if model_type == 'transformer-rope':
        return GPTRoPE(GPTRoPEConfig(**model_args))
    return GPT(GPTConfig(**model_args))


def full_logits_any(model, idx):
    """Return full per-position logits (B, L, V) for any architecture.

    Every model here only projects the last position when called without targets
    (an inference-time optimization), so we pass ``targets=idx`` to force the
    lm_head over all positions. The returned loss is ignored."""
    out = model(idx, targets=idx)
    return out[0] if isinstance(out, (tuple, list)) else out


def collect_sequences(seq_path, stoi, readout_pos, num_seqs):
    """Load up to ``num_seqs`` tokenized sequences that are at least ``readout_pos``
    tokens long. Returns a list of (ids_list, colon_index) where colon_index is the
    position of the ':' separator token in the sequence."""
    seqs = []
    with open(seq_path) as f:
        for line in f:
            parts = line.split()
            if ':' not in parts:
                continue
            colon = parts.index(':')
            try:
                ids = [stoi[t] for t in parts]
            except KeyError:
                continue
            if len(ids) < readout_pos:
                continue
            seqs.append((ids, colon))
            if len(seqs) >= num_seqs:
                break
    return seqs


_ensure_numpy_core_alias()


# --------- manually set the six models here (config picked by --tf_config/--rec_config) ---------
# (display label, model_type, config_kind 'tf'|'rec', checkpoint suffix)
MODELS = [
    ('Transformer',  'transformer',          'tf',  ''),
    ('Nextlat',      'transformer-nextlat',  'tf',  'NL'),
    ('Mamba',        'mamba',                'rec', ''),
    ('Mamba-2',      'mamba2',               'rec', ''),
    ('Gated-Delta',  'gated-deltanet',       'rec', ''),
    ('GRU',          'gru',                  'rec', ''),
]


def parse_args():
    p = argparse.ArgumentParser(description='Cross-architecture memory-length figure (Task A/C/E/H/I).')
    p.add_argument('--tasks', type=str, default='A1', help='Task tag, e.g. A1, C1, E1, H1, I1.')
    p.add_argument('--tf_config', type=str, default='3_1_256',
                   help='Config for the transformer family (layers_heads_dim), e.g. 3_1_256 or 12_12_576.')
    p.add_argument('--rec_config', type=str, default='6_256',
                   help='Config for the recurrent/SSM family (layers_dim), e.g. 6_256 or 24_576.')
    p.add_argument('--num_train', type=parse_count, default='500K')
    p.add_argument('--ckpt_iter', type=int, default=10000)
    p.add_argument('--path_type', type=str, default='RWs')
    p.add_argument('--num_nodes', type=int, default=100)
    p.add_argument('--dataset', type=str, default='maze')
    p.add_argument('--device', type=str, default='cuda:0')
    p.add_argument('--split', type=str, default='train', choices=['test', 'train'])
    p.add_argument('--test_size', type=str, default='10K')
    # ---- the two knobs of the test ----
    p.add_argument('--flip_start', type=int, default=10,
                   help='Start perturbing from this token position, then sweep one position '
                        'at a time up to readout_pos-1.')
    p.add_argument('--readout_pos', type=int, default=90,
                   help='Always read the prediction of the token at this position; only this '
                        'one fixed prediction is measured.')
    p.add_argument('--num_seqs', type=int, default=400)
    p.add_argument('--batch_size', type=int, default=384)
    p.add_argument('--seed', type=int, default=0)
    p.add_argument('--init_seed', type=int, default=1337,
                   help='Seed for the random init used when --ckpt_iter 0 (untrained baseline).')
    p.add_argument('--out_dir', type=str, default='out/plot')
    return p.parse_args()


def load_model(model_type, config, suffix, args, device):
    out_dir = f"out/{model_type.replace('-', '_')}/{args.dataset}_{config}_{args.num_nodes}"
    train_label = format_count(args.num_train)
    tag = f'{args.tasks}_{args.path_type}' + (f'_{suffix}' if suffix else '')
    if args.ckpt_iter == 0:
        return load_untrained_model(out_dir, tag, train_label, model_type, args, device)
    ckpt_path = os.path.join(out_dir, f'{args.ckpt_iter}_ckpt_maze_{tag}_{train_label}.pt')
    print(f'[{model_type}/{config}] loading {ckpt_path}')
    ckpt = torch.load(ckpt_path, map_location=device, weights_only=False)
    mt = ckpt.get('model_type', model_type)
    model = build_model(mt, ckpt['model_args']).to(device)
    model.load_state_dict({k.replace('_orig_mod.', ''): v for k, v in ckpt['model'].items()})
    model.eval()
    return model


def load_untrained_model(out_dir, tag, train_label, model_type, args, device):
    """Build a randomly-initialized (iter-0) baseline from a reference checkpoint's model_args."""
    pattern = os.path.join(out_dir, f'*_ckpt_maze_{tag}_{train_label}.pt')
    candidates = [p for p in glob.glob(pattern)
                  if not os.path.basename(p).startswith('0_ckpt_')]
    if not candidates:
        raise FileNotFoundError(
            f'No reference checkpoint matching {pattern} to infer model_args for iter 0.')
    ref_path = sorted(candidates)[0]
    print(f'[{model_type}/{tag}] iter 0 baseline from model_args of {ref_path}')
    ckpt = torch.load(ref_path, map_location='cpu', weights_only=False)
    mt = ckpt.get('model_type', model_type)
    torch.manual_seed(args.init_seed)
    if torch.cuda.is_available():
        torch.cuda.manual_seed(args.init_seed)
    model = build_model(mt, ckpt['model_args']).to(device)
    model.eval()
    return model


def fixed_readout_perturb(model, seqs, args, device, index_ids):
    """Hold the readout position fixed and perturb ONE earlier token at a time.

    For every sequence we always read the SAME prediction -- the distribution that
    predicts the token at --readout_pos (conditioned on the tokens before it). We
    then flip a single path-step token at position p (for p from --flip_start up to
    readout_pos-1) and measure KL(clean || perturbed) on that one fixed readout.

    Because the readout position (hence the context length) never changes, this
    removes the 1/length dilution confound of the persistence test. Returns
    (js, kl_mean) with j = readout_pos - p (distance back from the readout) and
    kl_mean[j] = mean KL over sequences and alternative flips.

    All perturbed contexts (across every sequence, position and alternative) are
    pooled into one big set and run through the model in batches of --batch_size,
    rather than one sequence at a time -- so the GPU stays saturated.
    """
    R = args.readout_pos
    start = args.flip_start
    index_set = set(index_ids)

    # ---- gather the clean (unperturbed) contexts, one per usable sequence ----
    bases = []                      # (S, R) int64 base contexts
    seq_meta = []                   # (colon, ids_list) per kept sequence
    for ids_list, colon in seqs:
        if len(ids_list) < R:
            continue
        bases.append(ids_list[:R])
        seq_meta.append((colon, ids_list))
    if not bases:
        return np.arange(R), np.full(R, np.nan)
    bases = np.asarray(bases, dtype=np.int64)               # (S, R)
    S = bases.shape[0]

    def _forward_batched(rows_np):
        """rows_np: (N, R) int64 -> softmax over the readout position, (N, V)."""
        outs = []
        for b in range(0, rows_np.shape[0], args.batch_size):
            chunk = torch.from_numpy(rows_np[b:b + args.batch_size]).to(device)
            with torch.no_grad():
                lg = full_logits_any(model, chunk)
            outs.append(torch.softmax(lg[:, R - 1, :], dim=-1))
        return torch.cat(outs, 0)                            # (N, V)

    # clean readout distribution for each sequence
    clean_all = _forward_batched(bases)                      # (S, V) on device

    # ---- build every perturbation (seq, position, alternative) up front ----
    seq_idx, pair_of, pair_p = [], [], []
    triples = []                    # (seq i, position p, alt token)
    pid = -1
    for i, (colon, ids_list) in enumerate(seq_meta):
        lo = max(start, colon + 1)
        for p in range(lo, R):
            orig = ids_list[p]
            if orig not in index_set:
                continue
            pid += 1
            pair_p.append(p)
            for alt in index_ids:
                if alt == orig:
                    continue
                triples.append((i, p, alt))
                seq_idx.append(i)
                pair_of.append(pid)
    if not triples:
        return np.arange(R), np.full(R, np.nan)

    rows_np = bases[[t[0] for t in triples]].copy()          # (N, R)
    for k, (_, p, alt) in enumerate(triples):
        rows_np[k, p] = alt
    seq_idx = np.asarray(seq_idx)
    pair_of = np.asarray(pair_of)
    pair_p = np.asarray(pair_p)
    n_pairs = pid + 1

    # ---- run all perturbed contexts and accumulate KL per (seq, position) ----
    pair_sum = np.zeros(n_pairs)
    pair_cnt = np.zeros(n_pairs)
    for b in range(0, rows_np.shape[0], args.batch_size):
        chunk = torch.from_numpy(rows_np[b:b + args.batch_size]).to(device)
        with torch.no_grad():
            lg = full_logits_any(model, chunk)
        pert = torch.softmax(lg[:, R - 1, :], dim=-1)        # (n, V)
        cl = clean_all[seq_idx[b:b + args.batch_size]]       # (n, V)
        kl = (cl * (torch.log(cl + 1e-12) - torch.log(pert + 1e-12))).sum(-1).cpu().numpy()
        po = pair_of[b:b + args.batch_size]
        np.add.at(pair_sum, po, kl)
        np.add.at(pair_cnt, po, 1)

    # mean over the alternative flips for each (seq, position), then bin by j = R - p
    pair_mean = pair_sum / np.maximum(pair_cnt, 1)
    kl_sum = np.zeros(R)
    cnt = np.zeros(R)
    for pid_i in range(n_pairs):
        j = R - pair_p[pid_i]
        kl_sum[j] += pair_mean[pid_i]
        cnt[j] += 1
    js = np.arange(R)
    kl_mean = np.where(cnt > 0, kl_sum / np.maximum(cnt, 1), np.nan)
    return js, kl_mean


def main():
    args = parse_args()
    device = args.device if torch.cuda.is_available() else 'cpu'

    data_path = f'data/{args.dataset}/{args.num_nodes}'
    with open(f'{data_path}/meta_{args.tasks}_{args.path_type}.pkl', 'rb') as f:
        meta = pickle.load(f)
    stoi = meta['stoi']

    train_label = format_count(args.num_train)
    if args.split == 'train':
        seq_path = f'{data_path}/train_{args.tasks}_{args.path_type}_{train_label}.txt'
    else:
        seq_path = f'{data_path}/test_{args.tasks}_{args.path_type}_{args.test_size}.txt'
    seqs = collect_sequences(seq_path, stoi, args.readout_pos, args.num_seqs)
    print(f'Using {len(seqs)} {args.split} sequences (> {args.readout_pos} tokens)')
    if not seqs:
        raise SystemExit(f'No sequences longer than readout_pos={args.readout_pos} in {seq_path}; '
                         f'lower --readout_pos.')

    # Derive the move/direction alphabet from the actual path region (after the colon).
    # Different tasks encode steps differently (e.g. H uses digits 1-4, A uses N/S/E/W),
    # so read the real step tokens from the data rather than hard-coding them.
    move_ids = set()
    for ids_list, colon in seqs:
        move_ids.update(ids_list[colon + 1:args.readout_pos])
    index_ids = sorted(move_ids)
    itos = {v: k for k, v in stoi.items()}
    print(f'Path-step alphabet ({len(index_ids)}): {[itos.get(i, i) for i in index_ids]}')

    results = {}
    for display, model_type, kind, suffix in MODELS:
        config = args.tf_config if kind == 'tf' else args.rec_config
        label = f'{display} {config}'
        try:
            model = load_model(model_type, config, suffix, args, device)
        except FileNotFoundError:
            print(f'  ! skip {label}: checkpoint not found')
            continue
        except ImportError as e:
            print(f'  ! skip {label}: {e}')
            continue
        js, kl_mean = fixed_readout_perturb(model, seqs, args, device, index_ids)
        kl1 = float(np.nan_to_num(kl_mean)[1]) if kl_mean.size > 1 else float('nan')
        results[label] = dict(js=js, kl=np.nan_to_num(kl_mean), kl1=kl1)
        print(f'  {label}: KL@(j=1)={kl1:.3f}')
        del model
        if device.startswith('cuda'):
            torch.cuda.empty_cache()

    if not results:
        raise SystemExit('No models loaded; nothing to plot.')

    os.makedirs(args.out_dir, exist_ok=True)
    tag = (f'{args.tasks}_{train_label}_{args.tf_config}_{args.rec_config}'
           f'_{args.path_type}_ckpt{args.ckpt_iter}_read{args.readout_pos}_{args.split}')
    fig, ax = plt.subplots(figsize=(8.5, 5.5))
    colors = plt.cm.tab10(np.linspace(0, 1, max(len(results), 3)))
    jmax = args.readout_pos - args.flip_start
    for (label, r), c in zip(results.items(), colors):
        m = (r['js'] >= 1) & (r['js'] <= jmax)
        ax.plot(r['js'][m], r['kl'][m], '-', color=c, lw=2, label=label)
    ax.set_xlabel(f'distance back from the fixed readout at token {args.readout_pos} '
                  f'(j = {args.readout_pos} - flipped position)')
    ax.set_ylabel('effect on the fixed prediction: KL(clean || perturbed)')
    ax.set_title(f'Single-token influence on a fixed readout, Task {args.tasks} '
                 f'({train_label}, {args.split})')
    ax.set_xlim(1, jmax)
    ax.set_ylim(bottom=0)
    ax.legend()
    ax.grid(alpha=0.3)
    fig.tight_layout()
    png = os.path.join(args.out_dir, f'memory_{tag}.png')
    fig.savefig(png, dpi=130)
    print(f'Wrote {png}')
    npz = os.path.join(args.out_dir, f'memory_{tag}.npz')
    np.savez(npz, **{label: np.stack([r['js'], r['kl']]) for label, r in results.items()})
    print(f'Wrote {npz}')


if __name__ == '__main__':
    main()