#!/usr/bin/env bash
# job_insitu.sh: GDN state commit, main (ff5045cd8) vs branch (perf/gdn-state-commit), both Python on 43d087648 kernels in
# local/arbi-serve:main-43d0876, 110 VM 4090, one lock hold. The branch's GDN binaries are AOT artifacts built on box 201's
# build slot and seeded into the boot cache's aot overlay; main's are the rig cache's own.
# 1) in-situ ncu at c=4, main and branch (root engine on a private cache copy, deleted after)
# 2) nsys step captures c=1, 4, 8, two per arm, interleaved, on the rig's shared cache.
cd ~/gdn-commit; SH=$HOME/small-row-main; pct() { df --output=pcent / | tail -1 | tr -dc 0-9; }
exec 9>/run/lock/arbi-gpu-0.lock; flock -w 43200 9 || exit 1
echo "lock held $(date -Is) root $(pct)%"
trim() { rm -rf $1/arbi-serve/flat-weights $1/pycache $1/arbi-serve/boot-store/dynamo $1/arbi-serve/boot-store/inductor $1/arbi-serve/boot-store/compile-bundles; }
mkdir -p $SH/cache-main/arbi-serve/aot && cp -n aot_br/* $SH/cache-main/arbi-serve/aot/
if [ "${SKIP_NCU:-0}" != 1 ]; then
  trim $SH/cache-main
  if [ "$(pct)" -le 79 ]; then
    docker run --rm --name gdn-cachecopy -v $SH/cache-main:/src:ro -v $HOME/gdn-commit:/dst --entrypoint bash local/arbi-serve:main-43d0876 -c "rm -rf /dst/cache-ncu && cp -a /src /dst/cache-ncu && chown -R 0:0 /dst/cache-ncu"
    echo "cache copy done root $(pct)%"
    for arm in gdnmain gdnbr; do
      CACHE_DIR=$HOME/gdn-commit/cache-ncu CONC=4 bash scripts/serve.sh ncu_${arm}_c4 ncu $arm >> logs/insitu.log 2>&1; echo "ncu $arm rc=$? $(date -Is) root $(pct)%"
      docker run --rm --name gdn-cacheclean -v $HOME/gdn-commit:/dst --entrypoint bash local/arbi-serve:main-43d0876 -c "rm -rf /dst/cache-ncu/arbi-serve/flat-weights; chown -R $(id -u):$(id -g) /dst/out"
    done
    docker run --rm --name gdn-cacheclean -v $HOME/gdn-commit:/dst --entrypoint bash local/arbi-serve:main-43d0876 -c "rm -rf /dst/cache-ncu; chown -R $(id -u):$(id -g) /dst/out"
    echo "ncu cache removed root $(pct)%"
  else echo "root $(pct)%: no room for the ncu cache copy, skipped"; fi
fi
for r in 1 2; do for c in ${CONCS:-1 4 8}; do for arm in gdnmain gdnbr; do
  trim $SH/cache-main; CONC=$c bash scripts/serve.sh step_${arm}_c${c}_r$r nsys $arm >> logs/insitu.log 2>&1; echo "step $arm c$c r$r rc=$? $(date -Is) root $(pct)%"
done; done; done
trim $SH/cache-main; echo "job_insitu done $(date -Is) root $(pct)%"
