File size: 5,658 Bytes
d6c063b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# Privoid model code, written from scratch in plain PyTorch (no pretrained weights).
import math
import torch
import torch.nn as nn
import torch.nn.functional as F


class RMSNorm(nn.Module):
    def __init__(self, dim, eps=1e-6):
        super().__init__()
        self.eps = eps
        self.weight = nn.Parameter(torch.ones(dim))

    def forward(self, x):
        xf = x.float()
        xf = xf * torch.rsqrt(xf.pow(2).mean(-1, keepdim=True) + self.eps)
        return (xf * self.weight.float()).type_as(x)


def build_rope(max_pos, head_dim, base=10000.0):
    inv = 1.0 / (base ** (torch.arange(0, head_dim, 2).float() / head_dim))
    freqs = torch.outer(torch.arange(max_pos).float(), inv)
    return freqs.cos(), freqs.sin()


def apply_rope(x, cos, sin):
    T = x.shape[-2]
    cos, sin = cos[:T], sin[:T]
    x1, x2 = x.float().chunk(2, dim=-1)
    return torch.cat([x1 * cos - x2 * sin, x1 * sin + x2 * cos], dim=-1).type_as(x)


class Attention(nn.Module):
    def __init__(self, d, n_heads, dropout):
        super().__init__()
        self.h = n_heads
        self.qkv = nn.Linear(d, 3 * d, bias=False)
        self.o = nn.Linear(d, d, bias=False)
        self.dropout = dropout

    def forward(self, x, cos, sin, attn_mask=None):
        B, T, C = x.shape
        q, k, v = self.qkv(x).view(B, T, 3, self.h, C // self.h).permute(2, 0, 3, 1, 4).unbind(0)
        q, k = apply_rope(q, cos, sin), apply_rope(k, cos, sin)
        y = F.scaled_dot_product_attention(q, k, v, attn_mask=attn_mask,
                                           dropout_p=self.dropout if self.training else 0.0)
        return self.o(y.transpose(1, 2).reshape(B, T, C))


class SwiGLU(nn.Module):
    def __init__(self, d, hidden):
        super().__init__()
        self.w1 = nn.Linear(d, hidden, bias=False)
        self.w3 = nn.Linear(d, hidden, bias=False)
        self.w2 = nn.Linear(hidden, d, bias=False)

    def forward(self, x):
        return self.w2(F.silu(self.w1(x)) * self.w3(x))


class Block(nn.Module):
    def __init__(self, d, n_heads, ffn_dim, dropout):
        super().__init__()
        self.n1, self.n2 = RMSNorm(d), RMSNorm(d)
        self.attn = Attention(d, n_heads, dropout)
        self.mlp = SwiGLU(d, ffn_dim)
        self.drop = nn.Dropout(dropout)

    def forward(self, x, cos, sin, attn_mask=None):
        x = x + self.drop(self.attn(self.n1(x), cos, sin, attn_mask))
        return x + self.drop(self.mlp(self.n2(x)))


class PrivoidEncoder(nn.Module):
    """Bidirectional transformer encoder: RoPE + RMSNorm + SwiGLU, pre-norm."""

    def __init__(self, cfg, dropout=0.0):
        super().__init__()
        d, L, H = cfg['d_model'], cfg['n_layers'], cfg['n_heads']
        assert d % H == 0 and (d // H) % 2 == 0
        self.tok_emb = nn.Embedding(cfg['vocab_size'], d)
        self.drop = nn.Dropout(dropout)
        self.blocks = nn.ModuleList([Block(d, H, cfg['ffn_dim'], dropout) for _ in range(L)])
        self.norm = RMSNorm(d)
        cos, sin = build_rope(cfg['max_pos'], d // H)
        self.register_buffer('rope_cos', cos, persistent=False)
        self.register_buffer('rope_sin', sin, persistent=False)
        self.apply(_init_weights)
        for name, p in self.named_parameters():      # scaled init for residual projections
            if name.endswith('attn.o.weight') or name.endswith('mlp.w2.weight'):
                nn.init.normal_(p, mean=0.0, std=0.02 / math.sqrt(2 * L))

    def forward(self, ids, pad_mask=None):
        x = self.drop(self.tok_emb(ids))
        attn_mask = pad_mask[:, None, None, :] if pad_mask is not None else None
        for blk in self.blocks:
            x = blk(x, self.rope_cos, self.rope_sin, attn_mask)
        return self.norm(x)


def _init_weights(m):
    if isinstance(m, nn.Linear):
        nn.init.normal_(m.weight, mean=0.0, std=0.02)
        if m.bias is not None:
            nn.init.zeros_(m.bias)
    elif isinstance(m, nn.Embedding):
        nn.init.normal_(m.weight, mean=0.0, std=0.02)


class PrivoidForMLM(nn.Module):
    """Stage 1: masked-language-model pre-training head (output tied to the input embedding)."""

    def __init__(self, cfg, dropout=0.0):
        super().__init__()
        d = cfg['d_model']
        self.encoder = PrivoidEncoder(cfg, dropout)
        self.head_dense = nn.Linear(d, d)
        self.head_norm = RMSNorm(d)
        self.head_bias = nn.Parameter(torch.zeros(cfg['vocab_size']))
        _init_weights(self.head_dense)
        self.__dict__['_enc_fn'] = None           # optional torch.compile'd encoder (not a submodule)

    def set_encoder_fn(self, fn):
        self.__dict__['_enc_fn'] = fn

    def forward(self, ids, labels):
        enc = self._enc_fn if self._enc_fn is not None else self.encoder
        h = enc(ids)
        sel = labels != -100
        hs = self.head_norm(F.gelu(self.head_dense(h[sel])))
        logits = F.linear(hs, self.encoder.tok_emb.weight, self.head_bias)
        return F.cross_entropy(logits.float(), labels[sel])


class PrivoidRouter(nn.Module):
    """Stage 2: prompt -> logit of 'needs a frontier model'."""

    def __init__(self, cfg, dropout=0.1):
        super().__init__()
        d = cfg['d_model']
        self.encoder = PrivoidEncoder(cfg, dropout)
        self.head = nn.Sequential(nn.Dropout(dropout), nn.Linear(d, d), nn.GELU(),
                                  nn.Dropout(dropout), nn.Linear(d, 1))
        self.head.apply(_init_weights)

    def forward(self, ids, pad_mask):
        h = self.encoder(ids, pad_mask)
        m = pad_mask.unsqueeze(-1).to(h.dtype)
        pooled = (h * m).sum(1) / m.sum(1).clamp(min=1.0)
        return self.head(pooled).squeeze(-1)