Datasets:
Download code/src/barbet_bgd/release_v3.py from voidful/barbet-sft: direct link, hf CLI and curl.
- Browser
- Download file 15 kB
-
https://huggingface.co/datasets/voidful/barbet-sft/resolve/main/code/src/barbet_bgd/release_v3.py
- Command line
-
hf download hf://datasets/voidful/barbet-sft/code/src/barbet_bgd/release_v3.py
-
curl -L -o release_v3.py https://huggingface.co/datasets/voidful/barbet-sft/resolve/main/code/src/barbet_bgd/release_v3.py
15 kB
| """Compute-node build, native streaming verification, and explicit public release.""" | |
| from __future__ import annotations | |
| import argparse | |
| from collections import Counter | |
| import hashlib | |
| import importlib.metadata | |
| import json | |
| import os | |
| from pathlib import Path | |
| import shutil | |
| import tarfile | |
| from .export_sft_v3 import export_sft | |
| from .io import sha256_file, write_json_atomic | |
| from .quality_v2 import validate_record_quality_v2 | |
| from .serializers_v3 import canonical_json_v3 | |
| from .v2_cli import run_build_v2, _source_snapshot_contents_match | |
| OLD_REPO = "voidful/barbet-bgd-synthetic-sft-1m-tw-v2" | |
| REPO = "voidful/barbet-sft" | |
| PROJECT = Path(__file__).resolve().parents[2] | |
| def require_compute() -> None: | |
| if not os.environ.get("SLURM_JOB_ID"): | |
| raise RuntimeError("Full release work must run within a Slurm compute allocation") | |
| def native_streaming_verify(root: Path, report: dict) -> dict: | |
| """Read every row using datasets, comparing per-shard full row digests.""" | |
| from datasets import load_dataset | |
| counts: Counter = Counter() | |
| checked = [] | |
| for shard in report["shards"]: | |
| stream = load_dataset( | |
| "parquet", data_files={shard["split"]: str(root / shard["path"])}, | |
| split=shard["split"], streaming=True, | |
| cache_dir=str(root / ".native-datasets-cache"), | |
| ) | |
| digest = hashlib.sha256() | |
| count = 0 | |
| for row in stream: | |
| if not isinstance(row["messages"], list): | |
| raise ValueError("datasets did not return a list of message structs") | |
| if [turn["role"] for turn in row["messages"]] != ["system", "user", "assistant"]: | |
| raise ValueError("invalid native message role order") | |
| digest.update(canonical_json_v3(row).encode("utf-8") + b"\n") | |
| count += 1 | |
| if count != shard["records"] or digest.hexdigest() != shard["rows_sha256"]: | |
| raise ValueError(f"native datasets digest mismatch: {shard['path']}") | |
| counts[shard["split"]] += count | |
| checked.append({"path": shard["path"], "records": count, "rows_sha256": digest.hexdigest()}) | |
| print(f"Native datasets verified {sum(counts.values())} records", flush=True) | |
| if dict(counts) != report["split_counts"]: | |
| raise ValueError("native datasets split counts differ from Parquet export") | |
| result = {"verified": True, "records": sum(counts.values()), "split_counts": dict(counts), | |
| "shards": checked, "datasets_version": importlib.metadata.version("datasets")} | |
| write_json_atomic(root / "reports" / "native-streaming-verification.json", result) | |
| return result | |
| def dataset_card(report: dict) -> str: | |
| counts = report["split_counts"] | |
| return f'''--- | |
| pretty_name: Barbet SFT | |
| language: | |
| - zh | |
| - en | |
| license: other | |
| license_name: barbet-sft-public-access | |
| license_link: LICENSE_DATA.md | |
| task_categories: | |
| - text-generation | |
| size_categories: | |
| - 1M<n<10M | |
| tags: | |
| - zh-TW | |
| - traditional-chinese | |
| - taiwan | |
| - sft | |
| - synthetic | |
| - grounded-decision | |
| configs: | |
| - config_name: sft | |
| default: true | |
| data_files: | |
| - split: train | |
| path: data/train-*.parquet | |
| - split: validation | |
| path: data/validation-*.parquet | |
| - split: test | |
| path: data/test-*.parquet | |
| --- | |
| # Barbet SFT | |
| 以臺灣繁體中文為中心的 {report["records"]:,} 筆結構化決策 SFT。 | |
| train {counts["train"]:,}、validation {counts["validation"]:,}、test {counts["test"]:,}。 | |
| ```python | |
| from datasets import load_dataset | |
| dataset = load_dataset("{REPO}", split="train", streaming=True) | |
| messages = next(iter(dataset))["messages"] | |
| ``` | |
| `messages` 可直接用作 system / user / assistant 訓練資料。 | |
| 預設只讀固定 schema Parquet;canonical 和品質 JSON 不參與資料欄位推斷。 | |
| 每筆 request 明示輸出格式,JSON、FUNCTION_CALL、COMPACT_TAGS、KEY_VALUE | |
| 共用相同 canonical 目標,沒有額外自由形式思考過程。 | |
| ## 品質與臺灣用語 | |
| 全部 {report["records"]:,} 筆均通過新版機械規則檢查、落盤重讀、 | |
| Parquet 往返與 `datasets` 原生串流全量讀取。 | |
| 檢查包含臺灣術語、已知不自然句型、來源證據、編輯操作、排序、格式及分割。 | |
| 忠實複製與刻意錯誤候選的例外均留有紀錄,不會無條件將原文改成另一種用語。 | |
| 證據:[臺灣用語報告](reports/taiwan-usage.json)、 | |
| [逐筆 SFT 匯出驗證](reports/sft-export-verification.json)、 | |
| [發布驗證](reports/release-verification.json)。 | |
| 逐筆 canonical 品質紀錄位於 `quality/verdicts/`。 | |
| ## 操作原語 | |
| COPY 100K、EDIT 130K、CLASSIFY 50K、EXTRACT 160K、LOCATE 130K、ALIGN 60K、 | |
| MATCH 40K、RANK 120K、VERIFY 140K、ROUTE 70K。來源群組不跨分割。 | |
| ## Canonical 與程式碼 | |
| `canonical/` 保留完整 IR;不建議直接對異構 canonical JSON 使用 Arrow 自動型別推斷。 | |
| 程式碼已展開於 [code/src/barbet_bgd](code/src/barbet_bgd), | |
| `barbet_bgd.io` 就在 [code/src/barbet_bgd/io.py](code/src/barbet_bgd/io.py)。 | |
| 安裝 `code/`,或先設定 `PYTHONPATH=code/src`,再執行: | |
| ```python | |
| from barbet_bgd.io import iter_jsonl_gz | |
| from barbet_bgd.serializers_v3 import build_messages_v3 | |
| record = next(iter_jsonl_gz("canonical/part-00000.jsonl.gz")) | |
| messages = build_messages_v3(record) | |
| ``` | |
| 來源快照、安裝資訊及測試均隨資料提供。舊 v2 source 與報告保留於版本歷史; | |
| 新版重新生成及驗證,沒有沿用舊版 KEEP 當作新版品質標籤。 | |
| ## 限制 | |
| 本版 **100% 確定性合成**,人工逐筆審核 0 筆,真實音訊/影像 0 筆。 | |
| 機械規則無法保證涵蓋所有臺灣用語與自然度問題;不宣稱人工 gold 或部署品質。 | |
| Confidence 為合成先驗,不是實測校準標籤。長度為輸入 Unicode 字元,非 tokenizer tokens。 | |
| 50K 長帳本仍有模板及可見狀態限制;不能據此宣稱完整 256K 推理或真實跨模態遷移能力。 | |
| `BASE_CAPABILITY_REPLAY` 是歷史 mixture 名稱,不代表使用了原始基模 replay 語料。 | |
| 此資料適合作為可機械驗證的訓練與流程測試資料,不是原始設計要求的人工 Anchor-50K | |
| 加真實模型錯誤混合資料;真實分布多樣性、人工評估與部署驗證仍需另補。 | |
| 資料已依擁有者指示公開存取;公開存取不自動增加其他著作權授權, | |
| 詳見 [資料存取聲明](LICENSE_DATA.md)。程式碼沿用 Apache-2.0。 | |
| ''' | |
| def finalize(root: Path) -> dict: | |
| marker = json.loads((root / "_PROMOTED.json").read_text()) | |
| if not marker["training_promotion_passed"] or not marker["public_release_promotion_passed"]: | |
| raise ValueError("canonical promotion/public-owner-authorization did not pass") | |
| if (sha256_file(root / "manifest.json") != marker["manifest_sha256"] | |
| or sha256_file(root / "reports/postwrite-verification.json") != marker["postwrite_report_sha256"]): | |
| raise ValueError("canonical promotion manifest/report hashes changed") | |
| manifest = json.loads((root / "manifest.json").read_text()) | |
| source_bundle = manifest["metadata"]["source_bundle"] | |
| snapshot = manifest["metadata"]["source_snapshot"] | |
| if not _source_snapshot_contents_match(snapshot, source_bundle): | |
| raise ValueError("pinned code snapshot integrity check failed") | |
| exported = export_sft(root, root, record_validator=validate_record_quality_v2, progress=print) | |
| native = native_streaming_verify(root, exported) | |
| code_dir = root / "code" | |
| if code_dir.exists(): | |
| raise FileExistsError(code_dir) | |
| with tarfile.open(root / "source_bundle_snapshot.tar.gz", "r:gz") as archive: | |
| archive.extractall(code_dir, filter="data") | |
| for entry in source_bundle["files"]: | |
| if sha256_file(code_dir / entry["logical_path"]) != entry["sha256"]: | |
| raise ValueError(f"extracted source differs from snapshot: {entry['logical_path']}") | |
| shutil.copyfile(code_dir / "LICENSE_DATA.md", root / "LICENSE_DATA.md") | |
| (root / "README.md").write_text(dataset_card(exported), encoding="utf-8") | |
| artifact_files = [] | |
| for path in sorted(root.rglob("*")): | |
| relative = path.relative_to(root) | |
| if not path.is_file() or any(part.startswith(".") for part in relative.parts): | |
| continue | |
| if "__pycache__" in relative.parts or path.name.endswith(".incomplete"): | |
| continue | |
| artifact_files.append({"path": relative.as_posix(), "bytes": path.stat().st_size, | |
| "sha256": sha256_file(path)}) | |
| result = { | |
| "release": "barbet-sft-v3", "records": exported["records"], | |
| "split_counts": exported["split_counts"], "verified": True, | |
| "checks": {"canonical_full_promotion": True, "explicit_owner_public_authorization": True, | |
| "sft_full_readback": exported["verified"], "native_full_streaming": native["verified"]}, | |
| "artifact_files": artifact_files, | |
| "public_access_is_not_additional_copyright_license": True, | |
| } | |
| write_json_atomic(root / "reports" / "release-verification.json", result) | |
| return result | |
| def publish(root: Path) -> dict: | |
| from huggingface_hub import HfApi | |
| from huggingface_hub.errors import RepositoryNotFoundError | |
| report = json.loads((root / "reports/release-verification.json").read_text()) | |
| mandatory_checks = {"canonical_full_promotion", "explicit_owner_public_authorization", | |
| "sft_full_readback", "native_full_streaming"} | |
| if (report.get("verified") is not True or report.get("records") != 1_000_000 | |
| or any(report.get("checks", {}).get(key) is not True for key in mandatory_checks)): | |
| raise ValueError("release did not pass full verification") | |
| paths = [] | |
| for item in report["artifact_files"]: | |
| path = root / item["path"] | |
| if path.stat().st_size != item["bytes"] or sha256_file(path) != item["sha256"]: | |
| raise ValueError(f"release artifact changed: {item['path']}") | |
| paths.append(item["path"]) | |
| paths.append("reports/release-verification.json") | |
| api = HfApi() | |
| config = json.loads((root / "config.snapshot.json").read_text()) | |
| expected_base = config["previous_release"]["revision"] | |
| receipt_path = root / "reports/upload-receipt.json" | |
| allowed_revisions = {expected_base} | |
| if receipt_path.exists(): | |
| receipt = json.loads(receipt_path.read_text()) | |
| if receipt.get("repo_id") != REPO: | |
| raise ValueError("upload receipt belongs to another repository") | |
| allowed_revisions.add(receipt["commit"]) | |
| try: | |
| existing = api.repo_info(REPO, repo_type="dataset") | |
| except RepositoryNotFoundError: | |
| existing = None | |
| if existing is None: | |
| original = api.repo_info(OLD_REPO, repo_type="dataset") | |
| if original.id != OLD_REPO or original.sha not in allowed_revisions: | |
| raise ValueError("original repository does not match explicit rename target") | |
| api.move_repo(from_id=OLD_REPO, to_id=REPO, repo_type="dataset") | |
| existing = api.repo_info(REPO, repo_type="dataset") | |
| elif existing.id != REPO: | |
| raise ValueError("unexpected repository redirect") | |
| else: | |
| original = api.repo_info(OLD_REPO, repo_type="dataset") | |
| if original.id != REPO: | |
| raise ValueError("barbet-sft is a separate existing repository, not the requested rename") | |
| if existing.sha not in allowed_revisions: | |
| raise ValueError("target repository has unexpected changes; refusing to overwrite") | |
| commit = api.upload_folder( | |
| repo_id=REPO, repo_type="dataset", folder_path=str(root), | |
| allow_patterns=paths, parent_commit=existing.sha, | |
| commit_message="Release reviewed Taiwan-centric Barbet SFT 1M with fixed-schema messages and full audits", | |
| ) | |
| write_json_atomic(receipt_path, {"repo_id": REPO, "commit": commit.oid}) | |
| remote = api.repo_info(REPO, repo_type="dataset", revision=commit.oid, files_metadata=True) | |
| remote_files = {file.rfilename: file for file in remote.siblings} | |
| for filename in paths: | |
| file = remote_files.get(filename) | |
| local = root / filename | |
| if file is None or file.size != local.stat().st_size: | |
| raise ValueError(f"remote file missing or size mismatch: {filename}") | |
| if file.lfs and file.lfs.sha256 != sha256_file(local): | |
| raise ValueError(f"remote LFS hash mismatch: {filename}") | |
| if not file.lfs: | |
| raw = local.read_bytes() | |
| digest = hashlib.sha1(f"blob {len(raw)}\0".encode() + raw).hexdigest() | |
| if file.blob_id != digest: | |
| raise ValueError(f"remote Git blob hash mismatch: {filename}") | |
| api.update_repo_settings(repo_id=REPO, repo_type="dataset", private=False, gated=False) | |
| anonymous = HfApi(token=False).repo_info(REPO, repo_type="dataset") | |
| if anonymous.private or anonymous.sha != commit.oid: | |
| raise ValueError("anonymous public verification failed or revision changed") | |
| from datasets import load_dataset | |
| anonymous_rows = {} | |
| export_report = json.loads((root / "reports/sft-export-verification.json").read_text()) | |
| for split in ("train", "validation", "test"): | |
| stream = load_dataset(REPO, name="sft", split=split, streaming=True, | |
| token=False, revision=commit.oid, | |
| cache_dir=str(root / ".anonymous-load-cache")) | |
| row = next(iter(stream)) | |
| expected = next(item for item in export_report["shards"] if item["split"] == split) | |
| if (row["record_id"] != expected["first_record_id"] or row["locale"] != "zh-TW" | |
| or not isinstance(row["messages"], list) | |
| or hashlib.sha256(canonical_json_v3(row["messages"]).encode()).hexdigest() != row["messages_sha256"]): | |
| raise ValueError(f"anonymous SFT loading failed: {split}") | |
| anonymous_rows[split] = row["record_id"] | |
| result = {"repo_id": REPO, "url": f"https://huggingface.co/datasets/{REPO}", | |
| "commit": commit.oid, "public": True, "anonymous_access": True, | |
| "verified_uploaded_files": len(paths), "anonymous_split_first_rows": anonymous_rows} | |
| write_json_atomic(root / "reports/remote-publication.json", result) | |
| return result | |
| def main() -> None: | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("command", choices=["build", "finalize", "publish"]) | |
| parser.add_argument("--config", default=str(PROJECT / "configs/barbet_sft.json")) | |
| parser.add_argument("--output", required=True) | |
| parser.add_argument("--workers", type=int, default=16) | |
| args = parser.parse_args() | |
| require_compute() | |
| root = Path(args.output).resolve() | |
| if args.command == "build": | |
| run_build_v2(config_path=args.config, output_root=root, workers=args.workers) | |
| result = finalize(root) | |
| elif args.command == "finalize": | |
| result = finalize(root) | |
| else: | |
| result = publish(root) | |
| print(json.dumps(result, ensure_ascii=False, indent=2), flush=True) | |
| if __name__ == "__main__": | |
| main() | |