Hans Elias J commited on
Commit
59c3fb3
1 Parent(s): b303079

add inference endpoints handler.py

Browse files
Files changed (1) hide show
  1. handler.py +35 -0
handler.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, List, Any
2
+ from transformers import pipeline
3
+
4
+ import torch.nn.functional as F
5
+ from torch import Tensor
6
+ from transformers import AutoTokenizer, AutoModel
7
+
8
+ def average_pool(last_hidden_states: Tensor,
9
+ attention_mask: Tensor) -> Tensor:
10
+ last_hidden = last_hidden_states.masked_fill(~attention_mask[..., None].bool(), 0.0)
11
+ return last_hidden.sum(dim=1) / attention_mask.sum(dim=1)[..., None]
12
+
13
+ class EndpointHandler():
14
+ def __init__(self, path=""):
15
+ self.pipeline = pipeline("feature-extraction", model=path)
16
+ self.tokenizer = AutoTokenizer.from_pretrained(path)
17
+ self.model = AutoModel.from_pretrained(path)
18
+
19
+ def __call__(self, data: Dict[str, Any]) -> List[Dict[str, Any]]:
20
+ """
21
+ data args:
22
+ inputs (:obj: `List[str]`)
23
+ Return:
24
+ A :obj:`List[List[int]]`: will be serialized and returned
25
+ """
26
+ # get inputs
27
+ inputs = data.pop("inputs",data)
28
+
29
+ batch_dict = self.tokenizer(inputs, max_length=512, padding=True, truncation=True, return_tensors='pt')
30
+
31
+ outputs = self.model(**batch_dict)
32
+
33
+ embeddings = average_pool(outputs.last_hidden_state, batch_dict['attention_mask'])
34
+
35
+ return embeddings