File size: 10,554 Bytes
fcfb990
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
import torch
import torch.nn as nn
import torch.nn.functional as F
import transformers
from transformers import GenerationMixin, PreTrainedModel
from transformers.cache_utils import DynamicCache, DynamicLayer
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
from .configuration_zedev_v2 import ZedevV2Config


class ZedevV2RMSNorm(nn.Module):
    def __init__(self, dim: int, eps: float = 1e-5):
        super().__init__()
        self.weight = nn.Parameter(torch.ones(dim))
        self.eps = eps

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


def apply_rope(z: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
    hd = z.shape[-1]
    a, b = z[..., : hd // 2], z[..., hd // 2 :]
    c, s = cos[:, None, :, :].to(z.dtype), sin[:, None, :, :].to(z.dtype)
    return torch.cat([a * c - b * s, a * s + b * c], dim=-1)


class ZedevV2Attention(nn.Module):
    def __init__(self, config: ZedevV2Config):
        super().__init__()
        self.num_heads = config.num_attention_heads
        self.num_kv_heads = config.num_key_value_heads
        self.head_dim = config.head_dim
        qkv_dim = (self.num_heads + 2 * self.num_kv_heads) * self.head_dim
        self.qkv_proj = nn.Linear(config.hidden_size, qkv_dim, bias=False)
        self.o_proj = nn.Linear(self.num_heads * self.head_dim, config.hidden_size, bias=False)
        self.q_norm = ZedevV2RMSNorm(self.head_dim, config.rms_norm_eps)
        self.k_norm = ZedevV2RMSNorm(self.head_dim, config.rms_norm_eps)

    def forward(self, x, cos, sin, attention_mask=None, past_key_values=None, cache_idx=0):
        B, T, _ = x.shape
        qkv = self.qkv_proj(x)
        q_dim = self.num_heads * self.head_dim
        kv_dim = self.num_kv_heads * self.head_dim
        q = self.q_norm(qkv[..., :q_dim].view(B, T, self.num_heads, self.head_dim)).transpose(1, 2)
        k = self.k_norm(qkv[..., q_dim : q_dim + kv_dim].view(B, T, self.num_kv_heads, self.head_dim)).transpose(1, 2)
        v = qkv[..., q_dim + kv_dim :].view(B, T, self.num_kv_heads, self.head_dim).transpose(1, 2)

        q = apply_rope(q, cos, sin)
        k = apply_rope(k, cos, sin)

        if past_key_values is not None:
            k, v = past_key_values.update(k, v, cache_idx)

        kh = k.repeat_interleave(self.num_heads // self.num_kv_heads, dim=1)
        vh = v.repeat_interleave(self.num_heads // self.num_kv_heads, dim=1)
        kv_len = kh.shape[2]
        past_len = kv_len - T

        if attention_mask is None and past_len == 0:
            a = F.scaled_dot_product_attention(q, kh, vh, is_causal=(T > 1))
        elif attention_mask is None and T == 1:
            a = F.scaled_dot_product_attention(q, kh, vh, is_causal=False)
        else:
            causal = torch.ones((T, kv_len), dtype=torch.bool, device=q.device).tril(diagonal=past_len)[None, None, :, :]
            if attention_mask is not None:
                if attention_mask.ndim == 2:
                    pad_m = attention_mask[:, -kv_len:].bool()[:, None, None, :]
                    mask_b = causal & pad_m
                elif attention_mask.ndim == 4:
                    am = attention_mask[..., -T:, -kv_len:]
                    mask_b = am.bool() if am.dtype == torch.bool else (am == 0)
                else:
                    mask_b = causal
                mask_b = mask_b | (~mask_b.any(dim=-1, keepdim=True))
            else:
                mask_b = causal
            attn_bias = torch.zeros(mask_b.shape, dtype=q.dtype, device=q.device).masked_fill(~mask_b, torch.finfo(q.dtype).min)
            a = F.scaled_dot_product_attention(q, kh, vh, attn_mask=attn_bias, is_causal=False)

        return self.o_proj(a.transpose(1, 2).reshape(B, T, self.num_heads * self.head_dim))


class ZedevV2MLP(nn.Module):
    def __init__(self, config: ZedevV2Config):
        super().__init__()
        self.ff = config.intermediate_size
        self.gate_up_proj = nn.Linear(config.hidden_size, 2 * self.ff, bias=False)
        self.down_proj = nn.Linear(self.ff, config.hidden_size, bias=False)

    def forward(self, x):
        gu = self.gate_up_proj(x)
        return self.down_proj(F.silu(gu[..., : self.ff]) * gu[..., self.ff :])


class ZedevV2DecoderLayer(nn.Module):
    def __init__(self, config: ZedevV2Config):
        super().__init__()
        self.self_attn = ZedevV2Attention(config)
        self.mlp = ZedevV2MLP(config)
        self.input_layernorm = ZedevV2RMSNorm(config.hidden_size, config.rms_norm_eps)
        self.post_attention_layernorm = ZedevV2RMSNorm(config.hidden_size, config.rms_norm_eps)

    def forward(self, x, cos, sin, attention_mask=None, past_key_values=None, cache_idx=0):
        x = x + self.self_attn(self.input_layernorm(x), cos, sin, attention_mask, past_key_values, cache_idx)
        x = x + self.mlp(self.post_attention_layernorm(x))
        return x


class ZedevV2Model(PreTrainedModel):
    config_class = ZedevV2Config

    def __init__(self, config: ZedevV2Config):
        super().__init__(config)
        self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size)
        self.layers = nn.ModuleList([ZedevV2DecoderLayer(config) for _ in range(config.num_hidden_layers)])
        self.norm = ZedevV2RMSNorm(config.hidden_size, config.rms_norm_eps)
        n_gates = max(config.num_loop_rounds - 1, 1)
        self.gate_weights = nn.Parameter(torch.zeros(n_gates, config.hidden_size))
        self.gate_biases = nn.Parameter(torch.zeros(n_gates))

    def forward(
        self,
        input_ids=None,
        attention_mask=None,
        position_ids=None,
        past_key_values=None,
        inputs_embeds=None,
        use_cache=None,
        output_hidden_states=False,
        **kwargs,
    ):
        past_key_values = kwargs.pop("cache", past_key_values)
        use_cache = use_cache if use_cache is not None else self.config.use_cache
        if use_cache and past_key_values is None:
            past_key_values = DynamicCache()

        n_pre = self.config.num_prelude_layers
        n_core = self.config.num_core_layers
        n_rounds = self.config.num_loop_rounds
        n_eff = n_pre + n_core * n_rounds + self.config.num_coda_layers
        if past_key_values is not None and isinstance(past_key_values, DynamicCache):
            while len(past_key_values.layers) < n_eff:
                past_key_values.layers.append(DynamicLayer())

        x = inputs_embeds if inputs_embeds is not None else self.embed_tokens(input_ids)
        B, T, _ = x.shape
        past_len = past_key_values.get_seq_length() if past_key_values is not None else 0

        if position_ids is None:
            if attention_mask is not None and attention_mask.ndim == 2:
                pos = attention_mask.long().cumsum(-1) - 1
                pos.masked_fill_(attention_mask == 0, 0)
                position_ids = pos[:, -T:]
            else:
                position_ids = torch.arange(past_len, past_len + T, device=x.device).unsqueeze(0).expand(B, T)

        inv_freq = 1.0 / (
            float(self.config.rope_theta)
            ** (torch.arange(0, self.config.head_dim, 2, device=x.device, dtype=torch.float32) / self.config.head_dim)
        )
        freqs = position_ids.float()[..., None] * inv_freq
        cos, sin = freqs.cos(), freqs.sin()

        c_idx = 0
        for l in range(n_pre):
            x = self.layers[l](x, cos, sin, attention_mask, past_key_values, c_idx)
            c_idx += 1

        for r in range(n_rounds):
            x_in = x
            for l in range(n_pre, n_pre + n_core):
                x = self.layers[l](x, cos, sin, attention_mask, past_key_values, c_idx)
                c_idx += 1
            if r > 0:
                gate = torch.sigmoid((x_in.float() @ self.gate_weights[r - 1].float()) + self.gate_biases[r - 1].float())
                x = x_in + gate.to(x.dtype).unsqueeze(-1) * (x - x_in)

        for l in range(n_pre + n_core, self.config.num_hidden_layers):
            x = self.layers[l](x, cos, sin, attention_mask, past_key_values, c_idx)
            c_idx += 1

        x = self.norm(x)
        return BaseModelOutputWithPast(
            last_hidden_state=x,
            past_key_values=past_key_values if use_cache else None,
        )


class ZedevV2ForCausalLM(PreTrainedModel, GenerationMixin):
    config_class = ZedevV2Config
    base_model_prefix = "model"
    _no_split_modules = ["ZedevV2DecoderLayer"]
    _tied_weights_keys = (
        {"lm_head.weight": "model.embed_tokens.weight"}
        if int(transformers.__version__.split(".")[0]) >= 5
        else ["lm_head.weight"]
    )

    def __init__(self, config: ZedevV2Config):
        super().__init__(config)
        self.model = ZedevV2Model(config)
        self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
        self.post_init()

    def get_input_embeddings(self):
        return self.model.embed_tokens

    def set_input_embeddings(self, value):
        self.model.embed_tokens = value

    def get_output_embeddings(self):
        return self.lm_head

    def set_output_embeddings(self, new_embeddings):
        self.lm_head = new_embeddings

    def forward(
        self,
        input_ids=None,
        attention_mask=None,
        position_ids=None,
        past_key_values=None,
        inputs_embeds=None,
        labels=None,
        use_cache=None,
        logits_to_keep=0,
        **kwargs,
    ):
        outputs = self.model(
            input_ids=input_ids,
            attention_mask=attention_mask,
            position_ids=position_ids,
            past_key_values=past_key_values,
            inputs_embeds=inputs_embeds,
            use_cache=use_cache,
            **kwargs,
        )
        hidden = outputs.last_hidden_state
        sl = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) and logits_to_keep > 0 else slice(None)
        logits = self.lm_head(hidden[:, sl, :])

        loss = None
        if labels is not None:
            shift_logits = logits[..., :-1, :].contiguous().float()
            shift_labels = labels[..., 1:].contiguous()
            loss = F.cross_entropy(shift_logits.view(-1, self.config.vocab_size), shift_labels.view(-1), ignore_index=-100)

        return CausalLMOutputWithPast(
            loss=loss,
            logits=logits,
            past_key_values=outputs.past_key_values,
        )