Datasets:
Download code/src/barbet_bgd/cli.py from voidful/barbet-sft: direct link, hf CLI and curl.
- Browser
- Download file 19.9 kB
-
https://huggingface.co/datasets/voidful/barbet-sft/resolve/main/code/src/barbet_bgd/cli.py
- Command line
-
hf download hf://datasets/voidful/barbet-sft/code/src/barbet_bgd/cli.py
-
curl -L -o cli.py https://huggingface.co/datasets/voidful/barbet-sft/resolve/main/code/src/barbet_bgd/cli.py
19.9 kB
| """Command-line entry points for generating and auditing BGD-SFT artifacts.""" | |
| from __future__ import annotations | |
| import argparse | |
| import hashlib | |
| import json | |
| import sys | |
| from collections import Counter | |
| from concurrent.futures import ProcessPoolExecutor, as_completed | |
| from dataclasses import dataclass | |
| from pathlib import Path | |
| from typing import Any, Iterable | |
| from .audit import StatsAccumulator, build_manifest, build_report | |
| from .generation import GenerationPlan, generate_record | |
| from .io import ( | |
| ShardResult, | |
| iter_jsonl_gz, | |
| sha256_file, | |
| write_json_atomic, | |
| write_jsonl_gz_atomic, | |
| ) | |
| from .serializers import build_messages | |
| from .validation import validate_record | |
| DEFAULT_CONFIG = Path(__file__).resolve().parents[2] / "configs" / "selected_sft_1m.json" | |
| class WorkerResult: | |
| shard: ShardResult | |
| stats: StatsAccumulator | |
| group_splits: dict[str, str] | |
| invalid_examples: list[dict[str, Any]] | |
| def _load_config(path: str | Path) -> dict[str, Any]: | |
| config_path = Path(path) | |
| config = json.loads(config_path.read_text(encoding="utf-8")) | |
| if not isinstance(config, dict): | |
| raise ValueError("config must be a JSON object") | |
| GenerationPlan(config) | |
| return config | |
| def _config_digest(config: dict[str, Any]) -> str: | |
| payload = json.dumps(config, ensure_ascii=False, sort_keys=True, separators=(",", ":")) | |
| return hashlib.sha256(payload.encode("utf-8")).hexdigest() | |
| def _record_stream( | |
| config: dict[str, Any], | |
| start: int, | |
| end: int, | |
| stats: StatsAccumulator, | |
| group_splits: dict[str, str], | |
| ) -> Iterable[dict[str, Any]]: | |
| plan = GenerationPlan(config) | |
| for index in range(start, end): | |
| record = generate_record(config, plan, index) | |
| errors = validate_record(record) | |
| if errors: | |
| raise ValueError( | |
| f"generated invalid record {record.get('record_id')}: " + "; ".join(errors) | |
| ) | |
| source_group = record["source_group"] | |
| split = record["split"] | |
| previous = group_splits.setdefault(source_group, split) | |
| if previous != split: | |
| raise ValueError(f"source group split leakage: {source_group}: {previous} vs {split}") | |
| stats.ingest(record) | |
| yield record | |
| def _generate_shard( | |
| config: dict[str, Any], | |
| output_path: str, | |
| start: int, | |
| end: int, | |
| compresslevel: int, | |
| ) -> WorkerResult: | |
| stats = StatsAccumulator() | |
| group_splits: dict[str, str] = {} | |
| shard = write_jsonl_gz_atomic( | |
| output_path, | |
| _record_stream(config, start, end, stats, group_splits), | |
| compresslevel=compresslevel, | |
| ) | |
| if shard.records != end - start: | |
| raise RuntimeError(f"short shard {output_path}: {shard.records} != {end - start}") | |
| return WorkerResult(shard=shard, stats=stats, group_splits=group_splits, invalid_examples=[]) | |
| def _audit_shard(expected: dict[str, Any]) -> WorkerResult: | |
| path = Path(expected["path"]) | |
| actual_hash = sha256_file(path) | |
| invalid_examples: list[dict[str, Any]] = [] | |
| stats = StatsAccumulator() | |
| group_splits: dict[str, str] = {} | |
| records = 0 | |
| for record in iter_jsonl_gz(path): | |
| records += 1 | |
| errors = validate_record(record) | |
| if errors and len(invalid_examples) < 20: | |
| invalid_examples.append({"record_id": record.get("record_id"), "errors": errors}) | |
| stats.ingest(record) | |
| source_group = record.get("source_group") | |
| split = record.get("split") | |
| if isinstance(source_group, str) and isinstance(split, str): | |
| previous = group_splits.setdefault(source_group, split) | |
| if previous != split and len(invalid_examples) < 20: | |
| invalid_examples.append( | |
| { | |
| "record_id": record.get("record_id"), | |
| "errors": [f"source group split leakage: {source_group}: {previous} vs {split}"], | |
| } | |
| ) | |
| if actual_hash != expected["sha256"]: | |
| invalid_examples.append( | |
| {"record_id": None, "errors": [f"checksum mismatch for {path}"]} | |
| ) | |
| if records != int(expected["records"]): | |
| invalid_examples.append( | |
| { | |
| "record_id": None, | |
| "errors": [f"record count mismatch for {path}: {records} != {expected['records']}"], | |
| } | |
| ) | |
| shard = ShardResult( | |
| path=path, | |
| records=records, | |
| sha256=actual_hash, | |
| compressed_bytes=path.stat().st_size, | |
| uncompressed_bytes=int(expected.get("uncompressed_bytes", 0)), | |
| ) | |
| return WorkerResult( | |
| shard=shard, | |
| stats=stats, | |
| group_splits=group_splits, | |
| invalid_examples=invalid_examples, | |
| ) | |
| def _merge_worker_results(results: list[WorkerResult]) -> tuple[StatsAccumulator, int, list[dict[str, Any]]]: | |
| stats = StatsAccumulator() | |
| all_group_splits: dict[str, str] = {} | |
| split_conflicts = 0 | |
| invalid_examples: list[dict[str, Any]] = [] | |
| for result in results: | |
| stats.merge(result.stats) | |
| for source_group, split in result.group_splits.items(): | |
| previous = all_group_splits.setdefault(source_group, split) | |
| if previous != split: | |
| split_conflicts += 1 | |
| if len(invalid_examples) < 20: | |
| invalid_examples.append( | |
| { | |
| "record_id": None, | |
| "errors": [ | |
| f"cross-shard source group leakage: {source_group}: {previous} vs {split}" | |
| ], | |
| } | |
| ) | |
| for example in result.invalid_examples: | |
| if len(invalid_examples) < 20: | |
| invalid_examples.append(example) | |
| return stats, split_conflicts, invalid_examples | |
| def _expected_counts(percent: dict[str, int], total: int) -> dict[str, int]: | |
| return {key: total * value // 100 for key, value in percent.items()} | |
| def _promotion_gates( | |
| config: dict[str, Any], | |
| stats: StatsAccumulator, | |
| *, | |
| requested_records: int, | |
| split_conflicts: int, | |
| invalid_examples: list[dict[str, Any]], | |
| ) -> dict[str, Any]: | |
| observed = stats.to_dict() | |
| full_run = requested_records == int(config["total_records"]) | |
| gates: dict[str, bool | None] = { | |
| "exact_requested_record_count": observed["total_records"] == requested_records, | |
| "all_records_primary_zh_tw": observed["primary_zh_tw_records"] == requested_records, | |
| "no_unannotated_simplified_only_hits": observed[ | |
| "unannotated_simplified_only_hit_records" | |
| ] | |
| == 0, | |
| "record_ids_unique": observed["duplicate_record_id_occurrences"] == 0, | |
| "evidence_references_resolve": observed["evidence_reference_missing"] == 0, | |
| "source_groups_split_locked": split_conflicts == 0, | |
| "all_records_semantically_valid": not invalid_examples, | |
| "exact_split_distribution": None, | |
| "exact_primitive_distribution": None, | |
| "exact_mixture_distribution": None, | |
| "exact_serializer_distribution": None, | |
| "exact_long_context_distribution": None, | |
| } | |
| if full_run: | |
| gates["exact_split_distribution"] = observed["split"] == _expected_counts( | |
| config["split_percent"], requested_records | |
| ) | |
| gates["exact_primitive_distribution"] = observed["primitive"] == _expected_counts( | |
| config["primitive_percent"], requested_records | |
| ) | |
| gates["exact_mixture_distribution"] = observed["mixture_category"] == _expected_counts( | |
| config["mixture_percent"], requested_records | |
| ) | |
| gates["exact_serializer_distribution"] = observed["serializer"] == _expected_counts( | |
| config["serializer_percent"], requested_records | |
| ) | |
| long_total = int(config["long_context_records"]) | |
| long_expected = _expected_counts(config["long_context_bucket_percent"], long_total) | |
| overall_expected = dict(long_expected) | |
| overall_expected["0.5K-4K"] += requested_records - long_total | |
| gates["exact_long_context_distribution"] = observed["context_bucket"] == overall_expected | |
| evaluated = [value for value in gates.values() if value is not None] | |
| return { | |
| "full_run": full_run, | |
| "gates": gates, | |
| "all_evaluated_gates_passed": all(evaluated), | |
| "invalid_examples": invalid_examples, | |
| "source_group_split_conflicts": split_conflicts, | |
| } | |
| def _publish_reports( | |
| output_root: Path, | |
| config: dict[str, Any], | |
| results: list[WorkerResult], | |
| stats: StatsAccumulator, | |
| gates: dict[str, Any], | |
| *, | |
| requested_records: int, | |
| report_prefix: str, | |
| ) -> tuple[Path, Path]: | |
| shards = sorted((result.shard for result in results), key=lambda shard: str(shard.path)) | |
| metadata = { | |
| "dataset_name": config["dataset_name"], | |
| "schema_version": config["schema_version"], | |
| "generator_version": config["generator_version"], | |
| "validator_version": config["validator_version"], | |
| "config_sha256": _config_digest(config), | |
| "requested_records": requested_records, | |
| "synthetic_only": True, | |
| "human_reviewed_records": 0, | |
| "teacher_generated_records": 0, | |
| } | |
| manifest = build_manifest(shards, stats=stats, metadata=metadata) | |
| manifest_path = output_root / f"{report_prefix}manifest.json" | |
| write_json_atomic(manifest_path, manifest) | |
| report = build_report(stats, metadata=metadata) | |
| report["promotion_gates"] = gates | |
| report_path = output_root / "reports" / f"{report_prefix}audit.json" | |
| write_json_atomic(report_path, report) | |
| return manifest_path, report_path | |
| def _run_parallel_generate( | |
| config: dict[str, Any], | |
| output_root: Path, | |
| requested_records: int, | |
| workers: int, | |
| ) -> list[WorkerResult]: | |
| shard_size = int(config["shard_size"]) | |
| tasks = [] | |
| for shard_index, start in enumerate(range(0, requested_records, shard_size)): | |
| end = min(requested_records, start + shard_size) | |
| path = output_root / "canonical" / f"part-{shard_index:05d}.jsonl.gz" | |
| tasks.append((config, str(path), start, end, int(config["gzip_compresslevel"]))) | |
| results: list[WorkerResult] = [] | |
| if workers == 1: | |
| for shard_index, task in enumerate(tasks, 1): | |
| result = _generate_shard(*task) | |
| results.append(result) | |
| print(f"generated {shard_index}/{len(tasks)} {result.shard.path.name}", flush=True) | |
| return results | |
| with ProcessPoolExecutor(max_workers=workers) as executor: | |
| futures = {executor.submit(_generate_shard, *task): task[1] for task in tasks} | |
| completed = 0 | |
| for future in as_completed(futures): | |
| path = futures.pop(future) | |
| result = future.result() | |
| results.append(result) | |
| completed += 1 | |
| print(f"generated {completed}/{len(tasks)} {Path(path).name}", flush=True) | |
| return results | |
| def command_generate(args: argparse.Namespace) -> int: | |
| config = _load_config(args.config) | |
| requested_records = int(args.limit or config["total_records"]) | |
| if not 1 <= requested_records <= int(config["total_records"]): | |
| raise ValueError("--limit must be between 1 and config.total_records") | |
| output_root = Path(args.output).resolve() | |
| if (output_root / "_SUCCESS.json").exists(): | |
| raise FileExistsError(f"completed dataset already exists: {output_root}") | |
| canonical = output_root / "canonical" | |
| if canonical.exists() and any(canonical.iterdir()): | |
| raise FileExistsError( | |
| f"output canonical directory is not empty: {canonical}; choose a new output path" | |
| ) | |
| output_root.mkdir(parents=True, exist_ok=True) | |
| write_json_atomic(output_root / "config.snapshot.json", config) | |
| workers = max(1, min(int(args.workers), (requested_records + config["shard_size"] - 1) // config["shard_size"])) | |
| results = _run_parallel_generate(config, output_root, requested_records, workers) | |
| stats, split_conflicts, invalid_examples = _merge_worker_results(results) | |
| gates = _promotion_gates( | |
| config, | |
| stats, | |
| requested_records=requested_records, | |
| split_conflicts=split_conflicts, | |
| invalid_examples=invalid_examples, | |
| ) | |
| manifest_path, report_path = _publish_reports( | |
| output_root, | |
| config, | |
| results, | |
| stats, | |
| gates, | |
| requested_records=requested_records, | |
| report_prefix="", | |
| ) | |
| success = { | |
| "dataset_name": config["dataset_name"], | |
| "records": requested_records, | |
| "shards": len(results), | |
| "manifest": str(manifest_path), | |
| "manifest_sha256": sha256_file(manifest_path), | |
| "audit": str(report_path), | |
| "audit_sha256": sha256_file(report_path), | |
| "all_evaluated_gates_passed": gates["all_evaluated_gates_passed"], | |
| } | |
| if not gates["all_evaluated_gates_passed"]: | |
| write_json_atomic(output_root / "_FAILED_GATES.json", success | {"gates": gates}) | |
| raise RuntimeError(f"generation gates failed; inspect {report_path}") | |
| write_json_atomic(output_root / "_SUCCESS.json", success) | |
| print(json.dumps(success, ensure_ascii=False, indent=2, sort_keys=True)) | |
| return 0 | |
| def _run_parallel_audit(manifest: dict[str, Any], workers: int) -> list[WorkerResult]: | |
| shards = manifest.get("shards") | |
| if not isinstance(shards, list) or not shards: | |
| raise ValueError("manifest has no shards") | |
| results: list[WorkerResult] = [] | |
| if workers == 1: | |
| for index, shard in enumerate(shards, 1): | |
| result = _audit_shard(shard) | |
| results.append(result) | |
| print(f"audited {index}/{len(shards)} {Path(shard['path']).name}", flush=True) | |
| return results | |
| with ProcessPoolExecutor(max_workers=workers) as executor: | |
| futures = {executor.submit(_audit_shard, shard): shard for shard in shards} | |
| completed = 0 | |
| for future in as_completed(futures): | |
| shard = futures.pop(future) | |
| results.append(future.result()) | |
| completed += 1 | |
| print(f"audited {completed}/{len(shards)} {Path(shard['path']).name}", flush=True) | |
| return results | |
| def command_audit(args: argparse.Namespace) -> int: | |
| output_root = Path(args.output).resolve() | |
| config = _load_config(args.config or output_root / "config.snapshot.json") | |
| manifest_path = Path(args.manifest or output_root / "manifest.json") | |
| manifest = json.loads(manifest_path.read_text(encoding="utf-8")) | |
| requested_records = int(manifest["metadata"]["requested_records"]) | |
| workers = max(1, min(int(args.workers), len(manifest["shards"]))) | |
| results = _run_parallel_audit(manifest, workers) | |
| stats, split_conflicts, invalid_examples = _merge_worker_results(results) | |
| gates = _promotion_gates( | |
| config, | |
| stats, | |
| requested_records=requested_records, | |
| split_conflicts=split_conflicts, | |
| invalid_examples=invalid_examples, | |
| ) | |
| _, report_path = _publish_reports( | |
| output_root, | |
| config, | |
| results, | |
| stats, | |
| gates, | |
| requested_records=requested_records, | |
| report_prefix="postwrite-", | |
| ) | |
| verified = { | |
| "dataset_name": config["dataset_name"], | |
| "records": stats.total_records, | |
| "shards": len(results), | |
| "source_manifest": str(manifest_path), | |
| "source_manifest_sha256": sha256_file(manifest_path), | |
| "audit": str(report_path), | |
| "audit_sha256": sha256_file(report_path), | |
| "all_evaluated_gates_passed": gates["all_evaluated_gates_passed"], | |
| } | |
| if not gates["all_evaluated_gates_passed"]: | |
| write_json_atomic(output_root / "_POSTWRITE_FAILED.json", verified | {"gates": gates}) | |
| raise RuntimeError(f"post-write audit failed; inspect {report_path}") | |
| write_json_atomic(output_root / "_VERIFIED.json", verified) | |
| print(json.dumps(verified, ensure_ascii=False, indent=2, sort_keys=True)) | |
| return 0 | |
| def command_build(args: argparse.Namespace) -> int: | |
| """Generate and then independently re-read every published shard.""" | |
| generate_args = argparse.Namespace( | |
| config=args.config, | |
| output=args.output, | |
| limit=args.limit, | |
| workers=args.workers, | |
| ) | |
| generated = command_generate(generate_args) | |
| if generated: | |
| return generated | |
| audit_args = argparse.Namespace( | |
| output=args.output, | |
| config=None, | |
| manifest=None, | |
| workers=args.workers, | |
| ) | |
| return command_audit(audit_args) | |
| def command_show_plan(args: argparse.Namespace) -> int: | |
| config = _load_config(args.config) | |
| plan = GenerationPlan(config) | |
| summary = { | |
| "dataset_name": config["dataset_name"], | |
| "total_records": config["total_records"], | |
| "primitive_per_100": dict(sorted(Counter(plan.primitive_cycle).items())), | |
| "mixture_per_100": dict(sorted(Counter(plan.mixture_cycle).items())), | |
| "serializer_per_100": dict(sorted(Counter(plan.serializer_cycle).items())), | |
| "long_slots": [ | |
| { | |
| "offset": offset, | |
| "primitive": plan.primitive_cycle[offset], | |
| "mixture": plan.mixture_cycle[offset], | |
| } | |
| for offset in plan.long_slots | |
| ], | |
| } | |
| print(json.dumps(summary, ensure_ascii=False, indent=2, sort_keys=True)) | |
| return 0 | |
| def command_render_sample(args: argparse.Namespace) -> int: | |
| config = _load_config(args.config) | |
| plan = GenerationPlan(config) | |
| record = generate_record(config, plan, int(args.index)) | |
| print( | |
| json.dumps( | |
| {"record": record, "messages": build_messages(record)}, | |
| ensure_ascii=False, | |
| indent=2, | |
| sort_keys=True, | |
| ) | |
| ) | |
| return 0 | |
| def build_parser() -> argparse.ArgumentParser: | |
| parser = argparse.ArgumentParser(description="Barbet BGD-SFT deterministic dataset builder") | |
| subparsers = parser.add_subparsers(dest="command", required=True) | |
| generate = subparsers.add_parser("generate", help="generate validated canonical shards") | |
| generate.add_argument("--config", default=str(DEFAULT_CONFIG)) | |
| generate.add_argument("--output", required=True) | |
| generate.add_argument("--limit", type=int) | |
| generate.add_argument("--workers", type=int, default=1) | |
| generate.set_defaults(func=command_generate) | |
| audit = subparsers.add_parser("audit", help="re-read, hash and semantically validate shards") | |
| audit.add_argument("--output", required=True) | |
| audit.add_argument("--config") | |
| audit.add_argument("--manifest") | |
| audit.add_argument("--workers", type=int, default=1) | |
| audit.set_defaults(func=command_audit) | |
| build = subparsers.add_parser( | |
| "build", help="generate the dataset and independently post-write audit every shard" | |
| ) | |
| build.add_argument("--config", default=str(DEFAULT_CONFIG)) | |
| build.add_argument("--output", required=True) | |
| build.add_argument("--limit", type=int) | |
| build.add_argument("--workers", type=int, default=1) | |
| build.set_defaults(func=command_build) | |
| show_plan = subparsers.add_parser("show-plan", help="print exact per-100 mixture") | |
| show_plan.add_argument("--config", default=str(DEFAULT_CONFIG)) | |
| show_plan.set_defaults(func=command_show_plan) | |
| render = subparsers.add_parser("render-sample", help="render one canonical record as SFT messages") | |
| 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()) | |