multiple_choice.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  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. """Multiple choice 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 MultipleChoice(MegatronModule):
  27. def __init__(self,
  28. num_tokentypes=2,
  29. pre_process=True,
  30. post_process=True):
  31. super(MultipleChoice, self).__init__(share_word_embeddings=False)
  32. args = get_args()
  33. init_method = init_method_normal(args.init_method_std)
  34. self.pre_process = pre_process
  35. self.post_process = post_process
  36. self.language_model, self._language_model_key = get_language_model(
  37. num_tokentypes=num_tokentypes,
  38. add_pooler=True,
  39. encoder_attn_mask_type=AttnMaskType.padding,
  40. init_method=init_method,
  41. scaled_init_method=scaled_init_method_normal(args.init_method_std,
  42. args.num_layers),
  43. pre_process=self.pre_process,
  44. post_process=self.post_process)
  45. # Multi-choice head.
  46. if self.post_process:
  47. self.multichoice_dropout = torch.nn.Dropout(args.hidden_dropout)
  48. self.multichoice_head = get_linear_layer(args.hidden_size, 1,
  49. init_method)
  50. self._multichoice_head_key = 'multichoice_head'
  51. def set_input_tensor(self, input_tensor):
  52. """See megatron.model.transformer.set_input_tensor()"""
  53. self.language_model.set_input_tensor(input_tensor)
  54. def forward(self, model_input, attention_mask, tokentype_ids=None):
  55. # [batch, choices, sequence] --> [batch * choices, sequence] -->
  56. # transformer --> [batch, choices] --> softmax
  57. # Ensure the shape is [batch-size, choices, sequence]
  58. assert len(attention_mask.shape) == 3
  59. num_choices = attention_mask.shape[1]
  60. # Reshape and treat choice dimension the same as batch.
  61. attention_mask = attention_mask.view(-1, attention_mask.size(-1))
  62. extended_attention_mask = bert_extended_attention_mask(attention_mask)
  63. input_ids = model_input
  64. # Do the same as attention_mask for input_ids, tokentype_ids
  65. assert len(input_ids.shape) == 3
  66. assert len(tokentype_ids.shape) == 3
  67. input_ids = input_ids.view(-1, input_ids.size(-1))
  68. tokentype_ids = tokentype_ids.view(-1, tokentype_ids.size(-1))
  69. position_ids = bert_position_ids(input_ids)
  70. lm_output = self.language_model(
  71. input_ids,
  72. position_ids,
  73. extended_attention_mask,
  74. tokentype_ids=tokentype_ids
  75. )
  76. if self.post_process:
  77. _, pooled_output = lm_output
  78. multichoice_output = self.multichoice_dropout(pooled_output)
  79. multichoice_logits = self.multichoice_head(multichoice_output)
  80. # Reshape back to separate choices.
  81. multichoice_logits = multichoice_logits.view(-1, num_choices)
  82. return multichoice_logits
  83. return lm_output
  84. def state_dict_for_save_checkpoint(self, destination=None, prefix='',
  85. keep_vars=False):
  86. """For easy load when model is combined with other heads,
  87. add an extra key."""
  88. state_dict_ = {}
  89. state_dict_[self._language_model_key] \
  90. = self.language_model.state_dict_for_save_checkpoint(
  91. destination, prefix, keep_vars)
  92. if self.post_process:
  93. state_dict_[self._multichoice_head_key] \
  94. = self.multichoice_head.state_dict(
  95. destination, prefix, keep_vars)
  96. return state_dict_
  97. def load_state_dict(self, state_dict, strict=True):
  98. """Customized load."""
  99. self.language_model.load_state_dict(
  100. state_dict[self._language_model_key], strict=strict)
  101. if self.post_process:
  102. if self._multichoice_head_key in state_dict:
  103. self.multichoice_head.load_state_dict(
  104. state_dict[self._multichoice_head_key], strict=strict)
  105. else:
  106. print_rank_last('***WARNING*** could not find {} in the checkpoint, '
  107. 'initializing to random'.format(
  108. self._multichoice_head_key))