chatbot.py 28.9 KB
Newer Older
lvhan028's avatar
lvhan028 committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# Copyright (c) OpenMMLab. All rights reserved.
import json
import logging
import queue
import random
import threading
from dataclasses import dataclass
from enum import Enum
from functools import partial
from typing import List, Union

import google.protobuf.json_format
import mmengine
import numpy as np
import tritonclient.grpc as grpcclient
from tritonclient.grpc.service_pb2 import ModelInferResponse

lvhan028's avatar
lvhan028 committed
18
from lmdeploy.model import MODELS
19
20
from lmdeploy.serve.turbomind.utils import (Postprocessor, Preprocessor,
                                            prepare_tensor)
21
from lmdeploy.utils import filter_suffix
lvhan028's avatar
lvhan028 committed
22
23
24
25
26
27


@dataclass
class Session:
    session_id: Union[int, str]
    request_id: str = ''
lvhan028's avatar
lvhan028 committed
28
    histories: str = ''  # history conversations of the session
lvhan028's avatar
lvhan028 committed
29
    sequence_length: int = 0  # the total generated token number in the session
lvhan028's avatar
lvhan028 committed
30
    prompt: str = ''
lvhan028's avatar
lvhan028 committed
31
32
33
34
35
36
37
    response: str = ''
    status: int = None  # status of the session


class StatusCode(Enum):
    TRITON_STREAM_END = 0  # end of streaming
    TRITON_STREAM_ING = 1  # response is in streaming
38
    TRITON_SESSION_READY = 2  # session is ready for inference
lvhan028's avatar
lvhan028 committed
39
40
41
42
43
44
45
    TRITON_SERVER_ERR = -1  # triton server's error
    TRITON_SESSION_CLOSED = -2  # session has been closed
    TRITON_SESSION_OUT_OF_LIMIT = -3  # request length out of limit
    TRITON_SESSION_INVALID_ARG = -4  # invalid argument


def stream_callback(que, result, error):
lvhan028's avatar
lvhan028 committed
46
    """callback function invoked by triton client."""
lvhan028's avatar
lvhan028 committed
47
48
49
50
51
52
53
54
    if error:
        print(error)
        que.put(dict(errcode=StatusCode.TRITON_SERVER_ERR, errmsg=f'{error}'))
    else:
        que.put(result.get_response(as_json=True))


def get_logger(log_file=None, log_level=logging.INFO):
lvhan028's avatar
lvhan028 committed
55
    """Return the logger."""
56
    from lmdeploy.utils import get_logger
lvhan028's avatar
lvhan028 committed
57
58
59
60
61
    logger = get_logger('service.ft', log_file=log_file, log_level=log_level)
    return logger


class Chatbot:
62
    """Chatbot for LLaMA series models with turbomind as inference engine.
lvhan028's avatar
lvhan028 committed
63
64
65
66
67
68
69

    Args:
        tritonserver_addr (str): communicating address '<ip>:<port>' of
            triton inference server
        model_name (str): name of the to-be-deployed mode
        log_level (int): the level of the log
        display (bool): display the generated text on consolo or not
lvhan028's avatar
lvhan028 committed
70
        profile_generation (bool): profile token generation or not
lvhan028's avatar
lvhan028 committed
71
72
73
74
    """

    def __init__(self,
                 tritonserver_addr: str,
75
                 model_name: str = '',
lvhan028's avatar
lvhan028 committed
76
                 ignore_eos: bool = False,
lvhan028's avatar
lvhan028 committed
77
                 log_level: int = logging.INFO,
lvhan028's avatar
lvhan028 committed
78
79
                 display: bool = False,
                 profile_generation: bool = False,
80
81
                 profile_serving: bool = False,
                 **model_kwargs):
82
        self.tritonserver_addr = tritonserver_addr
83
84
85
        self.model_name = model_name
        if self.model_name == '':
            self.model_name = self._get_model_name()
86
87
        assert self.model_name in MODELS.module_dict.keys(), \
            f"'{self.model_name}' is not supported. " \
lvhan028's avatar
lvhan028 committed
88
            f'The supported models are: {MODELS.module_dict.keys()}'
89
        self.model = MODELS.get(self.model_name)(**model_kwargs)
lvhan028's avatar
lvhan028 committed
90
        self._session = None
lvhan028's avatar
lvhan028 committed
91
92
93
94
95
96
97
98
99
        self.preprocess = Preprocessor(tritonserver_addr)
        self.postprocess = Postprocessor(tritonserver_addr)
        self.bos_id = self._get_bos()
        self.eos_id = self._get_eos()
        stop_words = self._stop_words(self.model.stop_words)
        bad_words = None
        if ignore_eos:
            stop_words = None
            bad_words = np.array([[[self.eos_id], [1]]], dtype=np.int32)
lvhan028's avatar
lvhan028 committed
100
        self.cfg = mmengine.Config(
101
102
103
104
105
            dict(session_len=self.model.session_len,
                 top_p=self.model.top_p,
                 top_k=self.model.top_k,
                 temperature=self.model.temperature,
                 repetition_penalty=self.model.repetition_penalty,
lvhan028's avatar
lvhan028 committed
106
107
                 stop_words=stop_words,
                 bad_words=bad_words))
lvhan028's avatar
lvhan028 committed
108
109
        self.log_level = log_level
        self.display = display
lvhan028's avatar
lvhan028 committed
110
111
        self.profile_generation = profile_generation
        self.profile_serving = profile_serving
lvhan028's avatar
lvhan028 committed
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152

    def stream_infer(self,
                     session_id: int,
                     prompt: str,
                     request_id: str = '',
                     request_output_len: int = None,
                     sequence_start: bool = False,
                     sequence_end: bool = False,
                     *args,
                     **kwargs):
        """Start a new round conversion of a session.

        Args:
            session_id (int): the identical id of a session
            prompt (str): user's prompt in this round conversation
            request_id (str): the identical id of this round conversation
            request_output_len (int): the expected generated token numbers
            sequence_start (bool): start flag of a session
            sequence_end (bool): end flag of a session
        Returns:
            iterator: The generated content by chatbot
        """
        assert isinstance(session_id, int), \
            f'INT session id is required, but got {type(session_id)}'

        logger = get_logger(log_level=self.log_level)
        logger.info(f'session {session_id}, request_id {request_id}, '
                    f'request_output_len {request_output_len}')

        if self._session is None:
            sequence_start = True
            self._session = Session(session_id=session_id)
        elif self._session.status == 0:
            logger.error(f'session {session_id} has been ended. Please set '
                         f'`sequence_start` be True if you want to restart it')
            yield StatusCode.TRITON_SESSION_CLOSED, '', 0
            return

        self._session.status = 1
        self._session.request_id = request_id
        self._session.response = ''
Lyu Han's avatar
Lyu Han committed
153
        self.cfg.update(**kwargs)
lvhan028's avatar
lvhan028 committed
154

lvhan028's avatar
lvhan028 committed
155
156
157
        self._session.prompt = self._get_prompt(prompt, sequence_start)
        for status, res, tokens in self._stream_infer(self._session,
                                                      self._session.prompt,
lvhan028's avatar
lvhan028 committed
158
159
160
                                                      request_output_len,
                                                      sequence_start,
                                                      sequence_end):
161
162
            if status == StatusCode.TRITON_STREAM_END:  # remove stop_words
                res = filter_suffix(res, self.model.stop_words)
163
            if status.value < 0:
164
165
166
167
168
169
170
171
172
                break
            else:
                yield status, res, tokens
        if status.value == 0:
            self._session.histories = \
                self._session.histories + self._session.prompt + \
                self._session.response
        else:
            yield status, res, tokens
lvhan028's avatar
lvhan028 committed
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202

    def end(self, session_id: int, *args, **kwargs):
        """end a session. Triton inference server will release the session's
        occupied resource when it is ended.

        Args:
            session_id (int): the identical id of a session

        Returns:
            int: 0: success, -1: session not found
        """
        assert isinstance(session_id, int), \
            f'INT session id is required, but got {type(session_id)}'

        logger = get_logger(log_level=self.log_level)
        logger.info(f'end session: {session_id}')

        if self._session is None:
            logger.error(
                f"session {session_id} doesn't exist. It cannot be ended")
            return StatusCode.TRITON_SESSION_INVALID_ARG
        if self._session.session_id != session_id:
            logger.error(f'you cannot end session {session_id}, because this '
                         f'session is {self._session.session_id}')
            return StatusCode.TRITON_SESSION_INVALID_ARG
        if self._session.status == 0:
            logger.warning(f'session {session_id} has already been ended')
            return StatusCode.TRITON_SESSION_CLOSED

        self._session.status = 0
lvhan028's avatar
lvhan028 committed
203
204
205
206
207
        for status, _, _ in self._stream_infer(self._session,
                                               prompt='',
                                               request_output_len=0,
                                               sequence_start=False,
                                               sequence_end=True):
208
209
            if status.value < 0:
                break
q.yao's avatar
q.yao committed
210
211

        self.reset_session()
212
        return status
lvhan028's avatar
lvhan028 committed
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242

    def cancel(self, session_id: int, *args, **kwargs):
        """Cancel the session during generating tokens.

        Args:
            session_id (int): the identical id of a session

        Returns:
            int: 0: success, -1: session not found
        """
        assert isinstance(session_id, int), \
            f'INT session id is required, but got {type(session_id)}'
        logger = get_logger(log_level=self.log_level)
        logger.info(f'cancel session: {session_id}')

        if self._session is None:
            logger.error(
                f"session {session_id} doesn't exist. It cannot be cancelled")
            return StatusCode.TRITON_SESSION_INVALID_ARG
        if self._session.session_id != session_id:
            logger.error(
                f'you cannot cancel session {session_id}, because this '
                f'session is {self._session.session_id}')
            return StatusCode.TRITON_SESSION_INVALID_ARG
        if self._session.status == 0:
            logger.error(f'session {session_id} has already been ended. '
                         f'It cannot be cancelled')
            return StatusCode.TRITON_SESSION_CLOSED

        prev_session = self._session
243
        status, res = None, None
lvhan028's avatar
lvhan028 committed
244
245
246
247
248
249
        for status, res, _ in self._stream_infer(self._session,
                                                 prompt='',
                                                 request_output_len=0,
                                                 sequence_start=False,
                                                 sequence_end=False,
                                                 cancel=True):
lvhan028's avatar
lvhan028 committed
250
251
252
253
            if status.value < 0:
                break
        if status == StatusCode.TRITON_STREAM_END:
            logger.info(f'cancel session {session_id} successfully')
lvhan028's avatar
lvhan028 committed
254
            if prev_session.histories:
255
                logger.warning(f'TODO: start to recover session {session_id}')
lvhan028's avatar
lvhan028 committed
256
257
258
259
        else:
            logger.info(f'cancel session {session_id} failed: {res}')
        return status

260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
    def resume(self, session_id: int, *args, **kwargs):
        """Resume a session by sending the history conversations to triton
        inference server. After resuming, users can continue chatting with
        chatbot.

        Args:
            session_id (int): the identical id of a session

        Returns:
            int: 0: success, -1: session not found
        """
        assert isinstance(session_id, int), \
            f'INT session id is required, but got {type(session_id)}'

        logger = get_logger(log_level=self.log_level)
        logger.info(f'resume session: {session_id}')

        if self._session is None:
            logger.error(
                f"session {session_id} doesn't exist. It cannot be recovered")
            return StatusCode.TRITON_SESSION_INVALID_ARG
        if self._session.session_id != session_id:
            logger.error(
                f'you cannot resume session {session_id}, because this '
                f'session is {self._session.session_id}')
            return StatusCode.TRITON_SESSION_INVALID_ARG

        self._session.status = 1
        self._session.sequence_length = 0
        histories = self._session.histories
        for status, _, _ in self._stream_infer(self._session,
                                               prompt=histories,
                                               request_output_len=0,
                                               sequence_start=True,
                                               sequence_end=False):
            if status.value < 0:
296
                break
297
298
299
300

        self._session.histories = histories
        return status

301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
    def infer(self,
              session_id: int,
              prompt: str,
              request_id: str = '',
              request_output_len: int = None,
              sequence_start: bool = False,
              sequence_end: bool = False,
              *args,
              **kwargs):
        """Start a new round conversion of a session. Return the chat
        completions in non-stream mode.

        Args:
            session_id (int): the identical id of a session
            prompt (str): user's prompt in this round conversation
            request_id (str): the identical id of this round conversation
            request_output_len (int): the expected generated token numbers
            sequence_start (bool): start flag of a session
            sequence_end (bool): end flag of a session
        Returns:
            tuple(Status, str, int): status, text/chat completion,
            generated token number
        """
        assert isinstance(session_id, int), \
            f'INT session id is required, but got {type(session_id)}'

        logger = get_logger(log_level=self.log_level)
        logger.info(f'session {session_id}, request_id {request_id}, '
                    f'request_output_len {request_output_len}')

        if self._session is None:
            sequence_start = True
            self._session = Session(session_id=session_id)
        elif self._session.status == 0:
            logger.error(f'session {session_id} has been ended. Please set '
                         f'`sequence_start` be True if you want to restart it')
            return StatusCode.TRITON_SESSION_CLOSED, '', 0

        self._session.status = 1
        self._session.request_id = request_id
        self._session.response = ''

        self._session.prompt = self._get_prompt(prompt, sequence_start)
        status, res, tokens = None, '', 0
        for status, res, tokens in self._stream_infer(self._session,
                                                      self._session.prompt,
                                                      request_output_len,
                                                      sequence_start,
                                                      sequence_end):
            if status.value < 0:
                break
352
353
            if status == StatusCode.TRITON_STREAM_END:  # remove stop_words
                res = filter_suffix(res, self.model.stop_words)
354
355
356
357
358
359
360
361
        if status.value == 0:
            self._session.histories = \
                self._session.histories + self._session.prompt + \
                self._session.response
            return status, res, tokens
        else:
            return status, res, tokens

lvhan028's avatar
lvhan028 committed
362
    def reset_session(self):
lvhan028's avatar
lvhan028 committed
363
        """reset session."""
lvhan028's avatar
lvhan028 committed
364
365
        self._session = None

366
367
368
369
370
371
372
373
374
375
    @property
    def session(self):
        """get session."""
        return self._session

    @session.setter
    def session(self, value):
        """set session."""
        self._session = value

376
377
378
379
380
381
382
383
    def _get_model_name(self):
        with grpcclient.InferenceServerClient(
                self.tritonserver_addr) as client:
            model_config = client.get_model_config(model_name='turbomind',
                                                   as_json=True)
            return model_config['config']['parameters']['model_name'][
                'string_value']

lvhan028's avatar
lvhan028 committed
384
    def _get_bos(self):
lvhan028's avatar
lvhan028 committed
385
        """return bos token id."""
lvhan028's avatar
lvhan028 committed
386
387
388
389
        token_ids, _ = self.preprocess('<BOS>')
        return token_ids[0][0]

    def _get_eos(self):
lvhan028's avatar
lvhan028 committed
390
        """return eos token id."""
lvhan028's avatar
lvhan028 committed
391
392
393
        token_ids, _ = self.preprocess('<EOS>')
        return token_ids[0][0]

394
    def _stop_words(self, stop_words: List[str]):
lvhan028's avatar
lvhan028 committed
395
        """return stop-words' token ids."""
lvhan028's avatar
lvhan028 committed
396
397
398
        if stop_words is None:
            return None
        assert isinstance(stop_words, List) and \
399
               all(isinstance(elem, str) for elem in stop_words), \
lvhan028's avatar
lvhan028 committed
400
401
402
               f'stop_words must be a list but got {type(stop_words)}'
        # each id in stop_words represents a stop word
        # refer to https://github.com/fauxpilot/fauxpilot/discussions/165 for
403
        # detailed explanation about turbomind's stop_words
404
405
406
407
408
409
410
        stop_words = [
            int(self.preprocess(stop_word)[0][0][-1])
            for stop_word in stop_words
        ]
        assert isinstance(stop_words, List) and \
               all(isinstance(elem, int) for elem in stop_words), \
               'invalid stop_words'
lvhan028's avatar
lvhan028 committed
411
412
413
414
415
        stop_word_offsets = range(1, len(stop_words) + 1)
        stop_words = np.array([[stop_words,
                                stop_word_offsets]]).astype(np.int32)
        return stop_words

lvhan028's avatar
lvhan028 committed
416
    def _get_prompt(self, prompt: str, sequence_start: bool):
lvhan028's avatar
lvhan028 committed
417
418
        """return the concatenated prompt according to the model's chat
        template."""
lvhan028's avatar
lvhan028 committed
419
        if self.profile_generation or self.profile_serving:
420
            return prompt
lvhan028's avatar
lvhan028 committed
421
        return self.model.get_prompt(prompt, sequence_start)
lvhan028's avatar
lvhan028 committed
422
423
424
425
426
427
428
429

    def _stream_infer(self,
                      session: Session,
                      prompt: str,
                      request_output_len: int = 512,
                      sequence_start: bool = True,
                      sequence_end: bool = False,
                      cancel: bool = False):
lvhan028's avatar
lvhan028 committed
430
431
432
433
434
435
436
437
438
439
440
441
442
        """communicate with inference server to chat, or cancel a session, or
        end a session.

        Args:
            session (Session): an instance of a session
            prompt (str): the concatenated prompt
            request_output_len (int): the max number of tokens to be generated
            sequence_start (bool): indicator for starting a sequence
            sequence_end (bool): indicator for ending a sequence
            cancel (bool): indicator for cancelling the session
        Yields:
            tuple: status, text, generated token number
        """
lvhan028's avatar
lvhan028 committed
443
444
445
446
447
448
449
450
451
452
453
454
        logger = get_logger(log_level=self.log_level)
        logger.info(f'session {session.session_id}, '
                    f'request id {session.request_id}, '
                    f'request_output_len {request_output_len}, '
                    f'start {sequence_start}, '
                    f'end {sequence_end}, cancel {cancel}')

        assert request_output_len is None or \
               isinstance(request_output_len, int), \
               f'request_output_len is supposed to be None or int, ' \
               f'but got {type(request_output_len)}'

lvhan028's avatar
lvhan028 committed
455
456
457
458
459
460
        if sequence_start:
            logger.info(f'session {session.session_id}, clear history since '
                        f'sequence_start is True')
            session.histories = ''
            session.sequence_length = 0

lvhan028's avatar
lvhan028 committed
461
        input_ids, input_lengths = self.preprocess(prompt)
462
463
464
465
        # will crash if last_token_id == eos_id and send empty input_ids
        if sequence_end and request_output_len == 0:
            input_ids = np.array([[self.bos_id]], dtype=np.uint32)
            input_lengths = np.array([[1]], dtype=np.uint32)
lvhan028's avatar
lvhan028 committed
466
        input_tokens = input_lengths.squeeze()
lvhan028's avatar
lvhan028 committed
467
468
469
        if self.profile_generation:
            yield StatusCode.TRITON_STREAM_ING, \
                  'ignore preprocessing during profiling generation', 0
lvhan028's avatar
lvhan028 committed
470
471
472
473
474
475
476
477
478
479
480
481
        if request_output_len is None:
            request_output_len = max(
                128,
                self.cfg.session_len - session.sequence_length - input_tokens)

        if input_tokens + request_output_len + \
                session.sequence_length > self.cfg.session_len:
            errmsg = f'session {session.session_id}, ' \
                     f'out of max sequence length {self.cfg.session_len}, ' \
                     f'#input tokens {input_tokens}, ' \
                     f'history tokens {session.sequence_length}, ' \
                     f'request length {request_output_len}'
482
            logger.warning(errmsg)
lvhan028's avatar
lvhan028 committed
483
            yield StatusCode.TRITON_SESSION_OUT_OF_LIMIT, errmsg, 0
484
485
            return

lvhan028's avatar
lvhan028 committed
486
        logger.info(f'session {session.session_id}, '
487
                    f'max length: {self.cfg.session_len}, '
lvhan028's avatar
lvhan028 committed
488
489
490
491
492
                    f'input tokens: {input_tokens}, '
                    f'request tokens: {request_output_len}, '
                    f'history tokens: {session.sequence_length}')

        preseq_length = session.sequence_length
lvhan028's avatar
lvhan028 committed
493
        session.response = ''
494
        session.status = StatusCode.TRITON_SESSION_READY
lvhan028's avatar
lvhan028 committed
495
496

        que = queue.Queue()
lvhan028's avatar
lvhan028 committed
497
498
499
500
501
        producer = threading.Thread(target=self._stream_producer,
                                    args=(self.tritonserver_addr, session, que,
                                          self.cfg, input_ids, input_lengths,
                                          request_output_len, sequence_start,
                                          sequence_end, preseq_length, cancel))
lvhan028's avatar
lvhan028 committed
502
        producer.start()
503
504
505
506
507
508
        for status, res, n_token in self.stream_consumer(
                self.postprocess, que, session, input_tokens, preseq_length,
                cancel, logger, self.display, self.profile_generation,
                self.eos_id):
            yield status, res, n_token

lvhan028's avatar
lvhan028 committed
509
510
511
512
513
514
515
516
517
518
519
        producer.join()
        self._session = que.get()
        curseq_length = self._session.sequence_length
        logger.info(f'session {session.session_id}, pre seq_len '
                    f'{preseq_length}, cur seq_len {curseq_length}, '
                    f'diff {curseq_length - preseq_length}')

    @staticmethod
    def _stream_producer(tritonserver_addr, session, que, cfg, input_ids,
                         input_lengths, request_output_len, sequence_start,
                         sequence_end, preseq_length, cancel):
lvhan028's avatar
lvhan028 committed
520
521
522
523
524
525
526
        """Send a request to the triton inference server.

        Args:
            tritonserver_addr (str): the communication address of the inference
                server
            session (Session): an instance of a session
            que (multiprocessing.Queue): response queue
Lyu Han's avatar
Lyu Han committed
527
            cfg (dict): parameters for sampling
lvhan028's avatar
lvhan028 committed
528
529
530
531
532
533
534
535
            input_ids (numpy.ndarray): token ids of input prompt
            input_lengths (numpy.ndarray): length of input_ids
            request_output_len (int): the max number of tokens to be generated
            sequence_start (bool): indicator for starting a sequence
            sequence_end (bool): indicator for ending a sequence
            preseq_length (int): the history sequence length
            cancel (bool): indicator for cancelling the session
        """
lvhan028's avatar
lvhan028 committed
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
        request_output_len = np.full(input_lengths.shape,
                                     request_output_len).astype(np.uint32)

        callback = partial(stream_callback, que)
        with grpcclient.InferenceServerClient(tritonserver_addr) as client:
            inputs = [
                prepare_tensor('input_ids', input_ids),
                prepare_tensor('input_lengths', input_lengths),
                prepare_tensor('request_output_len', request_output_len),
                prepare_tensor('runtime_top_p',
                               cfg.top_p * np.ones((1, 1), dtype=np.float32)),
                prepare_tensor(
                    'temperature',
                    cfg.temperature * np.ones((1, 1), dtype=np.float32)),
                prepare_tensor(
                    'repetition_penalty',
                    cfg.repetition_penalty * np.ones(
                        (1, 1), dtype=np.float32)),
                prepare_tensor('step',
                               preseq_length * np.ones((1, 1), dtype=np.int32))
            ]
557
558
559
560
            if cfg.top_k is not None:
                inputs += prepare_tensor(
                    'runtime_top_k',
                    cfg.top_k * np.ones((1, 1), dtype=np.uint32)),
lvhan028's avatar
lvhan028 committed
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
            if cfg.stop_words is not None:
                inputs += [prepare_tensor('stop_words_list', cfg.stop_words)]
            if cfg.bad_words is not None:
                inputs += [prepare_tensor('bad_words_list', cfg.bad_words)]

            inputs += [
                prepare_tensor(
                    'session_len',
                    cfg.session_len *
                    np.ones([input_ids.shape[0], 1], dtype=np.uint32)),
                prepare_tensor('START', (1 if sequence_start else 0) * np.ones(
                    (1, 1), dtype=np.int32)),
                prepare_tensor('END', (1 if sequence_end else 0) * np.ones(
                    (1, 1), dtype=np.int32)),
                prepare_tensor(
                    'CORRID',
                    session.session_id * np.ones((1, 1), dtype=np.uint64)),
                prepare_tensor('STOP', (1 if cancel else 0) * np.ones(
                    (1, 1), dtype=np.int32))
            ]
            if sequence_start:
                random_seed = random.getrandbits(64)
                inputs += [
                    prepare_tensor(
                        'random_seed',
                        random_seed * np.ones((1, 1), dtype=np.uint64))
                ]
            client.start_stream(callback)
589
            client.async_stream_infer('turbomind',
lvhan028's avatar
lvhan028 committed
590
591
592
593
594
                                      inputs,
                                      sequence_id=session.session_id,
                                      request_id=session.request_id,
                                      sequence_start=sequence_start,
                                      sequence_end=sequence_end)
lvhan028's avatar
lvhan028 committed
595
596
597
        que.put(None)

    @staticmethod
598
599
600
    def stream_consumer(postprocess, res_queue, session, n_input_token,
                        preseq_length, cancel, logger, display,
                        profile_generation, eos_id):
lvhan028's avatar
lvhan028 committed
601
        """Consume the response from the triton inference server.
lvhan028's avatar
lvhan028 committed
602

lvhan028's avatar
lvhan028 committed
603
604
605
606
607
        Args:
            postprocess (callable): postprocess function for
                the generated tokens
            res_queue (multiprocessing.Queue): response queue
            session (Session): an instance of a session
608
            n_input_token (int): token number of input prompt
lvhan028's avatar
lvhan028 committed
609
610
611
612
613
614
615
616
617
618
            preseq_length (int): the history sequence length
            cancel (bool): indicator for cancelling the session
            logger (util.Logger):
            display (bool): display the text in the consolo interface or not
            profile_generation (bool): indicator for profiling token generation
            eos_id (int): eos token id

        Yields:
            tuple: status, text, generated token number
        """
619
        status, res, n_token = None, '', 0
lvhan028's avatar
lvhan028 committed
620
621
622
        while True:
            result = res_queue.get()
            if result is None:
623
624
                status = StatusCode.TRITON_STREAM_END
                res = session.response
625
                session.status = StatusCode.TRITON_STREAM_END
lvhan028's avatar
lvhan028 committed
626
627
                break
            if 'errcode' in result:
628
                logger.error(f'got error from turbomind, code '
lvhan028's avatar
lvhan028 committed
629
630
631
                             f"{result['errcode']}, {result['errmsg']}, "
                             f'token {session.sequence_length}')
                session.sequence_length = preseq_length
632
633
634
635
                session.response = ''
                status = StatusCode.TRITON_SERVER_ERR
                res = f"{result['errcode']}, {result['errmsg']}"
                n_token = 0
lvhan028's avatar
lvhan028 committed
636
637
638
639
640
641
642
643
644
645
646
                break
            if cancel:
                continue
            try:
                message = ModelInferResponse()
                google.protobuf.json_format.Parse(json.dumps(result), message)
                result = grpcclient.InferResult(message)
                sequence_length = result.as_numpy('sequence_length')
                output_ids = result.as_numpy('output_ids')

                session.sequence_length = sequence_length.squeeze()
647
648
649
650
                output_ids = output_ids.reshape((1, 1, output_ids.shape[-1]))
                output_ids = output_ids[:, :, n_input_token +
                                        preseq_length:sequence_length.squeeze(
                                        )]
651
652
                last_token_id = None if output_ids.shape[
                    -1] == 0 else output_ids[-1, -1, -1]
lvhan028's avatar
lvhan028 committed
653
654
                if last_token_id == eos_id:
                    session.sequence_length = session.sequence_length - 1
655
                    output_ids = output_ids[:, :, :-1]
lvhan028's avatar
lvhan028 committed
656
657
658
659

                if profile_generation:
                    yield (StatusCode.TRITON_STREAM_ING,
                           'postprocessing is ignored during profiling '
660
                           'token generation', output_ids.shape[-1])
lvhan028's avatar
lvhan028 committed
661
                    continue
662
663
                output_str = postprocess(
                    output_ids, np.array([[n_token]], dtype=np.uint32))
lvhan028's avatar
lvhan028 committed
664
                text = output_str[0].decode()
665
666
667
668
669
670
                # utf-8 char at the end means it's a potential unfinished
                # byte sequence, continue to concate it with the next
                # sequence and decode them together
                if text.endswith('�'):
                    continue
                n_token = output_ids.shape[-1]
lvhan028's avatar
lvhan028 committed
671
                if display:
672
673
                    print(text, end='', flush=True)
                session.response += text
674
                yield (StatusCode.TRITON_STREAM_ING, session.response,
675
                       output_ids.shape[-1])
lvhan028's avatar
lvhan028 committed
676
677
            except Exception as e:
                logger.error(f'catch exception: {e}')
678
679
                logger.error(
                    f'session {session.session_id}: prompt: {session.prompt}')
lvhan028's avatar
lvhan028 committed
680
681
682
683
684
685
686
687

        # put session back to queue so that `_stream_infer` can update it in
        # `self.sessions`
        while not res_queue.empty():
            res_queue.get()
        res_queue.put(session)
        if display:
            print('\n')
688
        yield status, res, n_token