text_classification.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. # Copyright 2019 Facebook AI Research and the HuggingFace Inc. team.
  2. # Copyright (c) 2018, NVIDIA CORPORATION.
  3. # Copyright 2021-2022 The Alibaba DAMO NLP Team Authors.
  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. from transformers import RobertaForSequenceClassification
  18. from modelscope.metainfo import Models
  19. from modelscope.models import Model, TorchModel
  20. from modelscope.models.builder import MODELS
  21. from modelscope.outputs import AttentionTextClassificationModelOutput
  22. from modelscope.utils.constant import Tasks
  23. from modelscope.utils.nlp.utils import parse_labels_in_order
  24. from .configuration import VecoConfig
  25. @MODELS.register_module(Tasks.nli, module_name=Models.veco)
  26. @MODELS.register_module(
  27. Tasks.sentiment_classification, module_name=Models.veco)
  28. @MODELS.register_module(Tasks.sentence_similarity, module_name=Models.veco)
  29. @MODELS.register_module(Tasks.text_classification, module_name=Models.veco)
  30. class VecoForSequenceClassification(TorchModel,
  31. RobertaForSequenceClassification):
  32. """Veco Model transformer with a sequence classification/regression head on top (a linear layer on top of the
  33. pooled output) e.g. for GLUE tasks.
  34. This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic
  35. methods the library implements for all its model (such as downloading or saving, resizing the input embeddings,
  36. pruning heads etc.)
  37. This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)
  38. subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to
  39. general usage and behavior.
  40. Preprocessor:
  41. This is the text classification model of Veco, the preprocessor of this model
  42. is `modelscope.preprocessors.TextClassificationTransformersPreprocessor`.
  43. Trainer:
  44. This model should be trained by dataset which has mixed languages,
  45. and evaluated by datasets of languages one by one.
  46. For example, if the training dataset is xnli (which has sub datasets of multiple languages), then you
  47. should mix the sub-datasets with the languages you want to train to one training dataset, and evaluate
  48. the model one sub-dataset by one sub-dataset of different languages.
  49. This procedure can be done by custom code. If you are using trainer of ModelScope,
  50. the `VecoTrainer` is suggested to use to train this model. This trainer overrides the basic evaluation
  51. loop, and will call the evaluation dataset one by one. Besides, this trainer will use the `VecoTaskDataset`
  52. to mix the input datasets to one, you can check the API Doc for the details.
  53. To check the complete example please
  54. view the unittest `test_veco_xnli` in `tests.trainers.test_finetune_sequence_classification.py`
  55. Parameters:
  56. config ([`VecoConfig`]): Model configuration class with all the parameters of the
  57. model. Initializing with a config file does not load the weights associated with the model, only the
  58. configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model
  59. weights.
  60. This class overrides [`RobertaForSequenceClassification`]. Please check the superclass for the
  61. appropriate documentation alongside usage examples.
  62. """
  63. config_class = VecoConfig
  64. def __init__(self, config, **kwargs):
  65. super().__init__(config.name_or_path, **kwargs)
  66. super(Model, self).__init__(config)
  67. def forward(self, *args, **kwargs):
  68. """
  69. Returns:
  70. Returns `modelscope.outputs.AttentionTextClassificationModelOutput`
  71. Examples:
  72. >>> from modelscope.models import Model
  73. >>> from modelscope.preprocessors import Preprocessor
  74. >>> model = Model.from_pretrained('damo/nlp_veco_fill-mask-large',
  75. >>> task='text-classification', num_labels=2)
  76. >>> preprocessor = Preprocessor.from_pretrained('damo/nlp_veco_fill-mask-large',
  77. >>> label2id={'0': 0, '1': 1})
  78. >>> # Call the model, return some tensors
  79. >>> print(model(**preprocessor('这是个测试')))
  80. >>> # Call the pipeline, the result may be incorrect
  81. >>> from modelscope.pipelines import pipeline
  82. >>> pipeline_ins = pipeline('text-classification', pipeline_name='text-classification',
  83. >>> model=model, preprocessor=preprocessor)
  84. >>> print(pipeline_ins('这是个测试'))
  85. """
  86. kwargs['return_dict'] = True
  87. outputs = super(Model, self).forward(*args, **kwargs)
  88. return AttentionTextClassificationModelOutput(
  89. loss=outputs.loss,
  90. logits=outputs.logits,
  91. hidden_states=outputs.hidden_states,
  92. attentions=outputs.attentions,
  93. )
  94. @classmethod
  95. def _instantiate(cls, **kwargs):
  96. """Instantiate the model.
  97. Args:
  98. kwargs: Input args.
  99. model_dir: The model dir used to load the checkpoint and the label information.
  100. num_labels: An optional arg to tell the model how many classes to initialize.
  101. Method will call utils.parse_label_mapping if num_labels is not input.
  102. label2id: An optional label2id mapping, which will cover the label2id in configuration (if exists).
  103. Returns:
  104. The loaded model, which is initialized by transformers.PreTrainedModel.from_pretrained
  105. """
  106. model_dir = kwargs.pop('model_dir', None)
  107. cfg = kwargs.pop('cfg', None)
  108. model_args = parse_labels_in_order(model_dir, cfg, **kwargs)
  109. if model_dir is None:
  110. config = VecoConfig(**model_args)
  111. model = cls(config)
  112. else:
  113. model = super(Model, cls).from_pretrained(
  114. pretrained_model_name_or_path=model_dir, **model_args)
  115. return model