Spaces:
No application file
No application file
File size: 2,457 Bytes
602fb89 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | 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
|