| import torch |
| import torch.nn as nn |
| from transformers import AutoConfig, AutoModel |
|
|
| class DocBERT(nn.Module): |
| """ |
| Document classification using BERT with improved architecture |
| based on Hedwig implementation patterns. |
| """ |
| def __init__(self, num_classes, bert_model_name='bert-base-uncased', dropout_prob=0.1, num_categories=1): |
| super(DocBERT, self).__init__() |
| |
| |
| |
| self.bert = AutoModel.from_pretrained(bert_model_name) |
| self.config = AutoConfig.from_pretrained(bert_model_name) |
| |
| |
| self.dropout = nn.Dropout(dropout_prob) |
| |
| |
| self.hidden_size = self.config.hidden_size |
| self.num_categories = num_categories |
| self.classifier = nn.Linear(self.hidden_size, num_classes*num_categories) |
| |
| |
| self.layer_norm = nn.LayerNorm(self.hidden_size) |
| |
| def forward(self, input_ids, attention_mask=None, token_type_ids=None): |
| """ |
| Forward pass through the model |
| """ |
| |
| outputs = self.bert(input_ids=input_ids, |
| attention_mask=attention_mask, |
| token_type_ids=token_type_ids) |
| |
| |
| pooled_output = outputs.pooler_output |
| |
| |
| normalized_output = self.layer_norm(pooled_output) |
| |
| |
| dropped_output = self.dropout(normalized_output) |
| |
| |
| logits = self.classifier(dropped_output) |
| |
| return logits |