Download scripts/prepare_cpt_mix.py from Infinity08/KAWK50M-Project: direct link, hf CLI and curl.
- Browser
- Download file 5.41 kB
-
https://huggingface.co/datasets/Infinity08/KAWK50M-Project/resolve/main/scripts/prepare_cpt_mix.py
- Command line
-
hf download hf://datasets/Infinity08/KAWK50M-Project/scripts/prepare_cpt_mix.py
-
curl -L -o prepare_cpt_mix.py https://huggingface.co/datasets/Infinity08/KAWK50M-Project/resolve/main/scripts/prepare_cpt_mix.py
5.41 kB
| from __future__ import annotations | |
| import argparse | |
| import glob | |
| import json | |
| import os | |
| import shutil | |
| from pathlib import Path | |
| from typing import Any | |
| import numpy as np | |
| from kawk50m.cli import configure_utf8_stdio | |
| def parse_args() -> argparse.Namespace: | |
| parser = argparse.ArgumentParser( | |
| description=( | |
| "Build an exact-size long-context CPT mix with hard links for full " | |
| "uint16 shards and a bounded copy only for the final partial shard." | |
| ) | |
| ) | |
| parser.add_argument("--base-input", nargs="+", required=True) | |
| parser.add_argument("--structured-input", nargs="+", required=True) | |
| parser.add_argument("--validation-bin", required=True) | |
| parser.add_argument("--output-dir", required=True) | |
| parser.add_argument("--base-target-tokens", type=int, default=2_800_000_000) | |
| parser.add_argument( | |
| "--structured-target-tokens", type=int, default=200_000_000 | |
| ) | |
| return parser.parse_args() | |
| def discover(values: list[str]) -> list[Path]: | |
| paths: set[Path] = set() | |
| for value in values: | |
| matches = [Path(item) for item in glob.glob(value)] | |
| if matches: | |
| paths.update(path.resolve() for path in matches if path.is_file()) | |
| else: | |
| candidate = Path(value) | |
| if candidate.is_file(): | |
| paths.add(candidate.resolve()) | |
| return sorted(paths) | |
| def token_count(path: Path) -> int: | |
| size = path.stat().st_size | |
| if size % np.dtype(np.uint16).itemsize: | |
| raise ValueError(f"Not a uint16 binary: {path}") | |
| return size // np.dtype(np.uint16).itemsize | |
| def copy_prefix(source: Path, destination: Path, tokens: int) -> None: | |
| remaining = tokens * np.dtype(np.uint16).itemsize | |
| with source.open("rb") as input_handle, destination.open("xb") as output_handle: | |
| while remaining: | |
| block = input_handle.read(min(remaining, 16 * 1024 * 1024)) | |
| if not block: | |
| raise EOFError(f"{source} ended before {tokens:,} tokens") | |
| output_handle.write(block) | |
| remaining -= len(block) | |
| def select_shards( | |
| *, | |
| sources: list[Path], | |
| destination_dir: Path, | |
| target_tokens: int, | |
| ) -> dict[str, Any]: | |
| if target_tokens <= 0: | |
| raise ValueError("Target token count must be positive") | |
| destination_dir.mkdir() | |
| selected: list[dict[str, Any]] = [] | |
| written = 0 | |
| for index, source in enumerate(sources): | |
| available = token_count(source) | |
| remaining = target_tokens - written | |
| if remaining <= 0: | |
| break | |
| take = min(available, remaining) | |
| destination = destination_dir / f"{index:05d}-{source.name}" | |
| if take == available: | |
| os.link(source, destination) | |
| mode = "hardlink" | |
| else: | |
| destination = destination.with_name(destination.stem + "-partial.bin") | |
| copy_prefix(source, destination, take) | |
| mode = "prefix-copy" | |
| selected.append( | |
| { | |
| "source": str(source), | |
| "output": str(destination), | |
| "source_tokens": available, | |
| "tokens": take, | |
| "mode": mode, | |
| } | |
| ) | |
| written += take | |
| if written != target_tokens: | |
| raise RuntimeError( | |
| f"Only {written:,} tokens were available for target {target_tokens:,}" | |
| ) | |
| return {"tokens": written, "files": selected} | |
| def main() -> None: | |
| configure_utf8_stdio() | |
| args = parse_args() | |
| output_dir = Path(args.output_dir) | |
| if output_dir.exists(): | |
| raise FileExistsError(f"Refusing to overwrite {output_dir}") | |
| base_sources = discover(args.base_input) | |
| structured_sources = discover(args.structured_input) | |
| validation_source = Path(args.validation_bin).resolve() | |
| if not base_sources: | |
| raise FileNotFoundError("No base token shards were found") | |
| if not structured_sources: | |
| raise FileNotFoundError("No structured token shards were found") | |
| if not validation_source.is_file(): | |
| raise FileNotFoundError(validation_source) | |
| output_dir.mkdir(parents=True) | |
| try: | |
| base = select_shards( | |
| sources=base_sources, | |
| destination_dir=output_dir / "base", | |
| target_tokens=args.base_target_tokens, | |
| ) | |
| structured = select_shards( | |
| sources=structured_sources, | |
| destination_dir=output_dir / "structured", | |
| target_tokens=args.structured_target_tokens, | |
| ) | |
| validation_destination = output_dir / "validation.bin" | |
| os.link(validation_source, validation_destination) | |
| manifest = { | |
| "dtype": "uint16", | |
| "base": base, | |
| "structured": structured, | |
| "validation": { | |
| "source": str(validation_source), | |
| "output": str(validation_destination), | |
| "tokens": token_count(validation_destination), | |
| "mode": "hardlink", | |
| }, | |
| "total_train_tokens": base["tokens"] + structured["tokens"], | |
| } | |
| (output_dir / "manifest.json").write_text( | |
| json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", | |
| encoding="utf-8", | |
| ) | |
| print(json.dumps(manifest, ensure_ascii=False, indent=2)) | |
| except BaseException: | |
| shutil.rmtree(output_dir) | |
| raise | |
| if __name__ == "__main__": | |
| main() | |