lex4 0.4.4__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- lex4/__init__.py +5 -0
- lex4/adapt_gear.py +302 -0
- lex4/cli.py +880 -0
- lex4/engine/__init__.py +10 -0
- lex4/engine/_env.py +26 -0
- lex4/engine/blackwell_mma.py +2985 -0
- lex4/engine/codebooks.py +1086 -0
- lex4/engine/encoder.py +1112 -0
- lex4/engine/format.py +396 -0
- lex4/engine/kernels.py +1343 -0
- lex4/engine/pager.py +1875 -0
- lex4/engine/runtime.py +1064 -0
- lex4/engine/think_ctrl.py +549 -0
- lex4/engine/vllm_plugin.py +900 -0
- lex4/presets.py +165 -0
- lex4/proxy.py +1141 -0
- lex4-0.4.4.dist-info/METADATA +273 -0
- lex4-0.4.4.dist-info/RECORD +23 -0
- lex4-0.4.4.dist-info/WHEEL +5 -0
- lex4-0.4.4.dist-info/entry_points.txt +6 -0
- lex4-0.4.4.dist-info/licenses/LICENSE +165 -0
- lex4-0.4.4.dist-info/licenses/NOTICE +31 -0
- lex4-0.4.4.dist-info/top_level.txt +1 -0
lex4/__init__.py
ADDED
lex4/adapt_gear.py
ADDED
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
"""Two-gear fill-ratio adaptive speculative depth controller (`LEXICON_ADAPT_GEAR=1`).
|
|
2
|
+
|
|
3
|
+
Inert unless ``LEXICON_ADAPT_GEAR=1`` is set.
|
|
4
|
+
|
|
5
|
+
vLLM's built-in ``AcceptanceLengthController`` sets
|
|
6
|
+
``target = floor(mean_num_accepted_tokens + 1.5)``. Because ``mean_num_accepted_tokens``
|
|
7
|
+
is bounded above by the current depth ``d``, moderate-acceptance workloads like coding
|
|
8
|
+
(``mean_accepted ≈ 2.8`` at ``d=7``) immediately clamp down to ``d=4`` and then get
|
|
9
|
+
trapped at ``d=3..4``, losing 6–20% on coding and tool calls even though ``d=2`` gives
|
|
10
|
+
a +18.7% lossless speedup on conversational chat (``109 ms/pass`` vs ``148 ms/pass``).
|
|
11
|
+
|
|
12
|
+
This plugin replaces ``AcceptanceLengthController.observe_batch`` with a clean
|
|
13
|
+
two-gear fill-ratio controller (``low`` ↔ ``high``, default ``2 ↔ 7``):
|
|
14
|
+
|
|
15
|
+
- In high gear (``d = high``): shift down to ``low`` only when
|
|
16
|
+
``fill = mean_accepted / mean_draft < down_ratio`` (default ``0.30``).
|
|
17
|
+
Chat (``~20–24%`` fill) shifts immediately to ``d=2`` (``109 ms/pass``, ``+18.7%``),
|
|
18
|
+
while coding (``~41%``), tools (``~59%``), and edits (``~90%``) stay pinned at ``d=7``.
|
|
19
|
+
- In low gear (``d = low``): shift immediately back up to ``high`` as soon as
|
|
20
|
+
``fill = mean_accepted / mean_draft >= up_ratio`` (default ``0.64``).
|
|
21
|
+
Chat stays in low gear (``~56–59%`` fill), while coding (``~71%``), tools (``~90%``),
|
|
22
|
+
and edits (``~97%``) snap straight back to ``d=7`` within one window (~0.9 s).
|
|
23
|
+
"""
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
import os
|
|
27
|
+
from typing import Any
|
|
28
|
+
|
|
29
|
+
STATE: dict[str, Any] = {
|
|
30
|
+
"patched": False,
|
|
31
|
+
"config": None,
|
|
32
|
+
"windows": 0,
|
|
33
|
+
"low_windows": 0,
|
|
34
|
+
"high_windows": 0,
|
|
35
|
+
"shifts_down": 0,
|
|
36
|
+
"shifts_up": 0,
|
|
37
|
+
"last_depth": None,
|
|
38
|
+
"last_fill": None,
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def is_enabled(env=None) -> bool:
|
|
43
|
+
"""True when LEX4_ADAPT_GEAR=1 or LEXICON_ADAPT_GEAR=1 is set."""
|
|
44
|
+
src = os.environ if env is None else env
|
|
45
|
+
return src.get("LEX4_ADAPT_GEAR") == "1" or src.get("LEXICON_ADAPT_GEAR") == "1"
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def read_config(env=None) -> dict[str, Any]:
|
|
49
|
+
"""Parse and validate LEX4_ADAPT_* / LEXICON_ADAPT_* environment variables."""
|
|
50
|
+
src = os.environ if env is None else env
|
|
51
|
+
def _g(k: str, default: str) -> str:
|
|
52
|
+
return src.get(f"LEX4_{k}") or src.get(f"LEXICON_{k}") or default
|
|
53
|
+
low = int(_g("ADAPT_LOW", "2"))
|
|
54
|
+
high = int(_g("ADAPT_HIGH", "7"))
|
|
55
|
+
down_ratio = float(_g("ADAPT_DOWN_RATIO", "0.28"))
|
|
56
|
+
up_ratio = float(_g("ADAPT_UP_RATIO", "0.64"))
|
|
57
|
+
down_instant = float(_g("ADAPT_DOWN_INSTANT", str(min(0.20, down_ratio))))
|
|
58
|
+
up_instant = float(_g("ADAPT_UP_INSTANT", str(max(up_ratio, up_ratio))))
|
|
59
|
+
confirm_down = int(
|
|
60
|
+
src.get("LEX4_ADAPT_CONFIRM_DOWN")
|
|
61
|
+
or src.get("LEXICON_ADAPT_CONFIRM_DOWN")
|
|
62
|
+
or src.get("LEXICON_ADAPT_CONFIRM_WINDOWS")
|
|
63
|
+
or "2"
|
|
64
|
+
)
|
|
65
|
+
confirm_up = int(_g("ADAPT_CONFIRM_UP", "1"))
|
|
66
|
+
if low < 1:
|
|
67
|
+
raise ValueError(f"LEXICON_ADAPT_LOW must be >= 1, not {low}")
|
|
68
|
+
if high <= low:
|
|
69
|
+
raise ValueError(f"LEXICON_ADAPT_HIGH ({high}) must be > LEXICON_ADAPT_LOW ({low})")
|
|
70
|
+
if not (0.0 < down_ratio < 1.0):
|
|
71
|
+
raise ValueError(f"LEXICON_ADAPT_DOWN_RATIO must be in (0, 1), not {down_ratio}")
|
|
72
|
+
if not (0.0 < up_ratio <= 1.0):
|
|
73
|
+
raise ValueError(f"LEXICON_ADAPT_UP_RATIO must be in (0, 1], not {up_ratio}")
|
|
74
|
+
if up_ratio <= down_ratio:
|
|
75
|
+
raise ValueError(
|
|
76
|
+
f"LEXICON_ADAPT_UP_RATIO ({up_ratio}) must be > LEXICON_ADAPT_DOWN_RATIO ({down_ratio})"
|
|
77
|
+
)
|
|
78
|
+
if confirm_down < 1 or confirm_up < 1:
|
|
79
|
+
raise ValueError(f"confirm windows must be >= 1, got down={confirm_down} up={confirm_up}")
|
|
80
|
+
return {
|
|
81
|
+
"low": low,
|
|
82
|
+
"high": high,
|
|
83
|
+
"down_ratio": down_ratio,
|
|
84
|
+
"up_ratio": up_ratio,
|
|
85
|
+
"down_instant": down_instant,
|
|
86
|
+
"up_instant": up_instant,
|
|
87
|
+
"confirm_down": confirm_down,
|
|
88
|
+
"confirm_up": confirm_up,
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def active_query_lens(env=None) -> set[int]:
|
|
93
|
+
"""The two target decode query lengths (``d + 1``) needed for CUDA graph capture."""
|
|
94
|
+
cfg = read_config(env)
|
|
95
|
+
return {cfg["low"] + 1, cfg["high"] + 1}
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def next_gear(
|
|
99
|
+
current: int,
|
|
100
|
+
mean_accepted: float,
|
|
101
|
+
mean_draft: float,
|
|
102
|
+
*,
|
|
103
|
+
low: int,
|
|
104
|
+
high: int,
|
|
105
|
+
down_ratio: float,
|
|
106
|
+
up_ratio: float,
|
|
107
|
+
) -> tuple[int, float]:
|
|
108
|
+
"""Compute ``(new_depth, fill_ratio)`` for the two-gear controller."""
|
|
109
|
+
fill = (mean_accepted / mean_draft) if mean_draft > 0.0 else 0.0
|
|
110
|
+
if current > low:
|
|
111
|
+
return (low if fill < down_ratio else high), fill
|
|
112
|
+
return (high if fill >= up_ratio else low), fill
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def next_gear_hysteresis(
|
|
116
|
+
current: int,
|
|
117
|
+
mean_accepted: float,
|
|
118
|
+
mean_draft: float,
|
|
119
|
+
streak: int,
|
|
120
|
+
*,
|
|
121
|
+
low: int,
|
|
122
|
+
high: int,
|
|
123
|
+
down_ratio: float,
|
|
124
|
+
up_ratio: float,
|
|
125
|
+
down_instant: float = 0.20,
|
|
126
|
+
up_instant: float = 0.64,
|
|
127
|
+
confirm_down: int = 2,
|
|
128
|
+
confirm_up: int = 1,
|
|
129
|
+
) -> tuple[int, float, int]:
|
|
130
|
+
"""Asymmetric hysteresis transition returning ``(new_depth, fill_ratio, new_streak)``.
|
|
131
|
+
|
|
132
|
+
- Clear chat (`fill < down_instant`) snaps DOWN on window #1; borderline coding reasoning dips
|
|
133
|
+
(`down_instant <= fill < down_ratio`) require `confirm_down` consecutive windows so coding
|
|
134
|
+
stays pinned at `d=7`.
|
|
135
|
+
- Recovery to coding/tools (`fill >= up_ratio`, default `confirm_up=1`) snaps UP immediately so
|
|
136
|
+
short tool calls never lose speculative depth!
|
|
137
|
+
"""
|
|
138
|
+
fill = (mean_accepted / mean_draft) if mean_draft > 0.0 else 0.0
|
|
139
|
+
if current > low:
|
|
140
|
+
if fill < down_instant:
|
|
141
|
+
return low, fill, 0
|
|
142
|
+
if fill < down_ratio:
|
|
143
|
+
nxt_streak = streak + 1
|
|
144
|
+
if nxt_streak >= confirm_down:
|
|
145
|
+
return low, fill, 0
|
|
146
|
+
return high, fill, nxt_streak
|
|
147
|
+
return high, fill, 0
|
|
148
|
+
if fill >= up_instant:
|
|
149
|
+
return high, fill, 0
|
|
150
|
+
if fill >= up_ratio:
|
|
151
|
+
nxt_streak = streak + 1
|
|
152
|
+
if nxt_streak >= confirm_up:
|
|
153
|
+
return high, fill, 0
|
|
154
|
+
return low, fill, nxt_streak
|
|
155
|
+
return low, fill, 0
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def stats() -> dict[str, Any]:
|
|
159
|
+
"""Return telemetry snapshot for stats-rank*.json."""
|
|
160
|
+
out: dict[str, Any] = {
|
|
161
|
+
"patched": bool(STATE["patched"]),
|
|
162
|
+
"windows": int(STATE["windows"]),
|
|
163
|
+
"low_windows": int(STATE["low_windows"]),
|
|
164
|
+
"high_windows": int(STATE["high_windows"]),
|
|
165
|
+
"shifts_down": int(STATE["shifts_down"]),
|
|
166
|
+
"shifts_up": int(STATE["shifts_up"]),
|
|
167
|
+
"last_depth": STATE["last_depth"],
|
|
168
|
+
"last_fill": round(STATE["last_fill"], 4) if STATE["last_fill"] is not None else None,
|
|
169
|
+
}
|
|
170
|
+
if STATE["config"] is not None:
|
|
171
|
+
out["config"] = dict(STATE["config"])
|
|
172
|
+
return out
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def reset_stats() -> None:
|
|
176
|
+
"""Zero window and shift counters (e.g. on hook RESET)."""
|
|
177
|
+
STATE["windows"] = 0
|
|
178
|
+
STATE["low_windows"] = 0
|
|
179
|
+
STATE["high_windows"] = 0
|
|
180
|
+
STATE["shifts_down"] = 0
|
|
181
|
+
STATE["shifts_up"] = 0
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def patch(env=None) -> bool:
|
|
185
|
+
"""Monkey-patch ``AcceptanceLengthController.observe_batch`` with the two-gear fill-ratio rule.
|
|
186
|
+
|
|
187
|
+
Inert unless ``LEXICON_ADAPT_GEAR=1`` is set. Safe to call multiple times.
|
|
188
|
+
"""
|
|
189
|
+
if not is_enabled(env):
|
|
190
|
+
return False
|
|
191
|
+
if STATE["patched"]:
|
|
192
|
+
return True
|
|
193
|
+
cfg = read_config(env)
|
|
194
|
+
STATE["config"] = cfg
|
|
195
|
+
|
|
196
|
+
from vllm.v1.spec_decode.dynamic.acceptance_length import (
|
|
197
|
+
AcceptanceLengthController,
|
|
198
|
+
AcceptanceLengthUpdate,
|
|
199
|
+
)
|
|
200
|
+
|
|
201
|
+
low_cfg = cfg["low"]
|
|
202
|
+
high_cfg = cfg["high"]
|
|
203
|
+
down_ratio = cfg["down_ratio"]
|
|
204
|
+
up_ratio = cfg["up_ratio"]
|
|
205
|
+
down_instant = cfg["down_instant"]
|
|
206
|
+
up_instant = cfg["up_instant"]
|
|
207
|
+
confirm_down = cfg["confirm_down"]
|
|
208
|
+
confirm_up = cfg["confirm_up"]
|
|
209
|
+
|
|
210
|
+
def gear_observe_batch(
|
|
211
|
+
self,
|
|
212
|
+
*,
|
|
213
|
+
num_drafts: int,
|
|
214
|
+
num_draft_tokens: int,
|
|
215
|
+
num_accepted_tokens: int,
|
|
216
|
+
):
|
|
217
|
+
if num_drafts < 0 or num_draft_tokens < 0 or num_accepted_tokens < 0:
|
|
218
|
+
raise ValueError("Speculative decoding counts must be non-negative.")
|
|
219
|
+
if num_accepted_tokens > num_draft_tokens:
|
|
220
|
+
raise ValueError("num_accepted_tokens must not exceed num_draft_tokens.")
|
|
221
|
+
if num_drafts == 0:
|
|
222
|
+
if num_draft_tokens or num_accepted_tokens:
|
|
223
|
+
raise ValueError("Token counts require at least one draft.")
|
|
224
|
+
return None
|
|
225
|
+
|
|
226
|
+
# Stale-gear pipeline filter: ignore 1-2 post-shift in-flight steps drafted at the OLD gear
|
|
227
|
+
# so they never corrupt the newly entered gear's fill ratio!
|
|
228
|
+
step_draft_len = num_draft_tokens / num_drafts
|
|
229
|
+
if abs(step_draft_len - self.num_spec_tokens) > 0.25:
|
|
230
|
+
return None
|
|
231
|
+
|
|
232
|
+
self._num_observation_steps += 1
|
|
233
|
+
self._num_drafts += num_drafts
|
|
234
|
+
self._num_draft_tokens += num_draft_tokens
|
|
235
|
+
self._num_accepted_tokens += num_accepted_tokens
|
|
236
|
+
if self._num_observation_steps < self.observation_window:
|
|
237
|
+
return None
|
|
238
|
+
|
|
239
|
+
mean_acc = self._num_accepted_tokens / self._num_drafts
|
|
240
|
+
mean_draft = self._num_draft_tokens / self._num_drafts
|
|
241
|
+
high = min(high_cfg, self.max_num_spec_tokens)
|
|
242
|
+
low = min(low_cfg, high)
|
|
243
|
+
prev = self.num_spec_tokens
|
|
244
|
+
streak = int(getattr(self, "_lexicon_gear_streak", 0))
|
|
245
|
+
new_depth, fill, new_streak = next_gear_hysteresis(
|
|
246
|
+
prev,
|
|
247
|
+
mean_acc,
|
|
248
|
+
mean_draft,
|
|
249
|
+
streak,
|
|
250
|
+
low=low,
|
|
251
|
+
high=high,
|
|
252
|
+
down_ratio=down_ratio,
|
|
253
|
+
up_ratio=up_ratio,
|
|
254
|
+
down_instant=down_instant,
|
|
255
|
+
up_instant=up_instant,
|
|
256
|
+
confirm_down=confirm_down,
|
|
257
|
+
confirm_up=confirm_up,
|
|
258
|
+
)
|
|
259
|
+
self._lexicon_gear_streak = new_streak
|
|
260
|
+
self.num_spec_tokens = new_depth
|
|
261
|
+
self._reset_window()
|
|
262
|
+
|
|
263
|
+
STATE["windows"] += 1
|
|
264
|
+
if new_depth <= low:
|
|
265
|
+
STATE["low_windows"] += 1
|
|
266
|
+
else:
|
|
267
|
+
STATE["high_windows"] += 1
|
|
268
|
+
STATE["last_depth"] = int(new_depth)
|
|
269
|
+
STATE["last_fill"] = float(fill)
|
|
270
|
+
if new_depth < prev:
|
|
271
|
+
STATE["shifts_down"] += 1
|
|
272
|
+
print(
|
|
273
|
+
f"[lexicon_adapt_gear] shift DOWN {prev} -> {new_depth} "
|
|
274
|
+
f"(fill={100.0 * fill:.1f}% < {100.0 * down_ratio:.1f}%, "
|
|
275
|
+
f"mean_acc={mean_acc:.2f}/{mean_draft:.2f})",
|
|
276
|
+
flush=True,
|
|
277
|
+
)
|
|
278
|
+
elif new_depth > prev:
|
|
279
|
+
STATE["shifts_up"] += 1
|
|
280
|
+
print(
|
|
281
|
+
f"[lexicon_adapt_gear] shift UP {prev} -> {new_depth} "
|
|
282
|
+
f"(fill={100.0 * fill:.1f}% >= {100.0 * up_ratio:.1f}%, "
|
|
283
|
+
f"mean_acc={mean_acc:.2f}/{mean_draft:.2f})",
|
|
284
|
+
flush=True,
|
|
285
|
+
)
|
|
286
|
+
|
|
287
|
+
return AcceptanceLengthUpdate(
|
|
288
|
+
previous_num_spec_tokens=prev,
|
|
289
|
+
num_spec_tokens=new_depth,
|
|
290
|
+
mean_num_accepted_tokens=mean_acc,
|
|
291
|
+
mean_num_draft_tokens=mean_draft,
|
|
292
|
+
)
|
|
293
|
+
|
|
294
|
+
AcceptanceLengthController.observe_batch = gear_observe_batch
|
|
295
|
+
STATE["patched"] = True
|
|
296
|
+
print(
|
|
297
|
+
f"[lexicon_adapt_gear] enabled 2-gear hysteresis controller "
|
|
298
|
+
f"(low={low_cfg}, high={high_cfg}, down<{100.0 * down_instant:.0f}%/{100.0 * down_ratio:.0f}%x{confirm_down}, "
|
|
299
|
+
f"up>={100.0 * up_ratio:.0f}%x{confirm_up})",
|
|
300
|
+
flush=True,
|
|
301
|
+
)
|
|
302
|
+
return True
|