# WorldModelForMaze Template Code This is the modified NanoGPT code for studying world model representation for mazes. To configure the environment, we use conda create --name gptenv --file spec-file.txt Note: CLI helpers (e.g., `parse_count` for K/M/B shorthand on dataset sizes) live in [cli_utils.py](cli_utils.py), and filenames now use the formatted count (e.g., 3K instead of 3000). # Mazes ## Data Preparations To create the dataset, we can use python data/maze/create_maze.py The (optional) configurations include parser.add_argument('--grid_size', type=int, default=10, help='Size of the grid (n x n)') parser.add_argument('--edge_prob', type=float, default=0.6, help='Probability to keep an edge in the grid graph') parser.add_argument('--chance_in_train', type=float, default=0.5, help='Chance of a pair being in the training set') parser.add_argument('--num_of_paths', type=int, default=20, help='Number of paths per pair nodes in training dataset') parser.add_argument('--tasks', type=str, default='A:100:100', help='Task identifiers with percentages. Format: "TaskID:train_pct:test_pct,TaskID:train_pct:test_pct,...". Example: "A:100:100" or "A:50:50,B:30:30,C:20:20"') The `--tasks` argument supports multi-task data generation. Task identifiers (A, B, C, D, E, F, G, H) can be specified with their corresponding percentages in the training and test datasets. Currently implemented tasks: Task A (path-finding with absolute NESW moves), Task B (target identification), Task C (path-finding with relative turns L/R/F/T starting facing east), Task H (relative clockwise-index path encoding). The percentages for training and test tasks must each sum to 100%. Example usage: python data/maze/create_maze.py --grid_size=6 --edge_prob=0.5 python data/maze/create_maze.py --grid_size=10 --tasks "A:50:50,B:30:30,C:20:20" # Multi-task with A=50%, B=30%, C=20% Then we convert txt files to bin files by python data/maze/prepare_minigpt.py The (optional) configurations include parser.add_argument('--num_nodes', type=int, default=100, help='Number of nodes in the graph') parser.add_argument('--num_of_paths', type=int, default=20, help='Number of paths per pair nodes in training dataset') ## Model Training and Testing To train the model, we run python train_maze.py The (optional) configurations include parser.add_argument('--dataset', type=str, default='maze', help='Name of the dataset to use') parser.add_argument('--n_layer', type=int, default=1, help='Number of layers (default: 1)') parser.add_argument('--n_head', type=int, default=1, help='Number of attention heads (default: 1)') parser.add_argument('--n_embd', type=int, default=120, help='Size of the embeddings (default: 120)') parser.add_argument('--max_iters', type=int, default=10000, help='Number of Iterations (default: 10000)') parser.add_argument('--num_nodes', type=int, default=100, help='Number of Nodes (default: 100)') parser.add_argument('--num_of_paths', type=int, default=20, help='Number of Paths (default: 20)') parser.add_argument('--multitasks', action=argparse.BooleanOptionalAction, default=True, help='Use multitask data (default: True)') parser.add_argument('--num_train_dataset', type=int, default=50000, help='Number of multitask training entries (supports K/M/B, default: 50000)') parser.add_argument('--num_test_dataset', type=int, default=10000, help='Number of multitask test entries (supports K/M/B, default: 10000)') parser.add_argument('--graph_file', type=str, default=None, help='Optional GraphML path; if provided, load this graph instead of the default') parser.add_argument('--init_ckpt', type=int, default=0, help='Initial checkpoint iteration to resume from (default: 0 means train from scratch)') parser.add_argument('--validation', action=argparse.BooleanOptionalAction, default=False, help='Enable periodic validation and checkpointing (default: False)') parser.add_argument('--local', action='store_true', default=False, help='Disable flash attention for local GPU compatibility (default: False)') parser.add_argument('--path_type', type=str, default='RWa', choices=['RWc', 'RWa', 'RWs'], help='Path generation type: RWc (random walk with cycles), RWa (random walk acyclic, default), RWs (single source random walk)') parser.add_argument('--compile', action=argparse.BooleanOptionalAction, default=True, help='Use PyTorch 2.0 to compile the model (default: True). Disable with --no-compile if you encounter Triton/CUDA errors') parser.add_argument('--batch_size', type=int, default=1024, help='Training batch size (default: 1024). Reduce if you encounter OOM errors') To resume training from a previously saved checkpoint (e.g., iteration 2000): python train_maze.py --n_layer=1 --n_head=2 --n_embd=120 --init_ckpt=2000 To train on a local GPU that doesn't support flash attention (e.g., older laptop GPUs): python train_maze.py --n_layer=1 --n_head=2 --n_embd=120 --local The models are stored in "out_dir = f'out/{model}/{dataset}_{n_layer}_{n_head}_{n_embd}_{num_nodes}'", where `{model}` is selected by `--model {transformer,mamba}` (default `transformer`). For example, transformer checkpoints now live under `out/transformer/...` and Mamba checkpoints under `out/mamba/...`. ### NextLat Training (Next-Latent Prediction) NextLat ([arXiv:2511.05963](https://arxiv.org/abs/2511.05963)) augments standard next-token prediction with an auxiliary latent dynamics loss that encourages the transformer to learn compact belief-state representations. During training, a separate latent dynamics MLP predicts the next hidden state from the current hidden state and the next token embedding. At inference, the latent model is discarded — generation uses the standard GPT architecture unchanged. To train with NextLat enabled: python train_maze.py --tasks A1 --path_type RWs --num_train_dataset 500K --num_test_dataset 10K --num_nodes 100 --n_layer 2 --n_head 1 --n_embd 256 --max_iters 10000 --batch_size 1024 --NextLat Additional NextLat arguments: --NextLat Enable NextLat training objective --nextlat_horizon INT Latent dynamics rollout horizon d (default: 1) --lambda_h FLOAT Weight for next-hidden-state SmoothL1 loss (default: 1.0) --lambda_kl FLOAT Weight for KL divergence loss (default: 1.0) The total loss is: `L = L_next_token + lambda_h * L_next_h + lambda_kl * L_kl` - `L_next_h`: SmoothL1 regression between predicted and actual hidden states (stop-gradient on targets) - `L_kl`: KL divergence between output distributions from predicted vs actual hidden states (frozen output head) Checkpoints include `_NL` in the filename (e.g., `10000_ckpt_maze_A1_RWs_NL_500K.pt`) and contain the latent dynamics model state. Training logs show component losses: `loss 1.86 (nt=1.74, nh=0.001, kl=0.12)`. To test a NextLat-trained model (uses the same GPT generation, just loads the correct checkpoint): python test_maze.py --tasks A1 --path_type RWs --num_train_dataset 500K --num_test_dataset 10K --num_nodes 100 --config 2_1_256 --ckpt_iter 10000 --batch_size 1000 --num_iters 10 --NextLat ### PostGRU Training (Post-Transformer GRU Refinement) PostGRU adds a GRU cell after the transformer's final LayerNorm to refine hidden states sequentially. Unlike the standard transformer where each position's representation is computed independently, the GRU allows the model to carry forward a recurrent state: $s_t = \text{GRU}(h_t, s_{t-1})$, where $h_t$ is the transformer output at position $t$. During training, the GRU processes the full sequence sequentially. During generation, the GRU state is initialized by encoding the prompt and then carried forward step-by-step. To train with PostGRU enabled: python train_maze.py --tasks A1 --path_type RWs --num_train_dataset 500K --num_nodes 100 --n_layer 2 --n_head 1 --n_embd 256 --max_iters 10000 --PostGRU --no-compile Additional PostGRU arguments: --PostGRU Enable Post-Transformer GRU refinement layer --no-compile Required for PostGRU (torch.compile is incompatible with the sequential GRU loop) Checkpoints include `_PGR` in the filename (e.g., `10000_ckpt_maze_A1_RWs_PGR_500K.pt`). For embedding dimension $D$, the GRU adds $6D^2$ parameters (e.g., 0.39M for $D=256$). **Note**: The BFloat16 fused GRU CUDA kernel is not available, so GRU operations run in float32 with autocast disabled. Generation is slower than the standard transformer due to the sequential GRU loop. To test a PostGRU-trained model: python test_maze.py --tasks A1 --path_type RWs --num_train_dataset 500K --num_nodes 100 --config 2_1_256 --ckpt_iter 10000 --batch_size 1000 --num_iters 10 --PostGRU To test the model, we run python test_maze.py The (optional) configurations include parser.add_argument('--ckpt_iter', type=int, default=10000) parser.add_argument('--config', type=str, default='1_1_120') parser.add_argument('--temperature', type=float, default=1) parser.add_argument('--device', type=str, default='cuda:0') parser.add_argument('--num_nodes', type=int, default=100) parser.add_argument('--num_of_paths', type=int, default=20) parser.add_argument('--batch_size', type=int, default=100) parser.add_argument('--num_iters', type=int, default=10) parser.add_argument('--multitasks', action=argparse.BooleanOptionalAction, default=True, help='Use multitask data (default: True)') parser.add_argument('--num_train_dataset', type=int, default=50000, help='Number of multitask training entries (supports K/M/B, default: 50000)') parser.add_argument('--num_test_dataset', type=int, default=10000, help='Number of multitask test entries (supports K/M/B, default: 10000)') parser.add_argument('--graph_file', type=str, default=None, help='Optional GraphML path; if provided, load this graph instead of the default') parser.add_argument('--local', action='store_true', default=False, help='Disable flash attention for local GPU compatibility (default: False)') parser.add_argument('--path_type', type=str, default='RWa', choices=['RWc', 'RWa', 'RWs'], help='Path generation type: RWc (random walk with cycles), RWa (random walk acyclic, default), RWs (single source random walk)') parser.add_argument('--partial', action='store_true', default=False, help='Test with partial prefixes: use a random portion of the path as prompt instead of just "A source target:" (default: False)') parser.add_argument('--NextLat', action='store_true', default=False, help='Load NextLat checkpoint (adds _NL suffix to checkpoint filename)') parser.add_argument('--PostGRU', action='store_true', default=False, help='Load PostGRU checkpoint (adds _PGR suffix to checkpoint filename)') The results will be stored in `out/{dataset}_{config}_{num_nodes}/pred_test__{ckpt_iter}_{run_label}.txt` when `--multitasks` is enabled, where `run_label = batch_size * num_iters` (e.g., 1000) and `` is the task string (e.g., C1). Fallback filenames with the formatted test set size (e.g., 10K) or raw count (e.g., 10000) are still accepted. For single-task runs, the file is `pred_test_{ckpt_iter}_{num_of_paths}.txt`. Files list each prediction with an appended error tag. When `--partial` is enabled, the output filename includes `_partial` suffix (e.g., `pred_test_A1_RWs_10000_1000_partial.txt`). The output includes a `>` marker between the prefix and the model-generated suffix, making it easy to identify where generation begins. ## Analyzing Results To analyze the test results and get statistics on correct paths and error types, run python analyze_maze.py The (optional) configurations include parser.add_argument('--ckpt_iter', type=int, default=10000, help='Checkpoint iteration') parser.add_argument('--config', type=str, default='1_1_120', help='Model config') parser.add_argument('--dataset', type=str, default='maze', help='Dataset name') parser.add_argument('--num_nodes', type=int, default=100, help='Number of nodes') parser.add_argument('--num_of_paths', type=int, default=20, help='Number of paths') parser.add_argument('--multitasks', action=argparse.BooleanOptionalAction, default=True, help='Use multitask data (default: True)') parser.add_argument('--num_train_dataset', type=int, default=50000, help='Number of multitask training entries (supports K/M/B, default: 50000)') parser.add_argument('--num_test_dataset', type=int, default=10000, help='Number of multitask test entries (supports K/M/B, default: 10000)') parser.add_argument('--batch_size', type=int, default=100, help='Batch size used during prediction (matches test_maze.py)') parser.add_argument('--num_iters', type=int, default=10, help='Number of batches used during prediction (matches test_maze.py)') parser.add_argument('--graph_file', type=str, default=None, help='Optional GraphML path; if provided, load this graph instead of the default') parser.add_argument('--path_type', type=str, default='RWa', choices=['RWc', 'RWa', 'RWs'], help='Path generation type: RWc (random walk with cycles), RWa (random walk acyclic, default), RWs (single source random walk)') parser.add_argument('--partial', action='store_true', default=False, help='Analyze partial prefix test results (default: False)') parser.add_argument('--NextLat', action='store_true', default=False, help='Analyze NextLat predictions (adds _NL suffix to filenames)') parser.add_argument('--PostGRU', action='store_true', default=False, help='Analyze PostGRU predictions (adds _PGR suffix to filenames)') The script will output the total number of paths, number of correct paths, and breakdowns of error types with percentages. When `--multitasks` is enabled, it searches for prediction files in this order to match `test_maze.py`: `pred_test___.txt` (run_label = batch_size * num_iters), then the formatted test size (e.g., 10K), then the raw count (e.g., 10000). For single-task runs it reads `pred_test__.txt`. ## Compression Metric To evaluate sequence compression precision between different prefixes, run python maze_compression_test.py --ckpt_iter=10000 --config=1_1_120 --num_nodes=100 --num_of_paths=20 --num_trials=100 The (optional) configurations include parser.add_argument('--ckpt_iter', type=int, default=10000, help='Checkpoint iteration') parser.add_argument('--config', type=str, default='1_1_120', help='Model config') parser.add_argument('--num_nodes', type=int, default=100, help='Number of nodes') parser.add_argument('--num_of_paths', type=int, default=20, help='Number of paths') parser.add_argument('--device', type=str, default='cuda:0', help='Device to use') parser.add_argument('--num_suffix_samples', type=int, default=30, help='Number of suffix samples') parser.add_argument('--epsilon', type=float, default=0.01, help='Probability threshold') parser.add_argument('--temperature', type=float, default=1.0, help='Sampling temperature for suffix generation (default: 1.0)') parser.add_argument('--num_trials', type=int, default=100, help='Number of trials') parser.add_argument('--use_untrained_model', action='store_true', help='Use untrained model') parser.add_argument('--multitasks', action=argparse.BooleanOptionalAction, default=True, help='Use multitask data (default: True)') parser.add_argument('--num_train_dataset', type=int, default=50000, help='Number of multitask training entries (supports K/M/B, default: 50000)') parser.add_argument('--num_test_dataset', type=int, default=10000, help='Number of multitask test entries (supports K/M/B, default: 10000)') parser.add_argument('--tasks', type=str, default='A1', help='Task specification for file naming (e.g., A1, A1B1). Default: A1') parser.add_argument('--cmpr_tasks', type=str, default=None, help='Task specification for compression prefix generation. If not specified, uses --tasks value') parser.add_argument('--local', action='store_true', default=False, help='Disable flash attention for local GPU compatibility (default: False)') parser.add_argument('--path_type', type=str, default='RWa', choices=['RWc', 'RWa', 'RWs'], help='Path generation type: RWc (random walk with cycles), RWa (random walk acyclic, default), RWs (single source random walk)') The `--cmpr_tasks` argument controls the task distribution for generating compression test prefixes, independent from the `--tasks` argument which is used for file naming. For example, to test compression on a model trained with `A1C1` data but only generate Task A prefixes: python maze_compression_test.py --tasks=A1C1 --cmpr_tasks=A1 --num_nodes=100 Or to test with 2:1 ratio of Task A to Task C prefixes: python maze_compression_test.py --tasks=A1C1 --cmpr_tasks=A2C1 --num_nodes=100 The script reports the mean compression precision and its standard error over valid trials, and writes a summary to `out/maze__/compression__.txt` when multitask is enabled (otherwise `compression__.txt`). Checkpoint loading is multitask-aware, preferring `ckpt_maze_mt_.pt` with fallbacks to legacy names. ## Distinction Metric To evaluate distinction precision/recall between prefix pairs, run python maze_distinction_test.py --ckpt_iter=10000 --config=1_1_120 --num_nodes=100 --num_of_paths=20 --num_trials=100 The (optional) configurations include parser.add_argument('--ckpt_iter', type=int, default=10000, help='Checkpoint iteration') parser.add_argument('--config', type=str, default='1_1_120', help='Model config') parser.add_argument('--num_nodes', type=int, default=100, help='Number of nodes') parser.add_argument('--num_of_paths', type=int, default=20, help='Number of paths') parser.add_argument('--device', type=str, default='cuda:0', help='Device to use') parser.add_argument('--num_suffix_samples', type=int, default=30, help='Number of suffix samples') parser.add_argument('--epsilon', type=float, default=0.01, help='Probability threshold') parser.add_argument('--temperature', type=float, default=1.0, help='Sampling temperature for suffix generation (default: 1.0)') parser.add_argument('--num_trials', type=int, default=100, help='Number of trials') parser.add_argument('--max_suffix_length', type=int, default=5, help='Max suffix length for recall') parser.add_argument('--debug', action='store_true', help='Print prefixes and intermediate checks') parser.add_argument('--multitasks', action=argparse.BooleanOptionalAction, default=True, help='Use multitask data (default: True)') parser.add_argument('--num_train_dataset', type=int, default=50000, help='Number of multitask training entries (default: 50000)') parser.add_argument('--num_test_dataset', type=int, default=10000, help='Number of multitask test entries (default: 10000)') parser.add_argument('--local', action='store_true', default=False, help='Disable flash attention for local GPU compatibility (default: False)') parser.add_argument('--path_type', type=str, default='RWa', choices=['RWc', 'RWa', 'RWs'], help='Path generation type: RWc (random walk with cycles), RWa (random walk acyclic, default), RWs (single source random walk)') The script reports mean distinction precision/recall with standard errors over valid trials and writes a summary to `out/maze__/distinction_mt__.txt` when multitask is enabled (otherwise `distinction__.txt`). Checkpoint loading is multitask-aware (prefers `ckpt_maze_mt_.pt` then falls back to legacy names). # Multi-task Mazes - Data generation: data/maze/create_multitask_maze.py - Tokenization for multitask data: data/maze/prepare_multitask_minigpt.py ## Data Generation (multitask) To create multitask maze datasets: python data/maze/create_multitask_maze.py --grid_size=10 --edge_prob=0.6 --tasks "A:60:40,B:40:60" --num_train_dataset=50000 --num_test_dataset=10000 Key arguments: parser.add_argument('--grid_size', type=int, default=10, help='Size of the grid (n x n)') parser.add_argument('--edge_prob', type=float, default=0.6, help='Probability to keep an edge in the grid graph') parser.add_argument('--chance_in_train', type=float, default=0.5, help='Chance of a pair being in the training set for Task A reachability sampling') parser.add_argument('--num_train_dataset', type=int, default=50000, help='Number of training data entries to generate (supports K/M/B, default: 50000)') parser.add_argument('--num_test_dataset', type=int, default=10000, help='Number of test data entries to generate (supports K/M/B, default: 10000)') parser.add_argument('--tasks', type=str, default='A:100:100', help='Task identifiers with train/test percentages, e.g., "A:60:40,B:40:60"') parser.add_argument('--graph_file', type=str, default=None, help='Optional GraphML path; if provided, skip random graph generation and use this graph instead') parser.add_argument('--path_type', type=str, default='RWa', choices=['RWc', 'RWa', 'RWs'], help='Path generation type: RWc (random walk with cycles), RWa (random walk acyclic, default), RWs (single source random walk)') parser.add_argument('--num_labels', type=int, default=10, help='Number of distinct node labels (default: 10). When >10, filenames include _L suffix') Notes: - Outputs are written to data/maze//train___.txt and test___.txt - Grid visualization saved as maze____.txt; graph saved as maze_graph__.graphml (e.g., `maze_C1_RWa_6_0.6.txt` and `maze_graph_C1_RWa.graphml`) - Task C emits turn tokens (L, R, F, T) computed from shortest-path walks assuming the agent starts facing East; prompts remain source/target pairs. ### Path Type Options The `--path_type` argument controls how random walk paths are generated: - **RWa** (default): Random walks that never revisit nodes. Paths are guaranteed to be acyclic and relatively short (bounded by the number of nodes). - **RWc**: Random walks that can revisit nodes (cycles allowed). Paths can be much longer as the walk may loop before reaching the target. - **RWs**: Single source random walk. It starts from a random source node and takes a random number of steps (between 5 and $N^2$). The end node is determined by where the walk stops. This provides a "process-oriented" data distribution. **File Naming Convention**: - RWa (acyclic) paths: Files include `_RWa_` in the name (e.g., `train_C1_RWa_5M.txt`, `meta_A1_RWa.pkl`) - RWc (cyclic) paths: Files include `_RWc_` in the name (e.g., `train_C1_RWc_5M.txt`, `meta_A1_RWc.pkl`) - RWs (single source) paths: Files include `_RWs_` in the name (e.g., `train_C1_RWs_5M.txt`, `meta_A1_RWs.pkl`) **Memory Considerations**: Cyclic paths can be significantly longer than acyclic paths. For example, on a 6×6 grid: - Acyclic paths: Maximum ~28 tokens - Cyclic paths: Can exceed 3900 tokens This affects the `block_size` in `meta_{tasks_tag}.pkl` (e.g., `meta_A1_RWa.pkl`) and may require reducing `--batch_size` during training to avoid out-of-memory errors. ## Tokenization (multitask) Convert multitask text datasets to bin: python data/maze/prepare_multitask_minigpt.py --num_nodes=100 --num_train_dataset=50000 --num_test_dataset=10000 Key arguments: parser.add_argument('--num_nodes', type=int, default=100, help='Number of nodes in the graph') parser.add_argument('--num_train_dataset', type=int, default=50000, help='Number of training data entries to use (supports K/M/B, default: 50000)') parser.add_argument('--num_test_dataset', type=int, default=10000, help='Number of test data entries to use (supports K/M/B, default: 10000)') parser.add_argument('--path_type', type=str, default='RWa', choices=['RWc', 'RWa', 'RWs'], help='Path generation type: RWc (random walk with cycles), RWa (random walk acyclic, default), RWs (single source random walk)') Notes: - Reads train___.txt from data/maze// (where path_type_tag is RWc for cyclic, RWa for acyclic, or RWs for single source) - Writes train__.bin, val__.bin, and meta_.pkl in the same folder (e.g., meta_A1_RWa.pkl) - Vocabulary includes node IDs, direction tokens N/S/E/W, task tokens A–H, node labels a–j (or more when `--num_labels` > 10), and the special label '/' - Use `--num_labels` to match the label count used during data generation (default: 10). When non-default, filenames include `_L` suffix (e.g., `meta_E1_RWs_L20.pkl`) # Simple Graphs ## Data Preparations To create the dataset, we can use python data/simple_graph/create_graph.py The (optional) configurations include parser.add_argument('--num_nodes', type=int, default=100, help='Number of nodes in the graph') parser.add_argument('--edge_prob', type=float, default=0.1, help='Probability of creating an edge between two nodes') parser.add_argument('--DAG', type=bool, default=True, help='Whether the graph should be a Directed Acyclic Graph') parser.add_argument('--chance_in_train', type=float, default=0.5, help='Chance of a pair being in the training set') parser.add_argument('--num_of_paths', type=int, default=20, help='Number of paths per pair nodes in training dataset') Then we convert txt files to bin files by python data/simple_graph/prepare_minigpt.py The (optional) configurations include parser.add_argument('--num_nodes', type=int, default=100, help='Number of nodes in the graph') parser.add_argument('--num_of_paths', type=int, default=20, help='Number of paths per pair nodes in training dataset') ## Model Training and Testing To train the model, we run python train_simple.py The (optional) configurations include parser.add_argument('--dataset', type=str, default='simple_graph', help='Name of the dataset to use') parser.add_argument('--n_layer', type=int, default=1, help='Number of layers (default: 1)') parser.add_argument('--n_head', type=int, default=1, help='Number of attention heads (default: 1)') parser.add_argument('--n_embd', type=int, default=120, help='Size of the embeddings (default: 120)') parser.add_argument('--max_iters', type=int, default=10000, help='Number of Iterations (default: 10000)') parser.add_argument('--num_nodes', type=int, default=100, help='Number of Nodes (default: 100)') parser.add_argument('--num_of_paths', type=int, default=20, help='Number of Paths (default: 20)') parser.add_argument('--init_ckpt', type=int, default=0, help='Initial checkpoint iteration to resume from (default: 0 means train from scratch)') To resume training from a previously saved checkpoint (e.g., iteration 2000): python train_simple.py --n_layer=1 --n_head=2 --n_embd=120 --init_ckpt=2000 The models are stored in "out_dir = f'out/{dataset}_{n_layer}_{n_head}_{n_embd}_{num_nodes}'" To test the model, we run python test_simple.py The (optional) configurations include parser.add_argument('--ckpt_iter', type=int, default=10000) parser.add_argument('--config', type=str, default='1_1_120') parser.add_argument('--temperature', type=float, default=1) parser.add_argument('--device', type=str, default='cuda:0') parser.add_argument('--num_nodes', type=int, default=100) parser.add_argument('--num_of_paths', type=int, default=20) The results will be stored in "out_dir = f'out/{dataset}_{config}_{num_nodes}/pred_test_{ckpt_iter}.txt'", and will show the error type. ## Analyzing Results To analyze the test results and get statistics on correct paths and error types, run python analyze_simple.py The (optional) configurations include parser.add_argument('--ckpt_iter', type=int, default=10000) parser.add_argument('--config', type=str, default='1_1_120') parser.add_argument('--dataset', type=str, default='simple_graph') parser.add_argument('--num_nodes', type=int, default=100) parser.add_argument('--num_of_paths', type=int, default=20) The script will output the total number of paths, number of correct paths, and breakdowns of error types with percentages. ## Maze Task Definitions (D/E/F/G/H/I) These tasks are used in the maze multitask dataset (see `data/maze/create_multitask_maze.py`). - **Task D (Path finding with target label)**: Given a source node and a target label, output a shortest path to the nearest node with that label. Format: `D : ` - **Task E (Path finding with labels, compressed segments)**: Given source and target nodes, output direction+label pairs. Each pair represents moving straight in one direction until reaching the listed label; within a straight segment, labels must be unique (if a label repeats, a new segment starts and the direction may repeat). Format: `E : ...` - **Task F (Target identification with labels)**: Given a starting label and a direction sequence, predict the target label. The start node is implicit: any node with the given label is valid. Format: `F : ` - **Task G (Reachability choice with path)**: Given two source-target pairs, exactly one pair is reachable. Output the reachable pair and a valid path. Format: `G : ` - **Task H (Relative clockwise-index path)**: Given source and target nodes, output a sequence of 1-based indices. The agent starts facing East. At each step, feasible outgoing edges are enumerated clockwise starting from the current facing direction, and the token is the 1-based index of the chosen edge in that enumeration. The facing direction updates to the absolute direction of the step taken. Tokens are integers from 1 to 4. Format: `H : ...` Example: `H 42 52 : 2 2 2 2 2` This task is designed to be fundamentally harder than Task A because the model must track both its current position and facing direction throughout the path to decode the relative indices. - **Task I (Absolute clockwise-index path)**: Like Task H, but feasible outgoing edges are always enumerated clockwise from a fixed North reference (N→E→S→W) regardless of the previous move. The agent does not track a facing direction; its state is the current node alone, and the token is the 1-based index of the chosen direction among the node's feasible edges in this fixed order. Tokens are integers from 1 to 4. Format: `I : ...` This isolates state-conditioned retrieval (reading the node's feasible edge set) from facing tracking: compared to Task A it adds only retrieval, and compared to Task H it removes facing tracking. # Probing and Detour Tests ## Linear Probe Test To train linear probes on hidden states and measure how well the maze state is decoded, run python maze_probe_test.py --tasks C1 --config 12_6_384 --num_train_dataset 10M --num_test_dataset 10K --probe_target current Key arguments: --ckpt_iter Checkpoint iteration to load (default: 10000) --config Model config string, e.g. 12_6_384 --num_nodes Number of nodes in the maze (default: 100) --num_train_dataset Multitask training entries, supports K/M/B (default: 10M) --num_test_dataset Multitask test entries, supports K/M/B (default: 10K) --tasks Task spec for file naming, e.g. C1, A1E1 (default: C1) --path_type RWc/RWa/RWs (default: RWs) --probe_tasks Task identifier to probe (default: C) --probe_target Quantity to decode: current, source, target, rel_direction, dist_to_target, orientation, node_orientation, count_F/L/R/T, cum_disp_N/E/S/W, rot_sum/sin/cos --probe_train_samples Sequences sampled to train the probe (default: 5000) --probe_test_samples Sequences sampled to evaluate the probe (default: 1000) --probe_epochs Probe training epochs (default: 5) --probe_lr Probe learning rate (default: 1e-2) --plot_acc_by_dist Also plot probe accuracy vs. shortest-path distance to target --NLS / --no_task_tag / --local Checkpoint suffix / data-format / flash-attn flags A linear probe is trained per layer on the block outputs and accuracy is reported per layer, with optional position-wise heatmaps and accuracy-by-distance curves. ## k-step Detour Test To measure probe fidelity vs. next-step behaviour after injecting k low-probability legal detour steps, run python maze_kstep_detour_test.py --tasks H1 --model mamba2 --config 24_576 --num_train_dataset 10M --num_test_dataset 10K Key arguments: --ckpt_iter Checkpoint iteration (default: 10000) --model transformer, transformer-rope, transformer-nextlat, mamba, mamba2, gated-deltanet, gru --config Model config string (e.g. 24_576 for RNN/SSM, 6_6_384 for transformers) --num_nodes Number of nodes (default: 100) --num_train_dataset Training entries, supports K/M/B (default: 10M) --num_test_dataset Test entries, supports K/M/B (default: 10K) --tasks Task spec, e.g. H1 (default: H1) --path_type RWc/RWa/RWs (default: RWs) --num_trials Number of prompts to run detour on (default: 1000) --k_list Comma-separated detour lengths (default: 10,20,...,150) --probe_train_samples Sequences used to train the probe (default: 5000) --ref_samples Clean sequences used for the next-step reference table (default: 5000) --out_dir Output directory for per-k tables (default: out/maze_kdetour) Reports, for each k: probe accuracy (representation fidelity), illegal probability mass, conditional illegal mass, and matched JSD (history invariance) plus its conditional version. Results are written as CSV/NPZ under `out/maze_kdetour/`. ## Plotting Probe Results To plot k-step detour metrics across architectures (one figure per metric): python plot_kstep_probe_acc.py --task I1 --dataset 10M --tf_config 6_6_384 --rnn_config 12_384 To plot per-layer probe accuracy across architectures (transformer layers aligned to RNN/SSM layers): python plot_layer_probe_acc.py --task I1 --dataset 10M --tf_config 6_6_384 --rnn_config 12_384 Both scripts read the `out/maze_kdetour/kdetour_*.npz` files produced by `maze_kstep_detour_test.py` and write PNGs to `out/plot/`.