#!/usr/bin/env python3
"""why-check.py: look at WHY a different batch size or a restored prompt changes a model's answer.

Psychosonic Lab, experiment 05, follow-up. https://psychosonicconsulting.com/lab/agent-gym

repeat-check.py showed that, at temperature 0, gpt-oss 20B repeats itself byte for byte
inside one setup, and that Ollama changes the setup without saying so. This script asks
the next question: what happens inside the model when it does? It asks for the model's
own probability for every word it writes (a log probability, "logprob") and for the
runner-up at each step. Two setups that give the same answer have the same numbers. Two
that give different answers show where the numbers first part and how close the two best
words were when they did.

Put it next to repeat-check.py, which holds the task. Standard library only. It talks to
a server on this Mac and writes only the file you name.

    python3 -B why-check.py sample ollama gpt-oss:20b out/a.json --num-batch 512
    python3 -B why-check.py sample llama  gpt-oss     out/b.json --host http://127.0.0.1:8080
    python3 -B why-check.py compare out/a.json out/b.json

`sample ollama` sends the request repeat-check.py sends, with logprobs on and a cap on
how many words to write. `sample llama` talks to llama.cpp's own server, with no Ollama
in the way: it renders the task with the model's built in chat template, then asks for
the same thing. `compare` reads two sample files and prints the first word at which they
differ, with the two best words' log probabilities in each.
"""
import argparse
import datetime
import importlib.util
import json
import os
import sys
import urllib.error
import urllib.request

HERE = os.path.dirname(os.path.abspath(__file__))


def task():
    """The system text and the prompt, taken from repeat-check.py so there is one copy."""
    path = os.path.join(HERE, "repeat-check.py")
    spec = importlib.util.spec_from_file_location("repeat_check", path)
    mod = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(mod)
    return mod.SYSTEM, mod.PROMPT, dict(mod.OPTIONS)


def post(url, body, timeout):
    req = urllib.request.Request(url, json.dumps(body).encode(),
                                 {"Content-Type": "application/json"})
    with urllib.request.urlopen(req, timeout=timeout) as r:
        return json.load(r)


def get(url, timeout=10):
    with urllib.request.urlopen(url, timeout=timeout) as r:
        return json.load(r)


def pair(entry):
    """(token, logprob) of the chosen word and of the runner-up, from either server's reply."""
    top = entry.get("top_logprobs") or []
    others = [t for t in top if t.get("token") != entry["token"]]
    second = others[0] if others else None
    return [entry["token"], entry["logprob"],
            second["token"] if second else None, second["logprob"] if second else None]


def sample(args):
    system, prompt, options = task()
    options["num_predict"] = args.tokens
    meta = dict(script="why-check.py", started=datetime.datetime.now().isoformat(timespec="seconds"),
                backend=args.backend, model=args.model, host=args.host, max_tokens=args.tokens)
    host = args.host.rstrip("/")
    if args.backend == "ollama":
        if args.num_batch:
            options["num_batch"] = args.num_batch
        if args.num_gpu is not None:
            options["num_gpu"] = args.num_gpu
        meta.update(options=options, server_version=get(host + "/api/version").get("version", ""))
        body = {"model": args.model, "stream": False, "options": options,
                "logprobs": True, "top_logprobs": 2,
                "messages": [{"role": "system", "content": system}, {"role": "user", "content": prompt}]}
        resp = post(host + "/api/chat", body, args.timeout)
        entries = resp.get("logprobs") or []
        meta.update(prompt_tokens=resp.get("prompt_eval_count"),
                    prompt_tokens_from_cache=resp.get("prompt_eval_cached_count"),
                    done_reason=resp.get("done_reason"), eval_count=resp.get("eval_count"))
    else:
        rendered = post(host + "/apply-template", {"messages": [
            {"role": "system", "content": system}, {"role": "user", "content": prompt}]}, 60)["prompt"]
        body = {"prompt": rendered, "n_predict": args.tokens, "temperature": 0, "n_probs": 2,
                "cache_prompt": not args.no_cache}
        resp = post(host + "/completion", body, args.timeout)
        entries = resp.get("completion_probabilities") or []
        meta.update(prompt_tokens=resp.get("tokens_evaluated"), prompt_tokens_from_cache=resp.get("tokens_cached"),
                    done_reason=resp.get("stop_type"), eval_count=resp.get("tokens_predicted"),
                    cache_prompt=body["cache_prompt"])
    if not entries:
        sys.exit("The server sent no logprobs. This script needs a server that returns them.")
    meta["tokens_logged"] = len(entries)
    os.makedirs(os.path.dirname(os.path.abspath(args.out)), exist_ok=True)
    json.dump(dict(meta=meta, tokens=[pair(e) for e in entries]), open(args.out, "w"))
    print(f"{args.out}: {len(entries)} tokens logged, prompt {meta['prompt_tokens']} tokens "
          f"({meta['prompt_tokens_from_cache']} from cache)")


def compare(args):
    a, b = (json.load(open(p)) for p in (args.a, args.b))
    ta, tb = a["tokens"], b["tokens"]
    n = min(len(ta), len(tb))
    first = next((i for i in range(n) if ta[i][0] != tb[i][0]), None)
    upto = first if first is not None else n
    deltas = [abs(ta[i][1] - tb[i][1]) for i in range(upto)]
    moved = sum(d != 0 for d in deltas)
    out = dict(a=os.path.basename(args.a), b=os.path.basename(args.b), tokens_compared=n,
               first_different_token=first,
               same_before=upto, bit_identical_before=(moved == 0),
               positions_with_any_difference=moved,
               largest_logprob_difference=max(deltas, default=0.0),
               median_logprob_difference=sorted(deltas)[len(deltas) // 2] if deltas else 0.0)
    if first is not None:
        x, y = ta[first], tb[first]
        out.update(token_a=x[0], token_b=y[0],
                   a_best=x[1], a_runner_up=x[3], a_runner_up_token=x[2],
                   b_best=y[1], b_runner_up=y[3], b_runner_up_token=y[2])
        # The same two words, seen from each side: how far apart were they?
        if x[2] == y[0] and y[2] == x[0] and x[3] is not None and y[3] is not None:
            out["gap_in_a"] = x[1] - x[3]
            out["gap_in_b"] = y[1] - y[3]
            out["both_runs_had_the_same_two_best_words"] = True
        else:
            out["both_runs_had_the_same_two_best_words"] = False
    print(json.dumps(out, indent=2))
    if args.json:
        json.dump(out, open(args.json, "w"), indent=2)


def main():
    p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    s = p.add_subparsers(dest="cmd", required=True)
    r = s.add_parser("sample", help="write one sample file")
    r.add_argument("backend", choices=["ollama", "llama"])
    r.add_argument("model", help="an Ollama tag, or any label for llama.cpp's server")
    r.add_argument("out", help="the file to write")
    r.add_argument("--host", default=None)
    r.add_argument("--tokens", type=int, default=1500, help="how many words to let it write")
    r.add_argument("--num-batch", type=int, help="ollama only: fix the prompt batch size")
    r.add_argument("--num-gpu", type=int, help="ollama only: layers on the GPU (0 = CPU only)")
    r.add_argument("--no-cache", action="store_true", help="llama only: do not reuse the cached prompt")
    r.add_argument("--timeout", type=int, default=3600)
    c = s.add_parser("compare", help="compare two sample files")
    c.add_argument("a")
    c.add_argument("b")
    c.add_argument("--json", help="also write the result here")
    args = p.parse_args()
    if args.cmd == "sample":
        args.host = args.host or ("http://127.0.0.1:11434" if args.backend == "ollama" else "http://127.0.0.1:8080")
        sample(args)
    else:
        compare(args)


if __name__ == "__main__":
    main()
