Aluode/PerceptionLabPortable
0
1# coding=utf-82# Copyright 2024 Microsoft and the HuggingFace Inc. team. All rights reserved.3#4# Licensed under the Apache License, Version 2.0 (the "License");5# you may not use this file except in compliance with the License.6# You may obtain a copy of the License at7#8# http://www.apache.org/licenses/LICENSE-2.09#10# Unless required by applicable law or agreed to in writing, software11# distributed under the License is distributed on an "AS IS" BASIS,12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13# See the License for the specific language governing permissions and14# limitations under the License.15 16"""PyTorch Phi-3 model."""17 18from typing import Callable, Optional19 20import torch21from torch import nn22 23from ...activations import ACT2FN24from ...cache_utils import Cache25from ...generation import GenerationMixin26from ...modeling_flash_attention_utils import FlashAttentionKwargs27from ...modeling_utils import ALL_ATTENTION_FUNCTIONS28from ...processing_utils import Unpack29from ...utils import logging30from ...utils.deprecation import deprecate_kwarg31from ..mistral.modeling_mistral import (32 MistralDecoderLayer,33 MistralForCausalLM,34 MistralForSequenceClassification,35 MistralForTokenClassification,36 MistralPreTrainedModel,37 eager_attention_forward,38 rotate_half,39)40from .configuration_phi3 import Phi3Config41 42 43logger = logging.get_logger(__name__)44 45_CHECKPOINT_FOR_DOC = "microsoft/Phi-3-mini-4k-instruct"46_CONFIG_FOR_DOC = "Phi3Config"47 48 49class Phi3MLP(nn.Module):50 def __init__(self, config):51 super().__init__()52 53 self.config = config54 self.gate_up_proj = nn.Linear(config.hidden_size, 2 * config.intermediate_size, bias=False)55 self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)56 self.activation_fn = ACT2FN[config.hidden_act]57 58 def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:59 up_states = self.gate_up_proj(hidden_states)60 61 gate, up_states = up_states.chunk(2, dim=-1)62 up_states = up_states * self.activation_fn(gate)63 64 return self.down_proj(up_states)65 66 67def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):68 """Applies Rotary Position Embedding to the query and key tensors.69 70 Args:71 q (`torch.Tensor`): The query tensor.72 k (`torch.Tensor`): The key tensor.73 cos (`torch.Tensor`): The cosine part of the rotary embedding.74 sin (`torch.Tensor`): The sine part of the rotary embedding.75 position_ids (`torch.Tensor`, *optional*):76 Deprecated and unused.77 unsqueeze_dim (`int`, *optional*, defaults to 1):78 The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and79 sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note80 that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and81 k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes82 cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have83 the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.84 Returns:85 `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.86 """87 cos = cos.unsqueeze(unsqueeze_dim)88 sin = sin.unsqueeze(unsqueeze_dim)89 90 rotary_dim = cos.shape[-1]91 q_rot, q_pass = q[..., :rotary_dim], q[..., rotary_dim:]92 k_rot, k_pass = k[..., :rotary_dim], k[..., rotary_dim:]93 94 q_embed = torch.cat([(q_rot * cos) + (rotate_half(q_rot) * sin), q_pass], dim=-1)95 k_embed = torch.cat([(k_rot * cos) + (rotate_half(k_rot) * sin), k_pass], dim=-1)96 return q_embed, k_embed97 98 99class Phi3Attention(nn.Module):100 """Multi-headed attention from 'Attention Is All You Need' paper"""101 102 def __init__(self, config: Phi3Config, layer_idx: Optional[int] = None):103 super().__init__()104 self.config = config105 self.layer_idx = layer_idx106 self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)107 self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads108 self.num_key_value_heads = config.num_key_value_heads109 self.scaling = self.head_dim**-0.5110 self.attention_dropout = config.attention_dropout111 self.is_causal = True112 113 op_size = config.num_attention_heads * self.head_dim + 2 * (config.num_key_value_heads * self.head_dim)114 self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)115 self.qkv_proj = nn.Linear(config.hidden_size, op_size, bias=False)116 117 @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")118 def forward(119 self,120 hidden_states: torch.Tensor,121 position_embeddings: tuple[torch.Tensor, torch.Tensor],122 attention_mask: Optional[torch.Tensor],123 past_key_values: Optional[Cache] = None,124 cache_position: Optional[torch.LongTensor] = None,125 **kwargs: Unpack[FlashAttentionKwargs],126 ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:127 input_shape = hidden_states.shape[:-1]128 hidden_shape = (*input_shape, -1, self.head_dim)129 130 qkv = self.qkv_proj(hidden_states)131 query_pos = self.config.num_attention_heads * self.head_dim132 query_states = qkv[..., :query_pos]133 key_states = qkv[..., query_pos : query_pos + self.num_key_value_heads * self.head_dim]134 value_states = qkv[..., query_pos + self.num_key_value_heads * self.head_dim :]135 136 query_states = query_states.view(hidden_shape).transpose(1, 2)137 key_states = key_states.view(hidden_shape).transpose(1, 2)138 value_states = value_states.view(hidden_shape).transpose(1, 2)139 140 cos, sin = position_embeddings141 query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)142 143 if past_key_values is not None:144 # sin and cos are specific to RoPE models; cache_position needed for the static cache145 cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}146 key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)147 148 attention_interface: Callable = eager_attention_forward149 if self.config._attn_implementation != "eager":150 attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]151 152 attn_output, attn_weights = attention_interface(153 self,154 query_states,155 key_states,156 value_states,157 attention_mask,158 dropout=0.0 if not self.training else self.attention_dropout,159 scaling=self.scaling,160 sliding_window=getattr(self.config, "sliding_window", None),161 **kwargs,162 )163 164 attn_output = attn_output.reshape(*input_shape, -1).contiguous()165 attn_output = self.o_proj(attn_output)166 return attn_output, attn_weights167 168 169class Phi3DecoderLayer(MistralDecoderLayer):170 def __init__(self, config: Phi3Config, layer_idx: int):171 super().__init__(config, layer_idx)172 self.config = config173 self.self_attn = Phi3Attention(config=config, layer_idx=layer_idx)174 self.mlp = Phi3MLP(config)175 self.resid_attn_dropout = nn.Dropout(config.resid_pdrop)176 self.resid_mlp_dropout = nn.Dropout(config.resid_pdrop)177 178 @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")179 def forward(180 self,181 hidden_states: torch.Tensor,182 attention_mask: Optional[torch.Tensor] = None,183 position_ids: Optional[torch.LongTensor] = None,184 past_key_values: Optional[Cache] = None,185 use_cache: Optional[bool] = False,186 cache_position: Optional[torch.LongTensor] = None,187 position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC188 **kwargs: Unpack[FlashAttentionKwargs],189 ) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]:190 residual = hidden_states191 hidden_states = self.input_layernorm(hidden_states)192 193 hidden_states, self_attn_weights = self.self_attn(194 hidden_states=hidden_states,195 attention_mask=attention_mask,196 position_ids=position_ids,197 past_key_values=past_key_values,198 use_cache=use_cache,199 cache_position=cache_position,200 position_embeddings=position_embeddings,201 **kwargs,202 )203 hidden_states = residual + self.resid_attn_dropout(hidden_states) # main diff with Llama204 205 residual = hidden_states206 hidden_states = self.post_attention_layernorm(hidden_states)207 hidden_states = self.mlp(hidden_states)208 hidden_states = residual + self.resid_mlp_dropout(hidden_states) # main diff with Llama209 return hidden_states210 211 212class Phi3PreTrainedModel(MistralPreTrainedModel):213 _version = "0.0.5"214 215 216class Phi3ForCausalLM(MistralForCausalLM):217 def prepare_inputs_for_generation(218 self,219 input_ids,220 past_key_values=None,221 attention_mask=None,222 inputs_embeds=None,223 cache_position=None,224 position_ids=None,225 use_cache=True,226 logits_to_keep=None,227 **kwargs,228 ):229 # Overwritten -- this model may need to switch between short and long rope, invalidating the cache in the230 # process231 232 # When the first time input length reached long and short factor switching point, enforce re-compute cache233 # It will cause downside of slower at this single token position, however, better than current failure.234 if (235 past_key_values236 and self.config.rope_scaling237 and input_ids.shape[1] >= self.config.original_max_position_embeddings + 1238 ):239 past_length = cache_position[0]240 if past_length <= self.config.original_max_position_embeddings:241 past_key_values = None242 243 model_inputs = GenerationMixin.prepare_inputs_for_generation(244 self,245 input_ids=input_ids,246 past_key_values=past_key_values,247 attention_mask=attention_mask,248 inputs_embeds=inputs_embeds,249 cache_position=cache_position,250 position_ids=position_ids,251 use_cache=use_cache,252 logits_to_keep=logits_to_keep,253 **kwargs,254 )255 return model_inputs256 257 258class Phi3ForSequenceClassification(MistralForSequenceClassification):259 pass260 261 262class Phi3ForTokenClassification(MistralForTokenClassification):263 pass264 265 266__all__ = [267 "Phi3PreTrainedModel",268 "Phi3Model", # noqa: F822269 "Phi3ForCausalLM",270 "Phi3ForSequenceClassification",271 "Phi3ForTokenClassification",272]273 