import torch import torch.nn as nn from transformers import AutoModel from peft import LoraConfig, get_peft_model from typing import Any, List, Iterable class Model(nn.Module): """ Hybrid RoBERTa + engineered features classifier with LoRA fine-tuning. LoRA config: r=8, alpha=16, targeting query and value projection matrices. """ def __init__(self, n_extra=9, n_classes=2) -> None: super().__init__() # 1. Load the raw RoBERTa backbone self.backbone = AutoModel.from_pretrained("roberta-base") # 2. Apply LoRA lora_cfg = LoraConfig( r=8, lora_alpha=16, target_modules=['query', 'value'], # RoBERTa naming lora_dropout=0.1, bias='none', ) self.backbone = get_peft_model(self.backbone, lora_cfg) hidden_size = 768 # Standard for roberta-base # 3. Classification Head self.classifier = nn.Sequential( nn.Linear(hidden_size + n_extra, 256), nn.ReLU(), nn.Dropout(0.1), nn.Linear(256, n_classes) ) self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu") self.to(self.device) def forward(self, input_ids, attention_mask, extra): # Accessing the PEFT-wrapped backbone outputs = self.backbone(input_ids=input_ids, attention_mask=attention_mask) # Pulling the [CLS] token (first token) cls_token = outputs.last_hidden_state[:, 0, :] # Concatenate RoBERTa features with our 9 engineered features combined = torch.cat((cls_token, extra), dim=1) return self.classifier(combined) def predict(self, batch: Iterable[Any]) -> List[Any]: self.eval() predictions = [] with torch.no_grad(): for item in batch: # Move tensors to the correct device ids = item['input_ids'].unsqueeze(0).to(self.device) mask = item['attention_mask'].unsqueeze(0).to(self.device) extra = item['extra'].unsqueeze(0).to(self.device) logits = self.forward(input_ids=ids, attention_mask=mask, extra=extra) # Get the index of the highest logit (0 or 1) pred = torch.argmax(logits, dim=1).item() predictions.append(pred) return predictions