WorldModelForMaze / model /transformer_nextlat.py
Kalso42's picture
Upload folder using huggingface_hub
34e468d verified
Raw
History Blame Contribute Delete
30.3 kB
"""
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
# ============================================================================
# GPT backbone, copied from model/transformer.py so this model is fully
# self-contained and does NOT import anything from transformer.py. Only the
# standard Transformer path that NextLat actually exercises is included (no
# PostGRU / NLS / Dyadic variants). The module/attribute layout (self.gpt ->
# transformer.{wte,wpe,drop,h,ln_f} + lm_head, Block.{ln_1,attn,ln_2,mlp}) is
# identical to the plain GPT, so existing transformer-nextlat checkpoints load
# unchanged.
# ============================================================================
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
# key, query, value projections for all heads, but in a batch
self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd, bias=config.bias)
# output projection
self.c_proj = nn.Linear(config.n_embd, config.n_embd, bias=config.bias)
# regularization
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
# flash attention make GPU go brrrrr but support is only in PyTorch >= 2.0
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")
# causal mask to ensure that attention is only applied to the left in the input sequence
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() # batch size, sequence length, embedding dimensionality (n_embd)
# calculate query, key, values for all heads in batch and move head forward to be the batch dim
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) # (B, nh, T, hs)
q = q.view(B, T, nh, hs).transpose(1, 2) # (B, nh, T, hs)
v = v.view(B, T, nh, hs).transpose(1, 2) # (B, nh, T, hs)
if kv_cache is None:
# ---- standard path: full causal self-attention ----
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:
# ---- incremental path: append k,v to preallocated buffer, attend over full prefix ----
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] # (B, nh, new_end, hs)
v_full = kv_cache['v_buf'][:, :, :new_end]
if T == 1:
# Single new query attends to all prior keys; no causal mask needed.
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:
# Multiple new queries (e.g. initial prompt). Build rectangular causal mask.
device = q.device
q_abs = torch.arange(cur_len, new_end, device=device).unsqueeze(1) # (T, 1)
k_abs = torch.arange(0, new_end, device=device).unsqueeze(0) # (1, new_end)
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) # re-assemble all head outputs side by side
# output projection
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 # GPT-2 vocab_size of 50257, padded up to nearest multiple of 64 for efficiency
n_layer: int = 12
n_head: int = 12
n_embd: int = 768
dropout: float = 0.0
bias: bool = True # True: bias in Linears and LayerNorms, like GPT-2. False: a bit better and faster
use_flash: bool = True # Enable flash attention (disable for local GPUs that don't support it)
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) # (B, 2D)
x = self.ln(x)
x = F.gelu(self.fc1(x))
x = F.gelu(self.fc2(x))
x = self.fc3(x)
return x + h_t # residual connection
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)
# weight tying
self.transformer.wte.weight = self.lm_head.weight # https://paperswithcode.com/method/weight-tying
# init all weights
self.apply(self._init_weights)
# apply special scaled init to the residual projections, per GPT-2 paper
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)))
# report number of parameters
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()
# Determine position offset for incremental decoding.
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)
# forward the GPT model itself
tok_emb = self.transformer.wte(idx) # token embeddings of shape (b, t, n_embd)
pos_emb = self.transformer.wpe(pos) # position embeddings of shape (1, t, n_embd)
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:
# if we are given some desired targets also calculate the loss
logits = self.lm_head(x)
loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=0)
else:
# inference-time mini-optimization: only forward the lm_head on the very last position
logits = self.lm_head(x[:, [-1], :]) # note: using list [-1] to preserve the time dim
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)
# Forward the transformer to get hidden states
tok_emb = self.transformer.wte(idx) # (B, T, D)
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) # (B, T, D)
# Standard next-token prediction loss
logits = self.lm_head(hidden_states)
loss_next_token = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=0)
# NextLat auxiliary losses: token embeddings for the teacher-forced next tokens
target_tok_emb = self.transformer.wte(targets) # (B, T, D)
# For each starting position t, unroll latent dynamics for `horizon` steps
max_start = t - horizon
if max_start <= 0:
# Sequence too short for the given horizon; fall back to horizon=1
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
# Detach hidden state targets (stop-gradient)
hidden_targets = hidden_states.detach() # (B, T, D)
for d in range(1, horizon + 1):
if d == 1:
# First step: predict from actual hidden states
h_current = hidden_states[:, :max_start, :] # (B, max_start, D)
tok_emb_next = target_tok_emb[:, :max_start, :] # (B, max_start, D)
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) # (B, max_start, D)
else:
# Multi-step: unroll from previous predicted states
tok_emb_next = target_tok_emb[:, d-1:max_start+d-1, :] # (B, max_start, D)
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)
# SmoothL1 loss: compare predicted h with actual h (stop-gradient on target)
h_target = hidden_targets[:, d:max_start+d, :] # (B, max_start, D)
# Create valid mask to ignore padding tokens (index 0)
valid_mask = (targets[:, d:max_start+d] != 0) # (B, max_start)
valid_tokens_count = valid_mask.sum()
if valid_tokens_count > 0:
# Masked SmoothL1 Loss
h_loss_unreduced = F.smooth_l1_loss(h_pred, h_target, reduction='none') # (B, max_start, D)
h_loss_unreduced = h_loss_unreduced.mean(dim=-1) # (B, max_start)
loss_next_h = loss_next_h + (h_loss_unreduced * valid_mask).sum() / valid_tokens_count
# Masked KL Loss
with torch.no_grad():
logits_target = self.lm_head(h_target) # (B, max_start, V)
log_probs_target = F.log_softmax(logits_target, dim=-1)
# Use detached lm_head weights
logits_pred = F.linear(h_pred, self.lm_head.weight.detach()) # (B, max_start, V)
log_probs_pred = F.log_softmax(logits_pred, dim=-1)
# KL(p_target || p_pred); log_target=True for numerical stability
kl_unreduced = F.kl_div(log_probs_pred, log_probs_target, reduction='none', log_target=True)
kl_unreduced = kl_unreduced.sum(dim=-1) # sum over vocabulary -> (B, max_start)
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):
# model surgery to decrease the block size if necessary
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) # per second
flops_promised = 312e12 # A100 GPU bfloat16 peak flops is 312 TFLOPS
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)
# Fast path: KV-cached incremental decoding (disabled for PostGRU / training).
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) # (B, 1)
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) # (B, 1)
if return_confidence:
sampled_probs = probs.gather(1, idx_next).squeeze(-1) # (B,)
confidences.append(sampled_probs.cpu().tolist())
top3_prob_vals, top3_token_ids = torch.topk(probs, 3, dim=-1) # (B, 3)
top3_tokens.append(top3_token_ids.cpu().tolist())
top3_probs.append(top3_prob_vals.cpu().tolist())
return idx_next
# Initial forward over the full prompt (cropped if needed).
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:
# Caches full; slide the window: reset and re-encode the recent prefix.
_reset_caches()
idx_cond = idx[:, -(block_size - 1):]
logits, _ = self(idx_cond, nls_caches=nls_caches, kv_caches=kv_caches)
else:
# Incremental: feed only the most recently sampled token.
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
# ---- Legacy path: full re-forward each step ----
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:
# --- GPT backbone fields (mirror 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
# --- NextLat fields ---
mlp_hidden_dim: Optional[int] = None # latent MLP hidden dim (default: 2 * n_embd)
nextlat_horizon: int = 1 # latent-dynamics rollout horizon d
lambda_h: float = 1.0 # weight of next-hidden-state regression loss
lambda_kl: float = 1.0 # weight of KL divergence loss
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")
# Expose the backbone's transformer module so helpers that read
# `model.transformer.h` (e.g. get_block_list) work unchanged. Using a
# property (not a registered submodule) avoids double-counting parameters.
@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)