File size: 8,480 Bytes
c9faf30
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
"""Vocabulary coverage and document-length distribution for a calibration file.

    python tools/coverage.py --gguf /workspace/gguf/base/Muse-Glimmer-30B-BF16.gguf \
        builds/muse-glimmer-30b/calib_train.txt

    python tools/coverage.py --backend hf \
        --tokenizer /workspace/models/muse-glimmer-30b/tokenizer.json calib_train.txt

Two backends, because they answer slightly different questions:

* `llama-cpp` runs `llama-tokenize` against the GGUF the imatrix will actually
  be computed from.  This is the authoritative number — it goes through the same
  vocabulary and the same `llama4` pre-tokenizer that `llama-imatrix` will use.
* `hf` uses the model's `tokenizer.json` in-process.  Much faster, and the two
  are expected to agree; `--compare` checks that they do on a sample.

Coverage is reported against embedding rows, since that is the thing an imatrix
either has statistics for or does not: a row no calibration token ever selects
gets no importance data, and the quantiser has nothing to protect it with.
"""

from __future__ import annotations

import argparse
import json
import os
import subprocess
import sys
from collections import Counter

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)

import poollib as P

DEFAULT_LLAMA_TOKENIZE = "/workspace/src/llama.cpp/build/bin/llama-tokenize"
DEFAULT_GGUF = "/workspace/gguf/base/Muse-Glimmer-30B-BF16.gguf"


def tokenize_llama_cpp(path: str, gguf: str, binary: str) -> list[int]:
    """Token ids from llama-tokenize.

    That tool defaults to parse_special=true, so `<|start|>` and friends in the
    text become their own ids -- the same thing `llama-imatrix --parse-special`
    will do.
    """
    res = subprocess.run(
        [binary, "-m", gguf, "-f", path, "--ids", "--log-disable"],
        capture_output=True, text=True)
    if res.returncode != 0:
        raise SystemExit(f"llama-tokenize failed:\n{res.stderr[-3000:]}")
    out = res.stdout.strip()
    start = out.rfind("[")
    if start < 0:
        raise SystemExit(f"unexpected llama-tokenize output: {out[:300]!r}")
    return json.loads(out[start:])


def doc_lengths(text: str, tok, sep: str = "\n\n",
                manifest: str | None = None) -> list[int]:
    """Token count per document.

    Splitting on the blank-line separator is wrong for anything real: source
    files and prose both contain blank lines, so it reported 65,838 documents
    for a 3,356-document build and a p50 of 31 tokens. When the build manifest
    is available its `chars` column gives the exact boundaries, the same way
    pipeline/build.py wrote them.
    """
    if manifest and os.path.exists(manifest):
        recs = [json.loads(l) for l in open(manifest, encoding="utf-8") if l.strip()]
        # `chars` counts the characters that were written. Reading back with
        # universal newlines silently folds every CRLF into one character, so
        # the offsets drift and the split falls back to blank lines -- which is
        # how a 3,363-document build was reported as 65,838 documents.
        docs, pos = [], 0
        for i, r in enumerate(recs):
            docs.append(text[pos:pos + r["chars"]])
            pos += r["chars"] + (len(sep) if i < len(recs) - 1 else 0)
        if abs(pos - len(text)) <= 2:
            return [len(ids) for ids in tok.encode_batch(docs)]
        print(f"  ! {manifest} does not line up with the file "
              f"({pos} vs {len(text)} characters); falling back to separator split")
    docs = [d for d in text.split(sep) if d.strip()]
    return [len(ids) for ids in tok.encode_batch(docs)]


def percentiles(xs: list[int]) -> dict:
    if not xs:
        return {}
    s = sorted(xs)

    def q(p):
        return s[min(len(s) - 1, int(p * len(s)))]
    return {"p50": q(0.50), "p90": q(0.90), "p95": q(0.95), "p99": q(0.99),
            "min": s[0], "max": s[-1], "mean": round(sum(s) / len(s), 1)}


def report(name: str, ids: list[int], n_vocab: int, lengths: list[int] | None,
           label: str) -> dict:
    c = Counter(ids)
    ge1 = len(c)
    ge10 = sum(1 for v in c.values() if v >= 10)
    ge100 = sum(1 for v in c.values() if v >= 100)
    out = {
        "file": name,
        "backend": label,
        "tokens": len(ids),
        "vocab_rows": n_vocab,
        "coverage": {
            "seen_ge_1": {"ids": ge1, "percent": round(100.0 * ge1 / n_vocab, 3)},
            "seen_ge_10": {"ids": ge10, "percent": round(100.0 * ge10 / n_vocab, 3)},
            "seen_ge_100": {"ids": ge100, "percent": round(100.0 * ge100 / n_vocab, 3)},
            "unseen": {"ids": n_vocab - ge1,
                       "percent": round(100.0 * (n_vocab - ge1) / n_vocab, 3)},
        },
    }
    print(f"\n=== {name}  [{label}] ===")
    print(f"tokens: {len(ids):,}")
    print(f"vocabulary coverage (denominator = {n_vocab:,} embedding rows):")
    print(f"  seen >=1   : {ge1:>9,}  ({100.0*ge1/n_vocab:6.2f}%)")
    print(f"  seen >=10  : {ge10:>9,}  ({100.0*ge10/n_vocab:6.2f}%)")
    print(f"  seen >=100 : {ge100:>9,}  ({100.0*ge100/n_vocab:6.2f}%)")
    print(f"  unseen     : {n_vocab-ge1:>9,}  ({100.0*(n_vocab-ge1)/n_vocab:6.2f}%)")
    if lengths:
        p = percentiles(lengths)
        out["documents"] = len(lengths)
        out["document_tokens"] = p
        big = sum(1 for x in lengths if x >= 8192)
        big_tok = sum(x for x in lengths if x >= 8192)
        out["documents_ge_8k"] = {"documents": big,
                                  "percent_of_tokens": round(100.0 * big_tok / max(1, sum(lengths)), 2)}
        print(f"documents: {len(lengths):,}")
        print(f"  document tokens: p50={p['p50']:,}  p90={p['p90']:,}  "
              f"p95={p['p95']:,}  p99={p['p99']:,}  max={p['max']:,}")
        print(f"  docs >= 8k tokens: {big:,}  ({out['documents_ge_8k']['percent_of_tokens']}% of tokens)")
    return out


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("files", nargs="+")
    ap.add_argument("--backend", choices=("llama-cpp", "hf"), default="llama-cpp")
    ap.add_argument("--gguf", default=DEFAULT_GGUF)
    ap.add_argument("--llama-tokenize", default=DEFAULT_LLAMA_TOKENIZE)
    ap.add_argument("--tokenizer", default=None, help="tokenizer.json for the hf backend")
    ap.add_argument("--vocab-size", type=int, default=None)
    ap.add_argument("--sep", default="\n\n")
    ap.add_argument("--json-out", default=None)
    ap.add_argument("--manifest", default=None,
                    help="build manifest giving exact document boundaries; "
                         "defaults to <file>.manifest.jsonl beside the input")
    ap.add_argument("--compare", action="store_true",
                    help="tokenize with both backends and report disagreement")
    args = ap.parse_args()

    hf = P.TargetTokenizer(args.tokenizer, n_vocab=args.vocab_size) if args.tokenizer else None
    n_vocab = args.vocab_size or (hf.n_vocab if hf else 202048)

    results = []
    for path in args.files:
        text = open(path, encoding="utf-8", newline="").read()
        if args.backend == "hf":
            if hf is None:
                raise SystemExit("--tokenizer is required for --backend hf")
            ids = hf.encode(text)
            label = f"hf:{os.path.basename(args.tokenizer)}"
        else:
            ids = tokenize_llama_cpp(path, args.gguf, args.llama_tokenize)
            label = f"llama-tokenize:{os.path.basename(args.gguf)}"
        mf = args.manifest or os.path.splitext(path)[0] + ".manifest.jsonl"
        lengths = doc_lengths(text, hf, args.sep, mf) if hf else None
        results.append(report(path, ids, n_vocab, lengths, label))

        if args.compare and hf is not None and args.backend != "hf":
            hf_ids = hf.encode(text)
            same = hf_ids == ids
            print(f"  backend agreement: {'identical' if same else 'DIFFER'} "
                  f"({len(ids):,} vs {len(hf_ids):,} tokens)")
            results[-1]["backend_agreement"] = {
                "identical": same, "llama_cpp_tokens": len(ids),
                "hf_tokens": len(hf_ids),
                # llama-tokenize prepends BOS; one extra token is expected
                "difference": len(ids) - len(hf_ids)}

    if args.json_out:
        with open(args.json_out, "w", encoding="utf-8") as f:
            json.dump(results, f, indent=2)
            f.write("\n")
        print(f"\nwrote {args.json_out}")
    return 0


if __name__ == "__main__":
    sys.exit(main())