#!/bin/bash
# Psychosonic Lab 05 follow-up: does a different batch size, or a restored prompt, change a
# model's numbers on THIS Mac, and does temperature 0 repeat here? Written for a second Mac
# (Josh's Mac mini M4, 2026-10-26). Everything runs on a private `ollama serve` on port 11437,
# started and stopped by this script. It never touches the Ollama app's own server.
#
#   bash go.sh                      # stage 1 then stage 2, gpt-oss:20b
#   STAGES=1 bash go.sh             # only the quick stage
#   MODEL=llama3.2:3b bash go.sh    # a small model, for a Mac with less than 24 GB
#   N=5 bash go.sh                  # five cold runs in stage 2 instead of ten
#
#   stage 1  about 20 to 40 minutes. why-check.py: the model's own probabilities for its first
#            words, with the batch at 512 and 1,024, prompt fresh and restored, and each setup
#            loaded cold twice as a control.
#   stage 2  hours. repeat-check.py, the Lab 05 task, ten times, each on a freshly started
#            Ollama at its DEFAULT batch, to see how many different answers come back and
#            which batch Ollama chooses on this Mac.
#
# Before you start: quit the Ollama app (menu bar icon, Quit), keep the Mac plugged in, and
# do not start the run within an hour of midnight: Ollama writes the date into the prompt, so a
# repeat taken on another day is a different input. When it ends it writes results-*.zip beside
# this file. Send that file back.
set -u
HERE=$(cd "$(dirname "$0")" && pwd)
cd "$HERE" || exit 1
MODEL=${MODEL:-gpt-oss:20b}
PORT=${PORT:-11437}
TOK=${TOK:-1500}
N=${N:-10}
STAGES=${STAGES:-"1 2"}
APP_CLI=/Applications/Ollama.app/Contents/Resources/ollama
OLLAMA=${OLLAMA:-$([ -x "$APP_CLI" ] && echo "$APP_CLI" || command -v ollama || echo "$APP_CLI")}   # the app's own CLI first: it is what the Lab used
OUT=${OUT:-$HERE/results-$(date +%Y%m%d-%H%M)}
mkdir -p "$OUT/why" "$OUT/cold" || exit 1
say() { echo "[$(date '+%F %T')] $*" | tee -a "$OUT/run.log"; }

[ -x "$OLLAMA" ] || { say "Ollama not found. Install it from ollama.com, then run this again."; exit 1; }
command -v python3 >/dev/null || { say "python3 not found. Run: xcode-select --install"; exit 1; }
MEM_GB=$(( $(sysctl -n hw.memsize) / 1073741824 ))
case "$MODEL" in gpt-oss*)
  if [ "$MEM_GB" -lt 24 ] && [ "${FORCE:-0}" != 1 ]; then
    say "This Mac has $MEM_GB GB. gpt-oss 20B needs about 14 GB for the model plus room for the context, so it would swap and the numbers would say little."
    say "Run:  MODEL=llama3.2:3b bash go.sh      (or FORCE=1 to try anyway)"; exit 1
  fi ;;
esac
if [ "${FORCE:-0}" != 1 ] && curl -s -m 3 "http://127.0.0.1:11434/api/ps" | grep -q '"name"'; then
  say "The Ollama app still has a model loaded. Quit the Ollama app (menu bar icon, Quit) and run this again."; exit 1
fi
caffeinate -ims -w $$ &      # no sleep while this runs; ends when this script does
{
  echo "date: $(date '+%F %T %Z')"
  echo "model: $MODEL"
  echo "chip: $(sysctl -n machdep.cpu.brand_string)"
  echo "model id: $(sysctl -n hw.model)"
  echo "memory: $MEM_GB GB"
  echo "macOS: $(sw_vers -productVersion)"
  echo "ollama: $("$OLLAMA" --version 2>&1 | tail -1)"
  echo "python: $(python3 --version 2>&1)"
  echo "stages: $STAGES, tokens: $TOK, cold runs: $N"
} > "$OUT/machine.txt"
cat "$OUT/machine.txt" | tee -a "$OUT/run.log"

pid=""
start_srv() {  # $1 = name of this server's log
  OLLAMA_MODELS=~/.ollama/models OLLAMA_HOST=127.0.0.1:$PORT OLLAMA_MAX_LOADED_MODELS=1 OLLAMA_NUM_PARALLEL=1 OLLAMA_KEEP_ALIVE=-1 \
    "$OLLAMA" serve > "$OUT/server-$1.log" 2>&1 &
  pid=$!
  for _ in $(seq 60); do curl -sf -m 2 "http://127.0.0.1:$PORT/api/version" >/dev/null && return 0; sleep 1; done
  say "the private Ollama did not start; see $OUT/server-$1.log"; exit 1
}
stop_srv() {   # by the PIDs this script started, never by name
  [ -n "$pid" ] || return 0
  local kids kid; kids=$(pgrep -P "$pid")
  kill "$pid" 2>/dev/null; wait "$pid" 2>/dev/null
  for kid in $kids; do
    for _ in $(seq 60); do kill -0 "$kid" 2>/dev/null || break; sleep 1; done
    kill -0 "$kid" 2>/dev/null && kill -9 "$kid" 2>/dev/null
  done
  pid=""
}
trap stop_srv EXIT
trap 'say "stopped"; exit 143' TERM INT

# The model must be on this Mac. Pull it through the private server if it is not.
start_srv pull
if ! curl -s "http://127.0.0.1:$PORT/api/tags" | grep -q "\"name\":\"$MODEL\""; then
  say "$MODEL is not on this Mac. Downloading it (gpt-oss 20B is about 14 GB)."
  OLLAMA_HOST=127.0.0.1:$PORT "$OLLAMA" pull "$MODEL" 2>&1 | tail -2 | tee -a "$OUT/run.log"
fi
stop_srv

launched() {   # the batch flags the model runner was really started with, from the server's log
  grep -o 'msg="starting llama-server" cmd="[^"]*' "$OUT/server-$1.log" 2>/dev/null | grep -oE ' -b [0-9]+ -ub [0-9]+' | tr '\n' ';'
}
sample() {     # $1 = sample name, rest = why-check.py options
  python3 -B why-check.py sample ollama "$MODEL" "$OUT/why/$1.json" --host "http://127.0.0.1:$PORT" --tokens "$TOK" "${@:2}" 2>&1 \
    | tail -1 | tee -a "$OUT/run.log"
}

if [[ " $STAGES " == *" 1 "* ]]; then
  say "STAGE 1: the model's own probabilities, batch 512 and 1,024"
  start_srv s1-b512;  say "batch 512, cold";  sample a1  --num-batch 512;  say "same server, prompt now restored"; sample a1r --num-batch 512; stop_srv
  start_srv s2-b512;  say "batch 512, cold again (the control)"; sample a2 --num-batch 512; stop_srv
  start_srv s3-b1024; say "batch 1,024, cold"; sample b1 --num-batch 1024; say "same server, restored"; sample b1r --num-batch 1024; stop_srv
  start_srv s4-b1024; say "batch 1,024, cold again (the control)"; sample b2 --num-batch 1024; stop_srv
  for pair in "control-512:a1:a2" "control-1024:b1:b2" "restore-512:a1:a1r" "restore-1024:b1:b1r" "batch-fresh:a1:b1" "batch-restored:a1r:b1r"; do
    IFS=: read -r name x y <<< "$pair"
    python3 -B why-check.py compare "$OUT/why/$x.json" "$OUT/why/$y.json" --json "$OUT/why/compare-$name.json" > /dev/null 2>&1 || say "could not compare $name"
  done
  { echo "batch flags Ollama really used: s1 $(launched s1-b512) s2 $(launched s2-b512) s3 $(launched s3-b1024) s4 $(launched s4-b1024)"; } | tee -a "$OUT/run.log"
fi

if [[ " $STAGES " == *" 2 "* ]]; then
  say "STAGE 2: $N cold runs of the Lab 05 task, Ollama's default batch (each run can take 10 to 20 minutes)"
  for k in $(seq -f %02g 1 "$N"); do
    if [ -f "$OUT/cold/run-$k/results.csv" ]; then say "run $k already done"; continue; fi
    start_srv "cold-$k"
    python3 -B repeat-check.py run "$MODEL" --n 1 --host "http://127.0.0.1:$PORT" --out "$OUT/cold/run-$k" 2>&1 | tail -3 | tee -a "$OUT/run.log"
    stop_srv
    echo "batch Ollama chose: $(launched "cold-$k")" | tee "$OUT/cold/run-$k/batch.txt" | tee -a "$OUT/run.log"
  done
fi

# The summary, read from the files this run wrote.
python3 -I -B - "$OUT" <<'PY' | tee "$OUT/RESULT.txt" | tee -a "$OUT/run.log"
import csv, glob, json, os, sys
out = sys.argv[1]
print("=" * 70); print(open(os.path.join(out, "machine.txt")).read().strip()); print("=" * 70)
import re
fit = []
for f in sorted(glob.glob(os.path.join(out, "server-*.log"))):
    if f.endswith("server-pull.log"):
        continue
    t = open(f, errors="replace").read()
    m = re.findall(r"offloaded (\d+)/(\d+) layers to GPU", t)
    ok = bool(m) and m[-1][0] == m[-1][1] and "no changes needed" in t
    fit.append((os.path.basename(f)[7:-4], f"{m[-1][0]}/{m[-1][1]}" if m else "?", ok))
if fit:
    bad = [n for n, _, ok in fit if not ok]
    print("MEMORY FIT. Did the whole model sit on the GPU with nothing adjusted, in every server?")
    print("  " + ("YES, in all %d servers (%s layers)" % (len(fit), fit[0][1]) if not bad else
                  "NO in: " + ", ".join(f"{n} ({l} layers)" for n, l, ok in fit if not ok) +
                  ". Those runs measured a different setup: close other apps and run again."))
    print()
cmp = {os.path.basename(f)[8:-5]: json.load(open(f)) for f in sorted(glob.glob(os.path.join(out, "why", "compare-*.json")))}
if cmp:
    print("STAGE 1. Does the same setup repeat, and what changes the numbers?")
    for name, c in cmp.items():
        if c["first_different_token"] is None and c["positions_with_any_difference"] == 0:
            print(f"  {name:16} IDENTICAL at all {c['tokens_compared']:,} positions (every probability, to the last digit)")
        elif c["first_different_token"] is None:
            print(f"  {name:16} SAME WORDS, DIFFERENT NUMBERS: probabilities differ at {c['positions_with_any_difference']:,} of "
                  f"{c['tokens_compared']:,} positions, median {c['median_logprob_difference']:.4f}, largest {c['largest_logprob_difference']:.3f}; "
                  f"no word flipped in these {c['tokens_compared']:,} tokens")
        else:
            # The leads come from the two runs' own best and runner-up; they exist even when the runs did
            # not share the same two best words (a third word joined the near tie).
            la, lb = c["a_best"] - c["a_runner_up"], c["b_best"] - c["b_runner_up"]
            third = "" if c.get("both_runs_had_the_same_two_best_words") else " (a THIRD word joined the near tie: the two runs did not share the same two best words)"
            print(f"  {name:16} numbers differ at {c['positions_with_any_difference']:,} of {c['same_before']:,} positions, "
                  f"largest {c['largest_logprob_difference']:.3f}; first different word is token {c['first_different_token'] + 1:,}; "
                  f"the word each run wrote led by {la:.4f} and {lb:.4f}{third}")
    ctl = [cmp[k] for k in ("control-512", "control-1024") if k in cmp]
    if ctl:
        print("  CONTROLS:", "both repeat to the last digit" if all(c["first_different_token"] is None and c["positions_with_any_difference"] == 0 for c in ctl)
              else "A CONTROL DID NOT REPEAT. Check the dates below before trusting the rest.")
    days = sorted({json.load(open(f))["meta"]["started"][:10] for f in glob.glob(os.path.join(out, "why", "[ab]*.json"))})
    print("  sample days:", ", ".join(days), "(more than one day means the run crossed midnight and the controls are void)" if len(days) > 1 else "(one day)")
runs = []
for d in sorted(glob.glob(os.path.join(out, "cold", "run-*"))):
    try:
        (r,) = csv.DictReader(open(os.path.join(d, "results.csv")))
    except OSError:
        continue
    b = open(os.path.join(d, "batch.txt")).read().strip().replace("batch Ollama chose: ", "") if os.path.exists(os.path.join(d, "batch.txt")) else ""
    runs.append((os.path.basename(d), r, b))
if runs:
    print(f"\nSTAGE 2. {len(runs)} cold runs of the Lab 05 task at temperature 0")
    for name, r, b in runs:
        print(f"  {name}  {r['outcome']:10} {r['done_reason'] or '-':7} tokens {r['eval_count'] or '-':>6}  {(r['sha256'] or '-')[:10]}  {r['seconds']:>7}s  {b or 'batch not logged'}")
    shas = {r["sha256"] for _, r, _ in runs if r["sha256"]}
    print(f"  {sum(r['outcome'] == 'pass' for _, r, _ in runs)} of {len(runs)} passed, "
          f"{sum(r['outcome'] not in ('pass', 'fail') for _, r, _ in runs)} gave no answer, {len(shas)} different passing/failing answer file(s)")
    print("  batches chosen:", ", ".join(sorted({b for _, _, b in runs})) or "none logged")
PY
# Home folder out of anything we send back, then one file to send.
python3 -I -B - "$OUT" <<'PY'
import glob, os, sys
home = os.path.expanduser("~")
for p in glob.glob(os.path.join(sys.argv[1], "**", "*"), recursive=True):
    if os.path.isfile(p) and p.endswith((".log", ".txt", ".json", ".csv")):
        s = open(p, encoding="utf-8", errors="replace").read()
        if home in s:
            open(p, "w", encoding="utf-8").write(s.replace(home, "~"))
PY
ditto -c -k --keepParent "$OUT" "$OUT.zip" && say "DONE. Send this file back: $OUT.zip"
