modeling_cohere.py 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188
  1. # coding=utf-8
  2. # Copyright 2024 Cohere 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. # This file is based on the LLama model definition file in transformers
  21. """PyTorch Cohere model."""
  22. import math
  23. from typing import List, Optional, Tuple, Union
  24. import torch
  25. import torch.utils.checkpoint
  26. from torch import nn
  27. from ...activations import ACT2FN
  28. from ...cache_utils import Cache, DynamicCache, StaticCache
  29. from ...generation import GenerationMixin
  30. from ...modeling_attn_mask_utils import AttentionMaskConverter
  31. from ...modeling_outputs import (
  32. BaseModelOutputWithPast,
  33. CausalLMOutputWithPast,
  34. )
  35. from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS
  36. from ...modeling_utils import PreTrainedModel
  37. from ...pytorch_utils import ALL_LAYERNORM_LAYERS
  38. from ...utils import (
  39. add_start_docstrings,
  40. add_start_docstrings_to_model_forward,
  41. is_flash_attn_2_available,
  42. is_flash_attn_greater_or_equal_2_10,
  43. logging,
  44. replace_return_docstrings,
  45. )
  46. from .configuration_cohere import CohereConfig
  47. if is_flash_attn_2_available():
  48. from ...modeling_flash_attention_utils import _flash_attention_forward
  49. logger = logging.get_logger(__name__)
  50. _CONFIG_FOR_DOC = "CohereConfig"
  51. class CohereLayerNorm(nn.Module):
  52. def __init__(self, hidden_size=None, eps=1e-5, bias=False):
  53. """The hidden size can be a tuple or an int. The tuple is used for QKNorm to normalize across head_dim"""
  54. super().__init__()
  55. self.weight = nn.Parameter(torch.ones(hidden_size))
  56. self.variance_epsilon = eps
  57. def forward(self, hidden_states):
  58. input_dtype = hidden_states.dtype
  59. hidden_states = hidden_states.to(torch.float32)
  60. mean = hidden_states.mean(-1, keepdim=True)
  61. variance = (hidden_states - mean).pow(2).mean(-1, keepdim=True)
  62. hidden_states = (hidden_states - mean) * torch.rsqrt(variance + self.variance_epsilon)
  63. hidden_states = self.weight.to(torch.float32) * hidden_states
  64. return hidden_states.to(input_dtype)
  65. ALL_LAYERNORM_LAYERS.append(CohereLayerNorm)
  66. class CohereRotaryEmbedding(nn.Module):
  67. # Note: the forward pass of this RoPE is slightly different from Llama's, resulting in different `sin`/`cos` for
  68. # the same parameterization. The differences are highlighted with a comment.
  69. def __init__(
  70. self,
  71. dim=None,
  72. max_position_embeddings=2048,
  73. base=10000,
  74. device=None,
  75. scaling_factor=1.0,
  76. rope_type="default",
  77. config: Optional[CohereConfig] = None,
  78. ):
  79. super().__init__()
  80. # TODO (joao): remove the `if` below, only used for BC
  81. self.rope_kwargs = {}
  82. if config is None:
  83. logger.warning_once(
  84. "`CohereRotaryEmbedding` can now be fully parameterized by passing the model config through the "
  85. "`config` argument. All other arguments will be removed in v4.46"
  86. )
  87. self.rope_kwargs = {
  88. "rope_type": rope_type,
  89. "factor": scaling_factor,
  90. "dim": dim,
  91. "base": base,
  92. "max_position_embeddings": max_position_embeddings,
  93. }
  94. self.rope_type = rope_type
  95. self.max_seq_len_cached = max_position_embeddings
  96. self.original_max_seq_len = max_position_embeddings
  97. else:
  98. # BC: "rope_type" was originally "type"
  99. if config.rope_scaling is not None:
  100. self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
  101. else:
  102. self.rope_type = "default"
  103. self.max_seq_len_cached = config.max_position_embeddings
  104. self.original_max_seq_len = config.max_position_embeddings
  105. self.config = config
  106. self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
  107. inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, **self.rope_kwargs)
  108. self.register_buffer("inv_freq", inv_freq, persistent=False)
  109. self.original_inv_freq = self.inv_freq
  110. def _dynamic_frequency_update(self, position_ids, device):
  111. """
  112. dynamic RoPE layers should recompute `inv_freq` in the following situations:
  113. 1 - growing beyond the cached sequence length (allow scaling)
  114. 2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
  115. """
  116. seq_len = torch.max(position_ids) + 1
  117. if seq_len > self.max_seq_len_cached: # growth
  118. inv_freq, self.attention_scaling = self.rope_init_fn(
  119. self.config, device, seq_len=seq_len, **self.rope_kwargs
  120. )
  121. self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
  122. self.max_seq_len_cached = seq_len
  123. if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
  124. self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
  125. self.max_seq_len_cached = self.original_max_seq_len
  126. @torch.no_grad()
  127. def forward(self, x, position_ids):
  128. if "dynamic" in self.rope_type:
  129. self._dynamic_frequency_update(position_ids, device=x.device)
  130. # Core RoPE block
  131. inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
  132. position_ids_expanded = position_ids[:, None, :].float()
  133. # Force float32 (see https://github.com/huggingface/transformers/pull/29285)
  134. device_type = x.device.type
  135. device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
  136. with torch.autocast(device_type=device_type, enabled=False):
  137. freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
  138. emb = torch.repeat_interleave(freqs, 2, dim=-1) # This line differs from Llama's implementation
  139. cos = emb.cos()
  140. sin = emb.sin()
  141. # Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
  142. cos = cos * self.attention_scaling
  143. sin = sin * self.attention_scaling
  144. return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
  145. def rotate_half(x):
  146. # Split and rotate. Note that this function is different from e.g. Llama.
  147. x1 = x[..., ::2]
  148. x2 = x[..., 1::2]
  149. rot_x = torch.stack([-x2, x1], dim=-1).flatten(-2)
  150. return rot_x
  151. def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
  152. """Applies Rotary Position Embedding to the query and key tensors.
  153. Args:
  154. q (`torch.Tensor`): The query tensor.
  155. k (`torch.Tensor`): The key tensor.
  156. cos (`torch.Tensor`): The cosine part of the rotary embedding.
  157. sin (`torch.Tensor`): The sine part of the rotary embedding.
  158. position_ids (`torch.Tensor`, *optional*):
  159. Deprecated and unused.
  160. unsqueeze_dim (`int`, *optional*, defaults to 1):
  161. The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
  162. sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
  163. that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
  164. k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
  165. cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
  166. the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
  167. Returns:
  168. `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
  169. """
  170. dtype = q.dtype
  171. q = q.float()
  172. k = k.float()
  173. cos = cos.unsqueeze(unsqueeze_dim)
  174. sin = sin.unsqueeze(unsqueeze_dim)
  175. q_embed = (q * cos) + (rotate_half(q) * sin)
  176. k_embed = (k * cos) + (rotate_half(k) * sin)
  177. return q_embed.to(dtype=dtype), k_embed.to(dtype=dtype)
  178. class CohereMLP(nn.Module):
  179. def __init__(self, config):
  180. super().__init__()
  181. self.config = config
  182. self.hidden_size = config.hidden_size
  183. self.intermediate_size = config.intermediate_size
  184. self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
  185. self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
  186. self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
  187. self.act_fn = ACT2FN[config.hidden_act]
  188. # Ignore copy
  189. def forward(self, x):
  190. down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
  191. return down_proj
  192. # Copied from transformers.models.llama.modeling_llama.repeat_kv
  193. def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
  194. """
  195. This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
  196. num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
  197. """
  198. batch, num_key_value_heads, slen, head_dim = hidden_states.shape
  199. if n_rep == 1:
  200. return hidden_states
  201. hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
  202. return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
  203. class CohereAttention(nn.Module):
  204. """Multi-headed attention from 'Attention Is All You Need' paper"""
  205. def __init__(self, config: CohereConfig, layer_idx: Optional[int] = None):
  206. super().__init__()
  207. self.config = config
  208. self.layer_idx = layer_idx
  209. if layer_idx is None:
  210. logger.warning_once(
  211. f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
  212. "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
  213. "when creating this class."
  214. )
  215. self.attention_dropout = config.attention_dropout
  216. self.hidden_size = config.hidden_size
  217. self.num_heads = config.num_attention_heads
  218. self.head_dim = self.hidden_size // self.num_heads
  219. self.num_key_value_heads = config.num_key_value_heads
  220. self.num_key_value_groups = self.num_heads // self.num_key_value_heads
  221. self.max_position_embeddings = config.max_position_embeddings
  222. self.rope_theta = config.rope_theta
  223. self.is_causal = True
  224. self.use_qk_norm = config.use_qk_norm
  225. if (self.head_dim * self.num_heads) != self.hidden_size:
  226. raise ValueError(
  227. f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
  228. f" and `num_heads`: {self.num_heads})."
  229. )
  230. if self.use_qk_norm:
  231. # When sharding the model using Tensor Parallelism, need to be careful to use n_local_heads
  232. self.q_norm = CohereLayerNorm(hidden_size=(self.num_heads, self.head_dim), eps=config.layer_norm_eps)
  233. self.k_norm = CohereLayerNorm(
  234. hidden_size=(self.num_key_value_heads, self.head_dim), eps=config.layer_norm_eps
  235. )
  236. self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
  237. self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
  238. self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
  239. self.o_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=config.attention_bias)
  240. # TODO (joao): remove in v4.46 (RoPE is computed in the model, not in the decoder layers)
  241. self.rotary_emb = CohereRotaryEmbedding(config=self.config)
  242. def forward(
  243. self,
  244. hidden_states: torch.Tensor,
  245. attention_mask: Optional[torch.Tensor] = None,
  246. position_ids: Optional[torch.LongTensor] = None,
  247. past_key_value: Optional[Cache] = None,
  248. output_attentions: bool = False,
  249. use_cache: bool = False,
  250. cache_position: Optional[torch.LongTensor] = None,
  251. position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
  252. **kwargs,
  253. ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
  254. bsz, q_len, _ = hidden_states.size()
  255. query_states = self.q_proj(hidden_states)
  256. key_states = self.k_proj(hidden_states)
  257. value_states = self.v_proj(hidden_states)
  258. query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim)
  259. key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim)
  260. if self.use_qk_norm:
  261. query_states = self.q_norm(query_states)
  262. key_states = self.k_norm(key_states)
  263. query_states = query_states.transpose(1, 2)
  264. key_states = key_states.transpose(1, 2)
  265. value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
  266. if position_embeddings is None:
  267. logger.warning_once(
  268. "The attention layers in this model are transitioning from computing the RoPE embeddings internally "
  269. "through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
  270. "`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.46 `position_ids` will be "
  271. "removed and `position_embeddings` will be mandatory."
  272. )
  273. cos, sin = self.rotary_emb(value_states, position_ids)
  274. else:
  275. cos, sin = position_embeddings
  276. query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
  277. if past_key_value is not None:
  278. # sin and cos are specific to RoPE models; position_ids needed for the static cache
  279. cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
  280. key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
  281. key_states = repeat_kv(key_states, self.num_key_value_groups)
  282. value_states = repeat_kv(value_states, self.num_key_value_groups)
  283. attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
  284. if attention_mask is not None: # no matter the length, we just slice it
  285. causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
  286. attn_weights = attn_weights + causal_mask
  287. # upcast attention to fp32
  288. attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
  289. attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
  290. attn_output = torch.matmul(attn_weights, value_states)
  291. if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
  292. raise ValueError(
  293. f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
  294. f" {attn_output.size()}"
  295. )
  296. attn_output = attn_output.transpose(1, 2).contiguous()
  297. attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
  298. attn_output = self.o_proj(attn_output)
  299. if not output_attentions:
  300. attn_weights = None
  301. return attn_output, attn_weights, past_key_value
  302. # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2 with Llama->Cohere
  303. class CohereFlashAttention2(CohereAttention):
  304. """
  305. Cohere flash attention module. This module inherits from `CohereAttention` as the weights of the module stays
  306. untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
  307. flash attention and deal with padding tokens in case the input contains any of them.
  308. """
  309. def __init__(self, *args, **kwargs):
  310. super().__init__(*args, **kwargs)
  311. # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
  312. # 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.
  313. # 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).
  314. self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
  315. # Ignore copy
  316. def forward(
  317. self,
  318. hidden_states: torch.Tensor,
  319. attention_mask: Optional[torch.LongTensor] = None,
  320. position_ids: Optional[torch.LongTensor] = None,
  321. past_key_value: Optional[Cache] = None,
  322. output_attentions: bool = False,
  323. use_cache: bool = False,
  324. cache_position: Optional[torch.LongTensor] = None,
  325. position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
  326. **kwargs,
  327. ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
  328. if isinstance(past_key_value, StaticCache):
  329. raise ValueError(
  330. "`static` cache implementation is not compatible with `attn_implementation==flash_attention_2` "
  331. "make sure to use `sdpa` in the mean time, and open an issue at https://github.com/huggingface/transformers"
  332. )
  333. output_attentions = False
  334. bsz, q_len, _ = hidden_states.size()
  335. query_states = self.q_proj(hidden_states)
  336. key_states = self.k_proj(hidden_states)
  337. value_states = self.v_proj(hidden_states)
  338. query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim)
  339. key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim)
  340. if self.use_qk_norm:
  341. query_states = self.q_norm(query_states)
  342. key_states = self.k_norm(key_states)
  343. query_states = query_states.transpose(1, 2)
  344. key_states = key_states.transpose(1, 2)
  345. value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
  346. if position_embeddings is None:
  347. logger.warning_once(
  348. "The attention layers in this model are transitioning from computing the RoPE embeddings internally "
  349. "through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
  350. "`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.46 `position_ids` will be "
  351. "removed and `position_embeddings` will be mandatory."
  352. )
  353. cos, sin = self.rotary_emb(value_states, position_ids)
  354. else:
  355. cos, sin = position_embeddings
  356. query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
  357. if past_key_value is not None:
  358. # sin and cos are specific to RoPE models; position_ids needed for the static cache
  359. cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
  360. key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
  361. # 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
  362. # to be able to avoid many of these transpose/reshape/view.
  363. query_states = query_states.transpose(1, 2)
  364. key_states = key_states.transpose(1, 2)
  365. value_states = value_states.transpose(1, 2)
  366. dropout_rate = self.attention_dropout if self.training else 0.0
  367. # In PEFT, usually we cast the layer norms in float32 for training stability reasons
  368. # therefore the input hidden states gets silently casted in float32. Hence, we need
  369. # cast them back in the correct dtype just to be sure everything works as expected.
  370. # This might slowdown training & inference so it is recommended to not cast the LayerNorms
  371. # in fp32. (CohereLayerNorm handles it correctly)
  372. input_dtype = query_states.dtype
  373. if input_dtype == torch.float32:
  374. if torch.is_autocast_enabled():
  375. target_dtype = torch.get_autocast_gpu_dtype()
  376. # Handle the case where the model is quantized
  377. elif hasattr(self.config, "_pre_quantization_dtype"):
  378. target_dtype = self.config._pre_quantization_dtype
  379. else:
  380. target_dtype = self.q_proj.weight.dtype
  381. logger.warning_once(
  382. f"The input hidden states seems to be silently casted in float32, this might be related to"
  383. f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
  384. f" {target_dtype}."
  385. )
  386. query_states = query_states.to(target_dtype)
  387. key_states = key_states.to(target_dtype)
  388. value_states = value_states.to(target_dtype)
  389. attn_output = _flash_attention_forward(
  390. query_states,
  391. key_states,
  392. value_states,
  393. attention_mask,
  394. q_len,
  395. dropout=dropout_rate,
  396. use_top_left_mask=self._flash_attn_uses_top_left_mask,
  397. is_causal=self.is_causal,
  398. )
  399. attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
  400. attn_output = self.o_proj(attn_output)
  401. if not output_attentions:
  402. attn_weights = None
  403. return attn_output, attn_weights, past_key_value
  404. class CohereSdpaAttention(CohereAttention):
  405. """
  406. Cohere attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
  407. `CohereAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
  408. SDPA API.
  409. """
  410. def forward(
  411. self,
  412. hidden_states: torch.Tensor,
  413. attention_mask: Optional[torch.Tensor] = None,
  414. position_ids: Optional[torch.LongTensor] = None,
  415. past_key_value: Optional[Cache] = None,
  416. output_attentions: bool = False,
  417. use_cache: bool = False,
  418. cache_position: Optional[torch.LongTensor] = None,
  419. position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
  420. ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
  421. if output_attentions:
  422. # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
  423. logger.warning_once(
  424. "CohereModel is using CohereSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
  425. 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
  426. )
  427. return super().forward(
  428. hidden_states=hidden_states,
  429. attention_mask=attention_mask,
  430. position_ids=position_ids,
  431. past_key_value=past_key_value,
  432. output_attentions=output_attentions,
  433. use_cache=use_cache,
  434. cache_position=cache_position,
  435. )
  436. bsz, q_len, _ = hidden_states.size()
  437. query_states = self.q_proj(hidden_states)
  438. key_states = self.k_proj(hidden_states)
  439. value_states = self.v_proj(hidden_states)
  440. query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim)
  441. key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim)
  442. if self.use_qk_norm:
  443. query_states = self.q_norm(query_states)
  444. key_states = self.k_norm(key_states)
  445. query_states = query_states.transpose(1, 2)
  446. key_states = key_states.transpose(1, 2)
  447. value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
  448. if position_embeddings is None:
  449. logger.warning_once(
  450. "The attention layers in this model are transitioning from computing the RoPE embeddings internally "
  451. "through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
  452. "`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.46 `position_ids` will be "
  453. "removed and `position_embeddings` will be mandatory."
  454. )
  455. cos, sin = self.rotary_emb(value_states, position_ids)
  456. else:
  457. cos, sin = position_embeddings
  458. query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
  459. if past_key_value is not None:
  460. # sin and cos are specific to RoPE models; cache_position needed for the static cache
  461. cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
  462. key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
  463. key_states = repeat_kv(key_states, self.num_key_value_groups)
  464. value_states = repeat_kv(value_states, self.num_key_value_groups)
  465. causal_mask = attention_mask
  466. # if attention_mask is not None and cache_position is not None:
  467. if attention_mask is not None:
  468. causal_mask = causal_mask[:, :, :, : key_states.shape[-2]]
  469. # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
  470. # Reference: https://github.com/pytorch/pytorch/issues/112577.
  471. if query_states.device.type == "cuda" and causal_mask is not None:
  472. query_states = query_states.contiguous()
  473. key_states = key_states.contiguous()
  474. value_states = value_states.contiguous()
  475. # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
  476. # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
  477. is_causal = True if causal_mask is None and q_len > 1 else False
  478. attn_output = torch.nn.functional.scaled_dot_product_attention(
  479. query_states,
  480. key_states,
  481. value_states,
  482. attn_mask=causal_mask,
  483. dropout_p=self.attention_dropout if self.training else 0.0,
  484. is_causal=is_causal,
  485. )
  486. attn_output = attn_output.transpose(1, 2).contiguous()
  487. attn_output = attn_output.view(bsz, q_len, self.hidden_size)
  488. attn_output = self.o_proj(attn_output)
  489. return attn_output, None, past_key_value
  490. COHERE_ATTENTION_CLASSES = {
  491. "eager": CohereAttention,
  492. "flash_attention_2": CohereFlashAttention2,
  493. "sdpa": CohereSdpaAttention,
  494. }
  495. class CohereDecoderLayer(nn.Module):
  496. def __init__(self, config: CohereConfig, layer_idx: int):
  497. super().__init__()
  498. self.hidden_size = config.hidden_size
  499. self.self_attn = COHERE_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
  500. self.mlp = CohereMLP(config)
  501. self.input_layernorm = CohereLayerNorm(hidden_size=(config.hidden_size), eps=config.layer_norm_eps)
  502. def forward(
  503. self,
  504. hidden_states: torch.Tensor,
  505. attention_mask: Optional[torch.Tensor] = None,
  506. position_ids: Optional[torch.LongTensor] = None,
  507. past_key_value: Optional[Tuple[torch.Tensor]] = None,
  508. output_attentions: Optional[bool] = False,
  509. use_cache: Optional[bool] = False,
  510. cache_position: Optional[torch.LongTensor] = None,
  511. position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
  512. ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
  513. """
  514. Args:
  515. hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
  516. attention_mask (`torch.FloatTensor`, *optional*):
  517. attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
  518. query_sequence_length, key_sequence_length)` if default attention is used.
  519. output_attentions (`bool`, *optional*):
  520. Whether or not to return the attentions tensors of all attention layers. See `attentions` under
  521. returned tensors for more detail.
  522. use_cache (`bool`, *optional*):
  523. If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
  524. (see `past_key_values`).
  525. past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
  526. cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
  527. Indices depicting the position of the input sequence tokens in the sequence
  528. position_embeddings (`Tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
  529. Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
  530. with `head_dim` being the embedding dimension of each attention head.
  531. """
  532. residual = hidden_states
  533. hidden_states = self.input_layernorm(hidden_states)
  534. # Self Attention
  535. hidden_states_attention, self_attn_weights, present_key_value = self.self_attn(
  536. hidden_states=hidden_states,
  537. attention_mask=attention_mask,
  538. position_ids=position_ids,
  539. past_key_value=past_key_value,
  540. output_attentions=output_attentions,
  541. use_cache=use_cache,
  542. cache_position=cache_position,
  543. position_embeddings=position_embeddings,
  544. )
  545. # Fully Connected
  546. hidden_states_mlp = self.mlp(hidden_states)
  547. # Add everything together
  548. hidden_states = residual + hidden_states_attention + hidden_states_mlp
  549. outputs = (hidden_states,)
  550. if output_attentions:
  551. outputs += (self_attn_weights,)
  552. if use_cache:
  553. outputs += (present_key_value,)
  554. return outputs
  555. COHERE_START_DOCSTRING = r"""
  556. This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
  557. library implements for all its model (such as downloading or saving, resizing the input embeddings etc.).
  558. This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
  559. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
  560. and behavior.
  561. Parameters:
  562. config ([`CohereConfig`]):
  563. Model configuration class with all the parameters of the model. Initializing with a config file does not
  564. load the weights associated with the model, only the configuration. Check out the
  565. [`~PreTrainedModel.from_pretrained`] method to load the model weights.
  566. """
  567. @add_start_docstrings(
  568. "The bare Cohere Model outputting raw hidden-states without any specific head on top.",
  569. COHERE_START_DOCSTRING,
  570. )
  571. # Copied from transformers.models.llama.modeling_llama.LlamaPreTrainedModel with Llama->Cohere
  572. class CoherePreTrainedModel(PreTrainedModel):
  573. config_class = CohereConfig
  574. base_model_prefix = "model"
  575. supports_gradient_checkpointing = True
  576. _no_split_modules = ["CohereDecoderLayer"]
  577. _skip_keys_device_placement = ["past_key_values"]
  578. _supports_flash_attn_2 = True
  579. _supports_sdpa = True
  580. _supports_cache_class = True
  581. _supports_quantized_cache = True
  582. _supports_static_cache = True
  583. def _init_weights(self, module):
  584. std = self.config.initializer_range
  585. if isinstance(module, nn.Linear):
  586. module.weight.data.normal_(mean=0.0, std=std)
  587. if module.bias is not None:
  588. module.bias.data.zero_()
  589. elif isinstance(module, nn.Embedding):
  590. module.weight.data.normal_(mean=0.0, std=std)
  591. if module.padding_idx is not None:
  592. module.weight.data[module.padding_idx].zero_()
  593. COHERE_INPUTS_DOCSTRING = r"""
  594. Args:
  595. input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
  596. Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
  597. it.
  598. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
  599. [`PreTrainedTokenizer.__call__`] for details.
  600. [What are input IDs?](../glossary#input-ids)
  601. attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
  602. Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
  603. - 1 for tokens that are **not masked**,
  604. - 0 for tokens that are **masked**.
  605. [What are attention masks?](../glossary#attention-mask)
  606. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
  607. [`PreTrainedTokenizer.__call__`] for details.
  608. If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
  609. `past_key_values`).
  610. If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
  611. and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
  612. information on the default strategy.
  613. - 1 indicates the head is **not masked**,
  614. - 0 indicates the head is **masked**.
  615. position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  616. Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
  617. config.n_positions - 1]`.
  618. [What are position IDs?](../glossary#position-ids)
  619. past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
  620. Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
  621. blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
  622. returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
  623. Two formats are allowed:
  624. - a [`~cache_utils.Cache`] instance, see our
  625. [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);
  626. - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
  627. shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
  628. cache format.
  629. The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
  630. legacy cache format will be returned.
  631. If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
  632. have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
  633. of shape `(batch_size, sequence_length)`.
  634. inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
  635. Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
  636. is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
  637. model's internal embedding lookup matrix.
  638. use_cache (`bool`, *optional*):
  639. If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
  640. `past_key_values`).
  641. output_attentions (`bool`, *optional*):
  642. Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
  643. tensors for more detail.
  644. output_hidden_states (`bool`, *optional*):
  645. Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
  646. more detail.
  647. return_dict (`bool`, *optional*):
  648. Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
  649. """
  650. @add_start_docstrings(
  651. "The bare Cohere Model outputting raw hidden-states without any specific head on top.",
  652. COHERE_START_DOCSTRING,
  653. )
  654. # Copied from transformers.models.llama.modeling_llama.LlamaModel with Llama->Cohere, LLAMA->COHERE
  655. class CohereModel(CoherePreTrainedModel):
  656. """
  657. Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`CohereDecoderLayer`]
  658. Args:
  659. config: CohereConfig
  660. """
  661. # Ignore copy
  662. def __init__(self, config: CohereConfig):
  663. super().__init__(config)
  664. self.padding_idx = config.pad_token_id
  665. self.vocab_size = config.vocab_size
  666. self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
  667. self.layers = nn.ModuleList(
  668. [CohereDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
  669. )
  670. self.norm = CohereLayerNorm(hidden_size=(config.hidden_size), eps=config.layer_norm_eps)
  671. self.rotary_emb = CohereRotaryEmbedding(config=config)
  672. self.gradient_checkpointing = False
  673. # Initialize weights and apply final processing
  674. self.post_init()
  675. def get_input_embeddings(self):
  676. return self.embed_tokens
  677. def set_input_embeddings(self, value):
  678. self.embed_tokens = value
  679. @add_start_docstrings_to_model_forward(COHERE_INPUTS_DOCSTRING)
  680. def forward(
  681. self,
  682. input_ids: torch.LongTensor = None,
  683. attention_mask: Optional[torch.Tensor] = None,
  684. position_ids: Optional[torch.LongTensor] = None,
  685. past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
  686. inputs_embeds: Optional[torch.FloatTensor] = None,
  687. use_cache: Optional[bool] = None,
  688. output_attentions: Optional[bool] = None,
  689. output_hidden_states: Optional[bool] = None,
  690. return_dict: Optional[bool] = None,
  691. cache_position: Optional[torch.LongTensor] = None,
  692. ) -> Union[Tuple, BaseModelOutputWithPast]:
  693. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  694. output_hidden_states = (
  695. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  696. )
  697. use_cache = use_cache if use_cache is not None else self.config.use_cache
  698. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  699. if (input_ids is None) ^ (inputs_embeds is not None):
  700. raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
  701. if self.gradient_checkpointing and self.training and use_cache:
  702. logger.warning_once(
  703. "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
  704. )
  705. use_cache = False
  706. if inputs_embeds is None:
  707. inputs_embeds = self.embed_tokens(input_ids)
  708. # kept for BC (non `Cache` `past_key_values` inputs)
  709. return_legacy_cache = False
  710. if use_cache and not isinstance(past_key_values, Cache):
  711. return_legacy_cache = True
  712. if past_key_values is None:
  713. past_key_values = DynamicCache()
  714. else:
  715. past_key_values = DynamicCache.from_legacy_cache(past_key_values)
  716. logger.warning_once(
  717. "We detected that you are passing `past_key_values` as a tuple of tuples. This is deprecated and "
  718. "will be removed in v4.47. Please convert your cache or use an appropriate `Cache` class "
  719. "(https://huggingface.co/docs/transformers/kv_cache#legacy-cache-format)"
  720. )
  721. if cache_position is None:
  722. past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
  723. cache_position = torch.arange(
  724. past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
  725. )
  726. if position_ids is None:
  727. position_ids = cache_position.unsqueeze(0)
  728. causal_mask = self._update_causal_mask(
  729. attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
  730. )
  731. hidden_states = inputs_embeds
  732. # create position embeddings to be shared across the decoder layers
  733. position_embeddings = self.rotary_emb(hidden_states, position_ids)
  734. # decoder layers
  735. all_hidden_states = () if output_hidden_states else None
  736. all_self_attns = () if output_attentions else None
  737. next_decoder_cache = None
  738. for decoder_layer in self.layers:
  739. if output_hidden_states:
  740. all_hidden_states += (hidden_states,)
  741. if self.gradient_checkpointing and self.training:
  742. layer_outputs = self._gradient_checkpointing_func(
  743. decoder_layer.__call__,
  744. hidden_states,
  745. causal_mask,
  746. position_ids,
  747. past_key_values,
  748. output_attentions,
  749. use_cache,
  750. cache_position,
  751. position_embeddings,
  752. )
  753. else:
  754. layer_outputs = decoder_layer(
  755. hidden_states,
  756. attention_mask=causal_mask,
  757. position_ids=position_ids,
  758. past_key_value=past_key_values,
  759. output_attentions=output_attentions,
  760. use_cache=use_cache,
  761. cache_position=cache_position,
  762. position_embeddings=position_embeddings,
  763. )
  764. hidden_states = layer_outputs[0]
  765. if use_cache:
  766. next_decoder_cache = layer_outputs[2 if output_attentions else 1]
  767. if output_attentions:
  768. all_self_attns += (layer_outputs[1],)
  769. hidden_states = self.norm(hidden_states)
  770. # add hidden states from the last decoder layer
  771. if output_hidden_states:
  772. all_hidden_states += (hidden_states,)
  773. next_cache = next_decoder_cache if use_cache else None
  774. if return_legacy_cache:
  775. next_cache = next_cache.to_legacy_cache()
  776. if not return_dict:
  777. return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
  778. return BaseModelOutputWithPast(
  779. last_hidden_state=hidden_states,
  780. past_key_values=next_cache,
  781. hidden_states=all_hidden_states,
  782. attentions=all_self_attns,
  783. )
  784. def _update_causal_mask(
  785. self,
  786. attention_mask: torch.Tensor,
  787. input_tensor: torch.Tensor,
  788. cache_position: torch.Tensor,
  789. past_key_values: Cache,
  790. output_attentions: bool,
  791. ):
  792. if self.config._attn_implementation == "flash_attention_2":
  793. if attention_mask is not None and 0.0 in attention_mask:
  794. return attention_mask
  795. return None
  796. # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
  797. # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
  798. # to infer the attention mask.
  799. past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
  800. using_static_cache = isinstance(past_key_values, StaticCache)
  801. # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
  802. if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
  803. if AttentionMaskConverter._ignore_causal_mask_sdpa(
  804. attention_mask,
  805. inputs_embeds=input_tensor,
  806. past_key_values_length=past_seen_tokens,
  807. is_training=self.training,
  808. ):
  809. return None
  810. dtype, device = input_tensor.dtype, input_tensor.device
  811. sequence_length = input_tensor.shape[1]
  812. if using_static_cache:
  813. target_length = past_key_values.get_max_cache_shape()
  814. else:
  815. target_length = (
  816. attention_mask.shape[-1]
  817. if isinstance(attention_mask, torch.Tensor)
  818. else past_seen_tokens + sequence_length + 1
  819. )
  820. # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
  821. causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
  822. attention_mask,
  823. sequence_length=sequence_length,
  824. target_length=target_length,
  825. dtype=dtype,
  826. device=device,
  827. cache_position=cache_position,
  828. batch_size=input_tensor.shape[0],
  829. )
  830. if (
  831. self.config._attn_implementation == "sdpa"
  832. and attention_mask is not None
  833. and attention_mask.device.type == "cuda"
  834. and not output_attentions
  835. ):
  836. # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
  837. # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
  838. # Details: https://github.com/pytorch/pytorch/issues/110213
  839. min_dtype = torch.finfo(dtype).min
  840. causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
  841. return causal_mask
  842. @staticmethod
  843. def _prepare_4d_causal_attention_mask_with_cache_position(
  844. attention_mask: torch.Tensor,
  845. sequence_length: int,
  846. target_length: int,
  847. dtype: torch.dtype,
  848. device: torch.device,
  849. cache_position: torch.Tensor,
  850. batch_size: int,
  851. **kwargs,
  852. ):
  853. """
  854. Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
  855. `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
  856. Args:
  857. attention_mask (`torch.Tensor`):
  858. A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
  859. `(batch_size, 1, query_length, key_value_length)`.
  860. sequence_length (`int`):
  861. The sequence length being processed.
  862. target_length (`int`):
  863. The target length: when generating with static cache, the mask should be as long as the static cache,
  864. to account for the 0 padding, the part of the cache that is not filled yet.
  865. dtype (`torch.dtype`):
  866. The dtype to use for the 4D attention mask.
  867. device (`torch.device`):
  868. The device to plcae the 4D attention mask on.
  869. cache_position (`torch.Tensor`):
  870. Indices depicting the position of the input sequence tokens in the sequence.
  871. batch_size (`torch.Tensor`):
  872. Batch size.
  873. """
  874. if attention_mask is not None and attention_mask.dim() == 4:
  875. # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
  876. causal_mask = attention_mask
  877. else:
  878. min_dtype = torch.finfo(dtype).min
  879. causal_mask = torch.full(
  880. (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
  881. )
  882. if sequence_length != 1:
  883. causal_mask = torch.triu(causal_mask, diagonal=1)
  884. causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
  885. causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
  886. if attention_mask is not None:
  887. causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
  888. mask_length = attention_mask.shape[-1]
  889. padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
  890. padding_mask = padding_mask == 0
  891. causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
  892. padding_mask, min_dtype
  893. )
  894. return causal_mask
  895. # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM with Llama->Cohere
  896. class CohereForCausalLM(CoherePreTrainedModel, GenerationMixin):
  897. _tied_weights_keys = ["lm_head.weight"]
  898. # Ignore copy
  899. def __init__(self, config):
  900. super().__init__(config)
  901. self.model = CohereModel(config)
  902. self.vocab_size = config.vocab_size
  903. self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
  904. self.logit_scale = config.logit_scale
  905. self.tie_word_embeddings = config.tie_word_embeddings
  906. # Initialize weights and apply final processing
  907. self.post_init()
  908. def get_input_embeddings(self):
  909. return self.model.embed_tokens
  910. def set_input_embeddings(self, value):
  911. self.model.embed_tokens = value
  912. def get_output_embeddings(self):
  913. return self.lm_head
  914. def set_output_embeddings(self, new_embeddings):
  915. self.lm_head = new_embeddings
  916. def set_decoder(self, decoder):
  917. self.model = decoder
  918. def get_decoder(self):
  919. return self.model
  920. # Ignore copy
  921. @add_start_docstrings_to_model_forward(COHERE_INPUTS_DOCSTRING)
  922. @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
  923. def forward(
  924. self,
  925. input_ids: torch.LongTensor = None,
  926. attention_mask: Optional[torch.Tensor] = None,
  927. position_ids: Optional[torch.LongTensor] = None,
  928. past_key_values: Optional[List[torch.FloatTensor]] = None,
  929. inputs_embeds: Optional[torch.FloatTensor] = None,
  930. labels: Optional[torch.LongTensor] = None,
  931. use_cache: Optional[bool] = None,
  932. output_attentions: Optional[bool] = None,
  933. output_hidden_states: Optional[bool] = None,
  934. return_dict: Optional[bool] = None,
  935. cache_position: Optional[torch.LongTensor] = None,
  936. num_logits_to_keep: int = 0,
  937. **loss_kwargs,
  938. ) -> Union[Tuple, CausalLMOutputWithPast]:
  939. r"""
  940. Args:
  941. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  942. Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
  943. config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
  944. (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
  945. num_logits_to_keep (`int`, *optional*):
  946. Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all
  947. `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
  948. token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
  949. Returns:
  950. Example:
  951. ```python
  952. >> from transformers import AutoTokenizer, CohereForCausalLM
  953. >> model = CohereForCausalLM.from_pretrained("CohereForAI/c4ai-command-r-v01")
  954. >> tokenizer = AutoTokenizer.from_pretrained("CohereForAI/c4ai-command-r-v01")
  955. >> prompt = "Hey, are you conscious? Can you talk to me?"
  956. >> inputs = tokenizer(prompt, return_tensors="pt")
  957. >> # Generate
  958. >> generate_ids = model.generate(inputs.input_ids, max_length=30)
  959. >> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
  960. "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
  961. ```"""
  962. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  963. output_hidden_states = (
  964. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  965. )
  966. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  967. # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
  968. outputs = self.model(
  969. input_ids=input_ids,
  970. attention_mask=attention_mask,
  971. position_ids=position_ids,
  972. past_key_values=past_key_values,
  973. inputs_embeds=inputs_embeds,
  974. use_cache=use_cache,
  975. output_attentions=output_attentions,
  976. output_hidden_states=output_hidden_states,
  977. return_dict=return_dict,
  978. cache_position=cache_position,
  979. )
  980. hidden_states = outputs[0]
  981. # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
  982. logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :])
  983. logits = logits * self.logit_scale
  984. loss = None
  985. if labels is not None:
  986. loss = self.loss_function(logits, labels, self.vocab_size, **loss_kwargs)
  987. if not return_dict:
  988. output = (logits,) + outputs[1:]
  989. return (loss,) + output if loss is not None else output
  990. return CausalLMOutputWithPast(
  991. loss=loss,
  992. logits=logits,
  993. past_key_values=outputs.past_key_values,
  994. hidden_states=outputs.hidden_states,
  995. attentions=outputs.attentions,
  996. )