jed-tiotuico commited on
Commit
6d95be4
·
1 Parent(s): 502e8ec

added handler

Browse files
Files changed (1) hide show
  1. handler.py +73 -0
handler.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, List, Any
2
+ from transformers import pipeline, AutoTokenizer
3
+ import torch
4
+ import torch.nn as nn
5
+ from huggingface_hub import PyTorchModelHubMixin
6
+
7
+ embedding_dim = 128
8
+ rnn_units = 256
9
+ vocab_size = 8000
10
+
11
+
12
+ def get_model():
13
+ class AurelioRNN(nn.Module, PyTorchModelHubMixin):
14
+ def __init__(self, config: dict):
15
+ super().__init__()
16
+ vocab_size = config.get("vocab_size")
17
+ embedding_dim = config.get("embedding_dim")
18
+ rnn_units = config.get("rnn_units")
19
+ self.embedding = nn.Embedding(vocab_size, embedding_dim)
20
+ self.lstm = nn.LSTM(embedding_dim, rnn_units, batch_first=True)
21
+ self.fc = nn.Linear(rnn_units, vocab_size)
22
+
23
+ def forward(self, x, state):
24
+ x = self.embedding(x)
25
+ x, state = self.lstm(x, state)
26
+ x = self.fc(x)
27
+ return x, state
28
+
29
+ def init_state(self, batch_size):
30
+ return (
31
+ torch.zeros(1, batch_size, rnn_units).to("cpu"),
32
+ torch.zeros(1, batch_size, rnn_units).to("cpu"),
33
+ )
34
+
35
+ return AurelioRNN
36
+
37
+
38
+ class EndpointHandler:
39
+ def __init__(self, path=""):
40
+ # load the optimized model
41
+ config = {
42
+ "vocab_size": vocab_size,
43
+ "embedding_dim": embedding_dim,
44
+ "rnn_units": rnn_units,
45
+ }
46
+ lstm = get_model()
47
+ model = lstm.from_pretrained("jed-tiotuico/aurelio-rnn", config=config)
48
+ tokenizer = AutoTokenizer.from_pretrained(path)
49
+ # create inference pipeline
50
+ self.pipeline = pipeline(
51
+ "text-classification", model=model, tokenizer=tokenizer
52
+ )
53
+
54
+ def __call__(self, data: Any) -> List[List[Dict[str, float]]]:
55
+ """
56
+ Args:
57
+ data (:obj:):
58
+ includes the input data and the parameters for the inference.
59
+ Return:
60
+ A :obj:`list`:. The object returned should be a list of one list like [[{"label": 0.9939950108528137}]] containing :
61
+ - "label": A string representing what the label/class is. There can be multiple labels.
62
+ - "score": A score between 0 and 1 describing how confident the model is for this label/class.
63
+ """
64
+ inputs = data.pop("inputs", data)
65
+ parameters = data.pop("parameters", None)
66
+
67
+ # pass inputs with all kwargs in data
68
+ if parameters is not None:
69
+ prediction = self.pipeline(inputs, **parameters)
70
+ else:
71
+ prediction = self.pipeline(inputs)
72
+ # postprocess the prediction
73
+ return prediction