Download code/models/baselines/ut_nocarry.py from fhyfhy/HRM-Text-checkpoints: direct link, hf CLI and curl.
- Browser
- Download file 2.52 kB
-
https://huggingface.co/fhyfhy/HRM-Text-checkpoints/resolve/main/code/models/baselines/ut_nocarry.py
- Command line
-
hf download hf://fhyfhy/HRM-Text-checkpoints/code/models/baselines/ut_nocarry.py
-
curl -L -o ut_nocarry.py https://huggingface.co/fhyfhy/HRM-Text-checkpoints/resolve/main/code/models/baselines/ut_nocarry.py
2.52 kB
| from typing import Optional | |
| from contextlib import nullcontext | |
| import torch | |
| from torch import nn, Tensor | |
| from models.common import trunc_normal_init_ | |
| from models.transformer import TransformerConfig, Cache | |
| from models.baselines.hrm_nocarry_bp_warmup import HierarchicalReasoningModelRecurrentBlock | |
| class UniversalTransformerConfig(TransformerConfig): | |
| cycles: int | |
| bp_cycles: int | |
| # HRM-style BP warmup (default 0.0 = off, exact original behavior): | |
| # when > 0, backprop truncation ramps from bp_cycles up to FULL backprop | |
| # (all `cycles`) over the first bp_warmup_ratio fraction of total steps. | |
| bp_warmup_ratio: float = 0.0 | |
| class UniversalTransformer(nn.Module): | |
| def __init__(self, config_dict: dict) -> None: | |
| super().__init__() | |
| config = UniversalTransformerConfig(**config_dict) | |
| # Reasoning Layers | |
| self.L_level = HierarchicalReasoningModelRecurrentBlock(TransformerConfig(**config.model_dump())) | |
| # Config | |
| self.cycles = config.cycles | |
| self.bp_cycles = config.bp_cycles | |
| self.bp_warmup_ratio = config.bp_warmup_ratio | |
| self.head_hint = self.L_level.core.head_hint # Hint for LMHead init (inherit from H) | |
| self.zL_init = nn.Buffer(trunc_normal_init_(torch.empty(config.hidden_size, dtype=torch.bfloat16), std=1.0), persistent=True) # NOTE: hardcoded dtype. | |
| # Create cache function | |
| self.create_cache = lambda **kwargs: [self.L_level.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.bp_cycles | |
| z = self.zL_init | |
| for i in range(self.cycles): | |
| with (nullcontext if i >= self.cycles - bp_cycles else torch.no_grad)(): | |
| z = self.L_level(z, x, cache=cache[i] if cache is not None else None, **seq_info) | |
| return None, z | |
| def compute_train_extra_args(self, train_state): | |
| if self.bp_warmup_ratio <= 0.0: | |
| return {} # original fixed-truncation behavior | |
| 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_cycles + int(progress * (self.cycles - self.bp_cycles))) | |
| def initial_carry(self, batch_size: int, dtype: torch.dtype) -> None: | |
| return None | |