modeling_ctrl.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841
  1. # coding=utf-8
  2. # Copyright 2018 Salesforce and HuggingFace Inc. team.
  3. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. """PyTorch CTRL model."""
  17. from typing import Optional, Tuple, Union
  18. import numpy as np
  19. import torch
  20. from torch import nn
  21. from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
  22. from ...generation import GenerationMixin
  23. from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutput
  24. from ...modeling_utils import PreTrainedModel
  25. from ...pytorch_utils import Conv1D, find_pruneable_heads_and_indices, prune_linear_layer
  26. from ...utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings
  27. from .configuration_ctrl import CTRLConfig
  28. logger = logging.get_logger(__name__)
  29. _CONFIG_FOR_DOC = "CTRLConfig"
  30. def angle_defn(pos, i, d_model_size):
  31. angle_rates = 1 / torch.pow(10000, (2 * (i // 2)) / d_model_size)
  32. return pos * angle_rates
  33. def positional_encoding(position, d_model_size, dtype):
  34. # create the sinusoidal pattern for the positional encoding
  35. angle_rads = angle_defn(
  36. torch.arange(position, dtype=torch.int64).to(dtype).unsqueeze(1),
  37. torch.arange(d_model_size, dtype=torch.int64).to(dtype).unsqueeze(0),
  38. d_model_size,
  39. )
  40. sines = torch.sin(angle_rads[:, 0::2])
  41. cosines = torch.cos(angle_rads[:, 1::2])
  42. pos_encoding = torch.cat([sines, cosines], dim=-1)
  43. return pos_encoding
  44. def scaled_dot_product_attention(q, k, v, mask, attention_mask=None, head_mask=None):
  45. # calculate attention
  46. matmul_qk = torch.matmul(q, k.permute(0, 1, 3, 2))
  47. dk = k.shape[-1]
  48. scaled_attention_logits = matmul_qk / np.sqrt(dk)
  49. if mask is not None:
  50. nd, ns = scaled_attention_logits.size(-2), scaled_attention_logits.size(-1)
  51. scaled_attention_logits += mask[ns - nd : ns, :ns] * -1e4
  52. if attention_mask is not None:
  53. # Apply the attention mask
  54. scaled_attention_logits = scaled_attention_logits + attention_mask
  55. attention_weights = torch.softmax(scaled_attention_logits, dim=-1)
  56. # Mask heads if we want to
  57. if head_mask is not None:
  58. attention_weights = attention_weights * head_mask
  59. output = torch.matmul(attention_weights, v)
  60. return output, attention_weights
  61. class MultiHeadAttention(nn.Module):
  62. def __init__(self, d_model_size, num_heads):
  63. super().__init__()
  64. self.num_heads = num_heads
  65. self.d_model_size = d_model_size
  66. self.depth = int(d_model_size / self.num_heads)
  67. self.Wq = nn.Linear(d_model_size, d_model_size)
  68. self.Wk = nn.Linear(d_model_size, d_model_size)
  69. self.Wv = nn.Linear(d_model_size, d_model_size)
  70. self.dense = nn.Linear(d_model_size, d_model_size)
  71. self.pruned_heads = set()
  72. def prune_heads(self, heads):
  73. attention_head_size = self.d_model_size // self.num_heads
  74. if len(heads) == 0:
  75. return
  76. heads, index = find_pruneable_heads_and_indices(heads, self.num_heads, attention_head_size, self.pruned_heads)
  77. # Prune linear layers
  78. self.Wq = prune_linear_layer(self.Wq, index)
  79. self.Wk = prune_linear_layer(self.Wk, index)
  80. self.Wv = prune_linear_layer(self.Wv, index)
  81. self.dense = prune_linear_layer(self.dense, index, dim=1)
  82. # Update hyper params
  83. self.num_heads = self.num_heads - len(heads)
  84. self.d_model_size = attention_head_size * self.num_heads
  85. self.pruned_heads = self.pruned_heads.union(heads)
  86. def split_into_heads(self, x, batch_size):
  87. x = x.reshape(batch_size, -1, self.num_heads, self.depth)
  88. return x.permute([0, 2, 1, 3])
  89. def forward(
  90. self,
  91. v,
  92. k,
  93. q,
  94. mask,
  95. layer_past=None,
  96. attention_mask=None,
  97. head_mask=None,
  98. use_cache=False,
  99. output_attentions=False,
  100. ):
  101. batch_size = q.shape[0]
  102. q = self.Wq(q)
  103. k = self.Wk(k)
  104. v = self.Wv(v)
  105. q = self.split_into_heads(q, batch_size)
  106. k = self.split_into_heads(k, batch_size)
  107. v = self.split_into_heads(v, batch_size)
  108. if layer_past is not None:
  109. past_key, past_value = layer_past[0], layer_past[1]
  110. k = torch.cat((past_key, k), dim=-2)
  111. v = torch.cat((past_value, v), dim=-2)
  112. if use_cache is True:
  113. present = torch.stack((k, v))
  114. else:
  115. present = (None,)
  116. output = scaled_dot_product_attention(q, k, v, mask, attention_mask, head_mask)
  117. scaled_attention = output[0].permute([0, 2, 1, 3])
  118. attn = output[1]
  119. original_size_attention = scaled_attention.reshape(batch_size, -1, self.d_model_size)
  120. output = self.dense(original_size_attention)
  121. outputs = (output, present)
  122. if output_attentions:
  123. outputs = outputs + (attn,)
  124. return outputs
  125. def point_wise_feed_forward_network(d_model_size, dff):
  126. return nn.Sequential(nn.Linear(d_model_size, dff), nn.ReLU(), nn.Linear(dff, d_model_size))
  127. class EncoderLayer(nn.Module):
  128. def __init__(self, d_model_size, num_heads, dff, rate=0.1):
  129. super().__init__()
  130. self.multi_head_attention = MultiHeadAttention(d_model_size, num_heads)
  131. self.ffn = point_wise_feed_forward_network(d_model_size, dff)
  132. self.layernorm1 = nn.LayerNorm(d_model_size, eps=1e-6)
  133. self.layernorm2 = nn.LayerNorm(d_model_size, eps=1e-6)
  134. self.dropout1 = nn.Dropout(rate)
  135. self.dropout2 = nn.Dropout(rate)
  136. def forward(
  137. self, x, mask, layer_past=None, attention_mask=None, head_mask=None, use_cache=False, output_attentions=False
  138. ):
  139. normed = self.layernorm1(x)
  140. attn_outputs = self.multi_head_attention(
  141. normed,
  142. normed,
  143. normed,
  144. mask,
  145. layer_past=layer_past,
  146. attention_mask=attention_mask,
  147. head_mask=head_mask,
  148. use_cache=use_cache,
  149. output_attentions=output_attentions,
  150. )
  151. attn_output = attn_outputs[0]
  152. attn_output = self.dropout1(attn_output)
  153. out1 = x + attn_output
  154. out2 = self.layernorm2(out1)
  155. ffn_output = self.ffn(out2)
  156. ffn_output = self.dropout2(ffn_output)
  157. out2 = out1 + ffn_output
  158. outputs = (out2,) + attn_outputs[1:]
  159. return outputs
  160. class CTRLPreTrainedModel(PreTrainedModel):
  161. """
  162. An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
  163. models.
  164. """
  165. config_class = CTRLConfig
  166. base_model_prefix = "transformer"
  167. def _init_weights(self, module):
  168. """Initialize the weights."""
  169. if isinstance(module, (nn.Linear, Conv1D)):
  170. # Slightly different from the TF version which uses truncated_normal for initialization
  171. # cf https://github.com/pytorch/pytorch/pull/5617
  172. module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
  173. if module.bias is not None:
  174. module.bias.data.zero_()
  175. elif isinstance(module, nn.Embedding):
  176. module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
  177. if module.padding_idx is not None:
  178. module.weight.data[module.padding_idx].zero_()
  179. elif isinstance(module, nn.LayerNorm):
  180. module.bias.data.zero_()
  181. module.weight.data.fill_(1.0)
  182. CTRL_START_DOCSTRING = r"""
  183. This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
  184. library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
  185. etc.)
  186. This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
  187. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
  188. and behavior.
  189. Parameters:
  190. config ([`CTRLConfig`]): Model configuration class with all the parameters of the model.
  191. Initializing with a config file does not load the weights associated with the model, only the
  192. configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
  193. """
  194. CTRL_INPUTS_DOCSTRING = r"""
  195. Args:
  196. input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
  197. `input_ids_length` = `sequence_length` if `past_key_values` is `None` else `past_key_values[0].shape[-2]`
  198. (`sequence_length` of input past key value states). Indices of input sequence tokens in the vocabulary.
  199. If `past_key_values` is used, only input IDs that do not have their past calculated should be passed as
  200. `input_ids`.
  201. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.__call__`] and
  202. [`PreTrainedTokenizer.encode`] for details.
  203. [What are input IDs?](../glossary#input-ids)
  204. past_key_values (`Tuple[Tuple[torch.FloatTensor]]` of length `config.n_layers`):
  205. Contains pre-computed hidden-states (key and values in the attention blocks) as computed by the model (see
  206. `past_key_values` output below). Can be used to speed up sequential decoding. The `input_ids` which have
  207. their past given to this model should not be passed as input ids as they have already been computed.
  208. attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
  209. Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
  210. - 1 for tokens that are **not masked**,
  211. - 0 for tokens that are **masked**.
  212. [What are attention masks?](../glossary#attention-mask)
  213. token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  214. Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
  215. 1]`:
  216. - 0 corresponds to a *sentence A* token,
  217. - 1 corresponds to a *sentence B* token.
  218. [What are token type IDs?](../glossary#token-type-ids)
  219. position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  220. Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
  221. config.max_position_embeddings - 1]`.
  222. [What are position IDs?](../glossary#position-ids)
  223. head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
  224. Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
  225. - 1 indicates the head is **not masked**,
  226. - 0 indicates the head is **masked**.
  227. inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
  228. Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
  229. is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
  230. model's internal embedding lookup matrix.
  231. use_cache (`bool`, *optional*):
  232. If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
  233. `past_key_values`).
  234. output_attentions (`bool`, *optional*):
  235. Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
  236. tensors for more detail.
  237. output_hidden_states (`bool`, *optional*):
  238. Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
  239. more detail.
  240. return_dict (`bool`, *optional*):
  241. Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
  242. """
  243. @add_start_docstrings(
  244. "The bare CTRL Model transformer outputting raw hidden-states without any specific head on top.",
  245. CTRL_START_DOCSTRING,
  246. )
  247. class CTRLModel(CTRLPreTrainedModel):
  248. def __init__(self, config):
  249. super().__init__(config)
  250. self.d_model_size = config.n_embd
  251. self.num_layers = config.n_layer
  252. self.pos_encoding = positional_encoding(config.n_positions, self.d_model_size, torch.float)
  253. self.w = nn.Embedding(config.vocab_size, config.n_embd)
  254. self.dropout = nn.Dropout(config.embd_pdrop)
  255. self.h = nn.ModuleList(
  256. [EncoderLayer(config.n_embd, config.n_head, config.dff, config.resid_pdrop) for _ in range(config.n_layer)]
  257. )
  258. self.layernorm = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
  259. # Initialize weights and apply final processing
  260. self.post_init()
  261. def get_input_embeddings(self):
  262. return self.w
  263. def set_input_embeddings(self, new_embeddings):
  264. self.w = new_embeddings
  265. def _prune_heads(self, heads_to_prune):
  266. """
  267. Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer}
  268. """
  269. for layer, heads in heads_to_prune.items():
  270. self.h[layer].multi_head_attention.prune_heads(heads)
  271. @add_start_docstrings_to_model_forward(CTRL_INPUTS_DOCSTRING)
  272. @replace_return_docstrings(output_type=BaseModelOutputWithPast, config_class=_CONFIG_FOR_DOC)
  273. def forward(
  274. self,
  275. input_ids: Optional[torch.LongTensor] = None,
  276. past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
  277. attention_mask: Optional[torch.FloatTensor] = None,
  278. token_type_ids: Optional[torch.LongTensor] = None,
  279. position_ids: Optional[torch.LongTensor] = None,
  280. head_mask: Optional[torch.FloatTensor] = None,
  281. inputs_embeds: Optional[torch.FloatTensor] = None,
  282. use_cache: Optional[bool] = None,
  283. output_attentions: Optional[bool] = None,
  284. output_hidden_states: Optional[bool] = None,
  285. return_dict: Optional[bool] = None,
  286. ) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPast]:
  287. r"""
  288. Returns:
  289. Example:
  290. ```python
  291. >>> from transformers import AutoTokenizer, CTRLModel
  292. >>> import torch
  293. >>> tokenizer = AutoTokenizer.from_pretrained("Salesforce/ctrl")
  294. >>> model = CTRLModel.from_pretrained("Salesforce/ctrl")
  295. >>> # CTRL was trained with control codes as the first token
  296. >>> inputs = tokenizer("Opinion My dog is cute", return_tensors="pt")
  297. >>> assert inputs["input_ids"][0, 0].item() in tokenizer.control_codes.values()
  298. >>> outputs = model(**inputs)
  299. >>> last_hidden_states = outputs.last_hidden_state
  300. >>> list(last_hidden_states.shape)
  301. [1, 5, 1280]
  302. ```"""
  303. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  304. use_cache = use_cache if use_cache is not None else self.config.use_cache
  305. output_hidden_states = (
  306. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  307. )
  308. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  309. if input_ids is not None and inputs_embeds is not None:
  310. raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
  311. elif input_ids is not None:
  312. self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
  313. input_shape = input_ids.size()
  314. input_ids = input_ids.view(-1, input_shape[-1])
  315. batch_size = input_ids.shape[0]
  316. elif inputs_embeds is not None:
  317. input_shape = inputs_embeds.size()[:-1]
  318. batch_size = inputs_embeds.shape[0]
  319. else:
  320. raise ValueError("You have to specify either input_ids or inputs_embeds")
  321. device = input_ids.device if input_ids is not None else inputs_embeds.device
  322. if past_key_values is None:
  323. past_length = 0
  324. past_key_values = tuple([None] * len(self.h))
  325. else:
  326. past_length = past_key_values[0][0].size(-2)
  327. if position_ids is None:
  328. position_ids = torch.arange(past_length, input_shape[-1] + past_length, dtype=torch.long, device=device)
  329. position_ids = position_ids.unsqueeze(0)
  330. # Attention mask.
  331. if attention_mask is not None:
  332. if batch_size <= 0:
  333. raise ValueError("batch_size has to be defined and > 0")
  334. attention_mask = attention_mask.view(batch_size, -1)
  335. # We create a 3D attention mask from a 2D tensor mask.
  336. # Sizes are [batch_size, 1, 1, to_seq_length]
  337. # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
  338. # this attention mask is more simple than the triangular masking of causal attention
  339. # used in OpenAI GPT, we just need to prepare the broadcast dimension here.
  340. attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)
  341. # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
  342. # masked positions, this operation will create a tensor which is 0.0 for
  343. # positions we want to attend and the dtype's smallest value for masked positions.
  344. # Since we are adding it to the raw scores before the softmax, this is
  345. # effectively the same as removing these entirely.
  346. attention_mask = attention_mask.to(dtype=self.dtype) # fp16 compatibility
  347. attention_mask = (1.0 - attention_mask) * torch.finfo(self.dtype).min
  348. # Prepare head mask if needed
  349. head_mask = self.get_head_mask(head_mask, self.config.n_layer)
  350. if token_type_ids is not None:
  351. token_type_ids = token_type_ids.view(-1, input_shape[-1])
  352. token_type_embeds = self.w(token_type_ids)
  353. token_type_embeds *= np.sqrt(self.d_model_size)
  354. else:
  355. token_type_embeds = 0
  356. if inputs_embeds is None:
  357. inputs_embeds = self.w(input_ids)
  358. # inputs_embeds = embedded.unsqueeze(0) if len(input_ids.shape)<2 else embedded
  359. seq_len = input_shape[-1]
  360. mask = torch.triu(torch.ones(seq_len + past_length, seq_len + past_length), 1).to(device)
  361. inputs_embeds *= np.sqrt(self.d_model_size)
  362. # `self.pos_encoding` won't be sent to the correct device along the model, so we do it manually.
  363. self.pos_encoding = self.pos_encoding.to(device)
  364. pos_embeds = self.pos_encoding[position_ids, :]
  365. hidden_states = inputs_embeds + pos_embeds + token_type_embeds
  366. hidden_states = self.dropout(hidden_states)
  367. presents = () if use_cache else None
  368. all_hidden_states = () if output_hidden_states else None
  369. all_attentions = () if output_attentions else None
  370. for i, (h, layer_past) in enumerate(zip(self.h, past_key_values)):
  371. if output_hidden_states:
  372. all_hidden_states = all_hidden_states + (hidden_states,)
  373. outputs = h(
  374. hidden_states,
  375. mask,
  376. layer_past=layer_past,
  377. attention_mask=attention_mask,
  378. head_mask=head_mask[i],
  379. use_cache=use_cache,
  380. output_attentions=output_attentions,
  381. )
  382. hidden_states, present = outputs[:2]
  383. if use_cache is True:
  384. presents = presents + (present,)
  385. if output_attentions:
  386. all_attentions += (outputs[2],)
  387. hidden_states = self.layernorm(hidden_states)
  388. if output_hidden_states:
  389. all_hidden_states = all_hidden_states + (hidden_states,)
  390. if not return_dict:
  391. return tuple(v for v in [hidden_states, presents, all_hidden_states, all_attentions] if v is not None)
  392. return BaseModelOutputWithPast(
  393. last_hidden_state=hidden_states,
  394. past_key_values=presents,
  395. hidden_states=all_hidden_states,
  396. attentions=all_attentions,
  397. )
  398. @add_start_docstrings(
  399. """
  400. The CTRL Model transformer with a language modeling head on top (linear layer with weights tied to the input
  401. embeddings).
  402. """,
  403. CTRL_START_DOCSTRING,
  404. )
  405. class CTRLLMHeadModel(CTRLPreTrainedModel, GenerationMixin):
  406. _tied_weights_keys = ["lm_head.weight"]
  407. def __init__(self, config):
  408. super().__init__(config)
  409. self.transformer = CTRLModel(config)
  410. self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=True)
  411. # Initialize weights and apply final processing
  412. self.post_init()
  413. def get_output_embeddings(self):
  414. return self.lm_head
  415. def set_output_embeddings(self, new_embeddings):
  416. self.lm_head = new_embeddings
  417. @add_start_docstrings_to_model_forward(CTRL_INPUTS_DOCSTRING)
  418. @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
  419. def forward(
  420. self,
  421. input_ids: Optional[torch.LongTensor] = None,
  422. past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
  423. attention_mask: Optional[torch.FloatTensor] = None,
  424. token_type_ids: Optional[torch.LongTensor] = None,
  425. position_ids: Optional[torch.LongTensor] = None,
  426. head_mask: Optional[torch.FloatTensor] = None,
  427. inputs_embeds: Optional[torch.FloatTensor] = None,
  428. labels: Optional[torch.LongTensor] = None,
  429. use_cache: Optional[bool] = None,
  430. output_attentions: Optional[bool] = None,
  431. output_hidden_states: Optional[bool] = None,
  432. return_dict: Optional[bool] = None,
  433. ) -> Union[Tuple[torch.Tensor], CausalLMOutputWithPast]:
  434. r"""
  435. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  436. Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
  437. `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
  438. are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
  439. Returns:
  440. Example:
  441. ```python
  442. >>> import torch
  443. >>> from transformers import AutoTokenizer, CTRLLMHeadModel
  444. >>> tokenizer = AutoTokenizer.from_pretrained("Salesforce/ctrl")
  445. >>> model = CTRLLMHeadModel.from_pretrained("Salesforce/ctrl")
  446. >>> # CTRL was trained with control codes as the first token
  447. >>> inputs = tokenizer("Wikipedia The llama is", return_tensors="pt")
  448. >>> assert inputs["input_ids"][0, 0].item() in tokenizer.control_codes.values()
  449. >>> sequence_ids = model.generate(inputs["input_ids"])
  450. >>> sequences = tokenizer.batch_decode(sequence_ids)
  451. >>> sequences
  452. ['Wikipedia The llama is a member of the family Bovidae. It is native to the Andes of Peru,']
  453. >>> outputs = model(**inputs, labels=inputs["input_ids"])
  454. >>> round(outputs.loss.item(), 2)
  455. 9.21
  456. >>> list(outputs.logits.shape)
  457. [1, 5, 246534]
  458. ```"""
  459. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  460. transformer_outputs = self.transformer(
  461. input_ids,
  462. past_key_values=past_key_values,
  463. attention_mask=attention_mask,
  464. token_type_ids=token_type_ids,
  465. position_ids=position_ids,
  466. head_mask=head_mask,
  467. inputs_embeds=inputs_embeds,
  468. use_cache=use_cache,
  469. output_attentions=output_attentions,
  470. output_hidden_states=output_hidden_states,
  471. return_dict=return_dict,
  472. )
  473. hidden_states = transformer_outputs[0]
  474. lm_logits = self.lm_head(hidden_states)
  475. loss = None
  476. if labels is not None:
  477. # Shift so that tokens < n predict n
  478. shift_logits = lm_logits[..., :-1, :].contiguous()
  479. shift_labels = labels[..., 1:].contiguous()
  480. # Flatten the tokens
  481. loss_fct = CrossEntropyLoss()
  482. loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
  483. if not return_dict:
  484. output = (lm_logits,) + transformer_outputs[1:]
  485. return ((loss,) + output) if loss is not None else output
  486. return CausalLMOutputWithPast(
  487. loss=loss,
  488. logits=lm_logits,
  489. past_key_values=transformer_outputs.past_key_values,
  490. hidden_states=transformer_outputs.hidden_states,
  491. attentions=transformer_outputs.attentions,
  492. )
  493. def prepare_inputs_for_generation(self, input_ids, past_key_values=None, use_cache=None, **kwargs):
  494. # Overwritten -- inputs_embeds not working properly
  495. # only last tokens for inputs_ids if past is defined in kwargs
  496. if past_key_values is not None:
  497. past_length = past_key_values[0][0].shape[2]
  498. # Some generation methods already pass only the last input ID
  499. if input_ids.shape[1] > past_length:
  500. remove_prefix_length = past_length
  501. else:
  502. # Default to old behavior: keep only final ID
  503. remove_prefix_length = input_ids.shape[1] - 1
  504. input_ids = input_ids[:, remove_prefix_length:]
  505. return {"input_ids": input_ids, "past_key_values": past_key_values, "use_cache": use_cache}
  506. @staticmethod
  507. def _reorder_cache(
  508. past_key_values: Tuple[Tuple[torch.Tensor]], beam_idx: torch.Tensor
  509. ) -> Tuple[Tuple[torch.Tensor]]:
  510. """
  511. This function is used to re-order the `past_key_values` cache if [`~PreTrainedModel.beam_search`] or
  512. [`~PreTrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correct
  513. beam_idx at every generation step.
  514. """
  515. return tuple(
  516. tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past)
  517. for layer_past in past_key_values
  518. )
  519. @add_start_docstrings(
  520. """
  521. The CTRL Model transformer with a sequence classification head on top (linear layer).
  522. [`CTRLForSequenceClassification`] uses the last token in order to do the classification, as other causal models
  523. (e.g. GPT-2) do. Since it does classification on the last token, it requires to know the position of the last
  524. token. If a `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in
  525. each row. If no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot
  526. guess the padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last
  527. value in each row of the batch).
  528. """,
  529. CTRL_START_DOCSTRING,
  530. )
  531. class CTRLForSequenceClassification(CTRLPreTrainedModel):
  532. def __init__(self, config):
  533. super().__init__(config)
  534. self.num_labels = config.num_labels
  535. self.transformer = CTRLModel(config)
  536. self.classifier = nn.Linear(config.n_embd, self.num_labels, bias=False)
  537. # Initialize weights and apply final processing
  538. self.post_init()
  539. @add_start_docstrings_to_model_forward(CTRL_INPUTS_DOCSTRING)
  540. @replace_return_docstrings(output_type=SequenceClassifierOutput, config_class=_CONFIG_FOR_DOC)
  541. def forward(
  542. self,
  543. input_ids: Optional[torch.LongTensor] = None,
  544. past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
  545. attention_mask: Optional[torch.FloatTensor] = None,
  546. token_type_ids: Optional[torch.LongTensor] = None,
  547. position_ids: Optional[torch.LongTensor] = None,
  548. head_mask: Optional[torch.FloatTensor] = None,
  549. inputs_embeds: Optional[torch.FloatTensor] = None,
  550. labels: Optional[torch.LongTensor] = None,
  551. use_cache: Optional[bool] = None,
  552. output_attentions: Optional[bool] = None,
  553. output_hidden_states: Optional[bool] = None,
  554. return_dict: Optional[bool] = None,
  555. ) -> Union[Tuple[torch.Tensor], SequenceClassifierOutput]:
  556. r"""
  557. labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  558. Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
  559. config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
  560. `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
  561. Returns:
  562. Example of single-label classification:
  563. ```python
  564. >>> import torch
  565. >>> from transformers import AutoTokenizer, CTRLForSequenceClassification
  566. >>> tokenizer = AutoTokenizer.from_pretrained("Salesforce/ctrl")
  567. >>> model = CTRLForSequenceClassification.from_pretrained("Salesforce/ctrl")
  568. >>> # CTRL was trained with control codes as the first token
  569. >>> inputs = tokenizer("Opinion My dog is cute", return_tensors="pt")
  570. >>> assert inputs["input_ids"][0, 0].item() in tokenizer.control_codes.values()
  571. >>> with torch.no_grad():
  572. ... logits = model(**inputs).logits
  573. >>> predicted_class_id = logits.argmax().item()
  574. >>> model.config.id2label[predicted_class_id]
  575. 'LABEL_0'
  576. ```
  577. ```python
  578. >>> import torch
  579. >>> torch.manual_seed(42) # doctest: +IGNORE_RESULT
  580. >>> # To train a model on `num_labels` classes, you can pass `num_labels=num_labels` to `.from_pretrained(...)`
  581. >>> num_labels = len(model.config.id2label)
  582. >>> model = CTRLForSequenceClassification.from_pretrained("Salesforce/ctrl", num_labels=num_labels)
  583. >>> labels = torch.tensor(1)
  584. >>> loss = model(**inputs, labels=labels).loss
  585. >>> round(loss.item(), 2)
  586. 0.93
  587. ```
  588. Example of multi-label classification:
  589. ```python
  590. >>> import torch
  591. >>> from transformers import AutoTokenizer, CTRLForSequenceClassification
  592. >>> tokenizer = AutoTokenizer.from_pretrained("Salesforce/ctrl")
  593. >>> model = CTRLForSequenceClassification.from_pretrained(
  594. ... "Salesforce/ctrl", problem_type="multi_label_classification"
  595. ... )
  596. >>> # CTRL was trained with control codes as the first token
  597. >>> inputs = tokenizer("Opinion My dog is cute", return_tensors="pt")
  598. >>> assert inputs["input_ids"][0, 0].item() in tokenizer.control_codes.values()
  599. >>> with torch.no_grad():
  600. ... logits = model(**inputs).logits
  601. >>> predicted_class_id = logits.argmax().item()
  602. >>> model.config.id2label[predicted_class_id]
  603. 'LABEL_0'
  604. ```
  605. ```python
  606. >>> # To train a model on `num_labels` classes, you can pass `num_labels=num_labels` to `.from_pretrained(...)`
  607. >>> num_labels = len(model.config.id2label)
  608. >>> model = CTRLForSequenceClassification.from_pretrained("Salesforce/ctrl", num_labels=num_labels)
  609. >>> num_labels = len(model.config.id2label)
  610. >>> labels = torch.nn.functional.one_hot(torch.tensor([predicted_class_id]), num_classes=num_labels).to(
  611. ... torch.float
  612. ... )
  613. >>> loss = model(**inputs, labels=labels).loss
  614. >>> loss.backward() # doctest: +IGNORE_RESULT
  615. ```"""
  616. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  617. transformer_outputs = self.transformer(
  618. input_ids,
  619. past_key_values=past_key_values,
  620. attention_mask=attention_mask,
  621. token_type_ids=token_type_ids,
  622. position_ids=position_ids,
  623. head_mask=head_mask,
  624. inputs_embeds=inputs_embeds,
  625. use_cache=use_cache,
  626. output_attentions=output_attentions,
  627. output_hidden_states=output_hidden_states,
  628. return_dict=return_dict,
  629. )
  630. hidden_states = transformer_outputs[0]
  631. logits = self.classifier(hidden_states)
  632. if input_ids is not None:
  633. batch_size, sequence_length = input_ids.shape[:2]
  634. else:
  635. batch_size, sequence_length = inputs_embeds.shape[:2]
  636. if self.config.pad_token_id is None and batch_size != 1:
  637. raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
  638. if self.config.pad_token_id is None:
  639. sequence_lengths = -1
  640. else:
  641. if input_ids is not None:
  642. # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
  643. sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
  644. sequence_lengths = sequence_lengths % input_ids.shape[-1]
  645. sequence_lengths = sequence_lengths.to(logits.device)
  646. else:
  647. sequence_lengths = -1
  648. logger.warning_once(
  649. f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
  650. "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
  651. )
  652. pooled_logits = logits[range(batch_size), sequence_lengths]
  653. loss = None
  654. if labels is not None:
  655. if self.config.problem_type is None:
  656. if self.num_labels == 1:
  657. self.config.problem_type = "regression"
  658. elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
  659. self.config.problem_type = "single_label_classification"
  660. else:
  661. self.config.problem_type = "multi_label_classification"
  662. if self.config.problem_type == "regression":
  663. loss_fct = MSELoss()
  664. if self.num_labels == 1:
  665. loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
  666. else:
  667. loss = loss_fct(pooled_logits, labels)
  668. elif self.config.problem_type == "single_label_classification":
  669. loss_fct = CrossEntropyLoss()
  670. loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
  671. elif self.config.problem_type == "multi_label_classification":
  672. loss_fct = BCEWithLogitsLoss()
  673. loss = loss_fct(pooled_logits, labels)
  674. if not return_dict:
  675. output = (pooled_logits,) + transformer_outputs[2:]
  676. return ((loss,) + output) if loss is not None else output
  677. return SequenceClassifierOutput(
  678. loss=loss,
  679. logits=pooled_logits,
  680. hidden_states=transformer_outputs.hidden_states,
  681. attentions=transformer_outputs.attentions,
  682. )