modeling.py 70 KB

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