Spaces:
Running
Running
Commit ยท
117e6b5
1
Parent(s): dfcc2fe
Update checkout to v4 and add token validation check
Browse filesFiles changed (5)
7 unmodified lines891011121314151 unmodified line17181920217 unmodified linesjobs:sync-to-hub:runs-on: ubuntu-lateststeps:- uses: actions/checkout@v3with:fetch-depth: 0lfs: true1 unmodified lineenv:HF_TOKEN: ${{ secrets.HF_TOKEN }}run: |# Make sure to replace "SnippyCodes/Libratio" with your actual HF Space ID if it's different!git push -f https://SnippyCodes:$HF_TOKEN@huggingface.co/spaces/SnippyCodes/Libratio main7 unmodified lines8910111213141516171 unmodified line1920212223242526277 unmodified linesjobs:sync-to-hub:runs-on: ubuntu-latestenv:FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: truesteps:- uses: actions/checkout@v4with:fetch-depth: 0lfs: true1 unmodified lineenv:HF_TOKEN: ${{ secrets.HF_TOKEN }}run: |if [ -z "$HF_TOKEN" ]; thenecho "Error: HF_TOKEN is empty! Make sure you added it exactly as 'HF_TOKEN' in Settings > Secrets and variables > Actions"exit 1figit remote add space https://SnippyCodes:$HF_TOKEN@huggingface.co/spaces/SnippyCodes/Libratiogit push -f space main
21 unmodified lines2223242526272821 unmodified lines# --- Virtual environments ---venv/.venv/env/ENV/# --- IDE ---21 unmodified lines2223242526272821 unmodified lines# --- Virtual environments ---venv/.venv/.env/ENV/# --- IDE ---
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687# Mixed Precision Training Environment## Description and MotivationThe Mixed Precision Training Environment is a specialized reinforcement learning simulation designed for the Meta x Scalar Hackathon using the OpenEnv spec.**Motivation:** Training large language models (like Meta's LLaMA 3) at scale is incredibly resource-intensive. Machine Learning Engineers manually configure precision formats (FP32, FP16, BF16, FP8) for different neural network layers to speed up training and reduce memory overhead. However, assigning low precision to the wrong layer (e.g., embedding or normalization) causes catastrophic underflow, resulting in NaN loss and millions of dollars in wasted compute.This environment simulates this exact, high-stakes infrastructure optimization task, providing an agentic testing ground for AI to learn safe and Pareto-optimal mixed-precision configurations.---## Action and Observation SpacesThe environment utilizes heavily-typed Pydantic schemas (viewable in `app/models.py`) to parse agent outputs directly from text.### Observation SpaceObservations include structured contextual data based on the task:- **Task 1:** `model_architecture` (list of layer dicts detailing `gradient_sensitivity` and `activation_range`).- **Task 2:** `training_loss_trajectory` (a time-series array of loss values, including possible `NaN` entries) and the `current_config`.- **Task 3:** `constraints` (hard limits on `memory_budget_gb` and `time_budget_days`) and base `model_specs`.### Action SpaceActions represent the engineering decisions made by the agent:- **Task 1:** `precision_config` (Key-value pairs mapping layer names to their assigned precision format: `FP32`, `FP16`, `BF16`, or `FP8`).- **Task 2:** `instability_detected` (boolean), `step_detected` (integer), and `likely_cause` (string classification).- **Task 3:** `precision_strategy` (proposed tradeoff) and `predicted_metrics` (numeric efficiency predictions).---## Tasks & Expected Difficulty### Task 1: Static Precision Assignment- **Difficulty:** **Easy**- **Description:** The agent is given a model architecture definition. It must assign a precision format to each layer type. The agent must realize that `Embedding` and `Output` layers require FP32 for stability, `LayerNorm/Attention` can use BF16, while `FFN` can handle FP8.- **Grader:** Assigns normalized scores (0.0 - 1.0) based on stability. Any catastrophic failure assignment results in `0.0`. Valid assignments are scored by efficiency.### Task 2: Instability Detection (RCA)- **Difficulty:** **Medium**- **Description:** The agent is presented with a loss trajectory arrays containing normal descents or sudden divergences/NaNs. The agent must diagnose if the run crashed, exactly which step it crashed on, and infer the root precision cause.- **Grader:** Continuous scoring (0.0 - 1.0). Heavy penalties for false positives/negatives. Generous bonuses for detecting the failure early.### Task 3: Multi-Objective Optimization- **Difficulty:** **Hard**- **Description:** The agent is given hard limits on Time, Memory, and Accuracy thresholds. It must design a precision strategy that satisfies all three limits simultaneously.- **Grader:** Continuous scoring (0.0 - 1.0). Fails hard constraints = 0.0. Successes are graded on distance to the mathematical Pareto frontier.---## Setup and Usage Instructions### Docker Execution (Hugging Face Spaces Ready)1. Build the image:```bashdocker build -t mixed-precision-env .```2. Run the container:```bashdocker run -p 8000:8000 mixed-precision-env```3. The OpenEnv API is now live at `http://127.0.0.1:8000`.### Local Execution1. Create and activate a virtual environment:```bashpython -m venv venvsource venv/bin/activate # On Windows: .\venv\Scripts\activate```2. Install dependencies:```bashpip install -r requirements.txt```3. Start the server:```bashuvicorn app.main:app --host 127.0.0.1 --port 8000```---## Baseline ScoresThe environment includes a built-in OpenEnv baseline script (`inference.py`) evaluating standard agent capabilities dynamically.**Baseline Metrics (gpt-4-turbo proxy):**- **Task 1 Score:** `1.0` (Perfect stable assignment)- **Task 2 Score:** `1.0` (Correctly parsed and flagged NaN trajectories)- **Task 3 Score:** `1.0` (Achieved >95% proximity to Pareto optimal frontier)*Verified reproducible via automated validation tests.*123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283---title: Libratio โ Mixed Precision Training Envemoji: โ๏ธcolorFrom: bluecolorTo: indigosdk: dockerapp_port: 7860tags:- openenv- mixed-precision- reinforcement-learning- ml-engineering---# โ๏ธ Libratio โ Mixed Precision Training Environment> *Libratio (Latin): "the act of balancing"* โ the art of balancing precision, speed, and memory in modern AI training.A reinforcement learning environment simulating one of the highest-stakes decisions in large-scale AI infrastructure: **configuring floating-point precision formats (FP32, BF16, FP16, FP8) for neural network layers** during training.This is the exact problem Meta engineers face when training LLaMA at scale โ assign the wrong precision to the wrong layer and you waste millions of dollars in GPU compute, or worse, crash an entire training run with NaN losses.---## ๐ฏ MotivationTraining a 70B parameter model on H100 GPUs costs ~$1M+. Precision misconfiguration is one of the leading causes of:- **Training crashes** (NaN loss from FP8 on embedding layers)- **Wasted compute** (using FP32 everywhere when BF16 is safe)- **Memory overflows** (underestimating the memory footprint of your precision strategy)Libratio provides a structured RL environment where agents can learn, be evaluated, and improve at these decisions โ grounded in real empirical benchmarks from NVIDIA Transformer Engine and Meta's LLaMA-3 technical reports.---## ๐๏ธ Environment Architecture```POST /reset โ { task_id } โ Initial ObservationPOST /step โ { action } โ { observation, reward, done, info }POST /state โ {} โ Current StateGET /tasks โ {} โ Task Definitions```The environment follows the [OpenEnv](https://openenv.dev) specification with typed Pydantic models for all actions and observations.---## ๐ Observation & Action Spaces### Task 1: `precision_assignment` *(Easy)***Observation:**```json{"task_id": "precision_assignment","scenario_id": "llama3_70b","model_name": "LLaMA-3-70B","total_layers": 5,"current_layer_index": 2,"current_layer": {"name": "ffn_layer","layer_type": "ffn","num_params": 28000000000,"gradient_sensitivity": "low","activation_range": "bounded"},"assigned_so_far": { "embedding": "FP32", "attention": "BF16" },"available_precisions": ["FP32", "BF16", "FP16", "FP8"],"memory_budget_gb": 80.0,"memory_used_gb": 12.4,"speed_target_speedup": 2.0}```**Action:**```json{ "precision": "FP8", "reasoning": "FFN layers have bounded activations safe for FP8" }```---### Task 2: `instability_detection` *(Medium)***Observation:**```json{"task_id": "instability_detection","scenario_id": "fp8_embedding_crash","precision_config": { "embedding": "FP8", "attention": "BF16", "ffn": "FP8" },"total_training_steps": 100,"steps_revealed_so_far": 40,"loss_trajectory_window": [2.34, 2.18, 2.05, null, null, null],"window_index": 1,"windows_remaining": 3}```> `null` values represent `NaN` โ a training crash.**Action:**```json{"action_type": "flag_instability","analysis": "NaN values detected starting at step 23","flagged_step": 23,"root_cause": "fp8 embedding underflow causing gradient collapse"}```---### Task 3: `multi_objective_optimization` *(Hard)***Observation:**```json{"task_id": "multi_objective_optimization","scenario_id": "datacenter_gpu_cluster","constraints": {"memory_budget_gb": 35.0,"time_budget_days": 5.5,"accuracy_threshold": 0.95},"model_total_params": 12000000000,"iterations_remaining": 4,"best_score_so_far": 0.718,"previous_feedback": "Valid! Mem=27.5GB, Time=3.8d, Acc=0.991, Speedup=1.81x"}```**Action:**```json{"precision_strategy": {"embedding": "FP32","attention": "BF16","ffn": "FP8","layernorm": "BF16","output": "FP32"},"reasoning": "Baseline strategy satisfies all constraints with maximum FFN throughput"}```---## ๐ฎ Tasks & Difficulty| Task | Difficulty | Max Steps | Description ||---|---|---|---|| `precision_assignment` | **Easy** | 5 | Assign FP32/BF16/FP16/FP8 to each layer one at a time based on its gradient sensitivity and activation range || `instability_detection` | **Medium** | 5 | Progressively observe training loss windows, detect precision-induced crashes, identify root cause || `multi_objective_optimization` | **Hard** | 5 | Design a precision strategy satisfying memory, time, and accuracy constraints simultaneously; iteratively refine |### Reward Functions**Task 1 โ Per-step stability + efficiency score:**```FP32 on embedding โ 1.0 (IEEE 754 baseline, zero underflow risk)BF16 on attention โ 1.0 (Kalamkar2019: 1.85x throughput, stable)FP8 on ffn โ 1.0 (NVIDIA-TE 2023: 2.5x throughput, bounded activation)FP8 on embedding โ 0.0 (catastrophic: gradient underflow)```**Task 2 โ Timing + accuracy bonus:**- `continue_monitoring` on stable data โ `0.6` per step- Correct `flag_instability` โ `0.4` base + up to `0.3` for step accuracy + `0.3` for root cause match- False alarm โ `0.1` (heavy penalty)- Missed crash โ `0.1` (heavy penalty)**Task 3 โ Pareto frontier proximity:**```pythonscore = 0.5 + 0.2 * mem_efficiency + 0.15 * time_efficiency + 0.15 * accuracy_margin# 0.0 if any hard constraint is violated```Grounded in H100 cloud pricing + LLaMA-3 FLOPs data.---## โ๏ธ Setup & Usage### Option A: Docker (Recommended)```bashdocker build -t libratio .docker run -p 7860:7860 libratio# API available at http://localhost:7860```### Option B: Local Python```bashpython -m venv .venv# Windows: .venv\Scripts\activate# Linux/Mac: source .venv/bin/activatepip install -r requirements.txtuvicorn app.main:app --host 0.0.0.0 --port 7860```### Running the Baseline Inference Agent```bash# Required environment variablesexport API_BASE_URL="https://api.groq.com/openai/v1" # or any OpenAI-compatible endpointexport MODEL_NAME="llama-3.1-8b-instant"export HF_TOKEN="your_api_key_here"python inference.py```To run a single task:```bashexport TASK_ID="precision_assignment" # or instability_detection / multi_objective_optimizationpython inference.py```---## ๐ Baseline ScoresEvaluated using `llama-3.1-8b-instant` via Groq API (OpenAI-compatible):| Task | Baseline Score | Expected Range | Notes ||---|---|---|---|| `precision_assignment` | **1.000** | 0.91 โ 1.00 | Perfect โ model knows FP32/BF16/FP8 rules || `instability_detection` | **0.680** | 0.60 โ 0.85 | Scenario-dependent; improves with larger models || `multi_objective_optimization` | **0.718** | 0.65 โ 0.85 | Scenario-dependent; constrained by physics ceiling |> Scores vary slightly between runs due to random scenario selection. The physics model ensures graders are deterministic given the same scenario.---## ๐ฌ Physics Model SourcesAll rewards are grounded in published empirical benchmarks:| Claim | Source ||---|---|| BF16 attention โ 1.85x speedup | Kalamkar et al. (2019), *BFloat16 for Deep Learning* || FP8 FFN โ 2.5x speedup | NVIDIA Transformer Engine (2023) || FP8 embedding โ NaN crash | IEEE 754 analysis, confirmed in LLaMA-3 training logs || H100 cost model | AWS/GCP H100 cloud pricing (2024) || LLaMA-3 FLOPs estimate | Meta AI (2024), *LLaMA 3 Technical Report* |---## ๐๏ธ Project Structure```Libratio/โโโ app/โ โโโ main.py # FastAPI app โ /reset, /step, /state, /tasksโ โโโ models.py # Pydantic typed request/response modelsโโโ environment/โ โโโ mixed_precision_env.py # Core state machine & gradersโ โโโ physics_model.py # Empirical benchmark constants & computationsโโโ scenarios/โ โโโ task1_scenarios.py # Layer architectures (LLaMA-3 7B/13B/70B)โ โโโ task2_scenarios.py # Loss trajectories (stable/unstable/spike)โ โโโ task3_scenarios.py # Optimization scenarios (tight/balanced/generous)โโโ inference.py # Baseline LLM agent (OpenAI-compatible)โโโ openenv.yaml # OpenEnv spec metadata & task definitionsโโโ Dockerfile # Container for HF Spaces deploymentโโโ requirements.txtโโโ .env.example # Environment variable template```---## ๐ง Why This Problem MattersEvery frontier AI lab (Meta, Google DeepMind, Anthropic) runs into this problem at scale:- **GPT-4** training cost: estimated $100M+- **Precision misconfiguration**: can waste 10-40% of compute budget- **Manual tuning**: takes expert ML engineers days per modelAn agent that can reliably configure mixed precision could save **millions per training run** and is directly applicable to production ML infrastructure.---*Built for the Meta ร Scalar Hackathon 2026 | OpenEnv Specification*
19 unmodified lines20212223242526272833 unmodified lines62636465666719 unmodified linesclass MixedPrecisionEnvironment:TASK_DEFS = [{"task_id": "precision_assignment", "description": "Assign precision formats to model layers one at a time", "difficulty": "easy", "max_steps": 5},{"task_id": "instability_detection", "description": "Progressively analyze training loss to detect precision-induced instability", "difficulty": "medium", "max_steps": 5},{"task_id": "multi_objective_optimization", "description": "Iteratively optimize precision strategy under memory, time, and accuracy constraints", "difficulty": "hard", "max_steps": 5},]def __init__(self):33 unmodified linesdef state(self) -> Dict[str, Any]:return {"current_task": self.current_task,"current_scenario_id": self.scenario["scenario_id"] if self.scenario else None,"step_number": self.step_number,19 unmodified lines20212223242526272833 unmodified lines6263646566676819 unmodified linesclass MixedPrecisionEnvironment:TASK_DEFS = [{"id": "precision_assignment", "task_id": "precision_assignment", "description": "Assign precision formats to model layers one at a time", "difficulty": "easy", "max_steps": 5},{"id": "instability_detection", "task_id": "instability_detection", "description": "Progressively analyze training loss to detect precision-induced instability", "difficulty": "medium", "max_steps": 5},{"id": "multi_objective_optimization", "task_id": "multi_objective_optimization", "description": "Iteratively optimize precision strategy under memory, time, and accuracy constraints", "difficulty": "hard", "max_steps": 5},]def __init__(self):33 unmodified linesdef state(self) -> Dict[str, Any]:return {"task_id": self.current_task,"current_task": self.current_task,"current_scenario_id": self.scenario["scenario_id"] if self.scenario else None,"step_number": self.step_number,
9 unmodified lines10111213141516171819209 unmodified lines# Required environment variablesAPI_BASE_URL = os.environ.get("API_BASE_URL", "https://api.openai.com/v1")MODEL_NAME = os.environ.get("MODEL_NAME", "gpt-4o-mini")HF_TOKEN = os.environ.get("HF_TOKEN", "")ENV_URL = os.environ.get("ENV_URL", "http://localhost:7860")client = OpenAI(api_key=HF_TOKEN, base_url=API_BASE_URL)TASK_SYSTEM_PROMPTS = {"precision_assignment": """You are an expert ML infrastructure engineer configuring mixed-precision training.9 unmodified lines10111213141516171819209 unmodified lines# Required environment variablesAPI_BASE_URL = os.environ.get("API_BASE_URL", "https://api.openai.com/v1")MODEL_NAME = os.environ.get("MODEL_NAME", "gpt-4o-mini")API_KEY = os.environ.get("HF_TOKEN") or os.environ.get("OPENAI_API_KEY") or os.environ.get("API_KEY", "")ENV_URL = os.environ.get("ENV_URL", "http://localhost:7860")client = OpenAI(api_key=API_KEY, base_url=API_BASE_URL)TASK_SYSTEM_PROMPTS = {"precision_assignment": """You are an expert ML infrastructure engineer configuring mixed-precision training.
.github/workflows/sync_to_hf_space.yml+9-3
.gitignore+1-1
README.md+249-53
environment/mixed_precision_env.py+4-3
inference.py+2-2