Download code/models/baselines/gated_loop.py from fhyfhy/HRM-Text-checkpoints: direct link, hf CLI and curl.
- Browser
- Download file 3.25 kB
-
https://huggingface.co/fhyfhy/HRM-Text-checkpoints/resolve/main/code/models/baselines/gated_loop.py
- Command line
-
hf download hf://fhyfhy/HRM-Text-checkpoints/code/models/baselines/gated_loop.py
-
curl -L -o gated_loop.py https://huggingface.co/fhyfhy/HRM-Text-checkpoints/resolve/main/code/models/baselines/gated_loop.py
3.25 kB
| from typing import Any, Optional | |
| import torch | |
| import torch.nn.functional as F | |
| from torch import Tensor, nn | |
| from models.transformer import Transformer, TransformerConfig, Cache | |
| from models.layers import LinearInit | |
| class GatedLoopConfig(TransformerConfig): | |
| """Looped transformer with a gated loop channel between cycles. | |
| z_0 = token embeddings x. Cycle i produces h_i = core(z_i); the next | |
| cycle's input is z_{i+1} = (W1 h_i) ⊙ SiLU(W2 x), where W1 and W2 are | |
| d×d matrices (no bias) shared across all cycles. Final output is the | |
| last cycle's hidden state h_{cycles-1}. | |
| """ | |
| cycles: int = 4 | |
| # BP warmup (same scheme as looped_tf/ut): backprop through the last | |
| # bp_cycles iterations only, ramping bp_min_cycles -> bp_max_cycles | |
| # (default: all cycles) over the first bp_warmup_ratio fraction of | |
| # training steps. | |
| bp_warmup_ratio: float = 0.0 | |
| bp_min_cycles: int = 1 | |
| bp_max_cycles: Optional[int] = None | |
| class GatedLoopTransformer(nn.Module): | |
| def __init__(self, config_dict: dict) -> None: | |
| super().__init__() | |
| config = GatedLoopConfig(**config_dict) | |
| 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 | |
| # Loop gate: z_{i+1} = W1(h_i) * silu(W2(x)), shared across cycles. | |
| self.W1 = LinearInit(config.hidden_size, config.hidden_size, bias=False, init_std=config.init_config.in_std) | |
| self.W2 = LinearInit(config.hidden_size, config.hidden_size, bias=False, init_std=config.init_config.in_std) | |
| # 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)] | |
| def forward(self, carry: None, x: Tensor, cache: Optional[list[list[Cache]]] = None, bp_cycles: Optional[int] = None, **seq_info) -> tuple[None, Tensor]: | |
| if bp_cycles is None: | |
| bp_cycles = self.cycles # inference/eval: value only affects grad truncation | |
| z = x | |
| h = x | |
| 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)): | |
| h = self.core(z, cache=cache[i] if cache is not None else None, **seq_info) | |
| if i < self.cycles - 1: | |
| z = self.W1(h) * F.silu(self.W2(x)) | |
| return None, h | |
| 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 | |
| return dict(bp_cycles=self.bp_min_cycles + int(progress * (self.bp_max_cycles - self.bp_min_cycles))) | |
| def initial_carry(self, batch_size: int, dtype) -> None: | |
| return None | |