modeling_phi.py 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461
  1. # coding=utf-8
  2. # Copyright 2023 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 at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # 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 and
  14. # limitations under the License.
  15. """PyTorch Phi model."""
  16. import math
  17. from typing import List, Optional, Tuple, Union
  18. import torch
  19. import torch.utils.checkpoint
  20. from packaging import version
  21. from torch import nn
  22. from torch.nn import CrossEntropyLoss
  23. from ...activations import ACT2FN
  24. from ...cache_utils import Cache, DynamicCache, StaticCache
  25. from ...generation import GenerationMixin
  26. from ...modeling_attn_mask_utils import AttentionMaskConverter
  27. from ...modeling_outputs import (
  28. BaseModelOutputWithPast,
  29. CausalLMOutputWithPast,
  30. SequenceClassifierOutputWithPast,
  31. TokenClassifierOutput,
  32. )
  33. from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS
  34. from ...modeling_utils import PreTrainedModel
  35. from ...utils import (
  36. add_code_sample_docstrings,
  37. add_start_docstrings,
  38. add_start_docstrings_to_model_forward,
  39. get_torch_version,
  40. is_flash_attn_2_available,
  41. is_flash_attn_greater_or_equal_2_10,
  42. logging,
  43. replace_return_docstrings,
  44. )
  45. from .configuration_phi import PhiConfig
  46. if is_flash_attn_2_available():
  47. from ...modeling_flash_attention_utils import _flash_attention_forward
  48. logger = logging.get_logger(__name__)
  49. _CHECKPOINT_FOR_DOC = "microsoft/phi-1"
  50. _CONFIG_FOR_DOC = "PhiConfig"
  51. # Copied from transformers.models.llama.modeling_llama.LlamaRotaryEmbedding with Llama->Phi
  52. class PhiRotaryEmbedding(nn.Module):
  53. def __init__(
  54. self,
  55. dim=None,
  56. max_position_embeddings=2048,
  57. base=10000,
  58. device=None,
  59. scaling_factor=1.0,
  60. rope_type="default",
  61. config: Optional[PhiConfig] = None,
  62. ):
  63. super().__init__()
  64. # TODO (joao): remove the `if` below, only used for BC
  65. self.rope_kwargs = {}
  66. if config is None:
  67. logger.warning_once(
  68. "`PhiRotaryEmbedding` can now be fully parameterized by passing the model config through the "
  69. "`config` argument. All other arguments will be removed in v4.46"
  70. )
  71. self.rope_kwargs = {
  72. "rope_type": rope_type,
  73. "factor": scaling_factor,
  74. "dim": dim,
  75. "base": base,
  76. "max_position_embeddings": max_position_embeddings,
  77. }
  78. self.rope_type = rope_type
  79. self.max_seq_len_cached = max_position_embeddings
  80. self.original_max_seq_len = max_position_embeddings
  81. else:
  82. # BC: "rope_type" was originally "type"
  83. if config.rope_scaling is not None:
  84. self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
  85. else:
  86. self.rope_type = "default"
  87. self.max_seq_len_cached = config.max_position_embeddings
  88. self.original_max_seq_len = config.max_position_embeddings
  89. self.config = config
  90. self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
  91. inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, **self.rope_kwargs)
  92. self.register_buffer("inv_freq", inv_freq, persistent=False)
  93. self.original_inv_freq = self.inv_freq
  94. def _dynamic_frequency_update(self, position_ids, device):
  95. """
  96. dynamic RoPE layers should recompute `inv_freq` in the following situations:
  97. 1 - growing beyond the cached sequence length (allow scaling)
  98. 2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
  99. """
  100. seq_len = torch.max(position_ids) + 1
  101. if seq_len > self.max_seq_len_cached: # growth
  102. inv_freq, self.attention_scaling = self.rope_init_fn(
  103. self.config, device, seq_len=seq_len, **self.rope_kwargs
  104. )
  105. self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
  106. self.max_seq_len_cached = seq_len
  107. if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
  108. self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
  109. self.max_seq_len_cached = self.original_max_seq_len
  110. @torch.no_grad()
  111. def forward(self, x, position_ids):
  112. if "dynamic" in self.rope_type:
  113. self._dynamic_frequency_update(position_ids, device=x.device)
  114. # Core RoPE block
  115. inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
  116. position_ids_expanded = position_ids[:, None, :].float()
  117. # Force float32 (see https://github.com/huggingface/transformers/pull/29285)
  118. device_type = x.device.type
  119. device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
  120. with torch.autocast(device_type=device_type, enabled=False):
  121. freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
  122. emb = torch.cat((freqs, freqs), dim=-1)
  123. cos = emb.cos()
  124. sin = emb.sin()
  125. # Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
  126. cos = cos * self.attention_scaling
  127. sin = sin * self.attention_scaling
  128. return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
  129. # Copied from transformers.models.llama.modeling_llama.LlamaLinearScalingRotaryEmbedding with Llama->Phi
  130. class PhiLinearScalingRotaryEmbedding(PhiRotaryEmbedding):
  131. """PhiRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
  132. def __init__(self, *args, **kwargs):
  133. logger.warning_once(
  134. "`PhiLinearScalingRotaryEmbedding` is deprecated an will be removed in v4.46. Please use "
  135. "`PhiRotaryEmbedding`, which now also does linear scaling (simply pass the model config to __init__)."
  136. )
  137. kwargs["rope_type"] = "linear"
  138. super().__init__(*args, **kwargs)
  139. # Copied from transformers.models.llama.modeling_llama.LlamaDynamicNTKScalingRotaryEmbedding with Llama->Phi
  140. class PhiDynamicNTKScalingRotaryEmbedding(PhiRotaryEmbedding):
  141. """PhiRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
  142. def __init__(self, *args, **kwargs):
  143. logger.warning_once(
  144. "`PhiDynamicNTKScalingRotaryEmbedding` is deprecated an will be removed in v4.46. Please use "
  145. "`PhiRotaryEmbedding`, which now also does dynamic ntk scaling (simply pass the model config to "
  146. "__init__)."
  147. )
  148. kwargs["rope_type"] = "dynamic"
  149. super().__init__(*args, **kwargs)
  150. # Copied from transformers.models.llama.modeling_llama.rotate_half
  151. def rotate_half(x):
  152. """Rotates half the hidden dims of the input."""
  153. x1 = x[..., : x.shape[-1] // 2]
  154. x2 = x[..., x.shape[-1] // 2 :]
  155. return torch.cat((-x2, x1), dim=-1)
  156. # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
  157. def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
  158. """Applies Rotary Position Embedding to the query and key tensors.
  159. Args:
  160. q (`torch.Tensor`): The query tensor.
  161. k (`torch.Tensor`): The key tensor.
  162. cos (`torch.Tensor`): The cosine part of the rotary embedding.
  163. sin (`torch.Tensor`): The sine part of the rotary embedding.
  164. position_ids (`torch.Tensor`, *optional*):
  165. Deprecated and unused.
  166. unsqueeze_dim (`int`, *optional*, defaults to 1):
  167. The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
  168. sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
  169. that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
  170. k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
  171. cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
  172. the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
  173. Returns:
  174. `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
  175. """
  176. cos = cos.unsqueeze(unsqueeze_dim)
  177. sin = sin.unsqueeze(unsqueeze_dim)
  178. q_embed = (q * cos) + (rotate_half(q) * sin)
  179. k_embed = (k * cos) + (rotate_half(k) * sin)
  180. return q_embed, k_embed
  181. # Copied from transformers.models.clip.modeling_clip.CLIPMLP with CLIP->Phi
  182. class PhiMLP(nn.Module):
  183. def __init__(self, config):
  184. super().__init__()
  185. self.config = config
  186. self.activation_fn = ACT2FN[config.hidden_act]
  187. self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
  188. self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
  189. def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
  190. hidden_states = self.fc1(hidden_states)
  191. hidden_states = self.activation_fn(hidden_states)
  192. hidden_states = self.fc2(hidden_states)
  193. return hidden_states
  194. # Copied from transformers.models.llama.modeling_llama.repeat_kv with llama->phi
  195. def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
  196. """
  197. This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
  198. num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
  199. """
  200. batch, num_key_value_heads, slen, head_dim = hidden_states.shape
  201. if n_rep == 1:
  202. return hidden_states
  203. hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
  204. return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
  205. class PhiAttention(nn.Module):
  206. """Multi-headed attention from 'Attention Is All You Need' paper"""
  207. def __init__(self, config: PhiConfig, layer_idx: Optional[int] = None):
  208. super().__init__()
  209. self.config = config
  210. self.layer_idx = layer_idx
  211. if layer_idx is None:
  212. logger.warning_once(
  213. f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
  214. "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
  215. "when creating this class."
  216. )
  217. self.attention_dropout = config.attention_dropout
  218. self.hidden_size = config.hidden_size
  219. self.num_heads = config.num_attention_heads
  220. self.head_dim = self.hidden_size // self.num_heads
  221. self.num_key_value_heads = config.num_key_value_heads
  222. self.num_key_value_groups = self.num_heads // self.num_key_value_heads
  223. self.rope_theta = config.rope_theta
  224. self.rotary_ndims = int(self.head_dim * config.partial_rotary_factor)
  225. self.is_causal = True
  226. if (self.head_dim * self.num_heads) != self.hidden_size:
  227. raise ValueError(
  228. f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
  229. f" and `num_heads`: {self.num_heads})."
  230. )
  231. self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=True)
  232. self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
  233. self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
  234. self.dense = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=True)
  235. self.qk_layernorm = config.qk_layernorm
  236. if self.qk_layernorm:
  237. self.q_layernorm = nn.LayerNorm(
  238. config.hidden_size // self.num_heads, eps=config.layer_norm_eps, elementwise_affine=True
  239. )
  240. self.k_layernorm = nn.LayerNorm(
  241. config.hidden_size // self.num_heads, eps=config.layer_norm_eps, elementwise_affine=True
  242. )
  243. self.rotary_emb = PhiRotaryEmbedding(config=self.config)
  244. def forward(
  245. self,
  246. hidden_states: torch.Tensor,
  247. attention_mask: Optional[torch.Tensor] = None,
  248. position_ids: Optional[torch.LongTensor] = None,
  249. past_key_value: Optional[Cache] = None,
  250. output_attentions: bool = False,
  251. use_cache: bool = False,
  252. cache_position: Optional[torch.LongTensor] = None,
  253. position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
  254. ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
  255. bsz, q_len, _ = hidden_states.size()
  256. query_states = self.q_proj(hidden_states)
  257. key_states = self.k_proj(hidden_states)
  258. value_states = self.v_proj(hidden_states)
  259. if self.qk_layernorm:
  260. query_states = self.q_layernorm(query_states)
  261. key_states = self.k_layernorm(key_states)
  262. query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
  263. key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
  264. value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
  265. if position_embeddings is None:
  266. logger.warning_once(
  267. "The attention layers in this model are transitioning from computing the RoPE embeddings internally "
  268. "through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
  269. "`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.46 `position_ids` will be "
  270. "removed and `position_embeddings` will be mandatory."
  271. )
  272. cos, sin = self.rotary_emb(value_states, position_ids)
  273. else:
  274. cos, sin = position_embeddings
  275. # Partial rotary embedding
  276. query_rot, query_pass = (
  277. query_states[..., : self.rotary_ndims],
  278. query_states[..., self.rotary_ndims :],
  279. )
  280. key_rot, key_pass = (
  281. key_states[..., : self.rotary_ndims],
  282. key_states[..., self.rotary_ndims :],
  283. )
  284. # [batch_size, seq_length, num_heads, head_dim // config.partial_rotary_factor]
  285. query_rot, key_rot = apply_rotary_pos_emb(query_rot, key_rot, cos, sin)
  286. # [batch_size, seq_length, num_heads, head_dim]
  287. query_states = torch.cat((query_rot, query_pass), dim=-1)
  288. key_states = torch.cat((key_rot, key_pass), dim=-1)
  289. if past_key_value is not None:
  290. cache_kwargs = {
  291. "sin": sin,
  292. "cos": cos,
  293. "partial_rotation_size": self.rotary_ndims,
  294. "cache_position": cache_position,
  295. }
  296. key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
  297. key_states = repeat_kv(key_states, self.num_key_value_groups)
  298. value_states = repeat_kv(value_states, self.num_key_value_groups)
  299. # Queries and keys upcast to fp32 is required by Phi-2 to avoid overflow
  300. attn_weights = torch.matmul(
  301. query_states.to(torch.float32), key_states.to(torch.float32).transpose(2, 3)
  302. ) / math.sqrt(self.head_dim)
  303. if attention_mask is not None:
  304. causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
  305. attn_weights += causal_mask
  306. # upcast attention to fp32
  307. attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(value_states.dtype)
  308. attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
  309. attn_output = torch.matmul(attn_weights, value_states)
  310. if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
  311. raise ValueError(
  312. f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
  313. f" {attn_output.size()}"
  314. )
  315. attn_output = attn_output.transpose(1, 2).contiguous()
  316. attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
  317. attn_output = self.dense(attn_output)
  318. if not output_attentions:
  319. attn_weights = None
  320. return attn_output, attn_weights, past_key_value
  321. class PhiFlashAttention2(PhiAttention):
  322. """
  323. Phi flash attention module. This module inherits from `PhiAttention` as the weights of the module stays
  324. untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
  325. flash attention and deal with padding tokens in case the input contains any of them.
  326. """
  327. # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
  328. def __init__(self, *args, **kwargs):
  329. super().__init__(*args, **kwargs)
  330. # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
  331. # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
  332. # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
  333. self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
  334. def forward(
  335. self,
  336. hidden_states: torch.Tensor,
  337. attention_mask: Optional[torch.LongTensor] = None,
  338. position_ids: Optional[torch.LongTensor] = None,
  339. past_key_value: Optional[Cache] = None,
  340. output_attentions: bool = False,
  341. use_cache: bool = False,
  342. cache_position: Optional[torch.LongTensor] = None,
  343. position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
  344. **kwargs,
  345. ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
  346. # PhiFlashAttention2 attention does not support output_attentions
  347. output_attentions = False
  348. bsz, q_len, _ = hidden_states.size()
  349. query_states = self.q_proj(hidden_states)
  350. key_states = self.k_proj(hidden_states)
  351. value_states = self.v_proj(hidden_states)
  352. if self.qk_layernorm:
  353. query_states = self.q_layernorm(query_states)
  354. key_states = self.k_layernorm(key_states)
  355. # Flash attention requires the input to have the shape
  356. # batch_size x seq_length x head_dim x hidden_dim
  357. # therefore we just need to keep the original shape
  358. query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
  359. key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
  360. value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
  361. if position_embeddings is None:
  362. logger.warning_once(
  363. "The attention layers in this model are transitioning from computing the RoPE embeddings internally "
  364. "through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
  365. "`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.46 `position_ids` will be "
  366. "removed and `position_embeddings` will be mandatory."
  367. )
  368. cos, sin = self.rotary_emb(value_states, position_ids)
  369. else:
  370. cos, sin = position_embeddings
  371. # Partial rotary embedding
  372. query_rot, query_pass = (
  373. query_states[..., : self.rotary_ndims],
  374. query_states[..., self.rotary_ndims :],
  375. )
  376. key_rot, key_pass = (
  377. key_states[..., : self.rotary_ndims],
  378. key_states[..., self.rotary_ndims :],
  379. )
  380. # [batch_size, seq_length, num_heads, head_dim // config.partial_rotary_factor]
  381. query_rot, key_rot = apply_rotary_pos_emb(query_rot, key_rot, cos, sin)
  382. # [batch_size, seq_length, num_heads, head_dim]
  383. query_states = torch.cat((query_rot, query_pass), dim=-1)
  384. key_states = torch.cat((key_rot, key_pass), dim=-1)
  385. if past_key_value is not None:
  386. cache_kwargs = {
  387. "sin": sin,
  388. "cos": cos,
  389. "partial_rotation_size": self.rotary_ndims,
  390. "cache_position": cache_position,
  391. }
  392. key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
  393. # TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
  394. # to be able to avoid many of these transpose/reshape/view.
  395. query_states = query_states.transpose(1, 2)
  396. key_states = key_states.transpose(1, 2)
  397. value_states = value_states.transpose(1, 2)
  398. attn_dropout = self.attention_dropout if self.training else 0.0
  399. # In PEFT, usually we cast the layer norms in float32 for training stability reasons
  400. # therefore the input hidden states gets silently casted in float32. Hence, we need
  401. # cast them back in the correct dtype just to be sure everything works as expected.
  402. # This might slowdown training & inference so it is recommended to not cast the LayerNorms
  403. # in fp32.
  404. if query_states.dtype == torch.float32:
  405. if torch.is_autocast_enabled():
  406. target_dtype = torch.get_autocast_gpu_dtype()
  407. # Handle the case where the model is quantized
  408. elif hasattr(self.config, "_pre_quantization_dtype"):
  409. target_dtype = self.config._pre_quantization_dtype
  410. else:
  411. target_dtype = self.q_proj.weight.dtype
  412. logger.warning_once(
  413. f"The input hidden states seems to be silently casted in float32, this might be related to"
  414. f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
  415. f" {target_dtype}."
  416. )
  417. query_states = query_states.to(target_dtype)
  418. key_states = key_states.to(target_dtype)
  419. value_states = value_states.to(target_dtype)
  420. attn_output = _flash_attention_forward(
  421. query_states,
  422. key_states,
  423. value_states,
  424. attention_mask,
  425. q_len,
  426. position_ids=position_ids,
  427. dropout=attn_dropout,
  428. softmax_scale=None,
  429. use_top_left_mask=self._flash_attn_uses_top_left_mask,
  430. is_causal=self.is_causal,
  431. )
  432. attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
  433. attn_output = self.dense(attn_output)
  434. if not output_attentions:
  435. attn_weights = None
  436. return attn_output, attn_weights, past_key_value
  437. class PhiSdpaAttention(PhiAttention):
  438. def __init__(self, *args, **kwargs):
  439. super().__init__(*args, **kwargs)
  440. self.require_contiguous_qkv = version.parse(get_torch_version()) < version.parse("2.2.0")
  441. """
  442. SDPA attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
  443. `PhiAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
  444. SDPA API.
  445. """
  446. # Adapted from PhiAttention.forward
  447. def forward(
  448. self,
  449. hidden_states: torch.Tensor,
  450. attention_mask: Optional[torch.Tensor] = None,
  451. position_ids: Optional[torch.LongTensor] = None,
  452. past_key_value: Optional[Cache] = None,
  453. output_attentions: bool = False,
  454. use_cache: bool = False,
  455. cache_position: Optional[torch.LongTensor] = None,
  456. position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
  457. ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
  458. if output_attentions:
  459. # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
  460. logger.warning_once(
  461. "PhiModel is using PhiSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not "
  462. "support `output_attentions=True`. Falling back to the manual attention implementation, but specifying "
  463. "the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can "
  464. 'be removed using the argument `attn_implementation="eager"` when loading the model.'
  465. )
  466. return super().forward(
  467. hidden_states=hidden_states,
  468. attention_mask=attention_mask,
  469. position_ids=position_ids,
  470. past_key_value=past_key_value,
  471. output_attentions=output_attentions,
  472. use_cache=use_cache,
  473. )
  474. bsz, q_len, _ = hidden_states.size()
  475. query_states = self.q_proj(hidden_states)
  476. key_states = self.k_proj(hidden_states)
  477. value_states = self.v_proj(hidden_states)
  478. if self.qk_layernorm:
  479. query_states = self.q_layernorm(query_states)
  480. key_states = self.k_layernorm(key_states)
  481. query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
  482. key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
  483. value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
  484. if position_embeddings is None:
  485. logger.warning_once(
  486. "The attention layers in this model are transitioning from computing the RoPE embeddings internally "
  487. "through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
  488. "`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.46 `position_ids` will be "
  489. "removed and `position_embeddings` will be mandatory."
  490. )
  491. cos, sin = self.rotary_emb(value_states, position_ids)
  492. else:
  493. cos, sin = position_embeddings
  494. # Partial rotary embedding
  495. query_rot, query_pass = (
  496. query_states[..., : self.rotary_ndims],
  497. query_states[..., self.rotary_ndims :],
  498. )
  499. key_rot, key_pass = (
  500. key_states[..., : self.rotary_ndims],
  501. key_states[..., self.rotary_ndims :],
  502. )
  503. # [batch_size, seq_length, num_heads, head_dim // config.partial_rotary_factor]
  504. query_rot, key_rot = apply_rotary_pos_emb(query_rot, key_rot, cos, sin)
  505. # [batch_size, seq_length, num_heads, head_dim]
  506. query_states = torch.cat((query_rot, query_pass), dim=-1)
  507. key_states = torch.cat((key_rot, key_pass), dim=-1)
  508. if past_key_value is not None:
  509. cache_kwargs = {
  510. "sin": sin,
  511. "cos": cos,
  512. "partial_rotation_size": self.rotary_ndims,
  513. "cache_position": cache_position,
  514. }
  515. key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
  516. key_states = repeat_kv(key_states, self.num_key_value_groups)
  517. value_states = repeat_kv(value_states, self.num_key_value_groups)
  518. causal_mask = attention_mask
  519. if attention_mask is not None:
  520. causal_mask = causal_mask[:, :, :, : key_states.shape[-2]]
  521. # SDPA with memory-efficient backend is broken in torch==2.1.2 when using non-contiguous inputs and a custom
  522. # attn_mask, so we need to call `.contiguous()` here. This was fixed in torch==2.2.0.
  523. # Reference: https://github.com/pytorch/pytorch/issues/112577
  524. if self.require_contiguous_qkv and query_states.device.type == "cuda" and attention_mask is not None:
  525. query_states = query_states.contiguous()
  526. key_states = key_states.contiguous()
  527. value_states = value_states.contiguous()
  528. # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
  529. # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
  530. is_causal = True if causal_mask is None and q_len > 1 else False
  531. attn_output = torch.nn.functional.scaled_dot_product_attention(
  532. query_states,
  533. key_states,
  534. value_states,
  535. attn_mask=causal_mask,
  536. dropout_p=self.attention_dropout if self.training else 0.0,
  537. is_causal=is_causal,
  538. )
  539. attn_output = attn_output.transpose(1, 2).contiguous()
  540. attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
  541. attn_output = self.dense(attn_output)
  542. return attn_output, None, past_key_value
  543. PHI_ATTENTION_CLASSES = {
  544. "eager": PhiAttention,
  545. "flash_attention_2": PhiFlashAttention2,
  546. "sdpa": PhiSdpaAttention,
  547. }
  548. class PhiDecoderLayer(nn.Module):
  549. def __init__(self, config: PhiConfig, layer_idx: int):
  550. super().__init__()
  551. self.self_attn = PHI_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx=layer_idx)
  552. self.mlp = PhiMLP(config)
  553. self.input_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  554. self.resid_dropout = nn.Dropout(config.resid_pdrop)
  555. def forward(
  556. self,
  557. hidden_states: torch.Tensor,
  558. attention_mask: Optional[torch.Tensor] = None,
  559. position_ids: Optional[torch.LongTensor] = None,
  560. output_attentions: Optional[bool] = False,
  561. use_cache: Optional[bool] = False,
  562. past_key_value: Optional[Tuple[torch.Tensor]] = None,
  563. cache_position: Optional[torch.LongTensor] = None,
  564. position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
  565. **kwargs,
  566. ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
  567. """
  568. Args:
  569. hidden_states (`torch.FloatTensor`):
  570. input to the layer of shape `(batch, seq_len, embed_dim)`
  571. attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
  572. `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
  573. position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
  574. Indices of positions of each input sequence tokens in the position embeddings. Selected in the range
  575. `[0, config.n_positions - 1]`. [What are position IDs?](../glossary#position-ids)
  576. output_attentions (`bool`, *optional*):
  577. Whether or not to return the attentions tensors of all attention layers. See `attentions` under
  578. returned tensors for more detail.
  579. use_cache (`bool`, *optional*):
  580. If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
  581. (see `past_key_values`).
  582. past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
  583. cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
  584. Indices depicting the position of the input sequence tokens in the sequence
  585. position_embeddings (`Tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
  586. Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
  587. with `head_dim` being the embedding dimension of each attention head.
  588. kwargs (`dict`, *optional*):
  589. Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
  590. into the model
  591. """
  592. residual = hidden_states
  593. hidden_states = self.input_layernorm(hidden_states)
  594. # Self Attention
  595. attn_outputs, self_attn_weights, present_key_value = self.self_attn(
  596. hidden_states=hidden_states,
  597. attention_mask=attention_mask,
  598. position_ids=position_ids,
  599. past_key_value=past_key_value,
  600. output_attentions=output_attentions,
  601. use_cache=use_cache,
  602. cache_position=cache_position,
  603. position_embeddings=position_embeddings,
  604. )
  605. attn_outputs = self.resid_dropout(attn_outputs)
  606. feed_forward_hidden_states = self.resid_dropout(self.mlp(hidden_states))
  607. hidden_states = attn_outputs + feed_forward_hidden_states + residual
  608. outputs = (hidden_states,)
  609. if output_attentions:
  610. outputs += (self_attn_weights,)
  611. if use_cache:
  612. outputs += (present_key_value,)
  613. return outputs
  614. PHI_START_DOCSTRING = r"""
  615. This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
  616. library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
  617. etc.)
  618. This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
  619. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
  620. and behavior.
  621. Parameters:
  622. config ([`PhiConfig`]):
  623. Model configuration class with all the parameters of the model. Initializing with a config file does not
  624. load the weights associated with the model, only the configuration. Check out the
  625. [`~PreTrainedModel.from_pretrained`] method to load the model weights.
  626. """
  627. @add_start_docstrings(
  628. "The bare Phi Model outputting raw hidden-states without any specific head on top.",
  629. PHI_START_DOCSTRING,
  630. )
  631. class PhiPreTrainedModel(PreTrainedModel):
  632. config_class = PhiConfig
  633. base_model_prefix = "model"
  634. supports_gradient_checkpointing = True
  635. _no_split_modules = ["PhiDecoderLayer"]
  636. _skip_keys_device_placement = "past_key_values"
  637. _supports_flash_attn_2 = True
  638. _supports_sdpa = True
  639. _supports_cache_class = True
  640. _supports_static_cache = True
  641. _supports_quantized_cache = True
  642. def _init_weights(self, module):
  643. std = self.config.initializer_range
  644. if isinstance(module, nn.Linear):
  645. module.weight.data.normal_(mean=0.0, std=std)
  646. if module.bias is not None:
  647. module.bias.data.zero_()
  648. elif isinstance(module, nn.Embedding):
  649. module.weight.data.normal_(mean=0.0, std=std)
  650. if module.padding_idx is not None:
  651. module.weight.data[module.padding_idx].zero_()
  652. PHI_INPUTS_DOCSTRING = r"""
  653. Args:
  654. input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
  655. Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
  656. it.
  657. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
  658. [`PreTrainedTokenizer.__call__`] for details.
  659. [What are input IDs?](../glossary#input-ids)
  660. attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
  661. Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
  662. - 1 for tokens that are **not masked**,
  663. - 0 for tokens that are **masked**.
  664. [What are attention masks?](../glossary#attention-mask)
  665. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
  666. [`PreTrainedTokenizer.__call__`] for details.
  667. If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
  668. `past_key_values`).
  669. If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
  670. and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
  671. information on the default strategy.
  672. - 1 indicates the head is **not masked**,
  673. - 0 indicates the head is **masked**.
  674. position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  675. Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
  676. config.n_positions - 1]`.
  677. [What are position IDs?](../glossary#position-ids)
  678. past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
  679. Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
  680. blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
  681. returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
  682. Two formats are allowed:
  683. - a [`~cache_utils.Cache`] instance, see our
  684. [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);
  685. - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
  686. shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
  687. cache format.
  688. The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
  689. legacy cache format will be returned.
  690. If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
  691. have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
  692. of shape `(batch_size, sequence_length)`.
  693. inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
  694. Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
  695. is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
  696. model's internal embedding lookup matrix.
  697. use_cache (`bool`, *optional*):
  698. If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
  699. `past_key_values`).
  700. output_attentions (`bool`, *optional*):
  701. Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
  702. tensors for more detail.
  703. output_hidden_states (`bool`, *optional*):
  704. Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
  705. more detail.
  706. return_dict (`bool`, *optional*):
  707. Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
  708. cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
  709. Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
  710. this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
  711. the complete sequence length.
  712. """
  713. @add_start_docstrings(
  714. "The bare Phi Model outputting raw hidden-states without any specific head on top.",
  715. PHI_START_DOCSTRING,
  716. )
  717. class PhiModel(PhiPreTrainedModel):
  718. """
  719. Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`PhiDecoderLayer`]
  720. Args:
  721. config: PhiConfig
  722. """
  723. def __init__(self, config: PhiConfig):
  724. super().__init__(config)
  725. self.padding_idx = config.pad_token_id
  726. self.vocab_size = config.vocab_size
  727. self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
  728. self.embed_dropout = nn.Dropout(config.embd_pdrop)
  729. self.layers = nn.ModuleList(
  730. [PhiDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
  731. )
  732. self.final_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  733. self.rotary_emb = PhiRotaryEmbedding(config=config)
  734. self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
  735. self._use_sdpa = config._attn_implementation == "sdpa"
  736. self.gradient_checkpointing = False
  737. # Initialize weights and apply final processing
  738. self.post_init()
  739. def get_input_embeddings(self):
  740. return self.embed_tokens
  741. def set_input_embeddings(self, value):
  742. self.embed_tokens = value
  743. @add_start_docstrings_to_model_forward(PHI_INPUTS_DOCSTRING)
  744. def forward(
  745. self,
  746. input_ids: torch.LongTensor = None,
  747. attention_mask: Optional[torch.Tensor] = None,
  748. position_ids: Optional[torch.LongTensor] = None,
  749. past_key_values: Optional[List[torch.FloatTensor]] = None,
  750. inputs_embeds: Optional[torch.FloatTensor] = None,
  751. use_cache: Optional[bool] = None,
  752. output_attentions: Optional[bool] = None,
  753. output_hidden_states: Optional[bool] = None,
  754. return_dict: Optional[bool] = None,
  755. cache_position: Optional[torch.LongTensor] = None,
  756. ) -> Union[Tuple, BaseModelOutputWithPast]:
  757. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  758. output_hidden_states = (
  759. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  760. )
  761. use_cache = use_cache if use_cache is not None else self.config.use_cache
  762. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  763. if (input_ids is None) ^ (inputs_embeds is not None):
  764. raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
  765. if self.gradient_checkpointing and self.training:
  766. if use_cache:
  767. logger.warning_once(
  768. "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
  769. )
  770. use_cache = False
  771. # kept for BC (non `Cache` `past_key_values` inputs)
  772. return_legacy_cache = False
  773. if use_cache and not isinstance(past_key_values, Cache):
  774. return_legacy_cache = True
  775. if past_key_values is None:
  776. past_key_values = DynamicCache()
  777. else:
  778. past_key_values = DynamicCache.from_legacy_cache(past_key_values)
  779. logger.warning_once(
  780. "We detected that you are passing `past_key_values` as a tuple of tuples. This is deprecated and "
  781. "will be removed in v4.47. Please convert your cache or use an appropriate `Cache` class "
  782. "(https://huggingface.co/docs/transformers/kv_cache#legacy-cache-format)"
  783. )
  784. if inputs_embeds is None:
  785. inputs_embeds = self.embed_tokens(input_ids)
  786. if cache_position is None:
  787. past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
  788. cache_position = torch.arange(
  789. past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
  790. )
  791. if position_ids is None:
  792. position_ids = cache_position.unsqueeze(0)
  793. causal_mask = self._update_causal_mask(
  794. attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
  795. )
  796. inputs_embeds = self.embed_dropout(inputs_embeds)
  797. hidden_states = inputs_embeds
  798. # create position embeddings to be shared across the decoder layers
  799. position_embeddings = self.rotary_emb(hidden_states, position_ids)
  800. # decoder layers
  801. all_hidden_states = () if output_hidden_states else None
  802. all_self_attns = () if output_attentions else None
  803. next_decoder_cache = None
  804. for decoder_layer in self.layers:
  805. if output_hidden_states:
  806. all_hidden_states += (hidden_states,)
  807. if self.gradient_checkpointing and self.training:
  808. layer_outputs = self._gradient_checkpointing_func(
  809. decoder_layer.__call__,
  810. hidden_states,
  811. causal_mask,
  812. position_ids,
  813. output_attentions,
  814. use_cache,
  815. past_key_values,
  816. cache_position,
  817. position_embeddings,
  818. )
  819. else:
  820. layer_outputs = decoder_layer(
  821. hidden_states,
  822. attention_mask=causal_mask,
  823. position_ids=position_ids,
  824. past_key_value=past_key_values,
  825. output_attentions=output_attentions,
  826. use_cache=use_cache,
  827. cache_position=cache_position,
  828. position_embeddings=position_embeddings,
  829. )
  830. hidden_states = layer_outputs[0]
  831. if use_cache:
  832. next_decoder_cache = layer_outputs[2 if output_attentions else 1]
  833. if output_attentions:
  834. all_self_attns += (layer_outputs[1],)
  835. hidden_states = self.final_layernorm(hidden_states)
  836. # add hidden states from the last decoder layer
  837. if output_hidden_states:
  838. all_hidden_states += (hidden_states,)
  839. next_cache = next_decoder_cache if use_cache else None
  840. if return_legacy_cache:
  841. next_cache = next_cache.to_legacy_cache()
  842. if not return_dict:
  843. return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
  844. return BaseModelOutputWithPast(
  845. last_hidden_state=hidden_states,
  846. past_key_values=next_cache,
  847. hidden_states=all_hidden_states,
  848. attentions=all_self_attns,
  849. )
  850. # Copied from transformers.models.llama.modeling_llama.LlamaModel._update_causal_mask
  851. def _update_causal_mask(
  852. self,
  853. attention_mask: torch.Tensor,
  854. input_tensor: torch.Tensor,
  855. cache_position: torch.Tensor,
  856. past_key_values: Cache,
  857. output_attentions: bool,
  858. ):
  859. if self.config._attn_implementation == "flash_attention_2":
  860. if attention_mask is not None and 0.0 in attention_mask:
  861. return attention_mask
  862. return None
  863. # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
  864. # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
  865. # to infer the attention mask.
  866. past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
  867. using_static_cache = isinstance(past_key_values, StaticCache)
  868. # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
  869. if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
  870. if AttentionMaskConverter._ignore_causal_mask_sdpa(
  871. attention_mask,
  872. inputs_embeds=input_tensor,
  873. past_key_values_length=past_seen_tokens,
  874. is_training=self.training,
  875. ):
  876. return None
  877. dtype, device = input_tensor.dtype, input_tensor.device
  878. sequence_length = input_tensor.shape[1]
  879. if using_static_cache:
  880. target_length = past_key_values.get_max_cache_shape()
  881. else:
  882. target_length = (
  883. attention_mask.shape[-1]
  884. if isinstance(attention_mask, torch.Tensor)
  885. else past_seen_tokens + sequence_length + 1
  886. )
  887. # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
  888. causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
  889. attention_mask,
  890. sequence_length=sequence_length,
  891. target_length=target_length,
  892. dtype=dtype,
  893. device=device,
  894. cache_position=cache_position,
  895. batch_size=input_tensor.shape[0],
  896. )
  897. if (
  898. self.config._attn_implementation == "sdpa"
  899. and attention_mask is not None
  900. and attention_mask.device.type == "cuda"
  901. and not output_attentions
  902. ):
  903. # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
  904. # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
  905. # Details: https://github.com/pytorch/pytorch/issues/110213
  906. min_dtype = torch.finfo(dtype).min
  907. causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
  908. return causal_mask
  909. @staticmethod
  910. # Copied from transformers.models.llama.modeling_llama.LlamaModel._prepare_4d_causal_attention_mask_with_cache_position
  911. def _prepare_4d_causal_attention_mask_with_cache_position(
  912. attention_mask: torch.Tensor,
  913. sequence_length: int,
  914. target_length: int,
  915. dtype: torch.dtype,
  916. device: torch.device,
  917. cache_position: torch.Tensor,
  918. batch_size: int,
  919. **kwargs,
  920. ):
  921. """
  922. Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
  923. `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
  924. Args:
  925. attention_mask (`torch.Tensor`):
  926. A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
  927. `(batch_size, 1, query_length, key_value_length)`.
  928. sequence_length (`int`):
  929. The sequence length being processed.
  930. target_length (`int`):
  931. The target length: when generating with static cache, the mask should be as long as the static cache,
  932. to account for the 0 padding, the part of the cache that is not filled yet.
  933. dtype (`torch.dtype`):
  934. The dtype to use for the 4D attention mask.
  935. device (`torch.device`):
  936. The device to plcae the 4D attention mask on.
  937. cache_position (`torch.Tensor`):
  938. Indices depicting the position of the input sequence tokens in the sequence.
  939. batch_size (`torch.Tensor`):
  940. Batch size.
  941. """
  942. if attention_mask is not None and attention_mask.dim() == 4:
  943. # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
  944. causal_mask = attention_mask
  945. else:
  946. min_dtype = torch.finfo(dtype).min
  947. causal_mask = torch.full(
  948. (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
  949. )
  950. if sequence_length != 1:
  951. causal_mask = torch.triu(causal_mask, diagonal=1)
  952. causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
  953. causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
  954. if attention_mask is not None:
  955. causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
  956. mask_length = attention_mask.shape[-1]
  957. padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
  958. padding_mask = padding_mask == 0
  959. causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
  960. padding_mask, min_dtype
  961. )
  962. return causal_mask
  963. class PhiForCausalLM(PhiPreTrainedModel, GenerationMixin):
  964. _tied_weights_keys = ["lm_head.weight"]
  965. # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.__init__ with Llama->Phi,bias=False->bias=True
  966. def __init__(self, config):
  967. super().__init__(config)
  968. self.model = PhiModel(config)
  969. self.vocab_size = config.vocab_size
  970. self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=True)
  971. # Initialize weights and apply final processing
  972. self.post_init()
  973. # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_input_embeddings
  974. def get_input_embeddings(self):
  975. return self.model.embed_tokens
  976. # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_input_embeddings
  977. def set_input_embeddings(self, value):
  978. self.model.embed_tokens = value
  979. # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_output_embeddings
  980. def get_output_embeddings(self):
  981. return self.lm_head
  982. # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_output_embeddings
  983. def set_output_embeddings(self, new_embeddings):
  984. self.lm_head = new_embeddings
  985. # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_decoder
  986. def set_decoder(self, decoder):
  987. self.model = decoder
  988. # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_decoder
  989. def get_decoder(self):
  990. return self.model
  991. @add_start_docstrings_to_model_forward(PHI_INPUTS_DOCSTRING)
  992. @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
  993. def forward(
  994. self,
  995. input_ids: torch.LongTensor = None,
  996. attention_mask: Optional[torch.Tensor] = None,
  997. position_ids: Optional[torch.LongTensor] = None,
  998. past_key_values: Optional[List[torch.FloatTensor]] = None,
  999. inputs_embeds: Optional[torch.FloatTensor] = None,
  1000. labels: Optional[torch.LongTensor] = None,
  1001. use_cache: Optional[bool] = None,
  1002. output_attentions: Optional[bool] = None,
  1003. output_hidden_states: Optional[bool] = None,
  1004. return_dict: Optional[bool] = None,
  1005. cache_position: Optional[torch.LongTensor] = None,
  1006. num_logits_to_keep: int = 0,
  1007. **loss_kwargs,
  1008. ) -> Union[Tuple, CausalLMOutputWithPast]:
  1009. r"""
  1010. Args:
  1011. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  1012. Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
  1013. config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
  1014. (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
  1015. num_logits_to_keep (`int`, *optional*):
  1016. Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all
  1017. `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
  1018. token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
  1019. Returns:
  1020. Example:
  1021. ```python
  1022. >>> from transformers import AutoTokenizer, PhiForCausalLM
  1023. >>> model = PhiForCausalLM.from_pretrained("microsoft/phi-1")
  1024. >>> tokenizer = AutoTokenizer.from_pretrained("microsoft/phi-1")
  1025. >>> prompt = "This is an example script ."
  1026. >>> inputs = tokenizer(prompt, return_tensors="pt")
  1027. >>> # Generate
  1028. >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
  1029. >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
  1030. 'This is an example script .\n\n\n\nfrom typing import List\n\ndef find_most_common_letter(words: List[str'
  1031. ```"""
  1032. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  1033. output_hidden_states = (
  1034. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  1035. )
  1036. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  1037. # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
  1038. outputs = self.model(
  1039. input_ids=input_ids,
  1040. attention_mask=attention_mask,
  1041. position_ids=position_ids,
  1042. past_key_values=past_key_values,
  1043. inputs_embeds=inputs_embeds,
  1044. use_cache=use_cache,
  1045. output_attentions=output_attentions,
  1046. output_hidden_states=output_hidden_states,
  1047. return_dict=return_dict,
  1048. cache_position=cache_position,
  1049. )
  1050. hidden_states = outputs[0]
  1051. # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
  1052. logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :])
  1053. loss = None
  1054. if labels is not None:
  1055. loss = self.loss_function(logits, labels, self.vocab_size, **loss_kwargs)
  1056. if not return_dict:
  1057. output = (logits,) + outputs[1:]
  1058. return (loss,) + output if loss is not None else output
  1059. return CausalLMOutputWithPast(
  1060. loss=loss,
  1061. logits=logits,
  1062. past_key_values=outputs.past_key_values,
  1063. hidden_states=outputs.hidden_states,
  1064. attentions=outputs.attentions,
  1065. )
  1066. @add_start_docstrings(
  1067. """
  1068. The PhiModel with a sequence classification head on top (linear layer).
  1069. [`PhiForSequenceClassification`] uses the last token in order to do the classification, as other causal models
  1070. (e.g. GPT-2) do.
  1071. Since it does classification on the last token, it requires to know the position of the last token. If a
  1072. `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
  1073. no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
  1074. padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
  1075. each row of the batch).
  1076. """,
  1077. PHI_START_DOCSTRING,
  1078. )
  1079. # Copied from transformers.models.llama.modeling_llama.LlamaForSequenceClassification with LLAMA->PHI,Llama->Phi with self.transformer->self.model, transformer_outputs->model_outputs
  1080. class PhiForSequenceClassification(PhiPreTrainedModel):
  1081. def __init__(self, config):
  1082. super().__init__(config)
  1083. self.num_labels = config.num_labels
  1084. self.model = PhiModel(config)
  1085. self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
  1086. # Initialize weights and apply final processing
  1087. self.post_init()
  1088. def get_input_embeddings(self):
  1089. return self.model.embed_tokens
  1090. def set_input_embeddings(self, value):
  1091. self.model.embed_tokens = value
  1092. @add_start_docstrings_to_model_forward(PHI_INPUTS_DOCSTRING)
  1093. def forward(
  1094. self,
  1095. input_ids: Optional[torch.LongTensor] = None,
  1096. attention_mask: Optional[torch.Tensor] = None,
  1097. position_ids: Optional[torch.LongTensor] = None,
  1098. past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
  1099. inputs_embeds: Optional[torch.FloatTensor] = None,
  1100. labels: Optional[torch.LongTensor] = None,
  1101. use_cache: Optional[bool] = None,
  1102. output_attentions: Optional[bool] = None,
  1103. output_hidden_states: Optional[bool] = None,
  1104. return_dict: Optional[bool] = None,
  1105. ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
  1106. r"""
  1107. labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  1108. Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
  1109. config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
  1110. `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
  1111. """
  1112. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  1113. model_outputs = self.model(
  1114. input_ids,
  1115. attention_mask=attention_mask,
  1116. position_ids=position_ids,
  1117. past_key_values=past_key_values,
  1118. inputs_embeds=inputs_embeds,
  1119. use_cache=use_cache,
  1120. output_attentions=output_attentions,
  1121. output_hidden_states=output_hidden_states,
  1122. return_dict=return_dict,
  1123. )
  1124. hidden_states = model_outputs[0]
  1125. logits = self.score(hidden_states)
  1126. if input_ids is not None:
  1127. batch_size = input_ids.shape[0]
  1128. else:
  1129. batch_size = inputs_embeds.shape[0]
  1130. if self.config.pad_token_id is None and batch_size != 1:
  1131. raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
  1132. if self.config.pad_token_id is None:
  1133. sequence_lengths = -1
  1134. else:
  1135. if input_ids is not None:
  1136. # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
  1137. sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
  1138. sequence_lengths = sequence_lengths % input_ids.shape[-1]
  1139. sequence_lengths = sequence_lengths.to(logits.device)
  1140. else:
  1141. sequence_lengths = -1
  1142. pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
  1143. loss = None
  1144. if labels is not None:
  1145. loss = self.loss_function(logits=logits, labels=labels, pooled_logits=pooled_logits, config=self.config)
  1146. if not return_dict:
  1147. output = (pooled_logits,) + model_outputs[1:]
  1148. return ((loss,) + output) if loss is not None else output
  1149. return SequenceClassifierOutputWithPast(
  1150. loss=loss,
  1151. logits=pooled_logits,
  1152. past_key_values=model_outputs.past_key_values,
  1153. hidden_states=model_outputs.hidden_states,
  1154. attentions=model_outputs.attentions,
  1155. )
  1156. @add_start_docstrings(
  1157. """
  1158. PhiModel with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
  1159. Named-Entity-Recognition (NER) tasks.
  1160. """,
  1161. PHI_START_DOCSTRING,
  1162. )
  1163. # Copied from transformers.models.mpt.modeling_mpt.MptForTokenClassification with MPT->PHI,Mpt->Phi,self.transformer->self.model,transformer_outputs->model_outputs
  1164. class PhiForTokenClassification(PhiPreTrainedModel):
  1165. def __init__(self, config: PhiConfig):
  1166. super().__init__(config)
  1167. self.num_labels = config.num_labels
  1168. self.model = PhiModel(config)
  1169. if hasattr(config, "classifier_dropout") and config.classifier_dropout is not None:
  1170. classifier_dropout = config.classifier_dropout
  1171. elif hasattr(config, "hidden_dropout") and config.hidden_dropout is not None:
  1172. classifier_dropout = config.hidden_dropout
  1173. else:
  1174. classifier_dropout = 0.1
  1175. self.dropout = nn.Dropout(classifier_dropout)
  1176. self.classifier = nn.Linear(config.hidden_size, config.num_labels)
  1177. # Initialize weights and apply final processing
  1178. self.post_init()
  1179. @add_start_docstrings_to_model_forward(PHI_INPUTS_DOCSTRING)
  1180. @add_code_sample_docstrings(
  1181. checkpoint=_CHECKPOINT_FOR_DOC,
  1182. output_type=TokenClassifierOutput,
  1183. config_class=_CONFIG_FOR_DOC,
  1184. )
  1185. def forward(
  1186. self,
  1187. input_ids: Optional[torch.LongTensor] = None,
  1188. past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
  1189. attention_mask: Optional[torch.Tensor] = None,
  1190. inputs_embeds: Optional[torch.Tensor] = None,
  1191. labels: Optional[torch.Tensor] = None,
  1192. use_cache: Optional[bool] = None,
  1193. output_attentions: Optional[bool] = None,
  1194. output_hidden_states: Optional[bool] = None,
  1195. return_dict: Optional[bool] = None,
  1196. **deprecated_arguments,
  1197. ) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
  1198. r"""
  1199. labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  1200. Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
  1201. config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
  1202. `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
  1203. """
  1204. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  1205. model_outputs = self.model(
  1206. input_ids,
  1207. past_key_values=past_key_values,
  1208. attention_mask=attention_mask,
  1209. inputs_embeds=inputs_embeds,
  1210. use_cache=use_cache,
  1211. output_attentions=output_attentions,
  1212. output_hidden_states=output_hidden_states,
  1213. return_dict=return_dict,
  1214. )
  1215. hidden_states = model_outputs[0]
  1216. hidden_states = self.dropout(hidden_states)
  1217. logits = self.classifier(hidden_states)
  1218. loss = None
  1219. if labels is not None:
  1220. # move labels to correct device to enable model parallelism
  1221. labels = labels.to(logits.device)
  1222. batch_size, seq_length = labels.shape
  1223. loss_fct = CrossEntropyLoss()
  1224. loss = loss_fct(
  1225. logits.view(batch_size * seq_length, self.num_labels), labels.view(batch_size * seq_length)
  1226. )
  1227. if not return_dict:
  1228. output = (logits,) + model_outputs[2:]
  1229. return ((loss,) + output) if loss is not None else output
  1230. return TokenClassifierOutput(
  1231. loss=loss,
  1232. logits=logits,
  1233. hidden_states=model_outputs.hidden_states,
  1234. attentions=model_outputs.attentions,
  1235. )