Delete modeling_shell.py
Browse files- modeling_shell.py +0 -858
modeling_shell.py
DELETED
|
@@ -1,858 +0,0 @@
|
|
| 1 |
-
# coding=utf-8
|
| 2 |
-
# Copyright 2023 The Bigcode team and HuggingFace Inc. team.
|
| 3 |
-
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
-
# you may not use this file except in compliance with the License.
|
| 5 |
-
# You may obtain a copy of the License at
|
| 6 |
-
#
|
| 7 |
-
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
-
#
|
| 9 |
-
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
-
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
-
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
-
# See the License for the specific language governing permissions and
|
| 13 |
-
# limitations under the License.
|
| 14 |
-
"""PyTorch Shell model."""
|
| 15 |
-
import math
|
| 16 |
-
from typing import List, Optional, Tuple, Union
|
| 17 |
-
|
| 18 |
-
import torch
|
| 19 |
-
import torch.utils.checkpoint
|
| 20 |
-
from torch import nn
|
| 21 |
-
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
| 22 |
-
|
| 23 |
-
from transformers.activations import ACT2FN
|
| 24 |
-
from transformers.modeling_outputs import (
|
| 25 |
-
BaseModelOutputWithPastAndCrossAttentions,
|
| 26 |
-
CausalLMOutputWithCrossAttentions,
|
| 27 |
-
)
|
| 28 |
-
from transformers.modeling_utils import PreTrainedModel
|
| 29 |
-
from transformers.utils import (
|
| 30 |
-
add_start_docstrings,
|
| 31 |
-
add_start_docstrings_to_model_forward,
|
| 32 |
-
logging,
|
| 33 |
-
)
|
| 34 |
-
from .configuration_shell import ShellConfig
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
logger = logging.get_logger(__name__)
|
| 38 |
-
|
| 39 |
-
# Fused kernels
|
| 40 |
-
# Use separate functions for each case because conditionals prevent kernel fusion.
|
| 41 |
-
# TODO: Could have better fused kernels depending on scaling, dropout and head mask.
|
| 42 |
-
# Is it doable without writing 32 functions?
|
| 43 |
-
@torch.jit.script
|
| 44 |
-
def upcast_masked_softmax(
|
| 45 |
-
x: torch.Tensor, mask: torch.Tensor, mask_value: torch.Tensor, scale: float, softmax_dtype: torch.dtype
|
| 46 |
-
):
|
| 47 |
-
input_dtype = x.dtype
|
| 48 |
-
x = x.to(softmax_dtype) * scale
|
| 49 |
-
x = torch.where(mask, x, mask_value)
|
| 50 |
-
x = torch.nn.functional.softmax(x, dim=-1).to(input_dtype)
|
| 51 |
-
return x
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
@torch.jit.script
|
| 55 |
-
def upcast_softmax(x: torch.Tensor, scale: float, softmax_dtype: torch.dtype):
|
| 56 |
-
input_dtype = x.dtype
|
| 57 |
-
x = x.to(softmax_dtype) * scale
|
| 58 |
-
x = torch.nn.functional.softmax(x, dim=-1).to(input_dtype)
|
| 59 |
-
return x
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
@torch.jit.script
|
| 63 |
-
def masked_softmax(x: torch.Tensor, mask: torch.Tensor, mask_value: torch.Tensor):
|
| 64 |
-
x = torch.where(mask, x, mask_value)
|
| 65 |
-
x = torch.nn.functional.softmax(x, dim=-1)
|
| 66 |
-
return x
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
class ShellRotaryEmbedding(torch.nn.Module):
|
| 70 |
-
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
|
| 71 |
-
super().__init__()
|
| 72 |
-
|
| 73 |
-
self.dim = dim
|
| 74 |
-
self.max_position_embeddings = max_position_embeddings
|
| 75 |
-
self.base = base
|
| 76 |
-
inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
|
| 77 |
-
self.register_buffer("inv_freq", inv_freq)
|
| 78 |
-
|
| 79 |
-
# Build here to make `torch.jit.trace` work.
|
| 80 |
-
self._set_cos_sin_cache(
|
| 81 |
-
seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
|
| 82 |
-
)
|
| 83 |
-
|
| 84 |
-
def _set_cos_sin_cache(self, seq_len, device, dtype):
|
| 85 |
-
self.max_seq_len_cached = seq_len
|
| 86 |
-
t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
|
| 87 |
-
|
| 88 |
-
freqs = torch.einsum("i,j->ij", t, self.inv_freq)
|
| 89 |
-
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
| 90 |
-
emb = torch.cat((freqs, freqs), dim=-1)
|
| 91 |
-
self.register_buffer("cos_cached", emb.cos()[None, None, :, :].to(dtype), persistent=False)
|
| 92 |
-
self.register_buffer("sin_cached", emb.sin()[None, None, :, :].to(dtype), persistent=False)
|
| 93 |
-
|
| 94 |
-
def forward(self, x, seq_len=None):
|
| 95 |
-
# x: [bs, num_attention_heads, seq_len, head_size]
|
| 96 |
-
if seq_len > self.max_seq_len_cached:
|
| 97 |
-
self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
|
| 98 |
-
|
| 99 |
-
return (
|
| 100 |
-
self.cos_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
|
| 101 |
-
self.sin_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
|
| 102 |
-
)
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
class ShellLinearScalingRotaryEmbedding(ShellRotaryEmbedding):
|
| 106 |
-
"""ShellRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
|
| 107 |
-
|
| 108 |
-
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
|
| 109 |
-
self.scaling_factor = scaling_factor
|
| 110 |
-
super().__init__(dim, max_position_embeddings, base, device)
|
| 111 |
-
|
| 112 |
-
def _set_cos_sin_cache(self, seq_len, device, dtype):
|
| 113 |
-
self.max_seq_len_cached = seq_len
|
| 114 |
-
t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
|
| 115 |
-
t = t / self.scaling_factor
|
| 116 |
-
|
| 117 |
-
freqs = torch.einsum("i,j->ij", t, self.inv_freq)
|
| 118 |
-
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
| 119 |
-
emb = torch.cat((freqs, freqs), dim=-1)
|
| 120 |
-
self.register_buffer("cos_cached", emb.cos()[None, None, :, :].to(dtype), persistent=False)
|
| 121 |
-
self.register_buffer("sin_cached", emb.sin()[None, None, :, :].to(dtype), persistent=False)
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
class ShellDynamicNTKScalingRotaryEmbedding(ShellRotaryEmbedding):
|
| 125 |
-
"""ShellRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
|
| 126 |
-
|
| 127 |
-
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
|
| 128 |
-
self.scaling_factor = scaling_factor
|
| 129 |
-
super().__init__(dim, max_position_embeddings, base, device)
|
| 130 |
-
|
| 131 |
-
def _set_cos_sin_cache(self, seq_len, device, dtype):
|
| 132 |
-
self.max_seq_len_cached = seq_len
|
| 133 |
-
|
| 134 |
-
if seq_len > self.max_position_embeddings:
|
| 135 |
-
base = self.base * (
|
| 136 |
-
(self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
|
| 137 |
-
) ** (self.dim / (self.dim - 2))
|
| 138 |
-
inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
|
| 139 |
-
self.register_buffer("inv_freq", inv_freq)
|
| 140 |
-
|
| 141 |
-
t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
|
| 142 |
-
|
| 143 |
-
freqs = torch.einsum("i,j->ij", t, self.inv_freq)
|
| 144 |
-
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
| 145 |
-
emb = torch.cat((freqs, freqs), dim=-1)
|
| 146 |
-
self.register_buffer("cos_cached", emb.cos()[None, None, :, :].to(dtype), persistent=False)
|
| 147 |
-
self.register_buffer("sin_cached", emb.sin()[None, None, :, :].to(dtype), persistent=False)
|
| 148 |
-
|
| 149 |
-
def rotate_half(x):
|
| 150 |
-
"""Rotates half the hidden dims of the input."""
|
| 151 |
-
x1 = x[..., : x.shape[-1] // 2]
|
| 152 |
-
x2 = x[..., x.shape[-1] // 2 :]
|
| 153 |
-
return torch.cat((-x2, x1), dim=-1)
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
def apply_rotary_pos_emb(q, k, cos, sin, position_ids):
|
| 157 |
-
# The first two dimensions of cos and sin are always 1, so we can `squeeze` them.
|
| 158 |
-
cos = cos.squeeze(1).squeeze(0) # [seq_len, dim]
|
| 159 |
-
sin = sin.squeeze(1).squeeze(0) # [seq_len, dim]
|
| 160 |
-
cos = cos[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
|
| 161 |
-
sin = sin[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
|
| 162 |
-
q_embed = (q * cos) + (rotate_half(q) * sin)
|
| 163 |
-
k_embed = (k * cos) + (rotate_half(k) * sin)
|
| 164 |
-
return q_embed, k_embed
|
| 165 |
-
|
| 166 |
-
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
| 167 |
-
"""
|
| 168 |
-
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
| 169 |
-
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
| 170 |
-
"""
|
| 171 |
-
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
| 172 |
-
if n_rep == 1:
|
| 173 |
-
return hidden_states
|
| 174 |
-
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
| 175 |
-
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
| 176 |
-
|
| 177 |
-
class ShellAttention(nn.Module):
|
| 178 |
-
def __init__(self, config, layer_idx=None):
|
| 179 |
-
super().__init__()
|
| 180 |
-
self.mask_value = None
|
| 181 |
-
|
| 182 |
-
self.position_embedding_type = config.position_embedding_type
|
| 183 |
-
self.rope_scaling = config.rope_scaling
|
| 184 |
-
self.max_position_embeddings = config.max_position_embeddings
|
| 185 |
-
|
| 186 |
-
self.group_query_attention = config.group_query_attention
|
| 187 |
-
self.num_query_groups = config.num_query_groups
|
| 188 |
-
|
| 189 |
-
self.embed_dim = config.hidden_size
|
| 190 |
-
self.num_heads = config.num_attention_heads
|
| 191 |
-
self.head_dim = self.embed_dim // self.num_heads
|
| 192 |
-
self.kv_heads = config.num_query_groups if self.group_query_attention else self.num_heads
|
| 193 |
-
self.kv_dim = self.kv_heads * self.head_dim
|
| 194 |
-
self.split_size = self.embed_dim
|
| 195 |
-
if self.head_dim * self.num_heads != self.embed_dim:
|
| 196 |
-
raise ValueError(
|
| 197 |
-
f"`embed_dim` must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
|
| 198 |
-
f" {self.num_heads})."
|
| 199 |
-
)
|
| 200 |
-
|
| 201 |
-
self.layer_idx = layer_idx
|
| 202 |
-
|
| 203 |
-
self.c_attn = nn.Linear(self.embed_dim, self.embed_dim + 2 * self.kv_dim)
|
| 204 |
-
self.c_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
| 205 |
-
|
| 206 |
-
self.attn_dropout = nn.Dropout(config.attn_pdrop)
|
| 207 |
-
self.resid_dropout = nn.Dropout(config.resid_pdrop)
|
| 208 |
-
|
| 209 |
-
if self.position_embedding_type == "rope":
|
| 210 |
-
self._init_rope()
|
| 211 |
-
|
| 212 |
-
def _init_rope(self):
|
| 213 |
-
if self.rope_scaling is None:
|
| 214 |
-
self.rotary_emb = ShellRotaryEmbedding(self.head_dim, max_position_embeddings=self.max_position_embeddings)
|
| 215 |
-
else:
|
| 216 |
-
scaling_type = self.rope_scaling["type"]
|
| 217 |
-
scaling_factor = self.rope_scaling["factor"]
|
| 218 |
-
if scaling_type == "linear":
|
| 219 |
-
self.rotary_emb = ShellLinearScalingRotaryEmbedding(
|
| 220 |
-
self.head_dim, max_position_embeddings=self.max_position_embeddings, scaling_factor=scaling_factor
|
| 221 |
-
)
|
| 222 |
-
elif scaling_type == "dynamic":
|
| 223 |
-
self.rotary_emb = ShellDynamicNTKScalingRotaryEmbedding(
|
| 224 |
-
self.head_dim, max_position_embeddings=self.max_position_embeddings, scaling_factor=scaling_factor
|
| 225 |
-
)
|
| 226 |
-
else:
|
| 227 |
-
raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
def _get_mask_value(self, device, dtype):
|
| 231 |
-
# torch.where expects a tensor. We use a cache to avoid recreating it every time.
|
| 232 |
-
if self.mask_value is None or self.mask_value.dtype != dtype or self.mask_value.device != device:
|
| 233 |
-
self.mask_value = torch.full([], torch.finfo(dtype).min, dtype=dtype, device=device)
|
| 234 |
-
return self.mask_value
|
| 235 |
-
|
| 236 |
-
def forward(
|
| 237 |
-
self,
|
| 238 |
-
hidden_states: torch.Tensor,
|
| 239 |
-
layer_past: Optional[torch.Tensor] = None,
|
| 240 |
-
attention_mask: Optional[torch.Tensor] = None,
|
| 241 |
-
position_ids: Optional[torch.LongTensor] = None,
|
| 242 |
-
head_mask: Optional[torch.Tensor] = None,
|
| 243 |
-
encoder_hidden_states: Optional[torch.Tensor] = None,
|
| 244 |
-
encoder_attention_mask: Optional[torch.Tensor] = None,
|
| 245 |
-
use_cache: Optional[bool] = False,
|
| 246 |
-
output_attentions: Optional[bool] = False,
|
| 247 |
-
) -> Union[
|
| 248 |
-
Tuple[torch.Tensor, Optional[torch.Tensor]],
|
| 249 |
-
Tuple[torch.Tensor, Optional[torch.Tensor], Tuple[torch.Tensor, ...]],
|
| 250 |
-
]:
|
| 251 |
-
bsz, q_len, _ = hidden_states.size()
|
| 252 |
-
query_states, key_states, value_states = self.c_attn(hidden_states).split((self.embed_dim, self.kv_dim, self.kv_dim), dim=2)
|
| 253 |
-
|
| 254 |
-
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 255 |
-
key_states = key_states.view(bsz, q_len, self.num_query_groups, self.head_dim).transpose(1, 2)
|
| 256 |
-
value_states = value_states.view(bsz, q_len, self.num_query_groups, self.head_dim).transpose(1, 2)
|
| 257 |
-
|
| 258 |
-
kv_seq_len = key_states.shape[-2]
|
| 259 |
-
if past_key_value is not None:
|
| 260 |
-
kv_seq_len += past_key_value[0].shape[-2]
|
| 261 |
-
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
| 262 |
-
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
|
| 263 |
-
|
| 264 |
-
if past_key_value is not None:
|
| 265 |
-
# reuse k, v, self_attention
|
| 266 |
-
key_states = torch.cat([past_key_value[0], key_states], dim=2)
|
| 267 |
-
value_states = torch.cat([past_key_value[1], value_states], dim=2)
|
| 268 |
-
|
| 269 |
-
past_key_value = (key_states, value_states) if use_cache else None
|
| 270 |
-
|
| 271 |
-
# repeat k/v heads if n_kv_heads < n_heads
|
| 272 |
-
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
| 273 |
-
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
| 274 |
-
|
| 275 |
-
attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
|
| 276 |
-
|
| 277 |
-
if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
|
| 278 |
-
raise ValueError(
|
| 279 |
-
f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
|
| 280 |
-
f" {attn_weights.size()}"
|
| 281 |
-
)
|
| 282 |
-
|
| 283 |
-
if attention_mask is not None:
|
| 284 |
-
if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
|
| 285 |
-
raise ValueError(
|
| 286 |
-
f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
|
| 287 |
-
)
|
| 288 |
-
attn_weights = attn_weights + attention_mask
|
| 289 |
-
|
| 290 |
-
# upcast attention to fp32
|
| 291 |
-
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
|
| 292 |
-
attn_output = torch.matmul(attn_weights, value_states)
|
| 293 |
-
|
| 294 |
-
if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
|
| 295 |
-
raise ValueError(
|
| 296 |
-
f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
|
| 297 |
-
f" {attn_output.size()}"
|
| 298 |
-
)
|
| 299 |
-
|
| 300 |
-
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 301 |
-
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
|
| 302 |
-
|
| 303 |
-
attn_output = self.o_proj(attn_output)
|
| 304 |
-
|
| 305 |
-
outputs = (attn_output, past_key_value)
|
| 306 |
-
if output_attentions:
|
| 307 |
-
outputs += (attn_weights,)
|
| 308 |
-
|
| 309 |
-
return outputs # a, present, (attentions)
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
class ShellMLP(nn.Module):
|
| 313 |
-
def __init__(self, intermediate_size, config):
|
| 314 |
-
super().__init__()
|
| 315 |
-
embed_dim = config.hidden_size
|
| 316 |
-
self.c_fc = nn.Linear(embed_dim, intermediate_size)
|
| 317 |
-
self.c_proj = nn.Linear(intermediate_size, embed_dim)
|
| 318 |
-
self.act = ACT2FN[config.activation_function]
|
| 319 |
-
self.dropout = nn.Dropout(config.resid_pdrop)
|
| 320 |
-
|
| 321 |
-
# Copied from transformers.models.gpt2.modeling_gpt2.GPT2MLP.forward
|
| 322 |
-
def forward(self, hidden_states: Optional[Tuple[torch.Tensor]]) -> torch.Tensor:
|
| 323 |
-
hidden_states = self.c_fc(hidden_states)
|
| 324 |
-
hidden_states = self.act(hidden_states)
|
| 325 |
-
hidden_states = self.c_proj(hidden_states)
|
| 326 |
-
hidden_states = self.dropout(hidden_states)
|
| 327 |
-
return hidden_states
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
class ShellBlock(nn.Module):
|
| 331 |
-
def __init__(self, config, layer_idx=None):
|
| 332 |
-
super().__init__()
|
| 333 |
-
hidden_size = config.hidden_size
|
| 334 |
-
self.inner_dim = config.n_inner if config.n_inner is not None else 4 * hidden_size
|
| 335 |
-
|
| 336 |
-
self.ln_1 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
|
| 337 |
-
self.attn = ShellAttention(config, layer_idx=layer_idx)
|
| 338 |
-
self.ln_2 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
|
| 339 |
-
|
| 340 |
-
self.mlp = ShellMLP(self.inner_dim, config)
|
| 341 |
-
|
| 342 |
-
def forward(
|
| 343 |
-
self,
|
| 344 |
-
hidden_states: Optional[Tuple[torch.Tensor]],
|
| 345 |
-
layer_past: Optional[torch.Tensor] = None,
|
| 346 |
-
attention_mask: Optional[torch.Tensor] = None,
|
| 347 |
-
position_ids: Optional[torch.LongTensor] = None,
|
| 348 |
-
head_mask: Optional[torch.Tensor] = None,
|
| 349 |
-
encoder_hidden_states: Optional[torch.Tensor] = None,
|
| 350 |
-
encoder_attention_mask: Optional[torch.Tensor] = None,
|
| 351 |
-
use_cache: Optional[bool] = False,
|
| 352 |
-
output_attentions: Optional[bool] = False,
|
| 353 |
-
) -> Union[
|
| 354 |
-
Tuple[torch.Tensor], Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor, torch.Tensor, torch.Tensor]
|
| 355 |
-
]:
|
| 356 |
-
residual = hidden_states
|
| 357 |
-
hidden_states = self.ln_1(hidden_states)
|
| 358 |
-
attn_outputs = self.attn(
|
| 359 |
-
hidden_states,
|
| 360 |
-
layer_past=layer_past,
|
| 361 |
-
attention_mask=attention_mask,
|
| 362 |
-
position_ids=position_ids,
|
| 363 |
-
head_mask=head_mask,
|
| 364 |
-
use_cache=use_cache,
|
| 365 |
-
output_attentions=output_attentions,
|
| 366 |
-
)
|
| 367 |
-
attn_output = attn_outputs[0] # output_attn: a, present, (attentions)
|
| 368 |
-
|
| 369 |
-
outputs = attn_outputs[1:]
|
| 370 |
-
# residual connection
|
| 371 |
-
hidden_states = attn_output + residual
|
| 372 |
-
|
| 373 |
-
residual = hidden_states
|
| 374 |
-
hidden_states = self.ln_2(hidden_states)
|
| 375 |
-
feed_forward_hidden_states = self.mlp(hidden_states)
|
| 376 |
-
# residual connection
|
| 377 |
-
hidden_states = residual + feed_forward_hidden_states
|
| 378 |
-
|
| 379 |
-
if use_cache:
|
| 380 |
-
outputs = (hidden_states,) + outputs
|
| 381 |
-
else:
|
| 382 |
-
outputs = (hidden_states,) + outputs[1:]
|
| 383 |
-
|
| 384 |
-
return outputs # hidden_states, present, (attentions, cross_attentions)
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
class ShellPreTrainedModel(PreTrainedModel):
|
| 388 |
-
"""
|
| 389 |
-
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 390 |
-
models.
|
| 391 |
-
"""
|
| 392 |
-
|
| 393 |
-
config_class = ShellConfig
|
| 394 |
-
base_model_prefix = "transformer"
|
| 395 |
-
supports_gradient_checkpointing = True
|
| 396 |
-
_no_split_modules = ["ShellBlock"]
|
| 397 |
-
_skip_keys_device_placement = "past_key_values"
|
| 398 |
-
|
| 399 |
-
def __init__(self, *inputs, **kwargs):
|
| 400 |
-
super().__init__(*inputs, **kwargs)
|
| 401 |
-
|
| 402 |
-
def _init_weights(self, module):
|
| 403 |
-
"""Initialize the weights."""
|
| 404 |
-
if isinstance(module, (ShellMLP, ShellAttention)):
|
| 405 |
-
# Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
|
| 406 |
-
# > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
|
| 407 |
-
# > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
|
| 408 |
-
# > -- GPT-2 :: https://openai.com/blog/better-language-models/
|
| 409 |
-
#
|
| 410 |
-
# Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
|
| 411 |
-
module.c_proj.weight.data.normal_(
|
| 412 |
-
mean=0.0, std=(self.config.initializer_range / math.sqrt(2 * self.config.n_layer))
|
| 413 |
-
)
|
| 414 |
-
module.c_proj._is_hf_initialized = True
|
| 415 |
-
elif isinstance(module, nn.Linear):
|
| 416 |
-
# Slightly different from the TF version which uses truncated_normal for initialization
|
| 417 |
-
# cf https://github.com/pytorch/pytorch/pull/5617
|
| 418 |
-
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 419 |
-
if module.bias is not None:
|
| 420 |
-
module.bias.data.zero_()
|
| 421 |
-
elif isinstance(module, nn.Embedding):
|
| 422 |
-
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 423 |
-
if module.padding_idx is not None:
|
| 424 |
-
module.weight.data[module.padding_idx].zero_()
|
| 425 |
-
elif isinstance(module, nn.LayerNorm):
|
| 426 |
-
module.bias.data.zero_()
|
| 427 |
-
module.weight.data.fill_(1.0)
|
| 428 |
-
|
| 429 |
-
# Copied from transformers.models.gpt2.modeling_gpt2.GPT2PreTrainedModel._set_gradient_checkpointing with GPT2->Shell
|
| 430 |
-
def _set_gradient_checkpointing(self, module, value=False):
|
| 431 |
-
if isinstance(module, ShellModel):
|
| 432 |
-
module.gradient_checkpointing = value
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
GPT_BIGCODE_START_DOCSTRING = r"""
|
| 436 |
-
|
| 437 |
-
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 438 |
-
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 439 |
-
etc.)
|
| 440 |
-
|
| 441 |
-
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
| 442 |
-
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
| 443 |
-
and behavior.
|
| 444 |
-
|
| 445 |
-
Parameters:
|
| 446 |
-
config ([`ShellConfig`]): Model configuration class with all the parameters of the model.
|
| 447 |
-
Initializing with a config file does not load the weights associated with the model, only the
|
| 448 |
-
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 449 |
-
"""
|
| 450 |
-
|
| 451 |
-
GPT_BIGCODE_INPUTS_DOCSTRING = r"""
|
| 452 |
-
Args:
|
| 453 |
-
input_ids (`torch.Tensor` of shape `(batch_size, input_ids_length)`):
|
| 454 |
-
`input_ids_length` = `sequence_length` if `past_key_values` is `None` else
|
| 455 |
-
`past_key_values[0][0].shape[-2]` (`sequence_length` of input past key value states). Indices of input
|
| 456 |
-
sequence tokens in the vocabulary.
|
| 457 |
-
|
| 458 |
-
If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
|
| 459 |
-
`input_ids`.
|
| 460 |
-
|
| 461 |
-
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 462 |
-
[`PreTrainedTokenizer.__call__`] for details.
|
| 463 |
-
|
| 464 |
-
[What are input IDs?](../glossary#input-ids)
|
| 465 |
-
past_key_values (`Tuple[torch.Tensor]` of length `config.n_layers`):
|
| 466 |
-
Contains precomputed hidden-states (key and values in the attention blocks) as computed by the model (see
|
| 467 |
-
`past_key_values` output below). Can be used to speed up sequential decoding. The `input_ids` which have
|
| 468 |
-
their past given to this model should not be passed as `input_ids` as they have already been computed.
|
| 469 |
-
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 470 |
-
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 471 |
-
|
| 472 |
-
- 1 for tokens that are **not masked**,
|
| 473 |
-
- 0 for tokens that are **masked**.
|
| 474 |
-
|
| 475 |
-
If `past_key_values` is used, `attention_mask` needs to contain the masking strategy that was used for
|
| 476 |
-
`past_key_values`. In other words, the `attention_mask` always has to have the length:
|
| 477 |
-
`len(past_key_values) + len(input_ids)`
|
| 478 |
-
|
| 479 |
-
[What are attention masks?](../glossary#attention-mask)
|
| 480 |
-
token_type_ids (`torch.Tensor` of shape `(batch_size, input_ids_length)`, *optional*):
|
| 481 |
-
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
|
| 482 |
-
1]`:
|
| 483 |
-
|
| 484 |
-
- 0 corresponds to a *sentence A* token,
|
| 485 |
-
- 1 corresponds to a *sentence B* token.
|
| 486 |
-
|
| 487 |
-
[What are token type IDs?](../glossary#token-type-ids)
|
| 488 |
-
position_ids (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 489 |
-
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
| 490 |
-
config.max_position_embeddings - 1]`.
|
| 491 |
-
|
| 492 |
-
[What are position IDs?](../glossary#position-ids)
|
| 493 |
-
head_mask (`torch.Tensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
|
| 494 |
-
Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
|
| 495 |
-
|
| 496 |
-
- 1 indicates the head is **not masked**,
|
| 497 |
-
- 0 indicates the head is **masked**.
|
| 498 |
-
|
| 499 |
-
inputs_embeds (`torch.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 500 |
-
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
| 501 |
-
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
| 502 |
-
model's internal embedding lookup matrix.
|
| 503 |
-
|
| 504 |
-
If `past_key_values` is used, optionally only the last `inputs_embeds` have to be input (see
|
| 505 |
-
`past_key_values`).
|
| 506 |
-
use_cache (`bool`, *optional*):
|
| 507 |
-
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
| 508 |
-
`past_key_values`).
|
| 509 |
-
output_attentions (`bool`, *optional*):
|
| 510 |
-
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 511 |
-
tensors for more detail.
|
| 512 |
-
output_hidden_states (`bool`, *optional*):
|
| 513 |
-
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 514 |
-
more detail.
|
| 515 |
-
return_dict (`bool`, *optional*):
|
| 516 |
-
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 517 |
-
"""
|
| 518 |
-
|
| 519 |
-
|
| 520 |
-
@add_start_docstrings(
|
| 521 |
-
"The bare GPT_BIGCODE Model transformer outputting raw hidden-states without any specific head on top.",
|
| 522 |
-
GPT_BIGCODE_START_DOCSTRING,
|
| 523 |
-
)
|
| 524 |
-
class ShellModel(ShellPreTrainedModel):
|
| 525 |
-
def __init__(self, config):
|
| 526 |
-
super().__init__(config)
|
| 527 |
-
self.group_query_attention = config.group_query_attention
|
| 528 |
-
self.num_query_groups = config.num_query_groups
|
| 529 |
-
self.position_embedding_type = config.position_embedding_type
|
| 530 |
-
self.embed_dim = config.hidden_size
|
| 531 |
-
|
| 532 |
-
self.wte = nn.Embedding(config.vocab_size, self.embed_dim)
|
| 533 |
-
if self.position_embedding_type == "learned_absolute":
|
| 534 |
-
self.wpe = nn.Embedding(config.max_position_embeddings, self.embed_dim)
|
| 535 |
-
else:
|
| 536 |
-
pass
|
| 537 |
-
|
| 538 |
-
self.drop = nn.Dropout(config.embd_pdrop)
|
| 539 |
-
self.h = nn.ModuleList([ShellBlock(config, layer_idx=i) for i in range(config.num_hidden_layers)])
|
| 540 |
-
self.ln_f = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_epsilon)
|
| 541 |
-
|
| 542 |
-
max_positions = config.max_position_embeddings
|
| 543 |
-
self.register_buffer(
|
| 544 |
-
"bias", torch.tril(torch.ones((max_positions, max_positions), dtype=torch.bool)), persistent=False
|
| 545 |
-
)
|
| 546 |
-
|
| 547 |
-
self.gradient_checkpointing = False
|
| 548 |
-
|
| 549 |
-
# Initialize weights and apply final processing
|
| 550 |
-
self.post_init()
|
| 551 |
-
|
| 552 |
-
def get_input_embeddings(self):
|
| 553 |
-
return self.wte
|
| 554 |
-
|
| 555 |
-
def set_input_embeddings(self, new_embeddings):
|
| 556 |
-
self.wte = new_embeddings
|
| 557 |
-
|
| 558 |
-
@add_start_docstrings_to_model_forward(GPT_BIGCODE_INPUTS_DOCSTRING)
|
| 559 |
-
def forward(
|
| 560 |
-
self,
|
| 561 |
-
input_ids: Optional[torch.Tensor] = None,
|
| 562 |
-
past_key_values: Optional[List[torch.Tensor]] = None,
|
| 563 |
-
attention_mask: Optional[torch.Tensor] = None,
|
| 564 |
-
token_type_ids: Optional[torch.Tensor] = None,
|
| 565 |
-
position_ids: Optional[torch.Tensor] = None,
|
| 566 |
-
head_mask: Optional[torch.Tensor] = None,
|
| 567 |
-
inputs_embeds: Optional[torch.Tensor] = None,
|
| 568 |
-
encoder_hidden_states: Optional[torch.Tensor] = None,
|
| 569 |
-
encoder_attention_mask: Optional[torch.Tensor] = None,
|
| 570 |
-
use_cache: Optional[bool] = None,
|
| 571 |
-
output_attentions: Optional[bool] = None,
|
| 572 |
-
output_hidden_states: Optional[bool] = None,
|
| 573 |
-
return_dict: Optional[bool] = None,
|
| 574 |
-
) -> Union[Tuple, BaseModelOutputWithPastAndCrossAttentions]:
|
| 575 |
-
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 576 |
-
output_hidden_states = (
|
| 577 |
-
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 578 |
-
)
|
| 579 |
-
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 580 |
-
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 581 |
-
|
| 582 |
-
if input_ids is not None and inputs_embeds is not None:
|
| 583 |
-
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 584 |
-
elif input_ids is not None:
|
| 585 |
-
input_shape = input_ids.size()
|
| 586 |
-
input_ids = input_ids.reshape(-1, input_shape[-1])
|
| 587 |
-
batch_size = input_ids.shape[0]
|
| 588 |
-
elif inputs_embeds is not None:
|
| 589 |
-
input_shape = inputs_embeds.size()[:-1]
|
| 590 |
-
batch_size = inputs_embeds.shape[0]
|
| 591 |
-
else:
|
| 592 |
-
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 593 |
-
|
| 594 |
-
if batch_size <= 0:
|
| 595 |
-
raise ValueError("batch_size has to be defined and > 0")
|
| 596 |
-
|
| 597 |
-
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
| 598 |
-
|
| 599 |
-
if token_type_ids is not None:
|
| 600 |
-
token_type_ids = token_type_ids.reshape(-1, input_shape[-1])
|
| 601 |
-
if position_ids is not None:
|
| 602 |
-
position_ids = position_ids.reshape(-1, input_shape[-1])
|
| 603 |
-
|
| 604 |
-
if past_key_values is None:
|
| 605 |
-
past_length = 0
|
| 606 |
-
past_key_values = tuple([None] * len(self.h))
|
| 607 |
-
else:
|
| 608 |
-
past_length = past_key_values[0][0].size(-3)
|
| 609 |
-
|
| 610 |
-
if attention_mask is not None and len(attention_mask.shape) == 2 and position_ids is None:
|
| 611 |
-
# create position_ids on the fly for batch generation
|
| 612 |
-
position_ids = attention_mask.long().cumsum(-1) - 1
|
| 613 |
-
position_ids.masked_fill_(attention_mask == 0, 1)
|
| 614 |
-
if past_length > 0:
|
| 615 |
-
position_ids = position_ids[:, past_length : input_shape[-1] + past_length :]
|
| 616 |
-
elif position_ids is None:
|
| 617 |
-
position_ids = torch.arange(past_length, input_shape[-1] + past_length, dtype=torch.long, device=device)
|
| 618 |
-
position_ids = position_ids.unsqueeze(0).reshape(-1, input_shape[-1])
|
| 619 |
-
|
| 620 |
-
# Self-attention mask.
|
| 621 |
-
query_length = input_shape[-1]
|
| 622 |
-
key_length = past_length + query_length
|
| 623 |
-
self_attention_mask = self.bias[None, key_length - query_length : key_length, :key_length]
|
| 624 |
-
|
| 625 |
-
if attention_mask is not None:
|
| 626 |
-
self_attention_mask = self_attention_mask * attention_mask.reshape(batch_size, 1, -1).to(
|
| 627 |
-
dtype=torch.bool, device=self_attention_mask.device
|
| 628 |
-
)
|
| 629 |
-
|
| 630 |
-
# MQA models: (batch_size, query_length, n_heads, key_length)
|
| 631 |
-
# MHA models: (batch_size, n_heads, query_length, key_length)
|
| 632 |
-
attention_mask = self_attention_mask.unsqueeze(1)
|
| 633 |
-
|
| 634 |
-
encoder_attention_mask = None
|
| 635 |
-
|
| 636 |
-
# Prepare head mask if needed
|
| 637 |
-
# 1.0 in head_mask indicate we keep the head
|
| 638 |
-
# attention_probs has shape bsz x n_heads x N x N
|
| 639 |
-
# head_mask has shape n_layer x batch x n_heads x N x N
|
| 640 |
-
head_mask = self.get_head_mask(head_mask, self.config.n_layer)
|
| 641 |
-
|
| 642 |
-
if inputs_embeds is None:
|
| 643 |
-
inputs_embeds = self.wte(input_ids)
|
| 644 |
-
|
| 645 |
-
hidden_states = inputs_embeds
|
| 646 |
-
if self.position_embedding_type == "learned_absolute":
|
| 647 |
-
position_embeds = self.wpe(position_ids)
|
| 648 |
-
hidden_states = hidden_states + position_embeds
|
| 649 |
-
|
| 650 |
-
if token_type_ids is not None:
|
| 651 |
-
token_type_embeds = self.wte(token_type_ids)
|
| 652 |
-
hidden_states = hidden_states + token_type_embeds
|
| 653 |
-
|
| 654 |
-
hidden_states = self.drop(hidden_states)
|
| 655 |
-
|
| 656 |
-
output_shape = input_shape + (hidden_states.size(-1),)
|
| 657 |
-
|
| 658 |
-
presents = [] if use_cache else None
|
| 659 |
-
all_self_attentions = () if output_attentions else None
|
| 660 |
-
all_hidden_states = () if output_hidden_states else None
|
| 661 |
-
for i, (block, layer_past) in enumerate(zip(self.h, past_key_values)):
|
| 662 |
-
if output_hidden_states:
|
| 663 |
-
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 664 |
-
|
| 665 |
-
if self.gradient_checkpointing and self.training:
|
| 666 |
-
|
| 667 |
-
def create_custom_forward(module):
|
| 668 |
-
def custom_forward(*inputs):
|
| 669 |
-
# None for past_key_value
|
| 670 |
-
return module(*inputs, use_cache, output_attentions)
|
| 671 |
-
|
| 672 |
-
return custom_forward
|
| 673 |
-
|
| 674 |
-
outputs = torch.utils.checkpoint.checkpoint(
|
| 675 |
-
create_custom_forward(block),
|
| 676 |
-
hidden_states,
|
| 677 |
-
None,
|
| 678 |
-
attention_mask,
|
| 679 |
-
position_ids,
|
| 680 |
-
head_mask[i],
|
| 681 |
-
encoder_hidden_states,
|
| 682 |
-
encoder_attention_mask,
|
| 683 |
-
)
|
| 684 |
-
else:
|
| 685 |
-
outputs = block(
|
| 686 |
-
hidden_states,
|
| 687 |
-
layer_past=layer_past,
|
| 688 |
-
attention_mask=attention_mask,
|
| 689 |
-
position_ids=position_ids,
|
| 690 |
-
head_mask=head_mask[i],
|
| 691 |
-
encoder_hidden_states=encoder_hidden_states,
|
| 692 |
-
encoder_attention_mask=encoder_attention_mask,
|
| 693 |
-
use_cache=use_cache,
|
| 694 |
-
output_attentions=output_attentions,
|
| 695 |
-
)
|
| 696 |
-
|
| 697 |
-
hidden_states = outputs[0]
|
| 698 |
-
if use_cache:
|
| 699 |
-
presents.append(outputs[1])
|
| 700 |
-
|
| 701 |
-
if output_attentions:
|
| 702 |
-
all_self_attentions = all_self_attentions + (outputs[2 if use_cache else 1],)
|
| 703 |
-
|
| 704 |
-
hidden_states = self.ln_f(hidden_states)
|
| 705 |
-
hidden_states = hidden_states.reshape(output_shape)
|
| 706 |
-
# Add last hidden state
|
| 707 |
-
if output_hidden_states:
|
| 708 |
-
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 709 |
-
|
| 710 |
-
|
| 711 |
-
if not return_dict:
|
| 712 |
-
return tuple(
|
| 713 |
-
v
|
| 714 |
-
for v in [hidden_states, presents, all_hidden_states, all_self_attentions]
|
| 715 |
-
if v is not None
|
| 716 |
-
)
|
| 717 |
-
|
| 718 |
-
return BaseModelOutputWithPastAndCrossAttentions(
|
| 719 |
-
last_hidden_state=hidden_states,
|
| 720 |
-
past_key_values=presents,
|
| 721 |
-
hidden_states=all_hidden_states,
|
| 722 |
-
attentions=all_self_attentions,
|
| 723 |
-
)
|
| 724 |
-
|
| 725 |
-
|
| 726 |
-
@add_start_docstrings(
|
| 727 |
-
"""
|
| 728 |
-
The GPT_BIGCODE Model transformer with a language modeling head on top (linear layer with weights tied to the input
|
| 729 |
-
embeddings).
|
| 730 |
-
""",
|
| 731 |
-
GPT_BIGCODE_START_DOCSTRING,
|
| 732 |
-
)
|
| 733 |
-
class ShellForCausalLM(ShellPreTrainedModel):
|
| 734 |
-
_tied_weights_keys = ["lm_head.weight"]
|
| 735 |
-
|
| 736 |
-
def __init__(self, config):
|
| 737 |
-
super().__init__(config)
|
| 738 |
-
self.transformer = ShellModel(config)
|
| 739 |
-
self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
|
| 740 |
-
|
| 741 |
-
# Initialize weights and apply final processing
|
| 742 |
-
self.post_init()
|
| 743 |
-
|
| 744 |
-
def get_output_embeddings(self):
|
| 745 |
-
return self.lm_head
|
| 746 |
-
|
| 747 |
-
def set_output_embeddings(self, new_embeddings):
|
| 748 |
-
self.lm_head = new_embeddings
|
| 749 |
-
|
| 750 |
-
def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs):
|
| 751 |
-
token_type_ids = kwargs.get("token_type_ids", None)
|
| 752 |
-
# only last token for inputs_ids if past is defined in kwargs
|
| 753 |
-
if past_key_values:
|
| 754 |
-
input_ids = input_ids[:, -1].unsqueeze(-1)
|
| 755 |
-
if token_type_ids is not None:
|
| 756 |
-
token_type_ids = token_type_ids[:, -1].unsqueeze(-1)
|
| 757 |
-
|
| 758 |
-
attention_mask = kwargs.get("attention_mask", None)
|
| 759 |
-
position_ids = kwargs.get("position_ids", None)
|
| 760 |
-
|
| 761 |
-
if attention_mask is not None and position_ids is None:
|
| 762 |
-
# create position_ids on the fly for batch generation
|
| 763 |
-
position_ids = attention_mask.long().cumsum(-1) - 1
|
| 764 |
-
position_ids.masked_fill_(attention_mask == 0, 1)
|
| 765 |
-
if past_key_values:
|
| 766 |
-
position_ids = position_ids[:, -1].unsqueeze(-1)
|
| 767 |
-
else:
|
| 768 |
-
position_ids = None
|
| 769 |
-
|
| 770 |
-
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
| 771 |
-
if inputs_embeds is not None and past_key_values is None:
|
| 772 |
-
model_inputs = {"inputs_embeds": inputs_embeds}
|
| 773 |
-
else:
|
| 774 |
-
model_inputs = {"input_ids": input_ids}
|
| 775 |
-
|
| 776 |
-
model_inputs.update(
|
| 777 |
-
{
|
| 778 |
-
"past_key_values": past_key_values,
|
| 779 |
-
"use_cache": kwargs.get("use_cache"),
|
| 780 |
-
"position_ids": position_ids,
|
| 781 |
-
"attention_mask": attention_mask,
|
| 782 |
-
"token_type_ids": token_type_ids,
|
| 783 |
-
}
|
| 784 |
-
)
|
| 785 |
-
return model_inputs
|
| 786 |
-
|
| 787 |
-
@add_start_docstrings_to_model_forward(GPT_BIGCODE_INPUTS_DOCSTRING)
|
| 788 |
-
def forward(
|
| 789 |
-
self,
|
| 790 |
-
input_ids: Optional[torch.Tensor] = None,
|
| 791 |
-
past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
|
| 792 |
-
attention_mask: Optional[torch.Tensor] = None,
|
| 793 |
-
token_type_ids: Optional[torch.Tensor] = None,
|
| 794 |
-
position_ids: Optional[torch.Tensor] = None,
|
| 795 |
-
head_mask: Optional[torch.Tensor] = None,
|
| 796 |
-
inputs_embeds: Optional[torch.Tensor] = None,
|
| 797 |
-
encoder_hidden_states: Optional[torch.Tensor] = None,
|
| 798 |
-
encoder_attention_mask: Optional[torch.Tensor] = None,
|
| 799 |
-
labels: Optional[torch.Tensor] = None,
|
| 800 |
-
use_cache: Optional[bool] = None,
|
| 801 |
-
output_attentions: Optional[bool] = None,
|
| 802 |
-
output_hidden_states: Optional[bool] = None,
|
| 803 |
-
return_dict: Optional[bool] = None,
|
| 804 |
-
) -> Union[Tuple, CausalLMOutputWithCrossAttentions]:
|
| 805 |
-
r"""
|
| 806 |
-
labels (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 807 |
-
Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
|
| 808 |
-
`labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
|
| 809 |
-
are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
|
| 810 |
-
"""
|
| 811 |
-
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 812 |
-
|
| 813 |
-
transformer_outputs = self.transformer(
|
| 814 |
-
input_ids,
|
| 815 |
-
past_key_values=past_key_values,
|
| 816 |
-
attention_mask=attention_mask,
|
| 817 |
-
token_type_ids=token_type_ids,
|
| 818 |
-
position_ids=position_ids,
|
| 819 |
-
head_mask=head_mask,
|
| 820 |
-
inputs_embeds=inputs_embeds,
|
| 821 |
-
encoder_hidden_states=encoder_hidden_states,
|
| 822 |
-
encoder_attention_mask=encoder_attention_mask,
|
| 823 |
-
use_cache=use_cache,
|
| 824 |
-
output_attentions=output_attentions,
|
| 825 |
-
output_hidden_states=output_hidden_states,
|
| 826 |
-
return_dict=return_dict,
|
| 827 |
-
)
|
| 828 |
-
hidden_states = transformer_outputs[0]
|
| 829 |
-
lm_logits = self.lm_head(hidden_states)
|
| 830 |
-
loss = None
|
| 831 |
-
if labels is not None:
|
| 832 |
-
# Shift so that tokens < n predict n
|
| 833 |
-
shift_logits = lm_logits[..., :-1, :].contiguous()
|
| 834 |
-
shift_labels = labels[..., 1:].contiguous().to(shift_logits.device)
|
| 835 |
-
# Flatten the tokens
|
| 836 |
-
loss_fct = CrossEntropyLoss()
|
| 837 |
-
loss = loss_fct(shift_logits.reshape(-1, shift_logits.size(-1)), shift_labels.reshape(-1))
|
| 838 |
-
|
| 839 |
-
if not return_dict:
|
| 840 |
-
output = (lm_logits,) + transformer_outputs[1:]
|
| 841 |
-
return ((loss,) + output) if loss is not None else output
|
| 842 |
-
|
| 843 |
-
return CausalLMOutputWithCrossAttentions(
|
| 844 |
-
loss=loss,
|
| 845 |
-
logits=lm_logits,
|
| 846 |
-
past_key_values=transformer_outputs.past_key_values,
|
| 847 |
-
hidden_states=transformer_outputs.hidden_states,
|
| 848 |
-
attentions=transformer_outputs.attentions,
|
| 849 |
-
)
|
| 850 |
-
|
| 851 |
-
@staticmethod
|
| 852 |
-
def _reorder_cache(past_key_values, beam_idx):
|
| 853 |
-
reordered_past = ()
|
| 854 |
-
for layer_past in past_key_values:
|
| 855 |
-
reordered_past += (
|
| 856 |
-
tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
|
| 857 |
-
)
|
| 858 |
-
return reordered_past
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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