Implement TinyGPT(vocab_size, d_model, num_heads, num_layers, max_seq_len) as an nn.Module. The model combines token embeddings, learned positional embeddings, a stack of pre-LN transformer blocks, a final LayerNorm, and a linear projection back to the vocabulary.
Required attributes:
self.token_emb: nn.Embedding(vocab_size, d_model).self.pos_emb: nn.Embedding(max_seq_len, d_model).self.blocks: an nn.ModuleList of num_layers blocks. Each block is a nn.TransformerEncoderLayer with d_model, nhead=num_heads, dim_feedforward=4 * d_model, activation='gelu', batch_first=True, norm_first=True, and dropout=0.0.self.ln_f: a final nn.LayerNorm(d_model).self.head: nn.Linear(d_model, vocab_size, bias=False).The forward(idx) method takes idx of shape (B, T) with integer token ids and:
(B, T, vocab_size) and returns.torch.arange(T, device=idx.device); pos_emb will look them up.-inf above the diagonal. nn.Transformer.generate_square_subsequent_mask(T) produces one in the right format.TransformerEncoderLayer with batch_first=True and norm_first=True is the pre-LN block you implemented earlier - reuse it.