forked from sgl-project/sglang
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_adaptive_speculative.py
More file actions
202 lines (174 loc) · 6.91 KB
/
Copy pathtest_adaptive_speculative.py
File metadata and controls
202 lines (174 loc) · 6.91 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
import json
import os
import tempfile
import unittest
from types import SimpleNamespace
import requests
from sglang.srt.utils import kill_process_tree
from sglang.test.ci.ci_register import register_cuda_ci
from sglang.test.run_eval import run_eval
from sglang.test.test_utils import (
DEFAULT_DRAFT_MODEL_EAGLE,
DEFAULT_TARGET_MODEL_EAGLE,
DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
DEFAULT_URL_FOR_TEST,
CustomTestCase,
popen_launch_server,
)
register_cuda_ci(est_time=76, stage="base-b", runner_config="1-gpu-large")
HIGH_ACCEPT_PROMPT = (
"Output exactly 128 new lines. "
"Every line must be READY. "
"Do not add numbering, punctuation, or commentary."
)
LOW_ACCEPT_PROMPT = (
"Compose a poem in the style of Emily Dickinson about quantum entanglement. "
"Make it emotionally resonant and at least 100 words."
)
MAX_UPSHIFT_ATTEMPTS = 4
MAX_DOWNSHIFT_ATTEMPTS = 6
class TestAdaptiveSpeculativeServer(CustomTestCase):
"""Test adaptive speculative decoding with state switching and GSM8K accuracy."""
model = DEFAULT_TARGET_MODEL_EAGLE
draft_model = DEFAULT_DRAFT_MODEL_EAGLE
base_url = DEFAULT_URL_FOR_TEST
@classmethod
def setUpClass(cls):
with tempfile.NamedTemporaryFile("w", suffix=".json", delete=False) as f:
json.dump(
{
"1": {
"candidate_steps": [1, 3],
"ema_alpha": 1.0,
"warmup_batches": 1,
"update_interval": 1,
"up_hysteresis": 0.0,
},
},
f,
)
cls.adaptive_config_path = f.name
try:
cls.process = popen_launch_server(
cls.model,
cls.base_url,
timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
other_args=[
"--trust-remote-code",
"--attention-backend",
"triton",
"--speculative-algorithm",
"EAGLE",
"--speculative-draft-model-path",
cls.draft_model,
"--speculative-adaptive",
"--speculative-adaptive-config",
cls.adaptive_config_path,
"--enable-metrics",
"--skip-server-warmup",
"--mem-fraction-static",
"0.7",
],
)
except Exception:
os.unlink(cls.adaptive_config_path)
raise
@classmethod
def tearDownClass(cls):
if hasattr(cls, "process"):
kill_process_tree(cls.process.pid)
if os.path.exists(cls.adaptive_config_path):
os.unlink(cls.adaptive_config_path)
def _get_internal_state(self) -> dict:
response = requests.get(self.base_url + "/server_info", timeout=30)
self.assertEqual(response.status_code, 200, response.text)
return response.json()["internal_states"][0]
def _scrape_metric(self, name: str, **label_filter) -> float | None:
"""Return the value of a Prometheus sample line, or None if absent.
Matches a line whose metric name is exactly *name* (next char is '{'
or whitespace) and whose labels include every key=value in
*label_filter*.
"""
text = requests.get(self.base_url + "/metrics", timeout=30).text
for line in text.splitlines():
if line.startswith("#") or not line.startswith(name):
continue
rest = line[len(name) :]
if rest and rest[0] not in "{ ":
continue
if all(f'{k}="{v}"' in line for k, v in label_filter.items()):
return float(line.rsplit(" ", 1)[1])
return None
def _generate(self, prompt: str, max_new_tokens: int = 64) -> dict:
response = requests.post(
self.base_url + "/generate",
json={
"text": prompt,
"sampling_params": {
"temperature": 0,
"max_new_tokens": max_new_tokens,
"ignore_eos": True,
},
},
timeout=180,
)
self.assertEqual(response.status_code, 200, response.text)
return response.json()
def _drive_upshift(self) -> dict:
"""Send high-acceptance prompts until steps upshift to 3."""
state = self._get_internal_state()
for _ in range(MAX_UPSHIFT_ATTEMPTS):
self._generate(HIGH_ACCEPT_PROMPT)
state = self._get_internal_state()
if state["speculative_num_steps"] == 3:
return state
return state
def _drive_downshift(self) -> dict:
"""Send low-acceptance prompts until steps downshift to 1."""
state = self._get_internal_state()
for _ in range(MAX_DOWNSHIFT_ATTEMPTS):
self._generate(LOW_ACCEPT_PROMPT)
state = self._get_internal_state()
if state["speculative_num_steps"] == 1:
return state
return state
def test_gsm8k_after_adaptive_switches(self):
"""Exercise up/down/up adaptive switches, then verify GSM8K accuracy."""
state = self._drive_upshift()
self.assertEqual(state["speculative_num_steps"], 3, f"Never upshifted: {state}")
state = self._drive_downshift()
self.assertEqual(
state["speculative_num_steps"], 1, f"Never downshifted: {state}"
)
self._drive_upshift()
args = SimpleNamespace(
base_url=self.base_url,
model=self.model,
eval_name="gsm8k",
api="completion",
max_tokens=512,
num_examples=100,
num_threads=64,
)
metrics = run_eval(args)
print(f"GSM8K after adaptive switches: {metrics}")
self.assertGreater(metrics["score"], 0.20)
server_info = requests.get(self.base_url + "/server_info").json()
avg_accept_len = server_info["internal_states"][0]["avg_spec_accept_length"]
print(f"avg_spec_accept_length={avg_accept_len:.4f}")
def test_adaptive_metrics_exposed(self):
"""After an upshift, the adaptive current-state gauges are scrapeable."""
state = self._drive_upshift()
self.assertEqual(state["speculative_num_steps"], 3, f"Never upshifted: {state}")
# One more decode so the reporter emits a fresh logging interval.
self._generate(HIGH_ACCEPT_PROMPT)
steps = self._scrape_metric("sglang:spec_num_steps")
draft_tokens = self._scrape_metric("sglang:spec_num_draft_tokens")
self.assertIn(steps, {1.0, 3.0}, "spec_num_steps gauge has unexpected value")
self.assertIn(
draft_tokens,
{2.0, 4.0},
"spec_num_draft_tokens gauge has unexpected value",
)
if __name__ == "__main__":
unittest.main()