File size: 11,934 Bytes
015600d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5c3e4eb
 
 
 
 
 
 
015600d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Rebuild affected English decisions from lossless published source inputs.

Retain native examples, gold meanings and splits. Rebuild the task-specific
question and options through the current declarations. Obsolete generic prompt
variants, QuaRel's classification-only packs and all CLadder rows are removed.
Other sources and the entire vision config are unchanged. --publish is explicit.
"""
import hashlib,json,re,sys
from collections import Counter,defaultdict
from pathlib import Path
import numpy as np
import pyarrow as pa
import pyarrow.compute as pc
import pyarrow.parquet as pq
import yaml
from huggingface_hub import HfApi,CommitOperationAdd,DatasetCard
from tasksource import tasks
from tasksource.jev.options import choice_permutation
from tasksource.jev.augmentations import verification_question
from scripts.build_jev_dataset import example_key,source_family,row_format,validate_decisions
from datasets import Dataset,disable_progress_bars

ROOT=Path('build/english-task-repair');OUT=ROOT/'release';OUT.mkdir(exist_ok=True)
SNAP=Path((ROOT/'snapshot.txt').read_text())
REPO='tasksource/tasksource-jev-typed-decisions';PARENT='e4d7c06b6c3810ba17df2c3fd26c13e2baa64541'
MIP='missing-item-prediction/contrastive';ORDER='goal-step-wikihow/order';QUAREL='quarel'
QUESTIONS={MIP:tasks.mip.question,ORDER:tasks.gs_order.question,QUAREL:tasks.quarel.question}
AFFECTED=set(QUESTIONS)|{'cladder'}
disable_progress_bars()


def dump(path,x):path.write_text(json.dumps(x,indent=2,ensure_ascii=False)+'\n')


def pair(prompt):
    x=tasks._missing_item_pair({'prompt':prompt})
    return f"text_A: {x['items']}\ntext_B: {x['queried_item']}"


def rebuild(row):
    row=dict(row);source=row['source'];variant=row['variant']
    if source=='cladder':return None,'evaluation_only'
    if variant=='instruction_paraphrase':return None,'obsolete_generic_prompt_variant'
    if source==QUAREL and variant=='packed_derived':return None,'classification_pack_invalid_for_native_mc'
    question=QUESTIONS[source]
    if source==MIP:
        if variant=='packed_derived':
            row['state'],count=re.subn(r'(Item [A-Z]:\n)(.*?)(?=\n\nItem [A-Z]:\n|\Z)',
                lambda m:m[1]+pair(m[2]),row['state'],flags=re.S)
            assert count>=2
            row['question']=f'Each item answers: "{question}"\n'+row['question']
        else:row['state']=pair(row['state'])
    if source==QUAREL:
        stem,a,b=tasks._quarel_parts(row['state']);answers={'A':a,'B':b};row['state']=stem
        if a==b:return None,'duplicate_native_options'
        if row['kind']=='noul':
            match=re.fullmatch(r'Is "([AB])" the correct label for this example\?',row['question'])
            assert match,row['question']
            row['question']=verification_question(question,answers[match[1]])
        else:
            assert set(row['options'])=={'A','B'}
            old_gold={answers[o]:p for o,p in zip(row['options'],row['target'])}
            options=[answers[o] for o in row['options']]
            identifier=f"{source}:{row['split']}:{row['group_id'].rsplit(':',1)[1]}"
            order=choice_permutation(options,identifier) or list(range(len(options)))
            row['options']=[options[i] for i in order]
            row['target']=[row['target'][i] for i in order]
            assert dict(zip(row['options'],row['target']))==old_gold
            row['question']=question
    elif variant=='label_verification':row['question']=question+' '+row['question']
    elif variant!='packed_derived':row['question']=question
    return row,None


# All direct parents are in full, even when a smaller config caps some away.
cache_path=ROOT/'keys.json'
if cache_path.exists():
    cache=json.loads(cache_path.read_text())
    assert cache['parent']==PARENT and cache['questions']==QUESTIONS
    keys=cache['keys'];native_gold=Counter(cache['native_gold'])
else:
    keys={};fallback={};native_gold=Counter()
    for file in sorted(SNAP.glob('full/*.parquet')):
        table=pq.read_table(file)
        selected=table.filter(pc.is_in(table['source'],value_set=pa.array(sorted(AFFECTED))))
        for old in selected.to_pylist():
            row,reason=rebuild(old)
            if row is None:continue
            key=example_key(row['source'],row['state'],row['options'],row['target'])
            fallback.setdefault(row['group_id'],key)
            if row['variant']=='direct':
                keys[row['group_id']]=key
                native_gold[row['source']]+=1
    keys={**fallback,**keys}
    dump(cache_path,{'parent':PARENT,'questions':QUESTIONS,'keys':keys,'native_gold':dict(native_gold)})

api=HfApi();info=api.dataset_info(REPO,revision=PARENT,files_metadata=True)
remote={f.rfilename:f for f in info.siblings}
stats=defaultdict(lambda:defaultdict(Counter));removed=Counter();updated=Counter();files=[]
card=DatasetCard.load(SNAP/'README.md')
formats={r.id:r.task_type for r in __import__('tasksource').list_tasks(instruct=True,soft=True).itertuples()}
for config,directory in [('default','data'),('full','full'),('filtered-full','filtered-full')]:
    for path in sorted((SNAP/directory).glob('*.parquet')):
        table=pq.read_table(path);selected=pc.is_in(table['source'],value_set=pa.array(sorted(AFFECTED)))
        positions=pc.indices_nonzero(selected).to_pylist();changed=[];indices=[];drop=[]
        for index,old in zip(positions,table.filter(selected).to_pylist()):
            row,reason=rebuild(old)
            if row is None:
                drop.append(index);removed[(config,old['source'],reason)]+=1;continue
            row['example_id']=keys[row['group_id']]
            changed.append(row);indices.append(index);updated[(config,row['source'])]+=1
        patched=table
        fields=[f for f in ['state','question','options','target','example_id'] if f in table.column_names]
        for field in fields:
            values=pa.array([r[field] for r in changed],type=table.schema.field(field).type)
            take=np.arange(len(table),dtype=np.int64);take[indices]=len(table)+np.arange(len(indices))
            patched=patched.set_column(table.schema.get_field_index(field),table.schema.field(field),
                                      pc.take(pa.chunked_array([*table[field].chunks,values]),pa.array(take)))
        keep=np.ones(len(table),dtype=bool);keep[drop]=False;patched=patched.filter(pa.array(keep))
        expected_unchanged=table.filter(pc.and_(pc.invert(selected),pa.array(keep)))
        actual_unchanged=patched.filter(pc.invert(pc.is_in(patched['source'],value_set=pa.array(sorted(AFFECTED)))))
        assert expected_unchanged.equals(actual_unchanged)
        assert 'cladder' not in set(patched['source'].to_pylist())
        affected=patched.filter(pc.is_in(patched['source'],value_set=pa.array(sorted(QUESTIONS))))
        validate_decisions(Dataset(affected,fingerprint='rebuild-validation'),path.name)
        split=path.name.split('-')[0]
        bucket=stats[config][split]
        for field,name in [('source','sources'),('kind','kinds'),('variant','variants'),('license_use','license_use')]:
            bucket.setdefault(name,Counter()).update(patched[field].to_pylist())
        bucket.setdefault('bytes',Counter())['num_bytes']+=patched.nbytes
        if positions:
            dest=OUT/directory/path.name;dest.parent.mkdir(exist_ok=True)
            if not dest.exists() or not pq.read_table(dest).equals(patched):
                pq.write_table(patched,dest,compression='snappy')
            assert pq.read_table(dest).equals(patched)
            name=f'{directory}/{path.name}'
            files.append({'path':name,'local':str(dest),'sha256':hashlib.sha256(dest.read_bytes()).hexdigest(),
                          'size_change':dest.stat().st_size-remote[name].size})
        print(config,path.name,'updated',len(indices),'removed',len(drop),flush=True)
    config_info=next(c for c in card.data.dataset_info if c['config_name']==config)
    for split in config_info['splits']:
        bucket=stats[config][split['name']];split['num_examples']=sum(bucket['sources'].values());split['num_bytes']=bucket['bytes']['num_bytes']
    config_info['dataset_size']=sum(s['num_bytes'] for s in config_info['splits'])
    config_info['download_size']+=sum(f['size_change'] for f in files if f['path'].startswith(directory+'/'))

report={'parent_revision':PARENT,'updated':{'|'.join(k):v for k,v in updated.items()},
        'removed':{'|'.join(k):v for k,v in removed.items()},'native_direct_decisions_checked':dict(native_gold),
        'configs':{c:{s:{k:dict(v) for k,v in d.items()} for s,d in splits.items()} for c,splits in stats.items()},
        'checks':['all unrelated rows exactly unchanged','native gold meanings preserved after QuaRel permutation',
                  'all retained typed decisions valid','CLadder absent from all training configs','vision untouched'],
        'script_sha256':hashlib.sha256(Path(__file__).read_bytes()).hexdigest()}
release=json.loads((SNAP/'release-audit.json').read_text())
for split,bucket in stats['full'].items():
    families=Counter();fmts=Counter(release['splits'][split]['formats'])
    for source,n in bucket['sources'].items():families[source_family(source)]+=n
    # Preserve original format attribution for unrelated/native/multilingual sources.
    for source,old_type in [(MIP,'Classification'),(QUAREL,'Classification'),(ORDER,'MultipleChoice'),('cladder','Classification')]:
        fmts[old_type]-=release['splits'][split]['sources'].get(source,0)
        fmts['MultipleChoice' if source==QUAREL else old_type]+=bucket['sources'].get(source,0)
    assert sum(fmts.values())==sum(bucket['sources'].values())
    release['splits'][split]={'rows':sum(bucket['sources'].values()),**{k:dict(v) for k,v in bucket.items() if k!='bytes'},'families':dict(families),'formats':dict(fmts)}
release['mix']={s:{'rows':sum(d['sources'].values()),'sources':len(d['sources'])} for s,d in stats['default'].items()}
release['english_task_rebuild']=report
dump(OUT/'release-audit.json',release);dump(OUT/'english-task-rebuild.json',report)
sources=yaml.safe_load((SNAP/'sources.yaml').read_text());sources['sources'].pop('cladder',None)
for source,record in sources['sources'].items():
    record['rows']={s:d['sources'][source] for s,d in stats['full'].items() if d['sources'][source]}
(OUT/'sources.yaml').write_text(yaml.safe_dump(sources,sort_keys=False))
card.text+='''\n### English task correction and benchmark exclusion (2026-10-09)

CLadder is evaluation-only and removed from `default`, `full` and `filtered-full`.
Missing-item decisions now separate the list and query and explicitly ask about
membership; the previous query was at the end of the state. WikiHow order now
asks which step comes first. QuaRel uses native answer texts as MC options with
permuted, correctly remapped golds, replacing fixed A/B classes. Its old
classification-only packs and obsolete generic instruction-paraphrase variants
were removed. Source examples and splits remain; unrelated tasks and vision
are unchanged. Current counts are in the config metadata. See
[rebuild audit](english-task-rebuild.json) and [reproducible script](english-task-rebuild.py).
'''
card.save(OUT/'README.md');dump(OUT/'staged.json',{'files':files,'report':report})
if '--publish' in sys.argv:
    ops=[CommitOperationAdd(path_in_repo=f['path'],path_or_fileobj=f['local']) for f in files]
    for name in ('README.md','sources.yaml','release-audit.json','english-task-rebuild.json'):
        ops.append(CommitOperationAdd(path_in_repo=name,path_or_fileobj=str(OUT/name)))
    ops.append(CommitOperationAdd(path_in_repo='english-task-rebuild.py',path_or_fileobj=__file__))
    c=api.create_commit(REPO,repo_type='dataset',parent_commit=PARENT,operations=ops,commit_message='Rebuild three English decisions and remove evaluation-only CLadder')
    dump(OUT/'published.json',{'revision':c.oid,'url':c.commit_url});print(c.commit_url,flush=True)