backbone.py 100 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507
  1. import math
  2. import os
  3. import random
  4. import warnings
  5. from dataclasses import dataclass
  6. from typing import Optional, Tuple
  7. import torch
  8. import torch.nn.functional as F
  9. import torch.utils.checkpoint
  10. import transformers
  11. from torch import Tensor, device, dtype, nn
  12. from torch.nn import CrossEntropyLoss, MSELoss
  13. from transformers.activations import ACT2FN
  14. from transformers.file_utils import (ModelOutput, add_code_sample_docstrings,
  15. add_start_docstrings,
  16. add_start_docstrings_to_model_forward,
  17. replace_return_docstrings)
  18. from transformers.modeling_outputs import (
  19. BaseModelOutputWithPastAndCrossAttentions,
  20. BaseModelOutputWithPoolingAndCrossAttentions,
  21. CausalLMOutputWithCrossAttentions, MaskedLMOutput,
  22. MultipleChoiceModelOutput, NextSentencePredictorOutput,
  23. QuestionAnsweringModelOutput, SequenceClassifierOutput,
  24. TokenClassifierOutput)
  25. from transformers.modeling_utils import PreTrainedModel
  26. from transformers.models.bert.configuration_bert import BertConfig
  27. from transformers.utils import logging
  28. from modelscope.metainfo import Models
  29. from modelscope.models import Model, TorchModel
  30. from modelscope.models.builder import MODELS
  31. from modelscope.outputs import AttentionBackboneModelOutput
  32. from modelscope.utils.constant import Tasks
  33. from modelscope.utils.nlp.utils import parse_labels_in_order
  34. from modelscope.utils.torch_utils import (apply_chunking_to_forward,
  35. find_pruneable_heads_and_indices,
  36. prune_linear_layer)
  37. transformers.logging.set_verbosity_error()
  38. logger = logging.get_logger()
  39. _CONFIG_FOR_DOC = 'BertConfig'
  40. _TOKENIZER_FOR_DOC = 'BertTokenizer'
  41. def load_tf_weights_in_bert(model, config, tf_checkpoint_path):
  42. """Load tf checkpoints in a pytorch model."""
  43. try:
  44. import re
  45. import numpy as np
  46. import tensorflow as tf
  47. except ImportError:
  48. logger.error(
  49. 'Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see '
  50. 'https://www.tensorflow.org/install/ for installation instructions.'
  51. )
  52. raise
  53. tf_path = os.path.abspath(tf_checkpoint_path)
  54. logger.info('Converting TensorFlow checkpoint from {}'.format(tf_path))
  55. # Load weights from TF model
  56. init_vars = tf.train.list_variables(tf_path)
  57. names = []
  58. arrays = []
  59. for name, shape in init_vars:
  60. logger.info('Loading TF weight {} with shape {}'.format(name, shape))
  61. array = tf.train.load_variable(tf_path, name)
  62. names.append(name)
  63. arrays.append(array)
  64. for name, array in zip(names, arrays):
  65. name = name.split('/')
  66. # adam_v and adam_m are variables used in AdamWeightDecayOptimizer to
  67. # calculated m and v which are not required for using pretrained model
  68. if any(n in [
  69. 'adam_v', 'adam_m', 'AdamWeightDecayOptimizer',
  70. 'AdamWeightDecayOptimizer_1', 'global_step'
  71. ] for n in name):
  72. logger.info('Skipping {}'.format('/'.join(name)))
  73. continue
  74. pointer = model
  75. for m_name in name:
  76. if re.fullmatch(r'[A-Za-z]+_\d+', m_name):
  77. scope_names = re.split(r'_(\d+)', m_name)
  78. else:
  79. scope_names = [m_name]
  80. if scope_names[0] == 'kernel' or scope_names[0] == 'gamma':
  81. pointer = getattr(pointer, 'weight')
  82. elif scope_names[0] == 'output_bias' or scope_names[0] == 'beta':
  83. pointer = getattr(pointer, 'bias')
  84. elif scope_names[0] == 'output_weights':
  85. pointer = getattr(pointer, 'weight')
  86. elif scope_names[0] == 'squad':
  87. pointer = getattr(pointer, 'classifier')
  88. else:
  89. try:
  90. pointer = getattr(pointer, scope_names[0])
  91. except AttributeError:
  92. logger.info('Skipping {}'.format('/'.join(name)))
  93. continue
  94. if len(scope_names) >= 2:
  95. num = int(scope_names[1])
  96. pointer = pointer[num]
  97. if m_name[-11:] == '_embeddings':
  98. pointer = getattr(pointer, 'weight')
  99. elif m_name == 'kernel':
  100. array = np.transpose(array)
  101. try:
  102. assert (
  103. pointer.shape == array.shape
  104. ), f'Pointer shape {pointer.shape} and array shape {array.shape} mismatched'
  105. except AssertionError as e:
  106. e.args += (pointer.shape, array.shape)
  107. raise
  108. logger.info('Initialize PyTorch weight {}'.format(name))
  109. pointer.data = torch.from_numpy(array)
  110. return model
  111. class GisEmbeddings(nn.Module):
  112. """Construct the embeddings from word, position and token_type embeddings."""
  113. def __init__(self, config):
  114. super().__init__()
  115. self.word_embeddings = nn.Embedding(
  116. config.vocab_size, config.hidden_size, padding_idx=0)
  117. self.position_embeddings = nn.Embedding(config.max_position_embeddings,
  118. config.hidden_size)
  119. self.token_type_embeddings = nn.Embedding(
  120. config.type_vocab_size, config.hidden_size, padding_idx=0)
  121. self.rel_type_embeddings = nn.Embedding(
  122. config.rel_type_vocab_size, config.hidden_size, padding_idx=0)
  123. self.absolute_x_embeddings = nn.Embedding(
  124. config.absolute_x_vocab_size, config.hidden_size, padding_idx=0)
  125. self.absolute_y_embeddings = nn.Embedding(
  126. config.absolute_y_vocab_size, config.hidden_size, padding_idx=0)
  127. self.relative_x_embeddings = nn.Embedding(
  128. config.relative_x_vocab_size, config.hidden_size, padding_idx=0)
  129. self.relative_y_embeddings = nn.Embedding(
  130. config.relative_y_vocab_size, config.hidden_size, padding_idx=0)
  131. if hasattr(config, 'prov_vocab_size'):
  132. self.prov_embeddings = nn.Embedding(
  133. config.prov_vocab_size, config.hidden_size, padding_idx=0)
  134. self.city_embeddings = nn.Embedding(
  135. config.city_vocab_size, config.hidden_size, padding_idx=0)
  136. self.dist_embeddings = nn.Embedding(
  137. config.dist_vocab_size, config.hidden_size, padding_idx=0)
  138. # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
  139. # any TensorFlow checkpoint file
  140. self.LayerNorm = nn.LayerNorm(
  141. config.hidden_size, eps=config.layer_norm_eps)
  142. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  143. # position_ids (1, len position emb) is contiguous in memory and exported when serialized
  144. self.register_buffer(
  145. 'position_ids',
  146. torch.arange(config.max_position_embeddings).expand((1, -1)))
  147. self.position_embedding_type = getattr(config,
  148. 'position_embedding_type',
  149. 'absolute')
  150. self.config = config
  151. def forward(self,
  152. input_ids=None,
  153. token_type_ids=None,
  154. position_ids=None,
  155. inputs_embeds=None,
  156. past_key_values_length=0,
  157. rel_type_ids=None,
  158. absolute_position_ids=None,
  159. relative_position_ids=None,
  160. prov_ids=None,
  161. city_ids=None,
  162. dist_ids=None):
  163. if input_ids is not None:
  164. input_shape = input_ids.size()
  165. else:
  166. input_shape = inputs_embeds.size()[:-1]
  167. seq_length = input_shape[1]
  168. if position_ids is None:
  169. position_ids = self.position_ids[:,
  170. past_key_values_length:seq_length
  171. + past_key_values_length]
  172. if token_type_ids is None:
  173. token_type_ids = torch.zeros(
  174. input_shape, dtype=torch.long, device=self.position_ids.device)
  175. if inputs_embeds is None:
  176. inputs_embeds = self.word_embeddings(input_ids)
  177. token_type_embeddings = self.token_type_embeddings(token_type_ids)
  178. embeddings = inputs_embeds + token_type_embeddings
  179. if self.position_embedding_type == 'absolute':
  180. position_embeddings = self.position_embeddings(position_ids)
  181. embeddings += position_embeddings
  182. embeddings += self.rel_type_embeddings(rel_type_ids)
  183. embeddings += self.absolute_x_embeddings(absolute_position_ids[:, :,
  184. 0])
  185. embeddings += self.absolute_y_embeddings(absolute_position_ids[:, :,
  186. 1])
  187. embeddings += self.absolute_x_embeddings(absolute_position_ids[:, :,
  188. 2])
  189. embeddings += self.absolute_y_embeddings(absolute_position_ids[:, :,
  190. 3])
  191. embeddings += self.relative_x_embeddings(relative_position_ids[:, :,
  192. 0])
  193. embeddings += self.relative_y_embeddings(relative_position_ids[:, :,
  194. 1])
  195. embeddings += self.relative_x_embeddings(relative_position_ids[:, :,
  196. 2])
  197. embeddings += self.relative_y_embeddings(relative_position_ids[:, :,
  198. 3])
  199. if prov_ids is not None:
  200. embeddings += self.prov_embeddings(prov_ids)
  201. embeddings += self.city_embeddings(city_ids)
  202. embeddings += self.dist_embeddings(dist_ids)
  203. embeddings = self.LayerNorm(embeddings)
  204. embeddings = self.dropout(embeddings)
  205. return embeddings
  206. class BertEmbeddings(nn.Module):
  207. """Construct the embeddings from word, position and token_type
  208. embeddings."""
  209. def __init__(self, config):
  210. super().__init__()
  211. self.word_embeddings = nn.Embedding(
  212. config.vocab_size,
  213. config.hidden_size,
  214. padding_idx=config.pad_token_id)
  215. self.position_embeddings = nn.Embedding(config.max_position_embeddings,
  216. config.hidden_size)
  217. self.token_type_embeddings = nn.Embedding(config.type_vocab_size,
  218. config.hidden_size)
  219. # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
  220. # any TensorFlow checkpoint file
  221. self.LayerNorm = nn.LayerNorm(
  222. config.hidden_size, eps=config.layer_norm_eps)
  223. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  224. # position_ids (1, len position emb) is contiguous in memory and exported when serialized
  225. self.register_buffer(
  226. 'position_ids',
  227. torch.arange(config.max_position_embeddings).expand((1, -1)))
  228. self.position_embedding_type = getattr(config,
  229. 'position_embedding_type',
  230. 'absolute')
  231. self.config = config
  232. def forward(self,
  233. input_ids=None,
  234. token_type_ids=None,
  235. position_ids=None,
  236. inputs_embeds=None,
  237. past_key_values_length=0,
  238. rel_type_ids=None,
  239. absolute_position_ids=None,
  240. relative_position_ids=None):
  241. if input_ids is not None:
  242. input_shape = input_ids.size()
  243. else:
  244. input_shape = inputs_embeds.size()[:-1]
  245. seq_length = input_shape[1]
  246. if position_ids is None:
  247. position_ids = self.position_ids[:,
  248. past_key_values_length:seq_length
  249. + past_key_values_length]
  250. if token_type_ids is None:
  251. token_type_ids = torch.zeros(
  252. input_shape, dtype=torch.long, device=self.position_ids.device)
  253. if inputs_embeds is None:
  254. inputs_embeds = self.word_embeddings(input_ids)
  255. token_type_embeddings = self.token_type_embeddings(token_type_ids)
  256. embeddings = inputs_embeds + token_type_embeddings
  257. if self.position_embedding_type == 'absolute':
  258. position_embeddings = self.position_embeddings(position_ids)
  259. embeddings += position_embeddings
  260. embeddings = self.LayerNorm(embeddings)
  261. embeddings = self.dropout(embeddings)
  262. return embeddings
  263. class BertSelfAttention(nn.Module):
  264. def __init__(self, config, is_cross_attention):
  265. super().__init__()
  266. self.config = config
  267. if config.hidden_size % config.num_attention_heads != 0 and not hasattr(
  268. config, 'embedding_size'):
  269. raise ValueError(
  270. 'The hidden size (%d) is not a multiple of the number of attention '
  271. 'heads (%d)' %
  272. (config.hidden_size, config.num_attention_heads))
  273. self.num_attention_heads = config.num_attention_heads
  274. self.attention_head_size = int(config.hidden_size
  275. / config.num_attention_heads)
  276. self.all_head_size = self.num_attention_heads * self.attention_head_size
  277. self.query = nn.Linear(config.hidden_size, self.all_head_size)
  278. if is_cross_attention:
  279. self.key = nn.Linear(config.encoder_width, self.all_head_size)
  280. self.value = nn.Linear(config.encoder_width, self.all_head_size)
  281. else:
  282. self.key = nn.Linear(config.hidden_size, self.all_head_size)
  283. self.value = nn.Linear(config.hidden_size, self.all_head_size)
  284. self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
  285. self.position_embedding_type = getattr(config,
  286. 'position_embedding_type',
  287. 'absolute')
  288. if self.position_embedding_type == 'relative_key' or self.position_embedding_type == 'relative_key_query':
  289. self.max_position_embeddings = config.max_position_embeddings
  290. self.distance_embedding = nn.Embedding(
  291. 2 * config.max_position_embeddings - 1,
  292. self.attention_head_size)
  293. self.save_attention = False
  294. def save_attn_gradients(self, attn_gradients):
  295. self.attn_gradients = attn_gradients
  296. def get_attn_gradients(self):
  297. return self.attn_gradients
  298. def save_attention_map(self, attention_map):
  299. self.attention_map = attention_map
  300. def get_attention_map(self):
  301. return self.attention_map
  302. def transpose_for_scores(self, x):
  303. new_x_shape = x.size()[:-1] + (self.num_attention_heads,
  304. self.attention_head_size)
  305. x = x.view(*new_x_shape)
  306. return x.permute(0, 2, 1, 3)
  307. def forward(
  308. self,
  309. hidden_states,
  310. attention_mask=None,
  311. head_mask=None,
  312. encoder_hidden_states=None,
  313. encoder_attention_mask=None,
  314. past_key_value=None,
  315. output_attentions=False,
  316. ):
  317. mixed_query_layer = self.query(hidden_states)
  318. # If this is instantiated as a cross-attention module, the keys
  319. # and values come from an encoder; the attention mask needs to be
  320. # such that the encoder's padding tokens are not attended to.
  321. is_cross_attention = encoder_hidden_states is not None
  322. if is_cross_attention:
  323. key_layer = self.transpose_for_scores(
  324. self.key(encoder_hidden_states))
  325. value_layer = self.transpose_for_scores(
  326. self.value(encoder_hidden_states))
  327. attention_mask = encoder_attention_mask
  328. elif past_key_value is not None:
  329. key_layer = self.transpose_for_scores(self.key(hidden_states))
  330. value_layer = self.transpose_for_scores(self.value(hidden_states))
  331. key_layer = torch.cat([past_key_value[0], key_layer], dim=2)
  332. value_layer = torch.cat([past_key_value[1], value_layer], dim=2)
  333. else:
  334. key_layer = self.transpose_for_scores(self.key(hidden_states))
  335. value_layer = self.transpose_for_scores(self.value(hidden_states))
  336. query_layer = self.transpose_for_scores(mixed_query_layer)
  337. past_key_value = (key_layer, value_layer)
  338. # Take the dot product between "query" and "key" to get the raw attention scores.
  339. attention_scores = torch.matmul(query_layer,
  340. key_layer.transpose(-1, -2))
  341. if self.position_embedding_type == 'relative_key' or self.position_embedding_type == 'relative_key_query':
  342. seq_length = hidden_states.size()[1]
  343. position_ids_l = torch.arange(
  344. seq_length, dtype=torch.long,
  345. device=hidden_states.device).view(-1, 1)
  346. position_ids_r = torch.arange(
  347. seq_length, dtype=torch.long,
  348. device=hidden_states.device).view(1, -1)
  349. distance = position_ids_l - position_ids_r
  350. positional_embedding = self.distance_embedding(
  351. distance + self.max_position_embeddings - 1)
  352. positional_embedding = positional_embedding.to(
  353. dtype=query_layer.dtype) # fp16 compatibility
  354. if self.position_embedding_type == 'relative_key':
  355. relative_position_scores = torch.einsum(
  356. 'bhld,lrd->bhlr', query_layer, positional_embedding)
  357. attention_scores = attention_scores + relative_position_scores
  358. elif self.position_embedding_type == 'relative_key_query':
  359. relative_position_scores_query = torch.einsum(
  360. 'bhld,lrd->bhlr', query_layer, positional_embedding)
  361. relative_position_scores_key = torch.einsum(
  362. 'bhrd,lrd->bhlr', key_layer, positional_embedding)
  363. attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key
  364. attention_scores = attention_scores / math.sqrt(
  365. self.attention_head_size)
  366. if attention_mask is not None:
  367. # Apply the attention mask is (precomputed for all layers in BertModel forward() function)
  368. attention_scores = attention_scores + attention_mask
  369. # Normalize the attention scores to probabilities.
  370. attention_probs = nn.Softmax(dim=-1)(attention_scores)
  371. if is_cross_attention and self.save_attention:
  372. self.save_attention_map(attention_probs)
  373. attention_probs.register_hook(self.save_attn_gradients)
  374. # This is actually dropping out entire tokens to attend to, which might
  375. # seem a bit unusual, but is taken from the original Transformer paper.
  376. attention_probs_dropped = self.dropout(attention_probs)
  377. # Mask heads if we want to
  378. if head_mask is not None:
  379. attention_probs_dropped = attention_probs_dropped * head_mask
  380. context_layer = torch.matmul(attention_probs_dropped, value_layer)
  381. context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
  382. new_context_layer_shape = context_layer.size()[:-2] + (
  383. self.all_head_size, )
  384. context_layer = context_layer.view(*new_context_layer_shape)
  385. outputs = (context_layer,
  386. attention_probs) if output_attentions else (context_layer, )
  387. outputs = outputs + (past_key_value, )
  388. return outputs
  389. class BertSelfOutput(nn.Module):
  390. def __init__(self, config):
  391. super().__init__()
  392. self.dense = nn.Linear(config.hidden_size, config.hidden_size)
  393. self.LayerNorm = nn.LayerNorm(
  394. config.hidden_size, eps=config.layer_norm_eps)
  395. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  396. def forward(self, hidden_states, input_tensor):
  397. hidden_states = self.dense(hidden_states)
  398. hidden_states = self.dropout(hidden_states)
  399. hidden_states = self.LayerNorm(hidden_states + input_tensor)
  400. return hidden_states
  401. class BertAttention(nn.Module):
  402. def __init__(self, config, is_cross_attention=False):
  403. super().__init__()
  404. self.self = BertSelfAttention(config, is_cross_attention)
  405. self.output = BertSelfOutput(config)
  406. self.pruned_heads = set()
  407. def prune_heads(self, heads):
  408. if len(heads) == 0:
  409. return
  410. heads, index = find_pruneable_heads_and_indices(
  411. heads, self.self.num_attention_heads,
  412. self.self.attention_head_size, self.pruned_heads)
  413. # Prune linear layers
  414. self.self.query = prune_linear_layer(self.self.query, index)
  415. self.self.key = prune_linear_layer(self.self.key, index)
  416. self.self.value = prune_linear_layer(self.self.value, index)
  417. self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
  418. # Update hyper params and store pruned heads
  419. self.self.num_attention_heads = self.self.num_attention_heads - len(
  420. heads)
  421. self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
  422. self.pruned_heads = self.pruned_heads.union(heads)
  423. def forward(
  424. self,
  425. hidden_states,
  426. attention_mask=None,
  427. head_mask=None,
  428. encoder_hidden_states=None,
  429. encoder_attention_mask=None,
  430. past_key_value=None,
  431. output_attentions=False,
  432. ):
  433. self_outputs = self.self(
  434. hidden_states,
  435. attention_mask,
  436. head_mask,
  437. encoder_hidden_states,
  438. encoder_attention_mask,
  439. past_key_value,
  440. output_attentions,
  441. )
  442. attention_output = self.output(self_outputs[0], hidden_states)
  443. outputs = (attention_output,
  444. ) + self_outputs[1:] # add attentions if we output them
  445. return outputs
  446. class BertIntermediate(nn.Module):
  447. def __init__(self, config):
  448. super().__init__()
  449. self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
  450. if isinstance(config.hidden_act, str):
  451. self.intermediate_act_fn = ACT2FN[config.hidden_act]
  452. else:
  453. self.intermediate_act_fn = config.hidden_act
  454. def forward(self, hidden_states):
  455. hidden_states = self.dense(hidden_states)
  456. hidden_states = self.intermediate_act_fn(hidden_states)
  457. return hidden_states
  458. class BertOutput(nn.Module):
  459. def __init__(self, config):
  460. super().__init__()
  461. self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
  462. self.LayerNorm = nn.LayerNorm(
  463. config.hidden_size, eps=config.layer_norm_eps)
  464. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  465. def forward(self, hidden_states, input_tensor):
  466. hidden_states = self.dense(hidden_states)
  467. hidden_states = self.dropout(hidden_states)
  468. hidden_states = self.LayerNorm(hidden_states + input_tensor)
  469. return hidden_states
  470. class BertLayer(nn.Module):
  471. def __init__(self, config, layer_num):
  472. super().__init__()
  473. self.config = config
  474. self.chunk_size_feed_forward = config.chunk_size_feed_forward
  475. self.seq_len_dim = 1
  476. self.attention = BertAttention(config)
  477. self.has_cross_attention = (layer_num >= config.fusion_layer)
  478. if self.has_cross_attention:
  479. self.layer_num = layer_num
  480. self.crossattention = BertAttention(
  481. config, is_cross_attention=True)
  482. self.intermediate = BertIntermediate(config)
  483. self.output = BertOutput(config)
  484. def forward(
  485. self,
  486. hidden_states,
  487. attention_mask=None,
  488. head_mask=None,
  489. encoder_hidden_states=None,
  490. encoder_attention_mask=None,
  491. past_key_value=None,
  492. output_attentions=False,
  493. ):
  494. # decoder uni-directional self-attention cached key/values tuple is at
  495. # positions 1,2
  496. self_attn_past_key_value = past_key_value[:
  497. 2] if past_key_value is not None else None
  498. self_attention_outputs = self.attention(
  499. hidden_states,
  500. attention_mask,
  501. head_mask,
  502. output_attentions=output_attentions,
  503. past_key_value=self_attn_past_key_value,
  504. )
  505. attention_output = self_attention_outputs[0]
  506. outputs = self_attention_outputs[1:-1]
  507. present_key_value = self_attention_outputs[-1]
  508. if self.has_cross_attention:
  509. assert encoder_hidden_states is not None, 'encoder_hidden_states must be given for cross-attention layers'
  510. if type(encoder_hidden_states) == list:
  511. cross_attention_outputs = self.crossattention(
  512. attention_output,
  513. attention_mask,
  514. head_mask,
  515. encoder_hidden_states[(self.layer_num
  516. - self.config.fusion_layer)
  517. % len(encoder_hidden_states)],
  518. encoder_attention_mask[(self.layer_num
  519. - self.config.fusion_layer)
  520. % len(encoder_hidden_states)],
  521. output_attentions=output_attentions,
  522. )
  523. attention_output = cross_attention_outputs[0]
  524. outputs = outputs + cross_attention_outputs[1:-1]
  525. else:
  526. cross_attention_outputs = self.crossattention(
  527. attention_output,
  528. attention_mask,
  529. head_mask,
  530. encoder_hidden_states,
  531. encoder_attention_mask,
  532. output_attentions=output_attentions,
  533. )
  534. attention_output = cross_attention_outputs[0]
  535. outputs = outputs + cross_attention_outputs[
  536. 1:
  537. -1] # add cross attentions if we output attention weights
  538. layer_output = apply_chunking_to_forward(self.feed_forward_chunk,
  539. self.chunk_size_feed_forward,
  540. self.seq_len_dim,
  541. attention_output)
  542. outputs = (layer_output, ) + outputs
  543. outputs = outputs + (present_key_value, )
  544. return outputs
  545. def feed_forward_chunk(self, attention_output):
  546. intermediate_output = self.intermediate(attention_output)
  547. layer_output = self.output(intermediate_output, attention_output)
  548. return layer_output
  549. class BertEncoder(nn.Module):
  550. def __init__(self, config):
  551. super().__init__()
  552. self.config = config
  553. self.layer = nn.ModuleList(
  554. [BertLayer(config, i) for i in range(config.num_hidden_layers)])
  555. def forward(
  556. self,
  557. hidden_states,
  558. attention_mask=None,
  559. head_mask=None,
  560. encoder_hidden_states=None,
  561. encoder_attention_mask=None,
  562. past_key_values=None,
  563. use_cache=None,
  564. output_attentions=False,
  565. output_hidden_states=False,
  566. return_dict=True,
  567. mode='multi_modal',
  568. ):
  569. all_hidden_states = () if output_hidden_states else None
  570. all_self_attentions = () if output_attentions else None
  571. all_cross_attentions = (
  572. ) if output_attentions and self.config.add_cross_attention else None
  573. next_decoder_cache = () if use_cache else None
  574. if mode == 'text':
  575. start_layer = 0
  576. output_layer = self.config.fusion_layer
  577. elif mode == 'query':
  578. start_layer = 0
  579. output_layer = self.config.num_hidden_layers
  580. elif mode == 'fusion':
  581. start_layer = self.config.fusion_layer
  582. output_layer = self.config.num_hidden_layers
  583. elif mode == 'multi_modal':
  584. start_layer = 0
  585. output_layer = self.config.num_hidden_layers
  586. for i in range(start_layer, output_layer):
  587. layer_module = self.layer[i]
  588. if output_hidden_states:
  589. all_hidden_states = all_hidden_states + (hidden_states, )
  590. layer_head_mask = head_mask[i] if head_mask is not None else None
  591. past_key_value = past_key_values[
  592. i] if past_key_values is not None else None
  593. if getattr(self.config, 'gradient_checkpointing',
  594. False) and self.training:
  595. if use_cache:
  596. logger.warn(
  597. '`use_cache=True` is incompatible with `config.gradient_checkpointing=True`. Setting '
  598. '`use_cache=False`...')
  599. use_cache = False
  600. def create_custom_forward(module):
  601. def custom_forward(*inputs):
  602. return module(*inputs, past_key_value,
  603. output_attentions)
  604. return custom_forward
  605. layer_outputs = torch.utils.checkpoint.checkpoint(
  606. create_custom_forward(layer_module),
  607. hidden_states,
  608. attention_mask,
  609. layer_head_mask,
  610. encoder_hidden_states,
  611. encoder_attention_mask,
  612. )
  613. else:
  614. layer_outputs = layer_module(
  615. hidden_states,
  616. attention_mask,
  617. layer_head_mask,
  618. encoder_hidden_states,
  619. encoder_attention_mask,
  620. past_key_value,
  621. output_attentions,
  622. )
  623. hidden_states = layer_outputs[0]
  624. if use_cache:
  625. next_decoder_cache += (layer_outputs[-1], )
  626. if output_attentions:
  627. all_self_attentions = all_self_attentions + (
  628. layer_outputs[1], )
  629. if output_hidden_states:
  630. all_hidden_states = all_hidden_states + (hidden_states, )
  631. if not return_dict:
  632. return tuple(v for v in [
  633. hidden_states,
  634. next_decoder_cache,
  635. all_hidden_states,
  636. all_self_attentions,
  637. all_cross_attentions,
  638. ] if v is not None)
  639. return BaseModelOutputWithPastAndCrossAttentions(
  640. last_hidden_state=hidden_states,
  641. past_key_values=next_decoder_cache,
  642. hidden_states=all_hidden_states,
  643. attentions=all_self_attentions,
  644. cross_attentions=all_cross_attentions,
  645. )
  646. class BertPooler(nn.Module):
  647. def __init__(self, config):
  648. super().__init__()
  649. self.dense = nn.Linear(config.hidden_size, config.hidden_size)
  650. self.activation = nn.Tanh()
  651. def forward(self, hidden_states):
  652. # We "pool" the model by simply taking the hidden state corresponding
  653. # to the first token.
  654. first_token_tensor = hidden_states[:, 0]
  655. pooled_output = self.dense(first_token_tensor)
  656. pooled_output = self.activation(pooled_output)
  657. return pooled_output
  658. class BertPredictionHeadTransform(nn.Module):
  659. def __init__(self, config):
  660. super().__init__()
  661. self.dense = nn.Linear(config.hidden_size, config.hidden_size)
  662. if isinstance(config.hidden_act, str):
  663. self.transform_act_fn = ACT2FN[config.hidden_act]
  664. else:
  665. self.transform_act_fn = config.hidden_act
  666. self.LayerNorm = nn.LayerNorm(
  667. config.hidden_size, eps=config.layer_norm_eps)
  668. def forward(self, hidden_states):
  669. hidden_states = self.dense(hidden_states)
  670. hidden_states = self.transform_act_fn(hidden_states)
  671. hidden_states = self.LayerNorm(hidden_states)
  672. return hidden_states
  673. class BertLMPredictionHead(nn.Module):
  674. def __init__(self, config):
  675. super().__init__()
  676. self.transform = BertPredictionHeadTransform(config)
  677. # The output weights are the same as the input embeddings, but there is
  678. # an output-only bias for each token.
  679. self.decoder = nn.Linear(
  680. config.hidden_size, config.vocab_size, bias=False)
  681. self.bias = nn.Parameter(torch.zeros(config.vocab_size))
  682. # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
  683. self.decoder.bias = self.bias
  684. def forward(self, hidden_states):
  685. hidden_states = self.transform(hidden_states)
  686. hidden_states = self.decoder(hidden_states)
  687. return hidden_states
  688. class BertOnlyMLMHead(nn.Module):
  689. def __init__(self, config):
  690. super().__init__()
  691. self.predictions = BertLMPredictionHead(config)
  692. def forward(self, sequence_output):
  693. prediction_scores = self.predictions(sequence_output)
  694. return prediction_scores
  695. class BertOnlyNSPHead(nn.Module):
  696. def __init__(self, config):
  697. super().__init__()
  698. self.seq_relationship = nn.Linear(config.hidden_size, 2)
  699. def forward(self, pooled_output):
  700. seq_relationship_score = self.seq_relationship(pooled_output)
  701. return seq_relationship_score
  702. class BertPreTrainingHeads(nn.Module):
  703. def __init__(self, config):
  704. super().__init__()
  705. self.predictions = BertLMPredictionHead(config)
  706. self.seq_relationship = nn.Linear(config.hidden_size, 2)
  707. def forward(self, sequence_output, pooled_output):
  708. prediction_scores = self.predictions(sequence_output)
  709. seq_relationship_score = self.seq_relationship(pooled_output)
  710. return prediction_scores, seq_relationship_score
  711. class BertPreTrainedModel(PreTrainedModel):
  712. """
  713. An abstract class to handle weights initialization and a simple interface
  714. for downloading and loading pretrained models.
  715. """
  716. config_class = BertConfig
  717. load_tf_weights = load_tf_weights_in_bert
  718. base_model_prefix = 'bert'
  719. _keys_to_ignore_on_load_missing = [r'position_ids']
  720. def _init_weights(self, module):
  721. """ Initialize the weights """
  722. if isinstance(module, (nn.Linear, nn.Embedding)):
  723. # Slightly different from the TF version which uses truncated_normal for initialization
  724. # cf https://github.com/pytorch/pytorch/pull/5617
  725. module.weight.data.normal_(
  726. mean=0.0, std=self.config.initializer_range)
  727. elif isinstance(module, nn.LayerNorm):
  728. module.bias.data.zero_()
  729. module.weight.data.fill_(1.0)
  730. if isinstance(module, nn.Linear) and module.bias is not None:
  731. module.bias.data.zero_()
  732. @dataclass
  733. class BertForPreTrainingOutput(ModelOutput):
  734. """
  735. Output type of :class:`~transformers.BertForPreTraining`. Args:
  736. loss (`optional`, returned when ``labels`` is provided,
  737. ``torch.FloatTensor`` of shape :obj:`(1,)`):
  738. Total loss as the sum of the masked language modeling loss and the
  739. next sequence prediction (classification) loss.
  740. prediction_logits (:obj:`torch.FloatTensor` of shape :obj:`(batch_size,
  741. sequence_length, config.vocab_size)`):
  742. Prediction scores of the language modeling head (scores for each
  743. vocabulary token before SoftMax).
  744. seq_relationship_logits (:obj:`torch.FloatTensor` of shape
  745. :obj:`(batch_size, 2)`):
  746. Prediction scores of the next sequence prediction (classification)
  747. head (scores of True/False continuation before SoftMax).
  748. hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned
  749. when ``output_hidden_states=True`` is passed or when
  750. ``config.output_hidden_states=True``):
  751. Tuple of :obj:`torch.FloatTensor` (one for the output of the
  752. embeddings + one for the output of each layer) of shape
  753. :obj:`(batch_size, sequence_length, hidden_size)`. Hidden-states of
  754. the model at the output of each layer plus the initial embedding
  755. outputs.
  756. attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when
  757. ``output_attentions=True`` is passed or when
  758. ``config.output_attentions=True``):
  759. Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape
  760. :obj:`(batch_size, num_heads, sequence_length, sequence_length)`.
  761. Attentions weights after the attention softmax, used to compute the
  762. weighted average in the self-attention heads.
  763. """
  764. loss: Optional[torch.FloatTensor] = None
  765. prediction_logits: torch.FloatTensor = None
  766. seq_relationship_logits: torch.FloatTensor = None
  767. hidden_states: Optional[Tuple[torch.FloatTensor]] = None
  768. attentions: Optional[Tuple[torch.FloatTensor]] = None
  769. class BertModel(BertPreTrainedModel):
  770. """
  771. Noted that the bert model here is slightly updated from original bert, so we
  772. maintain the code here independently. The Bert Model transformer outputting
  773. raw hidden-states without any specific head on top.
  774. This model inherits from [`PreTrainedModel`]. Check the superclass
  775. documentation for the generic methods the library implements for all its
  776. model (such as downloading or saving, resizing the input embeddings, pruning
  777. heads etc.)
  778. This model is also a PyTorch
  779. [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)
  780. subclass. Use it as a regular PyTorch Module and refer to the PyTorch
  781. documentation for all matter related to general usage and behavior.
  782. Parameters:
  783. config ([`BertConfig`]): Model configuration class with all the
  784. parameters of the model.
  785. Initializing with a config file does not load the weights associated
  786. with the model, only the configuration. Check out the
  787. [`~PreTrainedModel.from_pretrained`] method to load the model
  788. weights.
  789. The model can behave as an encoder (with only self-attention) as well as a
  790. decoder, in which case a layer of cross-attention is added between the
  791. self-attention layers, following the architecture described in [Attention is
  792. all you need](https://arxiv.org/abs/1706.03762) by Ashish Vaswani, Noam
  793. Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz
  794. Kaiser and Illia Polosukhin.
  795. To behave as an decoder the model needs to be initialized with the
  796. `is_decoder` argument of the configuration set to `True`. To be used in a
  797. Seq2Seq model, the model needs to initialized with both `is_decoder`
  798. argument and `add_cross_attention` set to `True`; an `encoder_hidden_states`
  799. is then expected as an input to the forward pass.
  800. """
  801. def __init__(self, config, add_pooling_layer=True):
  802. super().__init__(config)
  803. self.config = config
  804. if config.gis_embedding == 0:
  805. self.embeddings = BertEmbeddings(config)
  806. else:
  807. self.embeddings = GisEmbeddings(config)
  808. self.encoder = BertEncoder(config)
  809. self.pooler = BertPooler(config) if add_pooling_layer else None
  810. self.init_weights()
  811. def get_input_embeddings(self):
  812. return self.embeddings.word_embeddings
  813. def set_input_embeddings(self, value):
  814. self.embeddings.word_embeddings = value
  815. def _prune_heads(self, heads_to_prune):
  816. """
  817. Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
  818. class PreTrainedModel
  819. """
  820. for layer, heads in heads_to_prune.items():
  821. self.encoder.layer[layer].attention.prune_heads(heads)
  822. def get_extended_attention_mask(self, attention_mask: Tensor,
  823. input_shape: Tuple[int], device: device,
  824. is_decoder: bool) -> Tensor:
  825. """
  826. Makes broadcastable attention and causal masks so that future and masked
  827. tokens are ignored.
  828. Arguments:
  829. attention_mask (:obj:`torch.Tensor`):
  830. Mask with ones indicating tokens to attend to, zeros for tokens
  831. to ignore.
  832. input_shape (:obj:`Tuple[int]`):
  833. The shape of the input to the model.
  834. device: (:obj:`torch.device`):
  835. The device of the input to the model.
  836. Returns:
  837. :obj:`torch.Tensor` The extended attention mask, with a the same
  838. dtype as :obj:`attention_mask.dtype`.
  839. """
  840. # We can provide a self-attention mask of dimensions [batch_size,
  841. # from_seq_length, to_seq_length] ourselves in which case we just need
  842. # to make it broadcastable to all heads.
  843. if attention_mask.dim() == 3:
  844. extended_attention_mask = attention_mask[:, None, :, :]
  845. elif attention_mask.dim() == 2:
  846. # Provided a padding mask of dimensions [batch_size, seq_length]
  847. # - if the model is a decoder, apply a causal mask in addition to
  848. # the padding mask
  849. # - if the model is an encoder, make the mask broadcastable to
  850. # [batch_size, num_heads, seq_length, seq_length]
  851. if is_decoder:
  852. batch_size, seq_length = input_shape
  853. seq_ids = torch.arange(seq_length, device=device)
  854. causal_mask = seq_ids[None, None, :].repeat(
  855. batch_size, seq_length, 1) <= seq_ids[None, :, None]
  856. # in case past_key_values are used we need to add a prefix ones
  857. # mask to the causal mask causal and attention masks must have
  858. # same type with pytorch version < 1.3
  859. causal_mask = causal_mask.to(attention_mask.dtype)
  860. if causal_mask.shape[1] < attention_mask.shape[1]:
  861. prefix_seq_len = attention_mask.shape[
  862. 1] - causal_mask.shape[1]
  863. causal_mask = torch.cat(
  864. [
  865. torch.ones(
  866. (batch_size, seq_length, prefix_seq_len),
  867. device=device,
  868. dtype=causal_mask.dtype),
  869. causal_mask,
  870. ],
  871. axis=-1,
  872. )
  873. extended_attention_mask = causal_mask[:,
  874. None, :, :] * attention_mask[:,
  875. None,
  876. None, :]
  877. else:
  878. extended_attention_mask = attention_mask[:, None, None, :]
  879. else:
  880. raise ValueError(
  881. 'Wrong shape for input_ids (shape {}) or attention_mask (shape {})'
  882. .format(input_shape, attention_mask.shape))
  883. # Since attention_mask is 1.0 for positions we want to attend and 0.0
  884. # for masked positions, this operation will create a tensor which is 0.0
  885. # for positions we want to attend and -10000.0 for masked positions.
  886. # Since we are adding it to the raw scores before the softmax, this is
  887. # effectively the same as removing these entirely.
  888. extended_attention_mask = extended_attention_mask.to(
  889. dtype=self.dtype) # fp16 compatibility
  890. extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0
  891. return extended_attention_mask
  892. def forward(
  893. self,
  894. input_ids=None,
  895. attention_mask=None,
  896. token_type_ids=None,
  897. position_ids=None,
  898. head_mask=None,
  899. inputs_embeds=None,
  900. encoder_embeds=None,
  901. encoder_hidden_states=None,
  902. encoder_attention_mask=None,
  903. past_key_values=None,
  904. use_cache=None,
  905. output_attentions=None,
  906. output_hidden_states=None,
  907. return_dict=None,
  908. is_decoder=False,
  909. mode='multi_modal',
  910. rel_type_ids=None,
  911. absolute_position_ids=None,
  912. relative_position_ids=None,
  913. prov_ids=None,
  914. city_ids=None,
  915. dist_ids=None,
  916. ):
  917. r"""
  918. Args:
  919. input_ids (`torch.LongTensor` of shape `((batch_size, sequence_length)`):
  920. Indices of input sequence tokens in the vocabulary.
  921. Indices can be obtained using [`BertTokenizer`]. See
  922. [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`]
  923. for details.
  924. [What are input IDs?](../glossary#input-ids)
  925. attention_mask (`torch.FloatTensor` of shape `((batch_size, sequence_length)`, *optional*):
  926. Mask to avoid performing attention on padding token indices. Mask
  927. values selected in `[0, 1]`:
  928. - 1 for tokens that are **not masked**,
  929. - 0 for tokens that are **masked**.
  930. [What are attention masks?](../glossary#attention-mask)
  931. token_type_ids (`torch.LongTensor` of shape `((batch_size, sequence_length)`, *optional*):
  932. Segment token indices to indicate first and second portions of the
  933. inputs. Indices are selected in `[0, 1]`:
  934. - 0 corresponds to a *sentence A* token,
  935. - 1 corresponds to a *sentence B* token.
  936. [What are token type IDs?](../glossary#token-type-ids)
  937. position_ids (`torch.LongTensor` of shape `((batch_size, sequence_length)`, *optional*):
  938. Indices of positions of each input sequence tokens in the position
  939. embeddings. Selected in the range `[0,
  940. config.max_position_embeddings - 1]`.
  941. [What are position IDs?](../glossary#position-ids)
  942. head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers,
  943. num_heads)`, *optional*):
  944. Mask to nullify selected heads of the self-attention modules. Mask
  945. values selected in `[0, 1]`:
  946. - 1 indicates the head is **not masked**,
  947. - 0 indicates the head is **masked**.
  948. inputs_embeds (`torch.FloatTensor` of shape `((batch_size, sequence_length, hidden_size)`,
  949. *optional*):
  950. Optionally, instead of passing `input_ids` you can choose to
  951. directly pass an embedded representation. This is useful if you want
  952. more control over how to convert `input_ids` indices into associated
  953. vectors than the model's internal embedding lookup matrix.
  954. output_attentions (`bool`, *optional*):
  955. Whether or not to return the attentions tensors of all attention
  956. layers. See `attentions` under returned tensors for more detail.
  957. output_hidden_states (`bool`, *optional*):
  958. Whether or not to return the hidden states of all layers. See
  959. `hidden_states` under returned tensors for more detail.
  960. return_dict (`bool`, *optional*):
  961. Whether or not to return a [`~file_utils.ModelOutput`] instead of a
  962. plain tuple.
  963. encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size,
  964. sequence_length, hidden_size)`, *optional*):
  965. Sequence of hidden-states at the output of the last layer of the
  966. encoder. Used in the cross-attention if the model is configured as a
  967. decoder.
  968. encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size,
  969. sequence_length)`, *optional*):
  970. Mask to avoid performing attention on the padding token indices of
  971. the encoder input. This mask is used in the cross-attention if the
  972. model is configured as a decoder. Mask values selected in `[0, 1]`:
  973. - 1 for tokens that are **not masked**,
  974. - 0 for tokens that are **masked**.
  975. past_key_values (`tuple(tuple(torch.FloatTensor))` of length
  976. `config.n_layers` with each tuple having 4 tensors of shape
  977. `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
  978. Contains precomputed key and value hidden states of the attention
  979. blocks. Can be used to speed up decoding.
  980. If `past_key_values` are used, the user can optionally input only
  981. the last `decoder_input_ids` (those that don't have their past key
  982. value states given to this model) of shape `(batch_size, 1)` instead
  983. of all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
  984. use_cache (`bool`, *optional*):
  985. If set to `True`, `past_key_values` key value states are returned
  986. and can be used to speed up decoding (see `past_key_values`).
  987. Others (**kwargs)
  988. some additional parameters might passed in from upstream pipeline,
  989. which not influence the results.
  990. """
  991. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  992. output_hidden_states = (
  993. output_hidden_states if output_hidden_states is not None else
  994. self.config.output_hidden_states)
  995. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  996. if is_decoder:
  997. use_cache = use_cache if use_cache is not None else self.config.use_cache
  998. else:
  999. use_cache = False
  1000. if input_ids is not None and inputs_embeds is not None:
  1001. raise ValueError(
  1002. 'You cannot specify both input_ids and inputs_embeds at the same time'
  1003. )
  1004. elif input_ids is not None:
  1005. input_shape = input_ids.size()
  1006. batch_size, seq_length = input_shape
  1007. device = input_ids.device
  1008. elif inputs_embeds is not None:
  1009. input_shape = inputs_embeds.size()[:-1]
  1010. batch_size, seq_length = input_shape
  1011. device = inputs_embeds.device
  1012. elif encoder_embeds is not None:
  1013. input_shape = encoder_embeds.size()[:-1]
  1014. batch_size, seq_length = input_shape
  1015. device = encoder_embeds.device
  1016. else:
  1017. raise ValueError(
  1018. 'You have to specify either input_ids or inputs_embeds or encoder_embeds'
  1019. )
  1020. # past_key_values_length
  1021. past_key_values_length = past_key_values[0][0].shape[
  1022. 2] if past_key_values is not None else 0
  1023. if attention_mask is None:
  1024. attention_mask = torch.ones(
  1025. ((batch_size, seq_length + past_key_values_length)),
  1026. device=device)
  1027. if token_type_ids is None:
  1028. token_type_ids = torch.zeros(
  1029. input_shape, dtype=torch.long, device=device)
  1030. # We can provide a self-attention mask of dimensions [batch_size,
  1031. # from_seq_length, to_seq_length] ourselves in which case we just need
  1032. # to make it broadcastable to all heads.
  1033. extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(
  1034. attention_mask, input_shape, device, is_decoder)
  1035. # If a 2D or 3D attention mask is provided for the cross-attention we
  1036. # need to make broadcastable to [batch_size, num_heads, seq_length,
  1037. # seq_length]
  1038. if encoder_hidden_states is not None:
  1039. if type(encoder_hidden_states) == list:
  1040. encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states[
  1041. 0].size()
  1042. else:
  1043. encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size(
  1044. )
  1045. encoder_hidden_shape = (encoder_batch_size,
  1046. encoder_sequence_length)
  1047. if type(encoder_attention_mask) == list:
  1048. encoder_extended_attention_mask = [
  1049. self.invert_attention_mask(mask)
  1050. for mask in encoder_attention_mask
  1051. ]
  1052. elif encoder_attention_mask is None:
  1053. encoder_attention_mask = torch.ones(
  1054. encoder_hidden_shape, device=device)
  1055. encoder_extended_attention_mask = self.invert_attention_mask(
  1056. encoder_attention_mask)
  1057. else:
  1058. encoder_extended_attention_mask = self.invert_attention_mask(
  1059. encoder_attention_mask)
  1060. else:
  1061. encoder_extended_attention_mask = None
  1062. # Prepare head mask if needed
  1063. # 1.0 in head_mask indicate we keep the head
  1064. # attention_probs has shape bsz x n_heads x N x N
  1065. # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
  1066. # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
  1067. head_mask = self.get_head_mask(head_mask,
  1068. self.config.num_hidden_layers)
  1069. if encoder_embeds is None:
  1070. embedding_output = self.embeddings(
  1071. input_ids=input_ids,
  1072. position_ids=position_ids,
  1073. token_type_ids=token_type_ids,
  1074. inputs_embeds=inputs_embeds,
  1075. past_key_values_length=past_key_values_length,
  1076. rel_type_ids=rel_type_ids,
  1077. absolute_position_ids=absolute_position_ids,
  1078. relative_position_ids=relative_position_ids,
  1079. prov_ids=prov_ids,
  1080. city_ids=city_ids,
  1081. dist_ids=dist_ids,
  1082. )
  1083. else:
  1084. embedding_output = encoder_embeds
  1085. encoder_outputs = self.encoder(
  1086. embedding_output,
  1087. attention_mask=extended_attention_mask,
  1088. head_mask=head_mask,
  1089. encoder_hidden_states=encoder_hidden_states,
  1090. encoder_attention_mask=encoder_extended_attention_mask,
  1091. past_key_values=past_key_values,
  1092. use_cache=use_cache,
  1093. output_attentions=output_attentions,
  1094. output_hidden_states=output_hidden_states,
  1095. return_dict=return_dict,
  1096. mode=mode,
  1097. )
  1098. sequence_output = encoder_outputs[0]
  1099. pooled_output = self.pooler(
  1100. sequence_output) if self.pooler is not None else None
  1101. if not return_dict:
  1102. return (sequence_output, pooled_output) + encoder_outputs[1:]
  1103. return BaseModelOutputWithPoolingAndCrossAttentions(
  1104. last_hidden_state=sequence_output,
  1105. pooler_output=pooled_output,
  1106. past_key_values=encoder_outputs.past_key_values,
  1107. hidden_states=encoder_outputs.hidden_states,
  1108. attentions=encoder_outputs.attentions,
  1109. cross_attentions=encoder_outputs.cross_attentions,
  1110. )
  1111. class BertForPreTraining(BertPreTrainedModel):
  1112. def __init__(self, config):
  1113. super().__init__(config)
  1114. self.bert = BertModel(config)
  1115. self.cls = BertPreTrainingHeads(config)
  1116. self.init_weights()
  1117. def get_output_embeddings(self):
  1118. return self.cls.predictions.decoder
  1119. def set_output_embeddings(self, new_embeddings):
  1120. self.cls.predictions.decoder = new_embeddings
  1121. def forward(
  1122. self,
  1123. input_ids=None,
  1124. attention_mask=None,
  1125. token_type_ids=None,
  1126. position_ids=None,
  1127. head_mask=None,
  1128. inputs_embeds=None,
  1129. labels=None,
  1130. next_sentence_label=None,
  1131. output_attentions=None,
  1132. output_hidden_states=None,
  1133. return_dict=None,
  1134. ):
  1135. r"""
  1136. labels (:obj:`torch.LongTensor` of shape ``(batch_size, sequence_length)``, `optional`):
  1137. Labels for computing the masked language modeling loss. Indices should be in ``[-100, 0, ...,
  1138. config.vocab_size]`` (see ``input_ids`` docstring) Tokens with indices set to ``-100`` are ignored
  1139. (masked), the loss is only computed for the tokens with labels in ``[0, ..., config.vocab_size]``
  1140. next_sentence_label (``torch.LongTensor`` of shape ``(batch_size,)``, `optional`):
  1141. Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair
  1142. (see :obj:`input_ids` docstring) Indices should be in ``[0, 1]``:
  1143. - 0 indicates sequence B is a continuation of sequence A,
  1144. - 1 indicates sequence B is a random sequence.
  1145. kwargs (:obj:`Dict[str, any]`, optional, defaults to `{}`):
  1146. Used to hide legacy arguments that have been deprecated.
  1147. Returns:
  1148. Example:
  1149. >>> from transformers import BertTokenizer, BertForPreTraining
  1150. >>> import torch
  1151. >>> tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
  1152. >>> model = BertForPreTraining.from_pretrained('bert-base-uncased')
  1153. >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
  1154. >>> outputs = model(**inputs)
  1155. >>> prediction_logits = outputs.prediction_logits
  1156. >>> seq_relationship_logits = outputs.seq_relationship_logits
  1157. """
  1158. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  1159. outputs = self.bert(
  1160. input_ids,
  1161. attention_mask=attention_mask,
  1162. token_type_ids=token_type_ids,
  1163. position_ids=position_ids,
  1164. head_mask=head_mask,
  1165. inputs_embeds=inputs_embeds,
  1166. output_attentions=output_attentions,
  1167. output_hidden_states=output_hidden_states,
  1168. return_dict=return_dict,
  1169. )
  1170. sequence_output, pooled_output = outputs[:2]
  1171. prediction_scores, seq_relationship_score = self.cls(
  1172. sequence_output, pooled_output)
  1173. total_loss = None
  1174. if labels is not None and next_sentence_label is not None:
  1175. loss_fct = CrossEntropyLoss()
  1176. masked_lm_loss = loss_fct(
  1177. prediction_scores.view(-1, self.config.vocab_size),
  1178. labels.view(-1))
  1179. next_sentence_loss = loss_fct(
  1180. seq_relationship_score.view(-1, 2),
  1181. next_sentence_label.view(-1))
  1182. total_loss = masked_lm_loss + next_sentence_loss
  1183. if not return_dict:
  1184. output = (prediction_scores, seq_relationship_score) + outputs[2:]
  1185. return ((total_loss, )
  1186. + output) if total_loss is not None else output
  1187. return BertForPreTrainingOutput(
  1188. loss=total_loss,
  1189. prediction_logits=prediction_scores,
  1190. seq_relationship_logits=seq_relationship_score,
  1191. hidden_states=outputs.hidden_states,
  1192. attentions=outputs.attentions,
  1193. )
  1194. class BertLMHeadModel(BertPreTrainedModel):
  1195. _keys_to_ignore_on_load_unexpected = [r'pooler']
  1196. _keys_to_ignore_on_load_missing = [
  1197. r'position_ids', r'predictions.decoder.bias'
  1198. ]
  1199. def __init__(self, config):
  1200. super().__init__(config)
  1201. self.bert = BertModel(config, add_pooling_layer=False)
  1202. self.cls = BertOnlyMLMHead(config)
  1203. self.init_weights()
  1204. def get_output_embeddings(self):
  1205. return self.cls.predictions.decoder
  1206. def set_output_embeddings(self, new_embeddings):
  1207. self.cls.predictions.decoder = new_embeddings
  1208. def forward(
  1209. self,
  1210. input_ids=None,
  1211. attention_mask=None,
  1212. token_type_ids=None,
  1213. position_ids=None,
  1214. head_mask=None,
  1215. inputs_embeds=None,
  1216. encoder_hidden_states=None,
  1217. encoder_attention_mask=None,
  1218. labels=None,
  1219. past_key_values=None,
  1220. use_cache=None,
  1221. output_attentions=None,
  1222. output_hidden_states=None,
  1223. return_dict=None,
  1224. is_decoder=True,
  1225. reduction='mean',
  1226. mode='multi_modal',
  1227. soft_labels=None,
  1228. alpha=0,
  1229. return_logits=False,
  1230. ):
  1231. r"""
  1232. encoder_hidden_states (:obj:`torch.FloatTensor` of shape
  1233. :obj:`(batch_size, sequence_length, hidden_size)`, `optional`):
  1234. Sequence of hidden-states at the output of the last layer of the
  1235. encoder. Used in the cross-attention if the model is configured as a
  1236. decoder.
  1237. encoder_attention_mask (:obj:`torch.FloatTensor` of shape
  1238. :obj:`(batch_size, sequence_length)`, `optional`):
  1239. Mask to avoid performing attention on the padding token indices of
  1240. the encoder input. This mask is used in the cross-attention if the
  1241. model is configured as a decoder. Mask values selected in ``[0,
  1242. 1]``: - 1 for tokens that are **not masked**, - 0 for tokens that
  1243. are **masked**.
  1244. labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size,
  1245. sequence_length)`, `optional`):
  1246. Labels for computing the left-to-right language modeling loss (next
  1247. word prediction). Indices should be in ``[-100, 0, ...,
  1248. config.vocab_size]`` (see ``input_ids`` docstring) Tokens with
  1249. indices set to ``-100`` are ignored (masked), the loss is only
  1250. computed for the tokens with labels n ``[0, ...,
  1251. config.vocab_size]``
  1252. past_key_values (:obj:`tuple(tuple(torch.FloatTensor))` of length
  1253. :obj:`config.n_layers` with each tuple having 4 tensors of shape
  1254. :obj:`(batch_size, num_heads, sequence_length - 1,
  1255. embed_size_per_head)`):
  1256. Contains precomputed key and value hidden states of the attention
  1257. blocks. Can be used to speed up decoding. If :obj:`past_key_values`
  1258. are used, the user can optionally input only the last
  1259. :obj:`decoder_input_ids` (those that don't have their past key value
  1260. states given to this model) of shape :obj:`(batch_size, 1)` instead
  1261. of all :obj:`decoder_input_ids` of shape :obj:`(batch_size,
  1262. sequence_length)`.
  1263. use_cache (:obj:`bool`, `optional`):
  1264. If set to :obj:`True`, :obj:`past_key_values` key value states are
  1265. returned and can be used to speed up decoding (see
  1266. :obj:`past_key_values`).
  1267. Returns:
  1268. Example:
  1269. >>> from transformers import BertTokenizer, BertLMHeadModel, BertConfig
  1270. >>> import torch
  1271. >>> tokenizer = BertTokenizer.from_pretrained('bert-base-cased')
  1272. >>> config = BertConfig.from_pretrained("bert-base-cased")
  1273. >>> model = BertLMHeadModel.from_pretrained('bert-base-cased', config=config)
  1274. >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
  1275. >>> outputs = model(**inputs)
  1276. >>> prediction_logits = outputs.logits
  1277. """
  1278. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  1279. if labels is not None:
  1280. use_cache = False
  1281. outputs = self.bert(
  1282. input_ids,
  1283. attention_mask=attention_mask,
  1284. token_type_ids=token_type_ids,
  1285. position_ids=position_ids,
  1286. head_mask=head_mask,
  1287. inputs_embeds=inputs_embeds,
  1288. encoder_hidden_states=encoder_hidden_states,
  1289. encoder_attention_mask=encoder_attention_mask,
  1290. past_key_values=past_key_values,
  1291. use_cache=use_cache,
  1292. output_attentions=output_attentions,
  1293. output_hidden_states=output_hidden_states,
  1294. return_dict=return_dict,
  1295. is_decoder=is_decoder,
  1296. mode=mode,
  1297. )
  1298. sequence_output = outputs[0]
  1299. prediction_scores = self.cls(sequence_output)
  1300. if return_logits:
  1301. return prediction_scores[:, :-1, :].contiguous()
  1302. lm_loss = None
  1303. if labels is not None:
  1304. # we are doing next-token prediction; shift prediction scores and input ids by one
  1305. shifted_prediction_scores = prediction_scores[:, :
  1306. -1, :].contiguous()
  1307. labels = labels[:, 1:].contiguous()
  1308. loss_fct = CrossEntropyLoss(reduction=reduction)
  1309. lm_loss = loss_fct(
  1310. shifted_prediction_scores.view(-1, self.config.vocab_size),
  1311. labels.view(-1))
  1312. lm_loss = lm_loss.view(prediction_scores.size(0), -1).sum(1)
  1313. if soft_labels is not None:
  1314. loss_distill = -torch.sum(
  1315. F.log_softmax(shifted_prediction_scores, dim=-1) * soft_labels,
  1316. dim=-1)
  1317. loss_distill = (loss_distill * (labels != -100)).sum(1)
  1318. lm_loss = (1 - alpha) * lm_loss + alpha * loss_distill
  1319. if not return_dict:
  1320. output = (prediction_scores, ) + outputs[2:]
  1321. return ((lm_loss, ) + output) if lm_loss is not None else output
  1322. return CausalLMOutputWithCrossAttentions(
  1323. loss=lm_loss,
  1324. logits=prediction_scores,
  1325. past_key_values=outputs.past_key_values,
  1326. hidden_states=outputs.hidden_states,
  1327. attentions=outputs.attentions,
  1328. cross_attentions=outputs.cross_attentions,
  1329. )
  1330. def prepare_inputs_for_generation(self,
  1331. input_ids,
  1332. past=None,
  1333. attention_mask=None,
  1334. **model_kwargs):
  1335. input_shape = input_ids.shape
  1336. # if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
  1337. if attention_mask is None:
  1338. attention_mask = input_ids.new_ones(input_shape)
  1339. # cut decoder_input_ids if past is used
  1340. if past is not None:
  1341. input_ids = input_ids[:, -1:]
  1342. return {
  1343. 'input_ids':
  1344. input_ids,
  1345. 'attention_mask':
  1346. attention_mask,
  1347. 'past_key_values':
  1348. past,
  1349. 'encoder_hidden_states':
  1350. model_kwargs.get('encoder_hidden_states', None),
  1351. 'encoder_attention_mask':
  1352. model_kwargs.get('encoder_attention_mask', None),
  1353. 'is_decoder':
  1354. True,
  1355. }
  1356. def _reorder_cache(self, past, beam_idx):
  1357. reordered_past = ()
  1358. for layer_past in past:
  1359. reordered_past += (tuple(
  1360. past_state.index_select(0, beam_idx)
  1361. for past_state in layer_past), )
  1362. return reordered_past
  1363. class GisBertLMPredictionHead(nn.Module):
  1364. def __init__(self, config, vocab_size):
  1365. super().__init__()
  1366. self.transform = BertPredictionHeadTransform(config)
  1367. # The output weights are the same as the input embeddings, but there is
  1368. # an output-only bias for each token.
  1369. self.decoder = nn.Linear(config.hidden_size, vocab_size, bias=False)
  1370. self.bias = nn.Parameter(torch.zeros(vocab_size))
  1371. # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
  1372. self.decoder.bias = self.bias
  1373. def forward(self, hidden_states):
  1374. hidden_states = self.transform(hidden_states)
  1375. hidden_states = self.decoder(hidden_states)
  1376. return hidden_states
  1377. class BertForGisMaskedLM(BertPreTrainedModel):
  1378. _keys_to_ignore_on_load_unexpected = [r'pooler']
  1379. _keys_to_ignore_on_load_missing = [
  1380. r'position_ids', r'predictions.decoder.bias'
  1381. ]
  1382. def __init__(self, config):
  1383. super().__init__(config)
  1384. self.bert = BertModel(config, add_pooling_layer=False)
  1385. self.cls_geom_id = GisBertLMPredictionHead(config, config.vocab_size)
  1386. self.cls_geom_type = GisBertLMPredictionHead(config,
  1387. config.type_vocab_size)
  1388. self.cls_rel_type = GisBertLMPredictionHead(config,
  1389. config.rel_type_vocab_size)
  1390. self.cls_absolute_position_x1 = GisBertLMPredictionHead(
  1391. config, config.absolute_x_vocab_size)
  1392. self.cls_absolute_position_x2 = GisBertLMPredictionHead(
  1393. config, config.absolute_x_vocab_size)
  1394. self.cls_absolute_position_y1 = GisBertLMPredictionHead(
  1395. config, config.absolute_y_vocab_size)
  1396. self.cls_absolute_position_y2 = GisBertLMPredictionHead(
  1397. config, config.absolute_y_vocab_size)
  1398. self.cls_relative_position_x1 = GisBertLMPredictionHead(
  1399. config, config.relative_x_vocab_size)
  1400. self.cls_relative_position_x2 = GisBertLMPredictionHead(
  1401. config, config.relative_x_vocab_size)
  1402. self.cls_relative_position_y1 = GisBertLMPredictionHead(
  1403. config, config.relative_y_vocab_size)
  1404. self.cls_relative_position_y2 = GisBertLMPredictionHead(
  1405. config, config.relative_y_vocab_size)
  1406. self.config = config
  1407. self.init_weights()
  1408. def forward(
  1409. self,
  1410. input_ids=None,
  1411. attention_mask=None,
  1412. token_type_ids=None,
  1413. position_ids=None,
  1414. head_mask=None,
  1415. inputs_embeds=None,
  1416. encoder_embeds=None,
  1417. encoder_hidden_states=None,
  1418. encoder_attention_mask=None,
  1419. labels=None,
  1420. output_attentions=None,
  1421. output_hidden_states=None,
  1422. return_dict=None,
  1423. is_decoder=False,
  1424. mode='multi_modal',
  1425. soft_labels=None,
  1426. alpha=0,
  1427. return_logits=False,
  1428. rel_type_ids=None,
  1429. absolute_position_ids=None,
  1430. relative_position_ids=None,
  1431. token_type_ids_label=None,
  1432. rel_type_ids_label=None,
  1433. absolute_position_ids_label=None,
  1434. relative_position_ids_label=None,
  1435. ):
  1436. r"""
  1437. labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size,
  1438. sequence_length)`, `optional`):
  1439. Labels for computing the masked language modeling loss. Indices
  1440. should be in ``[-100, 0, ..., config.vocab_size]`` (see
  1441. ``input_ids`` docstring) Tokens with indices set to ``-100`` are
  1442. ignored (masked), the loss is only computed for the tokens with
  1443. labels in ``[0, ..., config.vocab_size]``
  1444. """
  1445. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  1446. outputs = self.bert(
  1447. input_ids,
  1448. attention_mask=attention_mask,
  1449. token_type_ids=token_type_ids,
  1450. position_ids=position_ids,
  1451. head_mask=head_mask,
  1452. inputs_embeds=inputs_embeds,
  1453. encoder_embeds=encoder_embeds,
  1454. encoder_hidden_states=encoder_hidden_states,
  1455. encoder_attention_mask=encoder_attention_mask,
  1456. output_attentions=output_attentions,
  1457. output_hidden_states=output_hidden_states,
  1458. return_dict=return_dict,
  1459. is_decoder=is_decoder,
  1460. mode=mode,
  1461. rel_type_ids=rel_type_ids,
  1462. absolute_position_ids=absolute_position_ids,
  1463. relative_position_ids=relative_position_ids,
  1464. )
  1465. sequence_output = outputs[0]
  1466. prediction_scores = self.cls_geom_id(sequence_output)
  1467. loss_fct = CrossEntropyLoss() # -100 index = padding token
  1468. masked_lm_loss = loss_fct(
  1469. prediction_scores.view(-1, self.config.vocab_size),
  1470. labels.view(-1))
  1471. positions_cls = [
  1472. self.cls_geom_type, self.cls_rel_type,
  1473. self.cls_absolute_position_x1, self.cls_absolute_position_x2,
  1474. self.cls_absolute_position_y1, self.cls_absolute_position_y2,
  1475. self.cls_relative_position_x1, self.cls_relative_position_x2,
  1476. self.cls_relative_position_y1, self.cls_relative_position_y2
  1477. ]
  1478. positions_label = [
  1479. token_type_ids_label, rel_type_ids_label,
  1480. absolute_position_ids_label[:, :,
  1481. 0], absolute_position_ids_label[:, :,
  1482. 2],
  1483. absolute_position_ids_label[:, :,
  1484. 1], absolute_position_ids_label[:, :,
  1485. 3],
  1486. relative_position_ids_label[:, :,
  1487. 0], relative_position_ids_label[:, :,
  1488. 2],
  1489. relative_position_ids_label[:, :,
  1490. 1], relative_position_ids_label[:, :,
  1491. 3]
  1492. ]
  1493. positions_size = [
  1494. self.config.type_vocab_size, self.config.rel_type_vocab_size,
  1495. self.config.absolute_x_vocab_size,
  1496. self.config.absolute_x_vocab_size,
  1497. self.config.absolute_y_vocab_size,
  1498. self.config.absolute_y_vocab_size,
  1499. self.config.relative_x_vocab_size,
  1500. self.config.relative_x_vocab_size,
  1501. self.config.relative_y_vocab_size,
  1502. self.config.relative_y_vocab_size
  1503. ]
  1504. for mycls, mylabels, mysize in zip(positions_cls, positions_label,
  1505. positions_size):
  1506. if mylabels is not None:
  1507. myprediction_scores = mycls(sequence_output)
  1508. masked_lm_loss += loss_fct(
  1509. myprediction_scores.view(-1, mysize), mylabels.view(-1))
  1510. if not return_dict:
  1511. output = (prediction_scores, ) + outputs[2:]
  1512. return ((masked_lm_loss, )
  1513. + output) if masked_lm_loss is not None else output
  1514. return MaskedLMOutput(
  1515. loss=masked_lm_loss,
  1516. logits=prediction_scores,
  1517. hidden_states=outputs.hidden_states,
  1518. attentions=outputs.attentions,
  1519. )
  1520. def prepare_inputs_for_generation(self,
  1521. input_ids,
  1522. attention_mask=None,
  1523. **model_kwargs):
  1524. input_shape = input_ids.shape
  1525. effective_batch_size = input_shape[0]
  1526. # add a dummy token
  1527. assert self.config.pad_token_id is not None, 'The PAD token should be defined for generation'
  1528. padding_mask = attention_mask.new_zeros((attention_mask.shape[0], 1))
  1529. attention_mask = torch.cat([attention_mask, padding_mask], dim=-1)
  1530. dummy_token = torch.full((effective_batch_size, 1),
  1531. self.config.pad_token_id,
  1532. dtype=torch.long,
  1533. device=input_ids.device)
  1534. input_ids = torch.cat([input_ids, dummy_token], dim=1)
  1535. return {'input_ids': input_ids, 'attention_mask': attention_mask}
  1536. class BertForMaskedLM(BertPreTrainedModel):
  1537. _keys_to_ignore_on_load_unexpected = [r'pooler']
  1538. _keys_to_ignore_on_load_missing = [
  1539. r'position_ids', r'predictions.decoder.bias'
  1540. ]
  1541. def __init__(self, config):
  1542. super().__init__(config)
  1543. self.bert = BertModel(config, add_pooling_layer=False)
  1544. self.cls = BertOnlyMLMHead(config)
  1545. self.init_weights()
  1546. def get_output_embeddings(self):
  1547. return self.cls.predictions.decoder
  1548. def set_output_embeddings(self, new_embeddings):
  1549. self.cls.predictions.decoder = new_embeddings
  1550. def forward(
  1551. self,
  1552. input_ids=None,
  1553. attention_mask=None,
  1554. token_type_ids=None,
  1555. position_ids=None,
  1556. head_mask=None,
  1557. inputs_embeds=None,
  1558. encoder_embeds=None,
  1559. encoder_hidden_states=None,
  1560. encoder_attention_mask=None,
  1561. labels=None,
  1562. output_attentions=None,
  1563. output_hidden_states=None,
  1564. return_dict=None,
  1565. is_decoder=False,
  1566. mode='multi_modal',
  1567. soft_labels=None,
  1568. alpha=0,
  1569. return_logits=False,
  1570. rel_type_ids=None,
  1571. absolute_position_ids=None,
  1572. relative_position_ids=None,
  1573. ):
  1574. r"""
  1575. labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
  1576. Labels for computing the masked language modeling loss. Indices should be in ``[-100, 0, ...,
  1577. config.vocab_size]`` (see ``input_ids`` docstring) Tokens with indices set to ``-100`` are ignored
  1578. (masked), the loss is only computed for the tokens with labels in ``[0, ..., config.vocab_size]``
  1579. """
  1580. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  1581. outputs = self.bert(
  1582. input_ids,
  1583. attention_mask=attention_mask,
  1584. token_type_ids=token_type_ids,
  1585. position_ids=position_ids,
  1586. head_mask=head_mask,
  1587. inputs_embeds=inputs_embeds,
  1588. encoder_embeds=encoder_embeds,
  1589. encoder_hidden_states=encoder_hidden_states,
  1590. encoder_attention_mask=encoder_attention_mask,
  1591. output_attentions=output_attentions,
  1592. output_hidden_states=output_hidden_states,
  1593. return_dict=return_dict,
  1594. is_decoder=is_decoder,
  1595. mode=mode,
  1596. rel_type_ids=rel_type_ids,
  1597. absolute_position_ids=absolute_position_ids,
  1598. relative_position_ids=relative_position_ids,
  1599. )
  1600. sequence_output = outputs[0]
  1601. prediction_scores = self.cls(sequence_output)
  1602. if return_logits:
  1603. return prediction_scores
  1604. masked_lm_loss = None
  1605. if labels is not None:
  1606. loss_fct = CrossEntropyLoss() # -100 index = padding token
  1607. masked_lm_loss = loss_fct(
  1608. prediction_scores.view(-1, self.config.vocab_size),
  1609. labels.view(-1))
  1610. if soft_labels is not None:
  1611. loss_distill = -torch.sum(
  1612. F.log_softmax(prediction_scores, dim=-1) * soft_labels, dim=-1)
  1613. loss_distill = loss_distill[labels != -100].mean()
  1614. masked_lm_loss = (1
  1615. - alpha) * masked_lm_loss + alpha * loss_distill
  1616. if not return_dict:
  1617. output = (prediction_scores, ) + outputs[2:]
  1618. return ((masked_lm_loss, )
  1619. + output) if masked_lm_loss is not None else output
  1620. return MaskedLMOutput(
  1621. loss=masked_lm_loss,
  1622. logits=prediction_scores,
  1623. hidden_states=outputs.hidden_states,
  1624. attentions=outputs.attentions,
  1625. )
  1626. def prepare_inputs_for_generation(self,
  1627. input_ids,
  1628. attention_mask=None,
  1629. **model_kwargs):
  1630. input_shape = input_ids.shape
  1631. effective_batch_size = input_shape[0]
  1632. # add a dummy token
  1633. assert self.config.pad_token_id is not None, 'The PAD token should be defined for generation'
  1634. padding_mask = attention_mask.new_zeros((attention_mask.shape[0], 1))
  1635. attention_mask = torch.cat([attention_mask, padding_mask], dim=-1)
  1636. dummy_token = torch.full((effective_batch_size, 1),
  1637. self.config.pad_token_id,
  1638. dtype=torch.long,
  1639. device=input_ids.device)
  1640. input_ids = torch.cat([input_ids, dummy_token], dim=1)
  1641. return {'input_ids': input_ids, 'attention_mask': attention_mask}
  1642. class BertForNextSentencePrediction(BertPreTrainedModel):
  1643. def __init__(self, config):
  1644. super().__init__(config)
  1645. self.bert = BertModel(config)
  1646. self.cls = BertOnlyNSPHead(config)
  1647. self.init_weights()
  1648. def forward(self,
  1649. input_ids=None,
  1650. attention_mask=None,
  1651. token_type_ids=None,
  1652. position_ids=None,
  1653. head_mask=None,
  1654. inputs_embeds=None,
  1655. labels=None,
  1656. output_attentions=None,
  1657. output_hidden_states=None,
  1658. return_dict=None,
  1659. **kwargs):
  1660. r"""
  1661. labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`):
  1662. Labels for computing the next sequenåce prediction (classification) loss. Input should be a sequence pair
  1663. (see ``input_ids`` docstring). Indices should be in ``[0, 1]``:
  1664. - 0 indicates sequence B is a continuation of sequence A,
  1665. - 1 indicates sequence B is a random sequence.
  1666. Returns:
  1667. Example:
  1668. >>> from transformers import BertTokenizer, BertForNextSentencePrediction
  1669. >>> import torch
  1670. >>> tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
  1671. >>> model = BertForNextSentencePrediction.from_pretrained('bert-base-uncased')
  1672. >>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
  1673. >>> next_sentence = "The sky is blue due to the shorter wavelength of blue light."
  1674. >>> encoding = tokenizer(prompt, next_sentence, return_tensors='pt')
  1675. >>> outputs = model(**encoding, labels=torch.LongTensor([1]))
  1676. >>> logits = outputs.logits
  1677. >>> assert logits[0, 0] < logits[0, 1] # next sentence was random
  1678. """
  1679. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  1680. outputs = self.bert(
  1681. input_ids,
  1682. attention_mask=attention_mask,
  1683. token_type_ids=token_type_ids,
  1684. position_ids=position_ids,
  1685. head_mask=head_mask,
  1686. inputs_embeds=inputs_embeds,
  1687. output_attentions=output_attentions,
  1688. output_hidden_states=output_hidden_states,
  1689. return_dict=return_dict,
  1690. )
  1691. pooled_output = outputs[1]
  1692. seq_relationship_scores = self.cls(pooled_output)
  1693. next_sentence_loss = None
  1694. if labels is not None:
  1695. loss_fct = CrossEntropyLoss()
  1696. next_sentence_loss = loss_fct(
  1697. seq_relationship_scores.view(-1, 2), labels.view(-1))
  1698. if not return_dict:
  1699. output = (seq_relationship_scores, ) + outputs[2:]
  1700. return ((next_sentence_loss, )
  1701. + output) if next_sentence_loss is not None else output
  1702. return NextSentencePredictorOutput(
  1703. loss=next_sentence_loss,
  1704. logits=seq_relationship_scores,
  1705. hidden_states=outputs.hidden_states,
  1706. attentions=outputs.attentions,
  1707. )
  1708. class BertForSequenceClassification(BertPreTrainedModel):
  1709. def __init__(self, config):
  1710. super().__init__(config)
  1711. self.num_labels = config.num_labels
  1712. self.bert = BertModel(config)
  1713. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  1714. self.classifier = nn.Linear(config.hidden_size, config.num_labels)
  1715. self.init_weights()
  1716. def forward(
  1717. self,
  1718. input_ids=None,
  1719. attention_mask=None,
  1720. token_type_ids=None,
  1721. position_ids=None,
  1722. head_mask=None,
  1723. inputs_embeds=None,
  1724. labels=None,
  1725. output_attentions=None,
  1726. output_hidden_states=None,
  1727. return_dict=None,
  1728. ):
  1729. r"""
  1730. labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`):
  1731. Labels for computing the sequence classification/regression loss. Indices should be in :obj:`[0, ...,
  1732. config.num_labels - 1]`. If :obj:`config.num_labels == 1` a regression loss is computed (Mean-Square loss),
  1733. If :obj:`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
  1734. """
  1735. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  1736. outputs = self.bert(
  1737. input_ids,
  1738. attention_mask=attention_mask,
  1739. token_type_ids=token_type_ids,
  1740. position_ids=position_ids,
  1741. head_mask=head_mask,
  1742. inputs_embeds=inputs_embeds,
  1743. output_attentions=output_attentions,
  1744. output_hidden_states=output_hidden_states,
  1745. return_dict=return_dict,
  1746. )
  1747. pooled_output = outputs[1]
  1748. pooled_output = self.dropout(pooled_output)
  1749. logits = self.classifier(pooled_output)
  1750. loss = None
  1751. if labels is not None:
  1752. if self.num_labels == 1:
  1753. # We are doing regression
  1754. loss_fct = MSELoss()
  1755. loss = loss_fct(logits.view(-1), labels.view(-1))
  1756. else:
  1757. loss_fct = CrossEntropyLoss()
  1758. loss = loss_fct(
  1759. logits.view(-1, self.num_labels), labels.view(-1))
  1760. if not return_dict:
  1761. output = (logits, ) + outputs[2:]
  1762. return ((loss, ) + output) if loss is not None else output
  1763. return SequenceClassifierOutput(
  1764. loss=loss,
  1765. logits=logits,
  1766. hidden_states=outputs.hidden_states,
  1767. attentions=outputs.attentions,
  1768. )
  1769. class BertForMultipleChoice(BertPreTrainedModel):
  1770. def __init__(self, config):
  1771. super().__init__(config)
  1772. self.bert = BertModel(config)
  1773. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  1774. self.classifier = nn.Linear(config.hidden_size, 1)
  1775. self.init_weights()
  1776. def forward(
  1777. self,
  1778. input_ids=None,
  1779. attention_mask=None,
  1780. token_type_ids=None,
  1781. position_ids=None,
  1782. head_mask=None,
  1783. inputs_embeds=None,
  1784. labels=None,
  1785. output_attentions=None,
  1786. output_hidden_states=None,
  1787. return_dict=None,
  1788. ):
  1789. r"""
  1790. labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`,
  1791. `optional`):
  1792. Labels for computing the multiple choice classification loss.
  1793. Indices should be in ``[0, ..., num_choices-1]`` where
  1794. :obj:`num_choices` is the size of the second dimension of the input
  1795. tensors. (See :obj:`input_ids` above)
  1796. """
  1797. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  1798. num_choices = input_ids.shape[
  1799. 1] if input_ids is not None else inputs_embeds.shape[1]
  1800. input_ids = input_ids.view(
  1801. -1, input_ids.size(-1)) if input_ids is not None else None
  1802. attention_mask = attention_mask.view(
  1803. -1,
  1804. attention_mask.size(-1)) if attention_mask is not None else None
  1805. token_type_ids = token_type_ids.view(
  1806. -1,
  1807. token_type_ids.size(-1)) if token_type_ids is not None else None
  1808. position_ids = position_ids.view(
  1809. -1, position_ids.size(-1)) if position_ids is not None else None
  1810. inputs_embeds = (
  1811. inputs_embeds.view(-1, inputs_embeds.size(-2),
  1812. inputs_embeds.size(-1))
  1813. if inputs_embeds is not None else None)
  1814. outputs = self.bert(
  1815. input_ids,
  1816. attention_mask=attention_mask,
  1817. token_type_ids=token_type_ids,
  1818. position_ids=position_ids,
  1819. head_mask=head_mask,
  1820. inputs_embeds=inputs_embeds,
  1821. output_attentions=output_attentions,
  1822. output_hidden_states=output_hidden_states,
  1823. return_dict=return_dict,
  1824. )
  1825. pooled_output = outputs[1]
  1826. pooled_output = self.dropout(pooled_output)
  1827. logits = self.classifier(pooled_output)
  1828. reshaped_logits = logits.view(-1, num_choices)
  1829. loss = None
  1830. if labels is not None:
  1831. loss_fct = CrossEntropyLoss()
  1832. loss = loss_fct(reshaped_logits, labels)
  1833. if not return_dict:
  1834. output = (reshaped_logits, ) + outputs[2:]
  1835. return ((loss, ) + output) if loss is not None else output
  1836. return MultipleChoiceModelOutput(
  1837. loss=loss,
  1838. logits=reshaped_logits,
  1839. hidden_states=outputs.hidden_states,
  1840. attentions=outputs.attentions,
  1841. )
  1842. class BertForTokenClassification(BertPreTrainedModel):
  1843. _keys_to_ignore_on_load_unexpected = [r'pooler']
  1844. def __init__(self, config):
  1845. super().__init__(config)
  1846. self.num_labels = config.num_labels
  1847. self.bert = BertModel(config, add_pooling_layer=False)
  1848. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  1849. self.classifier = nn.Linear(config.hidden_size, config.num_labels)
  1850. self.init_weights()
  1851. def forward(
  1852. self,
  1853. input_ids=None,
  1854. attention_mask=None,
  1855. token_type_ids=None,
  1856. position_ids=None,
  1857. head_mask=None,
  1858. inputs_embeds=None,
  1859. labels=None,
  1860. output_attentions=None,
  1861. output_hidden_states=None,
  1862. return_dict=None,
  1863. ):
  1864. r"""
  1865. labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size,
  1866. sequence_length)`, `optional`):
  1867. Labels for computing the token classification loss. Indices should
  1868. be in ``[0, ..., config.num_labels - 1]``.
  1869. """
  1870. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  1871. outputs = self.bert(
  1872. input_ids,
  1873. attention_mask=attention_mask,
  1874. token_type_ids=token_type_ids,
  1875. position_ids=position_ids,
  1876. head_mask=head_mask,
  1877. inputs_embeds=inputs_embeds,
  1878. output_attentions=output_attentions,
  1879. output_hidden_states=output_hidden_states,
  1880. return_dict=return_dict,
  1881. )
  1882. sequence_output = outputs[0]
  1883. sequence_output = self.dropout(sequence_output)
  1884. logits = self.classifier(sequence_output)
  1885. loss = None
  1886. if labels is not None:
  1887. loss_fct = CrossEntropyLoss()
  1888. # Only keep active parts of the loss
  1889. if attention_mask is not None:
  1890. active_loss = attention_mask.view(-1) == 1
  1891. active_logits = logits.view(-1, self.num_labels)
  1892. active_labels = torch.where(
  1893. active_loss, labels.view(-1),
  1894. torch.tensor(loss_fct.ignore_index).type_as(labels))
  1895. loss = loss_fct(active_logits, active_labels)
  1896. else:
  1897. loss = loss_fct(
  1898. logits.view(-1, self.num_labels), labels.view(-1))
  1899. if not return_dict:
  1900. output = (logits, ) + outputs[2:]
  1901. return ((loss, ) + output) if loss is not None else output
  1902. return TokenClassifierOutput(
  1903. loss=loss,
  1904. logits=logits,
  1905. hidden_states=outputs.hidden_states,
  1906. attentions=outputs.attentions,
  1907. )
  1908. class BertForQuestionAnswering(BertPreTrainedModel):
  1909. _keys_to_ignore_on_load_unexpected = [r'pooler']
  1910. def __init__(self, config):
  1911. super().__init__(config)
  1912. self.num_labels = config.num_labels
  1913. self.bert = BertModel(config, add_pooling_layer=False)
  1914. self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
  1915. self.init_weights()
  1916. def forward(
  1917. self,
  1918. input_ids=None,
  1919. attention_mask=None,
  1920. token_type_ids=None,
  1921. position_ids=None,
  1922. head_mask=None,
  1923. inputs_embeds=None,
  1924. start_positions=None,
  1925. end_positions=None,
  1926. output_attentions=None,
  1927. output_hidden_states=None,
  1928. return_dict=None,
  1929. ):
  1930. r"""
  1931. start_positions (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`,
  1932. `optional`):
  1933. Labels for position (index) of the start of the labelled span for
  1934. computing the token classification loss. Positions are clamped to
  1935. the length of the sequence (:obj:`sequence_length`). Position
  1936. outside of the sequence are not taken into account for computing the
  1937. loss.
  1938. end_positions (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`,
  1939. `optional`):
  1940. Labels for position (index) of the end of the labelled span for
  1941. computing the token classification loss. Positions are clamped to
  1942. the length of the sequence (:obj:`sequence_length`). Position
  1943. outside of the sequence are not taken into account for computing the
  1944. loss.
  1945. """
  1946. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  1947. outputs = self.bert(
  1948. input_ids,
  1949. attention_mask=attention_mask,
  1950. token_type_ids=token_type_ids,
  1951. position_ids=position_ids,
  1952. head_mask=head_mask,
  1953. inputs_embeds=inputs_embeds,
  1954. output_attentions=output_attentions,
  1955. output_hidden_states=output_hidden_states,
  1956. return_dict=return_dict,
  1957. )
  1958. sequence_output = outputs[0]
  1959. logits = self.qa_outputs(sequence_output)
  1960. start_logits, end_logits = logits.split(1, dim=-1)
  1961. start_logits = start_logits.squeeze(-1)
  1962. end_logits = end_logits.squeeze(-1)
  1963. total_loss = None
  1964. if start_positions is not None and end_positions is not None:
  1965. # If we are on multi-GPU, split add a dimension
  1966. if len(start_positions.size()) > 1:
  1967. start_positions = start_positions.squeeze(-1)
  1968. if len(end_positions.size()) > 1:
  1969. end_positions = end_positions.squeeze(-1)
  1970. # sometimes the start/end positions are outside our model inputs, we ignore these terms
  1971. ignored_index = start_logits.size(1)
  1972. start_positions.clamp_(0, ignored_index)
  1973. end_positions.clamp_(0, ignored_index)
  1974. loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
  1975. start_loss = loss_fct(start_logits, start_positions)
  1976. end_loss = loss_fct(end_logits, end_positions)
  1977. total_loss = (start_loss + end_loss) / 2
  1978. if not return_dict:
  1979. output = (start_logits, end_logits) + outputs[2:]
  1980. return ((total_loss, )
  1981. + output) if total_loss is not None else output
  1982. return QuestionAnsweringModelOutput(
  1983. loss=total_loss,
  1984. start_logits=start_logits,
  1985. end_logits=end_logits,
  1986. hidden_states=outputs.hidden_states,
  1987. attentions=outputs.attentions,
  1988. )
  1989. class MGeoPreTrainedModel(TorchModel, PreTrainedModel):
  1990. """
  1991. An abstract class to handle weights initialization and a simple interface
  1992. for downloading and loading pretrained models.
  1993. """
  1994. config_class = BertConfig
  1995. base_model_prefix = 'bert'
  1996. supports_gradient_checkpointing = True
  1997. _keys_to_ignore_on_load_missing = [r'position_ids']
  1998. def __init__(self, config, **kwargs):
  1999. super().__init__(config.name_or_path, **kwargs)
  2000. super(Model, self).__init__(config)
  2001. def _init_weights(self, module):
  2002. """Initialize the weights"""
  2003. if isinstance(module, nn.Linear):
  2004. # Slightly different from the TF version which uses truncated_normal for initialization
  2005. # cf https://github.com/pytorch/pytorch/pull/5617
  2006. module.weight.data.normal_(
  2007. mean=0.0, std=self.config.initializer_range)
  2008. if module.bias is not None:
  2009. module.bias.data.zero_()
  2010. elif isinstance(module, nn.Embedding):
  2011. module.weight.data.normal_(
  2012. mean=0.0, std=self.config.initializer_range)
  2013. if module.padding_idx is not None:
  2014. module.weight.data[module.padding_idx].zero_()
  2015. elif isinstance(module, nn.LayerNorm):
  2016. module.bias.data.zero_()
  2017. module.weight.data.fill_(1.0)
  2018. def _set_gradient_checkpointing(self, module, value=False):
  2019. if isinstance(module, BertEncoder):
  2020. module.gradient_checkpointing = value
  2021. @classmethod
  2022. def _instantiate(cls, **kwargs):
  2023. """Instantiate the model.
  2024. Args:
  2025. kwargs: Input args.
  2026. model_dir: The model dir used to load the checkpoint and the
  2027. label information. num_labels: An optional arg to tell the
  2028. model how many classes to initialize.
  2029. Method will call utils.parse_label_mapping
  2030. if num_labels not supplied. If num_labels is
  2031. not found, the model will use the default
  2032. setting (2 classes).
  2033. Returns:
  2034. The loaded model, which is initialized by
  2035. transformers.PreTrainedModel.from_pretrained
  2036. """
  2037. model_dir = kwargs.pop('model_dir', None)
  2038. cfg = kwargs.pop('cfg', None)
  2039. model_args = parse_labels_in_order(model_dir, cfg, **kwargs)
  2040. if model_dir is None:
  2041. config = BertConfig(**model_args)
  2042. model = cls(config)
  2043. else:
  2044. model = super(Model, cls).from_pretrained(
  2045. pretrained_model_name_or_path=model_dir, **model_args)
  2046. model.model_dir = model_dir
  2047. return model
  2048. @MODELS.register_module(Tasks.backbone, module_name=Models.mgeo)
  2049. class MGeo(MGeoPreTrainedModel):
  2050. def __init__(self,
  2051. config: BertConfig,
  2052. finetune_mode: str = 'single-modal',
  2053. gis_num: int = 1,
  2054. add_pooling_layer=False,
  2055. **kwargs):
  2056. super().__init__(config)
  2057. self.finetune_mode = finetune_mode
  2058. self.config = config
  2059. self.text_encoder = BertModel(
  2060. config, add_pooling_layer=add_pooling_layer)
  2061. if self.finetune_mode == 'multi-modal':
  2062. gis_config = BertConfig.from_dict(config.gis_encoder)
  2063. self.gis_encoder = BertModel(gis_config, add_pooling_layer=False)
  2064. for param in self.gis_encoder.parameters():
  2065. param.requires_grad = False
  2066. self.gis2text = nn.Linear(gis_config.hidden_size,
  2067. self.config.hidden_size)
  2068. self.gis_type = nn.Embedding(gis_num, gis_config.hidden_size)
  2069. self.init_weights()
  2070. def forward(self,
  2071. input_ids=None,
  2072. attention_mask=None,
  2073. token_type_ids=None,
  2074. position_ids=None,
  2075. head_mask=None,
  2076. inputs_embeds=None,
  2077. encoder_embeds=None,
  2078. encoder_hidden_states=None,
  2079. encoder_attention_mask=None,
  2080. past_key_values=None,
  2081. use_cache=None,
  2082. output_attentions=None,
  2083. output_hidden_states=None,
  2084. return_dict=None,
  2085. is_decoder=False,
  2086. mode='single-modal',
  2087. gis_list=None,
  2088. gis_tp=None,
  2089. use_token_type=False):
  2090. if self.finetune_mode == 'multi-modal' and gis_list is not None and len(
  2091. gis_list) > 0:
  2092. gis_embs = []
  2093. gis_atts = []
  2094. for gis in gis_list:
  2095. gis_embs.append(
  2096. self.gis_encoder(return_dict=True, mode='text',
  2097. **gis).last_hidden_state)
  2098. gis_atts.append(gis['attention_mask'])
  2099. if use_token_type:
  2100. embedding_output = self.text_encoder.embeddings(
  2101. input_ids=input_ids,
  2102. position_ids=position_ids,
  2103. token_type_ids=token_type_ids,
  2104. )
  2105. else:
  2106. embedding_output = self.text_encoder.embeddings(
  2107. input_ids=input_ids, )
  2108. if self.finetune_mode == 'multi-modal' and gis_list is not None and len(
  2109. gis_list) > 0:
  2110. embs = [embedding_output]
  2111. atts = [attention_mask]
  2112. tp_emb = [self.gis_type(gtp) for gtp in gis_tp]
  2113. for ge, ga, gt in zip(gis_embs, gis_atts, tp_emb):
  2114. embs.append(self.gis2text(ge + gt))
  2115. atts.append(ga)
  2116. merge_emb = torch.cat(embs, dim=1)
  2117. merge_attention = torch.cat(atts, dim=-1)
  2118. else:
  2119. merge_emb = embedding_output
  2120. merge_attention = attention_mask
  2121. encoder_outputs = self.text_encoder(
  2122. attention_mask=merge_attention,
  2123. encoder_embeds=merge_emb,
  2124. output_attentions=output_attentions,
  2125. output_hidden_states=output_hidden_states,
  2126. return_dict=return_dict,
  2127. mode='text')
  2128. if not return_dict:
  2129. return encoder_outputs
  2130. return AttentionBackboneModelOutput(
  2131. last_hidden_state=encoder_outputs.last_hidden_state,
  2132. pooler_output=encoder_outputs.pooler_output,
  2133. past_key_values=encoder_outputs.past_key_values,
  2134. hidden_states=encoder_outputs.hidden_states,
  2135. attentions=encoder_outputs.attentions,
  2136. cross_attentions=encoder_outputs.cross_attentions,
  2137. )
  2138. return output
  2139. def extract_sequence_outputs(self, outputs):
  2140. return outputs['last_hidden_state']
  2141. def extract_pooled_outputs(self, outputs):
  2142. return outputs['pooler_output']