backbone.py 40 KB

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