modeling_llama.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. # coding=utf-8
  2. # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
  3. #
  4. # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
  5. # and OPT implementations in this library. It has been modified from its
  6. # original forms to accommodate minor architectural differences compared
  7. # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
  8. #
  9. # Licensed under the Apache License, Version 2.0 (the "License");
  10. # you may not use this file except in compliance with the License.
  11. # You may obtain a copy of the License at
  12. #
  13. # http://www.apache.org/licenses/LICENSE-2.0
  14. #
  15. # Unless required by applicable law or agreed to in writing, software
  16. # distributed under the License is distributed on an "AS IS" BASIS,
  17. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18. # See the License for the specific language governing permissions and
  19. # limitations under the License.
  20. from typing import Callable, Optional, Union
  21. import torch
  22. from torch import nn
  23. from ...activations import ACT2FN
  24. from ...cache_utils import Cache, DynamicCache
  25. from ...generation import GenerationMixin
  26. from ...integrations import use_kernel_forward_from_hub
  27. from ...masking_utils import create_causal_mask
  28. from ...modeling_layers import (
  29. GenericForQuestionAnswering,
  30. GenericForSequenceClassification,
  31. GenericForTokenClassification,
  32. GradientCheckpointingLayer,
  33. )
  34. from ...modeling_outputs import (
  35. BaseModelOutputWithPast,
  36. CausalLMOutputWithPast,
  37. )
  38. from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
  39. from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
  40. from ...processing_utils import Unpack
  41. from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, logging
  42. from ...utils.deprecation import deprecate_kwarg
  43. from ...utils.generic import check_model_inputs
  44. from .configuration_llama import LlamaConfig
  45. logger = logging.get_logger(__name__)
  46. @use_kernel_forward_from_hub("RMSNorm")
  47. class LlamaRMSNorm(nn.Module):
  48. def __init__(self, hidden_size, eps=1e-6):
  49. """
  50. LlamaRMSNorm is equivalent to T5LayerNorm
  51. """
  52. super().__init__()
  53. self.weight = nn.Parameter(torch.ones(hidden_size))
  54. self.variance_epsilon = eps
  55. def forward(self, hidden_states):
  56. input_dtype = hidden_states.dtype
  57. hidden_states = hidden_states.to(torch.float32)
  58. variance = hidden_states.pow(2).mean(-1, keepdim=True)
  59. hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
  60. return self.weight * hidden_states.to(input_dtype)
  61. def extra_repr(self):
  62. return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
  63. class LlamaRotaryEmbedding(nn.Module):
  64. inv_freq: torch.Tensor # fix linting for `register_buffer`
  65. def __init__(self, config: LlamaConfig, device=None):
  66. super().__init__()
  67. # BC: "rope_type" was originally "type"
  68. if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
  69. self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
  70. else:
  71. self.rope_type = "default"
  72. self.max_seq_len_cached = config.max_position_embeddings
  73. self.original_max_seq_len = config.max_position_embeddings
  74. self.config = config
  75. self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
  76. inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
  77. self.register_buffer("inv_freq", inv_freq, persistent=False)
  78. self.original_inv_freq = self.inv_freq
  79. @torch.no_grad()
  80. @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
  81. def forward(self, x, position_ids):
  82. inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
  83. position_ids_expanded = position_ids[:, None, :].float()
  84. device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
  85. with torch.autocast(device_type=device_type, enabled=False): # Force float32
  86. freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
  87. emb = torch.cat((freqs, freqs), dim=-1)
  88. cos = emb.cos() * self.attention_scaling
  89. sin = emb.sin() * self.attention_scaling
  90. return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
  91. def rotate_half(x):
  92. """Rotates half the hidden dims of the input."""
  93. x1 = x[..., : x.shape[-1] // 2]
  94. x2 = x[..., x.shape[-1] // 2 :]
  95. return torch.cat((-x2, x1), dim=-1)
  96. def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
  97. """Applies Rotary Position Embedding to the query and key tensors.
  98. Args:
  99. q (`torch.Tensor`): The query tensor.
  100. k (`torch.Tensor`): The key tensor.
  101. cos (`torch.Tensor`): The cosine part of the rotary embedding.
  102. sin (`torch.Tensor`): The sine part of the rotary embedding.
  103. position_ids (`torch.Tensor`, *optional*):
  104. Deprecated and unused.
  105. unsqueeze_dim (`int`, *optional*, defaults to 1):
  106. The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
  107. sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
  108. that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
  109. k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
  110. cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
  111. the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
  112. Returns:
  113. `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
  114. """
  115. cos = cos.unsqueeze(unsqueeze_dim)
  116. sin = sin.unsqueeze(unsqueeze_dim)
  117. q_embed = (q * cos) + (rotate_half(q) * sin)
  118. k_embed = (k * cos) + (rotate_half(k) * sin)
  119. return q_embed, k_embed
  120. class LlamaMLP(nn.Module):
  121. def __init__(self, config):
  122. super().__init__()
  123. self.config = config
  124. self.hidden_size = config.hidden_size
  125. self.intermediate_size = config.intermediate_size
  126. self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
  127. self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
  128. self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
  129. self.act_fn = ACT2FN[config.hidden_act]
  130. def forward(self, x):
  131. down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
  132. return down_proj
  133. def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
  134. """
  135. This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
  136. num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
  137. """
  138. batch, num_key_value_heads, slen, head_dim = hidden_states.shape
  139. if n_rep == 1:
  140. return hidden_states
  141. hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
  142. return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
  143. def eager_attention_forward(
  144. module: nn.Module,
  145. query: torch.Tensor,
  146. key: torch.Tensor,
  147. value: torch.Tensor,
  148. attention_mask: Optional[torch.Tensor],
  149. scaling: float,
  150. dropout: float = 0.0,
  151. **kwargs: Unpack[TransformersKwargs],
  152. ):
  153. key_states = repeat_kv(key, module.num_key_value_groups)
  154. value_states = repeat_kv(value, module.num_key_value_groups)
  155. attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
  156. if attention_mask is not None:
  157. causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
  158. attn_weights = attn_weights + causal_mask
  159. attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
  160. attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
  161. attn_output = torch.matmul(attn_weights, value_states)
  162. attn_output = attn_output.transpose(1, 2).contiguous()
  163. return attn_output, attn_weights
  164. class LlamaAttention(nn.Module):
  165. """Multi-headed attention from 'Attention Is All You Need' paper"""
  166. def __init__(self, config: LlamaConfig, layer_idx: int):
  167. super().__init__()
  168. self.config = config
  169. self.layer_idx = layer_idx
  170. self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
  171. self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
  172. self.scaling = self.head_dim**-0.5
  173. self.attention_dropout = config.attention_dropout
  174. self.is_causal = True
  175. self.q_proj = nn.Linear(
  176. config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
  177. )
  178. self.k_proj = nn.Linear(
  179. config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
  180. )
  181. self.v_proj = nn.Linear(
  182. config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
  183. )
  184. self.o_proj = nn.Linear(
  185. config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
  186. )
  187. @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
  188. def forward(
  189. self,
  190. hidden_states: torch.Tensor,
  191. position_embeddings: tuple[torch.Tensor, torch.Tensor],
  192. attention_mask: Optional[torch.Tensor],
  193. past_key_values: Optional[Cache] = None,
  194. cache_position: Optional[torch.LongTensor] = None,
  195. **kwargs: Unpack[TransformersKwargs],
  196. ) -> tuple[torch.Tensor, torch.Tensor]:
  197. input_shape = hidden_states.shape[:-1]
  198. hidden_shape = (*input_shape, -1, self.head_dim)
  199. query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
  200. key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
  201. value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
  202. cos, sin = position_embeddings
  203. query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
  204. if past_key_values is not None:
  205. # sin and cos are specific to RoPE models; cache_position needed for the static cache
  206. cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
  207. key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
  208. attention_interface: Callable = eager_attention_forward
  209. if self.config._attn_implementation != "eager":
  210. attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
  211. attn_output, attn_weights = attention_interface(
  212. self,
  213. query_states,
  214. key_states,
  215. value_states,
  216. attention_mask,
  217. dropout=0.0 if not self.training else self.attention_dropout,
  218. scaling=self.scaling,
  219. **kwargs,
  220. )
  221. attn_output = attn_output.reshape(*input_shape, -1).contiguous()
  222. attn_output = self.o_proj(attn_output)
  223. return attn_output, attn_weights
  224. class LlamaDecoderLayer(GradientCheckpointingLayer):
  225. def __init__(self, config: LlamaConfig, layer_idx: int):
  226. super().__init__()
  227. self.hidden_size = config.hidden_size
  228. self.self_attn = LlamaAttention(config=config, layer_idx=layer_idx)
  229. self.mlp = LlamaMLP(config)
  230. self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  231. self.post_attention_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  232. @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
  233. def forward(
  234. self,
  235. hidden_states: torch.Tensor,
  236. attention_mask: Optional[torch.Tensor] = None,
  237. position_ids: Optional[torch.LongTensor] = None,
  238. past_key_values: Optional[Cache] = None,
  239. use_cache: Optional[bool] = False,
  240. cache_position: Optional[torch.LongTensor] = None,
  241. position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
  242. **kwargs: Unpack[TransformersKwargs],
  243. ) -> torch.Tensor:
  244. residual = hidden_states
  245. hidden_states = self.input_layernorm(hidden_states)
  246. # Self Attention
  247. hidden_states, _ = self.self_attn(
  248. hidden_states=hidden_states,
  249. attention_mask=attention_mask,
  250. position_ids=position_ids,
  251. past_key_values=past_key_values,
  252. use_cache=use_cache,
  253. cache_position=cache_position,
  254. position_embeddings=position_embeddings,
  255. **kwargs,
  256. )
  257. hidden_states = residual + hidden_states
  258. # Fully Connected
  259. residual = hidden_states
  260. hidden_states = self.post_attention_layernorm(hidden_states)
  261. hidden_states = self.mlp(hidden_states)
  262. hidden_states = residual + hidden_states
  263. return hidden_states
  264. @auto_docstring
  265. class LlamaPreTrainedModel(PreTrainedModel):
  266. config: LlamaConfig
  267. base_model_prefix = "model"
  268. supports_gradient_checkpointing = True
  269. _no_split_modules = ["LlamaDecoderLayer"]
  270. _skip_keys_device_placement = ["past_key_values"]
  271. _supports_flash_attn = True
  272. _supports_sdpa = True
  273. _supports_flex_attn = True
  274. _can_compile_fullgraph = True
  275. _supports_attention_backend = True
  276. _can_record_outputs = {
  277. "hidden_states": LlamaDecoderLayer,
  278. "attentions": LlamaAttention,
  279. }
  280. @auto_docstring
  281. class LlamaModel(LlamaPreTrainedModel):
  282. def __init__(self, config: LlamaConfig):
  283. super().__init__(config)
  284. self.padding_idx = config.pad_token_id
  285. self.vocab_size = config.vocab_size
  286. self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
  287. self.layers = nn.ModuleList(
  288. [LlamaDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
  289. )
  290. self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  291. self.rotary_emb = LlamaRotaryEmbedding(config=config)
  292. self.gradient_checkpointing = False
  293. # Initialize weights and apply final processing
  294. self.post_init()
  295. @check_model_inputs()
  296. @auto_docstring
  297. def forward(
  298. self,
  299. input_ids: Optional[torch.LongTensor] = None,
  300. attention_mask: Optional[torch.Tensor] = None,
  301. position_ids: Optional[torch.LongTensor] = None,
  302. past_key_values: Optional[Cache] = None,
  303. inputs_embeds: Optional[torch.FloatTensor] = None,
  304. cache_position: Optional[torch.LongTensor] = None,
  305. use_cache: Optional[bool] = None,
  306. **kwargs: Unpack[TransformersKwargs],
  307. ) -> BaseModelOutputWithPast:
  308. if (input_ids is None) ^ (inputs_embeds is not None):
  309. raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
  310. if inputs_embeds is None:
  311. inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)
  312. if use_cache and past_key_values is None:
  313. past_key_values = DynamicCache(config=self.config)
  314. if cache_position is None:
  315. past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
  316. cache_position: torch.Tensor = torch.arange(
  317. past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
  318. )
  319. if position_ids is None:
  320. position_ids = cache_position.unsqueeze(0)
  321. causal_mask = create_causal_mask(
  322. config=self.config,
  323. input_embeds=inputs_embeds,
  324. attention_mask=attention_mask,
  325. cache_position=cache_position,
  326. past_key_values=past_key_values,
  327. position_ids=position_ids,
  328. )
  329. hidden_states = inputs_embeds
  330. position_embeddings = self.rotary_emb(hidden_states, position_ids)
  331. for decoder_layer in self.layers[: self.config.num_hidden_layers]:
  332. hidden_states = decoder_layer(
  333. hidden_states,
  334. attention_mask=causal_mask,
  335. position_ids=position_ids,
  336. past_key_values=past_key_values,
  337. cache_position=cache_position,
  338. position_embeddings=position_embeddings,
  339. **kwargs,
  340. )
  341. hidden_states = self.norm(hidden_states)
  342. return BaseModelOutputWithPast(
  343. last_hidden_state=hidden_states,
  344. past_key_values=past_key_values,
  345. )
  346. @auto_docstring
  347. class LlamaForCausalLM(LlamaPreTrainedModel, GenerationMixin):
  348. _tied_weights_keys = ["lm_head.weight"]
  349. _tp_plan = {"lm_head": "colwise_rep"}
  350. _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
  351. def __init__(self, config):
  352. super().__init__(config)
  353. self.model = LlamaModel(config)
  354. self.vocab_size = config.vocab_size
  355. self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
  356. # Initialize weights and apply final processing
  357. self.post_init()
  358. @can_return_tuple
  359. @auto_docstring
  360. def forward(
  361. self,
  362. input_ids: Optional[torch.LongTensor] = None,
  363. attention_mask: Optional[torch.Tensor] = None,
  364. position_ids: Optional[torch.LongTensor] = None,
  365. past_key_values: Optional[Cache] = None,
  366. inputs_embeds: Optional[torch.FloatTensor] = None,
  367. labels: Optional[torch.LongTensor] = None,
  368. use_cache: Optional[bool] = None,
  369. cache_position: Optional[torch.LongTensor] = None,
  370. logits_to_keep: Union[int, torch.Tensor] = 0,
  371. **kwargs: Unpack[TransformersKwargs],
  372. ) -> CausalLMOutputWithPast:
  373. r"""
  374. Example:
  375. ```python
  376. >>> from transformers import AutoTokenizer, LlamaForCausalLM
  377. >>> model = LlamaForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf")
  378. >>> tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf")
  379. >>> prompt = "Hey, are you conscious? Can you talk to me?"
  380. >>> inputs = tokenizer(prompt, return_tensors="pt")
  381. >>> # Generate
  382. >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
  383. >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
  384. "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
  385. ```"""
  386. outputs: BaseModelOutputWithPast = self.model(
  387. input_ids=input_ids,
  388. attention_mask=attention_mask,
  389. position_ids=position_ids,
  390. past_key_values=past_key_values,
  391. inputs_embeds=inputs_embeds,
  392. use_cache=use_cache,
  393. cache_position=cache_position,
  394. **kwargs,
  395. )
  396. hidden_states = outputs.last_hidden_state
  397. # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
  398. slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
  399. logits = self.lm_head(hidden_states[:, slice_indices, :])
  400. loss = None
  401. if labels is not None:
  402. loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
  403. return CausalLMOutputWithPast(
  404. loss=loss,
  405. logits=logits,
  406. past_key_values=outputs.past_key_values,
  407. hidden_states=outputs.hidden_states,
  408. attentions=outputs.attentions,
  409. )
  410. class LlamaForSequenceClassification(GenericForSequenceClassification, LlamaPreTrainedModel): ...
  411. class LlamaForQuestionAnswering(GenericForQuestionAnswering, LlamaPreTrainedModel):
  412. base_model_prefix = "transformer" # For BC, where `transformer` was used instead of `model`
  413. class LlamaForTokenClassification(GenericForTokenClassification, LlamaPreTrainedModel): ...
  414. __all__ = [
  415. "LlamaForCausalLM",
  416. "LlamaModel",
  417. "LlamaPreTrainedModel",
  418. "LlamaForSequenceClassification",
  419. "LlamaForQuestionAnswering",
  420. "LlamaForTokenClassification",
  421. ]