File size: 14,113 Bytes
7ec48b5 | 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 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 | """Grade the one-tile run: did it reach the objective, and how fast.
The reward is binary. Either the engine settled the stock guests-and-rating
objective -- the task's guest target in the park at a rating of at least 700 -- or
it did not, and nothing in between earns anything. There is no deadline and no partial
credit: how long the agent took is reported, not discounted, and models are
ranked against each other on `in_game_days`.
A run is three attempts, and `in_game_days` is the total across all of them. A
park that closes down can be started again from a pristine copy, so a model that
wins on its third attempt is credited with the win and charged for the days the
first two burned. That is the only thing an attempt costs, and it is what keeps
the ranking comparable between a model that got it right first time and one that
needed the practice.
Completion is never taken from telemetry alone. The engine's own objective must
have succeeded, corroborated by a native save reopened in a separate headless
engine, carrying the controller's origin marker and a scenario that still
matches the one this task hands out.
Everything else in the output -- peak guests, owned tiles, the rating clock --
is there to calibrate the target. None of it is scored.
"""
import argparse
import json
import os
from pathlib import Path
RATING_THRESHOLD = 700 # the engine's own threshold for this objective
# Attempts a run is allowed. run-supervisor.py compiles the same number into the
# controller, which stamps it on the hand-over; if the two disagree the run was
# played under rules this grader does not know, which is an evaluation error.
ATTEMPTS_ALLOWED = 3
# The target this task declares, shipped beside the grader. Two tasks share this
# environment and these tests -- a calibrated target and the video's 1,000 -- and
# this file is the one place they are meant to differ.
DECLARED_TARGET = Path(__file__).with_name('target-guests.txt')
def _parse_target(raw, source):
try:
guests = int(raw)
except ValueError:
raise ValueError(f'T39_TARGET_GUESTS must be an integer, got {raw!r} from {source}')
if guests < 1:
raise ValueError(f'T39_TARGET_GUESTS must be positive, got {guests} from {source}')
return guests
def target_guests():
"""The target to grade against: guests in the park at one moment, not admissions.
Two sources, and they have to agree. `target-guests.txt` is what the task
declares; `T39_TARGET_GUESTS` is what the run was actually given, and the run
has to have been given the same number the scenario was built with. If they
disagree, or if neither is there, that is an evaluation error -- grading a
200-guest run against 1,000, or the reverse, would be worse than refusing.
"""
raw_env = os.environ.get('T39_TARGET_GUESTS', '').strip()
raw_file = DECLARED_TARGET.read_text().strip() if DECLARED_TARGET.exists() else ''
if not raw_env and not raw_file:
raise ValueError('T39_TARGET_GUESTS is unset and '
f'{DECLARED_TARGET.name} is missing: no target to grade against')
from_env = _parse_target(raw_env, 'T39_TARGET_GUESTS') if raw_env else None
from_file = _parse_target(raw_file, DECLARED_TARGET.name) if raw_file else None
if None not in (from_env, from_file) and from_env != from_file:
raise ValueError(f'T39_TARGET_GUESTS is {from_env} but '
f'{DECLARED_TARGET.name} declares {from_file}')
return from_env if from_env is not None else from_file
def origin(guests):
"""The controller's marker. The target is in it, so a save from the other
task cannot pass as a completion of this one."""
return f'onetile-v1-{guests}guests-001'
def expected(guests):
"""The scenario onetile-config.js applies. A save that disagrees was not this
task, so it cannot be graded as a completion of it."""
return {
'mapSizeX': 52, 'mapSizeY': 52, # 50x50 playable
'landPrice': 900, # $90.00 a tile
'maxLoan': 0, # no borrowing
'objectiveType': 'guestsAndRating',
'objectiveGuests': guests,
}
def expected_baseline(guests):
"""What the controller must have recorded at hand-over, as a check on the
environment rather than on the agent."""
return {
'ownedTiles': 1, 'playable': 50, 'landPrice': 900, 'maxBankLoan': 0,
'objectiveGuests': guests, 'freeParkEntry': False,
# The engine disables the park window's open/close control for this
# objective type, so a park handed over closed can never be opened and
# the run is unwinnable. Not the agent's zero.
'parkOpen': True,
}
def scenario_intact(native, guests):
"""Does the reopened save still describe the scenario that was handed out?"""
want = expected(guests)
return {key: native.get(key) for key in want} == want
def this_run(events):
"""The part of the audit stream that belongs to the run being graded.
The audit is append-only and /logs is a Docker volume that can outlive a
container, so an earlier run's stream may be sitting in front of this one --
and with attempts counted by hand-overs, a stale one would charge this run for
attempts it never took. The supervisor stamps `run_started` when it takes the
engine; everything from the last of those is this run.
"""
starts = [index for index, event in enumerate(events)
if event.get('kind') == 'run_started']
return events[starts[-1]:] if starts else events
def check_baseline(events, guests):
"""The hand-over state of the last attempt, from the trusted controller.
Raises if any attempt was handed over wrong.
A baseline that does not match means the environment did not build the
scenario it promised, which is an evaluation error and not an agent's zero.
Every attempt is checked, not just the last: a restart that handed back a
different park would be a different task.
"""
initialized = [e for e in events if e.get('kind') == 'onetile_initialized']
if not initialized:
raise ValueError('Missing one-tile baseline')
for attempt, record in enumerate(initialized, start=1):
baseline = record.get('baseline') or {}
wrong = {key: baseline.get(key) for key, want in expected_baseline(guests).items()
if baseline.get(key) != want}
if wrong:
raise ValueError(f'Scenario was not configured as specified '
f'on attempt {attempt}: {wrong}')
allowed = baseline.get('attemptsAllowed')
if allowed != ATTEMPTS_ALLOWED:
raise ValueError(f'Run allowed {allowed} attempts but this grader '
f'scores {ATTEMPTS_ALLOWED}')
return initialized[-1].get('baseline') or {}
def grade(events, saved, guests=None):
"""Score the run and report both clocks."""
guests = target_guests() if guests is None else guests
events = this_run(events)
baseline = check_baseline(events, guests)
if any(e.get('kind') in ('controller_error', 'observer_error') for e in events):
raise ValueError('Controller/instrumentation failure')
samples = [e for e in events if e.get('kind') in
('onetile_state', 'onetile_save', 'outcome_state', 'baseline_state')]
if not samples:
raise ValueError('Missing state observations')
days = [e for e in events if e.get('kind') == 'onetile_day']
native = saved or {}
completions = [e for e in events if e.get('kind') == 'objective_complete']
failures = [e for e in events if e.get('kind') == 'objective_failed']
# A completion is the last word on a run whichever attempt it came on, so it
# is preferred over the save's own record -- the save may be an earlier
# attempt's. It still has to be corroborated by the save below.
outcome = ((completions[-1].get('outcome') if completions else None)
or native.get('outcome')
or (failures[-1].get('outcome') if failures else None))
attempts_used = len([e for e in events if e.get('kind') == 'onetile_initialized'])
# Each attempt's own day count, in order: the ranked figure is their sum.
by_attempt = {}
for day in days:
index = day.get('attempt') or 1
by_attempt[index] = max(by_attempt.get(index, 0), day.get('inGameDays') or 0)
days_played = sum(by_attempt.values())
# Playing a fourth park is not a fourth attempt: the run ended with the third.
over_limit = attempts_used > ATTEMPTS_ALLOWED
settled_on = (outcome or {}).get('attempt') or 1
def highest(field):
# The outcome record is included: it is the authoritative last word on a
# settled run, and a run that ended early may have no later sample.
return max([s.get(field) or 0 for s in samples]
+ [d.get(field) or 0 for d in days]
+ [native.get(field) or 0, (outcome or {}).get(field) or 0])
# A restart loads a pristine park and is counted as an attempt. Loading a park
# that had already been played is a rewind to a better moment instead, and it
# proves nothing, so the run stops counting.
valid = not any(e.get('kind') == 'onetile_reloaded' for e in events[:-1])
intact = scenario_intact(native, guests) if saved else False
complete = bool(
completions
and saved is not None
and valid
and not over_limit
and settled_on <= ATTEMPTS_ALLOWED
and intact
and native.get('origin') == origin(guests)
and native.get('scenarioStatus') == 'completed'
and (outcome or {}).get('result') == 'completed'
and ((outcome or {}).get('guests') or 0) >= guests
and ((outcome or {}).get('rating') or 0) >= RATING_THRESHOLD)
# The ranking metric. In-game days across every attempt are the clock the
# engine kept; the wall clock is a diagnostic, since fast-forward decouples
# the two. An older stream with no total is a single attempt by definition.
total_days = ((outcome or {}).get('totalInGameDays')
if (outcome or {}).get('totalInGameDays') is not None
else (outcome or {}).get('inGameDays'))
in_game_days = total_days if complete else None
return {
'schema': 1,
'reward': 1.0 if complete else 0.0,
'completion': 'complete' if complete else 'incomplete',
'speed_metric': 'in_game_days',
'in_game_days': in_game_days,
'in_game_days_final_attempt': (outcome or {}).get('inGameDays') if complete else None,
'attempts_allowed': ATTEMPTS_ALLOWED,
'attempts_used': attempts_used,
'attempts_failed': len(failures),
'settled_on_attempt': settled_on if complete else None,
'in_game_days_by_attempt': [by_attempt[k] for k in sorted(by_attempt)],
'attempt_limit_exceeded': over_limit,
'in_game_ticks': (outcome or {}).get('inGameTicks') if complete else None,
'in_game_months': (outcome or {}).get('monthsElapsed') if complete else None,
'wall_clock_seconds': (outcome or {}).get('wallClockSeconds') if complete else None,
# Unscored progress, for calibrating the target.
'target_guests': guests,
'peak_guests': highest('peakGuests') or highest('guests'),
'peak_owned_tiles': highest('peakOwnedTiles') or highest('ownedTiles'),
'owned_tiles_final': native.get('ownedTiles') if saved else highest('ownedTiles'),
'peak_rating': highest('peakRating') or highest('rating'),
'rating_warning_days_max': highest('ratingWarningDays'),
# Every attempt's days, whether or not anything was settled: this is what
# in_game_days would have been had the run finished.
'in_game_days_played': days_played,
'months_played': highest('monthsElapsed'),
'cash_final': native.get('cash') if saved else None,
'objective_completed_in_game': bool(completions),
'objective_failed_in_game': bool(failures),
# How the run ended, not how an attempt did: a park that closed down on
# attempt 1 and was restarted did not close the run down.
'park_closed_down': bool(failures) and not completions
and len(failures) >= attempts_used,
'native_save_reopened': saved is not None,
'scenario_intact': intact,
'reloaded': not valid,
'blocked_actions': sum(1 for e in events if e.get('kind') == 'blocked_action'),
'baseline': baseline,
'outcome': outcome,
}
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--artifacts', type=Path, default=Path('/logs/artifacts'))
parser.add_argument('--output', type=Path, default=Path('/logs/verifier'))
parser.add_argument('--saved-state', type=Path, default=None,
help='Reopened native state for the run')
parser.add_argument('--target-guests', type=int, default=None,
help='Grade against this target instead of resolving it '
'from target-guests.txt and T39_TARGET_GUESTS')
args = parser.parse_args()
args.output.mkdir(parents=True, exist_ok=True)
for name in ('reward.txt', 'reward.json', 'evaluation-error.txt'):
(args.output / name).unlink(missing_ok=True)
try:
events = [json.loads(line) for line in
(args.artifacts / 'audit/game.jsonl').read_text().splitlines() if line.strip()]
saved = json.loads(args.saved_state.read_text()) if args.saved_state else None
result = grade(events, saved, guests=args.target_guests)
(args.output / 'scores.json').write_text(json.dumps(result, indent=2) + '\n')
(args.output / 'reward.txt').write_text(str(result['reward']) + '\n')
print(json.dumps(result))
except Exception as error:
(args.output / 'evaluation-error.txt').write_text(str(error) + '\n')
raise
if __name__ == '__main__':
main()
|