Download src/pat/prepare.py from ICLRPAT27/PAT-code: direct link, hf CLI and curl.
- Browser
- Download file 3.7 kB
-
https://huggingface.co/ICLRPAT27/PAT-code/resolve/main/src/pat/prepare.py
- Command line
-
hf download hf://ICLRPAT27/PAT-code/src/pat/prepare.py
-
curl -L -o prepare.py https://huggingface.co/ICLRPAT27/PAT-code/resolve/main/src/pat/prepare.py
3.7 kB
| """Prepare JSONL documents with the release's exact tokenizer.""" | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import shutil | |
| import tempfile | |
| from pathlib import Path | |
| import numpy as np | |
| from .data import EOD, file_sha256 | |
| def prepare(input_path: Path, output: Path, tokenizer_path: Path | None, context_length: int) -> dict: | |
| from .tokenizer import Tokenizer | |
| if context_length <= 0: | |
| raise ValueError("context_length must be positive") | |
| if output.exists(): | |
| raise FileExistsError(f"Output already exists: {output}") | |
| artifact = tokenizer_path / "tokenizer.json" if tokenizer_path and tokenizer_path.is_dir() else tokenizer_path | |
| tokenizer = Tokenizer(artifact) | |
| artifact = tokenizer.path | |
| output.parent.mkdir(parents=True, exist_ok=True) | |
| temporary = Path(tempfile.mkdtemp(prefix=".prepare-", dir=output.parent)) | |
| offsets, lengths = [0], [] | |
| documents = 0 | |
| try: | |
| with input_path.open() as source, (temporary / "tokens.bin").open("wb") as sink: | |
| for line_number, line in enumerate(source, 1): | |
| row = json.loads(line) | |
| if not isinstance(row, dict) or not isinstance(row.get("text"), str): | |
| raise TypeError(f"Line {line_number} must contain a string 'text' field") | |
| ids = tokenizer.encode(row["text"]) | |
| if any(token >= EOD for token in ids): | |
| raise ValueError(f"Line {line_number} contains reserved control tokens") | |
| if not ids: | |
| continue | |
| documents += 1 | |
| for start in range(0, len(ids), context_length): | |
| piece = ids[start:start + context_length] | |
| lengths.append(len(piece)) | |
| if start + context_length >= len(ids): | |
| piece = piece + [EOD] | |
| np.asarray(piece, dtype="<u4").tofile(sink) | |
| offsets.append(offsets[-1] + len(piece)) | |
| if not lengths: | |
| raise ValueError("Input contains no nonempty documents") | |
| np.save(temporary / "offsets.npy", np.asarray(offsets, dtype="<i8"), allow_pickle=False) | |
| np.save(temporary / "lexical_lengths.npy", np.asarray(lengths, dtype="<i8"), allow_pickle=False) | |
| manifest = { | |
| "format": "pat-document-pieces-1", | |
| "context_length": context_length, | |
| "documents": documents, | |
| "pieces": len(lengths), | |
| "lexical_tokens": sum(lengths), | |
| "tokenizer_sha256": file_sha256(artifact), | |
| "source_sha256": file_sha256(input_path), | |
| "files": {name: file_sha256(temporary / name) for name in | |
| ("tokens.bin", "offsets.npy", "lexical_lengths.npy")}, | |
| } | |
| (temporary / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n") | |
| temporary.rename(output) | |
| return manifest | |
| finally: | |
| if temporary.exists(): | |
| shutil.rmtree(temporary) | |
| def main() -> None: | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--input", type=Path, required=True, help="JSONL with one text field per document") | |
| parser.add_argument("--output", type=Path, required=True, help="New prepared dataset directory") | |
| parser.add_argument("--tokenizer", type=Path, help="Exact release tokenizer file or directory (default: bundled)") | |
| parser.add_argument("--context-length", type=int, default=16384, help="Maximum lexical tokens per piece") | |
| args = parser.parse_args() | |
| print(json.dumps(prepare(args.input, args.output, args.tokenizer, args.context_length), indent=2)) | |
| if __name__ == "__main__": | |
| main() | |