File size: 5,555 Bytes
f730521
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""A causal transformer that gives the same output offline and frame by frame.

Offline (training): `forward(x)` uses a banded causal mask: token i attends to the
`window` tokens ending at i. Streaming (serving): `step(x, state)` keeps, per layer,
the keys and values of the last `window - 1` tokens. The two are the same function
(tests/test_streaming.py checks it), so a model trained on whole crops can be
served one 80 ms frame at a time without drift.

Positions are rotary, so only distances matter and a session can run for hours.
"""
import math

import torch
import torch.nn as nn
import torch.nn.functional as F


def _rope(pos, dim, device):
    """cos/sin tables [T, dim/2] for integer positions `pos` [T]. float64 angles so
    long sessions keep precision."""
    inv = 1.0 / (10000.0 ** (torch.arange(0, dim, 2, device=device, dtype=torch.float64) / dim))
    ang = pos.to(torch.float64)[:, None] * inv[None, :]
    return ang.cos().float(), ang.sin().float()


def _rotate(x, cos, sin):
    """x [B, H, T, Dh]; rotate pairs (even, odd) by the position angle."""
    x1, x2 = x[..., 0::2], x[..., 1::2]
    cos, sin = cos.to(x.dtype), sin.to(x.dtype)
    return torch.stack((x1 * cos - x2 * sin, x1 * sin + x2 * cos), dim=-1).flatten(-2)


class Block(nn.Module):
    def __init__(self, dim, heads, mlp_ratio=4):
        super().__init__()
        assert dim % heads == 0 and (dim // heads) % 2 == 0
        self.heads = heads
        self.ln1 = nn.LayerNorm(dim)
        self.qkv = nn.Linear(dim, 3 * dim)
        self.out = nn.Linear(dim, dim)
        self.ln2 = nn.LayerNorm(dim)
        self.mlp = nn.Sequential(nn.Linear(dim, mlp_ratio * dim), nn.GELU(), nn.Linear(mlp_ratio * dim, dim))

    def _qkv(self, x, cos, sin):
        B, T, D = x.shape
        q, k, v = self.qkv(self.ln1(x)).view(B, T, 3, self.heads, D // self.heads).permute(2, 0, 3, 1, 4)
        return _rotate(q, cos, sin), _rotate(k, cos, sin), v

    def forward(self, x, cos, sin, mask):
        q, k, v = self._qkv(x, cos, sin)
        a = F.scaled_dot_product_attention(q, k, v, attn_mask=mask)
        x = x + self.out(a.transpose(1, 2).flatten(2))
        return x + self.mlp(self.ln2(x))

    def step(self, x, cos, sin, cache, window, seen):
        """x [B, t, D] new tokens; cache = (k, v) of the last window-1 tokens; seen = tokens before this step.

        The cache has its full size from the first step (zeros, masked out until real tokens
        arrive), so every step has the same tensor shapes. Measured: with a cache that grew step
        by step, a controller step took 53 ms until the window was full and 13 ms after."""
        q, k, v = self._qkv(x, cos, sin)
        keep = window - 1
        if cache is None:
            cache = (k.new_zeros(k.shape[0], k.shape[1], keep, k.shape[3]), v.new_zeros(v.shape[0], v.shape[1], keep, v.shape[3]))
        k = torch.cat([cache[0], k], dim=2)
        v = torch.cat([cache[1], v], dim=2)
        t, S = q.shape[2], k.shape[2]
        # key j (0..S-1) sits at distance (S - t + i) - j behind new token i; the first keys are empty slots
        j = torch.arange(S, device=x.device)
        dist = (S - t + torch.arange(t, device=x.device))[:, None] - j[None, :]
        mask = (dist >= 0) & (dist < window) & (j[None, :] >= keep - min(seen, keep))
        a = F.scaled_dot_product_attention(q, k, v, attn_mask=mask)
        x = x + self.out(a.transpose(1, 2).flatten(2))
        return x + self.mlp(self.ln2(x)), (k[:, :, t:], v[:, :, t:])


class CausalTransformer(nn.Module):
    def __init__(self, dim, layers, heads, window):
        super().__init__()
        self.dim, self.heads, self.window = dim, heads, window
        self.blocks = nn.ModuleList([Block(dim, heads) for _ in range(layers)])

    def forward(self, x):
        T = x.shape[1]
        idx = torch.arange(T, device=x.device)
        cos, sin = _rope(idx, self.dim // self.heads, x.device)
        dist = idx[:, None] - idx[None, :]
        mask = (dist >= 0) & (dist < self.window)
        for b in self.blocks:
            x = b(x, cos, sin, mask)
        return x

    def init_state(self):
        return {"pos": 0, "cache": [None] * len(self.blocks)}

    def step(self, x, state):
        t = x.shape[1]
        pos = torch.arange(state["pos"], state["pos"] + t, device=x.device)
        cos, sin = _rope(pos, self.dim // self.heads, x.device)
        cache = []
        for b, c in zip(self.blocks, state["cache"]):
            x, c = b.step(x, cos, sin, c, self.window, state["pos"])
            cache.append(c)
        return x, {"pos": state["pos"] + t, "cache": cache}


def count_params(m):
    return sum(p.numel() for p in m.parameters())


def cosine_by_time(frac, warmup=0.02, floor=0.05):
    """LR multiplier as a function of elapsed wall-clock fraction (runs are time-budgeted)."""
    if frac < warmup:
        return frac / warmup
    return floor + (1 - floor) * 0.5 * (1 + math.cos(math.pi * min(1.0, (frac - warmup) / (1 - warmup))))


def read_checkpoint(path):
    """(cfg, state dict) of a model of this repository, from a training checkpoint (.pt) or from the
    published form: <name>.safetensors with <name>.json (the cfg) beside it."""
    import json
    from pathlib import Path
    path = Path(path)
    if path.suffix == ".safetensors":
        from safetensors.torch import load_file
        return json.loads(path.with_suffix(".json").read_text(encoding="utf-8"))["cfg"], load_file(str(path))
    ck = torch.load(path, map_location="cpu", weights_only=True)
    return ck["cfg"], ck["model"]