|
from typing import Dict, List, Any |
|
from transformers import AutoTokenizer, AutoModel |
|
from optimum.pipelines import pipeline |
|
from optimum.onnxruntime import ORTModelForFeatureExtraction |
|
from pathlib import Path |
|
import time |
|
|
|
import os |
|
import torch |
|
|
|
def max_pooling(model_output): |
|
|
|
_, Z, Y = model_output.shape |
|
|
|
output_array = [0] * Y |
|
|
|
for i in range(Z): |
|
|
|
for j in range(Y): |
|
|
|
if model_output[0][i][j] > output_array[j]: |
|
output_array[j] = model_output[0][i][j] |
|
return output_array |
|
|
|
|
|
def mean_pooling(model_output, attention_mask): |
|
token_embeddings = model_output[0] |
|
input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float() |
|
return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9) |
|
|
|
class EndpointHandler(): |
|
def __init__(self, path=""): |
|
print("HELLO THIS IS THE CWD:", os.getcwd()) |
|
print("HELLO THIS IS THE PATH ARG:", path) |
|
files = os.listdir(path) |
|
for file in files: |
|
print(file) |
|
|
|
task = "feature-extraction" |
|
self.tokenizer = AutoTokenizer.from_pretrained('sentence-transformers/msmarco-MiniLM-L-6-v3') |
|
model_regular = ORTModelForFeatureExtraction.from_pretrained("jpohhhh/msmarco-MiniLM-L-6-v3_onnx", from_transformers=False) |
|
|
|
self.onnx_extractor = pipeline(task, model=model_regular, tokenizer=self.tokenizer) |
|
|
|
|
|
|
|
def __call__(self, data: Dict[str, Any]) -> List[Dict[str, Any]]: |
|
""" |
|
data args: |
|
inputs (:obj: `str` | `PIL.Image` | `np.array`) |
|
kwargs |
|
Return: |
|
A :obj:`list` | `dict`: will be serialized and returned |
|
""" |
|
print("A") |
|
sentences = data.pop("inputs",data) |
|
print("B") |
|
sentence_embeddings = [] |
|
print("C") |
|
for sentence in sentences: |
|
print("D") |
|
|
|
|
|
|
|
with torch.no_grad(): |
|
model_output = self.onnx_extractor(sentence) |
|
print("E") |
|
|
|
|
|
|
|
print("F") |
|
|
|
sentence_embeddings.append(max_pooling(model_output)) |
|
print("G") |
|
return sentence_embeddings |