Datasets:
Download code/evaluation-code/v0.2-0c2690ae/np/final_select.py from VEHwang/cocogni4d: direct link, hf CLI and curl.
- Browser
- Download file 9.14 kB
-
https://huggingface.co/datasets/VEHwang/cocogni4d/resolve/main/code/evaluation-code/v0.2-0c2690ae/np/final_select.py
- Command line
-
hf download hf://datasets/VEHwang/cocogni4d/code/evaluation-code/v0.2-0c2690ae/np/final_select.py
-
curl -L -o final_select.py https://huggingface.co/datasets/VEHwang/cocogni4d/resolve/main/code/evaluation-code/v0.2-0c2690ae/np/final_select.py
9.14 kB
| """Seeded version × source-half quotas with catalog-nearest refill in each half.""" | |
| import hashlib | |
| import random | |
| from collections import Counter, defaultdict | |
| from embodied_pipeline.prover import final_balance, pose_balance | |
| def _rng(seed, key): | |
| return random.Random(hashlib.sha256(f'{seed}:{key}'.encode()).digest()) | |
| def _shares(weights, total, rng): | |
| keys = sorted(weights) | |
| rng.shuffle(keys) | |
| denominator = sum(weights.values()) | |
| shares = {k: weights[k] * total // denominator for k in keys} | |
| for k in sorted(keys, key=lambda k: -(weights[k] * total % denominator))[:total-sum(shares.values())]: | |
| shares[k] += 1 | |
| return shares | |
| def tree(families): | |
| """Family → subject → form → version, in the same order as quota_defaults.""" | |
| result = {} | |
| for family in families: | |
| subjects = result.setdefault(family['id'], {}) | |
| for version in family['versions']: | |
| vid = version['id'] | |
| form = vid.split('/')[0] | |
| subject = '.'.join(form.split('.')[:2]) | |
| subjects.setdefault(subject, {}).setdefault(form, {})[vid] = vid | |
| return result | |
| def select(rows, quotas, families, *, seed=0, pool_of=None): | |
| """Sample PASS rows within each source half. Old unlabeled rows cannot fill either half. | |
| pool_of reads the segment's fixed generator config in production; tags.pool is useful | |
| for already exported items. Odd quotas give the seeded first half the extra slot. | |
| """ | |
| root = tree(families) | |
| def leaves(node): | |
| if isinstance(node, str): | |
| return [node] | |
| return [vid for child in node.values() for vid in leaves(child)] | |
| versions = leaves(root) | |
| pool_of = pool_of or (lambda row: (row.get('tags') or {}).get('pool')) | |
| chosen, details, remaining = {}, {}, {} | |
| for vid in versions: | |
| quota = quotas.get(vid, 0) | |
| if not isinstance(quota, int) or isinstance(quota, bool) or quota < 0: | |
| raise ValueError(f'{vid}: quota must be a nonnegative integer') | |
| buckets = {p: [] for p in ('anti_shortcut', 'natural', 'unlabeled')} | |
| for row in rows.get(vid, []): | |
| if row.get('decision', {}).get('result') != 'PASS': | |
| continue | |
| pool = pool_of(row) or 'unlabeled' | |
| if pool not in buckets: | |
| raise ValueError(f'{vid}: unknown source pool {pool!r}') | |
| buckets[pool].append(row) | |
| rng = _rng(seed, vid) | |
| halves = ['anti_shortcut', 'natural'] | |
| rng.shuffle(halves) | |
| chosen[vid], strata, remaining[vid] = [], {}, {} | |
| for i, pool in enumerate(halves): | |
| need = quota // 2 + int(quota % 2 and i == 0) | |
| values = pose_balance.packets(buckets[pool], seed) | |
| unit = all(len(packet) == 1 for packet in values) | |
| draws = rng.sample(values, min(need, len(values)) if unit else len(values)) | |
| kept, kept_packets = [], set() | |
| for packet in draws: | |
| if len(kept) + len(packet) <= need: | |
| kept.extend(packet) | |
| kept_packets.add(id(packet)) | |
| chosen[vid].extend(kept) | |
| available = sum(map(len, values)) | |
| strata[pool] = dict(quota=need, available=available, taken=len(kept), unfilled=need-len(kept)) | |
| if vid in pose_balance.VERSIONS: | |
| strata[pool]['balance_dropped'] = len(buckets[pool]) - available | |
| spare = [packet for packet in values if id(packet) not in kept_packets] | |
| rng.shuffle(spare) | |
| remaining[vid][pool] = spare | |
| details[vid] = dict(quota=quota, available=sum(map(len, buckets.values())), taken=len(chosen[vid]), | |
| received=0, pools=strata, unlabeled=len(buckets['unlabeled'])) | |
| def refill(node, pool): | |
| if isinstance(node, str): | |
| return [node] * details[node]['pools'][pool]['unfilled'] | |
| gaps = [vid for child in node.values() for vid in refill(child, pool)] | |
| candidates = leaves(node) | |
| while gaps: | |
| spare = [vid for vid in candidates if any(len(p) <= len(gaps) for p in remaining[vid][pool])] | |
| if not spare: | |
| break | |
| for vid in spare: | |
| values = remaining[vid][pool] | |
| index = next((i for i in range(len(values)-1, -1, -1) if len(values[i]) <= len(gaps)), None) | |
| if index is None: | |
| continue | |
| packet = values.pop(index) | |
| chosen[vid].extend(packet) | |
| details[vid]['taken'] += len(packet) | |
| details[vid]['received'] += len(packet) | |
| details[vid]['pools'][pool]['taken'] += len(packet) | |
| for _ in packet: | |
| details[gaps.pop(0)]['pools'][pool]['unfilled'] -= 1 | |
| if not gaps: | |
| break | |
| return gaps | |
| for pool in ('anti_shortcut', 'natural'): | |
| refill(root, pool) | |
| shortages = [dict(version=vid, pool=pool, missing=s['unfilled']) | |
| for vid in versions for pool, s in details[vid]['pools'].items() if s['unfilled']] | |
| report = dict(seed=seed, versions=details, shortages=shortages, unfilled=sum(s['missing'] for s in shortages)) | |
| unknown = [vid for vid in quotas if vid not in details] | |
| if unknown: | |
| report['unknown'] = unknown | |
| return chosen, report | |
| def select_groups(rows, *, seed=0, versions=()): | |
| """Balance abilities using complete 3+3 packs, preserving input row order. | |
| rows maps script IDs to grouped question rows. Version-composition strata get | |
| proportional integer shares (largest remainder) seed the preference; joint | |
| answer and pose constraints may change shares. No row or pack is repeated. | |
| Missing counts compare with the larger original ability supply, not new demand. | |
| """ | |
| packets = defaultdict(list) | |
| for sid, values in rows.items(): | |
| for row in values: | |
| g = row['scope']['group'] | |
| if g['unit'].split('.')[0] not in ('1', '2', '3', '4', '5'): | |
| raise ValueError(f"unknown ability unit: {g['unit']}") | |
| packets[sid, g['unit'], g['id']].append(row) | |
| pools = {'1-4': [], '5': []} | |
| invalid = [] | |
| before = Counter(dict.fromkeys(versions, 0)) | |
| for key, packet in sorted(packets.items()): | |
| slots = [(r['scope']['group']['set'], r['scope']['group']['slot']) for r in packet] | |
| if (len(packet) != 6 or set(slots) != {(s, f'{s}{i}') for s in range(2) for i in range(3)} | |
| or any(r.get('decision', {}).get('result') != 'PASS' for r in packet)): | |
| invalid.append(dict(script_id=key[0], unit=key[1], id=key[2], rows=len(packet))) | |
| continue | |
| pools['5' if key[1].startswith('5.') else '1-4'].append((key, packet)) | |
| before.update(r['public']['version_id'] for r in packet) | |
| target = min(map(len, pools.values())) | |
| demand = max(map(len, pools.values())) | |
| selected = set() | |
| for ability, pool in pools.items(): | |
| strata = defaultdict(list) | |
| for key, packet in pool: | |
| composition = tuple(sorted(Counter(r['public']['version_id'] for r in packet).items())) | |
| strata[composition].append((key, packet)) | |
| rng = _rng(seed, ability) | |
| shares = _shares({k: len(v) for k, v in strata.items()}, target, rng) | |
| for k, count in shares.items(): | |
| selected.update(key for key, _ in rng.sample(strata[k], count)) | |
| selected, balance = final_balance.select(sorted(pools['1-4']+pools['5']), selected) | |
| taken = {g: sum(key in selected for key, _ in p) for g, p in pools.items()} | |
| chosen = {sid: [r for r in values if (sid, r['scope']['group']['unit'], r['scope']['group']['id']) in selected] | |
| for sid, values in rows.items()} | |
| after = Counter(r['public']['version_id'] for values in chosen.values() for r in values) | |
| report = dict(seed=seed, unit='complete_3+3_pack', ratio=1.0 if selected else None, | |
| invalid_packs=len(invalid), invalid=invalid, | |
| balance=balance, | |
| groups={g: dict(available=len(p), target=demand, taken=taken[g], | |
| missing=demand-len(p), dropped=len(p)-taken[g], | |
| questions_before=6*len(p), questions_after=6*taken[g]) | |
| for g, p in pools.items()}, | |
| versions={v: dict(available=before[v], taken=after[v], missing=before[v]-after[v]) | |
| for v in sorted(before)}) | |
| for ability, pool in pools.items(): | |
| available = Counter(r['public']['version_id'] for _, packet in pool for r in packet) | |
| taken = Counter(r['public']['version_id'] for key, packet in pool if key in selected for r in packet) | |
| wanted = _shares(available, 6*demand, _rng(seed, ability + ':shortage')) if pool else {} | |
| report['groups'][ability]['versions'] = { | |
| v: dict(available=available[v], target=wanted[v], taken=taken[v], missing=wanted[v]-taken[v], | |
| dropped=available[v]-taken[v]) for v in sorted(available)} | |
| return chosen, report | |