operator.py 20.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#   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
D
dongdaxiang 已提交
15

16 17 18 19 20 21
import threading
import multiprocessing
from paddle_serving_client import MultiLangClient, Client
from concurrent import futures
import logging
import func_timeout
22
import os
B
barrierye 已提交
23
import sys
B
barrierye 已提交
24
from numpy import *
25

B
barrierye 已提交
26
from .proto import pipeline_service_pb2
27
from .channel import ThreadChannel, ProcessChannel, ChannelDataEcode, ChannelData, ChannelDataType
B
barrierye 已提交
28
from .util import NameGenerator
B
barrierye 已提交
29
from .profiler import TimeProfiler
30

W
wangjiawei04 已提交
31
_LOGGER = logging.getLogger()
B
barrierye 已提交
32 33
_op_name_gen = NameGenerator("Op")

D
dongdaxiang 已提交
34 35 36

class Op(object):
    def __init__(self,
B
barrierye 已提交
37
                 name=None,
D
dongdaxiang 已提交
38 39
                 input_ops=[],
                 server_endpoints=[],
B
barrierye 已提交
40 41
                 fetch_list=[],
                 client_config=None,
D
dongdaxiang 已提交
42 43 44
                 concurrency=1,
                 timeout=-1,
                 retry=1):
B
barrierye 已提交
45
        if name is None:
B
barrierye 已提交
46
            name = _op_name_gen.next()
47 48
        self._is_run = False
        self.name = name  # to identify the type of OP, it must be globally unique
B
barrierye 已提交
49
        self.concurrency = concurrency  # amount of concurrency
B
barrierye 已提交
50
        self.set_input_ops(input_ops)
B
barrierye 已提交
51 52

        self._server_endpoints = server_endpoints
53
        self.with_serving = False
B
barrierye 已提交
54
        if len(self._server_endpoints) != 0:
55
            self.with_serving = True
B
barrierye 已提交
56 57 58
        self._client_config = client_config
        self._fetch_names = fetch_list

59 60 61 62
        self._timeout = timeout
        self._retry = max(1, retry)
        self._input = None
        self._outputs = []
B
barrierye 已提交
63 64

        self._use_profile = False
65

B
barrierye 已提交
66 67 68 69
        # only for multithread
        self._for_init_op_lock = threading.Lock()
        self._succ_init_op = False

B
barrierye 已提交
70
    def use_profiler(self, use_profile):
B
barrierye 已提交
71
        self._use_profile = use_profile
72 73 74 75 76 77

    def _profiler_record(self, string):
        if self._profiler is None:
            return
        self._profiler.record(string)

B
barrierye 已提交
78 79
    def init_client(self, client_type, client_config, server_endpoints,
                    fetch_names):
80
        if self.with_serving == False:
B
barrierye 已提交
81
            _LOGGER.debug("{} no client".format(self.name))
B
barrierye 已提交
82
            return None
B
barrierye 已提交
83 84
        _LOGGER.debug("{} client_config: {}".format(self.name, client_config))
        _LOGGER.debug("{} fetch_names: {}".format(self.name, fetch_names))
85
        if client_type == 'brpc':
B
barrierye 已提交
86 87
            client = Client()
            client.load_client_config(client_config)
88
        elif client_type == 'grpc':
B
barrierye 已提交
89
            client = MultiLangClient()
90 91
        else:
            raise ValueError("unknow client type: {}".format(client_type))
B
barrierye 已提交
92
        client.connect(server_endpoints)
93
        self._fetch_names = fetch_names
B
barrierye 已提交
94
        return client
95

B
barrierye 已提交
96
    def _get_input_channel(self):
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
        return self._input

    def get_input_ops(self):
        return self._input_ops

    def set_input_ops(self, ops):
        if not isinstance(ops, list):
            ops = [] if ops is None else [ops]
        self._input_ops = []
        for op in ops:
            if not isinstance(op, Op):
                raise TypeError(
                    self._log('input op must be Op type, not {}'.format(
                        type(op))))
            self._input_ops.append(op)
D
dongdaxiang 已提交
112

113 114 115 116 117 118 119
    def add_input_channel(self, channel):
        if not isinstance(channel, (ThreadChannel, ProcessChannel)):
            raise TypeError(
                self._log('input channel must be Channel type, not {}'.format(
                    type(channel))))
        channel.add_consumer(self.name)
        self._input = channel
D
dongdaxiang 已提交
120

B
barrierye 已提交
121
    def _get_output_channels(self):
122
        return self._outputs
D
dongdaxiang 已提交
123

124 125 126 127 128 129 130
    def add_output_channel(self, channel):
        if not isinstance(channel, (ThreadChannel, ProcessChannel)):
            raise TypeError(
                self._log('output channel must be Channel type, not {}'.format(
                    type(channel))))
        channel.add_producer(self.name)
        self._outputs.append(channel)
D
dongdaxiang 已提交
131

W
wangjiawei04 已提交
132
    def preprocess(self, input_dicts):
B
barrierye 已提交
133
        # multiple previous Op
B
barrierye 已提交
134
        if len(input_dicts) != 1:
135
            raise NotImplementedError(
B
barrierye 已提交
136
                'this Op has multiple previous inputs. Please override this func.'
137
            )
D
dongdaxiang 已提交
138

B
barrierye 已提交
139 140
        (_, input_dict), = input_dicts.items()
        return input_dict
B
barrierye 已提交
141

W
wangjiawei04 已提交
142
    def process(self, client_predict_handler, feed_dict):
B
barrierye 已提交
143 144 145 146
        err, err_info = ChannelData.check_npdata(feed_dict)
        if err != 0:
            raise NotImplementedError(
                "{} Please override preprocess func.".format(err_info))
B
barrierye 已提交
147
        call_result = client_predict_handler(
B
barrierye 已提交
148 149
            feed=feed_dict, fetch=self._fetch_names)
        _LOGGER.debug(self._log("get call_result"))
150 151
        return call_result

W
wangjiawei04 已提交
152
    def postprocess(self, input_dict, fetch_dict):
B
barrierye 已提交
153
        return fetch_dict
D
dongdaxiang 已提交
154 155

    def stop(self):
156 157
        self._is_run = False

B
barrierye 已提交
158
    def _parse_channeldata(self, channeldata_dict):
159
        data_id, error_channeldata = None, None
B
barrierye 已提交
160 161 162 163 164 165 166 167 168 169 170
        parsed_data = {}

        key = list(channeldata_dict.keys())[0]
        data_id = channeldata_dict[key].id

        for name, data in channeldata_dict.items():
            if data.ecode != ChannelDataEcode.OK.value:
                error_channeldata = data
                break
            parsed_data[name] = data.parse()
        return data_id, error_channeldata, parsed_data
171 172 173 174 175 176 177

    def _push_to_output_channels(self, data, channels, name=None):
        if name is None:
            name = self.name
        for channel in channels:
            channel.push(data, name)

B
barrierye 已提交
178
    def start_with_process(self, client_type):
179
        proces = []
B
barrierye 已提交
180
        for concurrency_idx in range(self.concurrency):
181 182
            p = multiprocessing.Process(
                target=self._run,
B
barrierye 已提交
183
                args=(concurrency_idx, self._get_input_channel(),
184
                      self._get_output_channels(), client_type, False))
185 186 187 188
            p.start()
            proces.append(p)
        return proces

B
barrierye 已提交
189
    def start_with_thread(self, client_type):
190
        threads = []
B
barrierye 已提交
191
        for concurrency_idx in range(self.concurrency):
192 193
            t = threading.Thread(
                target=self._run,
B
barrierye 已提交
194
                args=(concurrency_idx, self._get_input_channel(),
195
                      self._get_output_channels(), client_type, True))
196 197 198 199
            t.start()
            threads.append(t)
        return threads

B
barrierye 已提交
200
    def init_op(self):
B
barrierye 已提交
201 202
        pass

W
wangjiawei04 已提交
203
    def _run_preprocess(self, parsed_data, data_id, log_func):
204 205
        preped_data, error_channeldata = None, None
        try:
W
wangjiawei04 已提交
206
            preped_data = self.preprocess(parsed_data)
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
        except NotImplementedError as e:
            # preprocess function not implemented
            error_info = log_func(e)
            _LOGGER.error(error_info)
            error_channeldata = ChannelData(
                ecode=ChannelDataEcode.NOT_IMPLEMENTED.value,
                error_info=error_info,
                data_id=data_id)
        except TypeError as e:
            # Error type in channeldata.datatype
            error_info = log_func(e)
            _LOGGER.error(error_info)
            error_channeldata = ChannelData(
                ecode=ChannelDataEcode.TYPE_ERROR.value,
                error_info=error_info,
                data_id=data_id)
        except Exception as e:
            error_info = log_func(e)
            _LOGGER.error(error_info)
            error_channeldata = ChannelData(
                ecode=ChannelDataEcode.UNKNOW.value,
                error_info=error_info,
                data_id=data_id)
        return preped_data, error_channeldata

B
barrierye 已提交
232
    def _run_process(self, client_predict_handler, preped_data, data_id,
W
wangjiawei04 已提交
233
                     log_func):
234 235 236 237 238
        midped_data, error_channeldata = None, None
        if self.with_serving:
            ecode = ChannelDataEcode.OK.value
            if self._timeout <= 0:
                try:
B
barrierye 已提交
239
                    midped_data = self.process(client_predict_handler,
W
wangjiawei04 已提交
240
                                               preped_data)
241 242 243 244 245 246 247 248
                except Exception as e:
                    ecode = ChannelDataEcode.UNKNOW.value
                    error_info = log_func(e)
                    _LOGGER.error(error_info)
            else:
                for i in range(self._retry):
                    try:
                        midped_data = func_timeout.func_timeout(
B
barrierye 已提交
249 250
                            self._timeout,
                            self.process,
W
wangjiawei04 已提交
251
                            args=(client_predict_handler, preped_data))
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
                    except func_timeout.FunctionTimedOut as e:
                        if i + 1 >= self._retry:
                            ecode = ChannelDataEcode.TIMEOUT.value
                            error_info = log_func(e)
                            _LOGGER.error(error_info)
                        else:
                            _LOGGER.warn(
                                log_func("timeout, retry({})".format(i + 1)))
                    except Exception as e:
                        ecode = ChannelDataEcode.UNKNOW.value
                        error_info = log_func(e)
                        _LOGGER.error(error_info)
                        break
                    else:
                        break
            if ecode != ChannelDataEcode.OK.value:
                error_channeldata = ChannelData(
                    ecode=ecode, error_info=error_info, data_id=data_id)
            elif midped_data is None:
                # op client return None
                error_channeldata = ChannelData(
                    ecode=ChannelDataEcode.CLIENT_ERROR.value,
                    error_info=log_func(
                        "predict failed. pls check the server side."),
                    data_id=data_id)
        else:
            midped_data = preped_data
        return midped_data, error_channeldata

W
wangjiawei04 已提交
281
    def _run_postprocess(self, input_dict, midped_data, data_id, log_func):
282 283
        output_data, error_channeldata = None, None
        try:
W
wangjiawei04 已提交
284
            postped_data = self.postprocess(input_dict, midped_data)
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
        except Exception as e:
            error_info = log_func(e)
            _LOGGER.error(error_info)
            error_channeldata = ChannelData(
                ecode=ChannelDataEcode.UNKNOW.value,
                error_info=error_info,
                data_id=data_id)
            return output_data, error_channeldata

        if not isinstance(postped_data, dict):
            error_info = log_func("output of postprocess funticon must be " \
                    "dict type, but get {}".format(type(postped_data)))
            _LOGGER.error(error_info)
            error_channeldata = ChannelData(
                ecode=ChannelDataEcode.UNKNOW.value,
                error_info=error_info,
                data_id=data_id)
            return output_data, error_channeldata

        err, _ = ChannelData.check_npdata(postped_data)
        if err == 0:
            output_data = ChannelData(
                ChannelDataType.CHANNEL_NPDATA.value,
                npdata=postped_data,
                data_id=data_id)
        else:
            output_data = ChannelData(
                ChannelDataType.DICT.value,
                dictdata=postped_data,
                data_id=data_id)
        return output_data, error_channeldata

317 318
    def _run(self, concurrency_idx, input_channel, output_channels, client_type,
             use_multithread):
B
barrierye 已提交
319 320 321 322 323 324
        def get_log_func(op_info_prefix):
            def log_func(info_str):
                return "{} {}".format(op_info_prefix, info_str)

            return log_func

325
        op_info_prefix = "[{}|{}]".format(self.name, concurrency_idx)
B
barrierye 已提交
326
        log = get_log_func(op_info_prefix)
B
barrierye 已提交
327
        tid = threading.current_thread().ident
B
barrierye 已提交
328

329
        client = None
B
barrierye 已提交
330
        client_predict_handler = None
B
barrierye 已提交
331
        # create client based on client_type
332
        try:
333 334 335 336
            client = self.init_client(client_type, self._client_config,
                                      self._server_endpoints, self._fetch_names)
            if client is not None:
                client_predict_handler = client.predict
337 338 339
        except Exception as e:
            _LOGGER.error(log(e))
            os._exit(-1)
B
barrierye 已提交
340

B
barrierye 已提交
341
        # init op
342
        self.concurrency_idx = concurrency_idx
B
barrierye 已提交
343 344 345 346
        try:
            if use_multithread:
                with self._for_init_op_lock:
                    if not self._succ_init_op:
347
                        self.init_op()
B
barrierye 已提交
348 349
                        self._succ_init_op = True
            else:
350
                self.init_op()
B
barrierye 已提交
351 352 353
        except Exception as e:
            _LOGGER.error(log(e))
            os._exit(-1)
354

B
barrierye 已提交
355
        # init profiler
B
barrierye 已提交
356 357
        self._profiler = TimeProfiler()
        self._profiler.enable(self._use_profile)
B
barrierye 已提交
358

B
barrierye 已提交
359
        self._is_run = True
360
        while self._is_run:
B
barrierye 已提交
361
            #self._profiler_record("get#{}_0".format(op_info_prefix))
B
barrierye 已提交
362
            channeldata_dict = input_channel.front(self.name)
B
barrierye 已提交
363
            #self._profiler_record("get#{}_1".format(op_info_prefix))
B
barrierye 已提交
364
            _LOGGER.debug(log("input_data: {}".format(channeldata_dict)))
365

B
barrierye 已提交
366 367
            data_id, error_channeldata, parsed_data = self._parse_channeldata(
                channeldata_dict)
368 369 370 371 372 373 374
            # error data in predecessor Op
            if error_channeldata is not None:
                self._push_to_output_channels(error_channeldata,
                                              output_channels)
                continue

            # preprecess
B
barrierye 已提交
375
            self._profiler_record("prep#{}_0".format(op_info_prefix))
W
wangjiawei04 已提交
376 377
            preped_data, error_channeldata = self._run_preprocess(parsed_data,
                                                                  data_id, log)
B
barrierye 已提交
378
            self._profiler_record("prep#{}_1".format(op_info_prefix))
379 380 381
            if error_channeldata is not None:
                self._push_to_output_channels(error_channeldata,
                                              output_channels)
382 383
                continue

B
barrierye 已提交
384
            # process
B
barrierye 已提交
385
            self._profiler_record("midp#{}_0".format(op_info_prefix))
B
barrierye 已提交
386
            midped_data, error_channeldata = self._run_process(
W
wangjiawei04 已提交
387
                client_predict_handler, preped_data, data_id, log)
B
barrierye 已提交
388
            self._profiler_record("midp#{}_1".format(op_info_prefix))
389 390 391 392
            if error_channeldata is not None:
                self._push_to_output_channels(error_channeldata,
                                              output_channels)
                continue
393 394

            # postprocess
B
barrierye 已提交
395
            self._profiler_record("postp#{}_0".format(op_info_prefix))
W
wangjiawei04 已提交
396
            output_data, error_channeldata = self._run_postprocess(
W
wangjiawei04 已提交
397
                parsed_data, midped_data, data_id, log)
B
barrierye 已提交
398
            self._profiler_record("postp#{}_1".format(op_info_prefix))
399 400 401 402
            if error_channeldata is not None:
                self._push_to_output_channels(error_channeldata,
                                              output_channels)
                continue
403

B
barrierye 已提交
404 405 406 407 408 409
            if self._use_profile:
                profile_str = self._profiler.gen_profile_str()
                sys.stderr.write(profile_str)
                #TODO
                #output_data.add_profile(profile_str)

410
            # push data to channel (if run succ)
B
barrierye 已提交
411
            #self._profiler_record("push#{}_0".format(op_info_prefix))
412
            self._push_to_output_channels(output_data, output_channels)
B
barrierye 已提交
413
            #self._profiler_record("push#{}_1".format(op_info_prefix))
B
barrierye 已提交
414
            #self._profiler.print_profile()
415 416 417 418 419

    def _log(self, info):
        return "{} {}".format(self.name, info)


B
barrierye 已提交
420 421 422
class RequestOp(Op):
    """ RequestOp do not run preprocess, process, postprocess. """

B
barrierye 已提交
423
    def __init__(self, concurrency=1):
B
barrierye 已提交
424
        # PipelineService.name = "@G"
B
barrierye 已提交
425
        super(RequestOp, self).__init__(
B
barrierye 已提交
426
            name="@G", input_ops=[], concurrency=concurrency)
B
barrierye 已提交
427
        # init op
428
        try:
429
            self.init_op()
430
        except Exception as e:
B
bug fix  
barrierye 已提交
431
            _LOGGER.error(e)
432
            os._exit(-1)
B
barrierye 已提交
433 434 435 436

    def unpack_request_package(self, request):
        dictdata = {}
        for idx, key in enumerate(request.key):
B
barrierye 已提交
437 438 439 440 441 442
            data = request.value[idx]
            try:
                data = eval(data)
            except Exception as e:
                pass
            dictdata[key] = data
B
barrierye 已提交
443 444 445 446 447 448 449 450
        return dictdata


class ResponseOp(Op):
    """ ResponseOp do not run preprocess, process, postprocess. """

    def __init__(self, input_ops, concurrency=1):
        super(ResponseOp, self).__init__(
B
barrierye 已提交
451
            name="@R", input_ops=input_ops, concurrency=concurrency)
B
barrierye 已提交
452
        # init op
453
        try:
454
            self.init_op()
455
        except Exception as e:
B
bug fix  
barrierye 已提交
456
            _LOGGER.error(e)
457
            os._exit(-1)
B
barrierye 已提交
458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488

    def pack_response_package(self, channeldata):
        resp = pipeline_service_pb2.Response()
        resp.ecode = channeldata.ecode
        if resp.ecode == ChannelDataEcode.OK.value:
            if channeldata.datatype == ChannelDataType.CHANNEL_NPDATA.value:
                feed = channeldata.parse()
                # ndarray to string:
                # https://stackoverflow.com/questions/30167538/convert-a-numpy-ndarray-to-stringor-bytes-and-convert-it-back-to-numpy-ndarray
                for name, var in feed.items():
                    resp.value.append(var.__repr__())
                    resp.key.append(name)
            elif channeldata.datatype == ChannelDataType.DICT.value:
                feed = channeldata.parse()
                for name, var in feed.items():
                    if not isinstance(var, str):
                        resp.ecode = ChannelDataEcode.TYPE_ERROR.value
                        resp.error_info = self._log(
                            "fetch var type must be str({}).".format(
                                type(var)))
                        break
                    resp.value.append(var)
                    resp.key.append(name)
            else:
                resp.ecode = ChannelDataEcode.TYPE_ERROR.value
                resp.error_info = self._log(
                    "Error type({}) in datatype.".format(channeldata.datatype))
                _LOGGER.error(resp.error_info)
        else:
            resp.error_info = channeldata.error_info
        return resp
489 490 491 492 493 494 495


class VirtualOp(Op):
    ''' For connecting two channels. '''

    def __init__(self, name, concurrency=1):
        super(VirtualOp, self).__init__(
B
barrierye 已提交
496
            name=name, input_ops=None, concurrency=concurrency)
497 498 499 500 501
        self._virtual_pred_ops = []

    def add_virtual_pred_op(self, op):
        self._virtual_pred_ops.append(op)

B
barrierye 已提交
502 503 504 505 506 507 508 509
    def _actual_pred_op_names(self, op):
        if not isinstance(op, VirtualOp):
            return [op.name]
        names = []
        for x in op._virtual_pred_ops:
            names.extend(self._actual_pred_op_names(x))
        return names

510 511 512 513 514 515
    def add_output_channel(self, channel):
        if not isinstance(channel, (ThreadChannel, ProcessChannel)):
            raise TypeError(
                self._log('output channel must be Channel type, not {}'.format(
                    type(channel))))
        for op in self._virtual_pred_ops:
B
barrierye 已提交
516 517
            for op_name in self._actual_pred_op_names(op):
                channel.add_producer(op_name)
518
        self._outputs.append(channel)
D
dongdaxiang 已提交
519

520 521
    def _run(self, concurrency_idx, input_channel, output_channels, client_type,
             use_multithread):
B
barrierye 已提交
522 523 524 525 526 527
        def get_log_func(op_info_prefix):
            def log_func(info_str):
                return "{} {}".format(op_info_prefix, info_str)

            return log_func

528
        op_info_prefix = "[{}|{}]".format(self.name, concurrency_idx)
B
barrierye 已提交
529 530 531
        log = get_log_func(op_info_prefix)
        tid = threading.current_thread().ident

532 533
        self._is_run = True
        while self._is_run:
B
barrierye 已提交
534
            #self._profiler_record("get#{}_0".format(op_info_prefix))
B
barrierye 已提交
535
            channeldata_dict = input_channel.front(self.name)
B
barrierye 已提交
536
            #self._profiler_record("get#{}_1".format(op_info_prefix))
D
dongdaxiang 已提交
537

B
barrierye 已提交
538
            #self._profiler_record("push#{}_0".format(op_info_prefix))
B
barrierye 已提交
539
            for name, data in channeldata_dict.items():
540
                self._push_to_output_channels(
B
barrierye 已提交
541
                    data, channels=output_channels, name=name)
B
barrierye 已提交
542
            #self._profiler_record("push#{}_1".format(op_info_prefix))