#!/usr/bin/env python3
"""ppl2bpb.py - turn a llama.cpp perplexity into bits per byte (and nats/token, bits/token, bits/char).

Perplexity is per token, so two models with different tokenizers cannot be compared with it.
Bits per UTF-8 byte can. The conversion needs the number of tokens that were scored and the number of
bytes those tokens cover; llama-perplexity prints neither. This script works both out exactly, by
tokenizing the text with llama-tokenize the way llama-perplexity does and replaying its chunking:

  n_chunk = floor(n_tokens / n_ctx)            the tail that does not fill a chunk is not evaluated
  in each chunk only the second half is scored: tokens n_ctx/2 + 1 ... n_ctx - 1  (n_ctx - 1 - n_ctx/2 of them)

  bits per byte = ln(PPL) * tokens_scored / (ln 2 * bytes_covered_by_the_scored_tokens)

Three ways to use it (Python 3.8+, standard library only):

  # 1. run everything (llama-perplexity and llama-tokenize from the same llama.cpp build)
  python ppl2bpb.py --bin-dir llama.cpp/build/bin -m model.gguf -f text.txt [-c 512] [-- extra llama-perplexity args]

  # 2. you already have the perplexity (from a run with the same -f and -c): only tokenize
  python ppl2bpb.py --bin-dir llama.cpp/build/bin -m model.gguf -f text.txt -c 512 --ppl 7.4213

  # 3. no llama.cpp at all: plain arithmetic from numbers you supply
  python ppl2bpb.py --ppl 7.4213 --tokens 91290 --bytes 372100 [--chars 371950]

Checked against llama.cpp b12925 (tools/perplexity/perplexity.cpp). --ppl-stride runs are not supported.
"""
import argparse, json, math, os, re, subprocess, sys, tempfile

LN2 = math.log(2.0)


def units(nats_per_token, tokens, nbytes, nchars=None):
    total = nats_per_token * tokens
    out = {
        "perplexity": math.exp(nats_per_token),
        "nats_per_token": nats_per_token,
        "bits_per_token": nats_per_token / LN2,
        "log10_per_token": nats_per_token / math.log(10.0),
        "tokens_scored": tokens,
        "bytes_covered": nbytes,
        "bytes_per_token": nbytes / tokens,
        "total_nll_nats": total,
        "bits_per_byte": total / LN2 / nbytes,
        "byte_perplexity": math.exp(total / nbytes),
    }
    if nchars:
        out["chars_covered"] = nchars
        out["bits_per_char"] = total / LN2 / nchars
    return out


def run(cmd):
    p = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    if p.returncode != 0:
        sys.stderr.write(p.stderr.decode("utf-8", "replace")[-2000:])
        sys.exit("command failed: " + " ".join(cmd))
    return p.stdout, p.stderr


def tokenize(bin_dir, model, text_bytes):
    """Token ids and the bytes of every token piece, tokenized the way llama-perplexity tokenizes -f."""
    exe = os.path.join(bin_dir, "llama-tokenize")
    with tempfile.NamedTemporaryFile(suffix=".txt", delete=False) as tf:
        tf.write(text_bytes)
        tmp = tf.name
    try:
        # llama-perplexity does not process escapes and does not parse special tokens; llama-tokenize does both by default
        base = [exe, "-m", model, "-f", tmp, "--log-disable", "--no-escape", "--no-parse-special"]
        ids = json.loads(run(base + ["--ids"])[0].decode("ascii"))
        raw = run(base)[0]
    finally:
        os.unlink(tmp)
    # default output is one "%6d -> '%s'\n" per token; a piece may itself contain quotes and newlines,
    # so split on the marker of the next id that we already know
    pieces, pos = [], 0
    for k, tid in enumerate(ids):
        head = b"%6d -> '" % tid
        if not raw.startswith(head, pos):
            sys.exit("could not parse llama-tokenize output at token %d" % k)
        start = pos + len(head)
        if k + 1 < len(ids):
            nxt = b"'\n" + (b"%6d -> '" % ids[k + 1])
            end = raw.find(nxt, start)
            if end < 0:
                sys.exit("could not parse llama-tokenize output after token %d" % k)
        else:
            end = raw.rfind(b"'\n")
        pieces.append(raw[start:end])
        pos = end + 2
    return ids, pieces


def main():
    ap = argparse.ArgumentParser(description="llama.cpp perplexity -> bits per byte")
    ap.add_argument("--bin-dir", help="directory with llama-tokenize (and llama-perplexity)")
    ap.add_argument("-m", "--model", help="GGUF model (the one the perplexity was measured with)")
    ap.add_argument("-f", "--file", help="the text file given to llama-perplexity -f")
    ap.add_argument("-c", "--ctx-size", type=int, default=512, help="llama-perplexity -c (its default is 512)")
    ap.add_argument("--chunks", type=int, default=-1, help="llama-perplexity --chunks, if you limited it")
    ap.add_argument("--ppl", type=float, help="perplexity you already measured (skips running llama-perplexity)")
    ap.add_argument("--tokens", type=int, help="arithmetic only: number of scored tokens")
    ap.add_argument("--bytes", type=int, help="arithmetic only: UTF-8 bytes those tokens cover")
    ap.add_argument("--chars", type=int, help="arithmetic only: characters those tokens cover")
    ap.add_argument("--json", action="store_true", help="print JSON")
    ap.add_argument("extra", nargs="*", help="after --: extra arguments for llama-perplexity (-t, -ngl, ...)")
    a = ap.parse_args()

    if a.tokens and a.bytes:
        if a.ppl is None:
            sys.exit("--tokens/--bytes need --ppl")
        res = units(math.log(a.ppl), a.tokens, a.bytes, a.chars)
        res["mode"] = "arithmetic"
    else:
        if not (a.bin_dir and a.model and a.file):
            sys.exit("give --bin-dir, -m and -f, or --ppl with --tokens and --bytes (see --help)")
        if any(x.startswith("--ppl-stride") for x in a.extra):
            sys.exit("--ppl-stride runs use a different window; not supported")
        data = open(a.file, "rb").read()
        if data.endswith(b"\n"):
            data = data[:-1]  # llama.cpp's -f drops one trailing newline
        ids, pieces = tokenize(a.bin_dir, a.model, data)
        n_ctx = a.ctx_size
        if len(ids) < 2 * n_ctx:
            sys.exit("llama-perplexity needs at least %d tokens for -c %d; this text has %d" % (2 * n_ctx, n_ctx, len(ids)))
        n_chunk = len(ids) // n_ctx
        if a.chunks >= 0:
            n_chunk = min(n_chunk, a.chunks)
        first = n_ctx // 2
        per_chunk = n_ctx - 1 - first
        scored_bytes = scored_chars = 0
        partial = False
        for i in range(n_chunk):
            seg = b"".join(pieces[i * n_ctx + first + 1:(i + 1) * n_ctx])
            scored_bytes += len(seg)
            try:
                scored_chars += len(seg.decode("utf-8"))
            except UnicodeDecodeError:  # a chunk boundary fell inside a multi-byte character
                partial = True
                scored_chars += len(seg.decode("utf-8", "replace"))
        tokens_scored = n_chunk * per_chunk
        ppl, ran = a.ppl, None
        if ppl is None:
            exe = os.path.join(a.bin_dir, "llama-perplexity")
            cmd = [exe, "-m", a.model, "-f", a.file, "-c", str(n_ctx)] + (["--chunks", str(a.chunks)] if a.chunks >= 0 else []) + a.extra
            sys.stderr.write("running: " + " ".join(cmd) + "\n")
            so, se = run(cmd)
            log = (so + se).decode("utf-8", "replace")
            m = re.search(r"Final estimate: PPL = ([0-9.]+)", log)
            if not m:
                sys.exit("no 'Final estimate: PPL' in llama-perplexity output")
            ppl = float(m.group(1))
            c = re.search(r"calculating perplexity over (\d+) chunks, n_ctx=(\d+)", log)
            if c:
                ran = (int(c.group(1)), int(c.group(2)))
                if ran != (n_chunk, n_ctx):
                    sys.exit("llama-perplexity ran %d chunks at n_ctx=%d but this script expected %d at %d: "
                             "different build or options; do not trust the conversion" % (ran + (n_chunk, n_ctx)))
        res = units(math.log(ppl), tokens_scored, scored_bytes, scored_chars)
        # a BOS token the tokenizer added shows up as a piece ("<s>", "<|begin_of_text|>") that is not in the text
        has_bos = not data.startswith(pieces[0])
        whole_bytes = sum(len(p) for p in pieces[1 if has_bos else 0:])
        res.update({
            "mode": "llama-perplexity", "n_ctx": n_ctx, "n_chunk": n_chunk, "tokens_in_text": len(ids), "bos_added": has_bos,
            "file_bytes": len(data), "piece_bytes": whole_bytes,
            "share_of_text_scored": scored_bytes / len(data),
            # what you get if you divide by the whole file instead (the usual shortcut)
            "bits_per_byte_whole_file_shortcut": math.log(ppl) * len(ids) / LN2 / len(data),
            "chars_approximate": partial,
        })
    if a.json:
        print(json.dumps(res, indent=1))
        return
    r = res
    print("perplexity            %.4f" % r["perplexity"])
    print("nats per token        %.5f   (ln PPL; the usual 'loss')" % r["nats_per_token"])
    print("bits per token        %.5f" % r["bits_per_token"])
    print("log10 per token       %.5f" % r["log10_per_token"])
    print("tokens scored         %d" % r["tokens_scored"])
    print("bytes they cover      %d   (%.4f bytes per token)" % (r["bytes_covered"], r["bytes_per_token"]))
    print("bits per byte         %.5f   <- comparable across tokenizers" % r["bits_per_byte"])
    if "bits_per_char" in r:
        print("bits per character    %.5f%s" % (r["bits_per_char"], "   (approximate: a chunk edge split a character)" if r.get("chars_approximate") else ""))
    print("byte perplexity       %.5f" % r["byte_perplexity"])
    if r["mode"] == "llama-perplexity":
        print("")
        print("chunks                %d x n_ctx %d; text has %d tokens%s, %d bytes" % (r["n_chunk"], r["n_ctx"], r["tokens_in_text"], " (BOS included)" if r["bos_added"] else "", r["file_bytes"]))
        print("share of text scored  %.1f%% of the bytes (second half of each chunk; the tail is dropped)" % (100 * r["share_of_text_scored"]))
        print("whole-file shortcut   %.5f bits per byte if you use all tokens / all bytes instead (%+.2f%%)" % (
            r["bits_per_byte_whole_file_shortcut"], 100 * (r["bits_per_byte_whole_file_shortcut"] / r["bits_per_byte"] - 1)))
        if r["piece_bytes"] != r["file_bytes"]:
            print("note                  token pieces add up to %d bytes, the text is %d (the tokenizer adds or normalizes characters, e.g. SentencePiece's leading space)" % (r["piece_bytes"], r["file_bytes"]))


if __name__ == "__main__":
    main()
