forked from PaddlePaddle/FastDeploy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_ernie_21b_tp1_dp4_mtp.py
More file actions
569 lines (464 loc) · 17 KB
/
test_ernie_21b_tp1_dp4_mtp.py
File metadata and controls
569 lines (464 loc) · 17 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
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
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
296
297
298
299
300
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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
# Copyright (c) 2026 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.
import json
import os
import shutil
import signal
import subprocess
import sys
import time
import pytest
import requests
tests_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
sys.path.insert(0, tests_dir)
from e2e.utils.serving_utils import (
FD_API_PORT,
FD_CACHE_QUEUE_PORT,
FD_ENGINE_QUEUE_PORT,
FD_METRICS_PORT,
PORTS_TO_CLEAN,
clean_ports,
is_port_open,
)
@pytest.fixture(scope="session", autouse=True)
def setup_and_run_server(api_url):
"""
Pytest fixture that runs once per test session:
- Cleans ports before tests
- Starts the API server as a subprocess
- Waits for server port to open (up to 30 seconds)
- Tears down server after all tests finish
"""
print("Pre-test port cleanup...")
ports_to_add = [
FD_API_PORT + 1,
FD_API_PORT + 2,
FD_API_PORT + 3,
FD_METRICS_PORT + 1,
FD_METRICS_PORT + 2,
FD_METRICS_PORT + 3,
FD_CACHE_QUEUE_PORT + 1,
FD_CACHE_QUEUE_PORT + 2,
FD_CACHE_QUEUE_PORT + 3,
FD_ENGINE_QUEUE_PORT + 1,
FD_ENGINE_QUEUE_PORT + 2,
FD_ENGINE_QUEUE_PORT + 3,
]
for port in ports_to_add:
if port not in PORTS_TO_CLEAN:
PORTS_TO_CLEAN.append(port)
clean_ports(PORTS_TO_CLEAN)
print("log dir clean ")
if os.path.exists("log") and os.path.isdir("log"):
shutil.rmtree("log")
base_path = os.getenv("MODEL_PATH")
if base_path:
model_path = os.path.join(base_path, "ernie-4_5-21b-a3b-bf16-paddle")
else:
model_path = "./ernie-4_5-21b-a3b-bf16-paddle"
mtp_model_path = os.path.join(model_path, "mtp")
speculative_config = {"method": "mtp", "num_speculative_tokens": 1, "model": mtp_model_path}
log_path = "server.log"
cmd = [
sys.executable,
"-m",
"fastdeploy.entrypoints.openai.multi_api_server",
"--num-servers",
"4",
"--ports",
f"{FD_API_PORT},{FD_API_PORT + 1},{FD_API_PORT + 2},{FD_API_PORT + 3}",
"--metrics-ports",
f"{FD_METRICS_PORT},{FD_METRICS_PORT + 1},{FD_METRICS_PORT + 2},{FD_METRICS_PORT + 3}",
"--args",
"--model",
model_path,
"--engine-worker-queue-port",
f"{FD_ENGINE_QUEUE_PORT},{FD_ENGINE_QUEUE_PORT + 1},{FD_ENGINE_QUEUE_PORT + 2},{FD_ENGINE_QUEUE_PORT + 3}",
"--cache-queue-port",
f"{FD_CACHE_QUEUE_PORT},{FD_CACHE_QUEUE_PORT + 1},{FD_CACHE_QUEUE_PORT + 2},{FD_CACHE_QUEUE_PORT + 3}",
"--tensor-parallel-size",
"1",
"--data-parallel-size",
"4",
"--max-model-len",
"65536",
"--max-num-seqs",
"32",
"--quantization",
"block_wise_fp8",
"--enable-logprob",
"--speculative-config",
json.dumps(speculative_config),
"--graph-optimization-config",
'{"use_cudagraph":true, "use_unique_memory_pool":true, "draft_model_use_cudagraph":true}',
]
# Start subprocess in new process group
if os.path.exists("log"):
shutil.rmtree("log")
with open(log_path, "w") as logfile:
process = subprocess.Popen(
cmd,
stdout=logfile,
stderr=subprocess.STDOUT,
start_new_session=True, # Enables killing full group via os.killpg
)
# Wait up to 300 seconds for API server to be ready
for _ in range(300):
if is_port_open("127.0.0.1", FD_API_PORT):
print(f"Server is up on port {FD_API_PORT}")
break
time.sleep(1)
else:
print("[TIMEOUT] API server failed to start in 5 minutes. Cleaning up...")
try:
os.killpg(process.pid, signal.SIGTERM)
# clean()
except Exception as e:
print(f"Failed to kill process group: {e}")
raise RuntimeError(f"API server did not start on port {FD_API_PORT}")
yield # Run tests
print("\n===== Post-test server cleanup... =====")
try:
os.killpg(process.pid, signal.SIGTERM)
# clean()
time.sleep(10)
print(f"server (pid={process.pid}) terminated")
except Exception as e:
print(f"Failed to terminate API server: {e}")
@pytest.fixture(scope="session")
def api_url(request):
"""
Returns the API endpoint URL for chat completions.
"""
return f"http://0.0.0.0:{FD_API_PORT}/v1/chat/completions"
@pytest.fixture(scope="session")
def metrics_url(request):
"""
Returns the metrics endpoint URL.
"""
return f"http://0.0.0.0:{FD_METRICS_PORT}/metrics"
@pytest.fixture
def headers():
"""
Returns common HTTP request headers.
"""
return {"Content-Type": "application/json"}
def send_request(url, payload, timeout=60):
"""
Send a POST request to the specified URL with the given payload.
"""
headers = {
"Content-Type": "application/json",
}
try:
res = requests.post(url, headers=headers, json=payload, timeout=timeout)
print("🟢 Receiving response...\n")
return res
except requests.exceptions.Timeout:
print(f"❌ Request timed out (>{timeout} seconds)")
return None
except requests.exceptions.RequestException as e:
print(f"❌ Request failed: {e}")
return None
def get_stream_chunks(response):
"""
Parse a streaming HTTP response into a list of JSON chunks.
This helper processes Server-Sent Events (SSE) style responses,
strips the 'data:' prefix, ignores the '[DONE]' marker, and
decodes each chunk into a Python dict.
Args:
response: HTTP response returned by send_request().
Returns:
List[dict]: Parsed stream chunks in arrival order.
"""
chunks = []
if response.status_code == 200:
for line in response.iter_lines(decode_unicode=True):
if not line:
continue
if line.startswith("data: "):
line = line[len("data: ") :]
if line.strip() == "[DONE]":
break
try:
chunk = json.loads(line)
chunks.append(chunk)
except Exception as e:
print(f"Failed to parse chunk: {e}, raw line: {line}")
else:
print(f"Request failed, status code: {response.status_code}")
print("Response body:", response.text)
return chunks
def get_token_list(response):
"""
Extract generated token strings from a non-streaming response.
This function reads token-level information from
`choices[0].logprobs.content` and returns the generated token list
in order. It is mainly used for stop-sequence validation.
Args:
response (dict): JSON-decoded inference response.
Returns:
List[str]: Generated token strings.
"""
token_list = []
try:
content_logprobs = response["choices"][0]["logprobs"]["content"]
except (KeyError, IndexError, TypeError) as e:
print(f"Failed to extract logprobs: {e}")
return []
for token_info in content_logprobs:
token = token_info.get("token")
if token is not None:
token_list.append(token)
print(f"Token List: {token_list}")
return token_list
def extract_logprobs(chunks):
"""
Extract token-level logprobs from streaming response chunks.
This helper skips chunks without choices, usage-only chunks,
and chunks without logprobs, and aggregates token-level
logprob information in generation order.
Args:
chunks (List[dict]): Parsed streaming chunks.
Returns:
List[List[dict]]: Structured logprobs for each generated token.
"""
results = []
for chunk in chunks:
choices = chunk.get("choices")
if not choices:
continue
choice = choices[0]
logprobs = choice.get("logprobs")
if not logprobs or not logprobs.get("content"):
continue
token_infos = []
for item in logprobs["content"]:
token_infos.append(
{
"token": item["token"],
"logprob": item["logprob"],
"top_logprobs": [
{
"token": tlp["token"],
"logprob": tlp["logprob"],
}
for tlp in item.get("top_logprobs", [])
],
}
)
results.append(token_infos)
return results
def test_text_diff(api_url):
"""
Validate deterministic streaming output against a fixed text baseline.
The test uses fixed decoding parameters and seed, concatenates
all streamed content, and performs a strict byte-level comparison
with a stored baseline file.
"""
payload = {
"stream": True,
"seed": 21,
"top_p": 0,
"stop": ["</s>", "<eos>", "<|endoftext|>", "<|im_end|>"],
"chat_template_kwargs": {
"options": {"thinking_mode": "close"},
},
"bad_words_token_ids": [101031, 101032, 101027, 101028, 101023, 101024],
"messages": [{"role": "user", "content": "解释一下温故而知新"}],
}
response = send_request(url=api_url, payload=payload)
chunks = get_stream_chunks(response)
result = "".join(x["choices"][0]["delta"]["content"] for x in chunks)
print(result)
base_path = os.getenv("MODEL_PATH")
if base_path:
base_file = os.path.join(base_path, "21b_tp1_dp4_mtp_text_baseline.txt")
else:
base_file = "21b_tp1_dp4_mtp_text_baseline.txt"
with open(base_file, "r", encoding="utf-8") as f:
baseline = f.read()
if result != baseline:
with open("21b_tp1_dp4_mtp_text_tmp.txt", "w", encoding="utf-8") as f:
f.write(result)
assert result == baseline, f"Text mismatch with baseline\nresult: {result}\nbaseline: {baseline}"
def test_chat_usage_stream(api_url):
"""
Verify token usage statistics for chat completion in streaming mode.
The test ensures:
- Generated content is non-empty
- completion_tokens respects min/max constraints
- total_tokens equals prompt_tokens + completion_tokens
"""
payload = {
"stream": True,
"stream_options": {
"include_usage": True,
"continuous_usage_stats": True,
},
"messages": [{"role": "user", "content": "解释一下温故而知新"}],
"min_tokens": 10,
"max_tokens": 50,
}
response = send_request(url=api_url, payload=payload)
chunks = get_stream_chunks(response)
result = "".join(x["choices"][0]["delta"]["content"] for x in chunks[:-1])
assert result != "", "Empty generation result"
usage = chunks[-1]["usage"]
total_tokens = usage["completion_tokens"] + usage["prompt_tokens"]
assert payload["max_tokens"] >= usage["completion_tokens"]
assert payload["min_tokens"] <= usage["completion_tokens"]
assert usage["total_tokens"] == total_tokens
def test_chat_usage_non_stream(api_url):
"""
Verify token usage statistics for chat completion in non-streaming mode.
"""
payload = {
"stream": False,
"messages": [{"role": "user", "content": "解释一下温故而知新"}],
"temperature": 1.0,
"seed": 21,
"top_p": 0,
"stop": ["</s>", "<eos>", "<|endoftext|>", "<|im_end|>"],
"min_tokens": 10,
"max_tokens": 50,
"chat_template_kwargs": {
"options": {"thinking_mode": "close"},
},
"bad_words_token_ids": [101031, 101032, 101027, 101028, 101023, 101024],
}
response = send_request(url=api_url, payload=payload).json()
usage = response["usage"]
result = response["choices"][0]["message"]["content"]
assert result != "", "Empty generation result"
total_tokens = usage["completion_tokens"] + usage["prompt_tokens"]
assert payload["max_tokens"] >= usage["completion_tokens"]
assert payload["min_tokens"] <= usage["completion_tokens"]
assert usage["total_tokens"] == total_tokens
def test_non_chat_usage_stream(api_url):
"""
Verify usage statistics for completions API in streaming mode.
"""
payload = {
"model": "null",
"prompt": "你好,你是谁?",
"stream": True,
"stream_options": {
"include_usage": True,
"continuous_usage_stats": True,
},
"min_tokens": 10,
"max_tokens": 50,
"seed": 566,
"chat_template_kwargs": {
"options": {"thinking_mode": "close"},
},
"bad_words_token_ids": [101031, 101032, 101027, 101028, 101023, 101024],
}
api_url = api_url.replace("chat/completions", "completions")
response = send_request(url=api_url, payload=payload)
chunks = get_stream_chunks(response)
usage = chunks[-1]["usage"]
total_tokens = usage["completion_tokens"] + usage["prompt_tokens"]
assert payload["max_tokens"] >= usage["completion_tokens"]
assert payload["min_tokens"] <= usage["completion_tokens"]
assert usage["total_tokens"] == total_tokens
def test_non_chat_usage_non_stream(api_url):
"""
Verify usage statistics for completions API in non-streaming mode.
"""
payload = {
"model": "null",
"prompt": "你好,你是谁?",
"stream": False,
"min_tokens": 10,
"max_tokens": 50,
"seed": 566,
"chat_template_kwargs": {
"options": {"thinking_mode": "close"},
},
"bad_words_token_ids": [101031, 101032, 101027, 101028, 101023, 101024],
}
api_url = api_url.replace("chat/completions", "completions")
response = send_request(url=api_url, payload=payload).json()
usage = response["usage"]
result = response["choices"][0]["text"]
assert result != "", "Empty generation result"
total_tokens = usage["completion_tokens"] + usage["prompt_tokens"]
assert payload["max_tokens"] >= usage["completion_tokens"]
assert payload["min_tokens"] <= usage["completion_tokens"]
assert usage["total_tokens"] == total_tokens
def test_non_stream_with_logprobs(api_url):
"""
Verify deterministic logprobs output in non-streaming mode.
"""
payload = {
"stream": False,
"messages": [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "牛顿的三大运动定律是什么?"},
],
"max_tokens": 3,
"logprobs": True,
"top_logprobs": 5,
"seed": 21,
"min_tokens": 1,
"chat_template_kwargs": {
"options": {"thinking_mode": "close"},
},
"bad_words_token_ids": [101031, 101032, 101027, 101028, 101023, 101024],
}
resp_json = send_request(url=api_url, payload=payload).json()
logprobs = resp_json["choices"][0]["logprobs"]
base_path = os.getenv("MODEL_PATH")
if base_path:
base_file = os.path.join(base_path, "21b_tp1_dp4_mtp_logprobs_non_stream_static_baseline_0419.txt")
else:
base_file = "21b_tp1_dp4_mtp_logprobs_non_stream_static_baseline_0419.txt"
with open(base_file, "r", encoding="utf-8") as f:
baseline = json.load(f)
if logprobs != baseline:
with open("21b_tp1_dp4_mtp_logprobs_non_stream_static_tmp.txt", "w", encoding="utf-8") as f:
f.write(json.dumps(logprobs, ensure_ascii=False, indent=2))
assert logprobs == baseline
def test_stream_with_logprobs(api_url):
"""
Verify deterministic logprobs output in streaming mode.
"""
payload = {
"stream": True,
"messages": [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "牛顿的三大运动定律是什么?"},
],
"max_tokens": 3,
"logprobs": True,
"top_logprobs": 5,
"min_tokens": 1,
"seed": 21,
}
response = send_request(url=api_url, payload=payload)
chunks = get_stream_chunks(response)
logprobs = extract_logprobs(chunks)
base_path = os.getenv("MODEL_PATH")
if base_path:
base_file = os.path.join(base_path, "21b_tp1_dp4_mtp_logprobs_stream_static_baseline_0419.txt")
else:
base_file = "21b_tp1_dp4_mtp_logprobs_stream_static_baseline_0419.txt"
with open(base_file, "r", encoding="utf-8") as f:
baseline = json.load(f)
if logprobs != baseline:
with open("21b_tp1_dp4_mtp_logprobs_stream_static_tmp.txt", "w", encoding="utf-8") as f:
f.write(json.dumps(logprobs, ensure_ascii=False, indent=2))
assert logprobs == baseline