File size: 5,411 Bytes
91ac3cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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()