Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 19 additions & 4 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Added

- **Search throughput results and the harness that measures them.**
[`benchmarks/throughput.md`](benchmarks/throughput.md) gives the sustained
`hybrid` and `keyword` search rates, with latency, CPU and memory, of 1.7.1
and 1.8.0 on a 4-core, 8 GB server holding 169k memories: `hybrid` under 4
against 14 to 16 requests per second, `keyword` 70 against 120 to 140.
`benchmarks/throughput/` reproduces them: a store built from LoCoMo10 and
LongMemEval-S by EverOS's own extraction, stub model providers that replay
recorded query-embedding latency, and open-loop load with a kept-up verdict
per step.

### Changed

- **The LanceDB index cache is 64 MB where the open-file limit allows.**
Expand Down Expand Up @@ -34,10 +46,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
`libjemalloc2` present, `everos` re-executes with
`LD_PRELOAD=libjemalloc.so.2` and
`MALLOC_CONF=oversize_threshold:0,dirty_decay_ms:1000,narenas:4` beside the
existing `MALLOC_ARENA_MAX=2`. On a 4-core, 8 GB server keyword search went
from 80 to 161 QPS and hybrid search at 5 QPS from 4.3 to 2.4 s median,
while the last hour of an 8-hour write-and-search soak averaged 1125 MB
against 1221 MB with glibc. Without jemalloc nothing changes. An explicit
existing `MALLOC_ARENA_MAX=2`. On a 4-core, 8 GB server, before this
release's search fixes, keyword search went from 80 to 161 QPS and hybrid
search at 5 QPS from 4.3 to 2.4 s median, while the last hour of an 8-hour
write-and-search soak averaged 1125 MB against 1221 MB with glibc. With
those fixes the gap is smaller: keyword sustains 140 against 120 requests/s
and hybrid 16 against 14 (`benchmarks/throughput.md`), and the soak's last
hour averaged 1033 against 1036 MB. Without jemalloc nothing changes. An explicit
`MALLOC_ARENA_MAX` (or the glibc tunable) keeps glibc; an explicit
`LD_PRELOAD` or `MALLOC_CONF` keeps the operator's choice.

Expand Down
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,11 @@ Accuracy and search time across models and retrieval methods are in
[benchmarks/locomo.md](benchmarks/locomo.md); how to reproduce every number is in
[benchmarks/README.md](benchmarks/README.md).

Under load, on a 4-core, 8 GB server with 169k memories, 1.8.0 (pre-release main)
sustains 14 to 16 `hybrid` searches per second (1.7.1: under 4) and 120 to 140
`keyword` searches (1.7.1: 70); setup, latency, memory and how to reproduce are in
[benchmarks/throughput.md](benchmarks/throughput.md).

<br>

## Ecosystem Integrations
Expand Down
4 changes: 4 additions & 0 deletions README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,10 @@ agent trajectories 保存为可读 Markdown,并同步本地 SQLite 与 LanceDB
[benchmarks/locomo.zh.md](benchmarks/locomo.zh.md),每个数字怎么复现见
[benchmarks/README.zh.md](benchmarks/README.zh.md)。

加压下,在一台存着 16.9 万条记忆的 4 核 8 GB 服务器上,1.8.0(发版前的 main)的 `hybrid` 检索每秒撑得住 14 到 16 次(1.7.1:不到 4 次),
`keyword` 检索 120 到 140 次(1.7.1:70 次);环境、延迟、内存和复现方法见
[benchmarks/throughput.zh.md](benchmarks/throughput.zh.md)。

<br>

## 生态集成
Expand Down
3 changes: 3 additions & 0 deletions benchmarks/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@ its corrected answers.

- [LoCoMo](locomo.md): accuracy and search time of every retrieval method across models,
batch or step boundary detection, and write latency per stage.
- [Search throughput](throughput.md): sustained `hybrid` and `keyword` search rates,
latency, CPU and memory on a 4-core, 8 GB server, 1.7.1 against 1.8.0, and the
harness in `throughput/` that measures them.

## Quick start

Expand Down
2 changes: 2 additions & 0 deletions benchmarks/README.zh.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@

- [LoCoMo](locomo.zh.md):不同模型、不同检索方式的分数和检索耗时,批量和逐条边界检测的对比,
以及各环节的写入耗时。
- [检索吞吐](throughput.zh.md):4 核 8 GB 服务器上 `hybrid` 和 `keyword` 检索撑得住的频率、延迟、CPU
和内存,1.7.1 对比 1.8.0,以及测这些数字的工具 `throughput/`。

## 快速开始

Expand Down
384 changes: 384 additions & 0 deletions benchmarks/throughput.md

Large diffs are not rendered by default.

291 changes: 291 additions & 0 deletions benchmarks/throughput.zh.md

Large diffs are not rendered by default.

208 changes: 208 additions & 0 deletions benchmarks/throughput/build_store.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,208 @@
"""Build the throughput benchmark's store: real conversations, real extraction.

usage: python build_store.py <base_url> <sources_dir> --root <everos_root>
[--plan PLAN] [--workers N]

Ingests conversations into a running EverOS server (configured with real LLM and
embedding providers) under app ``perf`` / project ``real100k``:

locomo:<k> LoCoMo10 conversation k; each of its two speakers is a user
(``locomo<k>_<name>``)
lme:<i> LongMemEval-S question i's haystack sessions, one user (``lme_<i>``)

<sources_dir> holds ``locomo10.json`` and ``longmemeval_s_cleaned.json``
(``bash benchmarks/download_data.sh locomo``; the cleaned LongMemEval-S as in
benchmarks/throughput.md, Reproduce step 1). A LongMemEval
session shared by several questions goes to the first of them in plan order, so
no conversation is stored twice. Each session is one or more synchronous
``/memory/add`` calls of at most 50 messages, then ``/memory/flush``; a call
that fails (not 200, or no answer) is sent again, up to ``--attempts`` times. A
session still failing then is left unfinished, and once every worker is done the
build exits 1 listing them: a store missing sessions is not the documented one.
On EverOS 1.8.0 or later re-running it is safe: a resent message is not stored
twice. Otherwise it waits until the store stops growing: facts and profiles
are extracted in the background, and no HTTP signal tells when that work is
done, so it waits for five minutes in a row of an idle cascade, an empty
memorize queue and an unchanged markdown tree under --root (the server's
EVEROS_ROOT; extraction ends by writing markdown, which the cascade indexes).
"""

from __future__ import annotations

import argparse
import asyncio
import datetime as dt
import json
import os
import re
import time
from pathlib import Path

import httpx

WHERE = {"app_id": "perf", "project_id": "real100k"}


def lme_ms(date: str) -> int: # '2023/05/20 (Sat) 02:21'
d = dt.datetime.strptime(re.sub(r" \(\w+\)", "", date), "%Y/%m/%d %H:%M")
return int(d.replace(tzinfo=dt.UTC).timestamp() * 1000)


def locomo_ms(date: str) -> int: # '1:56 pm on 8 May, 2023'
d = dt.datetime.strptime(date, "%I:%M %p on %d %B, %Y")
return int(d.replace(tzinfo=dt.UTC).timestamp() * 1000)


def sessions(plan: str, sources: Path) -> list[tuple[str, list[dict]]]:
"""(session_id, messages) for every unit of the plan, in plan order."""
lme = json.loads((sources / "longmemeval_s_cleaned.json").read_text("utf-8"))
locomo = json.loads((sources / "locomo10.json").read_text("utf-8"))
units = []
for part in plan.split(","):
kind, span = part.split(":")
lo, _, hi = span.partition("-")
units += [(kind, i) for i in range(int(lo), int(hi or lo) + 1)]
out, seen = [], set()
for kind, i in units:
if kind == "lme":
q, owner = lme[i], f"lme_{i}"
for sid, sess, date in zip(
q["haystack_session_ids"],
q["haystack_sessions"],
q["haystack_dates"],
strict=True,
):
if sid in seen:
continue
seen.add(sid)
t0 = lme_ms(date)
msgs = [
{
"sender_id": owner if m["role"] == "user" else "assistant",
"role": m["role"],
"content": m["content"],
"timestamp": t0 + j * 30_000,
}
for j, m in enumerate(sess)
if m.get("content")
]
out.append((f"{owner}_{len(out)}", msgs))
else:
conv, k = locomo[i]["conversation"], 1
while f"session_{k}" in conv:
t0 = locomo_ms(conv[f"session_{k}_date_time"])
msgs = [
{
"sender_id": f"locomo{i}_{m['speaker'].lower()}",
"sender_name": m["speaker"],
"role": "user",
"content": m["text"],
"timestamp": t0 + j * 30_000,
}
for j, m in enumerate(conv[f"session_{k}"])
if m.get("text")
]
out.append((f"locomo{i}_s{k}", msgs))
k += 1
return [(sid, msgs) for sid, msgs in out if msgs]


async def post(
client: httpx.AsyncClient, path: str, body: dict, attempts: int, wait: float
) -> int | str:
"""POST until a 200, at most ``attempts`` times; the last status or error."""
status: int | str = "not sent"
for attempt in range(attempts):
if attempt:
await asyncio.sleep(wait * attempt)
try:
status = (await client.post(path, json=body)).status_code
except httpx.HTTPError as e:
status = f"error:{type(e).__name__}"
if status == 200:
break
return status


def markdown_state(root: Path) -> tuple[int, int, int]:
"""Count, total size and newest mtime of the markdown files under ``root``."""
count = size = newest = 0
for top, dirs, files in os.walk(root):
dirs[:] = [d for d in dirs if d != ".index"]
for name in files:
if name.endswith(".md"):
st = os.stat(os.path.join(top, name))
count, size, newest = (
count + 1,
size + st.st_size,
max(newest, st.st_mtime_ns),
)
return count, size, newest


async def background_work(client: httpx.AsyncClient) -> tuple[int, int]:
"""Changes the cascade has yet to index, and batches the memorize queue holds."""
health = (await client.get("/health")).json()
cascade = health.get("cascade") or {}
queue = health.get("memorize_queue") or {}
return cascade.get("pending", -1), queue.get("pending", 0)


async def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("base")
ap.add_argument("sources", type=Path)
ap.add_argument("--root", type=Path, required=True, help="the server's EVEROS_ROOT")
ap.add_argument("--plan", default="locomo:0-9,lme:0-111")
ap.add_argument("--workers", type=int, default=8)
ap.add_argument("--attempts", type=int, default=3)
ap.add_argument("--retry-wait", type=float, default=5.0)
a = ap.parse_args()
todo = sessions(a.plan, a.sources)
queue: asyncio.Queue[tuple[str, list[dict]]] = asyncio.Queue()
for item in todo:
queue.put_nowait(item)
started, failed, finished = time.monotonic(), [], 0
async with httpx.AsyncClient(base_url=a.base, timeout=900) as client:

async def worker() -> None:
nonlocal finished
while not queue.empty():
sid, msgs = queue.get_nowait()
calls = [
(
"/api/v2/memory/add",
{"session_id": sid, "messages": msgs[i : i + 50]},
)
for i in range(0, len(msgs), 50)
] + [("/api/v2/memory/flush", {"session_id": sid})]
codes: list[int | str] = []
for path, body in calls:
codes.append(
await post(client, path, body | WHERE, a.attempts, a.retry_wait)
)
if codes[-1] != 200:
failed.append((sid, codes))
break
finished += 1
print(f"{finished}/{len(todo)} {sid} {codes}", flush=True)

await asyncio.gather(*(worker() for _ in range(a.workers)))
print(f"ingested in {time.monotonic() - started:.0f} s", flush=True)
if failed:
for sid, codes in failed:
print(f"FAILED {sid} {codes}", flush=True)
raise SystemExit(f"{len(failed)} sessions failed; the store is incomplete")
calm, last = 0, None
while calm < 5:
await asyncio.sleep(60)
pending, queued = await background_work(client)
md = markdown_state(a.root)
calm = calm + 1 if pending == 0 and queued == 0 and md == last else 0
last = md
print(f"cascade {pending} queue {queued} markdown {md[:2]}", flush=True)
print(f"settled after {time.monotonic() - started:.0f} s")


if __name__ == "__main__":
asyncio.run(main())
48 changes: 48 additions & 0 deletions benchmarks/throughput/core_bench.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
"""Single-core speed of this machine, to set beside the throughput numbers.

usage: python core_bench.py

Two timings, best of five, one thread: a pure-Python loop (what request handling
spends its time on) and element-wise float32 dot products over 20k x 1024
vectors (numpy's SIMD loops, no BLAS). Lower is faster.
"""

from __future__ import annotations

import os
from collections.abc import Callable

os.environ.setdefault("OPENBLAS_NUM_THREADS", "1")
os.environ.setdefault("OMP_NUM_THREADS", "1")

import time

import numpy as np


def best(fn: Callable[[], float]) -> float:
return min(fn() for _ in range(5))


def py_loop() -> float:
t, s = time.perf_counter(), 0
for i in range(10_000_000):
s += i
return time.perf_counter() - t


M = np.random.default_rng(0).standard_normal((20_000, 1024), dtype=np.float32)
q = np.random.default_rng(1).standard_normal(1024, dtype=np.float32)


def dots() -> float:
t = time.perf_counter()
for _ in range(50):
(M * q).sum(axis=1).argmax()
return time.perf_counter() - t


print(
f"python loop 1e7: {best(py_loop) * 1000:.0f} ms "
f"numpy 50 x (20k x 1024 dot): {best(dots) * 1000:.0f} ms"
)
Loading