Download scripts/prepare_sft.py from Infinity08/KAWK50M-Project: direct link, hf CLI and curl.
- Browser
- Download file 15.8 kB
-
https://huggingface.co/datasets/Infinity08/KAWK50M-Project/resolve/main/scripts/prepare_sft.py
- Command line
-
hf download hf://datasets/Infinity08/KAWK50M-Project/scripts/prepare_sft.py
-
curl -L -o prepare_sft.py https://huggingface.co/datasets/Infinity08/KAWK50M-Project/resolve/main/scripts/prepare_sft.py
15.8 kB
| 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] = [] | |
| def complete(self) -> bool: | |
| return self.records >= self.target_records | |
| 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() | |