| """
|
| This training script can be run both on a single gpu in debug mode,
|
| and also in a larger training run with distributed data parallel (ddp).
|
|
|
| To run on a single GPU, example:
|
| $ python train_maze.py --batch_size=32 --compile=False
|
|
|
| To run with DDP on 4 gpus on 1 node, example:
|
| $ torchrun --standalone --nproc_per_node=4 train_maze.py
|
|
|
| To run with DDP on 4 gpus across 2 nodes, example:
|
| - Run on the first (master) node with example IP 123.456.123.456:
|
| $ torchrun --nproc_per_node=8 --nnodes=2 --node_rank=0 --master_addr=123.456.123.456 --master_port=1234 train_maze.py
|
| - Run on the worker node:
|
| $ torchrun --nproc_per_node=8 --nnodes=2 --node_rank=1 --master_addr=123.456.123.456 --master_port=1234 train_maze.py
|
| (If your cluster does not have Infiniband interconnect prepend NCCL_IB_DISABLE=1)
|
| """
|
|
|
| import os
|
| import time
|
| import math
|
| import pickle
|
| from contextlib import nullcontext
|
| import argparse
|
|
|
|
|
| import numpy as np
|
| import torch
|
| import torch.nn.functional as F
|
| from torch.nn.parallel import DistributedDataParallel as DDP
|
| from torch.distributed import init_process_group, destroy_process_group
|
| import networkx as nx
|
| import re
|
|
|
| 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 logger import get_logger
|
| import logging
|
| from cli_utils import parse_count, format_count
|
|
|
|
|
| logging.getLogger("torch._dynamo").setLevel(logging.WARNING)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| parser = argparse.ArgumentParser(description='Training of the NanoGPT for maze data.')
|
|
|
| parser.add_argument('--dataset', type=str, default='maze', help='Name of the dataset to use')
|
| parser.add_argument('--model', type=str, default='transformer-nextlat', choices=['transformer', 'transformer-rope', 'transformer-nextlat', 'mamba', 'mamba2', 'gated-deltanet', 'gru'],
|
| help='Model architecture to train. Outputs go to out/<model>/... (default: transformer)')
|
| parser.add_argument('--n_layer', type=int, default=6, help='Number of layers (default: 1)')
|
| parser.add_argument('--n_head', type=int, default=6, help='Number of attention heads (default: 1)')
|
| parser.add_argument('--n_embd', type=int, default=384, 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=parse_count, default='500K', help='Number of multitask training entries (supports K/M/B, default: 50000)')
|
| parser.add_argument('--num_test_dataset', type=parse_count, 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 (e.g., A1, A1B1, A3B2, A1D1F1). Default: A1')
|
| 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('--ckpt_interval', type=int, default=None, help='Override checkpoint save interval (default: max_iters // 2)')
|
| parser.add_argument('--CL', action=argparse.BooleanOptionalAction, default=False, help='Enable Task C label mode (append node labels after L/R turns) and add _CL_ in filenames')
|
| 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='RWs', 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=128, help='Training batch size (default: 1024). Reduce if you encounter OOM errors.')
|
| parser.add_argument('--grad_accum', type=int, default=8, help='Gradient accumulation steps (default: 1). Use a small --batch_size with larger --grad_accum to keep tokens/iter constant under memory limits (e.g. pure-PyTorch Mamba).')
|
| parser.add_argument('--mamba_cuda', action='store_true', default=True,
|
| help='For --model mamba: use the official mamba_ssm CUDA selective-scan kernel (much faster) instead of the pure-PyTorch parallel scan. Requires mamba-ssm + causal-conv1d to be installed.')
|
|
|
| parser.add_argument('--no_task_tag', action='store_true', default=False,
|
| help='Data files do not contain task identifiers (A, B, C, etc.). When enabled, data decoding will handle the no-task-tag format. This should match the setting used during data generation.')
|
| parser.add_argument('--num_labels', type=int, default=10,
|
| help='Number of distinct node labels (default: 10). Must match data generation.')
|
|
|
| parser.add_argument('--nextlat_horizon', type=int, default=8,
|
| help='NextLat latent dynamics rollout horizon d (default: 1)')
|
| parser.add_argument('--lambda_h', type=float, default=1.0,
|
| help='NextLat weight for next-hidden-state regression loss (default: 1.0)')
|
| parser.add_argument('--lambda_kl', type=float, default=0.1,
|
| help='NextLat weight for KL divergence loss (default: 1.0)')
|
| parser.add_argument('--mlp_hidden_dim', type=int, default=None,
|
| help='NextLat MLP hidden dimension (default: 2*n_embd)')
|
|
|
| parser.add_argument('--PostGRU', action='store_true', default=False,
|
| help='Enable Post-Transformer GRU refinement layer (adds _PGR suffix to filenames)')
|
|
|
| parser.add_argument('--NLS', action='store_true', default=False,
|
| help='Enable per-block Non-Linear prefix Scan sublayer (adds _NLS suffix to filenames)')
|
|
|
|
|
|
|
|
|
| parser.add_argument('--DyadicAttn', action='store_true', default=False,
|
| help='Enable DyadicTransformer baseline: replace self-attention with fixed 0.5/0.5 dyadic-pattern attention (adds _DA suffix to filenames)')
|
| parser.add_argument('--DyadicHybrid', action='store_true', default=False,
|
| help='Enable DyadicHybrid ablation: each --n_layer normal Transformer block is followed by ceil(log2(block_size)) DyadicAttn blocks (adds _DH suffix to filenames). Total physical blocks = n_layer * (1 + ceil(log2(block_size))).')
|
| parser.add_argument('--auto_n_layer', action='store_true', default=False,
|
| help='For DyadicAttn: automatically set n_layer = ceil(log2(block_size)) so the per-layer dyadic strides cover the full sequence length recorded in meta.')
|
|
|
|
|
|
|
| parser.add_argument('--aux_layer', type=int, default=None,
|
| help='1-based index of the block/layer whose OUTPUT hidden state is '
|
| 'supervised toward (node, facing). None disables the auxiliary loss '
|
| '(default: None). E.g. --aux_layer 3 = the 3rd layer. Supported on '
|
| 'transformer (Task C) and gru (Task H). Enabling it adds an _SA suffix '
|
| 'to checkpoint filenames.')
|
| parser.add_argument('--aux_lambda', type=float, default=1.0,
|
| help='Weight of the auxiliary (node, facing) cross-entropy loss.')
|
|
|
| args = parser.parse_args()
|
|
|
| dataset = args.dataset
|
| model_type = args.model
|
| n_layer = args.n_layer
|
| n_head = args.n_head
|
| n_embd = args.n_embd
|
| max_iters = args.max_iters
|
| num_nodes = args.num_nodes
|
| num_of_paths = args.num_of_paths
|
| multitasks = args.multitasks
|
| num_train_dataset = args.num_train_dataset
|
| num_test_dataset = args.num_test_dataset
|
| train_label = format_count(num_train_dataset)
|
| test_label = format_count(num_test_dataset)
|
| tasks_str = args.tasks
|
| tasks_tag = f"{tasks_str}_CL" if args.CL else tasks_str
|
|
|
| allow_cycles = (args.path_type == 'RWc')
|
| path_type_tag = args.path_type
|
| tasks_tag = f"{tasks_tag}_{path_type_tag}"
|
|
|
| if args.num_labels != 10:
|
| tasks_tag = f"{tasks_tag}_L{args.num_labels}"
|
|
|
| if args.no_task_tag:
|
| tasks_tag = f"{tasks_tag}_NT"
|
|
|
|
|
|
|
| use_nextlat = (args.model == 'transformer-nextlat')
|
| nextlat_horizon = args.nextlat_horizon
|
| lambda_h = args.lambda_h
|
| lambda_kl = args.lambda_kl
|
|
|
| data_tasks_tag = tasks_tag
|
|
|
| if use_nextlat:
|
| tasks_tag = f"{tasks_tag}_NL"
|
|
|
| use_post_gru = args.PostGRU
|
|
|
| if use_post_gru:
|
| tasks_tag = f"{tasks_tag}_PGR"
|
|
|
| use_nls = args.NLS
|
|
|
| use_dyadic_attn = args.DyadicAttn
|
| use_dyadic_hybrid = args.DyadicHybrid
|
| if use_dyadic_hybrid and use_dyadic_attn:
|
|
|
| print('[Info] --DyadicHybrid given; auto-disabling DyadicAttn for this run.')
|
| use_dyadic_attn = False
|
| if (use_dyadic_attn or use_dyadic_hybrid) and (use_post_gru or use_nextlat):
|
| raise ValueError('--DyadicAttn / --DyadicHybrid is mutually exclusive with --PostGRU / --model transformer-nextlat')
|
| if (use_dyadic_attn or use_dyadic_hybrid) and use_nls:
|
| print(f"[Info] --{'DyadicAttn' if use_dyadic_attn else 'DyadicHybrid'} given; auto-disabling NLS for this run.")
|
| use_nls = False
|
|
|
| if use_nls:
|
| tasks_tag = f"{tasks_tag}_NLS"
|
| if use_dyadic_attn:
|
| tasks_tag = f"{tasks_tag}_DA"
|
| if use_dyadic_hybrid:
|
| tasks_tag = f"{tasks_tag}_DH"
|
|
|
|
|
|
|
|
|
|
|
| use_aux = args.aux_layer is not None
|
|
|
| aux_layer = (args.aux_layer - 1) if use_aux else None
|
| aux_lambda = args.aux_lambda
|
| aux_task = None
|
| if use_aux:
|
| aux_task = args.tasks[0].upper()
|
| if model_type == 'transformer':
|
| if aux_task != 'C':
|
| raise ValueError('--aux_layer with --model transformer is defined for Task C only')
|
| elif model_type == 'gru':
|
| if aux_task != 'H':
|
| raise ValueError('--aux_layer with --model gru is defined for Task H only')
|
| else:
|
| raise ValueError('--aux_layer state-supervision is only implemented for '
|
| '--model transformer (Task C) or --model gru (Task H)')
|
| if use_nextlat or use_post_gru or use_nls or use_dyadic_attn or use_dyadic_hybrid:
|
| raise ValueError('--aux_layer is mutually exclusive with NextLat / PostGRU / NLS / DyadicAttn / DyadicHybrid')
|
| tasks_tag = f"{tasks_tag}_SA"
|
|
|
| if model_type in ('mamba', 'mamba2', 'gated-deltanet', 'gru') and (use_nextlat or use_post_gru or use_nls
|
| or use_dyadic_attn or use_dyadic_hybrid):
|
| raise ValueError(f'--model {model_type} is incompatible with '
|
| 'transformer-nextlat / --PostGRU / --NLS / --DyadicAttn / --DyadicHybrid')
|
|
|
| graph_tag = f"{tasks_str}_CL" if args.CL else tasks_str
|
|
|
| if args.no_task_tag:
|
| graph_tag = f"{graph_tag}_NT"
|
| init_ckpt = args.init_ckpt
|
| validation = args.validation
|
| local_mode = args.local
|
| no_task_tag = args.no_task_tag
|
|
|
| data_dir = os.path.join('data', f'{dataset}/{num_nodes}')
|
|
|
| def pick_first_existing(candidates):
|
| for path in candidates:
|
| if os.path.exists(path):
|
| return path
|
| return candidates[0]
|
|
|
| meta_path = pick_first_existing([
|
| os.path.join(data_dir, f'meta_{data_tasks_tag}.pkl'),
|
| os.path.join(data_dir, f'meta_{tasks_str}.pkl'),
|
| os.path.join(data_dir, 'meta.pkl'),
|
| ])
|
| print(f"Loading meta from {meta_path}...")
|
| with open(meta_path, 'rb') as f:
|
| meta = pickle.load(f)
|
|
|
| stoi, itos = meta['stoi'], meta['itos']
|
| block_size = meta['block_size']
|
|
|
|
|
|
|
| if use_dyadic_attn and args.auto_n_layer:
|
| auto_n = max(1, math.ceil(math.log2(block_size))) if block_size > 1 else 1
|
| if n_layer != auto_n:
|
| print(f"[auto_n_layer] DyadicAttn: overriding n_layer {n_layer} -> {auto_n}"
|
| f" (block_size={block_size}, ceil(log2)={auto_n})")
|
| n_layer = auto_n
|
| args.n_layer = auto_n
|
|
|
|
|
| meta_no_task_tag = meta.get('no_task_tag', False)
|
| print(f"Metadata no_task_tag flag: {meta_no_task_tag}")
|
| print(f"Command line no_task_tag flag: {no_task_tag}")
|
|
|
|
|
|
|
| if 'no_task_tag' in meta:
|
| no_task_tag = meta['no_task_tag']
|
| print(f"Using no_task_tag flag from metadata: {no_task_tag}")
|
|
|
| nt_suffix = '_NT' if args.no_task_tag else ''
|
| model_dir = model_type.replace('-', '_')
|
|
|
| if model_type in ('mamba', 'mamba2', 'gated-deltanet', 'gru'):
|
| arch_tag = f'{n_layer}_{n_embd}'
|
| else:
|
| arch_tag = f'{n_layer}_{n_head}_{n_embd}'
|
| out_dir = f'out/{model_dir}/{dataset}_{arch_tag}_{num_nodes}{nt_suffix}/'
|
|
|
|
|
|
|
| eval_interval = max_iters // 10 if validation else None
|
| checkpoint_interval = args.ckpt_interval if args.ckpt_interval is not None else max_iters // 2
|
| log_interval = max_iters // 100
|
| eval_iters = max_iters // 10 if validation else 1
|
|
|
| eval_only = False
|
| always_save_checkpoint = True
|
| init_from = 'resume' if init_ckpt > 0 else 'scratch'
|
|
|
| wandb_log = False
|
| wandb_project = 'owt'
|
| wandb_run_name = 'gpt2'
|
|
|
|
|
| gradient_accumulation_steps = args.grad_accum
|
| train_batch_size = args.batch_size
|
| val_batch_size = 64
|
| batch_size = train_batch_size
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| dropout = 0.0
|
| bias = False
|
|
|
| learning_rate = 5e-4
|
|
|
| weight_decay = 1e-1
|
| beta1 = 0.9
|
| beta2 = 0.95
|
| grad_clip = 1.0
|
|
|
| decay_lr = True
|
| warmup_iters = max_iters//20
|
| lr_decay_iters = max_iters
|
| min_lr = learning_rate/10
|
|
|
| backend = 'nccl'
|
|
|
| device = 'cuda'
|
| dtype = 'bfloat16'
|
| compile = args.compile
|
|
|
| '''check_type = 'shortest'
|
| max_path_len = 10
|
| max_new_tokens = 200
|
| flag = 0
|
| test_interval = 100'''
|
|
|
| config_keys = [k for k,v in globals().items() if not k.startswith('_') and isinstance(v, (int, float, bool, str))]
|
|
|
| config = {k: globals()[k] for k in config_keys}
|
|
|
|
|
|
|
| ddp = int(os.environ.get('RANK', -1)) != -1
|
| if ddp:
|
| init_process_group(backend=backend)
|
| ddp_rank = int(os.environ['RANK'])
|
| ddp_local_rank = int(os.environ['LOCAL_RANK'])
|
| ddp_world_size = int(os.environ['WORLD_SIZE'])
|
| device = f'cuda:{ddp_local_rank}'
|
| torch.cuda.set_device(device)
|
| master_process = ddp_rank == 0
|
| seed_offset = ddp_rank
|
| assert gradient_accumulation_steps % torch.cuda.device_count() == 0
|
| gradient_accumulation_steps //= torch.cuda.device_count()
|
| else:
|
|
|
| master_process = True
|
| seed_offset = 0
|
| ddp_world_size = 1
|
| tokens_per_iter = gradient_accumulation_steps * ddp_world_size * batch_size * block_size
|
| print(f"tokens per iteration will be: {tokens_per_iter:,}")
|
|
|
| if master_process:
|
| os.makedirs(out_dir, exist_ok=True)
|
| torch.manual_seed(1337 + seed_offset)
|
| torch.backends.cuda.matmul.allow_tf32 = True
|
| torch.backends.cudnn.allow_tf32 = True
|
| device_type = 'cuda' if 'cuda' in device else 'cpu'
|
|
|
| ptdtype = {'float32': torch.float32, 'bfloat16': torch.bfloat16, 'float16': torch.float16}[dtype]
|
| ctx = nullcontext() if device_type == 'cpu' else torch.amp.autocast(device_type=device_type, dtype=ptdtype)
|
|
|
|
|
| def pick_first_existing(candidates):
|
| for path in candidates:
|
| if os.path.exists(path):
|
| return path
|
| return candidates[0]
|
|
|
|
|
| if multitasks:
|
| train_file = pick_first_existing([
|
| os.path.join(data_dir, f'train_{data_tasks_tag}_{train_label}.bin'),
|
| os.path.join(data_dir, f'train_{data_tasks_tag}_{num_train_dataset}.bin'),
|
| os.path.join(data_dir, f'train_{tasks_str}_{train_label}.bin'),
|
| os.path.join(data_dir, f'train_{tasks_str}_{num_train_dataset}.bin'),
|
| ])
|
| val_file = pick_first_existing([
|
| os.path.join(data_dir, f'val_{data_tasks_tag}_{test_label}.bin'),
|
| os.path.join(data_dir, f'val_{data_tasks_tag}_{num_test_dataset}.bin'),
|
| os.path.join(data_dir, f'val_{tasks_str}_{test_label}.bin'),
|
| os.path.join(data_dir, f'val_{tasks_str}_{num_test_dataset}.bin'),
|
| ])
|
| train_data = np.memmap(train_file, dtype=np.uint16, mode='r')
|
| val_data = np.memmap(val_file, dtype=np.uint16, mode='r')
|
| else:
|
| if(num_of_paths == 0):
|
| train_file = os.path.join(data_dir, 'train.bin')
|
| val_file = os.path.join(data_dir, 'val.bin')
|
| else:
|
| train_file = os.path.join(data_dir, f'train_{num_of_paths}.bin')
|
| val_file = os.path.join(data_dir, 'val.bin')
|
| train_data = np.memmap(train_file, dtype=np.uint16, mode='r')
|
| val_data = np.memmap(val_file, dtype=np.uint16, mode='r')
|
|
|
| if master_process:
|
| print(f"Training data file: {train_file}")
|
| print(f"No task tag mode: {'Enabled' if no_task_tag else 'Disabled'}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| if use_aux:
|
| aux_n_grid = int(round(num_nodes ** 0.5))
|
| AUX_DELTA = {'N': -aux_n_grid, 'S': aux_n_grid, 'E': 1, 'W': -1}
|
| AUX_FACE = {'N': 0, 'E': 1, 'S': 2, 'W': 3}
|
| AUX_NUM_STATES = num_nodes * 4
|
| AUX_IGNORE = -1
|
| AUX_PAD_ID, AUX_NL_ID = 0, 1
|
| AUX_COLON_ID = stoi[':']
|
| assert 0 <= aux_layer < n_layer, f"--aux_layer must be in [1, {n_layer}] (1-based)"
|
| if aux_task == 'C':
|
| AUX_LEFT = {'N': 'W', 'W': 'S', 'S': 'E', 'E': 'N'}
|
| AUX_RIGHT = {v: k for k, v in AUX_LEFT.items()}
|
| AUX_OPP = {'N': 'S', 'S': 'N', 'E': 'W', 'W': 'E'}
|
| AUX_C_ID = stoi['C']
|
| AUX_L_ID, AUX_R_ID = stoi['L'], stoi['R']
|
| AUX_F_ID, AUX_T_ID = stoi['F'], stoi['T']
|
| else:
|
| AUX_CLOCKWISE_SCAN = {
|
| 'N': ['N', 'E', 'S', 'W'],
|
| 'E': ['E', 'S', 'W', 'N'],
|
| 'S': ['S', 'W', 'N', 'E'],
|
| 'W': ['W', 'N', 'E', 'S'],
|
| }
|
| AUX_H_ID = stoi['H']
|
| aux_graph_path = os.path.join(data_dir, f'maze_graph_{tasks_str}_{path_type_tag}.graphml')
|
| print(f"[aux] Loading maze graph from {aux_graph_path}...")
|
| _aux_G = nx.read_graphml(aux_graph_path)
|
| AUX_NODE_DIRS = {}
|
| for _nd in range(num_nodes):
|
| _dirs = set()
|
| for _d in ('N', 'E', 'S', 'W'):
|
| _nb = _nd + AUX_DELTA[_d]
|
| if 0 <= _nb < num_nodes and _aux_G.has_edge(str(_nd), str(_nb)):
|
| _dirs.add(_d)
|
| AUX_NODE_DIRS[_nd] = _dirs
|
|
|
|
|
| def row_state_labels_taskC(row):
|
| """Given a (block_size+1)-id Task C row, return a length-block_size int array
|
| S aligned to y (= row[1:]) where S[t] is the PRE-move state (node*4 + facing)
|
| the walker stands in just before emitting the turn token at row position t+1,
|
| and AUX_IGNORE elsewhere. Node token id n encodes node (n-2)."""
|
| S = np.full(block_size, AUX_IGNORE, dtype=np.int64)
|
| if len(row) < 5 or int(row[0]) != AUX_C_ID or int(row[3]) != AUX_COLON_ID:
|
| return S
|
| source = int(row[1]) - 2
|
| if not (0 <= source < num_nodes):
|
| return S
|
| current = source
|
| facing = 'E'
|
| p = 4
|
| while p < len(row):
|
| tok = int(row[p])
|
| if tok == AUX_NL_ID or tok == AUX_PAD_ID:
|
| break
|
| t = p - 1
|
| if 0 <= t < block_size:
|
| S[t] = current * 4 + AUX_FACE[facing]
|
| if tok == AUX_F_ID:
|
| new_facing = facing
|
| elif tok == AUX_L_ID:
|
| new_facing = AUX_LEFT[facing]
|
| elif tok == AUX_R_ID:
|
| new_facing = AUX_RIGHT[facing]
|
| elif tok == AUX_T_ID:
|
| new_facing = AUX_OPP[facing]
|
| else:
|
| break
|
| current = current + AUX_DELTA[new_facing]
|
| if not (0 <= current < num_nodes):
|
| break
|
| facing = new_facing
|
| p += 1
|
| return S
|
|
|
|
|
| def row_state_labels_taskH(row):
|
| """Given a (block_size+1)-id Task H row, return a length-block_size int array
|
| S aligned to y (= row[1:]) where S[t] is the PRE-move state (node*4 + facing)
|
| the walker stands in just before emitting the index token at row position
|
| t+1, and AUX_IGNORE elsewhere. Replays clockwise feasible-direction indices
|
| starting facing East. Node token id n encodes node (n-2)."""
|
| S = np.full(block_size, AUX_IGNORE, dtype=np.int64)
|
| if len(row) < 5 or int(row[0]) != AUX_H_ID or int(row[3]) != AUX_COLON_ID:
|
| return S
|
| source = int(row[1]) - 2
|
| if not (0 <= source < num_nodes):
|
| return S
|
| current = source
|
| facing = 'E'
|
| p = 4
|
| while p < len(row):
|
| tok = int(row[p])
|
| if tok == AUX_NL_ID or tok == AUX_PAD_ID:
|
| break
|
| idx = tok - 2
|
| t = p - 1
|
| if 0 <= t < block_size:
|
| S[t] = current * 4 + AUX_FACE[facing]
|
| scan_order = AUX_CLOCKWISE_SCAN[facing]
|
| feasible = [d for d in scan_order if d in AUX_NODE_DIRS[current]]
|
| if idx < 1 or idx > len(feasible):
|
| break
|
| direction = feasible[idx - 1]
|
| current = current + AUX_DELTA[direction]
|
| if not (0 <= current < num_nodes):
|
| break
|
| facing = direction
|
| p += 1
|
| return S
|
|
|
|
|
| if use_aux:
|
| row_state_labels = row_state_labels_taskC if aux_task == 'C' else row_state_labels_taskH
|
|
|
|
|
| def get_batch(split):
|
| data = train_data if split == 'train' else val_data
|
| batch_size = train_batch_size if split == 'train' else val_batch_size
|
|
|
| data_size = block_size + 1
|
| data = train_data if split == 'train' else val_data
|
| ix = torch.randint( (len(data) - data_size)//data_size , (batch_size,)) * data_size
|
| x = torch.stack([torch.from_numpy((data[i:i+block_size]).astype(np.int64)) for i in ix])
|
| y = torch.stack([torch.from_numpy((data[i+1:i+1+block_size]).astype(np.int64)) for i in ix])
|
|
|
| if use_aux:
|
| rows = [np.asarray(data[i:i + data_size]).astype(np.int64) for i in ix.tolist()]
|
| s = torch.stack([torch.from_numpy(row_state_labels(r)) for r in rows])
|
| else:
|
| s = None
|
|
|
| if device_type == 'cuda':
|
|
|
| x, y = x.pin_memory().to(device, non_blocking=True), y.pin_memory().to(device, non_blocking=True)
|
| if s is not None:
|
| s = s.pin_memory().to(device, non_blocking=True)
|
| else:
|
| x, y = x.to(device), y.to(device)
|
| if s is not None:
|
| s = s.to(device)
|
| return x, y, s
|
|
|
|
|
|
|
| iter_num = 0
|
| best_val_loss = 1e9
|
|
|
|
|
| if(num_of_paths == 0):
|
| logger = get_logger(os.path.join(out_dir, "no_output_train_maze.log"))
|
| log_file_name = os.path.join(out_dir, "train_maze.log")
|
|
|
| else:
|
| logger = get_logger(os.path.join(out_dir, f'no_output_train_maze_{num_of_paths}.log'))
|
| log_file_name = os.path.join(out_dir, f"train_maze_{num_of_paths}.log")
|
|
|
|
|
|
|
|
|
|
|
|
|
| meta_vocab_size = None
|
| if meta is not None and 'vocab_size' in meta:
|
| meta_vocab_size = meta['vocab_size']
|
| print(f"found vocab_size = {meta_vocab_size} (inside {meta_path})")
|
|
|
| def get_shortest(p_graph):
|
| shortest_paths = {}
|
| for i in p_graph.nodes:
|
| for j in p_graph.nodes:
|
| try:
|
| shortest_paths[(i,j)] = list(nx.all_shortest_paths(p_graph, i, j))
|
| except:
|
| shortest_paths[(i,j)] = []
|
| return shortest_paths
|
|
|
| if dataset == 'reasoning':
|
| p_graph_path = os.path.join(data_dir, 'fixed_model.graphml')
|
| p_graph = nx.read_graphml(p_graph_path)
|
| shortest_paths = get_shortest(p_graph)
|
|
|
| stoi, itos = meta['stoi'], meta['itos']
|
|
|
|
|
| def decode_token_list(l):
|
| """Decode a list of token IDs to string."""
|
| if no_task_tag:
|
|
|
| return ' '.join([itos[i] for i in l if i in itos])
|
| else:
|
|
|
| return ''.join([itos[i] for i in l if i in itos])
|
|
|
| decode = decode_token_list
|
|
|
|
|
| if model_type in ('transformer', 'transformer-rope'):
|
| model_args = dict(n_layer=n_layer, n_head=n_head, n_embd=n_embd, block_size=block_size,
|
| bias=bias, vocab_size=None, dropout=dropout, use_flash=not local_mode,
|
| post_gru=use_post_gru, per_block_nls=use_nls,
|
| dyadic_attn=use_dyadic_attn,
|
| dyadic_hybrid=use_dyadic_hybrid)
|
| elif model_type == 'transformer-nextlat':
|
|
|
|
|
| model_args = dict(model_type='transformer-nextlat',
|
| n_layer=n_layer, n_head=n_head, n_embd=n_embd, block_size=block_size,
|
| bias=bias, vocab_size=None, dropout=dropout, use_flash=not local_mode,
|
| mlp_hidden_dim=args.mlp_hidden_dim,
|
| nextlat_horizon=nextlat_horizon, lambda_h=lambda_h, lambda_kl=lambda_kl)
|
| elif model_type == 'gru':
|
|
|
|
|
| model_args = dict(model_type='gru', n_layer=n_layer, n_embd=n_embd,
|
| vocab_size=None, dropout=dropout, bias=bias, pad_id=0)
|
| elif model_type == 'gated-deltanet':
|
|
|
|
|
|
|
| model_args = dict(model_type='gated-deltanet', n_layer=n_layer, n_embd=n_embd,
|
| vocab_size=None, pad_id=0)
|
| else:
|
|
|
|
|
|
|
|
|
| if model_type == 'mamba2':
|
|
|
|
|
| model_args = dict(model_type='mamba2', n_layer=n_layer, n_embd=n_embd,
|
| vocab_size=None, pscan=True, use_cuda=args.mamba_cuda, pad_id=0)
|
| else:
|
| model_args = dict(model_type='mamba', n_layer=n_layer, n_embd=n_embd,
|
| vocab_size=None, pscan=True, use_cuda=args.mamba_cuda, pad_id=0)
|
|
|
|
|
| def build_model(margs):
|
| """Instantiate the architecture selected by --model from a model_args dict."""
|
| if model_type == 'mamba':
|
| return Mamba(MambaConfig(**margs))
|
| if model_type == 'mamba2':
|
| return Mamba2(Mamba2Config(**margs))
|
| if model_type == 'gated-deltanet':
|
| return GatedDeltaNet(GatedDeltaNetConfig(**margs))
|
| if model_type == 'transformer-nextlat':
|
| return TransformerNextLat(TransformerNextLatConfig(**margs))
|
| if model_type == 'transformer-rope':
|
| return GPTRoPE(GPTRoPEConfig(**margs))
|
| if model_type == 'gru':
|
| return GRU(GRUConfig(**margs))
|
| return GPT(GPTConfig(**margs))
|
|
|
|
|
| if init_from == 'scratch':
|
| print("Initializing a new model from scratch")
|
| if meta_vocab_size is None:
|
| print("defaulting to vocab_size of GPT-2 to 50304 (50257 rounded up for efficiency)")
|
| model_args['vocab_size'] = meta_vocab_size if meta_vocab_size is not None else 50304
|
| model = build_model(model_args)
|
| elif init_from == 'resume':
|
|
|
| if multitasks:
|
| candidate_ckpts = [
|
| os.path.join(out_dir, f'{init_ckpt}_ckpt_maze_{tasks_tag}_{train_label}.pt'),
|
| os.path.join(out_dir, f'{init_ckpt}_ckpt_maze_{tasks_tag}_{num_train_dataset}.pt'),
|
| os.path.join(out_dir, f'{init_ckpt}_ckpt_maze_{tasks_str}_{train_label}.pt'),
|
| os.path.join(out_dir, f'{init_ckpt}_ckpt_maze_{num_of_paths}.pt'),
|
| os.path.join(out_dir, f'{init_ckpt}_ckpt_maze.pt'),
|
| ]
|
| ckpt_path = None
|
| for path in candidate_ckpts:
|
| if os.path.exists(path):
|
| ckpt_path = path
|
| break
|
| if ckpt_path is None:
|
| ckpt_path = candidate_ckpts[0]
|
| else:
|
| if num_of_paths == 0:
|
| ckpt_path = os.path.join(out_dir, f'{init_ckpt}_ckpt_maze.pt')
|
| else:
|
| ckpt_path = os.path.join(out_dir, f'{init_ckpt}_ckpt_maze_{num_of_paths}.pt')
|
| print(f"Resuming training from {ckpt_path}")
|
|
|
| checkpoint = torch.load(ckpt_path, map_location=device)
|
| checkpoint_model_args = checkpoint['model_args']
|
|
|
|
|
| if model_type in ('transformer', 'transformer-rope'):
|
| for k in ['n_layer', 'n_head', 'n_embd', 'block_size', 'bias', 'vocab_size']:
|
| model_args[k] = checkpoint_model_args[k]
|
|
|
| for k in ['post_gru', 'per_block_nls', 'dyadic_attn', 'dyadic_hybrid']:
|
| if k in checkpoint_model_args:
|
| model_args[k] = checkpoint_model_args[k]
|
| elif model_type == 'transformer-nextlat':
|
| for k in ['model_type', 'n_layer', 'n_head', 'n_embd', 'block_size', 'bias',
|
| 'vocab_size', 'use_flash', 'dropout', 'mlp_hidden_dim',
|
| 'nextlat_horizon', 'lambda_h', 'lambda_kl']:
|
| if k in checkpoint_model_args:
|
| model_args[k] = checkpoint_model_args[k]
|
| elif model_type == 'gru':
|
| for k in ['model_type', 'n_layer', 'n_embd', 'vocab_size', 'dropout', 'bias', 'pad_id']:
|
| if k in checkpoint_model_args:
|
| model_args[k] = checkpoint_model_args[k]
|
| elif model_type == 'gated-deltanet':
|
| for k in ['model_type', 'n_layer', 'n_embd', 'vocab_size', 'pad_id',
|
| 'head_dim', 'expand_v', 'conv_size']:
|
| if k in checkpoint_model_args:
|
| model_args[k] = checkpoint_model_args[k]
|
| else:
|
| for k in ['model_type', 'n_layer', 'n_embd', 'vocab_size', 'pscan', 'use_cuda',
|
| 'pad_id', 'd_state', 'expand_factor', 'd_conv', 'dt_rank',
|
| 'headdim', 'ngroups']:
|
| if k in checkpoint_model_args:
|
| model_args[k] = checkpoint_model_args[k]
|
|
|
| model = build_model(model_args)
|
| state_dict = checkpoint['model']
|
|
|
|
|
| unwanted_prefix = '_orig_mod.'
|
| for k,v in list(state_dict.items()):
|
| if k.startswith(unwanted_prefix):
|
| state_dict[k[len(unwanted_prefix):]] = state_dict.pop(k)
|
| model.load_state_dict(state_dict)
|
| iter_num = checkpoint['iter_num']
|
| best_val_loss = checkpoint['best_val_loss']
|
| elif init_from.startswith('gpt2'):
|
| print(f"Initializing from OpenAI GPT-2 weights: {init_from}")
|
| override_args = dict(dropout=dropout)
|
| model = GPT.from_pretrained(init_from, override_args)
|
| for k in ['n_layer', 'n_head', 'n_embd', 'block_size', 'bias', 'vocab_size']:
|
| model_args[k] = getattr(model.config, k)
|
|
|
| if model_type in ('transformer', 'transformer-rope', 'transformer-nextlat') and block_size < model.config.block_size:
|
| model.crop_block_size(block_size)
|
| model_args['block_size'] = block_size
|
| model.to(device)
|
|
|
|
|
|
|
|
|
| if use_nextlat:
|
| print(f"NextLat (encapsulated) enabled: horizon={nextlat_horizon}, lambda_h={lambda_h}, lambda_kl={lambda_kl}, mlp_hidden_dim={args.mlp_hidden_dim if args.mlp_hidden_dim is not None else 2 * n_embd}")
|
|
|
| if use_post_gru:
|
| gru_params = sum(
|
| p.numel()
|
| for block in model.transformer.h
|
| if block.per_block_gru is not None
|
| for p in block.per_block_gru.parameters()
|
| )
|
| print(f"PostGRU enabled (per-block): total GRU parameters: {gru_params / 1e6:.4f}M")
|
|
|
| if use_nls:
|
| nls_params = sum(
|
| p.numel()
|
| for block in model.transformer.h
|
| if block.per_block_nls is not None
|
| for p in block.per_block_nls.parameters()
|
| )
|
|
|
|
|
| nls_levels = max(1, math.ceil(math.log2(block_size))) if block_size > 1 else 0
|
| nls_blocks = sum(1 for block in model.transformer.h if block.per_block_nls is not None)
|
| nls_share = all(
|
| block.per_block_nls.share
|
| for block in model.transformer.h
|
| if block.per_block_nls is not None
|
| )
|
| print(
|
| f"NLS enabled (per-block): {nls_blocks} blocks, "
|
| f"{nls_levels} scan levels per block (block_size={block_size}, share={nls_share}), "
|
| f"total NLS parameters: {nls_params / 1e6:.4f}M"
|
| )
|
|
|
|
|
| aux_head = None
|
| if use_aux:
|
| import torch.nn as nn
|
| aux_head = nn.Linear(n_embd, AUX_NUM_STATES, bias=True).to(device)
|
| _aux_unit = 'block' if model_type == 'transformer' else 'layer'
|
| print(f"Auxiliary supervision (Task {aux_task}): {_aux_unit} {aux_layer + 1} (1-based) output -> (node, facing) "
|
| f"{AUX_NUM_STATES}-way, lambda={aux_lambda}")
|
|
|
|
|
| optimizer = model.configure_optimizers(weight_decay, learning_rate, (beta1, beta2), device_type)
|
| if use_aux:
|
| optimizer.add_param_group({'params': [aux_head.weight], 'weight_decay': weight_decay})
|
| optimizer.add_param_group({'params': [aux_head.bias], 'weight_decay': 0.0})
|
| if init_from == 'resume':
|
| optimizer.load_state_dict(checkpoint['optimizer'])
|
| if use_aux and 'aux_head' in checkpoint:
|
| aux_head.load_state_dict(checkpoint['aux_head'])
|
|
|
|
|
| scaler = torch.cuda.amp.GradScaler(enabled=(dtype == 'float16'))
|
| if init_from == 'resume' and 'scaler' in checkpoint:
|
| scaler.load_state_dict(checkpoint['scaler'])
|
|
|
|
|
| if init_from == 'resume':
|
| if 'torch_rng_state' in checkpoint:
|
|
|
| torch.set_rng_state(checkpoint['torch_rng_state'].cpu())
|
| if 'cuda_rng_state' in checkpoint and checkpoint['cuda_rng_state'] is not None and torch.cuda.is_available():
|
|
|
| torch.cuda.set_rng_state(checkpoint['cuda_rng_state'].cpu())
|
| if 'numpy_rng_state' in checkpoint:
|
| np.random.set_state(checkpoint['numpy_rng_state'])
|
|
|
| checkpoint = None
|
|
|
|
|
| if compile and model_type in ('mamba', 'mamba2', 'gated-deltanet'):
|
| print(f"[Info] --model {model_type} uses a custom parallel-scan autograd Function; "
|
| "disabling torch.compile for stability.")
|
| compile = False
|
| if compile and use_aux:
|
| print("[Info] --aux_layer hooks into the model's internal blocks; disabling torch.compile.")
|
| compile = False
|
| if use_aux and ddp:
|
| raise ValueError('--aux_layer state-supervision does not support DDP; run on a single GPU.')
|
| if compile:
|
| print("compiling the model... (takes a ~minute)")
|
| unoptimized_model = model
|
| model = torch.compile(model)
|
|
|
|
|
| if ddp:
|
| model = DDP(model, device_ids=[ddp_local_rank])
|
|
|
|
|
| @torch.no_grad()
|
| def estimate_loss():
|
| out = {}
|
| model.eval()
|
| for split in ['train', 'val']:
|
| losses = torch.zeros(eval_iters)
|
| for k in range(eval_iters):
|
| X, Y, _ = get_batch(split)
|
| with ctx:
|
| _, loss = model(X, Y)
|
| losses[k] = loss.item()
|
| out[split] = losses.mean()
|
| model.train()
|
| return out
|
|
|
|
|
| def get_lr(it):
|
|
|
| if it < warmup_iters:
|
| return learning_rate * it / warmup_iters
|
|
|
| if it > lr_decay_iters:
|
| return min_lr
|
|
|
| decay_ratio = (it - warmup_iters) / (lr_decay_iters - warmup_iters)
|
| assert 0 <= decay_ratio <= 1
|
| coeff = 0.5 * (1.0 + math.cos(math.pi * decay_ratio))
|
| return min_lr + coeff * (learning_rate - min_lr)
|
|
|
| def open_and_append(filename, text):
|
| with open(filename, 'a') as file:
|
| file.write(text + '\n')
|
|
|
|
|
| if wandb_log and master_process:
|
| import wandb
|
| wandb.init(project=wandb_project, name=wandb_run_name, config=config)
|
|
|
|
|
| def format_time(seconds):
|
| hours = int(seconds // 3600)
|
| minutes = int((seconds % 3600) // 60)
|
| secs = int(seconds % 60)
|
| return f"{hours:02d}:{minutes:02d}:{secs:02d}"
|
|
|
|
|
| X, Y, S = get_batch('train')
|
| t0 = time.time()
|
| start_time = time.time()
|
| local_iter_num = 0
|
| raw_model = model.module if ddp else model
|
| running_mfu = -1.0
|
| accuracy = []
|
| corrects = []
|
| totals = []
|
|
|
|
|
| def forward_with_aux(idx, targets, state_targets):
|
| """Forward that also returns the auxiliary (node, facing) loss computed from
|
| the chosen block/layer's output. Branches on model_type: transformer mirrors
|
| GPT.forward, gru mirrors GRU.forward for the LM path."""
|
| if model_type == 'gru':
|
| h = raw_model.drop(raw_model.embedding(idx))
|
| h_aux = None
|
| for i, layer in enumerate(raw_model.layers):
|
| h = layer(h)
|
| if i == aux_layer:
|
| h_aux = h
|
| h = raw_model.out_norm(h)
|
| logits = raw_model.lm_head(h)
|
| else:
|
| b, t = idx.size()
|
| pos = torch.arange(0, t, dtype=torch.long, device=idx.device).unsqueeze(0)
|
| h = raw_model.transformer.drop(raw_model.transformer.wte(idx) + raw_model.transformer.wpe(pos))
|
| h_aux = None
|
| for i, block in enumerate(raw_model.transformer.h):
|
| h = block(h)
|
| if i == aux_layer:
|
| h_aux = h
|
| h = raw_model.transformer.ln_f(h)
|
| logits = raw_model.lm_head(h)
|
| lm_loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=AUX_PAD_ID)
|
| aux_logits = aux_head(h_aux)
|
| aux_loss = F.cross_entropy(aux_logits.view(-1, AUX_NUM_STATES), state_targets.view(-1), ignore_index=AUX_IGNORE)
|
| with torch.no_grad():
|
| mask = state_targets.view(-1) != AUX_IGNORE
|
| if mask.any():
|
| pred = aux_logits.view(-1, AUX_NUM_STATES).argmax(-1)
|
| aux_acc = (pred[mask] == state_targets.view(-1)[mask]).float().mean()
|
| else:
|
| aux_acc = torch.zeros((), device=idx.device)
|
| return logits, lm_loss, aux_loss, aux_acc
|
|
|
|
|
| if master_process:
|
| variant_flags = []
|
| if use_nextlat: variant_flags.append('NextLat')
|
| if use_post_gru: variant_flags.append('PostGRU')
|
| if use_nls: variant_flags.append('NLS')
|
| if use_dyadic_attn: variant_flags.append('DyadicAttn')
|
| if use_dyadic_hybrid: variant_flags.append('DyadicHybrid')
|
| if use_aux: variant_flags.append(f'AuxState{aux_task}(L{aux_layer + 1},λ{aux_lambda})')
|
| variant_str = '+'.join(variant_flags) if variant_flags else 'baseline'
|
| total_params = sum(p.numel() for p in raw_model.parameters())
|
| print("=" * 70)
|
| print("TRAINING CONFIGURATION")
|
| print("=" * 70)
|
| print(f" Variant : {variant_str}")
|
| print(f" Dataset : {dataset} | tasks={tasks_str} | path_type={args.path_type}"
|
| f" | num_nodes={num_nodes} | no_task_tag={no_task_tag}")
|
| print(f" Model : n_layer={n_layer}, n_head={n_head}, n_embd={n_embd},"
|
| f" block_size={block_size}, vocab_size={meta['vocab_size']}, bias={bias}, dropout={dropout}")
|
| print(f" Total params : {total_params / 1e6:.2f}M")
|
| print(f" Optim : AdamW lr={learning_rate} (min={min_lr}), wd={weight_decay},"
|
| f" betas=({beta1},{beta2}), grad_clip={grad_clip}")
|
| print(f" Schedule : max_iters={max_iters}, warmup={warmup_iters},"
|
| f" decay_iters={lr_decay_iters}, decay_lr={decay_lr}")
|
| print(f" Batch / dtype : batch_size={batch_size}, grad_accum={gradient_accumulation_steps},"
|
| f" tokens/iter={tokens_per_iter:,}, dtype={dtype}, compile={compile}, ddp={ddp} (world={ddp_world_size})")
|
| print(f" Init from : {init_from}" + (f" (iter {init_ckpt})" if init_from == 'resume' else ""))
|
| if use_nextlat:
|
| print(f" NextLat : horizon={nextlat_horizon}, lambda_h={lambda_h},"
|
| f" lambda_kl={lambda_kl}, mlp_hidden_dim={args.mlp_hidden_dim or 2 * n_embd}")
|
| if use_post_gru:
|
| print(f" PostGRU : per-block GRU enabled")
|
| if use_nls:
|
| print(f" NLS : per-block Non-Linear prefix Scan enabled")
|
| if use_dyadic_attn:
|
| recommended_layers = max(1, math.ceil(math.log2(block_size))) if block_size > 1 else 1
|
| warn = '' if n_layer == recommended_layers else f' [WARNING: for fair comparison set n_layer={recommended_layers} (= ceil(log2({block_size})))]'
|
| strides = [1 << i for i in range(n_layer)]
|
| print(f" DyadicAttn : fixed 0.5/0.5 attention; per-layer strides={strides}{warn}")
|
| if use_dyadic_hybrid:
|
| L_levels = max(1, math.ceil(math.log2(block_size))) if block_size > 1 else 1
|
| total_blocks = n_layer * (1 + L_levels)
|
| unit_strides = [1 << k for k in range(L_levels)]
|
| print(f" DyadicHybrid : {n_layer} units of (1 normal + {L_levels} DyadicAttn) = {total_blocks} physical blocks; per-unit dyadic strides={unit_strides}")
|
| print(f" Output dir : {out_dir}")
|
| print("=" * 70)
|
| logger.info(f"TRAINING CONFIG: variant={variant_str}, n_layer={n_layer}, n_head={n_head},"
|
| f" n_embd={n_embd}, block_size={block_size}, batch_size={batch_size},"
|
| f" max_iters={max_iters}, lr={learning_rate}, params={total_params/1e6:.2f}M")
|
| open_and_append(log_file_name,
|
| f"TRAINING CONFIG: variant={variant_str}, n_layer={n_layer}, n_head={n_head},"
|
| f" n_embd={n_embd}, block_size={block_size}, batch_size={batch_size},"
|
| f" max_iters={max_iters}, lr={learning_rate}, params={total_params/1e6:.2f}M")
|
|
|
| while True:
|
|
|
|
|
| lr = get_lr(iter_num) if decay_lr else learning_rate
|
| for param_group in optimizer.param_groups:
|
| param_group['lr'] = lr
|
|
|
|
|
| if iter_num % checkpoint_interval == 0 and master_process:
|
| losses = None
|
| if validation and eval_interval is not None:
|
| losses = estimate_loss()
|
| print(f"step {iter_num}: train loss {losses['train']:.4f}, val loss {losses['val']:.4f}")
|
| logger.info(f"step {iter_num}: train loss {losses['train']:.4f}, val loss {losses['val']:.4f}")
|
| open_and_append(log_file_name, f"step {iter_num}: train loss {losses['train']:.4f}, val loss {losses['val']:.4f}")
|
| if wandb_log:
|
| wandb.log({
|
| "iter": iter_num,
|
| "train/loss": losses['train'],
|
| "val/loss": losses['val'],
|
| "lr": lr,
|
| "mfu": running_mfu*100,
|
| })
|
|
|
|
|
| save_due_to_val = validation and losses is not None and losses['val'] < best_val_loss
|
| save_due_to_policy = always_save_checkpoint
|
|
|
| if (save_due_to_val or save_due_to_policy) and iter_num > 0:
|
| if validation and losses is not None:
|
| best_val_loss = min(best_val_loss, losses['val'])
|
| checkpoint = {
|
| 'model': raw_model.state_dict(),
|
| 'optimizer': optimizer.state_dict(),
|
| 'model_args': model_args,
|
| 'model_type': model_type,
|
| 'iter_num': iter_num,
|
| 'best_val_loss': best_val_loss,
|
| 'config': config,
|
| 'scaler': scaler.state_dict(),
|
| 'torch_rng_state': torch.get_rng_state(),
|
| 'cuda_rng_state': torch.cuda.get_rng_state() if torch.cuda.is_available() else None,
|
| 'numpy_rng_state': np.random.get_state(),
|
| }
|
| if use_aux:
|
| checkpoint['aux_head'] = aux_head.state_dict()
|
| checkpoint['aux_layer'] = aux_layer
|
| checkpoint['aux_lambda'] = aux_lambda
|
| print(f"saving checkpoint to {out_dir} (validation={'on' if validation else 'off'})")
|
| logger.info(f"saving checkpoint to {out_dir}")
|
| open_and_append(log_file_name, f"saving checkpoint to {out_dir}")
|
| if multitasks:
|
| torch.save(checkpoint, os.path.join(out_dir, f'{iter_num}_ckpt_maze_{tasks_tag}_{train_label}.pt'))
|
| elif num_of_paths == 0:
|
| torch.save(checkpoint, os.path.join(out_dir, f'{iter_num}_ckpt_maze.pt'))
|
| else:
|
| torch.save(checkpoint, os.path.join(out_dir, f'{iter_num}_ckpt_maze_{num_of_paths}.pt'))
|
|
|
|
|
|
|
|
|
|
|
|
|
| if iter_num == 0 and eval_only:
|
| break
|
|
|
|
|
|
|
| for micro_step in range(gradient_accumulation_steps):
|
| if ddp:
|
| model.require_backward_grad_sync = (micro_step == gradient_accumulation_steps - 1)
|
| with ctx:
|
| if use_aux:
|
| logits, lm_loss, aux_loss, aux_acc = forward_with_aux(X, Y, S)
|
| loss = (lm_loss + aux_lambda * aux_loss) / gradient_accumulation_steps
|
| elif use_nextlat:
|
| total_loss, loss_nt, loss_nh, loss_kl = raw_model.forward_nextlat(
|
| X, Y, horizon=nextlat_horizon,
|
| lambda_h=lambda_h, lambda_kl=lambda_kl)
|
| loss = total_loss / gradient_accumulation_steps
|
| else:
|
| logits, loss = model(X, Y)
|
| loss = loss / gradient_accumulation_steps
|
| X, Y, S = get_batch('train')
|
|
|
| scaler.scale(loss).backward()
|
|
|
| if grad_clip != 0.0:
|
| scaler.unscale_(optimizer)
|
| clip_params = list(model.parameters()) + (list(aux_head.parameters()) if use_aux else [])
|
| torch.nn.utils.clip_grad_norm_(clip_params, grad_clip)
|
| scaler.step(optimizer)
|
| scaler.update()
|
| optimizer.zero_grad(set_to_none=True)
|
|
|
|
|
| t1 = time.time()
|
| dt = t1 - t0
|
| t0 = t1
|
| if iter_num % log_interval == 0 and master_process:
|
| lossf = loss.item() * gradient_accumulation_steps
|
| if local_iter_num >= 5:
|
| mfu = raw_model.estimate_mfu(batch_size * gradient_accumulation_steps, dt)
|
| running_mfu = mfu if running_mfu == -1.0 else 0.9*running_mfu + 0.1*mfu
|
|
|
| elapsed = time.time() - start_time
|
| if iter_num > 0:
|
| eta = (elapsed / iter_num) * (max_iters - iter_num)
|
| elapsed_str = format_time(elapsed)
|
| eta_str = format_time(eta)
|
| time_info = f"elapsed {elapsed_str}, eta {eta_str}"
|
| else:
|
| time_info = "elapsed 00:00:00, eta --:--:--"
|
| if use_nextlat:
|
| print(f"iter {iter_num}: loss {lossf:.4f} (nt={loss_nt.item():.4f}, nh={loss_nh.item():.4f}, kl={loss_kl.item():.4f}), time {dt*1000:.2f}ms, mfu {running_mfu*100:.2f}%, {time_info}")
|
| elif use_aux:
|
| print(f"iter {iter_num}: loss {lossf:.4f} (lm={lm_loss.item():.4f}, aux={aux_loss.item():.4f}, aux_acc={aux_acc.item()*100:.1f}%), time {dt*1000:.2f}ms, mfu {running_mfu*100:.2f}%, {time_info}")
|
| else:
|
| print(f"iter {iter_num}: loss {lossf:.4f}, time {dt*1000:.2f}ms, mfu {running_mfu*100:.2f}%, {time_info}")
|
| logger.info(f"iter {iter_num}: loss {lossf:.4f}")
|
| open_and_append(log_file_name, f"iter {iter_num}: loss {lossf:.4f}")
|
| iter_num += 1
|
| local_iter_num += 1
|
|
|
| if iter_num > max_iters:
|
| break
|
|
|
| torch.save(torch.tensor(corrects).cpu(), os.path.join(out_dir, f'corrects_maze.pt'))
|
| torch.save(torch.tensor(totals).cpu(), os.path.join(out_dir, f'totals_maze.pt'))
|
|
|
|
|
| if master_process:
|
| total_elapsed = time.time() - start_time
|
| total_str = format_time(total_elapsed)
|
| avg_iter_ms = (total_elapsed / max(1, iter_num)) * 1000
|
| summary = (f"Total training time: {total_str} ({total_elapsed:.1f}s) "
|
| f"over {iter_num} iters, avg {avg_iter_ms:.2f} ms/iter")
|
| print(summary)
|
| logger.info(summary)
|
| open_and_append(log_file_name, summary)
|
|
|
| if ddp:
|
| destroy_process_group() |