""" 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()