| 370 | |
| 371 | |
| 372 | class BertLayer(nn.Module): |
| 373 | |
| 374 | def __init__(self, i, config, weights, biases): |
| 375 | super(BertLayer, self).__init__() |
| 376 | self.attention = BertAttention(i, config, weights, biases) |
| 377 | self.intermediate = BertIntermediate(config, weights, biases) |
| 378 | self.output = BertOutput(config, weights, biases) |
| 379 | self.weight = weights |
| 380 | self.biases = biases |
| 381 | |
| 382 | def forward(self, hidden_states, attention_mask, grads, collect_all_grads=False): |
| 383 | attention_output = self.attention(hidden_states, attention_mask) |
| 384 | intermediate_output = self.intermediate(attention_output) |
| 385 | layer_output = self.output(intermediate_output, attention_output) |
| 386 | |
| 387 | if collect_all_grads: |
| 388 | self.weight[2].register_hook(lambda x, self=self: grads.append([x, "V_W"])) |
| 389 | self.biases[2].register_hook(lambda x, self=self: grads.append([x, "V_B"])) |
| 390 | self.weight[3].register_hook(lambda x, self=self: grads.append([x, "O_W"])) |
| 391 | self.biases[3].register_hook(lambda x, self=self: grads.append([x, "O_B"])) |
| 392 | self.attention.output.LayerNorm.weight.register_hook(lambda x, self=self: grads.append([x, "N2_W"])) |
| 393 | self.attention.output.LayerNorm.bias.register_hook(lambda x, self=self: grads.append([x, "N2_B"])) |
| 394 | self.weight[5].register_hook(lambda x, self=self: grads.append([x, "int_W"])) |
| 395 | self.biases[5].register_hook(lambda x, self=self: grads.append([x, "int_B"])) |
| 396 | self.weight[6].register_hook(lambda x, self=self: grads.append([x, "out_W"])) |
| 397 | self.biases[6].register_hook(lambda x, self=self: grads.append([x, "out_B"])) |
| 398 | self.output.LayerNorm.weight.register_hook(lambda x, self=self: grads.append([x, "norm_W"])) |
| 399 | self.output.LayerNorm.bias.register_hook(lambda x, self=self: grads.append([x, "norm_B"])) |
| 400 | |
| 401 | return layer_output |
| 402 | |
| 403 | def get_w(self): |
| 404 | return self.attention.get_w() |
| 405 | |
| 406 | |
| 407 | class BertEncoder(nn.Module): |