"""Small, deterministic helpers for the four dataset configurations.""" from __future__ import annotations import hashlib import json from pathlib import Path import pyarrow as pa import pyarrow.parquet as pq ROOT = Path(__file__).resolve().parents[1] def load_json(path): return json.loads(Path(path).read_text(encoding='utf-8')) def write_json(path, value, *, compact=False): path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps(value, ensure_ascii=False, indent=None if compact else 2, separators=(',', ':') if compact else None) + '\n', encoding='utf-8') def sha256(path): result = hashlib.sha256() with Path(path).open('rb') as handle: for block in iter(lambda: handle.read(4194304), b''): result.update(block) return result.hexdigest() def id_hash(ids): return hashlib.sha256(('\n'.join(sorted(ids)) + '\n').encode()).hexdigest() def normalized_prompt(text): return ' '.join(text.split()) def ids_from_table(table): if 'problem_id' in table.column_names: return table['problem_id'].to_pylist() return [row['problem_id'] for row in table['extra_info'].to_pylist()] def write_parquet(path, table): path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) pq.write_table(table, path, compression='zstd', row_group_size=1024) def describe_file(path, root): path = Path(path) parquet = pq.ParquetFile(path) columns = ['problem_id'] if 'problem_id' in parquet.schema_arrow.names else ['extra_info'] ids = ids_from_table(parquet.read(columns=columns)) return {'path': path.relative_to(root).as_posix(), 'rows': parquet.metadata.num_rows, 'bytes': path.stat().st_size, 'sha256': sha256(path), 'problem_id_set_sha256': id_hash(ids), 'columns': parquet.schema_arrow.names} def make_manifest(root, family, split_policy): files = {} for kind in ['sft', 'rl']: for split in ['train', 'validation']: path = root / 'data' / family / kind / (split + '.parquet') files[f'{kind}/{split}'] = describe_file(path, root) result = {'version': '1.0.0', 'family': family, 'split_policy': split_policy, 'files': files} write_json(root / 'metadata' / family / 'dataset_manifest.json', result) return result def member_record(ids, removed_category=None): return {'rows': len(ids), 'problem_ids': ids, 'problem_id_set_sha256': id_hash(ids), 'removed_category': removed_category} def export_rows(table, ids, destination): all_ids = ids_from_table(table) lookup = {v: i for i, v in enumerate(all_ids)} if len(lookup) != len(all_ids): raise ValueError('Duplicate source IDs') missing = set(ids) - lookup.keys() if missing: raise ValueError(f'{len(missing)} arm IDs absent from this split') write_parquet(destination, table.take(pa.array([lookup[v] for v in ids], type=pa.int64())))