Switch to unified view

a b/src/codellama-main/llama/model.py
1
# Copyright (c) Meta Platforms, Inc. and affiliates.
2
# This software may be used and distributed according to the terms of the Llama 2 Community License Agreement.
3
4
import math
5
from dataclasses import dataclass
6
from typing import Any, Optional, Tuple
7
8
import fairscale.nn.model_parallel.initialize as fs_init
9
import torch
10
import torch.nn.functional as F
11
from fairscale.nn.model_parallel.layers import (
12
    ColumnParallelLinear,
13
    ParallelEmbedding,
14
    RowParallelLinear,
15
)
16
from torch import nn
17
18
if torch.cuda.is_available():
19
    device = "cuda"
20
elif torch.backends.mps.is_available():
21
    device = "mps"
22
else:
23
    device = "cpu"
24
25
@dataclass
26
class ModelArgs:
27
    dim: int = 4096
28
    n_layers: int = 32
29
    n_heads: int = 32
30
    n_kv_heads: Optional[int] = None
31
    vocab_size: int = -1  # defined later by tokenizer
32
    multiple_of: int = 256  # make SwiGLU hidden layer size multiple of large power of 2
33
    ffn_dim_multiplier: Optional[float] = None
34
    norm_eps: float = 1e-5
35
    rope_theta: float = 10000
36
37
    max_batch_size: int = 32
38
    max_seq_len: int = 2048
39
40
41
class RMSNorm(torch.nn.Module):
42
    def __init__(self, dim: int, eps: float = 1e-6):
43
        super().__init__()
44
        self.eps = eps
45
        self.weight = nn.Parameter(torch.ones(dim))
46
47
    def _norm(self, x):
48
        return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
49
50
    def forward(self, x):
51
        output = self._norm(x.float()).type_as(x)
52
        return output * self.weight
53
54
55
def precompute_freqs_cis(dim: int, end: int, theta: float = 10000.0):
56
    freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim))
57
58
    t = torch.arange(end, device=freqs.device, dtype=torch.float32)  # type: ignore
59
    freqs = torch.outer(t, freqs)  # type: ignore
60
    freqs_cis = torch.polar(torch.ones_like(freqs), freqs)  # complex64
61
    return freqs_cis
62
63
64
def reshape_for_broadcast(freqs_cis: torch.Tensor, x: torch.Tensor):
65
    ndim = x.ndim
66
    assert 0 <= 1 < ndim
67
    assert freqs_cis.shape == (x.shape[1], x.shape[-1])
68
    shape = [d if i == 1 or i == ndim - 1 else 1 for i, d in enumerate(x.shape)]
69
    return freqs_cis.view(*shape)
70
71
72
def apply_rotary_emb(
73
    xq: torch.Tensor,
74
    xk: torch.Tensor,
75
    freqs_cis: torch.Tensor,
76
) -> Tuple[torch.Tensor, torch.Tensor]:
77
    if not torch.cuda.is_available():
78
        xq = xq.to('cpu')
79
        xk = xk.to('cpu')
80
    xq_ = torch.view_as_complex(xq.float().reshape(*xq.shape[:-1], -1, 2))
81
    xk_ = torch.view_as_complex(xk.float().reshape(*xk.shape[:-1], -1, 2))
82
    freqs_cis = reshape_for_broadcast(freqs_cis, xq_)
83
    xq_out = torch.view_as_real(xq_ * freqs_cis).flatten(3)
84
    xk_out = torch.view_as_real(xk_ * freqs_cis).flatten(3)
85
    return xq_out.type_as(xq).to(device), xk_out.type_as(xk).to(device)
86
87
88
def repeat_kv(x: torch.Tensor, n_rep: int) -> torch.Tensor:
89
    """torch.repeat_interleave(x, dim=2, repeats=n_rep)"""
90
    bs, slen, n_kv_heads, head_dim = x.shape
91
    if n_rep == 1:
92
        return x
93
    return (
94
        x[:, :, :, None, :]
95
        .expand(bs, slen, n_kv_heads, n_rep, head_dim)
96
        .reshape(bs, slen, n_kv_heads * n_rep, head_dim)
97
    )
98
99
100
class Attention(nn.Module):
101
    def __init__(self, args: ModelArgs):
102
        super().__init__()
103
        self.n_kv_heads = args.n_heads if args.n_kv_heads is None else args.n_kv_heads
104
        model_parallel_size = fs_init.get_model_parallel_world_size()
105
        self.n_local_heads = args.n_heads // model_parallel_size
106
        self.n_local_kv_heads = self.n_kv_heads // model_parallel_size
107
        self.n_rep = self.n_local_heads // self.n_local_kv_heads
108
        self.head_dim = args.dim // args.n_heads
109
110
        self.wq = ColumnParallelLinear(
111
            args.dim,
112
            args.n_heads * self.head_dim,
113
            bias=False,
114
            gather_output=False,
115
            init_method=lambda x: x,
116
        )
117
        self.wk = ColumnParallelLinear(
118
            args.dim,
119
            self.n_kv_heads * self.head_dim,
120
            bias=False,
121
            gather_output=False,
122
            init_method=lambda x: x,
123
        )
124
        self.wv = ColumnParallelLinear(
125
            args.dim,
126
            self.n_kv_heads * self.head_dim,
127
            bias=False,
128
            gather_output=False,
129
            init_method=lambda x: x,
130
        )
131
        self.wo = RowParallelLinear(
132
            args.n_heads * self.head_dim,
133
            args.dim,
134
            bias=False,
135
            input_is_parallel=True,
136
            init_method=lambda x: x,
137
        )
138
139
        self.cache_k = torch.zeros(
140
            (
141
                args.max_batch_size,
142
                args.max_seq_len,
143
                self.n_local_kv_heads,
144
                self.head_dim,
145
            )
146
        ).to(device)
147
        self.cache_v = torch.zeros(
148
            (
149
                args.max_batch_size,
150
                args.max_seq_len,
151
                self.n_local_kv_heads,
152
                self.head_dim,
153
            )
154
        ).to(device)
155
156
    def forward(
157
        self,
158
        x: torch.Tensor,
159
        start_pos: int,
160
        freqs_cis: torch.Tensor,
161
        mask: Optional[torch.Tensor],
162
    ):
163
        bsz, seqlen, _ = x.shape
164
        xq, xk, xv = self.wq(x), self.wk(x), self.wv(x)
165
166
        xq = xq.view(bsz, seqlen, self.n_local_heads, self.head_dim)
167
        xk = xk.view(bsz, seqlen, self.n_local_kv_heads, self.head_dim)
168
        xv = xv.view(bsz, seqlen, self.n_local_kv_heads, self.head_dim)
169
170
        xq, xk = apply_rotary_emb(xq, xk, freqs_cis=freqs_cis)
171
172
        self.cache_k = self.cache_k.to(xq)
173
        self.cache_v = self.cache_v.to(xq)
174
175
        self.cache_k[:bsz, start_pos : start_pos + seqlen] = xk
176
        self.cache_v[:bsz, start_pos : start_pos + seqlen] = xv
177
178
        keys = self.cache_k[:bsz, : start_pos + seqlen]
179
        values = self.cache_v[:bsz, : start_pos + seqlen]
180
181
        # repeat k/v heads if n_kv_heads < n_heads
182
        keys = repeat_kv(keys, self.n_rep)  # (bs, seqlen, n_local_heads, head_dim)
183
        values = repeat_kv(values, self.n_rep)  # (bs, seqlen, n_local_heads, head_dim)
184
185
        xq = xq.transpose(1, 2)  # (bs, n_local_heads, seqlen, head_dim)
186
        keys = keys.transpose(1, 2)
187
        values = values.transpose(1, 2)
188
        scores = torch.matmul(xq, keys.transpose(2, 3)) / math.sqrt(self.head_dim)
189
        if mask is not None:
190
            scores = scores + mask  # (bs, n_local_heads, seqlen, cache_len + seqlen)
191
        scores = F.softmax(scores.float(), dim=-1).type_as(xq)
192
        output = torch.matmul(scores, values)  # (bs, n_local_heads, seqlen, head_dim)
193
        output = output.transpose(1, 2).contiguous().view(bsz, seqlen, -1)
194
        return self.wo(output)
195
196
197
class FeedForward(nn.Module):
198
    def __init__(
199
        self,
200
        dim: int,
201
        hidden_dim: int,
202
        multiple_of: int,
203
        ffn_dim_multiplier: Optional[float],
204
    ):
205
        super().__init__()
206
        hidden_dim = int(2 * hidden_dim / 3)
207
        # custom dim factor multiplier
208
        if ffn_dim_multiplier is not None:
209
            hidden_dim = int(ffn_dim_multiplier * hidden_dim)
210
        hidden_dim = multiple_of * ((hidden_dim + multiple_of - 1) // multiple_of)
211
212
        self.w1 = ColumnParallelLinear(
213
            dim, hidden_dim, bias=False, gather_output=False, init_method=lambda x: x
214
        )
215
        self.w2 = RowParallelLinear(
216
            hidden_dim, dim, bias=False, input_is_parallel=True, init_method=lambda x: x
217
        )
218
        self.w3 = ColumnParallelLinear(
219
            dim, hidden_dim, bias=False, gather_output=False, init_method=lambda x: x
220
        )
221
222
    def forward(self, x):
223
        return self.w2(F.silu(self.w1(x)) * self.w3(x))
224
225
226
class TransformerBlock(nn.Module):
227
    def __init__(self, layer_id: int, args: ModelArgs):
228
        super().__init__()
229
        self.n_heads = args.n_heads
230
        self.dim = args.dim
231
        self.head_dim = args.dim // args.n_heads
232
        self.attention = Attention(args)
233
        self.feed_forward = FeedForward(
234
            dim=args.dim,
235
            hidden_dim=4 * args.dim,
236
            multiple_of=args.multiple_of,
237
            ffn_dim_multiplier=args.ffn_dim_multiplier,
238
        )
239
        self.layer_id = layer_id
240
        self.attention_norm = RMSNorm(args.dim, eps=args.norm_eps)
241
        self.ffn_norm = RMSNorm(args.dim, eps=args.norm_eps)
242
243
    def forward(
244
        self,
245
        x: torch.Tensor,
246
        start_pos: int,
247
        freqs_cis: torch.Tensor,
248
        mask: Optional[torch.Tensor],
249
    ):
250
        h = x + self.attention.forward(
251
            self.attention_norm(x), start_pos, freqs_cis, mask
252
        )
253
        out = h + self.feed_forward.forward(self.ffn_norm(h))
254
        return out
255
256
257
class Transformer(nn.Module):
258
    def __init__(self, params: ModelArgs):
259
        super().__init__()
260
        self.params = params
261
        self.vocab_size = params.vocab_size
262
        self.n_layers = params.n_layers
263
264
        self.tok_embeddings = ParallelEmbedding(
265
            params.vocab_size, params.dim, init_method=lambda x: x,
266
        )
267
268
        self.layers = torch.nn.ModuleList()
269
        for layer_id in range(params.n_layers):
270
            self.layers.append(TransformerBlock(layer_id, params))
271
272
        self.norm = RMSNorm(params.dim, eps=params.norm_eps)
273
        self.output = ColumnParallelLinear(
274
            params.dim, params.vocab_size, bias=False, init_method=lambda x: x
275
        )
276
277
        self.freqs_cis = precompute_freqs_cis(
278
            self.params.dim // self.params.n_heads,
279
            self.params.max_seq_len * 2,
280
            params.rope_theta,
281
        )
282
283
    @torch.inference_mode()
284
    def forward(self, tokens: torch.Tensor, start_pos: int):
285
        _bsz, seqlen = tokens.shape
286
        h = self.tok_embeddings(tokens)
287
        self.freqs_cis = self.freqs_cis.to("cuda" if device == "cuda" else "cpu")
288
        freqs_cis = self.freqs_cis[start_pos : start_pos + seqlen]
289
290
        mask = None
291
        if seqlen > 1:
292
            mask = torch.full(
293
                (1, 1, seqlen, seqlen), float("-inf"), device=torch.device('cpu')
294
            )
295
            mask = mask.to(torch.float32).triu(diagonal=start_pos+1).type_as(h)
296
297
        for layer in self.layers:
298
            h = layer(h, start_pos, freqs_cis, (mask.to(device) if mask is not None else mask))
299
        h = self.norm(h)
300
        output = self.output(h).float()
301
        return output