File size: 8,325 Bytes
6f645f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import math
from dataclasses import asdict, dataclass

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


@dataclass
class GPTConfig:
    block_size: int = 1024
    vocab_size: int = 8192
    n_layer: int = 12
    n_head: int = 12
    n_embd: int = 768
    dropout: float = 0.0
    bias: bool = False


class CausalSelfAttention(nn.Module):
    def __init__(self, config: GPTConfig) -> None:
        super().__init__()
        if config.n_embd % config.n_head:
            raise ValueError("embedding dimension must be divisible by number of heads")
        self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd, bias=config.bias)
        self.c_proj = nn.Linear(config.n_embd, config.n_embd, bias=config.bias)
        self.attn_dropout = nn.Dropout(config.dropout)
        self.resid_dropout = nn.Dropout(config.dropout)
        self.n_head = config.n_head
        self.n_embd = config.n_embd
        self.dropout = config.dropout

    def forward(self, value: torch.Tensor) -> torch.Tensor:
        batch, time, channels = value.size()
        query, key, val = self.c_attn(value).split(self.n_embd, dim=2)
        head_size = channels // self.n_head
        query = query.view(batch, time, self.n_head, head_size).transpose(1, 2)
        key = key.view(batch, time, self.n_head, head_size).transpose(1, 2)
        val = val.view(batch, time, self.n_head, head_size).transpose(1, 2)
        attended = F.scaled_dot_product_attention(
            query,
            key,
            val,
            attn_mask=None,
            dropout_p=self.dropout if self.training else 0,
            is_causal=True,
        )
        attended = attended.transpose(1, 2).contiguous().view(batch, time, channels)
        return self.resid_dropout(self.c_proj(attended))


class MLP(nn.Module):
    def __init__(self, config: GPTConfig) -> None:
        super().__init__()
        self.c_fc = nn.Linear(config.n_embd, 4 * config.n_embd, bias=config.bias)
        self.gelu = nn.GELU()
        self.c_proj = nn.Linear(4 * config.n_embd, config.n_embd, bias=config.bias)
        self.dropout = nn.Dropout(config.dropout)

    def forward(self, value: torch.Tensor) -> torch.Tensor:
        return self.dropout(self.c_proj(self.gelu(self.c_fc(value))))


class Block(nn.Module):
    def __init__(self, config: GPTConfig) -> None:
        super().__init__()
        self.ln_1 = nn.LayerNorm(config.n_embd, bias=config.bias)
        self.attn = CausalSelfAttention(config)
        self.ln_2 = nn.LayerNorm(config.n_embd, bias=config.bias)
        self.mlp = MLP(config)

    def forward(self, value: torch.Tensor) -> torch.Tensor:
        value = value + self.attn(self.ln_1(value))
        return value + self.mlp(self.ln_2(value))


class GPT(nn.Module):
    def __init__(self, config: GPTConfig) -> None:
        super().__init__()
        self.config = config
        self.transformer = nn.ModuleDict(
            {
                "wte": nn.Embedding(config.vocab_size, config.n_embd),
                "wpe": nn.Embedding(config.block_size, config.n_embd),
                "drop": nn.Dropout(config.dropout),
                "h": nn.ModuleList([Block(config) for _ in range(config.n_layer)]),
                "ln_f": nn.LayerNorm(config.n_embd, bias=config.bias),
            }
        )
        self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
        self.transformer.wte.weight = self.lm_head.weight
        self.apply(self._init_weights)
        for name, parameter in self.named_parameters():
            if name.endswith("c_proj.weight"):
                torch.nn.init.normal_(
                    parameter, mean=0.0, std=0.02 / math.sqrt(2 * config.n_layer)
                )

    @staticmethod
    def _init_weights(module: nn.Module) -> None:
        if isinstance(module, nn.Linear):
            torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
            if module.bias is not None:
                torch.nn.init.zeros_(module.bias)
        elif isinstance(module, nn.Embedding):
            torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)

    def forward(
        self, index: torch.Tensor, targets: torch.Tensor | None = None
    ) -> tuple[torch.Tensor, torch.Tensor | None]:
        _, time = index.shape
        if time > self.config.block_size:
            raise ValueError("sequence exceeds model block size")
        positions = torch.arange(0, time, dtype=torch.long, device=index.device)
        value = self.transformer.drop(self.transformer.wte(index) + self.transformer.wpe(positions))
        for block in self.transformer.h:
            value = block(value)
        value = self.transformer.ln_f(value)
        logits = self.lm_head(value)
        loss = (
            F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=-1)
            if targets is not None
            else None
        )
        return logits, loss

    @torch.no_grad()
    def generate(
        self,
        index: torch.Tensor,
        max_new_tokens: int,
        temperature: float = 0.8,
        top_k: int | None = 200,
        top_p: float | None = None,
        repetition_penalty: float = 1.0,
        no_repeat_ngram_size: int | None = None,
    ) -> torch.Tensor:
        """Sample a continuation.

        The defaults reproduce the temperature/top-k-only sampler used for the
        phase 1-5 evaluations, so held-out numbers stay comparable. The
        additional knobs are opt-in: phase-5 generation samples showed the
        low-temperature repetition loop surviving the 345M -> 730M scale-up
        (reports/phase5_generation_samples.md), and the sampler had no
        repetition control of any kind to blame it on.
        """
        for _ in range(max_new_tokens):
            cropped = index[:, -self.config.block_size :]
            logits, _ = self(cropped)
            logits = logits[:, -1, :]
            if repetition_penalty != 1.0:
                for row, sequence in enumerate(index):
                    seen = torch.unique(sequence)
                    scores = logits[row, seen]
                    logits[row, seen] = torch.where(
                        scores > 0, scores / repetition_penalty, scores * repetition_penalty
                    )
            logits = logits / temperature
            if no_repeat_ngram_size:
                for row, sequence in enumerate(index):
                    for token in self._banned_ngram_tokens(sequence, no_repeat_ngram_size):
                        logits[row, token] = -float("Inf")
            if top_k is not None:
                values, _ = torch.topk(logits, min(top_k, logits.size(-1)))
                logits[logits < values[:, [-1]]] = -float("Inf")
            if top_p is not None:
                ordered, order = torch.sort(logits, descending=True, dim=-1)
                ranked = F.softmax(ordered, dim=-1)
                # Drop a token once the mass ahead of it already covers top_p,
                # which always keeps at least the most likely token.
                remove = ranked.cumsum(dim=-1) - ranked >= top_p
                logits = logits.masked_fill(
                    torch.zeros_like(remove).scatter(1, order, remove), -float("Inf")
                )
            probabilities = F.softmax(logits, dim=-1)
            index = torch.cat((index, torch.multinomial(probabilities, num_samples=1)), dim=1)
        return index

    @staticmethod
    def _banned_ngram_tokens(sequence: torch.Tensor, size: int) -> list[int]:
        """Tokens that would repeat an n-gram already present in ``sequence``."""
        if size < 2 or len(sequence) < size:
            return []
        tokens = sequence.tolist()
        prefix = tuple(tokens[-(size - 1) :])
        banned = [
            tokens[start + size - 1]
            for start in range(len(tokens) - size + 1)
            if tuple(tokens[start : start + size - 1]) == prefix
        ]
        return banned

    def parameter_count(self, non_embedding: bool = False) -> int:
        count = sum(parameter.numel() for parameter in self.parameters())
        if non_embedding:
            count -= self.transformer.wpe.weight.numel()
        return count

    def config_dict(self) -> dict[str, object]:
        return asdict(self.config)