modelingpreln.py 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619
  1. # Copyright (c) Microsoft Corporation.
  2. # SPDX-License-Identifier: Apache-2.0
  3. # DeepSpeed Team
  4. from __future__ import absolute_import, division, print_function, unicode_literals
  5. # Copyright The Microsoft DeepSpeed Team
  6. # DeepSpeed note, code taken from commit 3d59216cec89a363649b4fe3d15295ba936ced0f
  7. # https://github.com/NVIDIA/DeepLearningExamples/blob/master/PyTorch/LanguageModeling/BERT/modeling.py
  8. # coding=utf-8
  9. # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
  10. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
  11. #
  12. # Licensed under the Apache License, Version 2.0 (the "License");
  13. # you may not use this file except in compliance with the License.
  14. # You may obtain a copy of the License at
  15. #
  16. # http://www.apache.org/licenses/LICENSE-2.0
  17. #
  18. # Unless required by applicable law or agreed to in writing, software
  19. # distributed under the License is distributed on an "AS IS" BASIS,
  20. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  21. # See the License for the specific language governing permissions and
  22. # limitations under the License.
  23. """PyTorch BERT model."""
  24. import copy
  25. import json
  26. import logging
  27. import math
  28. import os
  29. import shutil
  30. import tarfile
  31. import tempfile
  32. from io import open
  33. import torch
  34. from torch import nn
  35. from torch.nn import CrossEntropyLoss
  36. from torch.utils import checkpoint
  37. import deepspeed.comm as dist
  38. from torch.nn import Module
  39. import torch.nn.functional as F
  40. import torch.nn.init as init
  41. from deepspeed.accelerator import get_accelerator
  42. #from numba import cuda
  43. #from deepspeed_cuda import DeepSpeedSoftmaxConfig, DeepSpeedSoftmax
  44. logger = logging.getLogger(__name__)
  45. PRETRAINED_MODEL_ARCHIVE_MAP = {
  46. 'bert-base-uncased': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-uncased.tar.gz",
  47. 'bert-large-uncased': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased.tar.gz",
  48. 'bert-base-cased': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-cased.tar.gz",
  49. 'bert-large-cased': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased.tar.gz",
  50. 'bert-base-multilingual-uncased':
  51. "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-multilingual-uncased.tar.gz",
  52. 'bert-base-multilingual-cased':
  53. "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-multilingual-cased.tar.gz",
  54. 'bert-base-chinese': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-chinese.tar.gz",
  55. }
  56. CONFIG_NAME = 'bert_config.json'
  57. WEIGHTS_NAME = 'pytorch_model.bin'
  58. TF_WEIGHTS_NAME = 'model.ckpt'
  59. def load_tf_weights_in_bert(model, tf_checkpoint_path):
  60. """ Load tf checkpoints in a pytorch model
  61. """
  62. try:
  63. import re
  64. import numpy as np
  65. import tensorflow as tf
  66. except ImportError:
  67. print("Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please see "
  68. "https://www.tensorflow.org/install/ for installation instructions.")
  69. raise
  70. tf_path = os.path.abspath(tf_checkpoint_path)
  71. print("Converting TensorFlow checkpoint from {}".format(tf_path))
  72. # Load weights from TF model
  73. init_vars = tf.train.list_variables(tf_path)
  74. names = []
  75. arrays = []
  76. for name, shape in init_vars:
  77. print("Loading TF weight {} with shape {}".format(name, shape))
  78. array = tf.train.load_variable(tf_path, name)
  79. names.append(name)
  80. arrays.append(array)
  81. for name, array in zip(names, arrays):
  82. name = name.split('/')
  83. # adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v
  84. # which are not required for using pretrained model
  85. if any(n in ["adam_v", "adam_m"] for n in name):
  86. print("Skipping {}".format("/".join(name)))
  87. continue
  88. pointer = model
  89. for m_name in name:
  90. if re.fullmatch(r'[A-Za-z]+_\d+', m_name):
  91. l = re.split(r'_(\d+)', m_name)
  92. else:
  93. l = [m_name]
  94. if l[0] == 'kernel' or l[0] == 'gamma':
  95. pointer = getattr(pointer, 'weight')
  96. elif l[0] == 'output_bias' or l[0] == 'beta':
  97. pointer = getattr(pointer, 'bias')
  98. elif l[0] == 'output_weights':
  99. pointer = getattr(pointer, 'weight')
  100. else:
  101. pointer = getattr(pointer, l[0])
  102. if len(l) >= 2:
  103. num = int(l[1])
  104. pointer = pointer[num]
  105. if m_name[-11:] == '_embeddings':
  106. pointer = getattr(pointer, 'weight')
  107. elif m_name == 'kernel':
  108. array = np.transpose(array)
  109. try:
  110. assert pointer.shape == array.shape
  111. except AssertionError as e:
  112. e.args += (pointer.shape, array.shape)
  113. raise
  114. print("Initialize PyTorch weight {}".format(name))
  115. pointer.data = torch.from_numpy(array)
  116. return model
  117. """
  118. @torch.jit.script
  119. def f_gelu(x):
  120. return x * 0.5 * (1.0 + torch.erf(x / 1.41421))
  121. @torch.jit.script
  122. def bias_gelu(bias, y):
  123. x = bias + y
  124. return x * 0.5 * (1.0 + torch.erf(x / 1.41421))
  125. @torch.jit.script
  126. def bias_tanh(bias, y):
  127. x = bias + y
  128. return torch.tanh(x)
  129. """
  130. def f_gelu(x):
  131. x_type = x.dtype
  132. x = x.float()
  133. x = x * 0.5 * (1.0 + torch.erf(x / 1.41421))
  134. return x.to(x_type)
  135. def bias_gelu(bias, y):
  136. y_type = y.dtype
  137. x = bias.float() + y.float()
  138. x = x * 0.5 * (1.0 + torch.erf(x / 1.41421))
  139. return x.to(y_type)
  140. def bias_tanh(bias, y):
  141. y_type = y.dtype
  142. x = bias.float() + y.float()
  143. x = torch.tanh(x)
  144. return x.to(y_type)
  145. def gelu(x):
  146. """Implementation of the gelu activation function.
  147. For information: OpenAI GPT's gelu is slightly different (and gives slightly different results):
  148. 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3))))
  149. Also see https://arxiv.org/abs/1606.08415
  150. """
  151. return f_gelu(x)
  152. def swish(x):
  153. return x * torch.sigmoid(x)
  154. ACT2FN = {"gelu": gelu, "relu": torch.nn.functional.relu, "swish": swish}
  155. class GPUTimer:
  156. def __init__(self):
  157. super().__init__()
  158. self.start = get_accelerator().Event() # noqa: F821
  159. self.stop = get_accelerator().Event() # noqa: F821
  160. def record(self):
  161. self.start.record()
  162. def elapsed(self):
  163. self.stop.record()
  164. self.stop.synchronize()
  165. return self.start.elapsed_time(self.stop) / 1000.0
  166. class LinearActivation(Module):
  167. r"""Fused Linear and activation Module.
  168. """
  169. __constants__ = ['bias']
  170. def __init__(self, in_features, out_features, weights, biases, act='gelu', bias=True):
  171. super(LinearActivation, self).__init__()
  172. self.in_features = in_features
  173. self.out_features = out_features
  174. self.fused_gelu = False
  175. self.fused_tanh = False
  176. if isinstance(act, str):
  177. if bias and act == 'gelu':
  178. self.fused_gelu = True
  179. elif bias and act == 'tanh':
  180. self.fused_tanh = True
  181. else:
  182. self.act_fn = ACT2FN[act]
  183. else:
  184. self.act_fn = act
  185. #self.weight = Parameter(torch.Tensor(out_features, in_features))
  186. self.weight = weights[5]
  187. self.bias = biases[5]
  188. #if bias:
  189. # self.bias = Parameter(torch.Tensor(out_features))
  190. #else:
  191. # self.register_parameter('bias', None)
  192. #self.reset_parameters()
  193. def reset_parameters(self):
  194. init.kaiming_uniform_(self.weight, a=math.sqrt(5))
  195. if self.bias is not None:
  196. fan_in, _ = init._calculate_fan_in_and_fan_out(self.weight)
  197. bound = 1 / math.sqrt(fan_in)
  198. init.uniform_(self.bias, -bound, bound)
  199. def forward(self, input):
  200. if self.fused_gelu:
  201. #timing = []
  202. #t1 = GPUTimer()
  203. #t1.record()
  204. y = F.linear(input, self.weight, None)
  205. #timing.append(t1.elapsed())
  206. #t1.record()
  207. bg = bias_gelu(self.bias, y)
  208. #timing.append(t1.elapsed())
  209. return bg
  210. elif self.fused_tanh:
  211. return bias_tanh(self.bias, F.linear(input, self.weight, None))
  212. else:
  213. return self.act_fn(F.linear(input, self.weight, self.bias))
  214. def extra_repr(self):
  215. return 'in_features={}, out_features={}, bias={}'.format(self.in_features, self.out_features, self.bias
  216. is not None)
  217. class BertConfig(object):
  218. """Configuration class to store the configuration of a `BertModel`.
  219. """
  220. def __init__(self,
  221. vocab_size_or_config_json_file,
  222. hidden_size=768,
  223. num_hidden_layers=12,
  224. num_attention_heads=12,
  225. intermediate_size=3072,
  226. batch_size=8,
  227. hidden_act="gelu",
  228. hidden_dropout_prob=0.1,
  229. attention_probs_dropout_prob=0.1,
  230. max_position_embeddings=512,
  231. type_vocab_size=2,
  232. initializer_range=0.02,
  233. fp16=False):
  234. """Constructs BertConfig.
  235. Args:
  236. vocab_size_or_config_json_file: Vocabulary size of `inputs_ids` in `BertModel`.
  237. hidden_size: Size of the encoder layers and the pooler layer.
  238. num_hidden_layers: Number of hidden layers in the Transformer encoder.
  239. num_attention_heads: Number of attention heads for each attention layer in
  240. the Transformer encoder.
  241. intermediate_size: The size of the "intermediate" (i.e., feed-forward)
  242. layer in the Transformer encoder.
  243. hidden_act: The non-linear activation function (function or string) in the
  244. encoder and pooler. If string, "gelu", "relu" and "swish" are supported.
  245. hidden_dropout_prob: The dropout probability for all fully connected
  246. layers in the embeddings, encoder, and pooler.
  247. attention_probs_dropout_prob: The dropout ratio for the attention
  248. probabilities.
  249. max_position_embeddings: The maximum sequence length that this model might
  250. ever be used with. Typically set this to something large just in case
  251. (e.g., 512 or 1024 or 2048).
  252. type_vocab_size: The vocabulary size of the `token_type_ids` passed into
  253. `BertModel`.
  254. initializer_range: The sttdev of the truncated_normal_initializer for
  255. initializing all weight matrices.
  256. """
  257. if isinstance(vocab_size_or_config_json_file, str):
  258. with open(vocab_size_or_config_json_file, "r", encoding='utf-8') as reader:
  259. json_config = json.loads(reader.read())
  260. for key, value in json_config.items():
  261. self.__dict__[key] = value
  262. elif isinstance(vocab_size_or_config_json_file, int):
  263. self.vocab_size = vocab_size_or_config_json_file
  264. self.hidden_size = hidden_size
  265. self.num_hidden_layers = num_hidden_layers
  266. self.num_attention_heads = num_attention_heads
  267. self.batch_size = batch_size
  268. self.hidden_act = hidden_act
  269. self.intermediate_size = intermediate_size
  270. self.hidden_dropout_prob = hidden_dropout_prob
  271. self.attention_probs_dropout_prob = attention_probs_dropout_prob
  272. self.max_position_embeddings = max_position_embeddings
  273. self.type_vocab_size = type_vocab_size
  274. self.initializer_range = initializer_range
  275. self.fp16 = fp16
  276. else:
  277. raise ValueError("First argument must be either a vocabulary size (int)"
  278. "or the path to a pretrained model config file (str)")
  279. @classmethod
  280. def from_dict(cls, json_object):
  281. """Constructs a `BertConfig` from a Python dictionary of parameters."""
  282. config = BertConfig(vocab_size_or_config_json_file=-1)
  283. for key, value in json_object.items():
  284. config.__dict__[key] = value
  285. return config
  286. @classmethod
  287. def from_json_file(cls, json_file):
  288. """Constructs a `BertConfig` from a json file of parameters."""
  289. with open(json_file, "r", encoding='utf-8') as reader:
  290. text = reader.read()
  291. return cls.from_dict(json.loads(text))
  292. def __repr__(self):
  293. return str(self.to_json_string())
  294. def to_dict(self):
  295. """Serializes this instance to a Python dictionary."""
  296. output = copy.deepcopy(self.__dict__)
  297. return output
  298. def to_json_string(self):
  299. """Serializes this instance to a JSON string."""
  300. return json.dumps(self.to_dict(), indent=2, sort_keys=True) + "\n"
  301. try:
  302. import apex
  303. #apex.amp.register_half_function(apex.normalization.fused_layer_norm, 'FusedLayerNorm')
  304. import apex.normalization
  305. #apex.amp.register_float_function(apex.normalization.FusedLayerNorm, 'forward')
  306. BertLayerNorm = apex.normalization.FusedLayerNorm
  307. except ImportError:
  308. print("Better speed can be achieved with apex installed from https://www.github.com/nvidia/apex.")
  309. class BertLayerNorm(nn.Module):
  310. def __init__(self, hidden_size, eps=1e-12):
  311. """Construct a layernorm module in the TF style (epsilon inside the square root).
  312. """
  313. super(BertLayerNorm, self).__init__()
  314. self.weight = nn.Parameter(torch.ones(hidden_size))
  315. self.bias = nn.Parameter(torch.zeros(hidden_size))
  316. self.variance_epsilon = eps
  317. def forward(self, x):
  318. pdtype = x.dtype
  319. x = x.float()
  320. u = x.mean(-1, keepdim=True)
  321. s = (x - u).pow(2).mean(-1, keepdim=True)
  322. x = (x - u) / torch.sqrt(s + self.variance_epsilon)
  323. return self.weight * x.to(pdtype) + self.bias
  324. #def forward(self, x):
  325. # u = x.mean(-1, keepdim=True)
  326. # s = (x - u).pow(2).mean(-1, keepdim=True)
  327. # x = (x - u) / torch.sqrt(s + self.variance_epsilon)
  328. # return self.weight * x + self.bias
  329. class BertEmbeddings(nn.Module):
  330. """Construct the embeddings from word, position and token_type embeddings.
  331. """
  332. def __init__(self, config):
  333. super(BertEmbeddings, self).__init__()
  334. self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size)
  335. self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
  336. self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
  337. # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
  338. # any TensorFlow checkpoint file
  339. self.LayerNorm = BertLayerNorm(config.hidden_size, eps=1e-12)
  340. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  341. def forward(self, input_ids, token_type_ids=None):
  342. seq_length = input_ids.size(1)
  343. position_ids = torch.arange(seq_length, dtype=torch.long, device=input_ids.device)
  344. position_ids = position_ids.unsqueeze(0).expand_as(input_ids)
  345. if token_type_ids is None:
  346. token_type_ids = torch.zeros_like(input_ids)
  347. words_embeddings = self.word_embeddings(input_ids)
  348. position_embeddings = self.position_embeddings(position_ids)
  349. token_type_embeddings = self.token_type_embeddings(token_type_ids)
  350. embeddings = words_embeddings + position_embeddings + token_type_embeddings
  351. embeddings = self.LayerNorm(embeddings)
  352. embeddings = self.dropout(embeddings)
  353. return embeddings
  354. class BertSelfAttention(nn.Module):
  355. def __init__(self, i, config, weights, biases):
  356. super(BertSelfAttention, self).__init__()
  357. if config.hidden_size % config.num_attention_heads != 0:
  358. raise ValueError("The hidden size (%d) is not a multiple of the number of attention "
  359. "heads (%d)" % (config.hidden_size, config.num_attention_heads))
  360. self.num_attention_heads = config.num_attention_heads
  361. self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
  362. self.all_head_size = self.num_attention_heads * self.attention_head_size
  363. self.query = nn.Linear(config.hidden_size, self.all_head_size)
  364. self.query.weight = weights[0]
  365. self.query.bias = biases[0]
  366. self.key = nn.Linear(config.hidden_size, self.all_head_size)
  367. self.key.weight = weights[1]
  368. self.key.bias = biases[1]
  369. self.value = nn.Linear(config.hidden_size, self.all_head_size)
  370. self.value.weight = weights[2]
  371. self.value.bias = biases[2]
  372. self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
  373. self.softmax = nn.Softmax(dim=-1)
  374. #self.softmax_config = DeepSpeedSoftmaxConfig()
  375. #self.softmax_config.batch_size = config.batch_size
  376. #self.softmax_config.max_seq_length = config.max_position_embeddings
  377. #self.softmax_config.hidden_size = config.hidden_size
  378. #self.softmax_config.heads = config.num_attention_heads
  379. #self.softmax_config.softmax_id = i
  380. #self.softmax_config.fp16 = config.fp16
  381. #self.softmax_config.prob_drop_out = 0.0
  382. #self.softmax = DeepSpeedSoftmax(i, self.softmax_config)
  383. def transpose_for_scores(self, x):
  384. new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
  385. x = x.view(*new_x_shape)
  386. return x.permute(0, 2, 1, 3)
  387. def transpose_key_for_scores(self, x):
  388. new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
  389. x = x.view(*new_x_shape)
  390. return x.permute(0, 2, 3, 1)
  391. def forward(self, hidden_states, attention_mask, grads=None):
  392. #timing = []
  393. #t1 = GPUTimer()
  394. #t1.record()
  395. mixed_query_layer = self.query(hidden_states)
  396. #timing.append(t1.elapsed())
  397. #print("Query elapsed: %s" % (time.clock() - start))
  398. #t1.record()
  399. mixed_key_layer = self.key(hidden_states)
  400. #timing.append(t1.elapsed())
  401. #print("Key elapsed: %s" % (time.clock() - start))
  402. #t1.record()
  403. mixed_value_layer = self.value(hidden_states)
  404. #timing.append(t1.elapsed())
  405. #print("Value elapsed: %s" % (time.clock() - start))
  406. #t1.record()
  407. query_layer = self.transpose_for_scores(mixed_query_layer)
  408. # print(query_layer)
  409. #timing.append(t1.elapsed())
  410. #print("Query-Transform elapsed: %s" % (time.clock() - start))
  411. #t1.record()
  412. key_layer = self.transpose_key_for_scores(mixed_key_layer)
  413. # print(key_layer)
  414. #timing.append(t1.elapsed())
  415. #print("Key-Transform elapsed: %s" % (time.clock() - start))
  416. #t1.record()
  417. value_layer = self.transpose_for_scores(mixed_value_layer)
  418. #print(value_layer)
  419. #timing.append(t1.elapsed())
  420. #print("Value-Transform elapsed: %s" % (time.clock() - start))
  421. # Take the dot product between "query" and "key" to get the raw attention scores.
  422. #t1.record()
  423. #print(query_layer.shape)
  424. #print(key_layer.shape)
  425. attention_scores = torch.matmul(query_layer, key_layer)
  426. #print(attention_scores.shape)
  427. attention_scores = attention_scores / math.sqrt(self.attention_head_size)
  428. #print("Pytorch: ", attention_scores)
  429. #timing.append(t1.elapsed())
  430. #print("Attention-Score elapsed: %s" % (time.clock() - start))
  431. # Apply the attention mask is (precomputed for all layers in BertModel forward() function)
  432. #t1.record()
  433. # context_layer = self.softmax(query_layer, key_layer, value_layer, attention_mask)
  434. #print("context shape is :", context_layer.shape)
  435. #print("Cuda-ext:, ", attention_scores1)
  436. # Normalize the attention scores to probabilities.
  437. ####attention_probs = self.softmax(attention_scores)
  438. #timing.append(t1.elapsed())
  439. #print("Softmax elapsed: %s" % (time.clock() - start))
  440. #t1 = GPUTimer()
  441. #t1.record()
  442. attention_scores = attention_scores + attention_mask
  443. attention_probs = self.softmax(attention_scores)
  444. #attention_scores = self.softmax(attention_scores, attention_mask)
  445. #print("Softmax elapse {0:8.2f} ms", t1.elapsed() * 1000)
  446. # This is actually dropping out entire tokens to attend to, which might
  447. # seem a bit unusual, but is taken from the original Transformer paper.
  448. attention_probs = self.dropout(attention_probs)
  449. #t1.record()
  450. context_layer = torch.matmul(attention_probs, value_layer)
  451. #timing.append(t1.elapsed())
  452. #print("Context elapsed: %s" % (time.clock() - start))
  453. #t1.record()
  454. #context_layer1 = context_layer.permute(
  455. # 0, 1, 3, 2, 4).contiguous()
  456. #if grads is not None:
  457. # context_layer.register_hook(lambda x, self = self : grads.append([x, "Context"]))
  458. context_layer1 = context_layer.permute(0, 2, 1, 3).contiguous()
  459. new_context_layer_shape = context_layer1.size()[:-2] + (self.all_head_size, )
  460. context_layer1 = context_layer1.view(*new_context_layer_shape)
  461. #timing.append(t1.elapsed())
  462. #print("Context-Transform elapsed: %s" % (time.clock() - start))
  463. if grads is not None:
  464. query_layer.register_hook(lambda x, self=self: grads.append([x, "Query"]))
  465. key_layer.register_hook(lambda x, self=self: grads.append([x, "Key"]))
  466. value_layer.register_hook(lambda x, self=self: grads.append([x, "Value"]))
  467. return context_layer1
  468. class BertSelfOutput(nn.Module):
  469. def __init__(self, config, weights, biases):
  470. super(BertSelfOutput, self).__init__()
  471. self.dense = nn.Linear(config.hidden_size, config.hidden_size)
  472. self.dense.weight = weights[3]
  473. self.dense.bias = biases[3]
  474. self.LayerNorm = BertLayerNorm(config.hidden_size, eps=1e-12)
  475. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  476. def forward(self, hidden_states, input_tensor):
  477. #timing = []
  478. #t1 = GPUTimer()
  479. #t1.record()
  480. hidden_states = self.dense(hidden_states)
  481. #timing.append(t1.elapsed())
  482. #print("Attention Output elapsed: %s" % (time.clock() - start))
  483. hidden_states = self.dropout(hidden_states)
  484. #t1.record()
  485. #hidden_states = self.LayerNorm(hidden_states + input_tensor)
  486. #timing.append(t1.elapsed())
  487. #print("LayerNorm elapsed: %s" % (time.clock() - start))
  488. return hidden_states
  489. def get_w(self):
  490. return self.dense.weight
  491. class BertAttention(nn.Module):
  492. def __init__(self, i, config, weights, biases):
  493. super(BertAttention, self).__init__()
  494. self.self = BertSelfAttention(i, config, weights, biases)
  495. self.output = BertSelfOutput(config, weights, biases)
  496. def forward(self, input_tensor, attention_mask):
  497. self_output = self.self(input_tensor, attention_mask)
  498. attention_output = self.output(self_output, input_tensor)
  499. return attention_output
  500. def get_w(self):
  501. return self.output.get_w()
  502. class BertIntermediate(nn.Module):
  503. def __init__(self, config, weights, biases):
  504. super(BertIntermediate, self).__init__()
  505. self.dense_act = LinearActivation(config.hidden_size,
  506. config.intermediate_size,
  507. weights,
  508. biases,
  509. act=config.hidden_act)
  510. def forward(self, hidden_states):
  511. hidden_states = self.dense_act(hidden_states)
  512. return hidden_states
  513. class BertOutput(nn.Module):
  514. def __init__(self, config, weights, biases):
  515. super(BertOutput, self).__init__()
  516. self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
  517. self.dense.weight = weights[6]
  518. self.dense.bias = biases[6]
  519. self.LayerNorm = BertLayerNorm(config.hidden_size, eps=1e-12)
  520. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  521. def forward(self, hidden_states, input_tensor):
  522. #timing = []
  523. #t1 = GPUTimer()
  524. #t1.record()
  525. #print (hidden_states)
  526. #print (self.dense.weight)
  527. hidden_states = self.dense(hidden_states)
  528. #timing.append(t1.elapsed())
  529. #print("FF2 elapsed: %s" % (time.clock() - start))
  530. hidden_states = self.dropout(hidden_states)
  531. #t1.record()
  532. #hidden_states = self.LayerNorm(hidden_states + input_tensor)
  533. #timing.append(t1.elapsed())
  534. #print("LayerNorm elapsed: %s" % (time.clock() - start))
  535. return hidden_states
  536. class BertLayer(nn.Module):
  537. def __init__(self, i, config, weights, biases):
  538. super(BertLayer, self).__init__()
  539. self.attention = BertAttention(i, config, weights, biases)
  540. self.PreAttentionLayerNorm = BertLayerNorm(config.hidden_size, eps=1e-12)
  541. self.PostAttentionLayerNorm = BertLayerNorm(config.hidden_size, eps=1e-12)
  542. self.intermediate = BertIntermediate(config, weights, biases)
  543. self.output = BertOutput(config, weights, biases)
  544. self.weight = weights
  545. self.biases = biases
  546. def forward(self, hidden_states, attention_mask, grads, collect_all_grads=False):
  547. input_layer_norm = self.PreAttentionLayerNorm(hidden_states)
  548. attention_output = self.attention(input_layer_norm, attention_mask)
  549. #print ("hidden shape is :", hidden_states.shape)
  550. intermediate_input = hidden_states + attention_output
  551. intermediate_layer_norm = self.PostAttentionLayerNorm(intermediate_input)
  552. intermediate_output = self.intermediate(intermediate_layer_norm)
  553. layer_output = self.output(intermediate_output, attention_output)
  554. #attention_output = self.attention(hidden_states, attention_mask)
  555. #intermediate_output = self.intermediate(attention_output)
  556. #layer_output = self.output(intermediate_output, attention_output)
  557. if collect_all_grads:
  558. # self.weight[0].register_hook(lambda x, self=self: grads.append([x,"Q_W"]))
  559. # self.biases[0].register_hook(lambda x, self=self: grads.append([x,"Q_B"]))
  560. # self.weight[1].register_hook(lambda x, self=self: grads.append([x,"K_W"]))
  561. # self.biases[1].register_hook(lambda x, self=self: grads.append([x,"K_B"]))
  562. self.weight[2].register_hook(lambda x, self=self: grads.append([x, "V_W"]))
  563. self.biases[2].register_hook(lambda x, self=self: grads.append([x, "V_B"]))
  564. self.weight[3].register_hook(lambda x, self=self: grads.append([x, "O_W"]))
  565. self.biases[3].register_hook(lambda x, self=self: grads.append([x, "O_B"]))
  566. self.PostAttentionLayerNorm.weight.register_hook(lambda x, self=self: grads.append([x, "N2_W"]))
  567. self.PostAttentionLayerNorm.bias.register_hook(lambda x, self=self: grads.append([x, "N2_B"]))
  568. self.weight[5].register_hook(lambda x, self=self: grads.append([x, "int_W"]))
  569. self.biases[5].register_hook(lambda x, self=self: grads.append([x, "int_B"]))
  570. self.weight[6].register_hook(lambda x, self=self: grads.append([x, "out_W"]))
  571. self.biases[6].register_hook(lambda x, self=self: grads.append([x, "out_B"]))
  572. self.PreAttentionLayerNorm.weight.register_hook(lambda x, self=self: grads.append([x, "norm_W"]))
  573. self.PreAttentionLayerNorm.bias.register_hook(lambda x, self=self: grads.append([x, "norm_B"]))
  574. return layer_output + intermediate_input
  575. def get_w(self):
  576. return self.attention.get_w()
  577. class BertEncoder(nn.Module):
  578. def __init__(self, config, weights, biases):
  579. super(BertEncoder, self).__init__()
  580. #layer = BertLayer(config, weights, biases)
  581. self.FinalLayerNorm = BertLayerNorm(config.hidden_size, eps=1e-12)
  582. self.layer = nn.ModuleList(
  583. [copy.deepcopy(BertLayer(i, config, weights, biases)) for i in range(config.num_hidden_layers)])
  584. self.grads = []
  585. self.graph = []
  586. def get_grads(self):
  587. return self.grads
  588. # def forward(self, hidden_states, attention_mask, output_all_encoded_layers=True):
  589. # all_encoder_layers = []
  590. # for layer_module in self.layer:
  591. # hidden_states = layer_module(hidden_states, attention_mask)
  592. # if output_all_encoded_layers:
  593. # all_encoder_layers.append(hidden_states)
  594. # if not output_all_encoded_layers:
  595. # all_encoder_layers.append(hidden_states)
  596. # return all_encoder_layers
  597. def get_modules(self, big_node, input):
  598. for mdl in big_node.named_children():
  599. self.graph.append(mdl)
  600. self.get_modules(self, mdl, input)
  601. def forward(self, hidden_states, attention_mask, output_all_encoded_layers=True, checkpoint_activations=False):
  602. all_encoder_layers = []
  603. def custom(start, end):
  604. def custom_forward(*inputs):
  605. layers = self.layer[start:end]
  606. x_ = inputs[0]
  607. for layer in layers:
  608. x_ = layer(x_, inputs[1])
  609. return x_
  610. return custom_forward
  611. if checkpoint_activations:
  612. l = 0
  613. num_layers = len(self.layer)
  614. chunk_length = math.ceil(math.sqrt(num_layers))
  615. while l < num_layers:
  616. hidden_states = checkpoint.checkpoint(custom(l, l + chunk_length), hidden_states, attention_mask * 1)
  617. l += chunk_length
  618. # decoder layers
  619. else:
  620. for i, layer_module in enumerate(self.layer):
  621. hidden_states = layer_module(hidden_states, attention_mask, self.grads, collect_all_grads=True)
  622. hidden_states.register_hook(lambda x, i=i, self=self: self.grads.append([x, "hidden_state"]))
  623. #print("pytorch weight is: ", layer_module.get_w())
  624. if output_all_encoded_layers:
  625. all_encoder_layers.append((hidden_states))
  626. if not output_all_encoded_layers or checkpoint_activations:
  627. hidden_states = self.FinalLayerNorm(hidden_states)
  628. all_encoder_layers.append((hidden_states))
  629. return all_encoder_layers
  630. #class BertEncoder(nn.Module):
  631. # def __init__(self, config):
  632. # super(BertEncoder, self).__init__()
  633. # layer = BertLayer(config)
  634. # self.layer = nn.ModuleList([copy.deepcopy(layer) for _ in range(config.num_hidden_layers)])
  635. #
  636. # def forward(self, hidden_states, attention_mask, output_all_encoded_layers=True):
  637. # all_encoder_layers = []
  638. # for layer_module in self.layer:
  639. # hidden_states = layer_module(hidden_states, attention_mask)
  640. # if output_all_encoded_layers:
  641. # all_encoder_layers.append(hidden_states)
  642. # if not output_all_encoded_layers:
  643. # all_encoder_layers.append(hidden_states)
  644. # return all_encoder_layers
  645. class BertPooler(nn.Module):
  646. def __init__(self, config):
  647. super(BertPooler, self).__init__()
  648. self.dense_act = LinearActivation(config.hidden_size, config.hidden_size, act="tanh")
  649. def forward(self, hidden_states):
  650. # We "pool" the model by simply taking the hidden state corresponding
  651. # to the first token.
  652. first_token_tensor = hidden_states[:, 0]
  653. pooled_output = self.dense_act(first_token_tensor)
  654. return pooled_output
  655. class BertPredictionHeadTransform(nn.Module):
  656. def __init__(self, config):
  657. super(BertPredictionHeadTransform, self).__init__()
  658. self.dense_act = LinearActivation(config.hidden_size, config.hidden_size, act=config.hidden_act)
  659. self.LayerNorm = BertLayerNorm(config.hidden_size, eps=1e-12)
  660. def forward(self, hidden_states):
  661. hidden_states = self.dense_act(hidden_states)
  662. hidden_states = self.LayerNorm(hidden_states)
  663. return hidden_states
  664. class BertLMPredictionHead(nn.Module):
  665. def __init__(self, config, bert_model_embedding_weights):
  666. super(BertLMPredictionHead, self).__init__()
  667. self.transform = BertPredictionHeadTransform(config)
  668. # The output weights are the same as the input embeddings, but there is
  669. # an output-only bias for each token.
  670. self.decoder = nn.Linear(bert_model_embedding_weights.size(1),
  671. bert_model_embedding_weights.size(0),
  672. bias=False)
  673. self.decoder.weight = bert_model_embedding_weights
  674. self.bias = nn.Parameter(torch.zeros(bert_model_embedding_weights.size(0)))
  675. def forward(self, hidden_states):
  676. hidden_states = self.transform(hidden_states)
  677. get_accelerator().range_push("decoder input.size() = {}, weight.size() = {}".format(
  678. hidden_states.size(), self.decoder.weight.size()))
  679. hidden_states = self.decoder(hidden_states) + self.bias
  680. get_accelerator().range_pop()
  681. return hidden_states
  682. class BertOnlyMLMHead(nn.Module):
  683. def __init__(self, config, bert_model_embedding_weights):
  684. super(BertOnlyMLMHead, self).__init__()
  685. self.predictions = BertLMPredictionHead(config, bert_model_embedding_weights)
  686. def forward(self, sequence_output):
  687. prediction_scores = self.predictions(sequence_output)
  688. return prediction_scores
  689. class BertOnlyNSPHead(nn.Module):
  690. def __init__(self, config):
  691. super(BertOnlyNSPHead, self).__init__()
  692. self.seq_relationship = nn.Linear(config.hidden_size, 2)
  693. def forward(self, pooled_output):
  694. seq_relationship_score = self.seq_relationship(pooled_output)
  695. return seq_relationship_score
  696. class BertPreTrainingHeads(nn.Module):
  697. def __init__(self, config, bert_model_embedding_weights):
  698. super(BertPreTrainingHeads, self).__init__()
  699. self.predictions = BertLMPredictionHead(config, bert_model_embedding_weights)
  700. self.seq_relationship = nn.Linear(config.hidden_size, 2)
  701. def forward(self, sequence_output, pooled_output):
  702. prediction_scores = self.predictions(sequence_output)
  703. seq_relationship_score = self.seq_relationship(pooled_output)
  704. return prediction_scores, seq_relationship_score
  705. class BertPreTrainedModel(nn.Module):
  706. """ An abstract class to handle weights initialization and
  707. a simple interface for downloading and loading pretrained models.
  708. """
  709. def __init__(self, config, *inputs, **kwargs):
  710. super(BertPreTrainedModel, self).__init__()
  711. if not isinstance(config, BertConfig):
  712. raise ValueError("Parameter config in `{}(config)` should be an instance of class `BertConfig`. "
  713. "To create a model from a Google pretrained model use "
  714. "`model = {}.from_pretrained(PRETRAINED_MODEL_NAME)`".format(
  715. self.__class__.__name__, self.__class__.__name__))
  716. self.config = config
  717. def init_bert_weights(self, module):
  718. """ Initialize the weights.
  719. """
  720. if isinstance(module, (nn.Linear, nn.Embedding)):
  721. # Slightly different from the TF version which uses truncated_normal for initialization
  722. # cf https://github.com/pytorch/pytorch/pull/5617
  723. module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
  724. elif isinstance(module, BertLayerNorm):
  725. module.bias.data.zero_()
  726. module.weight.data.fill_(1.0)
  727. if isinstance(module, nn.Linear) and module.bias is not None:
  728. module.bias.data.zero_()
  729. @classmethod
  730. def from_pretrained(cls,
  731. pretrained_model_name_or_path,
  732. state_dict=None,
  733. cache_dir=None,
  734. from_tf=False,
  735. *inputs,
  736. **kwargs):
  737. """
  738. Instantiate a BertPreTrainedModel from a pre-trained model file or a pytorch state dict.
  739. Download and cache the pre-trained model file if needed.
  740. Params:
  741. pretrained_model_name_or_path: either:
  742. - a str with the name of a pre-trained model to load selected in the list of:
  743. . `bert-base-uncased`
  744. . `bert-large-uncased`
  745. . `bert-base-cased`
  746. . `bert-large-cased`
  747. . `bert-base-multilingual-uncased`
  748. . `bert-base-multilingual-cased`
  749. . `bert-base-chinese`
  750. - a path or url to a pretrained model archive containing:
  751. . `bert_config.json` a configuration file for the model
  752. . `pytorch_model.bin` a PyTorch dump of a BertForPreTraining instance
  753. - a path or url to a pretrained model archive containing:
  754. . `bert_config.json` a configuration file for the model
  755. . `model.chkpt` a TensorFlow checkpoint
  756. from_tf: should we load the weights from a locally saved TensorFlow checkpoint
  757. cache_dir: an optional path to a folder in which the pre-trained models will be cached.
  758. state_dict: an optional state dictionary (collections.OrderedDict object) to use instead of Google pre-trained models
  759. *inputs, **kwargs: additional input for the specific Bert class
  760. (ex: num_labels for BertForSequenceClassification)
  761. """
  762. if pretrained_model_name_or_path in PRETRAINED_MODEL_ARCHIVE_MAP:
  763. archive_file = PRETRAINED_MODEL_ARCHIVE_MAP[pretrained_model_name_or_path]
  764. else:
  765. archive_file = pretrained_model_name_or_path
  766. if resolved_archive_file == archive_file: # noqa: F821
  767. logger.info("loading archive file {}".format(archive_file))
  768. else:
  769. logger.info("loading archive file {} from cache at {}".format(archive_file,
  770. resolved_archive_file)) # noqa: F821
  771. tempdir = None
  772. if os.path.isdir(resolved_archive_file) or from_tf: # noqa: F821
  773. serialization_dir = resolved_archive_file # noqa: F821
  774. else:
  775. # Extract archive to temp dir
  776. tempdir = tempfile.mkdtemp()
  777. logger.info("extracting archive file {} to temp dir {}".format(
  778. resolved_archive_file, # noqa: F821
  779. tempdir))
  780. with tarfile.open(resolved_archive_file, 'r:gz') as archive: # noqa: F821
  781. archive.extractall(tempdir)
  782. serialization_dir = tempdir
  783. # Load config
  784. config_file = os.path.join(serialization_dir, CONFIG_NAME)
  785. config = BertConfig.from_json_file(config_file)
  786. logger.info("Model config {}".format(config))
  787. # Instantiate model.
  788. model = cls(config, *inputs, **kwargs)
  789. if state_dict is None and not from_tf:
  790. weights_path = os.path.join(serialization_dir, WEIGHTS_NAME)
  791. state_dict = torch.load(weights_path, map_location='cpu' if not get_accelerator().is_available() else None)
  792. if tempdir:
  793. # Clean up temp dir
  794. shutil.rmtree(tempdir)
  795. if from_tf:
  796. # Directly load from a TensorFlow checkpoint
  797. weights_path = os.path.join(serialization_dir, TF_WEIGHTS_NAME)
  798. return load_tf_weights_in_bert(model, weights_path)
  799. # Load from a PyTorch state_dict
  800. old_keys = []
  801. new_keys = []
  802. for key in state_dict.keys():
  803. new_key = None
  804. if 'gamma' in key:
  805. new_key = key.replace('gamma', 'weight')
  806. if 'beta' in key:
  807. new_key = key.replace('beta', 'bias')
  808. if new_key:
  809. old_keys.append(key)
  810. new_keys.append(new_key)
  811. for old_key, new_key in zip(old_keys, new_keys):
  812. state_dict[new_key] = state_dict.pop(old_key)
  813. missing_keys = []
  814. unexpected_keys = []
  815. error_msgs = []
  816. # copy state_dict so _load_from_state_dict can modify it
  817. metadata = getattr(state_dict, '_metadata', None)
  818. state_dict = state_dict.copy()
  819. if metadata is not None:
  820. state_dict._metadata = metadata
  821. def load(module, prefix=''):
  822. local_metadata = {} if metadata is None else metadata.get(prefix[:-1], {})
  823. module._load_from_state_dict(state_dict, prefix, local_metadata, True, missing_keys, unexpected_keys,
  824. error_msgs)
  825. for name, child in module._modules.items():
  826. if child is not None:
  827. load(child, prefix + name + '.')
  828. start_prefix = ''
  829. if not hasattr(model, 'bert') and any(s.startswith('bert.') for s in state_dict.keys()):
  830. start_prefix = 'bert.'
  831. load(model, prefix=start_prefix)
  832. if len(missing_keys) > 0:
  833. logger.info("Weights of {} not initialized from pretrained model: {}".format(
  834. model.__class__.__name__, missing_keys))
  835. if len(unexpected_keys) > 0:
  836. logger.info("Weights from pretrained model not used in {}: {}".format(model.__class__.__name__,
  837. unexpected_keys))
  838. if len(error_msgs) > 0:
  839. raise RuntimeError('Error(s) in loading state_dict for {}:\n\t{}'.format(
  840. model.__class__.__name__, "\n\t".join(error_msgs)))
  841. return model
  842. class BertModel(BertPreTrainedModel):
  843. """BERT model ("Bidirectional Embedding Representations from a Transformer").
  844. Params:
  845. config: a BertConfig class instance with the configuration to build a new model
  846. Inputs:
  847. `input_ids`: a torch.LongTensor of shape [batch_size, sequence_length]
  848. with the word token indices in the vocabulary(see the tokens preprocessing logic in the scripts
  849. `extract_features.py`, `run_classifier.py` and `run_squad.py`)
  850. `token_type_ids`: an optional torch.LongTensor of shape [batch_size, sequence_length] with the token
  851. types indices selected in [0, 1]. Type 0 corresponds to a `sentence A` and type 1 corresponds to
  852. a `sentence B` token (see BERT paper for more details).
  853. `attention_mask`: an optional torch.LongTensor of shape [batch_size, sequence_length] with indices
  854. selected in [0, 1]. It's a mask to be used if the input sequence length is smaller than the max
  855. input sequence length in the current batch. It's the mask that we typically use for attention when
  856. a batch has varying length sentences.
  857. `output_all_encoded_layers`: boolean which controls the content of the `encoded_layers` output as described below. Default: `True`.
  858. Outputs: Tuple of (encoded_layers, pooled_output)
  859. `encoded_layers`: controlled by `output_all_encoded_layers` argument:
  860. - `output_all_encoded_layers=True`: outputs a list of the full sequences of encoded-hidden-states at the end
  861. of each attention block (i.e. 12 full sequences for BERT-base, 24 for BERT-large), each
  862. encoded-hidden-state is a torch.FloatTensor of size [batch_size, sequence_length, hidden_size],
  863. - `output_all_encoded_layers=False`: outputs only the full sequence of hidden-states corresponding
  864. to the last attention block of shape [batch_size, sequence_length, hidden_size],
  865. `pooled_output`: a torch.FloatTensor of size [batch_size, hidden_size] which is the output of a
  866. classifier pretrained on top of the hidden state associated to the first character of the
  867. input (`CLS`) to train on the Next-Sentence task (see BERT's paper).
  868. Example usage:
  869. ```python
  870. # Already been converted into WordPiece token ids
  871. input_ids = torch.LongTensor([[31, 51, 99], [15, 5, 0]])
  872. input_mask = torch.LongTensor([[1, 1, 1], [1, 1, 0]])
  873. token_type_ids = torch.LongTensor([[0, 0, 1], [0, 1, 0]])
  874. config = modeling.BertConfig(vocab_size_or_config_json_file=32000, hidden_size=768,
  875. num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072)
  876. model = modeling.BertModel(config=config)
  877. all_encoder_layers, pooled_output = model(input_ids, token_type_ids, input_mask)
  878. ```
  879. """
  880. def __init__(self, config):
  881. super(BertModel, self).__init__(config)
  882. self.embeddings = BertEmbeddings(config)
  883. self.encoder = BertEncoder(config)
  884. self.pooler = BertPooler(config)
  885. self.apply(self.init_bert_weights)
  886. def forward(self,
  887. input_ids,
  888. token_type_ids=None,
  889. attention_mask=None,
  890. output_all_encoded_layers=True,
  891. checkpoint_activations=False):
  892. if attention_mask is None:
  893. attention_mask = torch.ones_like(input_ids)
  894. if token_type_ids is None:
  895. token_type_ids = torch.zeros_like(input_ids)
  896. # We create a 3D attention mask from a 2D tensor mask.
  897. # Sizes are [batch_size, 1, 1, to_seq_length]
  898. # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
  899. # this attention mask is more simple than the triangular masking of causal attention
  900. # used in OpenAI GPT, we just need to prepare the broadcast dimension here.
  901. extended_attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)
  902. # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
  903. # masked positions, this operation will create a tensor which is 0.0 for
  904. # positions we want to attend and -10000.0 for masked positions.
  905. # Since we are adding it to the raw scores before the softmax, this is
  906. # effectively the same as removing these entirely.
  907. extended_attention_mask = extended_attention_mask.to(dtype=next(self.parameters()).dtype) # fp16 compatibility
  908. extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0
  909. embedding_output = self.embeddings(input_ids, token_type_ids)
  910. encoded_layers = self.encoder(embedding_output,
  911. extended_attention_mask,
  912. output_all_encoded_layers=output_all_encoded_layers,
  913. checkpoint_activations=checkpoint_activations)
  914. sequence_output = encoded_layers[-1]
  915. pooled_output = self.pooler(sequence_output)
  916. if not output_all_encoded_layers:
  917. encoded_layers = encoded_layers[-1]
  918. return encoded_layers, pooled_output
  919. class BertForPreTraining(BertPreTrainedModel):
  920. """BERT model with pre-training heads.
  921. This module comprises the BERT model followed by the two pre-training heads:
  922. - the masked language modeling head, and
  923. - the next sentence classification head.
  924. Params:
  925. config: a BertConfig class instance with the configuration to build a new model.
  926. Inputs:
  927. `input_ids`: a torch.LongTensor of shape [batch_size, sequence_length]
  928. with the word token indices in the vocabulary(see the tokens preprocessing logic in the scripts
  929. `extract_features.py`, `run_classifier.py` and `run_squad.py`)
  930. `token_type_ids`: an optional torch.LongTensor of shape [batch_size, sequence_length] with the token
  931. types indices selected in [0, 1]. Type 0 corresponds to a `sentence A` and type 1 corresponds to
  932. a `sentence B` token (see BERT paper for more details).
  933. `attention_mask`: an optional torch.LongTensor of shape [batch_size, sequence_length] with indices
  934. selected in [0, 1]. It's a mask to be used if the input sequence length is smaller than the max
  935. input sequence length in the current batch. It's the mask that we typically use for attention when
  936. a batch has varying length sentences.
  937. `masked_lm_labels`: optional masked language modeling labels: torch.LongTensor of shape [batch_size, sequence_length]
  938. with indices selected in [-1, 0, ..., vocab_size]. All labels set to -1 are ignored (masked), the loss
  939. is only computed for the labels set in [0, ..., vocab_size]
  940. `next_sentence_label`: optional next sentence classification loss: torch.LongTensor of shape [batch_size]
  941. with indices selected in [0, 1].
  942. 0 => next sentence is the continuation, 1 => next sentence is a random sentence.
  943. Outputs:
  944. if `masked_lm_labels` and `next_sentence_label` are not `None`:
  945. Outputs the total_loss which is the sum of the masked language modeling loss and the next
  946. sentence classification loss.
  947. if `masked_lm_labels` or `next_sentence_label` is `None`:
  948. Outputs a tuple comprising
  949. - the masked language modeling logits of shape [batch_size, sequence_length, vocab_size], and
  950. - the next sentence classification logits of shape [batch_size, 2].
  951. Example usage:
  952. ```python
  953. # Already been converted into WordPiece token ids
  954. input_ids = torch.LongTensor([[31, 51, 99], [15, 5, 0]])
  955. input_mask = torch.LongTensor([[1, 1, 1], [1, 1, 0]])
  956. token_type_ids = torch.LongTensor([[0, 0, 1], [0, 1, 0]])
  957. config = BertConfig(vocab_size_or_config_json_file=32000, hidden_size=768,
  958. num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072)
  959. model = BertForPreTraining(config)
  960. masked_lm_logits_scores, seq_relationship_logits = model(input_ids, token_type_ids, input_mask)
  961. ```
  962. """
  963. def __init__(self, config, args):
  964. super(BertForPreTraining, self).__init__(config)
  965. self.summary_writer = None
  966. if dist.get_rank() == 0:
  967. self.summary_writer = args.summary_writer
  968. self.samples_per_step = dist.get_world_size() * args.train_batch_size
  969. self.sample_count = self.samples_per_step
  970. self.bert = BertModel(config)
  971. self.cls = BertPreTrainingHeads(config, self.bert.embeddings.word_embeddings.weight)
  972. self.apply(self.init_bert_weights)
  973. def log_summary_writer(self, logs: dict, base='Train'):
  974. if dist.get_rank() == 0:
  975. module_name = "Samples" #self._batch_module_name.get(batch_type, self._get_batch_type_error(batch_type))
  976. for key, log in logs.items():
  977. self.summary_writer.add_scalar(f'{base}/{module_name}/{key}', log, self.sample_count)
  978. self.sample_count += self.samples_per_step
  979. def forward(self, batch, log=True):
  980. #input_ids, token_type_ids=None, attention_mask=None, masked_lm_labels=None, next_sentence_label=None, checkpoint_activations=False):
  981. input_ids = batch[1]
  982. token_type_ids = batch[3]
  983. attention_mask = batch[2]
  984. masked_lm_labels = batch[5]
  985. next_sentence_label = batch[4]
  986. checkpoint_activations = False
  987. sequence_output, pooled_output = self.bert(input_ids,
  988. token_type_ids,
  989. attention_mask,
  990. output_all_encoded_layers=False,
  991. checkpoint_activations=checkpoint_activations)
  992. prediction_scores, seq_relationship_score = self.cls(sequence_output, pooled_output)
  993. if masked_lm_labels is not None and next_sentence_label is not None:
  994. loss_fct = CrossEntropyLoss(ignore_index=-1)
  995. masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), masked_lm_labels.view(-1))
  996. next_sentence_loss = loss_fct(seq_relationship_score.view(-1, 2), next_sentence_label.view(-1))
  997. #print("loss is {} {}".format(masked_lm_loss, next_sentence_loss))
  998. total_loss = masked_lm_loss + next_sentence_loss
  999. # if log:
  1000. # self.log_summary_writer(logs={'train_loss': total_loss.item()})
  1001. return total_loss
  1002. else:
  1003. return prediction_scores, seq_relationship_score
  1004. class BertForMaskedLM(BertPreTrainedModel):
  1005. """BERT model with the masked language modeling head.
  1006. This module comprises the BERT model followed by the masked language modeling head.
  1007. Params:
  1008. config: a BertConfig class instance with the configuration to build a new model.
  1009. Inputs:
  1010. `input_ids`: a torch.LongTensor of shape [batch_size, sequence_length]
  1011. with the word token indices in the vocabulary(see the tokens preprocessing logic in the scripts
  1012. `extract_features.py`, `run_classifier.py` and `run_squad.py`)
  1013. `token_type_ids`: an optional torch.LongTensor of shape [batch_size, sequence_length] with the token
  1014. types indices selected in [0, 1]. Type 0 corresponds to a `sentence A` and type 1 corresponds to
  1015. a `sentence B` token (see BERT paper for more details).
  1016. `attention_mask`: an optional torch.LongTensor of shape [batch_size, sequence_length] with indices
  1017. selected in [0, 1]. It's a mask to be used if the input sequence length is smaller than the max
  1018. input sequence length in the current batch. It's the mask that we typically use for attention when
  1019. a batch has varying length sentences.
  1020. `masked_lm_labels`: masked language modeling labels: torch.LongTensor of shape [batch_size, sequence_length]
  1021. with indices selected in [-1, 0, ..., vocab_size]. All labels set to -1 are ignored (masked), the loss
  1022. is only computed for the labels set in [0, ..., vocab_size]
  1023. Outputs:
  1024. if `masked_lm_labels` is not `None`:
  1025. Outputs the masked language modeling loss.
  1026. if `masked_lm_labels` is `None`:
  1027. Outputs the masked language modeling logits of shape [batch_size, sequence_length, vocab_size].
  1028. Example usage:
  1029. ```python
  1030. # Already been converted into WordPiece token ids
  1031. input_ids = torch.LongTensor([[31, 51, 99], [15, 5, 0]])
  1032. input_mask = torch.LongTensor([[1, 1, 1], [1, 1, 0]])
  1033. token_type_ids = torch.LongTensor([[0, 0, 1], [0, 1, 0]])
  1034. config = BertConfig(vocab_size_or_config_json_file=32000, hidden_size=768,
  1035. num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072)
  1036. model = BertForMaskedLM(config)
  1037. masked_lm_logits_scores = model(input_ids, token_type_ids, input_mask)
  1038. ```
  1039. """
  1040. def __init__(self, config):
  1041. super(BertForMaskedLM, self).__init__(config)
  1042. self.bert = BertModel(config)
  1043. self.cls = BertOnlyMLMHead(config, self.bert.embeddings.word_embeddings.weight)
  1044. self.apply(self.init_bert_weights)
  1045. def forward(self,
  1046. input_ids,
  1047. token_type_ids=None,
  1048. attention_mask=None,
  1049. masked_lm_labels=None,
  1050. checkpoint_activations=False):
  1051. sequence_output, _ = self.bert(input_ids, token_type_ids, attention_mask, output_all_encoded_layers=False)
  1052. prediction_scores = self.cls(sequence_output)
  1053. if masked_lm_labels is not None:
  1054. loss_fct = CrossEntropyLoss(ignore_index=-1)
  1055. masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), masked_lm_labels.view(-1))
  1056. return masked_lm_loss
  1057. else:
  1058. return prediction_scores
  1059. class BertForNextSentencePrediction(BertPreTrainedModel):
  1060. """BERT model with next sentence prediction head.
  1061. This module comprises the BERT model followed by the next sentence classification head.
  1062. Params:
  1063. config: a BertConfig class instance with the configuration to build a new model.
  1064. Inputs:
  1065. `input_ids`: a torch.LongTensor of shape [batch_size, sequence_length]
  1066. with the word token indices in the vocabulary(see the tokens preprocessing logic in the scripts
  1067. `extract_features.py`, `run_classifier.py` and `run_squad.py`)
  1068. `token_type_ids`: an optional torch.LongTensor of shape [batch_size, sequence_length] with the token
  1069. types indices selected in [0, 1]. Type 0 corresponds to a `sentence A` and type 1 corresponds to
  1070. a `sentence B` token (see BERT paper for more details).
  1071. `attention_mask`: an optional torch.LongTensor of shape [batch_size, sequence_length] with indices
  1072. selected in [0, 1]. It's a mask to be used if the input sequence length is smaller than the max
  1073. input sequence length in the current batch. It's the mask that we typically use for attention when
  1074. a batch has varying length sentences.
  1075. `next_sentence_label`: next sentence classification loss: torch.LongTensor of shape [batch_size]
  1076. with indices selected in [0, 1].
  1077. 0 => next sentence is the continuation, 1 => next sentence is a random sentence.
  1078. Outputs:
  1079. if `next_sentence_label` is not `None`:
  1080. Outputs the total_loss which is the sum of the masked language modeling loss and the next
  1081. sentence classification loss.
  1082. if `next_sentence_label` is `None`:
  1083. Outputs the next sentence classification logits of shape [batch_size, 2].
  1084. Example usage:
  1085. ```python
  1086. # Already been converted into WordPiece token ids
  1087. input_ids = torch.LongTensor([[31, 51, 99], [15, 5, 0]])
  1088. input_mask = torch.LongTensor([[1, 1, 1], [1, 1, 0]])
  1089. token_type_ids = torch.LongTensor([[0, 0, 1], [0, 1, 0]])
  1090. config = BertConfig(vocab_size_or_config_json_file=32000, hidden_size=768,
  1091. num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072)
  1092. model = BertForNextSentencePrediction(config)
  1093. seq_relationship_logits = model(input_ids, token_type_ids, input_mask)
  1094. ```
  1095. """
  1096. def __init__(self, config):
  1097. super(BertForNextSentencePrediction, self).__init__(config)
  1098. self.bert = BertModel(config)
  1099. self.cls = BertOnlyNSPHead(config)
  1100. self.apply(self.init_bert_weights)
  1101. def forward(self,
  1102. input_ids,
  1103. token_type_ids=None,
  1104. attention_mask=None,
  1105. next_sentence_label=None,
  1106. checkpoint_activations=False):
  1107. _, pooled_output = self.bert(input_ids, token_type_ids, attention_mask, output_all_encoded_layers=False)
  1108. seq_relationship_score = self.cls(pooled_output)
  1109. if next_sentence_label is not None:
  1110. loss_fct = CrossEntropyLoss(ignore_index=-1)
  1111. next_sentence_loss = loss_fct(seq_relationship_score.view(-1, 2), next_sentence_label.view(-1))
  1112. return next_sentence_loss
  1113. else:
  1114. return seq_relationship_score
  1115. class BertForSequenceClassification(BertPreTrainedModel):
  1116. """BERT model for classification.
  1117. This module is composed of the BERT model with a linear layer on top of
  1118. the pooled output.
  1119. Params:
  1120. `config`: a BertConfig class instance with the configuration to build a new model.
  1121. `num_labels`: the number of classes for the classifier. Default = 2.
  1122. Inputs:
  1123. `input_ids`: a torch.LongTensor of shape [batch_size, sequence_length]
  1124. with the word token indices in the vocabulary(see the tokens preprocessing logic in the scripts
  1125. `extract_features.py`, `run_classifier.py` and `run_squad.py`)
  1126. `token_type_ids`: an optional torch.LongTensor of shape [batch_size, sequence_length] with the token
  1127. types indices selected in [0, 1]. Type 0 corresponds to a `sentence A` and type 1 corresponds to
  1128. a `sentence B` token (see BERT paper for more details).
  1129. `attention_mask`: an optional torch.LongTensor of shape [batch_size, sequence_length] with indices
  1130. selected in [0, 1]. It's a mask to be used if the input sequence length is smaller than the max
  1131. input sequence length in the current batch. It's the mask that we typically use for attention when
  1132. a batch has varying length sentences.
  1133. `labels`: labels for the classification output: torch.LongTensor of shape [batch_size]
  1134. with indices selected in [0, ..., num_labels].
  1135. Outputs:
  1136. if `labels` is not `None`:
  1137. Outputs the CrossEntropy classification loss of the output with the labels.
  1138. if `labels` is `None`:
  1139. Outputs the classification logits of shape [batch_size, num_labels].
  1140. Example usage:
  1141. ```python
  1142. # Already been converted into WordPiece token ids
  1143. input_ids = torch.LongTensor([[31, 51, 99], [15, 5, 0]])
  1144. input_mask = torch.LongTensor([[1, 1, 1], [1, 1, 0]])
  1145. token_type_ids = torch.LongTensor([[0, 0, 1], [0, 1, 0]])
  1146. config = BertConfig(vocab_size_or_config_json_file=32000, hidden_size=768,
  1147. num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072)
  1148. num_labels = 2
  1149. model = BertForSequenceClassification(config, num_labels)
  1150. logits = model(input_ids, token_type_ids, input_mask)
  1151. ```
  1152. """
  1153. def __init__(self, config, num_labels):
  1154. super(BertForSequenceClassification, self).__init__(config)
  1155. self.num_labels = num_labels
  1156. self.bert = BertModel(config)
  1157. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  1158. self.classifier = nn.Linear(config.hidden_size, num_labels)
  1159. self.apply(self.init_bert_weights)
  1160. def forward(self, input_ids, token_type_ids=None, attention_mask=None, labels=None, checkpoint_activations=False):
  1161. _, pooled_output = self.bert(input_ids, token_type_ids, attention_mask, output_all_encoded_layers=False)
  1162. pooled_output = self.dropout(pooled_output)
  1163. logits = self.classifier(pooled_output)
  1164. if labels is not None:
  1165. loss_fct = CrossEntropyLoss()
  1166. loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
  1167. return loss
  1168. else:
  1169. return logits
  1170. class BertForMultipleChoice(BertPreTrainedModel):
  1171. """BERT model for multiple choice tasks.
  1172. This module is composed of the BERT model with a linear layer on top of
  1173. the pooled output.
  1174. Params:
  1175. `config`: a BertConfig class instance with the configuration to build a new model.
  1176. `num_choices`: the number of classes for the classifier. Default = 2.
  1177. Inputs:
  1178. `input_ids`: a torch.LongTensor of shape [batch_size, num_choices, sequence_length]
  1179. with the word token indices in the vocabulary(see the tokens preprocessing logic in the scripts
  1180. `extract_features.py`, `run_classifier.py` and `run_squad.py`)
  1181. `token_type_ids`: an optional torch.LongTensor of shape [batch_size, num_choices, sequence_length]
  1182. with the token types indices selected in [0, 1]. Type 0 corresponds to a `sentence A`
  1183. and type 1 corresponds to a `sentence B` token (see BERT paper for more details).
  1184. `attention_mask`: an optional torch.LongTensor of shape [batch_size, num_choices, sequence_length] with indices
  1185. selected in [0, 1]. It's a mask to be used if the input sequence length is smaller than the max
  1186. input sequence length in the current batch. It's the mask that we typically use for attention when
  1187. a batch has varying length sentences.
  1188. `labels`: labels for the classification output: torch.LongTensor of shape [batch_size]
  1189. with indices selected in [0, ..., num_choices].
  1190. Outputs:
  1191. if `labels` is not `None`:
  1192. Outputs the CrossEntropy classification loss of the output with the labels.
  1193. if `labels` is `None`:
  1194. Outputs the classification logits of shape [batch_size, num_labels].
  1195. Example usage:
  1196. ```python
  1197. # Already been converted into WordPiece token ids
  1198. input_ids = torch.LongTensor([[[31, 51, 99], [15, 5, 0]], [[12, 16, 42], [14, 28, 57]]])
  1199. input_mask = torch.LongTensor([[[1, 1, 1], [1, 1, 0]],[[1,1,0], [1, 0, 0]]])
  1200. token_type_ids = torch.LongTensor([[[0, 0, 1], [0, 1, 0]],[[0, 1, 1], [0, 0, 1]]])
  1201. config = BertConfig(vocab_size_or_config_json_file=32000, hidden_size=768,
  1202. num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072)
  1203. num_choices = 2
  1204. model = BertForMultipleChoice(config, num_choices)
  1205. logits = model(input_ids, token_type_ids, input_mask)
  1206. ```
  1207. """
  1208. def __init__(self, config, num_choices):
  1209. super(BertForMultipleChoice, self).__init__(config)
  1210. self.num_choices = num_choices
  1211. self.bert = BertModel(config)
  1212. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  1213. self.classifier = nn.Linear(config.hidden_size, 1)
  1214. self.apply(self.init_bert_weights)
  1215. def forward(self, input_ids, token_type_ids=None, attention_mask=None, labels=None, checkpoint_activations=False):
  1216. flat_input_ids = input_ids.view(-1, input_ids.size(-1))
  1217. flat_token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1))
  1218. flat_attention_mask = attention_mask.view(-1, attention_mask.size(-1))
  1219. _, pooled_output = self.bert(flat_input_ids,
  1220. flat_token_type_ids,
  1221. flat_attention_mask,
  1222. output_all_encoded_layers=False)
  1223. pooled_output = self.dropout(pooled_output)
  1224. logits = self.classifier(pooled_output)
  1225. reshaped_logits = logits.view(-1, self.num_choices)
  1226. if labels is not None:
  1227. loss_fct = CrossEntropyLoss()
  1228. loss = loss_fct(reshaped_logits, labels)
  1229. return loss
  1230. else:
  1231. return reshaped_logits
  1232. class BertForTokenClassification(BertPreTrainedModel):
  1233. """BERT model for token-level classification.
  1234. This module is composed of the BERT model with a linear layer on top of
  1235. the full hidden state of the last layer.
  1236. Params:
  1237. `config`: a BertConfig class instance with the configuration to build a new model.
  1238. `num_labels`: the number of classes for the classifier. Default = 2.
  1239. Inputs:
  1240. `input_ids`: a torch.LongTensor of shape [batch_size, sequence_length]
  1241. with the word token indices in the vocabulary(see the tokens preprocessing logic in the scripts
  1242. `extract_features.py`, `run_classifier.py` and `run_squad.py`)
  1243. `token_type_ids`: an optional torch.LongTensor of shape [batch_size, sequence_length] with the token
  1244. types indices selected in [0, 1]. Type 0 corresponds to a `sentence A` and type 1 corresponds to
  1245. a `sentence B` token (see BERT paper for more details).
  1246. `attention_mask`: an optional torch.LongTensor of shape [batch_size, sequence_length] with indices
  1247. selected in [0, 1]. It's a mask to be used if the input sequence length is smaller than the max
  1248. input sequence length in the current batch. It's the mask that we typically use for attention when
  1249. a batch has varying length sentences.
  1250. `labels`: labels for the classification output: torch.LongTensor of shape [batch_size, sequence_length]
  1251. with indices selected in [0, ..., num_labels].
  1252. Outputs:
  1253. if `labels` is not `None`:
  1254. Outputs the CrossEntropy classification loss of the output with the labels.
  1255. if `labels` is `None`:
  1256. Outputs the classification logits of shape [batch_size, sequence_length, num_labels].
  1257. Example usage:
  1258. ```python
  1259. # Already been converted into WordPiece token ids
  1260. input_ids = torch.LongTensor([[31, 51, 99], [15, 5, 0]])
  1261. input_mask = torch.LongTensor([[1, 1, 1], [1, 1, 0]])
  1262. token_type_ids = torch.LongTensor([[0, 0, 1], [0, 1, 0]])
  1263. config = BertConfig(vocab_size_or_config_json_file=32000, hidden_size=768,
  1264. num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072)
  1265. num_labels = 2
  1266. model = BertForTokenClassification(config, num_labels)
  1267. logits = model(input_ids, token_type_ids, input_mask)
  1268. ```
  1269. """
  1270. def __init__(self, config, num_labels):
  1271. super(BertForTokenClassification, self).__init__(config)
  1272. self.num_labels = num_labels
  1273. self.bert = BertModel(config)
  1274. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  1275. self.classifier = nn.Linear(config.hidden_size, num_labels)
  1276. self.apply(self.init_bert_weights)
  1277. def forward(self, input_ids, token_type_ids=None, attention_mask=None, labels=None, checkpoint_activations=False):
  1278. sequence_output, _ = self.bert(input_ids, token_type_ids, attention_mask, output_all_encoded_layers=False)
  1279. sequence_output = self.dropout(sequence_output)
  1280. logits = self.classifier(sequence_output)
  1281. if labels is not None:
  1282. loss_fct = CrossEntropyLoss()
  1283. # Only keep active parts of the loss
  1284. if attention_mask is not None:
  1285. active_loss = attention_mask.view(-1) == 1
  1286. active_logits = logits.view(-1, self.num_labels)[active_loss]
  1287. active_labels = labels.view(-1)[active_loss]
  1288. loss = loss_fct(active_logits, active_labels)
  1289. else:
  1290. loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
  1291. return loss
  1292. else:
  1293. return logits
  1294. class BertForQuestionAnswering(BertPreTrainedModel):
  1295. """BERT model for Question Answering (span extraction).
  1296. This module is composed of the BERT model with a linear layer on top of
  1297. the sequence output that computes start_logits and end_logits
  1298. Params:
  1299. `config`: a BertConfig class instance with the configuration to build a new model.
  1300. Inputs:
  1301. `input_ids`: a torch.LongTensor of shape [batch_size, sequence_length]
  1302. with the word token indices in the vocabulary(see the tokens preprocessing logic in the scripts
  1303. `extract_features.py`, `run_classifier.py` and `run_squad.py`)
  1304. `token_type_ids`: an optional torch.LongTensor of shape [batch_size, sequence_length] with the token
  1305. types indices selected in [0, 1]. Type 0 corresponds to a `sentence A` and type 1 corresponds to
  1306. a `sentence B` token (see BERT paper for more details).
  1307. `attention_mask`: an optional torch.LongTensor of shape [batch_size, sequence_length] with indices
  1308. selected in [0, 1]. It's a mask to be used if the input sequence length is smaller than the max
  1309. input sequence length in the current batch. It's the mask that we typically use for attention when
  1310. a batch has varying length sentences.
  1311. `start_positions`: position of the first token for the labeled span: torch.LongTensor of shape [batch_size].
  1312. Positions are clamped to the length of the sequence and position outside of the sequence are not taken
  1313. into account for computing the loss.
  1314. `end_positions`: position of the last token for the labeled span: torch.LongTensor of shape [batch_size].
  1315. Positions are clamped to the length of the sequence and position outside of the sequence are not taken
  1316. into account for computing the loss.
  1317. Outputs:
  1318. if `start_positions` and `end_positions` are not `None`:
  1319. Outputs the total_loss which is the sum of the CrossEntropy loss for the start and end token positions.
  1320. if `start_positions` or `end_positions` is `None`:
  1321. Outputs a tuple of start_logits, end_logits which are the logits respectively for the start and end
  1322. position tokens of shape [batch_size, sequence_length].
  1323. Example usage:
  1324. ```python
  1325. # Already been converted into WordPiece token ids
  1326. input_ids = torch.LongTensor([[31, 51, 99], [15, 5, 0]])
  1327. input_mask = torch.LongTensor([[1, 1, 1], [1, 1, 0]])
  1328. token_type_ids = torch.LongTensor([[0, 0, 1], [0, 1, 0]])
  1329. config = BertConfig(vocab_size_or_config_json_file=32000, hidden_size=768,
  1330. num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072)
  1331. model = BertForQuestionAnswering(config)
  1332. start_logits, end_logits = model(input_ids, token_type_ids, input_mask)
  1333. ```
  1334. """
  1335. def __init__(self, config):
  1336. super(BertForQuestionAnswering, self).__init__(config)
  1337. self.bert = BertModel(config)
  1338. # TODO check with Google if it's normal there is no dropout on the token classifier of SQuAD in the TF version
  1339. # self.dropout = nn.Dropout(config.hidden_dropout_prob)
  1340. self.qa_outputs = nn.Linear(config.hidden_size, 2)
  1341. self.apply(self.init_bert_weights)
  1342. def forward(self,
  1343. input_ids,
  1344. token_type_ids=None,
  1345. attention_mask=None,
  1346. start_positions=None,
  1347. end_positions=None,
  1348. checkpoint_activations=False):
  1349. sequence_output, _ = self.bert(input_ids, token_type_ids, attention_mask, output_all_encoded_layers=False)
  1350. logits = self.qa_outputs(sequence_output)
  1351. start_logits, end_logits = logits.split(1, dim=-1)
  1352. start_logits = start_logits.squeeze(-1)
  1353. end_logits = end_logits.squeeze(-1)
  1354. if start_positions is not None and end_positions is not None:
  1355. # If we are on multi-GPU, split add a dimension
  1356. if len(start_positions.size()) > 1:
  1357. start_positions = start_positions.squeeze(-1)
  1358. if len(end_positions.size()) > 1:
  1359. end_positions = end_positions.squeeze(-1)
  1360. # sometimes the start/end positions are outside our model inputs, we ignore these terms
  1361. ignored_index = start_logits.size(1)
  1362. start_positions.clamp_(0, ignored_index)
  1363. end_positions.clamp_(0, ignored_index)
  1364. loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
  1365. start_loss = loss_fct(start_logits, start_positions)
  1366. end_loss = loss_fct(end_logits, end_positions)
  1367. total_loss = (start_loss + end_loss) / 2
  1368. return total_loss
  1369. else:
  1370. return start_logits, end_logits