Views
No views yet
1class AttentionOnlyTransformer(PreTrainedModel):
2 """Attention-only transformer with configurable number of attention layers."""
3 config_class = LlamaConfig
4
5 def __init__(self, config: LlamaConfig):
6 super().__init__(config)
7 self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size)
8 self.layers = nn.ModuleList([AttentionLayer(config) for _ in range(config.num_hidden_layers)])
9 self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
10
11 def forward(self, input_ids=None, attention_mask=None, labels=None, **kwargs):
12 batch_size, seq_len = input_ids.shape
13 hidden_states = self.embed_tokens(input_ids)
14 assert hidden_states.shape == (batch_size, seq_len, self.config.hidden_size)
15 assert attention_mask.shape == (batch_size, seq_len)
16
17 for layer in self.layers:
18 hidden_states = layer(hidden_states, attention_mask)
19 assert hidden_states.shape == (batch_size, seq_len, self.config.hidden_size)
20
21 logits = self.lm_head(hidden_states)
22 assert logits.shape == (batch_size, seq_len, self.config.vocab_size)
23
24 loss = None
25 if labels is not None:
26 shift_logits = logits[..., :-1, :].contiguous()
27 shift_labels = labels[..., 1:].contiguous()
28 loss_fct = nn.CrossEntropyLoss()
29 loss = loss_fct(
30 shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1)
31 )
32
33 return {"loss": loss, "logits": logits}
34
35
36model = AttentionOnlyTransformer.from_pretrained('Butanium/simple-stories-2L4H512D-attention-only-toy-transformer')