File size: 13,080 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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
from __future__ import annotations

import argparse
import json
import os
import sys
from collections import Counter
from dataclasses import asdict
from pathlib import Path
from typing import Any

import numpy as np
from datasets import load_dataset
from huggingface_hub import HfApi
from tqdm import tqdm
from transformers import AutoTokenizer

from kawk50m.cli import configure_utf8_stdio
from kawk50m.text import FilterConfig
from scripts.prepare_corpus import processed_documents


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        description=(
            "Stream a pinned FineWeb2 shard, strictly filter Korean documents, "
            "and write resumable uint16 token chunks without keeping raw text."
        )
    )
    parser.add_argument("--dataset", default="HuggingFaceFW/fineweb-2")
    parser.add_argument("--subset", default="kor_Hang")
    parser.add_argument("--split", default="train")
    parser.add_argument("--revision", default=None)
    parser.add_argument("--tokenizer-dir", required=True)
    parser.add_argument("--output-dir", required=True)
    parser.add_argument("--dataset-num-shards", type=int, default=4)
    parser.add_argument("--dataset-shard-index", type=int, required=True)
    parser.add_argument("--skip-documents", type=int, default=0)
    parser.add_argument("--max-output-tokens", type=int, required=True)
    parser.add_argument("--tokens-per-chunk", type=int, default=250_000_000)
    parser.add_argument("--shuffle-buffer", type=int, default=10_000)
    parser.add_argument("--seed", type=int, default=42)
    parser.add_argument("--workers", type=int, default=4)
    parser.add_argument("--worker-batch-size", type=int, default=64)
    parser.add_argument("--tokenize-batch-size", type=int, default=512)
    parser.add_argument("--cache-dir", default=".cache/huggingface/datasets")
    parser.add_argument("--resume", action="store_true")
    return parser.parse_args()


def atomic_json(path: Path, value: dict[str, Any]) -> None:
    temporary = path.with_suffix(path.suffix + ".tmp")
    with temporary.open("w", encoding="utf-8") as handle:
        json.dump(value, handle, ensure_ascii=False, indent=2)
        handle.write("\n")
    os.replace(temporary, path)


def output_row(row: dict[str, Any], index: int) -> dict[str, Any] | None:
    text = row.get("text")
    if not isinstance(text, str) or not text.strip():
        return None
    return {
        "id": f"fineweb2:{row.get('id', index)}",
        "text": text,
        "source": "fineweb2:kor_Hang",
        "url": row.get("url"),
        "license": "ODC-By-1.0",
    }


def main() -> None:
    configure_utf8_stdio()
    args = parse_args()
    for name in (
        "dataset_num_shards",
        "max_output_tokens",
        "tokens_per_chunk",
        "shuffle_buffer",
        "workers",
        "worker_batch_size",
        "tokenize_batch_size",
    ):
        if getattr(args, name) <= 0:
            raise ValueError(f"--{name.replace('_', '-')} must be positive")
    if not 0 <= args.dataset_shard_index < args.dataset_num_shards:
        raise ValueError("--dataset-shard-index is outside the shard range")

    output_dir = Path(args.output_dir)
    output_dir.mkdir(parents=True, exist_ok=True)
    state_path = output_dir / "state.json"
    filter_config = FilterConfig()
    tokenizer = AutoTokenizer.from_pretrained(
        args.tokenizer_dir, use_fast=False, legacy=True
    )
    tokenizer.model_max_length = int(1e30)
    if len(tokenizer) > np.iinfo(np.uint16).max:
        raise ValueError("uint16 requires a vocabulary no larger than 65,535")
    if tokenizer.eos_token_id is None:
        raise ValueError("Tokenizer must define eos_token_id")

    if args.resume:
        if not state_path.is_file():
            raise FileNotFoundError(f"Resume state is missing: {state_path}")
        state = json.loads(state_path.read_text(encoding="utf-8"))
        expected = {
            "dataset": args.dataset,
            "subset": args.subset,
            "split": args.split,
            "dataset_num_shards": args.dataset_num_shards,
            "dataset_shard_index": args.dataset_shard_index,
            "skip_documents": args.skip_documents,
            "max_output_tokens": args.max_output_tokens,
            "tokens_per_chunk": args.tokens_per_chunk,
            "tokenizer_vocab_size": len(tokenizer),
            "filter": asdict(filter_config),
        }
        for key, value in expected.items():
            if state.get(key) != value:
                raise ValueError(
                    f"Resume state mismatch for {key}: "
                    f"saved={state.get(key)!r}, requested={value!r}"
                )
        revision = state["revision"]
        seed = int(state["seed"])
        shuffle_buffer = int(state["shuffle_buffer"])
        documents_seen = int(state["documents_seen"])
        tokens_written = int(state["tokens_written"])
        completed_chunks = int(state["completed_chunks"])
        current_chunk_tokens = int(state["current_chunk_tokens"])
        counters = Counter(
            {key: int(value) for key, value in state["counts"].items()}
        )
        if state.get("complete"):
            print(json.dumps(state, ensure_ascii=False, indent=2))
            return
    else:
        if state_path.exists() or list(output_dir.glob("tokens-*.bin*")):
            raise FileExistsError(
                f"{output_dir} contains prior stream-tokenization artifacts"
            )
        revision = args.revision or HfApi().dataset_info(args.dataset).sha
        seed = args.seed
        shuffle_buffer = args.shuffle_buffer
        documents_seen = 0
        tokens_written = 0
        completed_chunks = 0
        current_chunk_tokens = 0
        counters: Counter[str] = Counter()

    def final_path(index: int) -> Path:
        return output_dir / f"tokens-{index:05d}.bin"

    def temporary_path(index: int) -> Path:
        return output_dir / f"tokens-{index:05d}.bin.tmp"

    def state_value(*, complete: bool) -> dict[str, Any]:
        return {
            "dataset": args.dataset,
            "subset": args.subset,
            "split": args.split,
            "revision": revision,
            "license": "ODC-By-1.0; subject to CommonCrawl Terms of Use",
            "dataset_num_shards": args.dataset_num_shards,
            "dataset_shard_index": args.dataset_shard_index,
            "skip_documents": args.skip_documents,
            "seed": seed,
            "shuffle_buffer": shuffle_buffer,
            "max_output_tokens": args.max_output_tokens,
            "tokens_per_chunk": args.tokens_per_chunk,
            "tokenizer": str(Path(args.tokenizer_dir).resolve()),
            "tokenizer_vocab_size": len(tokenizer),
            "filter": asdict(filter_config),
            "upstream_deduplication": "FineWeb2 global MinHash deduplication",
            "documents_seen": documents_seen,
            "tokens_written": tokens_written,
            "completed_chunks": completed_chunks,
            "current_chunk_tokens": current_chunk_tokens,
            "counts": dict(sorted(counters.items())),
            "complete": complete,
        }

    current_final = final_path(completed_chunks)
    current_temporary = temporary_path(completed_chunks)
    if current_chunk_tokens:
        if current_final.is_file() and not current_temporary.exists():
            completed_chunks += 1
            current_chunk_tokens = 0
            atomic_json(
                state_path,
                state_value(complete=tokens_written >= args.max_output_tokens),
            )
            current_final = final_path(completed_chunks)
            current_temporary = temporary_path(completed_chunks)
        elif current_temporary.is_file():
            expected_bytes = current_chunk_tokens * np.dtype(np.uint16).itemsize
            with current_temporary.open("r+b") as handle:
                handle.truncate(expected_bytes)
        else:
            raise RuntimeError("Resume state points to a missing current token chunk")
    elif current_final.exists() or current_temporary.exists():
        raise RuntimeError("Unexpected token chunk exists beyond committed state")

    dataset = load_dataset(
        args.dataset,
        name=args.subset,
        split=args.split,
        revision=revision,
        streaming=True,
        cache_dir=args.cache_dir,
    )
    dataset = dataset.shard(
        num_shards=args.dataset_num_shards,
        index=args.dataset_shard_index,
        contiguous=True,
    )
    dataset = dataset.shuffle(seed=seed, buffer_size=shuffle_buffer)
    total_skip = args.skip_documents + documents_seen
    if total_skip:
        dataset = dataset.skip(total_skip)

    def documents() -> Any:
        for index, row in enumerate(dataset, start=total_skip):
            document = output_row(row, index)
            if document is not None:
                yield document

    processed = processed_documents(
        documents(),
        filter_config=filter_config,
        workers=args.workers,
        batch_size=args.worker_batch_size,
        limit=None,
    )
    result_batch: list[Any] = []
    handle = current_temporary.open("ab")
    progress = tqdm(initial=documents_seen, unit="docs")

    def finalize_chunk(*, reopen: bool) -> None:
        nonlocal handle, completed_chunks, current_chunk_tokens
        handle.flush()
        os.fsync(handle.fileno())
        handle.close()
        atomic_json(state_path, state_value(complete=False))
        os.replace(temporary_path(completed_chunks), final_path(completed_chunks))
        completed_chunks += 1
        current_chunk_tokens = 0
        atomic_json(
            state_path,
            state_value(complete=tokens_written >= args.max_output_tokens),
        )
        if reopen:
            handle = temporary_path(completed_chunks).open("ab")

    def commit_batch() -> bool:
        nonlocal documents_seen, tokens_written, current_chunk_tokens
        if not result_batch:
            return False
        accepted_texts: list[str] = []
        for _, text, reason, _, _, _ in result_batch:
            if reason is None:
                accepted_texts.append(text)
                counters["accepted"] += 1
            else:
                counters[f"rejected_{reason}"] += 1
        documents_seen += len(result_batch)
        counters["seen"] += len(result_batch)
        progress.update(len(result_batch))
        result_batch.clear()

        if accepted_texts:
            encoded = tokenizer(
                accepted_texts,
                add_special_tokens=False,
                return_attention_mask=False,
                return_token_type_ids=False,
            )["input_ids"]
            flat: list[int] = []
            for token_ids in encoded:
                flat.extend(token_ids)
                flat.append(tokenizer.eos_token_id)
            remaining = args.max_output_tokens - tokens_written
            if len(flat) > remaining:
                flat = flat[:remaining]
            if flat:
                array = np.asarray(flat, dtype=np.uint16)
                array.tofile(handle)
                tokens_written += len(array)
                current_chunk_tokens += len(array)
        atomic_json(
            state_path,
            state_value(complete=tokens_written >= args.max_output_tokens),
        )
        if (
            current_chunk_tokens >= args.tokens_per_chunk
            or tokens_written >= args.max_output_tokens
        ):
            finalize_chunk(reopen=tokens_written < args.max_output_tokens)
        return tokens_written >= args.max_output_tokens

    try:
        for result in processed:
            result_batch.append(result)
            if len(result_batch) >= args.tokenize_batch_size and commit_batch():
                break
        else:
            commit_batch()
        if current_chunk_tokens and not handle.closed:
            handle.flush()
            atomic_json(state_path, state_value(complete=False))
    finally:
        close_processed = getattr(processed, "close", None)
        if close_processed is not None:
            close_processed()
        if not handle.closed:
            handle.close()
        progress.close()

    complete = tokens_written >= args.max_output_tokens
    atomic_json(state_path, state_value(complete=complete))
    print(json.dumps(state_value(complete=complete), ensure_ascii=False, indent=2))
    if not complete:
        raise RuntimeError(
            "FineWeb2 shard ended before the requested token target was reached"
        )
    # Some pyarrow/fsspec streaming combinations abort in interpreter finalizers
    # after a remote iterator is intentionally stopped early. All output handles,
    # worker generators, and the atomic state file are already closed above.
    # A direct successful exit avoids turning a fully committed shard into a
    # false pipeline failure (and avoids producing a large core dump).
    sys.stdout.flush()
    sys.stderr.flush()
    os._exit(0)


if __name__ == "__main__":
    main()