File size: 12,836 Bytes
31d8236
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
"""Add transparent difficulty priors and exclude foundations from the HF default.

Only unique curated tasks are screened. Full source annotations and their
original difficulty metadata remain available. No model difficulty is claimed.
"""
from __future__ import annotations
from collections import Counter
from datetime import datetime, timezone
import json
import os
from pathlib import Path
import shutil
import argparse

import pyarrow as pa
import pyarrow.parquet as pq
import yaml

from full_curation_common import BASE, ROOT
from assemble_task_dataset import RELEASE_SCHEMA, Shards, digest
from task_difficulty import annotate_difficulty

DIFFICULTY_SCHEMA = pa.schema(list(RELEASE_SCHEMA) + [
    ('difficulty_tier', pa.string()), ('difficulty_evidence', pa.list_(pa.string())),
    ('difficulty_tier_confidence', pa.string()), ('difficulty_target_model', pa.string()),
    ('difficulty_validation', pa.string()),
])
TIERS = ('foundational', 'core_candidate', 'uncalibrated')


def render_difficulty_card(release, report):
    counts = report['difficulty_tiers']
    n = report['unique_tasks_screened']
    card_path = release / 'README.md'
    _, header, body = card_path.read_text().split('---', 2)
    metadata = yaml.safe_load(header)
    for config in metadata['configs']:
        config.pop('default', None)
        if config['config_name'] == 'tasks':
            config['data_files'][0]['path'] = 'data/tasks/*/*.parquet'
    core_paths = [f'data/tasks/{tier}/*.parquet' for tier in ('core_candidate', 'uncalibrated') if counts[tier]]
    if not core_paths:
        raise ValueError('The screen yielded no core candidates')
    metadata['configs'] = [
        {'config_name': 'qwen_core', 'default': True, 'data_files': [{'split': 'collection', 'path': core_paths}]},
    ] + ([{'config_name': 'foundational', 'data_files': [{'split': 'collection', 'path': 'data/tasks/foundational/*.parquet'}]}] if counts['foundational'] else []) + metadata['configs']
    heading = '# Rubric Diversity Tasks\n'
    overview = f'''
The default **`qwen_core`** configuration contains **{report['qwen_core_task_groups']:,} curated task groups** after screening **{counts['foundational']:,} foundational tasks** into the separate `foundational` configuration. The `tasks` configuration retains all {n:,} curated task groups.

Difficulty is labeled for a **Qwen3.6-27B** curriculum using transparent source and structural priors. **No new Qwen3.6-27B success rates were measured.** `core_candidate` means an explicit nonfoundational source/structure signal; `uncalibrated` means the available evidence does not justify a difficulty claim. Both remain in the default view. The default view is a difficulty-screened research inventory; held-out source lineages remain labeled and must still be separated for evaluation.
'''
    body = body.replace(heading, heading + overview, 1)
    body = body.replace('load_dataset("asingh15/rubric-diversity-tasks", "tasks",', 'load_dataset("asingh15/rubric-diversity-tasks", "qwen_core",', 1)
    body = body.replace('## Configurations\n', '## Configurations\n\n- `qwen_core` (default): curated task groups excluding the foundational screen; includes explicitly labeled uncalibrated tasks.\n- `foundational`: basic/easy task candidates retained as controls and for calibration.\n', 1)
    body += '''
## Difficulty for Qwen3.6-27B

Each curated task has `difficulty_tier`, `difficulty_evidence`, `difficulty_tier_confidence`, `difficulty_target_model`, and `difficulty_validation`. Original source difficulty metadata is preserved. Source configurations retain their original difficulty columns; the new screen is applied to unique curated task groups.

GSM8K and MBPP supply foundational benchmark controls. Explicit basic/easy source labels and conservative task-structure checks provide additional foundational candidates. Competition/source labels alone do not establish target-model difficulty. Missing labels stay uncalibrated; prompt length, rubric count and schema size are not treated as difficulty measurements. See [the difficulty audit](audit/difficulty_report.json) and [the exact rules](curation/scripts/task_difficulty.py).

A calibrated revision would record a pinned Qwen checkpoint, multiple independent attempts, outcome-verified success criteria, and per-task pass rates. No such model run is claimed by this release.
'''
    card_path.write_text('---\n' + yaml.safe_dump(metadata, sort_keys=False) + '---\n' + body.lstrip())


def _screen_in_place(release):
    if (release / 'audit/difficulty_report.json').exists():
        raise ValueError('Difficulty screening already completed for this release')
    old_manifest = json.loads((release / 'release_manifest.json').read_text())
    expected = set(old_manifest['files']) | {'release_manifest.json'}
    actual = {str(p.relative_to(release)) for p in release.rglob('*') if p.is_file()}
    if actual != expected:
        raise ValueError('Pre-screen file inventory differs from the audited release')
    for name, entry in old_manifest['files'].items():
        path = release / name
        if path.is_symlink() or path.stat().st_size != entry['bytes'] or digest(path) != entry['sha256']:
            raise ValueError(f'Pre-screen checksum mismatch: {name}')
    incoming = release / 'data/tasks'
    temporary = release / 'data/tasks-screening'
    if temporary.exists():
        raise ValueError('An incomplete difficulty screen exists; inspect it before restarting')
    writers = {tier: Shards(temporary / tier, schema=DIFFICULTY_SCHEMA) for tier in TIERS}
    counts, sources, reasons, samples = Counter(), {}, Counter(), {}
    n = 0
    for shard in old_manifest['configs']['tasks']['shards']:
        path = release / shard['file']
        parquet = pq.ParquetFile(path)
        if not parquet.schema_arrow.equals(RELEASE_SCHEMA):
            raise ValueError(f'Unexpected task schema: {path.name}')
        for batch in parquet.iter_batches(batch_size=512):
            for row in batch.to_pylist():
                labels = annotate_difficulty(row)
                tier = labels['difficulty_tier']
                if tier not in TIERS or set(labels) != {'difficulty_tier', 'difficulty_evidence', 'difficulty_tier_confidence', 'difficulty_target_model', 'difficulty_validation'}:
                    raise ValueError('Invalid difficulty annotation')
                row.update(labels)
                writers[tier].add(row)
                n += 1; counts[tier] += 1
                sources.setdefault(row['source'], Counter())[tier] += 1
                reasons.update(labels['difficulty_evidence'])
                sample_key = row['source'] + ':' + tier
                if len(samples.setdefault(sample_key, [])) < 3:
                    samples[sample_key].append({'record_id': row['record_id'], 'prompt_excerpt': row['prompt'][:400],
                                               'evidence': labels['difficulty_evidence']})
        if n % 50000 == 0:
            print(json.dumps({'difficulty_screened': n, 'tiers': counts}), flush=True)
    configs = {tier: writer.close() for tier, writer in writers.items()}
    if n != old_manifest['counts']['eligible_task_groups']:
        raise ValueError('Difficulty screening changed the unique task count')
    # Keep the prior generated task view outside the publication allowlist.
    backup = BASE / ('unscreened_tasks_' + release.name)
    if backup.exists():
        raise ValueError(f'Unscreened task backup already exists: {backup}')
    incoming.rename(backup)
    temporary.rename(incoming)
    task_shards = []
    for tier, config in configs.items():
        for shard in config['shards']:
            shard['file'] = str((incoming / tier / Path(shard['file']).name).relative_to(release))
            task_shards.append(shard)
    core_shards = configs['core_candidate']['shards'] + configs['uncalibrated']['shards']
    old_manifest['configs']['tasks'] = {'rows': n, 'shards': task_shards}
    old_manifest['configs']['qwen_core'] = {'rows': counts['core_candidate'] + counts['uncalibrated'], 'shards': core_shards}
    old_manifest['configs']['foundational'] = configs['foundational']
    old_manifest['counts'].update(difficulty_tiers=dict(counts), qwen_core_task_groups=counts['core_candidate'] + counts['uncalibrated'])
    report = {'status': 'passed', 'generated_at': datetime.now(timezone.utc).isoformat(),
              'target_model': 'Qwen3.6-27B', 'unique_tasks_screened': n, 'difficulty_tiers': counts,
              'qwen_core_task_groups': counts['core_candidate'] + counts['uncalibrated'],
              'source_counts': sources, 'evidence_counts': reasons, 'illustrative_samples': samples,
              'model_inference_performed': False, 'empirical_difficulty_measured': False,
              'policy': 'Foundational source priors or explicit easy/basic labels are screened from qwen_core. Uncalibrated tasks remain marked, without a claim that they are difficult. Full source data and foundational controls are retained.',
              'limitations': ['These are source/structure priors, not measured Qwen3.6-27B success rates.',
                             'Prompt length, rubric count and schema size alone do not establish difficulty; combined structural constraints are explicit priors only.',
                             'Source labels and mathematical competition provenance can be imperfect; labels retain their evidence.',
                             'Benchmark overlap and held-out source protections remain independent of the difficulty screen.',
                             'Screening uses the representative annotation and group source identities; other annotations may contain additional difficulty evidence.']}
    (release / 'audit/difficulty_report.json').write_text(json.dumps(report, indent=2, ensure_ascii=False) + '\n')
    quality_path = release / 'audit/quality_report.json'
    quality = json.loads(quality_path.read_text())
    quality['counts'].update(old_manifest['counts'])
    quality['difficulty_screen'] = {k: report[k] for k in ('target_model', 'difficulty_tiers', 'qwen_core_task_groups', 'empirical_difficulty_measured')}
    quality['checks'].append('difficulty_screen_preserves_all_unique_task_groups')
    quality_path.write_text(json.dumps(quality, indent=2, ensure_ascii=False) + '\n')
    render_difficulty_card(release, report)
    for name in ('screen_task_difficulty.py', 'task_difficulty.py'):
        shutil.copyfile(ROOT / 'scripts' / name, release / 'curation/scripts' / name)
    shutil.copyfile(ROOT / 'pyproject.toml', release / 'curation/pyproject.toml')
    difficulty_audits = list(BASE.glob('audit_*_difficulty.json'))
    if (BASE / 'audit_difficulty_sources.json').exists():
        difficulty_audits.append(BASE / 'audit_difficulty_sources.json')
    for audit in difficulty_audits:
        shutil.copyfile(audit, release / 'audit' / audit.name)
    reproduction = release / 'curation/README.md'
    text = reproduction.read_text().replace('.venv/bin/python scripts/assemble_task_dataset.py\n', '.venv/bin/python scripts/assemble_task_dataset.py\n.venv/bin/python scripts/screen_task_difficulty.py\n')
    reproduction.write_text(text)
    # Freeze the final publication allowlist after all metadata updates.
    old_manifest['files'] = {str(p.relative_to(release)): {'bytes': p.stat().st_size, 'sha256': digest(p)}
        for p in sorted(release.rglob('*')) if p.is_file() and p.name != 'release_manifest.json'}
    (release / 'release_manifest.json').write_text(json.dumps(old_manifest, indent=2) + '\n')
    print(json.dumps({k: report[k] for k in ('status', 'unique_tasks_screened', 'difficulty_tiers', 'qwen_core_task_groups')}, indent=2), flush=True)


def screen(release):
    # Build against hard-linked immutable data and copied metadata. A failure
    # leaves the audited original release intact and never becomes publishable.
    working = release.with_name(release.name + '.difficulty-build')
    backup = release.with_name(release.name + '_before_difficulty')
    if working.exists() or backup.exists():
        raise ValueError('A difficulty build or backup already exists; inspect before restarting')
    def clone_file(source, destination):
        if Path(source).suffix == '.parquet':
            os.link(source, destination)
            return destination
        return shutil.copy2(source, destination)
    shutil.copytree(release, working, copy_function=clone_file)
    _screen_in_place(working)
    release.rename(backup)
    try:
        working.rename(release)
    except BaseException:
        backup.rename(release)
        raise


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--release', type=Path, default=BASE / 'release')
    args = parser.parse_args()
    screen(args.release)


if __name__ == '__main__':
    main()