sileod's picture
Clean vision prompt artifacts and fill original dataset license evidence
9a2996d verified
Raw History Blame Contribute Delete
12.7 kB
"""Repair the pinned vision release without reloading upstream image sources.
Local inputs are the materialized base and append builds recorded in the parent
release. Without those caches, load the pinned Hub config and separate its
original and appended rows using the published split counts.
"""
import copy
import hashlib
import json
import re
import subprocess
import sys
from collections import Counter
from pathlib import Path
import pyarrow as pa
import pyarrow.parquet as pq
import yaml
from datasets import Dataset, DatasetDict, load_dataset, load_from_disk, disable_progress_bars
from huggingface_hub import HfApi, hf_hub_download, DatasetCard, CommitOperationAdd
from scripts.build_jev_dataset import example_key, validate_decisions
from tasksource.licenses import source_license, provenance_repos
from tasksource.vision_tasks import clean_cauldron_question
ROOT = Path('build/vision-prompt-license-repair')
REPO = 'tasksource/tasksource-jev-typed-decisions'
PARENT = '94c2ebb18662a11f9d362f9f469aa13599e6f2dd'
BASE = Path('build/vision-expanded-5000/dataset')
ADD = Path('build/vision-append-release/additions/dataset')
disable_progress_bars()
def dump(path, value):
path.write_text(json.dumps(value, indent=2, ensure_ascii=False) + '\n')
def remote(name):
return Path(hf_hub_download(REPO, name, repo_type='dataset', revision=PARENT))
def stage():
api = HfApi()
info = api.dataset_info(REPO, files_metadata=True)
assert info.sha == PARENT, 'Review new Hub parent before repairing'
sizes = {f.rfilename: f.size for f in info.siblings}
if BASE.exists() and ADD.exists():
original = load_from_disk(str(BASE))
additions = load_from_disk(str(ADD))
else:
published = load_dataset(REPO, 'vision', revision=PARENT)
base_counts = {'train': 60097, 'validation': 375, 'test': 175}
original = DatasetDict({s: rows.select(range(base_counts[s])) for s, rows in published.items()})
additions = DatasetDict({s: rows.select(range(base_counts[s], len(rows))) for s, rows in published.items()})
train = original['train']
fields = ['state', 'metadata', 'license', 'license_use', 'id', 'group_id', 'question_id', 'example_id']
replacements = {key: [] for key in fields}
prompt_counts, license_counts, duplicates = Counter(), Counter(), Counter()
seen, kept = {}, []
evidence = {}
for index, row in enumerate(train.select_columns([k for k in train.column_names if k != 'images'])):
metadata = json.loads(row['metadata'])
state = clean_cauldron_question(row['state']) if metadata.get('source_question') else row['state']
old_license = metadata['licenses']
new_license = source_license(row['source'], provenance_repos(metadata['provenance']),
old_license.get('card_licenses', {}))
# Only incorporate newly reviewed original-source evidence, retaining all
# other source classifications exactly as published.
if 'source_license_evidence' not in new_license:
new_license = old_license
evidence[row['source']] = new_license
changed_state = state != row['state']
changed_license = new_license != old_license
if changed_state or changed_license:
metadata['export_repair'] = {'version': 1, 'parent_revision': PARENT, 'previous_id': row['id']}
if changed_license:
metadata['licenses'] = new_license
row.update({key: new_license[key] for key in ('license', 'license_use')})
license_counts[row['source']] += 1
if changed_state:
prompt_counts[row['source']] += 1
images = metadata['image_ids']
image_id = hashlib.sha256('\x1f'.join(images).encode()).hexdigest()[:24]
row['state'] = state
row['group_id'] = f"{row['source']}:train:{image_id}:{hashlib.sha256(state.encode()).hexdigest()[:16]}"
decision = json.dumps([state, row['question'], row['options']], ensure_ascii=False)
row['question_id'] = hashlib.sha256(decision.encode()).hexdigest()[:24]
row['id'] = row['group_id'] + ':' + row['question_id']
row['example_id'] = hashlib.sha256(('\x1f'.join(images) + example_key(
row['source'], state, row['options'], row['target'])).encode()).hexdigest()[:24]
key = (row['source'], tuple(metadata['image_ids']), state, row['question'], tuple(row['options']))
if key in seen:
assert row['target'] == seen[key], 'Conflicting native targets after cleanup'
duplicates[row['source']] += 1
else:
kept.append(index)
seen[key] = row['target']
row['metadata'] = json.dumps(metadata, ensure_ascii=False, sort_keys=True) if changed_state or changed_license else row['metadata']
for field in fields:
replacements[field].append(row[field])
table = train.data.table
for field, values in replacements.items():
table = table.set_column(table.schema.get_field_index(field), table.schema.field(field),
pa.array(values, type=table.schema.field(field).type))
fingerprint = hashlib.sha256((PARENT + Path(__file__).read_text()).encode()).hexdigest()
patched = Dataset(table, info=copy.deepcopy(train.info), fingerprint=fingerprint).select(kept)
validate_decisions(patched, 'train')
assert len(set(patched['id'])) == len(patched)
files = []
patched_bytes = 0
names = sorted(name for name in sizes if re.fullmatch(r'vision/train-\d{5}-of-\d{5}\.parquet', name))
assert len(names) == 36 and len(train) == 60097
for i, name in enumerate(names):
part = patched.shard(len(names), i, contiguous=True)
path = ROOT / Path(name).name
part.to_parquet(path)
# Compare serialized image payloads and gold decisions, with no image
# decoding or re-encoding. Only explicit repair fields can change.
expected = part.with_format('arrow')[:]
patched_bytes += expected.nbytes
restored = pq.read_table(path)
for field in part.column_names:
assert restored[field].equals(expected[field]), (name, field)
files.append({'local': str(path), 'remote': name, 'bytes': path.stat().st_size,
'sha256': hashlib.sha256(path.read_bytes()).hexdigest()})
print(f"staged {i+1}/{len(names)} {path.name}", flush=True)
release = json.loads(remote('vision/release-audit.json').read_text())
sources = yaml.safe_load(remote('vision/sources.yaml').read_text())
for source, license_info in evidence.items():
sources['sources'][source].update(license_info)
report = {'parent_revision': PARENT, 'prompt_suffixes_removed': dict(prompt_counts),
'license_evidence_filled': dict(license_counts), 'identical_requests_deduplicated': dict(duplicates),
'truncated_answer_should_be_states': 0,
'checks': ['every written Parquet column round-tripped exactly',
'image bytes, ordering, options and gold targets preserved for retained rows',
'deduplicated requests have identical native targets', 'unique repaired decision IDs'],
'license_policy': {'allowed_uses': ['commercial', 'non-commercial', 'unspecified'],
'note': 'Mixed-license scope retained; unspecified is not permission.'}, 'splits': {}}
for split in release['splits']:
parts = [patched if split == 'train' else original[split], additions[split]]
counts, families, uses = Counter(), Counter(), Counter()
for part in parts:
for row in part.select_columns(['source', 'license_use', 'state']):
assert not row['state'].rstrip().endswith('Your answer should be')
counts[row['source']] += 1
families['/'.join(row['source'].split('/')[:2])] += 1
uses[row['license_use']] += 1
summary = {'rows': sum(counts.values()), 'sources': dict(counts),
'families': dict(families), 'license_use': dict(uses)}
release['splits'][split] = summary
report['splits'][split] = {'rows': summary['rows'], 'license_use': dict(uses)}
for source, count in counts.items():
sources['sources'][source]['rows'][split] = count
release['repair'] = report
dump(ROOT / 'release-audit.json', release)
dump(ROOT / 'repair-audit.json', report)
sources['parent_tasksource_commit'] = sources['tasksource_commit']
sources['tasksource_commit'] = subprocess.check_output(['git', 'rev-parse', 'HEAD'], text=True).strip()
(ROOT / 'sources.yaml').write_text(yaml.safe_dump(sources, sort_keys=False))
manifest = {'operation': 'exact source-prompt cleanup and reviewed original-license evidence',
'parent_revision': PARENT, 'tasksource_commit': sources['tasksource_commit'],
'operation_script_sha256': hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
'license_policy': report['license_policy'], 'files': files,
'parent_manifest': json.loads(remote('vision/build-manifest.json').read_text())}
dump(ROOT / 'build-manifest.json', manifest)
quality = json.loads(remote('vision/quality-audit.json').read_text())
quality['repair_audit'] = report
dump(ROOT / 'quality-audit.json', quality)
card = DatasetCard.load(remote('README.md'))
vision = next(entry for entry in card.data.dataset_info if entry['config_name'] == 'vision')
stat = next(entry for entry in vision['splits'] if entry['name'] == 'train')
stat['num_examples'] = release['splits']['train']['rows']
stat['num_bytes'] += patched_bytes - train.data.nbytes
vision['dataset_size'] = sum(entry['num_bytes'] for entry in vision['splits'])
vision['download_size'] += sum(f['bytes'] - sizes[f['remote']] for f in files)
card.text = card.text.replace('66,097 train', '66,085 train')
card.text += '''\n### Vision prompt and license correction (2026-10-09)
Known Cauldron answer-style suffixes were removed from 18,353 training rows;
complete original questions remain in metadata. Twelve identical MapQA requests
with identical gold answers were deduplicated. Images and retained gold targets
are unchanged. There are **66,085 train, 972 validation and 475 test** decisions.
Original dataset terms for [CLEVR](https://cs.stanford.edu/people/jcjohns/clevr/),
[MapQA](https://github.com/OSU-slatelab/MapQA/blob/main/license), and
[TQA](https://registry.opendata.aws/allenai-tqa/) fill missing Hub-card evidence.
Training license-use counts are **26,987 commercial, 7,000 non-commercial, and
32,098 unspecified**. This remains a **mixed-license research pilot**, not a
commercial-cleared dataset. Unspecified does not grant permission. NLVR2 photo
rights and other unresolved sources remain unresolved; repository software
licenses do not establish image rights. LVIS/COCO classification conservatively
reflects the NC images included in their source mirrors.
Filter `license_use` when loading; new Tasksource vision builds also accept
`--license-use commercial` to exclude unresolved/NC sources before loading them.
See [repair-audit.json](vision/repair-audit.json) and the reproducible
[repair script](vision/repair.py); both record the pinned parent release.
'''
card.save(ROOT / 'README.md')
dump(ROOT / 'staged.json', {'parent': PARENT, 'files': files})
print(json.dumps(report, indent=2), flush=True)
def publish():
api = HfApi()
staged = json.loads((ROOT / 'staged.json').read_text())
assert api.dataset_info(REPO).sha == PARENT, 'Hub changed since staging'
operations = [CommitOperationAdd(path_in_repo=f['remote'], path_or_fileobj=f['local']) for f in staged['files']]
for name in ('release-audit.json', 'repair-audit.json', 'sources.yaml', 'build-manifest.json', 'quality-audit.json', 'repair.py'):
operations.append(CommitOperationAdd(path_in_repo='vision/' + name, path_or_fileobj=str(ROOT / name)))
operations.append(CommitOperationAdd(path_in_repo='README.md', path_or_fileobj=str(ROOT / 'README.md')))
result = api.create_commit(REPO, repo_type='dataset', parent_commit=PARENT, operations=operations,
commit_message='Clean vision prompt artifacts and fill original dataset license evidence')
dump(ROOT / 'published.json', {'revision': result.oid, 'url': result.commit_url})
print(result.commit_url, flush=True)
if __name__ == '__main__':
publish() if '--publish' in sys.argv else stage()