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.
| 715 | |
| 716 | |
| 717 | class MLP(torch.nn.Module): |
| 718 | """MLP. |
| 719 | |
| 720 | MLP will take the input with h hidden state, project it to 4*h |
| 721 | hidden dimension, perform nonlinear transformation, and project the |
| 722 | state back into h hidden dimension. |
| 723 | """ |
| 724 | |
| 725 | def __init__(self, config: ChatGLMConfig, device=None): |
| 726 | super(MLP, self).__init__() |
| 727 | |
| 728 | self.add_bias = config.add_bias_linear |
| 729 | |
| 730 | # Project to 4h. If using swiglu double the output width, see https://arxiv.org/pdf/2002.05202.pdf |
| 731 | self.dense_h_to_4h = nn.Linear( |
| 732 | config.hidden_size, |
| 733 | config.ffn_hidden_size * 2, |
| 734 | bias=self.add_bias, |
| 735 | device=device, |
| 736 | **_config_to_kwargs(config) |
| 737 | ) |
| 738 | |
| 739 | def swiglu(x): |
| 740 | x = torch.chunk(x, 2, dim=-1) |
| 741 | return F.silu(x[0]) * x[1] |
| 742 | |
| 743 | self.activation_func = swiglu |
| 744 | |
| 745 | # Project back to h. |
| 746 | self.dense_4h_to_h = nn.Linear( |
| 747 | config.ffn_hidden_size, |
| 748 | config.hidden_size, |
| 749 | bias=self.add_bias, |
| 750 | device=device, |
| 751 | **_config_to_kwargs(config) |
| 752 | ) |
| 753 | |
| 754 | def forward(self, hidden_states): |
| 755 | # [s, b, 4hp] |
| 756 | intermediate_parallel = self.dense_h_to_4h(hidden_states) |
| 757 | intermediate_parallel = self.activation_func(intermediate_parallel) |
| 758 | # [s, b, h] |
| 759 | output = self.dense_4h_to_h(intermediate_parallel) |
| 760 | return output |
| 761 | |
| 762 | |
| 763 | class GLMBlock(torch.nn.Module): |