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 lines21222324252627289 unmodified lines383940414243444546474849505152535455565758596061626364656667686970717273744 unmodified lines798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106020 unmodified lines[](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**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)- [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---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 || 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### ποΈ Component Architecture```mermaidflowchart TBsubgraph 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"]endsubgraph Server["FastAPI Server β server/app.py"]EP1["/reset POST"]EP2["/step POST"]EP3["/state GET"]EP4["/health GET"]EP5["/web Gradio"]EP6["/manifest.json"]endsubgraph 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"]endsubgraph 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"]endsubgraph 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"]endsubgraph Models["Pydantic Models β models.py"]M1["PairwiseAction / Observation"]M2["LikertAction / Observation"]M3["ConsistencyAction / Observation"]endsubgraph External["External Services"]LLM["HF Inference API<br/>meta-llama/Llama-3.1-8B"]endA1 -- "HTTP / WebSocket" --> ServerA2 -- "Direct import" --> EnvironmentA3 -- "Browser" --> EP5A4 --> ServerEP1 --> RESETEP2 --> STEPEP3 --> STATEEP5 --> RESETEP5 --> STEPRESET --> GradersSTEP --> GradersGraders --> G1Graders --> G2Graders --> G3Environment --> DataLayerD1 -.->|fallback| D4D2 -.->|fallback| D4D3 -.->|fallback| D4Models --> G1Models --> G2Models --> G3A2 -- "OpenAI client" --> LLMclassDef client fill:#1e3a5f,stroke:#4a90d9,color:#e8f4fd,stroke-width:2pxclassDef grader fill:#3a2a1a,stroke:#ff9800,color:#fff3e0,stroke-width:2pxclassDef data fill:#2a1a3a,stroke:#9c27b0,color:#f3e5f5,stroke-width:2pxclassDef model fill:#1a2a3a,stroke:#2196f3,color:#e3f2fd,stroke-width:2pxclassDef external fill:#3a1a1a,stroke:#f44336,color:#ffebee,stroke-width:2pxclassDef endpoint fill:#263238,stroke:#607d8b,color:#eceff1,stroke-width:1pxclass A1,A2,A3,A4 clientclass G1,G2,G3 graderclass D1,D2,D3,D4 dataclass M1,M2,M3 modelclass LLM externalclass EP1,EP2,EP3,EP4,EP5,EP6 endpoint```---### βοΈ Deployment Architecture```mermaidflowchart LRsubgraph Dev["Developer Machine"]CODE["Source Code<br/>preference-lab/"]GIT["git push"]CODE --> GITendsubgraph 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 --> UVICORNUVICORN --> WEBUVICORN --> RESTUVICORN --> HEALTHSECRETS -.->|env vars| CONTAINERHFSpace --> PUBURLendsubgraph LLMBackend["HF Inference API"]MODEL["meta-llama/Llama-3.1-8B-Instruct"]endsubgraph Consumers["Consumers"]U1["TRL / GRPO<br/>Training Loop"]U2["Developer<br/>Browser"]U3["inference.py<br/>Baseline Script"]U4["MCPToolClient<br/>PreferenceLabEnv"]endGIT --> HFSpaceU1 -- "WebSocket / OpenEnv" --> RESTU2 -- "HTTPS" --> WEBU3 -- "Direct import" --> UVICORNU4 -- "HTTP / MCP" --> RESTREST -- "OpenAI client<br/>API_BASE_URL + HF_TOKEN" --> MODELclassDef hf fill:#ff6b00,stroke:#ff9800,color:#fff,stroke-width:2pxclassDef docker fill:#0db7ed,stroke:#066da5,color:#fff,stroke-width:2pxclassDef consumer fill:#1e3a5f,stroke:#4a90d9,color:#e8f4fd,stroke-width:2pxclassDef llm fill:#4a235a,stroke:#9c27b0,color:#f3e5f5,stroke-width:2pxclassDef secret fill:#3a1a1a,stroke:#f44336,color:#ffebee,stroke-width:2pxclassDef dev fill:#1a3a2a,stroke:#4caf50,color:#e8f5e9,stroke-width:2pxclass PUBURL,HFSpace hfclass CONTAINER,UVICORN dockerclass U1,U2,U3,U4 consumerclass MODEL,LLMBackend llmclass SECRETS secretclass CODE,GIT dev```---subgraph HF["βοΈ Hugging Face Space Β· Docker Container"]direction TBsubgraph SERVER["β‘ FastAPI Server Β· server/app.py"]direction LREP1["/reset\nPOST"]EP2["/step\nPOST"]EP3["/state\nGET"]EP4["/health\nGET"]EP5["/web\nGradio UI"]EP6["/manifest.json\nPWA"]endsubgraph ENV["π¬ PreferenceLabEnvironment Β· server/environment.py"]direction TBRESET["reset()\nSeed Β· TaskType Β· EpisodeID"]STEP["step()\nGrade β Reward β Next Sample"]STATE["state @property\nState object Β· metadata"]subgraph GRADERS["βοΈ Deterministic Graders"]direction LRG1["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"]endendsubgraph DATA["ποΈ Data Layer Β· data/"]direction LRD1["pairwise_data.json\nHH-RLHF"]D2["likert_data.json\nUltraFeedback"]D3["consistency_data.json\nStanford SHP"]D4["π Synthetic\nFallback\n(built-in)"]endsubgraph MODELS["π Pydantic Models Β· models.py"]direction LRM1["PairwiseAction\nPairwiseObservation"]M2["LikertAction\nLikertObservation"]M3["ConsistencyAction\nConsistencyObservation"]endendsubgraph EXTERNAL["π External Services"]LLM["π€ HF Inference API\nmeta-llama/Llama-3.1-8B"]end%% Client β ServerA1 -- "HTTP / WebSocket\nOpenEnv Protocol" --> SERVERA2 -- "Direct import\n(local)" --> ENVA3 -- "Browser\nGradio" --> EP5A4 -- "REST / WS" --> SERVER%% Server β EnvironmentEP1 --> RESETEP2 --> STEPEP3 --> STATEEP5 --> RESETEP5 --> STEP%% Environment internalsRESET --> GRADERSSTEP --> GRADERSGRADERS --> G1GRADERS --> G2GRADERS --> G3%% Data loadingENV --> DATAD1 -.->|fallback| D4D2 -.->|fallback| D4D3 -.->|fallback| D4%% ModelsMODELS --> G1MODELS --> G2MODELS --> G3%% ExternalA2 -- "OpenAI client\nAPI_BASE_URL" --> LLM%% StylingclassDef client fill:#1e3a5f,stroke:#4a90d9,color:#e8f4fd,stroke-width:2pxclassDef server fill:#1a3a2a,stroke:#4caf50,color:#e8f5e9,stroke-width:2pxclassDef grader fill:#3a2a1a,stroke:#ff9800,color:#fff3e0,stroke-width:2pxclassDef data fill:#2a1a3a,stroke:#9c27b0,color:#f3e5f5,stroke-width:2pxclassDef model fill:#1a2a3a,stroke:#2196f3,color:#e3f2fd,stroke-width:2pxclassDef external fill:#3a1a1a,stroke:#f44336,color:#ffebee,stroke-width:2pxclassDef endpoint fill:#263238,stroke:#607d8b,color:#eceff1,stroke-width:1pxclass A1,A2,A3,A4 clientclass G1,G2,G3 graderclass D1,D2,D3,D4 dataclass M1,M2,M3 modelclass LLM externalclass EP1,EP2,EP3,EP4,EP5,EP6 endpoint```---### π Request Lifecycle β Data Flow```mermaidsequenceDiagramautonumberactor Agent as π€ AI Agent / TRLparticipant API as β‘ FastAPI Serverparticipant Env as π¬ PreferenceLabEnvironmentparticipant Grader as βοΈ Graderparticipant DB as ποΈ DatasetNote 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 JSONNote over Agent,DB: ββ Step Loop (max 5 steps) βββββββββββββββββββββββββββloop For each annotation stepAgent ->> 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_labelGrader -->> Env: reward=1.0, info={ verdict: "correct" }Env ->> DB: _sample_example(rng) Β· next exampleDB -->> Env: next exampleEnv -->> API: Observation { reward=1.0, done=false, step_count=N }API -->> Agent: 200 OK Β· StepResult JSONAgent ->> Agent: log_step Β· accumulate rewardendNote over Agent,DB: ββ Episode End βββββββββββββββββββββββββββββββββββββββEnv -->> API: Observation { done=true, step_count=5 }API -->> Agent: 200 OK Β· Final ObservationAgent ->> Agent: log_end( score, rewards )Agent ->> API: POST /reset Β· start new episode```---### π§ User Flow```mermaidflowchart TDSTART(["π 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"]endsubgraph 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"]endsubgraph 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"]endsubgraph 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"]endSTART --> S1 --> S2 --> S3S3 -->|Yes| S4 --> S6S3 -->|No| S5 --> S6S6 --> D1D1 -->|Local| D2D1 -->|Docker| D3D1 -->|Cloud| D4D2 & D3 & D4 --> U1U1 -->|Baseline| U2U1 -->|Interactive| U3U1 -->|Custom| U4U1 -->|CI/CD| U5U1 -->|Training| U6U2 & U3 & U4 & U6 --> E1E1 --> E2E2 -->|pairwise| E3E2 -->|likert| E4E2 -->|consistency| E5E3 & E4 & E5 --> E6 --> E7 --> E8E8 -->|No| E9 --> E6E8 -->|Yes| E10E10 -->|New Episode| E1E10 -->|Done| FINISH(["β Complete"])%% StylingclassDef phase fill:#0d1b2a,stroke:#4a90d9,color:#e8f4fd,stroke-width:2px,rx:8classDef decision fill:#1a1a2e,stroke:#e94560,color:#f5f5f5,stroke-width:2pxclassDef task1 fill:#1a3a2a,stroke:#4caf50,color:#e8f5e9,stroke-width:2pxclassDef task2 fill:#3a2a1a,stroke:#ff9800,color:#fff3e0,stroke-width:2pxclassDef task3 fill:#2a1a3a,stroke:#9c27b0,color:#f3e5f5,stroke-width:2pxclassDef terminal fill:#1b2838,stroke:#66c0f4,color:#c6d4df,stroke-width:3px,rx:20class S1,S2,S4,S5,S6 phaseclass D2,D3,D4 phaseclass U2,U3,U4,U5,U6 phaseclass E1,E6,E7,E9,E10 phaseclass S3,D1,U1,E2,E8 decisionclass E3 task1class E4 task2class E5 task3class START,FINISH terminal```---### βοΈ Deployment Architecture```mermaidflowchart LRsubgraph DEV["π» Developer Machine"]direction TBCODE["π preference-lab/\nSource Code"]GIT["git push"]endsubgraph HF["βοΈ Hugging Face Platform"]direction TBsubgraph SPACE["π€ HF Space Β· Docker SDK"]direction TBsubgraph DOCKER["π³ Docker Container\npython:3.10-slim"]direction TBUVIG["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"]endUVIG --> APPendENVVARS["π Secrets\nHF_TOKEN\nAPI_BASE_URL\nMODEL_NAME\nMAX_CONCURRENT_ENVS=64"]ENVVARS -.->|injected| DOCKERendPUBURL["π Public URL\nhttps://username-preference-lab.hf.space"]SPACE --> PUBURLendsubgraph LLMAPI["π€ HF Inference API"]MODEL["meta-llama/\nLlama-3.1-8B-Instruct"]endsubgraph USERS["π₯ Consumers"]direction TBU1["π€ TRL / GRPO\nTraining Loop"]U2["π§βπ» Developer\nBrowser Β· /web"]U3["β‘ inference.py\nBaseline script"]U4["π MCPToolClient\nPreferenceLabEnv"]endCODE --> GIT --> SPACEU1 -- "WebSocket\nOpenEnv" --> RESTU2 -- "HTTPS" --> WEBU3 -- "Direct\nimport" --> APPU4 -- "HTTP\nMCPToolClient" --> RESTAPP -- "OpenAI client\nAPI_BASE_URL + HF_TOKEN" --> MODELclassDef hf fill:#ff6b00,stroke:#ff9800,color:#fff,stroke-width:2pxclassDef docker fill:#0db7ed,stroke:#066da5,color:#fff,stroke-width:2pxclassDef user fill:#1e3a5f,stroke:#4a90d9,color:#e8f4fd,stroke-width:2pxclassDef api fill:#4a235a,stroke:#9c27b0,color:#f3e5f5,stroke-width:2pxclassDef secret fill:#3a1a1a,stroke:#f44336,color:#ffebee,stroke-width:2pxclass SPACE,PUBURL hfclass DOCKER,UVIG dockerclass U1,U2,U3,U4 userclass MODEL,LLMAPI apiclass ENVVARS secret```---## File Architecture```mermaidgraph TDsubgraph Root["preference-lab/"]direction TBsubgraph Config["Configuration Files"]direction LRPY[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]endsubgraph Core["Core Modules"]direction LRINIT[__init__.py<br/>Package exports]MOD[models.py<br/>Pydantic schemas]CLI[client.py<br/>OpenEnv client wrapper]INF[inference.py<br/>Baseline inference]endsubgraph Server["server/ - FastAPI Backend"]direction TBSINIT[__init__.py]SAPP[app.py<br/>App factory & endpoints]SENV[environment.py<br/>Core environment logic<br/>Graders & data loading]endsubgraph Data["data/ - Datasets"]direction TBDINIT[.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]endsubgraph Scripts["scripts/ - Utilities"]direction LRSCINIT[__init__.py]PREP[prepare_datasets.py<br/>Dataset preparation]endsubgraph Tests["tests/ - Test Suite"]direction LRTINIT[__init__.py]TENV[test_environment.py<br/>Environment tests]endsubgraph Standalone["Standalone Files"]direction LRTAPI[test_api.py<br/>API integration tests]endendclassDef config fill:#e3f2fd,stroke:#2196f3,color:#0d47a1classDef core fill:#f3e5f5,stroke:#9c27b0,color:#4a148cclassDef server fill:#e8f5e9,stroke:#4caf50,color:#1b5e20classDef data fill:#fff3e0,stroke:#ff9800,color:#e65100classDef scripts fill:#fce4ec,stroke:#e91e63,color:#880e4fclassDef tests fill:#f1f8e9,stroke:#8bc34a,color:#2e7d32classDef standalone fill:#e0f2f1,stroke:#009688,color:#004d40class PY,REQ,OPEN,DOCK,DOCKI,GITI configclass INIT,MOD,CLI,INF coreclass SINIT,SAPP,SENV serverclass DINIT,DREAD,PAIR,LIK,CONS dataclass SCINIT,PREP scriptsclass TINIT,TENV testsclass TAPI standalone``````---## 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)```**Action:**```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 \-e MODEL_NAME=meta-llama/Llama-3.1-8B-Instruct \preference-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 |---## Team**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>20 unmodified lines2122232425262728299 unmodified lines3940414243444546474849505152535455565758596061626364656667686970717273744 unmodified lines79808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670720 unmodified lines[](https://www.python.org/)[](https://fastapi.tiangolo.com/)[](https://docs.pydantic.dev/)[](https://gradio.app/)[](https://www.docker.com/)[](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](#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)- [Environment Variables](#environment-variables)- [API Reference](#api-reference)- [Integration Guide](#integration-guide)- [Testing](#testing)- [Deployment](#deployment)- [License](#license)---## Overview**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:| 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 β 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 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```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 suite25 test cases covering:reset / step / state / gradersconcurrent sessions / reproducibility```---## Task DesignPreferenceLab presents agents with three progressively harder annotation tasks, matching real RLHF data collection workflows.### Task 1 β Pairwise Ranking (Easy)The agent is shown a prompt and two LLM responses (A and B), and must pick the better one.**Observation fields:** `prompt`, `response_a`, `response_b`**Action:**```pythonPairwiseAction(choice="A", # "A" | "B" | "tie" | "skip"justification="..." # optional, not used for grading)```**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 is shown a prompt and a single LLM response, and must score it on four independent quality axes.**Observation fields:** `prompt`, `response`, `rubric`**Action:**```pythonLikertAction(helpfulness=4, # 1β5honesty=5, # 1β5harmlessness=5, # 1β5instruction_following=4 # 1β5)```**Grading (vs UltraFeedback gold scores):**```reward = 1.0 β (MAE / 4.0)where MAE = mean absolute error across all 4 axes4.0 = maximum possible error per axisPerfect 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 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 fields:** `prompt`, `response_a`, `response_b`, `response_c`, `response_d`**Action:**```pythonConsistencyAction(ranking=["B", "A", "D", "C"] # best β worst, all 4 required)```**Grading (Kendall-Ο + Transitivity bonus):**```reward = Ξ± Γ kendall_tau + Ξ² Γ transitivity_scorekendall_tau: normalized rank correlation vs gold rankingrange [β1.0, +1.0], clipped to [0, 1]transitivity_score: fraction of (A>B, B>C β A>C) triplets satisfiedpenalizes logically inconsistent rankingsΞ± = 0.7, Ξ² = 0.3 (weighted combination)```---## Reward Functions| Task | Formula | Range ||---|---|---|| 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]` |All rewards are bounded `[0, 1]` and emitted at **every step** (dense signal).---## Datasets| 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 |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```bash# 1. Clonegit clone https://github.com/SIBAM890/preferencelab.gitcd preference-lab# 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```Open **http://localhost:8000/web** for the interactive Gradio playground.### Verify the server is running```bashcurl http://localhost:8000/health# β {"status":"healthy"}curl http://localhost:8000/schema# β full action / observation JSON schema```### Run the baseline inference script```bash# 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-Instructpython inference.py```Expected 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```bashpytest tests/ -v# 25 test cases β reset, step, state, graders, concurrency, reproducibility```---## Environment Variables| 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 |---## API Reference### REST Endpoints| 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 |### POST /reset```json{"seed": 42,"task_type": "pairwise"}````task_type` accepts: `"pairwise"` | `"likert"` | `"consistency"` | omit for random.### POST /step```json{"action": {"choice": "A"}}```### Response (all step/reset endpoints)```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}```### WebSocket```ws://localhost:8000/ws```OpenEnv WebSocket protocol β send `reset`, `step`, `state`, `close` messages. Used by TRL training loops via `MCPToolClient`.---## Integration Guide### Direct Import (Local)```pythonfrom server.environment import PreferenceLabEnvironmentfrom models import PairwiseAction, LikertAction, ConsistencyActionenv = PreferenceLabEnvironment()# Pairwise taskobs = env.reset(seed=42, task_type="pairwise")print(obs.prompt)obs = env.step(PairwiseAction(choice="A"))print(obs.reward, obs.done)# State (property, not method)state = env.stateprint(state.episode_id, state.step_count)```### Using with TRL / GRPO Training```pythonimport asynciofrom openenv.core.env_client import EnvClientfrom models import PairwiseActionasync def train():async with EnvClient("http://localhost:8000") as env:obs = await env.reset(task_type="pairwise")for step in range(5):# Your policy predicts the actionaction = PairwiseAction(choice=your_policy(obs))obs = await env.step(action)reward = obs.rewarddone = obs.donetrain_on(obs, reward)if done:breakasyncio.run(train())```### MultiEnv Wrapper (Parallel Sessions)```pythonfrom openenv.core.env_client import MultiEnvClient# 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```bash# Full test suitepytest tests/ -v# Specific test classpytest tests/test_environment.py::TestPreferenceLabGraders -vpytest tests/test_environment.py::TestEpisodeManagement -v# Quick smoke test (direct import, no server needed)python test_api.py```**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---## Deployment### Docker (Local)```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```Visit `http://localhost:8000/web`### Hugging Face Spaces1. 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 useThe `Dockerfile` handles everything else. Health check polls `/health` every 30 seconds.---## LicenseThis project is licensed under the **MIT License** β see [LICENSE](LICENSE) for details.---<div align="center">**Built with β€οΈ for the Meta Γ Hugging Face OpenEnv Hackathon***Team Nexis*</div>
README.md+475-828