text_classification.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. # Copyright 2021-2022 The Alibaba DAMO NLP Team Authors.
  2. # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
  3. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
  4. # All rights reserved.
  5. #
  6. # Licensed under the Apache License, Version 2.0 (the "License");
  7. # you may not use this file except in compliance with the License.
  8. # You may obtain a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing, software
  13. # distributed under the License is distributed on an "AS IS" BASIS,
  14. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. # See the License for the specific language governing permissions and
  16. # limitations under the License.
  17. import torch
  18. import torch.nn as nn
  19. import torch.utils.checkpoint
  20. from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
  21. from modelscope.metainfo import Models
  22. from modelscope.models.builder import MODELS
  23. from modelscope.outputs import AttentionTextClassificationModelOutput
  24. from modelscope.utils import logger as logging
  25. from modelscope.utils.constant import Tasks
  26. from .adv_utils import compute_adv_loss
  27. from .backbone import SbertModel, SbertPreTrainedModel
  28. from .configuration import SbertConfig
  29. logger = logging.get_logger()
  30. @MODELS.register_module(
  31. Tasks.text_classification, module_name=Models.structbert)
  32. @MODELS.register_module(Tasks.nli, module_name=Models.structbert)
  33. @MODELS.register_module(
  34. Tasks.sentiment_classification, module_name=Models.structbert)
  35. @MODELS.register_module(
  36. Tasks.sentence_similarity, module_name=Models.structbert)
  37. @MODELS.register_module(
  38. Tasks.zero_shot_classification, module_name=Models.structbert)
  39. class SbertForSequenceClassification(SbertPreTrainedModel):
  40. r"""StructBERT Model transformer with a sequence classification/regression head on top
  41. (a linear layer on top of the pooled output) e.g. for GLUE tasks.
  42. This model inherits from :class:`~transformers.PreTrainedModel`. Check the superclass documentation for the generic
  43. methods the library implements for all its model (such as downloading or saving, resizing the input embeddings,
  44. pruning heads etc.)
  45. This model is also a PyTorch `torch.nn.Module <https://pytorch.org/docs/stable/nn.html#torch.nn.Module>`__
  46. subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to
  47. general usage and behavior.
  48. Preprocessor:
  49. This is the text classification model of StructBERT, the preprocessor of this model
  50. is `modelscope.preprocessors.TextClassificationTransformersPreprocessor`.
  51. Trainer:
  52. This model is a normal PyTorch model, and can be trained by variable trainers, like EpochBasedTrainer,
  53. NlpEpochBasedTrainer, or trainers from other frameworks.
  54. The preferred trainer in ModelScope is NlpEpochBasedTrainer.
  55. Parameters:
  56. config (:class:`~modelscope.models.nlp.structbert.SbertConfig`): Model configuration class with
  57. all the parameters of the model.
  58. Initializing with a config file does not load the weights associated with the model, only the
  59. configuration. Check out the :meth:`~transformers.PreTrainedModel.from_pretrained` method to load the model
  60. weights.
  61. """
  62. def __init__(self, config: SbertConfig, **kwargs):
  63. super().__init__(config)
  64. self.num_labels = config.num_labels
  65. self.config = config
  66. if self.config.adv_grad_factor is None:
  67. logger.warning(
  68. 'Adv parameters not set, skipping compute_adv_loss.')
  69. SbertForSequenceClassification.base_model_prefix = getattr(
  70. config, 'base_model_prefix',
  71. SbertForSequenceClassification.base_model_prefix)
  72. setattr(self, self.base_model_prefix, SbertModel(config))
  73. classifier_dropout = (
  74. config.classifier_dropout if config.classifier_dropout is not None
  75. else config.hidden_dropout_prob)
  76. self.dropout = nn.Dropout(classifier_dropout)
  77. self.classifier = nn.Linear(config.hidden_size, config.num_labels)
  78. self.init_weights()
  79. def _forward_call(self, **kwargs):
  80. outputs = self.base_model(**kwargs)
  81. pooled_output = outputs[1]
  82. pooled_output = self.dropout(pooled_output)
  83. logits = self.classifier(pooled_output)
  84. outputs['logits'] = logits
  85. outputs.kwargs = kwargs
  86. return outputs
  87. def forward(self,
  88. input_ids=None,
  89. attention_mask=None,
  90. token_type_ids=None,
  91. position_ids=None,
  92. head_mask=None,
  93. inputs_embeds=None,
  94. labels=None,
  95. output_attentions=None,
  96. output_hidden_states=None,
  97. return_dict=None,
  98. *args,
  99. **kwargs):
  100. r"""
  101. Args:
  102. input_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`):
  103. Indices of input sequence tokens in the vocabulary.
  104. Indices can be obtained using :class:`~modelscope.models.nlp.structbert.SbertTokenizer`. See
  105. :meth:`transformers.PreTrainedTokenizer.encode` and :meth:`transformers.PreTrainedTokenizer.__call__`
  106. for details.
  107. attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
  108. Mask to avoid performing attention on padding token indices. Mask values selected in ``[0, 1]``:
  109. - 1 for tokens that are **not masked**,
  110. - 0 for tokens that are **masked**.
  111. token_type_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
  112. Segment token indices to indicate first and second portions of the inputs. Indices are selected in ``[0,
  113. 1]``:
  114. - 0 corresponds to a `sentence A` token,
  115. - 1 corresponds to a `sentence B` token.
  116. position_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
  117. Indices of positions of each input sequence tokens in the position embeddings. Selected in the range
  118. ``[0, config.max_position_embeddings - 1]``.
  119. head_mask (:obj:`torch.FloatTensor` of shape :obj:`(num_heads,)` or :obj:`(num_layers, num_heads)`,
  120. `optional`):
  121. Mask to nullify selected heads of the self-attention modules. Mask values selected in ``[0, 1]``:
  122. - 1 indicates the head is **not masked**,
  123. - 0 indicates the head is **masked**.
  124. inputs_embeds (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`,
  125. `optional`):
  126. Optionally, instead of passing :obj:`input_ids` you can choose to directly pass an embedded
  127. representation. This is useful if you want more control over how to convert :obj:`input_ids` indices
  128. into associated vectors than the model's internal embedding lookup matrix.
  129. output_attentions (:obj:`bool`, `optional`):
  130. Whether or not to return the attentions tensors of all attention layers. See ``attentions`` under
  131. returned tensors for more detail.
  132. output_hidden_states (:obj:`bool`, `optional`):
  133. Whether or not to return the hidden states of all layers. See ``hidden_states`` under returned tensors
  134. for more detail.
  135. return_dict (:obj:`bool`, `optional`):
  136. Whether or not to return a :class:`~transformers.ModelOutput` instead of a plain tuple.
  137. labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`):
  138. Labels for computing the sequence classification/regression loss. Indices should be in :obj:`[0, ...,
  139. config.num_labels - 1]`. If :obj:`config.num_labels == 1` a regression loss is computed
  140. (Mean-Square loss), If :obj:`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
  141. Returns:
  142. Returns `modelscope.outputs.AttentionTextClassificationModelOutput`
  143. Examples:
  144. >>> from modelscope.models import Model
  145. >>> from modelscope.preprocessors import Preprocessor
  146. >>> model = Model.from_pretrained('damo/nlp_structbert_sentence-similarity_chinese-base')
  147. >>> preprocessor = Preprocessor.from_pretrained('damo/nlp_structbert_sentence-similarity_chinese-base')
  148. >>> # Call the model, return some tensors
  149. >>> print(model(**preprocessor(('这是个测试', '这也是个测试'))))
  150. >>> # Call the pipeline
  151. >>> from modelscope.pipelines import pipeline
  152. >>> pipeline_ins = pipeline('text-classification', model=model, preprocessor=preprocessor)
  153. >>> print(pipeline_ins(('这是个测试', '这也是个测试')))
  154. """
  155. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  156. if not return_dict:
  157. logger.error('Return tuple in sbert is not supported now.')
  158. outputs = self._forward_call(
  159. input_ids=input_ids,
  160. attention_mask=attention_mask,
  161. token_type_ids=token_type_ids,
  162. position_ids=position_ids,
  163. head_mask=head_mask,
  164. inputs_embeds=inputs_embeds,
  165. output_attentions=output_attentions,
  166. output_hidden_states=output_hidden_states,
  167. return_dict=return_dict)
  168. return self.compute_loss(outputs, labels, **outputs.kwargs)
  169. def compute_loss(self, outputs, labels, **kwargs):
  170. logits = outputs.logits
  171. embedding_output = outputs.embedding_output
  172. loss = None
  173. if labels is not None:
  174. if self.config.problem_type is None:
  175. if self.num_labels == 1:
  176. self.config.problem_type = 'regression'
  177. elif self.num_labels > 1 and (labels.dtype == torch.long
  178. or labels.dtype == torch.int):
  179. self.config.problem_type = 'single_label_classification'
  180. else:
  181. self.config.problem_type = 'multi_label_classification'
  182. if self.config.problem_type == 'regression':
  183. loss_fct = MSELoss()
  184. if self.num_labels == 1:
  185. loss = loss_fct(logits.squeeze(), labels.squeeze())
  186. else:
  187. loss = loss_fct(logits, labels)
  188. elif self.config.problem_type == 'single_label_classification':
  189. loss_fct = CrossEntropyLoss()
  190. loss = loss_fct(
  191. logits.view(-1, self.num_labels), labels.view(-1))
  192. if self.config.adv_grad_factor is not None and self.training:
  193. loss = compute_adv_loss(
  194. embedding=embedding_output,
  195. model=self._forward_call,
  196. ori_logits=logits,
  197. ori_loss=loss,
  198. adv_bound=self.config.adv_bound,
  199. adv_grad_factor=self.config.adv_grad_factor,
  200. sigma=self.config.sigma,
  201. **kwargs)
  202. elif self.config.problem_type == 'multi_label_classification':
  203. loss_fct = BCEWithLogitsLoss()
  204. loss = loss_fct(logits, labels)
  205. return AttentionTextClassificationModelOutput(
  206. loss=loss,
  207. logits=logits,
  208. hidden_states=outputs.hidden_states,
  209. attentions=outputs.attentions,
  210. )