Download code/models/baselines/loop_cot.py from fhyfhy/HRM-Text-checkpoints: direct link, hf CLI and curl.
- Browser
- Download file 15.3 kB
-
https://huggingface.co/fhyfhy/HRM-Text-checkpoints/resolve/main/code/models/baselines/loop_cot.py
- Command line
-
hf download hf://fhyfhy/HRM-Text-checkpoints/code/models/baselines/loop_cot.py
-
curl -L -o loop_cot.py https://huggingface.co/fhyfhy/HRM-Text-checkpoints/resolve/main/code/models/baselines/loop_cot.py
15.3 kB
| """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 | |