Datasets:
File size: 4,871 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 | """Quarantine pool documents that llama.cpp cannot tokenize.
python tools/screen.py --gguf /workspace/gguf/base/Muse-Glimmer-30B-BF16.gguf
`llama-tokenize` and `llama-imatrix` abort — not warn, abort — on some inputs:
$ printf '\\xF4\\x91\\x92\\x93' > t.txt # sixteen ASCII bytes
terminate called after throwing an instance of 'std::invalid_argument'
what(): invalid codepoint
The text is plain ASCII; the escape sequence is only *described*, not encoded.
`F4 91 92 93` would decode to U+111493, which is past U+10FFFF, and
`unicode_cpt_to_utf8` in src/unicode.cpp throws rather than substituting
U+FFFD. UTF-8 conformance test suites are full of such literals — nlohmann/json
has a file of them — so a corpus that samples test directories will hit it.
One aborted invocation costs a whole imatrix run, so the documents are found
here and quarantined rather than discovered mid-run. Screening is done by
divide and conquer: a shard is tokenized whole, and only a failing shard is
split, so a clean pool costs one invocation per shard.
"""
from __future__ import annotations
import argparse
import json
import os
import subprocess
import sys
import tempfile
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import poollib as P
DOC_SEP = "\n\n"
class Tokenizer:
def __init__(self, binary: str, gguf: str) -> None:
self.binary, self.gguf = binary, gguf
self.calls = 0
def ok(self, text: str) -> bool:
self.calls += 1
with tempfile.NamedTemporaryFile("w", suffix=".txt", encoding="utf-8",
delete=False) as f:
f.write(text)
path = f.name
try:
r = subprocess.run(
[self.binary, "-m", self.gguf, "-f", path, "--ids", "--log-disable"],
capture_output=True)
return r.returncode == 0
finally:
os.unlink(path)
def find_bad(tok: Tokenizer, docs: list[dict], texts: list[str]) -> list[int]:
"""Indices of documents that fail on their own."""
if not docs:
return []
if tok.ok(DOC_SEP.join(texts)):
return []
if len(docs) == 1:
return [0]
mid = len(docs) // 2
left = find_bad(tok, docs[:mid], texts[:mid])
right = find_bad(tok, docs[mid:], texts[mid:])
return left + [mid + i for i in right]
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--gguf", default="/workspace/gguf/base/Muse-Glimmer-30B-BF16.gguf")
ap.add_argument("--llama-tokenize",
default="/workspace/src/llama.cpp/build/bin/llama-tokenize")
ap.add_argument("--repo", default=P.REPO_ROOT)
ap.add_argument("--dry-run", action="store_true")
args = ap.parse_args()
tok = Tokenizer(args.llama_tokenize, args.gguf)
bad_records, report = [], []
for shard in P.shard_paths(P.POOL_ROOT):
rel = os.path.relpath(shard, args.repo)
if os.path.join("pool", "_quarantine") in rel:
continue
recs = list(P.read_jsonl(shard))
if not recs:
continue
texts = [P.render_record(r, None) for r in recs]
idx = find_bad(tok, recs, texts)
if not idx:
print(f" ok {rel} ({len(recs)} docs)")
continue
print(f" BAD {rel} {len(idx)} of {len(recs)} documents abort llama-tokenize")
keep = []
for i, r in enumerate(recs):
if i in idx:
print(f" {r['source']:20} {r['path'][:60]}")
r = dict(r)
r["provenance"] = dict(r.get("provenance") or {})
r["provenance"]["quarantined"] = (
"llama-tokenize aborts on this document (invalid codepoint in "
"src/unicode.cpp); it would kill an llama-imatrix run")
r["provenance"]["quarantined_from"] = rel
bad_records.append(r)
report.append({"shard": rel, "id": r["id"], "source": r["source"],
"path": r["path"]})
else:
keep.append(r)
if not args.dry_run:
P.write_jsonl(shard, keep)
print(f"\n{len(bad_records)} documents quarantined "
f"({tok.calls} llama-tokenize invocations)")
if bad_records and not args.dry_run:
out = os.path.join(P.POOL_ROOT, "_quarantine", "untokenizable.jsonl")
existing = list(P.read_jsonl(out)) if os.path.exists(out) else []
P.write_jsonl(out, existing + bad_records)
with open(os.path.join(P.POOL_ROOT, "screen-report.json"), "w") as f:
json.dump({"tool": "tools/screen.py", "gguf": args.gguf,
"quarantined": report}, f, indent=2)
f.write("\n")
return 0
if __name__ == "__main__":
sys.exit(main())
|