backbone.py 42 KB

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