Hoseob17 commited on
Commit
b80c35e
·
verified ·
1 Parent(s): 296ac84

Remove fixed Hierarchy and Nested positions from training examples

Browse files

Release v1.2.0: rerender 500 Hierarchy and 500 Nested gold/HN pairs with seed 20261109. Preserve every non-image row field, default schema and all 1,000 Vertical/Matrix rows.

Constraint: Keep query/answer identity and the 2,000-row train split
Confidence: high
Scope-risk: moderate
Directive: Pin immutable release tags and consult rendered specs rather than authored-order specs
Tested: 2,000 staged rows; 4,000 source images; baseline equality; 1,000 relation pairs; 2,000 rerendered PNG hashes

Files changed (24) hide show
  1. CHANGELOG.md +11 -0
  2. README.md +25 -3
  3. VERSION +1 -1
  4. data/train-00001-of-00003.parquet +2 -2
  5. data/train-00002-of-00003.parquet +2 -2
  6. metadata/hard_negatives/hierarchy/hard_negatives.json +0 -0
  7. metadata/hard_negatives/nested/hard_negatives.json +0 -0
  8. metadata/rendered_assets/hard/gpt-6-luna-hard-train-500/hierarchy/position_randomization.json +0 -0
  9. metadata/rendered_assets/hard/gpt-6-luna-hard-train-500/hierarchy/randomized_specs.json +0 -0
  10. metadata/rendered_assets/hard/gpt-6-luna-hard-train-500/hierarchy/render_provenance.json +0 -0
  11. metadata/rendered_assets/hard/gpt-6-luna-hard-train-500/hn/hard_negatives.json +0 -0
  12. metadata/rendered_assets/hard/gpt-6-luna-hard-train-500/hn/hierarchy/hard_negatives.json +0 -0
  13. metadata/rendered_assets/hard/gpt-6-luna-hard-train-500/hn/hierarchy/randomized_specs.json +0 -0
  14. metadata/rendered_assets/hard/gpt-6-luna-hard-train-500/hn/nested/hard_negatives.json +0 -0
  15. metadata/rendered_assets/hard/gpt-6-luna-hard-train-500/hn/nested/randomized_specs.json +0 -0
  16. metadata/rendered_assets/hard/gpt-6-luna-hard-train-500/nested/position_randomization.json +0 -0
  17. metadata/rendered_assets/hard/gpt-6-luna-hard-train-500/nested/randomized_specs.json +0 -0
  18. metadata/rendered_assets/hard/gpt-6-luna-hard-train-500/nested/render_provenance.json +0 -0
  19. reproduction/v1.2.0/publish_train_relation_version.py +284 -0
  20. reproduction/v1.2.0/randomize_train_relation_positions.py +243 -0
  21. reproduction/v1.2.0/verify_train_relation_positions.py +212 -0
  22. verification/v1.2.0/independent_verification.json +81 -0
  23. verification/v1.2.0/render_verification.json +92 -0
  24. versions/v1.2.0.json +0 -0
CHANGELOG.md CHANGED
@@ -1,5 +1,16 @@
1
  # Dataset version history
2
 
 
 
 
 
 
 
 
 
 
 
 
3
  ## v1.1.0 — 20261109
4
 
5
  - Matrix table entity positions randomized independently across rows and columns.
 
1
  # Dataset version history
2
 
3
+ ## v1.2.0 — 2026-11-09: Hierarchy/Nested position refresh
4
+
5
+ - Hierarchy 500쌍과 Nested 500쌍의 gold/HN을 재렌더링했습니다 (총 2,000 PNG, seed `20261109`).
6
+ - Hierarchy: parent 그룹 블록과 하위 행을 무작위로 재배치하고 다른 parent 중 swap 상대를 균등 확률로 선택합니다. 유한 표본의 위치별 개수는 정확히 같을 필요가 없습니다.
7
+ - Nested: target의 subtable·행·열 위치를 무작위 균등 배정합니다. 500개 target은 subtable별 125개, 행별 100개, 열별 166–167개입니다. 같은 target subtable 위치 안에서 swap 상대별 횟수 차이는 최대 1입니다.
8
+ - 기존 query, 정답, target identity, 스타일과 HN 관계 변경 규칙을 유지했습니다. Vertical/Matrix 1,000행은 `v1.1.0`와 완전히 같습니다.
9
+ - Rendered specs, HN metadata, position audits, provenance and verification reports are synchronized. Original authored specs remain unchanged.
10
+ - Parent revision: `296ac842567d45aefe3cda1e20bee02336dc8133`.
11
+
12
+ English: rerender 500 Hierarchy and 500 Nested gold/HN pairs to remove fixed display positions. Hierarchy uses seeded random parent/sibling permutations and a uniformly sampled other parent; Nested uses balanced randomized target positions and conditionally balanced swap partners. All query/answer/non-image fields and all Vertical/Matrix rows remain unchanged.
13
+
14
  ## v1.1.0 — 20261109
15
 
16
  - Matrix table entity positions randomized independently across rows and columns.
README.md CHANGED
@@ -25,10 +25,10 @@ dataset_info:
25
  dtype: string
26
  splits:
27
  - name: train
28
- num_bytes: 430784168.0
29
  num_examples: 2000
30
- download_size: 427785946
31
- dataset_size: 430784168.0
32
  configs:
33
  - config_name: default
34
  data_files:
@@ -62,3 +62,25 @@ Pin this version for reproducible training:
62
  from datasets import load_dataset
63
  ds = load_dataset("NLPRETGOOD/table_train", revision="v1.1.0", split="train")
64
  ```
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  dtype: string
26
  splits:
27
  - name: train
28
+ num_bytes: 430815279.0
29
  num_examples: 2000
30
+ download_size: 427887702
31
+ dataset_size: 430815279.0
32
  configs:
33
  - config_name: default
34
  data_files:
 
62
  from datasets import load_dataset
63
  ds = load_dataset("NLPRETGOOD/table_train", revision="v1.1.0", split="train")
64
  ```
65
+
66
+ ## v1.2.0 — 2026-11-09: Hierarchy/Nested position refresh
67
+
68
+ - Hierarchy 500쌍과 Nested 500쌍의 gold/HN을 재렌더링했습니다 (총 2,000 PNG, seed `20261109`).
69
+ - Hierarchy: parent 그룹 블록과 하위 행을 무작위로 재배치하고 다른 parent 중 swap 상대를 균등 확률로 선택합니다. 유한 표본의 위치별 개수는 정확히 같을 필요가 없습니다.
70
+ - Nested: target의 subtable·행·열 위치를 무작위 균등 배정합니다. 500개 target은 subtable별 125개, 행별 100개, 열별 166–167개입니다. 같은 target subtable 위치 안에서 swap 상대별 횟수 차이는 최대 1입니다.
71
+ - 기존 query, 정답, target identity, 스타일과 HN 관계 변경 규칙을 유지했습니다. Vertical/Matrix 1,000행은 `v1.1.0`와 완전히 같습니다.
72
+ - Rendered specs, HN metadata, position audits, provenance and verification reports are synchronized. Original authored specs remain unchanged.
73
+ - Parent revision: `296ac842567d45aefe3cda1e20bee02336dc8133`.
74
+
75
+ English: rerender 500 Hierarchy and 500 Nested gold/HN pairs to remove fixed display positions. Hierarchy uses seeded random parent/sibling permutations and a uniformly sampled other parent; Nested uses balanced randomized target positions and conditionally balanced swap partners. All query/answer/non-image fields and all Vertical/Matrix rows remain unchanged.
76
+
77
+ ### Reproducibility and metadata
78
+
79
+ The default split remains `train` (2,000 rows, four table types × 500). Pin this release with:
80
+
81
+ ```python
82
+ from datasets import load_dataset
83
+ ds = load_dataset("NLPRETGOOD/table_train", revision="v1.2.0", split="train")
84
+ ```
85
+
86
+ `metadata/specs/` contains the unchanged authored specs, whose order is not the final rendered order. The exact rendered gold and HN specs are `metadata/rendered_assets/hard/gpt-6-luna-hard-train-500/<type>/randomized_specs.json` and `metadata/rendered_assets/hard/gpt-6-luna-hard-train-500/hn/<type>/randomized_specs.json`. Position audits and render provenance are alongside the gold specs. See [CHANGELOG.md](CHANGELOG.md), [release manifest](versions/v1.2.0.json), and [independent verification](verification/v1.2.0/independent_verification.json). Prior version tags are retained.
VERSION CHANGED
@@ -1 +1 @@
1
- v1.1.0
 
1
+ v1.2.0
data/train-00001-of-00003.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:78299be99f7731540c37c1f81ed8a561486d23fd455c2cebd8b884ac11158932
3
- size 108116433
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c307e6a5da6a332ae76ca06a68b93f93476f43f61bf55f137b1f6000ef8b6ab6
3
+ size 108099627
data/train-00002-of-00003.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:3c79d2549f174d8638f27c61305efe2204aa11ce546f1d9b2331adddbcb38e46
3
- size 223948140
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:58f0404d2a54ab421fb3fb1492ae731bc00af6e54b6a59259f997c3fceea95ea
3
+ size 224066702
metadata/hard_negatives/hierarchy/hard_negatives.json CHANGED
The diff for this file is too large to render. See raw diff
 
metadata/hard_negatives/nested/hard_negatives.json CHANGED
The diff for this file is too large to render. See raw diff
 
metadata/rendered_assets/hard/gpt-6-luna-hard-train-500/hierarchy/position_randomization.json ADDED
The diff for this file is too large to render. See raw diff
 
metadata/rendered_assets/hard/gpt-6-luna-hard-train-500/hierarchy/randomized_specs.json ADDED
The diff for this file is too large to render. See raw diff
 
metadata/rendered_assets/hard/gpt-6-luna-hard-train-500/hierarchy/render_provenance.json ADDED
The diff for this file is too large to render. See raw diff
 
metadata/rendered_assets/hard/gpt-6-luna-hard-train-500/hn/hard_negatives.json CHANGED
The diff for this file is too large to render. See raw diff
 
metadata/rendered_assets/hard/gpt-6-luna-hard-train-500/hn/hierarchy/hard_negatives.json CHANGED
The diff for this file is too large to render. See raw diff
 
metadata/rendered_assets/hard/gpt-6-luna-hard-train-500/hn/hierarchy/randomized_specs.json ADDED
The diff for this file is too large to render. See raw diff
 
metadata/rendered_assets/hard/gpt-6-luna-hard-train-500/hn/nested/hard_negatives.json CHANGED
The diff for this file is too large to render. See raw diff
 
metadata/rendered_assets/hard/gpt-6-luna-hard-train-500/hn/nested/randomized_specs.json ADDED
The diff for this file is too large to render. See raw diff
 
metadata/rendered_assets/hard/gpt-6-luna-hard-train-500/nested/position_randomization.json ADDED
The diff for this file is too large to render. See raw diff
 
metadata/rendered_assets/hard/gpt-6-luna-hard-train-500/nested/randomized_specs.json ADDED
The diff for this file is too large to render. See raw diff
 
metadata/rendered_assets/hard/gpt-6-luna-hard-train-500/nested/render_provenance.json ADDED
The diff for this file is too large to render. See raw diff
 
reproduction/v1.2.0/publish_train_relation_version.py ADDED
@@ -0,0 +1,284 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Stage or publish the Hierarchy/Nested training refresh as an immutable version.
2
+
3
+ Default: package and verify locally. Use --publish only after reviewing the staged
4
+ README, changelog, release manifest and verification report.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import argparse
9
+ from collections import Counter
10
+ from datetime import datetime, timezone
11
+ import hashlib
12
+ import io
13
+ import json
14
+ from pathlib import Path
15
+ import shutil
16
+
17
+ from datasets import Dataset, Features, Image as DatasetImage, Value
18
+ from huggingface_hub import CommitOperationAdd, HfApi, hf_hub_download
19
+ from huggingface_hub.utils import disable_progress_bars
20
+ from PIL import Image
21
+ import pyarrow.parquet as pq
22
+ import yaml
23
+
24
+ ROOT = Path(__file__).resolve().parents[1]
25
+ REPO = 'NLPRETGOOD/table_train'
26
+ NAME = Path('hard/gpt-6-luna-hard-train-500')
27
+ TYPES = ('vertical', 'matrix', 'hierarchy', 'nested')
28
+ CHANGED_TYPES = ('hierarchy', 'nested')
29
+ SCOPE = ROOT / '.omx/state/table-train-relation-release'
30
+
31
+
32
+ def read(path):
33
+ return json.loads(path.read_text())
34
+
35
+
36
+ def write(path, data):
37
+ path.parent.mkdir(parents=True, exist_ok=True)
38
+ path.write_text(json.dumps(data, ensure_ascii=False, indent=2) + '\n')
39
+
40
+
41
+ def sha(path):
42
+ return hashlib.sha256(path.read_bytes()).hexdigest()
43
+
44
+
45
+ def remote_files(api, revision):
46
+ return {entry.path: entry for entry in api.list_repo_tree(
47
+ REPO, repo_type='dataset', recursive=True, revision=revision) if hasattr(entry, 'blob_id')}
48
+
49
+
50
+ def matches(path, entry):
51
+ data = path.read_bytes()
52
+ return (hashlib.sha256(data).hexdigest() == entry.lfs.sha256 if entry.lfs
53
+ else hashlib.sha1(b'blob ' + str(len(data)).encode() + b'\0' + data).hexdigest() == entry.blob_id)
54
+
55
+
56
+ def local_rows(stage, package_metadata):
57
+ image_root = ROOT / 'generated_rendered_images_train'
58
+ image_base = image_root / NAME
59
+ specs_base = ROOT / 'generated_content_train' / NAME
60
+ queries_base = ROOT / 'query/generated_content_train' / NAME
61
+ rows, image_hashes = [], {}
62
+ for kind in TYPES:
63
+ specs = read(specs_base / kind / 'samples.json')
64
+ queries = read(queries_base / kind / 'queries.json')['queries']
65
+ negatives = read(image_base / 'hn' / kind / 'hard_negatives.json')
66
+ assert len(specs) == len(queries) == len(negatives) == 500
67
+ for spec, query, negative in zip(specs, queries, negatives):
68
+ assert query['sample_index'] == negative['sample_index']
69
+ assert query['query'] == negative['query']
70
+ assert query['answer'] == negative['gold_answer']
71
+ assert query['cell'] == negative['target_cell']
72
+ embedded = []
73
+ for rel in (query['image'], negative['hard_negative_image']):
74
+ data = (image_base / rel).read_bytes()
75
+ with Image.open(io.BytesIO(data)) as image:
76
+ image.verify()
77
+ image_hashes[str(NAME / rel)] = hashlib.sha256(data).hexdigest()
78
+ embedded.append({'bytes': data, 'path': Path(rel).name})
79
+ rows.append(dict(id=negative['id'], table_type=kind, domain=spec['domain'], difficulty='hard',
80
+ sample_index=query['sample_index'], query=query['query'], answer=str(query['answer']),
81
+ positive_image=embedded[0], negative_image=embedded[1],
82
+ target_cell=json.dumps(query['cell'], ensure_ascii=False), negative_type=negative['swap_rule']))
83
+ if package_metadata:
84
+ for source, target in (
85
+ (specs_base / kind / 'samples.json', stage / 'metadata/specs' / kind / 'samples.json'),
86
+ (queries_base / kind / 'queries.json', stage / 'metadata/queries' / kind / 'queries.json'),
87
+ (image_base / kind / 'render_manifest.json', stage / 'metadata/render_manifests' / kind / 'render_manifest.json'),
88
+ (image_base / 'hn' / kind / 'hard_negatives.json', stage / 'metadata/hard_negatives' / kind / 'hard_negatives.json')):
89
+ target.parent.mkdir(parents=True, exist_ok=True)
90
+ shutil.copy2(source, target)
91
+ assert len(rows) == len({r['id'] for r in rows}) == 2000
92
+ assert len(image_hashes) == 4000
93
+ assert set(image_hashes) == {str(p.relative_to(image_root)) for p in image_root.rglob('*.png')}
94
+ if package_metadata:
95
+ for source in image_root.rglob('*.json'):
96
+ target = stage / 'metadata/rendered_assets' / source.relative_to(image_root)
97
+ target.parent.mkdir(parents=True, exist_ok=True)
98
+ shutil.copy2(source, target)
99
+ return rows, image_hashes
100
+
101
+
102
+ def verify_rows(paths, rows):
103
+ count = 0
104
+ for path in paths:
105
+ for batch in pq.ParquetFile(path).iter_batches(batch_size=32):
106
+ for row in batch.to_pylist():
107
+ assert row == rows[count], f'Packaged row differs at {count}'
108
+ count += 1
109
+ assert count == len(rows) == 2000
110
+ return count
111
+
112
+
113
+ def verify_baseline(api, revision, remote, rows):
114
+ expected = {row['id']: row for row in rows}
115
+ checked, image_changed, unchanged = Counter(), Counter(), Counter()
116
+ seen = set()
117
+ for name in sorted(p for p in remote if p.startswith('data/') and p.endswith('.parquet')):
118
+ path = hf_hub_download(REPO, name, repo_type='dataset', revision=revision)
119
+ for batch in pq.ParquetFile(path).iter_batches(batch_size=32):
120
+ for old in batch.to_pylist():
121
+ assert old['id'] not in seen
122
+ seen.add(old['id'])
123
+ new = expected[old['id']]
124
+ kind = old['table_type']
125
+ assert set(old) == set(new), f'Schema changed for {old["id"]}'
126
+ if kind not in CHANGED_TYPES:
127
+ assert old == new, f'Unexpected {kind} row change: {old["id"]}'
128
+ unchanged[kind] += 1
129
+ else:
130
+ assert all(old[k] == new[k] for k in old if k not in ('positive_image', 'negative_image')), old['id']
131
+ image_changed[kind] += sum(old[k] != new[k] for k in ('positive_image', 'negative_image'))
132
+ checked[kind] += 1
133
+ assert checked == dict.fromkeys(TYPES, 500)
134
+ assert seen == set(expected)
135
+ return dict(rows_by_type=dict(checked), fully_unchanged_rows_by_type=dict(unchanged),
136
+ changed_image_fields_by_type=dict(image_changed), all_nonimage_fields_preserved=True)
137
+
138
+
139
+ def release_text(version, baseline, parent):
140
+ return f'''## {version} — {datetime.now(timezone.utc).date().isoformat()}: Hierarchy/Nested position refresh
141
+
142
+ - Hierarchy 500쌍과 Nested 500쌍의 gold/HN을 재렌더링했습니다 (총 2,000 PNG, seed `20261109`).
143
+ - Hierarchy: parent 그룹 블록과 하위 행을 무작위로 재배치하고 다른 parent 중 swap 상대를 균등 확률로 선택합니다. 유한 표본의 위치별 개수는 정확히 같을 필요가 없습니다.
144
+ - Nested: target의 subtable·행·열 위치를 무작위 균등 배정합니다. 500개 target은 subtable별 125개, 행별 100개, 열별 166–167개입니다. 같은 target subtable 위치 안에서 swap 상대별 횟수 차이는 최대 1입니다.
145
+ - 기존 query, 정답, target identity, 스타일과 HN 관계 변경 규칙을 유지했습니다. Vertical/Matrix 1,000행은 `{baseline}`와 완전히 같습니다.
146
+ - Rendered specs, HN metadata, position audits, provenance and verification reports are synchronized. Original authored specs remain unchanged.
147
+ - Parent revision: `{parent}`.
148
+
149
+ English: rerender 500 Hierarchy and 500 Nested gold/HN pairs to remove fixed display positions. Hierarchy uses seeded random parent/sibling permutations and a uniformly sampled other parent; Nested uses balanced randomized target positions and conditionally balanced swap partners. All query/answer/non-image fields and all Vertical/Matrix rows remain unchanged.
150
+
151
+ '''
152
+
153
+
154
+ def stage_release(api, version, baseline, stage, state):
155
+ assert not stage.exists(), f'Stage already exists: {stage}; review or use --publish.'
156
+ stage.mkdir(parents=True)
157
+ info = api.repo_info(REPO, repo_type='dataset')
158
+ assert api.repo_info(REPO, repo_type='dataset', revision=baseline).sha == info.sha, 'Main is not the expected baseline'
159
+ refs = {tag.name for tag in api.list_repo_refs(REPO, repo_type='dataset').tags}
160
+ assert version not in refs, 'Version tag already exists'
161
+ state.update(active=True, phase='packaging', parent_commit=info.sha)
162
+ write(SCOPE / 'state.json', state)
163
+ latest = read(ROOT / '.omx/state/train-relation-position-randomization/latest.json')
164
+ verification_path = Path(latest['run']) / 'independent_verification.json'
165
+ verification = read(verification_path)
166
+ assert verification['passed'] and verification['pairs_verified'] == 1000 and verification['png_hashes_verified'] == 2000
167
+ rows, image_hashes = local_rows(stage, True)
168
+ remote = remote_files(api, info.sha)
169
+ baseline_check = verify_baseline(api, info.sha, remote, rows)
170
+ print('Verified baseline: all 2,000 non-image records unchanged; 1,000 Vertical/Matrix rows identical.', flush=True)
171
+ features = Features({key: DatasetImage() if key.endswith('_image') else Value('int32') if key == 'sample_index' else Value('string') for key in rows[0]})
172
+ ds = Dataset.from_list(rows, features=features)
173
+ (stage / 'data').mkdir()
174
+ for index in range(3):
175
+ ds.shard(num_shards=3, index=index, contiguous=True).to_parquet(stage / 'data' / f'train-{index:05d}-of-00003.parquet')
176
+ verify_rows(sorted((stage / 'data').glob('*.parquet')), rows)
177
+ current = Path(hf_hub_download(REPO, 'README.md', repo_type='dataset', revision=info.sha)).read_text()
178
+ _, front, body = current.split('---', 2)
179
+ card = yaml.safe_load(front)
180
+ card['dataset_info']['splits'][0].update(num_bytes=float(ds.data.nbytes), num_examples=2000)
181
+ card['dataset_info']['download_size'] = sum(p.stat().st_size for p in (stage / 'data').glob('*.parquet'))
182
+ card['dataset_info']['dataset_size'] = float(ds.data.nbytes)
183
+ release = release_text(version, baseline, info.sha)
184
+ note = f'''\n\n{release}### Reproducibility and metadata
185
+
186
+ The default split remains `train` (2,000 rows, four table types × 500). Pin this release with:
187
+
188
+ ```python
189
+ from datasets import load_dataset
190
+ ds = load_dataset("{REPO}", revision="{version}", split="train")
191
+ ```
192
+
193
+ `metadata/specs/` contains the unchanged authored specs, whose order is not the final rendered order. The exact rendered gold and HN specs are `metadata/rendered_assets/{NAME}/<type>/randomized_specs.json` and `metadata/rendered_assets/{NAME}/hn/<type>/randomized_specs.json`. Position audits and render provenance are alongside the gold specs. See [CHANGELOG.md](CHANGELOG.md), [release manifest](versions/{version}.json), and [independent verification](verification/{version}/independent_verification.json). Prior version tags are retained.
194
+ '''
195
+ (stage / 'README.md').write_text('---\n' + yaml.safe_dump(card, sort_keys=False) + '---\n' + body.strip() + note)
196
+ old_changelog = Path(hf_hub_download(REPO, 'CHANGELOG.md', repo_type='dataset', revision=info.sha)).read_text() if 'CHANGELOG.md' in remote else ''
197
+ (stage / 'CHANGELOG.md').write_text('# Dataset version history\n\n' + release + old_changelog.removeprefix('# Dataset version history').lstrip())
198
+ (stage / 'VERSION').write_text(version + '\n')
199
+ for source, name in ((verification_path, 'independent_verification.json'), (Path(latest['run']) / 'verification.json', 'render_verification.json')):
200
+ target = stage / 'verification' / version / name
201
+ target.parent.mkdir(parents=True, exist_ok=True)
202
+ shutil.copy2(source, target)
203
+ for name in ('publish_train_relation_version.py', 'randomize_train_relation_positions.py', 'verify_train_relation_positions.py'):
204
+ target = stage / 'reproduction' / version / name
205
+ target.parent.mkdir(parents=True, exist_ok=True)
206
+ shutil.copy2(ROOT / 'tools' / name, target)
207
+ manifest = dict(version=version, created_at=datetime.now(timezone.utc).isoformat(), parent_commit=info.sha,
208
+ baseline_version=baseline, source='generated_rendered_images_train', seed=20261109, rows=2000,
209
+ changed_types=list(CHANGED_TYPES), rerendered_pairs=1000, rerendered_pngs=2000,
210
+ total_pngs=4000, baseline_verification=baseline_check, render_position_distributions=latest['datasets'],
211
+ source_png_sha256=image_hashes, parquet_sha256={p.name: sha(p) for p in (stage / 'data').glob('*.parquet')},
212
+ verification=dict(pairs_verified=verification['pairs_verified'], png_hashes_verified=verification['png_hashes_verified'],
213
+ source_gold_maps_preserved=verification['source_gold_maps_preserved'], target_positions_verified=verification['target_positions_verified'],
214
+ swap_only_label_exchange_verified=verification['swap_only_label_exchange_verified'], nested_balance_verified=verification['nested_balance_verified']))
215
+ write(stage / 'versions' / f'{version}.json', manifest)
216
+ files = {p.relative_to(stage).as_posix(): p for p in stage.rglob('*') if p.is_file()}
217
+ changed = [name for name, path in files.items() if name not in remote or not matches(path, remote[name])]
218
+ report = dict(version=version, baseline_version=baseline, parent_commit=info.sha, stage=str(stage),
219
+ staged_rows_verified=2000, staged_images_verified=4000, staged_files=len(files), changed_files=changed,
220
+ baseline_verification=baseline_check, staged_sha256={name: sha(path) for name, path in files.items()})
221
+ write(SCOPE / f'{version}-staging.json', report)
222
+ state.update(active=False, phase='staged', parent_commit=info.sha, stage=str(stage),
223
+ staged_rows_verified=2000, staged_images_verified=4000, changed_files=len(changed))
224
+ write(SCOPE / 'state.json', state)
225
+ print(json.dumps({k: value for k, value in state.items()}, indent=2), flush=True)
226
+
227
+
228
+ def publish_release(api, version, baseline, stage, state):
229
+ report = read(SCOPE / f'{version}-staging.json')
230
+ assert report['baseline_version'] == baseline and report['version'] == version
231
+ assert api.repo_info(REPO, repo_type='dataset').sha == report['parent_commit'], 'Main changed after staging'
232
+ assert version not in {tag.name for tag in api.list_repo_refs(REPO, repo_type='dataset').tags}
233
+ files = {p.relative_to(stage).as_posix(): p for p in stage.rglob('*') if p.is_file()}
234
+ assert {name: sha(path) for name, path in files.items()} == report['staged_sha256'], 'Staged content changed after review'
235
+ rows, current_hashes = local_rows(stage, False)
236
+ manifest = read(stage / 'versions' / f'{version}.json')
237
+ assert current_hashes == manifest['source_png_sha256'], 'Local assets changed after staging'
238
+ verify_rows(sorted((stage / 'data').glob('*.parquet')), rows)
239
+ before = remote_files(api, report['parent_commit'])
240
+ state.update(active=True, phase='uploading', parent_commit=report['parent_commit'])
241
+ write(SCOPE / 'state.json', state)
242
+ result = api.create_commit(repo_id=REPO, repo_type='dataset', parent_commit=report['parent_commit'],
243
+ operations=[CommitOperationAdd(path_in_repo=name, path_or_fileobj=files[name]) for name in report['changed_files']],
244
+ commit_message='Remove fixed Hierarchy and Nested positions from training examples',
245
+ commit_description=f'''Release {version}: rerender 500 Hierarchy and 500 Nested gold/HN pairs with seed 20261109. Preserve every non-image row field, default schema and all 1,000 Vertical/Matrix rows.\n\nConstraint: Keep query/answer identity and the 2,000-row train split\nConfidence: high\nScope-risk: moderate\nDirective: Pin immutable release tags and consult rendered specs rather than authored-order specs\nTested: 2,000 staged rows; 4,000 source images; baseline equality; 1,000 relation pairs; 2,000 rerendered PNG hashes''')
246
+ state.update(phase='verifying_remote', commit=result.oid)
247
+ write(SCOPE / 'state.json', state)
248
+ uploaded = remote_files(api, result.oid)
249
+ assert set(before) <= set(uploaded), 'A remote file was deleted'
250
+ assert all(name in uploaded and matches(path, uploaded[name]) for name, path in files.items())
251
+ remote_parquets = [Path(hf_hub_download(REPO, name, repo_type='dataset', revision=result.oid))
252
+ for name in sorted(p for p in files if p.startswith('data/') and p.endswith('.parquet'))]
253
+ verify_rows(remote_parquets, rows)
254
+ api.create_tag(REPO, repo_type='dataset', tag=version, revision=result.oid,
255
+ tag_message='Hierarchy/Nested position refresh: 1,000 rerendered pairs, seed 20261109; preserve all queries, answers and Vertical/Matrix rows.')
256
+ assert api.repo_info(REPO, repo_type='dataset', revision=version).sha == result.oid
257
+ assert api.repo_info(REPO, repo_type='dataset', revision=baseline).sha == report['parent_commit']
258
+ state.update(active=False, phase='complete', verified_files=len(files), remote_rows_verified=2000,
259
+ remote_images_verified=4000, url=result.commit_url, version_url=f'https://huggingface.co/datasets/{REPO}/tree/{version}',
260
+ completed_at=datetime.now(timezone.utc).isoformat())
261
+ write(SCOPE / 'state.json', state)
262
+ write(SCOPE / f'{version}.json', state)
263
+ print(json.dumps(state, indent=2), flush=True)
264
+
265
+
266
+ def main():
267
+ parser = argparse.ArgumentParser(description=__doc__)
268
+ parser.add_argument('--version', default='v1.2.0')
269
+ parser.add_argument('--baseline-version', default='v1.1.0')
270
+ parser.add_argument('--publish', action='store_true')
271
+ args = parser.parse_args()
272
+ assert args.version.startswith('v') and '/' not in args.version
273
+ disable_progress_bars()
274
+ api = HfApi()
275
+ stage = ROOT / '.omx/tmp/table-train-versions' / args.version
276
+ state = dict(repo=REPO, version=args.version, baseline_version=args.baseline_version)
277
+ if args.publish:
278
+ publish_release(api, args.version, args.baseline_version, stage, state)
279
+ else:
280
+ stage_release(api, args.version, args.baseline_version, stage, state)
281
+
282
+
283
+ if __name__ == '__main__':
284
+ main()
reproduction/v1.2.0/randomize_train_relation_positions.py ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Apply evaluation Hierarchy/Nested position logic to local training pairs.
2
+
3
+ Stages every render before publication, backs up existing assets, and preserves
4
+ queries, answers, styles and other table types. No remote dataset is changed.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import argparse
9
+ from collections import Counter
10
+ from concurrent.futures import ProcessPoolExecutor, as_completed
11
+ from datetime import datetime, timezone
12
+ import hashlib
13
+ import json
14
+ from pathlib import Path
15
+ import random
16
+ import shutil
17
+ import sys
18
+
19
+ ROOT = Path(__file__).resolve().parents[1]
20
+ sys.path.insert(0, str(ROOT))
21
+ from hard_negative_generator import randomize_hierarchy_rows, swap_hierarchy_parent, swap_nested_domain
22
+ from render_sample_tables import _cell_map
23
+ from table_spec_generator.validation import validate_spec
24
+ from tools.randomize_hierarchy_positions import parent_order, grid_values
25
+ from tools.randomize_matrix_positions import read, write, sha, render_pair
26
+ from tools.randomize_nested_positions import BalancedPositions, reposition
27
+ from PIL import Image
28
+
29
+ SCOPE = 'train-relation-position-randomization'
30
+ TYPES = ('hierarchy', 'nested')
31
+
32
+
33
+ def prepare(image_root, stage, seed):
34
+ jobs, outputs, reports, provenance_jobs = [], {}, [], []
35
+ manifests = sorted(p for kind in TYPES for p in image_root.glob(f'*/*/{kind}/render_manifest.json'))
36
+ assert manifests, 'No training relation manifests found'
37
+ for manifest_path in manifests:
38
+ kind = manifest_path.parent.name
39
+ dataset_root = manifest_path.parent.parent
40
+ dataset = dataset_root.relative_to(image_root)
41
+ specs = read(ROOT/'generated_content_train'/dataset/kind/'samples.json')
42
+ queries = read(ROOT/'query/generated_content_train'/dataset/kind/'queries.json')['queries']
43
+ records_path = dataset_root/'hn'/kind/'hard_negatives.json'
44
+ records = read(records_path)
45
+ styles = {r['filename']:r for r in read(manifest_path)}
46
+ assert len(specs) == len(queries) == len(records) == len(styles)
47
+ assert [q['sample_index'] for q in queries] == list(range(1,len(specs)+1))
48
+ assert [r['sample_index'] for r in records] == list(range(1,len(specs)+1))
49
+ nested_rng = random.Random(f'{seed}:{dataset}:nested')
50
+ schedule = BalancedPositions(nested_rng)
51
+ golds, negatives, audits = [], [], []
52
+ for original, query, record in zip(specs, queries, records):
53
+ index = query['sample_index']
54
+ cell = query['cell']
55
+ key = (cell['outer_group'],tuple(cell['row_path']),tuple(cell['column_path']))
56
+ assert query['id'] == record['query_id'] and query['query'] == record['query']
57
+ assert cell == record['target_cell'] and query['answer'] == record['gold_answer']
58
+ assert _cell_map(original)[key] == query['answer']
59
+ if kind == 'hierarchy':
60
+ pair_seed = int.from_bytes(hashlib.sha256(f'{seed}:{dataset}:{index}'.encode()).digest()[:8], 'big')
61
+ rng = random.Random(pair_seed)
62
+ gold = randomize_hierarchy_rows(original,rng=rng)
63
+ negative, partner = swap_hierarchy_parent(gold,cell['row_path'],rng=rng)
64
+ parents = parent_order(gold)
65
+ old_parents = parent_order(original)
66
+ assert grid_values(gold) == grid_values(negative)
67
+ assert gold['structure']['relations'] == original['structure']['relations']
68
+ record.update(replacement_parent=partner,target_value_after=_cell_map(negative).get(key))
69
+ audit = dict(sample_index=index,seed=pair_seed,parent_count=len(parents),
70
+ old_group=old_parents.index(cell['row_path'][0])+1,
71
+ group=parents.index(cell['row_path'][0])+1,partner=parents.index(partner)+1,
72
+ old_row=original['structure']['rows'].index(cell['row_path'])+1,
73
+ row=gold['structure']['rows'].index(cell['row_path'])+1,
74
+ column=gold['structure']['columns'].index(cell['column_path'])+1)
75
+ else:
76
+ sub = next(s for s in original['structure']['subtables'] if s['group']==cell['outer_group'])
77
+ shape = (len(original['structure']['subtables']),len(sub['rows']),len(sub['columns']))
78
+ g = schedule.draw(('group',shape),shape[0])
79
+ r = schedule.draw(('row',shape),shape[1])
80
+ c = schedule.draw(('column',shape),shape[2])
81
+ candidates = [i for i in range(shape[0]) if i!=g]
82
+ partner_position = candidates[schedule.draw(('partner',shape,g),len(candidates))]
83
+ gold = reposition(original,cell,g,r,c,nested_rng)
84
+ partner = gold['structure']['subtables'][partner_position]['group']
85
+ negative, partner = swap_nested_domain(gold,cell['outer_group'],rng=nested_rng,replacement_domain=partner)
86
+ assert [s['rows'] for s in gold['structure']['subtables']] == [s['rows'] for s in negative['structure']['subtables']]
87
+ record.update(replacement_outer_domain=partner,target_value_after=None)
88
+ audit = dict(sample_index=index,shape=shape,group=g+1,row=r+1,column=c+1,partner=partner_position+1,
89
+ old_group=original['structure']['subtables'].index(sub)+1,old_row=sub['rows'].index(cell['row_path'])+1)
90
+ validate_spec(gold)
91
+ validate_spec(negative)
92
+ assert _cell_map(gold) == _cell_map(original)
93
+ assert _cell_map(gold)[key] == query['answer']
94
+ assert key not in _cell_map(negative)
95
+ golds.append(gold)
96
+ negatives.append(negative)
97
+ audits.append(audit)
98
+ style = styles[Path(query['image']).name]
99
+ assert style['title'] == gold['title']
100
+ positive = stage/dataset/record['source_image']
101
+ negative_path = stage/dataset/record['hard_negative_image']
102
+ positive.parent.mkdir(parents=True,exist_ok=True)
103
+ negative_path.parent.mkdir(parents=True,exist_ok=True)
104
+ jobs.append((gold,negative,style,positive,negative_path))
105
+ outputs[dataset_root/record['source_image']] = positive
106
+ outputs[dataset_root/record['hard_negative_image']] = negative_path
107
+ if kind == 'nested':
108
+ for shape in {tuple(a['shape']) for a in audits}:
109
+ subset = [a for a in audits if tuple(a['shape'])==shape]
110
+ for axis,size in zip(('group','row','column'),shape):
111
+ counts = Counter(a[axis] for a in subset)
112
+ assert max(counts[i] for i in range(1,size+1))-min(counts[i] for i in range(1,size+1))<=1
113
+ for g in range(1,shape[0]+1):
114
+ counts = Counter(a['partner'] for a in subset if a['group']==g)
115
+ eligible = [counts[i] for i in range(1,shape[0]+1) if i!=g]
116
+ assert max(eligible)-min(eligible)<=1
117
+ method = ('Uniform seeded shuffle of parent blocks and sibling rows; uniformly random other parent.'
118
+ if kind=='hierarchy' else 'Shuffled balanced blocks by shape; conditionally balanced swap partners.')
119
+ metadata = {records_path:records,dataset_root/kind/'randomized_specs.json':golds,
120
+ dataset_root/'hn'/kind/'randomized_specs.json':negatives,
121
+ dataset_root/kind/'position_randomization.json':dict(seed=seed,method=method,pairs=audits)}
122
+ for dest,data in metadata.items():
123
+ staged = stage/dest.relative_to(image_root)
124
+ write(staged,data)
125
+ outputs[dest] = staged
126
+ provenance_jobs.append((dataset,kind,records,method))
127
+ reports.append(dict(dataset=str(dataset),table_type=kind,pairs=len(audits),method=method,
128
+ old_group_counts=dict(Counter(a['old_group'] for a in audits)),
129
+ group_counts=dict(Counter(a['group'] for a in audits)),
130
+ row_counts=dict(Counter(a['row'] for a in audits)),
131
+ column_counts=dict(Counter(a['column'] for a in audits)),
132
+ partner_counts=dict(Counter(a['partner'] for a in audits))))
133
+ for dataset in {x[0] for x in provenance_jobs}:
134
+ combined_path = image_root/dataset/'hn/hard_negatives.json'
135
+ if combined_path.exists():
136
+ replacement = {r['id']:r for ds,_,records,_ in provenance_jobs if ds==dataset for r in records}
137
+ combined = [replacement.get(r['id'],r) for r in read(combined_path)]
138
+ staged = stage/dataset/'hn/hard_negatives.json'
139
+ write(staged,combined)
140
+ outputs[combined_path] = staged
141
+ return jobs,outputs,reports,provenance_jobs
142
+
143
+
144
+ def verify_hashes(expected):
145
+ changed = [p for p,h in expected.items() if not Path(p).is_file() or sha(Path(p))!=h]
146
+ assert not changed, f'Protected assets changed: {changed[:5]}'
147
+
148
+
149
+ def publish(outputs, backup, image_root):
150
+ original = {dest:sha(dest) if dest.exists() else None for dest in outputs}
151
+ for dest,expected in original.items():
152
+ if expected is not None:
153
+ saved = backup/dest.relative_to(image_root)
154
+ saved.parent.mkdir(parents=True,exist_ok=True)
155
+ shutil.copy2(dest,saved)
156
+ assert sha(saved)==expected
157
+ try:
158
+ for dest,staged in outputs.items():
159
+ dest.parent.mkdir(parents=True,exist_ok=True)
160
+ shutil.copy2(staged,dest)
161
+ assert sha(dest)==sha(staged)
162
+ except BaseException:
163
+ for dest,expected in original.items():
164
+ if expected is None:
165
+ dest.unlink(missing_ok=True)
166
+ else:
167
+ shutil.copy2(backup/dest.relative_to(image_root),dest)
168
+ raise
169
+
170
+
171
+ def main():
172
+ parser = argparse.ArgumentParser(description=__doc__)
173
+ parser.add_argument('--seed',type=int,default=20261109)
174
+ parser.add_argument('--workers',type=int,default=6)
175
+ parser.add_argument('--prepare-only',action='store_true')
176
+ parser.add_argument('--resume-run',type=Path)
177
+ args = parser.parse_args()
178
+ image_root = ROOT/'generated_rendered_images_train'
179
+ stamp = datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ')
180
+ run = args.resume_run.resolve() if args.resume_run else ROOT/'.omx/state'/SCOPE/stamp
181
+ stage = run/'staging'
182
+ backup = ROOT/'.omx/backups'/SCOPE/run.name
183
+ state = dict(active=True,phase='preparing',seed=args.seed,run=str(run))
184
+ write(run/'state.json',state)
185
+ try:
186
+ jobs,outputs,reports,provenance_jobs = prepare(image_root,stage,args.seed)
187
+ provenance_paths = {image_root/d/k/'render_provenance.json' for d,k,_,_ in provenance_jobs}
188
+ mutable = set(outputs)|provenance_paths
189
+ protected = {str(p):sha(p) for folder in ('generated_rendered_images_train','generated_rendered_images','query','generated_content_train')
190
+ for p in (ROOT/folder).rglob('*') if p.is_file() and p not in mutable}
191
+ write(run/'protected_hashes.json',protected)
192
+ write(run/'preparation.json',dict(seed=args.seed,pairs=len(jobs),datasets=reports))
193
+ print(f'Validated {len(jobs)} pairs; staging at {stage}',flush=True)
194
+ if args.prepare_only:
195
+ state.update(active=False,phase='prepared_only',completed_at=datetime.now(timezone.utc).isoformat())
196
+ write(run/'state.json',state)
197
+ return
198
+ state.update(phase='rendering',pairs=len(jobs))
199
+ write(run/'state.json',state)
200
+ if args.resume_run:
201
+ for _,_,_,positive,negative in jobs:
202
+ for path in (positive,negative):
203
+ with Image.open(path) as image:
204
+ image.verify()
205
+ else:
206
+ with ProcessPoolExecutor(max_workers=args.workers) as executor:
207
+ futures = [executor.submit(render_pair,job) for job in jobs]
208
+ for n,future in enumerate(as_completed(futures),1):
209
+ future.result()
210
+ if n%20==0:
211
+ print(f'Rendered {n}/{len(jobs)} pairs',flush=True)
212
+ for dataset,kind,records,method in provenance_jobs:
213
+ dest = image_root/dataset/kind/'render_provenance.json'
214
+ provenance = read(dest) if dest.exists() else {}
215
+ provenance.update(generated_at=datetime.now(timezone.utc).isoformat(),pairs=[dict(index=r['sample_index']-1,
216
+ positive=str(dataset/r['source_image']),negative=str(dataset/r['hard_negative_image']),
217
+ positive_sha256=sha(stage/dataset/r['source_image']),negative_sha256=sha(stage/dataset/r['hard_negative_image'])) for r in records],
218
+ position_randomization=dict(seed=args.seed,pairs=len(records),method=method,gold_specs='randomized_specs.json',negative_specs=f'../hn/{kind}/randomized_specs.json'),
219
+ code_sha256={name:sha(ROOT/name) for name in ('tools/randomize_train_relation_positions.py','tools/randomize_hierarchy_positions.py','tools/randomize_nested_positions.py','hard_negative_generator.py','prepare_luna_colqwen_eval.py','render_sample_tables.py')})
220
+ staged = stage/dest.relative_to(image_root)
221
+ write(staged,provenance)
222
+ outputs[dest] = staged
223
+ verify_hashes(protected)
224
+ state.update(phase='publishing')
225
+ write(run/'state.json',state)
226
+ publish(outputs,backup,image_root)
227
+ verify_hashes(protected)
228
+ report = dict(active=False,phase='complete',seed=args.seed,pairs=len(jobs),pngs=2*len(jobs),
229
+ backup=str(backup),completed_at=datetime.now(timezone.utc).isoformat(),datasets=reports,
230
+ queries_and_answers_preserved=True,all_gold_cell_maps_preserved=True,all_hns_break_target_relation=True,
231
+ protected_files_verified=len(protected),published_files=len(outputs))
232
+ write(run/'verification.json',report)
233
+ write(run/'state.json',report)
234
+ write(run.parent/'latest.json',dict(run=str(run),**report))
235
+ print(json.dumps(report,indent=2),flush=True)
236
+ except BaseException as error:
237
+ state.update(active=False,phase='failed',error=f'{type(error).__name__}: {error}')
238
+ write(run/'state.json',state)
239
+ raise
240
+
241
+
242
+ if __name__=='__main__':
243
+ main()
reproduction/v1.2.0/verify_train_relation_positions.py ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Independently verify published training Hierarchy/Nested relation positions."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ from collections import Counter
6
+ from datetime import datetime, timezone
7
+ import hashlib
8
+ import json
9
+ from pathlib import Path
10
+ import sys
11
+
12
+ ROOT = Path(__file__).resolve().parents[1]
13
+ sys.path.insert(0, str(ROOT))
14
+ from PIL import Image
15
+ from render_sample_tables import _cell_map
16
+ from table_spec_generator.validation import validate_spec
17
+
18
+
19
+ KINDS = ('hierarchy', 'nested')
20
+
21
+
22
+ def read(path):
23
+ return json.loads(path.read_text())
24
+
25
+
26
+ def digest(path):
27
+ return hashlib.sha256(path.read_bytes()).hexdigest()
28
+
29
+
30
+ def require(condition, message):
31
+ if not condition:
32
+ raise AssertionError(message)
33
+
34
+
35
+ def verify_dataset(image_root, dataset, kind, expected_count):
36
+ base = image_root / dataset
37
+ queries = read(ROOT / 'query/generated_content_train' / dataset / kind / 'queries.json')['queries']
38
+ originals = read(ROOT / 'generated_content_train' / dataset / kind / 'samples.json')
39
+ golds = read(base / kind / 'randomized_specs.json')
40
+ negatives = read(base / 'hn' / kind / 'randomized_specs.json')
41
+ records = read(base / 'hn' / kind / 'hard_negatives.json')
42
+ audit_file = read(base / kind / 'position_randomization.json')
43
+ audits = audit_file['pairs']
44
+ require(all(len(rows) == expected_count for rows in
45
+ (queries, originals, golds, negatives, records, audits)), f'{dataset}/{kind}: count mismatch')
46
+ groups, rows, columns, partners = Counter(), Counter(), Counter(), Counter()
47
+ for expected_index, (query, original, gold, negative, record, audit) in enumerate(
48
+ zip(queries, originals, golds, negatives, records, audits), 1):
49
+ prefix = f'{dataset}/{kind}/{expected_index}'
50
+ require(query['sample_index'] == record['sample_index'] == audit['sample_index'] == expected_index,
51
+ f'{prefix}: index mismatch')
52
+ cell = query['cell']
53
+ key = (cell['outer_group'], tuple(cell['row_path']), tuple(cell['column_path']))
54
+ validate_spec(gold)
55
+ validate_spec(negative)
56
+ original_map, gold_map, negative_map = map(_cell_map, (original, gold, negative))
57
+ require(gold_map == original_map, f'{prefix}: gold entity/value map changed')
58
+ require(gold_map[key] == query['answer'] == record['gold_answer'] == record['target_value_before'],
59
+ f'{prefix}: answer mismatch')
60
+ require(record['query'] == query['query'] and record['query_id'] == query['id']
61
+ and record['target_cell'] == cell, f'{prefix}: record/query mismatch')
62
+ require(key not in negative_map and record['target_value_after'] is None,
63
+ f'{prefix}: HN retains original query relation')
64
+ require(record['source_image'] == query['image'], f'{prefix}: gold path mismatch')
65
+ if kind == 'hierarchy':
66
+ old_parent = cell['row_path'][0]
67
+ new_parent = record['replacement_parent']
68
+ require(record['original_parent'] == old_parent and old_parent != new_parent,
69
+ f'{prefix}: invalid parent metadata')
70
+ require(record['swap_rule'] == 'different_parent_same_entity_and_column', f'{prefix}: swap rule')
71
+ display_rows = gold['structure']['rows']
72
+ parent_order = list(dict.fromkeys(row[0] for row in display_rows))
73
+ old_order = list(dict.fromkeys(row[0] for row in original['structure']['rows']))
74
+ require(audit['parent_count'] == len(parent_order)
75
+ and parent_order.index(old_parent) + 1 == audit['group']
76
+ and parent_order.index(new_parent) + 1 == audit['partner']
77
+ and display_rows.index(cell['row_path']) + 1 == audit['row']
78
+ and gold['structure']['columns'].index(cell['column_path']) + 1 == audit['column']
79
+ and old_order.index(old_parent) + 1 == audit['old_group']
80
+ and original['structure']['rows'].index(cell['row_path']) + 1 == audit['old_row'],
81
+ f'{prefix}: parent/row/column audit mismatch')
82
+ rename = {old_parent: new_parent, new_parent: old_parent}
83
+ expected_map = {(outer, (rename.get(row[0], row[0]),) + row[1:], column): value
84
+ for (outer, row, column), value in gold_map.items()}
85
+ expected_rows = [[rename.get(row[0], row[0]), *row[1:]] for row in display_rows]
86
+ require(negative['structure']['rows'] == expected_rows
87
+ and negative['structure']['columns'] == gold['structure']['columns'],
88
+ f'{prefix}: HN leaf or column position changed')
89
+ require(gold['structure']['relations'] == original['structure']['relations'],
90
+ f'{prefix}: gold relations changed')
91
+ expected_relations = [dict(relation, parent=rename.get(relation['parent'], relation['parent']))
92
+ for relation in gold['structure']['relations']]
93
+ require(negative['structure']['relations'] == expected_relations,
94
+ f'{prefix}: incorrect swapped hierarchy relations')
95
+ else:
96
+ old_parent = cell['outer_group']
97
+ new_parent = record['replacement_outer_domain']
98
+ require(record['original_outer_domain'] == old_parent and old_parent != new_parent,
99
+ f'{prefix}: invalid domain metadata')
100
+ require(record['swap_rule'] == 'different_outer_domain_same_entity_and_column', f'{prefix}: swap rule')
101
+ subtables = gold['structure']['subtables']
102
+ group = next(i for i, sub in enumerate(subtables) if sub['group'] == old_parent)
103
+ partner = next(i for i, sub in enumerate(subtables) if sub['group'] == new_parent)
104
+ selected = subtables[group]
105
+ original_subs = original['structure']['subtables']
106
+ original_group = next(i for i, sub in enumerate(original_subs) if sub['group'] == old_parent)
107
+ require(audit['shape'] == [len(subtables), len(selected['rows']), len(selected['columns'])]
108
+ and group + 1 == audit['group'] and partner + 1 == audit['partner']
109
+ and selected['rows'].index(cell['row_path']) + 1 == audit['row']
110
+ and selected['columns'].index(cell['column_path']) + 1 == audit['column']
111
+ and original_group + 1 == audit['old_group']
112
+ and original_subs[original_group]['rows'].index(cell['row_path']) + 1 == audit['old_row'],
113
+ f'{prefix}: subtable/row/column audit mismatch')
114
+ rename = {old_parent: new_parent, new_parent: old_parent}
115
+ expected_map = {(rename.get(outer, outer), row, column): value
116
+ for (outer, row, column), value in gold_map.items()}
117
+ negative_subs = negative['structure']['subtables']
118
+ require(len(negative_subs) == len(subtables), f'{prefix}: HN subtable count')
119
+ for gold_sub, hn_sub in zip(subtables, negative_subs):
120
+ expected_sub = dict(gold_sub, group=rename.get(gold_sub['group'], gold_sub['group']))
121
+ require(hn_sub == expected_sub, f'{prefix}: HN subtable content/positions changed')
122
+ require(negative_map == expected_map, f'{prefix}: values/entities changed beyond label exchange')
123
+ groups[audit['group']] += 1
124
+ rows[audit['row']] += 1
125
+ columns[audit['column']] += 1
126
+ partners[audit['partner']] += 1
127
+ if kind == 'nested':
128
+ for shape in {tuple(a['shape']) for a in audits}:
129
+ subset = [a for a in audits if tuple(a['shape']) == shape]
130
+ for axis, size in zip(('group', 'row', 'column'), shape):
131
+ counts = Counter(a[axis] for a in subset)
132
+ full = [counts[i] for i in range(1, size + 1)]
133
+ require(max(full) - min(full) <= 1, f'{dataset}: unbalanced nested {axis}')
134
+ for group in range(1, shape[0] + 1):
135
+ counts = Counter(a['partner'] for a in subset if a['group'] == group)
136
+ full = [counts[i] for i in range(1, shape[0] + 1) if i != group]
137
+ require(max(full) - min(full) <= 1, f'{dataset}: unbalanced nested conditional partner')
138
+ provenance = read(base / kind / 'render_provenance.json')
139
+ require(len(provenance['pairs']) == expected_count, f'{dataset}/{kind}: provenance count')
140
+ image_hashes = 0
141
+ seen = set()
142
+ for pair in provenance['pairs']:
143
+ index = pair['index']
144
+ require(0 <= index < expected_count and index not in seen, f'{dataset}/{kind}: provenance index')
145
+ seen.add(index)
146
+ record = records[index]
147
+ for name, source_field in (('positive', 'source_image'), ('negative', 'hard_negative_image')):
148
+ expected_path = str(dataset / record[source_field])
149
+ require(pair[name] == expected_path, f'{dataset}/{kind}: provenance image path mismatch')
150
+ path = image_root / pair[name]
151
+ require(digest(path) == pair[name + '_sha256'], f'{path}: PNG hash mismatch')
152
+ with Image.open(path) as image:
153
+ image.verify()
154
+ image_hashes += 1
155
+ return dict(dataset=str(dataset), table_type=kind, pairs=expected_count,
156
+ group_counts=dict(sorted(groups.items())), row_counts=dict(sorted(rows.items())),
157
+ column_counts=dict(sorted(columns.items())), partner_counts=dict(sorted(partners.items())),
158
+ png_hashes_verified=image_hashes)
159
+
160
+
161
+ def verify_combined(image_root, dataset):
162
+ base = image_root / dataset / 'hn'
163
+ combined = read(base / 'hard_negatives.json')
164
+ expected = []
165
+ for kind in ('vertical', 'matrix', *KINDS):
166
+ records = read(base / kind / 'hard_negatives.json')
167
+ expected.extend(records)
168
+ combined_by_id = {record['id']: record for record in combined}
169
+ expected_by_id = {record['id']: record for record in expected}
170
+ require(len(combined_by_id) == len(combined) == len(expected_by_id) == len(expected),
171
+ f'{dataset}: combined IDs missing/duplicated')
172
+ require(combined_by_id == expected_by_id, f'{dataset}: combined and per-type HN metadata differ')
173
+ return len(combined)
174
+
175
+
176
+ def main():
177
+ parser = argparse.ArgumentParser(description=__doc__)
178
+ parser.add_argument('--run', required=True, type=Path)
179
+ args = parser.parse_args()
180
+ run = args.run.resolve()
181
+ state = read(run / 'state.json')
182
+ require(state.get('phase') == 'complete' and state.get('active') is False,
183
+ 'Run is not published and complete; refusing to verify staging as live assets')
184
+ preparation = read(run / 'preparation.json')
185
+ image_root = ROOT / 'generated_rendered_images_train'
186
+ entries = preparation['datasets']
187
+ require(sum(item['pairs'] for item in entries) == 1000, 'Expected 1000 relation pairs')
188
+ require(Counter(item['table_type'] for item in entries) == Counter(KINDS),
189
+ 'Expected one 500-pair dataset for each relation type')
190
+ require(all(item['pairs'] == 500 for item in entries), 'Expected 500 pairs per type')
191
+ reports = [verify_dataset(image_root, Path(item['dataset']), item['table_type'], item['pairs'])
192
+ for item in entries]
193
+ combined_count = sum(verify_combined(image_root, dataset)
194
+ for dataset in {Path(item['dataset']) for item in entries})
195
+ protected = read(run / 'protected_hashes.json')
196
+ changed = [path for path, expected in protected.items()
197
+ if not Path(path).is_file() or digest(Path(path)) != expected]
198
+ require(not changed, f'Protected files changed: {changed[:5]}')
199
+ report = dict(verified_at=datetime.now(timezone.utc).isoformat(), run=str(run), passed=True,
200
+ pairs_verified=sum(item['pairs'] for item in reports),
201
+ png_hashes_verified=sum(item['png_hashes_verified'] for item in reports),
202
+ combined_records_verified=combined_count, protected_files_verified=len(protected),
203
+ source_gold_maps_preserved=True, query_answers_verified=True,
204
+ target_positions_verified=True, negative_relations_removed=True,
205
+ swap_only_label_exchange_verified=True, nested_balance_verified=True, datasets=reports)
206
+ output = run / 'independent_verification.json'
207
+ output.write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n')
208
+ print(json.dumps(report, indent=2))
209
+
210
+
211
+ if __name__ == '__main__':
212
+ main()
verification/v1.2.0/independent_verification.json ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "verified_at": "2026-11-09T09:27:32.701472+00:00",
3
+ "run": "/data/hoseob/llm/Project/vc_final/.omx/state/train-relation-position-randomization/20261109T091731Z",
4
+ "passed": true,
5
+ "pairs_verified": 1000,
6
+ "png_hashes_verified": 2000,
7
+ "combined_records_verified": 2000,
8
+ "protected_files_verified": 16169,
9
+ "source_gold_maps_preserved": true,
10
+ "query_answers_verified": true,
11
+ "target_positions_verified": true,
12
+ "negative_relations_removed": true,
13
+ "swap_only_label_exchange_verified": true,
14
+ "nested_balance_verified": true,
15
+ "datasets": [
16
+ {
17
+ "dataset": "hard/gpt-6-luna-hard-train-500",
18
+ "table_type": "hierarchy",
19
+ "pairs": 500,
20
+ "group_counts": {
21
+ "1": 135,
22
+ "2": 133,
23
+ "3": 118,
24
+ "4": 114
25
+ },
26
+ "row_counts": {
27
+ "1": 61,
28
+ "2": 74,
29
+ "3": 63,
30
+ "4": 70,
31
+ "5": 57,
32
+ "6": 61,
33
+ "7": 50,
34
+ "8": 64
35
+ },
36
+ "column_counts": {
37
+ "1": 125,
38
+ "2": 125,
39
+ "3": 125,
40
+ "4": 125
41
+ },
42
+ "partner_counts": {
43
+ "1": 118,
44
+ "2": 113,
45
+ "3": 114,
46
+ "4": 155
47
+ },
48
+ "png_hashes_verified": 1000
49
+ },
50
+ {
51
+ "dataset": "hard/gpt-6-luna-hard-train-500",
52
+ "table_type": "nested",
53
+ "pairs": 500,
54
+ "group_counts": {
55
+ "1": 125,
56
+ "2": 125,
57
+ "3": 125,
58
+ "4": 125
59
+ },
60
+ "row_counts": {
61
+ "1": 100,
62
+ "2": 100,
63
+ "3": 100,
64
+ "4": 100,
65
+ "5": 100
66
+ },
67
+ "column_counts": {
68
+ "1": 166,
69
+ "2": 167,
70
+ "3": 167
71
+ },
72
+ "partner_counts": {
73
+ "1": 124,
74
+ "2": 126,
75
+ "3": 124,
76
+ "4": 126
77
+ },
78
+ "png_hashes_verified": 1000
79
+ }
80
+ ]
81
+ }
verification/v1.2.0/render_verification.json ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "active": false,
3
+ "phase": "complete",
4
+ "seed": 20261109,
5
+ "pairs": 1000,
6
+ "pngs": 2000,
7
+ "backup": "/data/hoseob/llm/Project/vc_final/.omx/backups/train-relation-position-randomization/20261109T091731Z",
8
+ "completed_at": "2026-11-09T09:26:50.922947+00:00",
9
+ "datasets": [
10
+ {
11
+ "dataset": "hard/gpt-6-luna-hard-train-500",
12
+ "table_type": "hierarchy",
13
+ "pairs": 500,
14
+ "method": "Uniform seeded shuffle of parent blocks and sibling rows; uniformly random other parent.",
15
+ "old_group_counts": {
16
+ "1": 128,
17
+ "2": 128,
18
+ "3": 124,
19
+ "4": 120
20
+ },
21
+ "group_counts": {
22
+ "1": 135,
23
+ "2": 133,
24
+ "3": 118,
25
+ "4": 114
26
+ },
27
+ "row_counts": {
28
+ "1": 61,
29
+ "4": 70,
30
+ "6": 61,
31
+ "2": 74,
32
+ "8": 64,
33
+ "3": 63,
34
+ "5": 57,
35
+ "7": 50
36
+ },
37
+ "column_counts": {
38
+ "1": 125,
39
+ "2": 125,
40
+ "3": 125,
41
+ "4": 125
42
+ },
43
+ "partner_counts": {
44
+ "2": 113,
45
+ "1": 118,
46
+ "4": 155,
47
+ "3": 114
48
+ }
49
+ },
50
+ {
51
+ "dataset": "hard/gpt-6-luna-hard-train-500",
52
+ "table_type": "nested",
53
+ "pairs": 500,
54
+ "method": "Shuffled balanced blocks by shape; conditionally balanced swap partners.",
55
+ "old_group_counts": {
56
+ "1": 135,
57
+ "2": 125,
58
+ "3": 120,
59
+ "4": 120
60
+ },
61
+ "group_counts": {
62
+ "1": 125,
63
+ "4": 125,
64
+ "2": 125,
65
+ "3": 125
66
+ },
67
+ "row_counts": {
68
+ "1": 100,
69
+ "4": 100,
70
+ "3": 100,
71
+ "5": 100,
72
+ "2": 100
73
+ },
74
+ "column_counts": {
75
+ "1": 166,
76
+ "2": 167,
77
+ "3": 167
78
+ },
79
+ "partner_counts": {
80
+ "3": 124,
81
+ "1": 124,
82
+ "4": 126,
83
+ "2": 126
84
+ }
85
+ }
86
+ ],
87
+ "queries_and_answers_preserved": true,
88
+ "all_gold_cell_maps_preserved": true,
89
+ "all_hns_break_target_relation": true,
90
+ "protected_files_verified": 16169,
91
+ "published_files": 2011
92
+ }
versions/v1.2.0.json ADDED
The diff for this file is too large to render. See raw diff