modeling.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  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. from io import open
  29. import torch
  30. from torch import nn
  31. from torch.utils import checkpoint
  32. from torch.nn import Module
  33. import torch.nn.functional as F
  34. import torch.nn.init as init
  35. #from numba import cuda
  36. #from deepspeed_cuda import DeepSpeedSoftmaxConfig, DeepSpeedSoftmax
  37. from deepspeed.accelerator import get_accelerator
  38. logger = logging.getLogger(__name__)
  39. """
  40. @torch.jit.script
  41. def f_gelu(x):
  42. return x * 0.5 * (1.0 + torch.erf(x / 1.41421))
  43. @torch.jit.script
  44. def bias_gelu(bias, y):
  45. x = bias + y
  46. return x * 0.5 * (1.0 + torch.erf(x / 1.41421))
  47. @torch.jit.script
  48. def bias_tanh(bias, y):
  49. x = bias + y
  50. return torch.tanh(x)
  51. """
  52. def f_gelu(x):
  53. x_type = x.dtype
  54. x = x.float()
  55. x = x * 0.5 * (1.0 + torch.erf(x / 1.41421))
  56. return x.to(x_type)
  57. def bias_gelu(bias, y):
  58. y_type = y.dtype
  59. x = bias.float() + y.float()
  60. x = x * 0.5 * (1.0 + torch.erf(x / 1.41421))
  61. return x.to(y_type)
  62. def bias_tanh(bias, y):
  63. y_type = y.dtype
  64. x = bias.float() + y.float()
  65. x = torch.tanh(x)
  66. return x.to(y_type)
  67. def gelu(x):
  68. """Implementation of the gelu activation function.
  69. For information: OpenAI GPT's gelu is slightly different (and gives slightly different results):
  70. 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3))))
  71. Also see https://arxiv.org/abs/1606.08415
  72. """
  73. return f_gelu(x)
  74. def swish(x):
  75. return x * torch.sigmoid(x)
  76. ACT2FN = {"gelu": gelu, "relu": torch.nn.functional.relu, "swish": swish}
  77. class GPUTimer:
  78. def __init__(self):
  79. super().__init__()
  80. self.start = get_accelerator().Event() # noqa: F821
  81. self.stop = get_accelerator().Event() # noqa: F821
  82. def record(self):
  83. self.start.record()
  84. def elapsed(self):
  85. self.stop.record()
  86. self.stop.synchronize()
  87. return self.start.elapsed_time(self.stop) / 1000.0
  88. class LinearActivation(Module):
  89. r"""Fused Linear and activation Module.
  90. """
  91. __constants__ = ['bias']
  92. def __init__(self, in_features, out_features, weights, biases, act='gelu', bias=True):
  93. super(LinearActivation, self).__init__()
  94. self.in_features = in_features
  95. self.out_features = out_features
  96. self.fused_gelu = False
  97. self.fused_tanh = False
  98. if isinstance(act, str):
  99. if bias and act == 'gelu':
  100. self.fused_gelu = True
  101. elif bias and act == 'tanh':
  102. self.fused_tanh = True
  103. else:
  104. self.act_fn = ACT2FN[act]
  105. else:
  106. self.act_fn = act
  107. #self.weight = Parameter(torch.Tensor(out_features, in_features))
  108. self.weight = weights[5]
  109. self.bias = biases[5]
  110. #if bias:
  111. # self.bias = Parameter(torch.Tensor(out_features))
  112. #else:
  113. # self.register_parameter('bias', None)
  114. #self.reset_parameters()
  115. def reset_parameters(self):
  116. init.kaiming_uniform_(self.weight, a=math.sqrt(5))
  117. if self.bias is not None:
  118. fan_in, _ = init._calculate_fan_in_and_fan_out(self.weight)
  119. bound = 1 / math.sqrt(fan_in)
  120. init.uniform_(self.bias, -bound, bound)
  121. def forward(self, input):
  122. if self.fused_gelu:
  123. #timing = []
  124. #t1 = GPUTimer()
  125. #t1.record()
  126. y = F.linear(input, self.weight, None)
  127. #timing.append(t1.elapsed())
  128. #t1.record()
  129. bg = bias_gelu(self.bias, y)
  130. #timing.append(t1.elapsed())
  131. return bg
  132. elif self.fused_tanh:
  133. return bias_tanh(self.bias, F.linear(input, self.weight, None))
  134. else:
  135. return self.act_fn(F.linear(input, self.weight, self.bias))
  136. def extra_repr(self):
  137. return 'in_features={}, out_features={}, bias={}'.format(self.in_features, self.out_features, self.bias
  138. is not None)
  139. class BertConfig(object):
  140. """Configuration class to store the configuration of a `BertModel`.
  141. """
  142. def __init__(self,
  143. vocab_size_or_config_json_file,
  144. hidden_size=768,
  145. num_hidden_layers=12,
  146. num_attention_heads=12,
  147. intermediate_size=3072,
  148. batch_size=8,
  149. hidden_act="gelu",
  150. hidden_dropout_prob=0.1,
  151. attention_probs_dropout_prob=0.1,
  152. max_position_embeddings=512,
  153. type_vocab_size=2,
  154. initializer_range=0.02,
  155. fp16=False):
  156. """Constructs BertConfig.
  157. Args:
  158. vocab_size_or_config_json_file: Vocabulary size of `inputs_ids` in `BertModel`.
  159. hidden_size: Size of the encoder layers and the pooler layer.
  160. num_hidden_layers: Number of hidden layers in the Transformer encoder.
  161. num_attention_heads: Number of attention heads for each attention layer in
  162. the Transformer encoder.
  163. intermediate_size: The size of the "intermediate" (i.e., feed-forward)
  164. layer in the Transformer encoder.
  165. hidden_act: The non-linear activation function (function or string) in the
  166. encoder and pooler. If string, "gelu", "relu" and "swish" are supported.
  167. hidden_dropout_prob: The dropout probability for all fully connected
  168. layers in the embeddings, encoder, and pooler.
  169. attention_probs_dropout_prob: The dropout ratio for the attention
  170. probabilities.
  171. max_position_embeddings: The maximum sequence length that this model might
  172. ever be used with. Typically set this to something large just in case
  173. (e.g., 512 or 1024 or 2048).
  174. type_vocab_size: The vocabulary size of the `token_type_ids` passed into
  175. `BertModel`.
  176. initializer_range: The sttdev of the truncated_normal_initializer for
  177. initializing all weight matrices.
  178. """
  179. if isinstance(vocab_size_or_config_json_file, str):
  180. with open(vocab_size_or_config_json_file, "r", encoding='utf-8') as reader:
  181. json_config = json.loads(reader.read())
  182. self.__dict__.update(json_config)
  183. elif isinstance(vocab_size_or_config_json_file, int):
  184. self.vocab_size = vocab_size_or_config_json_file
  185. self.hidden_size = hidden_size
  186. self.num_hidden_layers = num_hidden_layers
  187. self.num_attention_heads = num_attention_heads
  188. self.batch_size = batch_size
  189. self.hidden_act = hidden_act
  190. self.intermediate_size = intermediate_size
  191. self.hidden_dropout_prob = hidden_dropout_prob
  192. self.attention_probs_dropout_prob = attention_probs_dropout_prob
  193. self.max_position_embeddings = max_position_embeddings
  194. self.type_vocab_size = type_vocab_size
  195. self.initializer_range = initializer_range
  196. self.fp16 = fp16
  197. else:
  198. raise ValueError("First argument must be either a vocabulary size (int)"
  199. "or the path to a pretrained model config file (str)")
  200. @classmethod
  201. def from_dict(cls, json_object):
  202. """Constructs a `BertConfig` from a Python dictionary of parameters."""
  203. config = BertConfig(vocab_size_or_config_json_file=-1)
  204. config.__dict__.update(json_object)
  205. return config
  206. @classmethod
  207. def from_json_file(cls, json_file):
  208. """Constructs a `BertConfig` from a json file of parameters."""
  209. with open(json_file, "r", encoding='utf-8') as reader:
  210. text = reader.read()
  211. return cls.from_dict(json.loads(text))
  212. def __repr__(self):
  213. return str(self.to_json_string())
  214. def to_dict(self):
  215. """Serializes this instance to a Python dictionary."""
  216. output = copy.deepcopy(self.__dict__)
  217. return output
  218. def to_json_string(self):
  219. """Serializes this instance to a JSON string."""
  220. return json.dumps(self.to_dict(), indent=2, sort_keys=True) + "\n"
  221. try:
  222. import apex
  223. #apex.amp.register_half_function(apex.normalization.fused_layer_norm, 'FusedLayerNorm')
  224. import apex.normalization
  225. #apex.amp.register_float_function(apex.normalization.FusedLayerNorm, 'forward')
  226. BertLayerNorm = apex.normalization.FusedLayerNorm
  227. except ImportError:
  228. print("Better speed can be achieved with apex installed from https://www.github.com/nvidia/apex.")
  229. class BertLayerNorm(nn.Module):
  230. def __init__(self, hidden_size, eps=1e-12):
  231. """Construct a layernorm module in the TF style (epsilon inside the square root).
  232. """
  233. super(BertLayerNorm, self).__init__()
  234. self.weight = nn.Parameter(torch.ones(hidden_size))
  235. self.bias = nn.Parameter(torch.zeros(hidden_size))
  236. self.variance_epsilon = eps
  237. def forward(self, x):
  238. u = x.mean(-1, keepdim=True)
  239. s = (x - u).pow(2).mean(-1, keepdim=True)
  240. x = (x - u) / torch.sqrt(s + self.variance_epsilon)
  241. return self.weight * x + self.bias
  242. class BertSelfAttention(nn.Module):
  243. def __init__(self, i, config, weights, biases):
  244. super(BertSelfAttention, self).__init__()
  245. if config.hidden_size % config.num_attention_heads != 0:
  246. raise ValueError("The hidden size (%d) is not a multiple of the number of attention "
  247. "heads (%d)" % (config.hidden_size, config.num_attention_heads))
  248. self.num_attention_heads = config.num_attention_heads
  249. self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
  250. self.all_head_size = self.num_attention_heads * self.attention_head_size
  251. self.query = nn.Linear(config.hidden_size, self.all_head_size)
  252. self.query.weight = weights[0]
  253. self.query.bias = biases[0]
  254. self.key = nn.Linear(config.hidden_size, self.all_head_size)
  255. self.key.weight = weights[1]
  256. self.key.bias = biases[1]
  257. self.value = nn.Linear(config.hidden_size, self.all_head_size)
  258. self.value.weight = weights[2]
  259. self.value.bias = biases[2]
  260. self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
  261. self.softmax = nn.Softmax(dim=-1)
  262. #self.softmax_config = DeepSpeedSoftmaxConfig()
  263. #self.softmax_config.batch_size = config.batch_size
  264. #self.softmax_config.max_seq_length = config.max_position_embeddings
  265. #self.softmax_config.hidden_size = config.hidden_size
  266. #self.softmax_config.heads = config.num_attention_heads
  267. #self.softmax_config.softmax_id = i
  268. #self.softmax_config.fp16 = config.fp16
  269. #self.softmax_config.prob_drop_out = 0.0
  270. #self.softmax = DeepSpeedSoftmax(i, self.softmax_config)
  271. def transpose_for_scores(self, x):
  272. new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
  273. x = x.view(*new_x_shape)
  274. return x.permute(0, 2, 1, 3)
  275. def transpose_key_for_scores(self, x):
  276. new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
  277. x = x.view(*new_x_shape)
  278. return x.permute(0, 2, 3, 1)
  279. def forward(self, hidden_states, attention_mask, grads=None):
  280. mixed_query_layer = self.query(hidden_states)
  281. mixed_key_layer = self.key(hidden_states)
  282. mixed_value_layer = self.value(hidden_states)
  283. query_layer = self.transpose_for_scores(mixed_query_layer)
  284. key_layer = self.transpose_key_for_scores(mixed_key_layer)
  285. value_layer = self.transpose_for_scores(mixed_value_layer)
  286. attention_scores = torch.matmul(query_layer, key_layer)
  287. attention_scores = attention_scores / math.sqrt(self.attention_head_size)
  288. attention_scores = attention_scores + attention_mask
  289. attention_probs = self.softmax(attention_scores)
  290. # This is actually dropping out entire tokens to attend to, which might
  291. # seem a bit unusual, but is taken from the original Transformer paper.
  292. attention_probs = self.dropout(attention_probs)
  293. context_layer = torch.matmul(attention_probs, value_layer)
  294. context_layer1 = context_layer.permute(0, 2, 1, 3).contiguous()
  295. new_context_layer_shape = context_layer1.size()[:-2] + (self.all_head_size, )
  296. context_layer1 = context_layer1.view(*new_context_layer_shape)
  297. return context_layer1
  298. class BertSelfOutput(nn.Module):
  299. def __init__(self, config, weights, biases):
  300. super(BertSelfOutput, self).__init__()
  301. self.dense = nn.Linear(config.hidden_size, config.hidden_size)
  302. self.dense.weight = weights[3]
  303. self.dense.bias = biases[3]
  304. self.LayerNorm = BertLayerNorm(config.hidden_size, eps=1e-12)
  305. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  306. def forward(self, hidden_states, input_tensor):
  307. hidden_states = self.dense(hidden_states)
  308. hidden_states = self.dropout(hidden_states)
  309. hidden_states = self.LayerNorm(hidden_states + input_tensor)
  310. return hidden_states
  311. def get_w(self):
  312. return self.dense.weight
  313. class BertAttention(nn.Module):
  314. def __init__(self, i, config, weights, biases):
  315. super(BertAttention, self).__init__()
  316. self.self = BertSelfAttention(i, config, weights, biases)
  317. self.output = BertSelfOutput(config, weights, biases)
  318. def forward(self, input_tensor, attention_mask):
  319. self_output = self.self(input_tensor, attention_mask)
  320. attention_output = self.output(self_output, input_tensor)
  321. return attention_output
  322. def get_w(self):
  323. return self.output.get_w()
  324. class BertIntermediate(nn.Module):
  325. def __init__(self, config, weights, biases):
  326. super(BertIntermediate, self).__init__()
  327. self.dense_act = LinearActivation(config.hidden_size,
  328. config.intermediate_size,
  329. weights,
  330. biases,
  331. act=config.hidden_act)
  332. def forward(self, hidden_states):
  333. hidden_states = self.dense_act(hidden_states)
  334. return hidden_states
  335. class BertOutput(nn.Module):
  336. def __init__(self, config, weights, biases):
  337. super(BertOutput, self).__init__()
  338. self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
  339. self.dense.weight = weights[6]
  340. self.dense.bias = biases[6]
  341. self.LayerNorm = BertLayerNorm(config.hidden_size, eps=1e-12)
  342. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  343. def forward(self, hidden_states, input_tensor):
  344. hidden_states = self.dense(hidden_states)
  345. hidden_states = self.dropout(hidden_states)
  346. hidden_states = self.LayerNorm(hidden_states + input_tensor)
  347. return hidden_states
  348. class BertLayer(nn.Module):
  349. def __init__(self, i, config, weights, biases):
  350. super(BertLayer, self).__init__()
  351. self.attention = BertAttention(i, config, weights, biases)
  352. self.intermediate = BertIntermediate(config, weights, biases)
  353. self.output = BertOutput(config, weights, biases)
  354. self.weight = weights
  355. self.biases = biases
  356. def forward(self, hidden_states, attention_mask, grads, collect_all_grads=False):
  357. attention_output = self.attention(hidden_states, attention_mask)
  358. intermediate_output = self.intermediate(attention_output)
  359. layer_output = self.output(intermediate_output, attention_output)
  360. if collect_all_grads:
  361. # self.weight[0].register_hook(lambda x, self=self: grads.append([x,"Q_W"]))
  362. # self.biases[0].register_hook(lambda x, self=self: grads.append([x,"Q_B"]))
  363. # self.weight[1].register_hook(lambda x, self=self: grads.append([x,"K_W"]))
  364. # self.biases[1].register_hook(lambda x, self=self: grads.append([x,"K_B"]))
  365. self.weight[2].register_hook(lambda x, self=self: grads.append([x, "V_W"]))
  366. self.biases[2].register_hook(lambda x, self=self: grads.append([x, "V_B"]))
  367. self.weight[3].register_hook(lambda x, self=self: grads.append([x, "O_W"]))
  368. self.biases[3].register_hook(lambda x, self=self: grads.append([x, "O_B"]))
  369. self.attention.output.LayerNorm.weight.register_hook(lambda x, self=self: grads.append([x, "N2_W"]))
  370. self.attention.output.LayerNorm.bias.register_hook(lambda x, self=self: grads.append([x, "N2_B"]))
  371. self.weight[5].register_hook(lambda x, self=self: grads.append([x, "int_W"]))
  372. self.biases[5].register_hook(lambda x, self=self: grads.append([x, "int_B"]))
  373. self.weight[6].register_hook(lambda x, self=self: grads.append([x, "out_W"]))
  374. self.biases[6].register_hook(lambda x, self=self: grads.append([x, "out_B"]))
  375. self.output.LayerNorm.weight.register_hook(lambda x, self=self: grads.append([x, "norm_W"]))
  376. self.output.LayerNorm.bias.register_hook(lambda x, self=self: grads.append([x, "norm_B"]))
  377. return layer_output
  378. def get_w(self):
  379. return self.attention.get_w()
  380. class BertEncoder(nn.Module):
  381. def __init__(self, config, weights, biases):
  382. super(BertEncoder, self).__init__()
  383. #layer = BertLayer(config, weights, biases)
  384. self.FinalLayerNorm = BertLayerNorm(config.hidden_size, eps=1e-12)
  385. self.layer = nn.ModuleList(
  386. [copy.deepcopy(BertLayer(i, config, weights, biases)) for i in range(config.num_hidden_layers)])
  387. self.grads = []
  388. self.graph = []
  389. def get_grads(self):
  390. return self.grads
  391. def get_modules(self, big_node, input):
  392. for mdl in big_node.named_children():
  393. self.graph.append(mdl)
  394. self.get_modules(self, mdl, input)
  395. def forward(self, hidden_states, attention_mask, output_all_encoded_layers=True, checkpoint_activations=False):
  396. all_encoder_layers = []
  397. def custom(start, end):
  398. def custom_forward(*inputs):
  399. layers = self.layer[start:end]
  400. x_ = inputs[0]
  401. for layer in layers:
  402. x_ = layer(x_, inputs[1])
  403. return x_
  404. return custom_forward
  405. if checkpoint_activations:
  406. l = 0
  407. num_layers = len(self.layer)
  408. chunk_length = math.ceil(math.sqrt(num_layers))
  409. while l < num_layers:
  410. hidden_states = checkpoint.checkpoint(custom(l, l + chunk_length), hidden_states, attention_mask * 1)
  411. l += chunk_length
  412. # decoder layers
  413. else:
  414. for i, layer_module in enumerate(self.layer):
  415. hidden_states = layer_module(hidden_states, attention_mask, self.grads, collect_all_grads=True)
  416. hidden_states.register_hook(lambda x, i=i, self=self: self.grads.append([x, "hidden_state"]))
  417. #print("pytorch weight is: ", layer_module.get_w())
  418. if output_all_encoded_layers:
  419. all_encoder_layers.append((hidden_states))
  420. if not output_all_encoded_layers or checkpoint_activations:
  421. all_encoder_layers.append((hidden_states))
  422. return all_encoder_layers