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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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
from __future__ import annotations

import argparse
import hashlib
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.chat import ROLE_HEADERS, build_assistant_examples, parse_chatml
from kawk50m.cli import configure_utf8_stdio
from kawk50m.text import FilterConfig, measure_text, normalize_text, rejection_reason


CODE_FENCE_RE = re.compile(r"```|~~~")
LATEX_RE = re.compile(
    r"\$\$|\\(?:begin|end|frac|dfrac|tfrac|sum|prod|sqrt|text|boxed)\b"
)


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        description=(
            "Stream a pinned Korean ChatML source and create packed SFT records "
            "whose loss mask supervises assistant responses only."
        )
    )
    parser.add_argument("--dataset", required=True)
    parser.add_argument("--data-file", action="append", default=[])
    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("--train-tokens", type=int, required=True)
    parser.add_argument("--validation-tokens", type=int, required=True)
    parser.add_argument("--sequence-length", type=int, default=5120)
    parser.add_argument("--validation-permyriad", type=int, default=128)
    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=128)
    parser.add_argument("--allowed-license", action="append", default=[])
    parser.add_argument("--exclude-source-regex")
    parser.add_argument("--resume", action="store_true")
    return parser.parse_args()


def sft_filter_config() -> FilterConfig:
    return FilterConfig(
        min_chars=30,
        max_chars=100_000,
        min_hangul_chars=10,
        min_hangul_letter_ratio=0.70,
        min_hangul_visible_ratio=0.45,
        max_digit_ratio=0.15,
        max_symbol_ratio=0.20,
        max_url_per_word=0.01,
        min_unique_line_ratio=0.50,
        min_unique_word_ratio=0.10,
        max_short_line_ratio=1.0,
        max_list_line_ratio=0.70,
        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.55,
        strip_html=True,
        mask_pii=True,
    )


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


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 validation_assignment(text: str, permyriad: int) -> bool:
    digest = hashlib.blake2b(text.encode("utf-8"), digest_size=8).digest()
    value = int.from_bytes(digest, "little") % 10_000
    return value < permyriad


class RecordPacker:
    def __init__(
        self,
        *,
        prefix: Path,
        sequence_length: int,
        target_tokens: int,
        pad_token_id: int,
        resume_records: int = 0,
        resume_nonpad_tokens: int = 0,
        resume_supervised_tokens: int = 0,
    ) -> None:
        self.sequence_length = sequence_length
        self.target_records = (target_tokens + sequence_length - 1) // sequence_length
        self.pad_token_id = pad_token_id
        self.input_path = Path(str(prefix) + ".input_ids.bin")
        self.mask_path = Path(str(prefix) + ".loss_mask.bin")
        self.input_path.parent.mkdir(parents=True, exist_ok=True)
        expected_tokens = resume_records * sequence_length
        for path, item_size in ((self.input_path, 2), (self.mask_path, 1)):
            if resume_records and not path.is_file():
                raise FileNotFoundError(path)
            if path.exists():
                with path.open("r+b") as handle:
                    handle.truncate(expected_tokens * item_size)
        self.input_handle = self.input_path.open("ab")
        self.mask_handle = self.mask_path.open("ab")
        self.records = resume_records
        self.nonpad_tokens = resume_nonpad_tokens
        self.supervised_tokens = resume_supervised_tokens
        self.buffer_ids: list[int] = []
        self.buffer_mask: list[int] = []

    @property
    def complete(self) -> bool:
        return self.records >= self.target_records

    @property
    def capacity_tokens(self) -> int:
        return self.records * self.sequence_length

    def add(self, input_ids: list[int], loss_mask: list[int]) -> None:
        if self.complete:
            return
        if len(input_ids) != len(loss_mask) or not input_ids:
            raise ValueError("Invalid SFT example")
        if len(input_ids) > self.sequence_length:
            raise ValueError("SFT example exceeds sequence length")
        if self.buffer_ids and len(self.buffer_ids) + len(input_ids) > self.sequence_length:
            self._write_buffer()
        if self.complete:
            return
        self.buffer_ids.extend(input_ids)
        self.buffer_mask.extend(loss_mask)
        if len(self.buffer_ids) == self.sequence_length:
            self._write_buffer()

    def _write_buffer(self) -> None:
        if not self.buffer_ids or self.complete:
            return
        used = len(self.buffer_ids)
        supervised = sum(self.buffer_mask)
        padding = self.sequence_length - used
        input_array = np.asarray(
            self.buffer_ids + [self.pad_token_id] * padding,
            dtype=np.uint16,
        )
        mask_array = np.asarray(
            self.buffer_mask + [0] * padding,
            dtype=np.uint8,
        )
        input_array.tofile(self.input_handle)
        mask_array.tofile(self.mask_handle)
        self.records += 1
        self.nonpad_tokens += used
        self.supervised_tokens += supervised
        self.buffer_ids.clear()
        self.buffer_mask.clear()

    def finalize_partial(self) -> None:
        if not self.complete:
            self._write_buffer()

    def sync(self) -> None:
        for handle in (self.input_handle, self.mask_handle):
            handle.flush()
            os.fsync(handle.fileno())

    def close(self) -> None:
        self.sync()
        self.input_handle.close()
        self.mask_handle.close()

    def state(self) -> dict[str, int]:
        return {
            "target_records": self.target_records,
            "records": self.records,
            "capacity_tokens": self.capacity_tokens,
            "nonpad_tokens": self.nonpad_tokens,
            "supervised_tokens": self.supervised_tokens,
        }


def normalize_blocks(blocks: list[tuple[str, str]]) -> list[tuple[str, str]]:
    normalized: list[tuple[str, str]] = []
    for role, content in blocks:
        cleaned = normalize_text(content, strip_html=True, mask_pii=True)
        if cleaned:
            normalized.append((role, cleaned))
    return normalized


def main() -> None:
    configure_utf8_stdio()
    args = parse_args()
    for name in (
        "train_tokens",
        "validation_tokens",
        "sequence_length",
        "shuffle_buffer",
        "batch_size",
    ):
        if getattr(args, name) <= 0:
            raise ValueError(f"--{name.replace('_', '-')} must be positive")
    if not 0 < args.validation_permyriad < 10_000:
        raise ValueError("--validation-permyriad must be between 1 and 9,999")

    output_dir = Path(args.output_dir)
    state_path = output_dir / "state.json"
    output_dir.mkdir(parents=True, exist_ok=True)
    tokenizer = AutoTokenizer.from_pretrained(
        args.tokenizer_dir, use_fast=False, legacy=True
    )
    tokenizer.model_max_length = args.sequence_length
    if len(tokenizer) > np.iinfo(np.uint16).max:
        raise ValueError("uint16 requires vocabulary <= 65,535")
    if tokenizer.pad_token_id is None:
        raise ValueError("Tokenizer must define pad_token_id")

    expected = {
        "dataset": args.dataset,
        "data_files": list(args.data_file),
        "split": args.split,
        "revision": args.revision,
        "tokenizer_vocab_size": len(tokenizer),
        "sequence_length": args.sequence_length,
        "train_tokens_requested": args.train_tokens,
        "validation_tokens_requested": args.validation_tokens,
        "validation_permyriad": args.validation_permyriad,
        "shuffle_buffer": args.shuffle_buffer,
        "seed": args.seed,
        "allowed_licenses": sorted(value.casefold() for value in args.allowed_license),
        "exclude_source_regex": args.exclude_source_regex,
    }
    if args.resume:
        if not state_path.is_file():
            raise FileNotFoundError(state_path)
        state = json.loads(state_path.read_text(encoding="utf-8"))
        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}"
                )
        if state.get("complete"):
            print(json.dumps(state, ensure_ascii=False, indent=2))
            return
        documents_seen = int(state["documents_seen"])
        counters = Counter({key: int(value) for key, value in state["counts"].items()})
        train_state = state["train"]
        validation_state = state["validation"]
    else:
        existing = [
            output_dir / "train.input_ids.bin",
            output_dir / "train.loss_mask.bin",
            output_dir / "validation.input_ids.bin",
            output_dir / "validation.loss_mask.bin",
        ]
        if state_path.exists() or any(path.exists() for path in existing):
            raise FileExistsError(f"{output_dir} contains previous SFT data")
        documents_seen = 0
        counters: Counter[str] = Counter()
        train_state = {}
        validation_state = {}

    train = RecordPacker(
        prefix=output_dir / "train",
        sequence_length=args.sequence_length,
        target_tokens=args.train_tokens,
        pad_token_id=int(tokenizer.pad_token_id),
        resume_records=int(train_state.get("records", 0)),
        resume_nonpad_tokens=int(train_state.get("nonpad_tokens", 0)),
        resume_supervised_tokens=int(train_state.get("supervised_tokens", 0)),
    )
    validation = RecordPacker(
        prefix=output_dir / "validation",
        sequence_length=args.sequence_length,
        target_tokens=args.validation_tokens,
        pad_token_id=int(tokenizer.pad_token_id),
        resume_records=int(validation_state.get("records", 0)),
        resume_nonpad_tokens=int(validation_state.get("nonpad_tokens", 0)),
        resume_supervised_tokens=int(validation_state.get("supervised_tokens", 0)),
    )
    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 = sft_filter_config()

    def state_value(*, complete: bool) -> dict[str, Any]:
        return {
            **expected,
            "tokenizer": str(Path(args.tokenizer_dir).resolve()),
            "documents_seen": documents_seen,
            "counts": dict(sorted(counters.items())),
            "train": train.state(),
            "validation": validation.state(),
            "complete": complete,
        }

    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)

    progress = tqdm(initial=documents_seen, unit="rows")
    batch: list[dict[str, Any]] = []

    def commit_batch() -> bool:
        nonlocal documents_seen
        for row in batch:
            counters["seen"] += 1
            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
            source_name = str(row.get("source_name", ""))
            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
            blocks = normalize_blocks(parse_chatml(raw_text))
            roles = {role for role, _ in blocks}
            if "user" not in roles or "assistant" not in roles:
                counters["rejected_chatml"] += 1
                continue
            rendered = "\n\n".join(
                ROLE_HEADERS[role] + content
                for role, content in blocks
                if role in ROLE_HEADERS
            )
            if contains_code_or_math(rendered):
                counters["rejected_explicit_code_or_math"] += 1
                continue
            reason = rejection_reason(
                rendered,
                filter_config,
                metrics=measure_text(rendered),
            )
            if reason is not None:
                counters[f"rejected_{reason}"] += 1
                continue
            packer = (
                validation
                if validation_assignment(raw_text, args.validation_permyriad)
                else train
            )
            if packer.complete:
                counters["skipped_split_complete"] += 1
                continue
            examples = list(
                build_assistant_examples(
                    blocks,
                    tokenizer,
                    max_length=args.sequence_length,
                )
            )
            if not examples:
                counters["rejected_no_assistant_example"] += 1
                continue
            for input_ids, loss_mask in examples:
                packer.add(input_ids, loss_mask)
                counters["examples"] += 1
                if packer.complete:
                    break
            counters["accepted_conversations"] += 1

        documents_seen += len(batch)
        progress.update(len(batch))
        batch.clear()
        train.sync()
        validation.sync()
        complete = train.complete and validation.complete
        atomic_json(state_path, state_value(complete=complete))
        return complete

    complete = False
    try:
        for row in dataset:
            batch.append(row)
            if len(batch) >= args.batch_size and commit_batch():
                complete = True
                break
        else:
            if batch:
                complete = commit_batch()
            train.finalize_partial()
            validation.finalize_partial()
            complete = train.complete and validation.complete
    finally:
        train.close()
        validation.close()
        progress.close()

    final_state = state_value(complete=complete)
    atomic_json(state_path, final_state)
    print(json.dumps(final_state, ensure_ascii=False, indent=2))
    if not complete:
        raise RuntimeError("Dataset ended before both SFT token targets were reached")
    sys.stdout.flush()
    sys.stderr.flush()


if __name__ == "__main__":
    main()