Download gui_interaction/src/experiment.py from Gen-Verse/RSI-Anything: direct link, hf CLI and curl.
- Browser
- Download file 7.12 kB
-
https://huggingface.co/datasets/Gen-Verse/RSI-Anything/resolve/main/gui_interaction/src/experiment.py
- Command line
-
hf download hf://datasets/Gen-Verse/RSI-Anything/gui_interaction/src/experiment.py
-
curl -L -o experiment.py https://huggingface.co/datasets/Gen-Verse/RSI-Anything/resolve/main/gui_interaction/src/experiment.py
7.12 kB
| """Frozen-policy browser inference.""" | |
| import argparse, json, random, time, math, urllib.request | |
| from pathlib import Path | |
| from common import ROOT, PORT, atomic, atomic_jsonl, context, correctness, digest, legal_actions, checkpoint_identity, effective_cost | |
| from gui_env import GUIEnv, rule_action | |
| def rank(obs, adapter=None): | |
| visible = {k: obs[k] for k in ['instruction', 'elements', 'remaining_actions']} | |
| payload = json.dumps({'observation': visible, 'adapter': str(adapter) if adapter else None}).encode() | |
| req = urllib.request.Request(f'http://127.0.0.1:{PORT}/rank', data=payload, headers={'Content-Type': 'application/json'}) | |
| with urllib.request.urlopen(req, timeout=180) as response: | |
| result = json.load(response) | |
| if not result.get('actions') or {'kind': 'submit'} not in result['actions']: | |
| raise RuntimeError('Invalid terminal-inclusive candidate pool') | |
| return result | |
| def sigmoid(x): | |
| return 1 / (1 + math.exp(-max(-60.0, min(60.0, x)))) | |
| def select(proposal, forecasts, controller): | |
| alpha = controller.get('alpha', 0.0) | |
| policy = [math.log(max(proposal['probabilities'][i], 1e-12)) for i in proposal['candidate_ids']] | |
| if alpha == 0: | |
| return (0, {'scores': policy, 'alpha': 0.0, 'world_used': False}) | |
| calibration = controller.get('terminal', {'temperature': 1.0, 'bias': 0.0}) | |
| values = [] | |
| for (action, prediction) in zip(proposal['actions'], forecasts): | |
| if action['kind'] == 'submit': | |
| v = 2 * sigmoid(prediction['submit_success_logit'] / calibration['temperature'] + calibration['bias']) - 1 | |
| else: | |
| v = prediction['value'] | |
| values.append(v) | |
| if alpha == 'pure': | |
| scores = values | |
| else: | |
| mean = sum(values) / len(values) | |
| std = (sum(((v - mean) ** 2 for v in values)) / len(values)) ** 0.5 | |
| scores = [p + alpha * (v - mean) / max(std, 0.1) for (p, v) in zip(policy, values)] | |
| return (max(range(len(scores)), key=lambda i: scores[i]), {'scores': scores, 'values': values, 'policy_scores': policy, 'alpha': alpha, 'terminal': calibration, 'world_used': True}) | |
| def episode(env, seed, method='policy', model=None, adapter=None, controller=None): | |
| wall_started = time.time() | |
| obs = env.reset(seed) | |
| initial = {k: obs[k] for k in ['instruction', 'elements']} | |
| started = time.monotonic() | |
| trace = [] | |
| actions = [] | |
| policy_seconds = world_seconds = browser_seconds = 0.0 | |
| hits = 0 | |
| controller = controller or {'alpha': 'pure'} | |
| for step in range(8): | |
| if obs['done']: | |
| break | |
| proposal = forecasts = selection = None | |
| if method == 'rule': | |
| action = rule_action(obs) | |
| else: | |
| proposal = rank(obs, adapter) | |
| policy_seconds += proposal['seconds'] | |
| hits += int(proposal['cached']) | |
| enabled = method in ['world', 'hybrid'] and controller['alpha'] != 0 | |
| if enabled: | |
| if model is None: | |
| raise RuntimeError('World selection without a model') | |
| (forecasts, elapsed) = model.forecast([context(obs, a) for a in proposal['actions']]) | |
| world_seconds += elapsed | |
| (index, selection) = select(proposal, forecasts, controller if method != 'policy' else {'alpha': 0.0}) | |
| action = proposal['actions'][index] | |
| (after, elapsed) = env.step(action) | |
| browser_seconds += elapsed | |
| row = dict(step=step, before=obs, action=action, after=after, seconds=elapsed) | |
| row.update(proposal=proposal, forecast=forecasts, selection=selection) | |
| trace.append(row) | |
| actions.append(action) | |
| obs = after | |
| success = int(bool(obs['submitted'] and obs['done'] and (correctness(obs) == 1.0) and (not obs.get('budget_exhausted')))) | |
| for row in trace: | |
| row['episode_success'] = success | |
| clicks = [a['slot'] for a in actions if a['kind'] == 'click'] | |
| result = {'episode_id': f'{seed}:t0', 'seed': seed, 'initial_hash': digest(initial), 'success': success, 'steps': len(actions), 'actions': actions, 'final': obs, 'wrong_submit': int(obs['submitted'] and (not success)), 'repeated_clicks': len(clicks) - len(set(clicks)), 'partial_fraction': correctness(obs), 'seconds': time.monotonic() - started, 'policy_nominal_seconds': policy_seconds, 'world_seconds': world_seconds, 'browser_seconds': browser_seconds, 'cached_policy_requests': hits, 'method': method, 'adapter': str(adapter) if adapter else None, 'controller': controller if method != 'policy' else {'alpha': 0.0}, 'started': wall_started, 'completed': time.time()} | |
| return (result, trace) | |
| def rollout(seeds, path, method='policy', model=None, adapter=None, controller=None): | |
| path = Path(path) | |
| commits = path.with_suffix('.episodes') | |
| commits.mkdir(parents=True, exist_ok=True) | |
| identity = {'seeds': list(seeds), 'method': method, 'world': checkpoint_identity(getattr(model, 'checkpoint_path', None)) if model else None, 'policy': checkpoint_identity(adapter), 'controller': controller, 'protocol': digest(json.loads((ROOT / 'protocol.json').read_text()))} | |
| meta = path.with_suffix('.identity.json') | |
| if meta.exists() and json.loads(meta.read_text()) != identity: | |
| raise RuntimeError('Rollout identity changed: ' + str(path)) | |
| atomic(meta, identity) | |
| env = GUIEnv() | |
| records = [] | |
| try: | |
| for seed in seeds: | |
| commit = commits / f'{seed}.json' | |
| if commit.exists(): | |
| record = json.loads(commit.read_text()) | |
| if record['identity_hash'] != digest(identity) or record['result']['seed'] != seed: | |
| raise RuntimeError('Invalid committed episode') | |
| else: | |
| (result, trace) = episode(env, seed, method, model, adapter, controller) | |
| record = {'identity_hash': digest(identity), 'result': result, 'transitions': trace} | |
| atomic(commit, record) | |
| records.append(record) | |
| atomic(path.with_suffix('.progress.json'), {'pid': __import__('os').getpid(), 'completed': len(records), 'total': len(seeds), 'updated': time.time()}) | |
| if len(records) % 10 == 0: | |
| print(json.dumps({'rollout': path.name, 'completed': len(records), 'total': len(seeds)}), flush=True) | |
| finally: | |
| env.close() | |
| outcomes = [r['result'] for r in records] | |
| trace = [t for r in records for t in r['transitions']] | |
| atomic_jsonl(path, outcomes) | |
| atomic_jsonl(path.with_suffix('.transitions.jsonl'), trace) | |
| atomic(path.with_suffix('.complete.json'), {'identity': identity, 'episodes': len(outcomes), 'transitions': len(trace), 'transactional': True, 'completed': time.time()}) | |
| return outcomes | |
| def summary(rows): | |
| n = len(rows) | |
| return {'n': n, 'success_rate': sum((r['success'] for r in rows)) / n, 'mean_steps': sum((r['steps'] for r in rows)) / n, 'mean_seconds': sum((r['seconds'] for r in rows)) / n, 'effective_seconds': effective_cost(rows), 'wrong_submits': sum((r['wrong_submit'] for r in rows)), 'repeated_clicks': sum((r['repeated_clicks'] for r in rows))} | |