Update modeling_alinlight.py
Browse files- modeling_alinlight.py +30 -5
modeling_alinlight.py
CHANGED
|
@@ -16,6 +16,9 @@
|
|
| 16 |
# -*- coding: utf-8 -*-
|
| 17 |
# Copyright 2026 EngineerGL Research.
|
| 18 |
|
|
|
|
|
|
|
|
|
|
| 19 |
import math
|
| 20 |
import torch
|
| 21 |
import torch.nn as nn
|
|
@@ -46,11 +49,15 @@ class AlinlightRotaryEmbedding(nn.Module):
|
|
| 46 |
self.max_position_embeddings = max_position_embeddings
|
| 47 |
self.scaling_factor = scaling_factor
|
| 48 |
|
|
|
|
| 49 |
inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.float32).to(device) / self.dim))
|
| 50 |
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
|
|
|
|
|
|
| 51 |
self._set_cos_sin_cache(seq_len=max_position_embeddings, device=device, dtype=torch.get_default_dtype())
|
| 52 |
|
| 53 |
def _set_cos_sin_cache(self, seq_len, device, dtype):
|
|
|
|
| 54 |
t = torch.arange(seq_len, device=device, dtype=torch.int64).type_as(self.inv_freq)
|
| 55 |
t = t / self.scaling_factor
|
| 56 |
freqs = torch.outer(t, self.inv_freq)
|
|
@@ -59,8 +66,10 @@ class AlinlightRotaryEmbedding(nn.Module):
|
|
| 59 |
self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
|
| 60 |
|
| 61 |
def forward(self, x, seq_len=None):
|
|
|
|
| 62 |
if seq_len > self.cos_cached.shape[0]:
|
| 63 |
self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
|
|
|
|
| 64 |
return (
|
| 65 |
self.cos_cached[:seq_len].to(dtype=x.dtype, device=x.device),
|
| 66 |
self.sin_cached[:seq_len].to(dtype=x.dtype, device=x.device)
|
|
@@ -136,13 +145,15 @@ class AlinlightAttention(nn.Module):
|
|
| 136 |
key_states = torch.cat([past_key_value[0], key_states], dim=2)
|
| 137 |
value_states = torch.cat([past_key_value[1], value_states], dim=2)
|
| 138 |
|
| 139 |
-
#
|
|
|
|
| 140 |
if self.sliding_window is not None and key_states.shape[2] > self.sliding_window:
|
| 141 |
key_states = key_states[:, :, -self.sliding_window:, :]
|
| 142 |
value_states = value_states[:, :, -self.sliding_window:, :]
|
| 143 |
|
| 144 |
past_key_value = (key_states, value_states) if use_cache else None
|
| 145 |
|
|
|
|
| 146 |
if self.num_key_value_groups > 1:
|
| 147 |
key_states = key_states[:, :, None, :, :].expand(
|
| 148 |
bsz, self.num_key_value_heads, self.num_key_value_groups, key_states.shape[-2], self.head_dim
|
|
@@ -152,9 +163,10 @@ class AlinlightAttention(nn.Module):
|
|
| 152 |
bsz, self.num_key_value_heads, self.num_key_value_groups, value_states.shape[-2], self.head_dim
|
| 153 |
).reshape(bsz, self.num_heads, value_states.shape[-2], self.head_dim)
|
| 154 |
|
| 155 |
-
#
|
| 156 |
-
#
|
| 157 |
-
#
|
|
|
|
| 158 |
is_causal = q_len > 1
|
| 159 |
|
| 160 |
attn_output = F.scaled_dot_product_attention(
|
|
@@ -220,14 +232,17 @@ class AlinlightModel(PreTrainedModel):
|
|
| 220 |
else:
|
| 221 |
inputs_embeds = kwargs.get("inputs_embeds")
|
| 222 |
|
|
|
|
| 223 |
seq_len = inputs_embeds.shape[1]
|
| 224 |
if past_key_values is not None:
|
| 225 |
seq_len += past_key_values[0][0].shape[2]
|
| 226 |
|
|
|
|
| 227 |
cos, sin = self.rotary_emb(inputs_embeds, seq_len=seq_len)
|
| 228 |
|
| 229 |
position_ids = kwargs.get("position_ids")
|
| 230 |
if position_ids is None:
|
|
|
|
| 231 |
position_ids = torch.arange(seq_len - inputs_embeds.shape[1], seq_len, dtype=torch.long, device=inputs_embeds.device)
|
| 232 |
position_ids = position_ids.unsqueeze(0).expand(inputs_embeds.shape[0], -1)
|
| 233 |
|
|
@@ -262,7 +277,14 @@ class AlinlightForCausalLM(PreTrainedModel, GenerationMixin):
|
|
| 262 |
super().__init__(config)
|
| 263 |
self.model = AlinlightModel(config)
|
| 264 |
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 265 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 266 |
self.post_init()
|
| 267 |
|
| 268 |
def get_input_embeddings(self): return self.model.embed_tokens
|
|
@@ -271,15 +293,18 @@ class AlinlightForCausalLM(PreTrainedModel, GenerationMixin):
|
|
| 271 |
def set_output_embeddings(self, new_embeddings): self.lm_head = new_embeddings
|
| 272 |
|
| 273 |
def prepare_inputs_for_generation(self, input_ids, past_key_values=None, **kwargs):
|
|
|
|
| 274 |
if past_key_values:
|
| 275 |
input_ids = input_ids[:, -1:]
|
| 276 |
|
| 277 |
position_ids = kwargs.get("position_ids", None)
|
| 278 |
if position_ids is None:
|
| 279 |
if past_key_values:
|
|
|
|
| 280 |
past_length = past_key_values[0][0].shape[2]
|
| 281 |
position_ids = torch.tensor([[past_length]], dtype=torch.long, device=input_ids.device)
|
| 282 |
else:
|
|
|
|
| 283 |
position_ids = torch.arange(input_ids.shape[1], dtype=torch.long, device=input_ids.device).unsqueeze(0)
|
| 284 |
|
| 285 |
return {
|
|
|
|
| 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
|
| 24 |
import torch.nn as nn
|
|
|
|
| 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 |
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 |
+
|
| 73 |
return (
|
| 74 |
self.cos_cached[:seq_len].to(dtype=x.dtype, device=x.device),
|
| 75 |
self.sin_cached[:seq_len].to(dtype=x.dtype, device=x.device)
|
|
|
|
| 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 |
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 |
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 |
|
|
|
|
| 277 |
super().__init__(config)
|
| 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 |
+
|
| 288 |
self.post_init()
|
| 289 |
|
| 290 |
def get_input_embeddings(self): return self.model.embed_tokens
|
|
|
|
| 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 {
|