modelingpreln.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649
  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 deepspeed.accelerator import get_accelerator
  36. logger = logging.getLogger(__name__)
  37. """
  38. @torch.jit.script
  39. def f_gelu(x):
  40. return x * 0.5 * (1.0 + torch.erf(x / 1.41421))
  41. @torch.jit.script
  42. def bias_gelu(bias, y):
  43. x = bias + y
  44. return x * 0.5 * (1.0 + torch.erf(x / 1.41421))
  45. @torch.jit.script
  46. def bias_tanh(bias, y):
  47. x = bias + y
  48. return torch.tanh(x)
  49. """
  50. def f_gelu(x):
  51. x_type = x.dtype
  52. x = x.float()
  53. x = x * 0.5 * (1.0 + torch.erf(x / 1.41421))
  54. return x.to(x_type)
  55. def bias_gelu(bias, y):
  56. y_type = y.dtype
  57. x = bias.float() + y.float()
  58. x = x * 0.5 * (1.0 + torch.erf(x / 1.41421))
  59. return x.to(y_type)
  60. def bias_tanh(bias, y):
  61. y_type = y.dtype
  62. x = bias.float() + y.float()
  63. x = torch.tanh(x)
  64. return x.to(y_type)
  65. def gelu(x):
  66. """Implementation of the gelu activation function.
  67. For information: OpenAI GPT's gelu is slightly different (and gives slightly different results):
  68. 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3))))
  69. Also see https://arxiv.org/abs/1606.08415
  70. """
  71. return f_gelu(x)
  72. def swish(x):
  73. return x * torch.sigmoid(x)
  74. ACT2FN = {"gelu": gelu, "relu": torch.nn.functional.relu, "swish": swish}
  75. class GPUTimer:
  76. def __init__(self):
  77. super().__init__()
  78. self.start = get_accelerator().Event() # noqa: F821
  79. self.stop = get_accelerator().Event() # noqa: F821
  80. def record(self):
  81. self.start.record()
  82. def elapsed(self):
  83. self.stop.record()
  84. self.stop.synchronize()
  85. return self.start.elapsed_time(self.stop) / 1000.0
  86. class LinearActivation(Module):
  87. r"""Fused Linear and activation Module.
  88. """
  89. __constants__ = ['bias']
  90. def __init__(self, in_features, out_features, weights, biases, act='gelu', bias=True):
  91. super(LinearActivation, self).__init__()
  92. self.in_features = in_features
  93. self.out_features = out_features
  94. self.fused_gelu = False
  95. self.fused_tanh = False
  96. if isinstance(act, str):
  97. if bias and act == 'gelu':
  98. self.fused_gelu = True
  99. elif bias and act == 'tanh':
  100. self.fused_tanh = True
  101. else:
  102. self.act_fn = ACT2FN[act]
  103. else:
  104. self.act_fn = act
  105. #self.weight = Parameter(torch.Tensor(out_features, in_features))
  106. self.weight = weights[5]
  107. self.bias = biases[5]
  108. #if bias:
  109. # self.bias = Parameter(torch.Tensor(out_features))
  110. #else:
  111. # self.register_parameter('bias', None)
  112. #self.reset_parameters()
  113. def reset_parameters(self):
  114. init.kaiming_uniform_(self.weight, a=math.sqrt(5))
  115. if self.bias is not None:
  116. fan_in, _ = init._calculate_fan_in_and_fan_out(self.weight)
  117. bound = 1 / math.sqrt(fan_in)
  118. init.uniform_(self.bias, -bound, bound)
  119. def forward(self, input):
  120. if self.fused_gelu:
  121. #timing = []
  122. #t1 = GPUTimer()
  123. #t1.record()
  124. y = F.linear(input, self.weight, None)
  125. #timing.append(t1.elapsed())
  126. #t1.record()
  127. bg = bias_gelu(self.bias, y)
  128. #timing.append(t1.elapsed())
  129. return bg
  130. elif self.fused_tanh:
  131. return bias_tanh(self.bias, F.linear(input, self.weight, None))
  132. else:
  133. return self.act_fn(F.linear(input, self.weight, self.bias))
  134. def extra_repr(self):
  135. return 'in_features={}, out_features={}, bias={}'.format(self.in_features, self.out_features, self.bias
  136. is not None)
  137. class BertConfig(object):
  138. """Configuration class to store the configuration of a `BertModel`.
  139. """
  140. def __init__(self,
  141. vocab_size_or_config_json_file,
  142. hidden_size=768,
  143. num_hidden_layers=12,
  144. num_attention_heads=12,
  145. intermediate_size=3072,
  146. batch_size=8,
  147. hidden_act="gelu",
  148. hidden_dropout_prob=0.1,
  149. attention_probs_dropout_prob=0.1,
  150. max_position_embeddings=512,
  151. type_vocab_size=2,
  152. initializer_range=0.02,
  153. fp16=False):
  154. """Constructs BertConfig.
  155. Args:
  156. vocab_size_or_config_json_file: Vocabulary size of `inputs_ids` in `BertModel`.
  157. hidden_size: Size of the encoder layers and the pooler layer.
  158. num_hidden_layers: Number of hidden layers in the Transformer encoder.
  159. num_attention_heads: Number of attention heads for each attention layer in
  160. the Transformer encoder.
  161. intermediate_size: The size of the "intermediate" (i.e., feed-forward)
  162. layer in the Transformer encoder.
  163. hidden_act: The non-linear activation function (function or string) in the
  164. encoder and pooler. If string, "gelu", "relu" and "swish" are supported.
  165. hidden_dropout_prob: The dropout probability for all fully connected
  166. layers in the embeddings, encoder, and pooler.
  167. attention_probs_dropout_prob: The dropout ratio for the attention
  168. probabilities.
  169. max_position_embeddings: The maximum sequence length that this model might
  170. ever be used with. Typically set this to something large just in case
  171. (e.g., 512 or 1024 or 2048).
  172. type_vocab_size: The vocabulary size of the `token_type_ids` passed into
  173. `BertModel`.
  174. initializer_range: The sttdev of the truncated_normal_initializer for
  175. initializing all weight matrices.
  176. """
  177. if isinstance(vocab_size_or_config_json_file, str):
  178. with open(vocab_size_or_config_json_file, "r", encoding='utf-8') as reader:
  179. json_config = json.loads(reader.read())
  180. for key, value in json_config.items():
  181. self.__dict__[key] = value
  182. elif isinstance(vocab_size_or_config_json_file, int):
  183. self.vocab_size = vocab_size_or_config_json_file
  184. self.hidden_size = hidden_size
  185. self.num_hidden_layers = num_hidden_layers
  186. self.num_attention_heads = num_attention_heads
  187. self.batch_size = batch_size
  188. self.hidden_act = hidden_act
  189. self.intermediate_size = intermediate_size
  190. self.hidden_dropout_prob = hidden_dropout_prob
  191. self.attention_probs_dropout_prob = attention_probs_dropout_prob
  192. self.max_position_embeddings = max_position_embeddings
  193. self.type_vocab_size = type_vocab_size
  194. self.initializer_range = initializer_range
  195. self.fp16 = fp16
  196. else:
  197. raise ValueError("First argument must be either a vocabulary size (int)"
  198. "or the path to a pretrained model config file (str)")
  199. @classmethod
  200. def from_dict(cls, json_object):
  201. """Constructs a `BertConfig` from a Python dictionary of parameters."""
  202. config = BertConfig(vocab_size_or_config_json_file=-1)
  203. for key, value in json_object.items():
  204. config.__dict__[key] = value
  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. pdtype = x.dtype
  239. x = x.float()
  240. u = x.mean(-1, keepdim=True)
  241. s = (x - u).pow(2).mean(-1, keepdim=True)
  242. x = (x - u) / torch.sqrt(s + self.variance_epsilon)
  243. return self.weight * x.to(pdtype) + self.bias
  244. #def forward(self, x):
  245. # u = x.mean(-1, keepdim=True)
  246. # s = (x - u).pow(2).mean(-1, keepdim=True)
  247. # x = (x - u) / torch.sqrt(s + self.variance_epsilon)
  248. # return self.weight * x + self.bias
  249. class BertEmbeddings(nn.Module):
  250. """Construct the embeddings from word, position and token_type embeddings.
  251. """
  252. def __init__(self, config):
  253. super(BertEmbeddings, self).__init__()
  254. self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size)
  255. self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
  256. self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
  257. # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
  258. # any TensorFlow checkpoint file
  259. self.LayerNorm = BertLayerNorm(config.hidden_size, eps=1e-12)
  260. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  261. def forward(self, input_ids, token_type_ids=None):
  262. seq_length = input_ids.size(1)
  263. position_ids = torch.arange(seq_length, dtype=torch.long, device=input_ids.device)
  264. position_ids = position_ids.unsqueeze(0).expand_as(input_ids)
  265. if token_type_ids is None:
  266. token_type_ids = torch.zeros_like(input_ids)
  267. words_embeddings = self.word_embeddings(input_ids)
  268. position_embeddings = self.position_embeddings(position_ids)
  269. token_type_embeddings = self.token_type_embeddings(token_type_ids)
  270. embeddings = words_embeddings + position_embeddings + token_type_embeddings
  271. embeddings = self.LayerNorm(embeddings)
  272. embeddings = self.dropout(embeddings)
  273. return embeddings
  274. class BertSelfAttention(nn.Module):
  275. def __init__(self, i, config, weights, biases):
  276. super(BertSelfAttention, self).__init__()
  277. if config.hidden_size % config.num_attention_heads != 0:
  278. raise ValueError("The hidden size (%d) is not a multiple of the number of attention "
  279. "heads (%d)" % (config.hidden_size, config.num_attention_heads))
  280. self.num_attention_heads = config.num_attention_heads
  281. self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
  282. self.all_head_size = self.num_attention_heads * self.attention_head_size
  283. self.query = nn.Linear(config.hidden_size, self.all_head_size)
  284. self.query.weight = weights[0]
  285. self.query.bias = biases[0]
  286. self.key = nn.Linear(config.hidden_size, self.all_head_size)
  287. self.key.weight = weights[1]
  288. self.key.bias = biases[1]
  289. self.value = nn.Linear(config.hidden_size, self.all_head_size)
  290. self.value.weight = weights[2]
  291. self.value.bias = biases[2]
  292. self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
  293. self.softmax = nn.Softmax(dim=-1)
  294. #self.softmax_config = DeepSpeedSoftmaxConfig()
  295. #self.softmax_config.batch_size = config.batch_size
  296. #self.softmax_config.max_seq_length = config.max_position_embeddings
  297. #self.softmax_config.hidden_size = config.hidden_size
  298. #self.softmax_config.heads = config.num_attention_heads
  299. #self.softmax_config.softmax_id = i
  300. #self.softmax_config.fp16 = config.fp16
  301. #self.softmax_config.prob_drop_out = 0.0
  302. #self.softmax = DeepSpeedSoftmax(i, self.softmax_config)
  303. def transpose_for_scores(self, x):
  304. new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
  305. x = x.view(*new_x_shape)
  306. return x.permute(0, 2, 1, 3)
  307. def transpose_key_for_scores(self, x):
  308. new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
  309. x = x.view(*new_x_shape)
  310. return x.permute(0, 2, 3, 1)
  311. def forward(self, hidden_states, attention_mask, grads=None):
  312. #timing = []
  313. #t1 = GPUTimer()
  314. #t1.record()
  315. mixed_query_layer = self.query(hidden_states)
  316. #timing.append(t1.elapsed())
  317. #print("Query elapsed: %s" % (time.clock() - start))
  318. #t1.record()
  319. mixed_key_layer = self.key(hidden_states)
  320. #timing.append(t1.elapsed())
  321. #print("Key elapsed: %s" % (time.clock() - start))
  322. #t1.record()
  323. mixed_value_layer = self.value(hidden_states)
  324. #timing.append(t1.elapsed())
  325. #print("Value elapsed: %s" % (time.clock() - start))
  326. #t1.record()
  327. query_layer = self.transpose_for_scores(mixed_query_layer)
  328. # print(query_layer)
  329. #timing.append(t1.elapsed())
  330. #print("Query-Transform elapsed: %s" % (time.clock() - start))
  331. #t1.record()
  332. key_layer = self.transpose_key_for_scores(mixed_key_layer)
  333. # print(key_layer)
  334. #timing.append(t1.elapsed())
  335. #print("Key-Transform elapsed: %s" % (time.clock() - start))
  336. #t1.record()
  337. value_layer = self.transpose_for_scores(mixed_value_layer)
  338. #print(value_layer)
  339. #timing.append(t1.elapsed())
  340. #print("Value-Transform elapsed: %s" % (time.clock() - start))
  341. # Take the dot product between "query" and "key" to get the raw attention scores.
  342. #t1.record()
  343. #print(query_layer.shape)
  344. #print(key_layer.shape)
  345. attention_scores = torch.matmul(query_layer, key_layer)
  346. #print(attention_scores.shape)
  347. attention_scores = attention_scores / math.sqrt(self.attention_head_size)
  348. #print("Pytorch: ", attention_scores)
  349. #timing.append(t1.elapsed())
  350. #print("Attention-Score elapsed: %s" % (time.clock() - start))
  351. # Apply the attention mask is (precomputed for all layers in BertModel forward() function)
  352. #t1.record()
  353. # context_layer = self.softmax(query_layer, key_layer, value_layer, attention_mask)
  354. #print("context shape is :", context_layer.shape)
  355. #print("Cuda-ext:, ", attention_scores1)
  356. # Normalize the attention scores to probabilities.
  357. ####attention_probs = self.softmax(attention_scores)
  358. #timing.append(t1.elapsed())
  359. #print("Softmax elapsed: %s" % (time.clock() - start))
  360. #t1 = GPUTimer()
  361. #t1.record()
  362. attention_scores = attention_scores + attention_mask
  363. attention_probs = self.softmax(attention_scores)
  364. #attention_scores = self.softmax(attention_scores, attention_mask)
  365. #print("Softmax elapse {0:8.2f} ms", t1.elapsed() * 1000)
  366. # This is actually dropping out entire tokens to attend to, which might
  367. # seem a bit unusual, but is taken from the original Transformer paper.
  368. attention_probs = self.dropout(attention_probs)
  369. #t1.record()
  370. context_layer = torch.matmul(attention_probs, value_layer)
  371. #timing.append(t1.elapsed())
  372. #print("Context elapsed: %s" % (time.clock() - start))
  373. #t1.record()
  374. #context_layer1 = context_layer.permute(
  375. # 0, 1, 3, 2, 4).contiguous()
  376. #if grads is not None:
  377. # context_layer.register_hook(lambda x, self = self : grads.append([x, "Context"]))
  378. context_layer1 = context_layer.permute(0, 2, 1, 3).contiguous()
  379. new_context_layer_shape = context_layer1.size()[:-2] + (self.all_head_size, )
  380. context_layer1 = context_layer1.view(*new_context_layer_shape)
  381. #timing.append(t1.elapsed())
  382. #print("Context-Transform elapsed: %s" % (time.clock() - start))
  383. if grads is not None:
  384. query_layer.register_hook(lambda x, self=self: grads.append([x, "Query"]))
  385. key_layer.register_hook(lambda x, self=self: grads.append([x, "Key"]))
  386. value_layer.register_hook(lambda x, self=self: grads.append([x, "Value"]))
  387. return context_layer1
  388. class BertSelfOutput(nn.Module):
  389. def __init__(self, config, weights, biases):
  390. super(BertSelfOutput, self).__init__()
  391. self.dense = nn.Linear(config.hidden_size, config.hidden_size)
  392. self.dense.weight = weights[3]
  393. self.dense.bias = biases[3]
  394. self.LayerNorm = BertLayerNorm(config.hidden_size, eps=1e-12)
  395. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  396. def forward(self, hidden_states, input_tensor):
  397. #timing = []
  398. #t1 = GPUTimer()
  399. #t1.record()
  400. hidden_states = self.dense(hidden_states)
  401. #timing.append(t1.elapsed())
  402. #print("Attention Output elapsed: %s" % (time.clock() - start))
  403. hidden_states = self.dropout(hidden_states)
  404. #t1.record()
  405. #hidden_states = self.LayerNorm(hidden_states + input_tensor)
  406. #timing.append(t1.elapsed())
  407. #print("LayerNorm elapsed: %s" % (time.clock() - start))
  408. return hidden_states
  409. def get_w(self):
  410. return self.dense.weight
  411. class BertAttention(nn.Module):
  412. def __init__(self, i, config, weights, biases):
  413. super(BertAttention, self).__init__()
  414. self.self = BertSelfAttention(i, config, weights, biases)
  415. self.output = BertSelfOutput(config, weights, biases)
  416. def forward(self, input_tensor, attention_mask):
  417. self_output = self.self(input_tensor, attention_mask)
  418. attention_output = self.output(self_output, input_tensor)
  419. return attention_output
  420. def get_w(self):
  421. return self.output.get_w()
  422. class BertIntermediate(nn.Module):
  423. def __init__(self, config, weights, biases):
  424. super(BertIntermediate, self).__init__()
  425. self.dense_act = LinearActivation(config.hidden_size,
  426. config.intermediate_size,
  427. weights,
  428. biases,
  429. act=config.hidden_act)
  430. def forward(self, hidden_states):
  431. hidden_states = self.dense_act(hidden_states)
  432. return hidden_states
  433. class BertOutput(nn.Module):
  434. def __init__(self, config, weights, biases):
  435. super(BertOutput, self).__init__()
  436. self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
  437. self.dense.weight = weights[6]
  438. self.dense.bias = biases[6]
  439. self.LayerNorm = BertLayerNorm(config.hidden_size, eps=1e-12)
  440. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  441. def forward(self, hidden_states, input_tensor):
  442. #timing = []
  443. #t1 = GPUTimer()
  444. #t1.record()
  445. #print (hidden_states)
  446. #print (self.dense.weight)
  447. hidden_states = self.dense(hidden_states)
  448. #timing.append(t1.elapsed())
  449. #print("FF2 elapsed: %s" % (time.clock() - start))
  450. hidden_states = self.dropout(hidden_states)
  451. #t1.record()
  452. #hidden_states = self.LayerNorm(hidden_states + input_tensor)
  453. #timing.append(t1.elapsed())
  454. #print("LayerNorm elapsed: %s" % (time.clock() - start))
  455. return hidden_states
  456. class BertLayer(nn.Module):
  457. def __init__(self, i, config, weights, biases):
  458. super(BertLayer, self).__init__()
  459. self.attention = BertAttention(i, config, weights, biases)
  460. self.PreAttentionLayerNorm = BertLayerNorm(config.hidden_size, eps=1e-12)
  461. self.PostAttentionLayerNorm = BertLayerNorm(config.hidden_size, eps=1e-12)
  462. self.intermediate = BertIntermediate(config, weights, biases)
  463. self.output = BertOutput(config, weights, biases)
  464. self.weight = weights
  465. self.biases = biases
  466. def forward(self, hidden_states, attention_mask, grads, collect_all_grads=False):
  467. input_layer_norm = self.PreAttentionLayerNorm(hidden_states)
  468. attention_output = self.attention(input_layer_norm, attention_mask)
  469. #print ("hidden shape is :", hidden_states.shape)
  470. intermediate_input = hidden_states + attention_output
  471. intermediate_layer_norm = self.PostAttentionLayerNorm(intermediate_input)
  472. intermediate_output = self.intermediate(intermediate_layer_norm)
  473. layer_output = self.output(intermediate_output, attention_output)
  474. #attention_output = self.attention(hidden_states, attention_mask)
  475. #intermediate_output = self.intermediate(attention_output)
  476. #layer_output = self.output(intermediate_output, attention_output)
  477. if collect_all_grads:
  478. # self.weight[0].register_hook(lambda x, self=self: grads.append([x,"Q_W"]))
  479. # self.biases[0].register_hook(lambda x, self=self: grads.append([x,"Q_B"]))
  480. # self.weight[1].register_hook(lambda x, self=self: grads.append([x,"K_W"]))
  481. # self.biases[1].register_hook(lambda x, self=self: grads.append([x,"K_B"]))
  482. self.weight[2].register_hook(lambda x, self=self: grads.append([x, "V_W"]))
  483. self.biases[2].register_hook(lambda x, self=self: grads.append([x, "V_B"]))
  484. self.weight[3].register_hook(lambda x, self=self: grads.append([x, "O_W"]))
  485. self.biases[3].register_hook(lambda x, self=self: grads.append([x, "O_B"]))
  486. self.PostAttentionLayerNorm.weight.register_hook(lambda x, self=self: grads.append([x, "N2_W"]))
  487. self.PostAttentionLayerNorm.bias.register_hook(lambda x, self=self: grads.append([x, "N2_B"]))
  488. self.weight[5].register_hook(lambda x, self=self: grads.append([x, "int_W"]))
  489. self.biases[5].register_hook(lambda x, self=self: grads.append([x, "int_B"]))
  490. self.weight[6].register_hook(lambda x, self=self: grads.append([x, "out_W"]))
  491. self.biases[6].register_hook(lambda x, self=self: grads.append([x, "out_B"]))
  492. self.PreAttentionLayerNorm.weight.register_hook(lambda x, self=self: grads.append([x, "norm_W"]))
  493. self.PreAttentionLayerNorm.bias.register_hook(lambda x, self=self: grads.append([x, "norm_B"]))
  494. return layer_output + intermediate_input
  495. def get_w(self):
  496. return self.attention.get_w()
  497. class BertEncoder(nn.Module):
  498. def __init__(self, config, weights, biases):
  499. super(BertEncoder, self).__init__()
  500. #layer = BertLayer(config, weights, biases)
  501. self.FinalLayerNorm = BertLayerNorm(config.hidden_size, eps=1e-12)
  502. self.layer = nn.ModuleList(
  503. [copy.deepcopy(BertLayer(i, config, weights, biases)) for i in range(config.num_hidden_layers)])
  504. self.grads = []
  505. self.graph = []
  506. def get_grads(self):
  507. return self.grads
  508. def get_modules(self, big_node, input):
  509. for mdl in big_node.named_children():
  510. self.graph.append(mdl)
  511. self.get_modules(self, mdl, input)
  512. def forward(self, hidden_states, attention_mask, output_all_encoded_layers=True, checkpoint_activations=False):
  513. all_encoder_layers = []
  514. def custom(start, end):
  515. def custom_forward(*inputs):
  516. layers = self.layer[start:end]
  517. x_ = inputs[0]
  518. for layer in layers:
  519. x_ = layer(x_, inputs[1])
  520. return x_
  521. return custom_forward
  522. if checkpoint_activations:
  523. l = 0
  524. num_layers = len(self.layer)
  525. chunk_length = math.ceil(math.sqrt(num_layers))
  526. while l < num_layers:
  527. hidden_states = checkpoint.checkpoint(custom(l, l + chunk_length), hidden_states, attention_mask * 1)
  528. l += chunk_length
  529. # decoder layers
  530. else:
  531. for i, layer_module in enumerate(self.layer):
  532. hidden_states = layer_module(hidden_states, attention_mask, self.grads, collect_all_grads=True)
  533. hidden_states.register_hook(lambda x, i=i, self=self: self.grads.append([x, "hidden_state"]))
  534. #print("pytorch weight is: ", layer_module.get_w())
  535. if output_all_encoded_layers:
  536. all_encoder_layers.append((hidden_states))
  537. if not output_all_encoded_layers or checkpoint_activations:
  538. hidden_states = self.FinalLayerNorm(hidden_states)
  539. all_encoder_layers.append((hidden_states))
  540. return all_encoder_layers