File size: 11,128 Bytes
4a258e7 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 | #!/usr/bin/env python3
"""Reconcile exact source counts, global keys, and every remote bundle hash."""
import argparse
import json
import sqlite3
from collections import Counter
from datetime import datetime, timezone
from pathlib import Path
from huggingface_hub import HfApi, CommitOperationAdd, get_token
from convert_release import RECIPES, readme, status_document
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--dataset", choices=list(RECIPES), required=True)
parser.add_argument(
"--root", type=Path, default=Path("/root/bagpiper-sft-conversion/releases")
)
args = parser.parse_args()
recipe = RECIPES[args.dataset]
root = args.root / args.dataset
pinned = json.loads((root / "SOURCE_MANIFEST.json").read_text())
inventory = pinned["shards"]
connection = sqlite3.connect(root / "conversion.sqlite3")
records = [
json.loads(x[0])
for x in connection.execute(
"SELECT record FROM shards WHERE uploaded=1 ORDER BY path"
)
]
connection.close()
by_path = {r["source_path"]: r for r in records}
assert (
len(by_path) == len(records) == len(inventory)
), "Missing/duplicate source shards"
assert set(by_path) == {item["path"] for item in inventory}
for item in inventory:
r = by_path[item["path"]]
assert r["rows"] == item["rows"] and r["source_sha256"] == item["sha256"]
assert r["partition"] == item["partition"]
assert r["source_bytes"] == item["parquet_bytes"]
assert sum(r["rows"] for r in records) == sum(r["rows"] for r in inventory)
global_db = root / "global-validation.sqlite3"
target = sqlite3.connect(global_db)
target.execute("DROP TABLE IF EXISTS ids")
target.execute("DROP TABLE IF EXISTS audio")
target.execute("CREATE TABLE ids (row_id TEXT PRIMARY KEY,partition TEXT)")
target.execute(
"CREATE TABLE audio (partition TEXT,sha TEXT,suffix TEXT,size INTEGER,PRIMARY KEY(partition,sha))"
)
state_files = []
if (root / "STREAM_PLAN.json").exists():
state_files = [
root / f"conversion-{s['stream_id']}.sqlite3"
for s in json.loads((root / "STREAM_PLAN.json").read_text())
]
else:
state_files = list(root.glob("conversion-*.sqlite3"))
for source in state_files:
assert source.exists(), f"Missing conversion state: {source}"
target.execute("ATTACH DATABASE ? AS source", (str(source),))
assert not target.execute(
"SELECT 1 FROM source.rows s JOIN ids i USING(row_id) "
"WHERE s.partition != i.partition LIMIT 1"
).fetchone(), f"Conflicting row provenance: {source}"
assert not target.execute(
"SELECT 1 FROM source.audio s JOIN audio a USING(partition,sha) "
"WHERE s.suffix != a.suffix OR s.size != a.size LIMIT 1"
).fetchone(), f"Conflicting audio filename/size across streams: {source}"
for path, record in target.execute("SELECT path,record FROM source.shards"):
assert (
path in by_path and json.loads(record) == by_path[path]
), f"Conflicting source shard state: {source}:{path}"
target.execute(
"INSERT OR IGNORE INTO ids SELECT row_id,partition FROM source.rows"
)
target.execute(
"INSERT OR IGNORE INTO audio SELECT partition,sha,suffix,size FROM source.audio"
)
target.commit()
target.execute("DETACH DATABASE source")
unique_ids = target.execute("SELECT count(*) FROM ids").fetchone()[0]
assert unique_ids == sum(
r["rows"] for r in records
), "Duplicate/missing global row IDs"
expected_partitions = Counter()
for record in inventory:
expected_partitions[record["partition"]] += record["rows"]
assert dict(
target.execute("SELECT partition,count(*) FROM ids GROUP BY partition")
) == dict(expected_partitions), "Per-partition row count mismatch"
audio_count, audio_bytes = target.execute(
"SELECT count(*),sum(size) FROM audio"
).fetchone()
partitions = {
p: {"rows": rows, "unique_audio": count, "audio_bytes": bytes_}
for p, rows, count, bytes_ in target.execute(
"SELECT i.partition,i.rows,a.count,a.bytes FROM (SELECT partition,count(*) rows FROM ids GROUP BY partition) i JOIN (SELECT partition,count(*) count,sum(size) bytes FROM audio GROUP BY partition) a USING(partition)"
)
}
target.close()
api = HfApi(token=get_token())
revision = api.repo_info(recipe["target"], repo_type="dataset").sha
files = list(
api.list_repo_tree(
recipe["target"], repo_type="dataset", revision=revision, recursive=True
)
)
bundles = {
f.path: f for f in files if hasattr(f, "size") and f.path.endswith(".tar.zst")
}
assert set(bundles) == {
r["archive_path"] for r in records
}, "Missing/extra remote archives"
for r in records:
f = bundles[r["archive_path"]]
assert (
f.size == r["archive_bytes"] and f.lfs.sha256 == r["archive_sha256"]
), f"Hash mismatch: {f.path}"
audit = dict(
state="passed",
completed_at=datetime.now(timezone.utc).isoformat(),
source_repository=recipe["source"],
source_revision=pinned["revision"],
verified_remote_revision=revision,
source_shards=len(inventory),
verified_archive_files=len(bundles),
source_rows=sum(x["rows"] for x in inventory),
unique_row_ids=unique_ids,
unique_audio_files=audio_count,
unique_audio_bytes=audio_bytes,
partition_statistics=partitions,
audio_bytes_preserved=True,
text_and_role_order_preserved=True,
checks=[
"All source shard paths/counts/SHA256 match pinned inventory",
"All global row IDs reconciled across workers",
"Per-partition row counts match the source; repeated hashes have consistent filenames/sizes across streams",
"All remote archive sizes and LFS SHA256 match conversion records",
"Original embedded audio SHA256 checked for every converted row; repeated hashes reuse prior validated audio",
],
limitations=[
"No full GPU training or inference validation",
"Per-shard integrity plus source/audio hashes; remote archives are verified by LFS hash, not all redownloaded",
"Dataset terms and paper-v1/v2 selection unchanged",
],
)
audit_file = root / "RELEASE_VALIDATION.json"
audit_file.write_text(json.dumps(audit, indent=2) + "\n")
status = status_document(recipe, pinned["revision"], inventory, records, "complete")
status["unique_audio_files"] = audio_count
status["unique_audio_bytes"] = audio_bytes
status["unique_audio_count_scope"] = "partition_and_sha256"
status["archive_audio_entries"] = sum(r["unique_audio_added"] for r in records)
status["archive_audio_bytes"] = sum(r["unique_audio_bytes_added"] for r in records)
status["validation"] = "RELEASE_VALIDATION.json"
(root / "STATUS.json").write_text(json.dumps(status, indent=2) + "\n")
card = readme(recipe, pinned["revision"])
if args.dataset == "general":
card = card.replace(
"\nEach `.tar.zst`",
"\n**Source selection:** this preserves the public recipe-v1 pool (including "
"1,193,006 understanding rows). It does not reconstruct the paper-v2 filtered selection.\n\nEach `.tar.zst`",
1,
)
card = card.replace(
"**Check `STATUS.json`: the release is usable in full only when `state` is `complete`.** An explicit prefix trial is possible while conversion is in progress.",
f"**Complete:** all {unique_ids:,} source rows and {len(bundles):,} shards are converted and uploaded. "
"[RELEASE_VALIDATION.json](./RELEASE_VALIDATION.json) records the full source/count/hash reconciliation.",
)
table = "\n## Verified release counts\n\n| Partition | Preserved rows | Distinct audio files |\n| --- | ---: | ---: |\n"
for partition, stats in sorted(partitions.items()):
table += f"| {partition} | {stats['rows']:,} | {stats['unique_audio']:,} |\n"
table += (
"\nDistinct audio counts use `(partition, SHA256)` after reconciling all conversion streams. "
"Archives may contain repeated files across streams; verified extraction merges them. "
"Every original training row remains present.\n\n"
"[VALIDATION.json](./VALIDATION.json) covers 3,814 original-versus-converted sample rows "
"across all eight partitions and 24 decoded waveform comparisons using the actual ESPnet reader. "
"The full release additionally checks every input shard hash, every embedded audio hash, "
"all row IDs, and every uploaded archive's size and LFS SHA256. GPU training and inference "
"have not been validated. Use `prepare_espnet.py` for local paths and manifests; "
"these bundles are not directly loadable with `datasets.load_dataset`.\n"
)
card = card.replace(
"\n## Prepare local training inputs\n",
table + "\n## Prepare local training inputs\n",
)
card = card.replace(
"For a small prefix trial, add `--max-shards 2 --allow-incomplete`.",
"For a small prefix trial, add `--max-shards 2`.",
)
(root / "README.md").write_text(card)
operations = [
CommitOperationAdd(path_in_repo=name, path_or_fileobj=root / name)
for name in ["STATUS.json", "RELEASE_VALIDATION.json", "README.md"]
]
if (root / "STREAM_PLAN.json").exists():
operations.append(
CommitOperationAdd(
path_in_repo="STREAM_PLAN.json",
path_or_fileobj=root / "STREAM_PLAN.json",
)
)
for name in ["STREAM_PLAN.before-rebalance.json", "REBALANCE.json"]:
if (root / name).exists():
operations.append(
CommitOperationAdd(path_in_repo=name, path_or_fileobj=root / name)
)
scripts = Path(__file__).resolve().parent
for name in [
"prepare_espnet.py",
"convert_release.py",
"finalize_release.py",
"CONVERSION.md",
"VALIDATION.json",
"test_converter.py",
"validate_public_release.py",
"PUBLIC_DOWNLOAD_VALIDATION.json",
"rebalance_streams.py",
"link_source_release.py",
"commit_staged_release.py",
"recipe-preparation.patch",
]:
operations.append(
CommitOperationAdd(path_in_repo=name, path_or_fileobj=scripts / name)
)
commit = api.create_commit(
recipe["target"],
repo_type="dataset",
operations=operations,
commit_message=f"Finalize verified ESPnet release: {unique_ids} unique rows, {len(bundles)} archives",
)
print(json.dumps(dict(**audit, final_commit=commit.oid), indent=2))
if __name__ == "__main__":
main()
|