model.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  1. """
  2. PyTorch BLOOM model that implements several memory-efficient modes.
  3. Based on https://github.com/huggingface/transformers/commit/ca2a55e9dfb245527b5e1c954fec6ffbb7aef07b
  4. See commit history for authorship.
  5. """
  6. from typing import Tuple, Union
  7. import torch
  8. import torch.nn.functional as F
  9. import torch.utils.checkpoint
  10. from hivemind import use_hivemind_log_handler
  11. from torch import nn
  12. from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, LayerNorm, MSELoss
  13. from transformers.file_utils import (
  14. add_code_sample_docstrings,
  15. add_start_docstrings,
  16. add_start_docstrings_to_model_forward,
  17. )
  18. from transformers.modeling_outputs import (
  19. BaseModelOutputWithPastAndCrossAttentions,
  20. CausalLMOutputWithCrossAttentions,
  21. SequenceClassifierOutputWithPast,
  22. )
  23. from transformers.modeling_utils import PreTrainedModel
  24. from transformers.models.bloom.configuration_bloom import BloomConfig
  25. from transformers.models.bloom.modeling_bloom import BloomPreTrainedModel
  26. from transformers.utils import logging
  27. from src.bloom.block import BloomBlock
  28. use_hivemind_log_handler("in_root_logger")
  29. logger = logging.get_logger(__file__)
  30. _CHECKPOINT_FOR_DOC = "bigscience/Bloom"
  31. _CONFIG_FOR_DOC = "BloomConfig"
  32. _TOKENIZER_FOR_DOC = "BloomTokenizer"
  33. BLOOM_START_DOCSTRING = r"""
  34. This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
  35. library implements for all its model (such as downloading or saving, resizing the input embeddings etc.)
  36. This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
  37. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
  38. and behavior.
  39. Parameters:
  40. config ([`MemoryEfficientBloomConfig`]): Model configuration class with all the parameters of the model.
  41. Initializing with a config file does not load the weights associated with the model, only the
  42. configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
  43. """
  44. BLOOM_INPUTS_DOCSTRING = r"""
  45. Args:
  46. input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
  47. `input_ids_length` = `sequence_length` if `past_key_values` is `None` else
  48. `past_key_values[0][0].shape[-2]` (`sequence_length` of input past key value states). Indices of input
  49. sequence tokens in the vocabulary.
  50. If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
  51. `input_ids`.
  52. Indices can be obtained using [`BloomTokenizer`]. See [`PreTrainedTokenizer.encode`] and
  53. [`PreTrainedTokenizer.__call__`] for details.
  54. [What are input IDs?](../glossary#input-ids)
  55. past_key_values (`Tuple[Tuple[torch.Tensor]]` of length `config.n_layers`):
  56. Contains precomputed hidden-states (key and values in the attention blocks) as computed by the model (see
  57. `past_key_values` output below). Can be used to speed up sequential decoding. The `input_ids` which have
  58. their past given to this model should not be passed as `input_ids` as they have already been computed.
  59. attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
  60. Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
  61. - 1 for tokens that are **not masked**,
  62. - 0 for tokens that are **masked**.
  63. [What are attention masks?](../glossary#attention-mask)
  64. position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  65. Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
  66. config.max_position_embeddings - 1]`.
  67. [What are position IDs?](../glossary#position-ids)
  68. head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
  69. Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
  70. - 1 indicates the head is **not masked**,
  71. - 0 indicates the head is **masked**.
  72. inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
  73. Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
  74. is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
  75. model's internal embedding lookup matrix.
  76. If `past_key_values` is used, optionally only the last `inputs_embeds` have to be input (see
  77. `past_key_values`).
  78. use_cache (`bool`, *optional*):
  79. If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
  80. `past_key_values`).
  81. output_attentions (`bool`, *optional*):
  82. Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
  83. tensors for more detail.
  84. output_hidden_states (`bool`, *optional*):
  85. Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
  86. more detail.
  87. return_dict (`bool`, *optional*):
  88. Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple.
  89. """
  90. @add_start_docstrings(
  91. "The bare Bloom Model transformer outputting raw hidden-states without any specific head on top.",
  92. BLOOM_START_DOCSTRING,
  93. )
  94. class BloomModel(BloomPreTrainedModel):
  95. def __init__(self, config):
  96. super().__init__(config)
  97. assert not config.slow_but_exact, "slow_but_exact mode was removed for code simplicity"
  98. self.embed_dim = config.hidden_size
  99. self.n_head = config.n_head
  100. # Embedding + LN Embedding
  101. self.word_embeddings = nn.Embedding(config.vocab_size, self.embed_dim)
  102. self.word_embeddings_layernorm = LayerNorm(self.embed_dim, eps=config.layer_norm_epsilon)
  103. # Transformer blocks
  104. self.h = nn.ModuleList([BloomBlock(config, layer_number=i) for i in range(config.num_hidden_layers)])
  105. # Final Layer Norm
  106. self.ln_f = LayerNorm(self.embed_dim, eps=config.layer_norm_epsilon)
  107. self.gradient_checkpointing = False
  108. # Initialize weights and apply final processing
  109. self.post_init()
  110. def get_input_embeddings(self):
  111. return self.word_embeddings
  112. def set_input_embeddings(self, new_embeddings):
  113. self.word_embeddings = new_embeddings
  114. @add_start_docstrings_to_model_forward(BLOOM_INPUTS_DOCSTRING)
  115. @add_code_sample_docstrings(
  116. processor_class=_TOKENIZER_FOR_DOC,
  117. checkpoint=_CHECKPOINT_FOR_DOC,
  118. output_type=BaseModelOutputWithPastAndCrossAttentions,
  119. config_class=_CONFIG_FOR_DOC,
  120. )
  121. def forward(
  122. self,
  123. input_ids=None,
  124. past_key_values=None,
  125. attention_mask=None,
  126. position_ids=None,
  127. head_mask=None,
  128. inputs_embeds=None,
  129. use_cache=None,
  130. output_attentions=None,
  131. output_hidden_states=None,
  132. return_dict=None,
  133. ):
  134. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  135. output_hidden_states = (
  136. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  137. )
  138. use_cache = use_cache if use_cache is not None else self.config.use_cache
  139. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  140. if input_ids is not None and inputs_embeds is not None:
  141. raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
  142. if position_ids is not None:
  143. logger.warning("position_ids are ignored in this bloom implementation")
  144. elif input_ids is not None:
  145. input_shape = input_ids.size()
  146. input_ids = input_ids.view(-1, input_shape[-1])
  147. elif inputs_embeds is not None:
  148. input_shape = inputs_embeds.size()[:-1]
  149. else:
  150. raise ValueError("You have to specify either input_ids or inputs_embeds")
  151. if past_key_values is None:
  152. past_key_values = tuple([None] * len(self.h))
  153. # Prepare head mask if needed
  154. # 1.0 in head_mask indicate we keep the head
  155. # attention_probs has shape bsz x n_head x N x N
  156. # head_mask has shape n_layer x batch x n_head x N x N
  157. head_mask = self.get_head_mask(head_mask, self.config.n_layer)
  158. if inputs_embeds is None:
  159. inputs_embeds = self.word_embeddings(input_ids)
  160. # Note: it supports only float32 or bfloat16 inputs
  161. hidden_states = self.word_embeddings_layernorm(inputs_embeds)
  162. output_shape = input_shape + (hidden_states.size(-1),)
  163. presents = () if use_cache else None
  164. all_self_attentions = () if output_attentions else None
  165. all_hidden_states = () if output_hidden_states else None
  166. # Compute alibi tensor: check build_alibi_tensor documentation
  167. current_sequence_length = hidden_states.shape[1]
  168. if past_key_values and past_key_values[0]:
  169. current_sequence_length += past_key_values[0][0].shape[1]
  170. for i, (block, layer_past) in enumerate(zip(self.h, past_key_values)):
  171. if output_hidden_states:
  172. all_hidden_states = all_hidden_states + (hidden_states,)
  173. if self.gradient_checkpointing and self.training:
  174. if use_cache:
  175. logger.warning(
  176. "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
  177. )
  178. use_cache = False
  179. def create_custom_forward(module):
  180. def custom_forward(*inputs):
  181. # None for past_key_value
  182. return module(*inputs, use_cache, output_attentions, alibi=None)
  183. return custom_forward
  184. outputs = torch.utils.checkpoint.checkpoint(
  185. create_custom_forward(block),
  186. hidden_states,
  187. None,
  188. attention_mask,
  189. head_mask[i],
  190. )
  191. else:
  192. outputs = block(
  193. hidden_states,
  194. layer_past=layer_past,
  195. attention_mask=attention_mask,
  196. head_mask=head_mask[i],
  197. use_cache=use_cache,
  198. output_attentions=output_attentions,
  199. alibi=None,
  200. )
  201. hidden_states = outputs[0]
  202. if use_cache is True:
  203. presents = presents + (outputs[1],)
  204. if output_attentions:
  205. all_self_attentions = all_self_attentions + (outputs[2 if use_cache else 1],)
  206. # Add last hidden state
  207. hidden_states = self.ln_f(hidden_states)
  208. if output_hidden_states:
  209. all_hidden_states = all_hidden_states + (hidden_states,)
  210. hidden_states = hidden_states.view(output_shape)
  211. if not return_dict:
  212. return tuple(v for v in [hidden_states, presents, all_hidden_states, all_self_attentions] if v is not None)
  213. return BaseModelOutputWithPastAndCrossAttentions(
  214. last_hidden_state=hidden_states,
  215. past_key_values=presents,
  216. hidden_states=all_hidden_states,
  217. attentions=all_self_attentions,
  218. )
  219. @add_start_docstrings(
  220. """
  221. The Bloom Model transformer with a language modeling head on top (linear layer with weights tied to the input
  222. embeddings).
  223. """,
  224. BLOOM_START_DOCSTRING,
  225. )
  226. class BloomForCausalLM(BloomPreTrainedModel):
  227. _keys_to_ignore_on_load_missing = [r"h.*.self_attention.scale_mask_softmax.causal_mask", r"lm_head.weight"]
  228. def __init__(self, config):
  229. super().__init__(config)
  230. self.transformer = BloomModel(config)
  231. self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
  232. # Initialize weights and apply final processing
  233. self.post_init()
  234. def get_output_embeddings(self):
  235. return self.lm_head
  236. def set_output_embeddings(self, new_embeddings):
  237. self.lm_head = new_embeddings
  238. def prepare_inputs_for_generation(self, input_ids, past=None, **kwargs):
  239. # only last token for inputs_ids if past is defined in kwargs
  240. if past:
  241. input_ids = input_ids[:, -1].unsqueeze(-1)
  242. attention_mask = kwargs.get("attention_mask", None)
  243. position_ids = kwargs.get("position_ids", None)
  244. if attention_mask is not None and position_ids is None:
  245. # create position_ids on the fly for batch generation
  246. position_ids = attention_mask.long().cumsum(-1) - 1
  247. position_ids.masked_fill_(attention_mask == 0, 1)
  248. if past:
  249. position_ids = position_ids[:, -1].unsqueeze(-1)
  250. else:
  251. position_ids = None
  252. return {
  253. "input_ids": input_ids,
  254. "past_key_values": past,
  255. "use_cache": kwargs.get("use_cache"),
  256. "position_ids": position_ids,
  257. "attention_mask": attention_mask,
  258. }
  259. @add_start_docstrings_to_model_forward(BLOOM_INPUTS_DOCSTRING)
  260. @add_code_sample_docstrings(
  261. processor_class=_TOKENIZER_FOR_DOC,
  262. checkpoint=_CHECKPOINT_FOR_DOC,
  263. output_type=CausalLMOutputWithCrossAttentions,
  264. config_class=_CONFIG_FOR_DOC,
  265. )
  266. def forward(
  267. self,
  268. input_ids=None,
  269. past_key_values=None,
  270. attention_mask=None,
  271. position_ids=None,
  272. head_mask=None,
  273. inputs_embeds=None,
  274. labels=None,
  275. use_cache=None,
  276. output_attentions=None,
  277. output_hidden_states=None,
  278. return_dict=None,
  279. ) -> Union[Tuple[torch.Tensor], CausalLMOutputWithCrossAttentions]:
  280. r"""
  281. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  282. Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
  283. `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
  284. are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
  285. """
  286. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  287. transformer_outputs = self.transformer(
  288. input_ids,
  289. past_key_values=past_key_values,
  290. attention_mask=attention_mask,
  291. position_ids=position_ids,
  292. head_mask=head_mask,
  293. inputs_embeds=inputs_embeds,
  294. use_cache=use_cache,
  295. output_attentions=output_attentions,
  296. output_hidden_states=output_hidden_states,
  297. return_dict=return_dict,
  298. )
  299. hidden_states = transformer_outputs[0]
  300. lm_logits = self.lm_head(hidden_states)
  301. loss = None
  302. if labels is not None:
  303. # Shift so that tokens < n predict n
  304. shift_logits = lm_logits[..., :-1, :].contiguous()
  305. shift_labels = labels[..., 1:].contiguous()
  306. # Flatten the tokens
  307. loss_fct = CrossEntropyLoss()
  308. loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
  309. if not return_dict:
  310. output = (lm_logits,) + transformer_outputs[1:]
  311. return ((loss,) + output) if loss is not None else output
  312. return CausalLMOutputWithCrossAttentions(
  313. loss=loss,
  314. logits=lm_logits,
  315. past_key_values=transformer_outputs.past_key_values,
  316. hidden_states=transformer_outputs.hidden_states,
  317. attentions=transformer_outputs.attentions,
  318. )
  319. @staticmethod
  320. def _reorder_cache(past: Tuple[Tuple[torch.Tensor]], beam_idx: torch.Tensor) -> Tuple[Tuple[torch.Tensor]]:
  321. """
  322. This function is used to re-order the `past_key_values` cache if [`~PreTrainedModel.beam_search`] or
  323. [`~PreTrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correct
  324. beam_idx at every generation step.
  325. """
  326. return tuple(
  327. tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past)
  328. for layer_past in past
  329. )
  330. @add_start_docstrings(
  331. """
  332. The modified language modeling head which does not create extra tensor for the linear layer with weights tied to the input
  333. embeddings. Thus, it reduces initial memory consumption which might be crucial for large dictionaries.
  334. In addition, it provides an effcient way to deal with half-precision word embeddings on CPU.
  335. """,
  336. BLOOM_START_DOCSTRING,
  337. )
  338. class LMHead(nn.Module):
  339. def __init__(self, config, word_embeddings: nn.Embedding):
  340. super().__init__()
  341. self.word_embeddings = word_embeddings
  342. self.chunk_size = config.chunk_size_for_efficient_fp16_on_cpu
  343. @property
  344. def in_features(self) -> int:
  345. return self.word_embeddings.num_embeddings
  346. @property
  347. def out_features(self) -> int:
  348. return self.word_embeddings.embedding_dim
  349. @property
  350. def weight(self):
  351. return self.word_embeddings.weight
  352. @property
  353. def bias(self):
  354. return None
  355. def forward(self, hidden_states):
  356. word_embeddings = self.word_embeddings.weight
  357. # We use 'chunked_forward' only when embeddings are in half-precision on CPU.
  358. if word_embeddings.dtype in [torch.float16, torch.bfloat16] and word_embeddings.device.type == "cpu":
  359. lm_logits = self.chunked_forward(hidden_states)
  360. else:
  361. # Switch dtype in case word_embeddings are fp16/bf16
  362. hidden_states = hidden_states.to(word_embeddings.dtype)
  363. lm_logits = F.linear(hidden_states, word_embeddings).float()
  364. return lm_logits
  365. def chunked_forward(self, hidden_states):
  366. """Splits word embeddings on chunks and iteratively casts them into fp32 to perform matmul more efficiently on CPU.
  367. chunk_size: provides trade-off between efficiency and extra memory consumption.
  368. """
  369. assert self.chunk_size > 0, "Chunk size for chunked forward must be positive"
  370. word_embeddings = self.word_embeddings.weight
  371. num_embeddings = self.word_embeddings.num_embeddings
  372. hidden_states = hidden_states.float()
  373. output = torch.zeros(*hidden_states.shape[:-1], num_embeddings)
  374. for i in range(0, num_embeddings, self.chunk_size):
  375. chunk = word_embeddings[i : i + self.chunk_size].float()
  376. output[..., i : i + self.chunk_size] = F.linear(hidden_states, chunk)
  377. return output
  378. @add_start_docstrings(
  379. """
  380. The Bloom Model transformer with a sequence classification head on top (linear layer).
  381. [`BloomForSequenceClassification`] uses the last token in order to do the classification, as other causal models
  382. (e.g. GPT-1) do.
  383. Since it does classification on the last token, it requires to know the position of the last token. If a
  384. `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
  385. no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
  386. padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
  387. each row of the batch).
  388. """,
  389. BLOOM_START_DOCSTRING,
  390. )
  391. class BloomForSequenceClassification(BloomPreTrainedModel):
  392. _keys_to_ignore_on_load_missing = [r"h.*.self_attention.scale_mask_softmax.causal_mask", r"lm_head.weight"]
  393. def __init__(self, config):
  394. super().__init__(config)
  395. self.num_labels = config.num_labels
  396. self.transformer = BloomModel(config)
  397. self.score = nn.Linear(config.hidden_size, config.num_labels, bias=False)
  398. # Initialize weights and apply final processing
  399. self.post_init()
  400. @add_start_docstrings_to_model_forward(BLOOM_INPUTS_DOCSTRING)
  401. @add_code_sample_docstrings(
  402. processor_class=_TOKENIZER_FOR_DOC,
  403. checkpoint=_CHECKPOINT_FOR_DOC,
  404. output_type=SequenceClassifierOutputWithPast,
  405. config_class=_CONFIG_FOR_DOC,
  406. )
  407. def forward(
  408. self,
  409. input_ids=None,
  410. past_key_values=None,
  411. attention_mask=None,
  412. position_ids=None,
  413. head_mask=None,
  414. inputs_embeds=None,
  415. labels=None,
  416. use_cache=None,
  417. output_attentions=None,
  418. output_hidden_states=None,
  419. return_dict=None,
  420. ) -> Union[Tuple[torch.Tensor], SequenceClassifierOutputWithPast]:
  421. r"""
  422. labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  423. Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
  424. config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
  425. `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
  426. """
  427. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  428. transformer_outputs = self.transformer(
  429. input_ids,
  430. past_key_values=past_key_values,
  431. attention_mask=attention_mask,
  432. position_ids=position_ids,
  433. head_mask=head_mask,
  434. inputs_embeds=inputs_embeds,
  435. use_cache=use_cache,
  436. output_attentions=output_attentions,
  437. output_hidden_states=output_hidden_states,
  438. return_dict=return_dict,
  439. )
  440. hidden_states = transformer_outputs[0]
  441. logits = self.score(hidden_states)
  442. if input_ids is not None:
  443. batch_size = input_ids.shape[0]
  444. else:
  445. batch_size = inputs_embeds.shape[0]
  446. if self.config.pad_token_id is None and batch_size != 1:
  447. raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
  448. if self.config.pad_token_id is None:
  449. sequence_lengths = -1
  450. else:
  451. if input_ids is not None:
  452. sequence_lengths = torch.ne(input_ids, self.config.pad_token_id).sum(-1) - 1
  453. else:
  454. sequence_lengths = -1
  455. logger.warning(
  456. f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
  457. "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
  458. )
  459. pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
  460. loss = None
  461. if labels is not None:
  462. if self.config.problem_type is None:
  463. if self.num_labels == 1:
  464. self.config.problem_type = "regression"
  465. elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
  466. self.config.problem_type = "single_label_classification"
  467. else:
  468. self.config.problem_type = "multi_label_classification"
  469. if self.config.problem_type == "regression":
  470. loss_fct = MSELoss()
  471. if self.num_labels == 1:
  472. loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
  473. else:
  474. loss = loss_fct(pooled_logits, labels)
  475. elif self.config.problem_type == "single_label_classification":
  476. loss_fct = CrossEntropyLoss()
  477. loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
  478. elif self.config.problem_type == "multi_label_classification":
  479. loss_fct = BCEWithLogitsLoss()
  480. loss = loss_fct(pooled_logits, labels)
  481. if not return_dict:
  482. output = (pooled_logits,) + transformer_outputs[1:]
  483. return ((loss,) + output) if loss is not None else output
  484. return SequenceClassifierOutputWithPast(
  485. loss=loss,
  486. logits=pooled_logits,
  487. past_key_values=transformer_outputs.past_key_values,
  488. hidden_states=transformer_outputs.hidden_states,
  489. attentions=transformer_outputs.attentions,
  490. )