| 139 | |
| 140 | |
| 141 | class RecurrentGPT2Block(nn.Module): |
| 142 | def __init__(self, config, num_iterations): |
| 143 | super().__init__() |
| 144 | self.config = config |
| 145 | self.num_iterations = num_iterations |
| 146 | self.blocks = nn.ModuleList([GPT2Block(config) for _ in range(config.n_layer)]) |
| 147 | |
| 148 | self.token_embedding = nn.Embedding(config.vocab_size, config.n_embd) |
| 149 | self.position_embedding = nn.Embedding(config.n_positions, config.n_embd) |
| 150 | |
| 151 | embd_pdrop = getattr(config, "embd_pdrop", 0.1) |
| 152 | self.dropout = nn.Dropout(embd_pdrop) |
| 153 | |
| 154 | layer_norm_epsilon = getattr(config, "layer_norm_epsilon", 1e-5) |
| 155 | self.ln_f = nn.LayerNorm(config.n_embd, eps=layer_norm_epsilon) |
| 156 | |
| 157 | self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False) |
| 158 | self.lm_head.weight = self.token_embedding.weight |
| 159 | |
| 160 | def forward(self, input_ids, attention_mask=None): |
| 161 | |
| 162 | batch_size, seq_len = input_ids.size() |
| 163 | device = input_ids.device |
| 164 | |
| 165 | position_ids = torch.arange(0, seq_len, dtype=torch.long, device=device) |
| 166 | position_ids = position_ids.unsqueeze(0).expand(batch_size, seq_len) |
| 167 | |
| 168 | token_embeds = self.token_embedding(input_ids) |
| 169 | pos_embeds = self.position_embedding(position_ids) |
| 170 | hidden_states = token_embeds + pos_embeds |
| 171 | hidden_states = self.dropout(hidden_states) |
| 172 | |
| 173 | if attention_mask is not None: |
| 174 | attention_mask = attention_mask.unsqueeze(1).unsqueeze(2) |
| 175 | attention_mask = attention_mask.to(dtype=hidden_states.dtype) |
| 176 | attention_mask = (1.0 - attention_mask) * -10000.0 |
| 177 | |
| 178 | for _ in range(self.num_iterations): |
| 179 | for block in self.blocks: |
| 180 | hidden_states = block(hidden_states, attention_mask=attention_mask)[0] |
| 181 | |
| 182 | hidden_states = self.ln_f(hidden_states) |
| 183 | logits = self.lm_head(hidden_states) |
| 184 | |
| 185 | return type("Output", (object,), {"logits": logits}) |
no outgoing calls
no test coverage detected