"""GPU-only readability measurement; compare the same inputs before/after prover changes.""" import argparse, glob, os, signal, json, collections, statistics, sys, time from pathlib import Path from multiprocessing import Pool REF = ('actor.', 'fixture.', 'area.', 'event.', 'instant.', 'period.') def walk(n, d, acc): if isinstance(n, list): for x in n: walk(x, d, acc) return if not isinstance(n, dict) or 'method' not in n: return m = n['method'] if m.startswith(REF): acc['nodes'] += 1; acc['depth'] = max(acc['depth'], d) if m in ('instant.clock_second', 'period.clock_span'): acc['clock'] += 1 if m == 'actor.appearance': acc['looks'].append(json.dumps(n.get('value'), sort_keys=True, ensure_ascii=False)) acc['look_n'] = max(acc['look_n'], len((n.get('value') or {}).get('look') or [])) for c in (n.get('fill') or {}).values(): walk(c, d+1 if m.startswith(REF) else d, acc) def one(job): d, vs = job from embodied_pipeline.prover import interp, surface def stop(*_): raise TimeoutError() signal.signal(signal.SIGALRM, stop); out = [] for v in vs: cpu, wall = time.process_time(), time.monotonic() signal.alarm(600) try: r = interp.run(d, v) pk = [] for p in r.get('packages') or []: acc = dict(nodes=0, depth=0, clock=0, looks=[], look_n=0) walk(list(p['slots'].values()), 0, acc) from np import prover_questions as questions ids = questions.entity_ids(p['slots']) if hasattr(questions, 'entity_ids') else None text = surface.render(v, p['slots'], 'zh', ids=ids) if ids is not None else surface.render(v, p['slots'], 'zh') pk.append(dict(text=text, nodes=acc['nodes'], depth=acc['depth'], clock=acc['clock'], look_n=acc['look_n'], dup=len(acc['looks'])-len(set(acc['looks'])))) out.append((d, v, r.get('publishable'), r.get('candidates'), r.get('reject_reasons') or {}, pk)) # None 是没求值,不当 0(10-24 rd1 把它混成全拒,挑错了版) except Exception as e: if isinstance(e, TimeoutError): print(f'{v}@{d}: CPU={time.process_time()-cpu:.3f}s wall={time.monotonic()-wall:.3f}s', file=sys.stderr) out.append((d, v, -1, 0, {type(e).__name__+': '+str(e): 1}, [])) signal.alarm(0) return out def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('script_glob', help='glob matching script.json files, with ** recursion') parser.add_argument('count', type=int, help='script count, round-robin across building groups') parser.add_argument('texts', help='output texts JSONL; per-case receipts use .results.jsonl') parser.add_argument('--workers', type=int, default=48) parser.add_argument('--fixture', default=str(Path(os.environ['FIX']) / 'short-90') if os.environ.get('FIX') else None, help='extra comparison script; defaults to $FIX/short-90; empty string disables it') a = parser.parse_args() if a.fixture is None: parser.error('set FIX to the fixture root or pass --fixture (empty string disables comparison)') if a.count < 1 or a.workers < 1: parser.error('count and workers must be positive') V = sorted(json.load(open('embodied_pipeline/prover/plans.json'))['versions']) all_scripts = sorted({os.path.dirname(p) for p in glob.glob(a.script_glob, recursive=True)}) groups = {} for d in all_scripts: groups.setdefault(os.path.basename(d).split('-g')[0], []).append(d) S = [d for k in range(len(all_scripts)) for h in sorted(groups) for d in groups[h][k:k+1]][:a.count] if len(S) != a.count: parser.error(f'requested {a.count} scripts, found {len(S)}') J = [(d, V[i::6]) for i in range(6) for d in S+([a.fixture] if a.fixture else [])] R = [x for xs in Pool(a.workers, maxtasksperchild=1).imap_unordered(one, J) for x in xs] expected = (len(S)+bool(a.fixture))*len(V) with Path(a.texts).with_suffix('.results.jsonl').open('w') as receipt: for d, v, p, c, rr, pk in R: receipt.write(json.dumps(dict(script=d, version=v, publishable=p, candidates=c, reasons=rr, packages=len(pk), ok=p != -1), ensure_ascii=False)+'\n') errors = [(d, v, rr) for d, v, p, c, rr, pk in R if p == -1] print('cases', len(R), '/', expected, 'errors', len(errors)) for error in errors: print('ERROR', error) with open(a.texts, 'w') as f: for d, v, p, c, rr, pk in R: for q in pk: f.write(json.dumps(dict(s=os.path.basename(d), v=v, **q), ensure_ascii=False)+'\n') fx = {v: (p, c, rr) for d, v, p, c, rr, pk in R if d == a.fixture} print('short-90 全拒版(有候选、0 题、有拒因、无 blocked):', [v for v, (p, c, rr) in sorted(fx.items()) if p == 0 and rr and 'blocked:no_evaluable_query' not in rr][:20]) print('short-90 未求值版(publishable 为 None):', sorted(v for v, (p, c, rr) in fx.items() if p is None)[:20]) P = [(v, q) for d, v, p, c, rr, pk in R if d != a.fixture for q in pk] def share(f): return f'{sum(map(f, (q for _, q in P)))}/{len(P)}' print('包', len(P), ' 嵌套≥3', share(lambda q: q['depth'] >= 3), ' 显式钟点≥3', share(lambda q: q['clock'] >= 3), ' 同一外观说两遍', share(lambda q: q['dup'] > 0), ' 外观≥3 项', share(lambda q: q['look_n'] >= 3), ' 字数≥80', share(lambda q: len(q['text']) >= 80)) if not P: print('No packages; measurement failed'); return 1 ch = sorted(len(q['text']) for _, q in P); print('字数 中位', ch[len(ch)//2], ' p90', ch[int(len(ch)*.9)], ' 最长', ch[-1]) by = collections.defaultdict(list) for v, q in P: by[v].append(q) print('逐版(包数, 字数中位, 嵌套≥3 占比, 钟点≥3, 说两遍, 外观≥3 项)按字数中位降序:') print('零包版:', sorted(set(V)-set(by))) for v, qs in sorted(by.items(), key=lambda x: -statistics.median(len(q['text']) for q in x[1])): n = len(qs); f = lambda g: f'{sum(map(g, qs))/n:.0%}' print(f' {v}: {n}, {statistics.median(len(q["text"]) for q in qs):.0f}, {f(lambda q: q["depth"]>=3)}, {f(lambda q: q["clock"]>=3)}, {f(lambda q: q["dup"]>0)}, {f(lambda q: q["look_n"]>=3)}') return int(bool(errors) or len(R) != expected) if __name__ == "__main__": raise SystemExit(main())