File size: 10,593 Bytes
431ffa3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
# -*- coding: utf-8 -*-

from __future__ import annotations

import torch
import torch.nn as nn
from torch.utils.checkpoint import checkpoint

from Model.blocks import RecurrentBlock
from Model.layers.rmsnorm import RMSNorm


class RecurrentCore(nn.Module):
    def __init__(self, cfg):
        super().__init__()

        self.cfg = cfg
        self.block = RecurrentBlock(cfg)
        self.inject = cfg.inject_embedding
        self.inject_scale = cfg.inject_scale
        self.use_act = cfg.use_act
        self.grad_ckpt = bool(getattr(cfg, "grad_ckpt_recurrent", False))

        if self.inject_scale < 0:
            raise ValueError("inject_scale must be non-negative")
        if cfg.recurrent_steps <= 0:
            raise ValueError("recurrent_steps must be positive")

        if self.use_act:
            if cfg.act_max_steps <= 0:
                raise ValueError("act_max_steps must be positive")
            if not (0.0 < cfg.act_threshold <= 1.0):
                raise ValueError("act_threshold must be in (0, 1]")
            self.halt_proj = nn.Linear(cfg.d_model, 1)
            # Normalize before the halt head: the hidden-state norm grows
            # across recurrent steps, which would otherwise saturate the
            # sigmoid and make halting depth-dependent at init.
            self.halt_norm = RMSNorm(cfg.d_model, eps=cfg.rmsnorm_eps)

    def forward(
        self,
        e0: torch.Tensor,
        word_pos: torch.Tensor | None = None,
        morph_depth: torch.Tensor | None = None,
        attn_mask: torch.Tensor | None = None,
        causal: bool = True,
        steps: int | None = None,
        bptt_window: int | None = None,
    ) -> tuple[torch.Tensor, dict]:
        self._check_inputs(e0, word_pos, morph_depth, attn_mask)

        if self.use_act:
            return self._forward_act(
                e0=e0,
                word_pos=word_pos,
                morph_depth=morph_depth,
                attn_mask=attn_mask,
                causal=causal,
            )

        return self._forward_fixed(
            e0=e0,
            word_pos=word_pos,
            morph_depth=morph_depth,
            attn_mask=attn_mask,
            causal=causal,
            steps=steps,
            bptt_window=bptt_window,
        )

    def _forward_fixed(
        self,
        e0: torch.Tensor,
        word_pos: torch.Tensor | None,
        morph_depth: torch.Tensor | None,
        attn_mask: torch.Tensor | None,
        causal: bool,
        steps: int | None,
        bptt_window: int | None,
    ) -> tuple[torch.Tensor, dict]:
        total_steps = int(steps if steps is not None else self.cfg.recurrent_steps)

        if total_steps <= 0:
            raise ValueError("steps must be positive")

        if bptt_window is not None:
            if bptt_window <= 0:
                raise ValueError("bptt_window must be positive")
            bptt_window = min(bptt_window, total_steps)

        h = e0

        for idx in range(total_steps):
            if bptt_window is not None and idx < total_steps - bptt_window:
                h = h.detach()

            if self.inject:
                h = h + self.inject_scale * e0

            h = self._run_block(
                h,
                word_pos=word_pos,
                morph_depth=morph_depth,
                attn_mask=attn_mask,
                causal=causal,
                step=idx,
            )

        return h, {
            "steps_used": total_steps,
            "ponder_cost": e0.new_tensor(0.0),
        }

    def _run_block(
        self,
        h: torch.Tensor,
        word_pos: torch.Tensor | None,
        morph_depth: torch.Tensor | None,
        attn_mask: torch.Tensor | None,
        causal: bool,
        step: int | None = None,
    ) -> torch.Tensor:
        # ``step`` is a Python int (the recurrent-loop index), closed over like
        # ``word_pos`` so it stays a constant under gradient checkpointing -- it
        # only matters when the block FFN is a step-aware MixtureLoRAFFN.
        if self.grad_ckpt and self.training and h.requires_grad:
            def _fn(h_in):
                return self.block(
                    h_in,
                    word_pos=word_pos,
                    morph_depth=morph_depth,
                    attn_mask=attn_mask,
                    causal=causal,
                    step=step,
                )

            return checkpoint(_fn, h, use_reentrant=False)
        return self.block(
            h,
            word_pos=word_pos,
            morph_depth=morph_depth,
            attn_mask=attn_mask,
            causal=causal,
            step=step,
        )

    def _forward_act(
        self,
        e0: torch.Tensor,
        word_pos: torch.Tensor | None,
        morph_depth: torch.Tensor | None,
        attn_mask: torch.Tensor | None,
        causal: bool,
    ) -> tuple[torch.Tensor, dict]:
        bsz, seq_len, _ = e0.shape
        dtype = e0.dtype

        h = e0
        output = torch.zeros_like(e0)

        halt_accum = torch.zeros(bsz, seq_len, device=e0.device, dtype=torch.float32)
        updates = torch.zeros(bsz, seq_len, device=e0.device, dtype=torch.float32)
        running = torch.ones(bsz, seq_len, device=e0.device, dtype=torch.float32)

        if attn_mask is not None:
            running = running * attn_mask.to(device=e0.device, dtype=torch.float32)

        for _idx in range(self.cfg.act_max_steps):
            if self.inject:
                h = h + self.inject_scale * e0

            h = self._run_block(
                h,
                word_pos=word_pos,
                morph_depth=morph_depth,
                attn_mask=attn_mask,
                causal=causal,
                step=_idx,
            )

            p = torch.sigmoid(self.halt_proj(self.halt_norm(h))).squeeze(-1).float()
            p = p * running

            new_halt = halt_accum + p
            reached = ((new_halt >= self.cfg.act_threshold).float()) * running

            remainder = (1.0 - halt_accum).clamp(min=0.0) * reached
            active_weight = p * (1.0 - reached)
            weight = active_weight + remainder

            output = output + weight.to(dtype).unsqueeze(-1) * h
            updates = updates + running

            halt_accum = new_halt
            running = running * (1.0 - reached)

        # NOTE: previously this used `running.sum().item() == 0` to break
        # early, but that forces a host sync every step. We unroll the full
        # act_max_steps and just account for never-halted positions below.

        # Leftover probability mass for positions that never crossed the
        # threshold: commit current h with the remaining `running` weight.
        output = output + running.to(dtype).unsqueeze(-1) * h

        denom = (
            attn_mask.to(device=e0.device, dtype=torch.float32).sum()
            if attn_mask is not None
            else torch.tensor(bsz * seq_len, device=e0.device, dtype=torch.float32)
        ).clamp(min=1.0)

        ponder_cost = updates.sum() / denom
        steps_used = updates.sum().detach() / denom.detach()

        return output, {
            "steps_used": float(steps_used),
            "ponder_cost": ponder_cost,
        }

    def _check_inputs(
        self,
        e0: torch.Tensor,
        word_pos: torch.Tensor | None,
        morph_depth: torch.Tensor | None,
        attn_mask: torch.Tensor | None,
    ) -> None:
        if e0.ndim != 3:
            raise ValueError("e0 must have shape [B, L, d_model]")

        bsz, seq_len, dim = e0.shape

        if dim != self.cfg.d_model:
            raise ValueError(f"expected d_model={self.cfg.d_model}, got {dim}")

        if word_pos is not None and word_pos.shape != (bsz, seq_len):
            raise ValueError("word_pos must have shape [B, L]")

        if morph_depth is not None and morph_depth.shape != (bsz, seq_len):
            raise ValueError("morph_depth must have shape [B, L]")

        if attn_mask is not None and attn_mask.shape != (bsz, seq_len):
            raise ValueError("attn_mask must have shape [B, L]")


def _grad_norm(x: torch.Tensor) -> float:
    if x.grad is None:
        return 0.0
    return x.grad.norm().item()


def _check() -> None:
    from Model.config import RDTConfig, tiny_config

    torch.manual_seed(0)

    cfg = tiny_config()
    core = RecurrentCore(cfg)
    core.eval()

    bsz, seq_len = 2, 16
    e0 = torch.randn(bsz, seq_len, cfg.d_model)
    word_pos = torch.arange(seq_len).unsqueeze(0).expand(bsz, seq_len)
    morph_depth = torch.zeros(bsz, seq_len, dtype=torch.long)

    h, info = core(e0, word_pos=word_pos, morph_depth=morph_depth)

    print("RecurrentCore")
    print(f"  fixed_steps: {cfg.recurrent_steps}")
    print(f"  shape: {tuple(e0.shape)} -> {tuple(h.shape)}")
    print(f"  steps_used: {info['steps_used']}")

    e0g = torch.randn(bsz, seq_len, cfg.d_model, requires_grad=True)
    h, _info = core(e0g, word_pos=word_pos, morph_depth=morph_depth)
    h.sum().backward()

    print(f"  grad_norm: {_grad_norm(e0g):.6f}")

    for steps in [2, 4, 8, 16]:
        with torch.no_grad():
            h, _info = core(
                e0,
                word_pos=word_pos,
                morph_depth=morph_depth,
                steps=steps,
            )
        print(f"  steps={steps}, out_norm={h.norm().item():.6f}")

    e0b = torch.randn(bsz, seq_len, cfg.d_model, requires_grad=True)
    h, _info = core(
        e0b,
        word_pos=word_pos,
        morph_depth=morph_depth,
        bptt_window=2,
    )
    h.sum().backward()

    print(f"  bptt_window=2, grad_norm={_grad_norm(e0b):.6f}")

    cfg_act = RDTConfig(
        d_model=512,
        n_heads=8,
        head_dim=64,
        kv_lora_rank=128,
        ffn_hidden=1536,
        n_prelude=2,
        n_coda=2,
        mamba_per_block=5,
        attn_per_block=1,
        recurrent_steps=4,
        max_seq_len=2048,
        use_official_mamba=False,
        use_act=True,
        act_max_steps=16,
    )

    core_act = RecurrentCore(cfg_act)
    core_act.eval()

    h, info = core_act(e0, word_pos=word_pos, morph_depth=morph_depth)

    print("ACT")
    print(f"  steps_used: {info['steps_used']:.6f}")
    print(f"  ponder_cost: {float(info['ponder_cost'].detach()):.6f}")

    e0a = torch.randn(bsz, seq_len, cfg_act.d_model, requires_grad=True)
    h, info = core_act(e0a, word_pos=word_pos, morph_depth=morph_depth)
    (h.sum() + cfg_act.act_ponder_cost * info["ponder_cost"]).backward()

    print(f"  act_grad_norm: {_grad_norm(e0a):.6f}")


if __name__ == "__main__":
    _check()