token_classification.py 4.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. import torch
  18. from transformers import RobertaForTokenClassification
  19. from modelscope.metainfo import Models
  20. from modelscope.models import Model, TorchModel
  21. from modelscope.models.builder import MODELS
  22. from modelscope.outputs import AttentionTokenClassificationModelOutput
  23. from modelscope.utils.constant import Tasks
  24. from modelscope.utils.nlp.utils import parse_labels_in_order
  25. from .configuration import VecoConfig
  26. @MODELS.register_module(Tasks.token_classification, module_name=Models.veco)
  27. class VecoForTokenClassification(TorchModel, RobertaForTokenClassification):
  28. """Veco Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g.
  29. for Named-Entity-Recognition (NER) tasks.
  30. This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic
  31. methods the library implements for all its model (such as downloading or saving, resizing the input embeddings,
  32. pruning heads etc.)
  33. This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)
  34. subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to
  35. general usage and behavior.
  36. Parameters:
  37. config ([`VecoConfig`]): Model configuration class with all the parameters of the
  38. model. Initializing with a config file does not load the weights associated with the model, only the
  39. configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model
  40. weights.
  41. This class overrides [`RobertaForTokenClassification`]. Please check the superclass for the
  42. appropriate documentation alongside usage examples.
  43. """
  44. config_class = VecoConfig
  45. def __init__(self, config, **kwargs):
  46. super().__init__(config.name_or_path, **kwargs)
  47. super(Model, self).__init__(config)
  48. def forward(self, *args, **kwargs):
  49. kwargs['return_dict'] = True
  50. outputs = super(Model, self).forward(*args, **kwargs)
  51. return AttentionTokenClassificationModelOutput(
  52. loss=outputs.loss,
  53. logits=outputs.logits,
  54. hidden_states=outputs.hidden_states,
  55. attentions=outputs.attentions,
  56. )
  57. @classmethod
  58. def _instantiate(cls, **kwargs):
  59. """Instantiate the model.
  60. Args:
  61. kwargs: Input args.
  62. model_dir: The model dir used to load the checkpoint and the label information.
  63. num_labels: An optional arg to tell the model how many classes to initialize.
  64. Method will call utils.parse_label_mapping if num_labels is not input.
  65. label2id: An optional label2id mapping, which will cover the label2id in configuration (if exists).
  66. Returns:
  67. The loaded model, which is initialized by transformers.PreTrainedModel.from_pretrained
  68. """
  69. model_dir = kwargs.pop('model_dir', None)
  70. cfg = kwargs.pop('cfg', None)
  71. model_args = parse_labels_in_order(model_dir, cfg, **kwargs)
  72. if model_dir is None:
  73. config = VecoConfig(**model_args)
  74. model = cls(config)
  75. else:
  76. model = super(Model, cls).from_pretrained(
  77. pretrained_model_name_or_path=model_dir, **model_args)
  78. return model