File size: 16,209 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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
"""Conservative task screening for a strong Qwen3.6-27B target.

These labels are source/structure priors, never measured model performance.
`core_candidate` identifies evidence worth testing; `uncalibrated` may still be
basic. Prompt/reference length, presence of tests/tools, and source prestige do
not establish difficulty. This module does not execute source programs or SQL.
"""
from __future__ import annotations

from collections import Counter
import json
from pathlib import Path
import re

TARGET_MODEL = 'Qwen3.6-27B'
POLICY_VERSION = 'qwen3.6-27b-structural-v1'
TIERS = ('foundational', 'core_candidate', 'uncalibrated')
DIFFICULTY_FIELDS = (
    'difficulty_tier', 'difficulty_evidence', 'difficulty_tier_confidence',
    'difficulty_target_model', 'difficulty_validation',
)

ARITHMETIC = re.compile(r"^(?:(?:what(?: is|'s)|calculate|compute|evaluate|solve|please (?:calculate|compute|evaluate))\s+)?([+-]?\d{1,3})\s*([+*/×÷-])\s*([+-]?\d{1,3})(?:\s*=)?\s*[?.!]*$", re.I)
CAPITAL = re.compile(r"^what(?: is|'s) the capital(?: city)? of (?:the )?(?:france|germany|italy|spain|portugal|japan|china|india|canada|australia|brazil|united states(?: of america)?|usa|u\.s\.a\.|united kingdom|uk|russia|egypt|south korea)\s*[?.!]*$", re.I)
GREETING = re.compile(r"^(?:hi|hello|hey|good morning|good afternoon|good evening)(?:[!., ]+(?:there|how are you))?\s*[?.!]*$", re.I)
UNITS = re.compile(r"^how many (seconds|minutes|hours|days|months|centimeters|millimeters|meters|grams) (?:are (?:there )?)?in (?:a|an|one|1) (minute|hour|day|week|year|meter|centimeter|kilometer|kilogram)\s*[?.!]*$", re.I)
UNIT_RELATIONS = {('seconds', 'minute'), ('minutes', 'hour'), ('hours', 'day'), ('days', 'week'), ('months', 'year'), ('centimeters', 'meter'), ('millimeters', 'centimeter'), ('millimeters', 'meter'), ('meters', 'kilometer'), ('grams', 'kilogram')}
LINEAR = re.compile(r'^(?:solve(?: for (?P<variable>[a-z]))?|find (?P<find_variable>[a-z]))\s*[:;,]?\s*(?P<equation>[0-9a-z+*/=(). \t-]+)[?.!]*$', re.I)
SQL_LITERAL_OR_COMMENT = re.compile(r"'(?:''|[^'])*'|\"(?:\"\"|[^\"])*\"|`[^`]*`|--[^\n]*|/\*.*?\*/", re.S)
COMPETITION_BUCKETS = {'olympiads', 'olympiads_ref', 'cn_contest', 'amc_aime', 'inequalities', 'number_theory'}
NUMINA_INVALID = {'source_problem_is_valid_not_yes', 'source_solution_is_valid_not_yes', 'missing_prompt', 'prompt_external_image_dependency', 'reference_external_image_dependency', 'prompt_language_needs_review'}


def _object(value):
    if isinstance(value, dict):
        return value
    if isinstance(value, str) and value:
        try:
            parsed = json.loads(value)
        except (ValueError, TypeError):
            return {}
        return parsed if isinstance(parsed, dict) else {}
    return {}


def _result(tier, evidence, confidence='structural_heuristic'):
    return {
        'difficulty_tier': tier,
        'difficulty_evidence': list(evidence),
        'difficulty_tier_confidence': confidence,
        'difficulty_target_model': TARGET_MODEL,
        'difficulty_validation': 'heuristic_not_model_measured',
    }


def elementary_signal(prompt, context=''):
    """Match whole unconstrained tasks, never substrings inside harder tasks."""
    if context and str(context).strip() not in {'', '[]'}:
        return None
    text = str(prompt or '').strip().replace('’', "'")
    # A surrounding mathematical delimiter does not create an extra task.
    text = text.replace('$', '')
    m = ARITHMETIC.fullmatch(text)
    if m and not (m[2] in {'/', '÷'} and int(m[3]) == 0):
        return 'exact_single_small_integer_arithmetic'
    if CAPITAL.fullmatch(text):
        return 'direct_common_country_capital_lookup'
    if GREETING.fullmatch(text):
        return 'greeting_only'
    m = UNITS.fullmatch(text)
    if m and (m[1].lower(), m[2].lower()) in UNIT_RELATIONS:
        return 'fixed_unit_conversion'
    m = LINEAR.fullmatch(text)
    if m:
        equation = m['equation'].lower().strip().rstrip('.')
        letters = re.findall(r'[a-z]', equation)
        variable = (m['variable'] or m['find_variable'] or (letters[0] if letters else '')).lower()
        numbers = re.findall(r'\d+(?:\.\d+)?', equation)
        term = r'(?:[+-]?\d{1,3}\s*\*?\s*)?' + re.escape(variable) + r'(?:\s*[+-]\s*\d{1,3})?'
        constant = r'[+-]?\d{1,3}'
        if (variable and letters == [variable] and equation.count('=') == 1
                and (re.fullmatch(term + r'\s*=\s*' + constant, equation)
                     or re.fullmatch(constant + r'\s*=\s*' + term, equation))):
            return 'exact_one_variable_linear_equation'
    return None


def _sql_difficulty(row, meta):
    label = str(meta.get('sql_complexity') or row.get('source_difficulty') or '')
    sql = SQL_LITERAL_OR_COMMENT.sub(' ', str(row.get('reference_solution') or ''))
    tokens = re.findall(r'[A-Za-z_]+', sql.upper())
    counts = Counter(tokens)
    statements = sum(bool(s.strip()) for s in sql.split(';'))
    selects, joins = counts['SELECT'], counts['JOIN']
    advanced = sorted(set(tokens) & {'WITH', 'OVER', 'UNION', 'INTERSECT', 'EXCEPT', 'RECURSIVE'})
    features = f'sql_structure:selects={selects};joins={joins};statements={statements};advanced={",".join(advanced) or "none"}'
    evidence = [f'source_sql_complexity:{label or "missing"}', features]
    if (label in {'basic SQL', 'aggregation', 'single join'} and tokens
            and selects <= 1 and joins <= 1 and statements == 1 and not advanced):
        return _result('foundational', evidence + ['single_statement_basic_query_or_update_without_advanced_query_structure'])
    # An isolated SQL feature is not sufficient to call a task challenging.
    aggregate = bool(set(tokens) & {'GROUP', 'HAVING', 'COUNT', 'SUM', 'AVG'})
    combined = (joins >= 2 and aggregate) or (selects >= 2 and counts['OVER']) or (counts['WITH'] and counts['OVER']) or counts['RECURSIVE']
    if combined:
        return _result('core_candidate', evidence + ['combined_relational_operations_require_calibration'])
    return _result('uncalibrated', evidence + ['source_sql_category_alone_does_not_establish_model_difficulty'], 'uncalibrated')


def _numina_difficulty(row, meta):
    bucket, kind = str(meta.get('source') or ''), str(meta.get('question_type') or '')
    evidence = [f'numina_source_bucket:{bucket or "missing"}', f'source_question_type:{kind or "missing"}']
    if set(row.get('quality_flags') or []) & NUMINA_INVALID:
        return _result('uncalibrated', evidence + ['source_validity_or_required_context_issue_prevents_difficulty_inference'], 'uncalibrated')
    prompt = str(row.get('prompt') or '')
    lower = prompt.lower()
    if bucket in COMPETITION_BUCKETS:
        proof = bool(re.search(r'\b(?:prove|show that|demonstrate that)\b', lower))
        find_all = bool(re.search(r'\b(?:find|determine) all\b', lower))
        functional = find_all and bool(re.search(r'\bfunctions?\b', lower)) and len(re.findall(r'\bf\s*\(', lower)) >= 2
        math_regions = ' '.join(re.findall(r'\$([^$]+)\$', prompt))
        variables = set(re.findall(r'\b[a-z]\b', math_regions.lower()))
        integer_classification = (find_all and len(variables) >= 3
            and bool(re.search(r'\b(?:positive integers?|integers?|prime numbers?)\b', lower))
            and 'such that' in lower and bool(re.search(r'\^\s*(?:\{?[a-z]|\{?[3-9])', lower)))
        multivariable_inequality = (proof and len(variables) >= 3
            and bool(re.search(r'\bpositive (?:real )?(?:numbers?|variables?)\b', lower))
            and bool(re.search(r'\\(?:le|ge|leq|geq)|inequalit', lower))
            and bool(re.search(r'\^\s*\{?[2-9]', lower)))
        geometry_structures = [term for term in ('cyclic', 'tangent', 'circumcircle', 'orthocenter', 'incircle', 'concurrent') if term in lower]
        geometry_proof = proof and len(geometry_structures) >= 2
        structures = []
        if functional:
            structures.append('universal_function_classification_with_multiple_function_applications')
        if integer_classification:
            structures.append('integer_classification_with_symbolic_or_higher_power_constraints')
        if multivariable_inequality:
            structures.append('proof_with_multivariable_nonlinear_inequality_constraints')
        if geometry_proof:
            structures.append('proof_combining_geometry_structures:' + ','.join(geometry_structures))
        if structures:
            return _result('core_candidate', evidence + structures + ['contest_source_and_structure_joint_prior_not_measured_difficulty'])
    return _result('uncalibrated', evidence + ['source_bucket_and_answer_or_solution_length_do_not_establish_difficulty'], 'uncalibrated')


def _schema_features(schema):
    """Read schema constraints as data; no validator/source code is executed."""
    schema = _object(schema)
    props = schema.get('properties', {})
    primitive = {'string', 'number', 'integer', 'boolean', 'null'}
    complex_keys = {'properties', 'items', '$ref', 'oneOf', 'anyOf', 'allOf', 'if', 'then', 'else', 'pattern', 'dependentSchemas', 'dependentRequired'}
    flat = schema.get('type') == 'object' and isinstance(props, dict) and 1 <= len(props) <= 6
    for value in props.values() if isinstance(props, dict) else []:
        if not isinstance(value, dict):
            flat = False
            continue
        kinds = value.get('type', [])
        kinds = [kinds] if isinstance(kinds, str) else kinds
        flat = flat and isinstance(kinds, list) and bool(kinds) and all(isinstance(k, str) for k in kinds) and set(kinds) <= primitive and not set(value) & complex_keys
    depth, branches = 0, 0
    stack = [(schema, 0)]
    seen = 0
    while stack:
        value, level = stack.pop()
        seen += 1
        if seen > 20000:
            return False, depth, branches
        if isinstance(value, dict):
            next_level = level + int(value.get('type') == 'object' or 'properties' in value)
            depth = max(depth, next_level)
            branches += sum(key in value for key in ('oneOf', 'anyOf', 'allOf', 'if', 'dependentSchemas'))
            stack.extend((v, next_level) for v in value.values() if isinstance(v, (list, dict)))
        elif isinstance(value, list):
            stack.extend((v, level) for v in value if isinstance(v, (list, dict)))
    return bool(flat) and not branches and not set(schema) & complex_keys.difference({'properties'}), depth, branches


def _structured_difficulty(row, meta):
    kind = str(meta.get('problem_type') or '')
    config = str(meta.get('config') or '')
    verifier = _object(row.get('verifier_json'))
    flat, depth, branches = _schema_features(verifier.get('schema_str'))
    evidence = [f'structured_config:{config or "missing"}', f'source_problem_type:{kind or "missing"}', f'schema_structure:object_depth={depth};constraint_branches={branches}']
    if kind == 'schema_only' and flat:
        return _result('foundational', evidence + ['placeholder_generation_for_flat_schema_with_at_most_six_primitive_fields'])
    try:
        distractors = int(meta.get('num_distractors') or 0)
    except (ValueError, TypeError):
        distractors = 0
    if config == 'tool_calling_extraction' and distractors >= 5 and (depth >= 3 or branches):
        return _result('core_candidate', evidence + [f'tool_schema_selection_distractors:{distractors}', 'tool_selection_combined_with_nested_or_branching_schema_requires_calibration'])
    return _result('uncalibrated', evidence + ['schema_size_format_or_conversation_length_alone_does_not_establish_model_difficulty'], 'uncalibrated')


def annotate_difficulty(row):
    """Return additive difficulty fields without modifying the normalized row."""
    source = str(row.get('source') or '')
    group_sources = row.get('group_sources') or []
    if isinstance(group_sources, str):
        try:
            group_sources = json.loads(group_sources)
        except ValueError:
            group_sources = []
    sources = {source} | {s for s in group_sources if isinstance(s, str)} if isinstance(group_sources, list) else {source}
    meta = _object(row.get('source_metadata_json'))
    if 'gsm8k' in sources:
        return _result('foundational', ['gsm8k_grade_school_arithmetic_source_prior', 'individual_exceptions_require_model_calibration'], 'source_prior')
    if 'mbpp' in sources:
        return _result('foundational', ['mbpp_entry_level_python_source_prior', 'individual_exceptions_require_model_calibration'], 'source_prior')
    if source == 'gretel_sql':
        return _sql_difficulty(row, meta)
    elementary = elementary_signal(row.get('prompt'), row.get('context'))
    if elementary:
        return _result('foundational', [elementary, 'whole_prompt_with_no_extra_context_constraints'])
    if source == 'numinamath':
        return _numina_difficulty(row, meta)
    if source == 'nemotron_structured':
        return _structured_difficulty(row, meta)
    source_label = str(row.get('source_difficulty') or '').strip()
    estimated = str(row.get('estimated_difficulty') or '').strip().lower()
    if source_label.lower() in {'easy', 'introductory', 'beginner', 'entry-level'} or estimated == 'introductory':
        return _result('foundational', [f'source_difficulty_label:{source_label or "missing"}', f'existing_difficulty_estimate:{estimated or "missing"}', 'source_or_adapter_prior_only_not_measured_qwen_performance'], 'source_prior')
    evidence = ['no_validated_difficulty_measurement_for_target_model']
    if source_label:
        evidence.append('source_difficulty_metadata:' + source_label)
    if source == 'nemotron_science':
        evidence.append('science_topic_reference_length_and_tool_access_do_not_establish_difficulty')
    else:
        evidence.append('source_family_medium_hard_labels_and_input_length_are_not_sufficient')
    return _result('uncalibrated', evidence, 'uncalibrated')


def main():
    import argparse
    import pyarrow.parquet as pq
    from full_curation_common import BASE, STAGING
    from assemble_task_dataset import classification
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--sources', nargs='+')
    parser.add_argument('--audit-output', type=Path, default=BASE / 'audit_difficulty_sources.json')
    args = parser.parse_args()
    folders = [STAGING / s for s in args.sources] if args.sources else sorted(p for p in STAGING.iterdir() if (p / 'manifest.json').exists())
    results = {}
    for folder in folders:
        counts, eligible, evidence_counts = Counter(), Counter(), Counter()
        for path in sorted(folder.glob('*.parquet')):
            for batch in pq.ParquetFile(path).iter_batches(batch_size=512):
                for row in batch.to_pylist():
                    annotation = annotate_difficulty(row)
                    tier = annotation['difficulty_tier']
                    counts[tier] += 1
                    if not classification(row):
                        eligible[tier] += 1
                    if tier != 'uncalibrated':
                        evidence_counts.update(annotation['difficulty_evidence'])
        results[folder.name] = {'annotations': dict(counts), 'eligible_annotations': dict(eligible), 'tier_evidence_counts': dict(evidence_counts)}
        print(json.dumps({'source': folder.name, **results[folder.name]}), flush=True)
    report = {'policy_version': POLICY_VERSION, 'target_model': TARGET_MODEL, 'validation': 'heuristic_not_model_measured',
              'unit': 'source annotations; final task groups must be counted after deduplication', 'sources': results,
              'limits': ['Foundational labels are transparent screening priors, not measured Qwen pass rates.',
                         'Uncalibrated tasks may still be easy; their inclusion does not certify a challenging core.',
                         'Core candidates combine explicit structural demands and source context; they require empirical testing.',
                         'No task length threshold, source prestige alone, test existence, or tool access determines difficulty.']}
    args.audit_output.write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n')


if __name__ == '__main__':
    main()