interplane.Get Omega
Read in your language

aien-sovereign-core-mv

AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.

Brought by drakestapleton

branch main Branches Tags History

aien-sovereign-core-mv / scripts / own30b-pkv-bench.sh

326 lines · 16178 bytes Raw Blame History
1#!/usr/bin/env bash
2# SPDX-License-Identifier: Apache-2.0
3# Copyright 2026 Drake Stapleton (AIEN / aien-dev)
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17# Persistent KV benchmark on the chip (sc#508, contract locked in #500). CHIP-ONLY: never run by
18# CI or cargo test. Same safety rules as own30b-pkv-chip-check.sh (see own30b-pkv-lib.sh): own
19# server on 127.0.0.1:18098 (PKV_CHECK_PORT), refuses while :18091 answers or the port is taken,
20# stops only the PID it started, key via `atlas-vault run AIEN_KV_STORE_KEY --` (never printed).
21#
22# scripts/own30b-pkv-bench.sh [--dry-run] <evidence-dir> <aien-serve-http binary>
23#
24# Workload: 8 two-turn conversations, each with its own ~2048-token prefix (a distinct session
25# line plus PKV_BENCH_RULES rules) that turn 2 shares with turn 1; greedy, PKV_BENCH_MAX_TOKENS
26# (64) new tokens, streamed so TTFT is measured on the client.
27# seed persistence on, store S: turn 1 of all 8 conversations, wait for the parks
28# disabled persistence off (AIEN_KV_STORE_DIR unset)
29# warm persistence on S, every store file read into the page cache before each batch
30# cold persistence on S, `sync; echo 3 > /proc/sys/vm/drop_caches` (sudo -n) before each
31# batch; cold is VERIFIED per batch by the server's /proc/<pid>/io read_bytes (reads
32# that reached the block layer) against health restore_bytes; no fincore/vmtouch here
33# Each mode: concurrency 1/2/4/8 x PKV_BENCH_REPS (3) batches. A batch first sends one short
34# unrelated chat (so the engine's RAM prefix is useless), then turn 2 of conversations 1..N at
35# once. The server runs one generation at a time and answers 503 when busy: clients retry every
36# 0.2 s (counted), latency and TTFT run from the first attempt, so they include the queue.
37# Raw evidence: every SSE stream with client timestamps, health and /proc/<pid>/io before and
38# after each batch, RSS every second, GPU memory (nvidia-smi compute-apps) every 5 s, iostat -dxk
39# 5, server logs. summary.txt: p50/p95 latency and TTFT, completion tokens/s, restores, restore
40# bytes, block reads, decrypt (open) and encrypt (seal) time, RSS/GPU peak, failures.
41# Budget: PKV_BENCH_BUDGET_S (2700) wall seconds; past it the remaining batches are skipped and
42# the verdict is INCOMPLETE. Rough duration: 4 server starts plus about 180 requests, 15 to 30 min.
43set -euo pipefail
44. "$(dirname "$0")/own30b-pkv-lib.sh"
45pkv_usage_args "$(basename "$0")" "$@"
46
47REPS=${PKV_BENCH_REPS:-3}
48MAXTOK=${PKV_BENCH_MAX_TOKENS:-64}
49RULES=${PKV_BENCH_RULES:-118}
50BUDGET=${PKV_BENCH_BUDGET_S:-2700}
51LEVELS="1 2 4 8"
52MODES="disabled warm cold"
53
54bench_prereqs() {
55 local bad=0 fs
56 for t in iostat nvidia-smi; do
57 if command -v "$t" >/dev/null; then echo " ok tool $t"; else echo " info tool $t missing (that column stays empty)"; fi
58 done
59 if sudo -n true 2>/dev/null; then
60 echo " ok sudo -n works (drop_caches for the cold mode)"
61 else
62 echo " MISS sudo -n (the cold mode needs: sync; echo 3 > /proc/sys/vm/drop_caches)"
63 bad=1
64 fi
65 fs=$(findmnt -no FSTYPE -T /tmp)
66 if [ "$fs" = tmpfs ] || [ "$fs" = ramfs ]; then
67 echo " MISS /tmp is $fs: the store must be on the NVMe for a cold restore"
68 bad=1
69 else
70 echo " ok store parent /tmp is $fs on $(findmnt -no SOURCE -T /tmp)"
71 fi
72 return $bad
73}
74
75if [ "$DRY" = 1 ]; then
76 echo "PLAN own30b-pkv-bench (#508): seed, then modes [$MODES] x concurrency [$LEVELS] x $REPS reps"
77 echo " 8 conversations, ~2048-token prefix each ($RULES rules), $MAXTOK new tokens, streamed"
78 echo " 4 server starts on :$PORT, about $((3 * REPS * (4 + 15) + 8)) requests, estimate 15 to 30 minutes, budget ${BUDGET} s"
79 echo " cold = drop_caches before each batch, verified by server block reads vs restore_bytes"
80 echo " evidence -> $dir"
81 echo "PREREQUISITES"
82 ok=1
83 pkv_prereqs 1 || ok=0
84 bench_prereqs || ok=0
85 if [ $ok = 1 ]; then echo "DRY RUN: ready"; exit 0; fi
86 echo "DRY RUN: NOT ready"
87 exit 1
88fi
89if ! bench_prereqs >/dev/null 2>&1; then
90 bench_prereqs >&2 || true
91 echo "refusing: a benchmark prerequisite is missing" >&2
92 exit 2
93fi
94pkv_begin
95
96SAMPLER=
97IOSTAT=
98stop_samplers() {
99 if [ -n "$SAMPLER" ]; then kill "$SAMPLER" 2>/dev/null || true; fi
100 SAMPLER=
101}
102trap 'stop_samplers; [ -n "$IOSTAT" ] && kill "$IOSTAT" 2>/dev/null; stop_server || PKV_LEAK=1; rm -rf "$work"; pkv_trap_status' EXIT
103
104if command -v iostat >/dev/null; then
105 iostat -dxk -t 5 >"$dir/iostat.txt" 2>&1 &
106 IOSTAT=$!
107fi
108
109start_samplers() { # <mode>: RSS every 1 s, GPU memory every 5 s
110 local mode=$1 p
111 p=$(server_pid)
112 (
113 n=0
114 while kill -0 "$p" 2>/dev/null; do
115 printf '%s %s\n' "$EPOCHREALTIME" "$(awk '/^VmRSS/ {print $2}' "/proc/$p/status" 2>/dev/null)" >>"$dir/rss-$mode.txt"
116 if [ $((n % 5)) = 0 ] && command -v nvidia-smi >/dev/null; then
117 printf '%s %s\n' "$EPOCHREALTIME" "$(nvidia-smi --query-compute-apps=pid,used_memory --format=csv,noheader,nounits 2>/dev/null | awk -F', *' -v p="$p" '$1 == p {print $2}')" >>"$dir/gpu-$mode.txt"
118 fi
119 n=$((n + 1))
120 sleep 1
121 done
122 ) &
123 SAMPLER=$!
124}
125
126# The conversations: k = 1..8, each prefix its own (the session line makes every chunk distinct).
127sys_k() {
128 local s="Session $1 of the OWN-30B benchmark. You are the OWN-30B assistant on the AIEN Spark. Answer briefly." i
129 for i in $(seq 1 "$RULES"); do s="$s Rule $i: keep answers short, never invent facts, say UNKNOWN when unsure."; done
130 printf '%s' "$s"
131}
132msgs1() { jq -n --arg s "$(sys_k "$1")" --arg q "$Q1" '[{role:"system",content:$s},{role:"user",content:$q}]'; }
133msgs2() { # <k> <turn-1 answer> <question>
134 jq -n --argjson m "$(msgs1 "$1")" --arg a "$2" --arg q "$3" '$m + [{role:"assistant",content:$a},{role:"user",content:$q}]'
135}
136FLUSH=$(jq -n '[{role:"user",content:"Say one word about the weather."}]')
137
138# send <name> <messages-json>: one streamed request, retried while the server answers 503.
139# Writes <name>.sse (client time + SSE line) and one line of requests.tsv.
140send() {
141 local name=$1 body="$work/$1.body" h="$work/$1.h" raw="$dir/sse/$1.sse" t0 code retries=0
142 jq -n --arg model "$SERVED_MODEL" --argjson m "$2" --argjson n "$MAXTOK" '{model:$model, messages:$m, max_tokens:$n, temperature:0, seed:1, stream:true}' >"$body"
143 t0=$EPOCHREALTIME
144 while :; do
145 rm -f "$h"
146 curl -sN -m 900 -D "$h" "$base/v1/chat/completions" -H "Authorization: Bearer $AIEN_SERVE_HTTP_BEARER_TOKEN" -H 'content-type: application/json' -d @"$body" |
147 while IFS= read -r line; do [ -n "$line" ] && printf '%s %s\n' "$EPOCHREALTIME" "$line"; done >"$raw" || true
148 code=$(awk 'NR == 1 {print $2}' "$h" 2>/dev/null)
149 if [ "$code" = 503 ] && [ "$retries" -lt 6000 ]; then
150 retries=$((retries + 1))
151 sleep 0.2
152 continue
153 fi
154 break
155 done
156 local row sha
157 row=$(awk -v t0="$t0" -v name="$name" -v code="${code:-none}" -v retries="$retries" '
158 / data: \{/ && first == "" && $0 ~ /"content":"[^"]/ { first = $1 }
159 /"usage":/ { if (match($0, /"completion_tokens":[0-9]+/)) ct = substr($0, RSTART + 20, RLENGTH - 20)
160 if (match($0, /"prompt_tokens":[0-9]+/)) pt = substr($0, RSTART + 16, RLENGTH - 16) }
161 / data: \[DONE\]/ { done = 1 }
162 { last = $1 }
163 END {
164 ttft = (first == "") ? "NA" : sprintf("%.4f", first - t0)
165 lat = (last == "") ? "NA" : sprintf("%.4f", last - t0)
166 ok = (code == "200" && done && first != "" && ct != "") ? "ok" : "FAIL"
167 printf "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s", name, ok, code, retries, ttft, lat, ct + 0, pt + 0
168 }' "$raw")
169 sha=$(sed -n 's/^[0-9.]* data: //p' "$raw" | grep -v '^\[DONE\]' | jq -rj '.choices[0].delta.content // empty' 2>/dev/null | sha256sum | cut -c1-16)
170 # One write per row: the N clients of a batch append at the same time.
171 printf '%s\t%s\n' "$row" "$sha" >>"$dir/requests.tsv"
172}
173
174# snap <tag>: health and /proc/<pid>/io of our server, and the NVMe line of /proc/diskstats.
175snap() {
176 local p
177 p=$(server_pid)
178 curl -s -m 10 "$base/health" >"$dir/snap/$1-health.json"
179 cat "/proc/$p/io" >"$dir/snap/$1-io.txt"
180 grep -w "$(basename "$(findmnt -no SOURCE -T /tmp)" | sed 's/p[0-9]*$//')" /proc/diskstats >"$dir/snap/$1-diskstats.txt" || true
181 awk '/^(Cached|MemAvailable):/' /proc/meminfo >"$dir/snap/$1-meminfo.txt"
182}
183hv() { jq -r "(.persistent_kv$2) // 0" "$dir/snap/$1-health.json" 2>/dev/null || echo 0; }
184iov() { awk -v k="$2:" '$1 == k {v = $2} END {print v + 0}' "$dir/snap/$1-io.txt" 2>/dev/null || echo 0; }
185
186# batch <mode> <N> <rep>
187batch() {
188 local mode=$1 n=$2 r=$3 tag="$1-c$2-r$3" k t0 t1 pids=()
189 send "$tag-flush" "$FLUSH"
190 case $mode in
191 warm) find "$S" -type f -exec cat {} + >/dev/null 2>&1 || true ;;
192 cold)
193 sync
194 sudo -n sh -c 'echo 3 > /proc/sys/vm/drop_caches'
195 ;;
196 esac
197 snap "$tag-pre"
198 t0=$EPOCHREALTIME
199 for k in $(seq 1 "$n"); do
200 send "$tag-k$k" "$(msgs2 "$k" "${A1[$k]}" "Benchmark question c$n r$r: which of those matters most on a bicycle, and why?")" &
201 pids+=("$!")
202 done
203 wait "${pids[@]}"
204 t1=$EPOCHREALTIME
205 snap "$tag-post"
206 printf '%s\t%s\t%s\t%.4f\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' "$mode" "$n" "$r" "$(awk -v a="$t0" -v b="$t1" 'BEGIN {print b - a}')" \
207 $(($(hv "$tag-post" .restores) - $(hv "$tag-pre" .restores))) \
208 $(($(hv "$tag-post" .restore_bytes) - $(hv "$tag-pre" .restore_bytes))) \
209 $(($(iov "$tag-post" read_bytes) - $(iov "$tag-pre" read_bytes))) \
210 $(($(iov "$tag-post" write_bytes) - $(iov "$tag-pre" write_bytes))) \
211 $(($(hv "$tag-post" .seal.open_ns) - $(hv "$tag-pre" .seal.open_ns))) \
212 $(($(hv "$tag-post" .seal.open_bytes) - $(hv "$tag-pre" .seal.open_bytes))) \
213 $(($(hv "$tag-post" .seal.seal_ns) - $(hv "$tag-pre" .seal.seal_ns))) \
214 $(($(hv "$tag-post" .seal.seal_bytes) - $(hv "$tag-pre" .seal.seal_bytes))) \
215 "$(jq -c '.persistent_kv.restore_misses // {}' "$dir/snap/$tag-post-health.json")" >>"$dir/batches.tsv"
216}
217
218mkdir -p "$dir/sse" "$dir/snap"
219printf 'name\tok\thttp\tretries_503\tttft_s\tlatency_s\tcompletion_tokens\tprompt_tokens\tcontent_sha\n' >"$dir/requests.tsv"
220printf 'mode\tconc\trep\twall_s\trestores\trestore_bytes\tproc_read_bytes\tproc_write_bytes\topen_ns\topen_bytes\tseal_ns\tseal_bytes\trestore_misses\n' >"$dir/batches.tsv"
221{
222 echo "reps $REPS max_tokens $MAXTOK rules $RULES budget_s $BUDGET levels $LEVELS"
223 echo "store parent $(findmnt -no SOURCE,FSTYPE -T /tmp)"
224} >>"$dir/run-info.txt"
225S="$work/store"
226declare -a A1
227
228echo "== seed: turn 1 of 8 conversations on store S"
229start_server seed "$S"
230start_samplers seed
231for k in $(seq 1 8); do
232 send "seed-k$k" "$(msgs1 "$k")"
233 A1[k]=$(sed -n 's/^[0-9.]* data: //p' "$dir/sse/seed-k$k.sse" | grep -v '^\[DONE\]' | jq -rj '.choices[0].delta.content // empty')
234 printf '%s' "${A1[$k]}" >"$dir/seed-k$k.answer.txt"
235done
236wait_parks
237health seed >/dev/null
238stop_samplers
239stop_server
240prefix=$(awk -F'\t' '$1 == "seed-k1" {print $8}' "$dir/requests.tsv")
241echo "turn-1 prompt tokens: $prefix (target ~2048)"
242if [ "${prefix:-0}" -lt 1843 ] || [ "${prefix:-0}" -gt 2253 ]; then
243 echo "the prefix is $prefix tokens, not ~2048: set PKV_BENCH_RULES (now $RULES) and rerun" | tee "$dir/summary.txt" >&2
244 pkv_seal
245 exit 1
246fi
247
248skipped=0
249for mode in $MODES; do
250 echo "== $mode"
251 if [ "$mode" = disabled ]; then start_server "$mode" -; else start_server "$mode" "$S"; fi
252 snap "$mode-start"
253 start_samplers "$mode"
254 for n in $LEVELS; do
255 for r in $(seq 1 "$REPS"); do
256 if [ "$SECONDS" -gt "$BUDGET" ]; then
257 echo "budget ${BUDGET} s spent: skipping $mode c$n r$r"
258 skipped=$((skipped + 1))
259 continue
260 fi
261 batch "$mode" "$n" "$r"
262 done
263 done
264 health "$mode" >/dev/null
265 stop_samplers
266 stop_server
267done
268
269pct() { # <p> on stdin numbers -> nearest rank
270 sort -g | awk -v p="$1" '{v[NR] = $1} END {if (NR == 0) {print "NA"; exit} i = int(p * NR + 0.9999); if (i < 1) i = 1; print v[i]}'
271}
272col() { # <mode> <conc> <column>: values of requests in that cell
273 awk -F'\t' -v m="$1" -v c="$2" -v col="$3" '$1 ~ "^" m "-c" c "-r[0-9]+-k[0-9]+$" && $5 != "NA" {print $col}' "$dir/requests.tsv"
274}
275peak() { awk '$2 != "" && $2 + 0 > m {m = $2 + 0} END {print m + 0}' "$1" 2>/dev/null || echo 0; }
276
277{
278 echo "PKV BENCH (#508) $(date -u +%FT%TZ) binary $(sha256sum "$BIN" | cut -c1-16) prefix $prefix tokens max_tokens $MAXTOK reps $REPS"
279 echo "latency and TTFT in seconds from the first attempt (queue included); tok/s = completion tokens / batch wall time"
280 printf '%-8s %4s %3s %4s %8s %8s %8s %8s %7s %6s %7s %10s %10s %9s %9s\n' mode conc n fail lat_p50 lat_p95 ttft_p50 ttft_p95 tok_s retry restores restore_MB block_rd_MB open_ms seal_ms
281 for mode in $MODES; do
282 for n in $LEVELS; do
283 cnt=$(col "$mode" "$n" 1 | wc -l)
284 fails=$(awk -F'\t' -v m="$mode" -v c="$n" '$1 ~ "^" m "-c" c "-r[0-9]+-k[0-9]+$" && $2 != "ok"' "$dir/requests.tsv" | wc -l)
285 read -r wall toks retr <<<"$(awk -F'\t' -v m="$mode" -v c="$n" '
286 FILENAME ~ /batches/ && $1 == m && $2 == c {w += $4}
287 FILENAME ~ /requests/ && $1 ~ "^" m "-c" c "-r[0-9]+-k[0-9]+$" {t += $7; r += $4}
288 END {print w + 0, t + 0, r + 0}' "$dir/batches.tsv" "$dir/requests.tsv")"
289 read -r rs rb rd on sn <<<"$(awk -F'\t' -v m="$mode" -v c="$n" '$1 == m && $2 == c {a += $5; b += $6; d += $7; o += $9; s += $11} END {print a + 0, b + 0, d + 0, o + 0, s + 0}' "$dir/batches.tsv")"
290 printf '%-8s %4s %3s %4s %8s %8s %8s %8s %7s %6s %7s %10.1f %10.1f %9.1f %9.1f\n' "$mode" "$n" "$cnt" "$fails" \
291 "$(col "$mode" "$n" 6 | pct 0.50)" "$(col "$mode" "$n" 6 | pct 0.95)" \
292 "$(col "$mode" "$n" 5 | pct 0.50)" "$(col "$mode" "$n" 5 | pct 0.95)" \
293 "$(awk -v t="$toks" -v w="$wall" 'BEGIN {printf "%.1f", (w > 0) ? t / w : 0}')" "$retr" "$rs" \
294 "$(awk -v b="$rb" 'BEGIN {print b / 1048576}')" "$(awk -v b="$rd" 'BEGIN {print b / 1048576}')" \
295 "$(awk -v b="$on" 'BEGIN {print b / 1e6}')" "$(awk -v b="$sn" 'BEGIN {print b / 1e6}')"
296 done
297 done
298 for mode in seed $MODES; do
299 echo "memory $mode: RSS peak $(($(peak "$dir/rss-$mode.txt") / 1024)) MiB, GPU (nvidia-smi compute-apps) peak $(peak "$dir/gpu-$mode.txt") MiB"
300 done
301 for mode in $MODES; do
302 echo "server prefill $mode (long prompts): p50 $(grep -ho 'prompt [0-9]* tok, [0-9]* reused from the previous turn, prefill [0-9]* ms' "$dir/$mode.log" | awk '$2 > 1000 {print $(NF - 1)}' | pct 0.50) ms"
303 done
304 echo "seed health: $(jq -c '.persistent_kv | {parked_chunks, park_bytes, park_failed, seal}' "$dir/seed-health.json")"
305 echo "CHECKS"
306 check "every request answered (http 200, content, usage)" "$(awk -F'\t' 'NR > 1 && $2 != "ok"' "$dir/requests.tsv" | wc -l)" 0
307 check "no batch skipped by the budget" "$skipped" 0
308 check "disabled: no persistent_kv in health" "$(jq -r 'has("persistent_kv")' "$dir/disabled-health.json")" false
309 for mode in warm cold; do
310 check "$mode: every request restored" "$(awk -F'\t' -v m="$mode" '$1 == m && $5 != $2' "$dir/batches.tsv" | wc -l)" 0
311 check "$mode: no park failed" "$(jq -r '.persistent_kv.park_failed' "$dir/$mode-health.json")" 0
312 done
313 check "warm: restores read from the page cache (block reads < 10% of restore bytes)" \
314 "$(awk -F'\t' '$1 == "warm" && $7 * 10 >= $6 && $6 > 0' "$dir/batches.tsv" | wc -l)" 0
315 check "cold: VERIFIED cold, block reads >= 90% of restore bytes in every batch" \
316 "$(awk -F'\t' '$1 == "cold" && !($6 > 0 && $7 * 10 >= $6 * 9)' "$dir/batches.tsv" | wc -l)" 0
317 check "answers identical across disabled/warm/cold" "$(awk -F'\t' '$1 ~ /-k[0-9]+$/ && $1 !~ /^seed/ {
318 split($1, p, "-"); key = p[2] "-" p[3] "-" p[4]; if (key in s && s[key] != $9) bad++; s[key] = $9 } END {print bad + 0}' "$dir/requests.tsv")" 0
319 [ $fail = 0 ] && echo "PKV BENCH: COMPLETE" || echo "PKV BENCH: INCOMPLETE (see FAIL lines)"
320} | tee "$dir/summary.txt"
321grep -q "PKV BENCH: COMPLETE" "$dir/summary.txt" || fail=1
322stop_samplers
323if [ -n "$IOSTAT" ]; then kill "$IOSTAT" 2>/dev/null || true; fi
324IOSTAT=
325pkv_seal
326exit $fail