Commit ·
fc7a567
0
Parent(s):
Initial commit: NiceWebRL social-learning task (12 places, 2-door choice, 75/15/10 self+partner)
Browse filesFiles changed (9)
- .gitignoreAdded+176
- README.mdAdded+79
- config.pyAdded+12
- consent.mdAdded+28
- experiment_structure.pyAdded+412
- pyproject.tomlAdded+34
- smoke_test.pyAdded+70
- uv.lockAdded
- web_app.pyAdded+544
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176# Byte-compiled / optimized / DLL files*.pdf*data/*.nicegui__pycache__/*.py[cod]*$py.class.DS_Store
# C extensions*.so
# Distribution / packaging.Pythonbuild/develop-eggs/dist/downloads/eggs/.eggs/lib/lib64/parts/sdist/var/wheels/share/python-wheels/*.egg-info/.installed.cfg*.eggMANIFEST
# PyInstaller# Usually these files are written by a python script from a template# before PyInstaller builds the exe, so as to inject date/other infos into it.*.manifest*.spec
# Installer logspip-log.txtpip-delete-this-directory.txt
# Unit test / coverage reportshtmlcov/.tox/.nox/.coverage.coverage.*.cachenosetests.xmlcoverage.xml*.cover*.py,cover.hypothesis/.pytest_cache/cover/
# Translations*.mo*.pot
# Django stuff:*.loglocal_settings.pydb.sqlite3db.sqlite3-journal
# Flask stuff:instance/.webassets-cache
# Scrapy stuff:.scrapy
# Sphinx documentationdocs/_build/
# PyBuilder.pybuilder/target/
# Jupyter Notebook.ipynb_checkpoints
# IPythonprofile_default/ipython_config.py
# pyenv# For a library or package, you might want to ignore these files since the code is# intended to run in multiple environments; otherwise, check them in:# .python-version
# pipenv# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.# However, in case of collaboration, if having platform-specific dependencies or dependencies# having no cross-platform support, pipenv may install dependencies that don't work, or not# install all needed dependencies.#Pipfile.lock
# poetry# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.# This is especially recommended for binary packages to ensure reproducibility, and is more# commonly ignored for libraries.# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control#poetry.lock
# pdm# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.#pdm.lock# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it# in version control.# https://pdm.fming.dev/latest/usage/project/#working-with-version-control.pdm.toml.pdm-python.pdm-build/
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm__pypackages__/
# Celery stuffcelerybeat-schedulecelerybeat.pid
# SageMath parsed files*.sage.py
# Environments.env.venvenv/venv/ENV/env.bak/venv.bak/
# Spyder project settings.spyderproject.spyproject
# Rope project settings.ropeproject
# mkdocs documentation/site
# mypy.mypy_cache/.dmypy.jsondmypy.json
# Pyre type checker.pyre/
# pytype static type analyzer.pytype/
# Cython debug symbolscython_debug/
# PyCharm# JetBrains specific template is maintained in a separate JetBrains.gitignore that can# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore# and can be added to the global gitignore or merged into this file. For a more nuclear# option (not recommended) you can uncomment the following to ignore the entire idea folder.#.idea/
# Project-specific configexamples/xland/config.py# nicewebrl runtime.venv/data/*.sqlite.nicegui/__pycache__/google-cloud-key.json12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879# task_sl-cu-nicewebrl
A NiceWebRL reimplementation of the **Social Decision Game (CU / "Minecraft" variant)**— a social reinforcement-learning task — forked from the `nicewebrl-example-jaxmaze`template.
## What it is
You explore **12 places**. Each place is a **binary door choice** repeated for **20 rounds**,then the place is "consumed" and you move to the next. Behind the doors are 4 abstractoptions A/B/C/D, each with a hidden reward profile for **you** and for a **partner**:
| Option | You | Partner ||--------|-----|---------|| A | good (75% coin) | good (75%) || B | good | bad (15%) || C | bad (15%) | good || D | bad | bad |
"good" = P(+1)=0.75, P(−1)=0.15, P(0)=0.10 · "bad" = P(+1)=0.15, P(−1)=0.75, P(0)=0.10(the neutral 0-coin outcome is **kept**). The 6 pairs AB, AC, AD, BC, BD, CD each appeartwice → 12 places. On each round one recipient's outcome is shown (10 self / 10 partnerper place).
## Run it
```bashcd task_sl-cu-nicewebrlexport PATH="$HOME/.local/bin:$PATH" # uvuv sync # first time onlyuv run python web_app.py # serves http://localhost:8082```
Controls: **← / →** pick a door, **Space** continues past the outcome. After 20 roundspress any arrow to move to the next place.
Headless check of the env logic (no browser):
```bashuv run python smoke_test.py```
## How it's built
- `experiment_structure.py` — **all the task logic**: - `SocialBanditEnv` — a gymnax-style JAX env (`reset`/`step`), wrapped by `TimestepWrapper` and handed to `JaxWebEnv`. - `render_state` — a plain **PIL** renderer (no sprite assets yet). `vmap_render_fn` renders one frame per action for client-side display. - One `EnvStage` per place (12), plus an instruction `Stage`, assembled into a `SimpleExperiment`.- `web_app.py` — the NiceGUI app shell (consent, demographics, stage loop, data saving). Mostly unchanged from the jaxmaze template; port set to **8082**, title updated.- Data is written locally under `data/` (msgpack). Google Cloud upload is a no-op unless you add `google-cloud-key.json` + `BUCKET_NAME`.
## Design knobs (things you'll likely want to tune)
First-pass decisions baked in — all easy to change in `experiment_structure.py`:
1. **Outcomes are drawn live** (probabilistic), not pre-baked per block like the original PsychoPy CSVs. So per-place counts aren't exactly 15/3/2 — they're 75/15/10 in expectation. Change in `_draw_outcome` / the `P_*` constants.2. **Only the displayed recipient's outcome is realized** each round (10 self / 10 partner). The original *also* draws the hidden recipient's outcome; if you want that, draw both in `step` and decide which counts toward payment.3. **Place order is fixed** (`PLACE_PAIRS`). Add per-subject counterbalancing/shuffling if needed (the original counterbalances block order).4. **No practice block, no quiz** yet (the original has 3 practice trials + a 6-item comprehension quiz). Add as extra `Stage`s / an `EnvStage`.5. **Partner is a static avatar**, not yet a "lil guy walking next to you." Animation is a rendering change in `render_state` (or a later sprite-based renderer).6. **Placeholder visuals** — colored doors stand in for the fractal images. Swap `render_state` for a sprite compositor to get the Minecraft look.
## Provenance
Original task: `/Users/md1864/Documents/GitHub/task_sl-cu` (PsychoPy/Pavlovia).Template: https://github.com/wcarvalho/nicewebrl-example-jaxmaze123456789101112"""Configuration file for API keys and other settings.This file should be added to .gitignore to keep sensitive information private."""
# Google Cloud StorageBUCKET_NAME = "jaxmaze"GOOGLE_CREDENTIALS = "./google-cloud-key.json"
# DataDATA_DIR = "./user_data"12345678910111213141516171819202122232425262728Please carefully read this consent agreement before deciding whether to participate in this experiment.
**Purpose of the research:** To understand how people learn and make decisions when getting assistance from an AI.
**What you will do in this research:** You will move around a virtual maze, navigating to different locations on screen to complete tasks. You will be able to ask an AI agent for help whenever you need it.
**Time required:** about 30 minutes.
**Risks:** There are no anticipated risks associated with participating in this study. The effects of participating should be comparable to those you would experience from viewing a computer monitor, clicking with the mouse, and pressing buttons on the keyboard for the duration of the experiment.
**Benefits:** The study provides important information about the nature of learning and decision making.
**Compensation:** You will receive $4 base pay for completing the experiment + a bonus of $0-3 based on your performance ($2 on average).
**Confidentiality:** Your participation in this study will remain confidential. No personally identifiable information will be associated with your data. Your de-identified data may be shared with other researchers and used in future projects.
**Participation and withdrawal:** Your participation in this study is completely voluntary and you may refuse to participate or you may choose to withdraw at any time without penalty or loss of benefits to which you are otherwise entitled.
**How to contact the researcher:** If you have questions or concerns about your participation or payment, please contact wcarvalho@g.harvard.edu.
Whom to contact about your rights in this research: For questions, concerns, suggestions, or complaints that have not been or cannot be addressed by the researcher, or to report research-related harm, please contact the Committee on the Use of Human Subjects in Research at Harvard University, 1414 Massachusetts Avenue, Second Floor, Cambridge, MA 02138. Phone: 617-496-2847. Email: cuhs@fas.harvard.edu. Please print or save a copy of this form for your records.
**Agreement:** The nature and purpose of this research have been sufficiently explained and I agree to participate in this study. I understand that I am free to withdraw at any time without incurring any penalty.
<p style="color: red;"><strong>Please close other tabs to improve the connection. Note that the session will be restarted if you leave this webpage for more than FIVE (5) minutes.</strong></p>
Please consent by checking the box, then click the button to continue. Otherwise, please exit the study at this time.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412"""Social-learning ("Minecraft") task for NiceWebRL.
First-pass reimplementation of the `task_sl-cu` Social Decision Game as a JAXenvironment driven by NiceWebRL.
Task summary------------- 4 abstract options A, B, C, D. Each has a (hidden) reward profile for SELF and PARTNER: A = good for self (75% coin), good for partner (75%) B = good for self, bad for partner (15%) C = bad for self (15%), good for partner D = bad for self, bad for partner "good" => P(+1)=0.75, P(-1)=0.15, P(0)=0.10 (neutral 0-coin outcome kept) "bad" => P(+1)=0.15, P(-1)=0.75, P(0)=0.10- A "place" is a pair of two options (a binary door choice). The 6 pairs AB, AC, AD, BC, BD, CD are each used twice => 12 places.- Each place = 20 trials, run consecutively, then the place is "consumed".- Each trial: choose a door -> an outcome is shown for ONE recipient (self or partner), 10 self / 10 partner per place; that recipient's coins update.
Interaction model (per trial = 2 key presses)--------------------------------------------- phase 0 (choice): ArrowLeft / ArrowRight picks a door -> resolves outcome phase 1 (outcome): Space continues -> next trialAfter the 20th trial the place ends (press any arrow to move on).
Architecture------------Plain gymnax-style env (reset->(obs,state), step->(obs,state,reward,done,info)),wrapped by nicewebrl's TimestepWrapper so it speaks `TimeStep`, handed to JaxWebEnv,rendered with a small PIL renderer (no sprite assets yet -- swap in Minecraft spriteslater inside `render_state`)."""
from typing import Optional
import jaximport jax.numpy as jnpimport jax.tree_util as jtuimport numpy as npfrom flax import structfrom nicegui import uifrom PIL import Image, ImageDraw
import nicewebrlfrom nicewebrl import JaxWebEnv, TimeStep, TimestepWrapperfrom nicewebrl import Stage, EnvStagefrom nicewebrl import get_loggerfrom nicewebrl.experiment import SimpleExperiment
logger = get_logger(__name__)
# ----------------------------------------------------------------------------# Task constants# ----------------------------------------------------------------------------N_TRIALS = 20 # trials per placeN_PLACES = 12 # 6 pairs x 2
# Option letter indices: A=0, B=1, C=2, D=3LETTER_SELF_GOOD = jnp.array([1, 1, 0, 0], dtype=jnp.int32) # A,B good for selfLETTER_OTHER_GOOD = jnp.array([1, 0, 1, 0], dtype=jnp.int32) # A,C good for partnerLETTER_NAMES = ["A", "B", "C", "D"]
# Reward probabilities (neutral / 0-coin outcome kept, as requested)P_PLUS_GOOD, P_MINUS_GOOD = 0.75, 0.15P_PLUS_BAD, P_MINUS_BAD = 0.15, 0.75# remaining mass (0.10) -> 0 coins
# The 6 unique pairs, each used twice -> 12 places.PAIRS = [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)] # AB AC AD BC BD CDPLACE_PAIRS = PAIRS + PAIRS
# ActionsACTION_LEFT, ACTION_RIGHT, ACTION_CONTINUE = 0, 1, 2action_keys = ["ArrowLeft", "ArrowRight", " "] # index -> browser keyaction_to_name = ["choose_left", "choose_right", "continue"]action_array = jnp.arange(len(action_keys))
# Visual identity per letter (stable across places so options are learnable).LETTER_COLOR = { 0: (46, 204, 113), # A green 1: (52, 152, 219), # B blue 2: (230, 126, 34), # C orange 3: (155, 89, 182), # D purple}
# ----------------------------------------------------------------------------# Environment# ----------------------------------------------------------------------------@struct.dataclassclass EnvParams: opt_letters: jax.Array # (2,) the two letter indices for this place's pair place_id: jax.Array # scalar int, 0..11 pair_code: jax.Array # scalar int, 0..5 (which of the 6 pairs) n_trials: jax.Array # scalar int
@struct.dataclassclass EnvState: trial: jax.Array # 0..N_TRIALS phase: jax.Array # 0=choice, 1=outcome self_coins: jax.Array other_coins: jax.Array left_letter: jax.Array # letter idx shown on the left this trial right_letter: jax.Array # letter idx shown on the right this trial cur_target: jax.Array # 0=self, 1=partner (whose outcome is shown this trial) chosen_side: jax.Array # 0=left,1=right (-1 if none yet) chosen_letter: jax.Array # letter idx chosen (-1 if none) last_outcome: jax.Array # -1 / 0 / +1 last_target: jax.Array # 0=self,1=partner of the shown outcome outcome_valid: jax.Array # 1 while an outcome is being shown target_schedule: jax.Array # (N_TRIALS,) 0/1 displayed-target per trial side_schedule: jax.Array # (N_TRIALS,) 0/1: 0 => opt_letters[0] on left place_id: jax.Array # carried for rendering pair_code: jax.Array
def _trial_layout(params: EnvParams, side_bit, target_bit): """Given side bit (0/1), return (left_letter, right_letter).""" o0, o1 = params.opt_letters[0], params.opt_letters[1] left = jnp.where(side_bit == 0, o0, o1) right = jnp.where(side_bit == 0, o1, o0) return left, right
def _select_state(cond, a: EnvState, b: EnvState) -> EnvState: """Pick pytree `a` where scalar cond is True else `b`.""" return jtu.tree_map(lambda x, y: jnp.where(cond, x, y), a, b)
class SocialBanditEnv: """gymnax-style env: reset->(obs,state), step->(obs,state,reward,done,info)."""
def _obs(self, state: EnvState) -> jax.Array: return jnp.array( [ state.trial, state.phase, state.self_coins, state.other_coins, state.left_letter, state.right_letter, state.cur_target, state.last_outcome, state.outcome_valid, state.last_target, ], dtype=jnp.float32, )
def reset(self, key, params: EnvParams): k_target, k_side = jax.random.split(key) base = jnp.concatenate( [jnp.zeros(N_TRIALS // 2, jnp.int32), jnp.ones(N_TRIALS // 2, jnp.int32)] ) target_schedule = jax.random.permutation(k_target, base) # balanced 10/10 side_schedule = jax.random.bernoulli(k_side, 0.5, (N_TRIALS,)).astype(jnp.int32)
left, right = _trial_layout(params, side_schedule[0], target_schedule[0]) state = EnvState( trial=jnp.int32(0), phase=jnp.int32(0), self_coins=jnp.int32(0), other_coins=jnp.int32(0), left_letter=left, right_letter=right, cur_target=target_schedule[0], chosen_side=jnp.int32(-1), chosen_letter=jnp.int32(-1), last_outcome=jnp.int32(0), last_target=jnp.int32(0), outcome_valid=jnp.int32(0), target_schedule=target_schedule, side_schedule=side_schedule, place_id=params.place_id, pair_code=params.pair_code, ) return self._obs(state), state
def _draw_outcome(self, key, good): """good: int (1 good, 0 bad). Returns -1/0/+1.""" u = jax.random.uniform(key) p_plus = jnp.where(good == 1, P_PLUS_GOOD, P_PLUS_BAD) p_minus = jnp.where(good == 1, P_MINUS_GOOD, P_MINUS_BAD) return jnp.where( u < p_plus, jnp.int32(1), jnp.where(u < p_plus + p_minus, jnp.int32(-1), jnp.int32(0)), )
def step(self, key, state: EnvState, action, params: EnvParams): """Returns (obs, state, reward, done, info) for TimestepWrapper.""" action = jnp.asarray(action, jnp.int32)
# ---------- choice phase: a left/right press resolves an outcome ---------- is_choice = (state.phase == 0) & ((action == ACTION_LEFT) | (action == ACTION_RIGHT)) chosen_side = jnp.where(action == ACTION_LEFT, jnp.int32(0), jnp.int32(1)) chosen_letter = jnp.where(chosen_side == 0, state.left_letter, state.right_letter) good = jnp.where( state.cur_target == 0, LETTER_SELF_GOOD[chosen_letter], LETTER_OTHER_GOOD[chosen_letter], ) outcome = self._draw_outcome(key, good) choice_state = state.replace( phase=jnp.int32(1), chosen_side=chosen_side, chosen_letter=chosen_letter, last_outcome=outcome, last_target=state.cur_target, outcome_valid=jnp.int32(1), self_coins=state.self_coins + jnp.where(state.cur_target == 0, outcome, 0), other_coins=state.other_coins + jnp.where(state.cur_target == 1, outcome, 0), )
# ---------- outcome phase: a continue press advances the trial ---------- is_continue = (state.phase == 1) & (action == ACTION_CONTINUE) next_trial = state.trial + 1 place_done = next_trial >= params.n_trials nt = jnp.clip(next_trial, 0, N_TRIALS - 1) # safe index; ignored when done n_left, n_right = _trial_layout(params, state.side_schedule[nt], state.target_schedule[nt]) advance_state = state.replace( trial=next_trial, phase=jnp.int32(0), left_letter=n_left, right_letter=n_right, cur_target=state.target_schedule[nt], chosen_side=jnp.int32(-1), chosen_letter=jnp.int32(-1), outcome_valid=jnp.int32(0), )
# ---------- select resulting state ---------- new_state = _select_state(is_choice, choice_state, state) new_state = _select_state(is_continue, advance_state, new_state)
done = is_continue & place_done reward = jnp.where(is_choice, outcome, jnp.int32(0)).astype(jnp.float32) return self._obs(new_state), new_state, reward, done, {}
# ----------------------------------------------------------------------------# Build the JaxWebEnv + per-place params# ----------------------------------------------------------------------------raw_env = SocialBanditEnv()wrapped_env = TimestepWrapper(raw_env, autoreset=True) # adds TimeStep semanticsjax_web_env = JaxWebEnv(env=wrapped_env, actions=action_array)
def make_place_params(place_id: int) -> EnvParams: pair = PLACE_PAIRS[place_id] return EnvParams( opt_letters=jnp.array(pair, dtype=jnp.int32), place_id=jnp.int32(place_id), pair_code=jnp.int32(PAIRS.index(pair)), n_trials=jnp.int32(N_TRIALS), )
place_params = [make_place_params(i) for i in range(N_PLACES)]
# ----------------------------------------------------------------------------# Rendering (plain numpy/PIL -- no jit, no sprite assets required yet)# ----------------------------------------------------------------------------W, H = 720, 460
def _i(x): return int(np.asarray(x))
def render_state(timestep: TimeStep) -> np.ndarray: """Render one TimeStep to an (H, W, 3) uint8 image.""" s = timestep.state place_id = _i(s.place_id) trial = _i(s.trial) phase = _i(s.phase) left_letter, right_letter = _i(s.left_letter), _i(s.right_letter) self_coins, other_coins = _i(s.self_coins), _i(s.other_coins) last_outcome = _i(s.last_outcome) last_target = _i(s.last_target) chosen_side = _i(s.chosen_side)
bg = (30 + (place_id * 7) % 40, 40 + (place_id * 13) % 40, 55 + (place_id * 5) % 40) img = Image.new("RGB", (W, H), bg) d = ImageDraw.Draw(img)
shown_trial = min(trial + 1, N_TRIALS) d.text((20, 16), f"Place {place_id + 1}/{N_PLACES}", fill=(235, 235, 235)) d.text((20, 34), f"Round {shown_trial}/{N_TRIALS}", fill=(235, 235, 235))
# ---- two doors ---- door_w, door_h = 150, 200 ly = ry = 110 lx, rx = 120, W - 120 - door_w for x, y, letter, side in ((lx, ly, left_letter, 0), (rx, ry, right_letter, 1)): color = LETTER_COLOR[letter] chosen = (phase == 1) and (chosen_side == side) outline = (255, 255, 0) if chosen else (15, 15, 15) width = 6 if chosen else 2 d.rectangle([x, y, x + door_w, y + door_h], fill=color, outline=outline, width=width) d.rectangle([x + 20, y + 20, x + door_w - 20, y + door_h - 20], outline=(0, 0, 0), width=2) d.ellipse([x + door_w - 45, y + door_h // 2 - 6, x + door_w - 33, y + door_h // 2 + 6], fill=(0, 0, 0)) d.text((lx + door_w // 2 - 30, ly + door_h + 10), "<-- Left door", fill=(220, 220, 220)) d.text((rx + door_w // 2 - 35, ry + door_h + 10), "Right door -->", fill=(220, 220, 220))
# ---- you + partner avatars with coin counters ---- d.ellipse([150, H - 70, 182, H - 38], fill=(52, 152, 219), outline=(0, 0, 0), width=2) d.text((140, H - 32), f"YOU: {self_coins}", fill=(235, 235, 235)) d.ellipse([W - 200, H - 70, W - 168, H - 38], fill=(46, 204, 113), outline=(0, 0, 0), width=2) d.text((W - 215, H - 32), f"PARTNER: {other_coins}", fill=(235, 235, 235))
# ---- instructions / outcome banner ---- if phase == 0: d.text((W // 2 - 90, H - 95), "Pick a door: <- or ->", fill=(255, 255, 255)) else: word = {1: "+1 coin", 0: "0 coins", -1: "-1 coin"}[last_outcome] who = "YOU" if last_target == 0 else "PARTNER" col = (46, 204, 113) if last_outcome > 0 else (231, 76, 60) if last_outcome < 0 else (200, 200, 200) d.text((W // 2 - 80, 70), f"{who} got {word}", fill=col) d.text((W // 2 - 110, H - 95), "Press SPACE to continue", fill=(255, 255, 255))
return np.asarray(img, dtype=np.uint8)
def vmap_render_fn(batched_timesteps) -> np.ndarray: """Render one image per action (EnvStage shows these client-side).
`batched_timesteps` is a TimeStep pytree whose leaves have a leading action axis. Plain python (no jit) so PIL rendering is fine. """ n = int(np.asarray(batched_timesteps.reward).shape[0]) images = [render_state(jtu.tree_map(lambda x: x[i], batched_timesteps)) for i in range(n)] return np.stack(images)
# ----------------------------------------------------------------------------# Display + stage callbacks# ----------------------------------------------------------------------------def _img_html(src): return ( '<div style="display:flex;justify-content:center;align-items:center;">' f'<img src="{src}" style="width:100%;height:100%;object-fit:contain;"></div>' )
async def env_stage_display_fn(stage: EnvStage, container: ui.element, timestep: TimeStep): image = nicewebrl.base64_npimage(stage.render_fn(timestep)) with container.style("align-items: center;"): nicewebrl.clear_element(container) ui.html(_img_html(image))
def never_success(timestep: TimeStep, params: Optional[struct.PyTreeNode] = None): return jnp.int32(0) # success not used to gate progression
def place_finished(timestep: TimeStep): return timestep.last() # end place when env signals done (after trial 20)
# ----------------------------------------------------------------------------# Assemble stages# ----------------------------------------------------------------------------all_stages = []
async def instruction_display_fn(stage, container): with container.style("align-items: center;"): nicewebrl.clear_element(container) ui.markdown(f"## {stage.name}") ui.markdown( """You are exploring **12 places**. At each place there are **two doors**.
- On each round, pick a door with the **Left / Right arrow keys**.- After you choose, you'll see the outcome (a coin for **YOU** or your **PARTNER**), then press **SPACE** to continue.- Each place has **20 rounds**. Some doors are more likely to give coins to *you*, some to your *partner*, some to *both*, and some to *neither*.- Try to learn what each door does! """ )
all_stages.append(Stage(name="Instructions", display_fn=instruction_display_fn))
def make_place_stage(place_id: int) -> EnvStage: return EnvStage( name=f"Place {place_id + 1}", web_env=jax_web_env, action_keys=action_keys, action_to_name=action_to_name, env_params=place_params[place_id], render_fn=render_state, vmap_render_fn=vmap_render_fn, # provided -> EnvStage skips jit precompile precompile=False, display_fn=env_stage_display_fn, evaluate_success_fn=never_success, check_finished=place_finished, min_success=10_000, # never triggers (success unused) max_episodes=1, notify_success=False, metadata=dict( place_id=place_id, pair="".join(LETTER_NAMES[i] for i in PLACE_PAIRS[place_id]), ), )
for pid in range(N_PLACES): all_stages.append(make_place_stage(pid))
experiment = SimpleExperiment(stages=all_stages, name="Social Learning CU")12345678910111213141516171819202122232425262728293031323334[project]name = "nicewebrl-jaxmaze"version = "0.1.0"description = "JaxMaze example for NiceWebRL"readme = "README.md"requires-python = ">=3.10"dependencies = [ "nicewebrl[jaxmaze] @ git+https://github.com/KempnerInstitute/nicewebrl.git",]
[project.optional-dependencies]dev = [ "pytest", "black", "isort",]
[build-system]requires = ["hatchling"]build-backend = "hatchling.build"
[tool.hatch.metadata]allow-direct-references = true
[tool.hatch.build.targets.wheel]packages = ["."]
[tool.black]line-length = 88target-version = ["py310"]
[tool.isort]profile = "black"line_length = 8812345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970"""Headless smoke test of the social-learning env (no web server)."""import jaximport jax.tree_util as jtuimport numpy as npimport experiment_structure as E
def pick(ts, action, params, seed): nxt = E.jax_web_env.next_steps(jax.random.PRNGKey(seed), ts, params) return jtu.tree_map(lambda x: x[action], nxt)
def run_place(place_id, choose="left"): p = E.place_params[place_id] rng = jax.random.PRNGKey(100 + place_id) ts = E.jax_web_env.reset(rng, p) assert bool(ts.first()), "reset should be FIRST"
# render check (all actions) nxt = E.jax_web_env.next_steps(rng, ts, p) imgs = E.vmap_render_fn(nxt) assert imgs.shape == (3, E.H, E.W, 3), imgs.shape
cur = ts targets_seen = {0: 0, 1: 0} last_done = False for t in range(E.N_TRIALS): tgt = int(cur.state.cur_target) targets_seen[tgt] += 1 action = E.ACTION_LEFT if choose == "left" else E.ACTION_RIGHT cur = pick(cur, action, p, seed=t + 1) # choose a door assert int(cur.state.phase) == 1, f"trial {t}: expected outcome phase" assert int(cur.state.outcome_valid) == 1 cur = pick(cur, E.ACTION_CONTINUE, p, seed=t + 1) # continue last_done = bool(cur.last()) pair = "".join(E.LETTER_NAMES[i] for i in E.PLACE_PAIRS[place_id]) print( f"place {place_id:2d} ({pair}): trial={int(cur.state.trial):2d} " f"done={last_done} self={int(cur.state.self_coins):+d} " f"other={int(cur.state.other_coins):+d} " f"targets(self/other)={targets_seen[0]}/{targets_seen[1]}" ) assert int(cur.state.trial) == E.N_TRIALS assert last_done, "place should be done after 20 trials" assert targets_seen[0] == 10 and targets_seen[1] == 10, "should be 10 self / 10 partner" return cur
print("=== Running 1 full place per choice side, all 12 places ===")for pid in range(E.N_PLACES): run_place(pid, choose="left")
# Sanity on probabilities: always pick option A in an AB place -> self should trend up,# always pick D in a CD place -> both trend down. Aggregate over many resets.print("\n=== Probability sanity (1000 self-target draws) ===")p_ab = E.place_params[0] # AB: left/right are A/B in some order# Force-resolve many choices of letter A (good for self & partner) on self-target trials.import collectionscounts = collections.Counter()key = jax.random.PRNGKey(0)env = E.raw_env# minimal state with A on the left, self targetst = env.reset(jax.random.PRNGKey(0), p_ab)[1]for i in range(1000): k = jax.random.PRNGKey(i) good = 1 # A is good for self counts[int(env._draw_outcome(k, good))] += 1total = sum(counts.values())print({k: round(counts[k] / total, 3) for k in (1, 0, -1)}, "(expect ~0.75 / 0.10 / 0.15)")print("\nALL SMOKE TESTS PASSED")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544import os.pathimport asynciofrom asyncio import Lockfrom nicegui import app, uifrom fastapi import Requestfrom tortoise import Tortoiseimport jaximport httpximport configimport nicewebrlfrom nicewebrl.logging import setup_logging, get_loggerfrom nicewebrl.utils import wait_for_button_or_keypressfrom nicewebrl import stages, TimeStep
import nicewebrlimport osfrom importlib.util import find_specimport shutilimport asyncioimport jsonimport timefrom nicewebrl.logging import get_loggerfrom nicegui import app
# Google Cloud Storage functionality (copied from xland-LLM-assistant)from dotenv import load_dotenvfrom google.auth.exceptions import TransportErrorfrom google.cloud import storagefrom google.cloud.exceptions import exceptions as gcs_exceptions
from experiment_structure import experiment
load_dotenv()logger = get_logger(__name__)
GOOGLE_CREDENTIALS = "./google-cloud-key.json"# Google Cloud StorageBUCKET_NAME = "jaxmaze"
# DataDATA_DIR = "./data"DATABASE_FILE = "db.sqlite"
_user_locks = {}async def save_file_to_gcs(local_filename, blob_filename, bucket_name: str): try: storage_client = storage.Client.from_service_account_json(GOOGLE_CREDENTIALS) bucket = storage_client.bucket(bucket_name) blob = bucket.blob(blob_filename)
# Run the blocking upload in a thread pool await asyncio.to_thread(blob.upload_from_filename, local_filename)
logger.info(f"Saved {blob_filename} in bucket {bucket.name}") return True # Successfully saved except Exception as e: logger.info(f"Unexpected error: {e}") logger.info("Skipping GCS upload")
return False # Failed to save
async def save_to_gcs_with_retries( files_to_save, max_retries=5, retry_delay=5, bucket_name: str = ""): """Save multiple files to Google Cloud Storage with retry logic.
Args: files_to_save: List of filenames max_retries: Number of retry attempts retry_delay: Seconds to wait between retries bucket_name: Name of the GCS bucket
Returns: bool: True if all files were saved successfully, False otherwise """ assert bucket_name != "", "Bucket name is required" for attempt in range(max_retries): try: # Try to save all files for local_file in files_to_save: saved = await save_file_to_gcs( local_filename=local_file, blob_filename=local_file, bucket_name=bucket_name ) if not saved: raise Exception(f"Failed to save {local_file}")
logger.info(f"Successfully saved data to GCS on attempt {attempt + 1}") return True
except Exception as e: if attempt < max_retries - 1: logger.info(f"Error saving to GCS: {e}. Retrying in {retry_delay} seconds...") await asyncio.sleep(retry_delay) else: logger.info(f"Failed to save to GCS after {max_retries} attempts: {e}") return False
async def finish_experiment(feedback=None, **kwargs): """Function to save data to Google Cloud Storage on experiment termination. This function requires: - google-cloud-key.json file in the same directory - BUCKET_NAME environment variable set - google-cloud-storage package installed """ bucket_name = os.getenv("BUCKET_NAME") if not GOOGLE_CREDENTIALS or not os.path.exists(GOOGLE_CREDENTIALS): logger.warning("No Google credentials found, skipping save") return if not bucket_name: logger.warning("No BUCKET_NAME environment variable found, skipping save") return
user_data_file = nicewebrl.user_data_file() user_metadata_file = nicewebrl.user_metadata_file()
# -------------------------------- # save user data to final line of file # -------------------------------- user_storage = nicewebrl.make_serializable(dict(app.storage.user)) metadata = dict( finished=True, feedback=feedback, user_storage=user_storage, **kwargs, ) with open(user_metadata_file, "w") as f: json.dump(metadata, f)
files_to_save = [user_data_file, user_metadata_file] logger.info(f"Saving to bucket: {bucket_name}") await save_to_gcs_with_retries( files_to_save, max_retries=5, bucket_name=bucket_name, )
# Try to delete local files after successful upload from nicewebrl.stages import StageStateModel
logger.info(f"Deleting data for user {app.storage.browser['id']}") await StageStateModel.filter(session_id=app.storage.browser["id"]).delete() logger.info( f"Successfully deleted stage information for user {app.storage.browser['id']}" ) for local_file in files_to_save: try: os.remove(local_file) logger.info(f"Successfully deleted local file: {local_file}") except Exception as e: logger.warning(f"Failed to delete local file {local_file}: {str(e)}")
def get_user_lock(): user_seed = app.storage.user["seed"] if user_seed not in _user_locks: _user_locks[user_seed] = Lock() return _user_locks[user_seed]
async def global_handle_key_press(e, container): logger.info("global_handle_key_press") if experiment.finished(): logger.info("Experiment finished") return
stage = await experiment.get_stage() if stage.get_user_data("finished", False): return
await stage.handle_key_press(e, container) local_handle_key_press = stage.get_user_data("local_handle_key_press") if local_handle_key_press is not None: await local_handle_key_press()
setup_logging(DATA_DIR, nicegui_storage_user_key="seed")logger = get_logger("main")
if not os.path.exists(DATA_DIR): os.mkdir(DATA_DIR)
async def init_db() -> None: await Tortoise.init( db_url=f"sqlite://{DATA_DIR}/{DATABASE_FILE}", modules={"models": ["nicewebrl.stages"]}, ) await Tortoise.generate_schemas()
async def close_db() -> None: await Tortoise.close_connections()
app.on_startup(init_db)app.on_shutdown(close_db)
###################################### Consent Form and demographic info#####################################
async def make_consent_form(container): consent_given = asyncio.Event() with container: ui.markdown("## Consent Form") with open("consent.md", "r") as consent_file: consent_text = consent_file.read() ui.markdown(consent_text)
def on_change(): print("on_change") consent_given.set()
ui.checkbox("I agree to participate.", on_change=on_change) print("waiting for consent") await consent_given.wait()
async def collect_demographic_info(container): # Create a markdown title for the section nicewebrl.clear_element(container) collected_demographic_info_event = asyncio.Event() with container: ui.markdown("## Demographic Info") ui.markdown("Please fill out the following information.")
with ui.column(): with ui.column(): ui.label("Biological Sex") sex_input = ui.radio(["Male", "Female"], value="Male").props("inline")
# Collect age with a textbox input age_input = ui.input("Age")
# Button to submit and store the data async def submit(): age = age_input.value sex = sex_input.value
# Validation for age input if not age.isdigit() or not (0 < int(age) < 100): ui.notify("Please enter a valid age between 1 and 99.", type="warning") return app.storage.user["age"] = int(age) app.storage.user["sex"] = sex logger.info(f"age: {int(age)}, sex: {sex}") collected_demographic_info_event.set()
button = ui.button("Submit", on_click=submit) await button.clicked()
async def start_experiment(meta_container, stage_container): # ======================================== # Consent form and demographic info # ======================================== if not (app.storage.user.get("experiment_started", False)): await make_consent_form(stage_container) await collect_demographic_info(stage_container) app.storage.user["experiment_started"] = True
# ======================================== # Force fullscreen # ======================================== # ui.run_javascript("window.require_fullscreen = true")
# ======================================== # Register global key press handler # ======================================== ui.on("key_pressed", lambda e: global_handle_key_press(e, stage_container))
# ======================================== # Start experiment # ======================================== logger.info("Starting experiment")
while not experiment.finished(): stage = await experiment.get_stage() await run_stage(stage, stage_container) await stage.finish_saving_user_data() await experiment.advance_stage()
await finish_experiment(meta_container)
async def finish_experiment(container): nicewebrl.clear_element(container) with container: ui.markdown("# Experiment over")
######################### # Save data ######################### async def submit(feedback): app.storage.user["experiment_finished"] = True status_container = None with container: nicewebrl.clear_element(container) ui.markdown( "## Your data is being saved. Please do not close or refresh the page." ) status_container = ui.markdown("Saving local files...")
try: # Create a task for the save operation with a timeout save_task = asyncio.create_task(save_data(feedback=feedback)) start_time = time.time()
# Update status every 2 seconds while waiting for save while not save_task.done(): elapsed_seconds = int(time.time() - start_time) status_container.content = ( f"Still saving... ({elapsed_seconds}s elapsed). This may take 5-10 minutes." ) try: # Wait for either task completion or timeout await asyncio.wait_for(asyncio.shield(save_task), timeout=2.0) except asyncio.TimeoutError: # This is expected - we use timeout to update status continue except Exception as e: logger.error(f"Error during save: {e}") status_container.content = ( "⚠️ Error saving data. Please contact the experimenter." ) raise
# If we get here, save was successful elapsed_seconds = int(time.time() - start_time) status_container.content = ( f"✅ Save complete in {elapsed_seconds}s! Moving to next screen..." ) app.storage.user["data_saved"] = True
except Exception as e: logger.error(f"Save failed: {e}") status_container.content = "⚠️ Error saving data. Please contact the experimenter." raise
app.storage.user["data_saved"] = app.storage.user.get("data_saved", False) if not app.storage.user["data_saved"]: with container: nicewebrl.clear_element(container) ui.markdown( "Please provide feedback on the experiment here. For example, please describe if anything went wrong or if you have any suggestions for the experiment." ) text = ui.textarea().style("width: 80%;") # Set width to 80% of the container button = ui.button("Submit") await button.clicked() await submit(text.value)
######################### # Final screen ######################### with container: nicewebrl.clear_element(container) ui.markdown("# Experiment over") ui.markdown("## Data saved") ui.markdown( "### Please record the following code which you will need to provide for compensation" ) ui.markdown("### 'carvalho.assistants 3'") ui.markdown("#### You may close the browser")
async def save_data(feedback=None, **kwargs): if not GOOGLE_CREDENTIALS: logger.warning("No Google credentials found, skipping save") return
user_data_file = nicewebrl.user_data_file() user_metadata_file = nicewebrl.user_metadata_file()
# -------------------------------- # save user data to final line of file # -------------------------------- user_storage = nicewebrl.make_serializable(dict(app.storage.user)) metadata = dict( finished=True, feedback=feedback, user_storage=user_storage, **kwargs, )
with open(user_metadata_file, "w") as f: json.dump(metadata, f)
files_to_save = [user_data_file, user_metadata_file] logger.info(f"Saving to bucket: {config.BUCKET_NAME}") await save_to_gcs_with_retries( files_to_save, max_retries=5, bucket_name=config.BUCKET_NAME, )
# Try to delete local files after successful upload from nicewebrl.stages import StageStateModel
logger.info(f"Deleting data for user {app.storage.browser['id']}") await StageStateModel.filter(session_id=app.storage.browser["id"]).delete() logger.info( f"Successfully deleted stage inforation for user {app.storage.browser['id']}" ) for local_file in files_to_save: try: os.remove(local_file) logger.info(f"Successfully deleted local file: {local_file}") except Exception as e: logger.warning(f"Failed to delete local file {local_file}: {str(e)}")
async def run_stage(stage, container): stage_over_event = asyncio.Event()
async def local_handle_key_press(): async with get_user_lock(): if stage.get_user_data("finished", False): logger.info(f"Finished {stage.name} via key press") stage_over_event.set()
await stage.set_user_data(local_handle_key_press=local_handle_key_press)
async def handle_button_press(): if stage.get_user_data("finished", False): return await stage.handle_button_press(container) async with get_user_lock(): if stage.get_user_data("finished", False): logger.info(f"Finished {stage.name} via button press") stage_over_event.set()
with container.style("align-items: center;"): await stage.activate(container)
if stage.get_user_data("finished", False): logger.info(f"Finished {stage.name} immediately after activation") stage_over_event.set()
if stage.next_button: with container: button = ui.button("Next page") await wait_for_button_or_keypress(button) await handle_button_press()
await stage_over_event.wait()
async def check_if_over(container, episode_limit=60): minutes_passed = nicewebrl.get_user_session_minutes() minutes_passed = app.storage.user["session_duration"] if minutes_passed > episode_limit: pass
@ui.page("/")async def index(request: Request): nicewebrl.initialize_user(request=request) await experiment.initialize()
model_list = ["gemini", "claude", "chatgpt"] # Initialize random model selection if not already set if "selected_model" not in app.storage.user: rng = nicewebrl.new_rng() idx = jax.random.randint(rng, (), 0, len(model_list)) app.storage.user["selected_model"] = model_list[int(idx)]
basic_javascript_file = nicewebrl.basic_javascript_file() with open(basic_javascript_file) as f: ui.add_body_html("<script>" + f.read() + "</script>")
card = ( ui.card(align_items=["center"]) .classes("fixed-center") .style( "width: 80vw;" # Set width to 90% of viewport width "max-height: 90vh;" # Keep the same max height "overflow: auto;" "display: flex;" "flex-direction: column;" "justify-content: flex-start;" "align-items: center;" "padding: 1rem;" ) ) with card: meta_container = ui.column() with meta_container.style("align-items: center;"): display_container = ui.row() with display_container.style("align-items: center;"): stage_container = ui.column() ui.timer( interval=10, callback=lambda: check_if_over( episode_limit=200, container=stage_container), ) footer_container = ui.row() with meta_container.style("align-items: center;"): await footer(footer_container) with display_container.style("align-items: center;"): await start_experiment(display_container, stage_container)
async def footer(footer_container): """Add user information and progress bar to the footer""" with footer_container: with ui.row():
ui.label().bind_text_from(app.storage.user, "user_id", lambda v: f"user id: {v}.") ui.label()
def text_display(v): stage_idx = max(experiment.num_stages, int(v) + 1) return f"stage: {stage_idx}/{experiment.num_stages}."
ui.label().bind_text_from(app.storage.user, "stage_idx", text_display) ui.label() ui.label() ui.label().bind_text_from( app.storage.user, "session_duration", lambda v: f"minutes passed: {int(v)}." )
ui.linear_progress( value=nicewebrl.get_progress()).bind_value_from(app.storage.user, "stage_progress")
ui.button( "Toggle fullscreen", icon="fullscreen", on_click=nicewebrl.utils.toggle_fullscreen, ).props("flat")
ui.run( storage_secret="private key to secure the browser session cookie", reload="FLY_ALLOC_ID" not in os.environ, title="Social Learning CU", port=8082,).gitignoreAdded+176
README.mdAdded+79
config.pyAdded+12
consent.mdAdded+28
experiment_structure.pyAdded+412
pyproject.tomlAdded+34
smoke_test.pyAdded+70
uv.lockAdded
web_app.pyAdded+544