File size: 4,103 Bytes
a3c9247
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Reconstruct a paper scaling corpus as a prefix of the archived 10M corpus.

The canonical collection is ordered as 100,195 BrowseComp-Plus documents
followed by the deterministic FineWeb stream. The paper's lower-scale corpora
are nested prefixes. The exact observed document counts are:

    100k -> 100,195
    200k -> 200,197
    400k -> 400,195
    800k -> 800,195
    10m  -> 10,000,195

Output uses Pyserini JsonCollection-compatible JSONL shards.
"""

from __future__ import annotations

import argparse
import contextlib
import hashlib
import json
import subprocess
from pathlib import Path
from typing import BinaryIO, Iterator


SIZES = {
    "100k": 100_195,
    "200k": 200_197,
    "400k": 400_195,
    "800k": 800_195,
    "10m": 10_000_195,
}


@contextlib.contextmanager
def open_source(path: Path) -> Iterator[BinaryIO]:
    if path.suffix != ".zst":
        with path.open("rb") as handle:
            yield handle
        return

    process = subprocess.Popen(
        ["zstd", "-dc", "--long=31", str(path)],
        stdout=subprocess.PIPE,
    )
    if process.stdout is None:
        process.kill()
        raise RuntimeError(f"Could not open zstd output stream for {path}")
    try:
        yield process.stdout
    finally:
        process.stdout.close()
        return_code = process.wait()
        # A requested prefix can end inside a compressed shard. Closing the
        # pipe then gives zstd SIGPIPE, which is expected and not corruption.
        if return_code not in (0, -13, 141):
            raise RuntimeError(f"zstd failed with status {return_code}: {path}")


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--source", type=Path, required=True)
    parser.add_argument("--size", choices=SIZES, required=True)
    parser.add_argument("--output", type=Path, required=True)
    parser.add_argument("--docs-per-shard", type=int, default=100_000)
    args = parser.parse_args()

    target = SIZES[args.size]
    compressed_files = sorted(args.source.glob("docs_*.jsonl.zst"))
    source_files = compressed_files or sorted(args.source.glob("docs_*.jsonl"))
    if not source_files:
        raise SystemExit(
            f"No docs_*.jsonl.zst or docs_*.jsonl files found under {args.source}"
        )
    if args.docs_per_shard <= 0:
        raise SystemExit("--docs-per-shard must be positive")

    args.output.mkdir(parents=True, exist_ok=True)
    copied = 0
    shard_index = 0
    in_shard = 0
    output_handle = None
    digest = hashlib.sha256()

    try:
        for source_file in source_files:
            with open_source(source_file) as source_handle:
                for line in source_handle:
                    if copied >= target:
                        break
                    if output_handle is None or in_shard >= args.docs_per_shard:
                        if output_handle is not None:
                            output_handle.close()
                        output_path = args.output / f"docs_{shard_index:05d}.jsonl"
                        output_handle = output_path.open("wb")
                        shard_index += 1
                        in_shard = 0
                    output_handle.write(line)
                    digest.update(line)
                    copied += 1
                    in_shard += 1
            if copied >= target:
                break
    finally:
        if output_handle is not None:
            output_handle.close()

    if copied != target:
        raise SystemExit(f"Source exhausted at {copied:,}; expected {target:,}")

    manifest = {
        "variant": args.size,
        "doc_count": copied,
        "docs_per_shard": args.docs_per_shard,
        "shard_count": shard_index,
        "source": str(args.source),
        "construction": "ordered prefix of canonical 10M collection",
        "content_sha256": digest.hexdigest(),
    }
    (args.output / "manifest.json").write_text(
        json.dumps(manifest, indent=2) + "\n", encoding="utf-8"
    )
    print(json.dumps(manifest, indent=2))


if __name__ == "__main__":
    main()