# /// script
# requires-python = ">=3.11"
# dependencies = ["numpy>=1.26,<3", "onnxruntime>=1.20,<2", "tokenizers>=0.21,<1", "huggingface_hub>=0.30,<2"]
# ///
"""Run a single-file, cached-decoder ONNX export from a versioned model registry."""
import argparse
import hashlib
import json
import platform
import re
import subprocess
import time
import uuid
from datetime import datetime, timezone
from pathlib import Path

import numpy as np
import onnxruntime as ort
from tokenizers import Tokenizer

PROMPTS = [
    "The capital of France is", "Two plus two equals",
    "Write a short description of the ocean.", "A GPU is useful for",
    "Water freezes at", "The opposite of north is",
    "A red apple and a green apple are", "The fastest way to boil water is",
]


def digest(path):
    with path.open("rb") as file:
        return hashlib.file_digest(file, "sha256").hexdigest()


def verify_hf_file(path, metadata):
    """Check the file against the pinned Hub snapshot and return its SHA-256."""
    sha256 = hashlib.sha256()
    git_blob = hashlib.sha1(usedforsecurity=False)
    size = path.stat().st_size
    git_blob.update(f"blob {size}\0".encode())
    with path.open("rb") as file:
        while chunk := file.read(1024 * 1024):
            sha256.update(chunk)
            if not metadata.lfs:
                git_blob.update(chunk)
    if metadata.lfs:
        valid = size == metadata.lfs.size and sha256.hexdigest() == metadata.lfs.sha256
    else:
        valid = git_blob.hexdigest() == metadata.blob_id
    if not valid:
        raise ValueError(f"File does not match the pinned Hugging Face snapshot: {metadata.rfilename}")
    return sha256.hexdigest()


def resolve(args, names):
    if args.registry == "hf":
        from huggingface_hub import HfApi, hf_hub_download
        repo, separator, revision = args.ref.partition("@")
        if not separator:
            revision = "main"
        info = HfApi().model_info(repo, revision=revision, files_metadata=True)
        if not re.fullmatch(r"[a-f0-9]{40}", info.sha or ""):
            raise ValueError("Hugging Face did not return a full commit hash.")
        files = {entry.rfilename: entry for entry in info.siblings}
        paths = {}
        hashes = {}
        for name in names:
            if name not in files:
                raise ValueError(f"Missing registry file {name}.")
            entry = files[name]
            cached = Path(args.bundle_cache, name) if args.bundle_cache else None
            if cached and cached.is_file():
                try:
                    hashes[name] = verify_hf_file(cached, entry)
                except ValueError:
                    pass
                else:
                    paths[name] = cached
                    continue
            paths[name] = Path(hf_hub_download(repo, name, revision=info.sha))
            hashes[name] = verify_hf_file(paths[name], entry)
        return info.id or repo, info.sha, paths, hashes
    if args.registry == "mlflow":
        import mlflow
        from mlflow.tracking import MlflowClient
        match = re.fullmatch(r"models:/([^/]+)/([1-9][0-9]*)", args.ref)
        if not match:
            raise ValueError("Use models:/NAME/NUMERIC_VERSION.")
        version = MlflowClient().get_model_version(*match.groups())
        paths = {name: Path(mlflow.artifacts.download_artifacts(artifact_uri=f"{args.ref}/{name}")) for name in names}
        return version.name, str(version.version), paths, {name: digest(path) for name, path in paths.items()}
    import wandb
    if not re.fullmatch(r"[^/]+/[^/]+/[^/:]+:v[0-9]+", args.ref):
        raise ValueError("Use entity/project/artifact:vN or organization/wandb-registry-name/collection:vN.")
    artifact = wandb.Api().artifact(args.ref)
    paths = {name: Path(artifact.get_entry(name).download()) for name in names}
    return args.ref.rsplit(":", 1)[0], artifact.digest, paths, {name: digest(path) for name, path in paths.items()}



def prefix_study(args, tokenizer, empty_cache, decoder_step):
    """Measure resident prefix reuse on identical sequences, alternating run order."""
    paragraph = (
        "A service receives user requests and returns a response. "
        "The report records the time until the first response token and the total time. "
        "Several requests may share an unchanged introduction while asking different questions. "
    )
    prefix_tokens = tokenizer.encode(paragraph * 110, add_special_tokens=False).ids
    suffix = tokenizer.encode("In one sentence, what does the report measure?", add_special_tokens=False).ids
    if not suffix or len(prefix_tokens) < 1024:
        raise ValueError("The tokenizer did not produce enough tokens for the prefix experiment.")

    def generate(ids, cached, prefix_length):
        length = prefix_length + ids.shape[1]
        generated = []
        started = time.perf_counter_ns()
        for _ in range(args.tokens):
            token, cached = decoder_step(ids, cached, length)
            generated.append(token)
            if len(generated) == 1:
                first = time.perf_counter_ns()
            length += 1
            ids = np.array([[token]], dtype=np.int64)
        return {
            "ttft_ms": (first - started) / 1e6,
            "decode_after_first_ms": (time.perf_counter_ns() - first) / 1e6,
            "generated_ids": generated,
        }

    samples = []
    for prefix_length in (128, 512, 1024):
        prefix = np.array([prefix_tokens[:prefix_length]], dtype=np.int64)
        tail = np.array([suffix], dtype=np.int64)
        whole = np.concatenate((prefix, tail), axis=1)
        started = time.perf_counter_ns()
        _, resident = decoder_step(prefix, empty_cache(), prefix_length)
        population_ms = (time.perf_counter_ns() - started) / 1e6
        conditions = {
            "cold": lambda: generate(whole, empty_cache(), 0),
            "warm": lambda: generate(tail, resident, prefix_length),
        }
        for operation in conditions.values():
            operation()
        for pair in range(args.requests):
            order = ["cold", "warm"] if pair % 2 == 0 else ["warm", "cold"]
            timings = {key: conditions[key]() for key in order}
            if timings["cold"]["generated_ids"] != timings["warm"]["generated_ids"]:
                raise ValueError(f"Generated tokens differ for {prefix_length}-token prefix, pair {pair + 1}.")
            samples.append({
                "prefix_tokens": prefix_length, "suffix_tokens": len(suffix), "pair": pair + 1,
                "cache_population_ms": population_ms, "order": order,
                **timings,
            })
    return {
        "experiment": "resident-prefix-reuse-cpu-v1",
        "created_at": datetime.now(timezone.utc).isoformat(),
        "pairs_per_prefix": args.requests,
        "output_tokens_per_request": args.tokens,
        "limits": [
            "Single-host CPU microbenchmark. The warm condition starts with resident KV state.",
            "Measured time excludes tokenization, model loading and warm cache population.",
            "Identical greedy token IDs verify behavior on this fixture only.",
        ],
        "samples": samples,
    }


def run(args):
    names = ["config.json", "tokenizer.json", args.graph]
    repo, revision, paths, files = resolve(args, names)
    config = json.loads(paths["config.json"].read_text())
    tokenizer = Tokenizer.from_file(str(paths["tokenizer.json"]))
    opts = ort.SessionOptions()
    opts.intra_op_num_threads = args.threads
    opts.inter_op_num_threads = 1
    session = ort.InferenceSession(str(paths[args.graph]), sess_options=opts, providers=["CPUExecutionProvider"])
    inputs = {x.name: x for x in session.get_inputs()}
    kv = [x for x in inputs if x.startswith("past_key_values.")]
    expected = {"input_ids", "attention_mask", "position_ids", *kv}
    outputs = [x.name for x in session.get_outputs()]
    present = {name: name.replace("past_key_values.", "present.", 1) for name in kv}
    if set(inputs) != expected or not kv or not {"logits", *present.values()} <= set(outputs):
        raise ValueError("This runner requires a cached decoder with input IDs, mask, positions, logits and named present tensors.")
    bindings = {name: outputs.index(value) for name, value in present.items()}
    logits_index = outputs.index("logits")
    def empty_cache():
        state = {}
        for name in kv:
            spec = inputs[name]
            state[name] = np.empty((1, int(spec.shape[1]), 0, int(spec.shape[3])), dtype={"tensor(float)": np.float32, "tensor(float16)": np.float16}[spec.type])
        return state

    def decoder_step(ids, state, length):
        batch = session.run(None, {
            **state,
            "input_ids": ids,
            "attention_mask": np.ones((1, length), dtype=np.int64),
            "position_ids": np.arange(length - ids.shape[1], length, dtype=np.int64)[None, :],
        })
        token = int(np.argmax(batch[logits_index][0, -1]))
        return token, {name: batch[index] for name, index in bindings.items()}

    hardware = platform.machine()
    if platform.system() == "Darwin":
        hardware = subprocess.check_output(["sysctl", "-n", "machdep.cpu.brand_string"], text=True).strip()
    if args.prefix_study:
        report = prefix_study(args, tokenizer, empty_cache, decoder_step)
        report.update({
            "registry": {"type": args.registry, "reference": args.ref, "resolved_revision": revision, "sha256": files},
            "artifact": {"id": args.graph, "sha256": files[args.graph]},
            "environment": {"runtime": ort.__version__, "hardware": hardware, "threads": args.threads},
        })
        return report

    tokens = [np.array([tokenizer.encode(t).ids], dtype=np.int64) for t in PROMPTS]
    def generate(index):
        ids = tokens[index % len(tokens)]
        length = ids.shape[1]
        state = empty_cache()
        generated = []
        start = time.perf_counter_ns()
        for step in range(args.tokens):
            token, state = decoder_step(ids, state, length)
            generated.append(token)
            if step == 0:
                first_ms = (time.perf_counter_ns() - start) / 1e6
            ids = np.array([[token]], dtype=np.int64)
            length += 1
        return {"request_id": index, "prompt_index": index % len(tokens), "ok": True, "input_tokens": tokens[index % len(tokens)].size,
                "output_tokens": args.tokens, "latency_ms": (time.perf_counter_ns()-start)/1e6,
                "ttft_ms": first_ms, "generated_ids": generated}
    for i in range(2):
        generate(i)
    start = time.perf_counter()
    samples = [generate(i) for i in range(args.requests)]
    duration = time.perf_counter() - start
    def quantiles(field):
        return {f"p{p}": float(np.percentile([s[field] for s in samples], p)) for p in (50, 95, 99)}
    platform_id = f"{platform.system()} {platform.release()} / {hardware} / {args.threads} threads"
    workload_hash = hashlib.sha256(json.dumps(PROMPTS).encode()).hexdigest()
    return {"id": str(uuid.uuid4()), "schema_version": "0.1", "runner_version": "registry-1", "system": f"ONNX Runtime CPU · {Path(args.graph).stem}",
            "role": args.role, "verification": "self_reported", "track": "local", "measurement_scope": "model",
            "created_at": datetime.now(timezone.utc).isoformat(), "quality": None,
            "registry": {"type": args.registry, "reference": args.ref, "resolved_revision": revision, "sha256": files},
            "artifact": {"id": args.graph, "sha256": files[args.graph]}, "warmup_requests": 2,
            "environment": {"runtime": ort.__version__, "numpy": np.__version__, "execution_provider": "CPUExecutionProvider", "hardware": hardware, "threads": args.threads},
            "comparison": {"model": repo, "model_revision": revision, "architecture": config["model_type"], "hardware": hardware,
                           "platform_fingerprint": platform_id, "workload_id": "eight-short-completions-v1", "workload_sha256": workload_hash,
                           "scenario": "serial local greedy decode", "concurrency": 1, "max_output_tokens": args.tokens,
                           "cache_policy": "empty per request; reused for decode", "timing_scope": "pre-tokenized input through last greedy token on CPU",
                           "generation": "greedy, fixed output length, EOS ignored"},
            "metrics": {"attempted": len(samples), "completed": len(samples), "duration_s": duration, "error_rate": 0,
                        "latency_ms": quantiles("latency_ms"), "ttft_ms": quantiles("ttft_ms"), "throughput_tps": args.tokens*len(samples)/duration,
                        "output_tokens": args.tokens*len(samples), "goodput_rps": None,"peak_vram_mib": None,"cost_usd": None},
            "prompts": PROMPTS, "samples": samples, "limitations": ["Small single-host engineering run. No provider, network, price or task-quality measurement."]}


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--registry", choices=["hf", "mlflow", "wandb"], default="hf")
    parser.add_argument("--ref", required=True)
    parser.add_argument("--graph", default="onnx/model.onnx")
    parser.add_argument("--bundle-cache", help="Reuse files only after matching the pinned Hugging Face file digest.")
    parser.add_argument("--requests", type=int, default=16)
    parser.add_argument("--tokens", type=int, default=12)
    parser.add_argument("--threads", type=int, default=4)
    parser.add_argument("--role", choices=["baseline", "candidate"], default="baseline")
    parser.add_argument("--prefix-study", action="store_true", help="Measure resident prefix reuse and produce a separate experimental report.")
    parser.add_argument("--out", type=Path, required=True)
    args = parser.parse_args()
    if min(args.requests, args.threads) < 1 or args.tokens < 2 or not re.fullmatch(r"(?:[\w-]+/)*[\w-]+\.onnx", args.graph):
        parser.error("Provide positive counts, at least two output tokens and a relative ONNX graph path.")
    report = run(args)
    args.out.write_text(json.dumps(report, indent=2) + "\n")
    if args.prefix_study:
        print(f"Saved {args.out.name}: {len(report['samples'])} paired observations")
    else:
        print(f"Saved {args.out.name}: {report['metrics']['completed']} requests")
