classification.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. # coding=utf-8
  2. # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """Classification model."""
  16. import torch
  17. from megatron import get_args, print_rank_last
  18. from megatron import mpu
  19. from megatron.model.enums import AttnMaskType
  20. from megatron.model.bert_model import bert_extended_attention_mask, bert_position_ids
  21. from megatron.model.language_model import get_language_model
  22. from megatron.model.utils import get_linear_layer
  23. from megatron.model.utils import init_method_normal
  24. from megatron.model.utils import scaled_init_method_normal
  25. from .module import MegatronModule
  26. class Classification(MegatronModule):
  27. def __init__(self,
  28. num_classes,
  29. num_tokentypes=2,
  30. pre_process=True,
  31. post_process=True):
  32. super(Classification, self).__init__(share_word_embeddings=False)
  33. args = get_args()
  34. self.num_classes = num_classes
  35. self.pre_process = pre_process
  36. self.post_process = post_process
  37. init_method = init_method_normal(args.init_method_std)
  38. self.language_model, self._language_model_key = get_language_model(
  39. num_tokentypes=num_tokentypes,
  40. add_pooler=True,
  41. encoder_attn_mask_type=AttnMaskType.padding,
  42. init_method=init_method,
  43. scaled_init_method=scaled_init_method_normal(args.init_method_std,
  44. args.num_layers),
  45. pre_process=self.pre_process,
  46. post_process=self.post_process)
  47. # Multi-choice head.
  48. if self.post_process:
  49. self.classification_dropout = torch.nn.Dropout(args.hidden_dropout)
  50. self.classification_head = get_linear_layer(args.hidden_size,
  51. self.num_classes,
  52. init_method)
  53. self._classification_head_key = 'classification_head'
  54. def set_input_tensor(self, input_tensor):
  55. """See megatron.model.transformer.set_input_tensor()"""
  56. self.language_model.set_input_tensor(input_tensor)
  57. def forward(self, model_input, attention_mask, tokentype_ids=None):
  58. extended_attention_mask = bert_extended_attention_mask(attention_mask)
  59. input_ids = model_input
  60. position_ids = bert_position_ids(input_ids)
  61. lm_output = self.language_model(
  62. input_ids,
  63. position_ids,
  64. extended_attention_mask,
  65. tokentype_ids=tokentype_ids
  66. )
  67. if self.post_process:
  68. _, pooled_output = lm_output
  69. classification_output = self.classification_dropout(pooled_output)
  70. classification_logits = self.classification_head(classification_output)
  71. # Reshape back to separate choices.
  72. classification_logits = classification_logits.view(-1, self.num_classes)
  73. return classification_logits
  74. return lm_output
  75. def state_dict_for_save_checkpoint(self, destination=None, prefix='',
  76. keep_vars=False):
  77. """For easy load when model is combined with other heads,
  78. add an extra key."""
  79. state_dict_ = {}
  80. state_dict_[self._language_model_key] \
  81. = self.language_model.state_dict_for_save_checkpoint(
  82. destination, prefix, keep_vars)
  83. if self.post_process:
  84. state_dict_[self._classification_head_key] \
  85. = self.classification_head.state_dict(
  86. destination, prefix, keep_vars)
  87. return state_dict_
  88. def load_state_dict(self, state_dict, strict=True):
  89. """Customized load."""
  90. self.language_model.load_state_dict(
  91. state_dict[self._language_model_key], strict=strict)
  92. if self.post_process:
  93. if self._classification_head_key in state_dict:
  94. self.classification_head.load_state_dict(
  95. state_dict[self._classification_head_key], strict=strict)
  96. else:
  97. print_rank_last('***WARNING*** could not find {} in the checkpoint, '
  98. 'initializing to random'.format(
  99. self._classification_head_key))