backbone.py 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897
  1. # Copyright (c) Alibaba, Inc. and its affiliates.
  2. # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
  3. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. """ PyTorch MegatronBERT model."""
  17. import math
  18. import torch
  19. import torch.utils.checkpoint
  20. from torch import nn
  21. from transformers.activations import ACT2FN
  22. from transformers.modeling_utils import PreTrainedModel
  23. from modelscope.metainfo import Models
  24. from modelscope.models import Model, TorchModel
  25. from modelscope.models.builder import MODELS
  26. from modelscope.outputs import AttentionBackboneModelOutput
  27. from modelscope.utils.constant import Tasks
  28. from modelscope.utils.logger import get_logger
  29. from modelscope.utils.nlp.utils import parse_labels_in_order
  30. from modelscope.utils.torch_utils import (apply_chunking_to_forward,
  31. find_pruneable_heads_and_indices,
  32. prune_linear_layer)
  33. from .configuration import MegatronBertConfig
  34. logger = get_logger()
  35. _CONFIG_FOR_DOC = 'MegatronBertConfig'
  36. class MegatronBertEmbeddings(nn.Module):
  37. """Construct the embeddings from word, position and token_type embeddings."""
  38. def __init__(self, config):
  39. super().__init__()
  40. self.word_embeddings = nn.Embedding(
  41. config.vocab_size,
  42. config.hidden_size,
  43. padding_idx=config.pad_token_id)
  44. self.position_embeddings = nn.Embedding(config.max_position_embeddings,
  45. config.hidden_size)
  46. self.token_type_embeddings = nn.Embedding(config.type_vocab_size,
  47. config.hidden_size)
  48. # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
  49. # any TensorFlow checkpoint file
  50. # In Megatron, layer-norm is applied after the 1st dropout.
  51. # self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  52. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  53. # position_ids (1, len position emb) is contiguous in memory and exported when serialized
  54. self.register_buffer(
  55. 'position_ids',
  56. torch.arange(config.max_position_embeddings).expand((1, -1)))
  57. self.position_embedding_type = getattr(config,
  58. 'position_embedding_type',
  59. 'absolute')
  60. def forward(
  61. self,
  62. input_ids=None,
  63. token_type_ids=None,
  64. position_ids=None,
  65. inputs_embeds=None,
  66. past_key_values_length=0,
  67. ) -> torch.Tensor:
  68. if input_ids is not None:
  69. input_shape = input_ids.size()
  70. else:
  71. input_shape = inputs_embeds.size()[:-1]
  72. seq_length = input_shape[1]
  73. if position_ids is None:
  74. position_ids = self.position_ids[:,
  75. past_key_values_length:seq_length
  76. + past_key_values_length]
  77. if token_type_ids is None:
  78. token_type_ids = torch.zeros(
  79. input_shape, dtype=torch.long, device=self.position_ids.device)
  80. if inputs_embeds is None:
  81. inputs_embeds = self.word_embeddings(input_ids)
  82. token_type_embeddings = self.token_type_embeddings(token_type_ids)
  83. embeddings = inputs_embeds + token_type_embeddings
  84. if self.position_embedding_type == 'absolute':
  85. position_embeddings = self.position_embeddings(position_ids)
  86. embeddings += position_embeddings
  87. # Megatron BERT moves that layer norm after the drop-out (and to each layer).
  88. # embeddings = self.LayerNorm(embeddings)
  89. embeddings = self.dropout(embeddings)
  90. return embeddings
  91. # Copied from transformers.models.bert.modeling_bert.BertSelfAttention with Bert->MegatronBert
  92. class MegatronBertSelfAttention(nn.Module):
  93. def __init__(self, config, position_embedding_type=None):
  94. super().__init__()
  95. if config.hidden_size % config.num_attention_heads != 0 and not hasattr(
  96. config, 'embedding_size'):
  97. raise ValueError(
  98. f'The hidden size ({config.hidden_size}) is not a multiple of the number of attention '
  99. f'heads ({config.num_attention_heads})')
  100. self.num_attention_heads = config.num_attention_heads
  101. self.attention_head_size = int(config.hidden_size
  102. / config.num_attention_heads)
  103. self.all_head_size = self.num_attention_heads * self.attention_head_size
  104. self.query = nn.Linear(config.hidden_size, self.all_head_size)
  105. self.key = nn.Linear(config.hidden_size, self.all_head_size)
  106. self.value = nn.Linear(config.hidden_size, self.all_head_size)
  107. self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
  108. self.position_embedding_type = position_embedding_type or getattr(
  109. config, 'position_embedding_type', 'absolute')
  110. if self.position_embedding_type == 'relative_key' or self.position_embedding_type == 'relative_key_query':
  111. self.max_position_embeddings = config.max_position_embeddings
  112. self.distance_embedding = nn.Embedding(
  113. 2 * config.max_position_embeddings - 1,
  114. self.attention_head_size)
  115. self.is_decoder = config.is_decoder
  116. def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor:
  117. new_x_shape = x.size()[:-1] + (self.num_attention_heads,
  118. self.attention_head_size)
  119. x = x.view(new_x_shape)
  120. return x.permute(0, 2, 1, 3)
  121. def forward(
  122. self,
  123. hidden_states,
  124. attention_mask=None,
  125. head_mask=None,
  126. encoder_hidden_states=None,
  127. encoder_attention_mask=None,
  128. past_key_value=None,
  129. output_attentions=False,
  130. ):
  131. mixed_query_layer = self.query(hidden_states)
  132. # If this is instantiated as a cross-attention module, the keys
  133. # and values come from an encoder; the attention mask needs to be
  134. # such that the encoder's padding tokens are not attended to.
  135. is_cross_attention = encoder_hidden_states is not None
  136. if is_cross_attention and past_key_value is not None:
  137. # reuse k,v, cross_attentions
  138. key_layer = past_key_value[0]
  139. value_layer = past_key_value[1]
  140. attention_mask = encoder_attention_mask
  141. elif is_cross_attention:
  142. key_layer = self.transpose_for_scores(
  143. self.key(encoder_hidden_states))
  144. value_layer = self.transpose_for_scores(
  145. self.value(encoder_hidden_states))
  146. attention_mask = encoder_attention_mask
  147. elif past_key_value is not None:
  148. key_layer = self.transpose_for_scores(self.key(hidden_states))
  149. value_layer = self.transpose_for_scores(self.value(hidden_states))
  150. key_layer = torch.cat([past_key_value[0], key_layer], dim=2)
  151. value_layer = torch.cat([past_key_value[1], value_layer], dim=2)
  152. else:
  153. key_layer = self.transpose_for_scores(self.key(hidden_states))
  154. value_layer = self.transpose_for_scores(self.value(hidden_states))
  155. query_layer = self.transpose_for_scores(mixed_query_layer)
  156. if self.is_decoder:
  157. # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
  158. # Further calls to cross_attention layer can then reuse all cross-attention
  159. # key/value_states (first "if" case)
  160. # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
  161. # all previous decoder key/value_states. Further calls to uni-directional self-attention
  162. # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
  163. # if encoder bi-directional self-attention `past_key_value` is always `None`
  164. past_key_value = (key_layer, value_layer)
  165. # Take the dot product between "query" and "key" to get the raw attention scores.
  166. attention_scores = torch.matmul(query_layer,
  167. key_layer.transpose(-1, -2))
  168. if self.position_embedding_type == 'relative_key' or self.position_embedding_type == 'relative_key_query':
  169. seq_length = hidden_states.size()[1]
  170. position_ids_l = torch.arange(
  171. seq_length, dtype=torch.long,
  172. device=hidden_states.device).view(-1, 1)
  173. position_ids_r = torch.arange(
  174. seq_length, dtype=torch.long,
  175. device=hidden_states.device).view(1, -1)
  176. distance = position_ids_l - position_ids_r
  177. positional_embedding = self.distance_embedding(
  178. distance + self.max_position_embeddings - 1)
  179. positional_embedding = positional_embedding.to(
  180. dtype=query_layer.dtype) # fp16 compatibility
  181. if self.position_embedding_type == 'relative_key':
  182. relative_position_scores = torch.einsum(
  183. 'bhld,lrd->bhlr', query_layer, positional_embedding)
  184. attention_scores = attention_scores + relative_position_scores
  185. elif self.position_embedding_type == 'relative_key_query':
  186. relative_position_scores_query = torch.einsum(
  187. 'bhld,lrd->bhlr', query_layer, positional_embedding)
  188. relative_position_scores_key = torch.einsum(
  189. 'bhrd,lrd->bhlr', key_layer, positional_embedding)
  190. attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key
  191. attention_scores = attention_scores / math.sqrt(
  192. self.attention_head_size)
  193. if attention_mask is not None:
  194. # Apply the attention mask is (precomputed for all layers in MegatronBertModel forward() function)
  195. attention_scores = attention_scores + attention_mask
  196. # Normalize the attention scores to probabilities.
  197. attention_probs = nn.functional.softmax(attention_scores, dim=-1)
  198. # This is actually dropping out entire tokens to attend to, which might
  199. # seem a bit unusual, but is taken from the original Transformer paper.
  200. attention_probs = self.dropout(attention_probs)
  201. # Mask heads if we want to
  202. if head_mask is not None:
  203. attention_probs = attention_probs * head_mask
  204. context_layer = torch.matmul(attention_probs, value_layer)
  205. context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
  206. new_context_layer_shape = context_layer.size()[:-2] + (
  207. self.all_head_size, )
  208. context_layer = context_layer.view(new_context_layer_shape)
  209. outputs = (context_layer,
  210. attention_probs) if output_attentions else (context_layer, )
  211. if self.is_decoder:
  212. outputs = outputs + (past_key_value, )
  213. return outputs
  214. # Based transformers.models.bert.modeling_bert.BertSelfOutput. Moved LayerNorm to MegatronBertAttention below.
  215. class MegatronBertSelfOutput(nn.Module):
  216. def __init__(self, config):
  217. super().__init__()
  218. self.dense = nn.Linear(config.hidden_size, config.hidden_size)
  219. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  220. def forward(self, hidden_states, residual):
  221. hidden_states = self.dense(hidden_states)
  222. hidden_states = self.dropout(hidden_states)
  223. return residual + hidden_states
  224. # Based transformers.models.bert.modeling_bert.BertAttention. Added LayerNorm.
  225. class MegatronBertAttention(nn.Module):
  226. def __init__(self, config):
  227. super().__init__()
  228. self.ln = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  229. self.self = MegatronBertSelfAttention(config)
  230. self.output = MegatronBertSelfOutput(config)
  231. self.pruned_heads = set()
  232. def prune_heads(self, heads):
  233. if len(heads) == 0:
  234. return
  235. heads, index = find_pruneable_heads_and_indices(
  236. heads, self.self.num_attention_heads,
  237. self.self.attention_head_size, self.pruned_heads)
  238. # Prune linear layers
  239. self.self.query = prune_linear_layer(self.self.query, index)
  240. self.self.key = prune_linear_layer(self.self.key, index)
  241. self.self.value = prune_linear_layer(self.self.value, index)
  242. self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
  243. # Update hyper params and store pruned heads
  244. self.self.num_attention_heads = self.self.num_attention_heads - len(
  245. heads)
  246. self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
  247. self.pruned_heads = self.pruned_heads.union(heads)
  248. def forward(
  249. self,
  250. hidden_states,
  251. attention_mask=None,
  252. head_mask=None,
  253. encoder_hidden_states=None,
  254. encoder_attention_mask=None,
  255. past_key_value=None,
  256. output_attentions=False,
  257. ):
  258. ln_outputs = self.ln(hidden_states)
  259. self_outputs = self.self(
  260. ln_outputs,
  261. attention_mask,
  262. head_mask,
  263. encoder_hidden_states,
  264. encoder_attention_mask,
  265. past_key_value,
  266. output_attentions,
  267. )
  268. attention_output = self.output(self_outputs[0], hidden_states)
  269. outputs = (attention_output,
  270. ) + self_outputs[1:] # add attentions if we output them
  271. return outputs
  272. # Copied from transformers.models.bert.modeling_bert.BertIntermediate with Bert->MegatronBert
  273. class MegatronBertIntermediate(nn.Module):
  274. def __init__(self, config):
  275. super().__init__()
  276. self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
  277. if isinstance(config.hidden_act, str):
  278. self.intermediate_act_fn = ACT2FN[config.hidden_act]
  279. else:
  280. self.intermediate_act_fn = config.hidden_act
  281. def forward(self, hidden_states):
  282. hidden_states = self.dense(hidden_states)
  283. hidden_states = self.intermediate_act_fn(hidden_states)
  284. return hidden_states
  285. # Based on transformers.models.bert.modeling_bert.BertOutput. Moved LayerNorm to MegatronBertLayer below.
  286. class MegatronBertOutput(nn.Module):
  287. def __init__(self, config):
  288. super().__init__()
  289. self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
  290. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  291. def forward(self, hidden_states: torch.Tensor,
  292. input_tensor: torch.Tensor) -> torch.Tensor:
  293. hidden_states = self.dense(hidden_states)
  294. hidden_states = self.dropout(hidden_states)
  295. return input_tensor + hidden_states
  296. # Based on transformers.models.bert.modeling_bert.BertLayer. Added LayerNorm.
  297. class MegatronBertLayer(nn.Module):
  298. def __init__(self, config):
  299. super().__init__()
  300. self.chunk_size_feed_forward = config.chunk_size_feed_forward
  301. self.seq_len_dim = 1
  302. self.attention = MegatronBertAttention(config)
  303. self.is_decoder = config.is_decoder
  304. self.add_cross_attention = config.add_cross_attention
  305. if self.add_cross_attention:
  306. if not self.is_decoder:
  307. raise TypeError(
  308. f'{self} should be used as a decoder model if cross attention is added'
  309. )
  310. self.crossattention = MegatronBertAttention(config)
  311. self.ln = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  312. self.intermediate = MegatronBertIntermediate(config)
  313. self.output = MegatronBertOutput(config)
  314. def forward(
  315. self,
  316. hidden_states,
  317. attention_mask=None,
  318. head_mask=None,
  319. encoder_hidden_states=None,
  320. encoder_attention_mask=None,
  321. past_key_value=None,
  322. output_attentions=False,
  323. ):
  324. # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
  325. self_attn_past_key_value = past_key_value[:
  326. 2] if past_key_value is not None else None
  327. self_attention_outputs = self.attention(
  328. hidden_states,
  329. attention_mask,
  330. head_mask,
  331. output_attentions=output_attentions,
  332. past_key_value=self_attn_past_key_value,
  333. )
  334. attention_output = self_attention_outputs[0]
  335. # if decoder, the last output is tuple of self-attn cache
  336. if self.is_decoder:
  337. outputs = self_attention_outputs[1:-1]
  338. present_key_value = self_attention_outputs[-1]
  339. else:
  340. outputs = self_attention_outputs[
  341. 1:] # add self attentions if we output attention weights
  342. cross_attn_present_key_value = None
  343. if self.is_decoder and encoder_hidden_states is not None:
  344. if not hasattr(self, 'crossattention'):
  345. raise AttributeError(
  346. f'If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers'
  347. ' by setting `config.add_cross_attention=True`')
  348. # cross_attn cached key/values tuple is at positions 3,4 of past_key_value tuple
  349. cross_attn_past_key_value = past_key_value[
  350. -2:] if past_key_value is not None else None
  351. cross_attention_outputs = self.crossattention(
  352. attention_output,
  353. attention_mask,
  354. head_mask,
  355. encoder_hidden_states,
  356. encoder_attention_mask,
  357. cross_attn_past_key_value,
  358. output_attentions,
  359. )
  360. attention_output = cross_attention_outputs[0]
  361. outputs = outputs + cross_attention_outputs[
  362. 1:-1] # add cross attentions if we output attention weights
  363. # add cross-attn cache to positions 3,4 of present_key_value tuple
  364. cross_attn_present_key_value = cross_attention_outputs[-1]
  365. present_key_value = present_key_value + cross_attn_present_key_value
  366. layer_output = apply_chunking_to_forward(self.feed_forward_chunk,
  367. self.chunk_size_feed_forward,
  368. self.seq_len_dim,
  369. attention_output)
  370. outputs = (layer_output, ) + outputs
  371. # if decoder, return the attn key/values as the last output
  372. if self.is_decoder:
  373. outputs = outputs + (present_key_value, )
  374. return outputs
  375. def feed_forward_chunk(self, attention_output):
  376. ln_output = self.ln(attention_output)
  377. intermediate_output = self.intermediate(ln_output)
  378. layer_output = self.output(intermediate_output, attention_output)
  379. return layer_output
  380. class MegatronBertEncoder(nn.Module):
  381. def __init__(self, config):
  382. super().__init__()
  383. self.config = config
  384. self.layer = nn.ModuleList([
  385. MegatronBertLayer(config) for _ in range(config.num_hidden_layers)
  386. ])
  387. # The final layer norm. We removed the 1st LN, moved LN to each hidden layer and this one
  388. # is simply the final LN (Transformer's BERT has it attached to each hidden layer).
  389. self.ln = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  390. self.gradient_checkpointing = False
  391. def forward(
  392. self,
  393. hidden_states,
  394. attention_mask=None,
  395. head_mask=None,
  396. encoder_hidden_states=None,
  397. encoder_attention_mask=None,
  398. past_key_values=None,
  399. use_cache=None,
  400. output_attentions=False,
  401. output_hidden_states=False,
  402. return_dict=True,
  403. ):
  404. all_hidden_states = () if output_hidden_states else None
  405. all_self_attentions = () if output_attentions else None
  406. all_cross_attentions = (
  407. ) if output_attentions and self.config.add_cross_attention else None
  408. next_decoder_cache = () if use_cache else None
  409. for i, layer_module in enumerate(self.layer):
  410. if output_hidden_states:
  411. all_hidden_states = all_hidden_states + (hidden_states, )
  412. layer_head_mask = head_mask[i] if head_mask is not None else None
  413. past_key_value = past_key_values[
  414. i] if past_key_values is not None else None
  415. if self.gradient_checkpointing and self.training:
  416. if use_cache:
  417. logger.warning(
  418. '`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...'
  419. )
  420. use_cache = False
  421. def create_custom_forward(module):
  422. def custom_forward(*inputs):
  423. return module(*inputs, past_key_value,
  424. output_attentions)
  425. return custom_forward
  426. layer_outputs = torch.utils.checkpoint.checkpoint(
  427. create_custom_forward(layer_module),
  428. hidden_states,
  429. attention_mask,
  430. layer_head_mask,
  431. encoder_hidden_states,
  432. encoder_attention_mask,
  433. )
  434. else:
  435. layer_outputs = layer_module(
  436. hidden_states,
  437. attention_mask,
  438. layer_head_mask,
  439. encoder_hidden_states,
  440. encoder_attention_mask,
  441. past_key_value,
  442. output_attentions,
  443. )
  444. # Because we moved the layer-norm at the end of the hidden layer, we have non-normali-
  445. # zed data here. If that's really needed, we must apply LN to match Transformer's BERT.
  446. hidden_states = layer_outputs[0]
  447. if use_cache:
  448. next_decoder_cache += (layer_outputs[-1], )
  449. if output_attentions:
  450. all_self_attentions = all_self_attentions + (
  451. layer_outputs[1], )
  452. if self.config.add_cross_attention:
  453. all_cross_attentions = all_cross_attentions + (
  454. layer_outputs[2], )
  455. # Finalize the hidden states.
  456. hidden_states = self.ln(hidden_states)
  457. if output_hidden_states:
  458. all_hidden_states = all_hidden_states + (hidden_states, )
  459. if not return_dict:
  460. return tuple(v for v in [
  461. hidden_states,
  462. next_decoder_cache,
  463. all_hidden_states,
  464. all_self_attentions,
  465. all_cross_attentions,
  466. ] if v is not None)
  467. return AttentionBackboneModelOutput(
  468. last_hidden_state=hidden_states,
  469. past_key_values=next_decoder_cache,
  470. hidden_states=all_hidden_states,
  471. attentions=all_self_attentions,
  472. cross_attentions=all_cross_attentions,
  473. )
  474. # Copied from transformers.models.bert.modeling_bert.BertPooler with Bert->MegatronBert
  475. class MegatronBertPooler(nn.Module):
  476. def __init__(self, config):
  477. super().__init__()
  478. self.dense = nn.Linear(config.hidden_size, config.hidden_size)
  479. self.activation = nn.Tanh()
  480. def forward(self, hidden_states):
  481. # We "pool" the model by simply taking the hidden state corresponding
  482. # to the first token.
  483. first_token_tensor = hidden_states[:, 0]
  484. pooled_output = self.dense(first_token_tensor)
  485. pooled_output = self.activation(pooled_output)
  486. return pooled_output
  487. class MegatronBertPreTrainedModel(TorchModel, PreTrainedModel):
  488. """
  489. An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
  490. models.
  491. """
  492. config_class = MegatronBertConfig
  493. base_model_prefix = 'bert'
  494. supports_gradient_checkpointing = True
  495. _keys_to_ignore_on_load_missing = [r'position_ids']
  496. def __init__(self, config, **kwargs):
  497. super().__init__(config.name_or_path, **kwargs)
  498. super(Model, self).__init__(config)
  499. def _init_weights(self, module):
  500. """Initialize the weights"""
  501. if isinstance(module, (nn.Linear, nn.Embedding)):
  502. # Slightly different from the TF version which uses truncated_normal for initialization
  503. # cf https://github.com/pytorch/pytorch/pull/5617
  504. module.weight.data.normal_(
  505. mean=0.0, std=self.config.initializer_range)
  506. elif isinstance(module, nn.LayerNorm):
  507. module.bias.data.zero_()
  508. module.weight.data.fill_(1.0)
  509. if isinstance(module, nn.Linear) and module.bias is not None:
  510. module.bias.data.zero_()
  511. def _set_gradient_checkpointing(self, module, value=False):
  512. if isinstance(module, MegatronBertEncoder):
  513. module.gradient_checkpointing = value
  514. @classmethod
  515. def _instantiate(cls, **kwargs):
  516. """Instantiate the model.
  517. Args:
  518. kwargs: Input args.
  519. model_dir: The model dir used to load the checkpoint and the label information.
  520. num_labels: An optional arg to tell the model how many classes to initialize.
  521. Method will call utils.parse_label_mapping if num_labels not supplied.
  522. If num_labels is not found, the model will use the default setting (2 classes).
  523. Returns:
  524. The loaded model, which is initialized by transformers.PreTrainedModel.from_pretrained
  525. """
  526. model_dir = kwargs.pop('model_dir', None)
  527. cfg = kwargs.pop('cfg', None)
  528. model_args = parse_labels_in_order(model_dir, cfg, **kwargs)
  529. if model_dir is None:
  530. config = MegatronBertConfig(**model_args)
  531. model = cls(config)
  532. else:
  533. model = super(Model, cls).from_pretrained(
  534. pretrained_model_name_or_path=model_dir, **model_args)
  535. model.model_dir = model_dir
  536. return model
  537. @MODELS.register_module(
  538. group_key=Tasks.backbone, module_name=Models.megatron_bert)
  539. class MegatronBertModel(MegatronBertPreTrainedModel):
  540. """The bare MegatronBert Model transformer outputting raw hidden-states without any specific head on top.",
  541. This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
  542. library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
  543. etc.)
  544. This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
  545. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
  546. and behavior.
  547. Parameters:
  548. config ([`MegatronBertConfig`]): Model configuration class with all the parameters of the model.
  549. Initializing with a config file does not load the weights associated with the model, only the
  550. configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
  551. The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
  552. cross-attention is added between the self-attention layers, following the architecture described in [Attention is
  553. all you need](https://arxiv.org/abs/1706.03762) by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
  554. Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
  555. To behave as an decoder the model needs to be initialized with the `is_decoder` argument of the configuration set
  556. to `True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and
  557. `add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass.
  558. """
  559. def __init__(self, config, add_pooling_layer=True):
  560. super().__init__(config)
  561. self.config = config
  562. self.embeddings = MegatronBertEmbeddings(config)
  563. self.encoder = MegatronBertEncoder(config)
  564. self.pooler = MegatronBertPooler(config) if add_pooling_layer else None
  565. # Initialize weights and apply final processing
  566. self.post_init()
  567. def get_input_embeddings(self):
  568. return self.embeddings.word_embeddings
  569. def set_input_embeddings(self, value):
  570. self.embeddings.word_embeddings = value
  571. def _prune_heads(self, heads_to_prune):
  572. """
  573. Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
  574. class PreTrainedModel
  575. """
  576. for layer, heads in heads_to_prune.items():
  577. self.encoder.layer[layer].attention.prune_heads(heads)
  578. def forward(self,
  579. input_ids=None,
  580. attention_mask=None,
  581. token_type_ids=None,
  582. position_ids=None,
  583. head_mask=None,
  584. inputs_embeds=None,
  585. encoder_hidden_states=None,
  586. encoder_attention_mask=None,
  587. past_key_values=None,
  588. use_cache=None,
  589. output_attentions=None,
  590. output_hidden_states=None,
  591. return_dict=None,
  592. **kwargs) -> AttentionBackboneModelOutput:
  593. r"""
  594. Args:
  595. input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
  596. Indices of input sequence tokens in the vocabulary.
  597. Indices can be obtained using [`BertTokenizer`]. See
  598. [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`]
  599. for details.
  600. [What are input IDs?](../glossary#input-ids)
  601. attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
  602. Mask to avoid performing attention on padding token indices. Mask
  603. values selected in `[0, 1]`:
  604. - 1 for tokens that are **not masked**,
  605. - 0 for tokens that are **masked**.
  606. [What are attention masks?](../glossary#attention-mask)
  607. token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  608. Segment token indices to indicate first and second portions of the
  609. inputs. Indices are selected in `[0, 1]`:
  610. - 0 corresponds to a *sentence A* token,
  611. - 1 corresponds to a *sentence B* token.
  612. [What are token type IDs?](../glossary#token-type-ids)
  613. position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  614. Indices of positions of each input sequence tokens in the position
  615. embeddings. Selected in the range `[0,
  616. config.max_position_embeddings - 1]`.
  617. [What are position IDs?](../glossary#position-ids)
  618. head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers,
  619. num_heads)`, *optional*):
  620. Mask to nullify selected heads of the self-attention modules. Mask
  621. values selected in `[0, 1]`:
  622. - 1 indicates the head is **not masked**,
  623. - 0 indicates the head is **masked**.
  624. inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`,
  625. *optional*):
  626. Optionally, instead of passing `input_ids` you can choose to
  627. directly pass an embedded representation. This is useful if you want
  628. more control over how to convert `input_ids` indices into associated
  629. vectors than the model's internal embedding lookup matrix.
  630. output_attentions (`bool`, *optional*):
  631. Whether or not to return the attentions tensors of all attention
  632. layers. See `attentions` under returned tensors for more detail.
  633. output_hidden_states (`bool`, *optional*):
  634. Whether or not to return the hidden states of all layers. See
  635. `hidden_states` under returned tensors for more detail.
  636. return_dict (`bool`, *optional*):
  637. Whether or not to return a [`~file_utils.ModelOutput`] instead of a
  638. plain tuple.
  639. encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size,
  640. sequence_length, hidden_size)`, *optional*):
  641. Sequence of hidden-states at the output of the last layer of the
  642. encoder. Used in the cross-attention if the model is configured as a
  643. decoder.
  644. encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size,
  645. sequence_length)`, *optional*):
  646. Mask to avoid performing attention on the padding token indices of
  647. the encoder input. This mask is used in the cross-attention if the
  648. model is configured as a decoder. Mask values selected in `[0, 1]`:
  649. - 1 for tokens that are **not masked**,
  650. - 0 for tokens that are **masked**.
  651. past_key_values (`tuple(tuple(torch.FloatTensor))` of length
  652. `config.n_layers` with each tuple having 4 tensors of shape
  653. `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
  654. Contains precomputed key and value hidden states of the attention
  655. blocks. Can be used to speed up decoding.
  656. If `past_key_values` are used, the user can optionally input only
  657. the last `decoder_input_ids` (those that don't have their past key
  658. value states given to this model) of shape `(batch_size, 1)` instead
  659. of all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
  660. use_cache (`bool`, *optional*):
  661. If set to `True`, `past_key_values` key value states are returned
  662. and can be used to speed up decoding (see `past_key_values`).
  663. Others (**kwargs)
  664. some additional parameters might passed in from upstream pipeline,
  665. which not influence the results.
  666. """
  667. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  668. output_hidden_states = (
  669. output_hidden_states if output_hidden_states is not None else
  670. self.config.output_hidden_states)
  671. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  672. if self.config.is_decoder:
  673. use_cache = use_cache if use_cache is not None else self.config.use_cache
  674. else:
  675. use_cache = False
  676. if input_ids is not None and inputs_embeds is not None:
  677. raise ValueError(
  678. 'You cannot specify both input_ids and inputs_embeds at the same time'
  679. )
  680. elif input_ids is not None:
  681. input_shape = input_ids.size()
  682. elif inputs_embeds is not None:
  683. input_shape = inputs_embeds.size()[:-1]
  684. else:
  685. raise ValueError(
  686. 'You have to specify either input_ids or inputs_embeds')
  687. batch_size, seq_length = input_shape
  688. device = input_ids.device if input_ids is not None else inputs_embeds.device
  689. # past_key_values_length
  690. past_key_values_length = past_key_values[0][0].shape[
  691. 2] if past_key_values is not None else 0
  692. if attention_mask is None:
  693. attention_mask = torch.ones(
  694. ((batch_size, seq_length + past_key_values_length)),
  695. device=device)
  696. if token_type_ids is None:
  697. token_type_ids = torch.zeros(
  698. input_shape, dtype=torch.long, device=device)
  699. # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
  700. # ourselves in which case we just need to make it broadcastable to all heads.
  701. extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(
  702. attention_mask, input_shape, device)
  703. # If a 2D or 3D attention mask is provided for the cross-attention
  704. # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
  705. if self.config.is_decoder and encoder_hidden_states is not None:
  706. encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size(
  707. )
  708. encoder_hidden_shape = (encoder_batch_size,
  709. encoder_sequence_length)
  710. if encoder_attention_mask is None:
  711. encoder_attention_mask = torch.ones(
  712. encoder_hidden_shape, device=device)
  713. encoder_extended_attention_mask = self.invert_attention_mask(
  714. encoder_attention_mask)
  715. else:
  716. encoder_extended_attention_mask = None
  717. # Prepare head mask if needed
  718. # 1.0 in head_mask indicate we keep the head
  719. # attention_probs has shape bsz x n_heads x N x N
  720. # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
  721. # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
  722. head_mask = self.get_head_mask(head_mask,
  723. self.config.num_hidden_layers)
  724. embedding_output = self.embeddings(
  725. input_ids=input_ids,
  726. position_ids=position_ids,
  727. token_type_ids=token_type_ids,
  728. inputs_embeds=inputs_embeds,
  729. past_key_values_length=past_key_values_length,
  730. )
  731. encoder_outputs = self.encoder(
  732. embedding_output,
  733. attention_mask=extended_attention_mask,
  734. head_mask=head_mask,
  735. encoder_hidden_states=encoder_hidden_states,
  736. encoder_attention_mask=encoder_extended_attention_mask,
  737. past_key_values=past_key_values,
  738. use_cache=use_cache,
  739. output_attentions=output_attentions,
  740. output_hidden_states=output_hidden_states,
  741. return_dict=return_dict,
  742. )
  743. sequence_output = encoder_outputs[0]
  744. pooled_output = self.pooler(
  745. sequence_output) if self.pooler is not None else None
  746. if not return_dict:
  747. return (sequence_output, pooled_output) + encoder_outputs[1:]
  748. return AttentionBackboneModelOutput(
  749. last_hidden_state=sequence_output,
  750. pooler_output=pooled_output,
  751. past_key_values=encoder_outputs.past_key_values,
  752. hidden_states=encoder_outputs.hidden_states,
  753. attentions=encoder_outputs.attentions,
  754. cross_attentions=encoder_outputs.cross_attentions,
  755. )