barbet-sft / release_tools /parallel_release.py
voidful's picture
Release reviewed Taiwan-centric Barbet SFT 1M with fixed-schema messages and full audits
0bf2389 verified
Raw History Blame Contribute Delete
25.5 kB
"""Additive parallel SFT export orchestrator; pinned core sources stay unchanged.
Each worker calls the original exporter, including full quality, language,
serialization and Parquet readback checks. The parent additionally verifies
global ID/source-group constraints and merges reports in canonical shard order.
Run full release work only in a Slurm allocation.
"""
from __future__ import annotations
import argparse
from collections import Counter
from concurrent.futures import ProcessPoolExecutor, as_completed
from dataclasses import dataclass
import hashlib
import inspect
import json
import multiprocessing
import os
from pathlib import Path
import shutil
import sqlite3
from typing import Any, Callable
from barbet_bgd.export_sft_v3 import EXPORT_VERSION, DEFAULT_SPLIT_COUNTS, export_sft as original_export_sft
from barbet_bgd.io import iter_jsonl_gz, sha256_file, write_json_atomic
from barbet_bgd.quality_v2 import validate_record_quality_v2
from barbet_bgd.release_v3 import native_streaming_verify as original_native_streaming_verify
from barbet_bgd.serializers_v3 import canonical_json_v3
WRAPPER_VERSION = "barbet.sft.parallel-release/1.0.0"
_SOURCE = Path(__file__).resolve()
@dataclass(frozen=True)
class Task:
index: int
canonical_path: str
quality_path: str
work_root: str
records: int
split: str
batch_rows: int
batch_bytes: int
validate_records: bool
@dataclass(frozen=True)
class NativeTask:
index: int
source_root: str
work_root: str
shard: dict[str, Any]
def _worker(task: Task) -> dict[str, Any]:
import pyarrow as pa
pa.set_cpu_count(1)
pa.set_io_thread_count(1)
canonical_path, quality_path = Path(task.canonical_path), Path(task.quality_path)
work = Path(task.work_root)
(work / "canonical").mkdir(parents=True, exist_ok=False)
(work / "quality" / "verdicts").mkdir(parents=True, exist_ok=False)
os.link(canonical_path, work / "canonical" / canonical_path.name)
os.link(quality_path, work / "quality" / "verdicts" / quality_path.name)
report = original_export_sft(
work, work, expected_records=task.records, expected_split_counts={task.split: task.records},
record_validator=validate_record_quality_v2 if task.validate_records else None,
batch_rows=task.batch_rows, batch_bytes=task.batch_bytes,
)
return {"index": task.index, "work_root": str(work), "report": report,
"taiwan": json.loads((work / "reports" / "taiwan-usage.json").read_text(encoding="utf-8"))}
def _native_worker(task: NativeTask) -> dict[str, Any]:
import pyarrow as pa
pa.set_cpu_count(1)
pa.set_io_thread_count(1)
source, work = Path(task.source_root), Path(task.work_root)
path = Path(task.shard["path"])
if path.is_absolute() or ".." in path.parts:
raise ValueError("invalid native shard path")
if sha256_file(source / path) != task.shard["parquet_sha256"]:
raise ValueError("native input Parquet hash mismatch")
(work / path.parent).mkdir(parents=True, exist_ok=False)
os.link(source / path, work / path)
report = original_native_streaming_verify(work, {
"shards": [task.shard], "split_counts": {task.shard["split"]: task.shard["records"]},
})
if sha256_file(work / path) != task.shard["parquet_sha256"]:
raise ValueError("native input Parquet changed during verification")
return {"index": task.index, "work_root": str(work), "report": report}
def parallel_native_streaming_verify(root: Path, report: dict, *, workers: int = 32,
progress: Callable[[str], None] | None = print) -> dict:
if not os.environ.get("SLURM_JOB_ID"):
raise RuntimeError("parallel native verification requires a Slurm allocation")
allocated = int(os.environ.get("SLURM_CPUS_PER_TASK", workers))
if workers < 1 or workers > min(32, allocated):
raise ValueError("invalid native worker count or Slurm allocation")
root = Path(root).resolve()
work_root = root / ".parallel-native-verification"
output_path = root / "reports/native-streaming-verification.json"
if work_root.exists() or output_path.exists():
raise FileExistsError("refusing to overwrite existing or partial native verification")
shards = report["shards"]
if not shards or len({item["path"] for item in shards}) != len(shards):
raise ValueError("native shard coverage is empty or contains duplicate paths")
if report.get("verified") is not True or sum(item["records"] for item in shards) != report["records"]:
raise ValueError("native verification requires complete verified export")
work_root.mkdir(exist_ok=False)
wrapper_hash, core_hash = sha256_file(_SOURCE), sha256_file(inspect.getfile(original_native_streaming_verify))
tasks = [NativeTask(index, str(root), str(work_root / f"shard-{index:05d}"), shard)
for index, shard in enumerate(shards)]
completed = {}
with ProcessPoolExecutor(max_workers=workers, mp_context=multiprocessing.get_context("spawn")) as executor:
futures = {executor.submit(_native_worker, task): task.index for task in tasks}
for future in as_completed(futures):
result = future.result()
if result["index"] in completed:
raise ValueError("duplicate native worker result")
completed[result["index"]] = result
if progress:
done = sum(item["report"]["records"] for item in completed.values())
progress(f"Parallel native datasets verified {len(completed)}/{len(tasks)} shards; {done} records")
if (set(completed) != set(range(len(tasks))) or sha256_file(_SOURCE) != wrapper_hash
or sha256_file(inspect.getfile(original_native_streaming_verify)) != core_hash):
raise ValueError("native worker coverage incomplete or source changed")
counts, merged_shards, pins = Counter(), [], []
datasets_version = None
for task in tasks:
result = completed[task.index]
worker = result["report"]
shard = task.shard
expected = {"path": shard["path"], "records": shard["records"], "rows_sha256": shard["rows_sha256"]}
if (worker.get("verified") is not True or worker.get("records") != shard["records"]
or worker.get("shards") != [expected]
or worker.get("split_counts") != {shard["split"]: shard["records"]}):
raise ValueError("native worker digest/count/split mismatch")
if datasets_version is None:
datasets_version = worker["datasets_version"]
elif datasets_version != worker["datasets_version"]:
raise ValueError("native workers used different datasets versions")
if sha256_file(root / shard["path"]) != shard["parquet_sha256"]:
raise ValueError("global Parquet changed after native verification")
source_path = Path(result["work_root"]) / "reports/native-streaming-verification.json"
if canonical_json_v3(json.loads(source_path.read_text(encoding="utf-8"))) != canonical_json_v3(worker):
raise ValueError("native worker report changed")
destination = root / "reports/parallel-workers" / f"shard-{task.index:05d}" / "native-streaming-verification.json"
destination.parent.mkdir(parents=True, exist_ok=True)
if destination.exists():
raise FileExistsError("refusing to overwrite native worker report")
shutil.copyfile(source_path, destination)
pins.append({"path": destination.relative_to(root).as_posix(), "sha256": sha256_file(destination)})
counts.update(worker["split_counts"])
merged_shards.append(expected)
if dict(counts) != report["split_counts"] or sum(counts.values()) != report["records"]:
raise ValueError("native global count/split coverage mismatch")
merged = {"verified": True, "records": sum(counts.values()), "split_counts": dict(counts),
"shards": merged_shards, "datasets_version": datasets_version,
"parallel_provenance": {
"orchestrator_version": WRAPPER_VERSION, "orchestrator_sha256": wrapper_hash,
"core_native_verifier_sha256": core_hash, "workers": workers,
"slurm_job_id": os.environ["SLURM_JOB_ID"], "worker_report_pins": pins,
"core_sources_modified": False,
}}
write_json_atomic(output_path, merged)
return merged
def _inspect_shards(source: Path, canonical_dir: Path, quality_dir: Path,
expected_records: int, expected_split_counts: dict[str, int],
shard_size: int | None) -> list[tuple[Path, Path, int, str]]:
files = sorted(canonical_dir.glob("part-*.jsonl.gz"))
if not files:
raise ValueError("No canonical shards found")
expected_quality = {quality_dir / path.name.replace(".jsonl.gz", ".quality.jsonl.gz") for path in files}
if set(quality_dir.glob("part-*.quality.jsonl.gz")) != expected_quality:
raise ValueError("canonical/quality shard sets do not match")
# Production uses the builder's complete manifest for exact per-shard row
# counts. A bounded test may explicitly provide a fixed shard size instead.
manifest_path = source / "manifest.json"
manifest_shards: dict[str, dict] = {}
if manifest_path.is_file():
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
for item in manifest.get("shards", []):
name = Path(item["canonical_path"]).name
if name in manifest_shards:
raise ValueError("duplicate manifest canonical shard")
manifest_shards[name] = item
if set(manifest_shards) != {path.name for path in files}:
raise ValueError("manifest/canonical shard sets do not match")
elif shard_size is None:
raise ValueError("production export requires the canonical build manifest")
results = []
counts: Counter = Counter()
remaining = expected_records
for path in files:
quality = quality_dir / path.name.replace(".jsonl.gz", ".quality.jsonl.gz")
first = next(iter_jsonl_gz(path), None)
if first is None or first.get("split") not in DEFAULT_SPLIT_COUNTS:
raise ValueError("empty shard or invalid first-row split")
split = first["split"]
records = manifest_shards[path.name]["records"] if manifest_shards else min(shard_size, remaining)
if not isinstance(records, int) or records <= 0:
raise ValueError("invalid shard record count")
if manifest_shards:
item = manifest_shards[path.name]
# Use hashes from the trusted build manifest when provided.
for key, target in (("canonical_sha256", path), ("verdict_sha256", quality)):
if key in item and sha256_file(target) != item[key]:
raise ValueError(f"manifest source hash mismatch: {target.name}")
remaining -= records
counts[split] += records
results.append((path, quality, records, split))
if remaining or dict(counts) != {key: value for key, value in expected_split_counts.items() if value}:
raise ValueError("manifest shard counts do not match expected total/splits")
return results
def _merge_taiwan(results: list[dict[str, Any]], total: int, expected_serializers: set[str]) -> dict[str, Any]:
decisions, findings = Counter(), Counter()
examples: dict[str, list] = {}
templates: dict[str, dict] = {}
records = readback = 0
static = None
for result in results:
report = result["taiwan"]
if report.get("passed") is not True or report.get("independent_readback_identical") is not True:
raise ValueError("worker Taiwan usage audit not passed")
current_static = {key: report[key] for key in ("ruleset_version", "limitations", "reference_sources", "human_reviewed")}
if static is None:
static = current_static
elif canonical_json_v3(static) != canonical_json_v3(current_static):
raise ValueError("worker Taiwan usage static rules differ")
records += report["records"]
readback += report["readback_records"]
decisions.update(report["decision_counts"])
findings.update(report["finding_counts"])
for rule, candidates in report["examples"].items():
selected = examples.setdefault(rule, [])
selected.extend(candidates[:max(0, 3 - len(selected))])
for serializer, template in report["rendering_templates"].items():
if serializer in templates and canonical_json_v3(templates[serializer]) != canonical_json_v3(template):
raise ValueError("worker rendering templates differ")
templates[serializer] = template
if (records != total or readback != total or sum(decisions.values()) != total
or decisions.get("PASS", 0) != total or decisions.get("REJECT", 0) or decisions.get("REVIEW", 0)):
raise ValueError("merged Taiwan usage counts did not pass")
if set(templates) != expected_serializers:
raise ValueError("Taiwan usage rendering template coverage differs from exported serializers")
if total == 1_000_000 and set(templates) != {"JSON", "FUNCTION_CALL", "COMPACT_TAGS", "KEY_VALUE"}:
raise ValueError("full release requires all four audited rendering templates")
return {**static, "records": records, "readback_records": readback, "passed": True,
"independent_readback_identical": True, "decision_counts": dict(decisions),
"finding_counts": dict(findings), "examples": examples, "rendering_templates": templates}
def parallel_export_sft(
canonical_root: str | Path, output_root: str | Path, *, quality_root: str | Path | None = None,
expected_records: int = 1_000_000, expected_split_counts: dict[str, int] | None = None,
record_validator: Callable | None = None, batch_rows: int = 32, batch_bytes: int = 8 * 1024 * 1024,
progress: Callable[[str], None] | None = None, workers: int = 32, shard_size: int | None = None,
) -> dict[str, Any]:
if not os.environ.get("SLURM_JOB_ID"):
raise RuntimeError("parallel release export requires a Slurm allocation")
if workers < 1 or workers > 32:
raise ValueError("workers must be between 1 and 32")
allocated = int(os.environ.get("SLURM_CPUS_PER_TASK", workers))
if workers > allocated:
raise ValueError("worker count exceeds Slurm CPU allocation")
import pyarrow as pa
pa.set_cpu_count(1)
pa.set_io_thread_count(1)
# Only this audited, importable validator is accepted across processes.
if record_validator not in (None, validate_record_quality_v2):
raise ValueError("unsupported worker record_validator")
split_targets = dict(DEFAULT_SPLIT_COUNTS if expected_split_counts is None else expected_split_counts)
if expected_records <= 0 or sum(split_targets.values()) != expected_records:
raise ValueError("invalid expected record/split counts")
source, output = Path(canonical_root).resolve(), Path(output_root).resolve()
canonical_dir = source / "canonical" if (source / "canonical").is_dir() else source
quality_dir = Path(quality_root).resolve() if quality_root else source / "quality" / "verdicts"
data_dir, work_root = output / "data", output / ".parallel-sft-export"
report_path, taiwan_path = output / "reports/sft-export-verification.json", output / "reports/taiwan-usage.json"
if any(path.exists() for path in (data_dir, work_root, report_path, taiwan_path)):
raise FileExistsError("refusing to overwrite an existing or partial parallel SFT export")
source_shards = _inspect_shards(source, canonical_dir, quality_dir, expected_records, split_targets, shard_size)
data_dir.mkdir(parents=True, exist_ok=False)
work_root.mkdir(exist_ok=False)
wrapper_hash = sha256_file(_SOURCE)
core_hash = sha256_file(inspect.getfile(original_export_sft))
tasks = [Task(index, str(canonical), str(quality), str(work_root / f"shard-{index:05d}"),
count, split, batch_rows, batch_bytes, record_validator is not None)
for index, (canonical, quality, count, split) in enumerate(source_shards)]
completed: dict[int, dict[str, Any]] = {}
with ProcessPoolExecutor(max_workers=workers, mp_context=multiprocessing.get_context("spawn")) as executor:
futures = {executor.submit(_worker, task): task.index for task in tasks}
for future in as_completed(futures):
result = future.result()
if result["index"] in completed:
raise ValueError("duplicate parallel worker result")
completed[result["index"]] = result
if progress:
done = sum(item["report"]["records"] for item in completed.values())
progress(f"Parallel SFT verified {len(completed)}/{len(tasks)} shards; {done} records")
if (set(completed) != set(range(len(tasks))) or sha256_file(_SOURCE) != wrapper_hash
or sha256_file(inspect.getfile(original_export_sft)) != core_hash):
raise ValueError("worker coverage incomplete or wrapper source changed")
ordered = [completed[index] for index in range(len(tasks))]
reference = ordered[0]["report"]
checks, static_fields = reference["checks"], ("export_version", "messages_version", "pyarrow_version", "schema", "independent_record_validator")
counts, serializers, families = Counter(), Counter(), Counter()
merged_shards = []
sqlite_path = work_root / "global-validation.sqlite"
connection = sqlite3.connect(sqlite_path)
connection.execute("PRAGMA cache_size=-8192")
connection.execute("PRAGMA temp_store=FILE")
connection.execute("CREATE TABLE ids (record_id TEXT PRIMARY KEY) WITHOUT ROWID")
connection.execute("CREATE TABLE groups (source_group TEXT PRIMARY KEY, split TEXT NOT NULL) WITHOUT ROWID")
import pyarrow.parquet as pq
global_rows = 0
worker_report_pins = []
try:
for task, result in zip(tasks, ordered, strict=True):
report, work = result["report"], Path(result["work_root"])
if report.get("verified") is not True or not report["checks"] or not all(value is True for value in report["checks"].values()):
raise ValueError("worker export report did not pass")
if set(report["checks"]) != set(checks):
raise ValueError("worker check schemas differ")
for name in static_fields:
if report[name] != reference[name]:
raise ValueError(f"worker export static metadata differs: {name}")
if len(report["shards"]) != 1 or report["records"] != task.records or report["readback_records"] != task.records:
raise ValueError("worker shard coverage mismatch")
original_info = report["shards"][0]
original_path = work / original_info["path"]
if original_info["split"] != task.split or report["split_counts"] != {task.split: task.records}:
raise ValueError("worker split mismatch")
if sha256_file(original_path) != original_info["parquet_sha256"]:
raise ValueError("worker Parquet changed after verification")
if sha256_file(task.canonical_path) != original_info["canonical_sha256"] or sha256_file(task.quality_path) != original_info["quality_sha256"]:
raise ValueError("canonical/quality changed after worker verification")
destination = data_dir / f"{task.split}-{task.index:05d}.parquet"
os.link(original_path, destination)
local_rows = 0
for batch in pq.ParquetFile(destination).iter_batches(batch_size=2048, columns=["record_id", "source_group", "split"]):
for row in batch.to_pylist():
if row["split"] != task.split:
raise ValueError("global readback split mismatch")
try:
connection.execute("INSERT INTO ids VALUES (?)", (row["record_id"],))
except sqlite3.IntegrityError as error:
raise ValueError(f"duplicate global record_id: {row['record_id']}") from error
previous = connection.execute("SELECT split FROM groups WHERE source_group=?", (row["source_group"],)).fetchone()
if previous is None:
connection.execute("INSERT INTO groups VALUES (?,?)", (row["source_group"], row["split"]))
elif previous[0] != row["split"]:
raise ValueError(f"global source_group crosses splits: {row['source_group']}")
local_rows += 1
if local_rows != task.records or sha256_file(destination) != original_info["parquet_sha256"]:
raise ValueError("global readback row count or Parquet hash mismatch")
global_rows += local_rows
connection.commit()
counts.update(report["split_counts"])
serializers.update(report["serializer_counts"])
families.update(report["task_family_counts"])
merged_shards.append({**original_info, "path": destination.relative_to(output).as_posix()})
for name in ("sft-export-verification.json", "taiwan-usage.json"):
path = work / "reports" / name
expected = report if name.startswith("sft-") else result["taiwan"]
if canonical_json_v3(json.loads(path.read_text(encoding="utf-8"))) != canonical_json_v3(expected):
raise ValueError("worker report changed during aggregation")
public_path = output / "reports" / "parallel-workers" / f"shard-{task.index:05d}" / name
public_path.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(path, public_path)
worker_report_pins.append({"path": public_path.relative_to(output).as_posix(),
"sha256": sha256_file(public_path),
"global_parquet_path": destination.relative_to(output).as_posix()})
unique_ids = connection.execute("SELECT count(*) FROM ids").fetchone()[0]
source_groups = connection.execute("SELECT count(*) FROM groups").fetchone()[0]
finally:
connection.close()
if global_rows != expected_records or unique_ids != expected_records or dict(counts) != {key: value for key, value in split_targets.items() if value}:
raise ValueError("global total/ID/split counts failed")
taiwan = _merge_taiwan(ordered, expected_records, set(serializers))
write_json_atomic(taiwan_path, taiwan)
provenance = {
"orchestrator_version": WRAPPER_VERSION, "orchestrator_sha256": wrapper_hash,
"core_exporter_sha256": core_hash,
"workers": workers, "slurm_job_id": os.environ["SLURM_JOB_ID"],
"core_sources_modified": False, "worker_report_pins": worker_report_pins,
"global_record_identity_rows_verified": global_rows,
}
merged = {
**{name: reference[name] for name in static_fields},
"records": expected_records, "readback_records": expected_records,
"unique_record_ids": unique_ids, "source_groups": source_groups,
"split_counts": dict(counts), "serializer_counts": dict(serializers),
"task_family_counts": dict(families), "shards": merged_shards,
"taiwan_usage_report": taiwan_path.relative_to(output).as_posix(),
"taiwan_usage_report_sha256": sha256_file(taiwan_path),
"checks": {**checks, "parallel_worker_reports_verified": True,
"global_cross_shard_identity_verified": True},
"verified": True, "parallel_provenance": provenance,
}
write_json_atomic(output / "reports/parallel-export-provenance.json", provenance)
write_json_atomic(report_path, merged)
return merged
def finalize_parallel(root: Path, workers: int) -> dict[str, Any]:
from barbet_bgd import release_v3
release_v3.require_compute()
tools_dir = root / "release_tools"
tools_dir.mkdir(exist_ok=False)
shutil.copyfile(_SOURCE, tools_dir / _SOURCE.name)
tooling = {"version": WRAPPER_VERSION, "path": "release_tools/" + _SOURCE.name,
"sha256": sha256_file(_SOURCE), "original_source_snapshot_unchanged": True}
write_json_atomic(tools_dir / "manifest.json", tooling)
def configured_export(*args, **kwargs):
return parallel_export_sft(*args, **kwargs, workers=workers)
def configured_native(*args, **kwargs):
return parallel_native_streaming_verify(*args, **kwargs, workers=workers)
release_v3.export_sft = configured_export
release_v3.native_streaming_verify = configured_native
report = release_v3.finalize(root)
report["parallel_orchestrator"] = tooling
write_json_atomic(root / "reports/release-verification.json", report)
return report
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("command", choices=["finalize"])
parser.add_argument("--output", type=Path, required=True)
parser.add_argument("--workers", type=int, default=32)
args = parser.parse_args()
result = finalize_parallel(args.output.resolve(), args.workers)
print(json.dumps(result, ensure_ascii=False, indent=2), flush=True)
if __name__ == "__main__":
main()