zheqiushui's picture
AX8860 llama.cpp package
6534c46 verified
Raw History Blame Contribute Delete
5.68 kB
#!/usr/bin/env python3
# random prompt-cache stress against llama-server: continue / regenerate / edit / truncate / long tool results / long replies.
# Every "check" request carries a fresh code the reply must repeat, so a wrong recurrent state shows up as a wrong answer.
# stress.py <port> <pkg dir> <seed> <ops> [seconds]
import json, sys, time, random, urllib.request, urllib.error
port, P, seed, nops = sys.argv[1], sys.argv[2], int(sys.argv[3]), int(sys.argv[4])
budget = float(sys.argv[5]) if len(sys.argv) > 5 else 1e9
rnd = random.Random(seed); T0 = time.time()
TEXT = open(P + "/p4k.txt", encoding="utf-8").read()
TOOLS = [{"type": "function", "function": {"name": n, "description": d, "parameters": {"type": "object", "properties": {
"path": {"type": "string"}, "text": {"type": "string"}}, "required": ["path"]}}} for n, d in
[("read_file", "Read a file."), ("run_shell", "Run a shell command."), ("search", "Search the code base.")]]
def post(msgs, n, cache=True):
body = {"messages": msgs, "max_tokens": n, "temperature": 0, "presence_penalty": 0, "top_k": 1, "seed": 1, "tools": TOOLS, "cache_prompt": cache,
"chat_template_kwargs": {"enable_thinking": False}}
try:
r = json.load(urllib.request.urlopen(urllib.request.Request("http://127.0.0.1:%s/v1/chat/completions" % port,
json.dumps(body).encode(), {"Content-Type": "application/json"}), timeout=600))
except urllib.error.HTTPError as e:
return None, e.read().decode()[:160], {}
except Exception as e:
return None, repr(e)[:160], {}
return r["choices"][0]["message"].get("content") or "", "", r.get("timings", {})
def sysmsg(k): return {"role": "system", "content": "You are a helpful assistant. Notes:\n" + TEXT[:k]}
def check_msg():
code = str(rnd.randint(100000, 999999))
return {"role": "user", "content": "The code is %s. Reply with only the code." % code}, code
def long_msg(): return {"role": "user", "content": "Write a long, detailed essay about %s. Do not stop early." % rnd.choice(["rivers", "trains", "tea", "bridges", "maps"])}
def tool_blob():
a = rnd.randint(0, 8000); return {"role": "user", "content": "Tool output:\n" + TEXT[a:a + rnd.choice([300, 1500, 6000])]}
msgs = [sysmsg(rnd.choice([400, 3000, 9000]))]; fails = wrong = done = 0; hist = []; model_wrong = [0]
def ask(tag, m, code, n):
global fails, wrong, done
c, err, t = post(m, n); done += 1
st = "OK"
if c is None: st = "FAIL " + err; fails += 1
elif code and code not in c.replace(",", "").replace(" ", ""):
# Ask the same request without the prompt cache as the control. If the control fails the check as well, the
# model itself is wrong; only a control that passes while the cached run fails points at the cached state.
c2, _, _ = post(m, n, cache=False)
ref_ok = c2 is not None and code in c2.replace(",", "").replace(" ", "")
model_bad = c2 is not None and not ref_ok
st = "%s got=%r want=%s nocache=%r" % ("MODEL" if model_bad else "WRONG", c[:30], code, (c2 or "")[:30])
if model_bad: model_wrong[0] += 1
else: wrong += 1
print("%3d %-10s msgs=%-3d cache_n=%-6s prompt_n=%-5s prompt_ms=%-6.0f gen_n=%-4s %s" % (done, tag, len(m), t.get("cache_n"), t.get("prompt_n"),
t.get("prompt_ms", 0), t.get("predicted_n"), st), flush=True)
return c
last_code = None
while done < nops and time.time() - T0 < budget:
op = rnd.choices(["cont", "long", "regen", "edit_last", "edit_mid", "trunc", "tool", "sys", "reset"], [30, 12, 8, 10, 8, 8, 10, 3, 2])[0]
if op == "cont" or len(msgs) < 2:
u, code = check_msg(); msgs.append(u); c = ask("cont", msgs, code, 12)
if c is None: msgs.pop(); continue
msgs.append({"role": "assistant", "content": c}); last_code = code
elif op == "long":
msgs.append(long_msg()); c = ask("long", msgs, None, rnd.choice([120, 300, 700]))
if c is None: msgs.pop(); continue
msgs.append({"role": "assistant", "content": c})
elif op == "tool":
msgs.append(tool_blob()); c = ask("tool", msgs, None, 20)
if c is None: msgs.pop(); continue
msgs.append({"role": "assistant", "content": c})
elif op == "regen" and msgs[-1]["role"] == "assistant":
ask("regen", msgs[:-1], None, 12)
elif op == "edit_last" and msgs[-1]["role"] == "assistant":
u, code = check_msg(); msgs[-2] = u; c = ask("edit_last", msgs[:-1], code, 12)
if c is not None: msgs[-1] = {"role": "assistant", "content": c}
elif op == "edit_mid" and len(msgs) > 5:
i = rnd.randrange(1, len(msgs) - 2)
m = json.loads(json.dumps(msgs)); m[i]["content"] = m[i]["content"][:len(m[i]["content"]) // 2] + " (edited %d)" % rnd.randint(0, 99)
u, code = check_msg(); m.append(u); c = ask("edit_mid", m, code, 12)
if c is not None: msgs = m + [{"role": "assistant", "content": c}]
elif op == "trunc" and len(msgs) > 5:
k = 2 * rnd.randint(1, (len(msgs) - 3) // 2); msgs = msgs[:-k]
u, code = check_msg(); msgs.append(u); c = ask("trunc", msgs, code, 12)
if c is None: msgs.pop(); continue
msgs.append({"role": "assistant", "content": c})
elif op == "sys":
msgs[0] = sysmsg(rnd.choice([400, 3000, 9000])); u, code = check_msg(); msgs.append(u); c = ask("sys", msgs, code, 12)
if c is None: msgs.pop(); continue
msgs.append({"role": "assistant", "content": c})
elif op == "reset":
msgs = [sysmsg(rnd.choice([400, 3000, 9000]))]
print("STRESS seed=%d requests=%d fail=%d wrong=%d model_wrong=%d" % (seed, done, fails, wrong, model_wrong[0]))