Spaces:
Running
Running
Sibam commited on
Commit Β·
fc4db35
1
Parent(s): cdf485e
Updated README of preferencelab
Browse files6 unmodified lines7891011121314151617181920212223242526272829303132333435363738394041424344454647481 unmodified line50515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641 unmodified line1661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402411 unmodified line2432442452462472482492502512522532546 unmodified linespinned: false---# π§ͺ PreferenceLab**An OpenEnv environment simulating the RLHF human preference data collection pipeline.**> Built for the Meta Γ Hugging Face OpenEnv Hackathon β Team Nexis---## OverviewPreferenceLab is a real-world OpenEnv environment where an AI agent learns to judgethe quality of LLM responses β exactly as a human annotator would in an RLHF pipeline.Instead of expensive, slow human annotators, the environment provides:- **Deterministic grading** using gold labels from real preference datasets- **Partial reward signals** at every step (not just binary end-of-episode)- **3 task difficulty levels**: pairwise β multi-axis scoring β transitive rankingThis fills a genuine gap: zero existing OpenEnv environments simulate the RLHFdata collection pipeline that powers models like Llama, Claude, and GPT-4.---## Action & Observation Spaces### Task 1 β Pairwise Ranking (Easy)**Observation:**```pythonPairwiseObservation(prompt: str, # The user instructionresponse_a: str, # Candidate response Aresponse_b: str, # Candidate response Breward: float, # Last step rewarddone: bool,step_count: int,)```1 unmodified line```pythonPairwiseAction(choice: Literal["A", "B", "tie", "skip"],justification: Optional[str], # not graded)```**Grader:** +1.0 correct | +0.3 skip | +0.1 tie | +0.0 wrong---### Task 2 β Multi-Axis Likert Scoring (Medium)**Observation:**```pythonLikertObservation(prompt: str,response: str,rubric: str, # Scoring instructionsreward: float,done: bool,step_count: int,)```**Action:**```pythonLikertAction(helpfulness: int, # 1-5honesty: int, # 1-5harmlessness: int, # 1-5instruction_following: int # 1-5)```**Grader:** `reward = 1.0 - (MAE / 4.0)` β continuous signal based on deviation from gold scores---### Task 3 β Transitive Consistency Ranking (Hard)**Observation:**```pythonConsistencyObservation(prompt: str,response_a: str,response_b: str,response_c: str,response_d: str,reward: float,done: bool,step_count: int,)```**Action:**```pythonConsistencyAction(ranking: list[str] # e.g. ["C", "A", "D", "B"] bestβworst)```**Grader:** Transitivity score (0.0β0.5) + Kendall's tau quality correlation (0.0β0.5)---## Reward Function| Component | Range | Description ||---|---|---|| Correctness | 0.0β1.0 | Agreement with gold label || Partial credit | 0.1β0.3 | For abstain/tie actions || Trajectory | cumulative | Sum over episode steps |Rewards are **non-sparse** β every step provides a signal. Graders are**deterministic** and **reproducible** β same seed = same episode.---## Setup### Local Development```bashgit clone https://github.com/your-username/preference-labcd preference-labpip install -e .# Optional: download real datasetspython scripts/prepare_datasets.py --samples 200# Run testspytest tests/ -v# Run inference baselinepython inference.py```### Environment Variables| Variable | Required | Default | Description ||---|---|---|---|| `API_BASE_URL` | Yes | `https://api-inference.huggingface.co/v1` | LLM API endpoint || `MODEL_NAME` | Yes | `meta-llama/Llama-3.1-8B-Instruct` | Model to use for inference || `HF_TOKEN` | Yes | β | Hugging Face API key || `ENV_BASE_URL` | No | `http://localhost:8000` | Space URL for remote use || `MAX_CONCURRENT_ENVS` | No | `64` | Parallel sessions supported |### Docker```bashdocker build -t preference-lab .docker run -p 8000:8000 \-e HF_TOKEN=$HF_TOKEN \-e API_BASE_URL=https://api-inference.huggingface.co/v1 \1 unmodified linepreference-lab```---## Using with TRL (GRPO Training)```pythonfrom preference_lab import PreferenceLabEnv, PairwiseActionclass PreferenceEnvWrapper:def __init__(self):self.client = PreferenceLabEnv(base_url="https://your-space.hf.space")self.reward = 0.0def reset(self, **kwargs):obs = self.client.reset()return obs.promptdef rank_responses(self, choice: str) -> str:"""Choose which response is better.Args:choice: 'A' if response A is better, 'B' if B is better, 'tie' if equal.Returns:Feedback on the annotation quality."""result = self.client.step(PairwiseAction(choice=choice))self.reward = result.rewardreturn f"Reward: {result.reward:.2f}"def reward_func(environments, **kwargs):return [env.reward for env in environments]```---## Datasets| Task | Dataset | License ||---|---|---|| Pairwise | Anthropic HH-RLHF | MIT || Likert | UltraFeedback | MIT || Consistency | Stanford SHP | CC BY 4.0 |Fallback synthetic data is included for zero-dependency testing.---## Project Structure```preference-lab/βββ __init__.py # Package exportsβββ models.py # Pydantic Action/Observation modelsβββ client.py # PreferenceLabEnv(MCPToolClient)βββ inference.py # Baseline inference script (START/STEP/END logs)βββ openenv.yaml # OpenEnv manifestβββ pyproject.toml # Dependenciesβββ Dockerfile # Container definitionβββ requirements.txt # Pip requirementsβββ README.md # This fileβββ data/ # Dataset JSONs (or synthetic fallback)βββ scripts/β βββ prepare_datasets.py # Dataset download + conversionβββ server/β βββ app.py # FastAPI serverβ βββ environment.py # Core environment + gradersβββ tests/βββ test_environment.py # Full test suite```---1 unmodified line**Team Nexis** β Sri Sri University Γ Zaalima Development Pvt. Ltd.- Sibam Nanda (Architecture + Core Environment)- Spandan Kar (Backend + Deployment)- Shayanna Behera (Config + Documentation)---## LicenseBSD 3-Clause License6 unmodified lines7891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233241 unmodified line3263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155161 unmodified line5185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766771 unmodified line6796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237246 unmodified linespinned: false---<div align="center"># π§ͺ PreferenceLab### An OpenEnv Environment Simulating the RLHF Human Preference Data Collection Pipeline[](https://www.python.org/)[](https://fastapi.tiangolo.com/)[](https://docs.pydantic.dev/)[](https://www.docker.com/)[](LICENSE)[](https://huggingface.co/)> **Built for the Meta Γ Hugging Face OpenEnv Hackathon β Team Nexis**>> Sri Sri University Γ Zaalima Development Pvt. Ltd.</div>---## Table of Contents- [Overview](#overview)- [Why PreferenceLab?](#why-preferencelab)- [System Architecture](#system-architecture)- [File Architecture](#file-architecture)- [Task Design](#task-design)- [Task 1 β Pairwise Ranking (Easy)](#task-1--pairwise-ranking-easy)- [Task 2 β Multi-Axis Likert Scoring (Medium)](#task-2--multi-axis-likert-scoring-medium)- [Task 3 β Transitive Consistency Ranking (Hard)](#task-3--transitive-consistency-ranking-hard)- [Reward Function](#reward-function)- [Datasets](#datasets)- [Quick Start](#quick-start)- [Local Development](#local-development)- [Environment Variables](#environment-variables)- [Docker Deployment](#docker-deployment)- [How the Project Runs](#how-the-project-runs)- [Integration Guide](#integration-guide)- [Using with TRL / GRPO Training](#using-with-trl--grpo-training)- [Client API Reference](#client-api-reference)- [Testing](#testing)- [Team](#team)- [License](#license)---## Overview**PreferenceLab** is a real-world [OpenEnv](https://github.com/meta-pytorch/openenv) environment where an AI agent learns to judge the quality of LLM responses β exactly as a human annotator would during an RLHF (Reinforcement Learning from Human Feedback) pipeline.Instead of expensive, slow human annotators, PreferenceLab provides:- β **Deterministic grading** using gold labels sourced from real preference datasets- β **Dense (non-sparse) reward signals** at every annotation step β not just episode-end- β **Three progressive difficulty levels**: pairwise choice β multi-axis Likert scoring β transitive 4-way ranking- β **Synthetic fallback data** for zero-dependency, offline testing- β **Concurrent session support** for parallel RL training (up to 64 sessions by default)- β **Reproducible episodes** via seeded random sampling---## Why PreferenceLab?There are **zero existing OpenEnv environments** that simulate the RLHF data collection pipeline β the same pipeline that produces the alignment data used to fine-tune models like Llama 3, Claude, and GPT-4.| Pain Point | PreferenceLab Solution ||---|---|| Human annotators are slow & expensive | AI agent replaces the annotator role || Binary end-of-episode rewards cause sparse gradients | Every step yields a graded reward signal || Single-task environments limit curriculum learning | Three tasks of increasing complexity || Hard-to-reproduce evaluations | Seeded episodes are fully deterministic || Local dev blocked by API dependencies | Built-in synthetic fallback datasets |---## System Architecture```ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ PreferenceLab System ββ ββ βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ ββ β External AI Agent / TRL β ββ β (e.g., GRPO training loop, inference.py baseline) β ββ ββββββββββββββββββ¬βββββββββββββββββββββββ¬βββββββββββββββββββββββββββββ ββ β HTTP / WebSocket β Structured JSON ββ β (OpenEnv Protocol) β Actions & Observations ββ βΌ βΌ ββ ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ ββ β FastAPI Server (server/app.py) β ββ β β ββ β ββββββββββββββββ ββββββββββββββββ ββββββββββββββββββββββββ β ββ β β /reset β β /step β β /state /health β β ββ β β endpoint β β endpoint β β endpoints β β ββ β ββββββββ¬ββββββββ ββββββββ¬ββββββββ ββββββββββββββββββββββββ β ββ β β β β ββ β βΌ βΌ β ββ β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β ββ β β PreferenceLabEnvironment β β ββ β β (server/environment.py) β β ββ β β β β ββ β β βββββββββββββββ ββββββββββββββββ βββββββββββββββββββββ β β ββ β β β Task 1 β β Task 2 β β Task 3 β β β ββ β β β Pairwise β β Likert β β Consistency β β β ββ β β β Grader β β Grader β β Grader β β β ββ β β β (MAE=0/1) β β (MAE/4.0) β β (tau+transitive) β β β ββ β β ββββββββ¬ββββββββ ββββββββ¬ββββββββ βββββββββββ¬βββββββββ β β ββ β β βββββββββββββββββββ΄βββββββββββββββββββββββ β β ββ β β β β β ββ β β reward, done, info β β ββ β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β ββ ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ ββ β ββ ββββββββββββββΌβββββββββββββββ ββ β data/ Directory β ββ β pairwise_data.json β ββ β likert_data.json β ββ β consistency_data.json β ββ β (β synthetic fallback β ββ β if files missing) β ββ βββββββββββββββββββββββββββββ ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ```### Data Flow```Agent Server Environmentβ β ββββ POST /reset ββββββββββΊβ ββ βββ env.reset(task_type) βββΊββ β βββ sample exampleβ β βββ build observationββββ Observation βββββββββββ PairwiseObservation ββββββ β ββββ POST /step βββββββββββΊβ ββ {action: {...}} βββ env.step(action) βββββββΊββ β βββ grade actionβ β βββ compute rewardβ β βββ sample next exampleββββ StepResult ββββββββββββ (obs, reward, done) ββββββ {reward: 0.87, ...} β β```### Deployment Architecture```ββββββββββββββββββββββββββββββββββββββββββββ Hugging Face Space ββ ββ ββββββββββββββββββββββββββββββββββ ββ β Docker Container β ββ β β ββ β ENV: uvicorn server.app:app β ββ β --host 0.0.0.0 β ββ β --port 8000 β ββ β β ββ β HF_TOKEN ββββββββββββββββββΊ β ββ β API_BASE_URL βββββββββββββββΊ β ββ β MODEL_NAME βββββββββββββββββΊ β ββ β MAX_CONCURRENT_ENVS=64 βββββΊ β ββ ββββββββββββββββββββββββββββββββββ ββ ββ Public URL: https://your-space.hf.spaceββββββββββββββββββββββββββββββββββββββββββββββ MCPToolClient (WebSocket/HTTP)βΌββββββββββββββββββββββββ External Trainer ββ (TRL / GRPO) ββββββββββββββββββββββββ```---## File Architecture```preference-lab/ββββ π __init__.py # Package entry point β exports PreferenceLabEnv,β # PairwiseAction, LikertAction, ConsistencyAction,β # and all Observation types.ββββ π models.py # Pydantic v2 data models for all actions andβ # observations. Defines the contract between agentβ # and environment (Actions β Observations).β # β’ PairwiseAction / PairwiseObservationβ # β’ LikertAction / LikertObservationβ # β’ ConsistencyAction/ ConsistencyObservationββββ π client.py # PreferenceLabEnv β thin wrapper aroundβ # openenv.core.MCPToolClient. Provides sync/asyncβ # tool-calling interface to the server.ββββ π inference.py # Baseline LLM inference script.β # Runs all three tasks end-to-end using theβ # OpenAI client against any compatible API.β # Produces structured START / STEP / END logs.ββββ π openenv.yaml # OpenEnv manifest (spec v1).β # Declares runtime=fastapi, app=server.app:app,β # port=8000, type=space.ββββ π pyproject.toml # Build config (setuptools) + project metadata.β # Core deps: openenv-core, fastapi, uvicorn,β # pydantic, openai, datasets, httpx, websockets.β # Dev extras: pytest, pytest-asyncio, httpx.ββββ π requirements.txt # Flat pip requirements (same as pyproject deps).ββββ π Dockerfile # Multi-stage Docker build.β # Builder stage: installs uv + deps via uv sync.β # Runtime stage: copies .venv + code, runs uvicorn.β # HEALTHCHECK: polls /health every 30s.ββββ π .dockerignore # Excludes .git, __pycache__, *.pyc, data/*.jsonβ # from Docker build context.ββββ π .gitignore # Standard Python .gitignore + data/*.json.βββββ π server/ # FastAPI server packageβ βββ π __init__.pyβ ββ βββ π app.py # App factory β calls openenv.core.create_app()β β # with PreferenceLabEnvironment as the factory,β β # PairwiseAction/Observation as the primary schema,β β # and MAX_CONCURRENT_ENVS (default: 64) for sessionβ β # concurrency. This produces all REST + WebSocketβ β # endpoints automatically.β ββ βββ π environment.py # Core environment logic (514 lines).β #β # ββ PreferenceLabEnvironment (Environment) βββββββ # β reset() β initial Observation ββ # β step() β (obs, reward, done, info) ββ # β state() β episode metadata dict ββ # βββββββββββββββββββββββββββββββββββββββββββββββββ #β # Graders:β # grade_pairwise() β {0.0, 0.1, 0.3, 1.0}β # grade_likert() β 1.0 - (MAE / 4.0)β # grade_consistency() β tau_score + transit_scoreβ #β # Synthetic fallback data embedded as functions:β # _synthetic_pairwise() β 8 examplesβ # _synthetic_likert() β 6 examplesβ # _synthetic_consistency() β 5 examplesβββββ π data/ # Dataset storage directoryβ βββ π .gitkeep # Ensures directory is tracked in git (data excluded)β βββ π README.md # Documents each JSON schemaβ ββ βββ π pairwise_data.json # [generated] HH-RLHF pairwise examplesβ β # Fields: prompt, response_a, response_b,β β # gold_label ("A"|"B"), sourceβ ββ βββ π likert_data.json # [generated] UltraFeedback multi-axis examplesβ β # Fields: prompt, response, rubric,β β # gold_scores {helpfulness, honesty,β β # harmlessness, instruction_following}β ββ βββ π consistency_data.json # [generated] Stanford SHP 4-way ranking examplesβ # Fields: prompt, response_a/b/c/d,β # gold_ranking (list[str])βββββ π scripts/ # Utility scriptsβ βββ π __init__.pyβ βββ π prepare_datasets.py # Downloads HH-RLHF, UltraFeedback, Stanford SHPβ # from Hugging Face and converts to PreferenceLabβ # JSON format. Writes to data/. Falls back gracefullyβ # if HF download fails.β # CLI: python scripts/prepare_datasets.py --samples Nβββββ π tests/ # Test suiteβββ π __init__.pyβββ π test_environment.py # Full test suite (248 lines, pytest).# TestPairwiseGrader (5 tests)# TestLikertGrader (4 tests)# TestConsistencyGrader (5 tests)# TestPreferenceLabEnvironment (11 tests)# Run: pytest tests/ -v```---## Task DesignPreferenceLab exposes three annotation tasks of increasing complexity. Each task type is a distinct Observation/Action contract, and episodes run for a fixed 5 steps.### Task 1 β Pairwise Ranking (Easy)The agent sees a prompt and two candidate responses (A, B). It must choose which is better.**Observation:**```pythonPairwiseObservation(task_id: str, # Unique step identifiertask_type: Literal["pairwise"],prompt: str, # The user instructionresponse_a: str, # Candidate response Aresponse_b: str, # Candidate response Breward: float, # Reward from the last stepdone: bool, # Whether the episode is completestep_count: int, # Current step index (0β5)info: dict, # Debug metadata)```1 unmodified line```pythonPairwiseAction(choice: Literal["A", "B", "tie", "skip"],justification: Optional[str], # Free-text reasoning (not graded))```**Source Dataset:** Anthropic HH-RLHF β `data/pairwise_data.json`---### Task 2 β Multi-Axis Likert Scoring (Medium)The agent scores a single response on four quality axes using a 1β5 Likert scale, guided by a scoring rubric.**Observation:**```pythonLikertObservation(task_id: str,task_type: Literal["likert"],prompt: str, # The user instructionresponse: str, # The single response to evaluaterubric: str, # Scoring rubric / instructionsreward: float,done: bool,step_count: int,info: dict,)```**Action:**```pythonLikertAction(helpfulness: int, # 1 (not helpful) β 5 (extremely helpful)honesty: int, # 1 (misleading) β 5 (fully honest)harmlessness: int, # 1 (harmful) β 5 (completely safe)instruction_following: int # 1 (ignores) β 5 (follows perfectly))```**Source Dataset:** UltraFeedback (openbmb) β `data/likert_data.json`---### Task 3 β Transitive Consistency Ranking (Hard)The agent sees a prompt with four candidate responses (A, B, C, D) and must rank them from best to worst. Scored on both ranking quality and internal consistency.**Observation:**```pythonConsistencyObservation(task_id: str,task_type: Literal["consistency"],prompt: str,response_a: str, # Candidate Aresponse_b: str, # Candidate Bresponse_c: str, # Candidate Cresponse_d: str, # Candidate Dreward: float,done: bool,step_count: int,info: dict,)```**Action:**```pythonConsistencyAction(ranking: list[str] # 4 IDs ordered best β worst, e.g. ["C", "A", "D", "B"])```**Source Dataset:** Stanford SHP (stanfordnlp) β `data/consistency_data.json`---## Reward FunctionAll rewards are **non-sparse** β every step produces a signal. All graders are **deterministic** and **reproducible** given the same seed.### Pairwise Grader| Agent Choice | Gold Label | Reward | Verdict ||---|---|---|---|| `"A"` | `"A"` | **1.0** | Correct || `"B"` | `"A"` | **0.0** | Incorrect || `"skip"` | any | **0.3** | Abstained (partial credit) || `"tie"` | any | **0.1** | Tie when gold is clear |### Likert GraderReward is computed as the normalised inverse of Mean Absolute Error (MAE) across all four axes:```MAE = mean(|agent_score[axis] - gold_score[axis]|) over 4 axesreward = 1.0 - (MAE / 4.0) β [0.0, 1.0]```> Max error per axis = 4 (scoring 1 when gold is 5, or vice versa).### Consistency GraderThe reward has two independent components:| Component | Range | Description ||---|---|---|| **Transitivity score** | 0.0 β 0.5 | 0.5 if ranking contains all valid IDs `{A, B, C, D}`, else 0.0 || **Quality score** | 0.0 β 0.5 | Kendall's Ο normalised from `[-1, 1]` to `[0, 0.5]` vs gold ranking || **Total reward** | 0.0 β 1.0 | `transitivity_score + quality_score` |### Episode-Level Reward Summary| Metric | Description ||---|---|| `step_reward` | Reward for the current annotation action || `cumulative_reward` | Sum of all step rewards in the episode || `avg_reward` | `cumulative_reward / steps` β reported at episode end |---## Datasets| Task | Dataset | Source | License | Samples ||---|---|---|---|---|| Pairwise Ranking | [Anthropic HH-RLHF](https://huggingface.co/datasets/Anthropic/hh-rlhf) | HuggingFace | MIT | 100 (default) || Likert Scoring | [UltraFeedback](https://huggingface.co/datasets/openbmb/UltraFeedback) | HuggingFace | MIT | 100 (default) || Consistency Ranking | [Stanford SHP](https://huggingface.co/datasets/stanfordnlp/SHP) | HuggingFace | CC BY 4.0 | 50 (default) |**Important:** If dataset JSON files are not present, the environment automatically falls back to embedded synthetic data covering all three task types. No download is required to run.---## Quick Start### Local Development**1. Clone and install:**```bashgit clone https://github.com/SIBAM890/preference-labcd preference-labpip install -e .```**2. (Optional) Download real preference datasets:**```bashpython scripts/prepare_datasets.py --samples 200```> If skipped, the environment uses built-in synthetic data β no configuration needed.**3. Run the test suite:**```bashpytest tests/ -v```**4. Start the FastAPI server locally:**```bashuvicorn server.app:app --host 0.0.0.0 --port 8000```**5. Run the baseline inference script:**```bashexport HF_TOKEN=hf_your_token_herepython inference.py```---### Environment Variables| Variable | Required | Default | Description ||---|---|---|---|| `HF_TOKEN` | **Yes** | β | Hugging Face API key (auto-injected in HF Spaces) || `API_BASE_URL` | Yes | `https://api-inference.huggingface.co/v1` | LLM API endpoint (OpenAI-compatible) || `MODEL_NAME` | Yes | `meta-llama/Llama-3.1-8B-Instruct` | Model identifier to use for inference || `ENV_BASE_URL` | No | `http://localhost:8000` | PreferenceLab Space URL (for remote client use) || `MAX_CONCURRENT_ENVS` | No | `64` | Maximum concurrent environment sessions |---### Docker Deployment**Build:**```bashdocker build -t preference-lab .```**Run locally:**```bashdocker run -p 8000:8000 \-e HF_TOKEN=$HF_TOKEN \-e API_BASE_URL=https://api-inference.huggingface.co/v1 \1 unmodified linepreference-lab```**Health check endpoint:**```GET http://localhost:8000/health```The container automatically polls `/health` every 30 seconds and restarts on failure.---## How the Project RunsThe startup sequence follows this order:```1. Docker / uvicorn startsβββΊ uvicorn server.app:app --host 0.0.0.0 --port 80002. server/app.py is importedβββΊ openenv.core.create_app(create_environment, PairwiseAction, ...)βββΊ Registers REST + WebSocket endpointsβββΊ Registers /reset, /step, /state, /health routesβββΊ MAX_CONCURRENT_ENVS session slots initialized3. First agent request: POST /resetβββΊ create_environment() called β PreferenceLabEnvironment()βββΊ Loads data/*.json (or falls back to synthetic)βββΊ env.reset(task_type=..., seed=...) calledβββΊ Returns initial Observation4. Agent steps: POST /stepβββΊ env.step(action) calledβββΊ _grade(action) dispatches to correct graderβββΊ _sample_example() draws next item from datasetβββΊ Returns (observation, reward, done, info)5. Episode ends (step_count == 5)βββΊ done=True returnedβββΊ Agent calls /reset to start new episode```**Local inference run (`python inference.py`):**```inference.pyββββ Imports PreferenceLabEnvironment directly (no HTTP)ββββ run_task1_pairwise()β βββ env.reset(task_type="pairwise")β βββ for step in range(5):β βββ call_llm() β parse_json_response() β PairwiseActionβ βββ env.step(action) β log_step()β βββ log_end()ββββ run_task2_likert() (same pattern)ββββ run_task3_consistency() (same pattern)ββββ Print RESULTS SUMMARY (avg_reward per task + overall)```---## Integration Guide### Using with TRL / GRPO Training```pythonfrom preference_lab import PreferenceLabEnv, PairwiseActionclass PreferenceEnvWrapper:"""OpenEnv wrapper compatible with TRL's GRPO trainer."""def __init__(self, base_url: str = "https://your-space.hf.space"):self.client = PreferenceLabEnv(base_url=base_url)self.reward = 0.0def reset(self, **kwargs) -> str:"""Reset environment and return the prompt string."""obs = self.client.reset()return obs.promptdef rank_responses(self, choice: str) -> str:"""Annotate which response is better.Args:choice: "A" if response A is better, "B" if B is better,"tie" if equal, "skip" if undecidable.Returns:Feedback string with reward value."""result = self.client.step(PairwiseAction(choice=choice))self.reward = result.rewardreturn f"Reward: {result.reward:.2f}"def reward_func(environments, **kwargs) -> list[float]:"""Reward function for TRL GRPO β returns reward per environment."""return [env.reward for env in environments]```---### Client API ReferenceThe `PreferenceLabEnv` client extends `MCPToolClient` and supports both sync and async usage:**Async (recommended for training loops):**```pythonfrom preference_lab import PreferenceLabEnv, LikertActionasync with PreferenceLabEnv(base_url="https://your-space.hf.space") as env:obs = await env.reset(task_type="likert")result = await env.step(LikertAction(helpfulness=4, honesty=5, harmlessness=5, instruction_following=4))print(f"Reward: {result.reward}")```**Sync (for simpler scripts):**```pythonfrom preference_lab import PreferenceLabEnv, ConsistencyActionwith PreferenceLabEnv(base_url="http://localhost:8000").sync() as env:obs = env.reset(task_type="consistency")tools = env.list_tools() # ["rank_responses", "score_response", "order_responses"]result = env.call_tool("order_responses", ranking=["C", "A", "D", "B"])```---## TestingThe full test suite covers grader correctness, environment integration, and edge cases:```bash# Run all testspytest tests/ -v# Run a specific test classpytest tests/test_environment.py::TestPairwiseGrader -v# Run with coveragepytest tests/ -v --cov=. --cov-report=term-missing```| Test Class | Tests | Coverage ||---|---|---|| `TestPairwiseGrader` | 5 | All pairwise reward branches (correct, wrong, skip, tie, range) || `TestLikertGrader` | 4 | Perfect score, worst score, partial error, reward range fuzz || `TestConsistencyGrader` | 5 | Perfect ranking, reversed, invalid IDs, all permutations, grader variance || `TestPreferenceLabEnvironment` | 11 | reset, step, episode termination, state, reproducibility, reward variance, all tasks |---1 unmodified line**Team Nexis** β Sri Sri University Γ Zaalima Development Pvt. Ltd.| Member | Role ||---|---|| **Sibam Nanda** | Architecture + Core Environment || **Spandan Kar** | Backend + Deployment || **Shayanna Behera** | Config + Documentation |---## License```BSD 3-Clause LicenseCopyright (c) 2024, Team NexisSri Sri University Γ Zaalima Development Pvt. Ltd.Redistribution and use in source and binary forms, with or withoutmodification, are permitted provided that the following conditions are met:1. Redistributions of source code must retain the above copyright notice,this list of conditions and the following disclaimer.2. Redistributions in binary form must reproduce the above copyright notice,this list of conditions and the following disclaimer in the documentationand/or other materials provided with the distribution.3. Neither the name of the copyright holder nor the names of its contributorsmay be used to endorse or promote products derived from this softwarewithout specific prior written permission.THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"AND WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED.```---<div align="center">**PreferenceLab** Β· Built with β€οΈ for the Meta Γ Hugging Face OpenEnv Hackathon[π€ Hugging Face Space](https://huggingface.co/) Β· [π OpenEnv Spec](https://github.com/meta-pytorch/openenv) Β· [π Issues](https://github.com/SIBAM890/preference-lab/issues)</div>
README.md+557-87