profile_generation.py 15.4 KB
Newer Older
1
2
3
4
5
# Copyright (c) OpenMMLab. All rights reserved.
import argparse
import csv
import logging
import os
lvhan028's avatar
lvhan028 committed
6
import time
7
from dataclasses import dataclass
8
9
from queue import Queue
from threading import Thread
10
from typing import List
lvhan028's avatar
lvhan028 committed
11
12

import numpy as np
13
14
15
16
17
from pynvml import (NVMLError, nvmlDeviceGetCount, nvmlDeviceGetHandleByIndex,
                    nvmlDeviceGetMemoryInfo, nvmlDeviceGetName,
                    nvmlDeviceGetPowerState, nvmlDeviceGetTemperature,
                    nvmlInit, nvmlShutdown, nvmlSystemGetDriverVersion)
from tqdm import tqdm
lvhan028's avatar
lvhan028 committed
18

19
from lmdeploy.turbomind import TurboMind
lvhan028's avatar
lvhan028 committed
20
21


22
def infer(model, session_id: int, input_ids: List, output_seqlen: int,
q.yao's avatar
q.yao committed
23
24
          test_round: int, que: Queue):
    chatbot = model.create_instance()
lvhan028's avatar
lvhan028 committed
25
    stats = []
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
    for _ in range(test_round):
        token_latency_stats = [0] * (output_seqlen + 1)
        prev = time.perf_counter()
        n_pre_token = 0
        """
        The iterator provided by `stream_infer` denotes the number of generated tokens so far,
        which is represented by the variable `n_token`.
        Please note that `n_token` is not a continuous value. In other words, during the iteration,
        its value might be 5, 7, 8, 16, and so on, rather than 1, 2, 3, 4, etc.
        So, it is quite difficult to get the latency of each generated token.
        As a work-around, we set the latency `new-prev` of each iteration to the first token of
        the new generated tokens, and leave the latency of the rest tokens being 0.
        For example, in the first iteration, 5 tokens are generated.
        The time elapsing in this iteration `now-prev` is set to the latency of first token of
        the 5 tokens, i.e. `token_latency_stats[0]`, and `token_latency_stats[1:4]` is set 0`
        """   # noqa: E501
42
43
44
45
46
        for outputs in chatbot.stream_infer(session_id,
                                            input_ids,
                                            request_output_len=output_seqlen,
                                            sequence_start=True,
                                            sequence_end=True,
47
48
49
50
51
52
53
54
55
56
57
58
59
                                            ignore_eos=True,
                                            stream_output=True):
            _, n_token = outputs[0]
            now = time.perf_counter()
            if n_pre_token != n_token:
                token_latency_stats[n_pre_token] = np.round(now - prev, 3)
                n_pre_token = n_token
            prev = now

        assert output_seqlen <= n_token <= output_seqlen + 1, \
            f'Error. session_id({session_id}) request {output_seqlen} ' \
            f'tokens, but generate {n_token} tokens'
        stats.append(token_latency_stats[:output_seqlen])
lvhan028's avatar
lvhan028 committed
60
61
62
    que.put((session_id, stats))


63
64
65
66
67
def warmup(model,
           concurrency: int,
           input_ids: List[int],
           output_seqlen: int,
           warmup_round: int = 2):
lvhan028's avatar
lvhan028 committed
68
69
    print('start to warmup ...')

q.yao's avatar
q.yao committed
70
71
    def _infer(model, session_id):
        chatbot = model.create_instance()
lvhan028's avatar
lvhan028 committed
72
        for _ in range(warmup_round):
73
            for _ in chatbot.stream_infer(session_id,
74
                                          input_ids=input_ids,
75
76
77
78
                                          request_output_len=output_seqlen,
                                          sequence_start=True,
                                          sequence_end=True,
                                          ignore_eos=True):
lvhan028's avatar
lvhan028 committed
79
80
81
82
                continue

    _start = time.perf_counter()
    procs = []
q.yao's avatar
q.yao committed
83
84
    for i in range(concurrency):
        proc = Thread(target=_infer, args=(model, i + 1))
lvhan028's avatar
lvhan028 committed
85
86
        procs.append(proc)
        proc.start()
q.yao's avatar
q.yao committed
87
88
89
90
91
92
93
94

    try:
        for proc in procs:
            proc.join()
    except Exception:
        for proc in procs:
            proc.stop()
        exit(1)
lvhan028's avatar
lvhan028 committed
95
96
97
98
    _end = time.perf_counter()
    print(f'end warmup, elapsed time: {round(_end - _start, 2)}s')


99
100
def profile_throughput(model_path: str,
                       concurrency: int = 1,
101
                       input_seqlen: int = 1,
102
103
                       output_seqlen: int = 512,
                       test_round: int = 10,
104
105
106
107
108
109
110
111
112
                       tp: int = 1,
                       **kwargs):
    # avoid turbomind checking chat template name by setting
    # `model_name='llama'`
    tm_model = TurboMind(model_path=model_path,
                         tp=tp,
                         model_name='llama',
                         **kwargs)
    tokenizer = tm_model.tokenizer
q.yao's avatar
q.yao committed
113

lvhan028's avatar
lvhan028 committed
114
    # make up a prompt that can be tokenized into {input_seqlen} tokens
115
    assert input_seqlen > 0, 'input_seqlen should > 0'
116
    input_ids = tokenizer('hi').input_ids
117
    input_ids = input_ids * input_seqlen
118
119
120

    warmup(tm_model, concurrency, input_ids, output_seqlen)

q.yao's avatar
q.yao committed
121
    que = Queue()
lvhan028's avatar
lvhan028 committed
122
123
    procs = []
    _start = time.perf_counter()
q.yao's avatar
q.yao committed
124

lvhan028's avatar
lvhan028 committed
125
    for i in range(concurrency):
q.yao's avatar
q.yao committed
126
        proc = Thread(target=infer,
127
128
                      args=(tm_model, i + 1, input_ids, output_seqlen,
                            test_round, que))
lvhan028's avatar
lvhan028 committed
129
130
        procs.append(proc)
        proc.start()
q.yao's avatar
q.yao committed
131
132
133
134
135
136
137
138

    try:
        for proc in procs:
            proc.join()
    except Exception:
        for proc in procs:
            proc.stop()
        exit(1)
lvhan028's avatar
lvhan028 committed
139
140
141
    _end = time.perf_counter()
    elapsed_time = _end - _start

142
    token_latency_stats = []
lvhan028's avatar
lvhan028 committed
143
    while not que.empty():
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
        _, _stats = que.get()
        token_latency_stats += _stats

    # The shape is [concurrency*test_round, output_seqlen]
    token_latency_stats = np.stack(token_latency_stats, axis=0)

    first_token_latency_min = np.round(
        np.min(token_latency_stats[:, 0], axis=0), 3)
    first_token_latency_max = np.round(
        np.max(token_latency_stats[:, 0], axis=0), 3)
    first_token_latency_ave = np.round(
        np.mean(token_latency_stats[:, 0], axis=0), 3)
    token_latency_max = np.round(np.max(np.sum(token_latency_stats, axis=1)),
                                 3)
    token_latency_min = np.round(np.min(np.sum(token_latency_stats, axis=1)),
                                 3)
    token_latency_ave = np.round(np.mean(np.sum(token_latency_stats, axis=1)),
                                 3)
    # sort token_latency without the first token's latency
    sorted_token_latency = np.sort(token_latency_stats[:, 1:].flatten())
    percentiles = [
        np.round(
            sorted_token_latency[int(percent * len(sorted_token_latency))], 3)
        for percent in [0.5, 0.75, 0.95, 0.99]
    ]

    throughput = np.round(token_latency_stats.size / elapsed_time, 2)
    print(f'\n{"-" * 50}\ntotal time: {elapsed_time:.2f}s\n'
          f'concurrency: {concurrency}, test_round: {test_round}\n'
          f'input_tokens: {input_seqlen}, output_tokens: {output_seqlen}\n'
lvhan028's avatar
lvhan028 committed
174
          f'first_token latency(min, max, ave): '
175
176
177
178
179
180
181
182
183
184
          f'{first_token_latency_min}s, {first_token_latency_max}s, '
          f'{first_token_latency_ave}s\ntotal_token latency(min, max, ave): '
          f'{token_latency_min}s, {token_latency_max}s, '
          f'{token_latency_ave}s\n'
          f'token_latency percentiles(50%,75%,95%,99%)(s): {percentiles}\n'
          f'throughput: {throughput} token/s\n{"-" * 50}')
    return tm_model.model_name, \
        [first_token_latency_min, first_token_latency_max,
         first_token_latency_ave], \
        percentiles, throughput, tm_model.gpu_count
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264


class MemoryMonitor:
    from multiprocessing import Manager
    max_mem = Manager().Value('f', 0)  # GB
    device_count = Manager().Value('f', 0)

    @staticmethod
    def nvidia_info():
        # pip install nvidia-ml-py
        nvidia_dict = {
            'state': True,
            'nvidia_version': '',
            'nvidia_count': 0,
            'gpus': []
        }
        try:
            nvmlInit()
            nvidia_dict['nvidia_version'] = nvmlSystemGetDriverVersion()
            nvidia_dict['nvidia_count'] = nvmlDeviceGetCount()
            for i in range(nvidia_dict['nvidia_count']):
                handle = nvmlDeviceGetHandleByIndex(i)
                memory_info = nvmlDeviceGetMemoryInfo(handle)
                gpu = {
                    'gpu_name': nvmlDeviceGetName(handle),
                    'total': memory_info.total,
                    'free': memory_info.free,
                    'used': memory_info.used,
                    'temperature': f'{nvmlDeviceGetTemperature(handle, 0)}℃',
                    'powerStatus': nvmlDeviceGetPowerState(handle)
                }
                nvidia_dict['gpus'].append(gpu)
        except NVMLError as _:  # noqa
            nvidia_dict['state'] = False
        except Exception as _:  # noqa
            nvidia_dict['state'] = False
        finally:
            try:
                nvmlShutdown()
            except:  # noqa
                pass
        return nvidia_dict

    @classmethod
    def mem_monitor(cls):
        info = cls.nvidia_info()
        max_mem = 0
        mem_start = 0
        cls.device_count.value = len(info['gpus'])
        for used_total in info['gpus']:
            mem_start += used_total['used']
        while True:
            info = cls.nvidia_info()
            used = 0
            for used_total in info['gpus']:
                used += used_total['used']
            if used > max_mem:
                max_mem = used
                cls.max_mem.value = (max_mem - mem_start) / (1 << 30)

    @classmethod
    def start(cls):
        cls._running = True
        from multiprocessing import Process
        cls.proc = Process(target=cls.mem_monitor)
        cls.proc.start()

    @classmethod
    def terminate(cls) -> float:
        """Terminate the subprocess and return maximum memory."""
        cls.proc.kill()
        return cls.max_mem.value


@dataclass
class ProfileResult:
    model_name: str
    batch: int
    prompt_tokens: int
    completion_tokens: int
265
266
    first_token_latency: List
    percentiles: List
267
268
269
270
271
272
273
274
275
    throughput_per_proc: float
    throughput_per_node: float
    mem_per_proc: float
    mem_per_gpu: float
    mem_per_node: float


def parse_args():
    parser = argparse.ArgumentParser(description='Regression Test')
276
    parser.add_argument('model_path',
277
                        type=str,
278
279
                        help='the path of the model in localhost or '
                        'the repo_id of the model in huggingface.co')
280
281
282
283
    parser.add_argument('--concurrency',
                        nargs='+',
                        type=int,
                        help='how many requests launched concurrently',
284
                        default=[1, 16, 32, 64])
285
286
287
288
289
290
    parser.add_argument(
        '--prompt-tokens',
        nargs='+',
        type=int,
        help='how many requests launched concurrently. One-to-one'
        'correspondence with completion-tokens',
291
        default=[1, 128, 128, 2048, 2048])
292
293
294
295
296
    parser.add_argument('--completion-tokens',
                        nargs='+',
                        type=int,
                        help='how many tokens to be generated. One-to-one'
                        'correspondence with prompt-tokens',
297
                        default=[128, 128, 2048, 128, 2048])
298
    parser.add_argument('--tp', type=int, help='Tensor parallel', default=1)
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
    parser.add_argument('--top_k',
                        type=int,
                        help='The number of highest probability vocabulary '
                        'tokens to keep for top-k-filtering',
                        default=1)
    parser.add_argument('--top_p',
                        type=float,
                        help='the set of most probable tokens with '
                        'probabilities that add up to top_p or higher '
                        'are kept for generation',
                        default=1.0)
    parser.add_argument('--temperature',
                        type=float,
                        help='The value used to modulate the next token '
                        'probabilities',
                        default=1.0)
    parser.add_argument('--csv',
316
317
318
319
320
                        type=str,
                        help='Where to save the result.',
                        default='profile_generation.csv')
    parser.add_argument('--log-level',
                        help='set log level',
321
                        default='ERROR',
322
                        choices=list(logging._nameToLevel.keys()))
323
324
325
326
    parser.add_argument('--test-round',
                        type=int,
                        help='number of test rounds',
                        default=10)
327
328
329
330
331
332
    args = parser.parse_args()
    return args


def main():
    args = parse_args()
333
334
335
336
    assert len(args.prompt_tokens) == len(args.completion_tokens), \
        f'mismatched size between `prompt-tokens` and `completion-tokenes`' \
        f', {len(args.prompt_tokens)} vs {len(args.completion_tokens)}'

337
338
339
340
341
342
343
344
345
346
347
348
    os.environ['TM_LOG_LEVEL'] = args.log_level
    results: List[ProfileResult] = []
    for batch in tqdm(args.concurrency):
        for prompt_tokens, completion_tokens in tqdm(
                zip(args.prompt_tokens, args.completion_tokens)):
            MemoryMonitor.start()
            from functools import partial
            from multiprocessing import Pool
            profile_target = partial(profile_throughput,
                                     concurrency=batch,
                                     input_seqlen=prompt_tokens,
                                     output_seqlen=completion_tokens,
349
350
351
352
353
                                     tp=args.tp,
                                     top_k=args.top_k,
                                     top_p=args.top_p,
                                     temperature=args.temperature,
                                     test_round=args.test_round)
354
            output = Pool(1).map(profile_target, (args.model_path, ))
355
356
            model_name, first_token_latency, percentiles, \
                throughput_per_proc, tp = output[0]
357
358
359
360
361
362
363
364
            time.sleep(5)  # wait a while for releasing GPU mem
            memory = MemoryMonitor.terminate()
            device_count = MemoryMonitor.device_count.value
            results.append(
                ProfileResult(model_name=model_name,
                              batch=batch,
                              prompt_tokens=prompt_tokens,
                              completion_tokens=completion_tokens,
365
366
                              first_token_latency=first_token_latency,
                              percentiles=percentiles,
367
368
369
370
371
372
                              throughput_per_proc=throughput_per_proc,
                              throughput_per_node=throughput_per_proc / tp *
                              device_count,
                              mem_per_proc=memory,
                              mem_per_gpu=memory / tp,
                              mem_per_node=memory / tp * device_count))
373
    with open(args.csv, 'w') as csvfile:
374
375
376
        writer = csv.writer(csvfile)
        writer.writerow([
            'batch', 'prompt_tokens', 'completion_tokens',
377
378
379
380
            '1st_token_latency(min)(s)', '1st_token_latency(max)(s)',
            '1st_token_latency(ave)(s)', 'percentile50(s)', 'percentile75(s)',
            'percentile95(s)', 'percentile99(s)', 'throughput(token/s)',
            'mem_per_proc(GB)', 'mem_per_gpu(GB)'
381
382
383
384
        ])
        for re in results:
            writer.writerow([
                re.batch, re.prompt_tokens, re.completion_tokens,
385
386
387
388
389
                re.first_token_latency[0], re.first_token_latency[1],
                re.first_token_latency[2], re.percentiles[0],
                re.percentiles[1], re.percentiles[2], re.percentiles[3],
                f'{re.throughput_per_proc:.2f}', f'{re.mem_per_proc:.2f}',
                f'{re.mem_per_gpu:.2f}'
390
            ])
lvhan028's avatar
lvhan028 committed
391
392
393


if __name__ == '__main__':
394
    main()