| """ |
| Transformer + NextLat (Next-Latent Prediction) as a standalone, selectable model. |
| |
| This packages a standard GPT together with the NextLat latent-dynamics auxiliary |
| objective (arXiv:2511.05963) into a single nn.Module, so it can be selected with |
| `--model transformer-nextlat` just like `transformer` / `mamba` / `mamba2`. |
| |
| Unlike the legacy `--NextLat` flag (which keeps a *separate* latent model and a |
| *separate* optimizer alongside a plain GPT), here the latent dynamics model is |
| **encapsulated** inside this module. Consequences: |
| * a single optimizer (configure_optimizers) covers both the GPT and the latent |
| model, and a single checkpoint (`model` state_dict) stores both; |
| * `.forward(idx, targets)` behaves EXACTLY like a plain GPT (returns |
| (logits, loss)), so inference / probing / evaluation are unchanged; |
| * the NextLat auxiliary losses are produced by `.forward_nextlat(idx, targets)`, |
| which is only used during training. |
| |
| The `.transformer` property plus the generate()/crop_block_size() delegations keep |
| it drop-in compatible with the rest of the pipeline (e.g. get_block_list, which |
| reads `model.transformer.h`). |
| """ |
|
|
| import math |
| import inspect |
| from dataclasses import dataclass, fields |
| from typing import Optional |
|
|
| import torch |
| import torch.nn as nn |
| from torch.nn import functional as F |
|
|
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| def new_gelu(x): |
| """GELU activation (identical to OpenAI GPT / Google BERT).""" |
| return 0.5 * x * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi) * (x + 0.044715 * torch.pow(x, 3.0)))) |
|
|
|
|
| class LayerNorm(nn.Module): |
| """ LayerNorm but with an optional bias. PyTorch doesn't support simply bias=False """ |
|
|
| def __init__(self, ndim, bias): |
| super().__init__() |
| self.weight = nn.Parameter(torch.ones(ndim)) |
| self.bias = nn.Parameter(torch.zeros(ndim)) if bias else None |
|
|
| def forward(self, input): |
| return F.layer_norm(input, self.weight.shape, self.weight, self.bias, 1e-5) |
|
|
|
|
| class CausalSelfAttention(nn.Module): |
|
|
| def __init__(self, config): |
| super().__init__() |
| assert config.n_embd % config.n_head == 0 |
| |
| self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd, bias=config.bias) |
| |
| self.c_proj = nn.Linear(config.n_embd, config.n_embd, bias=config.bias) |
| |
| self.attn_dropout = nn.Dropout(config.dropout) |
| self.resid_dropout = nn.Dropout(config.dropout) |
| self.n_head = config.n_head |
| self.n_embd = config.n_embd |
| self.dropout = config.dropout |
| |
| self.flash = config.use_flash and hasattr(torch.nn.functional, 'scaled_dot_product_attention') |
| if not self.flash: |
| if not config.use_flash: |
| print("INFO: Flash attention disabled via --local flag (for local GPU compatibility)") |
| else: |
| print("WARNING: using slow attention. Flash Attention requires PyTorch >= 2.0") |
| |
| self.register_buffer("bias", torch.tril(torch.ones(config.block_size, config.block_size)) |
| .view(1, 1, config.block_size, config.block_size)) |
|
|
| def forward(self, x, kv_cache=None): |
| B, T, C = x.size() |
|
|
| |
| q, k, v = self.c_attn(x).split(self.n_embd, dim=2) |
| nh = self.n_head; hs = C // nh |
| k = k.view(B, T, nh, hs).transpose(1, 2) |
| q = q.view(B, T, nh, hs).transpose(1, 2) |
| v = v.view(B, T, nh, hs).transpose(1, 2) |
|
|
| if kv_cache is None: |
| |
| if self.flash: |
| y = torch.nn.functional.scaled_dot_product_attention( |
| q, k, v, attn_mask=None, |
| dropout_p=self.dropout if self.training else 0, |
| is_causal=True) |
| else: |
| att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1))) |
| att = att.masked_fill(self.bias[:, :, :T, :T] == 0, float('-inf')) |
| att = F.softmax(att, dim=-1) |
| att = self.attn_dropout(att) |
| y = att @ v |
| else: |
| |
| cur_len = kv_cache.get('len', 0) |
| max_L = kv_cache['max_L'] |
| if 'k_buf' not in kv_cache: |
| kv_cache['k_buf'] = torch.empty(B, nh, max_L, hs, dtype=k.dtype, device=k.device) |
| kv_cache['v_buf'] = torch.empty(B, nh, max_L, hs, dtype=v.dtype, device=v.device) |
| new_end = cur_len + T |
| assert new_end <= max_L, f"KV cache overflow: {new_end} > {max_L}" |
| kv_cache['k_buf'][:, :, cur_len:new_end].copy_(k) |
| kv_cache['v_buf'][:, :, cur_len:new_end].copy_(v) |
| kv_cache['len'] = new_end |
|
|
| k_full = kv_cache['k_buf'][:, :, :new_end] |
| v_full = kv_cache['v_buf'][:, :, :new_end] |
|
|
| if T == 1: |
| |
| if self.flash: |
| y = torch.nn.functional.scaled_dot_product_attention( |
| q, k_full, v_full, attn_mask=None, dropout_p=0, is_causal=False) |
| else: |
| att = (q @ k_full.transpose(-2, -1)) * (1.0 / math.sqrt(hs)) |
| att = F.softmax(att, dim=-1) |
| y = att @ v_full |
| else: |
| |
| device = q.device |
| q_abs = torch.arange(cur_len, new_end, device=device).unsqueeze(1) |
| k_abs = torch.arange(0, new_end, device=device).unsqueeze(0) |
| mask = (k_abs <= q_abs).view(1, 1, T, new_end) |
| if self.flash: |
| y = torch.nn.functional.scaled_dot_product_attention( |
| q, k_full, v_full, attn_mask=mask, dropout_p=0, is_causal=False) |
| else: |
| att = (q @ k_full.transpose(-2, -1)) * (1.0 / math.sqrt(hs)) |
| att = att.masked_fill(~mask, float('-inf')) |
| att = F.softmax(att, dim=-1) |
| y = att @ v_full |
|
|
| y = y.transpose(1, 2).contiguous().view(B, T, C) |
|
|
| |
| y = self.resid_dropout(self.c_proj(y)) |
| return y |
|
|
|
|
| class MLP(nn.Module): |
|
|
| def __init__(self, config): |
| super().__init__() |
| self.c_fc = nn.Linear(config.n_embd, 4 * config.n_embd, bias=config.bias) |
| self.c_proj = nn.Linear(4 * config.n_embd, config.n_embd, bias=config.bias) |
| self.dropout = nn.Dropout(config.dropout) |
|
|
| def forward(self, x): |
| x = self.c_fc(x) |
| x = new_gelu(x) |
| x = self.c_proj(x) |
| x = self.dropout(x) |
| return x |
|
|
|
|
| class Block(nn.Module): |
|
|
| def __init__(self, config, layer_idx=0): |
| super().__init__() |
| self.layer_idx = layer_idx |
| self.ln_1 = LayerNorm(config.n_embd, bias=config.bias) |
| self.attn = CausalSelfAttention(config) |
| self.ln_2 = LayerNorm(config.n_embd, bias=config.bias) |
| self.mlp = MLP(config) |
|
|
| def forward(self, x, nls_cache=None, kv_cache=None): |
| x = x + self.attn(self.ln_1(x), kv_cache=kv_cache) |
| x = x + self.mlp(self.ln_2(x)) |
| return x |
|
|
|
|
| @dataclass |
| class GPTConfig: |
| block_size: int = 1024 |
| vocab_size: int = 50304 |
| n_layer: int = 12 |
| n_head: int = 12 |
| n_embd: int = 768 |
| dropout: float = 0.0 |
| bias: bool = True |
| use_flash: bool = True |
|
|
|
|
| class LatentDynamicsModel(nn.Module): |
| """ |
| NextLat latent dynamics model p_ψ (arXiv:2511.05963). |
| A 3-layer MLP that predicts the next hidden state from the current hidden state |
| and the next token embedding, using a residual connection: |
| h_hat_{t+1} = f_ψ(h_t, emb(x_{t+1})) + h_t |
| """ |
|
|
| def __init__(self, n_embd, mlp_hidden_dim=None): |
| super().__init__() |
| if mlp_hidden_dim is None: |
| mlp_hidden_dim = 2 * n_embd |
| self.ln = LayerNorm(2 * n_embd, bias=True) |
| self.fc1 = nn.Linear(2 * n_embd, mlp_hidden_dim) |
| self.fc2 = nn.Linear(mlp_hidden_dim, mlp_hidden_dim) |
| self.fc3 = nn.Linear(mlp_hidden_dim, n_embd) |
|
|
| def forward(self, h_t, tok_emb_next): |
| """ |
| Args: |
| h_t: (B, D) current hidden state |
| tok_emb_next: (B, D) token embedding of the next token |
| Returns: |
| h_hat_next: (B, D) predicted next hidden state |
| """ |
| x = torch.cat([h_t, tok_emb_next], dim=-1) |
| x = self.ln(x) |
| x = F.gelu(self.fc1(x)) |
| x = F.gelu(self.fc2(x)) |
| x = self.fc3(x) |
| return x + h_t |
|
|
|
|
| class GPT(nn.Module): |
|
|
| def __init__(self, config): |
| super().__init__() |
| assert config.vocab_size is not None |
| assert config.block_size is not None |
| self.config = config |
|
|
| block_list = nn.ModuleList([Block(config, layer_idx=i) for i in range(config.n_layer)]) |
|
|
| self.transformer = nn.ModuleDict(dict( |
| wte = nn.Embedding(config.vocab_size, config.n_embd), |
| wpe = nn.Embedding(config.block_size, config.n_embd), |
| drop = nn.Dropout(config.dropout), |
| h = block_list, |
| ln_f = LayerNorm(config.n_embd, bias=config.bias), |
| )) |
| self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False) |
| |
| self.transformer.wte.weight = self.lm_head.weight |
|
|
| |
| self.apply(self._init_weights) |
| |
| for pn, p in self.named_parameters(): |
| if pn.endswith('c_proj.weight'): |
| torch.nn.init.normal_(p, mean=0.0, std=0.02 / math.sqrt(2 * len(self.transformer.h))) |
|
|
| |
| print("number of parameters: %.2fM" % (self.get_num_params() / 1e6,)) |
|
|
| def get_num_params(self, non_embedding=True): |
| """Return the number of parameters in the model (excluding position |
| embeddings by default; token embeddings are tied to lm_head and kept).""" |
| n_params = sum(p.numel() for p in self.parameters()) |
| if non_embedding: |
| n_params -= self.transformer.wpe.weight.numel() |
| return n_params |
|
|
| def _init_weights(self, module): |
| if isinstance(module, nn.Linear): |
| torch.nn.init.normal_(module.weight, mean=0.0, std=0.02) |
| if module.bias is not None: |
| torch.nn.init.zeros_(module.bias) |
| elif isinstance(module, nn.Embedding): |
| torch.nn.init.normal_(module.weight, mean=0.0, std=0.02) |
|
|
| def forward(self, idx, targets=None, nls_caches=None, kv_caches=None): |
| device = idx.device |
| b, t = idx.size() |
|
|
| |
| if kv_caches is not None and len(kv_caches) > 0 and kv_caches[0].get('len', 0) > 0: |
| pos_offset = kv_caches[0]['len'] |
| else: |
| pos_offset = 0 |
|
|
| assert pos_offset + t <= self.config.block_size, ( |
| f"Cannot forward sequence of length {pos_offset + t}, block size is only {self.config.block_size}") |
| pos = torch.arange(pos_offset, pos_offset + t, dtype=torch.long, device=device).unsqueeze(0) |
|
|
| |
| tok_emb = self.transformer.wte(idx) |
| pos_emb = self.transformer.wpe(pos) |
| x = self.transformer.drop(tok_emb + pos_emb) |
| for i, block in enumerate(self.transformer.h): |
| blk_nls_cache = nls_caches[i] if nls_caches is not None else None |
| blk_kv_cache = kv_caches[i] if kv_caches is not None else None |
| x = block(x, nls_cache=blk_nls_cache, kv_cache=blk_kv_cache) |
| x = self.transformer.ln_f(x) |
|
|
| if targets is not None: |
| |
| logits = self.lm_head(x) |
| loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=0) |
| else: |
| |
| logits = self.lm_head(x[:, [-1], :]) |
| loss = None |
|
|
| return logits, loss |
|
|
| def forward_nextlat(self, idx, targets, latent_model, horizon=1, lambda_h=1.0, lambda_kl=1.0): |
| """ |
| NextLat forward pass (arXiv:2511.05963). |
| Computes standard next-token loss plus auxiliary latent dynamics losses. |
| |
| Returns: total_loss, loss_next_token, loss_next_h, loss_kl |
| """ |
| device = idx.device |
| b, t = idx.size() |
| assert t <= self.config.block_size |
| pos = torch.arange(0, t, dtype=torch.long, device=device).unsqueeze(0) |
|
|
| |
| tok_emb = self.transformer.wte(idx) |
| pos_emb = self.transformer.wpe(pos) |
| x = self.transformer.drop(tok_emb + pos_emb) |
| for block in self.transformer.h: |
| x = block(x) |
| hidden_states = self.transformer.ln_f(x) |
|
|
| |
| logits = self.lm_head(hidden_states) |
| loss_next_token = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=0) |
|
|
| |
| target_tok_emb = self.transformer.wte(targets) |
|
|
| |
| max_start = t - horizon |
| if max_start <= 0: |
| |
| horizon = max(1, t - 1) |
| max_start = t - horizon |
|
|
| loss_next_h = torch.tensor(0.0, device=device) |
| loss_kl = torch.tensor(0.0, device=device) |
| count = 0 |
|
|
| |
| hidden_targets = hidden_states.detach() |
|
|
| for d in range(1, horizon + 1): |
| if d == 1: |
| |
| h_current = hidden_states[:, :max_start, :] |
| tok_emb_next = target_tok_emb[:, :max_start, :] |
| B_T = b * max_start |
| h_pred = latent_model( |
| h_current.reshape(B_T, -1), |
| tok_emb_next.reshape(B_T, -1) |
| ).reshape(b, max_start, -1) |
| else: |
| |
| tok_emb_next = target_tok_emb[:, d-1:max_start+d-1, :] |
| B_T = b * max_start |
| h_pred = latent_model( |
| h_pred.reshape(B_T, -1), |
| tok_emb_next.reshape(B_T, -1) |
| ).reshape(b, max_start, -1) |
|
|
| |
| h_target = hidden_targets[:, d:max_start+d, :] |
|
|
| |
| valid_mask = (targets[:, d:max_start+d] != 0) |
| valid_tokens_count = valid_mask.sum() |
|
|
| if valid_tokens_count > 0: |
| |
| h_loss_unreduced = F.smooth_l1_loss(h_pred, h_target, reduction='none') |
| h_loss_unreduced = h_loss_unreduced.mean(dim=-1) |
| loss_next_h = loss_next_h + (h_loss_unreduced * valid_mask).sum() / valid_tokens_count |
|
|
| |
| with torch.no_grad(): |
| logits_target = self.lm_head(h_target) |
| log_probs_target = F.log_softmax(logits_target, dim=-1) |
|
|
| |
| logits_pred = F.linear(h_pred, self.lm_head.weight.detach()) |
| log_probs_pred = F.log_softmax(logits_pred, dim=-1) |
|
|
| |
| kl_unreduced = F.kl_div(log_probs_pred, log_probs_target, reduction='none', log_target=True) |
| kl_unreduced = kl_unreduced.sum(dim=-1) |
| loss_kl = loss_kl + (kl_unreduced * valid_mask).sum() / valid_tokens_count |
|
|
| count += 1 |
|
|
| if count > 0: |
| loss_next_h = loss_next_h / count |
| loss_kl = loss_kl / count |
|
|
| total_loss = loss_next_token + lambda_h * loss_next_h + lambda_kl * loss_kl |
| return total_loss, loss_next_token, loss_next_h, loss_kl |
|
|
| def crop_block_size(self, block_size): |
| |
| assert block_size <= self.config.block_size |
| self.config.block_size = block_size |
| self.transformer.wpe.weight = nn.Parameter(self.transformer.wpe.weight[:block_size]) |
| for block in self.transformer.h: |
| if hasattr(block.attn, 'bias'): |
| block.attn.bias = block.attn.bias[:, :, :block_size, :block_size] |
|
|
| def estimate_mfu(self, fwdbwd_per_iter, dt): |
| """ estimate model flops utilization (MFU) in units of A100 bfloat16 peak FLOPS """ |
| N = self.get_num_params() |
| cfg = self.config |
| L, H, Q, T = cfg.n_layer, cfg.n_head, cfg.n_embd // cfg.n_head, cfg.block_size |
| flops_per_token = 6 * N + 12 * L * H * Q * T |
| flops_per_fwdbwd = flops_per_token * T |
| flops_per_iter = flops_per_fwdbwd * fwdbwd_per_iter |
| flops_achieved = flops_per_iter * (1.0 / dt) |
| flops_promised = 312e12 |
| return flops_achieved / flops_promised |
|
|
| @torch.no_grad() |
| def generate(self, idx, max_new_tokens, temperature=1.0, top_k=None, return_confidence=False): |
| """ |
| Take a conditioning sequence of indices idx (LongTensor of shape (b,t)) and complete |
| the sequence max_new_tokens times, feeding the predictions back into the model each time. |
| """ |
| confidences = [] if return_confidence else None |
| top3_tokens = [] if return_confidence else None |
| top3_probs = [] if return_confidence else None |
| B = idx.size(0) |
|
|
| block_size = self.config.block_size |
| any_nls = any(getattr(b, 'per_block_nls', None) is not None for b in self.transformer.h) |
| any_postgru = any(getattr(b, 'per_block_gru', None) is not None for b in self.transformer.h) |
|
|
| |
| use_incremental = (not self.training) and (not any_postgru) |
|
|
| def _format_conf_outputs(): |
| """Reshape collected per-step (B, ...) lists into the documented format.""" |
| if B == 1: |
| return ([c[0] for c in confidences], |
| [t[0] for t in top3_tokens], |
| [p[0] for p in top3_probs]) |
| T = len(confidences) |
| conf_bs = [[confidences[t][b] for t in range(T)] for b in range(B)] |
| tok_bs = [[top3_tokens[t][b] for t in range(T)] for b in range(B)] |
| prob_bs = [[top3_probs[t][b] for t in range(T)] for b in range(B)] |
| return conf_bs, tok_bs, prob_bs |
|
|
| if use_incremental: |
| kv_caches = [{'max_L': block_size} for _ in self.transformer.h] |
| nls_caches = ([{'max_L': block_size, 'incremental': True} |
| for _ in self.transformer.h] if any_nls else None) |
|
|
| def _reset_caches(): |
| for c in kv_caches: |
| c.pop('k_buf', None) |
| c.pop('v_buf', None) |
| c['len'] = 0 |
| if nls_caches is not None: |
| for c in nls_caches: |
| c['bufs'] = [] |
| c['lens'] = [] |
|
|
| def _sample_from(logits_last): |
| if temperature <= 0: |
| probs = F.softmax(logits_last, dim=-1) |
| idx_next = probs.argmax(dim=-1, keepdim=True) |
| else: |
| logits_last = logits_last / temperature |
| if top_k is not None: |
| v, _ = torch.topk(logits_last, min(top_k, logits_last.size(-1))) |
| logits_last = torch.where(logits_last < v[:, [-1]], |
| torch.full_like(logits_last, -float('Inf')), |
| logits_last) |
| probs = F.softmax(logits_last, dim=-1) |
| idx_next = torch.multinomial(probs, num_samples=1) |
| if return_confidence: |
| sampled_probs = probs.gather(1, idx_next).squeeze(-1) |
| confidences.append(sampled_probs.cpu().tolist()) |
| top3_prob_vals, top3_token_ids = torch.topk(probs, 3, dim=-1) |
| top3_tokens.append(top3_token_ids.cpu().tolist()) |
| top3_probs.append(top3_prob_vals.cpu().tolist()) |
| return idx_next |
|
|
| |
| idx_cond = idx if idx.size(1) <= block_size else idx[:, -block_size:] |
| logits, _ = self(idx_cond, nls_caches=nls_caches, kv_caches=kv_caches) |
| idx_next = _sample_from(logits[:, -1, :]) |
| idx = torch.cat((idx, idx_next), dim=1) |
|
|
| for _ in range(max_new_tokens - 1): |
| cur_len = kv_caches[0]['len'] |
| if cur_len + 1 > block_size: |
| |
| _reset_caches() |
| idx_cond = idx[:, -(block_size - 1):] |
| logits, _ = self(idx_cond, nls_caches=nls_caches, kv_caches=kv_caches) |
| else: |
| |
| logits, _ = self(idx_next, nls_caches=nls_caches, kv_caches=kv_caches) |
| idx_next = _sample_from(logits[:, -1, :]) |
| idx = torch.cat((idx, idx_next), dim=1) |
|
|
| if return_confidence: |
| conf, t3t, t3p = _format_conf_outputs() |
| return idx, conf, t3t, t3p |
| return idx |
|
|
| |
| nls_caches = ([{'max_L': block_size} for _ in self.transformer.h] |
| if any_nls else None) |
| prev_cond_len = 0 |
|
|
| for _ in range(max_new_tokens): |
| idx_cond = idx if idx.size(1) <= block_size else idx[:, -block_size:] |
| if nls_caches is not None and ( |
| idx_cond.size(1) < prev_cond_len |
| or (idx_cond.size(1) == block_size and prev_cond_len == block_size) |
| ): |
| for c in nls_caches: |
| if isinstance(c, dict): |
| c['bufs'] = [] |
| c['lens'] = [] |
| else: |
| c.clear() |
| prev_cond_len = idx_cond.size(1) |
| logits, _ = self(idx_cond, nls_caches=nls_caches) |
| if temperature <= 0: |
| probs = F.softmax(logits[:, -1, :], dim=-1) |
| idx_next = probs.argmax(dim=-1, keepdim=True) |
| else: |
| logits = logits[:, -1, :] / temperature |
| if top_k is not None: |
| v, _ = torch.topk(logits, min(top_k, logits.size(-1))) |
| logits[logits < v[:, [-1]]] = -float('Inf') |
| probs = F.softmax(logits, dim=-1) |
| idx_next = torch.multinomial(probs, num_samples=1) |
|
|
| if return_confidence: |
| sampled_probs = probs.gather(1, idx_next).squeeze(-1) |
| confidences.append(sampled_probs.cpu().tolist()) |
| top3_prob_vals, top3_token_ids = torch.topk(probs, 3, dim=-1) |
| top3_tokens.append(top3_token_ids.cpu().tolist()) |
| top3_probs.append(top3_prob_vals.cpu().tolist()) |
|
|
| idx = torch.cat((idx, idx_next), dim=1) |
|
|
| if return_confidence: |
| conf, t3t, t3p = _format_conf_outputs() |
| return idx, conf, t3t, t3p |
| return idx |
|
|
|
|
| @dataclass |
| class TransformerNextLatConfig: |
| |
| block_size: int = 1024 |
| vocab_size: int = 50304 |
| n_layer: int = 12 |
| n_head: int = 12 |
| n_embd: int = 768 |
| dropout: float = 0.0 |
| bias: bool = True |
| use_flash: bool = True |
| |
| mlp_hidden_dim: Optional[int] = None |
| nextlat_horizon: int = 1 |
| lambda_h: float = 1.0 |
| lambda_kl: float = 1.0 |
| model_type: str = 'transformer-nextlat' |
|
|
| def gpt_config(self) -> GPTConfig: |
| """Build the backbone GPTConfig from the shared fields.""" |
| gpt_keys = {f.name for f in fields(GPTConfig)} |
| return GPTConfig(**{k: getattr(self, k) for k in gpt_keys}) |
|
|
|
|
| class TransformerNextLat(nn.Module): |
| def __init__(self, config: TransformerNextLatConfig): |
| super().__init__() |
| self.config = config |
| self.gpt = GPT(config.gpt_config()) |
| self.latent_model = LatentDynamicsModel(config.n_embd, config.mlp_hidden_dim) |
| self.nextlat_horizon = config.nextlat_horizon |
| self.lambda_h = config.lambda_h |
| self.lambda_kl = config.lambda_kl |
| n_latent = sum(p.numel() for p in self.latent_model.parameters()) |
| print(f"NextLat latent dynamics model parameters: {n_latent / 1e6:.2f}M") |
|
|
| |
| |
| |
| @property |
| def transformer(self): |
| return self.gpt.transformer |
|
|
| def forward(self, idx, targets=None, nls_caches=None, kv_caches=None): |
| """Standard GPT forward (used by eval / test / probes / generation).""" |
| return self.gpt(idx, targets, nls_caches=nls_caches, kv_caches=kv_caches) |
|
|
| def forward_nextlat(self, idx, targets, horizon=None, lambda_h=None, lambda_kl=None): |
| """NextLat training forward: next-token loss + latent-dynamics aux losses. |
| |
| Returns (total_loss, loss_next_token, loss_next_h, loss_kl).""" |
| return self.gpt.forward_nextlat( |
| idx, targets, self.latent_model, |
| horizon=self.nextlat_horizon if horizon is None else horizon, |
| lambda_h=self.lambda_h if lambda_h is None else lambda_h, |
| lambda_kl=self.lambda_kl if lambda_kl is None else lambda_kl, |
| ) |
|
|
| @torch.no_grad() |
| def generate(self, *args, **kwargs): |
| return self.gpt.generate(*args, **kwargs) |
|
|
| def crop_block_size(self, block_size): |
| self.gpt.crop_block_size(block_size) |
| self.config.block_size = block_size |
|
|
| def estimate_mfu(self, fwdbwd_per_iter, dt): |
| return self.gpt.estimate_mfu(fwdbwd_per_iter, dt) |
|
|
| def get_num_params(self, non_embedding=True): |
| return (self.gpt.get_num_params(non_embedding) |
| + sum(p.numel() for p in self.latent_model.parameters())) |
|
|
| def configure_optimizers(self, weight_decay, learning_rate, betas, device_type): |
| """Single optimizer over the GPT backbone AND the latent model. |
| |
| Uses a dim-based decay split (>=2D decayed, <2D not), which correctly |
| handles the tied embedding/lm_head weight (returned once by |
| named_parameters) and the latent MLP's LayerNorm/biases.""" |
| param_dict = {pn: p for pn, p in self.named_parameters() if p.requires_grad} |
| decay_params = [p for p in param_dict.values() if p.dim() >= 2] |
| nodecay_params = [p for p in param_dict.values() if p.dim() < 2] |
| optim_groups = [ |
| {"params": decay_params, "weight_decay": weight_decay}, |
| {"params": nodecay_params, "weight_decay": 0.0}, |
| ] |
| use_fused = (device_type == 'cuda') and ('fused' in inspect.signature(torch.optim.AdamW).parameters) |
| print(f"using fused AdamW: {use_fused}") |
| extra_args = dict(fused=True) if use_fused else dict() |
| return torch.optim.AdamW(optim_groups, lr=learning_rate, betas=betas, **extra_args) |
|
|