operator.py 67.3 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
        self._batch_size = batch_size
        self._auto_batching_timeout = auto_batching_timeout
J
Jiawei Wang 已提交
78 79
        self._use_encryption_model = None
        self._encryption_key = ""
80 81
        self._input = None
        self._outputs = []
B
barrierye 已提交
82

B
barriery 已提交
83 84 85 86 87 88 89 90 91
        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 已提交
92
    def init_from_dict(self, conf):
93 94 95 96 97 98 99 100 101 102 103 104
        """
        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 已提交
105
        # init op
B
barriery 已提交
106 107 108 109 110 111 112 113
        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")
J
Jiawei Wang 已提交
114 115 116 117 118
        if self._use_encryption_model is None:
            print ("config use_encryption model here", conf.get("use_encryption_model"))
            self._use_encryption_model = conf.get("use_encryption_model")
            if self._encryption_key is None or self._encryption_key=="":
                self._encryption_key = conf.get("encryption_key")
B
barriery 已提交
119 120 121 122 123 124 125 126 127 128 129 130
        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:
131
            _LOGGER.debug(
B
barriery 已提交
132 133 134 135 136 137 138
                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

139 140 141
        self.model_config = None
        self.workdir = None
        self.thread_num = self.concurrency
142
        self.device_type = -1
143 144 145
        self.devices = ""
        self.mem_optim = False
        self.ir_optim = False
146
        self.precision = "fp32"
T
TeslaZhao 已提交
147 148 149 150 151
        self.use_mkldnn = False
        self.mkldnn_cache_capacity = 0
        self.mkldnn_op_list = None
        self.mkldnn_bf16_op_list = None

B
barriery 已提交
152 153 154 155 156 157
        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
158
                self.client_type = conf["client_type"]
159
            else:
W
wangjiawei04 已提交
160
                if self._local_service_handler is None:
B
barriery 已提交
161
                    local_service_conf = conf.get("local_service_conf")
B
barriery 已提交
162 163
                    _LOGGER.info("local_service_conf: {}".format(
                        local_service_conf))
164
                    self.model_config = local_service_conf.get("model_config")
W
wangjiawei04 已提交
165
                    self.client_type = local_service_conf.get("client_type")
166 167
                    self.workdir = local_service_conf.get("workdir")
                    self.thread_num = local_service_conf.get("thread_num")
168
                    self.device_type = local_service_conf.get("device_type")
169 170 171 172
                    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")
173
                    self.precision = local_service_conf.get("precision")
T
TeslaZhao 已提交
174 175 176 177 178 179 180 181
                    self.use_mkldnn = local_service_conf.get("use_mkldnn")
                    self.mkldnn_cache_capacity = local_service_conf.get(
                        "mkldnn_cache_capacity")
                    self.mkldnn_op_list = local_service_conf.get(
                        "mkldnn_op_list")
                    self.mkldnn_bf16_op_list = local_service_conf.get(
                        "mkldnn_bf16_op_list")

182
                    if self.model_config is None:
B
barriery 已提交
183 184 185 186
                        self.with_serving = False
                    else:
                        # local rpc service
                        self.with_serving = True
W
wangjiawei04 已提交
187 188
                        if self.client_type == "brpc" or self.client_type == "grpc":
                            service_handler = local_service_handler.LocalServiceHandler(
189
                                model_config=self.model_config,
W
wangjiawei04 已提交
190
                                client_type=self.client_type,
191 192
                                workdir=self.workdir,
                                thread_num=self.thread_num,
193
                                device_type=self.device_type,
194 195
                                devices=self.devices,
                                mem_optim=self.mem_optim,
196
                                ir_optim=self.ir_optim,
T
TeslaZhao 已提交
197 198 199 200 201 202
                                precision=self.precision,
                                use_mkldnn=self.use_mkldnn,
                                mkldnn_cache_capacity=self.
                                mkldnn_cache_capacity,
                                mkldnn_op_list=self.mkldnn_bf16_op_list,
                                mkldnn_bf16_op_list=self.mkldnn_bf16_op_list)
W
wangjiawei04 已提交
203 204 205 206 207 208 209 210 211 212 213 214
                            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 已提交
215
                            service_handler = local_service_handler.LocalServiceHandler(
216
                                model_config=self.model_config,
W
wangjiawei04 已提交
217
                                client_type=self.client_type,
218 219
                                workdir=self.workdir,
                                thread_num=self.thread_num,
220
                                device_type=self.device_type,
221
                                devices=self.devices,
222 223
                                fetch_names=self._fetch_names,
                                mem_optim=self.mem_optim,
224
                                ir_optim=self.ir_optim,
T
TeslaZhao 已提交
225 226 227 228 229 230
                                precision=self.precision,
                                use_mkldnn=self.use_mkldnn,
                                mkldnn_cache_capacity=self.
                                mkldnn_cache_capacity,
                                mkldnn_op_list=self.mkldnn_op_list,
                                mkldnn_bf16_op_list=self.mkldnn_bf16_op_list)
W
wangjiawei04 已提交
231 232 233 234
                            if self._client_config is None:
                                self._client_config = service_handler.get_client_config(
                                )
                        self._local_service_handler = service_handler
B
barriery 已提交
235
                else:
B
barriery 已提交
236
                    self.with_serving = True
W
wangjiawei04 已提交
237
                    self._local_service_handler.prepare_server(
B
barriery 已提交
238
                    )  # get fetch_list
W
wangjiawei04 已提交
239
                    serivce_ports = self._local_service_handler.get_port_list()
B
barriery 已提交
240 241 242
                    self._server_endpoints = [
                        "127.0.0.1:{}".format(p) for p in serivce_ports
                    ]
B
barriery 已提交
243
                    if self._client_config is None:
W
wangjiawei04 已提交
244
                        self._client_config = self._local_service_handler.get_client_config(
B
barriery 已提交
245
                        )
B
barriery 已提交
246
                    if self._fetch_names is None:
W
wangjiawei04 已提交
247
                        self._fetch_names = self._local_service_handler.get_fetch_list(
B
barriery 已提交
248
                        )
B
barriery 已提交
249 250
        else:
            self.with_serving = True
B
barriery 已提交
251

252 253 254 255 256 257 258 259 260 261 262
        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 已提交
263
                              ", ".join([op.name for op in self._input_ops
264 265 266 267
                                         ]), self._server_endpoints,
                              self._fetch_names, self._client_config,
                              self.concurrency, self._timeout, self._retry,
                              self._batch_size, self._auto_batching_timeout)))
B
barriery 已提交
268

269
    def launch_local_rpc_service(self):
270 271 272 273 274 275 276 277 278
        """
        Launching multiple local rpc servers.

        Args:
            None

        Returns:
            None
        """
W
wangjiawei04 已提交
279
        if self._local_service_handler is None:
B
barriery 已提交
280 281
            _LOGGER.warning(
                self._log("Failed to launch local rpc"
W
wangjiawei04 已提交
282
                          " service: local_service_handler is None."))
B
barriery 已提交
283
            return
W
wangjiawei04 已提交
284
        port = self._local_service_handler.get_port_list()
W
wangjiawei04 已提交
285 286 287
        #if self._local_service_handler.client_type == "local_predictor":
        #    _LOGGER.info("Op({}) use local predictor.")
        #    return
W
wangjiawei04 已提交
288
        self._local_service_handler.start_server()
B
barriery 已提交
289
        _LOGGER.info("Op({}) use local rpc service at port: {}"
290 291
                     .format(self.name, port))

B
barriery 已提交
292
    def use_default_auto_batching_config(self):
293 294 295 296 297 298 299 300 301
        """
        Set the auto batching config default.

        Args:
            None

        Returns:
            None
        """
B
bug fix  
barriery 已提交
302
        if self._batch_size != 1:
303 304
            _LOGGER.warning("Op({}) reset batch_size=1 (original: {})"
                            .format(self.name, self._batch_size))
B
bug fix  
barriery 已提交
305 306
            self._batch_size = 1
        if self._auto_batching_timeout != None:
307
            _LOGGER.warning(
B
barriery 已提交
308 309
                "Op({}) reset auto_batching_timeout=None (original: {})"
                .format(self.name, self._auto_batching_timeout))
B
bug fix  
barriery 已提交
310
            self._auto_batching_timeout = None
B
barriery 已提交
311

B
barrierye 已提交
312
    def use_profiler(self, use_profile):
B
barrierye 已提交
313
        self._server_use_profile = use_profile
314

B
barriery 已提交
315 316 317
    def set_tracer(self, tracer):
        self._tracer = tracer

W
wangjiawei04 已提交
318
    def init_client(self, client_config, server_endpoints):
319 320 321 322 323 324 325 326 327 328 329 330
        """
        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.
        """
331
        if self.with_serving == False:
B
barriery 已提交
332
            _LOGGER.info("Op({}) has no client (and it also do not "
333
                         "run the process function)".format(self.name))
B
barrierye 已提交
334
            return None
W
wangjiawei04 已提交
335
        if self.client_type == 'brpc':
B
barrierye 已提交
336 337
            client = Client()
            client.load_client_config(client_config)
W
wangjiawei04 已提交
338
        elif self.client_type == 'grpc':
B
barrierye 已提交
339
            client = MultiLangClient()
W
wangjiawei04 已提交
340 341 342 343
        elif self.client_type == 'local_predictor':
            if self.local_predictor is None:
                raise ValueError("local predictor not yet created")
            client = self.local_predictor
344
        else:
B
barriery 已提交
345
            raise ValueError("Failed to init client: unknow client "
W
wangjiawei04 已提交
346
                             "type {}".format(self.client_type))
W
wangjiawei04 已提交
347 348 349
        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 已提交
350
        if self.client_type != "local_predictor":
J
Jiawei Wang 已提交
351 352 353 354 355 356
            if self._use_encryption_model is None or self._use_encryption_model is False:
               client.connect(server_endpoints)
            else:
               print("connect to encryption rpc client")
               client.use_key(self._encryption_key)
               client.connect(server_endpoints, encryption=True)
B
barrierye 已提交
357
        return client
358 359 360 361 362

    def get_input_ops(self):
        return self._input_ops

    def set_input_ops(self, ops):
363 364 365 366 367 368 369 370 371 372
        """
        Set input ops.Each op have many input ops, but only one input
        channel.

        Args:
            ops: op list

        Returns:
            None.
        """
373 374 375 376 377
        if not isinstance(ops, list):
            ops = [] if ops is None else [ops]
        self._input_ops = []
        for op in ops:
            if not isinstance(op, Op):
378
                _LOGGER.critical(
B
barriery 已提交
379 380
                    self._log("Failed to set input_ops: input op "
                              "must be Op type, not {}".format(type(op))))
381
                os._exit(-1)
382
            self._input_ops.append(op)
D
dongdaxiang 已提交
383

384
    def add_input_channel(self, channel):
385 386 387 388
        """
        Adding one input channel to the Op. Each op have many front op,
        but, only one input channel.
        """
389
        if not isinstance(channel, (ThreadChannel, ProcessChannel)):
390
            _LOGGER.critical(
B
barriery 已提交
391 392 393
                self._log("Failed to set input_channel: input "
                          "channel must be Channel type, not {}".format(
                              type(channel))))
394
            os._exit(-1)
395 396
        channel.add_consumer(self.name)
        self._input = channel
D
dongdaxiang 已提交
397

398
    def clean_input_channel(self):
B
barrierye 已提交
399 400 401 402
        self._input = None

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

404
    def add_output_channel(self, channel):
405 406 407 408 409 410 411 412 413 414
        """
        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
        """
415
        if not isinstance(channel, (ThreadChannel, ProcessChannel)):
416
            _LOGGER.critical(
B
barriery 已提交
417 418
                self._log("Failed to add output_channel: output channel "
                          "must be Channel type, not {}".format(type(channel))))
419
            os._exit(-1)
420 421
        channel.add_producer(self.name)
        self._outputs.append(channel)
D
dongdaxiang 已提交
422

423
    def clean_output_channels(self):
B
barrierye 已提交
424 425 426 427 428
        self._outputs = []

    def _get_output_channels(self):
        return self._outputs

429
    def preprocess(self, input_dicts, data_id=0, log_id=0):
T
TeslaZhao 已提交
430 431 432 433 434 435
        """
        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
436 437
            data_id: inner unique id, 0 default
            log_id: global unique id for RTT, 0 default
T
TeslaZhao 已提交
438 439

        Return:
T
TeslaZhao 已提交
440
            output_data: data for process stage
T
TeslaZhao 已提交
441 442 443 444 445
            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 已提交
446
        # multiple previous Op
B
barrierye 已提交
447
        if len(input_dicts) != 1:
448 449
            _LOGGER.critical(
                self._log(
B
barriery 已提交
450 451
                    "Failed to run preprocess: this Op has multiple previous "
                    "inputs. Please override this func."))
452
            os._exit(-1)
D
dongdaxiang 已提交
453

B
barrierye 已提交
454
        (_, input_dict), = input_dicts.items()
T
TeslaZhao 已提交
455
        return input_dict, False, None, ""
B
barrierye 已提交
456

457
    def process(self, feed_batch, typical_logid=0):
T
TeslaZhao 已提交
458 459 460 461 462
        """
        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
463 464
            typical_logid: mark batch predicts, usually the first logid in batch,
                0 default.
T
TeslaZhao 已提交
465 466 467 468

        Returns:
            call_result: predict result
        """
B
bug fix  
barriery 已提交
469
        err, err_info = ChannelData.check_batch_npdata(feed_batch)
B
barrierye 已提交
470
        if err != 0:
471
            _LOGGER.critical(
B
barriery 已提交
472 473
                self._log("Failed to run process: {}. Please override "
                          "preprocess func.".format(err_info)))
474
            os._exit(-1)
W
wangjiawei04 已提交
475 476 477
        if self.client_type == "local_predictor":
            call_result = self.client.predict(
                feed=feed_batch[0],
W
wangjiawei04 已提交
478
                fetch=self._fetch_names,
W
wangjiawei04 已提交
479 480 481 482 483
                batch=True,
                log_id=typical_logid)
        else:
            call_result = self.client.predict(
                feed=feed_batch,
W
wangjiawei04 已提交
484
                fetch=self._fetch_names,
W
wangjiawei04 已提交
485 486
                batch=True,
                log_id=typical_logid)
B
barriery 已提交
487 488 489 490
        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")
491 492
        return call_result

T
TeslaZhao 已提交
493
    def postprocess(self, input_data, fetch_data, log_id=0):
T
TeslaZhao 已提交
494 495 496
        """
        In postprocess stage, assemble data for next op or output.
        Args:
T
TeslaZhao 已提交
497 498
            input_data: data returned in preprocess stage, dict(for single predict) or list(for batch predict)
            fetch_data: data returned in process stage, dict(for single predict) or list(for batch predict)
499
            log_id: logid, 0 default
T
TeslaZhao 已提交
500 501

        Returns: 
T
TeslaZhao 已提交
502
            fetch_dict: fetch result must be dict type.
T
TeslaZhao 已提交
503 504 505 506
            prod_errcode: None default, otherwise, product errores occured.
                          It is handled in the same way as exception.
            prod_errinfo: "" default
        """
T
TeslaZhao 已提交
507 508 509
        fetch_dict = {}
        if isinstance(fetch_data, dict):
            fetch_dict = fetch_data
T
TeslaZhao 已提交
510
        return fetch_dict, None, ""
D
dongdaxiang 已提交
511

B
barrierye 已提交
512
    def _parse_channeldata(self, channeldata_dict):
T
TeslaZhao 已提交
513 514 515 516 517 518 519 520 521 522 523 524 525
        """
        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 
        """
526
        data_id, error_channeldata = None, None
B
barrierye 已提交
527
        client_need_profile, profile_set = False, set()
B
barrierye 已提交
528 529 530 531
        parsed_data = {}

        key = list(channeldata_dict.keys())[0]
        data_id = channeldata_dict[key].id
T
TeslaZhao 已提交
532
        log_id = channeldata_dict[key].log_id
B
barrierye 已提交
533
        client_need_profile = channeldata_dict[key].client_need_profile
B
barrierye 已提交
534 535

        for name, data in channeldata_dict.items():
T
TeslaZhao 已提交
536
            if data.error_code != ChannelDataErrcode.OK.value:
B
barrierye 已提交
537 538 539
                error_channeldata = data
                break
            parsed_data[name] = data.parse()
B
barrierye 已提交
540
            if client_need_profile:
B
barrierye 已提交
541
                profile_set |= data.profile_data_set
B
barrierye 已提交
542
        return (data_id, error_channeldata, parsed_data, client_need_profile,
T
TeslaZhao 已提交
543
                profile_set, log_id)
B
barrierye 已提交
544 545 546 547 548

    def _push_to_output_channels(self,
                                 data,
                                 channels,
                                 name=None,
B
barriery 已提交
549
                                 profile_str=None,
B
barrierye 已提交
550
                                 client_need_profile=False,
B
barrierye 已提交
551
                                 profile_set=None):
T
TeslaZhao 已提交
552 553 554 555 556 557 558 559 560 561 562 563 564 565
        """
        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
        """
566 567
        if name is None:
            name = self.name
B
barrierye 已提交
568

B
barriery 已提交
569
        # add profile into channeldata
B
barrierye 已提交
570
        if client_need_profile and profile_set is not None:
B
barriery 已提交
571 572
            if profile_str is not None:
                profile_set.add(profile_str)
B
barrierye 已提交
573
            data.add_profile(profile_set)
B
barrierye 已提交
574

B
barriery 已提交
575 576 577
        for channel in channels:
            channel.push(data, name)

W
wangjiawei04 已提交
578
    def start_with_process(self):
579 580 581 582 583 584 585 586 587 588
        """
        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 已提交
589 590 591
        trace_buffer = None
        if self._tracer is not None:
            trace_buffer = self._tracer.data_buffer()
W
wangjiawei04 已提交
592
        process = []
B
barrierye 已提交
593
        for concurrency_idx in range(self.concurrency):
594 595
            p = multiprocessing.Process(
                target=self._run,
B
barrierye 已提交
596
                args=(concurrency_idx, self._get_input_channel(),
597 598
                      self._get_output_channels(), False, trace_buffer,
                      self.model_config, self.workdir, self.thread_num,
599
                      self.device_type, self.devices, self.mem_optim,
T
TeslaZhao 已提交
600 601 602
                      self.ir_optim, self.precision, self.use_mkldnn,
                      self.mkldnn_cache_capacity, self.mkldnn_op_list,
                      self.mkldnn_bf16_op_list))
B
barriery 已提交
603
            p.daemon = True
604
            p.start()
W
wangjiawei04 已提交
605 606
            process.append(p)
        return process
607

W
wangjiawei04 已提交
608
    def start_with_thread(self):
609 610 611 612 613 614 615 616 617 618
        """
        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 已提交
619 620 621
        trace_buffer = None
        if self._tracer is not None:
            trace_buffer = self._tracer.data_buffer()
622 623 624 625

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

628
        threads = []
B
barrierye 已提交
629
        for concurrency_idx in range(self.concurrency):
630 631
            t = threading.Thread(
                target=self._run,
B
barrierye 已提交
632
                args=(concurrency_idx, self._get_input_channel(),
633 634
                      self._get_output_channels(), True, trace_buffer,
                      self.model_config, self.workdir, self.thread_num,
635
                      self.device_type, self.devices, self.mem_optim,
T
TeslaZhao 已提交
636 637 638
                      self.ir_optim, self.precision, self.use_mkldnn,
                      self.mkldnn_cache_capacity, self.mkldnn_op_list,
                      self.mkldnn_bf16_op_list))
B
barriery 已提交
639 640 641
            # When a process exits, it attempts to terminate
            # all of its daemonic child processes.
            t.daemon = True
642 643 644 645
            t.start()
            threads.append(t)
        return threads

B
barrierye 已提交
646
    def init_op(self):
B
barrierye 已提交
647 648
        pass

T
TeslaZhao 已提交
649 650 651 652 653 654 655 656 657 658 659 660 661 662
    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 已提交
663
        _LOGGER.debug("{} Running preprocess".format(op_info_prefix))
664 665
        preped_data_dict = collections.OrderedDict()
        err_channeldata_dict = collections.OrderedDict()
T
TeslaZhao 已提交
666
        skip_process_dict = {}
667 668
        for data_id, parsed_data in parsed_data_dict.items():
            preped_data, error_channeldata = None, None
T
TeslaZhao 已提交
669 670 671
            is_skip_process = False
            prod_errcode, prod_errinfo = None, None
            log_id = logid_dict.get(data_id)
672
            try:
T
TeslaZhao 已提交
673 674 675 676 677
                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
678 679
            except TypeError as e:
                # Error type in channeldata.datatype
T
TeslaZhao 已提交
680 681
                error_info = "(data_id={} log_id={}) {} Failed to preprocess: {}".format(
                    data_id, log_id, op_info_prefix, e)
B
barriery 已提交
682
                _LOGGER.error(error_info, exc_info=True)
683
                error_channeldata = ChannelData(
T
TeslaZhao 已提交
684
                    error_code=ChannelDataErrcode.TYPE_ERROR.value,
685
                    error_info=error_info,
T
TeslaZhao 已提交
686 687
                    data_id=data_id,
                    log_id=log_id)
688
            except Exception as e:
T
TeslaZhao 已提交
689 690
                error_info = "(data_id={} log_id={}) {} Failed to preprocess: {}".format(
                    data_id, log_id, op_info_prefix, e)
B
barriery 已提交
691
                _LOGGER.error(error_info, exc_info=True)
692
                error_channeldata = ChannelData(
T
TeslaZhao 已提交
693
                    error_code=ChannelDataErrcode.UNKNOW.value,
694
                    error_info=error_info,
T
TeslaZhao 已提交
695 696 697 698 699 700 701 702 703 704 705 706 707
                    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)

708 709 710 711
            if error_channeldata is not None:
                err_channeldata_dict[data_id] = error_channeldata
            else:
                preped_data_dict[data_id] = preped_data
B
barriery 已提交
712
        _LOGGER.debug("{} Succ preprocess".format(op_info_prefix))
T
TeslaZhao 已提交
713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728
        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 已提交
729
        _LOGGER.debug("{} Running process".format(op_info_prefix))
730 731
        midped_data_dict = collections.OrderedDict()
        err_channeldata_dict = collections.OrderedDict()
T
TeslaZhao 已提交
732
        is_skip_process = False
T
TeslaZhao 已提交
733
        data_ids = list(preped_data_dict.keys())
T
TeslaZhao 已提交
734 735

        # skip process stage
T
TeslaZhao 已提交
736 737
        if len(data_ids) == 1 and skip_process_dict.get(data_ids[0]) == True:
            is_skip_process = True
T
TeslaZhao 已提交
738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772
        if self.with_serving is False or is_skip_process is True:
            midped_data_dict = preped_data_dict
            _LOGGER.warning("(data_id={} log_id={}) OP={} skip process stage. " \
                "with_serving={}, is_skip_process={}".format(data_ids[0],
                logid_dict.get(data_ids[0]), self.name, self.with_serving,
                is_skip_process))
            return midped_data_dict, err_channeldata_dict

        # use typical_logid to mark batch data
        # data_ids is one self-increasing unique key. 
        typical_logid = data_ids[0]
        if len(data_ids) != 1:
            for data_id in data_ids:
                _LOGGER.info(
                    "(data_id={} logid={}) Auto-batching is On Op={}!!" \
                    "We selected logid={} (from batch: {}) as a " \
                    "representative for logging.".format(
                    data_id, logid_dict.get(data_id), self.name,
                    typical_logid, data_ids))

        one_input = preped_data_dict[data_ids[0]]
        feed_batch = []
        feed_dict = {}
        cur_offset = 0
        input_offset_dict = {}
        batch_input = False

        if isinstance(one_input, dict):
            # For dict type, data structure is dict.
            # Merge multiple dicts for data_ids into one dict.
            # feed_batch is the input param of predict func.
            # input_offset_dict is used for data restration[data_ids]
            if len(data_ids) == 1:
                feed_batch = [preped_data_dict[data_id] for data_id in data_ids]
            else:
773 774
                for data_id in data_ids:
                    for key, val in preped_data_dict[data_id].items():
T
TeslaZhao 已提交
775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819
                        has_val = feed_dict.get(key)
                        if has_val is None:
                            feed_dict[key] = val
                            continue
                        # merge 2 np.arrray
                        if isinstance(val, np.ndarray):
                            feed_dict[key] = np.append(
                                feed_dict[key], val, axis=0)
                feed_batch.append(feed_dict)

            for data_id in data_ids:
                start = cur_offset
                for key, val in preped_data_dict[data_id].items():
                    if isinstance(val, (list, np.ndarray)):
                        cur_offset += len(val)
                    else:
                        cur_offset += 1
                    break
                input_offset_dict[data_id] = [start, cur_offset]
        elif isinstance(one_input, list):
            # For list type, data structure of one_input is [dict, dict, ...]
            # Data structure of feed_batch is [dict1_1, dict1_2, dict2_1, ...]   
            # Data structure of input_offset_dict is { data_id : [start, end] }
            batch_input = True
            for data_id in data_ids:
                feed_batch.extend(preped_data_dict[data_id])
                data_size = len(preped_data_dict[data_id])
                start = cur_offset
                cur_offset = start + data_size
                input_offset_dict[data_id] = [start, cur_offset]
        else:
            _LOGGER.critical(
                "(data_id={} log_id={}){} Failed to process: expect input type is dict"
                " or list(batch input), but get {}".format(data_ids[
                    0], typical_logid, op_info_prefix, type(one_input)))
            for data_id in data_ids:
                error_code = ChannelDataErrcode.TYPE_ERROR.value
                error_info = "expect input type is dict or list, but get {}".format(
                    type(one_input))
                err_channeldata_dict[data_id] = ChannelData(
                    error_code=error_code,
                    error_info=error_info,
                    data_id=data_id,
                    log_id=logid_dict.get(data_id))
            return midped_data_dict, err_channeldata_dict
B
barrierye 已提交
820

T
TeslaZhao 已提交
821 822 823 824 825 826
        midped_batch = None
        error_code = ChannelDataErrcode.OK.value
        if self._timeout <= 0:
            # No retry
            try:
                if batch_input is False:
B
barriery 已提交
827
                    midped_batch = self.process(feed_batch, typical_logid)
T
TeslaZhao 已提交
828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844
                else:
                    midped_batch = []
                    for idx in range(len(feed_batch)):
                        predict_res = self.process([feed_batch[idx]],
                                                   typical_logid)
                        midped_batch.append(predict_res)
            except Exception as e:
                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)
                _LOGGER.error(error_info, exc_info=True)
        else:
            # retry N times configed in yaml files.
            for i in range(self._retry):
                try:
                    # time out for each process
                    if batch_input is False:
845
                        midped_batch = func_timeout.func_timeout(
B
barriery 已提交
846 847 848
                            self._timeout,
                            self.process,
                            args=(feed_batch, typical_logid))
849
                    else:
T
TeslaZhao 已提交
850 851 852 853 854 855 856 857 858 859 860 861 862 863
                        midped_batch = []
                        for idx in range(len(feed_batch)):
                            predict_res = func_timeout.func_timeout(
                                self._timeout,
                                self.process,
                                args=([feed_batch[idx]], typical_logid))
                            midped_batch[idx].append(predict_res)

                except func_timeout.FunctionTimedOut as e:
                    if i + 1 >= self._retry:
                        error_code = ChannelDataErrcode.TIMEOUT.value
                        error_info = "(log_id={}) {} Failed to process(batch: {}): " \
                            "exceeded retry count.".format(typical_logid, op_info_prefix, data_ids)
                        _LOGGER.error(error_info)
B
barrierye 已提交
864
                    else:
T
TeslaZhao 已提交
865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930
                        _LOGGER.warning(
                            "(log_id={}) {} Failed to process(batch: {}): timeout,"
                            " and retrying({}/{})...".format(
                                typical_logid, op_info_prefix, data_ids, i + 1,
                                self._retry))
                except Exception as e:
                    error_code = ChannelDataErrcode.UNKNOW.value
                    error_info = "(log_id={}) {} Failed to process(batch: {}): {}".format(
                        typical_logid, op_info_prefix, data_ids, e)
                    _LOGGER.error(error_info, exc_info=True)
                    break
                else:
                    break

        # 2 kinds of errors
        if error_code != ChannelDataErrcode.OK.value or midped_batch is None:
            error_info = "(log_id={}) {} failed to predict.".format(
                typical_logid, self.name)
            _LOGGER.error(error_info)
            for data_id in data_ids:
                err_channeldata_dict[data_id] = ChannelData(
                    error_code=ChannelDataErrcode.CLIENT_ERROR.value,
                    error_info=error_info,
                    data_id=data_id,
                    log_id=logid_dict.get(data_id))
            return midped_data_dict, err_channeldata_dict

        # Split batch infer result to each data_ids
        if batch_input is False:
            var_names = midped_batch.keys()
            lod_var_names = set()
            lod_offset_names = set()
            # midped_batch is dict type for single input 
            for name in var_names:
                lod_offset_name = "{}.lod".format(name)
                if lod_offset_name in var_names:
                    _LOGGER.debug("(log_id={}) {} {} is LodTensor".format(
                        typical_logid, op_info_prefix, name))
                    lod_var_names.add(name)
                    lod_offset_names.add(lod_offset_name)

            for idx, data_id in enumerate(data_ids):
                midped_data_dict[data_id] = {}

            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)
                    lod_offset = midped_batch[lod_offset_name]
                    for idx, data_id in enumerate(data_ids):
                        data_offset_left = input_offset_dict[data_id][0]
                        data_offset_right = input_offset_dict[data_id][1]
                        lod_offset_left = lod_offset[data_offset_left]
                        lod_offset_right = lod_offset[data_offset_right]
                        midped_data_dict[data_id][name] = value[
                            lod_offset_left:lod_offset_right]
                        midped_data_dict[data_id][lod_offset_name] = \
                            lod_offset[data_offset_left:data_offset_right + 1] - lod_offset[data_offset_left]
                else:
                    # normal tensor
                    for idx, data_id in enumerate(data_ids):
                        start = input_offset_dict[data_id][0]
                        end = input_offset_dict[data_id][1]
                        midped_data_dict[data_id][name] = value[start:end]
931
        else:
T
TeslaZhao 已提交
932 933 934 935 936
            # midped_batch is list type for batch input
            for idx, data_id in enumerate(data_ids):
                start = input_offset_dict[data_id][0]
                end = input_offset_dict[data_id][1]
                midped_data_dict[data_id] = midped_batch[start:end]
937 938
        return midped_data_dict, err_channeldata_dict

B
barriery 已提交
939
    def _run_postprocess(self, parsed_data_dict, midped_data_dict,
T
TeslaZhao 已提交
940 941 942 943 944 945 946 947 948 949 950 951 952 953
                         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 已提交
954
        _LOGGER.debug("{} Running postprocess".format(op_info_prefix))
955 956
        postped_data_dict = collections.OrderedDict()
        err_channeldata_dict = collections.OrderedDict()
B
bug fix  
barriery 已提交
957
        for data_id, midped_data in midped_data_dict.items():
T
TeslaZhao 已提交
958
            log_id = logid_dict.get(data_id)
959
            postped_data, err_channeldata = None, None
T
TeslaZhao 已提交
960
            prod_errcode, prod_errinfo = None, None
961
            try:
T
TeslaZhao 已提交
962 963 964
                postped_data, prod_errcode, prod_errinfo = self.postprocess(
                    parsed_data_dict[data_id], midped_data,
                    logid_dict.get(data_id))
965
            except Exception as e:
T
TeslaZhao 已提交
966 967
                error_info = "(data_id={} log_id={}) {} Failed to postprocess: {}".format(
                    data_id, log_id, op_info_prefix, e)
B
barriery 已提交
968
                _LOGGER.error(error_info, exc_info=True)
969
                err_channeldata = ChannelData(
T
TeslaZhao 已提交
970
                    error_code=ChannelDataErrcode.UNKNOW.value,
971
                    error_info=error_info,
T
TeslaZhao 已提交
972 973 974 975 976 977 978 979 980 981 982 983 984
                    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)

985 986 987 988 989
            if err_channeldata is not None:
                err_channeldata_dict[data_id] = err_channeldata
                continue
            else:
                if not isinstance(postped_data, dict):
T
TeslaZhao 已提交
990
                    error_info = "(log_id={} log_id={}) {} Failed to postprocess: " \
B
barriery 已提交
991 992
                            "output of postprocess funticon must be " \
                            "dict type, but get {}".format(
T
TeslaZhao 已提交
993
                                data_id, log_id, op_info_prefix,
B
barriery 已提交
994
                                type(postped_data))
995 996
                    _LOGGER.error(error_info)
                    err_channeldata = ChannelData(
T
TeslaZhao 已提交
997
                        error_code=ChannelDataErrcode.UNKNOW.value,
998
                        error_info=error_info,
T
TeslaZhao 已提交
999 1000
                        data_id=data_id,
                        log_id=log_id)
1001 1002 1003 1004 1005 1006 1007 1008 1009
                    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 已提交
1010 1011
                        data_id=data_id,
                        log_id=log_id)
1012 1013 1014 1015
                else:
                    output_data = ChannelData(
                        ChannelDataType.DICT.value,
                        dictdata=postped_data,
T
TeslaZhao 已提交
1016 1017
                        data_id=data_id,
                        log_id=log_id)
1018
                postped_data_dict[data_id] = output_data
B
barriery 已提交
1019
        _LOGGER.debug("{} Succ postprocess".format(op_info_prefix))
1020
        return postped_data_dict, err_channeldata_dict
B
barriery 已提交
1021 1022

    def _auto_batching_generator(self, input_channel, op_name, batch_size,
B
barriery 已提交
1023
                                 timeout, op_info_prefix):
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
        """
        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 已提交
1040 1041 1042 1043 1044 1045 1046 1047 1048
        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
1049
                        front_start_time = int(round(_time() * 1000000))
B
barriery 已提交
1050 1051 1052
                        if timeout is not None:
                            remaining = endtime - _time()
                            if remaining <= 0.0:
B
barriery 已提交
1053 1054
                                _LOGGER.debug("{} Failed to generate batch: "
                                              "timeout".format(op_info_prefix))
B
barriery 已提交
1055
                                break
B
barriery 已提交
1056 1057
                            channeldata_dict = input_channel.front(op_name,
                                                                   timeout)
B
barriery 已提交
1058 1059 1060
                        else:
                            channeldata_dict = input_channel.front(op_name)
                        batch.append(channeldata_dict)
1061
                        _LOGGER.debug(
1062 1063
                            "_auto_batching_generator get {} channeldata from op:{} input channel. time={}".
                            format(idx, op_name, front_start_time))
B
barriery 已提交
1064
                    except ChannelTimeoutError:
B
barriery 已提交
1065 1066
                        _LOGGER.debug("{} Failed to generate batch: "
                                      "timeout".format(op_info_prefix))
B
barriery 已提交
1067
                        break
B
barriery 已提交
1068 1069
            _LOGGER.debug("{} Got actual batch_size: {}".format(op_info_prefix,
                                                                len(batch)))
B
barriery 已提交
1070
            yield batch
1071

1072
    def _parse_channeldata_batch(self, batch, output_channels):
T
TeslaZhao 已提交
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084
        """
        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
        """
1085
        parsed_data_dict = collections.OrderedDict()
1086 1087
        need_profile_dict = {}
        profile_dict = {}
T
TeslaZhao 已提交
1088
        logid_dict = {}
B
bug fix  
barriery 已提交
1089
        for channeldata_dict in batch:
1090
            (data_id, error_channeldata, parsed_data,
T
TeslaZhao 已提交
1091
                    client_need_profile, profile_set, log_id) = \
1092 1093 1094 1095 1096
                            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 已提交
1097
                logid_dict[data_id] = log_id
1098 1099 1100
            else:
                # error data in predecessor Op
                # (error_channeldata with profile info)
B
barriery 已提交
1101 1102
                self._push_to_output_channels(error_channeldata,
                                              output_channels)
1103

T
TeslaZhao 已提交
1104
        return parsed_data_dict, need_profile_dict, profile_dict, logid_dict
B
barriery 已提交
1105

W
wangjiawei04 已提交
1106
    def _run(self, concurrency_idx, input_channel, output_channels,
1107
             is_thread_op, trace_buffer, model_config, workdir, thread_num,
T
TeslaZhao 已提交
1108 1109
             device_type, devices, mem_optim, ir_optim, precision, use_mkldnn,
             mkldnn_cache_capacity, mkldnn_op_list, mkldnn_bf16_op_list):
1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126
        """
        _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
1127
            device_type: support multiple devices
1128 1129
            devices: gpu id list[gpu], "" default[cpu]
            mem_optim: use memory/graphics memory optimization, True default.
1130
            ir_optim: use calculation chart optimization, False default.
T
TeslaZhao 已提交
1131 1132 1133 1134 1135
            precision: inference precision, e.g. "fp32", "fp16", "int8", "bf16"
            use_mkldnn: use mkldnn, default False.
            mkldnn_cache_capacity: cache capacity of mkldnn, 0 means no limit.
            mkldnn_op_list: OP list optimized by mkldnn, None default.
            mkldnn_bf16_op_list: OP list optimized by mkldnn bf16, None default.
1136 1137 1138 1139

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

1142
        # init ops
B
barriery 已提交
1143
        profiler = None
B
barrierye 已提交
1144
        try:
1145 1146 1147 1148 1149 1150
            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,
1151
                    device_type=device_type,
1152 1153
                    devices=devices,
                    mem_optim=mem_optim,
1154
                    ir_optim=ir_optim,
T
TeslaZhao 已提交
1155 1156 1157 1158 1159
                    precision=precision,
                    use_mkldnn=use_mkldnn,
                    mkldnn_cache_capacity=mkldnn_cache_capacity,
                    mkldnn_op_list=mkldnn_op_list,
                    mkldnn_bf16_op_list=mkldnn_bf16_op_list)
1160 1161 1162

                _LOGGER.info("Init cuda env in process {}".format(
                    concurrency_idx))
1163 1164
                self.local_predictor = self.service_handler.get_client(
                    concurrency_idx)
1165
            # check all ops initialized successfully.
W
wangjiawei04 已提交
1166
            profiler = self._initialize(is_thread_op, concurrency_idx)
1167

B
barrierye 已提交
1168
        except Exception as e:
B
barriery 已提交
1169
            _LOGGER.critical(
T
TeslaZhao 已提交
1170
                "{} failed to init op: {}".format(op_info_prefix, e),
B
barriery 已提交
1171
                exc_info=True)
B
barrierye 已提交
1172
            os._exit(-1)
B
barriery 已提交
1173
        _LOGGER.info("{} Succ init".format(op_info_prefix))
1174

B
barriery 已提交
1175
        batch_generator = self._auto_batching_generator(
B
barriery 已提交
1176 1177 1178 1179
            input_channel=input_channel,
            op_name=self.name,
            batch_size=self._batch_size,
            timeout=self._auto_batching_timeout,
B
barriery 已提交
1180
            op_info_prefix=op_info_prefix)
B
barriery 已提交
1181

B
barriery 已提交
1182
        start, end = None, None
B
barrierye 已提交
1183
        trace_que = collections.deque()
B
barrierye 已提交
1184
        while True:
B
barriery 已提交
1185
            start = int(round(_time() * 1000000))
B
barrierye 已提交
1186
            try:
B
barriery 已提交
1187
                channeldata_dict_batch = next(batch_generator)
B
barrierye 已提交
1188
            except ChannelStopError:
B
barriery 已提交
1189
                _LOGGER.debug("{} Stop.".format(op_info_prefix))
B
barriery 已提交
1190
                self._finalize(is_thread_op)
B
barrierye 已提交
1191
                break
B
barriery 已提交
1192
            end = int(round(_time() * 1000000))
B
barrierye 已提交
1193
            in_time = end - start
1194

B
barriery 已提交
1195 1196
            # parse channeldata batch
            try:
T
TeslaZhao 已提交
1197
                parsed_data_dict, need_profile_dict, profile_dict, logid_dict\
1198 1199
                        = self._parse_channeldata_batch(
                                channeldata_dict_batch, output_channels)
B
barriery 已提交
1200
            except ChannelStopError:
B
barriery 已提交
1201
                _LOGGER.debug("{} Stop.".format(op_info_prefix))
1202
                self._finalize(is_thread_op)
B
barriery 已提交
1203
                break
1204 1205 1206
            if len(parsed_data_dict) == 0:
                # data in the whole batch is all error data
                continue
1207

1208 1209 1210 1211 1212 1213 1214
            # print
            front_cost = int(round(_time() * 1000000)) - start
            for data_id, parsed_data in parsed_data_dict.items():
                _LOGGER.debug(
                    "(data_id={}) POP INPUT CHANNEL! op:{}, cost:{} ms".format(
                        data_id, self.name, front_cost / 1000.0))

1215
            # preprecess
B
barriery 已提交
1216
            start = profiler.record("prep#{}_0".format(op_info_prefix))
T
TeslaZhao 已提交
1217 1218
            preped_data_dict, err_channeldata_dict, skip_process_dict \
                    = self._run_preprocess(parsed_data_dict, op_info_prefix, logid_dict)
B
barriery 已提交
1219
            end = profiler.record("prep#{}_1".format(op_info_prefix))
B
barrierye 已提交
1220
            prep_time = end - start
1221
            try:
T
TeslaZhao 已提交
1222
                # put error requests into output channel, skip process and postprocess stage
1223
                for data_id, err_channeldata in err_channeldata_dict.items():
B
barrierye 已提交
1224
                    self._push_to_output_channels(
B
barriery 已提交
1225 1226
                        data=err_channeldata,
                        channels=output_channels,
1227 1228 1229
                        client_need_profile=need_profile_dict[data_id],
                        profile_set=profile_dict[data_id])
            except ChannelStopError:
B
barriery 已提交
1230
                _LOGGER.debug("{} Stop.".format(op_info_prefix))
1231 1232
                self._finalize(is_thread_op)
                break
B
bug fix  
barrierye 已提交
1233
            if len(preped_data_dict) == 0:
1234 1235
                continue

B
barrierye 已提交
1236
            # process
B
barriery 已提交
1237
            start = profiler.record("midp#{}_0".format(op_info_prefix))
1238
            midped_data_dict, err_channeldata_dict \
T
TeslaZhao 已提交
1239
                    = self._run_process(preped_data_dict, op_info_prefix, skip_process_dict, logid_dict)
B
barriery 已提交
1240
            end = profiler.record("midp#{}_1".format(op_info_prefix))
B
barrierye 已提交
1241
            midp_time = end - start
1242 1243
            try:
                for data_id, err_channeldata in err_channeldata_dict.items():
B
barrierye 已提交
1244
                    self._push_to_output_channels(
B
barriery 已提交
1245 1246
                        data=err_channeldata,
                        channels=output_channels,
B
barriery 已提交
1247 1248
                        client_need_profile=need_profile_dict[data_id],
                        profile_set=profile_dict[data_id])
1249
            except ChannelStopError:
B
barriery 已提交
1250
                _LOGGER.debug("{} Stop.".format(op_info_prefix))
1251 1252 1253
                self._finalize(is_thread_op)
                break
            if len(midped_data_dict) == 0:
1254
                continue
1255 1256

            # postprocess
B
barriery 已提交
1257
            start = profiler.record("postp#{}_0".format(op_info_prefix))
1258
            postped_data_dict, err_channeldata_dict \
T
TeslaZhao 已提交
1259
                    = self._run_postprocess(parsed_data_dict, midped_data_dict, op_info_prefix, logid_dict)
B
barriery 已提交
1260
            end = profiler.record("postp#{}_1".format(op_info_prefix))
B
barrierye 已提交
1261
            postp_time = end - start
1262
            after_postp_time = _time()
1263 1264
            try:
                for data_id, err_channeldata in err_channeldata_dict.items():
B
barrierye 已提交
1265
                    self._push_to_output_channels(
B
bug fix  
barrierye 已提交
1266
                        data=err_channeldata,
B
barriery 已提交
1267
                        channels=output_channels,
B
barriery 已提交
1268 1269
                        client_need_profile=need_profile_dict[data_id],
                        profile_set=profile_dict[data_id])
1270
            except ChannelStopError:
B
barriery 已提交
1271
                _LOGGER.debug("{} Stop.".format(op_info_prefix))
1272 1273 1274
                self._finalize(is_thread_op)
                break
            if len(postped_data_dict) == 0:
1275
                continue
1276
            # push data to channel (if run succ)
B
barriery 已提交
1277
            start = int(round(_time() * 1000000))
B
barrierye 已提交
1278
            try:
B
barriery 已提交
1279
                profile_str = profiler.gen_profile_str()
1280
                for data_id, postped_data in postped_data_dict.items():
B
barriery 已提交
1281 1282
                    if self._server_use_profile:
                        sys.stderr.write(profile_str)
1283
                    self._push_to_output_channels(
B
barriery 已提交
1284 1285 1286
                        data=postped_data,
                        channels=output_channels,
                        profile_str=profile_str,
B
barriery 已提交
1287 1288
                        client_need_profile=need_profile_dict[data_id],
                        profile_set=profile_dict[data_id])
1289 1290 1291 1292 1293 1294 1295 1296
                    after_outchannel_time = _time()
                    _LOGGER.debug(
                        "(data_id={}) PUSH OUTPUT CHANNEL! op:{} push cost:{} ms".
                        format(data_id, self.name, (after_outchannel_time -
                                                    after_postp_time) * 1000))
                    _LOGGER.debug(
                        "(data_id={}) PUSH OUTPUT CHANNEL! op:{} push data:{}".
                        format(data_id, self.name, postped_data.get_all_data()))
B
barrierye 已提交
1297
            except ChannelStopError:
B
barriery 已提交
1298
                _LOGGER.debug("{} Stop.".format(op_info_prefix))
1299
                self._finalize(is_thread_op)
B
barrierye 已提交
1300
                break
B
barriery 已提交
1301
            end = int(round(_time() * 1000000))
B
barrierye 已提交
1302
            out_time = end - start
1303
            after_outchannel_time = int(round(_time() * 1000000))
B
barriery 已提交
1304
            if trace_buffer is not None:
B
barrierye 已提交
1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321
                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 已提交
1322

W
wangjiawei04 已提交
1323
    def _initialize(self, is_thread_op, concurrency_idx):
1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336
        """
        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 已提交
1337 1338 1339 1340 1341 1342
        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 已提交
1343
                    self.client = self.init_client(self._client_config,
W
wangjiawei04 已提交
1344
                                                   self._server_endpoints)
B
barriery 已提交
1345 1346 1347 1348
                    # user defined
                    self.init_op()
                    self._succ_init_op = True
                    self._succ_close_op = False
B
bug fix  
barriery 已提交
1349 1350 1351
        else:
            self.concurrency_idx = concurrency_idx
            # init client
W
wangjiawei04 已提交
1352 1353
            self.client = self.init_client(self._client_config,
                                           self._server_endpoints)
B
bug fix  
barriery 已提交
1354 1355
            # user defined
            self.init_op()
B
barriery 已提交
1356

B
barriery 已提交
1357 1358 1359 1360 1361
        # use a separate TimeProfiler per thread or process
        profiler = TimeProfiler()
        profiler.enable(True)
        return profiler

B
barriery 已提交
1362 1363 1364 1365 1366 1367 1368 1369
    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
1370 1371 1372 1373 1374

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


B
barrierye 已提交
1375
class RequestOp(Op):
1376 1377 1378 1379 1380 1381
    """
    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 已提交
1382

B
barrierye 已提交
1383
    def __init__(self):
1384 1385 1386
        """
        Initialize the RequestOp
        """
B
barriery 已提交
1387 1388
        # PipelineService.name = "@DAGExecutor"
        super(RequestOp, self).__init__(name="@DAGExecutor", input_ops=[])
B
barrierye 已提交
1389
        # init op
1390
        try:
1391
            self.init_op()
1392
        except Exception as e:
B
barriery 已提交
1393
            _LOGGER.critical("Op(Request) Failed to init: {}".format(e))
1394
            os._exit(-1)
B
barrierye 已提交
1395 1396

    def unpack_request_package(self, request):
T
TeslaZhao 已提交
1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414
        """
        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")
1415 1416

        for idx, key in enumerate(request.key):
1417
            dict_data[key] = request.value[idx]
T
TeslaZhao 已提交
1418
        log_id = request.logid
1419 1420 1421
        _LOGGER.info("RequestOp unpack one request. log_id:{}, clientip:{} \
            name:{}, method:{}".format(log_id, request.clientip, request.name,
                                       request.method))
T
TeslaZhao 已提交
1422 1423

        return dict_data, log_id, None, ""
B
barrierye 已提交
1424 1425 1426


class ResponseOp(Op):
1427 1428 1429 1430 1431 1432
    """ 
    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 已提交
1433

B
barrierye 已提交
1434
    def __init__(self, input_ops):
1435 1436 1437
        """
        Initialize the ResponseOp
        """
B
barriery 已提交
1438 1439
        super(ResponseOp, self).__init__(
            name="@DAGExecutor", input_ops=input_ops)
B
barrierye 已提交
1440
        # init op
1441
        try:
1442
            self.init_op()
1443
        except Exception as e:
B
barriery 已提交
1444 1445
            _LOGGER.critical("Op(ResponseOp) Failed to init: {}".format(
                e, exc_info=True))
1446
            os._exit(-1)
B
barrierye 已提交
1447 1448

    def pack_response_package(self, channeldata):
T
TeslaZhao 已提交
1449
        """
1450 1451 1452 1453 1454 1455 1456 1457
        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 已提交
1458
        """
B
barrierye 已提交
1459
        resp = pipeline_service_pb2.Response()
T
TeslaZhao 已提交
1460 1461 1462
        error_code = channeldata.error_code
        error_info = ""
        if error_code == ChannelDataErrcode.OK.value:
1463
            # Framework level errors
B
barrierye 已提交
1464 1465 1466 1467
            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 已提交
1468
                np.set_printoptions(threshold=sys.maxsize)
B
barrierye 已提交
1469
                for name, var in feed.items():
1470 1471
                    resp.value.append(var.__repr__())
                    resp.key.append(name)
B
barrierye 已提交
1472 1473 1474 1475
            elif channeldata.datatype == ChannelDataType.DICT.value:
                feed = channeldata.parse()
                for name, var in feed.items():
                    if not isinstance(var, str):
T
TeslaZhao 已提交
1476 1477
                        error_code = ChannelDataErrcode.TYPE_ERROR.value
                        error_info = self._log(
B
barrierye 已提交
1478 1479
                            "fetch var type must be str({}).".format(
                                type(var)))
B
barriery 已提交
1480 1481
                        _LOGGER.error("(logid={}) Failed to pack RPC "
                                      "response package: {}".format(
W
wangjiawei04 已提交
1482
                                          channeldata.id, resp.err_msg))
B
barrierye 已提交
1483
                        break
1484 1485
                    resp.value.append(var)
                    resp.key.append(name)
B
barrierye 已提交
1486
            else:
T
TeslaZhao 已提交
1487 1488 1489
                error_code = ChannelDataErrcode.TYPE_ERROR.value
                error_info = self._log("error type({}) in datatype.".format(
                    channeldata.datatype))
B
barriery 已提交
1490
                _LOGGER.error("(logid={}) Failed to pack RPC response"
T
TeslaZhao 已提交
1491
                              " package: {}".format(channeldata.id, error_info))
B
barrierye 已提交
1492
        else:
1493
            # Product level errors
T
TeslaZhao 已提交
1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505
            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 已提交
1506
        return resp
1507 1508 1509


class VirtualOp(Op):
1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526
    """ 
    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/
    """
1527 1528 1529

    def __init__(self, name, concurrency=1):
        super(VirtualOp, self).__init__(
B
barrierye 已提交
1530
            name=name, input_ops=None, concurrency=concurrency)
1531 1532 1533
        self._virtual_pred_ops = []

    def add_virtual_pred_op(self, op):
1534 1535 1536 1537 1538 1539 1540 1541 1542
        """
        Add the front op of current vritual op.
        
        Args:
            op: one op object, may be a virtual op or not.

        Returns:
            None
        """
1543 1544
        self._virtual_pred_ops.append(op)

B
barrierye 已提交
1545
    def _actual_pred_op_names(self, op):
1546 1547 1548 1549 1550 1551 1552 1553 1554
        """
        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 已提交
1555
        # can use disjoint-set, but it's not necessary
B
barrierye 已提交
1556 1557 1558 1559 1560 1561 1562
        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

1563
    def add_output_channel(self, channel):
1564 1565 1566 1567 1568 1569 1570 1571 1572
        """
        Adding the output channel of non-virtual pred ops.

        Args:
            channel: one channel.
          
        Returns:
            None.
        """
1573
        if not isinstance(channel, (ThreadChannel, ProcessChannel)):
1574
            _LOGGER.critical(
B
barriery 已提交
1575 1576 1577
                self._log("Failed to add output_channel: output_channel"
                          " must be Channel type, not {}".format(
                              type(channel))))
1578
            os._exit(-1)
1579
        for op in self._virtual_pred_ops:
B
barrierye 已提交
1580 1581
            for op_name in self._actual_pred_op_names(op):
                channel.add_producer(op_name)
1582
        self._outputs.append(channel)
D
dongdaxiang 已提交
1583

1584
    def _run(self, concurrency_idx, input_channel, output_channels, client_type,
1585
             is_thread_op):
1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599
        """
        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
        """
1600
        op_info_prefix = "[{}|{}]".format(self.name, concurrency_idx)
B
barrierye 已提交
1601 1602 1603
        log = get_log_func(op_info_prefix)
        tid = threading.current_thread().ident

1604 1605 1606 1607 1608 1609 1610
        batch_generator = self._auto_batching_generator(
            input_channel=input_channel,
            op_name=self.name,
            batch_size=1,
            timeout=None,
            log_func=log)

B
barrierye 已提交
1611 1612
        while True:
            try:
1613
                channeldata_dict_batch = next(batch_generator)
B
barrierye 已提交
1614
            except ChannelStopError:
B
barriery 已提交
1615
                _LOGGER.debug("{} Stop.".format(op_info_prefix))
1616
                self._finalize(is_thread_op)
B
barrierye 已提交
1617
                break
D
dongdaxiang 已提交
1618

B
barrierye 已提交
1619
            try:
1620 1621 1622 1623
                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 已提交
1624
            except ChannelStopError:
B
barriery 已提交
1625
                _LOGGER.debug("{} Stop.".format(op_info_prefix))
1626
                self._finalize(is_thread_op)
B
barrierye 已提交
1627
                break