File size: 8,544 Bytes
be1fcdc
 
 
 
 
 
 
 
d7d73ca
be1fcdc
 
 
 
 
 
 
 
 
 
 
 
 
9b74a49
 
 
be1fcdc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b74a49
 
 
be1fcdc
9b74a49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
be1fcdc
9b74a49
 
 
be1fcdc
9b74a49
 
 
be1fcdc
 
9b74a49
be1fcdc
9b74a49
 
 
 
be1fcdc
 
 
9b74a49
be1fcdc
9b74a49
 
be1fcdc
9b74a49
 
be1fcdc
9b74a49
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
import argparse, collections, hashlib, json, re, struct, zlib
if not __debug__: raise RuntimeError('Validation requires Python assertions enabled')
from pathlib import Path
import pyarrow.parquet as pq
import pyarrow as pa
from datasets import Features, Image as HFImage
from PIL import Image
COUNTS={'train':25987,'validation':2589,'test':2731}
COLUMNS=['id', 'drawing_id', 'image', 'split', 'question', 'answer', 'difficulty', 'family', 'hop_count', 'reasoning_family', 'operation_types', 'branch_count', 'symbolic_trace', 'visible_facts', 'quality_grade', 'layout_id', 'reasoning_text', 'display_answer', 'answer_text', 'core_benchmark_eligible', 'training_eligible']
FORBIDDEN=['global_'+'qa_id','candidate_'+'id','source_'+'pdf','qa_'+'id']
HOPS={1:158,2:1390,3:152,4:458,5:395,6:89,7:58,9:20,13:11}
HARD={'hard_compare_then_component':89,'hard_compare_then_quantity':89,'hard_dual_traverse_quantity_compare':58,'hard_filter_quantity_then_diameter':31}
PATTERN=re.compile(r'/work' r'space/|/m' r'nt/|(?<![A-Za-z0-9])[A-Za-z]:[\\/]|SW_AUTO_' r'DRAWING|\bsk' r'-[A-Za-z0-9]{8,}|\bhf' r'_[A-Za-z0-9]{8,}|(?:checkpoint|server)[_-](?:path|name)\s*[:=]')

FAMILY_MAPPING = {'hard_compare_then_component': 'C1', 'hard_compare_then_quantity': 'C2', 'hard_dual_traverse_quantity_compare': 'C3', 'hard_filter_quantity_then_diameter': 'C4'}
FAMILY_COUNTS = {'train': {'Standard': 23773, 'C1': 1071, 'C2': 1071, 'C3': 51, 'C4': 21}, 'validation': {'Standard': 2345, 'C1': 79, 'C2': 79, 'C3': 66, 'C4': 20}, 'test': {'Standard': 2464, 'C1': 89, 'C2': 89, 'C3': 58, 'C4': 31}}
def check_taxonomy_row(row):
 family=FAMILY_MAPPING.get(row['reasoning_family'],'Standard')
 assert row['family']==family
 assert row['difficulty']==('Standard' if family=='Standard' else 'Hard')
def check_image_entry(value,drawing_id):
 assert isinstance(value,dict) and set(value)=={'bytes','path'}
 assert isinstance(value['bytes'],bytes) and value['bytes'].startswith(b'\x89PNG\r\n\x1a\n')
 assert value['path'] is None

def semantic_hash(rows,keys):
 h=hashlib.sha256()
 for r in rows:h.update((json.dumps({k:r[k] for k in keys},ensure_ascii=False,sort_keys=True,separators=(',',':'))+'\n').encode())
 return h.hexdigest()
def check_non_null_columns(rows):
 assert all(any(r[k] is not None for r in rows) for k in COLUMNS), 'Globally-null column'

def sha(p):
 h=hashlib.sha256()
 with p.open('rb') as f:
  for b in iter(lambda:f.read(1048576),b''): h.update(b)
 return h.hexdigest()
def check_columns(names):
 assert not set(FORBIDDEN)&set(names), 'Private columns present'
 assert set(COLUMNS)==set(names), 'Required public schema absent or unexpected columns'
def strings(obj):
 if isinstance(obj,str): yield obj
 elif isinstance(obj,dict):
  for k,v in obj.items(): yield str(k); yield from strings(v)
 elif isinstance(obj,(tuple,list)):
  for v in obj: yield from strings(v)
def scan(obj):
 assert all(not PATTERN.search(s) for s in strings(obj)), 'Private path or credential pattern detected'
def png_metadata(path):
 with path.open('rb') as f:
  assert f.read(8)==b'\x89PNG\r\n\x1a\n'
  while True:
   header=f.read(8); assert len(header)==8
   n,kind=struct.unpack('>I4s',header); data=f.read(n); crc=f.read(4)
   assert len(data)==n and len(crc)==4
   assert zlib.crc32(kind+data)&0xffffffff==struct.unpack('>I',crc)[0]
   if kind==b'tEXt': scan(data.decode('latin1'))
   elif kind==b'zTXt':
    key,rest=data.split(b'\0',1); scan(key.decode('latin1')); scan(zlib.decompress(rest[1:]).decode('latin1'))
   elif kind==b'iTXt':
    key,rest=data.split(b'\0',1); flag,method=rest[:2]; lang,translated,payload=rest[2:].split(b'\0',2)
    if flag: payload=zlib.decompress(payload)
    scan([key.decode('latin1'),lang.decode('ascii'),translated.decode('utf8'),payload.decode('utf8')])
   elif kind==b'eXIf': scan(data.decode('latin1'))
   if kind==b'IEND': assert not f.read(1); break
 with Image.open(path) as im: scan(im.info); im.verify()
def files(root):
 return sorted(p for p in root.rglob('*') if p.is_file() and not any(x in {'.cache','__pycache__'} for x in p.relative_to(root).parts))
def validate(root,checksums=True):
 root=Path(root).resolve();manifest=json.loads((root/'RELEASE_MANIFEST.json').read_text(encoding='utf8'))
 metadata=pq.read_table(root/'metadata/drawings.parquet').to_pylist();assert len(metadata)==1724
 drawings={r['drawing_id']:r for r in metadata};ids=set();refs=collections.Counter();nonnull=collections.Counter();coverage={g:collections.Counter() for g in ['All','Standard','Hard']}
 for split,count in COUNTS.items():
  file=pq.ParquetFile(root/'data'/(split+'.parquet'))
  try:
   check_columns(file.schema_arrow.names);assert file.metadata.num_rows==count
   assert file.schema_arrow.field('image').type==pa.struct([('bytes',pa.binary()),('path',pa.string())])
   assert isinstance(Features.from_arrow_schema(file.schema_arrow)['image'],HFImage)
   families=collections.Counter();hops=collections.Counter();digest=hashlib.sha256();keys=manifest['non_image_integrity']['columns'];rows_seen=0
   for batch in file.iter_batches(batch_size=64):
    for r in batch.to_pylist():
     scan(r);check_taxonomy_row(r);check_image_entry(r['image'],r['drawing_id']);assert r['split']==split
     assert re.fullmatch(r'forge_\d{6}_q\d{4}',r['id']) and r['id'] not in ids
     ids.add(r['id']);assert r['id'].startswith(r['drawing_id']+'_q')
     d=drawings[r['drawing_id']];assert d['split']==split
     assert hashlib.sha256(r['image']['bytes']).hexdigest()==d['sha256'], 'Embedded PNG differs from benchmark source'
     refs[r['drawing_id']]+=1;families[r['family']]+=1;hops[r['hop_count']]+=1;rows_seen+=1
     for k in COLUMNS:nonnull[k]+=r[k] is not None
     assert isinstance(r['symbolic_trace'],list) and isinstance(r['visible_facts'],list) and isinstance(r['reasoning_text'],str)
     for step in r['symbolic_trace']:assert set(step)=={'hop','relation','from','to'}
     for g in ['All',r['difficulty']]:
      coverage[g]['rows']+=1
      for k in ['symbolic_trace','visible_facts','reasoning_text']:coverage[g]['rows_with_'+k]+=bool(r[k])
     digest.update((json.dumps({k:r[k] for k in keys},ensure_ascii=False,sort_keys=True,separators=(',',':'))+'\n').encode())
   assert rows_seen==count and dict(families)==FAMILY_COUNTS[split]
   assert digest.hexdigest()==manifest['non_image_integrity']['sha256'][split], 'NON_IMAGE_CONTENT_DRIFT'
   if split=='test':assert dict(hops)==HOPS
  finally:file.close()
 assert len(ids)==31307 and len(refs)==1724 and sum(refs.values())==31307
 assert all(nonnull[k]>0 for k in COLUMNS), 'Globally-null public column'
 stats=json.loads((root/'metadata/dataset_stats.json').read_text(encoding='utf8'))
 assert {g:dict(c) for g,c in coverage.items()}==stats['coverage']
 assert manifest['source_to_public_row_drift']==0 and manifest['CONTENT_DRIFT']==0
 assert manifest['image_feature']['embedded_byte_rows']==31307
 assert len(list((root/'images').glob('*.png')))==1724
 for d in metadata:
  scan(d);p=root/d['image'];assert p.is_file() and sha(p)==d['sha256'] and d['qa_count']==refs[d['drawing_id']]
  with Image.open(p) as im:assert im.size==(d['width'],d['height'])
  png_metadata(p)
 for p in files(root):
  name=p.relative_to(root).as_posix();scan(name);assert not p.is_symlink()
  if p.suffix=='.parquet':
   if name.startswith('data/'):continue # QA rows and nested values were scanned above in bounded batches.
   t=pq.read_table(p);assert not set(FORBIDDEN)&set(t.column_names);scan(t.to_pylist())
  elif p.suffix in {'.md','.json','.py','.txt','.bib'} or p.name=='SHA256SUMS':scan(p.read_text(encoding='utf8'))
  elif p.suffix!='.png':raise AssertionError('Unexpected file type')
 if checksums:
  listed={}
  for line in (root/'checksums/SHA256SUMS').read_text().splitlines():
   h,name=line.split('  ',1);assert name not in listed;listed[name]=h
  actual={p.relative_to(root).as_posix() for p in files(root) if p.relative_to(root).as_posix()!='checksums/SHA256SUMS'}
  assert set(listed)==actual
  for name,h in listed.items():assert sha(root/name)==h,'Checksum mismatch'
 assert manifest['ready_for_hf_replacement'] is True
 print('VALIDATION_PASSED rows=31307 drawings=1724 exact_embedded_PNGs=31307 NON_IMAGE_CONTENT_DRIFT=0',flush=True)
 return {'rows':31307,'drawings':1724}
if __name__=='__main__':
 ap=argparse.ArgumentParser();ap.add_argument('--root',type=Path,default=Path(__file__).resolve().parents[1]);args=ap.parse_args();validate(args.root)