sidrefresh's picture
Add files using upload-large-folder tool
5463b45 verified
Raw History Blame Contribute Delete
9.68 kB
"""Grade preserved Micro Park observations.
The score belongs to the session, not to a single try. Reaching the $100,000
park value in any attempt is half of it; the other half asks whether the agent
used the three attempts it was given — that it wrote its learnings down, that it
played all three, and that the third attempt was better than the first two.
Reaching the target waives the rest: the environment ends the session the moment
the objective completes, so an agent that wins on attempt 1 cannot play or note
attempts that no longer exist. A completion therefore scores 1.0 outright.
Completion is never taken from telemetry alone: the engine's own objective must
have succeeded inside the deadline, corroborated by a native save reopened in a
separate headless engine.
"""
import argparse
import json
from pathlib import Path
TARGET = 1_000_000 # $100,000 park value, in game currency units
DEADLINE_MONTHS = 16 # two in-game years of eight months each
EXPECTED_TRIES = 3 # the session the instructions promise
WEIGHTS = {'goal': .50, 'improvement': .40, 'notes': .05, 'attempts': .05}
def clamp(value):
return max(0., min(1., value))
def grade(events, saved):
"""Describe one try. Diagnostic only: the reward is a session-level figure."""
if not any(e.get('kind') == 'micropark_initialized' for e in events):
raise ValueError('Missing Micro Park baseline')
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 ('micropark_state', 'micropark_save', 'outcome_state')]
if not samples:
raise ValueError('Missing state observations')
latest = samples[-1]
days = [e for e in events if e.get('kind') == 'micropark_day']
native = saved or {}
completion_events = [e for e in events if e.get('kind') == 'objective_complete']
peak = max([s.get('peakParkValue') or 0 for s in samples]
+ [s.get('parkValue') or 0 for s in samples]
+ [native.get('peakParkValue') or 0, native.get('parkValue') or 0])
months = max([s.get('monthsElapsed') or 0 for s in samples] + [native.get('monthsElapsed') or 0])
customers = max([s.get('totalCustomers') or 0 for s in samples] + [0])
rating = max([s.get('rating') or 0 for s in samples] + [0])
open_rides = max([s.get('openRides') or 0 for s in samples] + [0])
profitable = [d for d in days if (d.get('operatingNet') or 0) > 0]
complete = bool(
completion_events
and saved is not None
and native.get('origin') == 'micropark-v1-2yr-001'
and native.get('scenarioStatus') == 'completed'
and native.get('objectiveType') == 'parkValueBy'
and native.get('objectiveYear') == 2
and native.get('objectiveTarget') == TARGET
and (native.get('outcome') or {}).get('result') == 'completed'
and (native.get('outcome') or {}).get('monthsElapsed', DEADLINE_MONTHS + 1) <= DEADLINE_MONTHS
)
# Reloading a save is disallowed: it would let a failed deadline be retried.
# Such a try proves nothing, so it neither completes nor reports a peak.
valid = not any(e.get('kind') == 'micropark_reloaded' for e in events)
return {
'valid': valid,
'completion': 'complete' if (complete and valid) else 'incomplete',
'objective_completed_in_game': bool(completion_events),
'objective_failed_in_game': any(e.get('kind') == 'objective_failed' for e in events),
'reloaded': not valid,
'peak_park_value': peak if valid else 0,
'park_value_target': TARGET,
'park_value_fraction': clamp((peak if valid else 0) / TARGET),
'months_elapsed': months,
'deadline_months': DEADLINE_MONTHS,
'total_customers': customers,
'park_rating': rating,
'open_rides': open_rides,
'cash': native.get('cash') if saved else latest.get('cash'),
'in_game_days_recorded': len(days),
'profitable_days': len(profitable),
'native_save_reopened': saved is not None,
'blocked_actions': sum(1 for e in events if e.get('kind') == 'blocked_action'),
'outcome': native.get('outcome') or (completion_events[-1].get('outcome') if completion_events else None),
}
def notes_written(events):
"""Did the agent write anything of its own in the notepad?
The supervisor measures /notes when each try starts and ends, and reports the
size of the seed the environment installed there. Anything larger than the
seed is the agent's own writing. Runs from before the seed was reported fall
back to the first measurement, which is the seeded file unless the agent got
there first. None means no measurement at all (an older run still).
"""
marks = [event for event in events
if event.get('kind') in ('try_started', 'try_ended')]
sizes = [event['notes_bytes'] for event in marks
if isinstance(event.get('notes_bytes'), int)]
if not sizes:
return None
seeds = [event['notes_seed_bytes'] for event in marks
if isinstance(event.get('notes_seed_bytes'), int)]
baseline = min(seeds) if seeds else sizes[0]
return any(size > baseline for size in sizes)
def improved(peaks):
"""Was the third attempt better than the first two?
Needs all three attempts with trustworthy peaks; a reloaded try reports
none, so a session containing one cannot claim the improvement.
"""
if any(peaks.get(number) is None for number in (1, 2, 3)):
return False
return peaks[3] > peaks[1] and peaks[3] > peaks[2]
def grade_campaign(events, saved_by_try):
"""Score the session: goal, improvement, notes, attempts played."""
numbers = sorted({event.get('try', 1) for event in events
if event.get('kind') == 'micropark_initialized'})
if not numbers:
raise ValueError('Missing Micro Park baseline')
tries = []
for number in numbers:
result = grade([event for event in events if event.get('try', 1) == number],
saved_by_try.get(number))
tries.append(dict(result, **{'try': number}))
# How many attempts the environment offered, from the trusted controller's
# own baseline; the promised three when a run predates that field.
declared = [event['tries'] for event in events
if event.get('kind') == 'micropark_initialized' and event.get('tries')]
available = max(declared) if declared else EXPECTED_TRIES
peaks = {result['try']: (result['peak_park_value'] if result['valid'] else None)
for result in tries}
goal = next((result for result in tries if result['completion'] == 'complete'), None)
wrote = notes_written(events)
scores = {
'goal': float(goal is not None),
'improvement': float(improved(peaks)),
'notes': float(bool(wrote)),
'attempts': float(len(tries) >= available),
}
# Reaching the target ends the session, so the attempts it cut short cannot
# be held against the agent: a verified completion scores everything.
waived = goal is not None
if waived:
scores = {key: 1. for key in WEIGHTS}
weighted = {key: round(value * WEIGHTS[key], 6) for key, value in scores.items()}
best = max(tries, key=lambda result: (result['completion'] == 'complete',
result['peak_park_value']))
return {
'schema': 2,
'reward': round(sum(weighted.values()), 6),
'completion': 'complete' if goal else 'incomplete',
'goal_try': goal['try'] if goal else None,
'scored_components': scores,
'weighted_scores': weighted,
'component_waiver': waived,
'notes_written': wrote,
'peaks_by_try': peaks,
'peak_park_value': best['peak_park_value'],
'park_value_target': TARGET,
'tries': tries,
'tries_played': len(tries),
'tries_available': available,
'best_try': best['try'],
}
def parse_saved_state(value):
"""`2=/path/to/state.json`, or a bare path meaning the only try."""
number, separator, path = value.partition('=')
if not separator:
return 1, Path(value)
return int(number), Path(path)
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', action='append', default=[],
metavar='TRY=PATH', help='Reopened native state for one try')
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 = {}
for value in args.saved_state:
number, path = parse_saved_state(value)
saved[number] = json.loads(path.read_text())
result = grade_campaign(events, saved)
(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()