Datasets:
Download tools/screen.py from AtomicChat/calib-corpora: direct link, hf CLI and curl.
- Browser
- Download file 4.87 kB
-
https://huggingface.co/datasets/AtomicChat/calib-corpora/resolve/main/tools/screen.py
- Command line
-
hf download hf://datasets/AtomicChat/calib-corpora/tools/screen.py
-
curl -L -o screen.py https://huggingface.co/datasets/AtomicChat/calib-corpora/resolve/main/tools/screen.py
4.87 kB
| """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()) | |