A single transformer layer. Transformer layer takes input with size [s, b, h] and returns an output of the same size.
| 761 | |
| 762 | |
| 763 | class GLMBlock(torch.nn.Module): |
| 764 | """A single transformer layer. |
| 765 | |
| 766 | Transformer layer takes input with size [s, b, h] and returns an |
| 767 | output of the same size. |
| 768 | """ |
| 769 | |
| 770 | def __init__(self, config: ChatGLMConfig, layer_number, device=None): |
| 771 | super(GLMBlock, self).__init__() |
| 772 | self.layer_number = layer_number |
| 773 | |
| 774 | self.apply_residual_connection_post_layernorm = config.apply_residual_connection_post_layernorm |
| 775 | |
| 776 | self.fp32_residual_connection = config.fp32_residual_connection |
| 777 | |
| 778 | LayerNormFunc = RMSNorm if config.rmsnorm else LayerNorm |
| 779 | # Layernorm on the input data. |
| 780 | self.input_layernorm = LayerNormFunc(config.hidden_size, eps=config.layernorm_epsilon, device=device, |
| 781 | dtype=config.torch_dtype) |
| 782 | |
| 783 | # Self attention. |
| 784 | self.self_attention = SelfAttention(config, layer_number, device=device) |
| 785 | self.hidden_dropout = config.hidden_dropout |
| 786 | |
| 787 | # Layernorm on the attention output |
| 788 | self.post_attention_layernorm = LayerNormFunc(config.hidden_size, eps=config.layernorm_epsilon, device=device, |
| 789 | dtype=config.torch_dtype) |
| 790 | |
| 791 | # MLP |
| 792 | self.mlp = MLP(config, device=device) |
| 793 | |
| 794 | def forward( |
| 795 | self, hidden_states, attention_mask, rotary_pos_emb, kv_cache=None, use_cache=True, |
| 796 | ): |
| 797 | # hidden_states: [s, b, h] |
| 798 | |
| 799 | # Layer norm at the beginning of the transformer layer. |
| 800 | layernorm_output = self.input_layernorm(hidden_states) |
| 801 | # Self attention. |
| 802 | attention_output, kv_cache = self.self_attention( |
| 803 | layernorm_output, |
| 804 | attention_mask, |
| 805 | rotary_pos_emb, |
| 806 | kv_cache=kv_cache, |
| 807 | use_cache=use_cache |
| 808 | ) |
| 809 | |
| 810 | # Residual connection. |
| 811 | if self.apply_residual_connection_post_layernorm: |
| 812 | residual = layernorm_output |
| 813 | else: |
| 814 | residual = hidden_states |
| 815 | |
| 816 | layernorm_input = torch.nn.functional.dropout(attention_output, p=self.hidden_dropout, training=self.training) |
| 817 | layernorm_input = residual + layernorm_input |
| 818 | |
| 819 | # Layer norm post the self attention. |
| 820 | layernorm_output = self.post_attention_layernorm(layernorm_input) |