Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from transformers import AutoModelForMaskedLM, AutoTokenizer
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
model_id = "naver/ecir23-scratch-tydi-russian-splade"
|
| 6 |
+
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
| 7 |
+
model = AutoModelForMaskedLM.from_pretrained(model_id)
|
| 8 |
+
|
| 9 |
+
def compute_vector(question: str):
|
| 10 |
+
"""
|
| 11 |
+
Computes a vector from logits and attention mask using ReLU, log, and max operations.
|
| 12 |
+
|
| 13 |
+
Args:
|
| 14 |
+
logits (torch.Tensor): The logits output from a model.
|
| 15 |
+
attention_mask (torch.Tensor): The attention mask corresponding to the input tokens.
|
| 16 |
+
|
| 17 |
+
Returns:
|
| 18 |
+
torch.Tensor: Computed vector.
|
| 19 |
+
"""
|
| 20 |
+
# Извлекаем 'inputs' из полученного JSON
|
| 21 |
+
text = question.get('inputs', '')
|
| 22 |
+
# Проверяем, что text это строка
|
| 23 |
+
if not isinstance(text, str):
|
| 24 |
+
return {"error": "Неправильный формат входных данных. Ожидается строка."}
|
| 25 |
+
|
| 26 |
+
tokens = tokenizer(text, truncation=True, padding=True, max_length=2048, return_tensors="pt")
|
| 27 |
+
output = model(**tokens)
|
| 28 |
+
logits, attention_mask = output.logits, tokens.attention_mask
|
| 29 |
+
relu_log = torch.log(1 + torch.relu(logits))
|
| 30 |
+
weighted_log = relu_log * attention_mask.unsqueeze(-1)
|
| 31 |
+
max_val, _ = torch.max(weighted_log, dim=1)
|
| 32 |
+
vec = max_val.squeeze()
|
| 33 |
+
indices = vec.nonzero().numpy().flatten().tolist()
|
| 34 |
+
values = vec.detach().numpy()[indices].tolist()
|
| 35 |
+
|
| 36 |
+
return indices, values
|
| 37 |
+
|
| 38 |
+
sparse_int = gr.Interface(
|
| 39 |
+
fn=compute_vector,
|
| 40 |
+
inputs=gr.JSON(label="Введите JSON в формате {'inputs': 'sentence1'}"),
|
| 41 |
+
outputs="json",
|
| 42 |
+
title="Sparse vector",
|
| 43 |
+
description="Compute sparse vector using the 'naver/ecir23-scratch-tydi-russian-splade' model under the hood!"
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
sparse_int.launch()
|