modeling_persimmon.py 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184
  1. # coding=utf-8
  2. # Copyright 2023 EleutherAI and the HuggingFace Inc. team. All rights reserved.
  3. #
  4. # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
  5. # and OPT implementations in this library. It has been modified from its
  6. # original forms to accommodate minor architectural differences compared
  7. # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
  8. #
  9. # Licensed under the Apache License, Version 2.0 (the "License");
  10. # you may not use this file except in compliance with the License.
  11. # You may obtain a copy of the License at
  12. #
  13. # http://www.apache.org/licenses/LICENSE-2.0
  14. #
  15. # Unless required by applicable law or agreed to in writing, software
  16. # distributed under the License is distributed on an "AS IS" BASIS,
  17. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18. # See the License for the specific language governing permissions and
  19. # limitations under the License.
  20. """PyTorch Persimmon model."""
  21. import math
  22. from typing import List, Optional, Tuple, Union
  23. import torch
  24. import torch.utils.checkpoint
  25. from torch import nn
  26. from torch.nn import CrossEntropyLoss
  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. SequenceClassifierOutputWithPast,
  35. TokenClassifierOutput,
  36. )
  37. from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS
  38. from ...modeling_utils import PreTrainedModel
  39. from ...utils import (
  40. add_code_sample_docstrings,
  41. add_start_docstrings,
  42. add_start_docstrings_to_model_forward,
  43. logging,
  44. replace_return_docstrings,
  45. )
  46. from .configuration_persimmon import PersimmonConfig
  47. logger = logging.get_logger(__name__)
  48. _CHECKPOINT_FOR_DOC = "adept/persimmon-8b-base"
  49. _CONFIG_FOR_DOC = "PersimmonConfig"
  50. # Copied from transformers.models.llama.modeling_llama.LlamaRotaryEmbedding with Llama->Persimmon
  51. class PersimmonRotaryEmbedding(nn.Module):
  52. def __init__(
  53. self,
  54. dim=None,
  55. max_position_embeddings=2048,
  56. base=10000,
  57. device=None,
  58. scaling_factor=1.0,
  59. rope_type="default",
  60. config: Optional[PersimmonConfig] = None,
  61. ):
  62. super().__init__()
  63. # TODO (joao): remove the `if` below, only used for BC
  64. self.rope_kwargs = {}
  65. if config is None:
  66. logger.warning_once(
  67. "`PersimmonRotaryEmbedding` can now be fully parameterized by passing the model config through the "
  68. "`config` argument. All other arguments will be removed in v4.46"
  69. )
  70. self.rope_kwargs = {
  71. "rope_type": rope_type,
  72. "factor": scaling_factor,
  73. "dim": dim,
  74. "base": base,
  75. "max_position_embeddings": max_position_embeddings,
  76. }
  77. self.rope_type = rope_type
  78. self.max_seq_len_cached = max_position_embeddings
  79. self.original_max_seq_len = max_position_embeddings
  80. else:
  81. # BC: "rope_type" was originally "type"
  82. if config.rope_scaling is not None:
  83. self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
  84. else:
  85. self.rope_type = "default"
  86. self.max_seq_len_cached = config.max_position_embeddings
  87. self.original_max_seq_len = config.max_position_embeddings
  88. self.config = config
  89. self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
  90. inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, **self.rope_kwargs)
  91. self.register_buffer("inv_freq", inv_freq, persistent=False)
  92. self.original_inv_freq = self.inv_freq
  93. def _dynamic_frequency_update(self, position_ids, device):
  94. """
  95. dynamic RoPE layers should recompute `inv_freq` in the following situations:
  96. 1 - growing beyond the cached sequence length (allow scaling)
  97. 2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
  98. """
  99. seq_len = torch.max(position_ids) + 1
  100. if seq_len > self.max_seq_len_cached: # growth
  101. inv_freq, self.attention_scaling = self.rope_init_fn(
  102. self.config, device, seq_len=seq_len, **self.rope_kwargs
  103. )
  104. self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
  105. self.max_seq_len_cached = seq_len
  106. if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
  107. self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
  108. self.max_seq_len_cached = self.original_max_seq_len
  109. @torch.no_grad()
  110. def forward(self, x, position_ids):
  111. if "dynamic" in self.rope_type:
  112. self._dynamic_frequency_update(position_ids, device=x.device)
  113. # Core RoPE block
  114. inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
  115. position_ids_expanded = position_ids[:, None, :].float()
  116. # Force float32 (see https://github.com/huggingface/transformers/pull/29285)
  117. device_type = x.device.type
  118. device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
  119. with torch.autocast(device_type=device_type, enabled=False):
  120. freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
  121. emb = torch.cat((freqs, freqs), dim=-1)
  122. cos = emb.cos()
  123. sin = emb.sin()
  124. # Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
  125. cos = cos * self.attention_scaling
  126. sin = sin * self.attention_scaling
  127. return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
  128. # Copied from transformers.models.llama.modeling_llama.LlamaLinearScalingRotaryEmbedding with Llama->Persimmon
  129. class PersimmonLinearScalingRotaryEmbedding(PersimmonRotaryEmbedding):
  130. """PersimmonRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
  131. def __init__(self, *args, **kwargs):
  132. logger.warning_once(
  133. "`PersimmonLinearScalingRotaryEmbedding` is deprecated an will be removed in v4.46. Please use "
  134. "`PersimmonRotaryEmbedding`, which now also does linear scaling (simply pass the model config to __init__)."
  135. )
  136. kwargs["rope_type"] = "linear"
  137. super().__init__(*args, **kwargs)
  138. # Copied from transformers.models.llama.modeling_llama.LlamaDynamicNTKScalingRotaryEmbedding with Llama->Persimmon
  139. class PersimmonDynamicNTKScalingRotaryEmbedding(PersimmonRotaryEmbedding):
  140. """PersimmonRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
  141. def __init__(self, *args, **kwargs):
  142. logger.warning_once(
  143. "`PersimmonDynamicNTKScalingRotaryEmbedding` is deprecated an will be removed in v4.46. Please use "
  144. "`PersimmonRotaryEmbedding`, which now also does dynamic ntk scaling (simply pass the model config to "
  145. "__init__)."
  146. )
  147. kwargs["rope_type"] = "dynamic"
  148. super().__init__(*args, **kwargs)
  149. # Copied from transformers.models.llama.modeling_llama.rotate_half
  150. def rotate_half(x):
  151. """Rotates half the hidden dims of the input."""
  152. x1 = x[..., : x.shape[-1] // 2]
  153. x2 = x[..., x.shape[-1] // 2 :]
  154. return torch.cat((-x2, x1), dim=-1)
  155. # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
  156. def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
  157. """Applies Rotary Position Embedding to the query and key tensors.
  158. Args:
  159. q (`torch.Tensor`): The query tensor.
  160. k (`torch.Tensor`): The key tensor.
  161. cos (`torch.Tensor`): The cosine part of the rotary embedding.
  162. sin (`torch.Tensor`): The sine part of the rotary embedding.
  163. position_ids (`torch.Tensor`, *optional*):
  164. Deprecated and unused.
  165. unsqueeze_dim (`int`, *optional*, defaults to 1):
  166. The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
  167. sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
  168. that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
  169. k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
  170. cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
  171. the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
  172. Returns:
  173. `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
  174. """
  175. cos = cos.unsqueeze(unsqueeze_dim)
  176. sin = sin.unsqueeze(unsqueeze_dim)
  177. q_embed = (q * cos) + (rotate_half(q) * sin)
  178. k_embed = (k * cos) + (rotate_half(k) * sin)
  179. return q_embed, k_embed
  180. # Copied from transformers.models.gpt_neox.modeling_gpt_neox.GPTNeoXMLP with GPTNeoX->Persimmon
  181. class PersimmonMLP(nn.Module):
  182. def __init__(self, config):
  183. super().__init__()
  184. self.dense_h_to_4h = nn.Linear(config.hidden_size, config.intermediate_size)
  185. self.dense_4h_to_h = nn.Linear(config.intermediate_size, config.hidden_size)
  186. self.act = ACT2FN[config.hidden_act]
  187. def forward(self, hidden_states):
  188. hidden_states = self.dense_h_to_4h(hidden_states)
  189. hidden_states = self.act(hidden_states)
  190. hidden_states = self.dense_4h_to_h(hidden_states)
  191. return hidden_states
  192. class PersimmonAttention(nn.Module):
  193. """Multi-headed attention from 'Attention Is All You Need' paper"""
  194. def __init__(self, config: PersimmonConfig, layer_idx: Optional[int] = None):
  195. super().__init__()
  196. self.config = config
  197. self.layer_idx = layer_idx
  198. if layer_idx is None:
  199. logger.warning_once(
  200. f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
  201. "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
  202. "when creating this class."
  203. )
  204. self.hidden_size = config.hidden_size
  205. self.num_heads = config.num_attention_heads
  206. self.head_dim = self.hidden_size // self.num_heads
  207. self.rope_theta = config.rope_theta
  208. self.rotary_ndims = int(self.head_dim * config.partial_rotary_factor)
  209. self.is_causal = True
  210. if (self.head_dim * self.num_heads) != self.hidden_size:
  211. raise ValueError(
  212. f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
  213. f" and `num_heads`: {self.num_heads})."
  214. )
  215. self.query_key_value = nn.Linear(self.hidden_size, 3 * self.hidden_size, bias=True)
  216. self.dense = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=True)
  217. self.qk_layernorm = config.qk_layernorm
  218. if self.qk_layernorm:
  219. self.q_layernorm = nn.LayerNorm(
  220. config.hidden_size // self.num_heads, eps=config.layer_norm_eps, elementwise_affine=True
  221. )
  222. self.k_layernorm = nn.LayerNorm(
  223. config.hidden_size // self.num_heads, eps=config.layer_norm_eps, elementwise_affine=True
  224. )
  225. self.attention_dropout = nn.Dropout(config.attention_dropout)
  226. self.rotary_emb = PersimmonRotaryEmbedding(config=self.config)
  227. def _split_heads(self, fused_qkv: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
  228. """
  229. Split the last dimension into (num_heads, head_dim) without making any copies, results share same memory
  230. storage as `fused_qkv`
  231. Args:
  232. fused_qkv (`torch.tensor`): [batch_size, seq_length, num_heads * 3 * head_dim]
  233. Returns:
  234. query: [batch_size, seq_length, num_heads, head_dim] key: [batch_size, seq_length, num_heads, head_dim]
  235. value: [batch_size, seq_length, num_heads, head_dim]
  236. """
  237. batch_size, seq_length, three_times_hidden_size = fused_qkv.shape
  238. fused_qkv = fused_qkv.view(batch_size, seq_length, self.num_heads, 3, self.head_dim)
  239. return fused_qkv[..., 0, :], fused_qkv[..., 1, :], fused_qkv[..., 2, :]
  240. def forward(
  241. self,
  242. hidden_states: torch.Tensor,
  243. attention_mask: Optional[torch.Tensor] = None,
  244. position_ids: Optional[torch.LongTensor] = None,
  245. past_key_value: Optional[Cache] = None,
  246. output_attentions: bool = False,
  247. use_cache: bool = False,
  248. cache_position: Optional[torch.LongTensor] = None,
  249. position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
  250. ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
  251. bsz, q_len, _ = hidden_states.size()
  252. # [batch_size, seq_length, 3 x hidden_size]
  253. fused_qkv = self.query_key_value(hidden_states)
  254. # 3 x [batch_size, seq_length, num_heads, head_dim]
  255. (query_states, key_states, value_states) = self._split_heads(fused_qkv)
  256. if self.qk_layernorm:
  257. query_states = self.q_layernorm(query_states)
  258. key_states = self.k_layernorm(key_states)
  259. # [batch_size, num_heads, seq_length, head_dim] -> [batch_size, seq_length, num_heads, head_dim]
  260. query_states = query_states.transpose(1, 2)
  261. value_states = value_states.transpose(1, 2)
  262. key_states = key_states.transpose(1, 2)
  263. if position_embeddings is None:
  264. logger.warning_once(
  265. "The attention layers in this model are transitioning from computing the RoPE embeddings internally "
  266. "through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
  267. "`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.46 `position_ids` will be "
  268. "removed and `position_embeddings` will be mandatory."
  269. )
  270. cos, sin = self.rotary_emb(value_states, position_ids)
  271. else:
  272. cos, sin = position_embeddings
  273. # Partial rotary embedding
  274. query_rot, query_pass = (
  275. query_states[..., : self.rotary_ndims],
  276. query_states[..., self.rotary_ndims :],
  277. )
  278. key_rot, key_pass = (
  279. key_states[..., : self.rotary_ndims],
  280. key_states[..., self.rotary_ndims :],
  281. )
  282. # [batch_size, seq_length, num_heads, head_dim // config.partial_rotary_factor]
  283. query_rot, key_rot = apply_rotary_pos_emb(query_rot, key_rot, cos, sin)
  284. # [batch_size, seq_length, num_heads, head_dim]
  285. query_states = torch.cat((query_rot, query_pass), dim=-1)
  286. key_states = torch.cat((key_rot, key_pass), dim=-1)
  287. if past_key_value is not None:
  288. # Specific to RoPE models with partial rotation
  289. cache_kwargs = {
  290. "sin": sin,
  291. "cos": cos,
  292. "partial_rotation_size": self.rotary_ndims,
  293. "cache_position": cache_position,
  294. }
  295. key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
  296. attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
  297. if attention_mask is not None: # no matter the length, we just slice it
  298. causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
  299. attn_weights = attn_weights + causal_mask
  300. # upcast attention to fp32
  301. attn_weights = nn.functional.softmax(attn_weights, dtype=torch.float32, dim=-1).to(query_states.dtype)
  302. attn_weights = self.attention_dropout(attn_weights)
  303. attn_output = torch.matmul(attn_weights, value_states)
  304. if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
  305. raise ValueError(
  306. f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
  307. f" {attn_output.size()}"
  308. )
  309. attn_output = attn_output.transpose(1, 2).contiguous()
  310. attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
  311. attn_output = self.dense(attn_output)
  312. if not output_attentions:
  313. attn_weights = None
  314. return attn_output, attn_weights, past_key_value
  315. class PersimmonDecoderLayer(nn.Module):
  316. def __init__(self, config: PersimmonConfig, layer_idx: int):
  317. super().__init__()
  318. self.hidden_size = config.hidden_size
  319. self.self_attn = PersimmonAttention(config=config, layer_idx=layer_idx)
  320. self.mlp = PersimmonMLP(config)
  321. self.input_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  322. self.post_attention_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  323. self.dropout = nn.Dropout(config.hidden_dropout)
  324. def forward(
  325. self,
  326. hidden_states: torch.Tensor,
  327. attention_mask: Optional[torch.Tensor] = None,
  328. position_ids: Optional[torch.LongTensor] = None,
  329. past_key_value: Optional[Tuple[torch.Tensor]] = None,
  330. output_attentions: Optional[bool] = False,
  331. use_cache: Optional[bool] = False,
  332. cache_position: Optional[torch.LongTensor] = None,
  333. position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
  334. ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
  335. """
  336. Args:
  337. hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
  338. attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
  339. `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
  340. position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
  341. Indices of positions of each input sequence tokens in the position embeddings. Selected in the range
  342. `[0, config.n_positions - 1]`.
  343. [What are position IDs?](../glossary#position-ids)
  344. past_key_value (`Tuple(torch.FloatTensor)`, *optional*):
  345. cached past key and value projection states
  346. output_attentions (`bool`, *optional*):
  347. Whether or not to return the attentions tensors of all attention layers. See `attentions` under
  348. returned tensors for more detail.
  349. use_cache (`bool`, *optional*):
  350. If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
  351. (see `past_key_values`).
  352. cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
  353. Indices depicting the position of the input sequence tokens in the sequence
  354. position_embeddings (`Tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
  355. Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
  356. with `head_dim` being the embedding dimension of each attention head.
  357. """
  358. residual = hidden_states
  359. hidden_states = self.input_layernorm(hidden_states)
  360. # Self Attention
  361. hidden_states, self_attn_weights, present_key_value = self.self_attn(
  362. hidden_states=hidden_states,
  363. attention_mask=attention_mask,
  364. position_ids=position_ids,
  365. past_key_value=past_key_value,
  366. output_attentions=output_attentions,
  367. use_cache=use_cache,
  368. cache_position=cache_position,
  369. position_embeddings=position_embeddings,
  370. )
  371. hidden_states = residual + hidden_states
  372. # Fully Connected
  373. residual = hidden_states
  374. hidden_states = self.post_attention_layernorm(hidden_states)
  375. hidden_states = self.mlp(hidden_states)
  376. hidden_states = self.dropout(hidden_states)
  377. hidden_states = hidden_states + residual
  378. outputs = (hidden_states,)
  379. if output_attentions:
  380. outputs += (self_attn_weights,)
  381. if use_cache:
  382. outputs += (present_key_value,)
  383. return outputs
  384. PERSIMMON_START_DOCSTRING = r"""
  385. This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
  386. library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
  387. etc.)
  388. This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
  389. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
  390. and behavior.
  391. Parameters:
  392. config ([`PersimmonConfig`]):
  393. Model configuration class with all the parameters of the model. Initializing with a config file does not
  394. load the weights associated with the model, only the configuration. Check out the
  395. [`~PreTrainedModel.from_pretrained`] method to load the model weights.
  396. """
  397. @add_start_docstrings(
  398. "The bare Persimmon Model outputting raw hidden-states without any specific head on top.",
  399. PERSIMMON_START_DOCSTRING,
  400. )
  401. class PersimmonPreTrainedModel(PreTrainedModel):
  402. config_class = PersimmonConfig
  403. base_model_prefix = "model"
  404. supports_gradient_checkpointing = True
  405. _no_split_modules = ["PersimmonDecoderLayer"]
  406. _skip_keys_device_placement = "past_key_values"
  407. _supports_cache_class = True
  408. _supports_quantized_cache = True
  409. _supports_static_cache = True
  410. def _init_weights(self, module):
  411. std = self.config.initializer_range
  412. if isinstance(module, nn.Linear):
  413. module.weight.data.normal_(mean=0.0, std=std)
  414. if module.bias is not None:
  415. module.bias.data.zero_()
  416. elif isinstance(module, nn.Embedding):
  417. module.weight.data.normal_(mean=0.0, std=std)
  418. if module.padding_idx is not None:
  419. module.weight.data[module.padding_idx].zero_()
  420. PERSIMMON_INPUTS_DOCSTRING = r"""
  421. Args:
  422. input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
  423. Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
  424. it.
  425. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
  426. [`PreTrainedTokenizer.__call__`] for details.
  427. [What are input IDs?](../glossary#input-ids)
  428. attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
  429. Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
  430. - 1 for tokens that are **not masked**,
  431. - 0 for tokens that are **masked**.
  432. [What are attention masks?](../glossary#attention-mask)
  433. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
  434. [`PreTrainedTokenizer.__call__`] for details.
  435. If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
  436. `past_key_values`).
  437. If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
  438. and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
  439. information on the default strategy.
  440. - 1 indicates the head is **not masked**,
  441. - 0 indicates the head is **masked**.
  442. position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  443. Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
  444. config.n_positions - 1]`.
  445. [What are position IDs?](../glossary#position-ids)
  446. past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
  447. Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
  448. blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
  449. returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
  450. Two formats are allowed:
  451. - a [`~cache_utils.Cache`] instance, see our
  452. [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);
  453. - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
  454. shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
  455. cache format.
  456. The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
  457. legacy cache format will be returned.
  458. If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
  459. have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
  460. of shape `(batch_size, sequence_length)`.
  461. inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
  462. Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
  463. is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
  464. model's internal embedding lookup matrix.
  465. use_cache (`bool`, *optional*):
  466. If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
  467. `past_key_values`).
  468. output_attentions (`bool`, *optional*):
  469. Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
  470. tensors for more detail.
  471. output_hidden_states (`bool`, *optional*):
  472. Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
  473. more detail.
  474. return_dict (`bool`, *optional*):
  475. Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
  476. cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
  477. Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
  478. this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
  479. the complete sequence length.
  480. """
  481. @add_start_docstrings(
  482. "The bare Persimmon Model outputting raw hidden-states without any specific head on top.",
  483. PERSIMMON_START_DOCSTRING,
  484. )
  485. class PersimmonModel(PersimmonPreTrainedModel):
  486. """
  487. Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`PersimmonDecoderLayer`]
  488. Args:
  489. config: PersimmonConfig
  490. """
  491. def __init__(self, config: PersimmonConfig):
  492. super().__init__(config)
  493. self.padding_idx = config.pad_token_id
  494. self.vocab_size = config.vocab_size
  495. self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
  496. self.layers = nn.ModuleList(
  497. [PersimmonDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
  498. )
  499. self.final_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  500. self.rotary_emb = PersimmonRotaryEmbedding(config=config)
  501. self.gradient_checkpointing = False
  502. # Initialize weights and apply final processing
  503. self.post_init()
  504. def get_input_embeddings(self):
  505. return self.embed_tokens
  506. def set_input_embeddings(self, value):
  507. self.embed_tokens = value
  508. @add_start_docstrings_to_model_forward(PERSIMMON_INPUTS_DOCSTRING)
  509. def forward(
  510. self,
  511. input_ids: torch.LongTensor = None,
  512. attention_mask: Optional[torch.Tensor] = None,
  513. position_ids: Optional[torch.LongTensor] = None,
  514. past_key_values: Optional[List[torch.FloatTensor]] = None,
  515. inputs_embeds: Optional[torch.FloatTensor] = None,
  516. use_cache: Optional[bool] = None,
  517. output_attentions: Optional[bool] = None,
  518. output_hidden_states: Optional[bool] = None,
  519. return_dict: Optional[bool] = None,
  520. cache_position: Optional[torch.LongTensor] = None,
  521. ) -> Union[Tuple, BaseModelOutputWithPast]:
  522. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  523. output_hidden_states = (
  524. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  525. )
  526. use_cache = use_cache if use_cache is not None else self.config.use_cache
  527. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  528. if (input_ids is None) ^ (inputs_embeds is not None):
  529. raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
  530. if self.gradient_checkpointing and self.training:
  531. if use_cache:
  532. logger.warning_once(
  533. "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
  534. )
  535. use_cache = False
  536. # kept for BC (non `Cache` `past_key_values` inputs)
  537. return_legacy_cache = False
  538. if use_cache and not isinstance(past_key_values, Cache):
  539. return_legacy_cache = True
  540. if past_key_values is None:
  541. past_key_values = DynamicCache()
  542. else:
  543. past_key_values = DynamicCache.from_legacy_cache(past_key_values)
  544. logger.warning_once(
  545. "We detected that you are passing `past_key_values` as a tuple of tuples. This is deprecated and "
  546. "will be removed in v4.47. Please convert your cache or use an appropriate `Cache` class "
  547. "(https://huggingface.co/docs/transformers/kv_cache#legacy-cache-format)"
  548. )
  549. if inputs_embeds is None:
  550. inputs_embeds = self.embed_tokens(input_ids)
  551. if cache_position is None:
  552. past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
  553. cache_position = torch.arange(
  554. past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
  555. )
  556. if position_ids is None:
  557. position_ids = cache_position.unsqueeze(0)
  558. causal_mask = self._update_causal_mask(
  559. attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
  560. )
  561. hidden_states = inputs_embeds
  562. # create position embeddings to be shared across the decoder layers
  563. position_embeddings = self.rotary_emb(hidden_states, position_ids)
  564. # decoder layers
  565. all_hidden_states = () if output_hidden_states else None
  566. all_self_attns = () if output_attentions else None
  567. next_decoder_cache = None
  568. for decoder_layer in self.layers:
  569. if output_hidden_states:
  570. all_hidden_states += (hidden_states,)
  571. if self.gradient_checkpointing and self.training:
  572. layer_outputs = self._gradient_checkpointing_func(
  573. decoder_layer.__call__,
  574. hidden_states,
  575. causal_mask,
  576. position_ids,
  577. past_key_values,
  578. output_attentions,
  579. use_cache,
  580. cache_position,
  581. position_embeddings,
  582. )
  583. else:
  584. layer_outputs = decoder_layer(
  585. hidden_states,
  586. attention_mask=causal_mask,
  587. position_ids=position_ids,
  588. past_key_value=past_key_values,
  589. output_attentions=output_attentions,
  590. use_cache=use_cache,
  591. cache_position=cache_position,
  592. position_embeddings=position_embeddings,
  593. )
  594. hidden_states = layer_outputs[0]
  595. if use_cache:
  596. next_decoder_cache = layer_outputs[2 if output_attentions else 1]
  597. if output_attentions:
  598. all_self_attns += (layer_outputs[1],)
  599. hidden_states = self.final_layernorm(hidden_states)
  600. # add hidden states from the last decoder layer
  601. if output_hidden_states:
  602. all_hidden_states += (hidden_states,)
  603. next_cache = next_decoder_cache if use_cache else None
  604. if return_legacy_cache:
  605. next_cache = next_cache.to_legacy_cache()
  606. if not return_dict:
  607. return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
  608. return BaseModelOutputWithPast(
  609. last_hidden_state=hidden_states,
  610. past_key_values=next_cache,
  611. hidden_states=all_hidden_states,
  612. attentions=all_self_attns,
  613. )
  614. # Copied from transformers.models.llama.modeling_llama.LlamaModel._update_causal_mask
  615. def _update_causal_mask(
  616. self,
  617. attention_mask: torch.Tensor,
  618. input_tensor: torch.Tensor,
  619. cache_position: torch.Tensor,
  620. past_key_values: Cache,
  621. output_attentions: bool,
  622. ):
  623. if self.config._attn_implementation == "flash_attention_2":
  624. if attention_mask is not None and 0.0 in attention_mask:
  625. return attention_mask
  626. return None
  627. # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
  628. # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
  629. # to infer the attention mask.
  630. past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
  631. using_static_cache = isinstance(past_key_values, StaticCache)
  632. # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
  633. if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
  634. if AttentionMaskConverter._ignore_causal_mask_sdpa(
  635. attention_mask,
  636. inputs_embeds=input_tensor,
  637. past_key_values_length=past_seen_tokens,
  638. is_training=self.training,
  639. ):
  640. return None
  641. dtype, device = input_tensor.dtype, input_tensor.device
  642. sequence_length = input_tensor.shape[1]
  643. if using_static_cache:
  644. target_length = past_key_values.get_max_cache_shape()
  645. else:
  646. target_length = (
  647. attention_mask.shape[-1]
  648. if isinstance(attention_mask, torch.Tensor)
  649. else past_seen_tokens + sequence_length + 1
  650. )
  651. # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
  652. causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
  653. attention_mask,
  654. sequence_length=sequence_length,
  655. target_length=target_length,
  656. dtype=dtype,
  657. device=device,
  658. cache_position=cache_position,
  659. batch_size=input_tensor.shape[0],
  660. )
  661. if (
  662. self.config._attn_implementation == "sdpa"
  663. and attention_mask is not None
  664. and attention_mask.device.type == "cuda"
  665. and not output_attentions
  666. ):
  667. # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
  668. # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
  669. # Details: https://github.com/pytorch/pytorch/issues/110213
  670. min_dtype = torch.finfo(dtype).min
  671. causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
  672. return causal_mask
  673. @staticmethod
  674. # Copied from transformers.models.llama.modeling_llama.LlamaModel._prepare_4d_causal_attention_mask_with_cache_position
  675. def _prepare_4d_causal_attention_mask_with_cache_position(
  676. attention_mask: torch.Tensor,
  677. sequence_length: int,
  678. target_length: int,
  679. dtype: torch.dtype,
  680. device: torch.device,
  681. cache_position: torch.Tensor,
  682. batch_size: int,
  683. **kwargs,
  684. ):
  685. """
  686. Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
  687. `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
  688. Args:
  689. attention_mask (`torch.Tensor`):
  690. A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
  691. `(batch_size, 1, query_length, key_value_length)`.
  692. sequence_length (`int`):
  693. The sequence length being processed.
  694. target_length (`int`):
  695. The target length: when generating with static cache, the mask should be as long as the static cache,
  696. to account for the 0 padding, the part of the cache that is not filled yet.
  697. dtype (`torch.dtype`):
  698. The dtype to use for the 4D attention mask.
  699. device (`torch.device`):
  700. The device to plcae the 4D attention mask on.
  701. cache_position (`torch.Tensor`):
  702. Indices depicting the position of the input sequence tokens in the sequence.
  703. batch_size (`torch.Tensor`):
  704. Batch size.
  705. """
  706. if attention_mask is not None and attention_mask.dim() == 4:
  707. # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
  708. causal_mask = attention_mask
  709. else:
  710. min_dtype = torch.finfo(dtype).min
  711. causal_mask = torch.full(
  712. (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
  713. )
  714. if sequence_length != 1:
  715. causal_mask = torch.triu(causal_mask, diagonal=1)
  716. causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
  717. causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
  718. if attention_mask is not None:
  719. causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
  720. mask_length = attention_mask.shape[-1]
  721. padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
  722. padding_mask = padding_mask == 0
  723. causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
  724. padding_mask, min_dtype
  725. )
  726. return causal_mask
  727. class PersimmonForCausalLM(PersimmonPreTrainedModel, GenerationMixin):
  728. _tied_weights_keys = ["lm_head.weight"]
  729. # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.__init__ with LLAMA->PERSIMMON,Llama->Persimmon
  730. def __init__(self, config):
  731. super().__init__(config)
  732. self.model = PersimmonModel(config)
  733. self.vocab_size = config.vocab_size
  734. self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
  735. # Initialize weights and apply final processing
  736. self.post_init()
  737. # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_input_embeddings
  738. def get_input_embeddings(self):
  739. return self.model.embed_tokens
  740. # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_input_embeddings
  741. def set_input_embeddings(self, value):
  742. self.model.embed_tokens = value
  743. # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_output_embeddings
  744. def get_output_embeddings(self):
  745. return self.lm_head
  746. # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_output_embeddings
  747. def set_output_embeddings(self, new_embeddings):
  748. self.lm_head = new_embeddings
  749. # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_decoder
  750. def set_decoder(self, decoder):
  751. self.model = decoder
  752. # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_decoder
  753. def get_decoder(self):
  754. return self.model
  755. @add_start_docstrings_to_model_forward(PERSIMMON_INPUTS_DOCSTRING)
  756. @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
  757. def forward(
  758. self,
  759. input_ids: torch.LongTensor = None,
  760. attention_mask: Optional[torch.Tensor] = None,
  761. position_ids: Optional[torch.LongTensor] = None,
  762. past_key_values: Optional[List[torch.FloatTensor]] = None,
  763. inputs_embeds: Optional[torch.FloatTensor] = None,
  764. labels: Optional[torch.LongTensor] = None,
  765. use_cache: Optional[bool] = None,
  766. output_attentions: Optional[bool] = None,
  767. output_hidden_states: Optional[bool] = None,
  768. return_dict: Optional[bool] = None,
  769. cache_position: Optional[torch.LongTensor] = None,
  770. num_logits_to_keep: int = 0,
  771. ) -> Union[Tuple, CausalLMOutputWithPast]:
  772. r"""
  773. Args:
  774. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  775. Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
  776. config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
  777. (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
  778. num_logits_to_keep (`int`, *optional*):
  779. Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all
  780. `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
  781. token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
  782. Returns:
  783. Example:
  784. ```python
  785. >>> from transformers import AutoTokenizer, PersimmonForCausalLM
  786. >>> model = PersimmonForCausalLM.from_pretrained("adept/persimmon-8b-base")
  787. >>> tokenizer = AutoTokenizer.from_pretrained("adept/persimmon-8b-base")
  788. >>> prompt = "human: Hey, what should I eat for dinner?"
  789. >>> inputs = tokenizer(prompt, return_tensors="pt")
  790. >>> # Generate
  791. >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
  792. >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
  793. 'human: Hey, what should I eat for dinner?\n\ncat: 🐱\n\nhuman: 😐\n\n'
  794. ```"""
  795. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  796. output_hidden_states = (
  797. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  798. )
  799. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  800. # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
  801. outputs = self.model(
  802. input_ids=input_ids,
  803. attention_mask=attention_mask,
  804. position_ids=position_ids,
  805. past_key_values=past_key_values,
  806. inputs_embeds=inputs_embeds,
  807. use_cache=use_cache,
  808. output_attentions=output_attentions,
  809. output_hidden_states=output_hidden_states,
  810. return_dict=return_dict,
  811. cache_position=cache_position,
  812. )
  813. hidden_states = outputs[0]
  814. # No upscaling to float was ever done for Persimmon
  815. logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :])
  816. loss = None
  817. if labels is not None:
  818. # Shift so that tokens < n predict n
  819. shift_logits = logits[..., :-1, :].contiguous()
  820. shift_labels = labels[..., 1:].contiguous()
  821. # Flatten the tokens
  822. loss_fct = CrossEntropyLoss()
  823. shift_logits = shift_logits.view(-1, self.config.vocab_size)
  824. shift_labels = shift_labels.view(-1)
  825. # Enable model parallelism
  826. shift_labels = shift_labels.to(shift_logits.device)
  827. loss = loss_fct(shift_logits, shift_labels)
  828. if not return_dict:
  829. output = (logits,) + outputs[1:]
  830. return (loss,) + output if loss is not None else output
  831. return CausalLMOutputWithPast(
  832. loss=loss,
  833. logits=logits,
  834. past_key_values=outputs.past_key_values,
  835. hidden_states=outputs.hidden_states,
  836. attentions=outputs.attentions,
  837. )
  838. @add_start_docstrings(
  839. """
  840. The Persimmon transformer with a sequence classification head on top (linear layer).
  841. [`PersimmonForSequenceClassification`] uses the last token in order to do the classification, as other causal
  842. models (e.g. GPT-2) do.
  843. Since it does classification on the last token, it requires to know the position of the last token. If a
  844. `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
  845. no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
  846. padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
  847. each row of the batch).
  848. """,
  849. PERSIMMON_START_DOCSTRING,
  850. )
  851. # Copied from transformers.models.llama.modeling_llama.LlamaForSequenceClassification with LLAMA->PERSIMMON,Llama->Persimmon
  852. class PersimmonForSequenceClassification(PersimmonPreTrainedModel):
  853. def __init__(self, config):
  854. super().__init__(config)
  855. self.num_labels = config.num_labels
  856. self.model = PersimmonModel(config)
  857. self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
  858. # Initialize weights and apply final processing
  859. self.post_init()
  860. def get_input_embeddings(self):
  861. return self.model.embed_tokens
  862. def set_input_embeddings(self, value):
  863. self.model.embed_tokens = value
  864. @add_start_docstrings_to_model_forward(PERSIMMON_INPUTS_DOCSTRING)
  865. def forward(
  866. self,
  867. input_ids: Optional[torch.LongTensor] = None,
  868. attention_mask: Optional[torch.Tensor] = None,
  869. position_ids: Optional[torch.LongTensor] = None,
  870. past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
  871. inputs_embeds: Optional[torch.FloatTensor] = None,
  872. labels: Optional[torch.LongTensor] = None,
  873. use_cache: Optional[bool] = None,
  874. output_attentions: Optional[bool] = None,
  875. output_hidden_states: Optional[bool] = None,
  876. return_dict: Optional[bool] = None,
  877. ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
  878. r"""
  879. labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  880. Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
  881. config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
  882. `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
  883. """
  884. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  885. transformer_outputs = self.model(
  886. input_ids,
  887. attention_mask=attention_mask,
  888. position_ids=position_ids,
  889. past_key_values=past_key_values,
  890. inputs_embeds=inputs_embeds,
  891. use_cache=use_cache,
  892. output_attentions=output_attentions,
  893. output_hidden_states=output_hidden_states,
  894. return_dict=return_dict,
  895. )
  896. hidden_states = transformer_outputs[0]
  897. logits = self.score(hidden_states)
  898. if input_ids is not None:
  899. batch_size = input_ids.shape[0]
  900. else:
  901. batch_size = inputs_embeds.shape[0]
  902. if self.config.pad_token_id is None and batch_size != 1:
  903. raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
  904. if self.config.pad_token_id is None:
  905. sequence_lengths = -1
  906. else:
  907. if input_ids is not None:
  908. # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
  909. sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
  910. sequence_lengths = sequence_lengths % input_ids.shape[-1]
  911. sequence_lengths = sequence_lengths.to(logits.device)
  912. else:
  913. sequence_lengths = -1
  914. pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
  915. loss = None
  916. if labels is not None:
  917. loss = self.loss_function(logits=logits, labels=labels, pooled_logits=pooled_logits, config=self.config)
  918. if not return_dict:
  919. output = (pooled_logits,) + transformer_outputs[1:]
  920. return ((loss,) + output) if loss is not None else output
  921. return SequenceClassifierOutputWithPast(
  922. loss=loss,
  923. logits=pooled_logits,
  924. past_key_values=transformer_outputs.past_key_values,
  925. hidden_states=transformer_outputs.hidden_states,
  926. attentions=transformer_outputs.attentions,
  927. )
  928. @add_start_docstrings(
  929. """
  930. The Persimmon Model transformer with a token classification head on top (a linear layer on top of the hidden-states
  931. output) e.g. for Named-Entity-Recognition (NER) tasks.
  932. """,
  933. PERSIMMON_START_DOCSTRING,
  934. )
  935. # Copied from transformers.models.llama.modeling_llama.LlamaForTokenClassification with Llama->Persimmon, LLAMA->PERSIMMON
  936. class PersimmonForTokenClassification(PersimmonPreTrainedModel):
  937. def __init__(self, config):
  938. super().__init__(config)
  939. self.num_labels = config.num_labels
  940. self.model = PersimmonModel(config)
  941. if getattr(config, "classifier_dropout", None) is not None:
  942. classifier_dropout = config.classifier_dropout
  943. elif getattr(config, "hidden_dropout", None) is not None:
  944. classifier_dropout = config.hidden_dropout
  945. else:
  946. classifier_dropout = 0.1
  947. self.dropout = nn.Dropout(classifier_dropout)
  948. self.score = nn.Linear(config.hidden_size, config.num_labels)
  949. # Initialize weights and apply final processing
  950. self.post_init()
  951. def get_input_embeddings(self):
  952. return self.model.embed_tokens
  953. def set_input_embeddings(self, value):
  954. self.model.embed_tokens = value
  955. @add_start_docstrings_to_model_forward(PERSIMMON_INPUTS_DOCSTRING)
  956. @add_code_sample_docstrings(
  957. checkpoint=_CHECKPOINT_FOR_DOC,
  958. output_type=TokenClassifierOutput,
  959. config_class=_CONFIG_FOR_DOC,
  960. )
  961. def forward(
  962. self,
  963. input_ids: Optional[torch.LongTensor] = None,
  964. attention_mask: Optional[torch.Tensor] = None,
  965. position_ids: Optional[torch.LongTensor] = None,
  966. past_key_values: Optional[List[torch.FloatTensor]] = None,
  967. inputs_embeds: Optional[torch.FloatTensor] = None,
  968. labels: Optional[torch.LongTensor] = None,
  969. use_cache: Optional[bool] = None,
  970. output_attentions: Optional[bool] = None,
  971. output_hidden_states: Optional[bool] = None,
  972. return_dict: Optional[bool] = None,
  973. ) -> Union[Tuple, TokenClassifierOutput]:
  974. r"""
  975. labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  976. Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
  977. config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
  978. `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
  979. """
  980. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  981. outputs = self.model(
  982. input_ids,
  983. attention_mask=attention_mask,
  984. position_ids=position_ids,
  985. past_key_values=past_key_values,
  986. inputs_embeds=inputs_embeds,
  987. use_cache=use_cache,
  988. output_attentions=output_attentions,
  989. output_hidden_states=output_hidden_states,
  990. return_dict=return_dict,
  991. )
  992. sequence_output = outputs[0]
  993. sequence_output = self.dropout(sequence_output)
  994. logits = self.score(sequence_output)
  995. loss = None
  996. if labels is not None:
  997. loss = self.loss_function(logits, labels, self.config)
  998. if not return_dict:
  999. output = (logits,) + outputs[2:]
  1000. return ((loss,) + output) if loss is not None else output
  1001. return TokenClassifierOutput(
  1002. loss=loss,
  1003. logits=logits,
  1004. hidden_states=outputs.hidden_states,
  1005. attentions=outputs.attentions,
  1006. )