pyserver.py 8.6 KB
Newer Older
B
barrierye 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# pylint: disable=doc-string-missing
import threading
import multiprocessing
B
barrierye 已提交
17
import Queue
B
barrierye 已提交
18 19 20 21
import os
import paddle_serving_server
from paddle_serving_client import Client
from concurrent import futures
B
barrierye 已提交
22
import numpy
B
barrierye 已提交
23 24 25
import grpc
import general_python_service_pb2
import general_python_service_pb2_grpc
B
barrierye 已提交
26
import python_service_channel_pb2
B
barrierye 已提交
27 28


B
barrierye 已提交
29
class Channel(Queue.Queue):
B
barrierye 已提交
30
    def __init__(self, consumer=1, maxsize=-1, timeout=None, batchsize=1):
B
barrierye 已提交
31 32
        Queue.Queue.__init__(self, maxsize=maxsize)
        # super(Channel, self).__init__(maxsize=maxsize)
B
barrierye 已提交
33 34 35 36 37 38 39 40 41 42 43 44
        self._maxsize = maxsize
        self._timeout = timeout
        self._batchsize = batchsize
        self._consumer = consumer
        self._pushlock = threading.Lock()
        self._frontlock = threading.Lock()
        self._pushbatch = []
        self._frontbatch = None
        self._count = 0

    def push(self, item):
        with self._pushlock:
B
barrierye 已提交
45 46
            self._pushbatch.append(item)
            if len(self._pushbatch) == self._batchsize:
B
barrierye 已提交
47
                self.put(self._pushbatch, timeout=self._timeout)
B
barrierye 已提交
48
                # self.put(self._pushbatch)
B
barrierye 已提交
49 50 51
                self._pushbatch = []

    def front(self):
B
barrierye 已提交
52
        if self._consumer == 1:
B
barrierye 已提交
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
            return self.get(timeout=self._timeout)
        with self._frontlock:
            if self._count == 0:
                self._frontbatch = self.get(timeout=self._timeout)
            self._count += 1
            if self._count == self._consumer:
                self._count = 0
            return self._frontbatch


class Op(object):
    def __init__(self,
                 inputs,
                 outputs,
                 server_model=None,
                 server_port=None,
                 device=None,
                 client_config=None,
                 server_name=None,
                 fetch_names=None):
        self._run = False
        self.set_inputs(inputs)
        self.set_outputs(outputs)
B
barrierye 已提交
76
        self._client = None
B
barrierye 已提交
77 78 79 80 81 82
        if client_config is not None and \
                server_name is not None and \
                fetch_names is not None:
            self.set_client(client_config, server_name, fetch_names)
        self._server_model = server_model
        self._server_port = server_port
B
barrierye 已提交
83
        self._device = device
B
barrierye 已提交
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

    def set_client(self, client_config, server_name, fetch_names):
        self._client = Client()
        self._client.load_client_config(client_config)
        self._client.connect([server_name])
        self._fetch_names = fetch_names

    def with_serving(self):
        return self._client is not None

    def get_inputs(self):
        return self._inputs

    def set_inputs(self, channels):
        if not isinstance(channels, list):
            raise TypeError('channels must be list type')
        self._inputs = channels

    def get_outputs(self):
        return self._outputs

    def set_outputs(self, channels):
        if not isinstance(channels, list):
            raise TypeError('channels must be list type')
        self._outputs = channels

    def preprocess(self, input_data):
        return input_data

    def midprocess(self, data):
B
barrierye 已提交
114
        # data = preprocess(input), which must be a dict
B
barrierye 已提交
115 116
        print('data: {}'.format(data))
        print('fetch: {}'.format(self._fetch_names))
B
barrierye 已提交
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
        fetch_map = self._client.predict(feed=data, fetch=self._fetch_names)
        return fetch_map

    def postprocess(self, output_data):
        return output_data

    def stop(self):
        self._run = False

    def start(self):
        self._run = True
        while self._run:
            input_data = []
            for channel in self._inputs:
                input_data.append(channel.front())
B
barrierye 已提交
132 133 134 135
            if len(input_data) > 1:
                data = self.preprocess(input_data)
            else:
                data = self.preprocess(input_data[0])
B
barrierye 已提交
136 137 138 139 140 141 142 143 144 145 146 147 148

            if self.with_serving():
                fetch_map = self.midprocess(data)
                output_data = self.postprocess(fetch_map)
            else:
                output_data = self.postprocess(data)

            for channel in self._outputs:
                channel.push(output_data)


class GeneralPythonService(
        general_python_service_pb2_grpc.GeneralPythonService):
B
barrierye 已提交
149
    def __init__(self, in_channel, out_channel):
B
barrierye 已提交
150
        super(GeneralPythonService, self).__init__()
B
barrierye 已提交
151 152
        self._in_channel = in_channel
        self._out_channel = out_channel
B
barrierye 已提交
153
        print('succ init')
B
barrierye 已提交
154

B
barrierye 已提交
155
    def inference(self, request, context):
B
barrierye 已提交
156
        print('start inferce')
B
barrierye 已提交
157
        data = python_service_channel_pb2.ChannelData()
B
barrierye 已提交
158
        print('gen data: {}'.format(data))
B
barrierye 已提交
159
        for idx, name in enumerate(request.feed_var_names):
B
barrierye 已提交
160 161
            print('name: {}'.format(request.feed_var_names[idx]))
            print('data: {}'.format(request.feed_insts[idx]))
B
barrierye 已提交
162
            inst = python_service_channel_pb2.Inst()
B
barrierye 已提交
163
            inst.data = request.feed_insts[idx]
B
barrierye 已提交
164 165 166
            inst.name = name
            inst.id = 0  #TODO
            data.insts.append(inst)
B
barrierye 已提交
167
        print('push data')
B
barrierye 已提交
168
        self._in_channel.push(data)
B
barrierye 已提交
169
        print('wait for infer')
B
barrierye 已提交
170
        data = self._out_channel.front()
B
barrierye 已提交
171 172
        data = data[0]  #TODO batchsize = 1
        print('get data')
B
barrierye 已提交
173
        resp = general_python_service_pb2.Response()
B
barrierye 已提交
174 175
        print('gen resp')
        print(data)
B
barrierye 已提交
176
        for inst in data.insts:
B
barrierye 已提交
177 178 179
            print('append data')
            resp.fetch_insts.append(inst.data)
            print('append name')
B
barrierye 已提交
180 181
            resp.fetch_var_names.append(inst.name)
        return resp
B
barrierye 已提交
182 183 184 185 186 187 188 189 190


class PyServer(object):
    def __init__(self):
        self._channels = []
        self._ops = []
        self._op_threads = []
        self._port = None
        self._worker_num = None
B
barrierye 已提交
191 192
        self._in_channel = None
        self._out_channel = None
B
barrierye 已提交
193 194 195 196 197

    def add_channel(self, channel):
        self._channels.append(channel)

    def add_op(self, op):
B
barrierye 已提交
198
        self._ops.append(op)
B
barrierye 已提交
199 200

    def gen_desc(self):
B
barrierye 已提交
201
        print('here will generate desc for paas')
B
barrierye 已提交
202 203 204 205 206
        pass

    def prepare_server(self, port, worker_num):
        self._port = port
        self._worker_num = worker_num
B
barrierye 已提交
207 208
        inputs = set()
        outputs = set()
B
barrierye 已提交
209
        for op in self._ops:
B
barrierye 已提交
210 211
            inputs |= set(op.get_inputs())
            outputs |= set(op.get_outputs())
B
barrierye 已提交
212 213
            if op.with_serving():
                self.prepare_serving(op)
B
barrierye 已提交
214 215 216 217 218 219 220 221 222 223
        in_channel = inputs - outputs
        out_channel = outputs - inputs
        if len(in_channel) != 1 or len(out_channel) != 1:
            raise Exception(
                "in_channel(out_channel) more than 1 or no in_channel(out_channel)"
            )
        self._in_channel = in_channel.pop()
        self._out_channel = out_channel.pop()
        self.gen_desc()

B
barrierye 已提交
224 225 226
    def op_start_wrapper(self, op):
        return op.start()

B
barrierye 已提交
227 228
    def run_server(self):
        for op in self._ops:
B
barrierye 已提交
229 230
            # th = multiprocessing.Process(target=self.op_start_wrapper, args=(op, ))
            th = threading.Thread(target=self.op_start_wrapper, args=(op, ))
B
barrierye 已提交
231 232 233 234
            th.start()
            self._op_threads.append(th)
        server = grpc.server(
            futures.ThreadPoolExecutor(max_workers=self._worker_num))
B
barrierye 已提交
235
        general_python_service_pb2_grpc.add_GeneralPythonServiceServicer_to_server(
B
barrierye 已提交
236
            GeneralPythonService(self._in_channel, self._out_channel), server)
B
barrierye 已提交
237
        server.add_insecure_port('[::]:{}'.format(self._port))
B
barrierye 已提交
238 239 240 241
        server.start()
        try:
            for th in self._op_threads:
                th.join()
B
barrierye 已提交
242
            server.join()
B
barrierye 已提交
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
        except KeyboardInterrupt:
            server.stop(0)

    def prepare_serving(self, op):
        model_path = op._server_model
        port = op._server_port
        device = op._device

        # run a server (not in PyServing)
        if device == "cpu":
            cmd = "python -m paddle_serving_server.serve --model {} --thread 4 --port {} &>/dev/null &".format(
                model_path, port)
        else:
            cmd = "python -m paddle_serving_server_gpu.serve --model {} --thread 4 --port {} &>/dev/null &".format(
                model_path, port)
B
barrierye 已提交
258 259
        print(cmd)
        return
B
barrierye 已提交
260
        os.system(cmd)