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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Optional, Tuple, List
|
| 2 |
+
|
| 3 |
+
import math
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn as nn
|
| 6 |
+
import torch.nn.functional as F
|
| 7 |
+
|
| 8 |
+
from transformers import PreTrainedModel
|
| 9 |
+
from transformers.generation.utils import GenerationMixin
|
| 10 |
+
from transformers.modeling_outputs import CausalLMOutputWithPast
|
| 11 |
+
|
| 12 |
+
from .configuration_veronica import VeronicaConfig
|
| 13 |
+
from .modeling_components import PolymorphicMLP, router_aux_loss, Fp32LayerNorm, apply_rotary_pos_emb
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class MultiHeadSelfAttention(nn.Module):
|
| 17 |
+
def __init__(self, hidden_size: int, num_heads: int, dropout: float = 0.0, max_position_embeddings: int = 4096, rope_theta: float = 10000.0):
|
| 18 |
+
super().__init__()
|
| 19 |
+
assert hidden_size % num_heads == 0, "hidden_size must be divisible by n_head"
|
| 20 |
+
self.num_heads = num_heads
|
| 21 |
+
self.head_dim = hidden_size // num_heads
|
| 22 |
+
self.scale = 1.0 / math.sqrt(self.head_dim)
|
| 23 |
+
self.max_position_embeddings = max_position_embeddings
|
| 24 |
+
self.rope_theta = rope_theta
|
| 25 |
+
|
| 26 |
+
self.qkv = nn.Linear(hidden_size, 3 * hidden_size)
|
| 27 |
+
self.out_proj = nn.Linear(hidden_size, hidden_size)
|
| 28 |
+
self.attn_drop = nn.Dropout(dropout)
|
| 29 |
+
self.resid_drop = nn.Dropout(dropout)
|
| 30 |
+
|
| 31 |
+
# Precomputa RoPE frequencies
|
| 32 |
+
self._rope_cached_seq_len = 0
|
| 33 |
+
self._rope_cos_cached = None
|
| 34 |
+
self._rope_sin_cached = None
|
| 35 |
+
|
| 36 |
+
def _split_heads(self, x: torch.Tensor) -> torch.Tensor:
|
| 37 |
+
B, T, C = x.shape
|
| 38 |
+
x = x.view(B, T, self.num_heads, self.head_dim).transpose(1, 2) # (B, nh, T, hd)
|
| 39 |
+
return x
|
| 40 |
+
|
| 41 |
+
def _merge_heads(self, x: torch.Tensor) -> torch.Tensor:
|
| 42 |
+
B, nh, T, hd = x.shape
|
| 43 |
+
return x.transpose(1, 2).contiguous().view(B, T, nh * hd)
|
| 44 |
+
|
| 45 |
+
def _get_rope_cos_sin(self, seq_len: int, device: torch.device, dtype: torch.dtype) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 46 |
+
"""Genera o recupera dalla cache cos/sin per RoPE."""
|
| 47 |
+
if seq_len <= self._rope_cached_seq_len and self._rope_cos_cached is not None:
|
| 48 |
+
return self._rope_cos_cached[:, :, :seq_len, :].to(device=device, dtype=dtype), \
|
| 49 |
+
self._rope_sin_cached[:, :, :seq_len, :].to(device=device, dtype=dtype)
|
| 50 |
+
|
| 51 |
+
# Genera nuove frequenze
|
| 52 |
+
self._rope_cached_seq_len = max(seq_len, self.max_position_embeddings)
|
| 53 |
+
|
| 54 |
+
# inv_freq: (hd/2,)
|
| 55 |
+
dim = self.head_dim
|
| 56 |
+
inv_freq = 1.0 / (self.rope_theta ** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim))
|
| 57 |
+
|
| 58 |
+
# t: (seq_len,)
|
| 59 |
+
t = torch.arange(self._rope_cached_seq_len, dtype=torch.float32, device=device)
|
| 60 |
+
|
| 61 |
+
# freqs: (seq_len, hd/2)
|
| 62 |
+
freqs = torch.outer(t, inv_freq)
|
| 63 |
+
|
| 64 |
+
# Duplica per avere shape (seq_len, hd)
|
| 65 |
+
emb = torch.cat([freqs, freqs], dim=-1) # (seq_len, hd)
|
| 66 |
+
|
| 67 |
+
# cos, sin: (1, 1, seq_len, hd)
|
| 68 |
+
cos = emb.cos().unsqueeze(0).unsqueeze(0)
|
| 69 |
+
sin = emb.sin().unsqueeze(0).unsqueeze(0)
|
| 70 |
+
|
| 71 |
+
self._rope_cos_cached = cos
|
| 72 |
+
self._rope_sin_cached = sin
|
| 73 |
+
|
| 74 |
+
return cos[:, :, :seq_len, :].to(dtype=dtype), sin[:, :, :seq_len, :].to(dtype=dtype)
|
| 75 |
+
|
| 76 |
+
def forward(
|
| 77 |
+
self,
|
| 78 |
+
x: torch.Tensor,
|
| 79 |
+
attn_mask: Optional[torch.Tensor] = None, # additive mask [B,1,T,S] in float32
|
| 80 |
+
past_key_value: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
|
| 81 |
+
use_cache: bool = False,
|
| 82 |
+
position_offset: int = 0, # offset per posizione (per KV cache)
|
| 83 |
+
) -> Tuple[torch.Tensor, Optional[Tuple[torch.Tensor, torch.Tensor]]]:
|
| 84 |
+
B, T, C = x.shape
|
| 85 |
+
qkv = self.qkv(x)
|
| 86 |
+
q, k, v = qkv.split(C, dim=-1)
|
| 87 |
+
q = self._split_heads(q) # (B, nh, T, hd)
|
| 88 |
+
k = self._split_heads(k)
|
| 89 |
+
v = self._split_heads(v)
|
| 90 |
+
|
| 91 |
+
# Applica RoPE a q e k
|
| 92 |
+
cos, sin = self._get_rope_cos_sin(position_offset + T, q.device, q.dtype)
|
| 93 |
+
# Prendi solo le posizioni rilevanti [position_offset : position_offset+T]
|
| 94 |
+
cos = cos[:, :, position_offset:position_offset+T, :]
|
| 95 |
+
sin = sin[:, :, position_offset:position_offset+T, :]
|
| 96 |
+
q, k = apply_rotary_pos_emb(q, k, cos, sin)
|
| 97 |
+
|
| 98 |
+
present = None
|
| 99 |
+
if past_key_value is not None:
|
| 100 |
+
pk, pv = past_key_value # (B, nh, Tp, hd)
|
| 101 |
+
k = torch.cat([pk, k], dim=-2)
|
| 102 |
+
v = torch.cat([pv, v], dim=-2)
|
| 103 |
+
if use_cache:
|
| 104 |
+
present = (k, v)
|
| 105 |
+
|
| 106 |
+
att = (q @ k.transpose(-2, -1)) * self.scale # (B, nh, T, S)
|
| 107 |
+
att = att.float()
|
| 108 |
+
if attn_mask is not None:
|
| 109 |
+
att = att + attn_mask # additive bias: -inf on masked pos
|
| 110 |
+
att = F.softmax(att, dim=-1)
|
| 111 |
+
att = self.attn_drop(att)
|
| 112 |
+
att = att.to(v.dtype) # Cast back to match v's dtype (BF16/FP16/FP32)
|
| 113 |
+
y = att @ v # (B, nh, T, hd)
|
| 114 |
+
y = self._merge_heads(y)
|
| 115 |
+
y = self.out_proj(y)
|
| 116 |
+
y = self.resid_drop(y)
|
| 117 |
+
return y, present
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
class VeronicaBlock(nn.Module):
|
| 121 |
+
def __init__(self, config: VeronicaConfig):
|
| 122 |
+
super().__init__()
|
| 123 |
+
self.ln_1 = Fp32LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
|
| 124 |
+
self.attn = MultiHeadSelfAttention(
|
| 125 |
+
config.n_embd,
|
| 126 |
+
config.n_head,
|
| 127 |
+
dropout=config.dropout,
|
| 128 |
+
max_position_embeddings=config.max_position_embeddings,
|
| 129 |
+
rope_theta=getattr(config, 'rope_theta', 10000.0)
|
| 130 |
+
)
|
| 131 |
+
self.ln_2 = Fp32LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
|
| 132 |
+
self.mlp = PolymorphicMLP(
|
| 133 |
+
hidden_size=config.n_embd,
|
| 134 |
+
mlp_mult=config.mlp_mult,
|
| 135 |
+
num_funcs=config.num_funcs,
|
| 136 |
+
router_dim=config.router_dim,
|
| 137 |
+
dropout=config.dropout,
|
| 138 |
+
use_channel_attention=config.use_channel_attention,
|
| 139 |
+
router_tau=config.router_tau,
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
def forward(
|
| 143 |
+
self,
|
| 144 |
+
x: torch.Tensor,
|
| 145 |
+
attn_mask: Optional[torch.Tensor] = None,
|
| 146 |
+
past_key_value: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
|
| 147 |
+
use_cache: bool = False,
|
| 148 |
+
position_offset: int = 0,
|
| 149 |
+
) -> Tuple[torch.Tensor, torch.Tensor, Optional[Tuple[torch.Tensor, torch.Tensor]]]:
|
| 150 |
+
h = self.ln_1(x)
|
| 151 |
+
attn_out, present = self.attn(h, attn_mask, past_key_value=past_key_value, use_cache=use_cache, position_offset=position_offset)
|
| 152 |
+
x = x + attn_out
|
| 153 |
+
h = self.ln_2(x)
|
| 154 |
+
y, alpha = self.mlp(h)
|
| 155 |
+
x = x + y
|
| 156 |
+
return x, alpha, present
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
class VeronicaModel(PreTrainedModel):
|
| 160 |
+
config_class = VeronicaConfig
|
| 161 |
+
|
| 162 |
+
def __init__(self, config: VeronicaConfig):
|
| 163 |
+
super().__init__(config)
|
| 164 |
+
self.embed_dim = config.n_embd
|
| 165 |
+
self.wte = nn.Embedding(config.vocab_size, config.n_embd)
|
| 166 |
+
# RoPE sostituisce positional embeddings assoluti (wpe rimosso)
|
| 167 |
+
self.drop = nn.Dropout(config.dropout)
|
| 168 |
+
self.blocks = nn.ModuleList([VeronicaBlock(config) for _ in range(config.n_layer)])
|
| 169 |
+
self.ln_f = Fp32LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
|
| 170 |
+
|
| 171 |
+
self.register_buffer(
|
| 172 |
+
"causal_mask",
|
| 173 |
+
torch.tril(
|
| 174 |
+
torch.ones(
|
| 175 |
+
config.max_position_embeddings,
|
| 176 |
+
config.max_position_embeddings,
|
| 177 |
+
dtype=torch.uint8,
|
| 178 |
+
)
|
| 179 |
+
).view(1, 1, config.max_position_embeddings, config.max_position_embeddings),
|
| 180 |
+
persistent=False,
|
| 181 |
+
)
|
| 182 |
+
|
| 183 |
+
# Monitoring
|
| 184 |
+
self.router_alpha_entropy: Optional[torch.Tensor] = None
|
| 185 |
+
self.router_alpha_mean: Optional[torch.Tensor] = None
|
| 186 |
+
|
| 187 |
+
self._use_gradient_checkpointing: bool = getattr(config, "gradient_checkpointing", False)
|
| 188 |
+
|
| 189 |
+
def get_input_embeddings(self):
|
| 190 |
+
return self.wte
|
| 191 |
+
|
| 192 |
+
def set_input_embeddings(self, value):
|
| 193 |
+
self.wte = value
|
| 194 |
+
|
| 195 |
+
def gradient_checkpointing_enable(self, gradient_checkpointing_kwargs=None):
|
| 196 |
+
self._use_gradient_checkpointing = True
|
| 197 |
+
|
| 198 |
+
def gradient_checkpointing_disable(self):
|
| 199 |
+
self._use_gradient_checkpointing = False
|
| 200 |
+
|
| 201 |
+
def _build_attn_mask(
|
| 202 |
+
self,
|
| 203 |
+
attention_mask: Optional[torch.Tensor],
|
| 204 |
+
seq_len: int,
|
| 205 |
+
past_kv_len: int,
|
| 206 |
+
device: torch.device,
|
| 207 |
+
dtype: torch.dtype,
|
| 208 |
+
) -> torch.Tensor:
|
| 209 |
+
# Causal mask additiva in float32
|
| 210 |
+
T, P = seq_len, past_kv_len
|
| 211 |
+
causal = torch.full((T, T + P), float("-inf"), device=device, dtype=dtype)
|
| 212 |
+
causal = torch.triu(causal, diagonal=1 + P) # -inf per future, 0 altrove
|
| 213 |
+
|
| 214 |
+
if attention_mask is None:
|
| 215 |
+
return causal.unsqueeze(0).unsqueeze(1) # [1,1,T,T+P]
|
| 216 |
+
|
| 217 |
+
# attention_mask shape: [B, T+P] (0 pad, 1 valid)
|
| 218 |
+
attn_full = attention_mask.to(dtype)
|
| 219 |
+
pad_add = (1.0 - attn_full) * torch.finfo(dtype).min # [B, T+P]
|
| 220 |
+
pad_add = pad_add.unsqueeze(1).unsqueeze(2) # [B,1,1,T+P]
|
| 221 |
+
causal = causal.unsqueeze(0).unsqueeze(1) # [1,1,T,T+P]
|
| 222 |
+
return causal + pad_add
|
| 223 |
+
|
| 224 |
+
def forward(
|
| 225 |
+
self,
|
| 226 |
+
input_ids: torch.LongTensor,
|
| 227 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 228 |
+
labels: Optional[torch.LongTensor] = None,
|
| 229 |
+
output_router_stats: bool = True,
|
| 230 |
+
past_key_values: Optional[List[Tuple[torch.Tensor, torch.Tensor]]] = None,
|
| 231 |
+
use_cache: Optional[bool] = None,
|
| 232 |
+
**kwargs,
|
| 233 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[List[Tuple[torch.Tensor, torch.Tensor]]]]:
|
| 234 |
+
device = input_ids.device
|
| 235 |
+
B, T = input_ids.shape
|
| 236 |
+
|
| 237 |
+
if use_cache is None:
|
| 238 |
+
use_cache = False if self.training else True
|
| 239 |
+
|
| 240 |
+
pkv_list: Optional[List[Tuple[torch.Tensor, torch.Tensor]]] = [] if use_cache else None
|
| 241 |
+
|
| 242 |
+
P = 0
|
| 243 |
+
if (
|
| 244 |
+
past_key_values is not None
|
| 245 |
+
and len(past_key_values) > 0
|
| 246 |
+
and past_key_values[0] is not None
|
| 247 |
+
and isinstance(past_key_values[0], (tuple, list))
|
| 248 |
+
and past_key_values[0][0] is not None
|
| 249 |
+
):
|
| 250 |
+
P = past_key_values[0][0].size(-2)
|
| 251 |
+
|
| 252 |
+
# Solo token embeddings (RoPE gestisce le posizioni)
|
| 253 |
+
x = self.wte(input_ids)
|
| 254 |
+
x = self.drop(x)
|
| 255 |
+
|
| 256 |
+
# attention_mask full [B, T+P]
|
| 257 |
+
attn_full = None
|
| 258 |
+
if attention_mask is not None:
|
| 259 |
+
if attention_mask.size(-1) == T + P:
|
| 260 |
+
attn_full = attention_mask
|
| 261 |
+
elif attention_mask.size(-1) == T:
|
| 262 |
+
if P > 0:
|
| 263 |
+
ones = torch.ones((B, P), dtype=attention_mask.dtype, device=attention_mask.device)
|
| 264 |
+
attn_full = torch.cat([ones, attention_mask], dim=-1)
|
| 265 |
+
else:
|
| 266 |
+
attn_full = attention_mask
|
| 267 |
+
else:
|
| 268 |
+
attn_full = None
|
| 269 |
+
|
| 270 |
+
attn_bias = self._build_attn_mask(attn_full, T, P, device, torch.float32)
|
| 271 |
+
|
| 272 |
+
alpha_list: List[torch.Tensor] = []
|
| 273 |
+
if self.training:
|
| 274 |
+
self._acc_aux_sum = 0.0
|
| 275 |
+
self._acc_aux_count = 0
|
| 276 |
+
|
| 277 |
+
if getattr(self, "_use_gradient_checkpointing", False) and self.training:
|
| 278 |
+
def create_custom_forward(module, pkv):
|
| 279 |
+
def custom_forward(x):
|
| 280 |
+
out_x, out_alpha, _ = module(x, attn_bias, past_key_value=pkv, use_cache=False, position_offset=P)
|
| 281 |
+
return out_x, out_alpha
|
| 282 |
+
|
| 283 |
+
return custom_forward
|
| 284 |
+
|
| 285 |
+
if past_key_values is not None:
|
| 286 |
+
curr_past = [
|
| 287 |
+
pkv
|
| 288 |
+
if (pkv is not None and isinstance(pkv, (tuple, list)) and pkv[0] is not None and pkv[1] is not None)
|
| 289 |
+
else None
|
| 290 |
+
for pkv in past_key_values
|
| 291 |
+
]
|
| 292 |
+
else:
|
| 293 |
+
curr_past = [None] * len(self.blocks)
|
| 294 |
+
for layer_idx, block in enumerate(self.blocks):
|
| 295 |
+
x, alpha = torch.utils.checkpoint.checkpoint(
|
| 296 |
+
create_custom_forward(block, curr_past[layer_idx]), x, use_reentrant=False
|
| 297 |
+
)
|
| 298 |
+
alpha_list.append(alpha)
|
| 299 |
+
if self.training and getattr(block.mlp, "last_aux", None) is not None:
|
| 300 |
+
self._acc_aux_sum = self._acc_aux_sum + block.mlp.last_aux
|
| 301 |
+
self._acc_aux_count += 1
|
| 302 |
+
else:
|
| 303 |
+
if past_key_values is not None:
|
| 304 |
+
curr_past = [
|
| 305 |
+
pkv
|
| 306 |
+
if (pkv is not None and isinstance(pkv, (tuple, list)) and pkv[0] is not None and pkv[1] is not None)
|
| 307 |
+
else None
|
| 308 |
+
for pkv in past_key_values
|
| 309 |
+
]
|
| 310 |
+
else:
|
| 311 |
+
curr_past = [None] * len(self.blocks)
|
| 312 |
+
for layer_idx, block in enumerate(self.blocks):
|
| 313 |
+
x, alpha, present = block(x, attn_bias, past_key_value=curr_past[layer_idx], use_cache=use_cache, position_offset=P)
|
| 314 |
+
alpha_list.append(alpha)
|
| 315 |
+
if self.training and getattr(block.mlp, "last_aux", None) is not None:
|
| 316 |
+
self._acc_aux_sum = self._acc_aux_sum + block.mlp.last_aux
|
| 317 |
+
self._acc_aux_count += 1
|
| 318 |
+
if use_cache and pkv_list is not None:
|
| 319 |
+
pkv_list.append(present)
|
| 320 |
+
|
| 321 |
+
x = self.ln_f(x)
|
| 322 |
+
|
| 323 |
+
# Router stats
|
| 324 |
+
if output_router_stats and len(alpha_list) > 0:
|
| 325 |
+
alpha_stack = torch.stack(alpha_list, dim=0) # (L, B, T, K)
|
| 326 |
+
alpha_mean = alpha_stack.mean(dim=(0, 1, 2)) # (K,)
|
| 327 |
+
self.router_alpha_mean = alpha_mean.detach()
|
| 328 |
+
self.router_alpha_entropy = router_aux_loss(alpha_stack.mean(dim=0))
|
| 329 |
+
|
| 330 |
+
# Aux-loss medio su profondità
|
| 331 |
+
if hasattr(self, "_acc_aux_sum"):
|
| 332 |
+
if self._acc_aux_count > 0:
|
| 333 |
+
self._last_router_aux = self._acc_aux_sum / self._acc_aux_count
|
| 334 |
+
else:
|
| 335 |
+
self._last_router_aux = None
|
| 336 |
+
delattr(self, "_acc_aux_sum")
|
| 337 |
+
delattr(self, "_acc_aux_count")
|
| 338 |
+
|
| 339 |
+
return x, pkv_list
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
class VeronicaForCausalLM(VeronicaModel, GenerationMixin):
|
| 343 |
+
def __init__(self, config: VeronicaConfig):
|
| 344 |
+
super().__init__(config)
|
| 345 |
+
self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
|
| 346 |
+
self.post_init()
|
| 347 |
+
|
| 348 |
+
def get_output_embeddings(self):
|
| 349 |
+
return self.lm_head
|
| 350 |
+
|
| 351 |
+
def set_output_embeddings(self, new_embeddings):
|
| 352 |
+
self.lm_head = new_embeddings
|
| 353 |
+
|
| 354 |
+
def tie_weights(self):
|
| 355 |
+
self._tie_or_clone_weights(self.lm_head, self.get_input_embeddings())
|
| 356 |
+
|
| 357 |
+
def prepare_inputs_for_generation(
|
| 358 |
+
self,
|
| 359 |
+
input_ids: torch.LongTensor,
|
| 360 |
+
past_key_values: Optional[List[Tuple[torch.Tensor, torch.Tensor]]] = None,
|
| 361 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 362 |
+
**kwargs,
|
| 363 |
+
):
|
| 364 |
+
if past_key_values is not None and len(past_key_values) > 0:
|
| 365 |
+
input_ids = input_ids[:, -1:]
|
| 366 |
+
return {
|
| 367 |
+
"input_ids": input_ids,
|
| 368 |
+
"past_key_values": past_key_values,
|
| 369 |
+
"attention_mask": attention_mask,
|
| 370 |
+
"use_cache": True,
|
| 371 |
+
}
|
| 372 |
+
|
| 373 |
+
def _reorder_cache(self, past_key_values, beam_idx: torch.LongTensor):
|
| 374 |
+
if past_key_values is None:
|
| 375 |
+
return past_key_values
|
| 376 |
+
reordered = []
|
| 377 |
+
for (k, v) in past_key_values:
|
| 378 |
+
reordered.append((k.index_select(0, beam_idx), v.index_select(0, beam_idx)))
|
| 379 |
+
return reordered
|
| 380 |
+
|
| 381 |
+
def forward(
|
| 382 |
+
self,
|
| 383 |
+
input_ids: torch.LongTensor,
|
| 384 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 385 |
+
labels: Optional[torch.LongTensor] = None,
|
| 386 |
+
use_cache: Optional[bool] = None,
|
| 387 |
+
past_key_values: Optional[List[Tuple[torch.Tensor, torch.Tensor]]] = None,
|
| 388 |
+
**kwargs,
|
| 389 |
+
) -> CausalLMOutputWithPast:
|
| 390 |
+
hidden_states, present = super().forward(
|
| 391 |
+
input_ids=input_ids,
|
| 392 |
+
attention_mask=attention_mask,
|
| 393 |
+
labels=None,
|
| 394 |
+
use_cache=use_cache,
|
| 395 |
+
past_key_values=past_key_values,
|
| 396 |
+
**kwargs,
|
| 397 |
+
) # (B, T, H)
|
| 398 |
+
logits = self.lm_head(hidden_states)
|
| 399 |
+
|
| 400 |
+
loss = None
|
| 401 |
+
if labels is not None:
|
| 402 |
+
shift_logits = logits[:, :-1, :].contiguous()
|
| 403 |
+
shift_labels = labels[:, 1:].contiguous()
|
| 404 |
+
loss = F.cross_entropy(
|
| 405 |
+
shift_logits.view(-1, shift_logits.size(-1)),
|
| 406 |
+
shift_labels.view(-1),
|
| 407 |
+
ignore_index=-100,
|
| 408 |
+
)
|
| 409 |
+
|
| 410 |
+
aux = getattr(self, "_last_router_aux", None)
|
| 411 |
+
if aux is not None and getattr(self.config, "router_aux_weight", 0.0) > 0:
|
| 412 |
+
if not torch.is_tensor(aux):
|
| 413 |
+
aux = torch.as_tensor(aux, device=logits.device, dtype=logits.dtype)
|
| 414 |
+
else:
|
| 415 |
+
aux = aux.to(device=logits.device, dtype=logits.dtype)
|
| 416 |
+
aux = aux.clamp_min(0.0)
|
| 417 |
+
loss = loss + float(self.config.router_aux_weight) * aux
|
| 418 |
+
|
| 419 |
+
return CausalLMOutputWithPast(
|
| 420 |
+
loss=loss,
|
| 421 |
+
logits=logits,
|
| 422 |
+
past_key_values=present if use_cache else None,
|
| 423 |
+
hidden_states=None,
|
| 424 |
+
attentions=None,
|
| 425 |
+
)
|