File size: 2,935 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 | 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
|