Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266#!/usr/bin/env python3"""Sweep embed.BATCH_SIZE and record what each setting costs in memory and time.
BATCH_SIZE sets three llama-server arguments at once (`embed.py start()`):--ctx-size and --batch-size are both CONTEXT * BATCH_SIZE, while --ubatch-sizestays at CONTEXT. So it decides how much key/value cache the server allocates, andthat cache is nearly all of the server's resident memory under a decoder-onlymodel.
Runs its own server on its own port and its own data directory, so the sharedserver on 8177 and the shared index are untouched. Results land as JSON; theprose version is eval/batch-size.md.
CODE_INDEX_PORT=8178 uv run python eval/batch-size-sweep.py --out /tmp/sweep.json
`--mode growth` instead holds one batch size and records resident memory againstchunks embedded, which is the part a single measurement after model load misses."""
from __future__ import annotations
import argparseimport jsonimport osimport sysimport timeimport urllib.error
HERE = os.path.dirname(os.path.abspath(__file__))REPO = os.path.dirname(HERE)os.environ.setdefault("CODE_INDEX_PORT", "8178")os.environ.setdefault("CODE_INDEX_DATA", os.path.join(REPO, ".index-sweep"))sys.path.insert(0, os.path.join(REPO, "src"))
from code_index import embed # noqa: E402from code_index.chunk import MAX_CHUNK_CHARS, chunk_file # noqa: E402from code_index.files import discover # noqa: E402
# Enough that model load and the first batch are a small share of the run. This# repository yields only 184 chunks, so a larger --repo is needed for the growth# mode, where the plateau does not arrive until about 300.SAMPLE = 256
ASCII_DENSE = "{}[]();,.<>/|"CJK_DENSE = "代码検索索引"BASE64_DENSE = "QUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVow"
def filler(unit: str, chars: int) -> str: return (unit * (chars // len(unit) + 1))[:chars]
def sample_chunks(repo: str, n: int) -> list[str]: """The first `n` chunks of `repo`, in path order.
Real text rather than generated text, because token density is what decides whether a batch fits, and reproducible without shipping a fixture. """ files, _ = discover(repo) out: list[str] = [] for sf in sorted(files, key=lambda f: f.rel): try: with open(sf.abspath, encoding="utf-8") as fh: text = fh.read() except (OSError, UnicodeDecodeError): continue for ch in chunk_file(sf.rel, text): out.append(ch.embedding_text()) if len(out) >= n: return out return out
def proc_kb(pid: int, field: str) -> int: with open(f"/proc/{pid}/status") as fh: for line in fh: if line.startswith(field): return int(line.split()[1]) return 0
def mib(pid: int, field: str = "VmRSS") -> float: return proc_kb(pid, field) / 1024.0
def tokens(text: str) -> int: return len(embed._post("/tokenize", {"content": text}, 120)["tokens"])
def raw_embed(inputs: list[str]) -> str: """One request with no truncation and no retry, reporting how it failed.""" try: embed._post("/v1/embeddings", {"input": inputs, "model": embed.MODEL_NAME}, 600) return "ok" except urllib.error.HTTPError as exc: body = exc.read()[:300].decode("utf-8", "replace").replace("\n", " ") return f"HTTP {exc.code}: {body}" except Exception as exc: # noqa: BLE001 - recording whatever happens is the point return repr(exc)
def probe(batch: int) -> dict[str, str]: """Whether a batch that the chunker and the input cap allow actually fits.
The first two are exactly what embed() may send. The last two are larger than it can send, and exist to find where the server starts refusing at all. """ cap = embed.MAX_INPUT_CHARS return { "full batch, ascii at MAX_INPUT_CHARS": raw_embed( [filler(ASCII_DENSE, cap)] * batch ), "full batch, CJK at MAX_INPUT_CHARS": raw_embed([filler(CJK_DENSE, cap)] * batch), "one ascii input at 4x MAX_INPUT_CHARS": raw_embed([filler(ASCII_DENSE, 4 * cap)]), "one CJK input at 4x MAX_INPUT_CHARS": raw_embed([filler(CJK_DENSE, 4 * cap)]), }
def token_facts(texts: list[str]) -> dict: """How close real and pathological inputs get to the per-input ceiling.
A single input longer than --ubatch-size is the failure the character caps exist to prevent, and characters are only a proxy for tokens. """ cap = embed.MAX_INPUT_CHARS return { "ubatch_size": embed.CONTEXT, "max_chunk_chars": MAX_CHUNK_CHARS, "max_input_chars": cap, "worst_sample_chunk_tokens": max(tokens(t) for t in texts), "ascii_punctuation_at_cap_tokens": tokens(filler(ASCII_DENSE, cap)), "cjk_at_cap_tokens": tokens(filler(CJK_DENSE, cap)), "base64_at_cap_tokens": tokens(filler(BASE64_DENSE, cap)), }
def measure(batch: int, texts: list[str], collect_tokens: bool) -> tuple[dict, dict]: embed.BATCH_SIZE = batch
t0 = time.time() embed.start() load_s = time.time() - t0 pid = int(open(embed.PID_FILE).read().strip())
after_load = mib(pid) embed.embed(texts[:batch]) after_batch = mib(pid)
t0 = time.time() for off in range(0, len(texts), batch): embed.embed(texts[off : off + batch]) elapsed = time.time() - t0
run = { "batch_size": batch, "ctx_size": embed.CONTEXT * batch, "load_s": round(load_s, 1), "rss_after_load_mib": round(after_load), "rss_after_first_batch_mib": round(after_batch), "rss_after_sample_mib": round(mib(pid)), "rss_peak_mib": round(mib(pid, "VmHWM")), "sample_chunks": len(texts), "sample_s": round(elapsed, 1), "chunks_per_s": round(len(texts) / elapsed, 2), } facts = token_facts(texts) if collect_tokens else {} run["probes"] = probe(batch)
embed.stop() return run, facts
def growth(batch: int, texts: list[str], every: int) -> list[dict]: """Resident memory against chunks embedded, at one batch size.
What --ctx-size allocates is visible at load; what a run actually reaches is not, so a single reading after the first batch understates it. """ embed.BATCH_SIZE = batch embed.start() pid = int(open(embed.PID_FILE).read().strip())
series = [{"chunks": 0, "elapsed_s": 0.0, "rss_mib": round(mib(pid))}] t0 = time.time() done = 0 for off in range(0, len(texts), batch): embed.embed(texts[off : off + batch]) done += len(texts[off : off + batch]) if done % every < batch or done == len(texts): series.append( { "chunks": done, "elapsed_s": round(time.time() - t0, 1), "rss_mib": round(mib(pid)), } ) print(json.dumps(series[-1]), flush=True) series[-1]["rss_peak_mib"] = round(mib(pid, "VmHWM")) embed.stop() return series
def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--out", default=os.path.join(HERE, "batch-size-sweep.json")) ap.add_argument("--mode", choices=["sweep", "growth"], default="sweep") ap.add_argument("--sizes", default="32,16,8,4,2,32") ap.add_argument("--sample", type=int, default=SAMPLE) ap.add_argument("--repo", default=REPO) ap.add_argument("--every", type=int, default=100, help="growth: chunks per reading") ap.add_argument( "--context", type=int, default=embed.CONTEXT, help="override CONTEXT, which is --ubatch-size and a factor of --ctx-size", ) args = ap.parse_args()
embed.CONTEXT = args.context
if embed.PORT == 8177: raise SystemExit("refusing to run against the shared server; set CODE_INDEX_PORT")
texts = sample_chunks(args.repo, args.sample) print(f"sample: {len(texts)} chunks from {args.repo}", flush=True)
if args.mode == "growth": # A list rather than a map keyed by batch size: repeating a size is how # machine drift is told apart from a difference between settings, so the # second pass must not overwrite the first. runs = [] for i, raw in enumerate(args.sizes.split(",")): batch = int(raw) print(f"--- growth at batch {batch} (run {i + 1})", flush=True) series = growth(batch, texts, args.every) runs.append( { "batch_size": batch, "chunks_per_s": round(series[-1]["chunks"] / series[-1]["elapsed_s"], 2), "series": series, } ) with open(args.out, "w") as fh: json.dump({"repo": args.repo, "growth": runs}, fh, indent=2) print(f"wrote {args.out}", flush=True) return
runs: list[dict] = [] facts: dict = {} for i, raw in enumerate(args.sizes.split(",")): batch = int(raw) print(f"--- batch {batch} (run {i + 1})", flush=True) run, got = measure(batch, texts, collect_tokens=not facts) facts = facts or got runs.append(run) print(json.dumps(run, indent=2), flush=True)
out = {"model": os.path.basename(embed.MODEL_PATH), "tokens": facts, "runs": runs} with open(args.out, "w") as fh: json.dump(out, fh, indent=2) print(f"wrote {args.out}", flush=True)
if __name__ == "__main__": main()