muverqqw commited on
Commit
341ca1c
·
1 Parent(s): 56fe341

Update modeling_alinlight.py

Browse files
Files changed (1) hide show
  1. modeling_alinlight.py +13 -26
modeling_alinlight.py CHANGED
@@ -13,11 +13,6 @@
13
  # See the License for the specific language governing permissions and
14
  # limitations under the License.
15
 
16
- # -*- coding: utf-8 -*-
17
- # Copyright 2026 EngineerGL Research.
18
-
19
- # -*- coding: utf-8 -*-
20
- # Copyright 2026 EngineerGL Research.
21
 
22
  import math
23
  import torch
@@ -49,15 +44,15 @@ class AlinlightRotaryEmbedding(nn.Module):
49
  self.max_position_embeddings = max_position_embeddings
50
  self.scaling_factor = scaling_factor
51
 
52
- # Вычисляем частоты сразу
53
  inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.float32).to(device) / self.dim))
54
  self.register_buffer("inv_freq", inv_freq, persistent=False)
55
 
56
- # Инициализируем кэш
57
  self._set_cos_sin_cache(seq_len=max_position_embeddings, device=device, dtype=torch.get_default_dtype())
58
 
59
  def _set_cos_sin_cache(self, seq_len, device, dtype):
60
- # RoPE кэш считаем во float32 для точности, потом кастим
61
  t = torch.arange(seq_len, device=device, dtype=torch.int64).type_as(self.inv_freq)
62
  t = t / self.scaling_factor
63
  freqs = torch.outer(t, self.inv_freq)
@@ -66,7 +61,7 @@ class AlinlightRotaryEmbedding(nn.Module):
66
  self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
67
 
68
  def forward(self, x, seq_len=None):
69
- # Если вдруг длина последовательности больше кэша (редкий случай)
70
  if seq_len > self.cos_cached.shape[0]:
71
  self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
72
 
@@ -145,15 +140,14 @@ class AlinlightAttention(nn.Module):
145
  key_states = torch.cat([past_key_value[0], key_states], dim=2)
146
  value_states = torch.cat([past_key_value[1], value_states], dim=2)
147
 
148
- # === TPU/Efficiency Optimization: Physical Truncation ===
149
- # Вместо сложной маски просто обрезаем старые токены, вышедшие за пределы окна.
150
  if self.sliding_window is not None and key_states.shape[2] > self.sliding_window:
151
  key_states = key_states[:, :, -self.sliding_window:, :]
152
  value_states = value_states[:, :, -self.sliding_window:, :]
153
 
154
  past_key_value = (key_states, value_states) if use_cache else None
155
 
156
- # GQA / MQA Expansion
157
  if self.num_key_value_groups > 1:
158
  key_states = key_states[:, :, None, :, :].expand(
159
  bsz, self.num_key_value_heads, self.num_key_value_groups, key_states.shape[-2], self.head_dim
@@ -163,10 +157,7 @@ class AlinlightAttention(nn.Module):
163
  bsz, self.num_key_value_heads, self.num_key_value_groups, value_states.shape[-2], self.head_dim
164
  ).reshape(bsz, self.num_heads, value_states.shape[-2], self.head_dim)
165
 
166
- # === Fix for "Blind" Generation ===
167
- # is_causal=True нужно ТОЛЬКО при обучении (или prefill), когда q_len > 1.
168
- # Когда мы генерируем по 1 токену (q_len == 1), мы смотрим на весь кэш (прошлое).
169
- # Если поставить True при q_len=1, SDPA может замаскировать всё.
170
  is_causal = q_len > 1
171
 
172
  attn_output = F.scaled_dot_product_attention(
@@ -232,17 +223,17 @@ class AlinlightModel(PreTrainedModel):
232
  else:
233
  inputs_embeds = kwargs.get("inputs_embeds")
234
 
235
- # Определяем длину последовательности для RoPE
236
  seq_len = inputs_embeds.shape[1]
237
  if past_key_values is not None:
238
  seq_len += past_key_values[0][0].shape[2]
239
 
240
- # Получаем cos/sin
241
  cos, sin = self.rotary_emb(inputs_embeds, seq_len=seq_len)
242
 
243
  position_ids = kwargs.get("position_ids")
244
  if position_ids is None:
245
- # Генерируем position_ids сами
246
  position_ids = torch.arange(seq_len - inputs_embeds.shape[1], seq_len, dtype=torch.long, device=inputs_embeds.device)
247
  position_ids = position_ids.unsqueeze(0).expand(inputs_embeds.shape[0], -1)
248
 
@@ -278,10 +269,6 @@ class AlinlightForCausalLM(PreTrainedModel, GenerationMixin):
278
  self.model = AlinlightModel(config)
279
  self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
280
 
281
- # === ВАЖНЕЙШЕЕ ИСПРАВЛЕНИЕ ===
282
- # Связываем веса ТОЛЬКО если это разрешено в конфиге.
283
- # Раньше это было принудительно, что ломало генерацию для моделей типа Mistral/Llama3,
284
- # где tie_word_embeddings=False.
285
  if config.tie_word_embeddings:
286
  self.lm_head.weight = self.model.embed_tokens.weight
287
 
@@ -293,18 +280,18 @@ class AlinlightForCausalLM(PreTrainedModel, GenerationMixin):
293
  def set_output_embeddings(self, new_embeddings): self.lm_head = new_embeddings
294
 
295
  def prepare_inputs_for_generation(self, input_ids, past_key_values=None, **kwargs):
296
- # Если есть кэш, нам нужен только последний токен из input_ids
297
  if past_key_values:
298
  input_ids = input_ids[:, -1:]
299
 
300
  position_ids = kwargs.get("position_ids", None)
301
  if position_ids is None:
302
  if past_key_values:
303
- # Если есть кэш, позиция = длина кэша
304
  past_length = past_key_values[0][0].shape[2]
305
  position_ids = torch.tensor([[past_length]], dtype=torch.long, device=input_ids.device)
306
  else:
307
- # Если кэша нет (первый токен), позиции = [0, 1, 2...]
308
  position_ids = torch.arange(input_ids.shape[1], dtype=torch.long, device=input_ids.device).unsqueeze(0)
309
 
310
  return {
 
13
  # See the License for the specific language governing permissions and
14
  # limitations under the License.
15
 
 
 
 
 
 
16
 
17
  import math
18
  import torch
 
44
  self.max_position_embeddings = max_position_embeddings
45
  self.scaling_factor = scaling_factor
46
 
47
+
48
  inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.float32).to(device) / self.dim))
49
  self.register_buffer("inv_freq", inv_freq, persistent=False)
50
 
51
+
52
  self._set_cos_sin_cache(seq_len=max_position_embeddings, device=device, dtype=torch.get_default_dtype())
53
 
54
  def _set_cos_sin_cache(self, seq_len, device, dtype):
55
+
56
  t = torch.arange(seq_len, device=device, dtype=torch.int64).type_as(self.inv_freq)
57
  t = t / self.scaling_factor
58
  freqs = torch.outer(t, self.inv_freq)
 
61
  self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
62
 
63
  def forward(self, x, seq_len=None):
64
+
65
  if seq_len > self.cos_cached.shape[0]:
66
  self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
67
 
 
140
  key_states = torch.cat([past_key_value[0], key_states], dim=2)
141
  value_states = torch.cat([past_key_value[1], value_states], dim=2)
142
 
143
+
 
144
  if self.sliding_window is not None and key_states.shape[2] > self.sliding_window:
145
  key_states = key_states[:, :, -self.sliding_window:, :]
146
  value_states = value_states[:, :, -self.sliding_window:, :]
147
 
148
  past_key_value = (key_states, value_states) if use_cache else None
149
 
150
+
151
  if self.num_key_value_groups > 1:
152
  key_states = key_states[:, :, None, :, :].expand(
153
  bsz, self.num_key_value_heads, self.num_key_value_groups, key_states.shape[-2], self.head_dim
 
157
  bsz, self.num_key_value_heads, self.num_key_value_groups, value_states.shape[-2], self.head_dim
158
  ).reshape(bsz, self.num_heads, value_states.shape[-2], self.head_dim)
159
 
160
+
 
 
 
161
  is_causal = q_len > 1
162
 
163
  attn_output = F.scaled_dot_product_attention(
 
223
  else:
224
  inputs_embeds = kwargs.get("inputs_embeds")
225
 
226
+
227
  seq_len = inputs_embeds.shape[1]
228
  if past_key_values is not None:
229
  seq_len += past_key_values[0][0].shape[2]
230
 
231
+
232
  cos, sin = self.rotary_emb(inputs_embeds, seq_len=seq_len)
233
 
234
  position_ids = kwargs.get("position_ids")
235
  if position_ids is None:
236
+
237
  position_ids = torch.arange(seq_len - inputs_embeds.shape[1], seq_len, dtype=torch.long, device=inputs_embeds.device)
238
  position_ids = position_ids.unsqueeze(0).expand(inputs_embeds.shape[0], -1)
239
 
 
269
  self.model = AlinlightModel(config)
270
  self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
271
 
 
 
 
 
272
  if config.tie_word_embeddings:
273
  self.lm_head.weight = self.model.embed_tokens.weight
274
 
 
280
  def set_output_embeddings(self, new_embeddings): self.lm_head = new_embeddings
281
 
282
  def prepare_inputs_for_generation(self, input_ids, past_key_values=None, **kwargs):
283
+
284
  if past_key_values:
285
  input_ids = input_ids[:, -1:]
286
 
287
  position_ids = kwargs.get("position_ids", None)
288
  if position_ids is None:
289
  if past_key_values:
290
+
291
  past_length = past_key_values[0][0].shape[2]
292
  position_ids = torch.tensor([[past_length]], dtype=torch.long, device=input_ids.device)
293
  else:
294
+
295
  position_ids = torch.arange(input_ids.shape[1], dtype=torch.long, device=input_ids.device).unsqueeze(0)
296
 
297
  return {