probe_ingest_prewarm.py
9.37 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
"""摄入「预热」A/B 实测脚本:加不加预热,对 DashScope 上下文缓存命中率到底有没有帮助。
背景
----
摄入 Phase2 里,多个 Writer 并发调用同一个 system 前缀(skill+契约[+原文],即 shared_prefix),
各自尾部拼上不同的「本页任务」。DashScope 的隐式缓存只在「前缀已被写入缓存」后才对后续请求命中,
而写缓存有延迟。于是有人担心:并发 Writer 同时发出,前缀还没焼热,大家都全价——是否该先「预热」?
本脚本用三组对照,直接量出缓存命中率(cached_tokens / prompt_tokens):
组1 cold_concurrent —— 不预热,N 个 Writer 直接并发。
组2 planner_then_writers —— 先串行 1 个 Planner 请求焼热前缀,再并发 N 个 Writer(= 现状)。
组3 planner_prewarm_writers —— Planner 之后再插 1 个「纯前缀」预热请求,再并发 N 个 Writer。
三组的 N 个 Writer 请求(tail_0..tail_{N-1})完全一致,只有前面的预热策略不同,
所以 Writer 部分的命中率可直接对比:
- 组2 vs 组1:Planner 是否已经天然充当了预热;
- 组3 vs 组2:在 Planner 之外再加一个专门的预热,还有没有增量收益(以及它自身的额外成本/延迟)。
每组用各自独立的随机 salt 作为前缀开头,保证三组从「冷」开始、互不蹭缓存。
用法:
python scripts/probe_ingest_prewarm.py
可选环境变量:
PROBE_MODEL 默认取 config.INGEST_MODEL_NAME(qwen3.7-plus)
PROBE_WRITERS 每组并发 Writer 数,默认 6
PROBE_PREFIX_CHARS 共享前缀目标字符数,默认 6000(务必远超缓存最小长度)
PROBE_MAX_TOKENS 每次生成上限,默认 32(只关心 input 缓存,输出越短越省)
"""
import asyncio
import os
import sys
import time
import uuid
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import config # noqa: E402 读取 API_KEY / INGEST_MODEL_NAME / .env
from src.utils.llm_models import DEFAULT_DASHSCOPE_COMPATIBLE_BASE_URL # noqa: E402
from openai import AsyncOpenAI # noqa: E402
MODEL = os.environ.get("PROBE_MODEL", config.INGEST_MODEL_NAME)
BASE_URL = os.environ.get("DASHSCOPE_COMPATIBLE_BASE_URL", DEFAULT_DASHSCOPE_COMPATIBLE_BASE_URL)
N_WRITERS = int(os.environ.get("PROBE_WRITERS", "6"))
PREFIX_CHARS = int(os.environ.get("PROBE_PREFIX_CHARS", "6000"))
MAX_TOKENS = int(os.environ.get("PROBE_MAX_TOKENS", "32"))
client = AsyncOpenAI(api_key=config.API_KEY, base_url=BASE_URL)
# ------------------------------------------------------------------ 前缀 / 尾部构造
# 一段稳定的「类契约/类原文」文本,重复拼到目标长度,模拟 shared_prefix 里那份逐字节一致的大前缀。
_PREFIX_UNIT = (
"【Schema Contract】字段说明:每个页面必须包含 type、slug、title、related_links、sub_business;"
"type 取值来自 canonical_types 枚举;series/brand/business_category/role 为文档级过滤维度;"
"sub_business 为页面级维度,取值必须来自 sub_business_values 枚举。写作规则:忠实原文、"
"不编造事实、不展开评价、表格保留关键列名。【原始文档内容】以下为某长文档的稳定正文片段,"
"用于占位以拉长共享前缀,确保其长度远超上下文缓存的最小命中阈值,从而可被缓存命中。"
)
def build_shared_prefix(salt: str) -> str:
"""salt 放最前面:三组各自唯一 → 从冷开始、互不干扰;组内所有请求 salt 相同 → 共享同一前缀。"""
body = (_PREFIX_UNIT * (PREFIX_CHARS // len(_PREFIX_UNIT) + 1))[:PREFIX_CHARS]
return f"[probe-salt:{salt}]\n{body}"
def writer_tail(i: int) -> str:
"""每个 Writer 独有的「本页任务」,模拟并发请求在共享前缀之后的分叉。"""
return (
f"\n———— 以上为共享上下文,以下为你的本页任务 ————\n"
f"你是 WriterAgent。本页运行时上下文:page_index={i},"
f"slug=probe-page-{i},title=探针页面{i},sub_business=测试子业务{i}。\n"
f"请只回复两个字:完成。"
)
PLANNER_TAIL = (
"\n———— 以上为共享上下文,以下为你的任务 ————\n"
"你是 PlannerAgent。请只回复两个字:完成。"
)
async def one_call(system_prompt: str, tag: str) -> dict:
"""发一次非流式请求,返回 input / cached / 耗时。enable_thinking=False 省 token 且避免长输出。"""
t0 = time.perf_counter()
resp = await client.chat.completions.create(
model=MODEL,
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": "开始。"},
],
max_tokens=MAX_TOKENS,
temperature=0.1,
extra_body={"enable_thinking": False},
)
dt = time.perf_counter() - t0
usage = resp.usage
prompt_tokens = int(getattr(usage, "prompt_tokens", 0) or 0)
details = getattr(usage, "prompt_tokens_details", None)
cached = int(getattr(details, "cached_tokens", 0) or 0) if details else 0
return {"tag": tag, "input": prompt_tokens, "cached": cached, "dt": dt}
def _summarize(name: str, warmups: list[dict], writers: list[dict], wall: float) -> dict:
w_in = sum(r["input"] for r in writers)
w_cached = sum(r["cached"] for r in writers)
w_rate = (w_cached / w_in) if w_in else 0.0
all_calls = warmups + writers
a_in = sum(r["input"] for r in all_calls)
a_cached = sum(r["cached"] for r in all_calls)
a_rate = (a_cached / a_in) if a_in else 0.0
print(f"\n===== {name} =====")
print(f" 预热请求数={len(warmups)} 并发Writer数={len(writers)} 墙钟耗时={wall:.2f}s")
if warmups:
for r in warmups:
print(f" [预热:{r['tag']}] input={r['input']} cached={r['cached']} ({r['cached']/max(r['input'],1)*100:.1f}%)")
for r in writers:
print(f" [{r['tag']}] input={r['input']} cached={r['cached']} ({r['cached']/max(r['input'],1)*100:.1f}%)")
print(f" >> Writer部分命中率 = {w_cached}/{w_in} = {w_rate*100:.1f}%")
print(f" >> 全组(含预热)命中率 = {a_cached}/{a_in} = {a_rate*100:.1f}%")
return {
"name": name, "writer_rate": w_rate, "all_rate": a_rate,
"writer_in": w_in, "writer_cached": w_cached,
"all_in": a_in, "all_cached": a_cached, "wall": wall,
"n_warmup": len(warmups), "n_writers": len(writers),
}
# ------------------------------------------------------------------ 三组实验
async def group_cold() -> dict:
salt = uuid.uuid4().hex[:8]
prefix = build_shared_prefix(salt)
t0 = time.perf_counter()
writers = await asyncio.gather(
*(one_call(prefix + writer_tail(i), f"W{i}") for i in range(N_WRITERS))
)
return _summarize("组1 冷并发(不预热)", [], list(writers), time.perf_counter() - t0)
async def group_planner() -> dict:
salt = uuid.uuid4().hex[:8]
prefix = build_shared_prefix(salt)
t0 = time.perf_counter()
planner = await one_call(prefix + PLANNER_TAIL, "Planner") # 串行先行,焼热前缀
writers = await asyncio.gather(
*(one_call(prefix + writer_tail(i), f"W{i}") for i in range(N_WRITERS))
)
return _summarize("组2 现状:Planner先行→并发Writer", [planner], list(writers), time.perf_counter() - t0)
async def group_prewarm() -> dict:
salt = uuid.uuid4().hex[:8]
prefix = build_shared_prefix(salt)
t0 = time.perf_counter()
planner = await one_call(prefix + PLANNER_TAIL, "Planner")
prewarm = await one_call(prefix, "Prewarm(纯前缀)") # 额外串行预热,仅焼前缀
writers = await asyncio.gather(
*(one_call(prefix + writer_tail(i), f"W{i}") for i in range(N_WRITERS))
)
return _summarize("组3 额外预热:Planner→纯前缀预热→并发Writer",
[planner, prewarm], list(writers), time.perf_counter() - t0)
async def main() -> None:
print(f"模型={MODEL} base_url={BASE_URL}")
print(f"每组并发Writer数={N_WRITERS} 共享前缀字符数={PREFIX_CHARS} max_tokens={MAX_TOKENS}")
results = []
for runner in (group_cold, group_planner, group_prewarm):
results.append(await runner())
await asyncio.sleep(3) # 组间稍隔,避免时序上互相影响
r1, r2, r3 = results
print("\n" + "=" * 60)
print("结论对比(Writer 部分缓存命中率):")
print(f" 组1 冷并发不预热 : {r1['writer_rate']*100:5.1f}%")
print(f" 组2 Planner先行(现状) : {r2['writer_rate']*100:5.1f}% (相对组1 {(r2['writer_rate']-r1['writer_rate'])*100:+.1f}pp)")
print(f" 组3 额外加纯前缀预热 : {r3['writer_rate']*100:5.1f}% (相对组2 {(r3['writer_rate']-r2['writer_rate'])*100:+.1f}pp)")
print(f"\n墙钟耗时:组1={r1['wall']:.2f}s 组2={r2['wall']:.2f}s 组3={r3['wall']:.2f}s")
print(f"额外预热请求消耗的 input token(组3 两个预热请求全价、几乎 0 命中):"
f"{r3['all_in']-r3['writer_in']}")
print("=" * 60)
print("判读指引:")
print(" · 若 组2 >> 组1,说明 Planner 先行已天然预热了共享前缀,现状无需再额外加预热。")
print(" · 若 组3 相比组2 提升很小(≈0pp),则额外预热无收益,反而多花 1 次串行请求的时间与 token。")
if __name__ == "__main__":
asyncio.run(main())