File size: 12,832 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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
from __future__ import annotations

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

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

from kawk50m.cli import configure_utf8_stdio
from kawk50m.text import (
    FilterConfig,
    measure_text,
    normalize_text,
    rejection_reason,
)


CHATML_BLOCK_RE = re.compile(
    r"<\|im_start\|>\s*(system|user|assistant)\s*\n?(.*?)<\|im_end\|>",
    re.IGNORECASE | re.DOTALL,
)
CODE_FENCE_RE = re.compile(r"```|~~~")
LATEX_RE = re.compile(
    r"\$\$|\\(?:begin|end|frac|dfrac|tfrac|sum|prod|sqrt|text|boxed)\b"
)
ROLE_LABELS = {
    "system": "지침",
    "user": "사용자",
    "assistant": "도우미",
}


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        description=(
            "Stream a pinned Korean ChatML dataset, remove code/math and "
            "non-Korean-heavy rows, and write resumable uint16 token chunks."
        )
    )
    parser.add_argument("--dataset", required=True)
    parser.add_argument(
        "--data-file",
        action="append",
        default=[],
        help=(
            "Explicit repository data file; repeat for multiple shards. "
            "Use this to exclude manifest/metadata JSON files."
        ),
    )
    parser.add_argument("--split", default="train")
    parser.add_argument("--revision", required=True)
    parser.add_argument("--tokenizer-dir", required=True)
    parser.add_argument("--output-dir", required=True)
    parser.add_argument("--max-output-tokens", type=int, required=True)
    parser.add_argument("--tokens-per-chunk", type=int, default=50_000_000)
    parser.add_argument("--shuffle-buffer", type=int, default=10_000)
    parser.add_argument("--seed", type=int, default=42)
    parser.add_argument("--batch-size", type=int, default=256)
    parser.add_argument(
        "--allowed-license",
        action="append",
        default=[],
        help="Accepted per-row license value; repeat for multiple licenses.",
    )
    parser.add_argument(
        "--exclude-source-regex",
        default=None,
        help="Reject rows whose source_name matches this regular expression.",
    )
    parser.add_argument("--resume", action="store_true")
    return parser.parse_args()


def render_chatml(text: str) -> str | None:
    blocks = [
        (role.casefold(), content.strip())
        for role, content in CHATML_BLOCK_RE.findall(text)
        if content.strip()
    ]
    roles = {role for role, _ in blocks}
    if "user" not in roles or "assistant" not in roles:
        return None
    return "\n\n".join(
        f"{ROLE_LABELS[role]}:\n{content}"
        for role, content in blocks
        if role in ROLE_LABELS
    )


def contains_code_or_math(text: str) -> bool:
    return bool(CODE_FENCE_RE.search(text) or LATEX_RE.search(text))


def structured_filter_config() -> FilterConfig:
    return FilterConfig(
        min_chars=100,
        max_chars=100_000,
        min_hangul_chars=30,
        min_hangul_letter_ratio=0.70,
        min_hangul_visible_ratio=0.50,
        max_digit_ratio=0.10,
        max_symbol_ratio=0.15,
        max_url_per_word=0.01,
        min_unique_line_ratio=0.60,
        min_unique_word_ratio=0.15,
        max_short_line_ratio=0.75,
        max_list_line_ratio=0.50,
        max_table_line_ratio=0.20,
        max_boilerplate_hits_per_1k=3.0,
        max_repeated_character_run=30,
        max_code_line_ratio=0.05,
        max_code_math_char_ratio=0.08,
        min_quality_score=0.65,
        strip_html=True,
        mask_pii=True,
    )


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


def main() -> None:
    configure_utf8_stdio()
    args = parse_args()
    for name in (
        "max_output_tokens",
        "tokens_per_chunk",
        "shuffle_buffer",
        "batch_size",
    ):
        if getattr(args, name) <= 0:
            raise ValueError(f"--{name.replace('_', '-')} must be positive")

    output_dir = Path(args.output_dir)
    output_dir.mkdir(parents=True, exist_ok=True)
    state_path = output_dir / "state.json"
    allowed_licenses = {value.casefold() for value in args.allowed_license}
    source_pattern = (
        re.compile(args.exclude_source_regex)
        if args.exclude_source_regex
        else None
    )
    filter_config = structured_filter_config()
    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")

    expected_state = {
        "dataset": args.dataset,
        "data_files": list(args.data_file),
        "split": args.split,
        "revision": args.revision,
        "max_output_tokens": args.max_output_tokens,
        "tokens_per_chunk": args.tokens_per_chunk,
        "shuffle_buffer": args.shuffle_buffer,
        "seed": args.seed,
        "allowed_licenses": sorted(allowed_licenses),
        "exclude_source_regex": args.exclude_source_regex,
        "tokenizer_vocab_size": len(tokenizer),
    }
    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"))
        for key, value in expected_state.items():
            if state.get(key) != value:
                raise ValueError(
                    f"Resume state mismatch for {key}: "
                    f"saved={state.get(key)!r}, requested={value!r}"
                )
        if state.get("complete"):
            print(json.dumps(state, ensure_ascii=False, indent=2))
            return
        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()}
        )
    else:
        if state_path.exists() or list(output_dir.glob("tokens-*.bin*")):
            raise FileExistsError(
                f"{output_dir} contains prior structured-token artifacts"
            )
        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 {
            **expected_state,
            "tokenizer": str(Path(args.tokenizer_dir).resolve()),
            "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 not current_temporary.is_file():
            raise RuntimeError("Resume state points to a missing token chunk")
        expected_bytes = current_chunk_tokens * np.dtype(np.uint16).itemsize
        with current_temporary.open("r+b") as handle:
            handle.truncate(expected_bytes)
    elif current_final.exists() or current_temporary.exists():
        raise RuntimeError("Unexpected token chunk exists beyond committed state")

    dataset = load_dataset(
        args.dataset,
        data_files=args.data_file or None,
        split=args.split,
        revision=args.revision,
        streaming=True,
    ).shuffle(seed=args.seed, buffer_size=args.shuffle_buffer)
    if documents_seen:
        dataset = dataset.skip(documents_seen)

    handle = current_temporary.open("ab")
    progress = tqdm(initial=documents_seen, unit="rows")
    row_batch: list[dict[str, Any]] = []

    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
        accepted: list[str] = []
        for row in row_batch:
            source_name = str(row.get("source_name", ""))
            license_name = str(row.get("license", "")).casefold()
            counters[f"license_{license_name or 'missing'}"] += 1
            if allowed_licenses and license_name not in allowed_licenses:
                counters["rejected_license"] += 1
                continue
            if source_pattern and source_pattern.search(source_name):
                counters["rejected_source"] += 1
                continue
            raw_text = row.get("text")
            if not isinstance(raw_text, str):
                counters["rejected_missing_text"] += 1
                continue
            rendered = render_chatml(raw_text)
            if rendered is None:
                counters["rejected_chatml"] += 1
                continue
            if contains_code_or_math(rendered):
                counters["rejected_explicit_code_or_math"] += 1
                continue
            text = normalize_text(rendered)
            reason = rejection_reason(
                text,
                filter_config,
                metrics=measure_text(text),
            )
            if reason is not None:
                counters[f"rejected_{reason}"] += 1
                continue
            accepted.append(text)
            counters["accepted"] += 1

        documents_seen += len(row_batch)
        counters["seen"] += len(row_batch)
        progress.update(len(row_batch))
        row_batch.clear()
        if accepted:
            encoded = tokenizer(
                accepted,
                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

    complete = False
    try:
        for row in dataset:
            row_batch.append(row)
            if len(row_batch) >= args.batch_size and commit_batch():
                complete = True
                break
        else:
            complete = commit_batch()
    finally:
        if not handle.closed:
            handle.flush()
            os.fsync(handle.fileno())
            handle.close()
        progress.close()

    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(
            f"{args.dataset} ended after {tokens_written:,} accepted tokens; "
            f"target was {args.max_output_tokens:,}"
        )
    sys.stdout.flush()
    sys.stderr.flush()
    os._exit(0)


if __name__ == "__main__":
    main()