Download gui_interaction/src/gui_world.py from Gen-Verse/RSI-Anything: direct link, hf CLI and curl.
- Browser
- Download file 5.81 kB
-
https://huggingface.co/datasets/Gen-Verse/RSI-Anything/resolve/main/gui_interaction/src/gui_world.py
- Command line
-
hf download hf://datasets/Gen-Verse/RSI-Anything/gui_interaction/src/gui_world.py
-
curl -L -o gui_world.py https://huggingface.co/datasets/Gen-Verse/RSI-Anything/resolve/main/gui_interaction/src/gui_world.py
5.81 kB
| """Frozen GUI state and action forecasts.""" | |
| import copy | |
| import hashlib | |
| import json | |
| import random | |
| import sys | |
| import time | |
| from pathlib import Path | |
| import torch | |
| from torch import nn | |
| from torch.nn import functional as F | |
| from common import ROOT, BASE_WORLD, atomic, digest, file_hash | |
| sys.path.insert(0, str(ROOT / 'world_core/vendor/JEPA-Anything/jepa-anything-core/src')) | |
| sys.path.insert(0, str(ROOT / 'world_core/src')) | |
| from world import DomainEncoder, ExecutionWorld, D, K, R | |
| import world, jepa_anything_core | |
| class GUIEncoder(DomainEncoder): | |
| """Encode public state compactly; the causal last token observes the whole state.""" | |
| def forward(self, texts): | |
| rendered = [] | |
| for text in texts: | |
| obs = json.loads(text) | |
| parts = ['Task instruction: ' + obs['instruction'], 'Visible checkbox states:'] | |
| for e in obs['visible_elements']: | |
| parts.append(f"{e['slot']}: {e['label']} = {('checked' if e['checked'] else 'unchecked')}") | |
| parts.append('Remaining actions: ' + str(obs['remaining_actions'])) | |
| if 'candidate_action' in obs: | |
| a = obs['candidate_action'] | |
| parts.append('Candidate action: ' + ('Submit' if a['kind'] == 'submit' else f"click checkbox {a['slot']} ({obs['visible_elements'][a['slot']]['label']})")) | |
| else: | |
| parts.append(f"Submitted: {obs['submitted']}; terminated: {obs['terminated']}") | |
| parts.append('State representation:') | |
| rendered.append('\n'.join(parts)) | |
| batch = self.tokenizer(rendered, padding=True, truncation=False, return_tensors='pt', add_special_tokens=False) | |
| if batch['input_ids'].shape[-1] > self.max_length: | |
| raise RuntimeError('GUI input exceeds frozen token limit') | |
| device = next(self.backbone.parameters()).device | |
| batch = {k: v.to(device) for (k, v) in batch.items()} | |
| hidden = self.backbone(**batch, return_dict=True, use_cache=False).last_hidden_state | |
| positions = batch['attention_mask'].sum(1) - 1 | |
| pooled = hidden[torch.arange(len(texts), device=device), positions].float() | |
| return self.projection(pooled) | |
| class GUIWorld(ExecutionWorld): | |
| def __init__(self, mode='opf'): | |
| self.gui_mode = mode | |
| super().__init__(GUIEncoder(BASE_WORLD, max_length=1024), mode='standard' if mode == 'standard' else 'opf') | |
| self.readout = nn.Sequential(nn.LayerNorm(D), nn.Linear(D, 64), nn.GELU(), nn.Linear(64, 8)) | |
| self.state_head = nn.Sequential(nn.Linear(2, 32), nn.GELU(), nn.Linear(32, 1)) | |
| self.feature_encoder = nn.Sequential(nn.Linear(20, 64), nn.GELU(), nn.LayerNorm(64)) | |
| self.value_head = nn.Sequential(nn.Linear(2 * D + 70, 256), nn.GELU(), nn.Linear(256, 128), nn.GELU(), nn.Linear(128, 3)) | |
| def outputs(self, texts): | |
| c = self.encode(texts) | |
| (latent, factors) = self.predict_latent(c) | |
| state = self.readout(latent) | |
| features = [] | |
| for text in texts: | |
| obs = json.loads(text) | |
| elements = obs['visible_elements'] | |
| action = obs['candidate_action'] | |
| bits = [float(e['checked']) for e in elements] + [0.0] * (6 - len(elements)) | |
| mask = [1.0] * len(elements) + [0.0] * (6 - len(elements)) | |
| ids = [0.0] * 7 | |
| ids[6 if action['kind'] == 'submit' else action['slot']] = 1.0 | |
| features.append(bits + mask + ids + [obs['remaining_actions'] / 8.0]) | |
| visible = torch.tensor(features, device=state.device) | |
| slot_input = torch.stack([visible[:, :6], visible[:, 12:18]], dim=-1) | |
| state_logits = self.state_head(slot_input).squeeze(-1) + 0.1 * state[:, :6] | |
| state = torch.cat([state_logits, state[:, 6:]], dim=1) | |
| values = self.value_head(torch.cat([F.layer_norm(c, (D,)), F.layer_norm(latent, (D,)), torch.sigmoid(state[:, :6]), self.feature_encoder(visible)], dim=1)) | |
| return (c, latent, factors, state, values) | |
| def forecast(self, contexts): | |
| self.eval() | |
| start = time.monotonic() | |
| (_, _, _, out, values) = self.outputs(contexts) | |
| out = out.float() | |
| values = values.float() | |
| rows = [] | |
| for (x, v) in zip(out, values): | |
| rows.append({'checked_probabilities': torch.sigmoid(x[:6]).tolist(), 'done_probability': float(torch.sigmoid(x[6])), 'submit_success_logit': float(v[0]), 'success_probability': float(torch.sigmoid(v[0])), 'utility': float(v[1]), 'value': float(v[2]), 'seconds_prediction': float(F.softplus(x[7]) * 2)}) | |
| return (rows, time.monotonic() - start) | |
| def load_gui(cls, path): | |
| path = Path(path) | |
| metadata = json.loads((path / 'inference.json').read_text()) | |
| for (name, expected) in metadata['files'].items(): | |
| if hashlib.sha256((path / name).read_bytes()).hexdigest() != expected: | |
| raise RuntimeError('Model file checksum mismatch: ' + name) | |
| from peft.utils.save_and_load import load_peft_weights, set_peft_model_state_dict | |
| model = cls(metadata['mode']) | |
| result = set_peft_model_state_dict(model.online.backbone, load_peft_weights(str(path / 'online_lora'), device='cpu'), adapter_name='default') | |
| if result.unexpected_keys: | |
| raise RuntimeError(str(result.unexpected_keys)) | |
| state = torch.load(path / 'gui_state.pt', map_location='cpu', weights_only=True) | |
| result = model.load_state_dict(state, strict=False) | |
| missing = [k for k in result.missing_keys if not k.startswith('online.backbone.')] | |
| if result.unexpected_keys or missing: | |
| raise RuntimeError(str((result.unexpected_keys, missing))) | |
| model.checkpoint_path = str(path) | |
| return model.cuda().requires_grad_(False).eval() | |