MLP. MLP will take the input with h hidden state, project it to 4*h hidden dimension, perform nonlinear transformation, and project the state back into h hidden dimension.
| 457 | |
| 458 | |
| 459 | class MLP(torch.nn.Module): |
| 460 | """MLP. |
| 461 | |
| 462 | MLP will take the input with h hidden state, project it to 4*h |
| 463 | hidden dimension, perform nonlinear transformation, and project the |
| 464 | state back into h hidden dimension. |
| 465 | """ |
| 466 | |
| 467 | def __init__(self, config: ChatGLMConfig, device=None): |
| 468 | super(MLP, self).__init__() |
| 469 | |
| 470 | self.add_bias = config.add_bias_linear |
| 471 | |
| 472 | # Project to 4h. If using swiglu double the output width, see https://arxiv.org/pdf/2002.05202.pdf |
| 473 | self.dense_h_to_4h = nn.Linear( |
| 474 | config.hidden_size, |
| 475 | config.ffn_hidden_size * 2, |
| 476 | bias=self.add_bias, |
| 477 | device=device, |
| 478 | **_config_to_kwargs(config) |
| 479 | ) |
| 480 | |
| 481 | def swiglu(x): |
| 482 | x = torch.chunk(x, 2, dim=-1) |
| 483 | return F.silu(x[0]) * x[1] |
| 484 | |
| 485 | self.activation_func = swiglu |
| 486 | |
| 487 | # Project back to h. |
| 488 | self.dense_4h_to_h = nn.Linear( |
| 489 | config.ffn_hidden_size, |
| 490 | config.hidden_size, |
| 491 | bias=self.add_bias, |
| 492 | device=device, |
| 493 | **_config_to_kwargs(config) |
| 494 | ) |
| 495 | |
| 496 | def forward(self, hidden_states): |
| 497 | # [s, b, 4hp] |
| 498 | intermediate_parallel = self.dense_h_to_4h(hidden_states) |
| 499 | intermediate_parallel = self.activation_func(intermediate_parallel) |
| 500 | # [s, b, h] |
| 501 | output = self.dense_4h_to_h(intermediate_parallel) |
| 502 | return output |
| 503 | |
| 504 | |
| 505 | class GLMBlock(torch.nn.Module): |