| import torch |
| import torch.nn as nn |
| import torch.nn.functional as F |
|
|
| class DocumentBiLSTM(nn.Module): |
| """ |
| A simpler BiLSTM implementation that doesn't require pre-loaded embeddings |
| Good for getting started quickly |
| """ |
| def __init__(self, vocab_size, embedding_dim, hidden_dim, output_dim, |
| n_layers=2, dropout=0.5, pad_idx=0): |
| super().__init__() |
| |
| self.embedding = nn.Embedding(vocab_size, embedding_dim, padding_idx=pad_idx) |
| |
| self.lstm = nn.LSTM(embedding_dim, |
| hidden_dim, |
| num_layers=n_layers, |
| bidirectional=True, |
| dropout=dropout if n_layers > 1 else 0, |
| batch_first=True) |
| |
| self.fc = nn.Linear(hidden_dim * 2, output_dim) |
| |
| self.dropout = nn.Dropout(dropout) |
| |
| def forward(self, input_ids, attention_mask=None, **kwargs): |
| |
| |
| |
| embedded = self.embedding(input_ids) |
| |
| |
| embedded = self.dropout(embedded) |
| |
| if attention_mask is not None: |
| |
| |
| |
| pass |
| |
| |
| |
| |
| output, (hidden, cell) = self.lstm(embedded) |
| |
| |
| hidden = torch.cat((hidden[-2,:,:], hidden[-1,:,:]), dim=1) |
| |
| |
| hidden = self.dropout(hidden) |
| |
| |
| prediction = self.fc(hidden) |
| |
| return prediction |