bytkim's picture
AgentGridWorld Hard: nine rule-pressure gridworld tasks, with a local player
4a372d3 verified
Raw History Blame Contribute Delete
9.22 kB
"""Explicit pinned fresh model slots; no retries or automatic resumption."""
import argparse
from datetime import datetime, timezone
import json
import os
from pathlib import Path
import subprocess
import sys
from .model import MODEL, LUNA, TERRA, settings, save
from .pool import verify_pool, sha
from . import presentation
from .participant import ACTION_REVISION
SLOTS = [('mini-1', MODEL), ('mini-2', MODEL), ('luna-1', LUNA), ('luna-2', LUNA)]
LABELS={MODEL:'mini',LUNA:'luna',TERRA:'terra'}
def selected_models(models=None):
chosen=[MODEL,LUNA] if models is None else list(models)
if not chosen or len(set(chosen))!=len(chosen) or any(m not in LABELS for m in chosen):
raise ValueError('Select unique supported models')
return chosen
def slots_for(attempts_per_model=2, models=None):
if type(attempts_per_model) is not int or not 1<=attempts_per_model<=8:
raise ValueError('Attempts per model must be 1..8')
return [(f'{label}-{i}',model) for model in selected_models(models) for label in [LABELS[model]]
for i in range(1,attempts_per_model+1)]
def coverage_keys(attempts, models=None):
words={1:'one',2:'two',3:'three',4:'four',6:'six',8:'eight',16:'sixteen'}
word=lambda n:words.get(n,str(n))
return ('any_of_'+word(attempts*len(selected_models(models))), *[LABELS[m]+'_any_of_'+word(attempts) for m in selected_models(models)])
def protocol(pool, temperature=0, attempts_per_model=2, models=None, profile=ACTION_REVISION):
manifest = verify_pool(pool)
slots=slots_for(attempts_per_model,models)
result={**({} if attempts_per_model==2 else {'attempts_per_model':attempts_per_model}), 'schema': 'agentgridworld.evaluation.v1' if attempts_per_model==2 else 'agentgridworld.evaluation.v2',
'pool_manifest_sha256': sha(Path(pool)/'pool.json'),
'task_ids': [r['id'] for r in manifest['tasks']],
'slots': [{'id': name, 'model': model, 'settings': settings(model,temperature,action_only=profile==ACTION_REVISION)} for name, model in slots],
'maximum_model_calls': len(slots)*manifest['maximum_model_calls_per_attempt'],
'metric': 'mixed-model any-of-four compliant success; not a single-model pass@4 estimate' if attempts_per_model==2 else f'mixed-model any-of-{2*attempts_per_model} coverage; per-model any-of-{attempts_per_model} reported separately',
'retry_policy': 'zero; interrupted slots preserved, no automatic retry'}
if models is not None:
result.update(schema='agentgridworld.evaluation.v3',models=selected_models(models),attempts_per_model=attempts_per_model,
metric=f'per-model any-of-{attempts_per_model} compliant success; mixed coverage reported separately')
if profile != 'auto':
result['presentation'] = profile
result['presentation_profile_sha256'] = presentation.profile_sha256(profile)
return result
def aggregate(plan, reviews):
attempt_count=plan.get('attempts_per_model',2);models=plan.get('models');slots=slots_for(attempt_count,models)
keys=coverage_keys(attempt_count,models)
if [(s['id'],s['model']) for s in plan['slots']]!=slots or len(reviews)!=len(slots):
raise ValueError('Exactly the pinned model slots are required')
expected = set(plan['task_ids'])
for slot, report in zip(plan['slots'], reviews):
if (report['job'] != slot['id'] or not report['all_trials_verified']
or report['pool_manifest_sha256'] != plan['pool_manifest_sha256']
or len(report['tasks']) != len(expected)
or {r['id'] for r in report['tasks']} != expected
or any(r['model'] != slot['model'] for r in report['tasks'])):
raise ValueError('Evaluation slot membership/model mismatch')
rows = []
for task in plan['task_ids']:
attempts = [next(r for r in report['tasks'] if r['id'] == task) for report in reviews]
if len({r['classification'] for r in attempts}) != 1:
raise ValueError('Task classification changed')
successes = [r['outcome']['success'] for r in attempts]
rows.append({'id': task, 'environment': attempts[0]['environment'],
'classification': attempts[0]['classification'],
'successes': successes, keys[0]: any(successes),
**{key:any(successes[i*attempt_count:(i+1)*attempt_count]) for i,key in enumerate(keys[1:])},
'reported_rewards': [r['outcome']['reported_reward'] for r in attempts]})
def summary(items):
return {'tasks': len(items), **{k: sum(r[k] for r in items)
for k in keys}}
return {'schema': 'agentgridworld.evaluation.review.v3' if models is not None else 'agentgridworld.evaluation.review.v1' if attempt_count==2 else 'agentgridworld.evaluation.review.v2',
'qualification': 'complete', 'protocol': plan,
'episodes_verified': len(slots)*len(rows), 'all_tasks': summary(rows),
'solvable_tasks': summary([r for r in rows if r['classification'] == 'possible']),
'per_environment': {name: summary([r for r in rows if r['environment'] == name])
for name in sorted({r['environment'] for r in rows})},
'per_slot': [{k:v for k,v in r.items() if k != 'tasks'} for r in reviews],
'model_calls': sum(r['model_calls'] for r in reviews),
'input_tokens': sum(r['input_tokens'] for r in reviews),
'output_tokens': sum(r['output_tokens'] for r in reviews), 'tasks': rows}
def review_evaluation(pool, root):
from .review import review
root = Path(root)
plan = json.loads((root/'protocol.json').read_text())
if plan != protocol(pool,plan['slots'][0]['settings']['temperature'],plan.get('attempts_per_model',2),profile=plan.get('presentation','auto'),**({'models':plan['models']} if 'models' in plan else {})):
raise ValueError('Protocol changed since launch')
for slot in plan['slots']:
binding=json.loads((root/'jobs'/(slot['id']+'.pool-binding.json')).read_text())
if 'presentation' in plan and binding.get('presentation','base') != plan['presentation']:
raise ValueError('Slot presentation differs from campaign protocol')
if binding.get('settings')!=slot['settings']:
raise ValueError('Slot sampling differs from campaign protocol')
reviews = [review(pool, root/'jobs'/slot['id']) for slot in plan['slots']]
return aggregate(plan, reviews), reviews
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--pool', type=Path, required=True)
parser.add_argument('--output', type=Path)
parser.add_argument('--review', type=Path)
parser.add_argument('--env-file', type=Path)
parser.add_argument('--modal-profile')
parser.add_argument('--temperature',type=float,default=0)
parser.add_argument('--attempts-per-model',type=int,default=2)
parser.add_argument('--presentation',choices=presentation.PROFILES,default=ACTION_REVISION)
parser.add_argument('--models',nargs='+',choices=list(LABELS))
args = parser.parse_args()
if bool(args.output) == bool(args.review):
parser.error('Choose exactly one of --output or --review')
pool = args.pool.resolve()
if args.review:
root = args.review.resolve()
if (root/'summary.json').exists():
raise FileExistsError('Review already recorded')
result, reviews = review_evaluation(pool, root)
for slot, report in zip(result['protocol']['slots'], reviews):
save(root/(slot['id']+'.readback.json'), report)
save(root/'summary.json', result)
print(json.dumps({k:v for k,v in result.items() if k not in ('tasks','protocol','per_slot')}, indent=2))
return
root = args.output.resolve()
root.mkdir(parents=True, exist_ok=False)
plan = protocol(pool,args.temperature,args.attempts_per_model,args.models,profile=args.presentation)
save(root/'protocol.json', plan)
for slot in plan['slots']:
command = [sys.executable, '-m', 'agentgridworld.run', '--pool', str(pool),
'--mode', 'model', '--model', slot['model'], '--job-name', slot['id'],
'--jobs-dir', str(root/'jobs')]
if args.presentation != 'auto':command += ['--presentation',args.presentation]
if args.env_file: command += ['--env-file', str(args.env_file.resolve())]
if args.modal_profile: command += ['--modal-profile', args.modal_profile]
if args.temperature!=0: command += ['--temperature',str(args.temperature)]
print('Starting', slot['id'], flush=True)
result = subprocess.run(command, env={**os.environ, 'PYTHONHASHSEED':'0'})
save(root/(slot['id']+'.completion.json'), {'exit_code':result.returncode,
'finished_at':datetime.now(timezone.utc).isoformat()})
if result.returncode:
raise SystemExit('Slot failed; evidence preserved. No automatic retry.')
print(f'{len(plan["slots"])} slots finished; independent replay review is required.', flush=True)
if __name__ == '__main__': main()