Spaces:
Running
Running
Sibam commited on
Commit Β·
dada51b
1
Parent(s): 2d2788c
Enhancement
Browse filesFiles changed (4)
- requirements.txt+1
- server/app.py+59-9
- server/environment.py+23-1
- test_api.pyAdded+22
5 unmodified lines6785 unmodified linesdatasets>=2.14.0httpx>=0.25.0websockets>=11.05 unmodified lines67895 unmodified linesdatasets>=2.14.0httpx>=0.25.0websockets>=11.0gradio>=4.0.0
2 unmodified lines34567891011126 unmodified lines19202122232425261 unmodified line28293031323334353637382 unmodified linesExposes the PreferenceLabEnvironment via the OpenEnv HTTP interface.Supports concurrent sessions for parallel training."""import osfrom openenv.core.env_server import create_appfrom models import (6 unmodified lines)from server.environment import PreferenceLabEnvironmentSUPPORTS_CONCURRENT_SESSIONS: bool = TrueMAX_CONCURRENT_ENVS = int(os.environ.get("MAX_CONCURRENT_ENVS", "64"))def create_environment() -> PreferenceLabEnvironment:1 unmodified linereturn PreferenceLabEnvironment()# Use PairwiseAction/PairwiseObservation as the primary schema.# The environment internally handles all three task types.app = create_app(create_environment,PairwiseAction,PairwiseObservation,max_concurrent_envs=MAX_CONCURRENT_ENVS,)2 unmodified lines34567891011121314156 unmodified lines22232425262728291 unmodified line313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687882 unmodified linesExposes the PreferenceLabEnvironment via the OpenEnv HTTP interface.Supports concurrent sessions for parallel training.Web interface (Gradio UI at /web) is enabled when ENABLE_WEB_INTERFACE=true."""import osfrom fastapi.responses import JSONResponsefrom openenv.core.env_server import create_appfrom models import (6 unmodified lines)from server.environment import PreferenceLabEnvironmentMAX_CONCURRENT_ENVS = int(os.environ.get("MAX_CONCURRENT_ENVS", "64"))ENABLE_WEB_INTERFACE = os.environ.get("ENABLE_WEB_INTERFACE", "true").lower() == "true"def create_environment() -> PreferenceLabEnvironment:1 unmodified linereturn PreferenceLabEnvironment()if ENABLE_WEB_INTERFACE:try:from openenv.core.env_server import create_web_interface_app# Mounts the Gradio playground at /web and redirects / β /web/app = create_web_interface_app(create_environment,PairwiseAction,PairwiseObservation,env_name="preference_lab",max_concurrent_envs=MAX_CONCURRENT_ENVS,)except (ModuleNotFoundError, ImportError):# gradio not installed β fall back to plain APIENABLE_WEB_INTERFACE = Falseif not ENABLE_WEB_INTERFACE:# Plain REST + WebSocket API only (no Gradio)app = create_app(create_environment,PairwiseAction,PairwiseObservation,max_concurrent_envs=MAX_CONCURRENT_ENVS,)# ββ Browser housekeeping routes ββββββββββββββββββββββββββββββββ# Browsers auto-request these; returning proper responses prevents# console 404 noise and enables basic PWA support.@app.get("/manifest.json", include_in_schema=False)async def web_manifest():"""Basic PWA web app manifest β silences browser manifest fetch errors."""return JSONResponse({"name": "PreferenceLab","short_name": "PrefLab","description": "OpenEnv RLHF preference data collection environment","start_url": "/web/","display": "standalone","background_color": "#0f172a","theme_color": "#6366f1","icons": [{"src": "https://huggingface.co/front/assets/huggingface_logo-noborder.svg","sizes": "any","type": "image/svg+xml",}],})@app.get("/.well-known/appspecific/com.chrome.devtools.json", include_in_schema=False)async def chrome_devtools():"""Suppress Chrome DevTools discovery 404."""return JSONResponse({})
196 unmodified lines19719819920020120292 unmodified lines295296297298299300301302303304305306307308309196 unmodified linesThe task type is fixed per episode (chosen at reset)."""def __init__(self):self._episode_id: str = ""self._step_count: int = 092 unmodified linesreturn rng.choice(dataset)def _grade(self, action) -> tuple[float, dict]:"""Dispatch to the correct grader based on task type."""if self._task_type == "pairwise":return grade_pairwise(action, self._current_example)elif self._task_type == "likert":return grade_likert(action, self._current_example)elif self._task_type == "consistency":return grade_consistency(action, self._current_example)return 0.0, {"error": "unknown_task"}def _build_observation(self, reward: float, done: bool, info: dict):"""Build the appropriate observation type for the current task."""ex = self._current_example196 unmodified lines19719819920020120220320420520692 unmodified lines299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331196 unmodified linesThe task type is fixed per episode (chosen at reset)."""# All state is stored in instance variables (self._*), so each session# is fully isolated β concurrent use is safe.SUPPORTS_CONCURRENT_SESSIONS: bool = Truedef __init__(self):self._episode_id: str = ""self._step_count: int = 092 unmodified linesreturn rng.choice(dataset)def _grade(self, action) -> tuple[float, dict]:"""Dispatch to the correct grader.Priority: action *instance type* β self._task_type fallback.This matters for the web UI, which always submits a PairwiseAction(the primary schema). Routing by instance type prevents crashes whenthe internal task_type is 'likert' or 'consistency'."""if isinstance(action, PairwiseAction):return grade_pairwise(action, self._current_example)elif isinstance(action, LikertAction):return grade_likert(action, self._current_example)elif isinstance(action, ConsistencyAction):return grade_consistency(action, self._current_example)# Legacy fallback β dispatch by task_type string (e.g. dict-based actions)if self._task_type == "pairwise":return grade_pairwise(action, self._current_example)elif self._task_type == "likert":return grade_likert(action, self._current_example)elif self._task_type == "consistency":return grade_consistency(action, self._current_example)return 0.0, {"error": "unknown_task"}def _build_observation(self, reward: float, done: bool, info: dict):"""Build the appropriate observation type for the current task."""ex = self._current_example
12345678910111213141516171819202122from server.environment import PreferenceLabEnvironmentfrom models import PairwiseAction, LikertAction, ConsistencyAction
env = PreferenceLabEnvironment()
# Task 1obs = env.reset(seed=42, task_type='pairwise')print('TASK 1 prompt:', obs.prompt[:60])obs, r, done, _ = env.step(PairwiseAction(choice='A'))print('Reward:', r)
# Task 2 obs = env.reset(seed=42, task_type='likert')print('TASK 2 response:', obs.response[:60])obs, r, done, _ = env.step(LikertAction(helpfulness=5, honesty=5, harmlessness=5, instruction_following=5))print('Reward:', r)
# Task 3obs = env.reset(seed=42, task_type='consistency')print('TASK 3 prompt:', obs.prompt[:60])obs, r, done, _ = env.step(ConsistencyAction(ranking=['C','A','B','D']))print('Reward:', r)requirements.txt+1
server/app.py+59-9
server/environment.py+23-1
test_api.pyAdded+22