modeling_falcon.py 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396
  1. # coding=utf-8
  2. # Copyright 2023 the Falcon authors and 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 Falcon model."""
  16. import math
  17. from typing import Optional, Union
  18. import torch
  19. from torch import nn
  20. from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, LayerNorm, MSELoss
  21. from torch.nn import functional as F
  22. from ...activations import get_activation
  23. from ...cache_utils import Cache, DynamicCache, StaticCache
  24. from ...generation import GenerationMixin
  25. from ...modeling_attn_mask_utils import (
  26. AttentionMaskConverter,
  27. )
  28. from ...modeling_flash_attention_utils import flash_attn_supports_top_left_mask, is_flash_attn_available
  29. from ...modeling_layers import GradientCheckpointingLayer
  30. from ...modeling_outputs import (
  31. BaseModelOutputWithPastAndCrossAttentions,
  32. CausalLMOutputWithCrossAttentions,
  33. QuestionAnsweringModelOutput,
  34. SequenceClassifierOutputWithPast,
  35. TokenClassifierOutput,
  36. )
  37. from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
  38. from ...modeling_utils import PreTrainedModel
  39. from ...utils import (
  40. auto_docstring,
  41. logging,
  42. )
  43. from .configuration_falcon import FalconConfig
  44. if is_flash_attn_available():
  45. from ...modeling_flash_attention_utils import _flash_attention_forward
  46. logger = logging.get_logger(__name__)
  47. # NOTE(Hesslow): Unfortunately we did not fuse matmul and bias during training, this means that there's one additional quantization to bfloat16 between the operations.
  48. # In order not to degrade the quality of our HF-port, we keep these characteristics in the final model.
  49. class FalconLinear(nn.Linear):
  50. def forward(self, input: torch.Tensor) -> torch.Tensor:
  51. hidden_states = input @ self.weight.T
  52. if self.bias is None:
  53. return hidden_states
  54. return hidden_states + self.bias
  55. # Copied from transformers.models.llama.modeling_llama.rotate_half
  56. def rotate_half(x):
  57. """Rotates half the hidden dims of the input."""
  58. x1 = x[..., : x.shape[-1] // 2]
  59. x2 = x[..., x.shape[-1] // 2 :]
  60. return torch.cat((-x2, x1), dim=-1)
  61. # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
  62. def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
  63. """Applies Rotary Position Embedding to the query and key tensors.
  64. Args:
  65. q (`torch.Tensor`): The query tensor.
  66. k (`torch.Tensor`): The key tensor.
  67. cos (`torch.Tensor`): The cosine part of the rotary embedding.
  68. sin (`torch.Tensor`): The sine part of the rotary embedding.
  69. position_ids (`torch.Tensor`, *optional*):
  70. Deprecated and unused.
  71. unsqueeze_dim (`int`, *optional*, defaults to 1):
  72. The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
  73. sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
  74. that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
  75. k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
  76. cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
  77. the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
  78. Returns:
  79. `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
  80. """
  81. cos = cos.unsqueeze(unsqueeze_dim)
  82. sin = sin.unsqueeze(unsqueeze_dim)
  83. q_embed = (q * cos) + (rotate_half(q) * sin)
  84. k_embed = (k * cos) + (rotate_half(k) * sin)
  85. return q_embed, k_embed
  86. # Copied from transformers.models.llama.modeling_llama.LlamaRotaryEmbedding with Llama->Falcon
  87. class FalconRotaryEmbedding(nn.Module):
  88. inv_freq: torch.Tensor # fix linting for `register_buffer`
  89. def __init__(self, config: FalconConfig, device=None):
  90. super().__init__()
  91. # BC: "rope_type" was originally "type"
  92. if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
  93. self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
  94. else:
  95. self.rope_type = "default"
  96. self.max_seq_len_cached = config.max_position_embeddings
  97. self.original_max_seq_len = config.max_position_embeddings
  98. self.config = config
  99. self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
  100. inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
  101. self.register_buffer("inv_freq", inv_freq, persistent=False)
  102. self.original_inv_freq = self.inv_freq
  103. @torch.no_grad()
  104. @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
  105. def forward(self, x, position_ids):
  106. inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
  107. position_ids_expanded = position_ids[:, None, :].float()
  108. device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
  109. with torch.autocast(device_type=device_type, enabled=False): # Force float32
  110. freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
  111. emb = torch.cat((freqs, freqs), dim=-1)
  112. cos = emb.cos() * self.attention_scaling
  113. sin = emb.sin() * self.attention_scaling
  114. return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
  115. def build_alibi_tensor(attention_mask: torch.Tensor, num_heads: int, dtype: torch.dtype) -> torch.Tensor:
  116. batch_size, seq_length = attention_mask.shape
  117. closest_power_of_2 = 2 ** math.floor(math.log2(num_heads))
  118. base = torch.tensor(
  119. 2 ** (-(2 ** -(math.log2(closest_power_of_2) - 3))), device=attention_mask.device, dtype=torch.float32
  120. )
  121. powers = torch.arange(1, 1 + closest_power_of_2, device=attention_mask.device, dtype=torch.int32)
  122. slopes = torch.pow(base, powers)
  123. if closest_power_of_2 != num_heads:
  124. extra_base = torch.tensor(
  125. 2 ** (-(2 ** -(math.log2(2 * closest_power_of_2) - 3))), device=attention_mask.device, dtype=torch.float32
  126. )
  127. num_remaining_heads = min(closest_power_of_2, num_heads - closest_power_of_2)
  128. extra_powers = torch.arange(1, 1 + 2 * num_remaining_heads, 2, device=attention_mask.device, dtype=torch.int32)
  129. slopes = torch.cat([slopes, torch.pow(extra_base, extra_powers)], dim=0)
  130. # Note: alibi will added to the attention bias that will be applied to the query, key product of attention
  131. # => therefore alibi will have to be of shape (batch_size, num_heads, query_length, key_length)
  132. # => here we set (batch_size=1, num_heads=num_heads, query_length=1, key_length=max_length)
  133. # => the query_length dimension will then be broadcasted correctly
  134. # This is more or less identical to T5's relative position bias:
  135. # https://github.com/huggingface/transformers/blob/f681437203baa7671de3174b0fa583c349d9d5e1/src/transformers/models/t5/modeling_t5.py#L527
  136. arange_tensor = ((attention_mask.cumsum(dim=-1) - 1) * attention_mask)[:, None, :]
  137. alibi = slopes[..., None].bfloat16() * arange_tensor
  138. return alibi.reshape(batch_size * num_heads, 1, seq_length).to(dtype)
  139. # Copied from transformers.models.bloom.modeling_bloom.dropout_add
  140. def dropout_add(x: torch.Tensor, residual: torch.Tensor, prob: float, training: bool) -> torch.Tensor:
  141. """
  142. Dropout add function
  143. Args:
  144. x (`torch.tensor`):
  145. input tensor
  146. residual (`torch.tensor`):
  147. residual tensor
  148. prob (`float`):
  149. dropout probability
  150. training (`bool`):
  151. training mode
  152. """
  153. out = F.dropout(x, p=prob, training=training)
  154. out = residual + out
  155. return out
  156. class FalconAttention(nn.Module):
  157. def __init__(self, config: FalconConfig, layer_idx=None):
  158. super().__init__()
  159. self.config = config
  160. self.hidden_size = config.hidden_size
  161. self.num_heads = config.num_attention_heads
  162. self.head_dim = self.hidden_size // self.num_heads
  163. self.split_size = self.hidden_size
  164. self.hidden_dropout = config.hidden_dropout
  165. self.max_position_embeddings = config.max_position_embeddings
  166. self.rope_theta = config.rope_theta
  167. self.is_causal = True
  168. self.layer_idx = layer_idx
  169. if layer_idx is None:
  170. logger.warning_once(
  171. f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
  172. "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
  173. "when creating this class."
  174. )
  175. if self.head_dim * self.num_heads != self.hidden_size:
  176. raise ValueError(
  177. f"`hidden_size` must be divisible by num_heads (got `hidden_size`: {self.hidden_size} and `num_heads`:"
  178. f" {self.num_heads})."
  179. )
  180. # Layer-wise attention scaling
  181. self.inv_norm_factor = 1.0 / math.sqrt(self.head_dim)
  182. self.beta = self.inv_norm_factor
  183. if config.new_decoder_architecture:
  184. qkv_out_dim = (config.num_kv_heads * 2 + config.num_attention_heads) * self.head_dim
  185. elif config.multi_query:
  186. qkv_out_dim = self.hidden_size + 2 * self.head_dim
  187. else:
  188. qkv_out_dim = 3 * self.hidden_size
  189. self.query_key_value = FalconLinear(self.hidden_size, qkv_out_dim, bias=config.bias)
  190. self.new_decoder_architecture = config.new_decoder_architecture
  191. self.multi_query = config.multi_query
  192. self.dense = FalconLinear(self.hidden_size, self.hidden_size, bias=config.bias)
  193. self.attention_dropout = nn.Dropout(config.attention_dropout)
  194. self.num_kv_heads = config.num_kv_heads if (self.new_decoder_architecture or not self.multi_query) else 1
  195. def _split_heads(self, fused_qkv: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
  196. """
  197. Split the last dimension into (num_heads, head_dim), results share same memory storage as `fused_qkv`
  198. Args:
  199. fused_qkv (`torch.tensor`): [batch_size, seq_length, num_heads * 3 * head_dim]
  200. Returns:
  201. query: [batch_size, seq_length, num_heads, head_dim] key: [batch_size, seq_length, num_heads, head_dim]
  202. value: [batch_size, seq_length, num_heads, head_dim]
  203. """
  204. if self.new_decoder_architecture:
  205. batch, seq_len, _ = fused_qkv.shape
  206. qkv = fused_qkv.view(batch, seq_len, -1, self.num_heads // self.num_kv_heads + 2, self.head_dim)
  207. query = qkv[:, :, :, :-2]
  208. key = qkv[:, :, :, [-2]]
  209. value = qkv[:, :, :, [-1]]
  210. key = torch.broadcast_to(key, query.shape)
  211. value = torch.broadcast_to(value, query.shape)
  212. query, key, value = [x.flatten(2, 3) for x in (query, key, value)]
  213. return query, key, value
  214. elif not self.multi_query:
  215. batch_size, seq_length, three_times_hidden_size = fused_qkv.shape
  216. fused_qkv = fused_qkv.view(batch_size, seq_length, self.num_heads, 3, self.head_dim)
  217. return fused_qkv[..., 0, :], fused_qkv[..., 1, :], fused_qkv[..., 2, :]
  218. else:
  219. batch_size, seq_length, three_times_hidden_size = fused_qkv.shape
  220. fused_qkv = fused_qkv.view(batch_size, seq_length, self.num_heads + 2, self.head_dim)
  221. return fused_qkv[..., :-2, :], fused_qkv[..., [-2], :], fused_qkv[..., [-1], :]
  222. # Copied from transformers.models.bloom.modeling_bloom.BloomAttention._merge_heads
  223. def _merge_heads(self, x: torch.Tensor) -> torch.Tensor:
  224. """
  225. Merge heads together over the last dimension
  226. Args:
  227. x (`torch.tensor`): [batch_size * num_heads, seq_length, head_dim]
  228. Returns:
  229. torch.tensor: [batch_size, seq_length, num_heads * head_dim]
  230. """
  231. # What we want to achieve is:
  232. # batch_size * num_heads, seq_length, head_dim -> batch_size, seq_length, num_heads * head_dim
  233. batch_size_and_num_heads, seq_length, _ = x.shape
  234. batch_size = batch_size_and_num_heads // self.num_heads
  235. # First view to decompose the batch size
  236. # batch_size * num_heads, seq_length, head_dim -> batch_size, num_heads, seq_length, head_dim
  237. x = x.view(batch_size, self.num_heads, seq_length, self.head_dim)
  238. # batch_size, num_heads, seq_length, head_dim -> batch_size, seq_length, num_heads, head_dim
  239. x = x.permute(0, 2, 1, 3)
  240. # batch_size, seq_length, num_heads, head_dim -> batch_size, seq_length, num_heads * head_dim
  241. return x.reshape(batch_size, seq_length, self.num_heads * self.head_dim)
  242. def forward(
  243. self,
  244. hidden_states: torch.Tensor,
  245. alibi: Optional[torch.Tensor],
  246. attention_mask: torch.Tensor,
  247. position_ids: Optional[torch.LongTensor] = None,
  248. layer_past: Optional[Cache] = None,
  249. head_mask: Optional[torch.Tensor] = None,
  250. use_cache: bool = False,
  251. output_attentions: bool = False,
  252. cache_position: Optional[torch.LongTensor] = None,
  253. position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
  254. ):
  255. fused_qkv = self.query_key_value(hidden_states) # [batch_size, seq_length, 3 x hidden_size]
  256. num_kv_heads = self.num_heads if self.new_decoder_architecture else self.num_kv_heads
  257. # 3 x [batch_size, seq_length, num_heads, head_dim]
  258. (query_layer, key_layer, value_layer) = self._split_heads(fused_qkv)
  259. batch_size, query_length, _, _ = query_layer.shape
  260. query_layer = query_layer.transpose(1, 2).reshape(batch_size, self.num_heads, query_length, self.head_dim)
  261. key_layer = key_layer.transpose(1, 2).reshape(batch_size, num_kv_heads, query_length, self.head_dim)
  262. value_layer = value_layer.transpose(1, 2).reshape(batch_size, num_kv_heads, query_length, self.head_dim)
  263. if alibi is None:
  264. cos, sin = position_embeddings
  265. query_layer, key_layer = apply_rotary_pos_emb(query_layer, key_layer, cos, sin)
  266. if layer_past is not None:
  267. cache_kwargs = {"cache_position": cache_position}
  268. if alibi is None:
  269. cache_kwargs.update({"sin": sin, "cos": cos})
  270. key_layer, value_layer = layer_past.update(key_layer, value_layer, self.layer_idx, cache_kwargs)
  271. kv_length = key_layer.shape[-2]
  272. if (
  273. self.config._attn_implementation == "sdpa"
  274. and query_layer.device.type == "cuda"
  275. and attention_mask is not None
  276. ):
  277. # For torch<=2.1.2, SDPA with memory-efficient backend is bugged with non-contiguous inputs with custom attn_mask,
  278. # Reference: https://github.com/pytorch/pytorch/issues/112577.
  279. query_layer = query_layer.contiguous()
  280. key_layer = key_layer.contiguous()
  281. value_layer = value_layer.contiguous()
  282. if attention_mask is not None:
  283. attention_mask = attention_mask[:, :, :, : key_layer.shape[-2]]
  284. if alibi is None:
  285. if self.config._attn_implementation == "sdpa" and not output_attentions:
  286. # We dispatch to SDPA's Flash Attention or Efficient kernels via this if statement instead of an
  287. # inline conditional assignment to support both torch.compile's `dynamic=True` and `fullgraph=True`
  288. # The query_length > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not
  289. # create a causal mask in case query_length == 1.
  290. is_causal = self.is_causal and attention_mask is None and query_length > 1
  291. attn_output = torch.nn.functional.scaled_dot_product_attention(
  292. query_layer,
  293. key_layer,
  294. value_layer,
  295. attn_mask=attention_mask,
  296. dropout_p=0.0,
  297. is_causal=is_causal,
  298. )
  299. attention_scores = None
  300. else:
  301. attention_scores = query_layer @ key_layer.transpose(-1, -2)
  302. attention_scores /= math.sqrt(self.head_dim)
  303. attention_scores = F.softmax(attention_scores + attention_mask, dim=-1, dtype=hidden_states.dtype)
  304. # It is unclear why neither dropout nor head_mask is applied here (while it is with alibi).
  305. attn_output = attention_scores @ value_layer
  306. attn_output = attn_output.view(batch_size, self.num_heads, query_length, self.head_dim)
  307. attn_output = attn_output.permute(0, 2, 1, 3)
  308. attn_output = attn_output.reshape(batch_size, query_length, self.num_heads * self.head_dim)
  309. attn_output = self.dense(attn_output)
  310. return attn_output, attention_scores
  311. else:
  312. if self.config._attn_implementation == "sdpa" and not output_attentions and head_mask is None:
  313. # We dispatch to SDPA's Flash Attention or Efficient kernels via this if statement instead of an
  314. # inline conditional assignment to support both torch.compile's `dynamic=True` and `fullgraph=True`
  315. is_causal = self.is_causal and attention_mask is None and query_length > 1
  316. attn_output = torch.nn.functional.scaled_dot_product_attention(
  317. query_layer,
  318. key_layer,
  319. value_layer,
  320. attn_mask=attention_mask,
  321. dropout_p=self.attention_dropout.p if self.training else 0.0,
  322. is_causal=is_causal,
  323. )
  324. attention_probs = None
  325. attn_output = attn_output.transpose(1, 2)
  326. attn_output = attn_output.reshape(batch_size, query_length, self.num_heads * self.head_dim)
  327. attn_output = self.dense(attn_output)
  328. else:
  329. matmul_result = query_layer @ key_layer.transpose(-1, -2)
  330. # change view to [batch_size, num_heads, q_length, kv_length]
  331. attention_scores = matmul_result.view(batch_size, self.num_heads, query_length, kv_length)
  332. # cast attention scores to fp32, compute scaled softmax and cast back to initial dtype - [batch_size, num_heads, q_length, kv_length]
  333. input_dtype = attention_scores.dtype
  334. # `float16` has a minimum value of -65504.0, whereas `bfloat16` and `float32` have a minimum value of `-3.4e+38`
  335. if input_dtype == torch.float16 or input_dtype == torch.bfloat16:
  336. attention_scores = attention_scores.to(torch.float32)
  337. attention_logits = attention_scores + alibi.view(batch_size, self.num_heads, 1, -1)
  338. attention_logits *= self.inv_norm_factor
  339. attention_probs = F.softmax(attention_logits + attention_mask, dim=-1, dtype=hidden_states.dtype)
  340. # [batch_size, num_heads, q_length, kv_length]
  341. attention_probs = self.attention_dropout(attention_probs)
  342. if head_mask is not None:
  343. attention_probs = attention_probs * head_mask
  344. # change view [batch_size, num_heads, q_length, kv_length]
  345. attention_probs_reshaped = attention_probs.view(batch_size, self.num_heads, query_length, kv_length)
  346. # matmul: [batch_size * num_heads, q_length, head_dim]
  347. attn_output = (attention_probs_reshaped @ value_layer).flatten(0, 1)
  348. # change view [batch_size, q_length, num_heads * head_dim]
  349. attn_output = self._merge_heads(attn_output)
  350. attn_output = self.dense(attn_output)
  351. return attn_output, attention_probs
  352. class FalconFlashAttention2(FalconAttention):
  353. """
  354. Falcon flash attention module. This module inherits from `FalconAttention` as the weights of the module stays
  355. untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
  356. flash attention and deal with padding tokens in case the input contains any of them.
  357. """
  358. def __init__(self, *args, **kwargs):
  359. super().__init__(*args, **kwargs)
  360. # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
  361. # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignment, 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.
  362. # 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).
  363. self._flash_attn_uses_top_left_mask = flash_attn_supports_top_left_mask()
  364. def forward(
  365. self,
  366. hidden_states: torch.Tensor,
  367. alibi: Optional[torch.Tensor],
  368. attention_mask: torch.Tensor,
  369. position_ids: Optional[torch.LongTensor] = None,
  370. layer_past: Optional[Cache] = None,
  371. head_mask: Optional[torch.Tensor] = None,
  372. use_cache: bool = False,
  373. output_attentions: bool = False,
  374. cache_position: Optional[torch.LongTensor] = None,
  375. position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
  376. ):
  377. fused_qkv = self.query_key_value(hidden_states) # [batch_size, seq_length, 3 x hidden_size]
  378. num_kv_heads = self.num_heads if self.new_decoder_architecture else self.num_kv_heads
  379. # 3 x [batch_size, seq_length, num_heads, head_dim]
  380. (query_layer, key_layer, value_layer) = self._split_heads(fused_qkv)
  381. batch_size, query_length, _, _ = query_layer.shape
  382. query_layer = query_layer.transpose(1, 2).reshape(batch_size, self.num_heads, query_length, self.head_dim)
  383. key_layer = key_layer.transpose(1, 2).reshape(batch_size, num_kv_heads, query_length, self.head_dim)
  384. value_layer = value_layer.transpose(1, 2).reshape(batch_size, num_kv_heads, query_length, self.head_dim)
  385. if alibi is None:
  386. cos, sin = position_embeddings
  387. query_layer, key_layer = apply_rotary_pos_emb(query_layer, key_layer, cos, sin)
  388. if layer_past is not None:
  389. cache_kwargs = {"cache_position": cache_position}
  390. if alibi is None:
  391. cache_kwargs.update({"sin": sin, "cos": cos})
  392. key_layer, value_layer = layer_past.update(key_layer, value_layer, 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_layer = query_layer.transpose(1, 2)
  396. key_layer = key_layer.transpose(1, 2)
  397. value_layer = value_layer.transpose(1, 2)
  398. if alibi is not None:
  399. raise ValueError("`alibi` is not supported when `use_flash_attn` is True")
  400. attn_dropout = self.config.attention_dropout if self.training else 0.0
  401. # In PEFT, usually we cast the layer norms in float32 for training stability reasons
  402. # therefore the input hidden states gets silently casted in float32. Hence, we need
  403. # cast them back in float16 just to be sure everything works as expected.
  404. input_dtype = query_layer.dtype
  405. device_type = query_layer.device.type if query_layer.device.type != "mps" else "cpu"
  406. if input_dtype == torch.float32:
  407. if torch.is_autocast_enabled():
  408. target_dtype = (
  409. torch.get_autocast_dtype(device_type)
  410. if hasattr(torch, "get_autocast_dtype")
  411. else torch.get_autocast_gpu_dtype()
  412. )
  413. # Handle the case where the model is quantized
  414. elif hasattr(self.config, "_pre_quantization_dtype"):
  415. target_dtype = self.config._pre_quantization_dtype
  416. else:
  417. target_dtype = self.query_key_value.weight.dtype
  418. logger.warning_once(
  419. f"The input hidden states seems to be silently casted in float32, this might be related to"
  420. f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
  421. f" {target_dtype}."
  422. )
  423. query_layer = query_layer.to(target_dtype)
  424. key_layer = key_layer.to(target_dtype)
  425. value_layer = value_layer.to(target_dtype)
  426. attn_output = _flash_attention_forward(
  427. query_layer,
  428. key_layer,
  429. value_layer,
  430. attention_mask,
  431. query_length,
  432. position_ids=position_ids,
  433. dropout=attn_dropout,
  434. is_causal=self.is_causal,
  435. use_top_left_mask=self._flash_attn_uses_top_left_mask,
  436. )
  437. attn_weights = attn_output.reshape(batch_size, query_length, self.num_heads * self.head_dim)
  438. attn_output = self.dense(attn_weights)
  439. if not output_attentions:
  440. attn_weights = None
  441. return attn_output, attn_weights
  442. class FalconMLP(nn.Module):
  443. def __init__(self, config: FalconConfig):
  444. super().__init__()
  445. hidden_size = config.hidden_size
  446. self.dense_h_to_4h = FalconLinear(hidden_size, config.ffn_hidden_size, bias=config.bias)
  447. self.act = get_activation(config.activation)
  448. self.dense_4h_to_h = FalconLinear(config.ffn_hidden_size, hidden_size, bias=config.bias)
  449. self.hidden_dropout = config.hidden_dropout
  450. def forward(self, x: torch.Tensor) -> torch.Tensor:
  451. x = self.act(self.dense_h_to_4h(x))
  452. x = self.dense_4h_to_h(x)
  453. return x
  454. FALCON_ATTENTION_CLASSES = {
  455. "eager": FalconAttention,
  456. "sdpa": FalconAttention, # FalconAttention originally implemented both a forward with & without SDPA
  457. "flash_attention_2": FalconFlashAttention2,
  458. }
  459. class FalconDecoderLayer(GradientCheckpointingLayer):
  460. def __init__(self, config: FalconConfig, layer_idx=None):
  461. super().__init__()
  462. hidden_size = config.hidden_size
  463. self.num_heads = config.num_attention_heads
  464. self.self_attention = FALCON_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx)
  465. self.mlp = FalconMLP(config)
  466. self.hidden_dropout = config.hidden_dropout
  467. self.config = config
  468. if config.num_ln_in_parallel_attn is None and config.new_decoder_architecture:
  469. config.num_ln_in_parallel_attn = 2
  470. if not config.parallel_attn:
  471. self.post_attention_layernorm = LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
  472. self.input_layernorm = LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
  473. else:
  474. if config.num_ln_in_parallel_attn == 2:
  475. # The layer norm before self-attention
  476. self.ln_attn = LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
  477. # The layer norm before the MLP
  478. self.ln_mlp = LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
  479. else:
  480. self.input_layernorm = LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
  481. def forward(
  482. self,
  483. hidden_states: torch.Tensor,
  484. alibi: Optional[torch.Tensor],
  485. attention_mask: torch.Tensor,
  486. position_ids: Optional[torch.LongTensor] = None,
  487. layer_past: Optional[Union[Cache, tuple[torch.Tensor, torch.Tensor]]] = None,
  488. head_mask: Optional[torch.Tensor] = None,
  489. use_cache: bool = False,
  490. output_attentions: bool = False,
  491. cache_position: Optional[torch.LongTensor] = None,
  492. position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
  493. **kwargs,
  494. ):
  495. residual = hidden_states
  496. if self.config.new_decoder_architecture and self.config.num_ln_in_parallel_attn == 2:
  497. attention_layernorm_out = self.ln_attn(hidden_states)
  498. mlp_layernorm_out = self.ln_mlp(hidden_states)
  499. else:
  500. attention_layernorm_out = self.input_layernorm(hidden_states)
  501. # Self attention.
  502. attention_output, attn_weights = self.self_attention(
  503. attention_layernorm_out,
  504. layer_past=layer_past,
  505. attention_mask=attention_mask,
  506. position_ids=position_ids,
  507. alibi=alibi,
  508. head_mask=head_mask,
  509. use_cache=use_cache,
  510. output_attentions=output_attentions,
  511. cache_position=cache_position,
  512. position_embeddings=position_embeddings,
  513. )
  514. if not self.config.new_decoder_architecture:
  515. if self.config.parallel_attn:
  516. mlp_layernorm_out = attention_layernorm_out
  517. else:
  518. residual = dropout_add(
  519. attention_output, residual, self.config.attention_dropout, training=self.training
  520. )
  521. mlp_layernorm_out = self.post_attention_layernorm(residual)
  522. if (
  523. self.config.new_decoder_architecture
  524. and self.config.parallel_attn
  525. and self.config.num_ln_in_parallel_attn == 1
  526. ):
  527. mlp_layernorm_out = attention_layernorm_out
  528. # MLP.
  529. mlp_output = self.mlp(mlp_layernorm_out)
  530. if self.config.new_decoder_architecture or self.config.parallel_attn:
  531. mlp_output += attention_output
  532. output = dropout_add(mlp_output, residual, self.config.hidden_dropout, training=self.training)
  533. return output, attn_weights
  534. @auto_docstring
  535. class FalconPreTrainedModel(PreTrainedModel):
  536. config: FalconConfig
  537. base_model_prefix = "transformer"
  538. supports_gradient_checkpointing = True
  539. _no_split_modules = ["FalconDecoderLayer"]
  540. _supports_flash_attn = True
  541. _supports_sdpa = True
  542. _can_compile_fullgraph = True
  543. def __init__(self, *inputs, **kwargs):
  544. super().__init__(*inputs, **kwargs)
  545. def _init_weights(self, module: nn.Module):
  546. """Initialize the weights."""
  547. if isinstance(module, (nn.Linear, FalconLinear)):
  548. # Slightly different from the TF version which uses truncated_normal for initialization
  549. # cf https://github.com/pytorch/pytorch/pull/5617
  550. module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
  551. if module.bias is not None:
  552. module.bias.data.zero_()
  553. elif isinstance(module, nn.Embedding):
  554. module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
  555. if module.padding_idx is not None:
  556. module.weight.data[module.padding_idx].zero_()
  557. elif isinstance(module, LayerNorm):
  558. module.bias.data.zero_()
  559. module.weight.data.fill_(1.0)
  560. # Adapted from transformers.modeling_utils.PreTrainedModel._check_and_enable_sdpa
  561. @classmethod
  562. def _check_and_enable_sdpa(cls, config, hard_check_only: bool = False):
  563. _is_bettertransformer = getattr(cls, "use_bettertransformer", False)
  564. if _is_bettertransformer:
  565. return config
  566. if not hard_check_only:
  567. config._attn_implementation = "sdpa"
  568. return config
  569. @auto_docstring
  570. class FalconModel(FalconPreTrainedModel):
  571. def __init__(self, config: FalconConfig):
  572. super().__init__(config)
  573. self.embed_dim = config.hidden_size
  574. self.num_heads = config.num_attention_heads
  575. self.use_alibi = config.alibi
  576. # Embedding + LN Embedding
  577. self.word_embeddings = nn.Embedding(config.vocab_size, self.embed_dim)
  578. # Transformer blocks
  579. self.h = nn.ModuleList([FalconDecoderLayer(config, layer_idx=i) for i in range(config.num_hidden_layers)])
  580. # Final Layer Norm
  581. self.ln_f = LayerNorm(self.embed_dim, eps=config.layer_norm_epsilon)
  582. self.rotary_emb = FalconRotaryEmbedding(config=config)
  583. self.gradient_checkpointing = False
  584. # Initialize weights and apply final processing
  585. self.post_init()
  586. def get_input_embeddings(self):
  587. return self.word_embeddings
  588. def set_input_embeddings(self, new_embeddings: torch.Tensor):
  589. self.word_embeddings = new_embeddings
  590. @auto_docstring
  591. def forward(
  592. self,
  593. input_ids: Optional[torch.LongTensor] = None,
  594. past_key_values: Optional[Union[Cache, tuple[tuple[torch.Tensor, torch.Tensor], ...]]] = None,
  595. attention_mask: Optional[torch.Tensor] = None,
  596. position_ids: Optional[torch.LongTensor] = None,
  597. head_mask: Optional[torch.LongTensor] = None,
  598. inputs_embeds: Optional[torch.LongTensor] = None,
  599. use_cache: Optional[bool] = None,
  600. output_attentions: Optional[bool] = None,
  601. output_hidden_states: Optional[bool] = None,
  602. return_dict: Optional[bool] = None,
  603. cache_position: Optional[torch.LongTensor] = None,
  604. ) -> Union[tuple[torch.Tensor, ...], BaseModelOutputWithPastAndCrossAttentions]:
  605. r"""
  606. input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
  607. `input_ids_length` = `sequence_length` if `past_key_values` is `None` else `past_key_values.get_seq_length()`
  608. (`sequence_length` of input past key value states). Indices of input sequence tokens in the vocabulary.
  609. If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
  610. `input_ids`.
  611. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
  612. [`PreTrainedTokenizer.__call__`] for details.
  613. [What are input IDs?](../glossary#input-ids)
  614. """
  615. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  616. output_hidden_states = (
  617. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  618. )
  619. use_cache = use_cache if use_cache is not None else self.config.use_cache
  620. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  621. if (input_ids is None) ^ (inputs_embeds is not None):
  622. raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
  623. if self.gradient_checkpointing and self.training:
  624. if use_cache:
  625. logger.warning_once(
  626. "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
  627. )
  628. use_cache = False
  629. if inputs_embeds is None:
  630. inputs_embeds = self.word_embeddings(input_ids)
  631. if use_cache and past_key_values is None:
  632. past_key_values = DynamicCache(config=self.config)
  633. # Compute alibi tensor: check build_alibi_tensor documentation
  634. alibi = None
  635. past_key_values_length = past_key_values.get_seq_length() if past_key_values is not None else 0
  636. batch_size, seq_length, _ = inputs_embeds.shape
  637. if self.use_alibi:
  638. mask = (
  639. torch.ones(
  640. (batch_size, seq_length + past_key_values_length), device=inputs_embeds.device, dtype=torch.long
  641. )
  642. if attention_mask is None
  643. else attention_mask
  644. )
  645. alibi = build_alibi_tensor(mask, self.num_heads, dtype=inputs_embeds.dtype)
  646. if cache_position is None:
  647. cache_position = torch.arange(
  648. past_key_values_length, past_key_values_length + seq_length, device=inputs_embeds.device
  649. )
  650. if position_ids is None:
  651. position_ids = cache_position.unsqueeze(0)
  652. causal_mask = self._update_causal_mask(
  653. attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions, head_mask, alibi
  654. )
  655. # Prepare head mask if needed
  656. # 1.0 in head_mask indicate we keep the head
  657. # attention_probs has shape batch_size x num_heads x N x N
  658. # head_mask has shape n_layer x batch x num_heads x N x N
  659. head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
  660. hidden_states = inputs_embeds
  661. # create position embeddings to be shared across the decoder layers
  662. position_embeddings = self.rotary_emb(hidden_states, position_ids)
  663. all_self_attentions = () if output_attentions else None
  664. all_hidden_states = () if output_hidden_states else None
  665. for i, block in enumerate(self.h):
  666. if output_hidden_states:
  667. all_hidden_states = all_hidden_states + (hidden_states,)
  668. outputs = block(
  669. hidden_states,
  670. layer_past=past_key_values,
  671. attention_mask=causal_mask,
  672. position_ids=position_ids,
  673. head_mask=head_mask[i],
  674. use_cache=use_cache,
  675. output_attentions=output_attentions,
  676. alibi=alibi,
  677. cache_position=cache_position,
  678. position_embeddings=position_embeddings,
  679. )
  680. hidden_states = outputs[0]
  681. if output_attentions:
  682. all_self_attentions = all_self_attentions + (outputs[1],)
  683. # Add last hidden state
  684. hidden_states = self.ln_f(hidden_states)
  685. if output_hidden_states:
  686. all_hidden_states = all_hidden_states + (hidden_states,)
  687. if not return_dict:
  688. return tuple(
  689. v for v in [hidden_states, past_key_values, all_hidden_states, all_self_attentions] if v is not None
  690. )
  691. return BaseModelOutputWithPastAndCrossAttentions(
  692. last_hidden_state=hidden_states,
  693. past_key_values=past_key_values,
  694. hidden_states=all_hidden_states,
  695. attentions=all_self_attentions,
  696. )
  697. def _update_causal_mask(
  698. self,
  699. attention_mask: torch.Tensor,
  700. input_tensor: torch.Tensor,
  701. cache_position: torch.Tensor,
  702. past_key_values: Cache,
  703. output_attentions: bool,
  704. head_mask: torch.Tensor,
  705. alibi: torch.Tensor,
  706. ):
  707. # TODO: As of torch==2.2.0, the `attention_mask` passed to the model in `generate` is 2D and of dynamic length even when the static
  708. # KV cache is used. This is an issue for torch.compile which then recaptures cudagraphs at each decode steps due to the dynamic shapes.
  709. # (`recording cudagraph tree for symint key 13`, etc.), which is VERY slow. A workaround is `@torch.compiler.disable`, but this prevents using
  710. # `fullgraph=True`. See more context in https://github.com/huggingface/transformers/pull/29114
  711. if self.config._attn_implementation == "flash_attention_2":
  712. if attention_mask is not None and 0.0 in attention_mask:
  713. return attention_mask
  714. return None
  715. # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
  716. # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
  717. # to infer the attention mask.
  718. past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
  719. using_static_cache = isinstance(past_key_values, StaticCache)
  720. # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
  721. if (
  722. self.config._attn_implementation == "sdpa"
  723. and not using_static_cache
  724. and not output_attentions
  725. and head_mask is None
  726. and alibi is None
  727. ):
  728. if AttentionMaskConverter._ignore_causal_mask_sdpa(
  729. attention_mask,
  730. inputs_embeds=input_tensor,
  731. past_key_values_length=past_seen_tokens,
  732. is_training=self.training,
  733. ):
  734. return None
  735. dtype, device = input_tensor.dtype, input_tensor.device
  736. min_dtype = torch.finfo(dtype).min
  737. batch_size, sequence_length, _ = input_tensor.shape
  738. if using_static_cache:
  739. target_length = past_key_values.get_max_cache_shape()
  740. else:
  741. target_length = (
  742. attention_mask.shape[-1]
  743. if isinstance(attention_mask, torch.Tensor)
  744. else past_seen_tokens + sequence_length
  745. )
  746. # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
  747. causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
  748. attention_mask,
  749. sequence_length=sequence_length,
  750. target_length=target_length,
  751. dtype=dtype,
  752. device=device,
  753. cache_position=cache_position,
  754. batch_size=input_tensor.shape[0],
  755. )
  756. # We take care to integrate alibi bias in the causal_mask here
  757. if head_mask is None and alibi is not None:
  758. alibi = alibi.reshape(batch_size, -1, *alibi.shape[1:])
  759. causal_mask = torch.masked_fill(
  760. alibi / math.sqrt(self.config.hidden_size // self.num_heads),
  761. causal_mask < -1,
  762. min_dtype,
  763. )
  764. if (
  765. self.config._attn_implementation == "sdpa"
  766. and attention_mask is not None
  767. and attention_mask.device.type in ["cuda", "xpu", "npu"]
  768. and not output_attentions
  769. ):
  770. # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
  771. # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
  772. # Details: https://github.com/pytorch/pytorch/issues/110213
  773. causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
  774. return causal_mask
  775. @staticmethod
  776. # Copied from transformers.models.gptj.modeling_gptj.GPTJModel._prepare_4d_causal_attention_mask_with_cache_position
  777. def _prepare_4d_causal_attention_mask_with_cache_position(
  778. attention_mask: torch.Tensor,
  779. sequence_length: int,
  780. target_length: int,
  781. dtype: torch.dtype,
  782. cache_position: torch.Tensor,
  783. batch_size: int,
  784. **kwargs,
  785. ):
  786. """
  787. Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
  788. `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
  789. Args:
  790. attention_mask (`torch.Tensor`):
  791. A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
  792. `(batch_size, 1, query_length, key_value_length)`.
  793. sequence_length (`int`):
  794. The sequence length being processed.
  795. target_length (`int`):
  796. The target length: when generating with static cache, the mask should be as long as the static cache,
  797. to account for the 0 padding, the part of the cache that is not filled yet.
  798. dtype (`torch.dtype`):
  799. The dtype to use for the 4D attention mask.
  800. cache_position (`torch.Tensor`):
  801. Indices depicting the position of the input sequence tokens in the sequence.
  802. batch_size (`torch.Tensor`):
  803. Batch size.
  804. """
  805. if attention_mask is not None and attention_mask.dim() == 4:
  806. # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
  807. causal_mask = attention_mask
  808. else:
  809. min_dtype = torch.finfo(dtype).min
  810. causal_mask = torch.full(
  811. (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=cache_position.device
  812. )
  813. if sequence_length != 1:
  814. causal_mask = torch.triu(causal_mask, diagonal=1)
  815. causal_mask *= torch.arange(target_length, device=cache_position.device) > cache_position.reshape(-1, 1)
  816. causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
  817. if attention_mask is not None:
  818. causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
  819. mask_length = attention_mask.shape[-1]
  820. padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to(
  821. causal_mask.device
  822. )
  823. padding_mask = padding_mask == 0
  824. causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
  825. padding_mask, min_dtype
  826. )
  827. return causal_mask
  828. @auto_docstring(
  829. custom_intro="""
  830. The Falcon Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings).
  831. """
  832. )
  833. class FalconForCausalLM(FalconPreTrainedModel, GenerationMixin):
  834. _tied_weights_keys = ["lm_head.weight"]
  835. def __init__(self, config: FalconConfig):
  836. super().__init__(config)
  837. self.transformer = FalconModel(config)
  838. self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
  839. # Initialize weights and apply final processing
  840. self.post_init()
  841. def set_output_embeddings(self, new_embeddings: torch.Tensor):
  842. self.lm_head = new_embeddings
  843. @auto_docstring
  844. def forward(
  845. self,
  846. input_ids: Optional[torch.LongTensor] = None,
  847. past_key_values: Optional[Union[Cache, tuple[tuple[torch.Tensor, torch.Tensor], ...]]] = None,
  848. attention_mask: Optional[torch.Tensor] = None,
  849. position_ids: Optional[torch.LongTensor] = None,
  850. head_mask: Optional[torch.Tensor] = None,
  851. inputs_embeds: Optional[torch.Tensor] = None,
  852. labels: Optional[torch.Tensor] = None,
  853. use_cache: Optional[bool] = None,
  854. output_attentions: Optional[bool] = None,
  855. output_hidden_states: Optional[bool] = None,
  856. return_dict: Optional[bool] = None,
  857. cache_position: Optional[torch.LongTensor] = None,
  858. logits_to_keep: Union[int, torch.Tensor] = 0,
  859. **kwargs,
  860. ) -> Union[tuple[torch.Tensor], CausalLMOutputWithCrossAttentions]:
  861. r"""
  862. input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
  863. `input_ids_length` = `sequence_length` if `past_key_values` is `None` else `past_key_values.get_seq_length()`
  864. (`sequence_length` of input past key value states). Indices of input sequence tokens in the vocabulary.
  865. If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
  866. `input_ids`.
  867. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
  868. [`PreTrainedTokenizer.__call__`] for details.
  869. [What are input IDs?](../glossary#input-ids)
  870. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  871. Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
  872. `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
  873. are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
  874. """
  875. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  876. transformer_outputs = self.transformer(
  877. input_ids,
  878. past_key_values=past_key_values,
  879. attention_mask=attention_mask,
  880. position_ids=position_ids,
  881. head_mask=head_mask,
  882. inputs_embeds=inputs_embeds,
  883. use_cache=use_cache,
  884. output_attentions=output_attentions,
  885. output_hidden_states=output_hidden_states,
  886. return_dict=return_dict,
  887. cache_position=cache_position,
  888. )
  889. hidden_states = transformer_outputs[0]
  890. slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
  891. lm_logits = self.lm_head(hidden_states[:, slice_indices, :])
  892. loss = None
  893. if labels is not None:
  894. loss = self.loss_function(
  895. lm_logits,
  896. labels,
  897. vocab_size=self.config.vocab_size,
  898. **kwargs,
  899. )
  900. if not return_dict:
  901. output = (lm_logits,) + transformer_outputs[1:]
  902. return ((loss,) + output) if loss is not None else output
  903. return CausalLMOutputWithCrossAttentions(
  904. loss=loss,
  905. logits=lm_logits,
  906. past_key_values=transformer_outputs.past_key_values,
  907. hidden_states=transformer_outputs.hidden_states,
  908. attentions=transformer_outputs.attentions,
  909. )
  910. @auto_docstring(
  911. custom_intro="""
  912. The Falcon Model transformer with a sequence classification head on top (linear layer).
  913. [`FalconForSequenceClassification`] uses the last token in order to do the classification, as other causal models
  914. (e.g. GPT-1) do.
  915. Since it does classification on the last token, it requires to know the position of the last token. If a
  916. `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
  917. no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
  918. padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
  919. each row of the batch).
  920. """
  921. )
  922. class FalconForSequenceClassification(FalconPreTrainedModel):
  923. def __init__(self, config: FalconConfig):
  924. super().__init__(config)
  925. self.num_labels = config.num_labels
  926. self.transformer = FalconModel(config)
  927. self.score = nn.Linear(config.hidden_size, config.num_labels, bias=False)
  928. # Initialize weights and apply final processing
  929. self.post_init()
  930. @auto_docstring
  931. def forward(
  932. self,
  933. input_ids: Optional[torch.LongTensor] = None,
  934. past_key_values: Optional[Cache] = None,
  935. attention_mask: Optional[torch.Tensor] = None,
  936. head_mask: Optional[torch.Tensor] = None,
  937. inputs_embeds: Optional[torch.Tensor] = None,
  938. labels: Optional[torch.Tensor] = None,
  939. use_cache: Optional[bool] = None,
  940. output_attentions: Optional[bool] = None,
  941. output_hidden_states: Optional[bool] = None,
  942. return_dict: Optional[bool] = None,
  943. ) -> Union[tuple[torch.Tensor], SequenceClassifierOutputWithPast]:
  944. r"""
  945. input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
  946. `input_ids_length` = `sequence_length` if `past_key_values` is `None` else `past_key_values.get_seq_length()`
  947. (`sequence_length` of input past key value states). Indices of input sequence tokens in the vocabulary.
  948. If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
  949. `input_ids`.
  950. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
  951. [`PreTrainedTokenizer.__call__`] for details.
  952. [What are input IDs?](../glossary#input-ids)
  953. labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  954. Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
  955. config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
  956. `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
  957. """
  958. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  959. transformer_outputs = self.transformer(
  960. input_ids,
  961. past_key_values=past_key_values,
  962. attention_mask=attention_mask,
  963. head_mask=head_mask,
  964. inputs_embeds=inputs_embeds,
  965. use_cache=use_cache,
  966. output_attentions=output_attentions,
  967. output_hidden_states=output_hidden_states,
  968. return_dict=return_dict,
  969. )
  970. hidden_states = transformer_outputs[0]
  971. logits = self.score(hidden_states)
  972. if input_ids is not None:
  973. batch_size = input_ids.shape[0]
  974. else:
  975. batch_size = inputs_embeds.shape[0]
  976. if self.config.pad_token_id is None and batch_size != 1:
  977. raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
  978. if self.config.pad_token_id is None:
  979. last_non_pad_token = -1
  980. elif input_ids is not None:
  981. # To handle both left- and right- padding, we take the rightmost token that is not equal to pad_token_id
  982. non_pad_mask = (input_ids != self.config.pad_token_id).to(logits.device, torch.int32)
  983. token_indices = torch.arange(input_ids.shape[-1], device=logits.device, dtype=torch.int32)
  984. last_non_pad_token = (token_indices * non_pad_mask).argmax(-1)
  985. else:
  986. last_non_pad_token = -1
  987. logger.warning_once(
  988. f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
  989. "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
  990. )
  991. pooled_logits = logits[torch.arange(batch_size, device=logits.device), last_non_pad_token]
  992. loss = None
  993. if labels is not None:
  994. if self.config.problem_type is None:
  995. if self.num_labels == 1:
  996. self.config.problem_type = "regression"
  997. elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
  998. self.config.problem_type = "single_label_classification"
  999. else:
  1000. self.config.problem_type = "multi_label_classification"
  1001. if self.config.problem_type == "regression":
  1002. loss_fct = MSELoss()
  1003. if self.num_labels == 1:
  1004. loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
  1005. else:
  1006. loss = loss_fct(pooled_logits, labels)
  1007. elif self.config.problem_type == "single_label_classification":
  1008. loss_fct = CrossEntropyLoss()
  1009. loss = loss_fct(pooled_logits, labels)
  1010. elif self.config.problem_type == "multi_label_classification":
  1011. loss_fct = BCEWithLogitsLoss()
  1012. loss = loss_fct(pooled_logits, labels)
  1013. if not return_dict:
  1014. output = (pooled_logits,) + transformer_outputs[1:]
  1015. return ((loss,) + output) if loss is not None else output
  1016. return SequenceClassifierOutputWithPast(
  1017. loss=loss,
  1018. logits=pooled_logits,
  1019. past_key_values=transformer_outputs.past_key_values,
  1020. hidden_states=transformer_outputs.hidden_states,
  1021. attentions=transformer_outputs.attentions,
  1022. )
  1023. @auto_docstring
  1024. class FalconForTokenClassification(FalconPreTrainedModel):
  1025. def __init__(self, config: FalconConfig):
  1026. super().__init__(config)
  1027. self.num_labels = config.num_labels
  1028. self.transformer = FalconModel(config)
  1029. if getattr(config, "classifier_dropout", None) is not None:
  1030. classifier_dropout = config.classifier_dropout
  1031. elif getattr(config, "hidden_dropout", None) is not None:
  1032. classifier_dropout = config.hidden_dropout
  1033. else:
  1034. classifier_dropout = 0.1
  1035. self.dropout = nn.Dropout(classifier_dropout)
  1036. self.classifier = nn.Linear(config.hidden_size, config.num_labels)
  1037. # Initialize weights and apply final processing
  1038. self.post_init()
  1039. @auto_docstring
  1040. def forward(
  1041. self,
  1042. input_ids: Optional[torch.LongTensor] = None,
  1043. past_key_values: Optional[Cache] = None,
  1044. attention_mask: Optional[torch.Tensor] = None,
  1045. head_mask: Optional[torch.Tensor] = None,
  1046. inputs_embeds: Optional[torch.Tensor] = None,
  1047. labels: Optional[torch.Tensor] = None,
  1048. use_cache: Optional[bool] = None,
  1049. output_attentions: Optional[bool] = None,
  1050. output_hidden_states: Optional[bool] = None,
  1051. return_dict: Optional[bool] = None,
  1052. ) -> Union[tuple[torch.Tensor], TokenClassifierOutput]:
  1053. r"""
  1054. input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
  1055. `input_ids_length` = `sequence_length` if `past_key_values` is `None` else `past_key_values.get_seq_length()`
  1056. (`sequence_length` of input past key value states). Indices of input sequence tokens in the vocabulary.
  1057. If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
  1058. `input_ids`.
  1059. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
  1060. [`PreTrainedTokenizer.__call__`] for details.
  1061. [What are input IDs?](../glossary#input-ids)
  1062. labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  1063. Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
  1064. config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
  1065. `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
  1066. """
  1067. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  1068. transformer_outputs = self.transformer(
  1069. input_ids,
  1070. past_key_values=past_key_values,
  1071. attention_mask=attention_mask,
  1072. head_mask=head_mask,
  1073. inputs_embeds=inputs_embeds,
  1074. use_cache=use_cache,
  1075. output_attentions=output_attentions,
  1076. output_hidden_states=output_hidden_states,
  1077. return_dict=return_dict,
  1078. )
  1079. hidden_states = transformer_outputs[0]
  1080. hidden_states = self.dropout(hidden_states)
  1081. logits = self.classifier(hidden_states)
  1082. loss = None
  1083. if labels is not None:
  1084. batch_size, seq_length = labels.shape
  1085. loss_fct = CrossEntropyLoss()
  1086. loss = loss_fct(
  1087. logits.view(batch_size * seq_length, self.num_labels), labels.view(batch_size * seq_length)
  1088. )
  1089. if not return_dict:
  1090. output = (logits,) + transformer_outputs[2:]
  1091. return ((loss,) + output) if loss is not None else output
  1092. return TokenClassifierOutput(
  1093. loss=loss,
  1094. logits=logits,
  1095. hidden_states=transformer_outputs.hidden_states,
  1096. attentions=transformer_outputs.attentions,
  1097. )
  1098. @auto_docstring
  1099. class FalconForQuestionAnswering(FalconPreTrainedModel):
  1100. def __init__(self, config):
  1101. super().__init__(config)
  1102. self.transformer = FalconModel(config)
  1103. self.qa_outputs = nn.Linear(config.hidden_size, 2)
  1104. # Initialize weights and apply final processing
  1105. self.post_init()
  1106. @auto_docstring
  1107. def forward(
  1108. self,
  1109. input_ids: Optional[torch.LongTensor] = None,
  1110. attention_mask: Optional[torch.FloatTensor] = None,
  1111. head_mask: Optional[torch.FloatTensor] = None,
  1112. inputs_embeds: Optional[torch.FloatTensor] = None,
  1113. start_positions: Optional[torch.LongTensor] = None,
  1114. end_positions: Optional[torch.LongTensor] = None,
  1115. output_attentions: Optional[bool] = None,
  1116. output_hidden_states: Optional[bool] = None,
  1117. return_dict: Optional[bool] = None,
  1118. ) -> Union[tuple, QuestionAnsweringModelOutput]:
  1119. r"""
  1120. input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
  1121. `input_ids_length` = `sequence_length` if `past_key_values` is `None` else `past_key_values.get_seq_length()`
  1122. (`sequence_length` of input past key value states). Indices of input sequence tokens in the vocabulary.
  1123. If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
  1124. `input_ids`.
  1125. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
  1126. [`PreTrainedTokenizer.__call__`] for details.
  1127. [What are input IDs?](../glossary#input-ids)
  1128. """
  1129. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  1130. outputs = self.transformer(
  1131. input_ids,
  1132. attention_mask=attention_mask,
  1133. head_mask=head_mask,
  1134. inputs_embeds=inputs_embeds,
  1135. output_attentions=output_attentions,
  1136. output_hidden_states=output_hidden_states,
  1137. return_dict=return_dict,
  1138. )
  1139. sequence_output = outputs[0]
  1140. logits = self.qa_outputs(sequence_output)
  1141. start_logits, end_logits = logits.split(1, dim=-1)
  1142. start_logits = start_logits.squeeze(-1).contiguous()
  1143. end_logits = end_logits.squeeze(-1).contiguous()
  1144. total_loss = None
  1145. if start_positions is not None and end_positions is not None:
  1146. # If we are on multi-GPU, split add a dimension
  1147. if len(start_positions.size()) > 1:
  1148. start_positions = start_positions.squeeze(-1)
  1149. if len(end_positions.size()) > 1:
  1150. end_positions = end_positions.squeeze(-1)
  1151. # sometimes the start/end positions are outside our model inputs, we ignore these terms
  1152. ignored_index = start_logits.size(1)
  1153. start_positions = start_positions.clamp(0, ignored_index)
  1154. end_positions = end_positions.clamp(0, ignored_index)
  1155. loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
  1156. start_loss = loss_fct(start_logits, start_positions)
  1157. end_loss = loss_fct(end_logits, end_positions)
  1158. total_loss = (start_loss + end_loss) / 2
  1159. if not return_dict:
  1160. output = (start_logits, end_logits) + outputs[2:]
  1161. return ((total_loss,) + output) if total_loss is not None else output
  1162. return QuestionAnsweringModelOutput(
  1163. loss=total_loss,
  1164. start_logits=start_logits,
  1165. end_logits=end_logits,
  1166. hidden_states=outputs.hidden_states,
  1167. attentions=outputs.attentions,
  1168. )
  1169. __all__ = [
  1170. "FalconForCausalLM",
  1171. "FalconModel",
  1172. "FalconPreTrainedModel",
  1173. "FalconForSequenceClassification",
  1174. "FalconForTokenClassification",
  1175. "FalconForQuestionAnswering",
  1176. ]