Datasets:
Download code/src/barbet_bgd/v2_cli.py from voidful/barbet-sft: direct link, hf CLI and curl.
- Browser
- Download file 67.3 kB
-
https://huggingface.co/datasets/voidful/barbet-sft/resolve/main/code/src/barbet_bgd/v2_cli.py
- Command line
-
hf download hf://datasets/voidful/barbet-sft/code/src/barbet_bgd/v2_cli.py
-
curl -L -o v2_cli.py https://huggingface.co/datasets/voidful/barbet-sft/resolve/main/code/src/barbet_bgd/v2_cli.py
67.3 kB
| """Build and independently promote the deterministic BGD-SFT v2 corpus. | |
| The v2 builder deliberately treats generation and promotion as two different | |
| trust domains. Workers first generate a canonical shard and one quality | |
| verdict sidecar per record. A second set of workers then re-opens both files, | |
| regenerates every record from its global index, re-runs all validators, and | |
| recomputes the corpus-wide :class:`PromotionAccumulator`. | |
| Only a full corpus for which every record is ``KEEP`` and every corpus gate | |
| passes receives ``_PROMOTED.json`` (and the compatibility ``_SUCCESS.json``). | |
| Small ``--limit`` runs can still receive ``_VERIFIED.json`` so the exact same | |
| pipeline can be smoke-tested without weakening production promotion gates. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import gzip | |
| import hashlib | |
| import json | |
| import os | |
| import re | |
| import sys | |
| import tarfile | |
| from collections import Counter | |
| from collections.abc import Mapping, Sequence | |
| from concurrent.futures import ProcessPoolExecutor, as_completed | |
| from dataclasses import dataclass, field | |
| from pathlib import Path | |
| from typing import Any, Iterator | |
| from .generation_v2 import GenerationPlanV2, generate_record_v2 | |
| from .io import ( | |
| ShardResult, | |
| iter_jsonl_gz, | |
| sha256_file, | |
| write_json_atomic, | |
| write_jsonl_gz_atomic, | |
| ) | |
| from .quality_v2 import ( | |
| FAMILY_INPUT_SIGNATURES, | |
| QUALITY_V2_SCHEMA_VERSION, | |
| PromotionAccumulator, | |
| canonical_sha256_v2, | |
| validate_record_quality_v2, | |
| ) | |
| from .serializers_v2 import ( | |
| build_messages_v2, | |
| canonicalize_payload, | |
| parse_request_message_v2, | |
| parse_target_v2, | |
| roundtrip_target_v2, | |
| ) | |
| from .validation import find_disallowed_terms, validate_record | |
| from .taiwan_usage import audit_taiwan_usage | |
| PROJECT_ROOT = Path(__file__).resolve().parents[2] | |
| DEFAULT_CONFIG = PROJECT_ROOT / "configs" / "selected_sft_1m_v2.json" | |
| MANIFEST_VERSION = "bgd.v2.build.manifest.v1" | |
| POSTWRITE_VERSION = "bgd.v2.postwrite.v1" | |
| MARKER_VERSION = "bgd.v2.marker.v1" | |
| SOURCE_BUNDLE_VERSION = "bgd.v2.source-bundle.v1" | |
| PIPELINE_VERSION = "barbet.sft.pipeline.v3" | |
| _RECORD_ID_RE = re.compile(r"^bgd_tw_v2_(\d{7})$") | |
| _MAX_ISSUE_EXAMPLES = 100 | |
| def _canonical_json(value: Any) -> bytes: | |
| return json.dumps( | |
| value, | |
| ensure_ascii=False, | |
| sort_keys=True, | |
| separators=(",", ":"), | |
| allow_nan=False, | |
| ).encode("utf-8") | |
| def _semantic_sha256(value: Any) -> str: | |
| return hashlib.sha256(_canonical_json(value)).hexdigest() | |
| def _load_config(path: str | Path) -> dict[str, Any]: | |
| source = Path(path) | |
| value = json.loads(source.read_text(encoding="utf-8")) | |
| if not isinstance(value, dict): | |
| raise ValueError(f"v2 config must be a JSON object: {source}") | |
| GenerationPlanV2(value) | |
| required = { | |
| "dataset_name", | |
| "schema_version", | |
| "generator_version", | |
| "validator_version", | |
| "total_records", | |
| "shard_size", | |
| "gzip_compresslevel", | |
| } | |
| missing = sorted(required - set(value)) | |
| if missing: | |
| raise ValueError(f"v2 config is missing fields: {', '.join(missing)}") | |
| return value | |
| def _plan_payload(plan: GenerationPlanV2) -> dict[str, Any]: | |
| """Capture every public decision that maps a global index to a plan slot.""" | |
| return { | |
| "plan_class": type(plan).__name__, | |
| "total": int(plan.total), | |
| "primitive_cycle": list(plan.primitive_cycle), | |
| "mixture_cycle": list(plan.mixture_cycle), | |
| "serializer_cycle": list(plan.serializer_cycle), | |
| "long_per_cycle": int(plan.long_per_cycle), | |
| "long_slots": list(plan.long_slots), | |
| "train_end": int(plan.train_end), | |
| "validation_end": int(plan.validation_end), | |
| } | |
| def _source_bundle(project_root: Path, config_path: Path) -> dict[str, Any]: | |
| """Hash executable sources, schemas, packaging metadata, and active config.""" | |
| candidates: list[tuple[str, Path]] = [] | |
| package_root = project_root / "src" / "barbet_bgd" | |
| if package_root.is_dir(): | |
| for path in sorted(package_root.glob("*.py")): | |
| candidates.append((path.relative_to(project_root).as_posix(), path)) | |
| schema_root = project_root / "schema" | |
| if schema_root.is_dir(): | |
| for path in sorted(item for item in schema_root.rglob("*") if item.is_file()): | |
| candidates.append((path.relative_to(project_root).as_posix(), path)) | |
| pyproject = project_root / "pyproject.toml" | |
| if pyproject.is_file(): | |
| candidates.append(("pyproject.toml", pyproject)) | |
| for name in ("README.md", "LICENSE", "LICENSE_DATA.md", "requirements-release.txt"): | |
| path = project_root / name | |
| if path.is_file(): | |
| candidates.append((name, path)) | |
| for path in sorted((project_root / "tests").glob("*.py")): | |
| candidates.append((path.relative_to(project_root).as_posix(), path)) | |
| for pattern in ("configs/*.json", "slurm/*barbet_sft*", "docs/review_v3.md", "docs/taiwan_usage_review.md"): | |
| for path in sorted(project_root.glob(pattern)): | |
| candidates.append((path.relative_to(project_root).as_posix(), path)) | |
| config_path = config_path.resolve() | |
| try: | |
| config_logical = config_path.relative_to(project_root.resolve()).as_posix() | |
| except ValueError: | |
| config_logical = "runtime/selected_sft_1m_v2.json" | |
| candidates.append((config_logical, config_path)) | |
| entries: list[dict[str, Any]] = [] | |
| seen: set[tuple[str, str]] = set() | |
| for logical_path, path in sorted(candidates, key=lambda item: item[0]): | |
| key = (logical_path, str(path.resolve())) | |
| if key in seen: | |
| continue | |
| seen.add(key) | |
| entries.append( | |
| { | |
| "logical_path": logical_path, | |
| "path": str(path.resolve()), | |
| "sha256": sha256_file(path), | |
| "bytes": path.stat().st_size, | |
| } | |
| ) | |
| digest_rows = [ | |
| { | |
| "logical_path": row["logical_path"], | |
| "sha256": row["sha256"], | |
| "bytes": row["bytes"], | |
| } | |
| for row in entries | |
| ] | |
| return { | |
| "version": SOURCE_BUNDLE_VERSION, | |
| "sha256": _semantic_sha256(digest_rows), | |
| "files": entries, | |
| } | |
| def _write_source_snapshot_atomic( | |
| destination: Path, source_bundle: Mapping[str, Any] | |
| ) -> dict[str, Any]: | |
| """Publish a deterministic tar.gz containing every pinned source byte.""" | |
| destination.parent.mkdir(parents=True, exist_ok=True) | |
| incomplete = destination.with_name(f"{destination.name}.incomplete") | |
| entries = source_bundle.get("files") | |
| if not isinstance(entries, list) or not entries: | |
| raise ValueError("source bundle has no files to snapshot") | |
| try: | |
| with incomplete.open("wb") as raw: | |
| with gzip.GzipFile(filename="", mode="wb", fileobj=raw, mtime=0) as compressed: | |
| with tarfile.open(fileobj=compressed, mode="w|") as archive: | |
| for entry in entries: | |
| if not isinstance(entry, Mapping): | |
| raise ValueError("source bundle entry is not an object") | |
| logical_path = str(entry.get("logical_path", "")) | |
| if ( | |
| not logical_path | |
| or logical_path.startswith("/") | |
| or ".." in Path(logical_path).parts | |
| ): | |
| raise ValueError(f"unsafe snapshot path: {logical_path!r}") | |
| source = Path(str(entry.get("path", ""))) | |
| if sha256_file(source) != entry.get("sha256"): | |
| raise RuntimeError(f"source changed before snapshot: {source}") | |
| info = tarfile.TarInfo(logical_path) | |
| info.size = source.stat().st_size | |
| info.mode = 0o644 | |
| info.mtime = 0 | |
| info.uid = 0 | |
| info.gid = 0 | |
| info.uname = "" | |
| info.gname = "" | |
| with source.open("rb") as handle: | |
| archive.addfile(info, handle) | |
| raw.flush() | |
| os.fsync(raw.fileno()) | |
| os.replace(incomplete, destination) | |
| except BaseException: | |
| incomplete.unlink(missing_ok=True) | |
| raise | |
| return { | |
| "path": str(destination.resolve()), | |
| "sha256": sha256_file(destination), | |
| "bytes": destination.stat().st_size, | |
| "files": len(entries), | |
| "format": "deterministic-tar-gzip-v1", | |
| } | |
| def _source_snapshot_contents_match( | |
| snapshot: Mapping[str, Any], source_bundle: Mapping[str, Any] | |
| ) -> bool: | |
| """Verify the archive hash and every archived file against the pin set.""" | |
| path = Path(str(snapshot.get("path", ""))) | |
| if not path.is_file() or sha256_file(path) != snapshot.get("sha256"): | |
| return False | |
| expected_rows = source_bundle.get("files") | |
| if not isinstance(expected_rows, list): | |
| return False | |
| expected = { | |
| str(row.get("logical_path")): str(row.get("sha256")) | |
| for row in expected_rows | |
| if isinstance(row, Mapping) | |
| } | |
| observed: dict[str, str] = {} | |
| try: | |
| with tarfile.open(path, mode="r:gz") as archive: | |
| for member in archive.getmembers(): | |
| if not member.isfile() or member.name in observed: | |
| return False | |
| handle = archive.extractfile(member) | |
| if handle is None: | |
| return False | |
| digest = hashlib.sha256() | |
| for block in iter(lambda: handle.read(1024 * 1024), b""): | |
| digest.update(block) | |
| observed[member.name] = digest.hexdigest() | |
| except (OSError, tarfile.TarError, EOFError): | |
| return False | |
| return observed == expected | |
| def _serializer_errors(record: Mapping[str, Any]) -> list[str]: | |
| """Exercise the complete model-visible request and target round trip.""" | |
| errors: list[str] = [] | |
| try: | |
| presentation = record.get("presentation") | |
| if not isinstance(presentation, Mapping): | |
| return ["PRESENTATION_MISSING"] | |
| serializer = presentation.get("serializer") | |
| target = record.get("target") | |
| if not isinstance(serializer, str) or not isinstance(target, dict): | |
| return ["SERIALIZER_OR_TARGET_INVALID"] | |
| if not roundtrip_target_v2(target, serializer): | |
| errors.append("TARGET_ROUNDTRIP_MISMATCH") | |
| messages = build_messages_v2(dict(record)) | |
| if [message.get("role") for message in messages] != ["system", "user", "assistant"]: | |
| errors.append("MESSAGE_ROLE_SEQUENCE_INVALID") | |
| return errors | |
| request = parse_request_message_v2(messages[1]["content"]) | |
| expected_request = canonicalize_payload( | |
| { | |
| "schema": "barbet.bgd.request/v2", | |
| "record_id": record.get("record_id"), | |
| "primitive": record.get("primitive"), | |
| "task_family": record.get("task_family"), | |
| "task_spec": record.get("task_spec"), | |
| "inputs": record.get("inputs"), | |
| } | |
| ) | |
| if request != expected_request: | |
| errors.append("REQUEST_ROUNDTRIP_MISMATCH") | |
| parsed_target = parse_target_v2(messages[2]["content"], serializer) | |
| if canonical_sha256_v2(parsed_target) != canonical_sha256_v2(target): | |
| errors.append("ASSISTANT_TARGET_ROUNDTRIP_MISMATCH") | |
| except Exception as exc: | |
| errors.append(f"SERIALIZER_EXCEPTION:{type(exc).__name__}:{str(exc)[:240]}") | |
| return sorted(set(errors)) | |
| def _quality_exception_verdict(record: Mapping[str, Any], exc: Exception) -> dict[str, Any]: | |
| return { | |
| "record_id": record.get("record_id"), | |
| "quality_schema_version": QUALITY_V2_SCHEMA_VERSION, | |
| "primitive": record.get("primitive"), | |
| "task_family": record.get("task_family"), | |
| "split": record.get("split"), | |
| "record_sha256": canonical_sha256_v2(record), | |
| "checks": {"quality_validator_execution": False}, | |
| "failures_by_check": { | |
| "quality_validator_execution": ["QUALITY_V2_VALIDATOR_EXCEPTION"] | |
| }, | |
| "hard_failures": ["QUALITY_V2_VALIDATOR_EXCEPTION"], | |
| "training_ready": False, | |
| "disposition": "REJECT", | |
| "metrics": {}, | |
| "validator_exception": { | |
| "type": type(exc).__name__, | |
| "message": str(exc)[:500], | |
| }, | |
| } | |
| def _build_verdict( | |
| record: Mapping[str, Any], | |
| *, | |
| expected_index: int, | |
| source_shard: str, | |
| source_line: int, | |
| ) -> dict[str, Any]: | |
| """Combine independent quality, legacy structure, and serializer gates.""" | |
| structural_errors = list(validate_record(record)) | |
| serializer_errors = _serializer_errors(record) | |
| taiwan_audit = audit_taiwan_usage(record) | |
| try: | |
| verdict = dict(validate_record_quality_v2(record)) | |
| except Exception as exc: | |
| verdict = _quality_exception_verdict(record, exc) | |
| v2_keep = verdict.get("disposition") == "KEEP" and verdict.get("training_ready") is True | |
| pipeline_checks = { | |
| "existing_structural_validator": not structural_errors, | |
| "v2_quality_validator": v2_keep, | |
| "serializer_request_target_roundtrip": not serializer_errors, | |
| "taiwan_usage": taiwan_audit["passed"], | |
| } | |
| pipeline_failures: list[str] = [] | |
| if structural_errors: | |
| pipeline_failures.append("EXISTING_STRUCTURAL_VALIDATOR_FAILED") | |
| if not v2_keep: | |
| pipeline_failures.append("V2_QUALITY_VALIDATOR_REJECTED") | |
| if serializer_errors: | |
| pipeline_failures.append("SERIALIZER_ROUNDTRIP_FAILED") | |
| if not taiwan_audit["passed"]: | |
| pipeline_failures.append("TAIWAN_USAGE_FAILED") | |
| hard_failures = verdict.get("hard_failures") | |
| if not isinstance(hard_failures, list): | |
| hard_failures = ["V2_HARD_FAILURES_SHAPE_INVALID"] | |
| verdict["hard_failures"] = sorted( | |
| {str(value) for value in hard_failures} | set(pipeline_failures) | |
| ) | |
| verdict.update( | |
| { | |
| "record_id": record.get("record_id"), | |
| "record_index": expected_index, | |
| "expected_record_id": f"bgd_tw_v2_{expected_index:07d}", | |
| "source_shard": source_shard, | |
| "source_line": source_line, | |
| "record_sha256": canonical_sha256_v2(record), | |
| "pipeline_version": PIPELINE_VERSION, | |
| "pipeline_checks": pipeline_checks, | |
| "pipeline_failures": pipeline_failures, | |
| "structural_validation_errors": structural_errors, | |
| "serializer_roundtrip_errors": serializer_errors, | |
| "taiwan_usage": taiwan_audit, | |
| "training_ready": not pipeline_failures and not verdict["hard_failures"], | |
| } | |
| ) | |
| verdict["disposition"] = "KEEP" if verdict["training_ready"] else "REJECT" | |
| return verdict | |
| def _sorted_counter(counter: Counter[str]) -> dict[str, int]: | |
| return {key: counter[key] for key in sorted(counter)} | |
| def _expected_percent_counts(percent: Mapping[str, Any], total: int) -> dict[str, int]: | |
| counts = {str(key): total * int(value) // 100 for key, value in percent.items()} | |
| if sum(counts.values()) != total: | |
| raise ValueError("percentage distribution does not resolve to the exact corpus size") | |
| return dict(sorted(counts.items())) | |
| def _expected_context_bucket_counts(config: Mapping[str, Any]) -> dict[str, int]: | |
| total = int(config["total_records"]) | |
| long_total = int(config["long_context_records"]) | |
| long_counts = _expected_percent_counts(config["long_context_bucket_percent"], long_total) | |
| # Non-ledger samples are deliberately short and must not be mislabeled as | |
| # 0.5K-4K. Long-context percentages apply only to long_context_records. | |
| long_counts["SHORT_LT_0.5K"] = long_counts.get("SHORT_LT_0.5K", 0) + total - long_total | |
| return dict(sorted(long_counts.items())) | |
| def _visible_natural_language_texts(record: Mapping[str, Any]) -> Iterator[str]: | |
| """Yield human-language request text without counting IDs/schema keywords.""" | |
| task_spec = record.get("task_spec") | |
| if isinstance(task_spec, Mapping): | |
| for key in ("instruction", "query"): | |
| value = task_spec.get(key) | |
| if isinstance(value, str): | |
| yield value | |
| inputs = record.get("inputs") | |
| if isinstance(inputs, list): | |
| for item in inputs: | |
| if not isinstance(item, Mapping): | |
| continue | |
| units = item.get("units") | |
| if not isinstance(units, list): | |
| continue | |
| for unit in units: | |
| if isinstance(unit, Mapping) and isinstance(unit.get("text"), str): | |
| yield str(unit["text"]) | |
| class CorpusStatsV2: | |
| total_records: int = 0 | |
| keep_records: int = 0 | |
| reject_records: int = 0 | |
| structural_passed: int = 0 | |
| v2_quality_passed: int = 0 | |
| serializer_passed: int = 0 | |
| primary_zh_tw_records: int = 0 | |
| en_metadata_records: int = 0 | |
| natural_language_characters: int = 0 | |
| han_characters: int = 0 | |
| latin_alphabetic_characters: int = 0 | |
| disallowed_simplified_or_prc_hit_records: int = 0 | |
| primitive: Counter[str] = field(default_factory=Counter) | |
| task_family: Counter[str] = field(default_factory=Counter) | |
| mixture_category: Counter[str] = field(default_factory=Counter) | |
| split: Counter[str] = field(default_factory=Counter) | |
| serializer: Counter[str] = field(default_factory=Counter) | |
| context_bucket: Counter[str] = field(default_factory=Counter) | |
| disposition: Counter[str] = field(default_factory=Counter) | |
| hard_failures: Counter[str] = field(default_factory=Counter) | |
| structural_failures: Counter[str] = field(default_factory=Counter) | |
| v2_quality_failures: Counter[str] = field(default_factory=Counter) | |
| serializer_failures: Counter[str] = field(default_factory=Counter) | |
| source_group_splits: dict[str, str] = field(default_factory=dict) | |
| source_group_split_conflicts: int = 0 | |
| def ingest(self, record: Mapping[str, Any], verdict: Mapping[str, Any]) -> None: | |
| self.total_records += 1 | |
| disposition = str(verdict.get("disposition", "<MISSING>")) | |
| self.disposition[disposition] += 1 | |
| self.keep_records += disposition == "KEEP" | |
| self.reject_records += disposition != "KEEP" | |
| checks = verdict.get("pipeline_checks") | |
| if not isinstance(checks, Mapping): | |
| checks = {} | |
| self.structural_passed += bool(checks.get("existing_structural_validator")) | |
| self.v2_quality_passed += bool(checks.get("v2_quality_validator")) | |
| self.serializer_passed += bool(checks.get("serializer_request_target_roundtrip")) | |
| language = record.get("language") | |
| self.primary_zh_tw_records += bool( | |
| isinstance(language, Sequence) | |
| and not isinstance(language, (str, bytes, bytearray)) | |
| and language | |
| and language[0] == "zh-TW" | |
| and record.get("locale") == "zh-TW" | |
| ) | |
| self.en_metadata_records += bool( | |
| isinstance(language, Sequence) | |
| and not isinstance(language, (str, bytes, bytearray)) | |
| and "en" in language | |
| ) | |
| visible_texts = list(_visible_natural_language_texts(record)) | |
| visible = "".join(visible_texts) | |
| self.natural_language_characters += len(visible) | |
| self.han_characters += sum("\u4e00" <= character <= "\u9fff" for character in visible) | |
| self.latin_alphabetic_characters += sum( | |
| ("A" <= character <= "Z") or ("a" <= character <= "z") | |
| for character in visible | |
| ) | |
| self.disallowed_simplified_or_prc_hit_records += bool( | |
| any(find_disallowed_terms(text) for text in visible_texts) | |
| ) | |
| self.primitive[str(record.get("primitive", "<MISSING>"))] += 1 | |
| self.task_family[str(record.get("task_family", "<MISSING>"))] += 1 | |
| self.mixture_category[str(record.get("mixture_category", "<MISSING>"))] += 1 | |
| self.split[str(record.get("split", "<MISSING>"))] += 1 | |
| presentation = record.get("presentation") | |
| serializer = presentation.get("serializer") if isinstance(presentation, Mapping) else None | |
| self.serializer[str(serializer or "<MISSING>")] += 1 | |
| quality = record.get("quality") | |
| context_bucket = ( | |
| quality.get("context_length_bucket") if isinstance(quality, Mapping) else None | |
| ) | |
| if context_bucket is None and isinstance(presentation, Mapping): | |
| context_bucket = presentation.get("context_bucket") | |
| self.context_bucket[str(context_bucket or "<MISSING>")] += 1 | |
| source_group = record.get("source_group") | |
| split = record.get("split") | |
| if isinstance(source_group, str) and source_group and isinstance(split, str): | |
| previous = self.source_group_splits.setdefault(source_group, split) | |
| if previous != split: | |
| self.source_group_split_conflicts += 1 | |
| else: | |
| self.source_group_split_conflicts += 1 | |
| failures = verdict.get("hard_failures") | |
| if isinstance(failures, Sequence) and not isinstance( | |
| failures, (str, bytes, bytearray) | |
| ): | |
| self.hard_failures.update(str(value) for value in failures) | |
| structural = verdict.get("structural_validation_errors") | |
| if isinstance(structural, Sequence) and not isinstance( | |
| structural, (str, bytes, bytearray) | |
| ): | |
| self.structural_failures.update(str(value) for value in structural) | |
| serializer_errors = verdict.get("serializer_roundtrip_errors") | |
| if isinstance(serializer_errors, Sequence) and not isinstance( | |
| serializer_errors, (str, bytes, bytearray) | |
| ): | |
| self.serializer_failures.update(str(value) for value in serializer_errors) | |
| failures_by_check = verdict.get("failures_by_check") | |
| if isinstance(failures_by_check, Mapping): | |
| for values in failures_by_check.values(): | |
| if isinstance(values, Sequence) and not isinstance( | |
| values, (str, bytes, bytearray) | |
| ): | |
| self.v2_quality_failures.update(str(value) for value in values) | |
| def merge(self, other: "CorpusStatsV2") -> None: | |
| self.total_records += other.total_records | |
| self.keep_records += other.keep_records | |
| self.reject_records += other.reject_records | |
| self.structural_passed += other.structural_passed | |
| self.v2_quality_passed += other.v2_quality_passed | |
| self.serializer_passed += other.serializer_passed | |
| self.primary_zh_tw_records += other.primary_zh_tw_records | |
| self.en_metadata_records += other.en_metadata_records | |
| self.natural_language_characters += other.natural_language_characters | |
| self.han_characters += other.han_characters | |
| self.latin_alphabetic_characters += other.latin_alphabetic_characters | |
| self.disallowed_simplified_or_prc_hit_records += ( | |
| other.disallowed_simplified_or_prc_hit_records | |
| ) | |
| self.source_group_split_conflicts += other.source_group_split_conflicts | |
| for name in ( | |
| "primitive", | |
| "task_family", | |
| "mixture_category", | |
| "split", | |
| "serializer", | |
| "context_bucket", | |
| "disposition", | |
| "hard_failures", | |
| "structural_failures", | |
| "v2_quality_failures", | |
| "serializer_failures", | |
| ): | |
| getattr(self, name).update(getattr(other, name)) | |
| for source_group, split in other.source_group_splits.items(): | |
| previous = self.source_group_splits.setdefault(source_group, split) | |
| if previous != split: | |
| self.source_group_split_conflicts += 1 | |
| def to_dict(self) -> dict[str, Any]: | |
| total = self.total_records | |
| alphabetic = self.han_characters + self.latin_alphabetic_characters | |
| return { | |
| "total_records": total, | |
| "keep_records": self.keep_records, | |
| "reject_records": self.reject_records, | |
| "structural_passed_records": self.structural_passed, | |
| "v2_quality_passed_records": self.v2_quality_passed, | |
| "serializer_roundtrip_passed_records": self.serializer_passed, | |
| "primary_zh_tw_records": self.primary_zh_tw_records, | |
| "primary_zh_tw_ratio": self.primary_zh_tw_records / total if total else 0.0, | |
| "records_with_en_language_metadata": self.en_metadata_records, | |
| "model_visible_natural_language_character_scope": ( | |
| "task_spec.instruction + task_spec.query + inputs[*].units[*].text" | |
| ), | |
| "model_visible_natural_language_characters": self.natural_language_characters, | |
| "model_visible_han_characters": self.han_characters, | |
| "model_visible_latin_alphabetic_characters": self.latin_alphabetic_characters, | |
| "model_visible_han_to_han_plus_latin_ratio": ( | |
| self.han_characters / alphabetic if alphabetic else 0.0 | |
| ), | |
| "disallowed_simplified_or_prc_hit_records": ( | |
| self.disallowed_simplified_or_prc_hit_records | |
| ), | |
| "primitive": _sorted_counter(self.primitive), | |
| "task_family": _sorted_counter(self.task_family), | |
| "mixture_category": _sorted_counter(self.mixture_category), | |
| "split": _sorted_counter(self.split), | |
| "serializer": _sorted_counter(self.serializer), | |
| "context_bucket": _sorted_counter(self.context_bucket), | |
| "disposition": _sorted_counter(self.disposition), | |
| "hard_failures": _sorted_counter(self.hard_failures), | |
| "structural_failure_counts": _sorted_counter(self.structural_failures), | |
| "v2_quality_failure_counts": _sorted_counter(self.v2_quality_failures), | |
| "serializer_failure_counts": _sorted_counter(self.serializer_failures), | |
| "source_group_split_conflicts": self.source_group_split_conflicts, | |
| "unique_source_groups": len(self.source_group_splits), | |
| } | |
| class BuildShardTask: | |
| shard_index: int | |
| start_index: int | |
| end_index: int | |
| canonical_path: str | |
| verdict_path: str | |
| config: dict[str, Any] | |
| compresslevel: int | |
| minimum_family_records: int | |
| minimum_template_variants: int | |
| project_root: str | |
| config_path: str | |
| source_bundle_sha256: str | |
| class BuildShardResult: | |
| shard_index: int | |
| start_index: int | |
| end_index: int | |
| canonical: ShardResult | |
| verdict: ShardResult | |
| stats: CorpusStatsV2 | |
| promotion: PromotionAccumulator | |
| def _build_shard(task: BuildShardTask) -> BuildShardResult: | |
| if ( | |
| _source_bundle(Path(task.project_root), Path(task.config_path))["sha256"] | |
| != task.source_bundle_sha256 | |
| ): | |
| raise RuntimeError("pinned source bundle changed before shard generation") | |
| plan = GenerationPlanV2(task.config) | |
| expected_records = task.end_index - task.start_index | |
| stats = CorpusStatsV2() | |
| promotion = PromotionAccumulator( | |
| minimum_family_records=task.minimum_family_records, | |
| minimum_template_variants=task.minimum_template_variants, | |
| expected_total_records=int(task.config["total_records"]), | |
| ) | |
| verdict_rows: list[dict[str, Any]] = [] | |
| canonical_name = Path(task.canonical_path).name | |
| def records() -> Iterator[dict[str, Any]]: | |
| for line, index in enumerate(range(task.start_index, task.end_index), 1): | |
| record = generate_record_v2(task.config, plan, index) | |
| verdict = _build_verdict( | |
| record, | |
| expected_index=index, | |
| source_shard=canonical_name, | |
| source_line=line, | |
| ) | |
| # Fail closed before the canonical iterator yields the record. The | |
| # atomic writer then removes its .incomplete file, so a rejected | |
| # example can never appear in a published training shard. | |
| if verdict.get("disposition") != "KEEP" or verdict.get("training_ready") is not True: | |
| summary = { | |
| "record_id": record.get("record_id"), | |
| "record_index": index, | |
| "structural_validation_errors": verdict.get( | |
| "structural_validation_errors", [] | |
| ), | |
| "v2_hard_failures": verdict.get("hard_failures", []), | |
| "serializer_roundtrip_errors": verdict.get( | |
| "serializer_roundtrip_errors", [] | |
| ), | |
| } | |
| raise RuntimeError( | |
| "v2 record failed closed quality gates: " | |
| + json.dumps(summary, ensure_ascii=False, sort_keys=True) | |
| ) | |
| stats.ingest(record, verdict) | |
| promotion.add(record, verdict) | |
| verdict_rows.append(verdict) | |
| yield record | |
| canonical = write_jsonl_gz_atomic( | |
| task.canonical_path, | |
| records(), | |
| compresslevel=task.compresslevel, | |
| ) | |
| if canonical.records != expected_records: | |
| raise RuntimeError( | |
| f"short canonical shard {canonical.path}: {canonical.records} != {expected_records}" | |
| ) | |
| verdict = write_jsonl_gz_atomic( | |
| task.verdict_path, | |
| verdict_rows, | |
| compresslevel=task.compresslevel, | |
| ) | |
| if verdict.records != expected_records: | |
| raise RuntimeError( | |
| f"short verdict shard {verdict.path}: {verdict.records} != {expected_records}" | |
| ) | |
| if ( | |
| _source_bundle(Path(task.project_root), Path(task.config_path))["sha256"] | |
| != task.source_bundle_sha256 | |
| ): | |
| raise RuntimeError("pinned source bundle changed during shard generation") | |
| return BuildShardResult( | |
| shard_index=task.shard_index, | |
| start_index=task.start_index, | |
| end_index=task.end_index, | |
| canonical=canonical, | |
| verdict=verdict, | |
| stats=stats, | |
| promotion=promotion, | |
| ) | |
| def _merge_promotion( | |
| target: PromotionAccumulator, source: PromotionAccumulator | |
| ) -> PromotionAccumulator: | |
| """Use the public merge API, with a compatibility fallback for old checkouts.""" | |
| merge = getattr(target, "merge", None) | |
| if callable(merge): | |
| merge(source) | |
| return target | |
| if ( | |
| target.minimum_family_records != source.minimum_family_records | |
| or target.minimum_template_variants != source.minimum_template_variants | |
| or getattr(target, "expected_total_records", None) | |
| != getattr(source, "expected_total_records", None) | |
| ): | |
| raise ValueError("cannot merge PromotionAccumulator instances with different thresholds") | |
| for name in ("total", "keep", "reject"): | |
| setattr(target, name, getattr(target, name) + getattr(source, name)) | |
| for name in ("family_counts", "failure_counts"): | |
| getattr(target, name).update(getattr(source, name)) | |
| for name in ( | |
| "family_template_ids", | |
| "family_normalized_templates", | |
| "family_decisions", | |
| "family_confidence_bins", | |
| "family_confidence_values", | |
| "winner_positions", | |
| "alignment_permutations", | |
| "ledger_active_position_bins", | |
| ): | |
| destination = getattr(target, name) | |
| for key, values in getattr(source, name).items(): | |
| destination[key].update(values) | |
| return target | |
| def _run_build_tasks(tasks: list[BuildShardTask], workers: int) -> list[BuildShardResult]: | |
| worker_count = max(1, min(int(workers), len(tasks))) | |
| results: list[BuildShardResult] = [] | |
| if worker_count == 1: | |
| for ordinal, task in enumerate(tasks, 1): | |
| result = _build_shard(task) | |
| results.append(result) | |
| print( | |
| f"v2 generate {ordinal}/{len(tasks)} {result.canonical.path.name} " | |
| f"records={result.canonical.records}", | |
| flush=True, | |
| ) | |
| return results | |
| with ProcessPoolExecutor(max_workers=worker_count) as executor: | |
| futures = {executor.submit(_build_shard, task): task for task in tasks} | |
| completed = 0 | |
| for future in as_completed(futures): | |
| task = futures[future] | |
| result = future.result() | |
| results.append(result) | |
| completed += 1 | |
| print( | |
| f"v2 generate {completed}/{len(tasks)} part-{task.shard_index:05d} " | |
| f"records={result.canonical.records}", | |
| flush=True, | |
| ) | |
| return results | |
| class VerifyShardTask: | |
| shard_index: int | |
| start_index: int | |
| end_index: int | |
| canonical_path: str | |
| canonical_sha256: str | |
| verdict_path: str | |
| verdict_sha256: str | |
| config: dict[str, Any] | |
| minimum_family_records: int | |
| minimum_template_variants: int | |
| project_root: str | |
| config_path: str | |
| source_bundle_sha256: str | |
| class VerifyShardResult: | |
| shard_index: int | |
| records: int | |
| stats: CorpusStatsV2 | |
| promotion: PromotionAccumulator | |
| checks: Counter[str] | |
| issue_counts: Counter[str] | |
| issue_examples: list[dict[str, Any]] | |
| def _issue( | |
| counts: Counter[str], | |
| examples: list[dict[str, Any]], | |
| code: str, | |
| *, | |
| record_id: Any = None, | |
| detail: str | None = None, | |
| ) -> None: | |
| counts[code] += 1 | |
| if len(examples) < 10: | |
| row: dict[str, Any] = {"code": code, "record_id": record_id} | |
| if detail: | |
| row["detail"] = detail[:500] | |
| examples.append(row) | |
| def _verify_shard(task: VerifyShardTask) -> VerifyShardResult: | |
| checks: Counter[str] = Counter() | |
| issue_counts: Counter[str] = Counter() | |
| examples: list[dict[str, Any]] = [] | |
| if ( | |
| _source_bundle(Path(task.project_root), Path(task.config_path))["sha256"] | |
| != task.source_bundle_sha256 | |
| ): | |
| _issue(issue_counts, examples, "SOURCE_BUNDLE_CHANGED_BEFORE_VERIFICATION") | |
| expected_records = task.end_index - task.start_index | |
| canonical_path = Path(task.canonical_path) | |
| verdict_path = Path(task.verdict_path) | |
| if sha256_file(canonical_path) != task.canonical_sha256: | |
| _issue(issue_counts, examples, "CANONICAL_SHARD_SHA256_MISMATCH") | |
| else: | |
| checks["canonical_shard_sha256"] += 1 | |
| if sha256_file(verdict_path) != task.verdict_sha256: | |
| _issue(issue_counts, examples, "VERDICT_SHARD_SHA256_MISMATCH") | |
| else: | |
| checks["verdict_shard_sha256"] += 1 | |
| plan = GenerationPlanV2(task.config) | |
| stats = CorpusStatsV2() | |
| promotion = PromotionAccumulator( | |
| minimum_family_records=task.minimum_family_records, | |
| minimum_template_variants=task.minimum_template_variants, | |
| expected_total_records=int(task.config["total_records"]), | |
| ) | |
| canonical_iter = iter_jsonl_gz(canonical_path) | |
| verdict_iter = iter_jsonl_gz(verdict_path) | |
| processed = 0 | |
| canonical_name = canonical_path.name | |
| for line, index in enumerate(range(task.start_index, task.end_index), 1): | |
| try: | |
| record = next(canonical_iter) | |
| except StopIteration: | |
| _issue(issue_counts, examples, "CANONICAL_SHARD_SHORT", detail=f"line={line}") | |
| break | |
| try: | |
| verdict = next(verdict_iter) | |
| except StopIteration: | |
| _issue(issue_counts, examples, "VERDICT_SHARD_SHORT", detail=f"line={line}") | |
| break | |
| processed += 1 | |
| record_id = record.get("record_id") | |
| reproduced = generate_record_v2(task.config, plan, index) | |
| actual_hash = canonical_sha256_v2(record) | |
| reproduced_hash = canonical_sha256_v2(reproduced) | |
| if record != reproduced or actual_hash != reproduced_hash: | |
| _issue(issue_counts, examples, "EXACT_REGENERATION_MISMATCH", record_id=record_id) | |
| else: | |
| checks["exact_regeneration"] += 1 | |
| expected_id = reproduced.get("record_id") | |
| id_match = record_id == expected_id == verdict.get("record_id") | |
| match = _RECORD_ID_RE.fullmatch(str(record_id or "")) | |
| index_match = ( | |
| verdict.get("record_index") == index | |
| and verdict.get("expected_record_id") == f"bgd_tw_v2_{index:07d}" | |
| and match is not None | |
| and int(match.group(1)) == index | |
| ) | |
| if not id_match: | |
| _issue(issue_counts, examples, "RECORD_ID_ALIGNMENT_FAILED", record_id=record_id) | |
| else: | |
| checks["record_id_alignment"] += 1 | |
| if not index_match: | |
| _issue(issue_counts, examples, "RECORD_INDEX_ALIGNMENT_FAILED", record_id=record_id) | |
| else: | |
| checks["record_index_alignment"] += 1 | |
| if verdict.get("source_shard") != canonical_name or verdict.get("source_line") != line: | |
| _issue(issue_counts, examples, "SIDECAR_SOURCE_POINTER_FAILED", record_id=record_id) | |
| else: | |
| checks["sidecar_source_pointer"] += 1 | |
| if verdict.get("record_sha256") != actual_hash: | |
| _issue(issue_counts, examples, "SIDECAR_RECORD_HASH_FAILED", record_id=record_id) | |
| else: | |
| checks["sidecar_record_hash"] += 1 | |
| fresh_verdict = _build_verdict( | |
| record, | |
| expected_index=index, | |
| source_shard=canonical_name, | |
| source_line=line, | |
| ) | |
| if verdict != fresh_verdict or canonical_sha256_v2(verdict) != canonical_sha256_v2( | |
| fresh_verdict | |
| ): | |
| _issue(issue_counts, examples, "VERDICT_RECOMPUTATION_MISMATCH", record_id=record_id) | |
| else: | |
| checks["verdict_recomputation"] += 1 | |
| if verdict.get("disposition") != "KEEP" or verdict.get("training_ready") is not True: | |
| _issue(issue_counts, examples, "VERDICT_NOT_KEEP", record_id=record_id) | |
| else: | |
| checks["verdict_keep"] += 1 | |
| stats.ingest(record, verdict) | |
| promotion.add(record, verdict) | |
| try: | |
| extra = next(canonical_iter) | |
| except StopIteration: | |
| extra = None | |
| if extra is not None: | |
| _issue( | |
| issue_counts, | |
| examples, | |
| "CANONICAL_SHARD_LONG", | |
| record_id=extra.get("record_id"), | |
| ) | |
| try: | |
| extra = next(verdict_iter) | |
| except StopIteration: | |
| extra = None | |
| if extra is not None: | |
| _issue( | |
| issue_counts, | |
| examples, | |
| "VERDICT_SHARD_LONG", | |
| record_id=extra.get("record_id"), | |
| ) | |
| if processed != expected_records: | |
| _issue( | |
| issue_counts, | |
| examples, | |
| "PAIRED_RECORD_COUNT_MISMATCH", | |
| detail=f"processed={processed},expected={expected_records}", | |
| ) | |
| else: | |
| checks["paired_record_count"] += processed | |
| if ( | |
| _source_bundle(Path(task.project_root), Path(task.config_path))["sha256"] | |
| != task.source_bundle_sha256 | |
| ): | |
| _issue(issue_counts, examples, "SOURCE_BUNDLE_CHANGED_DURING_VERIFICATION") | |
| return VerifyShardResult( | |
| shard_index=task.shard_index, | |
| records=processed, | |
| stats=stats, | |
| promotion=promotion, | |
| checks=checks, | |
| issue_counts=issue_counts, | |
| issue_examples=examples, | |
| ) | |
| def _run_verify_tasks(tasks: list[VerifyShardTask], workers: int) -> list[VerifyShardResult]: | |
| worker_count = max(1, min(int(workers), len(tasks))) | |
| results: list[VerifyShardResult] = [] | |
| if worker_count == 1: | |
| for ordinal, task in enumerate(tasks, 1): | |
| result = _verify_shard(task) | |
| results.append(result) | |
| print( | |
| f"v2 verify {ordinal}/{len(tasks)} part-{task.shard_index:05d} " | |
| f"records={result.records}", | |
| flush=True, | |
| ) | |
| return results | |
| with ProcessPoolExecutor(max_workers=worker_count) as executor: | |
| futures = {executor.submit(_verify_shard, task): task for task in tasks} | |
| completed = 0 | |
| for future in as_completed(futures): | |
| task = futures[future] | |
| result = future.result() | |
| results.append(result) | |
| completed += 1 | |
| print( | |
| f"v2 verify {completed}/{len(tasks)} part-{task.shard_index:05d} " | |
| f"records={result.records}", | |
| flush=True, | |
| ) | |
| return results | |
| def _merge_build_results( | |
| results: Sequence[BuildShardResult], | |
| *, | |
| minimum_family_records: int, | |
| minimum_template_variants: int, | |
| expected_total_records: int, | |
| ) -> tuple[CorpusStatsV2, PromotionAccumulator]: | |
| stats = CorpusStatsV2() | |
| promotion = PromotionAccumulator( | |
| minimum_family_records=minimum_family_records, | |
| minimum_template_variants=minimum_template_variants, | |
| expected_total_records=expected_total_records, | |
| ) | |
| for result in sorted(results, key=lambda item: item.shard_index): | |
| stats.merge(result.stats) | |
| _merge_promotion(promotion, result.promotion) | |
| return stats, promotion | |
| def _merge_verify_results( | |
| results: Sequence[VerifyShardResult], | |
| *, | |
| minimum_family_records: int, | |
| minimum_template_variants: int, | |
| expected_total_records: int, | |
| ) -> tuple[ | |
| CorpusStatsV2, | |
| PromotionAccumulator, | |
| Counter[str], | |
| Counter[str], | |
| list[dict[str, Any]], | |
| ]: | |
| stats = CorpusStatsV2() | |
| promotion = PromotionAccumulator( | |
| minimum_family_records=minimum_family_records, | |
| minimum_template_variants=minimum_template_variants, | |
| expected_total_records=expected_total_records, | |
| ) | |
| checks: Counter[str] = Counter() | |
| issues: Counter[str] = Counter() | |
| examples: list[dict[str, Any]] = [] | |
| for result in sorted(results, key=lambda item: item.shard_index): | |
| stats.merge(result.stats) | |
| _merge_promotion(promotion, result.promotion) | |
| checks.update(result.checks) | |
| issues.update(result.issue_counts) | |
| for example in result.issue_examples: | |
| if len(examples) < _MAX_ISSUE_EXAMPLES: | |
| examples.append(example) | |
| return stats, promotion, checks, issues, examples | |
| def _build_tasks( | |
| *, | |
| config: dict[str, Any], | |
| output_root: Path, | |
| requested_records: int, | |
| minimum_family_records: int, | |
| minimum_template_variants: int, | |
| project_root: Path, | |
| config_path: Path, | |
| source_bundle_sha256: str, | |
| ) -> list[BuildShardTask]: | |
| shard_size = int(config["shard_size"]) | |
| compresslevel = int(config["gzip_compresslevel"]) | |
| tasks: list[BuildShardTask] = [] | |
| for shard_index, start in enumerate(range(0, requested_records, shard_size)): | |
| end = min(requested_records, start + shard_size) | |
| stem = f"part-{shard_index:05d}" | |
| tasks.append( | |
| BuildShardTask( | |
| shard_index=shard_index, | |
| start_index=start, | |
| end_index=end, | |
| canonical_path=str((output_root / "canonical" / f"{stem}.jsonl.gz").resolve()), | |
| verdict_path=str( | |
| (output_root / "quality" / "verdicts" / f"{stem}.quality.jsonl.gz").resolve() | |
| ), | |
| config=config, | |
| compresslevel=compresslevel, | |
| minimum_family_records=minimum_family_records, | |
| minimum_template_variants=minimum_template_variants, | |
| project_root=str(project_root.resolve()), | |
| config_path=str(config_path.resolve()), | |
| source_bundle_sha256=source_bundle_sha256, | |
| ) | |
| ) | |
| return tasks | |
| def _manifest_payload( | |
| *, | |
| config: Mapping[str, Any], | |
| config_path: Path, | |
| config_snapshot_path: Path, | |
| plan_payload: Mapping[str, Any], | |
| source_bundle: Mapping[str, Any], | |
| source_snapshot: Mapping[str, Any], | |
| source_bundle_manifest_path: Path, | |
| source_bundle_manifest_sha256: str, | |
| results: Sequence[BuildShardResult], | |
| stats: CorpusStatsV2, | |
| promotion_report: Mapping[str, Any], | |
| requested_records: int, | |
| ) -> dict[str, Any]: | |
| shards = [] | |
| for result in sorted(results, key=lambda item: item.shard_index): | |
| shards.append( | |
| { | |
| "shard_index": result.shard_index, | |
| "start_index": result.start_index, | |
| "end_index": result.end_index, | |
| "records": result.end_index - result.start_index, | |
| "canonical_path": str(result.canonical.path), | |
| "canonical_sha256": result.canonical.sha256, | |
| "canonical_compressed_bytes": result.canonical.compressed_bytes, | |
| "canonical_uncompressed_bytes": result.canonical.uncompressed_bytes, | |
| "verdict_path": str(result.verdict.path), | |
| "verdict_sha256": result.verdict.sha256, | |
| "verdict_compressed_bytes": result.verdict.compressed_bytes, | |
| "verdict_uncompressed_bytes": result.verdict.uncompressed_bytes, | |
| } | |
| ) | |
| return { | |
| "manifest_version": MANIFEST_VERSION, | |
| "pipeline_version": PIPELINE_VERSION, | |
| "metadata": { | |
| "dataset_name": config["dataset_name"], | |
| "schema_version": config["schema_version"], | |
| "generator_version": config["generator_version"], | |
| "validator_version": config["validator_version"], | |
| "quality_schema_version": QUALITY_V2_SCHEMA_VERSION, | |
| "requested_records": requested_records, | |
| "configured_total_records": int(config["total_records"]), | |
| "partial_run": requested_records != int(config["total_records"]), | |
| "synthetic_only": True, | |
| "real_modality_records": 0, | |
| "human_reviewed_records": 0, | |
| "config": { | |
| "path": str(config_path.resolve()), | |
| "raw_sha256": sha256_file(config_path), | |
| "semantic_sha256": _semantic_sha256(config), | |
| "snapshot_path": str(config_snapshot_path.resolve()), | |
| "snapshot_raw_sha256": sha256_file(config_snapshot_path), | |
| "snapshot_semantic_sha256": _semantic_sha256(config), | |
| }, | |
| "generation_plan": { | |
| "sha256": _semantic_sha256(plan_payload), | |
| "payload": dict(plan_payload), | |
| }, | |
| "source_bundle": dict(source_bundle), | |
| "source_snapshot": dict(source_snapshot), | |
| "source_bundle_manifest": { | |
| "path": str(source_bundle_manifest_path.resolve()), | |
| "sha256": source_bundle_manifest_sha256, | |
| }, | |
| }, | |
| "shards": shards, | |
| "statistics": stats.to_dict(), | |
| "promotion_quality": dict(promotion_report), | |
| "totals": { | |
| "records": sum(row["records"] for row in shards), | |
| "shards": len(shards), | |
| "canonical_compressed_bytes": sum(row["canonical_compressed_bytes"] for row in shards), | |
| "canonical_uncompressed_bytes": sum( | |
| row["canonical_uncompressed_bytes"] for row in shards | |
| ), | |
| "verdict_compressed_bytes": sum(row["verdict_compressed_bytes"] for row in shards), | |
| "verdict_uncompressed_bytes": sum( | |
| row["verdict_uncompressed_bytes"] for row in shards | |
| ), | |
| }, | |
| } | |
| def run_build_v2( | |
| *, | |
| config_path: str | Path = DEFAULT_CONFIG, | |
| output_root: str | Path, | |
| workers: int = 1, | |
| limit: int | None = None, | |
| minimum_family_records: int = 40, | |
| minimum_template_variants: int = 4, | |
| project_root: str | Path = PROJECT_ROOT, | |
| ) -> dict[str, Any]: | |
| """Generate, sidecar-validate, re-read, and conditionally promote v2.""" | |
| config_path = Path(config_path).resolve() | |
| output_root = Path(output_root).resolve() | |
| project_root = Path(project_root).resolve() | |
| config = _load_config(config_path) | |
| configured_total = int(config["total_records"]) | |
| requested_records = configured_total if limit is None else int(limit) | |
| if not 1 <= requested_records <= configured_total: | |
| raise ValueError("--limit must be between 1 and config.total_records") | |
| if workers < 1: | |
| raise ValueError("workers must be at least one") | |
| if minimum_family_records < 1 or minimum_template_variants < 1: | |
| raise ValueError("promotion thresholds must be positive") | |
| if output_root.exists() and any(output_root.iterdir()): | |
| raise FileExistsError(f"v2 output directory is not empty: {output_root}") | |
| output_root.mkdir(parents=True, exist_ok=True) | |
| config_snapshot_path = output_root / "config.snapshot.json" | |
| write_json_atomic(config_snapshot_path, config) | |
| plan = GenerationPlanV2(config) | |
| plan_payload = _plan_payload(plan) | |
| initial_source_bundle = _source_bundle(project_root, config_path) | |
| source_snapshot = _write_source_snapshot_atomic( | |
| output_root / "source_bundle_snapshot.tar.gz", | |
| initial_source_bundle, | |
| ) | |
| source_bundle_manifest_path = output_root / "source_bundle_manifest.json" | |
| write_json_atomic( | |
| source_bundle_manifest_path, | |
| { | |
| "source_bundle_manifest_version": SOURCE_BUNDLE_VERSION, | |
| "config": { | |
| "path": str(config_path), | |
| "raw_sha256": sha256_file(config_path), | |
| "semantic_sha256": _semantic_sha256(config), | |
| "snapshot_path": str(config_snapshot_path), | |
| "snapshot_raw_sha256": sha256_file(config_snapshot_path), | |
| }, | |
| "generation_plan": { | |
| "sha256": _semantic_sha256(plan_payload), | |
| "payload": plan_payload, | |
| }, | |
| "source_bundle": initial_source_bundle, | |
| "source_snapshot": source_snapshot, | |
| "runtime": { | |
| "python_version": sys.version, | |
| "python_executable": sys.executable, | |
| "slurm_job_id": os.environ.get("SLURM_JOB_ID"), | |
| }, | |
| }, | |
| ) | |
| source_bundle_manifest_sha256 = sha256_file(source_bundle_manifest_path) | |
| tasks = _build_tasks( | |
| config=config, | |
| output_root=output_root, | |
| requested_records=requested_records, | |
| minimum_family_records=minimum_family_records, | |
| minimum_template_variants=minimum_template_variants, | |
| project_root=project_root, | |
| config_path=config_path, | |
| source_bundle_sha256=initial_source_bundle["sha256"], | |
| ) | |
| expected_shards = (requested_records + int(config["shard_size"]) - 1) // int( | |
| config["shard_size"] | |
| ) | |
| worker_count = max(1, min(int(workers), expected_shards)) | |
| try: | |
| build_results = _run_build_tasks(tasks, worker_count) | |
| first_stats, first_promotion = _merge_build_results( | |
| build_results, | |
| minimum_family_records=minimum_family_records, | |
| minimum_template_variants=minimum_template_variants, | |
| expected_total_records=configured_total, | |
| ) | |
| first_promotion_report = first_promotion.finalize() | |
| manifest = _manifest_payload( | |
| config=config, | |
| config_path=config_path, | |
| config_snapshot_path=config_snapshot_path, | |
| plan_payload=plan_payload, | |
| source_bundle=initial_source_bundle, | |
| source_snapshot=source_snapshot, | |
| source_bundle_manifest_path=source_bundle_manifest_path, | |
| source_bundle_manifest_sha256=source_bundle_manifest_sha256, | |
| results=build_results, | |
| stats=first_stats, | |
| promotion_report=first_promotion_report, | |
| requested_records=requested_records, | |
| ) | |
| manifest_path = output_root / "manifest.json" | |
| write_json_atomic(manifest_path, manifest) | |
| complete = { | |
| "marker_version": MARKER_VERSION, | |
| "phase": "materialized", | |
| "dataset_name": config["dataset_name"], | |
| "records": first_stats.total_records, | |
| "shards": len(build_results), | |
| "manifest": str(manifest_path), | |
| "manifest_sha256": sha256_file(manifest_path), | |
| "all_records_keep": first_stats.keep_records == requested_records, | |
| } | |
| write_json_atomic(output_root / "_COMPLETE.json", complete) | |
| result_by_index = {result.shard_index: result for result in build_results} | |
| verify_tasks = [ | |
| VerifyShardTask( | |
| shard_index=task.shard_index, | |
| start_index=task.start_index, | |
| end_index=task.end_index, | |
| canonical_path=str(result_by_index[task.shard_index].canonical.path), | |
| canonical_sha256=result_by_index[task.shard_index].canonical.sha256, | |
| verdict_path=str(result_by_index[task.shard_index].verdict.path), | |
| verdict_sha256=result_by_index[task.shard_index].verdict.sha256, | |
| config=config, | |
| minimum_family_records=minimum_family_records, | |
| minimum_template_variants=minimum_template_variants, | |
| project_root=str(project_root), | |
| config_path=str(config_path), | |
| source_bundle_sha256=initial_source_bundle["sha256"], | |
| ) | |
| for task in tasks | |
| ] | |
| verify_results = _run_verify_tasks(verify_tasks, worker_count) | |
| ( | |
| second_stats, | |
| second_promotion, | |
| verification_checks, | |
| verification_issues, | |
| issue_examples, | |
| ) = _merge_verify_results( | |
| verify_results, | |
| minimum_family_records=minimum_family_records, | |
| minimum_template_variants=minimum_template_variants, | |
| expected_total_records=configured_total, | |
| ) | |
| second_promotion_report = second_promotion.finalize() | |
| current_source_bundle = _source_bundle(project_root, config_path) | |
| current_plan_payload = _plan_payload(GenerationPlanV2(config)) | |
| full_run = requested_records == configured_total | |
| production_100_shards = not full_run or expected_shards == 100 | |
| expected_task_families = set(FAMILY_INPUT_SIGNATURES) | |
| observed_task_families = set(second_stats.task_family) | |
| second_stats_payload = second_stats.to_dict() | |
| gates = { | |
| "exact_requested_record_count": second_stats.total_records == requested_records, | |
| "expected_shard_count": len(build_results) == len(verify_results) == expected_shards, | |
| "production_has_exactly_100_shards": production_100_shards, | |
| "all_canonical_shard_hashes_rechecked": verification_checks[ | |
| "canonical_shard_sha256" | |
| ] | |
| == expected_shards, | |
| "all_verdict_shard_hashes_rechecked": verification_checks[ | |
| "verdict_shard_sha256" | |
| ] | |
| == expected_shards, | |
| "all_verification_checks_passed": not verification_issues, | |
| "all_records_exactly_regenerated": verification_checks["exact_regeneration"] | |
| == requested_records, | |
| "all_record_ids_aligned": verification_checks["record_id_alignment"] | |
| == requested_records, | |
| "all_record_indices_aligned": verification_checks["record_index_alignment"] | |
| == requested_records, | |
| "all_sidecar_hashes_aligned": verification_checks["sidecar_record_hash"] | |
| == requested_records, | |
| "all_verdicts_independently_recomputed": verification_checks[ | |
| "verdict_recomputation" | |
| ] | |
| == requested_records, | |
| "all_verdicts_keep": second_stats.keep_records == requested_records, | |
| "all_existing_structural_checks_passed": second_stats.structural_passed | |
| == requested_records, | |
| "all_v2_quality_checks_passed": second_stats.v2_quality_passed | |
| == requested_records, | |
| "all_serializer_roundtrips_passed": second_stats.serializer_passed | |
| == requested_records, | |
| "all_records_primary_zh_tw": second_stats.primary_zh_tw_records | |
| == requested_records, | |
| "zero_disallowed_simplified_or_prc_hits": ( | |
| second_stats.disallowed_simplified_or_prc_hit_records == 0 | |
| ), | |
| "model_visible_han_characters_are_majority": ( | |
| second_stats_payload["model_visible_han_to_han_plus_latin_ratio"] > 0.5 | |
| ), | |
| "source_groups_split_locked": second_stats.source_group_split_conflicts == 0, | |
| "no_unknown_task_family": not (observed_task_families - expected_task_families), | |
| "exact_full_task_family_set": (not full_run) | |
| or observed_task_families == expected_task_families, | |
| "exact_primitive_distribution": (not full_run) | |
| or second_stats_payload["primitive"] | |
| == _expected_percent_counts(config["primitive_percent"], configured_total), | |
| "exact_mixture_distribution": (not full_run) | |
| or second_stats_payload["mixture_category"] | |
| == _expected_percent_counts(config["mixture_percent"], configured_total), | |
| "exact_serializer_distribution": (not full_run) | |
| or second_stats_payload["serializer"] | |
| == _expected_percent_counts(config["serializer_percent"], configured_total), | |
| "exact_split_distribution": (not full_run) | |
| or second_stats_payload["split"] | |
| == _expected_percent_counts(config["split_percent"], configured_total), | |
| "exact_long_context_bucket_distribution": (not full_run) | |
| or second_stats_payload["context_bucket"] | |
| == _expected_context_bucket_counts(config), | |
| "first_and_second_corpus_statistics_equal": first_stats.to_dict() | |
| == second_stats.to_dict(), | |
| "first_and_second_promotion_accumulators_equal": first_promotion_report | |
| == second_promotion_report, | |
| "config_snapshot_semantically_equal": json.loads( | |
| config_snapshot_path.read_text(encoding="utf-8") | |
| ) | |
| == config, | |
| "config_hash_unchanged": sha256_file(config_path) | |
| == manifest["metadata"]["config"]["raw_sha256"], | |
| "source_bundle_unchanged": current_source_bundle == initial_source_bundle, | |
| "source_bundle_manifest_unchanged": sha256_file(source_bundle_manifest_path) | |
| == source_bundle_manifest_sha256, | |
| "source_snapshot_hash_unchanged": sha256_file( | |
| Path(str(source_snapshot["path"])) | |
| ) | |
| == source_snapshot["sha256"], | |
| "source_snapshot_contents_match_pin": _source_snapshot_contents_match( | |
| source_snapshot, initial_source_bundle | |
| ), | |
| "generation_plan_hash_unchanged": _semantic_sha256(current_plan_payload) | |
| == manifest["metadata"]["generation_plan"]["sha256"], | |
| } | |
| artifact_verified = all(gates.values()) | |
| training_promotion_passed = bool( | |
| artifact_verified | |
| and full_run | |
| and first_promotion_report.get("promotion_passed") | |
| and second_promotion_report.get("promotion_passed") | |
| ) | |
| redistribution_cleared = ( | |
| config.get("redistribution") == "owner-approved-public-access" | |
| and config.get("public_release_authorization", {}).get("approved") is True | |
| ) | |
| public_release_promotion_passed = training_promotion_passed and redistribution_cleared | |
| postwrite = { | |
| "postwrite_version": POSTWRITE_VERSION, | |
| "pipeline_version": PIPELINE_VERSION, | |
| "dataset_name": config["dataset_name"], | |
| "requested_records": requested_records, | |
| "configured_total_records": configured_total, | |
| "partial_run": not full_run, | |
| "expected_shards": expected_shards, | |
| "statistics": second_stats.to_dict(), | |
| "promotion_quality": second_promotion_report, | |
| "verification_checks": _sorted_counter(verification_checks), | |
| "verification_issue_counts": _sorted_counter(verification_issues), | |
| "verification_issue_examples": issue_examples, | |
| "gates": gates, | |
| "quality_artifacts_verified": artifact_verified, | |
| "training_promotion_passed": training_promotion_passed, | |
| "public_release_promotion_passed": public_release_promotion_passed, | |
| "pins": { | |
| "manifest_sha256": sha256_file(manifest_path), | |
| "config_raw_sha256": sha256_file(config_path), | |
| "config_semantic_sha256": _semantic_sha256(config), | |
| "source_bundle_sha256": current_source_bundle["sha256"], | |
| "source_snapshot_sha256": source_snapshot["sha256"], | |
| "generation_plan_sha256": _semantic_sha256(current_plan_payload), | |
| }, | |
| } | |
| report_path = output_root / "reports" / "postwrite-verification.json" | |
| write_json_atomic(report_path, postwrite) | |
| marker = { | |
| "marker_version": MARKER_VERSION, | |
| "dataset_name": config["dataset_name"], | |
| "records": second_stats.total_records, | |
| "shards": len(verify_results), | |
| "manifest": str(manifest_path), | |
| "manifest_sha256": sha256_file(manifest_path), | |
| "postwrite_report": str(report_path), | |
| "postwrite_report_sha256": sha256_file(report_path), | |
| "quality_artifacts_verified": artifact_verified, | |
| "training_promotion_passed": training_promotion_passed, | |
| "public_release_promotion_passed": public_release_promotion_passed, | |
| } | |
| if artifact_verified: | |
| write_json_atomic(output_root / "_VERIFIED.json", marker) | |
| else: | |
| write_json_atomic( | |
| output_root / "_FAILED_GATES.json", | |
| marker | |
| | { | |
| "gates": gates, | |
| "verification_issue_counts": _sorted_counter(verification_issues), | |
| }, | |
| ) | |
| if training_promotion_passed: | |
| write_json_atomic(output_root / "_PROMOTED.json", marker) | |
| write_json_atomic(output_root / "_SUCCESS.json", marker) | |
| elif full_run: | |
| failed_corpus_gates = { | |
| name: detail | |
| for name, detail in second_promotion_report.get("gates", {}).items() | |
| if isinstance(detail, Mapping) and not detail.get("passed") | |
| } | |
| write_json_atomic( | |
| output_root / "_FAILED_PROMOTION.json", | |
| marker | |
| | { | |
| "artifact_gates": gates, | |
| "failed_corpus_gates": failed_corpus_gates, | |
| }, | |
| ) | |
| return marker | { | |
| "partial_run": not full_run, | |
| "gates": gates, | |
| "promotion_quality": second_promotion_report, | |
| } | |
| except BaseException as exc: | |
| failure = { | |
| "marker_version": MARKER_VERSION, | |
| "dataset_name": config.get("dataset_name"), | |
| "requested_records": requested_records, | |
| "error_type": type(exc).__name__, | |
| "error": str(exc)[:1000], | |
| } | |
| write_json_atomic(output_root / "_BUILD_FAILED.json", failure) | |
| raise | |
| # Readable aliases for callers and compatibility with the v1 runner naming. | |
| run_v2_build = run_build_v2 | |
| def command_build(args: argparse.Namespace) -> int: | |
| result = run_build_v2( | |
| config_path=args.config, | |
| output_root=args.output, | |
| workers=args.workers, | |
| limit=args.limit, | |
| minimum_family_records=args.minimum_family_records, | |
| minimum_template_variants=args.minimum_template_variants, | |
| project_root=args.project_root, | |
| ) | |
| summary = {key: value for key, value in result.items() if key != "promotion_quality"} | |
| summary["corpus_promotion_quality_passed"] = bool( | |
| result.get("promotion_quality", {}).get("promotion_passed") | |
| ) | |
| print(json.dumps(summary, ensure_ascii=False, indent=2, sort_keys=True)) | |
| if not result["quality_artifacts_verified"]: | |
| raise RuntimeError("v2 post-write integrity or per-record quality gates failed") | |
| if not result["partial_run"] and not result["training_promotion_passed"]: | |
| raise RuntimeError("full v2 corpus failed PromotionAccumulator gates") | |
| return 0 | |
| def command_show_plan(args: argparse.Namespace) -> int: | |
| config = _load_config(args.config) | |
| payload = _plan_payload(GenerationPlanV2(config)) | |
| print( | |
| json.dumps( | |
| { | |
| "dataset_name": config["dataset_name"], | |
| "config_sha256": _semantic_sha256(config), | |
| "generation_plan_sha256": _semantic_sha256(payload), | |
| "generation_plan": payload, | |
| }, | |
| ensure_ascii=False, | |
| indent=2, | |
| sort_keys=True, | |
| ) | |
| ) | |
| return 0 | |
| def command_render_sample(args: argparse.Namespace) -> int: | |
| config = _load_config(args.config) | |
| plan = GenerationPlanV2(config) | |
| index = int(args.index) | |
| record = generate_record_v2(config, plan, index) | |
| verdict = _build_verdict( | |
| record, | |
| expected_index=index, | |
| source_shard="render-sample", | |
| source_line=1, | |
| ) | |
| print( | |
| json.dumps( | |
| { | |
| "record": record, | |
| "messages": build_messages_v2(record), | |
| "quality_verdict": verdict, | |
| }, | |
| ensure_ascii=False, | |
| indent=2, | |
| sort_keys=True, | |
| ) | |
| ) | |
| return 0 | |
| def build_parser() -> argparse.ArgumentParser: | |
| parser = argparse.ArgumentParser( | |
| description="Barbet BGD-SFT v2 generate + quality sidecar + promotion pipeline" | |
| ) | |
| subparsers = parser.add_subparsers(dest="command", required=True) | |
| build = subparsers.add_parser("build", help="materialize and independently verify v2") | |
| build.add_argument("--config", default=str(DEFAULT_CONFIG)) | |
| build.add_argument("--output", required=True) | |
| build.add_argument("--workers", type=int, default=1) | |
| build.add_argument("--limit", type=int) | |
| build.add_argument("--minimum-family-records", type=int, default=40) | |
| build.add_argument("--minimum-template-variants", type=int, default=4) | |
| build.add_argument("--project-root", default=str(PROJECT_ROOT)) | |
| build.set_defaults(func=command_build) | |
| show = subparsers.add_parser("show-plan", help="show and hash the v2 generation plan") | |
| show.add_argument("--config", default=str(DEFAULT_CONFIG)) | |
| show.set_defaults(func=command_show_plan) | |
| render = subparsers.add_parser("render-sample", help="render one v2 record and verdict") | |
| render.add_argument("--config", default=str(DEFAULT_CONFIG)) | |
| render.add_argument("--index", type=int, default=0) | |
| render.set_defaults(func=command_render_sample) | |
| return parser | |
| def main(argv: list[str] | None = None) -> int: | |
| parser = build_parser() | |
| args = parser.parse_args(argv) | |
| try: | |
| return int(args.func(args)) | |
| except Exception as exc: | |
| print(f"ERROR: {exc}", file=sys.stderr) | |
| return 1 | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |