""" Training-trajectory "memory length" figure. For each saved checkpoint (e.g. every 500 iters), run the fixed-readout single-token perturbation test (same as maze_vis_memory.py): always read ONE fixed prediction -- the token at --readout_pos -- and perturb ONE earlier path-step token at a time (positions from --flip_start up to readout_pos-1), measuring KL(clean || perturbed) on that fixed readout as a function of the distance back j = readout_pos - position. Because the readout position never changes, every perturbation is measured under the same context length (no 1/length dilution). That whole KL-vs-j curve is reduced to a single scalar "effective memory length": L = first distance j where the KL curve drops below the absolute threshold --halflife_kl (default 0.1), linearly interpolated. L tells you, on average, how many tokens back a perturbation's influence still reaches -- i.e. how many previous tokens the model effectively attends to. A recency-shortcut model stays at L ~ 1-2; a global state-tracker grows L large. Plotting L against the training iteration shows the LEARNING DYNAMICS: - early checkpoints sit at small L -> model first learns to look ~1 token back - whether L later grows or stays flat -> does it escape the recency shortcut? Overlay the train-loss curve to see whether loss saturates BEFORE L grows (i.e. the recency shortcut already drives loss low while global state is unlearned). Same model set / config flags as maze_vis_memory.py. The two knobs are --flip_start (default 10) and --readout_pos (default 90). Sweep checkpoints with --iters "500,1000,...,10000" or --iter_start/--iter_end/--iter_step. Missing checkpoints are skipped. Gated-Delta needs the dedicated `fla` conda env. Run the whole script there: PYTHONNOUSERSITE=1 conda run -n fla python maze_vis_memory_trajectory.py ... Example: PYTHONNOUSERSITE=1 conda run -n fla python maze_vis_memory_trajectory.py \ --tasks C1 --tf_config 6_6_384 --rec_config 12_384 --num_train 10M \ --iter_start 500 --iter_end 10000 --iter_step 500 --flip_start 10 --readout_pos 90 """ import os import pickle import argparse import numpy as np import torch import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from maze_vis_memory import ( _ensure_numpy_core_alias, build_model, full_logits_any, collect_sequences, fixed_readout_perturb, ) from cli_utils import parse_count, format_count _ensure_numpy_core_alias() # (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='Memory-length vs training-iteration trajectory.') p.add_argument('--tasks', type=str, default='C1', help='Task tag, e.g. A1, C1, E1, H1, I1.') p.add_argument('--tf_config', type=str, default='6_6_384', help='Config for the transformer family (layers_heads_dim).') p.add_argument('--rec_config', type=str, default='12_384', help='Config for the recurrent/SSM family (layers_dim).') p.add_argument('--num_train', type=parse_count, default='10M') 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 (same as maze_vis_memory.py) ---- 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 per perturbation.') 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 used to synthesize an iter-0 untrained baseline when no 0 checkpoint exists. ' 'train_maze.py initializes from torch seed 1337 in non-DDP runs.') # checkpoint sweep p.add_argument('--iters', type=str, default=None, help='Comma-separated checkpoint iters, e.g. "500,1000,1500". ' 'Overrides --iter_start/--iter_end/--iter_step.') p.add_argument('--iter_start', type=int, default=500) p.add_argument('--iter_end', type=int, default=10000) p.add_argument('--iter_step', type=int, default=500) p.add_argument('--models', type=str, default=None, help='Comma-separated subset of display labels to include ' '(default: all). e.g. "Transformer,GRU".') p.add_argument('--eps', type=float, default=1e-6, help='Ignore offsets whose KL is below this when computing L.') p.add_argument('--halflife_kl', type=float, default=0.1, help='Absolute KL threshold: memory length L = first distance where the ' 'KL curve drops below this value (linearly interpolated).') p.add_argument('--out_dir', type=str, default='out/plot') return p.parse_args() def ckpt_iters(args): if args.iters: return [int(x) for x in args.iters.split(',') if x.strip()] return list(range(args.iter_start, args.iter_end + 1, args.iter_step)) def checkpoint_path(model_type, config, suffix, ckpt_iter, args): 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 '') return os.path.join(out_dir, f'{ckpt_iter}_ckpt_maze_{tag}_{train_label}.pt') def load_checkpoint_model(ckpt_path, model_type, device): 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(model_type, config, suffix, args, device, reference_iters): """Create an iter-0 baseline from the model_args stored in the first available ckpt.""" ref_path = None for it in reference_iters: if it == 0: continue candidate = checkpoint_path(model_type, config, suffix, it, args) if os.path.exists(candidate): ref_path = candidate break if ref_path is None: raise FileNotFoundError('No nonzero checkpoint found to infer model_args for iter 0.') 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 load_model(model_type, config, suffix, ckpt_iter, args, device, reference_iters): ckpt_path = checkpoint_path(model_type, config, suffix, ckpt_iter, args) if os.path.exists(ckpt_path): return load_checkpoint_model(ckpt_path, model_type, device) if ckpt_iter == 0: return load_untrained_model(model_type, config, suffix, args, device, reference_iters) raise FileNotFoundError(ckpt_path) def effective_memory_length(ds, kl, eps, thresh_kl=0.1): """Memory length L (tokens) = first distance where the KL-vs-offset curve drops below the absolute threshold `thresh_kl`, linearly interpolated.""" d = np.asarray(ds, dtype=float) w = np.asarray(kl, dtype=float) keep = (d >= 1) & np.isfinite(w) & (w > eps) if not keep.any(): return float('nan') dk, wk = d[keep], w[keep] pk = int(np.argmax(wk)) # peak position within the kept region # if even the strongest (peak) influence is below the threshold, the curve never # crosses 0.1 from above -> no measurable memory; floor at the smallest distance. if wk[pk] <= thresh_kl: return float(dk[0]) # walk forward from the peak to the first sub-threshold offset for j in range(pk, len(wk)): if wk[j] <= thresh_kl: if j == 0: return float(dk[0]) # linear interpolation between (dk[j-1], wk[j-1]) and (dk[j], wk[j]); # here wk[j-1] > thresh >= wk[j], so t in [0,1] and the result is bounded. w0, w1 = wk[j - 1], wk[j] d0, d1 = dk[j - 1], dk[j] if w0 == w1: return float(d1) t = (w0 - thresh_kl) / (w0 - w1) return float(d0 + t * (d1 - d0)) # never crosses within the window: report the largest kept offset (right-censored) return float(dk[-1]) def main(): args = parse_args() device = args.device if torch.cuda.is_available() else 'cpu' wanted = set(s.strip() for s in args.models.split(',')) if args.models else None 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 alphabet from the actual path region (after the colon). 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]}') iters = ckpt_iters(args) print(f'Sweeping {len(iters)} checkpoints: {iters}') # results[label] = list of (iter, L) results = {} for display, model_type, kind, suffix in MODELS: if wanted is not None and display not in wanted: continue config = args.tf_config if kind == 'tf' else args.rec_config label = f'{display} {config}' series = [] for it in iters: try: model = load_model(model_type, config, suffix, it, args, device, iters) except FileNotFoundError: continue except ImportError as e: print(f' ! skip {label}: {e}') break js, kl_curve = fixed_readout_perturb(model, seqs, args, device, index_ids) L = effective_memory_length(js, kl_curve, args.eps, thresh_kl=args.halflife_kl) series.append((it, L)) print(f' [{label}] iter {it}: L={L:.2f}') del model if device.startswith('cuda'): torch.cuda.empty_cache() if series: results[label] = series if not results: raise SystemExit('No checkpoints 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}_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))) all_iters = sorted({it for series in results.values() for it, _ in series}) for (label, series), c in zip(results.items(), colors): xs = [it for it, _ in series] ys = [L for _, L in series] ax.plot(xs, ys, '-o', color=c, lw=2, ms=4, label=label) ax.set_xlabel('training iteration') ax.set_ylabel(f'effective memory length L (tokens, KL<{args.halflife_kl:g})') ax.set_title(f'Memory length vs training on Task {args.tasks} ' f'({train_label}, {args.split}, readout={args.readout_pos})') ax.set_ylim(bottom=0) if all_iters: ax.set_xlim(all_iters[0], all_iters[-1]) ax.legend() ax.grid(alpha=0.3) fig.tight_layout() png = os.path.join(args.out_dir, f'memtraj_{tag}.png') fig.savefig(png, dpi=130) print(f'Wrote {png}') # also dump the raw numbers for overlaying with the loss curve later npz = os.path.join(args.out_dir, f'memtraj_{tag}.npz') np.savez(npz, **{label: np.array(series) for label, series in results.items()}) print(f'Wrote {npz}') if __name__ == '__main__': main()