diff --git a/records/track_10min_16mb/2026-04-12_SP8192_ImprovedParResid_Muon097_TTT5ep_NgramTilt_HessianSDClip/submission.json b/records/track_10min_16mb/2026-04-12_SP8192_ImprovedParResid_Muon097_TTT5ep_NgramTilt_HessianSDClip/submission.json new file mode 100644 index 0000000000..88e6386566 --- /dev/null +++ b/records/track_10min_16mb/2026-04-12_SP8192_ImprovedParResid_Muon097_TTT5ep_NgramTilt_HessianSDClip/submission.json @@ -0,0 +1,38 @@ +{ + "author": "ndokutovich", + "github_id": "ndokutovich", + "name": "SP8192 + Improved Parallel Residuals + Muon 0.97 + LR 0.03 + Score-First TTT 5ep + Causal N-gram Tilt + Hessian SDClip", + "date": "2026-04-12", + "track": "10min_16mb", + "val_bpb": 1.07730, + "val_bpb_std": 0.00040, + "seeds": [42, 314, 999], + "seed_results": { + "42": {"val_bpb": 1.07684, "artifact_bytes": 15965495}, + "314": {"val_bpb": 1.07748, "artifact_bytes": 15965495}, + "999": {"val_bpb": 1.07757, "artifact_bytes": 15965495} + }, + "hardware": "8xH100 80GB SXM", + "pytorch_version": "2.4.0", + "technique_summary": "SP8192 + Improved Parallel Residuals (cross-lane L7+) + 3-Layer Depth Recurrence (L3-5) + Muon 0.97 + Matrix LR 0.03 + EMA 0.997 + QK-Gain 5.0 + Score-First TTT (SGD 5ep lr=0.005) + Causal N-gram Tilt (beta=2.0 agree=0.1) + Hessian-Aware SDClip (lambda=0.175) + GPTQ int6/int8 + Brotli", + "compliance": { + "train_under_600s": true, + "artifact_under_16mb": true, + "eval_under_600s": true, + "no_slot": true, + "no_pre_quant_ttt": true, + "no_etlb": true, + "no_ngram_cache": true, + "no_hash_embed": true, + "score_first_ttt": true, + "causal_ngram_tilt": true, + "three_seeds": true + }, + "attribution": { + "base": "PR #1529 msisovic (1.0753 BPB) — improved parallel residuals architecture", + "ttt": "Score-first TTT from PR #461 framework", + "ngram_tilt": "Causal n-gram tilt from PR #1514 AnirudhRahul", + "hessian_sdclip": "Hessian-Aware SDClip from PR #1412 Robby955", + "optimizer": "Muon 0.97 + LR 0.03 from PR #1493 bigbag tuning" + } +} diff --git a/records/track_10min_16mb/2026-04-12_SP8192_ImprovedParResid_Muon097_TTT5ep_NgramTilt_HessianSDClip/train_gpt.py b/records/track_10min_16mb/2026-04-12_SP8192_ImprovedParResid_Muon097_TTT5ep_NgramTilt_HessianSDClip/train_gpt.py new file mode 100644 index 0000000000..ecf94d1bb4 --- /dev/null +++ b/records/track_10min_16mb/2026-04-12_SP8192_ImprovedParResid_Muon097_TTT5ep_NgramTilt_HessianSDClip/train_gpt.py @@ -0,0 +1,2392 @@ +import collections, copy, glob, io, lzma, math, os, struct +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +import random, re, subprocess, sys, time, uuid, numpy as np, sentencepiece as spm, torch, torch.distributed as dist, torch.nn.functional as F +from torch import Tensor, nn +from flash_attn_interface import flash_attn_func as flash_attn_3_func, flash_attn_varlen_func +_HAS_TRITON_TMA = False +_HAS_CUTLASS_EVT = False +try: + import triton + import triton.language as tl + from triton.tools.tensor_descriptor import TensorDescriptor + _HAS_TRITON_TMA = True +except ImportError: + pass +try: + sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), 'cutlass_evt_fusion')) + import cutlass_evt_fusion + import torch.library + + @torch.library.register_fake('cutlass_evt::gemm_mul') + def _gemm_mul_fake(go, down_w, act_grad): + return go.new_empty(go.size(0), down_w.size(1)) + _HAS_CUTLASS_EVT = True +except Exception: + pass +if _HAS_TRITON_TMA: + + @triton.jit + def _fused_leaky_relu_sq_kernel(a_desc, b_desc, c_desc, aux_desc, M, N, K, BLOCK_SIZE_M: tl.constexpr, BLOCK_SIZE_N: tl.constexpr, BLOCK_SIZE_K: tl.constexpr, GROUP_SIZE_M: tl.constexpr, NUM_SMS: tl.constexpr): + dtype = tl.bfloat16 + start_pid = tl.program_id(axis=0) + num_pid_m = tl.cdiv(M, BLOCK_SIZE_M) + num_pid_n = tl.cdiv(N, BLOCK_SIZE_N) + k_tiles = tl.cdiv(K, BLOCK_SIZE_K) + num_tiles = num_pid_m * num_pid_n + for tile_id in tl.range(start_pid, num_tiles, NUM_SMS, flatten=True): + pid_m = tile_id // num_pid_n + pid_n = tile_id % num_pid_n + offs_am = pid_m * BLOCK_SIZE_M + offs_bn = pid_n * BLOCK_SIZE_N + accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32) + for ki in range(k_tiles): + offs_k = ki * BLOCK_SIZE_K + a = a_desc.load([offs_am, offs_k]) + b = b_desc.load([offs_bn, offs_k]) + accumulator = tl.dot(a, b.T, accumulator) + acc = tl.reshape(accumulator, (BLOCK_SIZE_M, 2, BLOCK_SIZE_N // 2)) + acc = tl.permute(acc, (0, 2, 1)) + acc0, acc1 = tl.split(acc) + c0 = acc0.to(dtype) + c0_ag = tl.where(c0 > 0, 2.0 * c0, 0.5 * c0) + c_desc.store([offs_am, offs_bn], c0_ag) + c0_post = 0.5 * c0_ag * c0 + aux_desc.store([offs_am, offs_bn], c0_post) + c1 = acc1.to(dtype) + c1_ag = tl.where(c1 > 0, 2.0 * c1, 0.5 * c1) + c_desc.store([offs_am, offs_bn + BLOCK_SIZE_N // 2], c1_ag) + c1_post = 0.5 * c1_ag * c1 + aux_desc.store([offs_am, offs_bn + BLOCK_SIZE_N // 2], c1_post) + + def _triton_fused_leaky_relu_sq(a, b): + M, K = a.shape + N, K2 = b.shape + assert K == K2 + act_grad = torch.empty((M, N), device=a.device, dtype=a.dtype) + post = torch.empty((M, N), device=a.device, dtype=a.dtype) + NUM_SMS = torch.cuda.get_device_properties('cuda').multi_processor_count + BLOCK_SIZE_M, BLOCK_SIZE_N, BLOCK_SIZE_K = (128, 256, 64) + a_desc = TensorDescriptor.from_tensor(a, [BLOCK_SIZE_M, BLOCK_SIZE_K]) + b_desc = TensorDescriptor.from_tensor(b, [BLOCK_SIZE_N, BLOCK_SIZE_K]) + c_desc = TensorDescriptor.from_tensor(act_grad, [BLOCK_SIZE_M, BLOCK_SIZE_N // 2]) + aux_desc = TensorDescriptor.from_tensor(post, [BLOCK_SIZE_M, BLOCK_SIZE_N // 2]) + + def grid(META): + return (min(NUM_SMS, triton.cdiv(M, BLOCK_SIZE_M) * triton.cdiv(N, BLOCK_SIZE_N)),) + _fused_leaky_relu_sq_kernel[grid](a_desc, b_desc, c_desc, aux_desc, M, N, K, BLOCK_SIZE_M=BLOCK_SIZE_M, BLOCK_SIZE_N=BLOCK_SIZE_N, BLOCK_SIZE_K=BLOCK_SIZE_K, GROUP_SIZE_M=1, NUM_SMS=NUM_SMS, num_stages=4, num_warps=8) + return (act_grad, post) + + class _FusedMLP(torch.autograd.Function): + + @staticmethod + def forward(ctx, x, fc_w, proj_w): + x_flat = x.reshape(-1, x.shape[-1]) + act_grad, post = _triton_fused_leaky_relu_sq(x_flat, fc_w) + out = F.linear(post, proj_w) + ctx.save_for_backward(x_flat, fc_w, proj_w, act_grad, post) + return out.reshape(*x.shape[:-1], out.shape[-1]) + + @staticmethod + def backward(ctx, grad_output): + x_flat, fc_w, proj_w, act_grad, post = ctx.saved_tensors + go = grad_output.reshape(-1, grad_output.shape[-1]) + dW_proj = go.T @ post + if _HAS_CUTLASS_EVT: + dpre = torch.ops.cutlass_evt.gemm_mul(go, proj_w, act_grad) + else: + dpre = go @ proj_w * act_grad + dW_fc = dpre.T @ x_flat + dx = dpre @ fc_w + return (dx.reshape(grad_output.shape), dW_fc, dW_proj) + +class Hyperparameters: + data_dir = os.environ.get('DATA_DIR', './data/') + seed = int(os.environ.get('SEED', 1337)) + run_id = os.environ.get('RUN_ID', str(uuid.uuid4())) + iterations = int(os.environ.get('ITERATIONS', 20000)) + warmdown_frac = float(os.environ.get('WARMDOWN_FRAC', 0.667)) + warmup_steps = int(os.environ.get('WARMUP_STEPS', 20)) + train_batch_tokens = int(os.environ.get('TRAIN_BATCH_TOKENS', 786432)) + train_seq_len = int(os.environ.get('TRAIN_SEQ_LEN', 2048)) + train_log_every = int(os.environ.get('TRAIN_LOG_EVERY', 500)) + max_wallclock_seconds = float(os.environ.get('MAX_WALLCLOCK_SECONDS', 600.0)) + val_batch_tokens = int(os.environ.get('VAL_BATCH_TOKENS', 524288)) + eval_seq_len = int(os.environ.get('EVAL_SEQ_LEN', 2048)) + val_loss_every = int(os.environ.get('VAL_LOSS_EVERY', 4000)) + sliding_window_enabled = bool(int(os.environ.get('SLIDING_WINDOW_ENABLED', '1'))) + vocab_size = int(os.environ.get('VOCAB_SIZE', 8192)) + num_layers = int(os.environ.get('NUM_LAYERS', 11)) + xsa_last_n = int(os.environ.get('XSA_LAST_N', 11)) + model_dim = int(os.environ.get('MODEL_DIM', 512)) + embedding_dim = int(os.environ.get('EMBEDDING_DIM', 512)) + num_kv_heads = int(os.environ.get('NUM_KV_HEADS', 4)) + num_heads = int(os.environ.get('NUM_HEADS', 8)) + mlp_mult = float(os.environ.get('MLP_MULT', 4.0)) + skip_gates_enabled = bool(int(os.environ.get('SKIP_GATES_ENABLED', '1'))) + tie_embeddings = bool(int(os.environ.get('TIE_EMBEDDINGS', '1'))) + logit_softcap = float(os.environ.get('LOGIT_SOFTCAP', 30.0)) + rope_base = float(os.environ.get('ROPE_BASE', 10000.0)) + rope_dims = int(os.environ.get('ROPE_DIMS', 16)) + rope_train_seq_len = int(os.environ.get('ROPE_TRAIN_SEQ_LEN', 2048)) + ln_scale = bool(int(os.environ.get('LN_SCALE', '1'))) + qk_gain_init = float(os.environ.get('QK_GAIN_INIT', 5.0)) + num_loops = int(os.environ.get('NUM_LOOPS', 2)) + loop_start = int(os.environ.get('LOOP_START', 3)) + loop_end = int(os.environ.get('LOOP_END', 5)) + enable_looping_at = float(os.environ.get('ENABLE_LOOPING_AT', 0.35)) + parallel_residual_start = int(os.environ.get('PARALLEL_RESIDUAL_START', os.environ.get('PARALLEL_START_LAYER', 7))) + parallel_residual = bool(int(os.environ.get('PARALLEL_RESIDUAL', '1'))) + parallel_start_layer = parallel_residual_start + parallel_start_layer_is_physical = bool(int(os.environ.get('PARALLEL_START_LAYER_IS_PHYSICAL', '1'))) + parallel_final_lane = os.environ.get('PARALLEL_FINAL_LANE', 'mean') + parallel_freeze_lane0 = bool(int(os.environ.get('PARALLEL_FREEZE_LANE0', '0'))) + parallel_identity_init = bool(int(os.environ.get('PARALLEL_IDENTITY_INIT', '1'))) + parallel_skip_lane0_only = bool(int(os.environ.get('PARALLEL_SKIP_LANE0_ONLY', '1'))) + parallel_mlp_read_mix = bool(int(os.environ.get('PARALLEL_MLP_READ_MIX', '0'))) + min_lr = float(os.environ.get('MIN_LR', 0.0)) + embed_lr = float(os.environ.get('EMBED_LR', 0.6)) + head_lr = float(os.environ.get('HEAD_LR', 0.008)) + tied_embed_lr = float(os.environ.get('TIED_EMBED_LR', 0.03)) + tied_embed_init_std = float(os.environ.get('TIED_EMBED_INIT_STD', 0.005)) + matrix_lr = float(os.environ.get('MATRIX_LR', 0.022)) + scalar_lr = float(os.environ.get('SCALAR_LR', 0.02)) + muon_momentum = float(os.environ.get('MUON_MOMENTUM', 0.99)) + muon_backend_steps = int(os.environ.get('MUON_BACKEND_STEPS', 5)) + muon_momentum_warmup_start = float(os.environ.get('MUON_MOMENTUM_WARMUP_START', 0.92)) + muon_momentum_warmup_steps = int(os.environ.get('MUON_MOMENTUM_WARMUP_STEPS', 1500)) + muon_row_normalize = bool(int(os.environ.get('MUON_ROW_NORMALIZE', '1'))) + beta1 = float(os.environ.get('BETA1', 0.9)) + beta2 = float(os.environ.get('BETA2', 0.95)) + adam_eps = float(os.environ.get('ADAM_EPS', 1e-08)) + grad_clip_norm = float(os.environ.get('GRAD_CLIP_NORM', 0.3)) + eval_stride = int(os.environ.get('EVAL_STRIDE', 64)) + muon_beta2 = float(os.environ.get('MUON_BETA2', 0.95)) + adam_wd = float(os.environ.get('ADAM_WD', 0.02)) + muon_wd = float(os.environ.get('MUON_WD', 0.095)) + embed_wd = float(os.environ.get('EMBED_WD', 0.095)) + ema_decay = float(os.environ.get('EMA_DECAY', 0.997)) + ttt_enabled = bool(int(os.environ.get('TTT_ENABLED', '1'))) + ttt_lr = float(os.environ.get('TTT_LR', 0.005)) + ttt_epochs = int(os.environ.get('TTT_EPOCHS', 3)) + ttt_chunk_tokens = int(os.environ.get('TTT_CHUNK_TOKENS', 32768)) + ttt_freeze_blocks = int(os.environ.get('TTT_FREEZE_BLOCKS', 0)) + ttt_momentum = float(os.environ.get('TTT_MOMENTUM', 0.9)) + ttt_batch_seqs = int(os.environ.get('TTT_BATCH_SEQS', 32)) + ttt_grad_clip = float(os.environ.get('TTT_GRAD_CLIP', 1.0)) + ttt_optimizer = os.environ.get('TTT_OPTIMIZER', 'sgd') + ttt_adamw_wd = float(os.environ.get('TTT_ADAMW_WD', 0.0)) + hash_embed_enabled = bool(int(os.environ.get('HASH_EMBED_ENABLED', '0'))) + hash_embed_size = int(os.environ.get('HASH_EMBED_SIZE', 16384)) + compressor = os.environ.get('COMPRESSOR', 'brotli') + gptq_calibration_batches = int(os.environ.get('GPTQ_CALIBRATION_BATCHES', 64)) + gptq_reserve_seconds = float(os.environ.get('GPTQ_RESERVE_SECONDS', 12.0)) + matrix_bits = int(os.environ.get('MATRIX_BITS', 6)) + embed_bits = int(os.environ.get('EMBED_BITS', 8)) + matrix_clip_sigmas = float(os.environ.get('MATRIX_CLIP_SIGMAS', 12.85)) + embed_clip_sigmas = float(os.environ.get('EMBED_CLIP_SIGMAS', 20.0)) + hessian_clip_lambda = float(os.environ.get('HESSIAN_CLIP_LAMBDA', 0.175)) + ngram_tilt_enabled = bool(int(os.environ.get('NGRAM_TILT_ENABLED', '0'))) + ngram_base_beta = float(os.environ.get('NGRAM_BASE_BETA', 2.0)) + ngram_agree_bonus = float(os.environ.get('NGRAM_AGREE_BONUS', 0.1)) + ngram_within_threshold = float(os.environ.get('NGRAM_WITHIN_THRESHOLD', 0.25)) + ngram_within_beta = float(os.environ.get('NGRAM_WITHIN_BETA', 0.0)) + ngram_word_threshold = float(os.environ.get('NGRAM_WORD_THRESHOLD', 0.8)) + ngram_word_beta = float(os.environ.get('NGRAM_WORD_BETA', 0.0)) + ngram_open_table_bits = int(os.environ.get('NGRAM_OPEN_TABLE_BITS', 26)) + ngram_token_threshold_scale = float(os.environ.get('NGRAM_TOKEN_THRESHOLD_SCALE', 1.0)) + ngram_order_stride = int(os.environ.get('NGRAM_ORDER_STRIDE', 2)) + lora_ttt_enabled = bool(int(os.environ.get('LORA_TTT_ENABLED', '0'))) + ttt_lora_rank = int(os.environ.get('TTT_LORA_RANK', '96')) + ttt_k_lora = bool(int(os.environ.get('TTT_K_LORA', '1'))) + ttt_o_lora = bool(int(os.environ.get('TTT_O_LORA', '1'))) + ttt_mlp_lora = bool(int(os.environ.get('TTT_MLP_LORA', '1'))) + ttt_lora_lr = float(os.environ.get('TTT_LORA_LR', '0.001')) + ttt_lora_grad_steps = int(os.environ.get('TTT_LORA_GRAD_STEPS', '1')) + ttt_lora_chunk_size = int(os.environ.get('TTT_LORA_CHUNK_SIZE', '64')) + ttt_lora_batch_size = int(os.environ.get('TTT_LORA_BATCH_SIZE', '64')) + ttt_lora_eval_seq_len = int(os.environ.get('TTT_LORA_EVAL_SEQ_LEN', '2048')) + ttt_lora_weight_decay = float(os.environ.get('TTT_LORA_WEIGHT_DECAY', '0.5')) + ttt_lora_beta1 = float(os.environ.get('TTT_LORA_BETA1', '0')) + ttt_lora_beta2 = float(os.environ.get('TTT_LORA_BETA2', '0.999')) + ttt_lora_eval_batches = os.environ.get('TTT_LORA_EVAL_BATCHES', '') + ttt_lora_output_dir = os.environ.get('TTT_LORA_OUTPUT_DIR', '') + val_doc_fraction = float(os.environ.get('VAL_DOC_FRACTION', '1.0')) + varlen_training = bool(int(os.environ.get('VARLEN_TRAINING', '0'))) + distributed = 'RANK' in os.environ and 'WORLD_SIZE' in os.environ + rank = int(os.environ.get('RANK', '0')) + world_size = int(os.environ.get('WORLD_SIZE', '1')) + local_rank = int(os.environ.get('LOCAL_RANK', '0')) + is_main_process = rank == 0 + grad_accum_steps = 8 // world_size + datasets_dir = os.path.join(data_dir, 'datasets', f'fineweb10B_sp{vocab_size}') + train_files = os.path.join(datasets_dir, 'fineweb_train_*.bin') + val_files = os.path.join(datasets_dir, 'fineweb_val_*.bin') + tokenizer_path = os.path.join(data_dir, 'tokenizers', f'fineweb_{vocab_size}_bpe.model') + logfile = f'logs/{run_id}.txt' + model_path = 'final_model.pt' + quantized_model_path = 'final_model.int6.ptz' +_logger_hparams = None + +def set_logging_hparams(h): + global _logger_hparams + _logger_hparams = h + +def log(msg, console=True): + if _logger_hparams is None: + print(msg) + return + if _logger_hparams.is_main_process: + if console: + print(msg) + if _logger_hparams.logfile is not None: + with open(_logger_hparams.logfile, 'a', encoding='utf-8') as f: + print(msg, file=f) + +class ValidationData: + + def __init__(self, h, device): + self.sp = spm.SentencePieceProcessor(model_file=h.tokenizer_path) + if int(self.sp.vocab_size()) != h.vocab_size: + raise ValueError(f'VOCAB_SIZE={h.vocab_size} does not match tokenizer vocab_size={int(self.sp.vocab_size())}') + self.val_tokens = load_validation_tokens(h.val_files, h.eval_seq_len) + self.base_bytes_lut, self.has_leading_space_lut, self.is_boundary_token_lut = build_sentencepiece_luts(self.sp, h.vocab_size, device) + +def build_sentencepiece_luts(sp, vocab_size, device): + sp_vocab_size = int(sp.vocab_size()) + table_size = max(sp_vocab_size, vocab_size) + base_bytes_np = np.zeros((table_size,), dtype=np.int16) + has_leading_space_np = np.zeros((table_size,), dtype=np.bool_) + is_boundary_token_np = np.ones((table_size,), dtype=np.bool_) + for token_id in range(sp_vocab_size): + if sp.is_control(token_id) or sp.is_unknown(token_id) or sp.is_unused(token_id): + continue + is_boundary_token_np[token_id] = False + if sp.is_byte(token_id): + base_bytes_np[token_id] = 1 + continue + piece = sp.id_to_piece(token_id) + if piece.startswith('▁'): + has_leading_space_np[token_id] = True + piece = piece[1:] + base_bytes_np[token_id] = len(piece.encode('utf-8')) + return (torch.tensor(base_bytes_np, dtype=torch.int16, device=device), torch.tensor(has_leading_space_np, dtype=torch.bool, device=device), torch.tensor(is_boundary_token_np, dtype=torch.bool, device=device)) + +def load_validation_tokens(pattern, seq_len): + files = [Path(p) for p in sorted(glob.glob(pattern))] + if not files: + raise FileNotFoundError(f'No files found for pattern: {pattern}') + tokens = torch.cat([load_data_shard(file) for file in files]).contiguous() + usable = (tokens.numel() - 1) // seq_len * seq_len + if usable <= 0: + raise ValueError(f'Validation split is too short for TRAIN_SEQ_LEN={seq_len}') + return tokens[:usable + 1] + +def load_data_shard(file): + header_bytes = 256 * np.dtype(' 0 else 0 + num_sequences = (self.num_tokens[si] - 1 - phase) // self.seq_len + sequence_order = self.rng.permutation(num_sequences) + self.start_inds[si] = (phase + sequence_order * self.seq_len).tolist() + + def next_batch(self, global_tokens, grad_accum_steps): + device_tokens = global_tokens // (self.world_size * grad_accum_steps) + device_batch_size = device_tokens // self.seq_len + remaining = np.array([len(s) for s in self.start_inds], dtype=np.float64) + x = torch.empty((device_batch_size, self.seq_len), dtype=torch.int64) + y = torch.empty((device_batch_size, self.seq_len), dtype=torch.int64) + for bi in range(device_batch_size): + total = remaining.sum() + if total <= 0: + for si in range(len(self.files)): + self._reset_shard(si) + remaining = np.array([len(s) for s in self.start_inds], dtype=np.float64) + total = remaining.sum() + probs = remaining / total + si = int(self.rng.choice(len(self.files), p=probs)) + start_ind = self.start_inds[si].pop() + remaining[si] -= 1 + mm = _get_shard_memmap(self.files[si]) + window = torch.as_tensor(np.array(mm[start_ind:start_ind + self.seq_len + 1], dtype=np.int64)) + x[bi] = window[:-1] + y[bi] = window[1:] + return (x.to(self.device, non_blocking=True), y.to(self.device, non_blocking=True)) + +BOS_ID = None + +def _build_cu_seqlens(bos_pos, total_len, device, max_doc_len=0, bucket_size=64): + if not bos_pos or bos_pos[0] != 0: + bos_pos = [0] + bos_pos + seg_starts = [] + starts_with_end = bos_pos + [total_len] + for i in range(len(starts_with_end) - 1): + start = starts_with_end[i] + end = starts_with_end[i + 1] + if max_doc_len > 0: + pos = start + while pos < end: + seg_starts.append(pos) + pos += max_doc_len + else: + seg_starts.append(start) + boundaries = seg_starts + [total_len] + padded_len = ((len(boundaries) + bucket_size - 1) // bucket_size) * bucket_size + cu = torch.full((padded_len,), total_len, dtype=torch.int32, device=device) + cu[:len(boundaries)] = torch.tensor(boundaries, dtype=torch.int32, device=device) + seg_ends = seg_starts[1:] + [total_len] + max_seqlen = max(end - start for start, end in zip(seg_starts, seg_ends)) + return cu, max_seqlen + +class DocumentPackingLoader: + _shard_pool = ThreadPoolExecutor(1) + + def __init__(self, h, device, cu_bucket_size=64): + self.rank = h.rank + self.world_size = h.world_size + self.device = device + self.cu_bucket_size = cu_bucket_size + self.max_seq_len = h.train_seq_len + all_files = [Path(p) for p in sorted(glob.glob(h.train_files))] + if not all_files: + raise FileNotFoundError(f'No files found for pattern: {h.train_files}') + self.files = all_files + self.file_iter = iter(self.files) + self._init_shard(load_data_shard(next(self.file_iter))) + self._next_shard = self._submit_next_shard() + self._batch_pool = ThreadPoolExecutor(1) + self._next_batch = None + + def _init_shard(self, tokens): + global BOS_ID + self.tokens = tokens + self.shard_size = tokens.numel() + if BOS_ID is None: + BOS_ID = 1 + self.bos_idx = ( + (tokens == BOS_ID).nonzero(as_tuple=True)[0].to(torch.int64).cpu().numpy() + ) + if self.bos_idx.size == 0: + self.bos_idx = np.array([0], dtype=np.int64) + self.cursor = int(self.bos_idx[0]) + + def _submit_next_shard(self): + try: + path = next(self.file_iter) + return self._shard_pool.submit(load_data_shard, path) + except StopIteration: + return None + + def _advance_shard(self): + if self._next_shard is None: + self.file_iter = iter(self.files) + self._next_shard = self._shard_pool.submit(load_data_shard, next(self.file_iter)) + self._init_shard(self._next_shard.result()) + self._next_shard = self._submit_next_shard() + + def _local_doc_starts(self, local_start, total_len): + lo = np.searchsorted(self.bos_idx, local_start, side='left') + hi = np.searchsorted(self.bos_idx, local_start + total_len, side='left') + return (self.bos_idx[lo:hi] - local_start).tolist() + + def _prepare_batch(self, num_tokens_local, max_seq_len): + per_rank_span = num_tokens_local + 1 + global_span = per_rank_span * self.world_size + while self.cursor + global_span > self.shard_size: + self._advance_shard() + local_start = self.cursor + self.rank * per_rank_span + buf = self.tokens[local_start:local_start + per_rank_span] + inputs = buf[:-1].to(dtype=torch.int64).pin_memory() + targets = buf[1:].to(dtype=torch.int64).pin_memory() + starts = self._local_doc_starts(local_start, inputs.numel()) + cu_seqlens, max_seqlen = _build_cu_seqlens( + starts, inputs.numel(), inputs.device, max_seq_len, self.cu_bucket_size + ) + cu_seqlens = cu_seqlens.pin_memory() + self.cursor += global_span + return inputs, targets, cu_seqlens, max_seqlen + + def next_batch(self, global_tokens, grad_accum_steps): + num_tokens_local = global_tokens // (self.world_size * grad_accum_steps) + if self._next_batch is not None: + inputs, targets, cu_seqlens, max_seqlen = self._next_batch.result() + else: + inputs, targets, cu_seqlens, max_seqlen = self._prepare_batch( + num_tokens_local, self.max_seq_len + ) + self._next_batch = self._batch_pool.submit( + self._prepare_batch, num_tokens_local, self.max_seq_len + ) + return ( + inputs[None].to(self.device, non_blocking=True), + targets[None].to(self.device, non_blocking=True), + cu_seqlens.to(self.device, non_blocking=True), + max_seqlen, + ) + +class RMSNorm(nn.Module): + + def __init__(self, eps=None): + super().__init__() + self.eps = eps + + def forward(self, x): + return F.rms_norm(x, (x.size(-1),), eps=self.eps) + +class CastedLinear(nn.Linear): + + def forward(self, x): + w = self.weight.to(x.dtype) + bias = self.bias.to(x.dtype) if self.bias is not None else None + return F.linear(x, w, bias) + +class Rotary(nn.Module): + + def __init__(self, dim, base=10000.0, train_seq_len=1024, rope_dims=0): + super().__init__() + self.dim = dim + self.base = base + self.train_seq_len = train_seq_len + self.rope_dims = rope_dims if rope_dims > 0 else dim + inv_freq = 1.0 / base ** (torch.arange(0, self.rope_dims, 2, dtype=torch.float32) / self.rope_dims) + self.register_buffer('inv_freq', inv_freq, persistent=False) + self._seq_len_cached = 0 + self._cos_cached = None + self._sin_cached = None + + def forward(self, seq_len, device, dtype): + if self._cos_cached is None or self._sin_cached is None or self._seq_len_cached != seq_len or (self._cos_cached.device != device): + rd = self.rope_dims + if seq_len > self.train_seq_len: + scale = seq_len / self.train_seq_len + new_base = self.base * scale ** (rd / (rd - 2)) + inv_freq = 1.0 / new_base ** (torch.arange(0, rd, 2, dtype=torch.float32, device=device) / rd) + else: + inv_freq = self.inv_freq.to(device) + t = torch.arange(seq_len, device=device, dtype=inv_freq.dtype) + freqs = torch.outer(t, inv_freq) + self._cos_cached = freqs.cos()[None, :, None, :] + self._sin_cached = freqs.sin()[None, :, None, :] + self._seq_len_cached = seq_len + return (self._cos_cached.to(dtype=dtype), self._sin_cached.to(dtype=dtype)) + +def apply_rotary_emb(x, cos, sin, rope_dims=0): + if rope_dims > 0 and rope_dims < x.size(-1): + x_rope, x_pass = (x[..., :rope_dims], x[..., rope_dims:]) + half = rope_dims // 2 + x1, x2 = (x_rope[..., :half], x_rope[..., half:]) + x_rope = torch.cat((x1 * cos + x2 * sin, x1 * -sin + x2 * cos), dim=-1) + return torch.cat((x_rope, x_pass), dim=-1) + half = x.size(-1) // 2 + x1, x2 = (x[..., :half], x[..., half:]) + return torch.cat((x1 * cos + x2 * sin, x1 * -sin + x2 * cos), dim=-1) + +class CausalSelfAttention(nn.Module): + + def __init__(self, dim, num_heads, num_kv_heads, rope_base, qk_gain_init, train_seq_len): + super().__init__() + if dim % num_heads != 0: + raise ValueError('model_dim must be divisible by num_heads') + if num_heads % num_kv_heads != 0: + raise ValueError('num_heads must be divisible by num_kv_heads') + self.num_heads = num_heads + self.num_kv_heads = num_kv_heads + self.head_dim = dim // num_heads + if self.head_dim % 2 != 0: + raise ValueError('head_dim must be even for RoPE') + self.q_gain = nn.Parameter(torch.full((num_heads,), qk_gain_init, dtype=torch.float32)) + self.rope_dims = 0 + self.rotary = Rotary(self.head_dim, base=rope_base, train_seq_len=train_seq_len) + self.use_xsa = False + + def _xsa_efficient(self, y, v): + B, T, H, D = y.shape + Hkv = v.size(-2) + group = H // Hkv + y_g = y.reshape(B, T, Hkv, group, D) + vn = F.normalize(v, dim=-1).unsqueeze(-2) + proj = (y_g * vn).sum(dim=-1, keepdim=True) * vn + return (y_g - proj).reshape(B, T, H, D) + + def forward(self, x, q_w, k_w, v_w, out_w, cu_seqlens=None, max_seqlen=0): + bsz, seqlen, dim = x.shape + q = F.linear(x, q_w.to(x.dtype)).reshape(bsz, seqlen, self.num_heads, self.head_dim) + k = F.linear(x, k_w.to(x.dtype)).reshape(bsz, seqlen, self.num_kv_heads, self.head_dim) + v = F.linear(x, v_w.to(x.dtype)).reshape(bsz, seqlen, self.num_kv_heads, self.head_dim) + q = F.rms_norm(q, (q.size(-1),)) + k = F.rms_norm(k, (k.size(-1),)) + cos, sin = self.rotary(seqlen, x.device, q.dtype) + q = apply_rotary_emb(q, cos, sin, self.rope_dims) + k = apply_rotary_emb(k, cos, sin, self.rope_dims) + q = q * self.q_gain.to(dtype=q.dtype)[None, None, :, None] + if cu_seqlens is not None: + y = flash_attn_varlen_func( + q[0], k[0], v[0], + cu_seqlens_q=cu_seqlens, cu_seqlens_k=cu_seqlens, + max_seqlen_q=max_seqlen, max_seqlen_k=max_seqlen, + causal=True, window_size=(-1, -1), + )[None] + else: + y = flash_attn_3_func(q, k, v, causal=True) + if self.use_xsa: + y = self._xsa_efficient(y, v) + y = y.reshape(bsz, seqlen, dim) + self._last_proj_input = y.detach() if getattr(self, '_calib', False) else None + return F.linear(y, out_w.to(x.dtype)) + +class MLP(nn.Module): + + def __init__(self, dim, mlp_mult): + super().__init__() + self.use_fused = True + + def forward(self, x, up_w, down_w): + if _HAS_TRITON_TMA and x.is_cuda and self.training and self.use_fused: + return _FusedMLP.apply(x, up_w.to(x.dtype), down_w.to(x.dtype)) + hidden = F.leaky_relu(F.linear(x, up_w.to(x.dtype)), negative_slope=0.5).square() + self._last_down_input = hidden.detach() if getattr(self, '_calib', False) else None + return F.linear(hidden, down_w.to(x.dtype)) + +class Block(nn.Module): + + def __init__(self, dim, num_heads, num_kv_heads, mlp_mult, rope_base, qk_gain_init, train_seq_len, layer_idx=0, ln_scale=False): + super().__init__() + self.attn_norm = RMSNorm() + self.mlp_norm = RMSNorm() + self.attn = CausalSelfAttention(dim, num_heads, num_kv_heads, rope_base, qk_gain_init, train_seq_len) + self.mlp = MLP(dim, mlp_mult) + self.attn_scale = nn.Parameter(torch.ones(dim, dtype=torch.float32)) + self.mlp_scale = nn.Parameter(torch.ones(dim, dtype=torch.float32)) + self.resid_mix = nn.Parameter(torch.stack((torch.ones(dim), torch.zeros(dim))).float()) + self.ln_scale_factor = 1.0 / math.sqrt(layer_idx + 1) if ln_scale else 1.0 + + def forward(self, x, x0, q_w, k_w, v_w, out_w, up_w, down_w, cu_seqlens=None, max_seqlen=0): + mix = self.resid_mix.to(dtype=x.dtype) + x_in = mix[0][None, None, :] * x + mix[1][None, None, :] * x0 + attn_out = self.attn(self.attn_norm(x_in) * self.ln_scale_factor, q_w, k_w, v_w, out_w, cu_seqlens=cu_seqlens, max_seqlen=max_seqlen) + x_out = x_in + self.attn_scale.to(dtype=x_in.dtype)[None, None, :] * attn_out + x_out = x_out + self.mlp_scale.to(dtype=x_out.dtype)[None, None, :] * self.mlp(self.mlp_norm(x_out) * self.ln_scale_factor, up_w, down_w) + return x_out + + def forward_attn(self, x, x0, q_w, k_w, v_w, out_w): + mix = self.resid_mix.to(dtype=x.dtype) + x_in = mix[0][None, None, :] * x + mix[1][None, None, :] * x0 + attn_out = self.attn(self.attn_norm(x_in) * self.ln_scale_factor, q_w, k_w, v_w, out_w) + return x_in + self.attn_scale.to(dtype=x_in.dtype)[None, None, :] * attn_out + + def forward_mlp(self, x, up_w, down_w): + return x + self.mlp_scale.to(dtype=x.dtype)[None, None, :] * self.mlp(self.mlp_norm(x) * self.ln_scale_factor, up_w, down_w) + +class BatchedLinearLoRA(nn.Module): + + def __init__(self, bsz, in_features, out_features, rank): + super().__init__() + self._bound = 1.0 / math.sqrt(in_features) + self.A = nn.Parameter(torch.empty(bsz, rank, in_features).uniform_(-self._bound, self._bound)) + self.B = nn.Parameter(torch.zeros(bsz, out_features, rank)) + + def reset(self): + with torch.no_grad(): + self.A.uniform_(-self._bound, self._bound) + self.B.zero_() + + def forward(self, x): + return (x @ self.A.transpose(1, 2)) @ self.B.transpose(1, 2) + +class BatchedTTTLoRA(nn.Module): + + def __init__(self, bsz, model, rank, k_lora=True, mlp_lora=True, o_lora=True): + super().__init__() + self.bsz = bsz + dim = model.qo_bank.shape[-1] + vocab = model.tok_emb.num_embeddings + if getattr(model, 'looping_active', False): + num_slots = len(model.encoder_indices) + len(model.decoder_indices) + else: + num_slots = len(model.blocks) + kv_dim = model.blocks[0].attn.num_kv_heads * (dim // model.blocks[0].attn.num_heads) + embed_dim = model.tok_emb.embedding_dim + self.lm_head_lora = BatchedLinearLoRA(bsz, embed_dim, vocab, rank) + self.q_loras = nn.ModuleList([BatchedLinearLoRA(bsz, dim, dim, rank) for _ in range(num_slots)]) + self.v_loras = nn.ModuleList([BatchedLinearLoRA(bsz, dim, kv_dim, rank) for _ in range(num_slots)]) + self.k_loras = nn.ModuleList([BatchedLinearLoRA(bsz, dim, kv_dim, rank) for _ in range(num_slots)]) if k_lora else None + self.mlp_loras = nn.ModuleList([BatchedLinearLoRA(bsz, dim, dim, rank) for _ in range(num_slots)]) if mlp_lora else None + self.o_loras = nn.ModuleList([BatchedLinearLoRA(bsz, dim, dim, rank) for _ in range(num_slots)]) if o_lora else None + + def reset(self): + with torch.no_grad(): + self.lm_head_lora.reset() + for loras in [self.q_loras, self.v_loras, self.k_loras, self.mlp_loras, self.o_loras]: + if loras is not None: + for lora in loras: + lora.reset() + +class GPT(nn.Module): + + def __init__(self, h): + super().__init__() + if h.logit_softcap <= 0.0: + raise ValueError(f'logit_softcap must be positive, got {h.logit_softcap}') + self.tie_embeddings = h.tie_embeddings + self.tied_embed_init_std = h.tied_embed_init_std + self.logit_softcap = h.logit_softcap + self.tok_emb = nn.Embedding(h.vocab_size, h.embedding_dim) + if h.embedding_dim != h.model_dim: + self.embed_proj = CastedLinear(h.embedding_dim, h.model_dim, bias=False) + self.head_proj = CastedLinear(h.model_dim, h.embedding_dim, bias=False) + else: + self.embed_proj = None + self.head_proj = None + self.num_layers = h.num_layers + head_dim = h.model_dim // h.num_heads + kv_dim = h.num_kv_heads * head_dim + hidden_dim = int(h.mlp_mult * h.model_dim) + self.qo_bank = nn.Parameter(torch.empty(2 * h.num_layers, h.model_dim, h.model_dim)) + self.kv_bank = nn.Parameter(torch.empty(2 * h.num_layers, kv_dim, h.model_dim)) + self.mlp_up_bank = nn.Parameter(torch.empty(h.num_layers, hidden_dim, h.model_dim)) + self.mlp_down_bank = nn.Parameter(torch.empty(h.num_layers, h.model_dim, hidden_dim)) + self.num_encoder_layers = h.num_layers // 2 + self.num_decoder_layers = h.num_layers - self.num_encoder_layers + self.blocks = nn.ModuleList([Block(h.model_dim, h.num_heads, h.num_kv_heads, h.mlp_mult, h.rope_base, h.qk_gain_init, h.train_seq_len, layer_idx=i, ln_scale=h.ln_scale) for i in range(h.num_layers)]) + if h.rope_dims > 0: + head_dim = h.model_dim // h.num_heads + for block in self.blocks: + block.attn.rope_dims = h.rope_dims + block.attn.rotary = Rotary(head_dim, base=h.rope_base, train_seq_len=h.train_seq_len, rope_dims=h.rope_dims) + self.final_norm = RMSNorm() + self.lm_head = None if h.tie_embeddings else CastedLinear(h.embedding_dim, h.vocab_size, bias=False) + if self.lm_head is not None: + self.lm_head._zero_init = True + if h.xsa_last_n > 0: + for i in range(max(0, h.num_layers - h.xsa_last_n), h.num_layers): + self.blocks[i].attn.use_xsa = True + self.looping_active = False + if h.num_loops > 0: + loop_seg = list(range(h.loop_start, h.loop_end + 1)) + all_indices = list(range(h.loop_start)) + for _ in range(h.num_loops + 1): + all_indices.extend(loop_seg) + all_indices.extend(range(h.loop_end + 1, h.num_layers)) + num_enc = len(all_indices) // 2 + self.encoder_indices = all_indices[:num_enc] + self.decoder_indices = all_indices[num_enc:] + else: + self.encoder_indices = list(range(self.num_encoder_layers)) + self.decoder_indices = list(range(self.num_encoder_layers, h.num_layers)) + self.num_skip_weights = min(len(self.encoder_indices), len(self.decoder_indices)) + self.skip_weights = nn.Parameter(torch.ones(self.num_skip_weights, h.model_dim, dtype=torch.float32)) + self.skip_gates = nn.Parameter(torch.zeros(self.num_skip_weights, h.model_dim, dtype=torch.float32)) if h.skip_gates_enabled else None + self.parallel_residual = h.parallel_residual + self.parallel_start_layer = max(0, h.parallel_start_layer) + self.parallel_start_layer_is_physical = h.parallel_start_layer_is_physical + self.parallel_final_lane = h.parallel_final_lane.lower() + self.parallel_freeze_lane0 = h.parallel_freeze_lane0 + self.parallel_identity_init = h.parallel_identity_init + self.parallel_skip_lane0_only = h.parallel_skip_lane0_only + self.parallel_mlp_read_mix = h.parallel_mlp_read_mix + if self.parallel_final_lane not in ('mlp', 'mean', 'attn'): + raise ValueError(f"PARALLEL_FINAL_LANE must be one of 'mlp', 'mean', or 'attn', got {h.parallel_final_lane!r}") + if self.parallel_residual: + if self.parallel_identity_init: + self.parallel_post_lambdas = nn.Parameter(torch.ones(h.num_layers, 2, 2, dtype=torch.float32)) + self.parallel_resid_lambdas = nn.Parameter(torch.full((h.num_layers, 2), 1.1, dtype=torch.float32)) + else: + self.parallel_post_lambdas = nn.Parameter(torch.ones(h.num_layers, 2, 2, dtype=torch.float32)) + self.parallel_resid_lambdas = nn.Parameter(torch.full((h.num_layers, 2), 1.1 ** 0.5, dtype=torch.float32)) + else: + self.parallel_post_lambdas = None + self.parallel_resid_lambdas = None + self._init_weights() + + def _init_weights(self): + if self.tie_embeddings: + nn.init.normal_(self.tok_emb.weight, mean=0.0, std=self.tied_embed_init_std) + n = self.num_layers + proj_scale = 1.0 / math.sqrt(2 * n) + for i in range(n): + nn.init.orthogonal_(self.qo_bank.data[i], gain=1.0) + nn.init.zeros_(self.qo_bank.data[n + i]) + self.qo_bank.data[n + i].mul_(proj_scale) + nn.init.orthogonal_(self.kv_bank.data[i], gain=1.0) + nn.init.orthogonal_(self.kv_bank.data[n + i], gain=1.0) + nn.init.orthogonal_(self.mlp_up_bank.data[i], gain=1.0) + nn.init.zeros_(self.mlp_down_bank.data[i]) + self.mlp_down_bank.data[i].mul_(proj_scale) + for name, module in self.named_modules(): + if isinstance(module, nn.Linear): + if getattr(module, '_zero_init', False): + nn.init.zeros_(module.weight) + elif module.weight.ndim == 2 and module.weight.shape[0] >= 64 and (module.weight.shape[1] >= 64): + nn.init.orthogonal_(module.weight, gain=1.0) + + def _bank_weights(self, i): + n = self.num_layers + return (self.qo_bank[i], self.kv_bank[i], self.kv_bank[n + i], self.qo_bank[n + i], self.mlp_up_bank[i], self.mlp_down_bank[i]) + + def _parallel_active_for_layer(self, physical_idx, virtual_idx): + if self.parallel_post_lambdas is None: + return False + if self.parallel_start_layer_is_physical: + return physical_idx >= self.parallel_start_layer + return virtual_idx >= self.parallel_start_layer + + def _mix_with_x0(self, lane, x0, resid_mix): + mix = resid_mix.to(dtype=lane.dtype) + return mix[0][None, None, :] * lane + mix[1][None, None, :] * x0 + + def _apply_skip_single(self, x, skip, skip_idx): + if isinstance(skip, tuple): + skip = skip[1] + scaled_skip = self.skip_weights[skip_idx].to(dtype=x.dtype)[None, None, :] * skip + if self.skip_gates is None: + return x + scaled_skip + g = torch.sigmoid(self.skip_gates[skip_idx].to(dtype=x.dtype))[None, None, :] + return torch.lerp(scaled_skip, x, g) + + def _apply_skip_parallel(self, lane0, lane1, skip, skip_idx): + if isinstance(skip, tuple): + skip0, skip1 = skip + else: + skip0 = skip1 = skip + w = self.skip_weights[skip_idx].to(dtype=lane0.dtype)[None, None, :] + if self.parallel_skip_lane0_only: + if self.skip_gates is None: + next_lane0 = lane0 if self.parallel_freeze_lane0 else lane0 + w * skip0 + return (next_lane0, lane1) + g = torch.sigmoid(self.skip_gates[skip_idx].to(dtype=lane0.dtype))[None, None, :] + next_lane0 = lane0 if self.parallel_freeze_lane0 else torch.lerp(w * skip0, lane0, g) + return (next_lane0, lane1) + if self.skip_gates is None: + next_lane0 = lane0 if self.parallel_freeze_lane0 else lane0 + w * skip0 + return (next_lane0, lane1 + w * skip1) + g = torch.sigmoid(self.skip_gates[skip_idx].to(dtype=lane0.dtype))[None, None, :] + next_lane0 = lane0 if self.parallel_freeze_lane0 else torch.lerp(w * skip0, lane0, g) + return (next_lane0, torch.lerp(w * skip1, lane1, g)) + + def _final_parallel_hidden(self, lane0, lane1): + if self.parallel_final_lane == 'mlp': + return lane1 + if self.parallel_final_lane == 'attn': + return lane0 + return 0.5 * (lane0 + lane1) + + def _parallel_block(self, block_idx, lane0, lane1, x0, q_w, k_w, v_w, out_w, up_w, down_w, cu_seqlens=None, max_seqlen=0): + if self.parallel_post_lambdas is None or self.parallel_resid_lambdas is None: + raise RuntimeError('parallel residual weights are not initialized') + block = self.blocks[block_idx] + attn_read = self._mix_with_x0(lane0, x0, block.resid_mix) + attn_out = block.attn(block.attn_norm(attn_read) * block.ln_scale_factor, q_w, k_w, v_w, out_w, cu_seqlens=cu_seqlens, max_seqlen=max_seqlen) + attn_out = block.attn_scale.to(dtype=attn_out.dtype)[None, None, :] * attn_out + mlp_read = self._mix_with_x0(lane1, x0, block.resid_mix) if self.parallel_mlp_read_mix else lane1 + mlp_out = block.mlp_scale.to(dtype=lane1.dtype)[None, None, :] * block.mlp(block.mlp_norm(mlp_read) * block.ln_scale_factor, up_w, down_w) + attn_resid = self.parallel_resid_lambdas[block_idx, 0].to(dtype=lane0.dtype) + attn_post = self.parallel_post_lambdas[block_idx, 0].to(dtype=lane0.dtype) + mlp_resid = self.parallel_resid_lambdas[block_idx, 1].to(dtype=lane0.dtype) + mlp_post = self.parallel_post_lambdas[block_idx, 1].to(dtype=lane0.dtype) + next_lane0 = lane0 + if not self.parallel_freeze_lane0: + next_lane0 = attn_resid * lane0 + attn_post[0] * attn_out + mlp_post[0] * mlp_out + next_lane1 = mlp_resid * lane1 + attn_post[1] * attn_out + mlp_post[1] * mlp_out + return (next_lane0, next_lane1) + + def _forward_logits_from_embeddings(self, x, cu_seqlens=None, max_seqlen=0): + x0 = x + skips = [] + enc_iter = list(self.encoder_indices) if self.looping_active else list(range(self.num_encoder_layers)) + dec_iter = list(self.decoder_indices) if self.looping_active else list(range(self.num_encoder_layers, self.num_encoder_layers + self.num_decoder_layers)) + lane0 = None + lane1 = None + for virtual_idx, block_idx in enumerate(enc_iter): + q_w, k_w, v_w, out_w, up_w, down_w = self._bank_weights(block_idx) + if self._parallel_active_for_layer(block_idx, virtual_idx): + if lane0 is None or lane1 is None: + lane0 = x + lane1 = x + lane0, lane1 = self._parallel_block(block_idx, lane0, lane1, x0, q_w, k_w, v_w, out_w, up_w, down_w, cu_seqlens=cu_seqlens, max_seqlen=max_seqlen) + skips.append((lane0, lane1)) + else: + x = self.blocks[block_idx](x, x0, q_w, k_w, v_w, out_w, up_w, down_w, cu_seqlens=cu_seqlens, max_seqlen=max_seqlen) + skips.append(x) + dec_offset = len(enc_iter) + for skip_idx, block_idx in enumerate(dec_iter): + virtual_idx = dec_offset + skip_idx + q_w, k_w, v_w, out_w, up_w, down_w = self._bank_weights(block_idx) + if self._parallel_active_for_layer(block_idx, virtual_idx): + if lane0 is None or lane1 is None: + if self.parallel_skip_lane0_only and skip_idx < self.num_skip_weights and skips: + x = self._apply_skip_single(x, skips.pop(), skip_idx) + lane0 = x + lane1 = x + elif skip_idx < self.num_skip_weights and skips: + lane0, lane1 = self._apply_skip_parallel(lane0, lane1, skips.pop(), skip_idx) + lane0, lane1 = self._parallel_block(block_idx, lane0, lane1, x0, q_w, k_w, v_w, out_w, up_w, down_w, cu_seqlens=cu_seqlens, max_seqlen=max_seqlen) + else: + if skip_idx < self.num_skip_weights and skips: + x = self._apply_skip_single(x, skips.pop(), skip_idx) + x = self.blocks[block_idx](x, x0, q_w, k_w, v_w, out_w, up_w, down_w, cu_seqlens=cu_seqlens, max_seqlen=max_seqlen) + if lane1 is not None: + x = self._final_parallel_hidden(lane0, lane1) + x = self.final_norm(x) + if self.head_proj is not None: + x = self.head_proj(x) + if self.tie_embeddings: + logits_proj = F.linear(x, self.tok_emb.weight) + else: + logits_proj = self.lm_head(x) + return self.logit_softcap * torch.tanh(logits_proj / self.logit_softcap) + + def forward_logits(self, input_ids, cu_seqlens=None, max_seqlen=0): + x = self.tok_emb(input_ids) + x = F.rms_norm(x, (x.size(-1),)) + if self.embed_proj is not None: + x = self.embed_proj(x) + return self._forward_logits_from_embeddings(x, cu_seqlens=cu_seqlens, max_seqlen=max_seqlen) + + def forward(self, input_ids, target_ids, cu_seqlens=None, max_seqlen=0): + logits = self.forward_logits(input_ids, cu_seqlens=cu_seqlens, max_seqlen=max_seqlen) + return F.cross_entropy(logits.reshape(-1, logits.size(-1)).float(), target_ids.reshape(-1), reduction='mean') + + def _block_with_lora(self, block, x, x0, lora, slot, q_w, k_w, v_w, out_w, up_w, down_w): + mix = block.resid_mix.to(dtype=x.dtype) + x_in = mix[0][None, None, :] * x + mix[1][None, None, :] * x0 + n = block.attn_norm(x_in) * block.ln_scale_factor + attn = block.attn + bsz, seqlen, dim = n.shape + q = (F.linear(n, q_w.to(n.dtype)) + lora.q_loras[slot](n)).reshape(bsz, seqlen, attn.num_heads, attn.head_dim) + k = F.linear(n, k_w.to(n.dtype)) + if lora.k_loras is not None: + k = k + lora.k_loras[slot](n) + k = k.reshape(bsz, seqlen, attn.num_kv_heads, attn.head_dim) + v = (F.linear(n, v_w.to(n.dtype)) + lora.v_loras[slot](n)).reshape(bsz, seqlen, attn.num_kv_heads, attn.head_dim) + q = F.rms_norm(q, (q.size(-1),)) + k = F.rms_norm(k, (k.size(-1),)) + cos, sin = attn.rotary(seqlen, n.device, q.dtype) + q = apply_rotary_emb(q, cos, sin, attn.rope_dims) + k = apply_rotary_emb(k, cos, sin, attn.rope_dims) + q = q * attn.q_gain.to(dtype=q.dtype)[None, None, :, None] + y = flash_attn_3_func(q, k, v, causal=True) + if attn.use_xsa: + y = attn._xsa_efficient(y, v) + y = y.reshape(bsz, seqlen, dim) + attn_out = F.linear(y, out_w.to(n.dtype)) + if lora.o_loras is not None: + attn_out = attn_out + lora.o_loras[slot](n) + x_out = x_in + block.attn_scale.to(dtype=x_in.dtype)[None, None, :] * attn_out + mlp_n = block.mlp_norm(x_out) * block.ln_scale_factor + mlp_out = block.mlp(mlp_n, up_w, down_w) + if lora.mlp_loras is not None: + mlp_out = mlp_out + lora.mlp_loras[slot](mlp_n) + x_out = x_out + block.mlp_scale.to(dtype=x_out.dtype)[None, None, :] * mlp_out + return x_out + + def _block_with_lora_attn(self, block, x, x0, lora, slot, q_w, k_w, v_w, out_w): + mix = block.resid_mix.to(dtype=x.dtype) + x_in = mix[0][None, None, :] * x + mix[1][None, None, :] * x0 + n = block.attn_norm(x_in) * block.ln_scale_factor + attn = block.attn + bsz, seqlen, dim = n.shape + q = (F.linear(n, q_w.to(n.dtype)) + lora.q_loras[slot](n)).reshape(bsz, seqlen, attn.num_heads, attn.head_dim) + k = F.linear(n, k_w.to(n.dtype)) + if lora.k_loras is not None: + k = k + lora.k_loras[slot](n) + k = k.reshape(bsz, seqlen, attn.num_kv_heads, attn.head_dim) + v = (F.linear(n, v_w.to(n.dtype)) + lora.v_loras[slot](n)).reshape(bsz, seqlen, attn.num_kv_heads, attn.head_dim) + q = F.rms_norm(q, (q.size(-1),)) + k = F.rms_norm(k, (k.size(-1),)) + cos, sin = attn.rotary(seqlen, n.device, q.dtype) + q = apply_rotary_emb(q, cos, sin, attn.rope_dims) + k = apply_rotary_emb(k, cos, sin, attn.rope_dims) + q = q * attn.q_gain.to(dtype=q.dtype)[None, None, :, None] + y = flash_attn_3_func(q, k, v, causal=True) + if attn.use_xsa: + y = attn._xsa_efficient(y, v) + y = y.reshape(bsz, seqlen, dim) + attn_out = F.linear(y, out_w.to(n.dtype)) + if lora.o_loras is not None: + attn_out = attn_out + lora.o_loras[slot](n) + return x_in + block.attn_scale.to(dtype=x_in.dtype)[None, None, :] * attn_out + + def _block_with_lora_mlp(self, block, x, lora, slot, up_w, down_w): + mlp_n = block.mlp_norm(x) * block.ln_scale_factor + mlp_out = block.mlp(mlp_n, up_w, down_w) + if lora.mlp_loras is not None: + mlp_out = mlp_out + lora.mlp_loras[slot](mlp_n) + return x + block.mlp_scale.to(dtype=x.dtype)[None, None, :] * mlp_out + + def _parallel_block_with_lora(self, block_idx, lane0, lane1, x0, lora, slot, q_w, k_w, v_w, out_w, up_w, down_w): + block = self.blocks[block_idx] + attn_read = self._mix_with_x0(lane0, x0, block.resid_mix) + n = block.attn_norm(attn_read) * block.ln_scale_factor + attn = block.attn + bsz, seqlen, dim = n.shape + q = (F.linear(n, q_w.to(n.dtype)) + lora.q_loras[slot](n)).reshape(bsz, seqlen, attn.num_heads, attn.head_dim) + k = F.linear(n, k_w.to(n.dtype)) + if lora.k_loras is not None: + k = k + lora.k_loras[slot](n) + k = k.reshape(bsz, seqlen, attn.num_kv_heads, attn.head_dim) + v = (F.linear(n, v_w.to(n.dtype)) + lora.v_loras[slot](n)).reshape(bsz, seqlen, attn.num_kv_heads, attn.head_dim) + q = F.rms_norm(q, (q.size(-1),)) + k = F.rms_norm(k, (k.size(-1),)) + cos, sin = attn.rotary(seqlen, n.device, q.dtype) + q = apply_rotary_emb(q, cos, sin, attn.rope_dims) + k = apply_rotary_emb(k, cos, sin, attn.rope_dims) + q = q * attn.q_gain.to(dtype=q.dtype)[None, None, :, None] + y = flash_attn_3_func(q, k, v, causal=True) + if attn.use_xsa: + y = attn._xsa_efficient(y, v) + y = y.reshape(bsz, seqlen, dim) + attn_out_raw = F.linear(y, out_w.to(n.dtype)) + if lora.o_loras is not None: + attn_out_raw = attn_out_raw + lora.o_loras[slot](n) + attn_out = block.attn_scale.to(dtype=attn_out_raw.dtype)[None, None, :] * attn_out_raw + mlp_read = self._mix_with_x0(lane1, x0, block.resid_mix) if self.parallel_mlp_read_mix else lane1 + mlp_n = block.mlp_norm(mlp_read) * block.ln_scale_factor + mlp_out_raw = block.mlp(mlp_n, up_w, down_w) + if lora.mlp_loras is not None: + mlp_out_raw = mlp_out_raw + lora.mlp_loras[slot](mlp_n) + mlp_out = block.mlp_scale.to(dtype=lane1.dtype)[None, None, :] * mlp_out_raw + attn_resid = self.parallel_resid_lambdas[block_idx, 0].to(dtype=lane0.dtype) + attn_post = self.parallel_post_lambdas[block_idx, 0].to(dtype=lane0.dtype) + mlp_resid = self.parallel_resid_lambdas[block_idx, 1].to(dtype=lane0.dtype) + mlp_post = self.parallel_post_lambdas[block_idx, 1].to(dtype=lane0.dtype) + next_lane0 = lane0 + if not self.parallel_freeze_lane0: + next_lane0 = attn_resid * lane0 + attn_post[0] * attn_out + mlp_post[0] * mlp_out + next_lane1 = mlp_resid * lane1 + attn_post[1] * attn_out + mlp_post[1] * mlp_out + return (next_lane0, next_lane1) + + def forward_ttt(self, input_ids, target_ids, lora): + x = self.tok_emb(input_ids) + x = F.rms_norm(x, (x.size(-1),)) + if self.embed_proj is not None: + x = self.embed_proj(x) + x0 = x + skips = [] + enc_iter = list(self.encoder_indices) if self.looping_active else list(range(self.num_encoder_layers)) + dec_iter = list(self.decoder_indices) if self.looping_active else list(range(self.num_encoder_layers, self.num_encoder_layers + self.num_decoder_layers)) + lane0 = None + lane1 = None + slot = 0 + for virtual_idx, block_idx in enumerate(enc_iter): + q_w, k_w, v_w, out_w, up_w, down_w = self._bank_weights(block_idx) + if self._parallel_active_for_layer(block_idx, virtual_idx): + if lane0 is None or lane1 is None: + lane0 = x + lane1 = x + lane0, lane1 = self._parallel_block_with_lora(block_idx, lane0, lane1, x0, lora, slot, q_w, k_w, v_w, out_w, up_w, down_w) + skips.append((lane0, lane1)) + else: + x = self._block_with_lora(self.blocks[block_idx], x, x0, lora, slot, q_w, k_w, v_w, out_w, up_w, down_w) + skips.append(x) + slot += 1 + dec_offset = len(enc_iter) + for skip_idx, block_idx in enumerate(dec_iter): + virtual_idx = dec_offset + skip_idx + q_w, k_w, v_w, out_w, up_w, down_w = self._bank_weights(block_idx) + if self._parallel_active_for_layer(block_idx, virtual_idx): + if lane0 is None or lane1 is None: + if self.parallel_skip_lane0_only and skip_idx < self.num_skip_weights and skips: + x = self._apply_skip_single(x, skips.pop(), skip_idx) + lane0 = x + lane1 = x + elif skip_idx < self.num_skip_weights and skips: + lane0, lane1 = self._apply_skip_parallel(lane0, lane1, skips.pop(), skip_idx) + lane0, lane1 = self._parallel_block_with_lora(block_idx, lane0, lane1, x0, lora, slot, q_w, k_w, v_w, out_w, up_w, down_w) + else: + if skip_idx < self.num_skip_weights and skips: + if lane1 is not None: + x = self._final_parallel_hidden(lane0, lane1) + lane0 = None + lane1 = None + x = self._apply_skip_single(x, skips.pop(), skip_idx) + x = self._block_with_lora(self.blocks[block_idx], x, x0, lora, slot, q_w, k_w, v_w, out_w, up_w, down_w) + slot += 1 + if lane1 is not None: + x = self._final_parallel_hidden(lane0, lane1) + x = self.final_norm(x) + if self.head_proj is not None: + x = self.head_proj(x) + if self.tie_embeddings: + logits = F.linear(x, self.tok_emb.weight) + else: + logits = self.lm_head(x) + logits = logits + lora.lm_head_lora(x) + logits = self.logit_softcap * torch.tanh(logits / self.logit_softcap) + bsz, sl, V = logits.shape + return F.cross_entropy(logits.float().reshape(-1, V), target_ids.reshape(-1), reduction='none').reshape(bsz, sl) + +def classify_param(name): + if 'tok_emb' in name or 'lm_head' in name: + return 'embed' + if '.mlp.' in name: + return 'mlp' + if '.attn.' in name or ('.proj.' in name and '.mlp.' not in name): + return 'attn' + return 'other' + +@torch.compile +def zeropower_via_newtonschulz5(G, steps=10, eps=1e-07): + a, b, c = (3.4445, -4.775, 2.0315) + was_2d = G.ndim == 2 + if was_2d: + G = G.unsqueeze(0) + X = G.bfloat16() + transposed = X.size(-2) > X.size(-1) + if transposed: + X = X.mT + X = X / (X.norm(dim=(-2, -1), keepdim=True) + eps) + for _ in range(steps): + A = X @ X.mT + B = b * A + c * (A @ A) + X = a * X + B @ X + if transposed: + X = X.mT + if was_2d: + X = X.squeeze(0) + return X + +class Muon(torch.optim.Optimizer): + + def __init__(self, params, lr, momentum, backend_steps, nesterov=True, weight_decay=0.0, row_normalize=False): + super().__init__(params, dict(lr=lr, momentum=momentum, backend_steps=backend_steps, nesterov=nesterov, weight_decay=weight_decay, row_normalize=row_normalize)) + self._built = False + + def _build(self): + self._distributed = dist.is_available() and dist.is_initialized() + self._world_size = dist.get_world_size() if self._distributed else 1 + self._rank = dist.get_rank() if self._distributed else 0 + ws = self._world_size + self._bank_meta = [] + for group in self.param_groups: + for p in group['params']: + B = p.shape[0] + padded_B = (B + ws - 1) // ws * ws + shard_B = padded_B // ws + tail = p.shape[1:] + dev = p.device + self._bank_meta.append({'p': p, 'B': B, 'padded_grad': torch.zeros(padded_B, *tail, device=dev, dtype=torch.bfloat16), 'shard': torch.zeros(shard_B, *tail, device=dev, dtype=torch.bfloat16), 'shard_mom': torch.zeros(shard_B, *tail, device=dev, dtype=torch.bfloat16), 'full_update': torch.zeros(padded_B, *tail, device=dev, dtype=torch.bfloat16), 'scale': max(1, p.shape[-2] / p.shape[-1]) ** 0.5}) + self._bank_meta.sort(key=lambda m: -m['p'].numel()) + self._built = True + + def launch_reduce_scatters(self): + if not self._built: + self._build() + if not self._distributed: + return + self._rs_futures = [] + for m in self._bank_meta: + p = m['p'] + if p.grad is None: + self._rs_futures.append(None) + continue + pg = m['padded_grad'] + pg[:m['B']].copy_(p.grad.bfloat16()) + if pg.shape[0] > m['B']: + pg[m['B']:].zero_() + fut = dist.reduce_scatter_tensor(m['shard'], pg, op=dist.ReduceOp.AVG, async_op=True) + self._rs_futures.append(fut) + + @torch.no_grad() + def step(self, closure=None): + loss = None + if closure is not None: + with torch.enable_grad(): + loss = closure() + if not self._built: + self._build() + for group in self.param_groups: + lr = group['lr'] + momentum = group['momentum'] + backend_steps = group['backend_steps'] + nesterov = group['nesterov'] + wd = group.get('weight_decay', 0.0) + row_normalize = group.get('row_normalize', False) + prev_ag_handle = None + prev_m = None + sharded = self._distributed and hasattr(self, '_rs_futures') + for idx, m in enumerate(self._bank_meta): + p = m['p'] + if p.grad is None: + continue + if prev_ag_handle is not None: + prev_ag_handle.wait() + pp = prev_m['p'] + upd = prev_m['full_update'][:prev_m['B']] + if wd > 0.0: + pp.data.mul_(1.0 - lr * wd) + pp.add_(upd.to(dtype=pp.dtype), alpha=-lr * prev_m['scale']) + if sharded and self._rs_futures[idx] is not None: + self._rs_futures[idx].wait() + g = m['shard'] + buf = m['shard_mom'] + else: + g = p.grad.bfloat16() + state = self.state[p] + if 'momentum_buffer' not in state: + state['momentum_buffer'] = torch.zeros_like(g) + buf = state['momentum_buffer'] + buf.mul_(momentum).add_(g) + if nesterov: + update = g.add(buf, alpha=momentum) + else: + update = buf + if row_normalize: + rn = update.float().norm(dim=-1, keepdim=True).clamp_min(1e-07) + update = update / rn.to(update.dtype) + update = zeropower_via_newtonschulz5(update, steps=backend_steps) + if sharded: + prev_ag_handle = dist.all_gather_into_tensor(m['full_update'], update, async_op=True) + prev_m = m + else: + if wd > 0.0: + p.data.mul_(1.0 - lr * wd) + p.add_(update.to(dtype=p.dtype), alpha=-lr * m['scale']) + if prev_ag_handle is not None: + prev_ag_handle.wait() + pp = prev_m['p'] + upd = prev_m['full_update'][:prev_m['B']] + if wd > 0.0: + pp.data.mul_(1.0 - lr * wd) + pp.add_(upd.to(dtype=pp.dtype), alpha=-lr * prev_m['scale']) + if hasattr(self, '_rs_futures'): + del self._rs_futures + return loss +CONTROL_TENSOR_NAME_PATTERNS = tuple((pattern for pattern in os.environ.get('CONTROL_TENSOR_NAME_PATTERNS', 'attn_scale,attn_scales,mlp_scale,mlp_scales,resid_mix,resid_mixes,q_gain,skip_weight,skip_weights,skip_gates,parallel_post_lambdas,parallel_resid_lambdas').split(',') if pattern)) + +class Optimizers: + + def __init__(self, h, base_model): + matrix_params = [base_model.qo_bank, base_model.kv_bank, base_model.mlp_up_bank, base_model.mlp_down_bank] + block_named_params = list(base_model.blocks.named_parameters()) + scalar_params = [p for name, p in block_named_params if p.ndim < 2 or any((pattern in name for pattern in CONTROL_TENSOR_NAME_PATTERNS))] + if base_model.skip_weights.numel() > 0: + scalar_params.append(base_model.skip_weights) + if base_model.skip_gates is not None and base_model.skip_gates.numel() > 0: + scalar_params.append(base_model.skip_gates) + if base_model.parallel_post_lambdas is not None: + scalar_params.append(base_model.parallel_post_lambdas) + if base_model.parallel_resid_lambdas is not None: + scalar_params.append(base_model.parallel_resid_lambdas) + token_lr = h.tied_embed_lr if h.tie_embeddings else h.embed_lr + tok_params = [{'params': [base_model.tok_emb.weight], 'lr': token_lr, 'base_lr': token_lr}] + self.optimizer_tok = torch.optim.AdamW(tok_params, betas=(h.beta1, h.beta2), eps=h.adam_eps, weight_decay=h.embed_wd, fused=True) + self.optimizer_muon = Muon(matrix_params, lr=h.matrix_lr, momentum=h.muon_momentum, backend_steps=h.muon_backend_steps, weight_decay=h.muon_wd, row_normalize=h.muon_row_normalize) + for group in self.optimizer_muon.param_groups: + group['base_lr'] = h.matrix_lr + scalar_groups = [{'params': scalar_params, 'lr': h.scalar_lr, 'base_lr': h.scalar_lr, 'weight_decay': h.adam_wd}] + self.optimizer_scalar = torch.optim.AdamW(scalar_groups, betas=(h.beta1, h.beta2), eps=h.adam_eps, fused=True) + self.optimizers = [self.optimizer_tok, self.optimizer_muon, self.optimizer_scalar] + if base_model.lm_head is not None: + self.optimizer_head = torch.optim.Adam([{'params': [base_model.lm_head.weight], 'lr': h.head_lr, 'base_lr': h.head_lr}], betas=(h.beta1, h.beta2), eps=h.adam_eps, fused=True) + self.optimizers.insert(1, self.optimizer_head) + else: + self.optimizer_head = None + self.replicated_params = list(tok_params[0]['params']) + self.replicated_params.extend(scalar_params) + if base_model.lm_head is not None: + self.replicated_params.append(base_model.lm_head.weight) + + def __iter__(self): + return iter(self.optimizers) + + def zero_grad_all(self): + for opt in self.optimizers: + opt.zero_grad(set_to_none=True) + + def step(self, distributed=False): + self.optimizer_muon.launch_reduce_scatters() + if distributed: + for p in self.replicated_params: + if p.grad is not None: + dist.all_reduce(p.grad, op=dist.ReduceOp.AVG) + self.optimizer_tok.step() + self.optimizer_scalar.step() + if self.optimizer_head is not None: + self.optimizer_head.step() + self.optimizer_muon.step() + self.zero_grad_all() + +def restore_fp32_params(model): + for module in model.modules(): + if isinstance(module, CastedLinear): + module.float() + for name, param in model.named_parameters(): + if (param.ndim < 2 or any((pattern in name for pattern in CONTROL_TENSOR_NAME_PATTERNS))) and param.dtype != torch.float32: + param.data = param.data.float() + if hasattr(model, 'qo_bank'): + model.qo_bank.data = model.qo_bank.data.float() + model.kv_bank.data = model.kv_bank.data.float() + model.mlp_up_bank.data = model.mlp_up_bank.data.float() + model.mlp_down_bank.data = model.mlp_down_bank.data.float() + +def log_parallel_residual_converged(log0, model): + if getattr(model, 'parallel_post_lambdas', None) is None: + return + if model.looping_active: + v2p = list(model.encoder_indices) + list(model.decoder_indices) + else: + v2p = list(range(model.num_encoder_layers + model.num_decoder_layers)) + used_layers = [vi for vi, pi in enumerate(v2p) if model._parallel_active_for_layer(pi, vi)] + post = model.parallel_post_lambdas.detach().cpu() + resid = model.parallel_resid_lambdas.detach().cpu() + mode = 'physical' if model.parallel_start_layer_is_physical else 'virtual' + log0(f'parallel_residual:converged active=1 start_layer={model.parallel_start_layer} start_mode={mode} final_lane={model.parallel_final_lane} freeze_lane0={int(model.parallel_freeze_lane0)} identity_init={int(model.parallel_identity_init)} skip_lane0_only={int(model.parallel_skip_lane0_only)} mlp_read_mix={int(model.parallel_mlp_read_mix)} used_layers={len(used_layers)}') + for vi in used_layers: + pi = int(v2p[vi]) + if not (0 <= pi < post.shape[0] and 0 <= pi < resid.shape[0]): + log0(f'parallel_residual layer:{vi} physical:{pi} skipped=out_of_range') + continue + log0(f'parallel_residual layer:{vi} physical:{pi} attn_resid:{resid[pi, 0]:.4f} attn_to_attn:{post[pi, 0, 0]:.4f} attn_to_mlp:{post[pi, 0, 1]:.4f} mlp_resid:{resid[pi, 1]:.4f} mlp_to_attn:{post[pi, 1, 0]:.4f} mlp_to_mlp:{post[pi, 1, 1]:.4f}') + +def _unbank_state_dict(state_dict, num_layers): + sd = {} + n = num_layers + for k, v in state_dict.items(): + t = v.detach().cpu() + if k == 'qo_bank': + for i in range(n): + sd[f'blocks.{i}.attn.c_q.weight'] = t[i] + sd[f'blocks.{i}.attn.proj.weight'] = t[n + i] + elif k == 'kv_bank': + for i in range(n): + sd[f'blocks.{i}.attn.c_k.weight'] = t[i] + sd[f'blocks.{i}.attn.c_v.weight'] = t[n + i] + elif k == 'mlp_up_bank': + for i in range(n): + sd[f'blocks.{i}.mlp.fc.weight'] = t[i] + elif k == 'mlp_down_bank': + for i in range(n): + sd[f'blocks.{i}.mlp.proj.weight'] = t[i] + else: + sd[k] = t + return sd + +def _rebank_state_dict(flat_sd, num_layers, model_dim, kv_dim, hidden_dim): + sd = {} + n = num_layers + sd['qo_bank'] = torch.zeros(2 * n, model_dim, model_dim) + sd['kv_bank'] = torch.zeros(2 * n, kv_dim, model_dim) + sd['mlp_up_bank'] = torch.zeros(n, hidden_dim, model_dim) + sd['mlp_down_bank'] = torch.zeros(n, model_dim, hidden_dim) + for i in range(n): + sd['qo_bank'][i] = flat_sd[f'blocks.{i}.attn.c_q.weight'] + sd['qo_bank'][n + i] = flat_sd[f'blocks.{i}.attn.proj.weight'] + sd['kv_bank'][i] = flat_sd[f'blocks.{i}.attn.c_k.weight'] + sd['kv_bank'][n + i] = flat_sd[f'blocks.{i}.attn.c_v.weight'] + sd['mlp_up_bank'][i] = flat_sd[f'blocks.{i}.mlp.fc.weight'] + sd['mlp_down_bank'][i] = flat_sd[f'blocks.{i}.mlp.proj.weight'] + for k, v in flat_sd.items(): + if not (k.startswith('blocks.') and any((p in k for p in ['.attn.c_q.', '.attn.c_k.', '.attn.c_v.', '.attn.proj.', '.mlp.fc.', '.mlp.proj.']))): + sd[k] = v + return sd + +def collect_hessians(model, train_loader, h, device, n_calibration_batches=64): + hessians = {} + hooks = [] + n = model.num_layers + for i, block in enumerate(model.blocks): + block.attn._calib = True + block.mlp._calib = True + + def make_attn_hook(layer_idx): + + def hook_fn(module, inp, out): + x = inp[0].detach().float() + if x.ndim == 3: + x = x.reshape(-1, x.shape[-1]) + for suffix in ['c_q', 'c_k', 'c_v']: + name = f'blocks.{layer_idx}.attn.{suffix}.weight' + if name not in hessians: + hessians[name] = torch.zeros(x.shape[1], x.shape[1], dtype=torch.float32, device=device) + hessians[name].addmm_(x.T, x) + y = module._last_proj_input + if y is not None: + y = y.float() + if y.ndim == 3: + y = y.reshape(-1, y.shape[-1]) + name = f'blocks.{layer_idx}.attn.proj.weight' + if name not in hessians: + hessians[name] = torch.zeros(y.shape[1], y.shape[1], dtype=torch.float32, device=device) + hessians[name].addmm_(y.T, y) + return hook_fn + + def make_mlp_hook(layer_idx): + + def hook_fn(module, inp, out): + x = inp[0].detach().float() + if x.ndim == 3: + x = x.reshape(-1, x.shape[-1]) + name = f'blocks.{layer_idx}.mlp.fc.weight' + if name not in hessians: + hessians[name] = torch.zeros(x.shape[1], x.shape[1], dtype=torch.float32, device=device) + hessians[name].addmm_(x.T, x) + h_act = module._last_down_input + if h_act is not None: + h_act = h_act.float() + if h_act.ndim == 3: + h_act = h_act.reshape(-1, h_act.shape[-1]) + name = f'blocks.{layer_idx}.mlp.proj.weight' + if name not in hessians: + hessians[name] = torch.zeros(h_act.shape[1], h_act.shape[1], dtype=torch.float32, device=device) + hessians[name].addmm_(h_act.T, h_act) + return hook_fn + for i, block in enumerate(model.blocks): + hooks.append(block.attn.register_forward_hook(make_attn_hook(i))) + hooks.append(block.mlp.register_forward_hook(make_mlp_hook(i))) + if model.tie_embeddings: + hook_module = model.head_proj if model.head_proj is not None else model.final_norm + + def make_output_hook(name): + + def hook_fn(module, inp, out): + x = out.detach().float() + if x.ndim == 3: + x = x.reshape(-1, x.shape[-1]) + if name not in hessians: + hessians[name] = torch.zeros(x.shape[1], x.shape[1], dtype=torch.float32, device=device) + hessians[name].addmm_(x.T, x) + return hook_fn + hooks.append(hook_module.register_forward_hook(make_output_hook('tok_emb.weight'))) + model.eval() + with torch.no_grad(): + for _ in range(n_calibration_batches): + x, _ = train_loader.next_batch(h.train_batch_tokens, h.grad_accum_steps) + model.forward_logits(x) + for hook in hooks: + hook.remove() + for i, block in enumerate(model.blocks): + block.attn._calib = False + block.mlp._calib = False + for name in hessians: + hessians[name] = hessians[name].cpu() / n_calibration_batches + return hessians + +def gptq_quantize_weight(w, H, clip_sigmas=3.0, clip_range=63, block_size=128, hessian_clip_lambda=0.175): + W_orig = w.float().clone() + rows, cols = W_orig.shape + H = H.float().clone() + diagH_orig = torch.diag(H).clone() + dead = torch.diag(H) == 0 + H[dead, dead] = 1 + damp = 0.01 * H.diag().mean() + H.diagonal().add_(damp) + perm = torch.argsort(H.diag(), descending=True) + invperm = torch.argsort(perm) + W_perm = W_orig[:, perm].clone() + W_perm[:, dead[perm]] = 0 + H = H[perm][:, perm] + Hinv = torch.cholesky_inverse(torch.linalg.cholesky(H)) + Hinv = torch.linalg.cholesky(Hinv, upper=True) + row_std = W_orig.std(dim=1) + if hessian_clip_lambda > 0.0: + col_imp = (diagH_orig / diagH_orig.mean().clamp_min(1e-12)).to(W_orig.dtype) + row_imp = (W_orig.abs() * col_imp.unsqueeze(0)).mean(dim=1) + row_imp = row_imp / row_imp.mean().clamp_min(1e-12) + row_std = row_std * (1.0 + hessian_clip_lambda * (row_imp - 1.0)) + s = (clip_sigmas * row_std / clip_range).clamp_min(1e-10).to(torch.float16) + sf = s.float() + Q = torch.zeros(rows, cols, dtype=torch.int8) + W_work = W_perm.clone() + for i1 in range(0, cols, block_size): + i2 = min(i1 + block_size, cols) + W_block = W_work[:, i1:i2].clone() + Hinv_block = Hinv[i1:i2, i1:i2] + Err = torch.zeros(rows, i2 - i1) + for j in range(i2 - i1): + w_col = W_block[:, j] + d = Hinv_block[j, j] + q_col = torch.clamp(torch.round(w_col / sf), -clip_range, clip_range) + Q[:, i1 + j] = q_col.to(torch.int8) + err = (w_col - q_col.float() * sf) / d + Err[:, j] = err + W_block[:, j:] -= err.unsqueeze(1) * Hinv_block[j, j:].unsqueeze(0) + if i2 < cols: + W_work[:, i2:] -= Err @ Hinv[i1:i2, i2:] + return (Q[:, invperm], s) + +def gptq_mixed_quantize(state_dict, hessians, h): + result = {} + meta = {} + for name, tensor in state_dict.items(): + t = tensor.detach().cpu().contiguous() + if not t.is_floating_point() or t.numel() <= 65536: + result[name] = t.to(torch.float16) if t.is_floating_point() else t + meta[name] = 'passthrough (float16)' + continue + cs = h.embed_clip_sigmas if 'tok_emb' in name else h.matrix_clip_sigmas + bits = h.embed_bits if 'tok_emb' in name else h.matrix_bits + q, s = gptq_quantize_weight(t, hessians[name], clip_sigmas=cs, clip_range=2 ** (bits - 1) - 1, + hessian_clip_lambda=h.hessian_clip_lambda) + result[name + '.q'] = q + result[name + '.scale'] = s + meta[name] = f'gptq (int{bits})' + categories = collections.defaultdict(set) + for name, cat in meta.items(): + short = re.sub('\\.\\d+$', '', re.sub('blocks\\.\\d+', 'blocks', name)) + categories[cat].add(short) + log('Quantized weights:') + for cat in sorted(categories): + log(f" {cat}: {', '.join(sorted(categories[cat]))}") + return (result, meta) + +def dequantize_mixed(result, meta, template_sd): + out = {} + for name, orig in template_sd.items(): + info = meta.get(name) + if info is None: + continue + orig_dtype = orig.dtype + if 'passthrough' in info: + t = result[name] + if t.dtype == torch.float16 and orig_dtype in (torch.float32, torch.bfloat16): + t = t.to(orig_dtype) + out[name] = t + continue + q, s = (result[name + '.q'], result[name + '.scale']) + if s.ndim > 0: + out[name] = (q.float() * s.float().view(q.shape[0], *[1] * (q.ndim - 1))).to(orig_dtype) + else: + out[name] = (q.float() * float(s.item())).to(orig_dtype) + return out +_BSHF_MAGIC = b'BSHF' + +def _byte_shuffle(data, stride=2): + if stride <= 1 or len(data) < stride: + return data + src = np.frombuffer(data, dtype=np.uint8) + n = len(src) + out = np.empty(n, dtype=np.uint8) + dest_off = 0 + for pos in range(stride): + chunk = src[pos::stride] + out[dest_off:dest_off + len(chunk)] = chunk + dest_off += len(chunk) + return _BSHF_MAGIC + bytes([stride]) + out.tobytes() + +def _byte_unshuffle(data): + if len(data) < 5 or data[:4] != _BSHF_MAGIC: + return data + stride = data[4] + if stride < 2: + return data[5:] + payload = np.frombuffer(data, dtype=np.uint8, offset=5) + n = len(payload) + out = np.empty(n, dtype=np.uint8) + src_off = 0 + for pos in range(stride): + chunk_len = n // stride + (1 if pos < n % stride else 0) + out[pos::stride][:chunk_len] = payload[src_off:src_off + chunk_len] + src_off += chunk_len + return out.tobytes() + +def _compress(data, compressor): + data = _byte_shuffle(data) + if compressor == 'lzma': + return lzma.compress(data, preset=6) + elif compressor == 'brotli': + import brotli + return brotli.compress(data, quality=11) + raise ValueError(f'Unknown compressor: {compressor!r}') + +def _decompress(data, compressor): + if compressor == 'lzma': + raw = lzma.decompress(data) + elif compressor == 'brotli': + import brotli + raw = brotli.decompress(data) + else: + raise ValueError(f'Unknown compressor: {compressor!r}') + raw = _byte_unshuffle(raw) + return raw + +_ANS_MAGIC = b'GAH2' +_ANS_NUM_SYMBOLS = 256 +_ANS_OFFSET = 127 + +def _compress_quant_ans(quant_result, quant_meta): + import brotli + from ans_compress import compress_int_chunks + int_chunks, residual = [], {} + for name, tensor in quant_result.items(): + if name.endswith('.q') and isinstance(tensor, torch.Tensor) and tensor.dtype == torch.int8: + int_chunks.append((name, tensor.contiguous().cpu().numpy())) + else: + residual[name] = tensor + int_chunks.sort(key=lambda kv: kv[0]) + ans_blob = compress_int_chunks(int_chunks, num_symbols=_ANS_NUM_SYMBOLS, signed_offset=_ANS_OFFSET) + residual_buf = io.BytesIO() + torch.save({'w': residual, 'm': quant_meta}, residual_buf) + residual_brotli = brotli.compress(residual_buf.getvalue(), quality=11) + out = bytearray(_ANS_MAGIC) + out.extend(struct.pack(' 0: + scored_nll = ngram_state.tilt_nll( + scored_nll=scored_nll, + scored_logits=logits[i, s:wlen].float(), + target_ids=y_batch[i, s:wlen], + global_positions=torch.arange(ws + s + 1, ws + wlen + 1, device=device, dtype=torch.int64), + ) + loss_sum += scored_nll.sum() + token_count += float(wlen - s) + tgt = y_batch[i, s:wlen] + prev = x_batch[i, s:wlen] + tb = val_data.base_bytes_lut[tgt].to(torch.float64) + tb += (val_data.has_leading_space_lut[tgt] & ~val_data.is_boundary_token_lut[prev]).to(torch.float64) + byte_count += tb.sum() + is_last_chunk = ci == num_chunks - 1 + if not is_last_chunk and h.ttt_epochs > 0: + base_model.train() + chunk_seqs = (chunk_end - chunk_start) // seq_len + if chunk_seqs > 0: + cos_lr = h.ttt_lr * 0.5 * (1.0 + math.cos(math.pi * ci / max(num_chunks - 1, 1))) + for pg in optimizer.param_groups: + pg['lr'] = cos_lr + my_seq_s = chunk_seqs * rank // world_size + my_seq_e = chunk_seqs * (rank + 1) // world_size + my_chunk_seqs = my_seq_e - my_seq_s + for _ep in range(h.ttt_epochs): + for bs in range(0, my_chunk_seqs, batch_seqs): + be = min(bs + batch_seqs, my_chunk_seqs) + actual_bs = my_seq_s + bs + start_tok = chunk_start + actual_bs * seq_len + end_tok = chunk_start + (my_seq_s + be) * seq_len + 1 + if end_tok > val_data.val_tokens.numel(): + continue + local = val_data.val_tokens[start_tok:end_tok].to(device=device, dtype=torch.int64) + x = local[:-1].reshape(-1, seq_len) + y = local[1:].reshape(-1, seq_len) + optimizer.zero_grad(set_to_none=True) + with torch.autocast(device_type='cuda', dtype=torch.bfloat16): + loss = base_model(x, y) + loss.backward() + if world_size > 1: + for p in ttt_params: + if p.grad is not None: + dist.all_reduce(p.grad, op=dist.ReduceOp.AVG) + torch.nn.utils.clip_grad_norm_(ttt_params, h.ttt_grad_clip) + optimizer.step() + if rank == 0 and (ci % 10 == 0 or ci == num_chunks - 1): + elapsed = time.perf_counter() - t0 + rl = loss_sum.item() / max(token_count.item(), 1) + rbpb = rl / math.log(2.0) * (token_count.item() / max(byte_count.item(), 1)) + log(f' ttt_chunk [{ci + 1}/{num_chunks}] bpb={rbpb:.6f} time={elapsed:.1f}s') + if dist.is_available() and dist.is_initialized(): + dist.all_reduce(loss_sum, op=dist.ReduceOp.SUM) + dist.all_reduce(token_count, op=dist.ReduceOp.SUM) + dist.all_reduce(byte_count, op=dist.ReduceOp.SUM) + val_loss = (loss_sum / token_count).item() + val_bpb = val_loss / math.log(2.0) * (token_count.item() / byte_count.item()) + if orig_forward_logits is not None: + base_model.forward_logits = orig_forward_logits + for p in base_model.parameters(): + p.requires_grad_(True) + base_model.eval() + log(f'ttt_sliding:done val_loss={val_loss:.6f} val_bpb={val_bpb:.8f} elapsed={time.perf_counter() - t0:.1f}s') + return (val_loss, val_bpb) + +def _find_docs_lora(all_tokens): + bos_positions = (all_tokens == BOS_ID).nonzero(as_tuple=True)[0].numpy() + docs = [] + for i in range(len(bos_positions)): + start = int(bos_positions[i]) + end = int(bos_positions[i + 1]) if i + 1 < len(bos_positions) else all_tokens.numel() + if i + 1 < len(bos_positions): + end += 1 + if end - start >= 2: + docs.append((start, end - start)) + return docs + +def _build_ttt_lora_global_batches(doc_entries, batch_size, ascending=False): + global_doc_entries = sorted(doc_entries, key=lambda x: x[1][1]) + global_batches = [global_doc_entries[i:i + batch_size] for i in range(0, len(global_doc_entries), batch_size)] + indexed = list(enumerate(global_batches)) + if not ascending: + indexed.sort(key=lambda ib: -max(dl for _, (_, dl) in ib[1])) + return indexed + +def _compute_lora_chunk_window(ci, pred_len, num_chunks, chunk_size, eval_seq_len): + chunk_end = pred_len if ci == num_chunks - 1 else (ci + 1) * chunk_size + win_start = max(0, chunk_end - eval_seq_len) + win_len = chunk_end - win_start + chunk_start = ci * chunk_size + chunk_offset = chunk_start - win_start + chunk_len = chunk_end - chunk_start + return win_start, win_len, chunk_offset, chunk_len + +def _accumulate_lora_bpb(ptl, x, y, chunk_offsets, chunk_lens, pos_idx, base_bytes_lut, has_leading_space_lut, is_boundary_token_lut, loss_sum, byte_sum, token_count): + pos = pos_idx[:x.size(1)].unsqueeze(0) + mask = (chunk_lens.unsqueeze(1) > 0) & (pos >= chunk_offsets.unsqueeze(1)) & (pos < (chunk_offsets + chunk_lens).unsqueeze(1)) + mask_f64 = mask.to(torch.float64) + tok_bytes = base_bytes_lut[y].to(torch.float64) + tok_bytes += (has_leading_space_lut[y] & ~is_boundary_token_lut[x]).to(torch.float64) + loss_sum += (ptl.to(torch.float64) * mask_f64).sum() + byte_sum += (tok_bytes * mask_f64).sum() + token_count += chunk_lens.to(torch.float64).sum() + +def eval_val_ttt_lora(h, base_model, device, val_data, forward_ttt_train): + import json as _json + global BOS_ID + if BOS_ID is None: + BOS_ID = 1 + base_model.eval() + for p in base_model.parameters(): + p.requires_grad_(False) + all_tokens = val_data.val_tokens + all_tokens_idx = all_tokens.to(torch.int32) + docs = _find_docs_lora(all_tokens) + doc_entries = list(enumerate(docs)) + if h.val_doc_fraction < 1.0: + sample_n = max(1, int(round(len(docs) * h.val_doc_fraction))) + sampled_indices = sorted(random.Random(h.seed).sample(range(len(docs)), sample_n)) + doc_entries = [(i, docs[i]) for i in sampled_indices] + log(f'ttt_lora:docs:{len(doc_entries)} rank:{h.ttt_lora_rank} lr:{h.ttt_lora_lr} chunk:{h.ttt_lora_chunk_size}') + chunk_size = h.ttt_lora_chunk_size + eval_seq_len = h.ttt_lora_eval_seq_len + batch_size = h.ttt_lora_batch_size + eval_batch_set = None + if h.ttt_lora_eval_batches: + eval_batch_set = set(int(x) for x in h.ttt_lora_eval_batches.split(',') if x.strip()) + use_ascending = eval_batch_set is not None + global_batches_sorted = _build_ttt_lora_global_batches(doc_entries, batch_size, ascending=use_ascending) + queue_len = len(global_batches_sorted) + if h.world_size > 1: + all_indices = list(range(queue_len)) + my_indices = [idx for idx in all_indices if idx % h.world_size == h.rank] + else: + my_indices = list(range(queue_len)) + loss_sum = torch.zeros((), device=device, dtype=torch.float64) + byte_sum = torch.zeros((), device=device, dtype=torch.float64) + token_count = torch.zeros((), device=device, dtype=torch.float64) + t_start = time.perf_counter() + local_batch_count = 0 + reusable_lora = BatchedTTTLoRA(batch_size, base_model, h.ttt_lora_rank, k_lora=h.ttt_k_lora, mlp_lora=h.ttt_mlp_lora, o_lora=h.ttt_o_lora).to(device) + + def _build_lora_opt(lora_mod): + if h.ttt_optimizer == 'sgd': + return torch.optim.SGD(lora_mod.parameters(), lr=h.ttt_lora_lr, momentum=h.ttt_lora_beta1, weight_decay=h.ttt_lora_weight_decay) + return torch.optim.AdamW(lora_mod.parameters(), lr=h.ttt_lora_lr, betas=(h.ttt_lora_beta1, h.ttt_lora_beta2), eps=1e-10, weight_decay=h.ttt_lora_weight_decay, fused=True) + + reusable_opt = _build_lora_opt(reusable_lora) + progress_f = None + if h.ttt_lora_output_dir and h.rank == 0: + os.makedirs(h.ttt_lora_output_dir, exist_ok=True) + progress_f = open(os.path.join(h.ttt_lora_output_dir, 'progress.jsonl'), 'w') + try: + for queue_idx in my_indices: + orig_batch_idx, batch_entries = global_batches_sorted[queue_idx] + batch = [doc for _, doc in batch_entries] + bsz = len(batch) + prev_loss = loss_sum.item() + prev_bytes = byte_sum.item() + prev_tokens = token_count.item() + if bsz == reusable_lora.bsz: + reusable_lora.reset() + for s in reusable_opt.state.values(): + for k, v in s.items(): + if isinstance(v, torch.Tensor): + v.zero_() + elif k == 'step': + s[k] = 0 + cur_lora = reusable_lora + cur_opt = reusable_opt + else: + cur_lora = BatchedTTTLoRA(bsz, base_model, h.ttt_lora_rank, k_lora=h.ttt_k_lora, mlp_lora=h.ttt_mlp_lora, o_lora=h.ttt_o_lora).to(device) + cur_opt = _build_lora_opt(cur_lora) + pred_lens = [doc_len - 1 for _, doc_len in batch] + num_chunks = [(pl + chunk_size - 1) // chunk_size for pl in pred_lens] + max_nc = max(num_chunks) + num_chunks_t = torch.tensor(num_chunks, dtype=torch.int64, device=device) + for ci in range(max_nc): + active = [ci < nc for nc in num_chunks] + needs_train = any(ci < nc - 1 for nc in num_chunks) + tok_starts = torch.zeros(bsz, dtype=torch.int64) + tok_wls = torch.zeros(bsz, dtype=torch.int64) + chunk_offsets_cpu = torch.zeros(bsz, dtype=torch.int64) + chunk_lens_cpu = torch.zeros(bsz, dtype=torch.int64) + for b in range(bsz): + if not active[b]: + continue + doc_start, doc_len = batch[b] + win_start, win_len, chunk_offset, chunk_len = _compute_lora_chunk_window(ci, pred_lens[b], num_chunks[b], chunk_size, eval_seq_len) + tok_starts[b] = doc_start + win_start + tok_wls[b] = win_len + chunk_offsets_cpu[b] = chunk_offset + chunk_lens_cpu[b] = chunk_len + _, context_size, chunk_offset, _ = _compute_lora_chunk_window(ci, (ci + 1) * chunk_size, ci + 1, chunk_size, eval_seq_len) + col_idx = torch.arange(context_size + 1) + idx = tok_starts.unsqueeze(1) + col_idx.unsqueeze(0) + idx.clamp_(max=all_tokens.numel() - 1) + gathered_gpu = all_tokens_idx[idx].to(device=device, dtype=torch.int64, non_blocking=True) + valid = (col_idx[:context_size].unsqueeze(0) < tok_wls.unsqueeze(1)).to(device, non_blocking=True) + chunk_offsets = chunk_offsets_cpu.to(device, non_blocking=True) + chunk_lens = chunk_lens_cpu.to(device, non_blocking=True) + x = torch.where(valid, gathered_gpu[:, :context_size], 0) + y = torch.where(valid, gathered_gpu[:, 1:context_size + 1], 0) + ctx_pos = torch.arange(context_size, device=device, dtype=torch.int64) + with torch.autocast(device_type='cuda', dtype=torch.bfloat16): + per_tok_loss = forward_ttt_train(x, y, lora=cur_lora) + with torch.no_grad(): + _accumulate_lora_bpb(per_tok_loss, x, y, chunk_offsets, chunk_lens, ctx_pos, val_data.base_bytes_lut, val_data.has_leading_space_lut, val_data.is_boundary_token_lut, loss_sum, byte_sum, token_count) + if needs_train: + activate_chunk_mask = (num_chunks_t - 1 > ci).float() + for gi in range(h.ttt_lora_grad_steps): + if gi > 0: + with torch.autocast(device_type='cuda', dtype=torch.bfloat16): + per_tok_loss = forward_ttt_train(x, y, lora=cur_lora) + per_doc = per_tok_loss[:, chunk_offset:chunk_offset + chunk_size].mean(dim=-1) + cur_opt.zero_grad(set_to_none=True) + (per_doc * activate_chunk_mask).sum().backward() + cur_opt.step() + else: + del per_tok_loss + local_batch_count += 1 + batch_num = orig_batch_idx + 1 + doc_lens = [dl for _, dl in batch] + should_report = False + if eval_batch_set is not None: + should_report = batch_num in eval_batch_set + else: + should_report = True + if should_report: + cur_tokens = token_count.item() + cur_loss_val = loss_sum.item() + cur_bytes_val = byte_sum.item() + dt = cur_tokens - prev_tokens + if dt > 0: + b_loss = (cur_loss_val - prev_loss) / dt + b_bpb = b_loss / math.log(2.0) * (dt / (cur_bytes_val - prev_bytes)) + else: + b_loss = b_bpb = 0.0 + r_loss = cur_loss_val / max(cur_tokens, 1) + r_bpb = r_loss / math.log(2.0) * (cur_tokens / max(cur_bytes_val, 1)) + elapsed = time.perf_counter() - t_start + log(f'ttt_lora_progress: batch {batch_num}/{queue_len} batch_loss:{b_loss:.4f} batch_bpb:{b_bpb:.4f} running_loss:{r_loss:.4f} running_bpb:{r_bpb:.4f} doc_len:{min(doc_lens)}-{max(doc_lens)}') + if progress_f is not None: + progress_f.write(_json.dumps({'batch': batch_num, 'total_batches': queue_len, 'batch_loss': round(b_loss, 8), 'batch_bpb': round(b_bpb, 8), 'running_loss': round(r_loss, 8), 'running_bpb': round(r_bpb, 8), 'doc_len_min': min(doc_lens), 'doc_len_max': max(doc_lens), 'chunk_size': chunk_size, 'elapsed_s': round(elapsed, 3)}) + '\n') + progress_f.flush() + del cur_lora, cur_opt + finally: + if progress_f is not None: + progress_f.close() + if dist.is_available() and dist.is_initialized(): + dist.all_reduce(loss_sum, op=dist.ReduceOp.SUM) + dist.all_reduce(byte_sum, op=dist.ReduceOp.SUM) + dist.all_reduce(token_count, op=dist.ReduceOp.SUM) + for p in base_model.parameters(): + p.requires_grad_(True) + base_model.train() + val_loss = (loss_sum / token_count).item() + val_bpb = val_loss / math.log(2.0) * (token_count.item() / byte_sum.item()) + return val_loss, val_bpb + +def timed_eval(label, fn, *args, **kwargs): + torch.cuda.synchronize() + t0 = time.perf_counter() + val_loss, val_bpb = fn(*args, **kwargs) + torch.cuda.synchronize() + elapsed_ms = 1000.0 * (time.perf_counter() - t0) + log(f'{label} val_loss:{val_loss:.8f} val_bpb:{val_bpb:.8f} eval_time:{elapsed_ms:.0f}ms') + return (val_loss, val_bpb) + +def train_model(h, device, val_data): + base_model = GPT(h).to(device).bfloat16() + restore_fp32_params(base_model) + if h.varlen_training: + compiled_model = base_model + else: + compiled_model = torch.compile(base_model, dynamic=False, fullgraph=True) + model = compiled_model + log(f'model_params:{sum((p.numel() for p in base_model.parameters()))}') + log(f"parallel_residual:active={int(base_model.parallel_post_lambdas is not None)} start_layer={base_model.parallel_start_layer} start_mode={'physical' if base_model.parallel_start_layer_is_physical else 'virtual'} final_lane={base_model.parallel_final_lane} freeze_lane0={int(base_model.parallel_freeze_lane0)} identity_init={int(base_model.parallel_identity_init)} skip_lane0_only={int(base_model.parallel_skip_lane0_only)} mlp_read_mix={int(base_model.parallel_mlp_read_mix)}") + optimizers = Optimizers(h, base_model) + if h.varlen_training: + train_loader = DocumentPackingLoader(h, device) + log('train_loader:DocumentPackingLoader (VarLen training active)') + else: + train_loader = ShuffledSequenceLoader(h, device) + log('train_loader:ShuffledSequenceLoader (standard)') + max_wallclock_ms = 1000.0 * h.max_wallclock_seconds if h.max_wallclock_seconds > 0 else None + if max_wallclock_ms is not None: + max_wallclock_ms -= h.gptq_reserve_seconds * 1000.0 + log(f'gptq:reserving {h.gptq_reserve_seconds:.0f}s, effective={max_wallclock_ms:.0f}ms') + + def training_frac(step, elapsed_ms): + if max_wallclock_ms is None: + return step / max(h.iterations, 1) + return elapsed_ms / max(max_wallclock_ms, 1e-09) + + def lr_mul(frac): + if h.warmdown_frac <= 0: + return 1.0 + if frac >= 1.0 - h.warmdown_frac: + return max((1.0 - frac) / h.warmdown_frac, h.min_lr) + return 1.0 + + def step_fn(step, lr_scale): + optimizers.zero_grad_all() + train_loss = torch.zeros((), device=device) + for micro_step in range(h.grad_accum_steps): + if h.varlen_training: + x, y, cu_seqlens, max_seqlen = train_loader.next_batch(h.train_batch_tokens, h.grad_accum_steps) + with torch.autocast(device_type='cuda', dtype=torch.bfloat16, enabled=True): + loss = model(x, y, cu_seqlens=cu_seqlens, max_seqlen=max_seqlen) + else: + x, y = train_loader.next_batch(h.train_batch_tokens, h.grad_accum_steps) + with torch.autocast(device_type='cuda', dtype=torch.bfloat16, enabled=True): + loss = model(x, y) + train_loss += loss.detach() + (loss / h.grad_accum_steps).backward() + train_loss /= h.grad_accum_steps + frac = min(step / h.muon_momentum_warmup_steps, 1.0) if h.muon_momentum_warmup_steps > 0 else 1.0 + muon_momentum = (1 - frac) * h.muon_momentum_warmup_start + frac * h.muon_momentum + for group in optimizers.optimizer_muon.param_groups: + group['momentum'] = muon_momentum + for opt in optimizers: + for group in opt.param_groups: + group['lr'] = group['base_lr'] * lr_scale + if h.grad_clip_norm > 0: + torch.nn.utils.clip_grad_norm_(base_model.parameters(), h.grad_clip_norm) + optimizers.step(distributed=h.distributed) + return train_loss + if h.warmup_steps > 0: + initial_model_state = {name: tensor.detach().cpu().clone() for name, tensor in base_model.state_dict().items()} + initial_optimizer_states = [copy.deepcopy(opt.state_dict()) for opt in optimizers] + model.train() + for warmup_step in range(h.warmup_steps): + step_fn(warmup_step, 1.0) + if warmup_step <= 5 or (warmup_step + 1) % 10 == 0 or warmup_step + 1 == h.warmup_steps: + log(f'warmup_step: {warmup_step + 1}/{h.warmup_steps}') + if h.num_loops > 0: + base_model.looping_active = True + log(f'loop_warmup:enabled encoder:{base_model.encoder_indices} decoder:{base_model.decoder_indices}') + for warmup_step in range(h.warmup_steps): + step_fn(warmup_step, 1.0) + if warmup_step <= 5 or (warmup_step + 1) % 10 == 0 or warmup_step + 1 == h.warmup_steps: + log(f'loop_warmup_step: {warmup_step + 1}/{h.warmup_steps}') + base_model.looping_active = False + base_model.load_state_dict(initial_model_state, strict=True) + for opt, state in zip(optimizers, initial_optimizer_states, strict=True): + opt.load_state_dict(state) + optimizers.zero_grad_all() + if h.varlen_training: + train_loader = DocumentPackingLoader(h, device) + else: + train_loader = ShuffledSequenceLoader(h, device) + ema_state = {name: t.detach().float().clone() for name, t in base_model.state_dict().items()} + ema_decay = h.ema_decay + training_time_ms = 0.0 + stop_after_step = None + torch.cuda.synchronize() + t0 = time.perf_counter() + step = 0 + while True: + last_step = step == h.iterations or (stop_after_step is not None and step >= stop_after_step) + should_validate = last_step or (h.val_loss_every > 0 and step % h.val_loss_every == 0) + if should_validate: + torch.cuda.synchronize() + training_time_ms += 1000.0 * (time.perf_counter() - t0) + val_loss, val_bpb = eval_val(h, device, val_data, model) + log(f'{step}/{h.iterations} val_loss: {val_loss:.4f} val_bpb: {val_bpb:.4f}') + torch.cuda.synchronize() + t0 = time.perf_counter() + if last_step: + if stop_after_step is not None and step < h.iterations: + log(f'stopping_early: wallclock_cap train_time: {training_time_ms:.0f}ms step: {step}/{h.iterations}') + break + elapsed_ms = training_time_ms + 1000.0 * (time.perf_counter() - t0) + frac = training_frac(step, elapsed_ms) + scale = lr_mul(frac) + if h.num_loops > 0 and (not base_model.looping_active) and (frac >= h.enable_looping_at): + base_model.looping_active = True + log(f'layer_loop:enabled step:{step} frac:{frac:.3f} encoder:{base_model.encoder_indices} decoder:{base_model.decoder_indices}') + train_loss = step_fn(step, scale) + with torch.no_grad(): + for name, t in base_model.state_dict().items(): + ema_state[name].mul_(ema_decay).add_(t.detach().float(), alpha=1.0 - ema_decay) + step += 1 + approx_training_time_ms = training_time_ms + 1000.0 * (time.perf_counter() - t0) + should_log_train = h.train_log_every > 0 and (step <= 5 or step % h.train_log_every == 0 or stop_after_step is not None) + if should_log_train: + tok_per_sec = step * h.train_batch_tokens / (approx_training_time_ms / 1000.0) + log(f'{step}/{h.iterations} train_loss: {train_loss.item():.4f} train_time: {approx_training_time_ms / 60000:.1f}m tok/s: {tok_per_sec:.0f}') + reached_cap = max_wallclock_ms is not None and approx_training_time_ms >= max_wallclock_ms + if h.distributed and max_wallclock_ms is not None: + reached_cap_tensor = torch.tensor(int(reached_cap), device=device) + dist.all_reduce(reached_cap_tensor, op=dist.ReduceOp.MAX) + reached_cap = bool(reached_cap_tensor.item()) + if stop_after_step is None and reached_cap: + stop_after_step = step + log(f'peak memory allocated: {torch.cuda.max_memory_allocated() // 1024 // 1024} MiB reserved: {torch.cuda.max_memory_reserved() // 1024 // 1024} MiB') + log('ema:applying EMA weights') + current_state = base_model.state_dict() + avg_state = {name: t.to(dtype=current_state[name].dtype) for name, t in ema_state.items()} + base_model.load_state_dict(avg_state, strict=True) + log_parallel_residual_converged(log, base_model) + return (base_model, compiled_model) + +def train_and_eval(h, device): + random.seed(h.seed) + np.random.seed(h.seed) + torch.manual_seed(h.seed) + torch.cuda.manual_seed_all(h.seed) + val_data = ValidationData(h, device) + log(f"train_shards: {len(list(Path(h.datasets_dir).resolve().glob('fineweb_train_*.bin')))}") + log(f'val_tokens: {val_data.val_tokens.numel() - 1}') + base_model, compiled_model = train_model(h, device, val_data) + torch._dynamo.reset() + timed_eval('pre-quantization post-ema', eval_val, h, device, val_data, compiled_model) + serialize(h, base_model, Path(__file__).read_text(encoding='utf-8')) + if h.distributed: + dist.barrier() + eval_model = deserialize(h, device) + if h.num_loops > 0: + eval_model.looping_active = True + compiled_model = torch.compile(eval_model, dynamic=False, fullgraph=True) + timed_eval('quantized', eval_val, h, device, val_data, compiled_model) + if h.sliding_window_enabled: + timed_eval('quantized_sliding_window', eval_val_sliding, h, device, val_data, eval_model) + if h.lora_ttt_enabled: + del base_model, eval_model, compiled_model + torch._dynamo.reset() + torch.cuda.empty_cache() + ttt_model = deserialize(h, device) + if h.num_loops > 0: + ttt_model.looping_active = True + for p in ttt_model.parameters(): + p.requires_grad_(False) + for block in ttt_model.blocks: + block.attn.rotary._cos_cached = None + block.attn.rotary._sin_cached = None + block.attn.rotary._seq_len_cached = 0 + block.attn.rotary(h.ttt_lora_eval_seq_len, device, torch.bfloat16) + + def _fwd_ttt(input_ids, target_ids, lora): + return ttt_model.forward_ttt(input_ids, target_ids, lora=lora) + + _ttt_debug_bypass = bool(os.environ.get('TTT_DEBUG_BYPASS')) + if _ttt_debug_bypass: + def _fwd_ttt_bypass(input_ids, target_ids, lora): + logits = ttt_model.forward_logits(input_ids) + dummy = lora.q_loras[0].B.sum() * 0 + logits = logits + dummy + bsz, sl, V = logits.shape + return F.cross_entropy(logits.float().reshape(-1, V), target_ids.reshape(-1), reduction='none').reshape(bsz, sl) + fwd_ttt_compiled = _fwd_ttt_bypass + log('ttt_lora:DEBUG BYPASS active') + else: + fwd_ttt_compiled = _fwd_ttt + log('ttt_lora:eager mode (no compile)') + global BOS_ID + if BOS_ID is None: + BOS_ID = 1 + val_tokens_idx = val_data.val_tokens.to(torch.int32) + t_warmup = time.perf_counter() + for bsz in [h.ttt_lora_batch_size]: + wl = BatchedTTTLoRA(bsz, ttt_model, h.ttt_lora_rank, k_lora=h.ttt_k_lora, mlp_lora=h.ttt_mlp_lora, o_lora=h.ttt_o_lora).to(device) + wo = torch.optim.AdamW(wl.parameters(), lr=h.ttt_lora_lr, betas=(h.ttt_lora_beta1, h.ttt_lora_beta2), eps=1e-10, weight_decay=h.ttt_lora_weight_decay, fused=True) + for ctx_len in (h.ttt_lora_chunk_size, h.ttt_lora_eval_seq_len): + col_w = torch.arange(ctx_len + 1) + idx_w = col_w.clamp_(max=val_data.val_tokens.numel() - 1) + row_w = val_tokens_idx[idx_w].to(device=device, dtype=torch.int64) + xw = row_w[:ctx_len].unsqueeze(0).expand(bsz, -1).contiguous() + yw = row_w[1:ctx_len + 1].unsqueeze(0).expand(bsz, -1).contiguous() + with torch.autocast(device_type='cuda', dtype=torch.bfloat16): + ptl = fwd_ttt_compiled(xw, yw, lora=wl) + ptl[:, :min(h.ttt_lora_chunk_size, ctx_len)].mean(dim=-1).sum().backward() + wo.step() + wo.zero_grad(set_to_none=True) + del wl, wo + del val_tokens_idx + torch.cuda.empty_cache() + log(f'ttt_lora:compile warmup done ({time.perf_counter() - t_warmup:.1f}s)') + torch.cuda.synchronize() + t_ttt = time.perf_counter() + ttt_val_loss, ttt_val_bpb = eval_val_ttt_lora(h, ttt_model, device, val_data, forward_ttt_train=fwd_ttt_compiled) + torch.cuda.synchronize() + log(f'quantized_ttt_lora val_loss:{ttt_val_loss:.8f} val_bpb:{ttt_val_bpb:.8f} eval_time:{1e3 * (time.perf_counter() - t_ttt):.0f}ms') + del ttt_model + elif h.ttt_enabled: + del eval_model, compiled_model + torch._dynamo.reset() + torch.cuda.empty_cache() + ttt_model = deserialize(h, device) + if h.num_loops > 0: + ttt_model.looping_active = True + ngram_state = None + if h.ngram_tilt_enabled: + if h.distributed: + dist.barrier() + log(f'ngram_tilt:construct base_beta={h.ngram_base_beta} within_beta={h.ngram_within_beta} ' + f'word_beta={h.ngram_word_beta} table_bits={h.ngram_open_table_bits}') + from ngram_tilt import NgramTiltState + ngram_state = NgramTiltState( + val_tokens=val_data.val_tokens, + has_leading_space_lut=val_data.has_leading_space_lut, + is_boundary_token_lut=val_data.is_boundary_token_lut, + rank=h.rank, world_size=h.world_size, device=device, + base_beta=h.ngram_base_beta, agree_bonus=h.ngram_agree_bonus, + within_threshold=h.ngram_within_threshold, within_beta=h.ngram_within_beta, + word_threshold=h.ngram_word_threshold, word_beta=h.ngram_word_beta, + open_table_bits=h.ngram_open_table_bits, + token_threshold_scale=h.ngram_token_threshold_scale, + order_stride=h.ngram_order_stride, log=log, + ) + if h.distributed: + dist.barrier() + timed_eval('legal_ttt_exact', eval_val_sliding_ttt, h, ttt_model, h.rank, h.world_size, + device, val_data, stride=h.eval_stride, ngram_state=ngram_state) + del ttt_model + +def main(): + world_size = int(os.environ.get('WORLD_SIZE', '1')) + local_rank = int(os.environ.get('LOCAL_RANK', '0')) + distributed = 'RANK' in os.environ and 'WORLD_SIZE' in os.environ + if not torch.cuda.is_available(): + raise RuntimeError('CUDA is required') + if world_size <= 0: + raise ValueError(f'WORLD_SIZE must be positive, got {world_size}') + if 8 % world_size != 0: + raise ValueError(f'WORLD_SIZE={world_size} must divide 8 so grad_accum_steps stays integral') + device = torch.device('cuda', local_rank) + torch.cuda.set_device(device) + if distributed: + dist.init_process_group(backend='nccl', device_id=device) + dist.barrier() + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + torch.set_float32_matmul_precision('high') + from torch.backends.cuda import enable_cudnn_sdp, enable_flash_sdp, enable_math_sdp, enable_mem_efficient_sdp + enable_cudnn_sdp(False) + enable_flash_sdp(True) + enable_mem_efficient_sdp(False) + enable_math_sdp(False) + torch._dynamo.config.optimize_ddp = False + h = Hyperparameters() + set_logging_hparams(h) + if h.is_main_process: + os.makedirs('logs', exist_ok=True) + log(100 * '=', console=False) + log('Hyperparameters:', console=True) + for k, v in sorted(vars(type(h)).items()): + if not k.startswith('_'): + log(f' {k}: {v}', console=True) + log('=' * 100, console=False) + log(f'Running Python {sys.version}', console=False) + log(f'Running PyTorch {torch.__version__}', console=False) + log(subprocess.run(['nvidia-smi'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=False).stdout, console=False) + log('=' * 100, console=False) + train_and_eval(h, device) + if distributed: + dist.destroy_process_group() +if __name__ == '__main__': + main() diff --git a/records/track_10min_16mb/2026-04-12_SP8192_ImprovedParResid_Muon097_TTT5ep_NgramTilt_HessianSDClip/train_seed314.log b/records/track_10min_16mb/2026-04-12_SP8192_ImprovedParResid_Muon097_TTT5ep_NgramTilt_HessianSDClip/train_seed314.log new file mode 100644 index 0000000000..0f4da055d4 --- /dev/null +++ b/records/track_10min_16mb/2026-04-12_SP8192_ImprovedParResid_Muon097_TTT5ep_NgramTilt_HessianSDClip/train_seed314.log @@ -0,0 +1,322 @@ +W0411 23:39:16.852000 90276 torch/distributed/run.py:803] +W0411 23:39:16.852000 90276 torch/distributed/run.py:803] ***************************************** +W0411 23:39:16.852000 90276 torch/distributed/run.py:803] Setting OMP_NUM_THREADS environment variable for each process to be 1 in default, to avoid your system being overloaded, please further tune the variable for optimal performance in your application as needed. +W0411 23:39:16.852000 90276 torch/distributed/run.py:803] ***************************************** +Hyperparameters: + adam_eps: 1e-08 + adam_wd: 0.02 + beta1: 0.9 + beta2: 0.95 + compressor: brotli + data_dir: ./data/ + datasets_dir: ./data/datasets/fineweb10B_sp8192 + distributed: True + ema_decay: 0.997 + embed_bits: 8 + embed_clip_sigmas: 20.0 + embed_lr: 0.6 + embed_wd: 0.095 + embedding_dim: 512 + enable_looping_at: 0.35 + eval_seq_len: 2048 + eval_stride: 64 + gptq_calibration_batches: 64 + gptq_reserve_seconds: 12.0 + grad_accum_steps: 1 + grad_clip_norm: 0.3 + hash_embed_enabled: False + hash_embed_size: 16384 + head_lr: 0.008 + hessian_clip_lambda: 0.175 + is_main_process: True + iterations: 20000 + ln_scale: True + local_rank: 0 + logfile: logs/d9d74cc8-e20b-4a69-b0f3-d123d5b92299.txt + logit_softcap: 30.0 + loop_end: 5 + loop_start: 3 + lora_ttt_enabled: False + matrix_bits: 6 + matrix_clip_sigmas: 12.85 + matrix_lr: 0.03 + max_wallclock_seconds: 600.0 + min_lr: 0.0 + mlp_mult: 4.0 + model_dim: 512 + model_path: final_model.pt + muon_backend_steps: 5 + muon_beta2: 0.95 + muon_momentum: 0.97 + muon_momentum_warmup_start: 0.92 + muon_momentum_warmup_steps: 1500 + muon_row_normalize: True + muon_wd: 0.095 + ngram_agree_bonus: 0.1 + ngram_base_beta: 2.0 + ngram_open_table_bits: 26 + ngram_order_stride: 2 + ngram_tilt_enabled: True + ngram_token_threshold_scale: 1.0 + ngram_within_beta: 0.0 + ngram_within_threshold: 0.25 + ngram_word_beta: 0.0 + ngram_word_threshold: 0.8 + num_heads: 8 + num_kv_heads: 4 + num_layers: 11 + num_loops: 3 + parallel_final_lane: mean + parallel_freeze_lane0: False + parallel_identity_init: True + parallel_mlp_read_mix: False + parallel_residual: True + parallel_residual_start: 7 + parallel_skip_lane0_only: True + parallel_start_layer: 7 + parallel_start_layer_is_physical: True + qk_gain_init: 5.0 + quantized_model_path: final_model.int6.ptz + rank: 0 + rope_base: 10000.0 + rope_dims: 16 + rope_train_seq_len: 2048 + run_id: d9d74cc8-e20b-4a69-b0f3-d123d5b92299 + scalar_lr: 0.02 + seed: 314 + skip_gates_enabled: True + sliding_window_enabled: True + tie_embeddings: True + tied_embed_init_std: 0.005 + tied_embed_lr: 0.03 + tokenizer_path: ./data/tokenizers/fineweb_8192_bpe.model + train_batch_tokens: 786432 + train_files: ./data/datasets/fineweb10B_sp8192/fineweb_train_*.bin + train_log_every: 500 + train_seq_len: 2048 + ttt_adamw_wd: 0.0 + ttt_batch_seqs: 32 + ttt_chunk_tokens: 32768 + ttt_enabled: True + ttt_epochs: 5 + ttt_freeze_blocks: 0 + ttt_grad_clip: 1.0 + ttt_k_lora: True + ttt_lora_batch_size: 64 + ttt_lora_beta1: 0.0 + ttt_lora_beta2: 0.999 + ttt_lora_chunk_size: 64 + ttt_lora_eval_batches: + ttt_lora_eval_seq_len: 2048 + ttt_lora_grad_steps: 1 + ttt_lora_lr: 0.001 + ttt_lora_output_dir: + ttt_lora_rank: 96 + ttt_lora_weight_decay: 0.5 + ttt_lr: 0.005 + ttt_mlp_lora: True + ttt_momentum: 0.9 + ttt_o_lora: True + ttt_optimizer: sgd + val_batch_tokens: 524288 + val_doc_fraction: 1.0 + val_files: ./data/datasets/fineweb10B_sp8192/fineweb_val_*.bin + val_loss_every: 4000 + varlen_training: False + vocab_size: 8192 + warmdown_frac: 0.667 + warmup_steps: 20 + world_size: 8 + xsa_last_n: 11 +train_shards: 80 +val_tokens: 40540160 +model_params:35946650 +parallel_residual:active=1 start_layer=7 start_mode=physical final_lane=mean freeze_lane0=0 identity_init=1 skip_lane0_only=1 mlp_read_mix=0 +train_loader:ShuffledSequenceLoader (standard) +gptq:reserving 12s, effective=588000ms +warmup_step: 1/20 +warmup_step: 2/20 +warmup_step: 3/20 +warmup_step: 4/20 +warmup_step: 5/20 +warmup_step: 6/20 +warmup_step: 10/20 +warmup_step: 20/20 +loop_warmup:enabled encoder:[0, 1, 2, 3, 4, 5, 3, 4, 5, 3] decoder:[4, 5, 3, 4, 5, 6, 7, 8, 9, 10] +loop_warmup_step: 1/20 +loop_warmup_step: 2/20 +loop_warmup_step: 3/20 +loop_warmup_step: 4/20 +loop_warmup_step: 5/20 +loop_warmup_step: 6/20 +loop_warmup_step: 10/20 +loop_warmup_step: 20/20 +0/20000 val_loss: 9.0092 val_bpb: 3.4877 +1/20000 train_loss: 9.0113 train_time: 0.0m tok/s: 17206375 +2/20000 train_loss: 12.4241 train_time: 0.0m tok/s: 12897086 +3/20000 train_loss: 11.0288 train_time: 0.0m tok/s: 10663760 +4/20000 train_loss: 9.4708 train_time: 0.0m tok/s: 9756959 +5/20000 train_loss: 8.2281 train_time: 0.0m tok/s: 9251553 +500/20000 train_loss: 3.3745 train_time: 0.8m tok/s: 7745292 +1000/20000 train_loss: 3.2931 train_time: 1.7m tok/s: 7734476 +1500/20000 train_loss: 3.1999 train_time: 2.5m tok/s: 7738934 +2000/20000 train_loss: 3.1188 train_time: 3.4m tok/s: 7743098 +layer_loop:enabled step:2026 frac:0.350 encoder:[0, 1, 2, 3, 4, 5, 3, 4, 5, 3] decoder:[4, 5, 3, 4, 5, 6, 7, 8, 9, 10] +2500/20000 train_loss: 3.1507 train_time: 4.8m tok/s: 6827137 +3000/20000 train_loss: 2.9167 train_time: 6.2m tok/s: 6297139 +3500/20000 train_loss: 2.9347 train_time: 7.7m tok/s: 5967947 +4000/20000 train_loss: 2.7835 train_time: 9.1m tok/s: 5742722 +4000/20000 val_loss: 2.8399 val_bpb: 1.0994 +4233/20000 val_loss: 2.8058 val_bpb: 1.0862 +stopping_early: wallclock_cap train_time: 588201ms step: 4233/20000 +peak memory allocated: 46659 MiB reserved: 46748 MiB +ema:applying EMA weights +parallel_residual:converged active=1 start_layer=7 start_mode=physical final_lane=mean freeze_lane0=0 identity_init=1 skip_lane0_only=1 mlp_read_mix=0 used_layers=4 +parallel_residual layer:16 physical:7 attn_resid:2.7029 attn_to_attn:-0.2027 attn_to_mlp:0.4972 mlp_resid:0.5158 mlp_to_attn:-0.1746 mlp_to_mlp:0.6211 +parallel_residual layer:17 physical:8 attn_resid:2.2493 attn_to_attn:1.4245 attn_to_mlp:0.4277 mlp_resid:0.5300 mlp_to_attn:0.3604 mlp_to_mlp:0.5045 +parallel_residual layer:18 physical:9 attn_resid:1.0939 attn_to_attn:-0.1884 attn_to_mlp:0.4213 mlp_resid:0.5324 mlp_to_attn:1.7324 mlp_to_mlp:0.4499 +parallel_residual layer:19 physical:10 attn_resid:-0.0202 attn_to_attn:0.2306 attn_to_mlp:0.2306 mlp_resid:0.5323 mlp_to_attn:0.6737 mlp_to_mlp:0.6737 +pre-quantization post-ema val_loss:2.80916557 val_bpb:1.08751553 eval_time:7037ms +Serialized model: 135417328 bytes +Code size: 122618 bytes +GPTQ:collecting Hessians from calibration data... +GPTQ:collected 67 Hessians in 14.8s +Quantized weights: + gptq (int6): blocks.attn.c_k.weight, blocks.attn.c_q.weight, blocks.attn.c_v.weight, blocks.attn.proj.weight, blocks.mlp.fc.weight, blocks.mlp.proj.weight + gptq (int8): tok_emb.weight + passthrough (float16): blocks.attn.q_gain, blocks.attn_scale, blocks.mlp_scale, blocks.resid_mix, parallel_post_lambdas, parallel_resid_lambdas, skip_gates, skip_weights +Serialized model quantized+brotli: 15961688 bytes +Total submission size quantized+brotli: 16084306 bytes +quantized val_loss:2.83319456 val_bpb:1.09681790 eval_time:9943ms +quantized_sliding_window val_loss:2.78933188 val_bpb:1.07983729 eval_time:106206ms +ngram_tilt:construct base_beta=2.0 within_beta=0.0 word_beta=0.0 table_bits=26 +ngram_tilt:precompute n_tok=40540161 hints=9560451 (23.58%) elapsed=27.8s base_beta=2.0 within_beta=0.0 agree_bonus=0.1 +ttt_sliding:start chunks=1238 chunk_tokens=32768 total_windows=633409 stride=64 ttt_lr=0.005 ttt_epochs=5 freeze_blocks=0 optimizer=sgd hash_embed=False +ttt_sliding:params unfrozen=35946650 frozen=0 + ttt_chunk [1/1238] bpb=1.116574 time=5.6s + ttt_chunk [11/1238] bpb=1.069042 time=12.3s + ttt_chunk [21/1238] bpb=1.106872 time=16.7s + ttt_chunk [31/1238] bpb=1.100427 time=21.2s + ttt_chunk [41/1238] bpb=1.093418 time=25.6s + ttt_chunk [51/1238] bpb=1.086370 time=30.1s + ttt_chunk [61/1238] bpb=1.078109 time=34.6s + ttt_chunk [71/1238] bpb=1.085199 time=39.0s + ttt_chunk [81/1238] bpb=1.078418 time=43.4s + ttt_chunk [91/1238] bpb=1.074933 time=47.9s + ttt_chunk [101/1238] bpb=1.074587 time=52.3s + ttt_chunk [111/1238] bpb=1.072834 time=56.7s + ttt_chunk [121/1238] bpb=1.075857 time=61.2s + ttt_chunk [131/1238] bpb=1.079568 time=65.6s + ttt_chunk [141/1238] bpb=1.080313 time=70.1s + ttt_chunk [151/1238] bpb=1.080017 time=74.5s + ttt_chunk [161/1238] bpb=1.080548 time=78.9s + ttt_chunk [171/1238] bpb=1.080492 time=83.4s + ttt_chunk [181/1238] bpb=1.079015 time=87.8s + ttt_chunk [191/1238] bpb=1.078766 time=92.3s + ttt_chunk [201/1238] bpb=1.076354 time=96.7s + ttt_chunk [211/1238] bpb=1.080755 time=101.1s + ttt_chunk [221/1238] bpb=1.081098 time=105.6s + ttt_chunk [231/1238] bpb=1.082856 time=110.0s + ttt_chunk [241/1238] bpb=1.080982 time=114.4s + ttt_chunk [251/1238] bpb=1.080933 time=118.8s + ttt_chunk [261/1238] bpb=1.081966 time=123.3s + ttt_chunk [271/1238] bpb=1.082340 time=127.7s + ttt_chunk [281/1238] bpb=1.081630 time=132.6s + ttt_chunk [291/1238] bpb=1.082748 time=137.1s + ttt_chunk [301/1238] bpb=1.082958 time=141.5s + ttt_chunk [311/1238] bpb=1.081849 time=146.4s + ttt_chunk [321/1238] bpb=1.081673 time=150.8s + ttt_chunk [331/1238] bpb=1.081970 time=155.3s + ttt_chunk [341/1238] bpb=1.081119 time=159.7s + ttt_chunk [351/1238] bpb=1.081852 time=164.2s + ttt_chunk [361/1238] bpb=1.080711 time=168.6s + ttt_chunk [371/1238] bpb=1.079145 time=173.1s + ttt_chunk [381/1238] bpb=1.079548 time=177.5s + ttt_chunk [391/1238] bpb=1.079211 time=182.0s + ttt_chunk [401/1238] bpb=1.079224 time=186.5s + ttt_chunk [411/1238] bpb=1.079778 time=190.9s + ttt_chunk [421/1238] bpb=1.079252 time=195.4s + ttt_chunk [431/1238] bpb=1.079430 time=199.9s + ttt_chunk [441/1238] bpb=1.079464 time=204.3s + ttt_chunk [451/1238] bpb=1.080690 time=208.8s + ttt_chunk [461/1238] bpb=1.078920 time=213.3s + ttt_chunk [471/1238] bpb=1.078968 time=217.7s + ttt_chunk [481/1238] bpb=1.079107 time=222.2s + ttt_chunk [491/1238] bpb=1.079591 time=226.7s + ttt_chunk [501/1238] bpb=1.079222 time=231.1s + ttt_chunk [511/1238] bpb=1.078837 time=235.6s + ttt_chunk [521/1238] bpb=1.078356 time=240.1s + ttt_chunk [531/1238] bpb=1.078336 time=244.5s + ttt_chunk [541/1238] bpb=1.078429 time=249.0s + ttt_chunk [551/1238] bpb=1.077986 time=253.4s + ttt_chunk [561/1238] bpb=1.077271 time=257.9s + ttt_chunk [571/1238] bpb=1.076750 time=262.3s + ttt_chunk [581/1238] bpb=1.077115 time=266.8s + ttt_chunk [591/1238] bpb=1.077333 time=271.2s + ttt_chunk [601/1238] bpb=1.077234 time=275.7s + ttt_chunk [611/1238] bpb=1.077810 time=280.2s + ttt_chunk [621/1238] bpb=1.078689 time=284.6s + ttt_chunk [631/1238] bpb=1.078743 time=289.1s + ttt_chunk [641/1238] bpb=1.079202 time=293.6s + ttt_chunk [651/1238] bpb=1.079553 time=298.0s + ttt_chunk [661/1238] bpb=1.078890 time=302.5s + ttt_chunk [671/1238] bpb=1.078658 time=307.0s + ttt_chunk [681/1238] bpb=1.079962 time=311.4s + ttt_chunk [691/1238] bpb=1.080163 time=315.9s + ttt_chunk [701/1238] bpb=1.079979 time=320.3s + ttt_chunk [711/1238] bpb=1.080653 time=324.8s + ttt_chunk [721/1238] bpb=1.080985 time=329.2s + ttt_chunk [731/1238] bpb=1.080333 time=333.7s + ttt_chunk [741/1238] bpb=1.080020 time=338.2s + ttt_chunk [751/1238] bpb=1.079111 time=342.7s + ttt_chunk [761/1238] bpb=1.078516 time=347.1s + ttt_chunk [771/1238] bpb=1.077513 time=351.6s + ttt_chunk [781/1238] bpb=1.077506 time=356.0s + ttt_chunk [791/1238] bpb=1.077861 time=360.5s + ttt_chunk [801/1238] bpb=1.078137 time=364.9s + ttt_chunk [811/1238] bpb=1.077649 time=369.4s + ttt_chunk [821/1238] bpb=1.076442 time=373.9s + ttt_chunk [831/1238] bpb=1.076105 time=378.3s + ttt_chunk [841/1238] bpb=1.075629 time=382.8s + ttt_chunk [851/1238] bpb=1.075336 time=387.2s + ttt_chunk [861/1238] bpb=1.074979 time=391.6s + ttt_chunk [871/1238] bpb=1.074867 time=396.1s + ttt_chunk [881/1238] bpb=1.074393 time=400.5s + ttt_chunk [891/1238] bpb=1.073866 time=405.1s + ttt_chunk [901/1238] bpb=1.074214 time=409.5s + ttt_chunk [911/1238] bpb=1.073905 time=414.0s + ttt_chunk [921/1238] bpb=1.074183 time=418.4s + ttt_chunk [931/1238] bpb=1.074834 time=422.9s + ttt_chunk [941/1238] bpb=1.075205 time=427.4s + ttt_chunk [951/1238] bpb=1.075119 time=431.9s + ttt_chunk [961/1238] bpb=1.075935 time=436.3s + ttt_chunk [971/1238] bpb=1.076335 time=440.8s + ttt_chunk [981/1238] bpb=1.076690 time=445.6s + ttt_chunk [991/1238] bpb=1.076479 time=450.1s + ttt_chunk [1001/1238] bpb=1.076514 time=454.6s + ttt_chunk [1011/1238] bpb=1.076850 time=459.4s + ttt_chunk [1021/1238] bpb=1.077557 time=463.8s + ttt_chunk [1031/1238] bpb=1.078028 time=468.3s + ttt_chunk [1041/1238] bpb=1.078491 time=472.7s + ttt_chunk [1051/1238] bpb=1.078415 time=477.2s + ttt_chunk [1061/1238] bpb=1.078401 time=481.6s + ttt_chunk [1071/1238] bpb=1.078556 time=486.1s + ttt_chunk [1081/1238] bpb=1.078431 time=490.5s + ttt_chunk [1091/1238] bpb=1.078626 time=494.9s + ttt_chunk [1101/1238] bpb=1.079163 time=499.4s + ttt_chunk [1111/1238] bpb=1.079464 time=503.9s + ttt_chunk [1121/1238] bpb=1.079627 time=508.3s + ttt_chunk [1131/1238] bpb=1.079276 time=512.7s + ttt_chunk [1141/1238] bpb=1.078946 time=517.2s + ttt_chunk [1151/1238] bpb=1.078983 time=521.6s + ttt_chunk [1161/1238] bpb=1.079100 time=526.1s + ttt_chunk [1171/1238] bpb=1.078867 time=530.5s + ttt_chunk [1181/1238] bpb=1.078392 time=535.0s + ttt_chunk [1191/1238] bpb=1.078538 time=539.5s + ttt_chunk [1201/1238] bpb=1.078656 time=543.9s + ttt_chunk [1211/1238] bpb=1.078321 time=548.3s + ttt_chunk [1221/1238] bpb=1.077853 time=552.8s + ttt_chunk [1231/1238] bpb=1.077490 time=557.2s + ttt_chunk [1238/1238] bpb=1.077483 time=562.1s +ttt_sliding:done val_loss=2.783255 val_bpb=1.07748457 elapsed=562.1s +legal_ttt_exact val_loss:2.78325454 val_bpb:1.07748457 eval_time:562324ms diff --git a/records/track_10min_16mb/2026-04-12_SP8192_ImprovedParResid_Muon097_TTT5ep_NgramTilt_HessianSDClip/train_seed42.log b/records/track_10min_16mb/2026-04-12_SP8192_ImprovedParResid_Muon097_TTT5ep_NgramTilt_HessianSDClip/train_seed42.log new file mode 100644 index 0000000000..7f7518ed53 --- /dev/null +++ b/records/track_10min_16mb/2026-04-12_SP8192_ImprovedParResid_Muon097_TTT5ep_NgramTilt_HessianSDClip/train_seed42.log @@ -0,0 +1,322 @@ +W0411 23:10:05.367000 3416 torch/distributed/run.py:803] +W0411 23:10:05.367000 3416 torch/distributed/run.py:803] ***************************************** +W0411 23:10:05.367000 3416 torch/distributed/run.py:803] Setting OMP_NUM_THREADS environment variable for each process to be 1 in default, to avoid your system being overloaded, please further tune the variable for optimal performance in your application as needed. +W0411 23:10:05.367000 3416 torch/distributed/run.py:803] ***************************************** +Hyperparameters: + adam_eps: 1e-08 + adam_wd: 0.02 + beta1: 0.9 + beta2: 0.95 + compressor: brotli + data_dir: ./data/ + datasets_dir: ./data/datasets/fineweb10B_sp8192 + distributed: True + ema_decay: 0.997 + embed_bits: 8 + embed_clip_sigmas: 20.0 + embed_lr: 0.6 + embed_wd: 0.095 + embedding_dim: 512 + enable_looping_at: 0.35 + eval_seq_len: 2048 + eval_stride: 64 + gptq_calibration_batches: 64 + gptq_reserve_seconds: 12.0 + grad_accum_steps: 1 + grad_clip_norm: 0.3 + hash_embed_enabled: False + hash_embed_size: 16384 + head_lr: 0.008 + hessian_clip_lambda: 0.175 + is_main_process: True + iterations: 20000 + ln_scale: True + local_rank: 0 + logfile: logs/29e66d9d-9e6d-414b-af41-f8cc2d98677a.txt + logit_softcap: 30.0 + loop_end: 5 + loop_start: 3 + lora_ttt_enabled: False + matrix_bits: 6 + matrix_clip_sigmas: 12.85 + matrix_lr: 0.03 + max_wallclock_seconds: 600.0 + min_lr: 0.0 + mlp_mult: 4.0 + model_dim: 512 + model_path: final_model.pt + muon_backend_steps: 5 + muon_beta2: 0.95 + muon_momentum: 0.97 + muon_momentum_warmup_start: 0.92 + muon_momentum_warmup_steps: 1500 + muon_row_normalize: True + muon_wd: 0.095 + ngram_agree_bonus: 0.1 + ngram_base_beta: 2.0 + ngram_open_table_bits: 26 + ngram_order_stride: 2 + ngram_tilt_enabled: True + ngram_token_threshold_scale: 1.0 + ngram_within_beta: 0.0 + ngram_within_threshold: 0.25 + ngram_word_beta: 0.0 + ngram_word_threshold: 0.8 + num_heads: 8 + num_kv_heads: 4 + num_layers: 11 + num_loops: 3 + parallel_final_lane: mean + parallel_freeze_lane0: False + parallel_identity_init: True + parallel_mlp_read_mix: False + parallel_residual: True + parallel_residual_start: 7 + parallel_skip_lane0_only: True + parallel_start_layer: 7 + parallel_start_layer_is_physical: True + qk_gain_init: 5.0 + quantized_model_path: final_model.int6.ptz + rank: 0 + rope_base: 10000.0 + rope_dims: 16 + rope_train_seq_len: 2048 + run_id: 29e66d9d-9e6d-414b-af41-f8cc2d98677a + scalar_lr: 0.02 + seed: 42 + skip_gates_enabled: True + sliding_window_enabled: True + tie_embeddings: True + tied_embed_init_std: 0.005 + tied_embed_lr: 0.03 + tokenizer_path: ./data/tokenizers/fineweb_8192_bpe.model + train_batch_tokens: 786432 + train_files: ./data/datasets/fineweb10B_sp8192/fineweb_train_*.bin + train_log_every: 500 + train_seq_len: 2048 + ttt_adamw_wd: 0.0 + ttt_batch_seqs: 32 + ttt_chunk_tokens: 32768 + ttt_enabled: True + ttt_epochs: 5 + ttt_freeze_blocks: 0 + ttt_grad_clip: 1.0 + ttt_k_lora: True + ttt_lora_batch_size: 64 + ttt_lora_beta1: 0.0 + ttt_lora_beta2: 0.999 + ttt_lora_chunk_size: 64 + ttt_lora_eval_batches: + ttt_lora_eval_seq_len: 2048 + ttt_lora_grad_steps: 1 + ttt_lora_lr: 0.001 + ttt_lora_output_dir: + ttt_lora_rank: 96 + ttt_lora_weight_decay: 0.5 + ttt_lr: 0.005 + ttt_mlp_lora: True + ttt_momentum: 0.9 + ttt_o_lora: True + ttt_optimizer: sgd + val_batch_tokens: 524288 + val_doc_fraction: 1.0 + val_files: ./data/datasets/fineweb10B_sp8192/fineweb_val_*.bin + val_loss_every: 4000 + varlen_training: False + vocab_size: 8192 + warmdown_frac: 0.667 + warmup_steps: 20 + world_size: 8 + xsa_last_n: 11 +train_shards: 80 +val_tokens: 40540160 +model_params:35946650 +parallel_residual:active=1 start_layer=7 start_mode=physical final_lane=mean freeze_lane0=0 identity_init=1 skip_lane0_only=1 mlp_read_mix=0 +train_loader:ShuffledSequenceLoader (standard) +gptq:reserving 12s, effective=588000ms +warmup_step: 1/20 +warmup_step: 2/20 +warmup_step: 3/20 +warmup_step: 4/20 +warmup_step: 5/20 +warmup_step: 6/20 +warmup_step: 10/20 +warmup_step: 20/20 +loop_warmup:enabled encoder:[0, 1, 2, 3, 4, 5, 3, 4, 5, 3] decoder:[4, 5, 3, 4, 5, 6, 7, 8, 9, 10] +loop_warmup_step: 1/20 +loop_warmup_step: 2/20 +loop_warmup_step: 3/20 +loop_warmup_step: 4/20 +loop_warmup_step: 5/20 +loop_warmup_step: 6/20 +loop_warmup_step: 10/20 +loop_warmup_step: 20/20 +0/20000 val_loss: 9.0078 val_bpb: 3.4872 +1/20000 train_loss: 9.0109 train_time: 0.0m tok/s: 17006830 +2/20000 train_loss: 12.4418 train_time: 0.0m tok/s: 12726197 +3/20000 train_loss: 11.0467 train_time: 0.0m tok/s: 10642083 +4/20000 train_loss: 9.4361 train_time: 0.0m tok/s: 9772901 +5/20000 train_loss: 8.2187 train_time: 0.0m tok/s: 9313484 +500/20000 train_loss: 3.3819 train_time: 0.8m tok/s: 7772028 +1000/20000 train_loss: 3.2920 train_time: 1.7m tok/s: 7746547 +1500/20000 train_loss: 3.1984 train_time: 2.5m tok/s: 7745495 +2000/20000 train_loss: 3.1149 train_time: 3.4m tok/s: 7748563 +layer_loop:enabled step:2028 frac:0.350 encoder:[0, 1, 2, 3, 4, 5, 3, 4, 5, 3] decoder:[4, 5, 3, 4, 5, 6, 7, 8, 9, 10] +2500/20000 train_loss: 3.1502 train_time: 4.8m tok/s: 6834732 +3000/20000 train_loss: 2.9115 train_time: 6.2m tok/s: 6305144 +3500/20000 train_loss: 2.9341 train_time: 7.7m tok/s: 5973748 +4000/20000 train_loss: 2.7831 train_time: 9.1m tok/s: 5747962 +4000/20000 val_loss: 2.8383 val_bpb: 1.0988 +4236/20000 val_loss: 2.8035 val_bpb: 1.0853 +stopping_early: wallclock_cap train_time: 588069ms step: 4236/20000 +peak memory allocated: 46666 MiB reserved: 46704 MiB +ema:applying EMA weights +parallel_residual:converged active=1 start_layer=7 start_mode=physical final_lane=mean freeze_lane0=0 identity_init=1 skip_lane0_only=1 mlp_read_mix=0 used_layers=4 +parallel_residual layer:16 physical:7 attn_resid:2.7322 attn_to_attn:1.2994 attn_to_mlp:0.4689 mlp_resid:0.4959 mlp_to_attn:-0.2032 mlp_to_mlp:0.6743 +parallel_residual layer:17 physical:8 attn_resid:1.7172 attn_to_attn:-0.1355 attn_to_mlp:0.4416 mlp_resid:0.4931 mlp_to_attn:0.0180 mlp_to_mlp:0.5477 +parallel_residual layer:18 physical:9 attn_resid:1.2159 attn_to_attn:1.1393 attn_to_mlp:0.3261 mlp_resid:0.5166 mlp_to_attn:0.5664 mlp_to_mlp:0.5157 +parallel_residual layer:19 physical:10 attn_resid:-0.0100 attn_to_attn:0.2948 attn_to_mlp:0.2948 mlp_resid:0.4978 mlp_to_attn:0.6582 mlp_to_mlp:0.6582 +pre-quantization post-ema val_loss:2.80687123 val_bpb:1.08662732 eval_time:7074ms +Serialized model: 135417328 bytes +Code size: 122618 bytes +GPTQ:collecting Hessians from calibration data... +GPTQ:collected 67 Hessians in 14.7s +Quantized weights: + gptq (int6): blocks.attn.c_k.weight, blocks.attn.c_q.weight, blocks.attn.c_v.weight, blocks.attn.proj.weight, blocks.mlp.fc.weight, blocks.mlp.proj.weight + gptq (int8): tok_emb.weight + passthrough (float16): blocks.attn.q_gain, blocks.attn_scale, blocks.mlp_scale, blocks.resid_mix, parallel_post_lambdas, parallel_resid_lambdas, skip_gates, skip_weights +Serialized model quantized+brotli: 15965495 bytes +Total submission size quantized+brotli: 16088113 bytes +quantized val_loss:2.83429203 val_bpb:1.09724277 eval_time:33043ms +quantized_sliding_window val_loss:2.79036667 val_bpb:1.08023789 eval_time:141540ms +ngram_tilt:construct base_beta=2.0 within_beta=0.0 word_beta=0.0 table_bits=26 +ngram_tilt:precompute n_tok=40540161 hints=9560451 (23.58%) elapsed=28.5s base_beta=2.0 within_beta=0.0 agree_bonus=0.1 +ttt_sliding:start chunks=1238 chunk_tokens=32768 total_windows=633409 stride=64 ttt_lr=0.005 ttt_epochs=5 freeze_blocks=0 optimizer=sgd hash_embed=False +ttt_sliding:params unfrozen=35946650 frozen=0 + ttt_chunk [1/1238] bpb=1.108835 time=42.4s + ttt_chunk [11/1238] bpb=1.069574 time=49.1s + ttt_chunk [21/1238] bpb=1.105955 time=53.5s + ttt_chunk [31/1238] bpb=1.099836 time=57.9s + ttt_chunk [41/1238] bpb=1.093373 time=62.3s + ttt_chunk [51/1238] bpb=1.086414 time=66.7s + ttt_chunk [61/1238] bpb=1.077951 time=71.1s + ttt_chunk [71/1238] bpb=1.084893 time=75.5s + ttt_chunk [81/1238] bpb=1.078231 time=79.8s + ttt_chunk [91/1238] bpb=1.074561 time=84.2s + ttt_chunk [101/1238] bpb=1.074331 time=88.6s + ttt_chunk [111/1238] bpb=1.072461 time=92.9s + ttt_chunk [121/1238] bpb=1.075364 time=97.3s + ttt_chunk [131/1238] bpb=1.079073 time=101.7s + ttt_chunk [141/1238] bpb=1.079661 time=106.1s + ttt_chunk [151/1238] bpb=1.079459 time=110.5s + ttt_chunk [161/1238] bpb=1.080043 time=114.9s + ttt_chunk [171/1238] bpb=1.079978 time=119.2s + ttt_chunk [181/1238] bpb=1.078499 time=123.6s + ttt_chunk [191/1238] bpb=1.078317 time=127.9s + ttt_chunk [201/1238] bpb=1.075939 time=132.3s + ttt_chunk [211/1238] bpb=1.080323 time=136.7s + ttt_chunk [221/1238] bpb=1.080619 time=141.1s + ttt_chunk [231/1238] bpb=1.082296 time=145.5s + ttt_chunk [241/1238] bpb=1.080449 time=149.9s + ttt_chunk [251/1238] bpb=1.080395 time=154.2s + ttt_chunk [261/1238] bpb=1.081467 time=158.6s + ttt_chunk [271/1238] bpb=1.081848 time=163.0s + ttt_chunk [281/1238] bpb=1.081168 time=167.4s + ttt_chunk [291/1238] bpb=1.082333 time=171.8s + ttt_chunk [301/1238] bpb=1.082548 time=176.2s + ttt_chunk [311/1238] bpb=1.081456 time=180.6s + ttt_chunk [321/1238] bpb=1.081244 time=184.9s + ttt_chunk [331/1238] bpb=1.081523 time=189.3s + ttt_chunk [341/1238] bpb=1.080690 time=193.7s + ttt_chunk [351/1238] bpb=1.081432 time=198.0s + ttt_chunk [361/1238] bpb=1.080341 time=202.4s + ttt_chunk [371/1238] bpb=1.078732 time=206.8s + ttt_chunk [381/1238] bpb=1.079112 time=211.1s + ttt_chunk [391/1238] bpb=1.078765 time=215.5s + ttt_chunk [401/1238] bpb=1.078787 time=219.9s + ttt_chunk [411/1238] bpb=1.079293 time=224.2s + ttt_chunk [421/1238] bpb=1.078763 time=228.6s + ttt_chunk [431/1238] bpb=1.078932 time=233.0s + ttt_chunk [441/1238] bpb=1.078949 time=237.4s + ttt_chunk [451/1238] bpb=1.080091 time=241.8s + ttt_chunk [461/1238] bpb=1.078336 time=246.2s + ttt_chunk [471/1238] bpb=1.078291 time=250.6s + ttt_chunk [481/1238] bpb=1.078459 time=255.0s + ttt_chunk [491/1238] bpb=1.078886 time=259.5s + ttt_chunk [501/1238] bpb=1.078538 time=265.1s + ttt_chunk [511/1238] bpb=1.078172 time=270.7s + ttt_chunk [521/1238] bpb=1.077686 time=275.1s + ttt_chunk [531/1238] bpb=1.077636 time=279.5s + ttt_chunk [541/1238] bpb=1.077721 time=284.0s + ttt_chunk [551/1238] bpb=1.077241 time=288.3s + ttt_chunk [561/1238] bpb=1.076491 time=292.7s + ttt_chunk [571/1238] bpb=1.075978 time=297.1s + ttt_chunk [581/1238] bpb=1.076313 time=301.5s + ttt_chunk [591/1238] bpb=1.076546 time=305.9s + ttt_chunk [601/1238] bpb=1.076435 time=310.2s + ttt_chunk [611/1238] bpb=1.077018 time=314.6s + ttt_chunk [621/1238] bpb=1.077886 time=320.2s + ttt_chunk [631/1238] bpb=1.077959 time=324.5s + ttt_chunk [641/1238] bpb=1.078409 time=331.4s + ttt_chunk [651/1238] bpb=1.078756 time=335.8s + ttt_chunk [661/1238] bpb=1.078097 time=340.2s + ttt_chunk [671/1238] bpb=1.077847 time=344.6s + ttt_chunk [681/1238] bpb=1.079141 time=349.0s + ttt_chunk [691/1238] bpb=1.079342 time=353.5s + ttt_chunk [701/1238] bpb=1.079171 time=357.9s + ttt_chunk [711/1238] bpb=1.079869 time=362.3s + ttt_chunk [721/1238] bpb=1.080187 time=366.7s + ttt_chunk [731/1238] bpb=1.079518 time=371.1s + ttt_chunk [741/1238] bpb=1.079222 time=375.6s + ttt_chunk [751/1238] bpb=1.078311 time=380.0s + ttt_chunk [761/1238] bpb=1.077713 time=384.5s + ttt_chunk [771/1238] bpb=1.076713 time=388.9s + ttt_chunk [781/1238] bpb=1.076695 time=393.3s + ttt_chunk [791/1238] bpb=1.077029 time=397.7s + ttt_chunk [801/1238] bpb=1.077321 time=402.2s + ttt_chunk [811/1238] bpb=1.076831 time=406.6s + ttt_chunk [821/1238] bpb=1.075624 time=411.1s + ttt_chunk [831/1238] bpb=1.075283 time=415.5s + ttt_chunk [841/1238] bpb=1.074782 time=419.9s + ttt_chunk [851/1238] bpb=1.074494 time=424.4s + ttt_chunk [861/1238] bpb=1.074127 time=428.8s + ttt_chunk [871/1238] bpb=1.074001 time=433.2s + ttt_chunk [881/1238] bpb=1.073538 time=437.7s + ttt_chunk [891/1238] bpb=1.072990 time=442.1s + ttt_chunk [901/1238] bpb=1.073354 time=446.5s + ttt_chunk [911/1238] bpb=1.073020 time=451.0s + ttt_chunk [921/1238] bpb=1.073302 time=455.4s + ttt_chunk [931/1238] bpb=1.073985 time=459.9s + ttt_chunk [941/1238] bpb=1.074369 time=464.3s + ttt_chunk [951/1238] bpb=1.074310 time=468.7s + ttt_chunk [961/1238] bpb=1.075143 time=473.1s + ttt_chunk [971/1238] bpb=1.075529 time=477.5s + ttt_chunk [981/1238] bpb=1.075907 time=481.9s + ttt_chunk [991/1238] bpb=1.075691 time=487.5s + ttt_chunk [1001/1238] bpb=1.075709 time=491.9s + ttt_chunk [1011/1238] bpb=1.076043 time=496.3s + ttt_chunk [1021/1238] bpb=1.076737 time=500.8s + ttt_chunk [1031/1238] bpb=1.077194 time=505.2s + ttt_chunk [1041/1238] bpb=1.077668 time=509.6s + ttt_chunk [1051/1238] bpb=1.077604 time=514.0s + ttt_chunk [1061/1238] bpb=1.077595 time=518.5s + ttt_chunk [1071/1238] bpb=1.077739 time=522.9s + ttt_chunk [1081/1238] bpb=1.077607 time=527.3s + ttt_chunk [1091/1238] bpb=1.077794 time=531.7s + ttt_chunk [1101/1238] bpb=1.078349 time=536.1s + ttt_chunk [1111/1238] bpb=1.078627 time=540.5s + ttt_chunk [1121/1238] bpb=1.078785 time=545.0s + ttt_chunk [1131/1238] bpb=1.078443 time=549.4s + ttt_chunk [1141/1238] bpb=1.078114 time=553.8s + ttt_chunk [1151/1238] bpb=1.078135 time=558.2s + ttt_chunk [1161/1238] bpb=1.078257 time=562.6s + ttt_chunk [1171/1238] bpb=1.078030 time=567.1s + ttt_chunk [1181/1238] bpb=1.077565 time=571.5s + ttt_chunk [1191/1238] bpb=1.077713 time=575.9s + ttt_chunk [1201/1238] bpb=1.077856 time=580.3s + ttt_chunk [1211/1238] bpb=1.077514 time=584.7s + ttt_chunk [1221/1238] bpb=1.077049 time=589.1s + ttt_chunk [1231/1238] bpb=1.076689 time=593.6s + ttt_chunk [1238/1238] bpb=1.076695 time=616.7s +ttt_sliding:done val_loss=2.781595 val_bpb=1.07684192 elapsed=616.7s +legal_ttt_exact val_loss:2.78159452 val_bpb:1.07684192 eval_time:616850ms diff --git a/records/track_10min_16mb/2026-04-12_SP8192_ImprovedParResid_Muon097_TTT5ep_NgramTilt_HessianSDClip/train_seed999.log b/records/track_10min_16mb/2026-04-12_SP8192_ImprovedParResid_Muon097_TTT5ep_NgramTilt_HessianSDClip/train_seed999.log new file mode 100644 index 0000000000..ff551b48b9 --- /dev/null +++ b/records/track_10min_16mb/2026-04-12_SP8192_ImprovedParResid_Muon097_TTT5ep_NgramTilt_HessianSDClip/train_seed999.log @@ -0,0 +1,322 @@ +W0412 00:03:53.450000 94548 torch/distributed/run.py:803] +W0412 00:03:53.450000 94548 torch/distributed/run.py:803] ***************************************** +W0412 00:03:53.450000 94548 torch/distributed/run.py:803] Setting OMP_NUM_THREADS environment variable for each process to be 1 in default, to avoid your system being overloaded, please further tune the variable for optimal performance in your application as needed. +W0412 00:03:53.450000 94548 torch/distributed/run.py:803] ***************************************** +Hyperparameters: + adam_eps: 1e-08 + adam_wd: 0.02 + beta1: 0.9 + beta2: 0.95 + compressor: brotli + data_dir: ./data/ + datasets_dir: ./data/datasets/fineweb10B_sp8192 + distributed: True + ema_decay: 0.997 + embed_bits: 8 + embed_clip_sigmas: 20.0 + embed_lr: 0.6 + embed_wd: 0.095 + embedding_dim: 512 + enable_looping_at: 0.35 + eval_seq_len: 2048 + eval_stride: 64 + gptq_calibration_batches: 64 + gptq_reserve_seconds: 12.0 + grad_accum_steps: 1 + grad_clip_norm: 0.3 + hash_embed_enabled: False + hash_embed_size: 16384 + head_lr: 0.008 + hessian_clip_lambda: 0.175 + is_main_process: True + iterations: 20000 + ln_scale: True + local_rank: 0 + logfile: logs/9a12d03b-4c56-4d50-8e28-f095b3d2fd82.txt + logit_softcap: 30.0 + loop_end: 5 + loop_start: 3 + lora_ttt_enabled: False + matrix_bits: 6 + matrix_clip_sigmas: 12.85 + matrix_lr: 0.03 + max_wallclock_seconds: 600.0 + min_lr: 0.0 + mlp_mult: 4.0 + model_dim: 512 + model_path: final_model.pt + muon_backend_steps: 5 + muon_beta2: 0.95 + muon_momentum: 0.97 + muon_momentum_warmup_start: 0.92 + muon_momentum_warmup_steps: 1500 + muon_row_normalize: True + muon_wd: 0.095 + ngram_agree_bonus: 0.1 + ngram_base_beta: 2.0 + ngram_open_table_bits: 26 + ngram_order_stride: 2 + ngram_tilt_enabled: True + ngram_token_threshold_scale: 1.0 + ngram_within_beta: 0.0 + ngram_within_threshold: 0.25 + ngram_word_beta: 0.0 + ngram_word_threshold: 0.8 + num_heads: 8 + num_kv_heads: 4 + num_layers: 11 + num_loops: 3 + parallel_final_lane: mean + parallel_freeze_lane0: False + parallel_identity_init: True + parallel_mlp_read_mix: False + parallel_residual: True + parallel_residual_start: 7 + parallel_skip_lane0_only: True + parallel_start_layer: 7 + parallel_start_layer_is_physical: True + qk_gain_init: 5.0 + quantized_model_path: final_model.int6.ptz + rank: 0 + rope_base: 10000.0 + rope_dims: 16 + rope_train_seq_len: 2048 + run_id: 9a12d03b-4c56-4d50-8e28-f095b3d2fd82 + scalar_lr: 0.02 + seed: 999 + skip_gates_enabled: True + sliding_window_enabled: True + tie_embeddings: True + tied_embed_init_std: 0.005 + tied_embed_lr: 0.03 + tokenizer_path: ./data/tokenizers/fineweb_8192_bpe.model + train_batch_tokens: 786432 + train_files: ./data/datasets/fineweb10B_sp8192/fineweb_train_*.bin + train_log_every: 500 + train_seq_len: 2048 + ttt_adamw_wd: 0.0 + ttt_batch_seqs: 32 + ttt_chunk_tokens: 32768 + ttt_enabled: True + ttt_epochs: 5 + ttt_freeze_blocks: 0 + ttt_grad_clip: 1.0 + ttt_k_lora: True + ttt_lora_batch_size: 64 + ttt_lora_beta1: 0.0 + ttt_lora_beta2: 0.999 + ttt_lora_chunk_size: 64 + ttt_lora_eval_batches: + ttt_lora_eval_seq_len: 2048 + ttt_lora_grad_steps: 1 + ttt_lora_lr: 0.001 + ttt_lora_output_dir: + ttt_lora_rank: 96 + ttt_lora_weight_decay: 0.5 + ttt_lr: 0.005 + ttt_mlp_lora: True + ttt_momentum: 0.9 + ttt_o_lora: True + ttt_optimizer: sgd + val_batch_tokens: 524288 + val_doc_fraction: 1.0 + val_files: ./data/datasets/fineweb10B_sp8192/fineweb_val_*.bin + val_loss_every: 4000 + varlen_training: False + vocab_size: 8192 + warmdown_frac: 0.667 + warmup_steps: 20 + world_size: 8 + xsa_last_n: 11 +train_shards: 80 +val_tokens: 40540160 +model_params:35946650 +parallel_residual:active=1 start_layer=7 start_mode=physical final_lane=mean freeze_lane0=0 identity_init=1 skip_lane0_only=1 mlp_read_mix=0 +train_loader:ShuffledSequenceLoader (standard) +gptq:reserving 12s, effective=588000ms +warmup_step: 1/20 +warmup_step: 2/20 +warmup_step: 3/20 +warmup_step: 4/20 +warmup_step: 5/20 +warmup_step: 6/20 +warmup_step: 10/20 +warmup_step: 20/20 +loop_warmup:enabled encoder:[0, 1, 2, 3, 4, 5, 3, 4, 5, 3] decoder:[4, 5, 3, 4, 5, 6, 7, 8, 9, 10] +loop_warmup_step: 1/20 +loop_warmup_step: 2/20 +loop_warmup_step: 3/20 +loop_warmup_step: 4/20 +loop_warmup_step: 5/20 +loop_warmup_step: 6/20 +loop_warmup_step: 10/20 +loop_warmup_step: 20/20 +0/20000 val_loss: 9.0088 val_bpb: 3.4876 +1/20000 train_loss: 9.0104 train_time: 0.0m tok/s: 16192685 +2/20000 train_loss: 12.3738 train_time: 0.0m tok/s: 12608243 +3/20000 train_loss: 10.9830 train_time: 0.0m tok/s: 10533970 +4/20000 train_loss: 9.3627 train_time: 0.0m tok/s: 9731269 +5/20000 train_loss: 8.1461 train_time: 0.0m tok/s: 9257466 +500/20000 train_loss: 3.3873 train_time: 0.8m tok/s: 7738897 +1000/20000 train_loss: 3.2989 train_time: 1.7m tok/s: 7727760 +1500/20000 train_loss: 3.2037 train_time: 2.5m tok/s: 7726958 +2000/20000 train_loss: 3.1200 train_time: 3.4m tok/s: 7729605 +layer_loop:enabled step:2023 frac:0.350 encoder:[0, 1, 2, 3, 4, 5, 3, 4, 5, 3] decoder:[4, 5, 3, 4, 5, 6, 7, 8, 9, 10] +2500/20000 train_loss: 3.1517 train_time: 4.8m tok/s: 6815773 +3000/20000 train_loss: 2.9158 train_time: 6.3m tok/s: 6289117 +3500/20000 train_loss: 2.9326 train_time: 7.7m tok/s: 5962514 +4000/20000 train_loss: 2.7836 train_time: 9.1m tok/s: 5738933 +4000/20000 val_loss: 2.8399 val_bpb: 1.0994 +4231/20000 val_loss: 2.8060 val_bpb: 1.0863 +stopping_early: wallclock_cap train_time: 588120ms step: 4231/20000 +peak memory allocated: 46659 MiB reserved: 46748 MiB +ema:applying EMA weights +parallel_residual:converged active=1 start_layer=7 start_mode=physical final_lane=mean freeze_lane0=0 identity_init=1 skip_lane0_only=1 mlp_read_mix=0 used_layers=4 +parallel_residual layer:16 physical:7 attn_resid:3.3611 attn_to_attn:-0.2883 attn_to_mlp:0.5559 mlp_resid:0.5273 mlp_to_attn:-0.0287 mlp_to_mlp:0.6364 +parallel_residual layer:17 physical:8 attn_resid:1.9514 attn_to_attn:1.8986 attn_to_mlp:0.2975 mlp_resid:0.5644 mlp_to_attn:1.0762 mlp_to_mlp:0.5331 +parallel_residual layer:18 physical:9 attn_resid:1.0925 attn_to_attn:0.1549 attn_to_mlp:0.3589 mlp_resid:0.5305 mlp_to_attn:0.4218 mlp_to_mlp:0.5554 +parallel_residual layer:19 physical:10 attn_resid:-0.0242 attn_to_attn:0.2764 attn_to_mlp:0.2764 mlp_resid:0.5200 mlp_to_attn:0.6985 mlp_to_mlp:0.6985 +pre-quantization post-ema val_loss:2.80955186 val_bpb:1.08766508 eval_time:7121ms +Serialized model: 135417328 bytes +Code size: 122618 bytes +GPTQ:collecting Hessians from calibration data... +GPTQ:collected 67 Hessians in 14.8s +Quantized weights: + gptq (int6): blocks.attn.c_k.weight, blocks.attn.c_q.weight, blocks.attn.c_v.weight, blocks.attn.proj.weight, blocks.mlp.fc.weight, blocks.mlp.proj.weight + gptq (int8): tok_emb.weight + passthrough (float16): blocks.attn.q_gain, blocks.attn_scale, blocks.mlp_scale, blocks.resid_mix, parallel_post_lambdas, parallel_resid_lambdas, skip_gates, skip_weights +Serialized model quantized+brotli: 15961209 bytes +Total submission size quantized+brotli: 16083827 bytes +quantized val_loss:2.83261788 val_bpb:1.09659465 eval_time:10047ms +quantized_sliding_window val_loss:2.78895665 val_bpb:1.07969203 eval_time:106282ms +ngram_tilt:construct base_beta=2.0 within_beta=0.0 word_beta=0.0 table_bits=26 +ngram_tilt:precompute n_tok=40540161 hints=9560451 (23.58%) elapsed=27.6s base_beta=2.0 within_beta=0.0 agree_bonus=0.1 +ttt_sliding:start chunks=1238 chunk_tokens=32768 total_windows=633409 stride=64 ttt_lr=0.005 ttt_epochs=5 freeze_blocks=0 optimizer=sgd hash_embed=False +ttt_sliding:params unfrozen=35946650 frozen=0 + ttt_chunk [1/1238] bpb=1.113770 time=5.7s + ttt_chunk [11/1238] bpb=1.068760 time=12.4s + ttt_chunk [21/1238] bpb=1.105600 time=16.9s + ttt_chunk [31/1238] bpb=1.099369 time=21.5s + ttt_chunk [41/1238] bpb=1.092485 time=26.1s + ttt_chunk [51/1238] bpb=1.086132 time=30.6s + ttt_chunk [61/1238] bpb=1.077755 time=35.2s + ttt_chunk [71/1238] bpb=1.084913 time=39.8s + ttt_chunk [81/1238] bpb=1.078352 time=44.5s + ttt_chunk [91/1238] bpb=1.074738 time=49.0s + ttt_chunk [101/1238] bpb=1.074623 time=53.6s + ttt_chunk [111/1238] bpb=1.072978 time=58.2s + ttt_chunk [121/1238] bpb=1.076071 time=62.8s + ttt_chunk [131/1238] bpb=1.079832 time=67.4s + ttt_chunk [141/1238] bpb=1.080453 time=72.0s + ttt_chunk [151/1238] bpb=1.080156 time=76.6s + ttt_chunk [161/1238] bpb=1.080536 time=81.1s + ttt_chunk [171/1238] bpb=1.080376 time=85.7s + ttt_chunk [181/1238] bpb=1.078908 time=90.3s + ttt_chunk [191/1238] bpb=1.078700 time=94.9s + ttt_chunk [201/1238] bpb=1.076322 time=99.5s + ttt_chunk [211/1238] bpb=1.080786 time=104.1s + ttt_chunk [221/1238] bpb=1.081100 time=108.6s + ttt_chunk [231/1238] bpb=1.082765 time=113.2s + ttt_chunk [241/1238] bpb=1.080947 time=117.8s + ttt_chunk [251/1238] bpb=1.080933 time=122.4s + ttt_chunk [261/1238] bpb=1.081922 time=127.0s + ttt_chunk [271/1238] bpb=1.082304 time=131.6s + ttt_chunk [281/1238] bpb=1.081611 time=136.6s + ttt_chunk [291/1238] bpb=1.082768 time=141.3s + ttt_chunk [301/1238] bpb=1.082989 time=145.9s + ttt_chunk [311/1238] bpb=1.081880 time=150.9s + ttt_chunk [321/1238] bpb=1.081697 time=155.6s + ttt_chunk [331/1238] bpb=1.082016 time=160.2s + ttt_chunk [341/1238] bpb=1.081117 time=164.8s + ttt_chunk [351/1238] bpb=1.081858 time=169.4s + ttt_chunk [361/1238] bpb=1.080724 time=174.0s + ttt_chunk [371/1238] bpb=1.079159 time=178.6s + ttt_chunk [381/1238] bpb=1.079562 time=183.2s + ttt_chunk [391/1238] bpb=1.079222 time=187.8s + ttt_chunk [401/1238] bpb=1.079288 time=192.4s + ttt_chunk [411/1238] bpb=1.079800 time=197.0s + ttt_chunk [421/1238] bpb=1.079254 time=201.6s + ttt_chunk [431/1238] bpb=1.079481 time=206.2s + ttt_chunk [441/1238] bpb=1.079484 time=210.9s + ttt_chunk [451/1238] bpb=1.080676 time=215.5s + ttt_chunk [461/1238] bpb=1.078917 time=220.1s + ttt_chunk [471/1238] bpb=1.078927 time=224.8s + ttt_chunk [481/1238] bpb=1.079065 time=229.4s + ttt_chunk [491/1238] bpb=1.079512 time=234.1s + ttt_chunk [501/1238] bpb=1.079145 time=238.7s + ttt_chunk [511/1238] bpb=1.078758 time=243.3s + ttt_chunk [521/1238] bpb=1.078252 time=247.9s + ttt_chunk [531/1238] bpb=1.078294 time=252.5s + ttt_chunk [541/1238] bpb=1.078371 time=257.2s + ttt_chunk [551/1238] bpb=1.077925 time=261.8s + ttt_chunk [561/1238] bpb=1.077193 time=266.5s + ttt_chunk [571/1238] bpb=1.076666 time=271.0s + ttt_chunk [581/1238] bpb=1.077025 time=275.7s + ttt_chunk [591/1238] bpb=1.077237 time=280.2s + ttt_chunk [601/1238] bpb=1.077117 time=284.9s + ttt_chunk [611/1238] bpb=1.077660 time=289.5s + ttt_chunk [621/1238] bpb=1.078476 time=294.1s + ttt_chunk [631/1238] bpb=1.078554 time=298.7s + ttt_chunk [641/1238] bpb=1.079027 time=303.3s + ttt_chunk [651/1238] bpb=1.079370 time=308.0s + ttt_chunk [661/1238] bpb=1.078730 time=312.6s + ttt_chunk [671/1238] bpb=1.078540 time=317.2s + ttt_chunk [681/1238] bpb=1.079845 time=321.9s + ttt_chunk [691/1238] bpb=1.080037 time=326.5s + ttt_chunk [701/1238] bpb=1.079857 time=331.1s + ttt_chunk [711/1238] bpb=1.080554 time=335.7s + ttt_chunk [721/1238] bpb=1.080848 time=340.3s + ttt_chunk [731/1238] bpb=1.080182 time=345.0s + ttt_chunk [741/1238] bpb=1.079891 time=349.6s + ttt_chunk [751/1238] bpb=1.078977 time=354.3s + ttt_chunk [761/1238] bpb=1.078367 time=358.9s + ttt_chunk [771/1238] bpb=1.077362 time=363.5s + ttt_chunk [781/1238] bpb=1.077333 time=368.1s + ttt_chunk [791/1238] bpb=1.077681 time=372.7s + ttt_chunk [801/1238] bpb=1.077961 time=377.4s + ttt_chunk [811/1238] bpb=1.077463 time=382.0s + ttt_chunk [821/1238] bpb=1.076251 time=386.6s + ttt_chunk [831/1238] bpb=1.075922 time=391.3s + ttt_chunk [841/1238] bpb=1.075442 time=395.9s + ttt_chunk [851/1238] bpb=1.075150 time=400.5s + ttt_chunk [861/1238] bpb=1.074797 time=405.1s + ttt_chunk [871/1238] bpb=1.074704 time=409.8s + ttt_chunk [881/1238] bpb=1.074228 time=414.4s + ttt_chunk [891/1238] bpb=1.073697 time=419.0s + ttt_chunk [901/1238] bpb=1.074084 time=423.7s + ttt_chunk [911/1238] bpb=1.073761 time=428.3s + ttt_chunk [921/1238] bpb=1.074044 time=432.9s + ttt_chunk [931/1238] bpb=1.074731 time=437.5s + ttt_chunk [941/1238] bpb=1.075108 time=442.2s + ttt_chunk [951/1238] bpb=1.075030 time=446.9s + ttt_chunk [961/1238] bpb=1.075854 time=451.5s + ttt_chunk [971/1238] bpb=1.076251 time=456.1s + ttt_chunk [981/1238] bpb=1.076622 time=461.2s + ttt_chunk [991/1238] bpb=1.076423 time=465.8s + ttt_chunk [1001/1238] bpb=1.076450 time=470.5s + ttt_chunk [1011/1238] bpb=1.076792 time=475.5s + ttt_chunk [1021/1238] bpb=1.077491 time=480.2s + ttt_chunk [1031/1238] bpb=1.077950 time=484.8s + ttt_chunk [1041/1238] bpb=1.078398 time=489.5s + ttt_chunk [1051/1238] bpb=1.078317 time=494.2s + ttt_chunk [1061/1238] bpb=1.078318 time=498.8s + ttt_chunk [1071/1238] bpb=1.078477 time=503.5s + ttt_chunk [1081/1238] bpb=1.078346 time=508.1s + ttt_chunk [1091/1238] bpb=1.078530 time=512.8s + ttt_chunk [1101/1238] bpb=1.079074 time=517.4s + ttt_chunk [1111/1238] bpb=1.079360 time=522.1s + ttt_chunk [1121/1238] bpb=1.079545 time=526.7s + ttt_chunk [1131/1238] bpb=1.079199 time=531.4s + ttt_chunk [1141/1238] bpb=1.078868 time=536.1s + ttt_chunk [1151/1238] bpb=1.078901 time=540.7s + ttt_chunk [1161/1238] bpb=1.079012 time=545.4s + ttt_chunk [1171/1238] bpb=1.078783 time=550.1s + ttt_chunk [1181/1238] bpb=1.078317 time=554.8s + ttt_chunk [1191/1238] bpb=1.078449 time=559.5s + ttt_chunk [1201/1238] bpb=1.078558 time=564.2s + ttt_chunk [1211/1238] bpb=1.078234 time=569.0s + ttt_chunk [1221/1238] bpb=1.077766 time=573.7s + ttt_chunk [1231/1238] bpb=1.077407 time=578.4s + ttt_chunk [1238/1238] bpb=1.077412 time=583.6s +ttt_sliding:done val_loss=2.783480 val_bpb=1.07757183 elapsed=583.6s +legal_ttt_exact val_loss:2.78347994 val_bpb:1.07757183 eval_time:583793ms