muverqqw commited on
Commit
941cc12
·
verified ·
1 Parent(s): 58460cf

Upload modeling_alinlight.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. modeling_alinlight.py +245 -0
modeling_alinlight.py ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright 2026 EngineerGL Research.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import math
17
+ import torch
18
+ import torch.nn as nn
19
+ import torch.nn.functional as F
20
+ from typing import Optional, Tuple, List, Union
21
+ from transformers import PreTrainedModel
22
+ from transformers.modeling_outputs import CausalLMOutputWithPast, BaseModelOutputWithPast
23
+ from transformers import GenerationMixin
24
+ from configuration_alinlight import AlinlightConfig # Импортируем конфиг из соседнего файла
25
+
26
+ class AlinlightRMSNorm(nn.Module):
27
+ def __init__(self, hidden_size, eps=1e-6):
28
+ super().__init__()
29
+ self.weight = nn.Parameter(torch.ones(hidden_size))
30
+ self.eps = eps
31
+ def forward(self, x):
32
+ input_dtype = x.dtype
33
+ x = x.to(torch.float32)
34
+ variance = x.pow(2).mean(-1, keepdim=True)
35
+ x = x * torch.rsqrt(variance + self.eps)
36
+ return self.weight * x.to(input_dtype)
37
+
38
+ class AlinlightRotaryEmbedding(nn.Module):
39
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
40
+ super().__init__()
41
+ self.dim = dim
42
+ self.base = base
43
+ self.max_position_embeddings = max_position_embeddings
44
+ self.scaling_factor = scaling_factor
45
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.float32).to(device) / self.dim))
46
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
47
+ self._set_cos_sin_cache(seq_len=max_position_embeddings, device=device, dtype=torch.get_default_dtype())
48
+
49
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
50
+ t = torch.arange(seq_len, device=device, dtype=torch.int64).type_as(self.inv_freq)
51
+ t = t / self.scaling_factor
52
+ freqs = torch.outer(t, self.inv_freq)
53
+ emb = torch.cat((freqs, freqs), dim=-1)
54
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
55
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
56
+
57
+ def forward(self, x, seq_len=None):
58
+ if seq_len > self.cos_cached.shape[0]:
59
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
60
+ return self.cos_cached[:seq_len].to(dtype=x.dtype), self.sin_cached[:seq_len].to(dtype=x.dtype)
61
+
62
+ def rotate_half(x):
63
+ x1 = x[..., : x.shape[-1] // 2]
64
+ x2 = x[..., x.shape[-1] // 2 :]
65
+ return torch.cat((-x2, x1), dim=-1)
66
+
67
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
68
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
69
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
70
+ q_embed = (q * cos) + (rotate_half(q) * sin)
71
+ k_embed = (k * cos) + (rotate_half(k) * sin)
72
+ return q_embed, k_embed
73
+
74
+ class AlinlightMLP(nn.Module):
75
+ def __init__(self, config):
76
+ super().__init__()
77
+ self.hidden_size = config.hidden_size
78
+ self.intermediate_size = config.intermediate_size
79
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
80
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
81
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
82
+ self.act_fn = nn.SiLU()
83
+
84
+ def forward(self, x):
85
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
86
+
87
+ class AlinlightAttention(nn.Module):
88
+ def __init__(self, config, layer_idx: Optional[int] = None):
89
+ super().__init__()
90
+ self.config = config
91
+ self.layer_idx = layer_idx
92
+ self.hidden_size = config.hidden_size
93
+ self.num_heads = config.num_attention_heads
94
+ self.head_dim = self.hidden_size // self.num_heads
95
+ self.num_key_value_heads = config.num_key_value_heads
96
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
97
+ self.sliding_window = config.sliding_window
98
+ self.attention_dropout = config.attention_dropout
99
+
100
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
101
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
102
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
103
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
104
+
105
+ def forward(self, hidden_states, attention_mask=None, position_ids=None, past_key_value=None, output_attentions=False, use_cache=False, cos_sin=None):
106
+ bsz, q_len, _ = hidden_states.size()
107
+ query_states = self.q_proj(hidden_states)
108
+ key_states = self.k_proj(hidden_states)
109
+ value_states = self.v_proj(hidden_states)
110
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
111
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
112
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
113
+
114
+ if cos_sin is not None:
115
+ cos, sin = cos_sin
116
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
117
+
118
+ if past_key_value is not None:
119
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
120
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
121
+
122
+ # Truncation logic for sliding window
123
+ if self.sliding_window is not None and key_states.shape[2] > self.sliding_window:
124
+ key_states = key_states[:, :, -self.sliding_window:, :]
125
+ value_states = value_states[:, :, -self.sliding_window:, :]
126
+
127
+ past_key_value = (key_states, value_states) if use_cache else None
128
+
129
+ if self.num_key_value_groups > 1:
130
+ key_states = key_states[:, :, None, :, :].expand(bsz, self.num_key_value_heads, self.num_key_value_groups, key_states.shape[-2], self.head_dim).reshape(bsz, self.num_heads, key_states.shape[-2], self.head_dim)
131
+ value_states = value_states[:, :, None, :, :].expand(bsz, self.num_key_value_heads, self.num_key_value_groups, value_states.shape[-2], self.head_dim).reshape(bsz, self.num_heads, value_states.shape[-2], self.head_dim)
132
+
133
+ # Use Scaled Dot Product Attention
134
+ attn_output = F.scaled_dot_product_attention(query_states, key_states, value_states, attn_mask=None, dropout_p=0.0, is_causal=True)
135
+ attn_output = attn_output.transpose(1, 2).contiguous().view(bsz, q_len, self.hidden_size)
136
+ return self.o_proj(attn_output), None, past_key_value
137
+
138
+ class AlinlightDecoderLayer(nn.Module):
139
+ def __init__(self, config, layer_idx: int):
140
+ super().__init__()
141
+ self.self_attn = AlinlightAttention(config, layer_idx=layer_idx)
142
+ self.mlp = AlinlightMLP(config)
143
+ self.input_layernorm = AlinlightRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
144
+ self.post_attention_layernorm = AlinlightRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
145
+
146
+ def forward(self, hidden_states, attention_mask=None, position_ids=None, past_key_value=None, output_attentions=False, use_cache=False, cos_sin=None):
147
+ residual = hidden_states
148
+ hidden_states = self.input_layernorm(hidden_states)
149
+ hidden_states, _, present_key_value = self.self_attn(hidden_states, attention_mask, position_ids, past_key_value, output_attentions, use_cache, cos_sin)
150
+ hidden_states = residual + hidden_states
151
+ residual = hidden_states
152
+ hidden_states = self.post_attention_layernorm(hidden_states)
153
+ hidden_states = self.mlp(hidden_states)
154
+ hidden_states = residual + hidden_states
155
+ return hidden_states, None, present_key_value
156
+
157
+ class AlinlightModel(PreTrainedModel):
158
+ config_class = AlinlightConfig
159
+ def __init__(self, config: AlinlightConfig):
160
+ super().__init__(config)
161
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, config.pad_token_id)
162
+ self.layers = nn.ModuleList([AlinlightDecoderLayer(config, layer_idx=i) for i in range(config.num_hidden_layers)])
163
+ self.norm = AlinlightRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
164
+
165
+ scaling_factor = 1.0
166
+ if config.rope_scaling and config.rope_scaling.get("type") == "linear":
167
+ scaling_factor = config.rope_scaling.get("factor", 1.0)
168
+
169
+ self.rotary_emb = AlinlightRotaryEmbedding(config.hidden_size // config.num_attention_heads, max_position_embeddings=config.max_position_embeddings, base=config.rope_theta, scaling_factor=scaling_factor)
170
+
171
+ def forward(self, input_ids=None, past_key_values=None, use_cache=None, **kwargs):
172
+ if input_ids is not None:
173
+ inputs_embeds = self.embed_tokens(input_ids)
174
+ else:
175
+ inputs_embeds = kwargs.get("inputs_embeds")
176
+
177
+ seq_len = inputs_embeds.shape[1]
178
+ if past_key_values is not None:
179
+ seq_len += past_key_values[0][0].shape[2]
180
+
181
+ cos, sin = self.rotary_emb(inputs_embeds, seq_len=seq_len)
182
+
183
+ position_ids = kwargs.get("position_ids")
184
+ if position_ids is None:
185
+ position_ids = torch.arange(seq_len - inputs_embeds.shape[1], seq_len, dtype=torch.long, device=inputs_embeds.device)
186
+ position_ids = position_ids.unsqueeze(0).expand(inputs_embeds.shape[0], -1)
187
+
188
+ hidden_states = inputs_embeds
189
+ next_decoder_cache = () if use_cache else None
190
+
191
+ for idx, layer in enumerate(self.layers):
192
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
193
+ layer_outputs = layer(hidden_states, position_ids=position_ids, past_key_value=past_key_value, use_cache=use_cache, cos_sin=(cos, sin))
194
+ hidden_states = layer_outputs[0]
195
+ if use_cache:
196
+ next_decoder_cache += (layer_outputs[2],)
197
+
198
+ hidden_states = self.norm(hidden_states)
199
+
200
+ return BaseModelOutputWithPast(
201
+ last_hidden_state=hidden_states,
202
+ past_key_values=next_decoder_cache
203
+ )
204
+
205
+ class AlinlightForCausalLM(PreTrainedModel, GenerationMixin):
206
+ config_class = AlinlightConfig
207
+ _keys_to_ignore_on_load_missing = ["model.rotary_emb.inv_freq"]
208
+
209
+ def __init__(self, config):
210
+ super().__init__(config)
211
+ self.model = AlinlightModel(config)
212
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
213
+ self.lm_head.weight = self.model.embed_tokens.weight
214
+
215
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, **kwargs):
216
+ if past_key_values:
217
+ input_ids = input_ids[:, -1:]
218
+
219
+ position_ids = kwargs.get("position_ids", None)
220
+ if position_ids is None:
221
+ if past_key_values:
222
+ past_length = past_key_values[0][0].shape[2]
223
+ position_ids = torch.tensor([[past_length]], dtype=torch.long, device=input_ids.device)
224
+ else:
225
+ position_ids = torch.arange(input_ids.shape[1], dtype=torch.long, device=input_ids.device).unsqueeze(0)
226
+
227
+ return {
228
+ "input_ids": input_ids,
229
+ "past_key_values": past_key_values,
230
+ "use_cache": True,
231
+ "position_ids": position_ids
232
+ }
233
+
234
+ def forward(self, input_ids=None, past_key_values=None, labels=None, **kwargs):
235
+ outputs = self.model(input_ids=input_ids, past_key_values=past_key_values, **kwargs)
236
+ hidden_states = outputs.last_hidden_state
237
+ logits = self.lm_head(hidden_states)
238
+
239
+ loss = None
240
+ if labels is not None:
241
+ shift_logits = logits[..., :-1, :].contiguous()
242
+ shift_labels = labels[..., 1:].contiguous()
243
+ loss = F.cross_entropy(shift_logits.view(-1, self.config.vocab_size), shift_labels.view(-1))
244
+
245
+ return CausalLMOutputWithPast(loss=loss, logits=logits, past_key_values=outputs.past_key_values)