Download code/models/baselines/looped_tf.py from fhyfhy/HRM-Text-checkpoints: direct link, hf CLI and curl.
- Browser
- Download file 2.94 kB
-
https://huggingface.co/fhyfhy/HRM-Text-checkpoints/resolve/main/code/models/baselines/looped_tf.py
- Command line
-
hf download hf://fhyfhy/HRM-Text-checkpoints/code/models/baselines/looped_tf.py
-
curl -L -o looped_tf.py https://huggingface.co/fhyfhy/HRM-Text-checkpoints/resolve/main/code/models/baselines/looped_tf.py
2.94 kB
| from typing import Any, Optional | |
| import torch | |
| from torch import Tensor, nn | |
| from models.transformer import Transformer, TransformerConfig, Cache | |
| class LoopedTransformerConfig(TransformerConfig): | |
| """A looped transformer: an HRM with the L module removed. | |
| A single full-size (n_layers, NOT halved) transformer stack H is iterated | |
| H_cycles times on its own state: z <- H(z), with z initialized from the | |
| token embeddings (same as HRM's z_H init). No input injection between | |
| cycles. Blocks/attention/norm/MLP/init are identical to HRM's (same | |
| TransformerConfig machinery), so at equal n_layers the parameter count | |
| matches the `transformer` and `hrm` presets exactly. | |
| """ | |
| H_cycles: int = 2 | |
| # BP warmup (simplified HRM scheme, see compute_train_extra_args): | |
| # backprop through the last `bp_cycles` iterations only, ramping from | |
| # bp_min_cycles to bp_max_cycles (default: all cycles) over the first | |
| # bp_warmup_ratio fraction of total training steps. | |
| bp_warmup_ratio: float = 0.0 | |
| bp_min_cycles: int = 1 | |
| bp_max_cycles: Optional[int] = None | |
| class LoopedTransformer(nn.Module): | |
| def __init__(self, config_dict: dict) -> None: | |
| super().__init__() | |
| config = LoopedTransformerConfig(**config_dict) | |
| self.core = Transformer(TransformerConfig(**config.model_dump())) | |
| self.H_cycles = config.H_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.H_cycles | |
| assert 1 <= self.bp_min_cycles <= self.bp_max_cycles <= self.H_cycles | |
| self.head_hint = self.core.head_hint # Hint for LMHead init | |
| # Create cache function (one KV cache per iteration for inference) | |
| self.create_cache = lambda **kwargs: [self.core.create_cache(**kwargs) for _i in range(self.H_cycles)] | |
| def forward(self, carry: None, x: Tensor, cache: Optional[list[list[Cache]]] = None, bp_cycles: int = 1, **seq_info) -> tuple[None, Tensor]: | |
| z = x | |
| for i in range(self.H_cycles): | |
| # Gradient flows only through the last `bp_cycles` iterations; | |
| # earlier ones run as constants (truncated backprop-through-depth). | |
| with torch.set_grad_enabled(torch.is_grad_enabled() and (i >= self.H_cycles - bp_cycles)): | |
| z = self.core(z, 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 | |
| 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 | |