Text Generation
PyTorch
English
File size: 4,241 Bytes
2d1f5a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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.weight = nn.Parameter(torch.ones(dim))
        self.eps = eps

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


def apply_rope(q, k, theta=10000.0):
    B, H, T, D = q.shape

    inv_freq = 1.0 / (
        theta ** (
            torch.arange(
                0, D, 2,
                device=q.device,
                dtype=torch.float32
            ) / D
        )
    )

    positions = torch.arange(
        T, device=q.device, dtype=torch.float32
    )

    freqs = torch.outer(positions, inv_freq)
    cos = freqs.cos()[None, None, :, :]
    sin = freqs.sin()[None, None, :, :]

    def rotate(x):
        x1 = x[..., 0::2].float()
        x2 = x[..., 1::2].float()

        out1 = x1 * cos - x2 * sin
        out2 = x1 * sin + x2 * cos

        return torch.stack(
            (out1, out2), dim=-1
        ).flatten(-2).to(x.dtype)

    return rotate(q), rotate(k)


class Attention(nn.Module):
    def __init__(self, config):
        super().__init__()

        dim = config["hidden_size"]
        self.heads = config["num_heads"]
        self.head_dim = dim // self.heads
        self.theta = config["rope_theta"]

        self.q_proj = nn.Linear(dim, dim, bias=False)
        self.k_proj = nn.Linear(dim, dim, bias=False)
        self.v_proj = nn.Linear(dim, dim, bias=False)
        self.o_proj = nn.Linear(dim, dim, bias=False)

    def forward(self, x):
        B, T, C = x.shape

        q = self.q_proj(x).view(
            B, T, self.heads, self.head_dim
        ).transpose(1, 2)

        k = self.k_proj(x).view(
            B, T, self.heads, self.head_dim
        ).transpose(1, 2)

        v = self.v_proj(x).view(
            B, T, self.heads, self.head_dim
        ).transpose(1, 2)

        q, k = apply_rope(q, k, self.theta)

        out = F.scaled_dot_product_attention(
            q, k, v, is_causal=True
        )

        out = out.transpose(1, 2).contiguous().view(B, T, C)
        return self.o_proj(out)


class SwiGLU(nn.Module):
    def __init__(self, config):
        super().__init__()

        dim = config["hidden_size"]
        hidden = config["intermediate_size"]

        self.gate_proj = nn.Linear(dim, hidden, bias=False)
        self.up_proj = nn.Linear(dim, hidden, bias=False)
        self.down_proj = nn.Linear(hidden, dim, bias=False)

    def forward(self, x):
        return self.down_proj(
            F.silu(self.gate_proj(x)) * self.up_proj(x)
        )


class TransformerBlock(nn.Module):
    def __init__(self, config):
        super().__init__()

        dim = config["hidden_size"]

        self.attention_norm = RMSNorm(dim)
        self.attention = Attention(config)

        self.ffn_norm = RMSNorm(dim)
        self.feed_forward = SwiGLU(config)

    def forward(self, x):
        x = x + self.attention(self.attention_norm(x))
        x = x + self.feed_forward(self.ffn_norm(x))
        return x


class SupernovaTinyArc(nn.Module):
    def __init__(self, config):
        super().__init__()

        self.config = config

        self.embedding = nn.Embedding(
            config["vocab_size"],
            config["hidden_size"]
        )

        self.layers = nn.ModuleList([
            TransformerBlock(config)
            for _ in range(config["num_layers"])
        ])

        self.norm = RMSNorm(config["hidden_size"])

        self.lm_head = nn.Linear(
            config["hidden_size"],
            config["vocab_size"],
            bias=False
        )

        if config["tie_embeddings"]:
            self.lm_head.weight = self.embedding.weight

    def forward(self, input_ids, targets=None):
        x = self.embedding(input_ids)

        for layer in self.layers:
            x = layer(x)

        x = self.norm(x)
        logits = self.lm_head(x)

        loss = None

        if targets is not None:
            loss = F.cross_entropy(
                logits.reshape(-1, logits.size(-1)),
                targets.reshape(-1)
            )

        return logits, loss