KAWK50M-Project / scripts /stream_tokenize_chatml.py
Infinity08's picture
Add files using upload-large-folder tool
91ac3cc verified
Raw History Blame Contribute Delete
12.8 kB
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()