Yi vs llama

Criado O diff nunca expira
510 remoções
623 linhas
407 adições
538 linhas
""" PyTorch Yi model."""
# coding=utf-8
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
#
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
# and OPT implementations in this library. It has been modified from its
# original forms to accommodate minor architectural differences compared
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
""" PyTorch LLaMA model."""
import math
import math
import warnings
from typing import List, Optional, Tuple, Union
from typing import List, Optional, Tuple, Union


import torch
import torch.nn.functional as F
import torch.utils.checkpoint
import torch.utils.checkpoint
from einops import repeat
from torch import nn
from torch import nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
from transformers.activations import ACT2FN

from transformers.modeling_outputs import (
from ...activations import ACT2FN
BaseModelOutputWithPast,
from ...modeling_attn_mask_utils import AttentionMaskConverter, _prepare_4d_causal_attention_mask
CausalLMOutputWithPast,
from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
SequenceClassifierOutputWithPast,
from ...modeling_utils import PreTrainedModel
)
from ...pytorch_utils import ALL_LAYERNORM_LAYERS
from transformers.modeling_utils import PreTrainedModel
from ...utils import (
from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS
from transformers.utils import (
add_start_docstrings,
add_start_docstrings,
add_start_docstrings_to_model_forward,
add_start_docstrings_to_model_forward,
is_flash_attn_2_available,
logging,
logging,
replace_return_docstrings,
replace_return_docstrings,
)
)
from ...utils.import_utils import is_torch_fx_available
from .configuration_llama import LlamaConfig


from .configuration_yi import YiConfig


is_flash_attn_available = True
if is_flash_attn_2_available():
try:
from flash_attn import flash_attn_func, flash_attn_varlen_func
from flash_attn import flash_attn_func
from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
except Exception:

is_flash_attn_available = False

# This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
# It means that the function will not be traced through and simply appear as a node in the graph.
if is_torch_fx_available():
_prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)



logger = logging.get_logger(__name__)
logger = logging.get_logger(__name__)


_CONFIG_FOR_DOC = "YiConfig"
_CONFIG_FOR_DOC = "LlamaConfig"




# Copied from transformers.models.bart.modeling_bart._make_causal_mask
def _get_unpad_data(attention_mask):
def _make_causal_mask(
seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
input_ids_shape: torch.Size,
indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
dtype: torch.dtype,
max_seqlen_in_batch = seqlens_in_batch.max().item()
device: torch.device,
cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
past_key_values_length: int = 0,
return (
):
indices,
"""
cu_seqlens,
Make causal mask used for bi-directional self-attention.
max_seqlen_in_batch,
"""
bsz, tgt_len = input_ids_shape
mask = torch.full(
(tgt_len, tgt_len),
torch.tensor(torch.finfo(dtype).min, device=device),
device=device,
)
mask_cond = torch.arange(mask.size(-1), device=device)
mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
mask = mask.to(dtype)

if past_key_values_length > 0:
mask = torch.cat(
[
torch.zeros(
tgt_len, past_key_values_length, dtype=dtype, device=device
),
mask,
],
dim=-1,
)
return mask[None, None, :, :].expand(
bsz, 1, tgt_len, tgt_len + past_key_values_length
)
)




# Copied from transformers.models.bart.modeling_bart._expand_mask
def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
"""
warnings.warn(
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
"Calling `transformers.models.llama.modeling_llama._prepare_4d_attention_mask` is deprecated and will be removed in v4.37. Use `transformers.modeling_attn_mask_utils.AttentionMaskConverter._prepare_4d_attention_mask"
"""
)
bsz, src_len = mask.size()
return AttentionMaskConverter._prepare_4d_attention_mask(mask=mask, dtype=dtype, tgt_len=tgt_len)
tgt_len = tgt_len if tgt_len is not None else src_len

expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)


inverted_mask = 1.0 - expanded_mask


return inverted_mask.masked_fill(
def _make_causal_mask(
inverted_mask.to(torch.bool), torch.finfo(dtype).min
input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
):
warnings.warn(
"Calling `transformers.models.llama.modeling_llama._make_causal_mask` is deprecated and will be removed in v4.37. Use `transformers.models.llama.modeling_llama.AttentionMaskConverter._make_causal_mask"
)
return AttentionMaskConverter._make_causal_mask(
input_ids_shape=input_ids_shape, dtype=dtype, device=device, past_key_values_length=past_key_values_length
)
)




class YiRMSNorm(nn.Module):
class LlamaRMSNorm(nn.Module):
def __init__(self, hidden_size, eps=1e-5):
def __init__(self, hidden_size, eps=1e-6):
"""
"""
YiRMSNorm is equivalent to T5LayerNorm
LlamaRMSNorm is equivalent to T5LayerNorm
"""
"""
super().__init__()
super().__init__()
self.weight = nn.Parameter(torch.ones(hidden_size))
self.weight = nn.Parameter(torch.ones(hidden_size))
self.variance_epsilon = eps
self.variance_epsilon = eps


def forward(self, hidden_states):
def forward(self, hidden_states):
input_dtype = hidden_states.dtype
input_dtype = hidden_states.dtype
hidden_states = hidden_states.to(torch.float32)
hidden_states = hidden_states.to(torch.float32)
variance = hidden_states.pow(2).mean(-1, keepdim=True)
variance = hidden_states.pow(2).mean(-1, keepdim=True)
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)

return self.weight * hidden_states.to(input_dtype)
return self.weight * hidden_states.to(input_dtype)




ALL_LAYERNORM_LAYERS.append(YiRMSNorm)
ALL_LAYERNORM_LAYERS.append(LlamaRMSNorm)




class YiRotaryEmbedding(torch.nn.Module):
class LlamaRotaryEmbedding(nn.Module):
def __init__(self, dim, max_position_embeddings=4096, base=5000000, device=None):
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
super().__init__()
super().__init__()


self.dim = dim
self.dim = dim
self.max_position_embeddings = max_position_embeddings
self.max_position_embeddings = max_position_embeddings
self.base = base
self.base = base
inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
self.register_buffer("inv_freq", inv_freq, persistent=False)


# Build here to make `torch.jit.trace` work.
# Build here to make `torch.jit.trace` work.
self._set_cos_sin_cache(seq_len=max_position_embeddings, device=device)
self._set_cos_sin_cache(
seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
)


def _set_cos_sin_cache(self, seq_len, device):
def _set_cos_sin_cache(self, seq_len, device, dtype):
self.max_seq_len_cached = seq_len
self.max_seq_len_cached = seq_len
inv_freq = 1.0 / (
t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)

)
freqs = torch.einsum("i,j->ij", t, self.inv_freq)
t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.float32)
freqs = torch.einsum("i,j->ij", t, inv_freq)
# Different from paper, but it uses a different permutation in order to obtain the same calculation
# Different from paper, but it uses a different permutation in order to obtain the same calculation
emb = torch.cat((freqs, freqs), dim=-1)
emb = torch.cat((freqs, freqs), dim=-1)
self.register_buffer(
self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
"cos_cached", emb.cos()[None, None, :, :], persistent=False
self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
)
self.register_buffer(
"sin_cached", emb.sin()[None, None, :, :], persistent=False
)


def forward(self, x, seq_len=None):
def forward(self, x, seq_len=None):
# x: [bs, num_attention_heads, seq_len, head_size]
# x: [bs, num_attention_heads, seq_len, head_size]
if seq_len > self.max_seq_len_cached:
if seq_len > self.max_seq_len_cached:
self._set_cos_sin_cache(seq_len=seq_len, device=x.device)
self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)


return (
return (
self.cos_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
self.cos_cached[:seq_len].to(dtype=x.dtype),
self.sin_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
self.sin_cached[:seq_len].to(dtype=x.dtype),
)
)




class LlamaLinearScalingRotaryEmbedding(LlamaRotaryEmbedding):
"""LlamaRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""

def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
self.scaling_factor = scaling_factor
super().__init__(dim, max_position_embeddings, base, device)

def _set_cos_sin_cache(self, seq_len, device, dtype):
self.max_seq_len_cached = seq_len
t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
t = t / self.scaling_factor

freqs = torch.einsum("i,j->ij", t, self.inv_freq)
# Different from paper, but it uses a different permutation in order to obtain the same calculation
emb = torch.cat((freqs, freqs), dim=-1)
self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)


class LlamaDynamicNTKScalingRotaryEmbedding(LlamaRotaryEmbedding):
"""LlamaRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""

def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
self.scaling_factor = scaling_factor
super().__init__(dim, max_position_embeddings, base, device)

def _set_cos_sin_cache(self, seq_len, device, dtype):
self.max_seq_len_cached = seq_len

if seq_len > self.max_position_embeddings:
base = self.base * (
(self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
) ** (self.dim / (self.dim - 2))
inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
self.register_buffer("inv_freq", inv_freq, persistent=False)

t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)

freqs = torch.einsum("i,j->ij", t, self.inv_freq)
# Different from paper, but it uses a different permutation in order to obtain the same calculation
emb = torch.cat((freqs, freqs), dim=-1)
self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)


def rotate_half(x):
def rotate_half(x):
"""Rotates half the hidden dims of the input."""
"""Rotates half the hidden dims of the input."""
x1 = x[..., : x.shape[-1] // 2]
x1 = x[..., : x.shape[-1] // 2]
x2 = x[..., x.shape[-1] // 2 :]
x2 = x[..., x.shape[-1] // 2 :]
return torch.cat((-x2, x1), dim=-1)
return torch.cat((-x2, x1), dim=-1)




def apply_rotary_pos_emb(q, k, cos, sin, position_ids, flash_attn_available):
def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
# The first two dimensions of cos and sin are always 1, so we can `squeeze` them.
"""Applies Rotary Position Embedding to the query and key tensors.
cos = cos.squeeze(1).squeeze(0) # [seq_len, dim]

sin = sin.squeeze(1).squeeze(0) # [seq_len, dim]
Args:
expand_dim = 2 if flash_attn_available else 1
q (`torch.Tensor`): The query tensor.
cos = cos[position_ids].unsqueeze(expand_dim) # [bs, seq_len, dim]
k (`torch.Tensor`): The key tensor.
sin = sin[position_ids].unsqueeze(expand_dim) # [bs, seq_len, dim]
cos (`torch.Tensor`): The cosine part of the rotary embedding.
sin (`torch.Tensor`): The sine part of the rotary embedding.
position_ids (`torch.Tensor`):
The position indices of the tokens corresponding to the query and key tensors. For example, this can be
used to pass offsetted position ids when working with a KV-cache.
unsqueeze_dim (`int`, *optional*, defaults to 1):
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
Returns:
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
"""
cos = cos[position_ids].unsqueeze(unsqueeze_dim)
sin = sin[position_ids].unsqueeze(unsqueeze_dim)
q_embed = (q * cos) + (rotate_half(q) * sin)
q_embed = (q * cos) + (rotate_half(q) * sin)