Datasets:
Download scripts/build_taco_leetcode.py from CodeLogic-Team/CodeLens: direct link, hf CLI and curl.
- Browser
- Download file 8.34 kB
-
https://huggingface.co/datasets/CodeLogic-Team/CodeLens/resolve/71713cc79eebe62162c26a5ad34ce792bf503c8d/scripts/build_taco_leetcode.py
- Command line
-
hf download hf://datasets/CodeLogic-Team/CodeLens@71713cc79eebe62162c26a5ad34ce792bf503c8d/scripts/build_taco_leetcode.py
-
curl -L -o build_taco_leetcode.py https://huggingface.co/datasets/CodeLogic-Team/CodeLens/resolve/71713cc79eebe62162c26a5ad34ce792bf503c8d/scripts/build_taco_leetcode.py
8.34 kB
| """Build the legacy family, add a fixed SFT holdout, or export historical arms.""" | |
| from __future__ import annotations | |
| import argparse | |
| import hashlib | |
| from collections import Counter, defaultdict | |
| from pathlib import Path | |
| import pyarrow as pa | |
| import pyarrow.parquet as pq | |
| from release_utils import (ROOT, export_rows, load_json, make_manifest, member_record, | |
| normalized_prompt, write_json, write_parquet) | |
| SPLIT_SEED = 20260907 | |
| CATEGORIES = ['math_number_theory', 'data_structure', 'dynamic_programming', 'greedy_search', | |
| 'implementation_simulation', 'graph', 'other_algorithm'] | |
| RAW_TO_FORMAL = {x: x for x in CATEGORIES + ['no_tags']} | |
| RAW_TO_FORMAL.update({x: 'other_algorithm' for x in | |
| ['sorting', 'string', 'bit_manipulation', 'recursion_backtracking', 'geometry', 'other_tagged']}) | |
| def formal(value): | |
| return RAW_TO_FORMAL.get(value, 'other_algorithm') if value else 'no_tags' | |
| def choose_validation(rows, count=100): | |
| """Largest-remainder source/category allocation, hash-ranked unique prompts.""" | |
| multiplicity = Counter(normalized_prompt(r['prompt']) for r in rows) | |
| strata = defaultdict(list) | |
| full_counts = Counter((r['dataset'], r['primary_category']) for r in rows) | |
| for row in rows: | |
| if multiplicity[normalized_prompt(row['prompt'])] == 1: | |
| strata[row['dataset'], row['primary_category']].append(row) | |
| quotas = {key: count * n // len(rows) for key, n in full_counts.items()} | |
| remaining = count - sum(quotas.values()) | |
| order = sorted(full_counts, key=lambda key: (-(count * full_counts[key] % len(rows)), key)) | |
| for key in order[:remaining]: | |
| quotas[key] += 1 | |
| selected = [] | |
| for key in sorted(quotas): | |
| if len(strata[key]) < quotas[key]: | |
| raise ValueError(f'Insufficient unique prompts for stratum {key}') | |
| ranked = sorted(strata[key], key=lambda r: hashlib.sha256(f'{SPLIT_SEED}:{r["id"]}'.encode()).hexdigest()) | |
| selected.extend(r['id'] for r in ranked[:quotas[key]]) | |
| assert len(selected) == count | |
| return set(selected), {'seed': SPLIT_SEED, 'rows': count, | |
| 'method': 'source/category largest remainder; SHA256(seed:id) rank; unique prompts only', | |
| 'strata': {'::'.join(k): v for k, v in sorted(quotas.items())}} | |
| def build(source, root): | |
| rows = pq.read_table(source / 'sft_original.parquet').to_pylist() | |
| if len(rows) != 21879 or len({r['id'] for r in rows}) != 21879: | |
| raise ValueError('Expected the original 21,879 distinct SFT rows') | |
| for row in rows: | |
| row['raw_primary_category'] = row['primary_category'] | |
| row['raw_overlap_categories'] = row['overlap_categories'] | |
| row['primary_category'] = formal(row['primary_category']) | |
| row['overlap_categories'] = sorted({formal(x) for x in | |
| (row['raw_overlap_categories'] or [row['raw_primary_category']])}) | |
| selected, policy = choose_validation(rows) | |
| full_table = pa.Table.from_pylist(rows) | |
| full_table = full_table.append_column('problem_id', full_table['id']) | |
| full_table = full_table.append_column('response', full_table['answer']) | |
| full_table = full_table.append_column('source_row_index', pa.array(range(len(rows)), type=pa.int32())) | |
| for split in ['train', 'validation']: | |
| indices = [i for i, r in enumerate(rows) if (r['id'] in selected) == (split == 'validation')] | |
| write_parquet(root / 'data/taco_leetcode/sft' / (split + '.parquet'), full_table.take(pa.array(indices))) | |
| categories = load_json(source / 'category_index.json') | |
| rl_ids = {} | |
| for split in ['train', 'validation']: | |
| table = pq.read_table(source / ('rl_' + split + '.parquet')) | |
| infos = table['extra_info'].to_pylist() | |
| ids = [info['problem_id'] for info in infos] | |
| rl_ids[split] = ids | |
| if not set(ids) <= categories.keys(): | |
| raise ValueError('Missing original RL category index') | |
| # Retain model names and counts, without machine-specific filesystem paths. | |
| for info in infos: | |
| token_counts = info.get('prompt_tokens_by_model') | |
| if token_counts: | |
| info['prompt_tokens_by_model'] = {Path(k).name: v for k, v in token_counts.items()} | |
| table = table.set_column(table.schema.get_field_index('extra_info'), 'extra_info', pa.array(infos)) | |
| table = table.append_column('problem_id', pa.array(ids)) | |
| table = table.append_column('primary_category', pa.array([formal(categories[x]['primary_category']) for x in ids])) | |
| table = table.append_column('overlap_categories', pa.array([ | |
| sorted({formal(v) for v in (categories[x]['overlap_categories'] or [categories[x]['primary_category']])}) | |
| for x in ids], type=pa.list_(pa.string()))) | |
| write_parquet(root / 'data/taco_leetcode/rl' / (split + '.parquet'), table) | |
| recorded = load_json(source / 'memberships.json') | |
| membership = {'version': '1.0.0', 'sft_historical': {}, 'sft_release': {}, 'rl_historical': {}, | |
| 'sft_rule': 'Frozen original arms, followed by removal of the new SFT holdout for release arms.', | |
| 'rl_rule': 'Remove every intersecting overlap category; frozen seed-20260610 12,168-row samples.', | |
| 'split_seed': SPLIT_SEED, 'validation_ids': sorted(selected)} | |
| for arm, ids in recorded['sft'].items(): | |
| removed = arm[3:] if arm.startswith('no_') else None | |
| membership['sft_historical'][arm] = member_record(ids, removed) | |
| membership['sft_release'][arm] = member_record([x for x in ids if x not in selected], removed) | |
| membership['rl_historical']['full_dapo'] = member_record(rl_ids['train']) | |
| for arm, ids in recorded['rl'].items(): | |
| membership['rl_historical'][arm] = member_record(ids, arm[3:] if arm.startswith('no_') else None) | |
| metadata = root / 'metadata/taco_leetcode' | |
| write_json(metadata / 'ablation_membership.json', membership, compact=True) | |
| write_json(metadata / 'taxonomy.json', {'name': 'taco_leetcode_legacy_7', 'version': '1.0.0', | |
| 'categories': CATEGORIES, 'unlabeled_value': 'no_tags', 'raw_to_formal': RAW_TO_FORMAL, | |
| 'ablation_rule': 'Remove any row whose overlap_categories contains the selected category.'}) | |
| policy['origin'] = 'Added for this release; not the historical experiment validation set.' | |
| policy['historical_sft_rows'] = 21879 | |
| policy['historical_rl_validation_overlap_with_original_sft_train'] = len(set(rl_ids['validation']) & {r['id'] for r in rows}) | |
| make_manifest(root, 'taco_leetcode', {'sft': policy, 'rl': 'Original 17,249 train + 100 validation'}) | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument('--source', type=Path, help='Frozen source export directory') | |
| parser.add_argument('--root', type=Path, default=ROOT) | |
| parser.add_argument('--arm') | |
| parser.add_argument('--kind', choices=['sft', 'rl'], default='sft') | |
| parser.add_argument('--historical', action='store_true', help='Restore original SFT membership including the new holdout') | |
| parser.add_argument('--output', type=Path) | |
| args = parser.parse_args() | |
| if args.arm: | |
| if args.output is None: | |
| parser.error('--output is required with --arm') | |
| members = load_json(args.root / 'metadata/taco_leetcode/ablation_membership.json') | |
| kind = 'rl_historical' if args.kind == 'rl' else 'sft_historical' if args.historical else 'sft_release' | |
| table = pq.read_table(args.root / 'data/taco_leetcode' / args.kind / 'train.parquet') | |
| if args.kind == 'sft' and args.historical: | |
| table = pa.concat_tables([table, pq.read_table(args.root / 'data/taco_leetcode/sft/validation.parquet')]) | |
| table = table.set_column(table.schema.get_field_index('primary_category'), 'primary_category', table['raw_primary_category']) | |
| table = table.set_column(table.schema.get_field_index('overlap_categories'), 'overlap_categories', table['raw_overlap_categories']) | |
| export_rows(table, members[kind][args.arm]['problem_ids'], args.output) | |
| elif args.source: | |
| build(args.source, args.root) | |
| else: | |
| parser.error('Use --source to build or --arm NAME --output FILE to export.') | |
| if __name__ == '__main__': | |
| main() | |