| 86 | |
| 87 | |
| 88 | class Qwen2EncoderLayer(nn.Module): |
| 89 | def __init__(self, config: Qwen2Config, layer_idx: int): |
| 90 | super().__init__() |
| 91 | self.hidden_size = config.hidden_size |
| 92 | self.self_attn = Qwen2BidirectionalSdpaAttention(config, layer_idx) |
| 93 | self.mlp = Qwen2MLP(config) |
| 94 | |
| 95 | self.input_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps) |
| 96 | self.post_attention_layernorm = Qwen2RMSNorm( |
| 97 | config.hidden_size, eps=config.rms_norm_eps |
| 98 | ) |
| 99 | |
| 100 | def forward( |
| 101 | self, |
| 102 | hidden_states: torch.Tensor, |
| 103 | position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, |
| 104 | ): |
| 105 | # Norm + Self-Attn |
| 106 | residual = hidden_states |
| 107 | hidden_states = self.input_layernorm(hidden_states) |
| 108 | |
| 109 | hidden_states = self.self_attn( |
| 110 | hidden_states=hidden_states, |
| 111 | position_embeddings=position_embeddings, |
| 112 | ) |
| 113 | hidden_states = residual + hidden_states |
| 114 | |
| 115 | # Norm + MLP |
| 116 | residual = hidden_states |
| 117 | hidden_states = self.post_attention_layernorm(hidden_states) |
| 118 | hidden_states = self.mlp(hidden_states) |
| 119 | hidden_states = residual + hidden_states |
| 120 | |
| 121 | return hidden_states |
| 122 | |
| 123 | |
| 124 | class Qwen2Encoder(Qwen2PreTrainedModel): |