Skip to content

Commit c6cd629

Browse files
authored
[Inference]ADD Bench Chatglm2 script (#4963)
* add bench chatglm * fix bug and make utils --------- Co-authored-by: CjhHa1 <cjh18671720497outlook.com>
1 parent 785802e commit c6cd629

File tree

6 files changed

+160
-98
lines changed

6 files changed

+160
-98
lines changed

examples/inference/_utils.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
def print_perf_stats(latency_set, config, bs, warmup=3):
2+
# trim warmup queries
3+
latency_set = list(latency_set)
4+
latency_set = latency_set[warmup:]
5+
count = len(latency_set)
6+
7+
if count > 0:
8+
latency_set.sort()
9+
avg = sum(latency_set) / count
10+
num_layers = (
11+
getattr(config, "num_layers") if hasattr(config, "num_layers") else getattr(config, "num_hidden_layers")
12+
)
13+
num_parameters = num_layers * config.hidden_size * config.hidden_size * 12
14+
num_bytes = 2 # float16
15+
16+
print("Avg Per Token Latency: {0:8.2f} ms".format(avg * 1000))
17+
print("Avg BW: {0:8.2f} GB/s".format(1 / avg * num_parameters * num_bytes / 1e9))
18+
print("Avg flops: {0:8.2f} TFlops/s".format(1 / avg * num_parameters * num_bytes * bs / 1e12))
19+
print("Avg Throughput: tokens/s: {}".format((1000 / (avg * 1000)) * bs))

examples/inference/bench_bloom.py

Lines changed: 1 addition & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import time
44

55
import torch
6+
from _utils import print_perf_stats
67
from transformers import BloomForCausalLM, BloomTokenizerFast
78

89
import colossalai
@@ -14,25 +15,6 @@
1415
os.environ["TRANSFORMERS_NO_ADVISORY_WARNINGS"] = "true"
1516

1617

17-
def print_perf_stats(latency_set, config, bs, warmup=3):
18-
# trim warmup queries
19-
latency_set = list(latency_set)
20-
latency_set = latency_set[warmup:]
21-
count = len(latency_set)
22-
23-
if count > 0:
24-
latency_set.sort()
25-
avg = sum(latency_set) / count
26-
num_layers = getattr(config, "num_layers", config.num_hidden_layers)
27-
num_parameters = num_layers * config.hidden_size * config.hidden_size * 12
28-
num_bytes = 2 # float16
29-
30-
print("Avg Per Token Latency: {0:8.2f} ms".format(avg * 1000))
31-
print("Avg BW: {0:8.2f} GB/s".format(1 / avg * num_parameters * num_bytes / 1e9))
32-
print("Avg flops: {0:8.2f} TFlops/s".format(1 / avg * num_parameters * num_bytes * bs / 1e12))
33-
print("Avg Throughput: tokens/s: {}".format((1000 / (avg * 1000)) * bs))
34-
35-
3618
def bench_bloom(args):
3719
model_path = args.path
3820
max_batch_size = args.batch_size
Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
import argparse
2+
import os
3+
import time
4+
5+
import torch
6+
from _utils import print_perf_stats
7+
from transformers import AutoTokenizer
8+
9+
import colossalai
10+
from colossalai.inference.tensor_parallel.engine import TPInferEngine
11+
from colossalai.logging import disable_existing_loggers
12+
from colossalai.shardformer import ShardConfig
13+
from colossalai.shardformer.modeling.chatglm2_6b.modeling_chatglm import ChatGLMForConditionalGeneration
14+
from colossalai.testing import rerun_if_address_is_in_use, spawn
15+
16+
os.environ["TRANSFORMERS_NO_ADVISORY_WARNINGS"] = "true"
17+
18+
19+
def run_chatglm2_test(args):
20+
chatglm2_model_path = args.path
21+
max_batch_size = args.batch_size
22+
max_input_len = args.input_len
23+
max_output_len = args.output_len
24+
args.test_mode
25+
26+
print("max_batch_size : " + str(max_batch_size))
27+
28+
tokenizer = AutoTokenizer.from_pretrained("THUDM/chatglm2-6b", trust_remote_code=True)
29+
model = ChatGLMForConditionalGeneration.from_pretrained(chatglm2_model_path, pad_token_id=tokenizer.eos_token_id)
30+
model = model.half()
31+
model.config
32+
33+
shard_config = ShardConfig(enable_tensor_parallelism=True if args.tp_size > 1 else False, inference_only=True)
34+
infer_engine = TPInferEngine(model, shard_config, max_batch_size, max_input_len, max_output_len)
35+
36+
generate_kwargs = dict(max_new_tokens=1, do_sample=False)
37+
input_tokens = {
38+
"input_ids": torch.randint(1, 1000, (max_batch_size, max_input_len), device="cuda"),
39+
"attention_mask": torch.ones((max_batch_size, max_input_len), device="cuda"),
40+
}
41+
42+
iters = 10
43+
prefill_times = []
44+
45+
warmup = 3
46+
47+
for i in range(iters):
48+
torch.cuda.synchronize()
49+
start = time.time()
50+
outputs = infer_engine.generate(input_tokens, **generate_kwargs)
51+
torch.cuda.synchronize()
52+
end = time.time()
53+
out_len = outputs.shape[1]
54+
print("generation time {} s".format(str(end - start)))
55+
print(out_len - max_input_len)
56+
prefill_times.append((end - start) / (out_len - max_input_len))
57+
58+
prefill_times = prefill_times[warmup:]
59+
prefill_time_avg = sum(prefill_times) / len(prefill_times)
60+
generate_kwargs = dict(max_new_tokens=max_output_len, do_sample=False)
61+
62+
times = []
63+
decoder_times = []
64+
for i in range(iters):
65+
torch.cuda.synchronize()
66+
start = time.time()
67+
outputs = infer_engine.generate(input_tokens, **generate_kwargs)
68+
torch.cuda.synchronize()
69+
end = time.time()
70+
out_len = outputs.shape[1]
71+
print("generation time {} s".format(str(end - start)))
72+
print(out_len - max_input_len)
73+
times.append((end - start) / (out_len - max_input_len))
74+
if args.test_mode == "decoder_test":
75+
decoder_times.append((end - start - prefill_time_avg) / (out_len - max_input_len - 1))
76+
77+
times = times[warmup:]
78+
latency = sum(times) / len(times)
79+
print("total process latency is : " + str(latency) + " s")
80+
print("total throughput is : " + str(1 / latency * max_batch_size))
81+
82+
if args.test_mode == "decoder_test":
83+
decoder_times = decoder_times[warmup:]
84+
latency = sum(decoder_times) / len(decoder_times)
85+
86+
print("decoder process latency is : " + str(latency) + " s")
87+
print("decoder throughput is : " + str(1 / latency * max_batch_size))
88+
89+
print_perf_stats(times, model.config, max_batch_size)
90+
91+
92+
def check_chatglm2(rank, world_size, port, args):
93+
disable_existing_loggers()
94+
colossalai.launch(config={}, rank=rank, world_size=world_size, host="localhost", port=port, backend="nccl")
95+
run_chatglm2_test(args)
96+
97+
98+
@rerun_if_address_is_in_use()
99+
def test_chatglm2(args):
100+
spawn(check_chatglm2, args.tp_size, args=args)
101+
102+
103+
if __name__ == "__main__":
104+
parser = argparse.ArgumentParser()
105+
parser.add_argument("-p", "--path", type=str, help="Model path", required=True)
106+
parser.add_argument("-tp", "--tp_size", type=int, default=1, help="Tensor parallel size")
107+
parser.add_argument("-b", "--batch_size", type=int, default=16, help="Maximum batch size")
108+
parser.add_argument("--input_len", type=int, default=256, help="Maximum input length")
109+
parser.add_argument("--output_len", type=int, default=128, help="Maximum output length")
110+
parser.add_argument(
111+
"--test_mode", type=str, help="Test mode", default="e2e_test", choices=["e2e_test", "decoder_test"]
112+
)
113+
114+
args = parser.parse_args()
115+
116+
test_chatglm2(args)

examples/inference/bench_llama.py

Lines changed: 3 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import time
44

55
import torch
6+
from _utils import print_perf_stats
67
from transformers import LlamaForCausalLM, LlamaTokenizer
78

89
import colossalai
@@ -14,25 +15,6 @@
1415
os.environ["TRANSFORMERS_NO_ADVISORY_WARNINGS"] = "true"
1516

1617

17-
def print_perf_stats(latency_set, config, bs, warmup=3):
18-
torch.cuda.empty_cache()
19-
# trim warmup queries
20-
latency_set = list(latency_set)
21-
latency_set = latency_set[warmup:]
22-
count = len(latency_set)
23-
24-
if count > 0:
25-
latency_set.sort()
26-
avg = sum(latency_set) / count
27-
num_layers = getattr(config, "num_layers", config.num_hidden_layers)
28-
num_parameters = num_layers * config.hidden_size * config.hidden_size * 12
29-
num_bytes = 2
30-
31-
print("Avg Per Token Latency: {0:8.2f} ms".format(avg * 1000))
32-
print("Avg BW: {0:8.2f} GB/s".format(1 / avg * num_parameters * num_bytes / 1e9))
33-
print("Avg flops: {0:8.2f} TFlops/s".format(1 / avg * num_parameters * num_bytes * bs / 1e12))
34-
35-
3618
def run_llama_test(args):
3719
llama_model_path = args.path
3820
max_batch_size = args.batch_size
@@ -104,6 +86,8 @@ def run_llama_test(args):
10486
print("decoder process latency is : " + str(latency) + " s")
10587
print("decoder throughput is : " + str(1 / latency * max_batch_size))
10688

89+
print_perf_stats(times, model.config, max_batch_size)
90+
10791

10892
def check_llama(rank, world_size, port, args):
10993
disable_existing_loggers()

examples/inference/gptq_bloom.py

Lines changed: 20 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -1,43 +1,22 @@
11
import argparse
2-
import logging
32
import os
43
import time
54

65
import torch
7-
from auto_gptq import AutoGPTQForCausalLM, BaseQuantizeConfig
8-
from auto_gptq.nn_modules.qlinear import GeneralQuantLinear
9-
from transformers import AutoTokenizer, BloomForCausalLM, BloomTokenizerFast, LlamaForCausalLM, LlamaTokenizer
6+
from _utils import print_perf_stats
7+
from auto_gptq import AutoGPTQForCausalLM
8+
from transformers import BloomTokenizerFast
109

1110
import colossalai
1211
from colossalai.inference.tensor_parallel.engine import TPInferEngine
1312
from colossalai.logging import disable_existing_loggers
1413
from colossalai.shardformer import ShardConfig
1514
from colossalai.testing import clear_cache_before_run, rerun_if_address_is_in_use, spawn
1615

17-
os.environ['TRANSFORMERS_NO_ADVISORY_WARNINGS'] = 'true'
18-
19-
20-
def print_perf_stats(latency_set, config, bs, warmup=3):
21-
# trim warmup queries
22-
latency_set = list(latency_set)
23-
latency_set = latency_set[warmup:]
24-
count = len(latency_set)
25-
26-
if count > 0:
27-
latency_set.sort()
28-
avg = sum(latency_set) / count
29-
num_layers = getattr(config, "num_layers", config.num_hidden_layers)
30-
num_parameters = num_layers * config.hidden_size * config.hidden_size * 12
31-
num_bytes = 2 # float16
32-
33-
print("Avg Per Token Latency: {0:8.2f} ms".format(avg * 1000))
34-
print("Avg BW: {0:8.2f} GB/s".format(1 / avg * num_parameters * num_bytes / 1e9))
35-
print("Avg flops: {0:8.2f} TFlops/s".format(1 / avg * num_parameters * num_bytes * bs / 1e12))
36-
print("Avg Throughput: tokens/s: {}".format((1000 / (avg * 1000)) * bs))
16+
os.environ["TRANSFORMERS_NO_ADVISORY_WARNINGS"] = "true"
3717

3818

3919
def bench_bloom(args):
40-
4120
pretrained_model_dir = args.path
4221
quantized_model_dir = args.quantized_path
4322
max_batch_size = args.batch_size
@@ -48,9 +27,9 @@ def bench_bloom(args):
4827
tokenizer.pad_token = tokenizer.eos_token
4928

5029
# load quantized model to the first GPU
51-
model = AutoGPTQForCausalLM.from_quantized(quantized_model_dir,
52-
device=torch.cuda.current_device(),
53-
inject_fused_attention=False)
30+
model = AutoGPTQForCausalLM.from_quantized(
31+
quantized_model_dir, device=torch.cuda.current_device(), inject_fused_attention=False
32+
)
5433

5534
model = model.half()
5635

@@ -60,22 +39,22 @@ def bench_bloom(args):
6039
generate_kwargs = dict(max_new_tokens=max_output_len, do_sample=False)
6140

6241
input_tokens = {
63-
"input_ids": torch.randint(1, 1000, (max_batch_size, max_input_len), device='cuda'),
64-
"attention_mask": torch.ones((max_batch_size, max_input_len), device='cuda')
42+
"input_ids": torch.randint(1, 1000, (max_batch_size, max_input_len), device="cuda"),
43+
"attention_mask": torch.ones((max_batch_size, max_input_len), device="cuda"),
6544
}
6645

6746
# init TPInferEngine and shard the original model
6847
# To benchmark torch original, comment out the line of optimizing model
69-
shard_config = ShardConfig(enable_tensor_parallelism=True if args.tp_size > 1 else False,
70-
inference_only=True,
71-
inference_gptq=True)
48+
shard_config = ShardConfig(
49+
enable_tensor_parallelism=True if args.tp_size > 1 else False, inference_only=True, inference_gptq=True
50+
)
7251
infer_engine = TPInferEngine(model, shard_config, max_batch_size, max_input_len, max_output_len)
7352

7453
# prepare data for generation
7554
generate_kwargs = dict(max_new_tokens=max_output_len, do_sample=False)
7655
input_tokens = {
7756
"input_ids": torch.randint(10, 1000, (max_batch_size, max_input_len)),
78-
"attention_mask": torch.ones((max_batch_size, max_input_len))
57+
"attention_mask": torch.ones((max_batch_size, max_input_len)),
7958
}
8059
for t in input_tokens:
8160
if torch.is_tensor(input_tokens[t]):
@@ -99,7 +78,7 @@ def bench_bloom(args):
9978

10079
def check_bloom(rank, world_size, port, args):
10180
disable_existing_loggers()
102-
colossalai.launch(config={}, rank=rank, world_size=world_size, host='localhost', port=port, backend='nccl')
81+
colossalai.launch(config={}, rank=rank, world_size=world_size, host="localhost", port=port, backend="nccl")
10382
bench_bloom(args)
10483

10584

@@ -111,12 +90,12 @@ def test_bloom(args):
11190

11291
if __name__ == "__main__":
11392
parser = argparse.ArgumentParser()
114-
parser.add_argument('-p', '--path', type=str, help='Model path', required=True)
115-
parser.add_argument('-q', '--quantized_path', type=str, help='Model path', required=True)
116-
parser.add_argument('-tp', '--tp_size', type=int, default=1, help='Tensor parallel size')
117-
parser.add_argument('-b', '--batch_size', type=int, default=16, help='Maximum batch size')
118-
parser.add_argument('--input_len', type=int, default=1024, help='Maximum input length')
119-
parser.add_argument('--output_len', type=int, default=128, help='Maximum output length')
93+
parser.add_argument("-p", "--path", type=str, help="Model path", required=True)
94+
parser.add_argument("-q", "--quantized_path", type=str, help="Model path", required=True)
95+
parser.add_argument("-tp", "--tp_size", type=int, default=1, help="Tensor parallel size")
96+
parser.add_argument("-b", "--batch_size", type=int, default=16, help="Maximum batch size")
97+
parser.add_argument("--input_len", type=int, default=1024, help="Maximum input length")
98+
parser.add_argument("--output_len", type=int, default=128, help="Maximum output length")
12099

121100
args = parser.parse_args()
122101

examples/inference/gptq_llama.py

Lines changed: 1 addition & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import time
44

55
import torch
6+
from _utils import print_perf_stats
67
from auto_gptq import AutoGPTQForCausalLM
78
from transformers import LlamaTokenizer
89

@@ -15,25 +16,6 @@
1516
os.environ["TRANSFORMERS_NO_ADVISORY_WARNINGS"] = "true"
1617

1718

18-
def print_perf_stats(latency_set, config, bs, warmup=3):
19-
# trim warmup queries
20-
latency_set = list(latency_set)
21-
latency_set = latency_set[warmup:]
22-
count = len(latency_set)
23-
24-
if count > 0:
25-
latency_set.sort()
26-
avg = sum(latency_set) / count
27-
num_layers = getattr(config, "num_layers", config.num_hidden_layers)
28-
num_parameters = num_layers * config.hidden_size * config.hidden_size * 12
29-
num_bytes = 2
30-
31-
print("Avg Per Token Latency: {0:8.2f} ms".format(avg * 1000))
32-
print("Avg BW: {0:8.2f} GB/s".format(1 / avg * num_parameters * num_bytes / 1e9))
33-
print("Avg flops: {0:8.2f} TFlops/s".format(1 / avg * num_parameters * num_bytes * bs / 1e12))
34-
print("Avg Throughput: tokens/s: {}".format((1000 / (avg * 1000)) * bs))
35-
36-
3719
def run_llama_test(args):
3820
pretrained_model_dir = args.path
3921
quantized_model_dir = args.quantized_path

0 commit comments

Comments
 (0)