File size: 7,167 Bytes
982a4de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import torch
import torch.nn as nn
import torch.nn.functional as F
from models.norm import RMSNorm
from models.rope import precompute_freqs_cis, apply_rotary_emb
import bitsandbytes as bnb
import math


class NormalLinear(nn.Linear):
    def reset_parameters(self) -> None:
        pass


class BnbInt8Linear(bnb.nn.Linear8bitLt):
    def __init__(self, *args, **kwargs):
        super().__init__(has_fp16_weights=False, threshold=6.0, *args, **kwargs)

    def reset_parameters(self) -> None:
        pass


def get_linear_layer(use_int8):
    if use_int8:
        return BnbInt8Linear
    return NormalLinear


class WordEmbedding(nn.Module):
    def __init__(self, args):
        super(WordEmbedding, self).__init__()
        self.embedding = nn.Embedding(args.vocab_size, args.emb_size)

    def forward(self, src):
        emb = self.embedding(src)
        return emb


class MultiHeadedAttention(nn.Module):
    def __init__(self, args, hidden_size, heads_num, attention_head_size, has_bias=True, use_int8=True):
        super(MultiHeadedAttention, self).__init__()
        self.heads_num = heads_num

        self.per_head_size = attention_head_size
        self.inner_hidden_size = heads_num * attention_head_size

        Linear = get_linear_layer(use_int8)
        self.linear_layers = nn.ModuleList(
            [Linear(hidden_size, self.inner_hidden_size, bias=has_bias) for _ in range(3)]
        )

        self.final_linear = Linear(self.inner_hidden_size, hidden_size, bias=has_bias)

        # add cache to reduce compute source.
        self.cache_k = torch.zeros(
            (args.batch_size, args.seq_length, self.heads_num, self.per_head_size)
        )
        self.cache_v = torch.zeros(
            (args.batch_size, args.seq_length, self.heads_num, self.per_head_size)
        )

    def forward(self, key, value, query, start_pos, continue_exsample, mask, freqs_cis):
        batch_size, seq_length, _ = query.size()
        heads_num = self.heads_num
        per_head_size = self.per_head_size
        query, key, value = [l(x).view(batch_size, -1, heads_num, per_head_size) \
                             for l, x in zip(self.linear_layers, (query, key, value))]
        query, key = apply_rotary_emb(query, key, freqs_cis=freqs_cis)
        if self.cache_k.device != key.device:
            self.cache_k = self.cache_k.to(key)
        if self.cache_v.device != value.device:
            self.cache_v = self.cache_v.to(value)

        self.cache_k[continue_exsample, start_pos: start_pos + seq_length] = key
        self.cache_v[continue_exsample, start_pos: start_pos + seq_length] = value

        key = self.cache_k[continue_exsample, : start_pos + seq_length]
        value = self.cache_v[continue_exsample, : start_pos + seq_length]

        query, key, value = [x.transpose(1, 2) for x in (query, key, value)]

        scores = torch.matmul(query, key.transpose(-2, -1))
        scores = scores / math.sqrt(float(per_head_size))
        if mask is not None:
            scores += mask
        # probs = nn.Softmax(dim=-1)(scores)
        probs = F.softmax(scores.float(), dim=-1).type_as(query)
        output = torch.matmul(probs, value).transpose(1, 2).\
            contiguous().view(batch_size, seq_length, -1)
        return self.final_linear(output)


class GatedFeedForward(nn.Module):
    def __init__(self, hidden_size, feedforward_size, has_bias=True, use_int8=True):
        super(GatedFeedForward, self).__init__()
        Linear = get_linear_layer(use_int8)
        self.linear_gate = Linear(hidden_size, feedforward_size, bias=has_bias)
        self.linear_1 = Linear(hidden_size, feedforward_size, bias=has_bias)
        self.linear_2 = Linear(feedforward_size, hidden_size, bias=has_bias)
        self.act = F.silu

    def forward(self, x):
        # gate = self.act(self.linear_gate(x))
        gate = self.act(self.linear_gate(x)).type_as(x)
        inter_linear = self.linear_1(x)
        inter = gate * inter_linear
        output = self.linear_2(inter)
        return output


class TransformerLayer(nn.Module):
    def __init__(self, args):
        super(TransformerLayer, self).__init__()

        if hasattr(args, "attention_head_size"):
            attention_head_size = args.attention_head_size
        else:
            attention_head_size = args.hidden_size // args.heads_num

        has_bias = bool(1 - args.remove_transformer_bias)
        # Multi-head Attention
        self.self_attn = MultiHeadedAttention(
            args, args.hidden_size, args.heads_num, attention_head_size, has_bias=has_bias,
            use_int8=args.use_int8
        )

        # FFN
        self.feed_forward = GatedFeedForward(
            args.hidden_size, args.feedforward_size, has_bias, use_int8=args.use_int8
        )

        self.layer_norm_1 = RMSNorm(args.hidden_size)
        self.layer_norm_2 = RMSNorm(args.hidden_size)

    def forward(self, hidden, start_pos, continue_exsample, mask, freqs_cis=None):
        inter = self.layer_norm_1(hidden)
        inter = self.self_attn(inter, inter, inter, start_pos, continue_exsample, mask, freqs_cis)
        hidden = hidden + inter
        output = self.layer_norm_2(hidden)
        output = self.feed_forward(output) + hidden
        return output


class TransformerEncoder(nn.Module):
    def __init__(self, args):
        super(TransformerEncoder, self).__init__()
        self.mask = args.mask
        self.layers_num = args.layers_num

        self.transformer = nn.ModuleList(
            [TransformerLayer(args) for _ in range(self.layers_num)]
        )

        self.layer_norm = RMSNorm(args.hidden_size)
        self.freqs_cis = precompute_freqs_cis(args.hidden_size // args.heads_num, args.max_seq_length * 2)

    def forward(self, emb, start_pos, continue_exsample):
        batch_size, seq_length, _ = emb.size()
        mask = None
        if seq_length > 1:
            mask = torch.ones(seq_length, seq_length, device=emb.device)
            mask = torch.tril(mask)
            mask = (1.0 - mask) * -10000
            mask = mask.repeat(batch_size, 1, 1, 1)

        hidden = emb
        freqs_cis = self.freqs_cis[start_pos: start_pos + seq_length].to(hidden.device)

        for i in range(self.layers_num):
            hidden = self.transformer[i](hidden, start_pos, continue_exsample, mask, freqs_cis=freqs_cis)
        return self.layer_norm(hidden)


class LmOutput(nn.Module):
    def __init__(self, args):
        super(LmOutput, self).__init__()
        # update: lm output not use int8
        Linear = get_linear_layer(False)
        self.lm = Linear(args.hidden_size, args.vocab_size, bias=False)

    def forward(self, x):
        return self.lm(x[:, -1, :])


class LLaMa(nn.Module):
    def __init__(self, args):
        super(LLaMa, self).__init__()
        self.embedding = WordEmbedding(args)
        self.encoder = TransformerEncoder(args)
        self.target = LmOutput(args)

    #@torch.inference_mode()
    def forward(self, src, start_pos, continue_exsample):
        emb = self.embedding(src)
        output = self.encoder(emb, start_pos, continue_exsample)
        output = self.target(output)
        return output