File size: 15,317 Bytes
23c39b5 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 | """Looped transformer with a soft chain-of-thought channel between cycles.
Port of loop-cot's `loop_cot_transformer` into the HRM-Text stack, modified as
follows (everything else — decode, top-k truncation, gates — kept faithful):
- No sandwich: no pre/coda layers, no per-layer injection. A single
full-size stack (n_layers, NOT halved) is looped `cycles` times.
- UT-style state init: z starts from a frozen random vector (zL_init),
not from the token embeddings.
- Cycle input is `z + alpha * decoded(z) + beta * x` (no RMSNorm), where
x is the token embedding stream and decoded(z) re-expresses z as the
expected token embedding under the model's own next-token distribution.
Readout matrix (`cot_decode_readout`) — IMPORTANT: upstream loop-cot runs with
tie_word_embeddings=True, so its decode logits ARE the model's next-token
logits. HRM-Text keeps embed_tokens and lm_head as SEPARATE matrices, so the
faithful port reads out through lm_head ("lm_head", logits = h @ W_out^T) and
writes back through the input embedding (probs @ scale*W_in). The "embed"
setting reproduces the earlier (mis-wired) behavior where the input embedding
served as both readout and write-back; kept only for continuity with the
loop-cot / loop-cot-b1 / loop-cot-a011 runs.
Alpha schedule: each cycle's alpha is either a constant (from
`cot_alpha_fixed_per_cycle[i]`) or a learned sigmoid gate. Cycles whose alpha
is constant 0 skip the decode entirely (no readout matmul). With
`cot_alpha_activate_after_warmup`, alpha is 0 everywhere while the BP warmup
is still ramping, and the learned gates only switch on afterwards (they are
untouched until then, so they activate at exactly `cot_alpha_init`).
`cot_alpha_per_cycle_params` gives every learned cycle its own gate vector.
"""
from typing import Any, Literal, Optional
import math
import torch
from torch import Tensor, nn
from models.common import trunc_normal_init_
from models.transformer import Transformer, TransformerConfig, Cache
class LoopCoTConfig(TransformerConfig):
cycles: int = 4
# CoT channel (defaults follow the loop-cot reference configs)
cot_gate_mode: Literal["scalar", "dynamic"] = "dynamic"
cot_decode_readout: Literal["lm_head", "embed"] = "embed"
cot_decode_temperature: float = 1.0
cot_detach_decode_embedding: bool = False
cot_decode_topk: int = 100
cot_decode_topk_chunk_size: int = 8192
cot_alpha_init: float = 0.5
cot_beta_init: float = 0.5
# When set, beta is this CONSTANT (no learned beta gate). E.g. 1.0
# restores UT's hard input injection, leaving alpha*decoded as the only
# learned incremental channel.
cot_beta_fixed: Optional[float] = None
# Per-cycle alpha (length == cycles). An entry is either a constant
# (0.0 disables the CoT mix for that cycle and skips its decode) or null
# to keep that cycle's alpha a learned gate.
cot_alpha_fixed_per_cycle: Optional[list[Optional[float]]] = None
# Give each learned cycle its own gate parameters (default: one shared).
cot_alpha_per_cycle_params: bool = False
# Hold alpha at 0 for every cycle until the BP warmup has finished.
cot_alpha_activate_after_warmup: bool = False
# BP warmup (same scheme as looped_tf): backprop through the last
# bp_cycles iterations, ramping bp_min_cycles -> bp_max_cycles (default:
# all cycles) over the first bp_warmup_ratio fraction of training.
bp_warmup_ratio: float = 0.0
bp_min_cycles: int = 1
bp_max_cycles: Optional[int] = None
ALPHA_HIST_BINS = 50 # per-token alpha histogram resolution over [0, 1]
def _inv_sigmoid(p: float) -> float:
p = min(max(p, 1e-6), 1 - 1e-6)
return math.log(p / (1 - p))
class LoopedCoTTransformer(nn.Module):
# LMHead passes the readout/write-back matrices as forward kwargs.
wants_decode_embeddings = True
def __init__(self, config_dict: dict) -> None:
super().__init__()
config = LoopCoTConfig(**config_dict)
self.config = config
self.core = Transformer(TransformerConfig(**config.model_dump()))
self.cycles = config.cycles
self.bp_warmup_ratio = config.bp_warmup_ratio
self.bp_min_cycles = config.bp_min_cycles
self.bp_max_cycles = config.bp_max_cycles if config.bp_max_cycles is not None else config.cycles
assert 1 <= self.bp_min_cycles <= self.bp_max_cycles <= self.cycles
self.head_hint = self.core.head_hint # Hint for LMHead init
# UT-style frozen random initial state, broadcast over positions
self.zL_init = nn.Buffer(trunc_normal_init_(torch.empty(config.hidden_size, dtype=torch.bfloat16), std=1.0), persistent=True) # NOTE: hardcoded dtype.
# ---- Alpha gates ----
fixed = config.cot_alpha_fixed_per_cycle
if fixed is not None:
assert len(fixed) == config.cycles, "cot_alpha_fixed_per_cycle must have one entry per cycle"
# Cycles whose alpha is learned, and where each one reads its params.
learn_cycles = [i for i in range(config.cycles) if fixed is None or fixed[i] is None]
n_gates = (len(learn_cycles) if config.cot_alpha_per_cycle_params else min(1, len(learn_cycles)))
self._alpha_gate_index = {c: (k if config.cot_alpha_per_cycle_params else 0)
for k, c in enumerate(learn_cycles)}
a_init = _inv_sigmoid(config.cot_alpha_init)
if config.cot_alpha_per_cycle_params:
# Separate gate per learned cycle -> ParameterList.
if config.cot_gate_mode == "scalar":
self.cot_alpha_logits_list = nn.ParameterList([nn.Parameter(torch.full((1,), a_init)) for _ in range(n_gates)])
else:
self.cot_alpha_weights_list = nn.ParameterList([nn.Parameter(torch.zeros(config.hidden_size)) for _ in range(n_gates)])
self.cot_alpha_bias_list = nn.ParameterList([nn.Parameter(torch.full((1,), a_init)) for _ in range(n_gates)])
elif n_gates:
# Single shared gate -> plain parameters (checkpoint-compatible
# with the earlier loop-cot runs).
if config.cot_gate_mode == "scalar":
self.cot_alpha_logits = nn.Parameter(torch.full((1,), a_init))
else:
self.cot_alpha_weights = nn.Parameter(torch.zeros(config.hidden_size))
self.cot_alpha_bias = nn.Parameter(torch.full((1,), a_init))
# ---- Beta gate ----
if config.cot_beta_fixed is None:
b_init = _inv_sigmoid(config.cot_beta_init)
if config.cot_gate_mode == "scalar":
self.cot_beta_logits = nn.Parameter(torch.full((1,), b_init))
elif config.cot_gate_mode == "dynamic":
self.cot_beta_weights = nn.Parameter(torch.zeros(config.hidden_size))
self.cot_beta_bias = nn.Parameter(torch.full((1,), b_init))
else:
raise ValueError(f"Unsupported cot_gate_mode: {config.cot_gate_mode}")
# Optional per-cycle channel diagnostics: set to a list (eager mode
# only) to receive one dict per cycle per forward with the mean
# per-token L2 norms of the three input channels (z, alpha*decoded,
# beta*x) and the mean gate values. None (default) = zero overhead.
self._stats_sink: Optional[list] = None
# Create cache function (one KV cache per cycle for inference)
self.create_cache = lambda **kwargs: [self.core.create_cache(**kwargs) for _i in range(self.cycles)]
# ---- CoT channel -------------------------------------------------------
def _decode(self, hidden: Tensor, readout_w: Tensor, readout_scale: float,
embed_w: Tensor, embed_scale: float) -> Tensor:
"""Expected token embedding under softmax(top-k(hidden @ readout^T)/T).
Returns sum_v p_v * (embed_scale * embed_w[v]) over the top-k tokens —
an exact convex combination of the effective input embeddings.
"""
if self.config.cot_detach_decode_embedding:
readout_w = readout_w.detach()
embed_w = embed_w.detach()
matmul_dtype = hidden.dtype if hidden.dtype in (torch.float16, torch.bfloat16) else torch.float32
flat = hidden.to(matmul_dtype).reshape(-1, hidden.shape[-1])
readout_w = readout_w.to(matmul_dtype)
embed_w = embed_w.to(matmul_dtype)
num_tokens, hidden_size = flat.shape
vocab_size = readout_w.shape[0]
topk = min(self.config.cot_decode_topk, vocab_size)
temp = self.config.cot_decode_temperature
if topk <= 0: # full-vocab decode
logits = (flat.float() @ readout_w.float().T) * readout_scale
probs = torch.softmax(logits / temp, dim=-1)
decoded = (probs @ embed_w.float()) * embed_scale
return decoded.to(hidden.dtype).reshape(hidden.shape)
chunk_size = max(self.config.cot_decode_topk_chunk_size, topk)
topk_values = None
topk_indices = None
for start in range(0, vocab_size, chunk_size):
end = min(start + chunk_size, vocab_size)
chunk_logits = (flat @ readout_w[start:end].T) * readout_scale
if temp != 1.0:
chunk_logits = chunk_logits / temp
chunk_topk = min(topk, end - start)
chunk_values, chunk_indices = torch.topk(chunk_logits, k=chunk_topk, dim=-1)
chunk_indices = chunk_indices + start
if topk_values is None:
topk_values, topk_indices = chunk_values, chunk_indices
continue
merged_values = torch.cat([topk_values, chunk_values], dim=-1)
merged_indices = torch.cat([topk_indices, chunk_indices], dim=-1)
topk_values, selection = torch.topk(merged_values, k=topk, dim=-1)
topk_indices = torch.gather(merged_indices, -1, selection)
probs = torch.softmax(topk_values.float(), dim=-1).to(embed_w.dtype)
selected = embed_w.index_select(0, topk_indices.reshape(-1)).view(num_tokens, topk, hidden_size)
# einsum keeps the reduction in a matmul kernel (fp32 accumulate) and
# avoids materializing a second (num_tokens, topk, hidden) tensor.
decoded = torch.einsum("nk,nkh->nh", probs, selected) * embed_scale
return decoded.to(hidden.dtype).reshape(*hidden.shape[:-1], hidden_size)
def _alpha_gate(self, decoded: Tensor, cycle: int):
idx = self._alpha_gate_index[cycle]
per_cycle = self.config.cot_alpha_per_cycle_params
if self.config.cot_gate_mode == "scalar":
logits = (self.cot_alpha_logits_list[idx] if per_cycle else self.cot_alpha_logits)
return torch.sigmoid(logits).to(decoded.dtype)
w = self.cot_alpha_weights_list[idx] if per_cycle else self.cot_alpha_weights
b = self.cot_alpha_bias_list[idx] if per_cycle else self.cot_alpha_bias
alpha_logits = torch.sum(decoded.to(w.dtype) * w, dim=-1, keepdim=True) + b
return torch.sigmoid(alpha_logits).to(decoded.dtype)
def _beta_gate(self, x: Tensor):
if self.config.cot_beta_fixed is not None:
return self.config.cot_beta_fixed # constant beta (e.g. 1.0 = UT hard injection)
if self.config.cot_gate_mode == "scalar":
return torch.sigmoid(self.cot_beta_logits).to(x.dtype)
beta_logits = torch.sum(x.to(self.cot_beta_weights.dtype) * self.cot_beta_weights, dim=-1, keepdim=True) + self.cot_beta_bias
return torch.sigmoid(beta_logits).to(x.dtype)
# ---- Model API ---------------------------------------------------------
def forward(self, carry: None, x: Tensor, cache: Optional[list[list[Cache]]] = None,
bp_cycles: Optional[int] = None, alpha_on: bool = True,
decode_embed_weight: Optional[Tensor] = None, decode_embed_scale: float = 1.0,
decode_lm_head_weight: Optional[Tensor] = None, **seq_info) -> tuple[None, Tensor]:
assert decode_embed_weight is not None, "loop_cot requires decode weights from LMHead (wants_decode_embeddings)"
if self.config.cot_decode_readout == "lm_head":
readout_w, readout_scale = decode_lm_head_weight, 1.0
else:
readout_w, readout_scale = decode_embed_weight, decode_embed_scale
if bp_cycles is None:
bp_cycles = self.cycles # inference/eval: value only affects grad truncation
fixed = self.config.cot_alpha_fixed_per_cycle
z = self.zL_init
for i in range(self.cycles):
# Gradient flows only through the last `bp_cycles` iterations.
with torch.set_grad_enabled(torch.is_grad_enabled() and (i >= self.cycles - bp_cycles)):
alpha_i = fixed[i] if fixed is not None else None
if not alpha_on or alpha_i == 0.0:
alpha, mix_a = 0.0, None # decode skipped entirely
else:
decoded = self._decode(z, readout_w, readout_scale, decode_embed_weight, decode_embed_scale)
alpha = alpha_i if alpha_i is not None else self._alpha_gate(decoded, i)
mix_a = alpha * decoded
beta = self._beta_gate(x)
mix_b = beta * x
if self._stats_sink is not None:
with torch.no_grad():
def _tok_norm(t: Tensor) -> float:
return t.float().norm(dim=-1).mean().item() if t.dim() > 1 else t.float().norm().item()
rec = dict(
cycle=i,
z_norm=_tok_norm(z),
alpha_decoded_norm=_tok_norm(mix_a) if mix_a is not None else 0.0,
beta_x_norm=_tok_norm(mix_b),
alpha_mean=alpha.float().mean().item() if torch.is_tensor(alpha) else float(alpha),
beta_mean=beta.float().mean().item() if torch.is_tensor(beta) else float(beta),
)
# Per-token alpha distribution (sigmoid => support [0,1]).
if torch.is_tensor(alpha) and alpha.numel() > 1:
rec["alpha_hist"] = torch.histc(alpha.float(), bins=ALPHA_HIST_BINS, min=0.0, max=1.0).tolist()
self._stats_sink.append(rec)
inp = z + mix_b if mix_a is None else z + mix_a + mix_b
z = self.core(inp, cache=cache[i] if cache is not None else None, **seq_info)
return None, z
def compute_train_extra_args(self, train_state: Any) -> dict[str, Any]:
warmup_steps = train_state.total_steps * self.bp_warmup_ratio
progress = min(1.0, train_state.step / warmup_steps) if warmup_steps > 0 else 1.0
args = dict(bp_cycles=self.bp_min_cycles + int(progress * (self.bp_max_cycles - self.bp_min_cycles)))
if self.config.cot_alpha_activate_after_warmup:
# Gates stay unused (hence untouched at their init) until the BP
# warmup has fully ramped, then switch on together.
args["alpha_on"] = progress >= 1.0
return args
def initial_carry(self, batch_size: int, dtype) -> None:
return None
|