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typing import List, Optional, Tuple, Union
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
import torch.nn.functional as F
|
| 11 |
+
import torch.utils.checkpoint
|
| 12 |
+
from torch import nn
|
| 13 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
| 14 |
+
|
| 15 |
+
from transformers.activations import ACT2FN
|
| 16 |
+
from transformers.cache_utils import Cache, DynamicCache
|
| 17 |
+
from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask
|
| 18 |
+
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
|
| 19 |
+
from transformers.modeling_utils import PreTrainedModel
|
| 20 |
+
from transformers.utils import logging
|
| 21 |
+
|
| 22 |
+
from .configuration_kirim import KirimConfig
|
| 23 |
+
|
| 24 |
+
logger = logging.get_logger(__name__)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class KirimRMSNorm(nn.Module):
|
| 28 |
+
def __init__(self, hidden_size, eps=1e-6):
|
| 29 |
+
super().__init__()
|
| 30 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
| 31 |
+
self.variance_epsilon = eps
|
| 32 |
+
|
| 33 |
+
def forward(self, hidden_states):
|
| 34 |
+
input_dtype = hidden_states.dtype
|
| 35 |
+
hidden_states = hidden_states.to(torch.float32)
|
| 36 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
| 37 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
| 38 |
+
return self.weight * hidden_states.to(input_dtype)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class KirimRotaryEmbedding(nn.Module):
|
| 42 |
+
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
|
| 43 |
+
super().__init__()
|
| 44 |
+
self.dim = dim
|
| 45 |
+
self.max_position_embeddings = max_position_embeddings
|
| 46 |
+
self.base = base
|
| 47 |
+
inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
|
| 48 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
| 49 |
+
|
| 50 |
+
@torch.no_grad()
|
| 51 |
+
def forward(self, x, seq_len=None):
|
| 52 |
+
if seq_len > self.max_position_embeddings:
|
| 53 |
+
base = self.base * ((seq_len / self.max_position_embeddings) - 1) + 1
|
| 54 |
+
inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(x.device) / self.dim))
|
| 55 |
+
else:
|
| 56 |
+
inv_freq = self.inv_freq
|
| 57 |
+
|
| 58 |
+
t = torch.arange(seq_len, device=x.device, dtype=inv_freq.dtype)
|
| 59 |
+
freqs = torch.einsum("i,j->ij", t, inv_freq)
|
| 60 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 61 |
+
return emb.cos().to(dtype=x.dtype), emb.sin().to(dtype=x.dtype)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def rotate_half(x):
|
| 65 |
+
x1 = x[..., : x.shape[-1] // 2]
|
| 66 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
| 67 |
+
return torch.cat((-x2, x1), dim=-1)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids):
|
| 71 |
+
cos = cos[position_ids].unsqueeze(1)
|
| 72 |
+
sin = sin[position_ids].unsqueeze(1)
|
| 73 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
| 74 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
| 75 |
+
return q_embed, k_embed
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
class KirimMLP(nn.Module):
|
| 79 |
+
def __init__(self, config):
|
| 80 |
+
super().__init__()
|
| 81 |
+
self.config = config
|
| 82 |
+
self.hidden_size = config.hidden_size
|
| 83 |
+
self.intermediate_size = config.intermediate_size
|
| 84 |
+
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
| 85 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
| 86 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
|
| 87 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
| 88 |
+
|
| 89 |
+
def forward(self, x):
|
| 90 |
+
return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
class KirimAttention(nn.Module):
|
| 94 |
+
def __init__(self, config: KirimConfig, layer_idx: Optional[int] = None):
|
| 95 |
+
super().__init__()
|
| 96 |
+
self.config = config
|
| 97 |
+
self.layer_idx = layer_idx
|
| 98 |
+
self.hidden_size = config.hidden_size
|
| 99 |
+
self.num_heads = config.num_attention_heads
|
| 100 |
+
self.head_dim = self.hidden_size // self.num_heads
|
| 101 |
+
self.num_key_value_heads = config.num_key_value_heads
|
| 102 |
+
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
|
| 103 |
+
self.max_position_embeddings = config.max_position_embeddings
|
| 104 |
+
self.rope_theta = config.rope_theta
|
| 105 |
+
|
| 106 |
+
if (self.head_dim * self.num_heads) != self.hidden_size:
|
| 107 |
+
raise ValueError(
|
| 108 |
+
f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
|
| 109 |
+
f" and `num_heads`: {self.num_heads})."
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
|
| 113 |
+
self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
|
| 114 |
+
self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
|
| 115 |
+
self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
|
| 116 |
+
|
| 117 |
+
self.rotary_emb = KirimRotaryEmbedding(
|
| 118 |
+
self.head_dim,
|
| 119 |
+
max_position_embeddings=self.max_position_embeddings,
|
| 120 |
+
base=self.rope_theta,
|
| 121 |
+
)
|
| 122 |
+
|
| 123 |
+
def forward(
|
| 124 |
+
self,
|
| 125 |
+
hidden_states: torch.Tensor,
|
| 126 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 127 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 128 |
+
past_key_value: Optional[Cache] = None,
|
| 129 |
+
output_attentions: bool = False,
|
| 130 |
+
use_cache: bool = False,
|
| 131 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 132 |
+
bsz, q_len, _ = hidden_states.size()
|
| 133 |
+
|
| 134 |
+
query_states = self.q_proj(hidden_states)
|
| 135 |
+
key_states = self.k_proj(hidden_states)
|
| 136 |
+
value_states = self.v_proj(hidden_states)
|
| 137 |
+
|
| 138 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 139 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 140 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 141 |
+
|
| 142 |
+
kv_seq_len = key_states.shape[-2]
|
| 143 |
+
if past_key_value is not None:
|
| 144 |
+
kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
|
| 145 |
+
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
| 146 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
|
| 147 |
+
|
| 148 |
+
if past_key_value is not None:
|
| 149 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx)
|
| 150 |
+
|
| 151 |
+
key_states = key_states.repeat_interleave(self.num_key_value_groups, dim=1)
|
| 152 |
+
value_states = value_states.repeat_interleave(self.num_key_value_groups, dim=1)
|
| 153 |
+
|
| 154 |
+
attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
|
| 155 |
+
|
| 156 |
+
if attention_mask is not None:
|
| 157 |
+
attn_weights = attn_weights + attention_mask
|
| 158 |
+
|
| 159 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
|
| 160 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
| 161 |
+
|
| 162 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 163 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
|
| 164 |
+
attn_output = self.o_proj(attn_output)
|
| 165 |
+
|
| 166 |
+
return attn_output, attn_weights if output_attentions else None, past_key_value
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
class KirimDecoderLayer(nn.Module):
|
| 170 |
+
def __init__(self, config: KirimConfig, layer_idx: int):
|
| 171 |
+
super().__init__()
|
| 172 |
+
self.hidden_size = config.hidden_size
|
| 173 |
+
self.self_attn = KirimAttention(config=config, layer_idx=layer_idx)
|
| 174 |
+
self.mlp = KirimMLP(config)
|
| 175 |
+
self.input_layernorm = KirimRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 176 |
+
self.post_attention_layernorm = KirimRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 177 |
+
|
| 178 |
+
def forward(
|
| 179 |
+
self,
|
| 180 |
+
hidden_states: torch.Tensor,
|
| 181 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 182 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 183 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
| 184 |
+
output_attentions: Optional[bool] = False,
|
| 185 |
+
use_cache: Optional[bool] = False,
|
| 186 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
| 187 |
+
residual = hidden_states
|
| 188 |
+
hidden_states = self.input_layernorm(hidden_states)
|
| 189 |
+
|
| 190 |
+
hidden_states, self_attn_weights, present_key_value = self.self_attn(
|
| 191 |
+
hidden_states=hidden_states,
|
| 192 |
+
attention_mask=attention_mask,
|
| 193 |
+
position_ids=position_ids,
|
| 194 |
+
past_key_value=past_key_value,
|
| 195 |
+
output_attentions=output_attentions,
|
| 196 |
+
use_cache=use_cache,
|
| 197 |
+
)
|
| 198 |
+
hidden_states = residual + hidden_states
|
| 199 |
+
|
| 200 |
+
residual = hidden_states
|
| 201 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
| 202 |
+
hidden_states = self.mlp(hidden_states)
|
| 203 |
+
hidden_states = residual + hidden_states
|
| 204 |
+
|
| 205 |
+
outputs = (hidden_states,)
|
| 206 |
+
if output_attentions:
|
| 207 |
+
outputs += (self_attn_weights,)
|
| 208 |
+
if use_cache:
|
| 209 |
+
outputs += (present_key_value,)
|
| 210 |
+
|
| 211 |
+
return outputs
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
class KirimPreTrainedModel(PreTrainedModel):
|
| 215 |
+
config_class = KirimConfig
|
| 216 |
+
base_model_prefix = "model"
|
| 217 |
+
supports_gradient_checkpointing = True
|
| 218 |
+
_no_split_modules = ["KirimDecoderLayer"]
|
| 219 |
+
_skip_keys_device_placement = "past_key_values"
|
| 220 |
+
|
| 221 |
+
def _init_weights(self, module):
|
| 222 |
+
std = self.config.initializer_range
|
| 223 |
+
if isinstance(module, nn.Linear):
|
| 224 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 225 |
+
if module.bias is not None:
|
| 226 |
+
module.bias.data.zero_()
|
| 227 |
+
elif isinstance(module, nn.Embedding):
|
| 228 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 229 |
+
if module.padding_idx is not None:
|
| 230 |
+
module.weight.data[module.padding_idx].zero_()
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
class KirimModel(KirimPreTrainedModel):
|
| 234 |
+
def __init__(self, config: KirimConfig):
|
| 235 |
+
super().__init__(config)
|
| 236 |
+
self.padding_idx = config.pad_token_id
|
| 237 |
+
self.vocab_size = config.vocab_size
|
| 238 |
+
|
| 239 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
| 240 |
+
self.layers = nn.ModuleList([KirimDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)])
|
| 241 |
+
self.norm = KirimRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 242 |
+
|
| 243 |
+
self.gradient_checkpointing = False
|
| 244 |
+
self.post_init()
|
| 245 |
+
|
| 246 |
+
def get_input_embeddings(self):
|
| 247 |
+
return self.embed_tokens
|
| 248 |
+
|
| 249 |
+
def set_input_embeddings(self, value):
|
| 250 |
+
self.embed_tokens = value
|
| 251 |
+
|
| 252 |
+
def forward(
|
| 253 |
+
self,
|
| 254 |
+
input_ids: torch.LongTensor = None,
|
| 255 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 256 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 257 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
| 258 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 259 |
+
use_cache: Optional[bool] = None,
|
| 260 |
+
output_attentions: Optional[bool] = None,
|
| 261 |
+
output_hidden_states: Optional[bool] = None,
|
| 262 |
+
return_dict: Optional[bool] = None,
|
| 263 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
| 264 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 265 |
+
output_hidden_states = (
|
| 266 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 267 |
+
)
|
| 268 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 269 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 270 |
+
|
| 271 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 272 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 273 |
+
elif input_ids is not None:
|
| 274 |
+
batch_size, seq_length = input_ids.shape[:2]
|
| 275 |
+
elif inputs_embeds is not None:
|
| 276 |
+
batch_size, seq_length = inputs_embeds.shape[:2]
|
| 277 |
+
else:
|
| 278 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 279 |
+
|
| 280 |
+
past_key_values_length = 0
|
| 281 |
+
if past_key_values is not None:
|
| 282 |
+
past_key_values_length = past_key_values[0][0].shape[2]
|
| 283 |
+
|
| 284 |
+
if position_ids is None:
|
| 285 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
| 286 |
+
position_ids = torch.arange(
|
| 287 |
+
past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
|
| 288 |
+
)
|
| 289 |
+
position_ids = position_ids.unsqueeze(0)
|
| 290 |
+
|
| 291 |
+
if inputs_embeds is None:
|
| 292 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
| 293 |
+
|
| 294 |
+
attention_mask = _prepare_4d_causal_attention_mask(
|
| 295 |
+
attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
|
| 296 |
+
)
|
| 297 |
+
|
| 298 |
+
hidden_states = inputs_embeds
|
| 299 |
+
|
| 300 |
+
all_hidden_states = () if output_hidden_states else None
|
| 301 |
+
all_self_attns = () if output_attentions else None
|
| 302 |
+
next_decoder_cache = () if use_cache else None
|
| 303 |
+
|
| 304 |
+
for idx, decoder_layer in enumerate(self.layers):
|
| 305 |
+
if output_hidden_states:
|
| 306 |
+
all_hidden_states += (hidden_states,)
|
| 307 |
+
|
| 308 |
+
past_key_value = past_key_values[idx] if past_key_values is not None else None
|
| 309 |
+
|
| 310 |
+
if self.gradient_checkpointing and self.training:
|
| 311 |
+
layer_outputs = self._gradient_checkpointing_func(
|
| 312 |
+
decoder_layer.__call__,
|
| 313 |
+
hidden_states,
|
| 314 |
+
attention_mask,
|
| 315 |
+
position_ids,
|
| 316 |
+
past_key_value,
|
| 317 |
+
output_attentions,
|
| 318 |
+
use_cache,
|
| 319 |
+
)
|
| 320 |
+
else:
|
| 321 |
+
layer_outputs = decoder_layer(
|
| 322 |
+
hidden_states,
|
| 323 |
+
attention_mask=attention_mask,
|
| 324 |
+
position_ids=position_ids,
|
| 325 |
+
past_key_value=past_key_value,
|
| 326 |
+
output_attentions=output_attentions,
|
| 327 |
+
use_cache=use_cache,
|
| 328 |
+
)
|
| 329 |
+
|
| 330 |
+
hidden_states = layer_outputs[0]
|
| 331 |
+
|
| 332 |
+
if use_cache:
|
| 333 |
+
next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
|
| 334 |
+
|
| 335 |
+
if output_attentions:
|
| 336 |
+
all_self_attns += (layer_outputs[1],)
|
| 337 |
+
|
| 338 |
+
hidden_states = self.norm(hidden_states)
|
| 339 |
+
|
| 340 |
+
if output_hidden_states:
|
| 341 |
+
all_hidden_states += (hidden_states,)
|
| 342 |
+
|
| 343 |
+
next_cache = next_decoder_cache if use_cache else None
|
| 344 |
+
|
| 345 |
+
if not return_dict:
|
| 346 |
+
return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
|
| 347 |
+
return BaseModelOutputWithPast(
|
| 348 |
+
last_hidden_state=hidden_states,
|
| 349 |
+
past_key_values=next_cache,
|
| 350 |
+
hidden_states=all_hidden_states,
|
| 351 |
+
attentions=all_self_attns,
|
| 352 |
+
)
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
class KirimForCausalLM(KirimPreTrainedModel):
|
| 356 |
+
_tied_weights_keys = ["lm_head.weight"]
|
| 357 |
+
|
| 358 |
+
def __init__(self, config):
|
| 359 |
+
super().__init__(config)
|
| 360 |
+
self.model = KirimModel(config)
|
| 361 |
+
self.vocab_size = config.vocab_size
|
| 362 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 363 |
+
|
| 364 |
+
self.post_init()
|
| 365 |
+
|
| 366 |
+
def get_input_embeddings(self):
|
| 367 |
+
return self.model.embed_tokens
|
| 368 |
+
|
| 369 |
+
def set_input_embeddings(self, value):
|
| 370 |
+
self.model.embed_tokens = value
|
| 371 |
+
|
| 372 |
+
def get_output_embeddings(self):
|
| 373 |
+
return self.lm_head
|
| 374 |
+
|
| 375 |
+
def set_output_embeddings(self, new_embeddings):
|
| 376 |
+
self.lm_head = new_embeddings
|
| 377 |
+
|
| 378 |
+
def set_decoder(self, decoder):
|
| 379 |
+
self.model = decoder
|
| 380 |
+
|
| 381 |
+
def get_decoder(self):
|
| 382 |
+
return self.model
|
| 383 |
+
|
| 384 |
+
def forward(
|
| 385 |
+
self,
|
| 386 |
+
input_ids: torch.LongTensor = None,
|
| 387 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 388 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 389 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
| 390 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 391 |
+
labels: Optional[torch.LongTensor] = None,
|
| 392 |
+
use_cache: Optional[bool] = None,
|
| 393 |
+
output_attentions: Optional[bool] = None,
|
| 394 |
+
output_hidden_states: Optional[bool] = None,
|
| 395 |
+
return_dict: Optional[bool] = None,
|
| 396 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
| 397 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 398 |
+
output_hidden_states = (
|
| 399 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 400 |
+
)
|
| 401 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 402 |
+
|
| 403 |
+
outputs = self.model(
|
| 404 |
+
input_ids=input_ids,
|
| 405 |
+
attention_mask=attention_mask,
|
| 406 |
+
position_ids=position_ids,
|
| 407 |
+
past_key_values=past_key_values,
|
| 408 |
+
inputs_embeds=inputs_embeds,
|
| 409 |
+
use_cache=use_cache,
|
| 410 |
+
output_attentions=output_attentions,
|
| 411 |
+
output_hidden_states=output_hidden_states,
|
| 412 |
+
return_dict=return_dict,
|
| 413 |
+
)
|
| 414 |
+
|
| 415 |
+
hidden_states = outputs[0]
|
| 416 |
+
logits = self.lm_head(hidden_states)
|
| 417 |
+
logits = logits.float()
|
| 418 |
+
|
| 419 |
+
loss = None
|
| 420 |
+
if labels is not None:
|
| 421 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
| 422 |
+
shift_labels = labels[..., 1:].contiguous()
|
| 423 |
+
loss_fct = CrossEntropyLoss()
|
| 424 |
+
shift_logits = shift_logits.view(-1, self.config.vocab_size)
|
| 425 |
+
shift_labels = shift_labels.view(-1)
|
| 426 |
+
shift_labels = shift_labels.to(shift_logits.device)
|
| 427 |
+
loss = loss_fct(shift_logits, shift_labels)
|
| 428 |
+
|
| 429 |
+
if not return_dict:
|
| 430 |
+
output = (logits,) + outputs[1:]
|
| 431 |
+
return (loss,) + output if loss is not None else output
|
| 432 |
+
|
| 433 |
+
return CausalLMOutputWithPast(
|
| 434 |
+
loss=loss,
|
| 435 |
+
logits=logits,
|
| 436 |
+
past_key_values=outputs.past_key_values,
|
| 437 |
+
hidden_states=outputs.hidden_states,
|
| 438 |
+
attentions=outputs.attentions,
|
| 439 |
+
)
|
| 440 |
+
|
| 441 |
+
def prepare_inputs_for_generation(
|
| 442 |
+
self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
|
| 443 |
+
):
|
| 444 |
+
if past_key_values is not None:
|
| 445 |
+
past_length = past_key_values[0][0].shape[2]
|
| 446 |
+
if input_ids.shape[1] > past_length:
|
| 447 |
+
remove_prefix_length = past_length
|
| 448 |
+
else:
|
| 449 |
+
remove_prefix_length = input_ids.shape[1] - 1
|
| 450 |
+
input_ids = input_ids[:, remove_prefix_length:]
|
| 451 |
+
|
| 452 |
+
position_ids = kwargs.get("position_ids", None)
|
| 453 |
+
if attention_mask is not None and position_ids is None:
|
| 454 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
| 455 |
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
| 456 |
+
if past_key_values:
|
| 457 |
+
position_ids = position_ids[:, -input_ids.shape[1] :]
|
| 458 |
+
|
| 459 |
+
if inputs_embeds is not None and past_key_values is None:
|
| 460 |
+
model_inputs = {"inputs_embeds": inputs_embeds}
|
| 461 |
+
else:
|
| 462 |
+
model_inputs = {"input_ids": input_ids}
|
| 463 |
+
|
| 464 |
+
model_inputs.update(
|
| 465 |
+
{
|
| 466 |
+
"position_ids": position_ids,
|
| 467 |
+
"past_key_values": past_key_values,
|
| 468 |
+
"use_cache": kwargs.get("use_cache"),
|
| 469 |
+
"attention_mask": attention_mask,
|
| 470 |
+
}
|
| 471 |
+
)
|
| 472 |
+
return model_inputs
|
| 473 |
+
|
| 474 |
+
@staticmethod
|
| 475 |
+
def _reorder_cache(past_key_values, beam_idx):
|
| 476 |
+
reordered_past = ()
|
| 477 |
+
for layer_past in past_key_values:
|
| 478 |
+
reordered_past += (
|
| 479 |
+
tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
|
| 480 |
+
)
|
| 481 |
+
return reordered_past
|