Spaces:
Running
Running
File size: 6,746 Bytes
283dd4a afd8852 283dd4a a0a0073 283dd4a afd8852 283dd4a |
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 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 |
import streamlit as st
import json
import numpy as np
import torch
from transformers import (
DebertaV2Config,
DebertaV2Model,
DebertaV2Tokenizer,
)
import sentencepiece
model_name = "microsoft/deberta-v3-base"
tokenizer = DebertaV2Tokenizer.from_pretrained(model_name)
def preprocess_text(text, tokenizer, max_length=512):
inputs = tokenizer(
text,
padding="max_length",
truncation=True,
max_length=max_length,
return_tensors="pt"
)
return inputs
def classify_text(text, model, tokenizer, device, threshold=0.5):
inputs = preprocess_text(text, tokenizer)
input_ids = inputs["input_ids"].to(device)
attention_mask = inputs["attention_mask"].to(device)
model.eval()
with torch.no_grad():
logits = model(input_ids, attention_mask)
probs = torch.sigmoid(logits)
predictions = (probs > threshold).int().cpu().numpy()
return probs.cpu().numpy(), predictions
def get_themes(text, model, tokenizer, label_to_theme, device, limit=5):
probabilities, _ = classify_text(text, model, tokenizer, device)
themes = []
for label in probabilities[0].argsort()[-limit:]:
themes.append((label_to_theme[str(label)], probabilities[0][label]))
return themes
class DebertPaperClassifier(torch.nn.Module):
def __init__(self, num_labels, device, dropout_rate=0.1, class_weights=None):
super().__init__()
self.config = DebertaV2Config.from_pretrained(model_name)
self.deberta = DebertaV2Model.from_pretrained(model_name, config=self.config)
self.classifier = torch.nn.Sequential(
torch.nn.Dropout(dropout_rate),
torch.nn.Linear(self.config.hidden_size, 512),
torch.nn.LayerNorm(512),
torch.nn.GELU(),
torch.nn.Dropout(dropout_rate),
torch.nn.Linear(512, num_labels)
)
self._init_weights()
if class_weights is not None:
self.loss_fct = torch.nn.BCEWithLogitsLoss(weight=class_weights.to(device))
else:
self.loss_fct = torch.nn.BCEWithLogitsLoss()
class DebertPaperClassifierV5(torch.nn.Module):
def __init__(self, device, num_labels=47, dropout_rate=0.1, class_weights=None):
super().__init__()
self.config = DebertaV2Config.from_pretrained("microsoft/deberta-v3-base")
self.deberta = DebertaV2Model.from_pretrained("microsoft/deberta-v3-base", config=self.config)
self.classifier = torch.nn.Sequential(
torch.nn.Dropout(dropout_rate),
torch.nn.Linear(self.config.hidden_size, 512),
torch.nn.LayerNorm(512),
torch.nn.GELU(),
torch.nn.Dropout(dropout_rate),
torch.nn.Linear(512, num_labels)
)
if class_weights is not None:
self.loss_fct = torch.nn.BCEWithLogitsLoss(weight=class_weights.to(device))
else:
self.loss_fct = torch.nn.BCEWithLogitsLoss()
def forward(self, input_ids, attention_mask, labels=None):
outputs = self.deberta(
input_ids=input_ids,
attention_mask=attention_mask
)
logits = self.classifier(outputs.last_hidden_state[:, 0, :])
loss = None
if labels is not None:
loss = self.loss_fct(logits, labels)
return (loss, logits) if loss is not None else logits
def _init_weights(self):
for module in self.classifier.modules():
if isinstance(module, torch.nn.Linear):
module.weight.data.normal_(mean=0.0, std=0.02)
if module.bias is not None:
module.bias.data.zero_()
def forward(self,
input_ids,
attention_mask,
labels=None,
):
outputs = self.deberta(
input_ids=input_ids,
attention_mask=attention_mask
)
cls_output = outputs.last_hidden_state[:, 0, :]
logits = self.classifier(cls_output)
loss = None
if labels is not None:
loss = self.loss_fct(logits, labels)
return (loss, logits) if loss is not None else logits
@st.cache_resource
def load_model(test=False):
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
try:
path = '/Users/bvd757/my_documents/Машинное обучение 2/Howework4'
with open(f'{path}/label_to_theme.json', 'r') as f:
label_to_theme = json.load(f)
except:
path = '/home/user/app'
with open(f'{path}/label_to_theme.json', 'r') as f:
label_to_theme = json.load(f)
class_weights = torch.load(f'{path}/class_weights.pth').to(device)
model = DebertPaperClassifier(device=device, num_labels=len(label_to_theme), class_weights=class_weights).to(device)
model.load_state_dict(torch.load(f"{path}/full_model_v4.pth", map_location=device))
if test:
print(device)
print(model)
print("Model!!!")
text = 'We propose an architecture for VQA which utilizes recurrent layers to\ngenerate visual and textual attention. The memory characteristic of the\nproposed recurrent attention units offers a rich joint embedding of visual and\ntextual features and enables the model to reason relations between several\nparts of the image and question. Our single model outperforms the first place\nwinner on the VQA 1.0 dataset, performs within margin to the current\nstate-of-the-art ensemble model. We also experiment with replacing attention\nmechanisms in other state-of-the-art models with our implementation and show\nincreased accuracy. In both cases, our recurrent attention mechanism improves\nperformance in tasks requiring sequential or relational reasoning on the VQA\ndataset.'
print(get_themes(text, model, tokenizer, label_to_theme, device))
return model, tokenizer, label_to_theme, device
def kek():
title = st.text_input("Title")
abstract = st.text_area("Abstract")
if st.button("Classify"):
if not title and not abstract:
st.warning("Please enter an abstract")
return
text = f"{title}\n\n{abstract}" if title and abstract else title or abstract
model, tokenizer, label_to_theme, device = load_model()
with st.spinner("Classifying..."):
themes = get_themes(text, model, tokenizer, label_to_theme, device, lim)
st.success("Classification results:")
for theme, prob in themes:
st.write(f"- {theme}: {prob:.2%}")
if __name__ == "__main__":
inp = '0'
if inp != '0':
kek()
else:
load_model(True)
|