Download tasks/t39-rct-onetile/tests/grade.py from refreshdotdev/Refresh-GUI-dataset: direct link, hf CLI and curl.
- Browser
- Download file 14.1 kB
-
https://huggingface.co/datasets/refreshdotdev/Refresh-GUI-dataset/resolve/main/tasks/t39-rct-onetile/tests/grade.py
- Command line
-
hf download hf://datasets/refreshdotdev/Refresh-GUI-dataset/tasks/t39-rct-onetile/tests/grade.py
-
curl -L -o grade.py https://huggingface.co/datasets/refreshdotdev/Refresh-GUI-dataset/resolve/main/tasks/t39-rct-onetile/tests/grade.py
14.1 kB
| """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() | |