operator.py 60.9 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
B
barriery 已提交
15
from time import time as _time
B
barriery 已提交
16
import time
17 18 19 20 21 22
import threading
import multiprocessing
from paddle_serving_client import MultiLangClient, Client
from concurrent import futures
import logging
import func_timeout
23
import os
B
barrierye 已提交
24
import sys
25
import collections
B
barrierye 已提交
26
import numpy as np
T
TeslaZhao 已提交
27
import json
B
barrierye 已提交
28
from numpy import *
B
barrierye 已提交
29 30 31 32 33 34
if sys.version_info.major == 2:
    import Queue
elif sys.version_info.major == 3:
    import queue as Queue
else:
    raise Exception("Error Python version")
35

B
barrierye 已提交
36
from .proto import pipeline_service_pb2
T
TeslaZhao 已提交
37
from .channel import (ThreadChannel, ProcessChannel, ChannelDataErrcode,
B
bug fix  
barriery 已提交
38
                      ChannelData, ChannelDataType, ChannelStopError,
T
TeslaZhao 已提交
39
                      ChannelTimeoutError, ProductErrCode)
B
barrierye 已提交
40
from .util import NameGenerator
B
barriery 已提交
41
from .profiler import UnsafeTimeProfiler as TimeProfiler
W
wangjiawei04 已提交
42
from . import local_service_handler
43

44
_LOGGER = logging.getLogger(__name__)
B
barrierye 已提交
45 46
_op_name_gen = NameGenerator("Op")

D
dongdaxiang 已提交
47 48 49

class Op(object):
    def __init__(self,
B
barrierye 已提交
50
                 name=None,
D
dongdaxiang 已提交
51
                 input_ops=[],
B
barriery 已提交
52 53
                 server_endpoints=None,
                 fetch_list=None,
B
barrierye 已提交
54
                 client_config=None,
W
wangjiawei04 已提交
55
                 client_type=None,
B
barriery 已提交
56 57
                 concurrency=None,
                 timeout=None,
T
TeslaZhao 已提交
58
                 retry=0,
B
barriery 已提交
59
                 batch_size=None,
60
                 auto_batching_timeout=None,
W
wangjiawei04 已提交
61
                 local_service_handler=None):
B
barriery 已提交
62
        # In __init__, all the parameters are just saved and Op is not initialized
B
barrierye 已提交
63
        if name is None:
B
barrierye 已提交
64
            name = _op_name_gen.next()
65
        self.name = name  # to identify the type of OP, it must be globally unique
B
barrierye 已提交
66
        self.concurrency = concurrency  # amount of concurrency
B
barrierye 已提交
67
        self.set_input_ops(input_ops)
B
barrierye 已提交
68

W
wangjiawei04 已提交
69
        self._local_service_handler = local_service_handler
B
barriery 已提交
70
        self._server_endpoints = server_endpoints
B
barrierye 已提交
71
        self._fetch_names = fetch_list
B
barriery 已提交
72
        self._client_config = client_config
W
wangjiawei04 已提交
73
        self.client_type = client_type
B
barriery 已提交
74
        self._timeout = timeout
75
        self._retry = max(1, retry)
B
barriery 已提交
76 77 78
        self._batch_size = batch_size
        self._auto_batching_timeout = auto_batching_timeout

79 80
        self._input = None
        self._outputs = []
B
barrierye 已提交
81

B
barriery 已提交
82 83 84 85 86 87 88 89 90
        self._server_use_profile = False
        self._tracer = None

        # only for thread op
        self._for_init_op_lock = threading.Lock()
        self._for_close_op_lock = threading.Lock()
        self._succ_init_op = False
        self._succ_close_op = False

B
barriery 已提交
91
    def init_from_dict(self, conf):
92 93 94 95 96 97 98 99 100 101 102 103
        """
        Initializing one Op from config.yaml. If server_endpoints exist,
        which is remote RPC mode, otherwise it is local RPC mode. There
        are three types of predictios in local RPC mode, brpc, grpc and
        local_predictor.

        Args:
            conf: config.yaml

        Returns:
            None
        """
B
barriery 已提交
104
        # init op
B
barriery 已提交
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
        if self.concurrency is None:
            self.concurrency = conf["concurrency"]
        if self._retry is None:
            self._retry = conf["retry"]
        if self._fetch_names is None:
            self._fetch_names = conf.get("fetch_list")
        if self._client_config is None:
            self._client_config = conf.get("client_config")

        if self._timeout is None:
            self._timeout = conf["timeout"]
        if self._timeout > 0:
            self._timeout = self._timeout / 1000.0
        else:
            self._timeout = -1

        if self._batch_size is None:
            self._batch_size = conf["batch_size"]
        if self._auto_batching_timeout is None:
            self._auto_batching_timeout = conf["auto_batching_timeout"]
        if self._auto_batching_timeout <= 0 or self._batch_size == 1:
            _LOGGER.warning(
                self._log(
                    "Because auto_batching_timeout <= 0 or batch_size == 1,"
                    " set auto_batching_timeout to None."))
            self._auto_batching_timeout = None
        else:
            self._auto_batching_timeout = self._auto_batching_timeout / 1000.0

134 135 136
        self.model_config = None
        self.workdir = None
        self.thread_num = self.concurrency
137
        self.device_type = -1
138 139 140
        self.devices = ""
        self.mem_optim = False
        self.ir_optim = False
B
barriery 已提交
141 142 143 144 145 146
        if self._server_endpoints is None:
            server_endpoints = conf.get("server_endpoints", [])
            if len(server_endpoints) != 0:
                # remote service
                self.with_serving = True
                self._server_endpoints = server_endpoints
147
                self.client_type = conf["client_type"]
148
            else:
W
wangjiawei04 已提交
149
                if self._local_service_handler is None:
B
barriery 已提交
150
                    local_service_conf = conf.get("local_service_conf")
B
barriery 已提交
151 152
                    _LOGGER.info("local_service_conf: {}".format(
                        local_service_conf))
153
                    self.model_config = local_service_conf.get("model_config")
W
wangjiawei04 已提交
154
                    self.client_type = local_service_conf.get("client_type")
155 156
                    self.workdir = local_service_conf.get("workdir")
                    self.thread_num = local_service_conf.get("thread_num")
157
                    self.device_type = local_service_conf.get("device_type")
158 159 160 161 162
                    self.devices = local_service_conf.get("devices")
                    self.mem_optim = local_service_conf.get("mem_optim")
                    self.ir_optim = local_service_conf.get("ir_optim")
                    self._fetch_names = local_service_conf.get("fetch_list")
                    if self.model_config is None:
B
barriery 已提交
163 164 165 166
                        self.with_serving = False
                    else:
                        # local rpc service
                        self.with_serving = True
W
wangjiawei04 已提交
167 168
                        if self.client_type == "brpc" or self.client_type == "grpc":
                            service_handler = local_service_handler.LocalServiceHandler(
169
                                model_config=self.model_config,
W
wangjiawei04 已提交
170
                                client_type=self.client_type,
171 172
                                workdir=self.workdir,
                                thread_num=self.thread_num,
173
                                device_type=self.device_type,
174 175 176
                                devices=self.devices,
                                mem_optim=self.mem_optim,
                                ir_optim=self.ir_optim)
W
wangjiawei04 已提交
177 178 179 180 181 182 183 184 185 186 187 188
                            service_handler.prepare_server()  # get fetch_list
                            serivce_ports = service_handler.get_port_list()
                            self._server_endpoints = [
                                "127.0.0.1:{}".format(p) for p in serivce_ports
                            ]
                            if self._client_config is None:
                                self._client_config = service_handler.get_client_config(
                                )
                            if self._fetch_names is None:
                                self._fetch_names = service_handler.get_fetch_list(
                                )
                        elif self.client_type == "local_predictor":
W
wangjiawei04 已提交
189
                            service_handler = local_service_handler.LocalServiceHandler(
190
                                model_config=self.model_config,
W
wangjiawei04 已提交
191
                                client_type=self.client_type,
192 193
                                workdir=self.workdir,
                                thread_num=self.thread_num,
194
                                device_type=self.device_type,
195
                                devices=self.devices,
196 197 198
                                fetch_names=self._fetch_names,
                                mem_optim=self.mem_optim,
                                ir_optim=self.ir_optim)
W
wangjiawei04 已提交
199 200 201 202
                            if self._client_config is None:
                                self._client_config = service_handler.get_client_config(
                                )
                        self._local_service_handler = service_handler
B
barriery 已提交
203
                else:
B
barriery 已提交
204
                    self.with_serving = True
W
wangjiawei04 已提交
205
                    self._local_service_handler.prepare_server(
B
barriery 已提交
206
                    )  # get fetch_list
W
wangjiawei04 已提交
207
                    serivce_ports = self._local_service_handler.get_port_list()
B
barriery 已提交
208 209 210
                    self._server_endpoints = [
                        "127.0.0.1:{}".format(p) for p in serivce_ports
                    ]
B
barriery 已提交
211
                    if self._client_config is None:
W
wangjiawei04 已提交
212
                        self._client_config = self._local_service_handler.get_client_config(
B
barriery 已提交
213
                        )
B
barriery 已提交
214
                    if self._fetch_names is None:
W
wangjiawei04 已提交
215
                        self._fetch_names = self._local_service_handler.get_fetch_list(
B
barriery 已提交
216
                        )
B
barriery 已提交
217 218
        else:
            self.with_serving = True
B
barriery 已提交
219

220 221 222 223 224 225 226 227 228 229 230
        if not isinstance(self, RequestOp) and not isinstance(self, ResponseOp):
            _LOGGER.info(
                self._log("\n\tinput_ops: {},"
                          "\n\tserver_endpoints: {}"
                          "\n\tfetch_list: {}"
                          "\n\tclient_config: {}"
                          "\n\tconcurrency: {},"
                          "\n\ttimeout(s): {},"
                          "\n\tretry: {},"
                          "\n\tbatch_size: {},"
                          "\n\tauto_batching_timeout(s): {}".format(
B
barriery 已提交
231
                              ", ".join([op.name for op in self._input_ops
232 233 234 235
                                         ]), self._server_endpoints,
                              self._fetch_names, self._client_config,
                              self.concurrency, self._timeout, self._retry,
                              self._batch_size, self._auto_batching_timeout)))
B
barriery 已提交
236

237
    def launch_local_rpc_service(self):
238 239 240 241 242 243 244 245 246
        """
        Launching multiple local rpc servers.

        Args:
            None

        Returns:
            None
        """
W
wangjiawei04 已提交
247
        if self._local_service_handler is None:
B
barriery 已提交
248 249
            _LOGGER.warning(
                self._log("Failed to launch local rpc"
W
wangjiawei04 已提交
250
                          " service: local_service_handler is None."))
B
barriery 已提交
251
            return
W
wangjiawei04 已提交
252
        port = self._local_service_handler.get_port_list()
W
wangjiawei04 已提交
253 254 255
        #if self._local_service_handler.client_type == "local_predictor":
        #    _LOGGER.info("Op({}) use local predictor.")
        #    return
W
wangjiawei04 已提交
256
        self._local_service_handler.start_server()
B
barriery 已提交
257
        _LOGGER.info("Op({}) use local rpc service at port: {}"
258 259
                     .format(self.name, port))

B
barriery 已提交
260
    def use_default_auto_batching_config(self):
261 262 263 264 265 266 267 268 269
        """
        Set the auto batching config default.

        Args:
            None

        Returns:
            None
        """
B
bug fix  
barriery 已提交
270
        if self._batch_size != 1:
271 272
            _LOGGER.warning("Op({}) reset batch_size=1 (original: {})"
                            .format(self.name, self._batch_size))
B
bug fix  
barriery 已提交
273 274
            self._batch_size = 1
        if self._auto_batching_timeout != None:
275
            _LOGGER.warning(
B
barriery 已提交
276 277
                "Op({}) reset auto_batching_timeout=None (original: {})"
                .format(self.name, self._auto_batching_timeout))
B
bug fix  
barriery 已提交
278
            self._auto_batching_timeout = None
B
barriery 已提交
279

B
barrierye 已提交
280
    def use_profiler(self, use_profile):
B
barrierye 已提交
281
        self._server_use_profile = use_profile
282

B
barriery 已提交
283 284 285
    def set_tracer(self, tracer):
        self._tracer = tracer

W
wangjiawei04 已提交
286
    def init_client(self, client_config, server_endpoints):
287 288 289 290 291 292 293 294 295 296 297 298
        """
        Initialize the client object. There are three types of clients, brpc,
        grpc and local_predictor. In grpc or brpc mode, the client connects 
        endpoints.

        Args:
            client_config: client config info
            server_endpoints: server IP/Port list.

        Returns:
            client: client object.
        """
299
        if self.with_serving == False:
B
barriery 已提交
300
            _LOGGER.info("Op({}) has no client (and it also do not "
301
                         "run the process function)".format(self.name))
B
barrierye 已提交
302
            return None
W
wangjiawei04 已提交
303
        if self.client_type == 'brpc':
B
barrierye 已提交
304 305
            client = Client()
            client.load_client_config(client_config)
W
wangjiawei04 已提交
306
        elif self.client_type == 'grpc':
B
barrierye 已提交
307
            client = MultiLangClient()
W
wangjiawei04 已提交
308 309 310 311
        elif self.client_type == 'local_predictor':
            if self.local_predictor is None:
                raise ValueError("local predictor not yet created")
            client = self.local_predictor
312
        else:
B
barriery 已提交
313
            raise ValueError("Failed to init client: unknow client "
W
wangjiawei04 已提交
314
                             "type {}".format(self.client_type))
W
wangjiawei04 已提交
315 316 317
        if self._fetch_names is None:
            self._fetch_names = client.fetch_names_
            _LOGGER.info("Op({}) has no fetch name set. So fetch all vars")
W
wangjiawei04 已提交
318 319
        if self.client_type != "local_predictor":
            client.connect(server_endpoints)
B
barrierye 已提交
320
        return client
321 322 323 324 325

    def get_input_ops(self):
        return self._input_ops

    def set_input_ops(self, ops):
326 327 328 329 330 331 332 333 334 335
        """
        Set input ops.Each op have many input ops, but only one input
        channel.

        Args:
            ops: op list

        Returns:
            None.
        """
336 337 338 339 340
        if not isinstance(ops, list):
            ops = [] if ops is None else [ops]
        self._input_ops = []
        for op in ops:
            if not isinstance(op, Op):
341
                _LOGGER.critical(
B
barriery 已提交
342 343
                    self._log("Failed to set input_ops: input op "
                              "must be Op type, not {}".format(type(op))))
344
                os._exit(-1)
345
            self._input_ops.append(op)
D
dongdaxiang 已提交
346

347
    def add_input_channel(self, channel):
348 349 350 351
        """
        Adding one input channel to the Op. Each op have many front op,
        but, only one input channel.
        """
352
        if not isinstance(channel, (ThreadChannel, ProcessChannel)):
353
            _LOGGER.critical(
B
barriery 已提交
354 355 356
                self._log("Failed to set input_channel: input "
                          "channel must be Channel type, not {}".format(
                              type(channel))))
357
            os._exit(-1)
358 359
        channel.add_consumer(self.name)
        self._input = channel
D
dongdaxiang 已提交
360

361
    def clean_input_channel(self):
B
barrierye 已提交
362 363 364 365
        self._input = None

    def _get_input_channel(self):
        return self._input
D
dongdaxiang 已提交
366

367
    def add_output_channel(self, channel):
368 369 370 371 372 373 374 375 376 377
        """
        Adding one output channel to the Op. Each op have many output channels,
        But only one front channel.

        Args:
            channel: an output channel object.

        Returns:
            None
        """
378
        if not isinstance(channel, (ThreadChannel, ProcessChannel)):
379
            _LOGGER.critical(
B
barriery 已提交
380 381
                self._log("Failed to add output_channel: output channel "
                          "must be Channel type, not {}".format(type(channel))))
382
            os._exit(-1)
383 384
        channel.add_producer(self.name)
        self._outputs.append(channel)
D
dongdaxiang 已提交
385

386
    def clean_output_channels(self):
B
barrierye 已提交
387 388 389 390 391
        self._outputs = []

    def _get_output_channels(self):
        return self._outputs

392
    def preprocess(self, input_dicts, data_id=0, log_id=0):
T
TeslaZhao 已提交
393 394 395 396 397 398
        """
        In preprocess stage, assembling data for process stage. users can 
        override this function for model feed features.

        Args:
            input_dicts: input data to be preprocessed
399 400
            data_id: inner unique id, 0 default
            log_id: global unique id for RTT, 0 default
T
TeslaZhao 已提交
401 402 403 404 405 406 407 408

        Return:
            input_dict: data for process stage
            is_skip_process: skip process stage or not, False default
            prod_errcode: None default, otherwise, product errores occured.
                          It is handled in the same way as exception. 
            prod_errinfo: "" default
        """
B
barrierye 已提交
409
        # multiple previous Op
B
barrierye 已提交
410
        if len(input_dicts) != 1:
411 412
            _LOGGER.critical(
                self._log(
B
barriery 已提交
413 414
                    "Failed to run preprocess: this Op has multiple previous "
                    "inputs. Please override this func."))
415
            os._exit(-1)
D
dongdaxiang 已提交
416

B
barrierye 已提交
417
        (_, input_dict), = input_dicts.items()
T
TeslaZhao 已提交
418
        return input_dict, False, None, ""
B
barrierye 已提交
419

420
    def process(self, feed_batch, typical_logid=0):
T
TeslaZhao 已提交
421 422 423 424 425
        """
        In process stage, send requests to the inference server or predict locally.
        users do not need to inherit this function
        Args:
            feed_batch: data to be fed to inference server
426 427
            typical_logid: mark batch predicts, usually the first logid in batch,
                0 default.
T
TeslaZhao 已提交
428 429 430 431

        Returns:
            call_result: predict result
        """
B
bug fix  
barriery 已提交
432
        err, err_info = ChannelData.check_batch_npdata(feed_batch)
B
barrierye 已提交
433
        if err != 0:
434
            _LOGGER.critical(
B
barriery 已提交
435 436
                self._log("Failed to run process: {}. Please override "
                          "preprocess func.".format(err_info)))
437
            os._exit(-1)
W
wangjiawei04 已提交
438 439 440
        if self.client_type == "local_predictor":
            call_result = self.client.predict(
                feed=feed_batch[0],
W
wangjiawei04 已提交
441
                fetch=self._fetch_names,
W
wangjiawei04 已提交
442 443 444 445 446
                batch=True,
                log_id=typical_logid)
        else:
            call_result = self.client.predict(
                feed=feed_batch,
W
wangjiawei04 已提交
447
                fetch=self._fetch_names,
W
wangjiawei04 已提交
448 449
                batch=True,
                log_id=typical_logid)
B
barriery 已提交
450 451 452 453
        if isinstance(self.client, MultiLangClient):
            if call_result is None or call_result["serving_status_code"] != 0:
                return None
            call_result.pop("serving_status_code")
454 455
        return call_result

456
    def postprocess(self, input_dict, fetch_dict, log_id=0):
T
TeslaZhao 已提交
457 458 459 460 461
        """
        In postprocess stage, assemble data for next op or output.
        Args:
            input_dict: data returned in preprocess stage.
            fetch_dict: data returned in process stage.
462
            log_id: logid, 0 default
T
TeslaZhao 已提交
463 464 465 466 467 468 469 470

        Returns: 
            fetch_dict: return fetch_dict default
            prod_errcode: None default, otherwise, product errores occured.
                          It is handled in the same way as exception.
            prod_errinfo: "" default
        """
        return fetch_dict, None, ""
D
dongdaxiang 已提交
471

B
barrierye 已提交
472
    def _parse_channeldata(self, channeldata_dict):
T
TeslaZhao 已提交
473 474 475 476 477 478 479 480 481 482 483 484 485
        """
        Parse one channeldata 
        Args:
            channeldata_dict : channel data to be parsed, dict type
        
        Return:
            data_id: created by dag._id_generator, unique
            error_channeldata: error channeldata
            parsed_data: get np/dict data from channeldata
            client_need_profile: need profile info
            profile_set: profile info
            log_id: logid for tracing a request 
        """
486
        data_id, error_channeldata = None, None
B
barrierye 已提交
487
        client_need_profile, profile_set = False, set()
B
barrierye 已提交
488 489 490 491
        parsed_data = {}

        key = list(channeldata_dict.keys())[0]
        data_id = channeldata_dict[key].id
T
TeslaZhao 已提交
492
        log_id = channeldata_dict[key].log_id
B
barrierye 已提交
493
        client_need_profile = channeldata_dict[key].client_need_profile
B
barrierye 已提交
494 495

        for name, data in channeldata_dict.items():
T
TeslaZhao 已提交
496
            if data.error_code != ChannelDataErrcode.OK.value:
B
barrierye 已提交
497 498 499
                error_channeldata = data
                break
            parsed_data[name] = data.parse()
B
barrierye 已提交
500
            if client_need_profile:
B
barrierye 已提交
501
                profile_set |= data.profile_data_set
B
barrierye 已提交
502
        return (data_id, error_channeldata, parsed_data, client_need_profile,
T
TeslaZhao 已提交
503
                profile_set, log_id)
B
barrierye 已提交
504 505 506 507 508

    def _push_to_output_channels(self,
                                 data,
                                 channels,
                                 name=None,
B
barriery 已提交
509
                                 profile_str=None,
B
barrierye 已提交
510
                                 client_need_profile=False,
B
barrierye 已提交
511
                                 profile_set=None):
T
TeslaZhao 已提交
512 513 514 515 516 517 518 519 520 521 522 523 524 525
        """
        Push data to output channels, Do not run the later stage(preprocess,
        process, postprocess)
        Args:
            data: channeldata, to be pushed
            channels: output channels
            name: op name  
            profile_str: one profile message
            client_need_profile: False default
            profile_set: profile message collections

        Returns:
            None
        """
526 527
        if name is None:
            name = self.name
B
barrierye 已提交
528

B
barriery 已提交
529
        # add profile into channeldata
B
barrierye 已提交
530
        if client_need_profile and profile_set is not None:
B
barriery 已提交
531 532
            if profile_str is not None:
                profile_set.add(profile_str)
B
barrierye 已提交
533
            data.add_profile(profile_set)
B
barrierye 已提交
534

B
barriery 已提交
535 536 537
        for channel in channels:
            channel.push(data, name)

W
wangjiawei04 已提交
538
    def start_with_process(self):
539 540 541 542 543 544 545 546 547 548
        """
        Each OP creates a process to run the main loop, initializes the CUDA
        environment in each individual process.

        Args:
            None

        Returns:
            process array
        """
B
barriery 已提交
549 550 551
        trace_buffer = None
        if self._tracer is not None:
            trace_buffer = self._tracer.data_buffer()
W
wangjiawei04 已提交
552
        process = []
B
barrierye 已提交
553
        for concurrency_idx in range(self.concurrency):
554 555
            p = multiprocessing.Process(
                target=self._run,
B
barrierye 已提交
556
                args=(concurrency_idx, self._get_input_channel(),
557 558
                      self._get_output_channels(), False, trace_buffer,
                      self.model_config, self.workdir, self.thread_num,
559 560
                      self.device_type, self.devices, self.mem_optim,
                      self.ir_optim))
B
barriery 已提交
561
            p.daemon = True
562
            p.start()
W
wangjiawei04 已提交
563 564
            process.append(p)
        return process
565

W
wangjiawei04 已提交
566
    def start_with_thread(self):
567 568 569 570 571 572 573 574 575 576
        """
        Each OP creates a thread to run the main loop, initializes the CUDA 
        environment in the main thread.

        Args:
            None
 
        Returns:
            thread array
        """
B
barriery 已提交
577 578 579
        trace_buffer = None
        if self._tracer is not None:
            trace_buffer = self._tracer.data_buffer()
580 581 582 583

        #Init cuda env in main thread
        if self.client_type == "local_predictor":
            _LOGGER.info("Init cuda env in main thread")
584
            self.local_predictor = self._local_service_handler.get_client(0)
585

586
        threads = []
B
barrierye 已提交
587
        for concurrency_idx in range(self.concurrency):
588 589
            t = threading.Thread(
                target=self._run,
B
barrierye 已提交
590
                args=(concurrency_idx, self._get_input_channel(),
591 592
                      self._get_output_channels(), True, trace_buffer,
                      self.model_config, self.workdir, self.thread_num,
593 594
                      self.device_type, self.devices, self.mem_optim,
                      self.ir_optim))
B
barriery 已提交
595 596 597
            # When a process exits, it attempts to terminate
            # all of its daemonic child processes.
            t.daemon = True
598 599 600 601
            t.start()
            threads.append(t)
        return threads

B
barrierye 已提交
602
    def init_op(self):
B
barrierye 已提交
603 604
        pass

T
TeslaZhao 已提交
605 606 607 608 609 610 611 612 613 614 615 616 617 618
    def _run_preprocess(self, parsed_data_dict, op_info_prefix, logid_dict):
        """
        Run preprocess stage
        Args:
            parsed_data_dict: data to be pre-processed
            op_info_prefix: input op info
            logid_dict: logid dict

        Returns:
            preped_data_dict: data preprocessed, to be processed 
            err_channeldata_dict: when exceptions occurred, putting errors in it.
            skip_process_dict: skip process stage or not

        """
B
barriery 已提交
619
        _LOGGER.debug("{} Running preprocess".format(op_info_prefix))
620 621
        preped_data_dict = collections.OrderedDict()
        err_channeldata_dict = collections.OrderedDict()
T
TeslaZhao 已提交
622
        skip_process_dict = {}
623 624
        for data_id, parsed_data in parsed_data_dict.items():
            preped_data, error_channeldata = None, None
T
TeslaZhao 已提交
625 626 627
            is_skip_process = False
            prod_errcode, prod_errinfo = None, None
            log_id = logid_dict.get(data_id)
628
            try:
T
TeslaZhao 已提交
629 630 631 632 633
                preped_data, is_skip_process, prod_errcode, prod_errinfo = self.preprocess(
                    parsed_data, data_id, logid_dict.get(data_id))
                # Set skip_process_dict
                if is_skip_process is True:
                    skip_process_dict[data_id] = True
634 635
            except TypeError as e:
                # Error type in channeldata.datatype
T
TeslaZhao 已提交
636 637
                error_info = "(data_id={} log_id={}) {} Failed to preprocess: {}".format(
                    data_id, log_id, op_info_prefix, e)
B
barriery 已提交
638
                _LOGGER.error(error_info, exc_info=True)
639
                error_channeldata = ChannelData(
T
TeslaZhao 已提交
640
                    error_code=ChannelDataErrcode.TYPE_ERROR.value,
641
                    error_info=error_info,
T
TeslaZhao 已提交
642 643
                    data_id=data_id,
                    log_id=log_id)
644
            except Exception as e:
T
TeslaZhao 已提交
645 646
                error_info = "(data_id={} log_id={}) {} Failed to preprocess: {}".format(
                    data_id, log_id, op_info_prefix, e)
B
barriery 已提交
647
                _LOGGER.error(error_info, exc_info=True)
648
                error_channeldata = ChannelData(
T
TeslaZhao 已提交
649
                    error_code=ChannelDataErrcode.UNKNOW.value,
650
                    error_info=error_info,
T
TeslaZhao 已提交
651 652 653 654 655 656 657 658 659 660 661 662 663
                    data_id=data_id,
                    log_id=log_id)

            if prod_errcode is not None:
                # product errors occured
                error_channeldata = ChannelData(
                    error_code=ChannelDataErrcode.PRODUCT_ERROR.value,
                    error_info="",
                    prod_error_code=prod_errcode,
                    prod_error_info=prod_errinfo,
                    data_id=data_id,
                    log_id=log_id)

664 665 666 667
            if error_channeldata is not None:
                err_channeldata_dict[data_id] = error_channeldata
            else:
                preped_data_dict[data_id] = preped_data
B
barriery 已提交
668
        _LOGGER.debug("{} Succ preprocess".format(op_info_prefix))
T
TeslaZhao 已提交
669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
        return preped_data_dict, err_channeldata_dict, skip_process_dict

    def _run_process(self, preped_data_dict, op_info_prefix, skip_process_dict,
                     logid_dict):
        """
        Run process stage
        Args:
            preped_data_dict: feed the data to be predicted by the model.  
            op_info_prefix: prefix op info
            skip_process_dict: skip process stage or not
            logid_dict: logid dict

        Returns:
            midped_data_dict: data midprocessed, to be post-processed 
            err_channeldata_dict: when exceptions occurred, putting errors in it 
        """
B
barriery 已提交
685
        _LOGGER.debug("{} Running process".format(op_info_prefix))
686 687
        midped_data_dict = collections.OrderedDict()
        err_channeldata_dict = collections.OrderedDict()
T
TeslaZhao 已提交
688 689
        ### if (batch_num == 1 && skip == True) ,then skip the process stage.
        is_skip_process = False
T
TeslaZhao 已提交
690
        data_ids = list(preped_data_dict.keys())
T
TeslaZhao 已提交
691 692 693 694 695 696 697
        if len(data_ids) == 1 and skip_process_dict.get(data_ids[0]) == True:
            is_skip_process = True
            _LOGGER.info("(data_id={} log_id={}) skip process stage".format(
                data_ids[0], logid_dict.get(data_ids[0])))

        if self.with_serving is True and is_skip_process is False:
            # use typical_logid to mark batch data
B
barriery 已提交
698 699 700 701
            typical_logid = data_ids[0]
            if len(data_ids) != 1:
                for data_id in data_ids:
                    _LOGGER.info(
T
TeslaZhao 已提交
702
                        "(data_id={} logid={}) {} During access to PaddleServingService,"
703 704
                        " we selected logid={} (from batch: {}) as a "
                        "representative for logging.".format(
T
TeslaZhao 已提交
705 706 707
                            data_id,
                            logid_dict.get(data_id), op_info_prefix,
                            typical_logid, data_ids))
B
barrierye 已提交
708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726

            # combine samples to batch
            one_input = preped_data_dict[data_ids[0]]
            feed_batch = []
            input_offset = None
            if isinstance(one_input, dict):
                # sample input
                feed_batch = [preped_data_dict[data_id] for data_id in data_ids]
                input_offset = list(range(len(data_ids) + 1))
            elif isinstance(one_input, list):
                # batch input
                input_offset = [0]
                for data_id in data_ids:
                    batch_input = preped_data_dict[data_id]
                    offset = input_offset[-1] + len(batch_input)
                    feed_batch += batch_input
                    input_offset.append(offset)
            else:
                _LOGGER.critical(
T
TeslaZhao 已提交
727 728 729
                    "(data_id={} log_id={}){} Failed to process: expect input type is dict(sample"
                    " input) or list(batch input), but get {}".format(data_ids[
                        0], typical_logid, op_info_prefix, type(one_input)))
B
barrierye 已提交
730 731
                os._exit(-1)

B
bug fix  
barriery 已提交
732
            midped_batch = None
T
TeslaZhao 已提交
733
            error_code = ChannelDataErrcode.OK.value
734 735
            if self._timeout <= 0:
                try:
B
barriery 已提交
736
                    midped_batch = self.process(feed_batch, typical_logid)
737
                except Exception as e:
T
TeslaZhao 已提交
738 739 740
                    error_code = ChannelDataErrcode.UNKNOW.value
                    error_info = "(data_id={} log_id={}) {} Failed to process(batch: {}): {}".format(
                        data_ids[0], typical_logid, op_info_prefix, data_ids, e)
B
barriery 已提交
741
                    _LOGGER.error(error_info, exc_info=True)
742
            else:
T
TeslaZhao 已提交
743
                # retry N times configed in yaml files.
744 745
                for i in range(self._retry):
                    try:
T
TeslaZhao 已提交
746
                        # time out for each process
747
                        midped_batch = func_timeout.func_timeout(
B
barriery 已提交
748 749 750
                            self._timeout,
                            self.process,
                            args=(feed_batch, typical_logid))
751 752
                    except func_timeout.FunctionTimedOut as e:
                        if i + 1 >= self._retry:
T
TeslaZhao 已提交
753 754
                            error_code = ChannelDataErrcode.TIMEOUT.value
                            error_info = "(log_id={}) {} Failed to process(batch: {}): " \
B
barriery 已提交
755
                                    "exceeded retry count.".format(
B
barriery 已提交
756
                                            typical_logid, op_info_prefix, data_ids)
757 758
                            _LOGGER.error(error_info)
                        else:
759
                            _LOGGER.warning(
T
TeslaZhao 已提交
760
                                "(log_id={}) {} Failed to process(batch: {}): timeout,"
B
barriery 已提交
761 762 763
                                " and retrying({}/{})...".format(
                                    typical_logid, op_info_prefix, data_ids, i +
                                    1, self._retry))
764
                    except Exception as e:
T
TeslaZhao 已提交
765 766
                        error_code = ChannelDataErrcode.UNKNOW.value
                        error_info = "(log_id={}) {} Failed to process(batch: {}): {}".format(
B
barriery 已提交
767
                            typical_logid, op_info_prefix, data_ids, e)
B
barriery 已提交
768
                        _LOGGER.error(error_info, exc_info=True)
769 770 771
                        break
                    else:
                        break
T
TeslaZhao 已提交
772
            if error_code != ChannelDataErrcode.OK.value:
773 774
                for data_id in data_ids:
                    err_channeldata_dict[data_id] = ChannelData(
T
TeslaZhao 已提交
775 776 777 778
                        error_code=error_code,
                        error_info=error_info,
                        data_id=data_id,
                        log_id=logid_dict.get(data_id))
779
            elif midped_batch is None:
780
                # op client return None
T
TeslaZhao 已提交
781
                error_info = "(log_id={}) {} Failed to predict, please check if " \
B
barriery 已提交
782 783 784
                        "PaddleServingService is working properly.".format(
                                typical_logid, op_info_prefix)
                _LOGGER.error(error_info)
785 786
                for data_id in data_ids:
                    err_channeldata_dict[data_id] = ChannelData(
T
TeslaZhao 已提交
787
                        error_code=ChannelDataErrcode.CLIENT_ERROR.value,
B
barriery 已提交
788
                        error_info=error_info,
T
TeslaZhao 已提交
789 790
                        data_id=data_id,
                        log_id=logid_dict.get(data_id))
791 792
            else:
                # transform np format to dict format
B
barrierye 已提交
793 794 795 796 797 798
                var_names = midped_batch.keys()
                lod_var_names = set()
                lod_offset_names = set()
                for name in var_names:
                    lod_offset_name = "{}.lod".format(name)
                    if lod_offset_name in var_names:
T
TeslaZhao 已提交
799
                        _LOGGER.debug("(log_id={}) {} {} is LodTensor".format(
B
barrierye 已提交
800 801 802
                            typical_logid, op_info_prefix, name))
                        lod_var_names.add(name)
                        lod_offset_names.add(lod_offset_name)
B
barriery 已提交
803

804
                for idx, data_id in enumerate(data_ids):
B
barrierye 已提交
805
                    midped_data_dict[data_id] = {}
B
barriery 已提交
806

B
barrierye 已提交
807 808 809 810 811 812
                for name, value in midped_batch.items():
                    if name in lod_offset_names:
                        continue
                    if name in lod_var_names:
                        # lodtensor
                        lod_offset_name = "{}.lod".format(name)
B
barrierye 已提交
813
                        lod_offset = midped_batch[lod_offset_name]
B
barrierye 已提交
814
                        for idx, data_id in enumerate(data_ids):
B
barrierye 已提交
815 816 817 818
                            data_offset_left = input_offset[idx]
                            data_offset_right = input_offset[idx + 1]
                            lod_offset_left = lod_offset[data_offset_left]
                            lod_offset_right = lod_offset[data_offset_right]
B
barriery 已提交
819 820
                            midped_data_dict[data_id][name] = value[
                                lod_offset_left:lod_offset_right]
B
barrierye 已提交
821 822
                            midped_data_dict[data_id][lod_offset_name] = \
                                    lod_offset[data_offset_left:data_offset_right + 1] - lod_offset[data_offset_left]
B
barrierye 已提交
823
                    else:
B
barrierye 已提交
824
                        # normal tensor
B
barrierye 已提交
825
                        for idx, data_id in enumerate(data_ids):
B
barrierye 已提交
826 827 828
                            left = input_offset[idx]
                            right = input_offset[idx + 1]
                            midped_data_dict[data_id][name] = value[left:right]
829
        else:
830
            midped_data_dict = preped_data_dict
B
barriery 已提交
831
        _LOGGER.debug("{} Succ process".format(op_info_prefix))
832 833
        return midped_data_dict, err_channeldata_dict

B
barriery 已提交
834
    def _run_postprocess(self, parsed_data_dict, midped_data_dict,
T
TeslaZhao 已提交
835 836 837 838 839 840 841 842 843 844 845 846 847 848
                         op_info_prefix, logid_dict):
        """
        Run postprocess stage.
        Args:
            parsed_data_dict: data returned in preprocess stage 
            midped_data_dict: data returned in process stage
            op_info_prefix: prefix op info
            logid_dict: logid dict

        Returns:
            postped_data_dict: data postprocessed 
            err_channeldata_dict: when exceptions occurred, putting errors in it
 
        """
B
barriery 已提交
849
        _LOGGER.debug("{} Running postprocess".format(op_info_prefix))
850 851
        postped_data_dict = collections.OrderedDict()
        err_channeldata_dict = collections.OrderedDict()
B
bug fix  
barriery 已提交
852
        for data_id, midped_data in midped_data_dict.items():
T
TeslaZhao 已提交
853
            log_id = logid_dict.get(data_id)
854
            postped_data, err_channeldata = None, None
T
TeslaZhao 已提交
855
            prod_errcode, prod_errinfo = None, None
856
            try:
T
TeslaZhao 已提交
857 858 859
                postped_data, prod_errcode, prod_errinfo = self.postprocess(
                    parsed_data_dict[data_id], midped_data,
                    logid_dict.get(data_id))
860
            except Exception as e:
T
TeslaZhao 已提交
861 862
                error_info = "(data_id={} log_id={}) {} Failed to postprocess: {}".format(
                    data_id, log_id, op_info_prefix, e)
B
barriery 已提交
863
                _LOGGER.error(error_info, exc_info=True)
864
                err_channeldata = ChannelData(
T
TeslaZhao 已提交
865
                    error_code=ChannelDataErrcode.UNKNOW.value,
866
                    error_info=error_info,
T
TeslaZhao 已提交
867 868 869 870 871 872 873 874 875 876 877 878 879
                    data_id=data_id,
                    log_id=log_id)

            if prod_errcode is not None:
                # product errors occured
                err_channeldata = ChannelData(
                    error_code=ChannelDataErrcode.PRODUCT_ERROR.value,
                    error_info="",
                    prod_error_code=prod_errcode,
                    prod_error_info=prod_errinfo,
                    data_id=data_id,
                    log_id=log_id)

880 881 882 883 884
            if err_channeldata is not None:
                err_channeldata_dict[data_id] = err_channeldata
                continue
            else:
                if not isinstance(postped_data, dict):
T
TeslaZhao 已提交
885
                    error_info = "(log_id={} log_id={}) {} Failed to postprocess: " \
B
barriery 已提交
886 887
                            "output of postprocess funticon must be " \
                            "dict type, but get {}".format(
T
TeslaZhao 已提交
888
                                data_id, log_id, op_info_prefix,
B
barriery 已提交
889
                                type(postped_data))
890 891
                    _LOGGER.error(error_info)
                    err_channeldata = ChannelData(
T
TeslaZhao 已提交
892
                        error_code=ChannelDataErrcode.UNKNOW.value,
893
                        error_info=error_info,
T
TeslaZhao 已提交
894 895
                        data_id=data_id,
                        log_id=log_id)
896 897 898 899 900 901 902 903 904
                    err_channeldata_dict[data_id] = err_channeldata
                    continue

                output_data = None
                err, _ = ChannelData.check_npdata(postped_data)
                if err == 0:
                    output_data = ChannelData(
                        ChannelDataType.CHANNEL_NPDATA.value,
                        npdata=postped_data,
T
TeslaZhao 已提交
905 906
                        data_id=data_id,
                        log_id=log_id)
907 908 909 910
                else:
                    output_data = ChannelData(
                        ChannelDataType.DICT.value,
                        dictdata=postped_data,
T
TeslaZhao 已提交
911 912
                        data_id=data_id,
                        log_id=log_id)
913
                postped_data_dict[data_id] = output_data
B
barriery 已提交
914
        _LOGGER.debug("{} Succ postprocess".format(op_info_prefix))
915
        return postped_data_dict, err_channeldata_dict
B
barriery 已提交
916 917

    def _auto_batching_generator(self, input_channel, op_name, batch_size,
B
barriery 已提交
918
                                 timeout, op_info_prefix):
919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934
        """
        Merge batch_size requests for one prediction.Taking one piece of data 
        from the input channel each time until equals batch_size, or the waiting 
        time exceeds auto_batching_timeout.

        Args:
            input_channel: the input channel of Op
            op_name: op name
            batch_size: batch size, Less than worker_num
            timeout: batch timeout, seconds, If timeout is None, and the quantity 
                taken from the front is less than batch_size, blocking occured.
            op_info_prefix: op link info.

        Returns:
            None
        """
B
barriery 已提交
935 936 937 938 939 940 941 942 943 944 945 946
        while True:
            batch = []
            while len(batch) == 0:
                endtime = None
                if timeout is not None:
                    endtime = _time() + timeout
                for idx in range(batch_size):
                    try:
                        channeldata_dict = None
                        if timeout is not None:
                            remaining = endtime - _time()
                            if remaining <= 0.0:
B
barriery 已提交
947 948
                                _LOGGER.debug("{} Failed to generate batch: "
                                              "timeout".format(op_info_prefix))
B
barriery 已提交
949
                                break
B
barriery 已提交
950 951
                            channeldata_dict = input_channel.front(op_name,
                                                                   timeout)
B
barriery 已提交
952 953 954
                        else:
                            channeldata_dict = input_channel.front(op_name)
                        batch.append(channeldata_dict)
955 956 957
                        _LOGGER.debug(
                            "_auto_batching_generator get {} channeldata from op:{} into batch, batch_size:{}".
                            format(idx, op_name, batch_size))
B
barriery 已提交
958
                    except ChannelTimeoutError:
B
barriery 已提交
959 960
                        _LOGGER.debug("{} Failed to generate batch: "
                                      "timeout".format(op_info_prefix))
B
barriery 已提交
961
                        break
B
barriery 已提交
962 963
            _LOGGER.debug("{} Got actual batch_size: {}".format(op_info_prefix,
                                                                len(batch)))
B
barriery 已提交
964
            yield batch
965

966
    def _parse_channeldata_batch(self, batch, output_channels):
T
TeslaZhao 已提交
967 968 969 970 971 972 973 974 975 976 977 978
        """
        Parse channeldatas batch
        Args:
            batch: auto-batching batch datas
            output_channels: output channels 

        Returns:
            parsed_data_dict: parsed from channeldata in batch
            need_profile_dict: need profile dict in batch 
            profile_dict: profile info dict in batch
            logid_dict: trace each request in batch
        """
979
        parsed_data_dict = collections.OrderedDict()
980 981
        need_profile_dict = {}
        profile_dict = {}
T
TeslaZhao 已提交
982
        logid_dict = {}
B
bug fix  
barriery 已提交
983
        for channeldata_dict in batch:
984
            (data_id, error_channeldata, parsed_data,
T
TeslaZhao 已提交
985
                    client_need_profile, profile_set, log_id) = \
986 987 988 989 990
                            self._parse_channeldata(channeldata_dict)
            if error_channeldata is None:
                parsed_data_dict[data_id] = parsed_data
                need_profile_dict[data_id] = client_need_profile
                profile_dict[data_id] = profile_set
T
TeslaZhao 已提交
991
                logid_dict[data_id] = log_id
992 993 994
            else:
                # error data in predecessor Op
                # (error_channeldata with profile info)
B
barriery 已提交
995 996
                self._push_to_output_channels(error_channeldata,
                                              output_channels)
997

T
TeslaZhao 已提交
998
        return parsed_data_dict, need_profile_dict, profile_dict, logid_dict
B
barriery 已提交
999

W
wangjiawei04 已提交
1000
    def _run(self, concurrency_idx, input_channel, output_channels,
1001
             is_thread_op, trace_buffer, model_config, workdir, thread_num,
1002
             device_type, devices, mem_optim, ir_optim):
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
        """
        _run() is the entry function of OP process / thread model.When client 
        type is local_predictor in process mode, the CUDA environment needs to 
        be initialized by LocalServiceHandler[child process], otherwise, Cuda
        error(3), initialization error is occured. Preprocess, process and 
        postprocess are executed in the main loop. The preprocess and postprocess
        function is usually rewrited by users. Trace data is recorded by trace_que.

        Args:
            concurrency_idx: thread/process index
            input_channel: input channel, take the data to be processed
            output_channels: output channel, store processed data
            is_thread_op: False, It's process op; True, It's thread op
            trace_buffer: store trace infomations
            model_config: model config path
            workdir: work directory
            thread_num: number of threads, concurrent quantity
1020
            device_type: support multiple devices
1021 1022 1023 1024 1025 1026 1027
            devices: gpu id list[gpu], "" default[cpu]
            mem_optim: use memory/graphics memory optimization, True default.
            ir_optim: use calculation chart optimization, False default. 

        Returns:
            None
        """
1028
        op_info_prefix = "[{}|{}]".format(self.name, concurrency_idx)
B
barrierye 已提交
1029

1030
        # init ops
B
barriery 已提交
1031
        profiler = None
B
barrierye 已提交
1032
        try:
1033 1034 1035 1036 1037 1038
            if is_thread_op == False and self.client_type == "local_predictor":
                self.service_handler = local_service_handler.LocalServiceHandler(
                    model_config=model_config,
                    client_type="local_predictor",
                    workdir=workdir,
                    thread_num=thread_num,
1039
                    device_type=device_type,
1040 1041 1042 1043 1044 1045
                    devices=devices,
                    mem_optim=mem_optim,
                    ir_optim=ir_optim)

                _LOGGER.info("Init cuda env in process {}".format(
                    concurrency_idx))
1046 1047
                self.local_predictor = self.service_handler.get_client(
                    concurrency_idx)
1048
            # check all ops initialized successfully.
W
wangjiawei04 已提交
1049
            profiler = self._initialize(is_thread_op, concurrency_idx)
1050

B
barrierye 已提交
1051
        except Exception as e:
B
barriery 已提交
1052
            _LOGGER.critical(
T
TeslaZhao 已提交
1053
                "{} failed to init op: {}".format(op_info_prefix, e),
B
barriery 已提交
1054
                exc_info=True)
B
barrierye 已提交
1055
            os._exit(-1)
B
barriery 已提交
1056
        _LOGGER.info("{} Succ init".format(op_info_prefix))
1057

B
barriery 已提交
1058
        batch_generator = self._auto_batching_generator(
B
barriery 已提交
1059 1060 1061 1062
            input_channel=input_channel,
            op_name=self.name,
            batch_size=self._batch_size,
            timeout=self._auto_batching_timeout,
B
barriery 已提交
1063
            op_info_prefix=op_info_prefix)
B
barriery 已提交
1064

B
barriery 已提交
1065
        start, end = None, None
B
barrierye 已提交
1066
        trace_que = collections.deque()
B
barrierye 已提交
1067
        while True:
B
barriery 已提交
1068
            start = int(round(_time() * 1000000))
B
barrierye 已提交
1069
            try:
B
barriery 已提交
1070
                channeldata_dict_batch = next(batch_generator)
B
barrierye 已提交
1071
            except ChannelStopError:
B
barriery 已提交
1072
                _LOGGER.debug("{} Stop.".format(op_info_prefix))
B
barriery 已提交
1073
                self._finalize(is_thread_op)
B
barrierye 已提交
1074
                break
B
barriery 已提交
1075
            end = int(round(_time() * 1000000))
B
barrierye 已提交
1076
            in_time = end - start
1077

B
barriery 已提交
1078 1079
            # parse channeldata batch
            try:
T
TeslaZhao 已提交
1080
                parsed_data_dict, need_profile_dict, profile_dict, logid_dict\
1081 1082
                        = self._parse_channeldata_batch(
                                channeldata_dict_batch, output_channels)
B
barriery 已提交
1083
            except ChannelStopError:
B
barriery 已提交
1084
                _LOGGER.debug("{} Stop.".format(op_info_prefix))
1085
                self._finalize(is_thread_op)
B
barriery 已提交
1086
                break
1087 1088 1089
            if len(parsed_data_dict) == 0:
                # data in the whole batch is all error data
                continue
1090 1091

            # preprecess
B
barriery 已提交
1092
            start = profiler.record("prep#{}_0".format(op_info_prefix))
T
TeslaZhao 已提交
1093 1094
            preped_data_dict, err_channeldata_dict, skip_process_dict \
                    = self._run_preprocess(parsed_data_dict, op_info_prefix, logid_dict)
B
barriery 已提交
1095
            end = profiler.record("prep#{}_1".format(op_info_prefix))
B
barrierye 已提交
1096
            prep_time = end - start
1097
            try:
T
TeslaZhao 已提交
1098
                # put error requests into output channel, skip process and postprocess stage
1099
                for data_id, err_channeldata in err_channeldata_dict.items():
B
barrierye 已提交
1100
                    self._push_to_output_channels(
B
barriery 已提交
1101 1102
                        data=err_channeldata,
                        channels=output_channels,
1103 1104 1105
                        client_need_profile=need_profile_dict[data_id],
                        profile_set=profile_dict[data_id])
            except ChannelStopError:
B
barriery 已提交
1106
                _LOGGER.debug("{} Stop.".format(op_info_prefix))
1107 1108
                self._finalize(is_thread_op)
                break
B
bug fix  
barrierye 已提交
1109
            if len(preped_data_dict) == 0:
1110 1111
                continue

B
barrierye 已提交
1112
            # process
B
barriery 已提交
1113
            start = profiler.record("midp#{}_0".format(op_info_prefix))
1114
            midped_data_dict, err_channeldata_dict \
T
TeslaZhao 已提交
1115
                    = self._run_process(preped_data_dict, op_info_prefix, skip_process_dict, logid_dict)
B
barriery 已提交
1116
            end = profiler.record("midp#{}_1".format(op_info_prefix))
B
barrierye 已提交
1117
            midp_time = end - start
1118 1119
            try:
                for data_id, err_channeldata in err_channeldata_dict.items():
B
barrierye 已提交
1120
                    self._push_to_output_channels(
B
barriery 已提交
1121 1122
                        data=err_channeldata,
                        channels=output_channels,
B
barriery 已提交
1123 1124
                        client_need_profile=need_profile_dict[data_id],
                        profile_set=profile_dict[data_id])
1125
            except ChannelStopError:
B
barriery 已提交
1126
                _LOGGER.debug("{} Stop.".format(op_info_prefix))
1127 1128 1129
                self._finalize(is_thread_op)
                break
            if len(midped_data_dict) == 0:
1130
                continue
1131 1132

            # postprocess
B
barriery 已提交
1133
            start = profiler.record("postp#{}_0".format(op_info_prefix))
1134
            postped_data_dict, err_channeldata_dict \
T
TeslaZhao 已提交
1135
                    = self._run_postprocess(parsed_data_dict, midped_data_dict, op_info_prefix, logid_dict)
B
barriery 已提交
1136
            end = profiler.record("postp#{}_1".format(op_info_prefix))
B
barrierye 已提交
1137
            postp_time = end - start
1138 1139
            try:
                for data_id, err_channeldata in err_channeldata_dict.items():
B
barrierye 已提交
1140
                    self._push_to_output_channels(
B
bug fix  
barrierye 已提交
1141
                        data=err_channeldata,
B
barriery 已提交
1142
                        channels=output_channels,
B
barriery 已提交
1143 1144
                        client_need_profile=need_profile_dict[data_id],
                        profile_set=profile_dict[data_id])
1145
            except ChannelStopError:
B
barriery 已提交
1146
                _LOGGER.debug("{} Stop.".format(op_info_prefix))
1147 1148 1149
                self._finalize(is_thread_op)
                break
            if len(postped_data_dict) == 0:
1150
                continue
1151 1152

            # push data to channel (if run succ)
B
barriery 已提交
1153
            start = int(round(_time() * 1000000))
B
barrierye 已提交
1154
            try:
B
barriery 已提交
1155
                profile_str = profiler.gen_profile_str()
1156
                for data_id, postped_data in postped_data_dict.items():
B
barriery 已提交
1157 1158
                    if self._server_use_profile:
                        sys.stderr.write(profile_str)
1159
                    self._push_to_output_channels(
B
barriery 已提交
1160 1161 1162
                        data=postped_data,
                        channels=output_channels,
                        profile_str=profile_str,
B
barriery 已提交
1163 1164
                        client_need_profile=need_profile_dict[data_id],
                        profile_set=profile_dict[data_id])
B
barrierye 已提交
1165
            except ChannelStopError:
B
barriery 已提交
1166
                _LOGGER.debug("{} Stop.".format(op_info_prefix))
1167
                self._finalize(is_thread_op)
B
barrierye 已提交
1168
                break
B
barriery 已提交
1169
            end = int(round(_time() * 1000000))
B
barrierye 已提交
1170
            out_time = end - start
B
barriery 已提交
1171
            if trace_buffer is not None:
B
barrierye 已提交
1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188
                trace_que.append({
                    "name": self.name,
                    "actions": {
                        "in": in_time,
                        "prep": prep_time,
                        "midp": midp_time,
                        "postp": postp_time,
                        "out": out_time,
                    }
                })
                while trace_que:
                    info = trace_que[0]
                    try:
                        trace_buffer.put_nowait(info)
                        trace_que.popleft()
                    except Queue.Full:
                        break
B
barriery 已提交
1189

W
wangjiawei04 已提交
1190
    def _initialize(self, is_thread_op, concurrency_idx):
1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203
        """
        Initialize one OP object in the target function of a thread or porcess.
        Initialize the client object with _client_config and _server_endpoints.
        Create a TimeProfiler per thread or process for recording profiler info.

        Args:
            is_thread_op: True, one op runs in one thread; False, one op runs
                in one process.
            concurrency_idx: process id, Thread mode does not use this param.

        Returns:
            TimeProfiler
        """
B
barriery 已提交
1204 1205 1206 1207 1208 1209
        if is_thread_op:
            with self._for_init_op_lock:
                if not self._succ_init_op:
                    # for the threaded version of Op, each thread cannot get its concurrency_idx
                    self.concurrency_idx = None
                    # init client
W
wangjiawei04 已提交
1210
                    self.client = self.init_client(self._client_config,
W
wangjiawei04 已提交
1211
                                                   self._server_endpoints)
B
barriery 已提交
1212 1213 1214 1215
                    # user defined
                    self.init_op()
                    self._succ_init_op = True
                    self._succ_close_op = False
B
bug fix  
barriery 已提交
1216 1217 1218
        else:
            self.concurrency_idx = concurrency_idx
            # init client
W
wangjiawei04 已提交
1219 1220
            self.client = self.init_client(self._client_config,
                                           self._server_endpoints)
B
bug fix  
barriery 已提交
1221 1222
            # user defined
            self.init_op()
B
barriery 已提交
1223

B
barriery 已提交
1224 1225 1226 1227 1228
        # use a separate TimeProfiler per thread or process
        profiler = TimeProfiler()
        profiler.enable(True)
        return profiler

B
barriery 已提交
1229 1230 1231 1232 1233 1234 1235 1236
    def _finalize(self, is_thread_op):
        if is_thread_op:
            with self._for_close_op_lock:
                if not self._succ_close_op:
                    self._profiler = None
                    self.client = None
                    self._succ_init_op = False
                    self._succ_close_op = True
1237 1238 1239 1240 1241

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


B
barrierye 已提交
1242
class RequestOp(Op):
1243 1244 1245 1246 1247 1248
    """
    RequestOp is a special Op, for unpacking one request package. If the
    request needs one special unpackaging method, you need to inherit class
    RequestOp and rewrite function unpack_request_package.Notice!!! Class
    RequestOp does not run preprocess, process, postprocess.
    """
B
barrierye 已提交
1249

B
barrierye 已提交
1250
    def __init__(self):
1251 1252 1253
        """
        Initialize the RequestOp
        """
B
barriery 已提交
1254 1255
        # PipelineService.name = "@DAGExecutor"
        super(RequestOp, self).__init__(name="@DAGExecutor", input_ops=[])
B
barrierye 已提交
1256
        # init op
1257
        try:
1258
            self.init_op()
1259
        except Exception as e:
B
barriery 已提交
1260
            _LOGGER.critical("Op(Request) Failed to init: {}".format(e))
1261
            os._exit(-1)
B
barrierye 已提交
1262 1263

    def unpack_request_package(self, request):
T
TeslaZhao 已提交
1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281
        """
        Unpack request package by gateway.proto
        Args:
            request: HTTP body, JSON format

        Returns:
            dict_data: json fields in HTTP body
            log_id: log_id
            prod_errcode: None or ProductErrCode.SUCC.value default, otherwise,
                          product errores occured.It is handled in the same way
                          as exception.
            prod_errinfo: "" default 
        """
        dict_data = {}
        log_id = None
        if request is None:
            _LOGGER.critical("request is None")
            raise ValueError("request is None")
1282 1283 1284 1285 1286 1287 1288 1289 1290 1291

        for idx, key in enumerate(request.key):
            data = request.value[idx]
            try:
                evaled_data = eval(data)
                if isinstance(evaled_data, np.ndarray):
                    data = evaled_data
            except Exception as e:
                pass
            dict_data[key] = data
T
TeslaZhao 已提交
1292
        log_id = request.logid
1293 1294 1295
        _LOGGER.info("RequestOp unpack one request. log_id:{}, clientip:{} \
            name:{}, method:{}".format(log_id, request.clientip, request.name,
                                       request.method))
T
TeslaZhao 已提交
1296 1297

        return dict_data, log_id, None, ""
B
barrierye 已提交
1298 1299 1300


class ResponseOp(Op):
1301 1302 1303 1304 1305 1306
    """ 
    ResponseOp is a special Op, for packing one response package. If the channeldata 
    needs a special packaging method, you need to inherit class ReponseOp and rewrite
    pack_response_package function. Notice!!! Class ResponseOp does not run preprocess,
    process, postprocess.
    """
B
barrierye 已提交
1307

B
barrierye 已提交
1308
    def __init__(self, input_ops):
1309 1310 1311
        """
        Initialize the ResponseOp
        """
B
barriery 已提交
1312 1313
        super(ResponseOp, self).__init__(
            name="@DAGExecutor", input_ops=input_ops)
B
barrierye 已提交
1314
        # init op
1315
        try:
1316
            self.init_op()
1317
        except Exception as e:
B
barriery 已提交
1318 1319
            _LOGGER.critical("Op(ResponseOp) Failed to init: {}".format(
                e, exc_info=True))
1320
            os._exit(-1)
B
barrierye 已提交
1321 1322

    def pack_response_package(self, channeldata):
T
TeslaZhao 已提交
1323
        """
1324 1325 1326 1327 1328 1329 1330 1331
        Getting channeldata from the last channel, packting the response 
        package serialized by protobuf.  

        Args:
            channeldata: Type ChannelData

        Returns:
            resp: pipeline_service_pb2.Response()
T
TeslaZhao 已提交
1332
        """
B
barrierye 已提交
1333
        resp = pipeline_service_pb2.Response()
T
TeslaZhao 已提交
1334 1335 1336
        error_code = channeldata.error_code
        error_info = ""
        if error_code == ChannelDataErrcode.OK.value:
1337
            # Framework level errors
B
barrierye 已提交
1338 1339 1340 1341
            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
B
barrierye 已提交
1342
                np.set_printoptions(threshold=sys.maxsize)
B
barrierye 已提交
1343
                for name, var in feed.items():
1344 1345
                    resp.value.append(var.__repr__())
                    resp.key.append(name)
B
barrierye 已提交
1346 1347 1348 1349
            elif channeldata.datatype == ChannelDataType.DICT.value:
                feed = channeldata.parse()
                for name, var in feed.items():
                    if not isinstance(var, str):
T
TeslaZhao 已提交
1350 1351
                        error_code = ChannelDataErrcode.TYPE_ERROR.value
                        error_info = self._log(
B
barrierye 已提交
1352 1353
                            "fetch var type must be str({}).".format(
                                type(var)))
B
barriery 已提交
1354 1355
                        _LOGGER.error("(logid={}) Failed to pack RPC "
                                      "response package: {}".format(
W
wangjiawei04 已提交
1356
                                          channeldata.id, resp.err_msg))
B
barrierye 已提交
1357
                        break
1358 1359
                    resp.value.append(var)
                    resp.key.append(name)
B
barrierye 已提交
1360
            else:
T
TeslaZhao 已提交
1361 1362 1363
                error_code = ChannelDataErrcode.TYPE_ERROR.value
                error_info = self._log("error type({}) in datatype.".format(
                    channeldata.datatype))
B
barriery 已提交
1364
                _LOGGER.error("(logid={}) Failed to pack RPC response"
T
TeslaZhao 已提交
1365
                              " package: {}".format(channeldata.id, error_info))
B
barrierye 已提交
1366
        else:
1367
            # Product level errors
T
TeslaZhao 已提交
1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379
            error_info = channeldata.error_info
            if error_code == ChannelDataErrcode.PRODUCT_ERROR.value:
                #rewrite error_code when product errors occured
                error_code = channeldata.prod_error_code
                error_info = channeldata.prod_error_info

        # pack results
        if error_code is None:
            error_code = 0
        resp.err_no = error_code
        resp.err_msg = error_info

B
barrierye 已提交
1380
        return resp
1381 1382 1383


class VirtualOp(Op):
1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400
    """ 
    To connect 2 ops across levels in dag view, we create virtual ops
    between non-virtual ops, and transfer data only. For examples, 
    the pred ops of F are D & E.In the process of building DAG, we will
    create channels layer by layer according to dag views.Op F is not 
    in the next layer view of [B, E], so we will create a virtual OP 
    'V1' whose pred OP is E. And so on, we create two virtual op 'V2'
    and 'V3', Finally, we find the non-virtual op F. we create 4 channels
    among E, V1, V2, V3 and F, the producer of V1, V2, V3 and F is E.
    
        DAG: [A -> B -> C -> D -> F]
               \-> E ----------/

        DAG view: [[A], [B, E], [C], [D], [F]]
        BUILD DAG: [A -> B -> C -> D -> E -> F]
                     \-> E -> V1-> V2-> V3/
    """
1401 1402 1403

    def __init__(self, name, concurrency=1):
        super(VirtualOp, self).__init__(
B
barrierye 已提交
1404
            name=name, input_ops=None, concurrency=concurrency)
1405 1406 1407
        self._virtual_pred_ops = []

    def add_virtual_pred_op(self, op):
1408 1409 1410 1411 1412 1413 1414 1415 1416
        """
        Add the front op of current vritual op.
        
        Args:
            op: one op object, may be a virtual op or not.

        Returns:
            None
        """
1417 1418
        self._virtual_pred_ops.append(op)

B
barrierye 已提交
1419
    def _actual_pred_op_names(self, op):
1420 1421 1422 1423 1424 1425 1426 1427 1428
        """
        Recursively find the front op which is a non-virtual op.
   
        Args:
            op: one op object
            
        Returns:
            names: the name of non-virtual pred ops.
        """
B
barriery 已提交
1429
        # can use disjoint-set, but it's not necessary
B
barrierye 已提交
1430 1431 1432 1433 1434 1435 1436
        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

1437
    def add_output_channel(self, channel):
1438 1439 1440 1441 1442 1443 1444 1445 1446
        """
        Adding the output channel of non-virtual pred ops.

        Args:
            channel: one channel.
          
        Returns:
            None.
        """
1447
        if not isinstance(channel, (ThreadChannel, ProcessChannel)):
1448
            _LOGGER.critical(
B
barriery 已提交
1449 1450 1451
                self._log("Failed to add output_channel: output_channel"
                          " must be Channel type, not {}".format(
                              type(channel))))
1452
            os._exit(-1)
1453
        for op in self._virtual_pred_ops:
B
barrierye 已提交
1454 1455
            for op_name in self._actual_pred_op_names(op):
                channel.add_producer(op_name)
1456
        self._outputs.append(channel)
D
dongdaxiang 已提交
1457

1458
    def _run(self, concurrency_idx, input_channel, output_channels, client_type,
1459
             is_thread_op):
1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473
        """
        The target function _run() only transfers data between OPs in one thread
        or process.

        Args:
            concurrency_idx: process id, not avaliable in thread mode.
            input_channel: input channel
            output_channels: output channels
            client_type: no use
            is_thread_op: True, thread mode; False, process mode

        Returns:
            None
        """
1474
        op_info_prefix = "[{}|{}]".format(self.name, concurrency_idx)
B
barrierye 已提交
1475 1476 1477
        log = get_log_func(op_info_prefix)
        tid = threading.current_thread().ident

1478 1479 1480 1481 1482 1483 1484
        batch_generator = self._auto_batching_generator(
            input_channel=input_channel,
            op_name=self.name,
            batch_size=1,
            timeout=None,
            log_func=log)

B
barrierye 已提交
1485 1486
        while True:
            try:
1487
                channeldata_dict_batch = next(batch_generator)
B
barrierye 已提交
1488
            except ChannelStopError:
B
barriery 已提交
1489
                _LOGGER.debug("{} Stop.".format(op_info_prefix))
1490
                self._finalize(is_thread_op)
B
barrierye 已提交
1491
                break
D
dongdaxiang 已提交
1492

B
barrierye 已提交
1493
            try:
1494 1495 1496 1497
                for channeldata_dict in channeldata_dict_batch:
                    for name, data in channeldata_dict.items():
                        self._push_to_output_channels(
                            data, channels=output_channels, name=name)
B
barrierye 已提交
1498
            except ChannelStopError:
B
barriery 已提交
1499
                _LOGGER.debug("{} Stop.".format(op_info_prefix))
1500
                self._finalize(is_thread_op)
B
barrierye 已提交
1501
                break