Spaces:
Running
Running
Sibam commited on
Commit Β·
792fb5f
1
Parent(s): e1b44ad
docs: complete README rewrite with ASCII architecture, accurate API/file docs
Browse files20 unmodified lines212223242525262728299 unmodified lines3940414142434442434445464747484950484950525351555253545556575862596061626667686970716364656667686970717273744 unmodified lines79808182828384858687888990919192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535549293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310640311312313314644315316646647648649650651652653654655656657658659317318319320321664665322323324325326669327328329330331332333334335336337338339675340341677678679680681682683684685686687688689690342343344345346695696697698347348349350351352353702354355356357358359360361362363364365366367368369370371708372373710711712713714715716717718719720721722723724725374375376377378730379380381382734735736737738739740383384742743744745746747748749385386387751388389390753391392393755756757394395396760761762397398764399400766401402768769770771772403404405406774775776777778407408409410411412784785786787788413414415416417418790419420421422423424425426427428429430431432433434435436437438439798440441800442443802444445446447448449450451452453454455456457458805459460461462463807464465466467468469809470811471472473813474475476477478479480816817818481482483484485486487488489490491492493494821495823824496497498499500501829502503831832833834835836837504505506507508509510511512513514515841516517843844845846518519848849850851852853854855520521522523524525526527528529857858859530531532533534535536537538862539540864541542866543544545546547548549550868551552870871872873874875876877878879880881882883884885886887888889890891892893894553554555556557558559560561562563564565566567568569570897571572573900901902903904905906907908909910911912913914915574575576577578579580581582922583584585925926927928586587588930931932589590934935936937591592593594939940941595596597943944945946947948949950951952598599600601602603604955956957958605606607608609960610611612613962614615616617618619620964621622623624966967968969970971972973974975625626627978628629630980631632982983984985633634635636637638639640641642992993643995644645646998999647648649650100110026516526536541005100610071008100910106556566576586596606616626636646656661014101510166676681018101910201021102210231024669670102667167267367467567667767867910296801031103268168210341035683684103710386856866876886896901040104110426916921044104510466936941048104910506956966976986997007017021056703704105870570670720 unmodified lines[](https://www.python.org/)[](https://fastapi.tiangolo.com/)[](https://docs.pydantic.dev/)[](https://gradio.app/)[](https://www.docker.com/)[](LICENSE)[](LICENSE)[](https://huggingface.co/)
> **Built for the Meta Γ Hugging Face OpenEnv Hackathon β Team Nexis**9 unmodified lines- [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) - [Task 1 β Pairwise Ranking](#task-1--pairwise-ranking-easy) - [Task 2 β Multi-Axis Likert Scoring](#task-2--multi-axis-likert-scoring-medium) - [Task 3 β Transitive Consistency Ranking](#task-3--transitive-consistency-ranking-hard)- [Reward Functions](#reward-functions)- [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)- [Environment Variables](#environment-variables)- [API Reference](#api-reference)- [Integration Guide](#integration-guide) - [Using with TRL / GRPO Training](#using-with-trl--grpo-training) - [Client API Reference](#client-api-reference)- [Testing](#testing)- [Team](#team)- [Deployment](#deployment)- [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.**PreferenceLab** is a production-grade [OpenEnv](https://github.com/meta-pytorch/openenv) environment that teaches AI agents to judge LLM response quality β exactly as human annotators do during RLHF (Reinforcement Learning from Human Feedback) pipelines.
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| Feature | Details ||---|---|| β
**Deterministic grading** | Gold labels from real preference datasets (HH-RLHF, UltraFeedback, SHP) || β
**Dense reward signals** | Reward at every annotation step, not just episode-end || β
**Three difficulty levels** | Pairwise β Likert scoring β Transitive 4-way ranking || β
**Synthetic fallback** | Zero-dependency offline testing with built-in data || β
**Concurrent sessions** | Up to 64 parallel RL training sessions by default || β
**Reproducible episodes** | Fully seeded random sampling || β
**Web playground** | Gradio UI at `/web` for interactive testing |
---
4 unmodified lines| 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 || Binary end-of-episode rewards β 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 || No visual interface for debugging | Gradio playground at `/web` |
---
## System Architecture
### ποΈ Component Architecture
```mermaidflowchart TB subgraph Clients["Clients and Consumers"] A1["AI Agent<br/>GRPO / TRL Training"] A2["Baseline Inference<br/>inference.py"] A3["Gradio Web UI<br/>/web"] A4["REST / WebSocket<br/>Direct API"] end
subgraph Server["FastAPI Server β server/app.py"] EP1["/reset POST"] EP2["/step POST"] EP3["/state GET"] EP4["/health GET"] EP5["/web Gradio"] EP6["/manifest.json"] end
subgraph Environment["PreferenceLabEnvironment β server/environment.py"] RESET["reset()<br/>seed Β· task_type Β· episode_id"] STEP["step()<br/>grade action β reward β sample next"] STATE["state<br/>@property β State object"] end
subgraph Graders["Deterministic Graders"] G1["Task 1 Β· Pairwise<br/>+1.0 / 0.3 / 0.1 / 0.0"] G2["Task 2 Β· Likert<br/>1 β MAE / 4.0"] G3["Task 3 Β· Consistency<br/>Kendall-tau + Transitivity"] end
subgraph DataLayer["Data Layer β data/"] D1["pairwise_data.json<br/>HH-RLHF"] D2["likert_data.json<br/>UltraFeedback"] D3["consistency_data.json<br/>Stanford SHP"] D4["Synthetic Fallback<br/>built-in, no download"] end
subgraph Models["Pydantic Models β models.py"] M1["PairwiseAction / Observation"] M2["LikertAction / Observation"] M3["ConsistencyAction / Observation"] end
subgraph External["External Services"] LLM["HF Inference API<br/>meta-llama/Llama-3.1-8B"] end
A1 -- "HTTP / WebSocket" --> Server A2 -- "Direct import" --> Environment A3 -- "Browser" --> EP5 A4 --> Server
EP1 --> RESET EP2 --> STEP EP3 --> STATE EP5 --> RESET EP5 --> STEP
RESET --> Graders STEP --> Graders Graders --> G1 Graders --> G2 Graders --> G3
Environment --> DataLayer D1 -.->|fallback| D4 D2 -.->|fallback| D4 D3 -.->|fallback| D4
Models --> G1 Models --> G2 Models --> G3
A2 -- "OpenAI client" --> LLM
classDef client fill:#1e3a5f,stroke:#4a90d9,color:#e8f4fd,stroke-width:2px classDef grader fill:#3a2a1a,stroke:#ff9800,color:#fff3e0,stroke-width:2px classDef data fill:#2a1a3a,stroke:#9c27b0,color:#f3e5f5,stroke-width:2px classDef model fill:#1a2a3a,stroke:#2196f3,color:#e3f2fd,stroke-width:2px classDef external fill:#3a1a1a,stroke:#f44336,color:#ffebee,stroke-width:2px classDef endpoint fill:#263238,stroke:#607d8b,color:#eceff1,stroke-width:1px
class A1,A2,A3,A4 client class G1,G2,G3 grader class D1,D2,D3,D4 data class M1,M2,M3 model class LLM external class EP1,EP2,EP3,EP4,EP5,EP6 endpoint```
---
### βοΈ Deployment Architecture
```mermaidflowchart LR subgraph Dev["Developer Machine"] CODE["Source Code<br/>preference-lab/"] GIT["git push"] CODE --> GIT end
subgraph HFSpace["Hugging Face Space β Docker SDK"] SECRETS["Secrets Injected<br/>HF_TOKEN<br/>API_BASE_URL<br/>MODEL_NAME<br/>MAX_CONCURRENT_ENVS=64"] CONTAINER["Docker Container<br/>python:3.10-slim"] UVICORN["uvicorn server.app:app<br/>host 0.0.0.0 port 8000"] WEB["Gradio UI<br/>/web"] REST["REST API<br/>/reset /step /state"] HEALTH["Health Check<br/>/health"] PUBURL["Public URL<br/>https://username-preflab.hf.space"]
CONTAINER --> UVICORN UVICORN --> WEB UVICORN --> REST UVICORN --> HEALTH SECRETS -.->|env vars| CONTAINER HFSpace --> PUBURL end
subgraph LLMBackend["HF Inference API"] MODEL["meta-llama/Llama-3.1-8B-Instruct"] end
subgraph Consumers["Consumers"] U1["TRL / GRPO<br/>Training Loop"] U2["Developer<br/>Browser"] U3["inference.py<br/>Baseline Script"] U4["MCPToolClient<br/>PreferenceLabEnv"] end
GIT --> HFSpace
U1 -- "WebSocket / OpenEnv" --> REST U2 -- "HTTPS" --> WEB U3 -- "Direct import" --> UVICORN U4 -- "HTTP / MCP" --> REST
REST -- "OpenAI client<br/>API_BASE_URL + HF_TOKEN" --> MODEL
classDef hf fill:#ff6b00,stroke:#ff9800,color:#fff,stroke-width:2px classDef docker fill:#0db7ed,stroke:#066da5,color:#fff,stroke-width:2px classDef consumer fill:#1e3a5f,stroke:#4a90d9,color:#e8f4fd,stroke-width:2px classDef llm fill:#4a235a,stroke:#9c27b0,color:#f3e5f5,stroke-width:2px classDef secret fill:#3a1a1a,stroke:#f44336,color:#ffebee,stroke-width:2px classDef dev fill:#1a3a2a,stroke:#4caf50,color:#e8f5e9,stroke-width:2px
class PUBURL,HFSpace hf class CONTAINER,UVICORN docker class U1,U2,U3,U4 consumer class MODEL,LLMBackend llm class SECRETS secret class CODE,GIT dev```
---
subgraph HF["βοΈ Hugging Face Space Β· Docker Container"] direction TB
subgraph SERVER["β‘ FastAPI Server Β· server/app.py"] direction LR EP1["/reset\nPOST"] EP2["/step\nPOST"] EP3["/state\nGET"] EP4["/health\nGET"] EP5["/web\nGradio UI"] EP6["/manifest.json\nPWA"] end
subgraph ENV["π¬ PreferenceLabEnvironment Β· server/environment.py"] direction TB RESET["reset()\nSeed Β· TaskType Β· EpisodeID"] STEP["step()\nGrade β Reward β Next Sample"] STATE["state @property\nState object Β· metadata"]
subgraph GRADERS["βοΈ Deterministic Graders"] direction LR G1["Task 1\nPairwise\n+1.0 / 0.3 / 0.1 / 0.0"] G2["Task 2\nLikert\n1 β MAE/4.0"] G3["Task 3\nConsistency\nΟ + Transitivity"] end end
subgraph DATA["ποΈ Data Layer Β· data/"] direction LR D1["pairwise_data.json\nHH-RLHF"] D2["likert_data.json\nUltraFeedback"] D3["consistency_data.json\nStanford SHP"] D4["π Synthetic\nFallback\n(built-in)"] end
subgraph MODELS["π Pydantic Models Β· models.py"] direction LR M1["PairwiseAction\nPairwiseObservation"] M2["LikertAction\nLikertObservation"] M3["ConsistencyAction\nConsistencyObservation"] end end
subgraph EXTERNAL["π External Services"] LLM["π€ HF Inference API\nmeta-llama/Llama-3.1-8B"] end
%% Client β Server A1 -- "HTTP / WebSocket\nOpenEnv Protocol" --> SERVER A2 -- "Direct import\n(local)" --> ENV A3 -- "Browser\nGradio" --> EP5 A4 -- "REST / WS" --> SERVER
%% Server β Environment EP1 --> RESET EP2 --> STEP EP3 --> STATE EP5 --> RESET EP5 --> STEP
%% Environment internals RESET --> GRADERS STEP --> GRADERS GRADERS --> G1 GRADERS --> G2 GRADERS --> G3
%% Data loading ENV --> DATA D1 -.->|fallback| D4 D2 -.->|fallback| D4 D3 -.->|fallback| D4
%% Models MODELS --> G1 MODELS --> G2 MODELS --> G3
%% External A2 -- "OpenAI client\nAPI_BASE_URL" --> LLM
%% Styling classDef client fill:#1e3a5f,stroke:#4a90d9,color:#e8f4fd,stroke-width:2px classDef server fill:#1a3a2a,stroke:#4caf50,color:#e8f5e9,stroke-width:2px classDef grader fill:#3a2a1a,stroke:#ff9800,color:#fff3e0,stroke-width:2px classDef data fill:#2a1a3a,stroke:#9c27b0,color:#f3e5f5,stroke-width:2px classDef model fill:#1a2a3a,stroke:#2196f3,color:#e3f2fd,stroke-width:2px classDef external fill:#3a1a1a,stroke:#f44336,color:#ffebee,stroke-width:2px classDef endpoint fill:#263238,stroke:#607d8b,color:#eceff1,stroke-width:1px
class A1,A2,A3,A4 client class G1,G2,G3 grader class D1,D2,D3,D4 data class M1,M2,M3 model class LLM external class EP1,EP2,EP3,EP4,EP5,EP6 endpoint```
---
### π Request Lifecycle β Data Flow
```mermaidsequenceDiagram autonumber actor Agent as π€ AI Agent / TRL participant API as β‘ FastAPI Server participant Env as π¬ PreferenceLabEnvironment participant Grader as βοΈ Grader participant DB as ποΈ Dataset
Note over Agent,DB: ββ Episode Start βββββββββββββββββββββββββββββββββββββ
Agent ->> API: POST /reset { task_type, seed } API ->> Env: env.reset(task_type, seed) Env ->> DB: _sample_example(rng) DB -->> Env: example { prompt, response_a, response_b, gold_label } Env -->> API: PairwiseObservation { prompt, response_a, response_b, reward=0.0, done=false } API -->> Agent: 200 OK Β· Observation JSON
Note over Agent,DB: ββ Step Loop (max 5 steps) βββββββββββββββββββββββββββ
loop For each annotation step Agent ->> Agent: call_llm(system, user_prompt) Agent ->> API: POST /step { action: { choice: "A" } } API ->> Env: env.step(PairwiseAction) Env ->> Grader: grade_pairwise(action, example) Grader ->> Grader: compare choice vs gold_label Grader -->> Env: reward=1.0, info={ verdict: "correct" } Env ->> DB: _sample_example(rng) Β· next example DB -->> Env: next example Env -->> API: Observation { reward=1.0, done=false, step_count=N } API -->> Agent: 200 OK Β· StepResult JSON Agent ->> Agent: log_step Β· accumulate reward end
Note over Agent,DB: ββ Episode End βββββββββββββββββββββββββββββββββββββββ
Env -->> API: Observation { done=true, step_count=5 } API -->> Agent: 200 OK Β· Final Observation Agent ->> Agent: log_end( score, rewards ) Agent ->> API: POST /reset Β· start new episode```
---
### π§ User Flow
```mermaidflowchart TD START(["π Start"])
subgraph SETUP["βοΈ Setup Phase"] S1["Clone repository\ngit clone"] S2["Install dependencies\npip install -e ."] S3{"Need real\ndatasets?"} S4["Download datasets\nscripts/prepare_datasets.py"] S5["Use synthetic\nfallback data\n(built-in, no download)"] S6["Set environment vars\nHF_TOKEN Β· MODEL_NAME Β· API_BASE_URL"] end
subgraph DEPLOY["π’ Deployment Mode"] D1{"Choose\nmode"} D2["π Local Dev\nuvicorn server.app:app\n--port 8000"] D3["π³ Docker\ndocker build & run"] D4["βοΈ HF Space\ngit push to HuggingFace"] end
subgraph USE["π¬ Usage Mode"] U1{"How to\nuse?"} U2["π Run Baseline\npython inference.py\n[START][STEP][END] logs"] U3["π Web Playground\nlocalhost:8000/web\nGradio UI"] U4["π API Integration\nREST + WebSocket\nOpenEnv Protocol"] U5["π§ͺ Run Tests\npytest tests/ -v\n25 test cases"] U6["π€ TRL / GRPO\nPreferenceLabEnv wrapper\nParallel training sessions"] end
subgraph EPISODE["π Episode Loop"] E1["POST /reset\nChoose task type + seed"] E2{"Task\nType?"} E3["Task 1 Β· Pairwise\nChoose A or B\nreward: 0.0 β 1.0"] E4["Task 2 Β· Likert\nScore 4 axes 1-5\nreward: 1 β MAE/4"] E5["Task 3 Β· Consistency\nRank A B C D\nreward: Ο + transitivity"] E6["POST /step\nSubmit action"] E7["Receive Observation\n+ reward + done"] E8{"done\n== true?"} E9["Next step\nNew example sampled"] E10["Episode complete\nlog_end Β· avg reward"] end
START --> S1 --> S2 --> S3 S3 -->|Yes| S4 --> S6 S3 -->|No| S5 --> S6 S6 --> D1
D1 -->|Local| D2 D1 -->|Docker| D3 D1 -->|Cloud| D4
D2 & D3 & D4 --> U1
U1 -->|Baseline| U2 U1 -->|Interactive| U3 U1 -->|Custom| U4 U1 -->|CI/CD| U5 U1 -->|Training| U6
U2 & U3 & U4 & U6 --> E1
E1 --> E2 E2 -->|pairwise| E3 E2 -->|likert| E4 E2 -->|consistency| E5 E3 & E4 & E5 --> E6 --> E7 --> E8 E8 -->|No| E9 --> E6 E8 -->|Yes| E10
E10 -->|New Episode| E1 E10 -->|Done| FINISH(["β
Complete"])
%% Styling classDef phase fill:#0d1b2a,stroke:#4a90d9,color:#e8f4fd,stroke-width:2px,rx:8 classDef decision fill:#1a1a2e,stroke:#e94560,color:#f5f5f5,stroke-width:2px classDef task1 fill:#1a3a2a,stroke:#4caf50,color:#e8f5e9,stroke-width:2px classDef task2 fill:#3a2a1a,stroke:#ff9800,color:#fff3e0,stroke-width:2px classDef task3 fill:#2a1a3a,stroke:#9c27b0,color:#f3e5f5,stroke-width:2px classDef terminal fill:#1b2838,stroke:#66c0f4,color:#c6d4df,stroke-width:3px,rx:20
class S1,S2,S4,S5,S6 phase class D2,D3,D4 phase class U2,U3,U4,U5,U6 phase class E1,E6,E7,E9,E10 phase class S3,D1,U1,E2,E8 decision class E3 task1 class E4 task2 class E5 task3 class START,FINISH terminal```
---
### βοΈ Deployment Architecture
```mermaidflowchart LR subgraph DEV["π» Developer Machine"] direction TB CODE["π preference-lab/\nSource Code"] GIT["git push"] end
subgraph HF["βοΈ Hugging Face Platform"] direction TB subgraph SPACE["π€ HF Space Β· Docker SDK"] direction TB subgraph DOCKER["π³ Docker Container\npython:3.10-slim"] direction TB UVIG["uvicorn\nserver.app:app\n0.0.0.0:8000"] subgraph APP["FastAPI Application"] WEB["Gradio UI\n/web"] REST["REST API\n/reset Β· /step Β· /state"] HEALTH["Health\n/health"] end UVIG --> APP end ENVVARS["π Secrets\nHF_TOKEN\nAPI_BASE_URL\nMODEL_NAME\nMAX_CONCURRENT_ENVS=64"] ENVVARS -.->|injected| DOCKER end PUBURL["π Public URL\nhttps://username-preference-lab.hf.space"] SPACE --> PUBURL end
subgraph LLMAPI["π€ HF Inference API"] MODEL["meta-llama/\nLlama-3.1-8B-Instruct"] end
subgraph USERS["π₯ Consumers"] direction TB U1["π€ TRL / GRPO\nTraining Loop"] U2["π§βπ» Developer\nBrowser Β· /web"] U3["β‘ inference.py\nBaseline script"] U4["π MCPToolClient\nPreferenceLabEnv"] end
CODE --> GIT --> SPACE
U1 -- "WebSocket\nOpenEnv" --> REST U2 -- "HTTPS" --> WEB U3 -- "Direct\nimport" --> APP U4 -- "HTTP\nMCPToolClient" --> REST
APP -- "OpenAI client\nAPI_BASE_URL + HF_TOKEN" --> MODEL
classDef hf fill:#ff6b00,stroke:#ff9800,color:#fff,stroke-width:2px classDef docker fill:#0db7ed,stroke:#066da5,color:#fff,stroke-width:2px classDef user fill:#1e3a5f,stroke:#4a90d9,color:#e8f4fd,stroke-width:2px classDef api fill:#4a235a,stroke:#9c27b0,color:#f3e5f5,stroke-width:2px classDef secret fill:#3a1a1a,stroke:#f44336,color:#ffebee,stroke-width:2px
class SPACE,PUBURL hf class DOCKER,UVIG docker class U1,U2,U3,U4 user class MODEL,LLMAPI api class ENVVARS secret### Component Overview
```ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ PREFERENCELAB SYSTEM ββ ββ Consumers ββ ββββββββββββββββ ββββββββββββββββ ββββββββββββββββ ββββββββββββββββ ββ β AI Agent β β TRL / GRPO β β Gradio UI β β REST Client β ββ β (training) β β trainer β β (browser) β β (direct) β ββ ββββββββ¬ββββββββ ββββββββ¬ββββββββ ββββββββ¬ββββββββ ββββββββ¬ββββββββ ββ β β β β ββ βββββββββββββββββββ΄ββββ HTTP / WebSocket βββββββββββββββ ββ β ββ βββββββββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββ ββ β FastAPI Server (server/app.py) β ββ β β ββ β /reset /step /state /health /web /manifest.json β ββ βββββββββββββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββ ββ β ββ βββββββββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββ ββ β PreferenceLabEnvironment (server/environment.py) β ββ β β ββ β reset(seed, task_type) step(action) state @property β ββ β β β β ββ β βΌ βΌ β ββ β βββββββββββββ ββββββββββββββββββββββββββββββββββββββββββββββββ β ββ β β Sample β β Deterministic Graders β β ββ β β Example β β β β ββ β β from DB β β grade_pairwise() grade_likert() grade_ β β ββ β βββββββ¬ββββββ β consistency()β β ββ β β ββββββββββββββββββββββββββββββββββββββββββββββββ β ββ β βΌ β ββ β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β ββ β β Data Layer (data/) β β ββ β β β β ββ β β pairwise_data.json likert_data.json consistency_data.jsonβ β ββ β β (HH-RLHF) (UltraFeedback) (Stanford SHP) β β ββ β β β fallback β β ββ β β Synthetic built-in data (no download needed) β β ββ β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β ββ βββββοΏ½οΏ½οΏ½ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ```
### Request Lifecycle
``` Agent / Trainer FastAPI Server PreferenceLabEnvironment β β β βββ POST /reset βββββββββββΊβ β β { task_type, seed } βββ env.reset(task, seed) ββββΊβ β β βββ sample example β β βββ build Observation ββββ 200 Observation βββββββββ PairwiseObservation ββββββ β { prompt, resp_a/b } β { reward=0.0, done=false }β β β β βββ POST /step ββββββββββββΊβ β β { action: { βββ env.step(action) ββββββββββΊβ β choice: "A" } } β βββ grade action β β βββ compute reward β β βββ sample next ββββ 200 Observation βββββββββ PairwiseObservation ββββββ β { reward: 1.0, β { reward, done, step_count}β β done: false } β β β β β β ... repeat up to 5 steps per episode ... β β β β ββββ 200 Observation βββββββββ { done: true } βββββββββββ βββ POST /reset βββββββββββΊβ (start new episode) β```
### Deployment Architecture
``` Developer Machine Hugging Face Platform ββββββββββββββββββ ββββββββββββββββββββββββββββββββββββββββββββββββ β β β HF Space (Docker SDK) β β git push βββββββββββββββββΊ β β β β β ββββββββββββββββββββββββββββββββββββββββ β β preference- β β β Docker Container python:3.10-slim β β β lab/ β β β β β β β β β uvicorn server.app:app β β ββββββββββββββββββ β β host 0.0.0.0 port 8000 β β β β β β β β Env Secrets: β β β β HF_TOKEN βββββββββββββΊ β β β β API_BASE_URL βββββββββββββΊ β β β β MODEL_NAME βββββββββββββΊ β β β β MAX_CONCURRENT_ENVS=64 β β β ββββββββββββββββββββββββββββββββββββββββ β β β β Public: https://user-preflab.hf.space β βββββββββββββββββββββββββββββββββ¬βββββββββββββββ β βββββββββββββββββββββββββββββββββββββββββ€ β β β β ββββββΌββββ βββββββΌβββ βββββββΌβββ ββββΌβββββββ β TRL / β οΏ½οΏ½οΏ½Browser β βinfere- β βMCP β β GRPO β β /web β βnce.py β βToolCl. β ββββββββββ ββββββββββ ββββββββββ βββββββββββ```
---
## File Architecture
```mermaidgraph TD subgraph Root["preference-lab/"] direction TB
subgraph Config["Configuration Files"] direction LR PY[pyproject.toml<br/>Build config & metadata] REQ[requirements.txt<br/>Python dependencies] OPEN[openenv.yaml<br/>OpenEnv manifest] DOCK[Dockerfile<br/>Multi-stage build] DOCKI[.dockerignore<br/>Docker exclusions] GITI[.gitignore<br/>Git exclusions] end
subgraph Core["Core Modules"] direction LR INIT[__init__.py<br/>Package exports] MOD[models.py<br/>Pydantic schemas] CLI[client.py<br/>OpenEnv client wrapper] INF[inference.py<br/>Baseline inference] end
subgraph Server["server/ - FastAPI Backend"] direction TB SINIT[__init__.py] SAPP[app.py<br/>App factory & endpoints] SENV[environment.py<br/>Core environment logic<br/>Graders & data loading] end
subgraph Data["data/ - Datasets"] direction TB DINIT[.gitkeep<br/>Directory placeholder] DREAD[README.md<br/>Schema documentation] PAIR[pairwise_data.json<br/>HH-RLHF examples] LIK[likert_data.json<br/>UltraFeedback examples] CONS[consistency_data.json<br/>Stanford SHP examples] end
subgraph Scripts["scripts/ - Utilities"] direction LR SCINIT[__init__.py] PREP[prepare_datasets.py<br/>Dataset preparation] end
subgraph Tests["tests/ - Test Suite"] direction LR TINIT[__init__.py] TENV[test_environment.py<br/>Environment tests] end
subgraph Standalone["Standalone Files"] direction LR TAPI[test_api.py<br/>API integration tests] end end
classDef config fill:#e3f2fd,stroke:#2196f3,color:#0d47a1 classDef core fill:#f3e5f5,stroke:#9c27b0,color:#4a148c classDef server fill:#e8f5e9,stroke:#4caf50,color:#1b5e20 classDef data fill:#fff3e0,stroke:#ff9800,color:#e65100 classDef scripts fill:#fce4ec,stroke:#e91e63,color:#880e4f classDef tests fill:#f1f8e9,stroke:#8bc34a,color:#2e7d32 classDef standalone fill:#e0f2f1,stroke:#009688,color:#004d40
class PY,REQ,OPEN,DOCK,DOCKI,GITI config class INIT,MOD,CLI,INF core class SINIT,SAPP,SENV server class DINIT,DREAD,PAIR,LIK,CONS data class SCINIT,PREP scripts class TINIT,TENV tests class TAPI standalone```preference-lab/ββββ π README.md β You are hereβββ π LICENSEβββ π .gitignoreβββ π .dockerignoreββββ π openenv.yaml β OpenEnv manifestβ β runtime: fastapiβ β app: server.app:appβ β port: 8000β β type: spaceβ ββββ π Dockerfile β HF Spaces production imageβ β Base: python:3.10-slimβ β CMD: uvicorn server.app:appβ β HEALTHCHECK: polls /health every 30sβ ββββ π requirements.txt β Flat pip dependency listβ β openenv-core, fastapi, uvicorn,β β pydantic, openai, datasets,β β httpx, websockets, gradioβ ββββ π pyproject.toml β Build config + project metadataβ β (setuptools, same deps as above)β ββββ π __init__.py β Package entry pointβ β Exports: PreferenceLabEnv,β β PairwiseAction, LikertAction,β β ConsistencyAction + all Observationsβ ββββ π models.py β Pydantic v2 data modelsβ β Defines the agent β env contractβ ββ β ACTIONS OBSERVATIONSβ β βββββββββββββββββββββββββββββ ββββββββββββββββββββββββββββββββββ β PairwiseAction PairwiseObservationβ β .choice: A|B|tie|skip .prompt, .response_a, .response_bβ β .justification: str? .reward, .done, .step_countβ β ββββββββββββββββββββββββββββββββββ β LikertAction LikertObservationβ β .helpfulness: 1-5 .prompt, .responseβ β .honesty: 1-5 .rubric, .reward, .doneβ β .harmlessness: 1-5 ββββββββββββββββββββββββββββββββββ β .instruction_following: 1-5 ConsistencyObservationβ β .promptβ β ConsistencyAction .response_a, .response_bβ β .ranking: list[str] (len=4) .response_c, .response_dβ β .reward, .doneβ ββββ π client.py β PreferenceLabEnv client wrapperβ β Thin sync/async wrapper aroundβ β openenv.core.MCPToolClientβ ββββ π inference.py β Baseline LLM inference scriptβ β Mandatory stdout format:β β [START] task= env= model=β β [STEP] step= action= reward= done=β β [END] success= steps= score=β ββββ π test_api.py β Quick smoke-test (direct import)β β Tests all 3 tasks in sequenceβ ββββ server/ β Core server packageβ ββ βββ π __init__.pyβ ββ βββ π app.py β FastAPI application factoryβ β ENABLE_WEB_INTERFACE=true β Gradioβ β MAX_CONCURRENT_ENVS=64β β Routes: /manifest.json, /.well-known/β ββ βββ π environment.py β Core OpenEnv environmentβ PreferenceLabEnvironment(Environment)β SUPPORTS_CONCURRENT_SESSIONS = Trueβ ββββββββββββββββββββββββββββββββββββββ reset(seed, task_type, **kwargs)β β Observationβ step(action)β β Observation [reward & done inline]β state @propertyβ β State(episode_id, step_count, ...)β ββββββββββββββββββββββββββββββββββββββ Graders (internal):β grade_pairwise() β +1.0 / 0.3 / 0.1 / 0.0β grade_likert() β 1 β MAE/4.0β grade_consistency()β Kendall-Ο + transitivityββββ data/ β Dataset files (git-ignored)β βββ π pairwise_data.json HH-RLHF gold labelsβ βββ π likert_data.json UltraFeedback multi-axis scoresβ βββ π consistency_data.json Stanford SHP ranking pairsβ (All 3 auto-fallback to syntheticβ data if files are missing)ββββ scripts/β βββ π prepare_datasets.py β Downloads & formats datasetsβ from Hugging Face Hubβ Usage: python scripts/prepare_datasets.pyββββ tests/ βββ π test_environment.py β pytest test suite 25 test cases covering: reset / step / state / graders concurrent sessions / reproducibility```
---
## Task Design
PreferenceLab exposes three annotation tasks of increasing complexity. Each task type is a distinct Observation/Action contract, and episodes run for a fixed 5 steps.PreferenceLab presents agents with three progressively harder annotation tasks, matching real RLHF data collection workflows.
### Task 1 β Pairwise Ranking (Easy)
The agent sees a prompt and two candidate responses (A, B). It must choose which is better.The agent is shown a prompt and two LLM responses (A and B), and must pick the better one.
**Observation:**```pythonPairwiseObservation( task_id: str, # Unique step identifier task_type: Literal["pairwise"], prompt: str, # The user instruction response_a: str, # Candidate response A response_b: str, # Candidate response B reward: float, # Reward from the last step done: bool, # Whether the episode is complete step_count: int, # Current step index (0β5) info: dict, # Debug metadata)```**Observation fields:** `prompt`, `response_a`, `response_b`
**Action:**```pythonPairwiseAction( choice: Literal["A", "B", "tie", "skip"], justification: Optional[str], # Free-text reasoning (not graded) choice="A", # "A" | "B" | "tie" | "skip" justification="..." # optional, not used for grading)```
**Source Dataset:** Anthropic HH-RLHF β `data/pairwise_data.json`**Grading (vs HH-RLHF gold label):**
| Agent choice | Outcome | Reward ||---|---|---|| Correct (matches gold) | β
| `+1.0` || `skip` | β οΈ Abstain | `+0.3` || `tie` (when gold is clear) | β οΈ Hedging | `+0.1` || Wrong choice | β | `+0.0` |
---
### 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.The agent is shown a prompt and a single LLM response, and must score it on four independent quality axes.
**Observation:**```pythonLikertObservation( task_id: str, task_type: Literal["likert"], prompt: str, # The user instruction response: str, # The single response to evaluate rubric: str, # Scoring rubric / instructions reward: float, done: bool, step_count: int, info: dict,)```**Observation fields:** `prompt`, `response`, `rubric`
**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) helpfulness=4, # 1β5 honesty=5, # 1β5 harmlessness=5, # 1β5 instruction_following=4 # 1β5)```
**Source Dataset:** UltraFeedback (openbmb) β `data/likert_data.json`**Grading (vs UltraFeedback gold scores):**
```reward = 1.0 β (MAE / 4.0)
where MAE = mean absolute error across all 4 axes 4.0 = maximum possible error per axis
Perfect match β reward = 1.0Off by 1 each β reward = 0.75Off by 2 each β reward = 0.50Worst case β reward = 0.0```
---
### 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.The agent is shown a prompt and four LLM responses (A, B, C, D), and must rank all four from best to worst. Grading checks both ranking quality and logical transitivity.
**Observation:**```pythonConsistencyObservation( task_id: str, task_type: Literal["consistency"], prompt: str, response_a: str, # Candidate A response_b: str, # Candidate B response_c: str, # Candidate C response_d: str, # Candidate D reward: float, done: bool, step_count: int, info: dict,)```**Observation fields:** `prompt`, `response_a`, `response_b`, `response_c`, `response_d`
**Action:**```pythonConsistencyAction( ranking: list[str] # 4 IDs ordered best β worst, e.g. ["C", "A", "D", "B"] ranking=["B", "A", "D", "C"] # best β worst, all 4 required)```
**Source Dataset:** Stanford SHP (stanfordnlp) β `data/consistency_data.json`
---
## Reward Function
All rewards are **non-sparse** β every step produces a signal. All graders are **deterministic** and **reproducible** given the same seed.**Grading (Kendall-Ο + Transitivity bonus):**
### 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 |```reward = Ξ± Γ kendall_tau + Ξ² Γ transitivity_score
### Likert Graderkendall_tau: normalized rank correlation vs gold ranking range [β1.0, +1.0], clipped to [0, 1]
Reward is computed as the normalised inverse of Mean Absolute Error (MAE) across all four axes:transitivity_score: fraction of (A>B, B>C β A>C) triplets satisfied penalizes logically inconsistent rankings
```MAE = mean(|agent_score[axis] - gold_score[axis]|) over 4 axesreward = 1.0 - (MAE / 4.0) β [0.0, 1.0]Ξ± = 0.7, Ξ² = 0.3 (weighted combination)```
> Max error per axis = 4 (scoring 1 when gold is 5, or vice versa).
### Consistency Grader---
The reward has two independent components:## Reward Functions
| Component | Range | Description || Task | Formula | Range ||---|---|---|| **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| Pairwise | Exact match reward table | `{0.0, 0.1, 0.3, 1.0}` || Likert | `1 β mean(|agent_score β gold_score|) / 4` | `[0.0, 1.0]` || Consistency | `0.7 Γ Kendall-Ο + 0.3 Γ Transitivity` | `[0.0, 1.0]` |
| 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 |All rewards are bounded `[0, 1]` and emitted at **every step** (dense signal).
---
## 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) || Dataset | Task | Source | Samples ||---|---|---|---|| [HH-RLHF](https://huggingface.co/datasets/Anthropic/hh-rlhf) | Pairwise | Anthropic | ~160K pairs || [UltraFeedback](https://huggingface.co/datasets/openbmb/UltraFeedback) | Likert | OpenBMB | ~64K responses || [Stanford SHP](https://huggingface.co/datasets/stanfordnlp/SHP) | Consistency | Stanford | ~385K pairs |
**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.Download all datasets:
```bashpython scripts/prepare_datasets.py# or with custom sample count:python scripts/prepare_datasets.py --samples 5000```
If JSON files are absent, the environment automatically uses **built-in synthetic data** β no download needed for local development.
---
## Quick Start
### Prerequisites
- Python 3.10+- `git`
### Local Development
**1. Clone and install:**```bash# 1. Clonegit clone https://github.com/SIBAM890/preference-labgit clone https://github.com/SIBAM890/preferencelab.gitcd preference-labpip install -e .
# 2. Create virtual environmentpython -m venv venvsource venv/bin/activate # Windows: venv\Scripts\activate
# 3. Install dependenciespip install -r requirements.txt
# 4. (Optional) Download real datasetspython scripts/prepare_datasets.py
# 5. Start the serverpython -m uvicorn server.app:app --host 0.0.0.0 --port 8000 --reload```
**2. (Optional) Download real preference datasets:**Open **http://localhost:8000/web** for the interactive Gradio playground.
### Verify the server is running
```bashpython scripts/prepare_datasets.py --samples 200curl http://localhost:8000/health# β {"status":"healthy"}
curl http://localhost:8000/schema# β full action / observation JSON schema```> If skipped, the environment uses built-in synthetic data β no configuration needed.
**3. Run the test suite:**### Run the baseline inference script
```bashpytest tests/ -v# Set your API credentials (or use any OpenAI-compatible endpoint)export HF_TOKEN=hf_your_token_hereexport MODEL_NAME=meta-llama/Llama-3.1-8B-Instruct
python inference.py```
**4. Start the FastAPI server locally:**```bashuvicorn server.app:app --host 0.0.0.0 --port 8000Expected output format:
```[START] task=pairwise-ranking env=preference_lab model=meta-llama/Llama-3.1-8B-Instruct[STEP] step=1 action=choice=A reward=1.00 done=false error=null[STEP] step=2 action=choice=B reward=0.00 done=false error=null[STEP] step=3 action=choice=A reward=1.00 done=false error=null[STEP] step=4 action=choice=A reward=1.00 done=false error=null[STEP] step=5 action=choice=B reward=0.00 done=true error=null[END] success=true steps=5 score=0.60 rewards=1.00,0.00,1.00,1.00,0.00```
### Run tests
**5. Run the baseline inference script:**```bashexport HF_TOKEN=hf_your_token_herepython inference.pypytest tests/ -v# 25 test cases β reset, step, state, graders, concurrency, reproducibility```
---
### Environment Variables## 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 || Variable | Default | Description ||---|---|---|| `HF_TOKEN` | _(none)_ | Hugging Face API token for LLM inference || `API_BASE_URL` | `https://api-inference.huggingface.co/v1` | LLM API endpoint (any OpenAI-compatible URL) || `MODEL_NAME` | `meta-llama/Llama-3.1-8B-Instruct` | Model identifier sent to the API || `MAX_CONCURRENT_ENVS` | `64` | Maximum parallel WebSocket sessions || `ENABLE_WEB_INTERFACE` | `true` | Mount Gradio UI at `/web` || `ENV_BASE_URL` | `http://localhost:8000` | PreferenceLab server URL (for remote clients) || `ENV_README_PATH` | _(none)_ | Custom path to README for web interface |
---
### Docker Deployment## API Reference
**Build:**```bashdocker build -t preference-lab .```### REST Endpoints
**Run locally:**```bashdocker run -p 8000:8000 \ -e HF_TOKEN=$HF_TOKEN \ -e API_BASE_URL=https://api-inference.huggingface.co/v1 \ -e MODEL_NAME=meta-llama/Llama-3.1-8B-Instruct \ preference-lab```| Method | Path | Description ||---|---|---|| `GET` | `/health` | Server health check || `GET` | `/schema` | Action + Observation JSON schemas || `GET` | `/state` | Current episode state || `POST` | `/reset` | Start a new episode || `POST` | `/step` | Submit an action, receive observation || `GET` | `/web` | Gradio interactive playground || `GET` | `/manifest.json` | PWA web manifest |
**Health check endpoint:**```GET http://localhost:8000/health### POST /reset
```json{ "seed": 42, "task_type": "pairwise"}```
The container automatically polls `/health` every 30 seconds and restarts on failure.`task_type` accepts: `"pairwise"` | `"likert"` | `"consistency"` | omit for random.
---### POST /step
## How the Project Runs```json{ "action": { "choice": "A" }}```
The startup sequence follows this order:### Response (all step/reset endpoints)
```1. Docker / uvicorn starts βββΊ uvicorn server.app:app --host 0.0.0.0 --port 8000
2. 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 initialized
3. 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 Observation
4. 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```json{ "observation": { "task_id": "abc123_step1", "task_type": "pairwise", "prompt": "Explain backpropagation.", "response_a": "...", "response_b": "...", "reward": 1.0, "done": false, "step_count": 1, "info": { "verdict": "correct", "gold_label": "A" } }, "reward": 1.0, "done": false}```
**Local inference run (`python inference.py`):**### WebSocket
```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)ws://localhost:8000/ws```
OpenEnv WebSocket protocol β send `reset`, `step`, `state`, `close` messages. Used by TRL training loops via `MCPToolClient`.
---
## Integration Guide
### Using with TRL / GRPO Training### Direct Import (Local)
```pythonfrom preference_lab import PreferenceLabEnv, PairwiseAction
class PreferenceEnvWrapper: """OpenEnv wrapper compatible with TRL's GRPO trainer."""from server.environment import PreferenceLabEnvironmentfrom models import PairwiseAction, LikertAction, ConsistencyAction
def __init__(self, base_url: str = "https://your-space.hf.space"): self.client = PreferenceLabEnv(base_url=base_url) self.reward = 0.0env = PreferenceLabEnvironment()
def reset(self, **kwargs) -> str: """Reset environment and return the prompt string.""" obs = self.client.reset() return obs.prompt# Pairwise taskobs = env.reset(seed=42, task_type="pairwise")print(obs.prompt)
def rank_responses(self, choice: str) -> str: """ Annotate which response is better.obs = env.step(PairwiseAction(choice="A"))print(obs.reward, obs.done)
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.reward return f"Reward: {result.reward:.2f}"# State (property, not method)state = env.stateprint(state.episode_id, state.step_count)```
### Using with TRL / GRPO Training
def reward_func(environments, **kwargs) -> list[float]: """Reward function for TRL GRPO β returns reward per environment.""" return [env.reward for env in environments]``````pythonimport asynciofrom openenv.core.env_client import EnvClientfrom models import PairwiseAction
---async def train(): async with EnvClient("http://localhost:8000") as env: obs = await env.reset(task_type="pairwise")
### Client API Reference for step in range(5): # Your policy predicts the action action = PairwiseAction(choice=your_policy(obs)) obs = await env.step(action) reward = obs.reward done = obs.done
The `PreferenceLabEnv` client extends `MCPToolClient` and supports both sync and async usage: train_on(obs, reward) if done: break
**Async (recommended for training loops):**```pythonfrom preference_lab import PreferenceLabEnv, LikertAction
async 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}")asyncio.run(train())```
**Sync (for simpler scripts):**### MultiEnv Wrapper (Parallel Sessions)
```pythonfrom preference_lab import PreferenceLabEnv, ConsistencyActionfrom openenv.core.env_client import MultiEnvClient
with 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"])# Spin up 8 parallel sessions on the same serverasync with MultiEnvClient("http://localhost:8000", n=8) as envs: observations = await envs.reset_all(task_type="pairwise") # envs.step_all(actions) β list of observations```
---
## Testing
The full test suite covers grader correctness, environment integration, and edge cases:
```bash# Run all tests# Full test suitepytest tests/ -v
# Run a specific test classpytest tests/test_environment.py::TestPairwiseGrader -v# Specific test classpytest tests/test_environment.py::TestPreferenceLabGraders -vpytest tests/test_environment.py::TestEpisodeManagement -v
# Run with coveragepytest tests/ -v --cov=. --cov-report=term-missing# Quick smoke test (direct import, no server needed)python test_api.py```
| 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 |**Test coverage:**- β
`reset()` with seed, task_type, episode_id- β
`step()` for all 3 task types- β
`state` property returns correct `State` object- β
Grader reward ranges `[0.0, 1.0]`- β
Episode terminates after `MAX_STEPS_PER_EPISODE`- β
Reproducible outputs across identical seeds- β
Rewards vary across actions (anti-constant guard)- β
Concurrent session isolation
---
## Team
**Team Nexis** β Sri Sri University Γ Zaalima Development Pvt. Ltd.## Deployment
| Member | Role ||---|---|| **Sibam Nanda** | Architecture + Core Environment || **Spandan Kar** | Backend + Deployment || **Shayanna Behera** | Config + Documentation |
---### Docker (Local)
## License```bashdocker build -t preferencelab .
docker run -p 8000:8000 \ -e HF_TOKEN=hf_your_token \ -e MODEL_NAME=meta-llama/Llama-3.1-8B-Instruct \ -e MAX_CONCURRENT_ENVS=64 \ preferencelab```BSD 3-Clause License
Copyright (c) 2024, Team NexisSri Sri University Γ Zaalima Development Pvt. Ltd.Visit `http://localhost:8000/web`
Redistribution and use in source and binary forms, with or withoutmodification, are permitted provided that the following conditions are met:### Hugging Face Spaces
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.1. Fork or push this repository to a Hugging Face Space with **Docker SDK**2. Add the following secrets in Space Settings: - `HF_TOKEN` β your Hugging Face token - `API_BASE_URL` β inference endpoint (e.g. `https://api-inference.huggingface.co/v1`) - `MODEL_NAME` β model to use
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.The `Dockerfile` handles everything else. Health check polls `/health` every 30 seconds.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without 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.```## License
This project is licensed under the **MIT License** β see [LICENSE](LICENSE) for details.
---
<div align="center">
**PreferenceLab** Β· Built with β€οΈ for the Meta Γ Hugging Face OpenEnv Hackathon**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)*Team Nexis*
</div>README.md+475-828