forked from Wenyueh/MinivLLM
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbenchmark_tps.py
More file actions
203 lines (160 loc) · 5.15 KB
/
benchmark_tps.py
File metadata and controls
203 lines (160 loc) · 5.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
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
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
203
import time
import os
import torch
import numpy as np
import matplotlib.pyplot as plt
from transformers import AutoTokenizer,AutoModelForCausalLM
# ===== minivllm =====
from myvllm.engine.llm_engine import LLMEngine as MiniLLM
from myvllm.sampling_parameters import SamplingParams as MiniSamplingParams
# ===== vllm =====
from vllm import LLM as VLLM
from vllm import SamplingParams as VLLMSamplingParams
config = {
'max_num_sequences': 16,
'max_num_batched_tokens': 1024,
'max_cached_blocks': 1024,
'block_size': 256,
'world_size': 1,
'model_name_or_path': 'Qwen/Qwen3-0.6B',
'enforce_eager': True,
'vocab_size': 151936, # Fixed: was 151643, HF model uses 151936
'hidden_size': 1024,
'num_heads': 16,
'head_dim': 128, # Fixed: was 64, should be 128 (hidden_size / num_heads for GQA output)
'num_kv_heads': 8,
'intermediate_size': 3072,
'num_layers': 28,
'tie_word_embeddings': True,
'base': 1000000, # Fixed: was 10000, HF uses rope_theta=1000000
'rms_norm_epsilon': 1e-6,
'qkv_bias': False,
'scale': 1,
'max_position': 32768, # should be >= max_model_length, max position index allowed in rotary embedding
'ffn_bias': False, # Fixed: HF Qwen3 doesn't use MLP bias
'max_num_batch_tokens': 4096,
'max_model_length': 128,
'gpu_memory_utilization': 0.9,
'eos': 151645, # Fixed: should match tokenizer.eos_token_id
}
MODEL_NAME = "Qwen/Qwen3-0.6B"
PROMPTS = [
"introduce yourself" ,
"list all prime numbers within 100" ,
"give me your opinion on the impact of artificial intelligence on society" ,
]
WARMUP_STEPS = 2
OUTPUT_TOKENS = 256 # ouput token num
device = "cuda" if torch.cuda.is_available() else "cpu"
def cuda_sync():
if torch.cuda.is_available():
torch.cuda.synchronize()
def run_minivllm(tokenizer):
llm = MiniLLM(config=config)
sampling = MiniSamplingParams(
temperature=0.6,
max_tokens=OUTPUT_TOKENS,
max_model_length=128,
)
prompts = [
tokenizer.apply_chat_template(
[{"role": "user", "content": p}],
tokenize=False,
add_generation_prompt=True,
)
for p in PROMPTS
]
# warmup
for _ in range(WARMUP_STEPS):
llm.generate(prompts, sampling)
cuda_sync()
start = time.perf_counter()
outputs = llm.generate(prompts, sampling)
cuda_sync()
end = time.perf_counter()
total_tokens = sum(len(x) for x in outputs["token_ids"])
latency = end - start
return {
"latency": latency,
"tokens": total_tokens,
"tps": total_tokens / latency,
}
def run_vllm(tokenizer):
# vLLM
llm = VLLM(
model=MODEL_NAME,
tokenizer=MODEL_NAME,
trust_remote_code=False,
gpu_memory_utilization=0.75,
max_model_len=256,
speculative_config=None,
)
sampling = VLLMSamplingParams(
temperature=0.6,
max_tokens=OUTPUT_TOKENS,
)
prompts = [
tokenizer.apply_chat_template(
[{"role": "user", "content": p}],
tokenize=False,
add_generation_prompt=True,
)
for p in PROMPTS
]
# warmup
for _ in range(WARMUP_STEPS):
llm.generate(prompts, sampling)
cuda_sync()
start = time.perf_counter()
outputs = llm.generate(prompts, sampling)
cuda_sync()
end = time.perf_counter()
total_tokens = sum(len(o.outputs[0].token_ids) for o in outputs)
latency = end - start
return {
"latency": latency,
"tokens": total_tokens,
"tps": total_tokens / latency,
}
def run_transformers_test(tokenizer):
# transformers
inputs = tokenizer(PROMPTS, return_tensors="pt", padding=True, truncation=True).to(device)
model = AutoModelForCausalLM.from_pretrained(MODEL_NAME).to(device)
# Prepare attention_mask explicitly
attention_mask = inputs["attention_mask"]
# warmup
for _ in range(WARMUP_STEPS):
with torch.no_grad():
model.generate(inputs['input_ids'], attention_mask=attention_mask, max_length=OUTPUT_TOKENS)
start = time.perf_counter()
with torch.no_grad():
outputs = model.generate(inputs['input_ids'], attention_mask=attention_mask, max_length=OUTPUT_TOKENS)
end = time.perf_counter()
total_tokens = sum(len(output) for output in outputs)
latency = end - start
tps = total_tokens / latency
return {
"latency": latency,
"tokens": total_tokens,
"tps": tps,
}
def main():
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, trust_remote_code=True, padding_side='left')
print("Running minivllm benchmark...")
mini = run_minivllm(tokenizer)
print("Running vLLM benchmark...")
vllm = run_vllm(tokenizer)
print("Running transformers benchmark...")
transformers = run_transformers_test(tokenizer)
results = {
"minivllm": mini,
"vLLM": vllm,
"transformers":transformers
}
print("\n=== Benchmark Results ===")
for k, v in results.items():
print(f"{k}:")
for kk, vv in v.items():
print(f" {kk}: {vv:.4f}")
if __name__ == "__main__":
main()