Spaces:
Running
Running
Aaryan Parik commited on
Commit ·
0a7b128
1
Parent(s): 5655786
fix: harden HF Space Docker runtime, session isolation, hardware profiles, and tests
Browse filesFiles changed (33)
- .dockerignore+3-1
- .github/workflows/sync_to_hf_space.yml+7
- Dockerfile+12-2
- LICENSEAdded+21
- agent/adk_agent.py+113-106
- colab_qlora_grpo_fleet.py+10-6
- environment/aws_database.pyAdded+491
- environment/fleet_env.py+108-20
- environment/local_arm_engine.pyAdded+181
- environment/physics_model.py+119-43
- environment/thermal_kernel.pyDeleted-146
- fleet_inference.py+82-43
- frontend/main.js+9-2
- kernel_interface.py+28-11
- mongodb_metrics.py+15-16
- mongodb_streams.py+8-9
- mongodb_vector.py+19-7
- notebooks/qlora_grpo_training.pyDeleted-457
- predictive_agent.py+55-170
- pyproject.toml+12-3
- requirements-extras.txtAdded+10
- requirements-local.txtAdded+6
- requirements.txt+2-11
- scenarios/fleet_scenarios.py+66
- server/app.py+282-259
- server/models.py+12-121
- setup_arm_inference.mdAdded+71
- test_aws_database.pyAdded+138
- test_fleet.py+144-96
- test_hardware_profiles.pyAdded+132
- test_local_inference.pyAdded+75
- train_fleet.py+6-2
- vercel.jsonAdded+27
28 unmodified lines293031323334353628 unmodified lines*.code-workspacescratch/# Notebooksnotebooks/# OS cruft.DS_Store28 unmodified lines2930313233343536373828 unmodified lines*.code-workspacescratch/# Notebooks & static docs assets not needed at runtimenotebooks/images/test_*.py# OS cruft.DS_Store
14 unmodified lines15161718192014 unmodified lineswith:fetch-depth: 0lfs: true- name: Push to hubenv:HF_TOKEN: ${{ secrets.HF_TOKEN }}14 unmodified lines1516171819202122232425262714 unmodified lineswith:fetch-depth: 0lfs: true- uses: actions/setup-python@v5with:python-version: "3.12"- name: Run tests before deployingrun: |pip install -r requirements.txt pytest pytest-asynciopytest -q- name: Push to hubenv:HF_TOKEN: ${{ secrets.HF_TOKEN }}
123456789101112FROM python:3.12-slimWORKDIR /appCOPY requirements.txt .RUN pip install --no-cache-dir -r requirements.txtCOPY . .EXPOSE 7860CMD ["uvicorn", "server.app:app", "--host", "0.0.0.0", "--port", "7860"]12345678910111213141516171819202122FROM python:3.12-slimENV PYTHONDONTWRITEBYTECODE=1 \PYTHONUNBUFFERED=1RUN useradd -m -u 1000 userWORKDIR /appCOPY requirements.txt .RUN pip install --no-cache-dir -r requirements.txtCOPY --chown=user:user . .USER userEXPOSE 7860HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:7860/health', timeout=3)" || exit 1CMD ["uvicorn", "server.app:app", "--host", "0.0.0.0", "--port", "7860", "--workers", "1"]
123456789101112131415161718192021MIT License
Copyright (c) 2026 Libratio Fleet Contributors
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.22 unmodified lines2324252627282930313217 unmodified lines505152535455565758596061626364656667686981 unmodified lines15115215315415515615715815916016116216316416516616743 unmodified lines21121221321421521664 unmodified lines28128228328428528628728828929029129229351 unmodified lines34534634734834935035135235385 unmodified lines4394404414424434444454464474484494504512 unmodified lines45445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648710 unmodified lines49849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958022 unmodified lines"""import asyncioimport jsonimport osimport sysimport loggingfrom typing import Optionalfrom dotenv import load_dotenv17 unmodified lines# ── Config ──────────────────────────────────────────────────────────────────MONGO_URI = os.getenv("MONGO_URI", "")GEMINI_API_KEY = os.getenv("GEMINI_API_KEY", "")# Use Vertex AI if GCP project is configured, otherwise AI Studio (free)USE_VERTEX_AI = os.getenv("GOOGLE_GENAI_USE_VERTEXAI", "FALSE").upper() == "TRUE"if not USE_VERTEX_AI:# Unset Vertex AI env variables in Python to force the SDK to use the API keyos.environ.pop("GOOGLE_CLOUD_PROJECT", None)os.environ.pop("GOOGLE_CLOUD_LOCATION", None)print("AI Studio mode enabled (Vertex AI environment variables cleared)")# Model — Gemini 2.0 Flash is fast and free-tier friendlyADK_MODEL = os.getenv("ADK_MODEL", "gemini-2.0-flash")logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s")logger = logging.getLogger("libratio.adk")81 unmodified lines# Gemini can call these to interact with the physics-based RL environment.# ═══════════════════════════════════════════════════════════════════════════# Module-level fleet env instance (created lazily)_fleet_env_instance = Nonedef _fleet_env():global _fleet_env_instanceif _fleet_env_instance is None:sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))from environment.fleet_env import FleetEnvironment_fleet_env_instance = FleetEnvironment()return _fleet_env_instancedef reset_fleet_environment(task_id: str) -> dict:43 unmodified linesaction = json.loads(action_json)result = _fleet_env().step(action)score = max(0.01, min(0.99, float(result["reward"]["score"])))logger.info(f"[Tool] step_fleet_environment: score={score:.3f}")return {"success": True,64 unmodified lines# Gemini calls them exactly like MCP tools — same purpose, same data.# ═══════════════════════════════════════════════════════════════════════════def _get_mongo_db():"""Get a pymongo database connection (reuses existing MONGO_URI)."""try:import certififrom pymongo import MongoClientclient = MongoClient(MONGO_URI, tlsCAFile=certifi.where(), serverSelectionTimeoutMS=5000)return client["libratio"]except Exception as e:logger.warning(f"MongoDB connection failed: {e}")return None51 unmodified linestry:import json as _jsonfrom datetime import datetime, timezonedoc = {"task_id": task_id,"score": score,"action": _json.loads(action_json) if isinstance(action_json, str) else action_json,"reasoning": reasoning,"agent": "libratio_fleet_commander_adk",85 unmodified lineslogger.info(f" Model: {ADK_MODEL} | MongoDB: enabled | Physics: enabled")logger.info(f"{'='*60}")# ── Step 1: Build tools ──────────────────────────────────────────────# Try MCP first (ideal for hackathon), fallback to pymongo tools (always works)mongo_mcp = get_mongodb_mcp_toolset()physics_tools = get_fleet_physics_tools()mongo_fallback_tools = get_mongodb_fallback_tools()# Assemble: MCP toolset (if available) + pymongo fallback + physics toolsall_tools = physics_tools + mongo_fallback_toolsmongodb_mode = "pymongo (ADK FunctionTool)"if mongo_mcp:2 unmodified lineslogger.info(f"MongoDB mode: {mongodb_mode}")# ── Step 2: Create the ADK Agent ─────────────────────────────────────# This is the "Google Cloud Agent Builder" code-first integrationagent = Agent(model=ADK_MODEL, # Gemini 2.0 Flashname="libratio_fleet_commander",instruction=FLEET_AGENT_INSTRUCTION,tools=all_tools,)logger.info(f"Agent created: model={ADK_MODEL}, tools={len(all_tools)}")# ── Step 3: Create InMemoryRunner (ADK 2.2.0 simplified API) ─────────# InMemoryRunner bundles the agent + session service togetherrunner = InMemoryRunner(agent=agent,app_name="libratio_fleet",)# ── Step 4: Create a session ──────────────────────────────────────────session = await runner.session_service.create_session(app_name="libratio_fleet",user_id="fleet_commander",)session_id = session.idlogger.info(f"Session created: {session_id}")# ── Step 5: Build the task prompt ──────────────────────────────────────task_prompt = f"""Run a complete Libratio fleet task: {task_id}10 unmodified linesDatabase: libratio | Collections: trajectories (read), runs (write)"""# ── Step 6: Run the agent (with retry for rate limits) ──────────────mongo_tools_called = []physics_tools_called = []final_text = ""final_score = 0.0event_count = 0max_retries = 3for attempt in range(max_retries):try:async for event in runner.run_async(user_id="fleet_commander",session_id=session_id,new_message=genai_types.Content(role="user",parts=[genai_types.Part(text=task_prompt)],),):event_count += 1# Track tool calls for demo visibilityif hasattr(event, "content") and event.content:for part in event.content.parts:# Detect function calls (tool invocations)if hasattr(part, "function_call") and part.function_call:tool_name = part.function_call.namelogger.info(f" [Tool called] {tool_name}")# Categorize which type of tool was usedmongo_keywords = ["find", "aggregate", "insert", "collection", "mongo","vector_search", "count", "query_mongodb", "log_run"]physics_keywords = ["fleet", "precision", "physics", "reset", "step", "compute"]if any(kw in tool_name.lower() for kw in mongo_keywords):mongo_tools_called.append(tool_name)elif any(kw in tool_name.lower() for kw in physics_keywords):physics_tools_called.append(tool_name)else:physics_tools_called.append(tool_name)# Capture final text responseif hasattr(part, "text") and part.text:final_text += part.text# Detect final response eventif hasattr(event, "is_final_response") and callable(event.is_final_response):if event.is_final_response():logger.info(" [Final response received]")# If we got here, agent completed successfullybreakexcept Exception as e:error_msg = str(e)if "429" in error_msg or "RESOURCE_EXHAUSTED" in error_msg:wait_time = 35 * (attempt + 1) # 35s, 70s, 105slogger.warning(f" Rate limited (attempt {attempt+1}/{max_retries}). Waiting {wait_time}s...")await asyncio.sleep(wait_time)# Create a new session for retry (old one may be stale)session = await runner.session_service.create_session(app_name="libratio_fleet",user_id="fleet_commander",)session_id = session.idelse:logger.error(f"ADK agent run error: {e}")raise# Try to extract score from final textimport rescore_matches = re.findall(r'score[:\s=]+([0-9.]+)', final_text.lower())if score_matches:try:final_score = float(score_matches[-1])final_score = max(0.01, min(0.99, final_score))except ValueError:final_score = 0.5result = {"task_id": task_id,22 unmodified lines23242526272829303132333417 unmodified lines52535455565758596081 unmodified lines14214314414514614714814915015115215315415515615715815916016116216316416516643 unmodified lines21021121221321421521664 unmodified lines28128228328428528628728828929029129229329429529629729829930030130230330451 unmodified lines35635735835936036136236336436536636736885 unmodified lines4544554564574584594604614624634644654664674684692 unmodified lines47247347447547647747847948048148248348448548648748848949049149249349449510 unmodified lines50650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658722 unmodified lines"""import asyncioimport contextvarsimport jsonimport loggingimport osimport sysimport threadingfrom typing import Optionalfrom dotenv import load_dotenv17 unmodified lines# ── Config ──────────────────────────────────────────────────────────────────MONGO_URI = os.getenv("MONGO_URI", "")GEMINI_API_KEY = os.getenv("GEMINI_API_KEY", "")USE_VERTEX_AI = os.getenv("GOOGLE_GENAI_USE_VERTEXAI", "FALSE").upper() == "TRUE"ADK_MODEL = os.getenv("ADK_MODEL", "gemini-2.0-flash")logger = logging.getLogger("libratio.adk")81 unmodified lines# Gemini can call these to interact with the physics-based RL environment.# ═══════════════════════════════════════════════════════════════════════════_fleet_env_var: contextvars.ContextVar[Optional[object]] = contextvars.ContextVar("adk_fleet_env", default=None)_last_step_score_var: contextvars.ContextVar[Optional[float]] = contextvars.ContextVar("adk_last_step_score", default=None)_fallback_fleet_env = Nonedef _fleet_env():env = _fleet_env_var.get()if env is not None:return envglobal _fallback_fleet_envif _fallback_fleet_env is None:sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))from environment.fleet_env import FleetEnvironment_fallback_fleet_env = FleetEnvironment()return _fallback_fleet_envdef reset_fleet_environment(task_id: str) -> dict:43 unmodified linesaction = json.loads(action_json)result = _fleet_env().step(action)score = max(0.01, min(0.99, float(result["reward"]["score"])))_last_step_score_var.set(score)logger.info(f"[Tool] step_fleet_environment: score={score:.3f}")return {"success": True,64 unmodified lines# Gemini calls them exactly like MCP tools — same purpose, same data.# ═══════════════════════════════════════════════════════════════════════════_adk_mongo_client = None_adk_mongo_lock = threading.Lock()def _get_mongo_db():"""Get a shared pymongo database handle (reuses one MongoClient pool)."""global _adk_mongo_clientif not MONGO_URI:return Nonetry:import certififrom pymongo import MongoClientwith _adk_mongo_lock:if _adk_mongo_client is None:_adk_mongo_client = MongoClient(MONGO_URI, tlsCAFile=certifi.where(), serverSelectionTimeoutMS=5000)return _adk_mongo_client["libratio"]except Exception as e:logger.warning(f"MongoDB connection failed: {e}")return None51 unmodified linestry:import json as _jsonfrom datetime import datetime, timezonescore_val = float(score)doc = {"task_id": task_id,"model_name": ADK_MODEL,"model_id": ADK_MODEL,"score": score_val,"success": score_val >= 0.60,"action": _json.loads(action_json) if isinstance(action_json, str) else action_json,"reasoning": reasoning,"agent": "libratio_fleet_commander_adk",85 unmodified lineslogger.info(f" Model: {ADK_MODEL} | MongoDB: enabled | Physics: enabled")logger.info(f"{'='*60}")sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))from environment.fleet_env import FleetEnvironmentenv_token = _fleet_env_var.set(FleetEnvironment())score_token = _last_step_score_var.set(None)mongo_mcp = get_mongodb_mcp_toolset()physics_tools = get_fleet_physics_tools()mongo_fallback_tools = get_mongodb_fallback_tools()all_tools = physics_tools + mongo_fallback_toolsmongodb_mode = "pymongo (ADK FunctionTool)"if mongo_mcp:2 unmodified lineslogger.info(f"MongoDB mode: {mongodb_mode}")agent = Agent(model=ADK_MODEL,name="libratio_fleet_commander",instruction=FLEET_AGENT_INSTRUCTION,tools=all_tools,)runner = InMemoryRunner(agent=agent,app_name="libratio_fleet",)session = await runner.session_service.create_session(app_name="libratio_fleet",user_id="fleet_commander",)session_id = session.idtask_prompt = f"""Run a complete Libratio fleet task: {task_id}10 unmodified linesDatabase: libratio | Collections: trajectories (read), runs (write)"""mongo_tools_called = []physics_tools_called = []final_text = ""final_score = 0.0event_count = 0try:max_retries = 3for attempt in range(max_retries):try:async for event in runner.run_async(user_id="fleet_commander",session_id=session_id,new_message=genai_types.Content(role="user",parts=[genai_types.Part(text=task_prompt)],),):event_count += 1if hasattr(event, "content") and event.content:for part in event.content.parts:if hasattr(part, "function_call") and part.function_call:tool_name = part.function_call.namelogger.info(f" [Tool called] {tool_name}")mongo_keywords = ["find", "aggregate", "insert", "collection", "mongo","vector_search", "count", "query_mongodb", "log_run"]if any(kw in tool_name.lower() for kw in mongo_keywords):mongo_tools_called.append(tool_name)else:physics_tools_called.append(tool_name)if hasattr(part, "text") and part.text:final_text += part.textif hasattr(event, "is_final_response") and callable(event.is_final_response):if event.is_final_response():logger.info(" [Final response received]")breakexcept Exception as e:error_msg = str(e)if "429" in error_msg or "RESOURCE_EXHAUSTED" in error_msg:wait_time = 35 * (attempt + 1)logger.warning(f" Rate limited (attempt {attempt+1}/{max_retries}). Waiting {wait_time}s...")await asyncio.sleep(wait_time)session = await runner.session_service.create_session(app_name="libratio_fleet",user_id="fleet_commander",)session_id = session.idelse:logger.error(f"ADK agent run error: {e}")raiserecorded_score = _last_step_score_var.get()if recorded_score is not None:final_score = recorded_scoreelse:import rescore_matches = re.findall(r'score[:\s=]+([0-9]+(?:\.[0-9]+)?)', final_text.lower())if score_matches:try:final_score = max(0.01, min(0.99, float(score_matches[-1])))except ValueError:final_score = 0.01finally:if mongo_mcp is not None and hasattr(mongo_mcp, "close"):try:await mongo_mcp.close()except Exception:pass_fleet_env_var.reset(env_token)_last_step_score_var.reset(score_token)result = {"task_id": task_id,
374 unmodified lines375376377378379380381382383384385386374 unmodified linesprint(f"Merged model: {MERGED_DIR}")print("\nTo download, run in a new cell:")print(" from google.colab import files")print(" !zip -r fleet_model.zip ./results")print(" files.download('fleet_model.zip')")print(" files.download('<path-from-artifact_paths.reward_curve_png>')")print(" files.download('<path-from-artifact_paths.loss_curve_png>')")!zip -r fleet_adapter.zip results/qlora_grpo_fleet/ results/training_logs.jsonfrom google.colab import filesfiles.download('fleet_adapter.zip')374 unmodified lines375376377378379380381382383384385386387388389390374 unmodified linesprint(f"Merged model: {MERGED_DIR}")print("\nTo download, run in a new cell:")print(" from google.colab import files")print(" import shutil; shutil.make_archive('fleet_model', 'zip', './results')")print(" files.download('fleet_model.zip')")import shutilif os.path.exists("results/qlora_grpo_fleet"):shutil.make_archive("fleet_adapter", "zip", "results/qlora_grpo_fleet")try:from google.colab import filesif os.path.exists("fleet_adapter.zip"):files.download("fleet_adapter.zip")except ImportError:pass
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491"""Libratio Fleet AWS Database Adapter.
Supports Amazon DynamoDB (for step metrics and run telemetry) and Amazon AuroraPostgreSQL with pgvector (for semantic RAG over historical trajectories), withan offline JSON and in-memory fallback when AWS credentials or Aurora hosts arenot configured."""from __future__ import annotations
import jsonimport mathimport osimport reimport timefrom datetime import datetime, timezonefrom decimal import Decimalfrom pathlib import Pathfrom typing import Any, Dict, List, Optional
from dotenv import load_dotenv
from mongodb_vector import ( EMBEDDING_DIM, _GEMINI_AVAILABLE as GEMINI_AVAILABLE, generate_embedding, live_state_to_query_text, trajectory_to_text,)
load_dotenv()
try: import boto3 from botocore.config import Config as BotoConfig from botocore.exceptions import BotoCoreError, ClientError BOTO3_AVAILABLE = Trueexcept ImportError: boto3 = None BotoConfig = None BotoCoreError = Exception ClientError = Exception BOTO3_AVAILABLE = False
try: import psycopg2 PSYCOPG2_AVAILABLE = Trueexcept ImportError: psycopg2 = None PSYCOPG2_AVAILABLE = False
AWS_REGION = os.getenv("AWS_REGION", os.getenv("AWS_DEFAULT_REGION", "us-east-1"))DYNAMODB_STEPS_TABLE = os.getenv("DYNAMODB_STEPS_TABLE", "libratio_step_metrics")DYNAMODB_RUNS_TABLE = os.getenv("DYNAMODB_RUNS_TABLE", "libratio_runs")AURORA_PG_HOST = os.getenv("AURORA_PG_HOST", "")AURORA_PG_PORT = int(os.getenv("AURORA_PG_PORT", "5432"))AURORA_PG_DB = os.getenv("AURORA_PG_DB", "libratio")AURORA_PG_USER = os.getenv("AURORA_PG_USER", "")AURORA_PG_PASSWORD = os.getenv("AURORA_PG_PASSWORD", "")
_ROOT_DIR = Path(__file__).resolve().parent.parent_TRAJECTORIES_PATH = _ROOT_DIR / "synthetic_trajectories.json"
_dynamodb_resource = None_cached_trajectories: Optional[List[Dict[str, Any]]] = None_local_step_logs: List[Dict[str, Any]] = []_local_run_logs: List[Dict[str, Any]] = []
def _get_dynamodb_resource(): """Return a cached boto3 DynamoDB resource configured with short timeouts.""" global _dynamodb_resource if not BOTO3_AVAILABLE: return None if not (os.getenv("AWS_ACCESS_KEY_ID") or os.getenv("AWS_PROFILE")): return None if _dynamodb_resource is None: cfg = BotoConfig( retries={"total_max_attempts": 2, "mode": "adaptive"}, connect_timeout=5, read_timeout=10, max_pool_connections=20, ) _dynamodb_resource = boto3.resource("dynamodb", region_name=AWS_REGION, config=cfg) return _dynamodb_resource
def _to_decimal_safe(value: Any) -> Any: """Convert Python floats recursively to Decimal for DynamoDB resource writes.""" if isinstance(value, float): return Decimal(str(round(value, 6))) if isinstance(value, list): return [_to_decimal_safe(v) for v in value] if isinstance(value, dict): return {k: _to_decimal_safe(v) for k, v in value.items()} return value
def _get_aurora_connection(): """Open an Aurora PostgreSQL connection if configured, else return None.""" if not PSYCOPG2_AVAILABLE or not AURORA_PG_HOST: return None return psycopg2.connect( host=AURORA_PG_HOST, port=AURORA_PG_PORT, dbname=AURORA_PG_DB, user=AURORA_PG_USER, password=AURORA_PG_PASSWORD, connect_timeout=5, )
def create_aws_tables() -> bool: """Create DynamoDB tables if AWS is configured; otherwise confirm offline store.""" ddb = _get_dynamodb_resource() if ddb is None: return True
specs = [ ( DYNAMODB_STEPS_TABLE, [{"AttributeName": "run_key", "KeyType": "HASH"}, {"AttributeName": "step", "KeyType": "RANGE"}], [{"AttributeName": "run_key", "AttributeType": "S"}, {"AttributeName": "step", "AttributeType": "N"}], ), ( DYNAMODB_RUNS_TABLE, [{"AttributeName": "run_id", "KeyType": "HASH"}], [{"AttributeName": "run_id", "AttributeType": "S"}], ), ] client = ddb.meta.client for table_name, key_schema, attr_defs in specs: try: client.describe_table(TableName=table_name) except client.exceptions.ResourceNotFoundException: try: ddb.create_table( TableName=table_name, KeySchema=key_schema, AttributeDefinitions=attr_defs, BillingMode="PAY_PER_REQUEST", ) except client.exceptions.ResourceInUseException: pass except (ClientError, BotoCoreError): return False except (ClientError, BotoCoreError): return False return True
def setup_aurora_pgvector_table() -> bool: """Ensure the pgvector trajectories table exists in Aurora PostgreSQL.""" if not PSYCOPG2_AVAILABLE or not AURORA_PG_HOST: return True conn = None try: conn = _get_aurora_connection() with conn, conn.cursor() as cur: cur.execute("CREATE EXTENSION IF NOT EXISTS vector;") cur.execute( f""" CREATE TABLE IF NOT EXISTS trajectories ( id SERIAL PRIMARY KEY, model_name TEXT, total_params_b DOUBLE PRECISION, outcome TEXT, failure_reason TEXT, memory_used_gb DOUBLE PRECISION, thermal_risk TEXT, estimated_power_pct DOUBLE PRECISION, precision_strategy JSONB, source_text TEXT, embedding vector({EMBEDDING_DIM}) ); """ ) return True except Exception: return False finally: if conn is not None: conn.close()
def log_step_metrics( task_id: str, model_id: str, step: int, reward: float, memory_used_gb: float, thermal_risk: str, power_util: float,) -> bool: """Persist one step metric record to DynamoDB or local fallback list.""" item = { "run_key": f"{task_id}#{model_id}", "step": int(step), "task_id": str(task_id), "model_id": str(model_id), "reward": float(reward), "memory_used_gb": float(memory_used_gb), "thermal_risk": str(thermal_risk), "power_util": float(power_util), "timestamp": datetime.now(timezone.utc).isoformat(), } _local_step_logs.append(item)
ddb = _get_dynamodb_resource() if ddb is None: return True
try: table = ddb.Table(DYNAMODB_STEPS_TABLE) table.put_item(Item=_to_decimal_safe(item)) return True except (ClientError, BotoCoreError): return True
def log_run_telemetry( task_id: str, model_name: str, score: float, steps: int, success: bool, rewards: List[float],) -> bool: """Persist one completed episode summary to DynamoDB or local fallback list.""" item = { "run_id": f"{task_id}-{model_name}-{int(time.time() * 1000)}", "task_id": str(task_id), "model_name": str(model_name), "score": float(score), "steps": int(steps), "success": bool(success), "rewards": [float(r) for r in (rewards or [])], "timestamp": datetime.now(timezone.utc).isoformat(), } _local_run_logs.append(item)
ddb = _get_dynamodb_resource() if ddb is None: return True
try: table = ddb.Table(DYNAMODB_RUNS_TABLE) table.put_item(Item=_to_decimal_safe(item)) return True except (ClientError, BotoCoreError): return True
def _load_local_trajectories() -> List[Dict[str, Any]]: """Load flattened trajectory records from synthetic_trajectories.json if present.""" global _cached_trajectories if _cached_trajectories is not None: return _cached_trajectories
if _TRAJECTORIES_PATH.exists(): try: with open(_TRAJECTORIES_PATH, "r", encoding="utf-8") as fh: episodes = json.load(fh) flat: List[Dict[str, Any]] = [] for ep in episodes: cap = ep.get("cluster_capacity_gb", 0) ep_id = ep.get("episode_id", 0) for traj in ep.get("trajectories", []): flat.append({**traj, "episode_id": ep_id, "cluster_capacity_gb": cap}) if flat: _cached_trajectories = flat return _cached_trajectories except (OSError, json.JSONDecodeError): pass
_cached_trajectories = [ { "model_name": "LLaMA-3-70B", "total_params_b": 70.0, "precision_strategy": { "embedding": "FP8", "attention": "BF16", "ffn": "FP8", "layernorm": "BF16", "output": "FP32", }, "memory_used_gb": 112.0, "memory_utilization_pct": 87.5, "thermal_risk": "HIGH", "estimated_power_pct": 74.0, "speedup_vs_fp32": 2.1, "outcome": "CRASH_NUMERICAL_INSTABILITY", "failure_reason": "embedding at FP8 (stability=0.0) on NVIDIA H100", }, { "model_name": "LLaMA-3-13B", "total_params_b": 13.0, "precision_strategy": { "embedding": "FP32", "attention": "BF16", "ffn": "FP8", "layernorm": "BF16", "output": "FP32", }, "memory_used_gb": 22.8, "memory_utilization_pct": 57.0, "thermal_risk": "LOW", "estimated_power_pct": 69.0, "speedup_vs_fp32": 2.15, "outcome": "SUCCESS", }, ] return _cached_trajectories
def _cosine_similarity(vec_a: List[float], vec_b: List[float]) -> float: dot = sum(a * b for a, b in zip(vec_a, vec_b)) norm_a = math.sqrt(sum(a * a for a in vec_a)) norm_b = math.sqrt(sum(b * b for b in vec_b)) if norm_a == 0.0 or norm_b == 0.0: return 0.0 return dot / (norm_a * norm_b)
def search_trajectories_aws( query: str, limit: int = 5, live_state: Optional[Dict[str, Any]] = None,) -> List[Dict[str, Any]]: """Search historical trajectories via Aurora pgvector or local hybrid RRF simulation.""" top_k = max(1, int(limit)) query_vec = generate_embedding(query, task_type="RETRIEVAL_QUERY")
conn = None try: conn = _get_aurora_connection() if conn is not None: vec_literal = "[" + ",".join(f"{v:.6f}" for v in query_vec) + "]" with conn.cursor() as cur: cur.execute( """ SELECT model_name, total_params_b, outcome, failure_reason, memory_used_gb, thermal_risk, estimated_power_pct, precision_strategy, 1 - (embedding <=> %s::vector) AS similarity FROM trajectories ORDER BY embedding <=> %s::vector LIMIT %s; """, (vec_literal, vec_literal, top_k), ) rows = cur.fetchall() return [ { "model_name": row[0], "total_params_b": row[1], "outcome": row[2], "failure_reason": row[3], "memory_used_gb": row[4], "thermal_risk": row[5], "estimated_power_pct": row[6], "precision_strategy": row[7] or {}, "rrf_score": float(row[8] or 0.0), } for row in rows ] except Exception: pass finally: if conn is not None: conn.close()
# Local JSON pgvector + keyword RRF simulation (bounded sample for sub-10ms latency) records = _load_local_trajectories() sample = records[:250] tokens = {tok for tok in re.findall(r"[a-z0-9_]+", query.lower()) if len(tok) > 1}
vec_ranked = [] text_ranked = [] for idx, traj in enumerate(sample): text = trajectory_to_text(traj) text_tokens = set(re.findall(r"[a-z0-9_]+", text.lower())) overlap = len(tokens & text_tokens) sim = _cosine_similarity(query_vec, generate_embedding(text, task_type="RETRIEVAL_DOCUMENT")) vec_ranked.append((sim, idx)) text_ranked.append((overlap, idx))
vec_ranked.sort(key=lambda item: item[0], reverse=True) text_ranked.sort(key=lambda item: item[0], reverse=True)
k_rrf = 60.0 rrf_scores: Dict[int, float] = {} for rank, (_, idx) in enumerate(vec_ranked[: top_k * 4]): rrf_scores[idx] = rrf_scores.get(idx, 0.0) + 1.0 / (k_rrf + rank + 1) for rank, (overlap, idx) in enumerate(text_ranked[: top_k * 4]): if overlap > 0: rrf_scores[idx] = rrf_scores.get(idx, 0.0) + 1.0 / (k_rrf + rank + 1)
if not rrf_scores: for rank, (_, idx) in enumerate(vec_ranked[:top_k]): rrf_scores[idx] = 1.0 / (k_rrf + rank + 1)
ordered = sorted(rrf_scores.items(), key=lambda item: item[1], reverse=True)[:top_k] results = [] for idx, score in ordered: item = dict(sample[idx]) item["rrf_score"] = round(score, 4) results.append(item) return results
def retrieve_historical_context_aws(live_state: Dict[str, Any], top_k: int = 5) -> str: """Retrieve and format top-k historical trajectories for the predictive SRE prompt.""" query_text = live_state_to_query_text(live_state) results = search_trajectories_aws(query=query_text, limit=top_k, live_state=live_state) if not results: return "HISTORICAL CRASH DATA (AWS Adapter): No matching historical trajectories found."
lines = ["HISTORICAL CRASH DATA (Amazon Aurora pgvector / Local RAG Simulation):"] for idx, traj in enumerate(results, 1): strategy = traj.get("precision_strategy", {}) strat_str = ", ".join(f"{k}={v}" for k, v in strategy.items()) if strategy else "unknown" entry = ( f"\n[{idx}] Similarity/RRF: {traj.get('rrf_score', 0.0):.4f}\n" f" Model: {traj.get('model_name', 'unknown')} ({traj.get('total_params_b', '?')}B params)\n" f" Outcome: {traj.get('outcome', 'UNKNOWN')} | " f"VRAM: {traj.get('memory_used_gb', '?')}GB | " f"Thermal: {traj.get('thermal_risk', '?')} | " f"Power: {traj.get('estimated_power_pct', '?')}%\n" f" Strategy: {strat_str}" ) if traj.get("failure_reason"): entry += f"\n Failure: {traj['failure_reason']}" lines.append(entry) return "\n".join(lines)
def get_runs_analytics_aws() -> Dict[str, Any]: """Aggregate run telemetry from DynamoDB if configured, else from local runs.""" runs = list(_local_run_logs) db_status = "offline_fallback"
ddb = _get_dynamodb_resource() if ddb is not None: try: table = ddb.Table(DYNAMODB_RUNS_TABLE) resp = table.scan(Limit=500) items = resp.get("Items", []) if items: runs = items db_status = "dynamodb_connected" except (ClientError, BotoCoreError): db_status = "dynamodb_fallback"
by_task: Dict[str, List[float]] = {} by_task_success: Dict[str, int] = {} by_model: Dict[str, List[float]] = {} for run in runs: tid = str(run.get("task_id", "unknown")) mname = str(run.get("model_name", "unknown")) score = float(run.get("score", 0.0)) by_task.setdefault(tid, []).append(score) if run.get("success"): by_task_success[tid] = by_task_success.get(tid, 0) + 1 by_model.setdefault(mname, []).append(score)
task_analytics = [ { "task_id": tid, "avg_score": round(sum(scores) / len(scores), 3), "max_score": round(max(scores), 3), "min_score": round(min(scores), 3), "success_rate_pct": round(100.0 * by_task_success.get(tid, 0) / len(scores), 1), "total_runs": len(scores), } for tid, scores in by_task.items() ] model_analytics = [ { "model_name": mname, "avg_score": round(sum(scores) / len(scores), 3), "total_runs": len(scores), } for mname, scores in by_model.items() ]
return { "database_status": db_status, "total_runs_logged": len(runs), "task_analytics": task_analytics, "model_analytics": model_analytics, }27 unmodified lines28293031323382 unmodified lines11611711811912012136 unmodified lines15815916016116216316416516616716816917017117217317417517617761 unmodified lines2392402412422432442452462472482499 unmodified lines25926026126226326426513 unmodified lines27928028128228328420 unmodified lines3053063073083093103113123133143153163173183195 unmodified lines325326327328329330331218 unmodified lines55055155255355455555648 unmodified lines6056066076086096106112 unmodified lines61461561661761861962058 unmodified lines67968068168268368468568668768868969069169269369430 unmodified lines7257267277287297304 unmodified lines73573673773873974074174274374474574674774874975075175275375475575675775875976011 unmodified lines77277377477577677777830 unmodified lines8098108118128138148151 unmodified line817818819820821822246 unmodified lines106910701071107210731074107511 unmodified lines10871088108910901091109227 unmodified linesTHROUGHPUT_MULTIPLIER,ACCURACY_PENALTY,H100_COST_PER_HOUR_USD,compute_training_cost,score_precision_layer,compute_hardware_safety,82 unmodified lines"info": {},}if self.current_task == "fleet_precision":return self._step_fleet_precision(action)elif self.current_task == "fleet_oversight":36 unmodified lines"""if task_id == "fleet_precision":strategy = action.get("precision_strategy", {})values = list(strategy.values())# Hack: all FP8 everywhere (crashes training but minimizes memory)if values and all(v == "FP8" for v in values):return True, -0.5, "IRD: All-FP8 is degenerate — training would crash on embedding+output"# Hack: all FP32 everywhere (no optimization, wastes fleet resources)if values and all(v == "FP32" for v in values):return True, -0.2, "IRD: All-FP32 wastes fleet resources — zero optimization"# Hack: no strategy providedif not strategy:return True, -0.4, "IRD: Empty precision strategy is invalid"elif task_id == "fleet_resource":allocations = action.get("allocations", {})if not allocations:return True, -0.4, "IRD: Empty allocations are invalid"# Hack: starve any model completelyfor mid, alloc in allocations.items():61 unmodified lines}remaining_memory = cluster["total_memory_gb"] - s["fleet_memory_used_gb"]return {"task_id": "fleet_precision","scenario_id": self.scenario["scenario_id"],"cluster": {"total_gpus": cluster["total_gpus"],"total_memory_gb": cluster["total_memory_gb"],"memory_used_gb": round(s["fleet_memory_used_gb"], 2),9 unmodified lines},"other_agents": other_agents_summary,"agents_remaining": len(s["models"]) - agent_idx - 1,"available_precisions": ["FP32", "BF16", "FP16", "FP8"],"step_number": self.step_number + 1,"total_steps": len(s["models"]),}13 unmodified linesmodel_id = model["model_id"]strategy = action.get("precision_strategy", {})cluster = s["cluster"]self.step_number += 120 unmodified linestotal_params=model["total_params"],precision_strategy=strategy,layer_distribution=model["layer_distribution"],)# ── Phase 3: Hardware safety dashboard ──hw_safety = compute_hardware_safety(total_params=model["total_params"],precision_strategy=strategy,layer_distribution=model["layer_distribution"],num_gpus=max(1, cluster["total_gpus"] // len(s["models"])),gpu_memory_gb=cluster.get("gpu_memory_gb", 80.0),)s["agent_configs"][model_id] = strategy5 unmodified linesbreadcrumbs = []for layer_type in model["layer_distribution"]:precision = strategy.get(layer_type, "FP32")lscore, lfeedback = score_precision_layer(layer_type, precision)layer_scores.append(lscore)# Breadcrumb: tell agent exactly which layers are good/badif lscore >= 0.95:218 unmodified lineshas_issues = Falsefor model_id, traj_data in self.scenario["trajectories"].items():window = traj_data["loss"][current_idx*ws:(current_idx+1)*ws]if any(v != v for v in window if isinstance(v, float)):has_issues = Truebreak48 unmodified linesparts = ["Correctly detected fleet instability (+0.30)."]# Did agent identify the RIGHT model?flagged_model = action.get("flagged_model", "")if flagged_model and flagged_model.lower() == gt["crashing_model"].lower():score += 0.25parts.append(f"Identified correct model: {flagged_model} (+0.25).")2 unmodified linesparts.append(f"Identified wrong model: {flagged_model} (actual: {gt['crashing_model']}) (+0.05).")# Did agent pinpoint the failure step?flagged_step = action.get("flagged_step", -1)actual_step = gt["failure_step"]if flagged_step is not None and actual_step > 0:diff = abs(flagged_step - actual_step)58 unmodified lines"priority_reason": m["priority_reason"],})return {"task_id": "fleet_resource","scenario_id": self.scenario["scenario_id"],"cluster": {"total_gpus": cluster["total_gpus"],"gpu_memory_gb": cluster["gpu_memory_gb"],"total_memory_gb": cluster["total_memory_gb"],"cost_per_gpu_hour_usd": cluster["cost_per_gpu_hour_usd"],},"models": model_specs,"iterations_remaining": s["max_iterations"] - s["iteration"],"best_score_so_far": round(s["best_score"], 3),"previous_result": s["prev_result"],30 unmodified lines}# allocations = { model_id: { "gpus": N, "precision_strategy": {...} } }total_gpus_assigned = 0fleet_cost = 0.0fleet_fp32_cost = 0.04 unmodified linesfor model in s["models"]:mid = model["model_id"]alloc = allocations.get(mid, {})gpus = alloc.get("gpus", 0)strategy = alloc.get("precision_strategy", {"embedding": "FP32", "attention": "BF16","ffn": "FP8", "layernorm": "BF16", "output": "FP32",})total_gpus_assigned += gpusif gpus <= 0:all_valid = Falseissues.append(f"{mid}: assigned 0 GPUs")per_model_results[mid] = {"gpus": 0, "valid": False}continue# Compute metricsmetrics = compute_training_cost(total_params=model["total_params"],precision_strategy=strategy,layer_distribution=model["layer_distribution"],)# Memory check: model must fit in allocated GPU memoryavailable_mem = gpus * cluster["gpu_memory_gb"]mem_ok = metrics["memory_gb"] <= available_mem11 unmodified lines"training_days": metrics["training_days"],"speedup": metrics["speedup_vs_fp32"],"stable": metrics["estimated_stable"],"valid": mem_ok and metrics["estimated_stable"],}fleet_cost += metrics["cost_usd"]fleet_fp32_cost += metrics["fp32_baseline_cost_usd"]30 unmodified lines# ── Phase 4: Difference Rewards ──# Counterfactual: what if we used naive equal-split allocation?naive_gpus = cluster["total_gpus"] // max(len(s["models"]), 1)naive_cost = 0.0for model in s["models"]:naive_metrics = compute_training_cost(1 unmodified lineprecision_strategy={"embedding": "FP32", "attention": "BF16","ffn": "BF16", "layernorm": "BF16", "output": "FP32"},layer_distribution=model["layer_distribution"],)naive_cost += naive_metrics["cost_usd"]# Agent's improvement over naive baseline246 unmodified linesefficient than the naive fix while maintaining stability."""new_strategy = action.get("new_precision_strategy", {})fleet = state["fleet"]crashed_id = state["crashed_model_id"]# Find the crashed model11 unmodified linestotal_params=crashed_model["total_params"],precision_strategy=new_strategy,layer_distribution=crashed_model["layer_distribution"],)score = 0.2027 unmodified lines2829303132333482 unmodified lines11711811912012112212312412512612712812913036 unmodified lines16716816917017117217317417517617717817918018118218318418561 unmodified lines2472482492502512522532542552562572582592602619 unmodified lines27127227327427527627713 unmodified lines29129229329429529629729820 unmodified lines3193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563575 unmodified lines363364365366367368369218 unmodified lines58858959059159259359448 unmodified lines6436446456466476486496502 unmodified lines65365465565665765865966066166266366466558 unmodified lines72472572672772872973073173273373473573673773873974074174274374474530 unmodified lines7767777787797807817827834 unmodified lines78878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084111 unmodified lines85385485585685785885930 unmodified lines8908918928938948958961 unmodified line898899900901902903904905906246 unmodified lines115311541155115611571158115911601161116211 unmodified lines117411751176117711781179118027 unmodified linesTHROUGHPUT_MULTIPLIER,ACCURACY_PENALTY,H100_COST_PER_HOUR_USD,get_hardware_profile,compute_training_cost,score_precision_layer,compute_hardware_safety,82 unmodified lines"info": {},}if not isinstance(action, dict):return {"observation": None,"reward": {"score": 0.01, "feedback": "Invalid action: expected JSON object."},"done": self.is_done,"info": {"invalid_action": True},}if self.current_task == "fleet_precision":return self._step_fleet_precision(action)elif self.current_task == "fleet_oversight":36 unmodified lines"""if task_id == "fleet_precision":strategy = action.get("precision_strategy", {})if not isinstance(strategy, dict) or not strategy:return True, -0.4, "IRD: Empty or invalid precision strategy"values = list(strategy.values())# Hack: all low-bit (FP8/INT8) everywhere (crashes training on embedding+output)if values and all(v in ("FP8", "INT8") for v in values):return True, -0.5, "IRD: All-FP8/INT8 is degenerate — training would crash on embedding+output"# Hack: all FP32 everywhere (no optimization, wastes fleet resources)if values and all(v == "FP32" for v in values):return True, -0.2, "IRD: All-FP32 wastes fleet resources — zero optimization"elif task_id == "fleet_resource":allocations = action.get("allocations", {})if not isinstance(allocations, dict) or not allocations:return True, -0.4, "IRD: Empty allocations are invalid"# Hack: starve any model completelyfor mid, alloc in allocations.items():61 unmodified lines}remaining_memory = cluster["total_memory_gb"] - s["fleet_memory_used_gb"]hw_profile = cluster.get("hardware_profile", "nvidia_h100")profile = get_hardware_profile(hw_profile)return {"task_id": "fleet_precision","scenario_id": self.scenario["scenario_id"],"cluster": {"hardware_profile": hw_profile,"vendor": cluster.get("vendor", profile["vendor"]),"total_gpus": cluster["total_gpus"],"total_memory_gb": cluster["total_memory_gb"],"memory_used_gb": round(s["fleet_memory_used_gb"], 2),9 unmodified lines},"other_agents": other_agents_summary,"agents_remaining": len(s["models"]) - agent_idx - 1,"available_precisions": list(profile["available_precisions"]),"step_number": self.step_number + 1,"total_steps": len(s["models"]),}13 unmodified linesmodel_id = model["model_id"]strategy = action.get("precision_strategy", {})cluster = s["cluster"]hw_profile = cluster.get("hardware_profile", "nvidia_h100")profile = get_hardware_profile(hw_profile)self.step_number += 120 unmodified linestotal_params=model["total_params"],precision_strategy=strategy,layer_distribution=model["layer_distribution"],hardware_profile=hw_profile,)# Reject hardware-unsupported precisions immediately (e.g., FP8 on Google TPU)if metrics.get("unsupported_precisions"):bad = ", ".join(metrics["unsupported_precisions"])feedback = (f"CRITICAL: UNSUPPORTED precision on {hw_profile} ({profile['vendor']}): {bad}. "f"Supported: {profile['available_precisions']}.")self.history.append({"step": self.step_number, "agent": model_id,"strategy": strategy, "score": 0.01, "unsupported_precision": True,})s["current_agent_idx"] += 1done = s["current_agent_idx"] >= len(s["models"])if done:self.is_done = Truereturn {"observation": None if done else self._fleet_precision_observation(),"reward": {"score": 0.01, "feedback": feedback},"done": done,"info": {"unsupported_precisions": metrics["unsupported_precisions"]},}# ── Phase 3: Hardware safety dashboard ──hw_safety = compute_hardware_safety(total_params=model["total_params"],precision_strategy=strategy,layer_distribution=model["layer_distribution"],num_gpus=max(1, cluster["total_gpus"] // len(s["models"])),gpu_memory_gb=cluster.get("gpu_memory_gb", profile["gpu_memory_gb"]),hardware_profile=hw_profile,)s["agent_configs"][model_id] = strategy5 unmodified linesbreadcrumbs = []for layer_type in model["layer_distribution"]:precision = strategy.get(layer_type, "FP32")lscore, lfeedback = score_precision_layer(layer_type, precision, hardware_profile=hw_profile)layer_scores.append(lscore)# Breadcrumb: tell agent exactly which layers are good/badif lscore >= 0.95:218 unmodified lineshas_issues = Falsefor model_id, traj_data in self.scenario["trajectories"].items():window = traj_data["loss"][current_idx*ws:(current_idx+1)*ws]if any(isinstance(v, (int, float)) and (v != v or v > 100.0) for v in window):has_issues = Truebreak48 unmodified linesparts = ["Correctly detected fleet instability (+0.30)."]# Did agent identify the RIGHT model?raw_model = action.get("flagged_model")flagged_model = raw_model if isinstance(raw_model, str) else ""if flagged_model and flagged_model.lower() == gt["crashing_model"].lower():score += 0.25parts.append(f"Identified correct model: {flagged_model} (+0.25).")2 unmodified linesparts.append(f"Identified wrong model: {flagged_model} (actual: {gt['crashing_model']}) (+0.05).")# Did agent pinpoint the failure step?raw_step = action.get("flagged_step")flagged_step = Noneif raw_step is not None and not isinstance(raw_step, bool):try:flagged_step = int(raw_step)except (ValueError, TypeError):flagged_step = Noneactual_step = gt["failure_step"]if flagged_step is not None and actual_step > 0:diff = abs(flagged_step - actual_step)58 unmodified lines"priority_reason": m["priority_reason"],})hw_profile = cluster.get("hardware_profile", "nvidia_h100")profile = get_hardware_profile(hw_profile)return {"task_id": "fleet_resource","scenario_id": self.scenario["scenario_id"],"cluster": {"hardware_profile": hw_profile,"vendor": cluster.get("vendor", profile["vendor"]),"total_gpus": cluster["total_gpus"],"gpu_memory_gb": cluster["gpu_memory_gb"],"total_memory_gb": cluster["total_memory_gb"],"cost_per_gpu_hour_usd": cluster["cost_per_gpu_hour_usd"],},"models": model_specs,"available_precisions": list(profile["available_precisions"]),"iterations_remaining": s["max_iterations"] - s["iteration"],"best_score_so_far": round(s["best_score"], 3),"previous_result": s["prev_result"],30 unmodified lines}# allocations = { model_id: { "gpus": N, "precision_strategy": {...} } }hw_profile = cluster.get("hardware_profile", "nvidia_h100")profile = get_hardware_profile(hw_profile)total_gpus_assigned = 0fleet_cost = 0.0fleet_fp32_cost = 0.04 unmodified linesfor model in s["models"]:mid = model["model_id"]alloc = allocations.get(mid, {})if not isinstance(alloc, dict):all_valid = Falseissues.append(f"{mid}: invalid allocation entry")per_model_results[mid] = {"gpus": 0, "valid": False}continueraw_gpus = alloc.get("gpus", 0)if isinstance(raw_gpus, bool):gpus = -1else:try:gpus = int(raw_gpus)except (ValueError, TypeError):gpus = -1default_ffn = profile.get("ideal_ffn", "FP8")strategy = alloc.get("precision_strategy", {"embedding": "FP32", "attention": "BF16","ffn": default_ffn, "layernorm": "BF16", "output": "FP32",})if not isinstance(strategy, dict):all_valid = Falseissues.append(f"{mid}: invalid precision_strategy")per_model_results[mid] = {"gpus": max(0, gpus), "valid": False}continueif gpus <= 0:all_valid = Falseissues.append(f"{mid}: assigned invalid GPU count ({raw_gpus})")per_model_results[mid] = {"gpus": 0, "valid": False}continuetotal_gpus_assigned += gpus# Compute metrics with actual allocated GPUs and cluster ratemetrics = compute_training_cost(total_params=model["total_params"],precision_strategy=strategy,layer_distribution=model["layer_distribution"],num_gpus=gpus,cost_per_gpu_hour=cluster["cost_per_gpu_hour_usd"],hardware_profile=hw_profile,)if metrics.get("unsupported_precisions"):all_valid = Falseissues.append(f"{mid}: unsupported precision {metrics['unsupported_precisions']}")# Memory check: model must fit in allocated GPU memoryavailable_mem = gpus * cluster["gpu_memory_gb"]mem_ok = metrics["memory_gb"] <= available_mem11 unmodified lines"training_days": metrics["training_days"],"speedup": metrics["speedup_vs_fp32"],"stable": metrics["estimated_stable"],"valid": mem_ok and metrics["estimated_stable"] and not metrics.get("unsupported_precisions"),}fleet_cost += metrics["cost_usd"]fleet_fp32_cost += metrics["fp32_baseline_cost_usd"]30 unmodified lines# ── Phase 4: Difference Rewards ──# Counterfactual: what if we used naive equal-split allocation?naive_gpus = max(1, cluster["total_gpus"] // max(len(s["models"]), 1))naive_cost = 0.0for model in s["models"]:naive_metrics = compute_training_cost(1 unmodified lineprecision_strategy={"embedding": "FP32", "attention": "BF16","ffn": "BF16", "layernorm": "BF16", "output": "FP32"},layer_distribution=model["layer_distribution"],num_gpus=naive_gpus,cost_per_gpu_hour=cluster["cost_per_gpu_hour_usd"],hardware_profile=hw_profile,)naive_cost += naive_metrics["cost_usd"]# Agent's improvement over naive baseline246 unmodified linesefficient than the naive fix while maintaining stability."""new_strategy = action.get("new_precision_strategy", {})if not isinstance(new_strategy, dict) or not new_strategy:return 0.01, "Invalid or empty new_precision_strategy."fleet = state["fleet"]hw_profile = fleet.get("cluster", {}).get("hardware_profile", "nvidia_h100")crashed_id = state["crashed_model_id"]# Find the crashed model11 unmodified linestotal_params=crashed_model["total_params"],precision_strategy=new_strategy,layer_distribution=crashed_model["layer_distribution"],hardware_profile=hw_profile,)score = 0.20
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181"""Local Arm64 GGUF Inference Engine (llama-cpp-python) with Mock Fallback.
Runs local quantized GGUF models on Arm64 CPUs (Apple Silicon, AWS Graviton,Raspberry Pi) and falls back cleanly to deterministic mock outputs whenMOCK_LOCAL_INFERENCE=True, model_path="mock", or llama_cpp is unavailable."""from __future__ import annotations
import jsonimport osimport refrom typing import Any, Dict, Optional
try: from llama_cpp import Llama LLAMA_CPP_AVAILABLE = Trueexcept ImportError: Llama = None LLAMA_CPP_AVAILABLE = False
class LocalArmInferenceEngine: """Local GGUF inference wrapper with resilient JSON extraction and mock fallback."""
def __init__(self, model_path: Optional[str] = None, n_ctx: int = 2048, n_threads: Optional[int] = None): resolved_path = model_path if model_path is not None else os.getenv("LOCAL_MODEL_PATH", "") force_mock = os.getenv("MOCK_LOCAL_INFERENCE", "False").lower() == "true"
self.model_path = resolved_path self.llm = None self.is_mock = True
if ( not force_mock and resolved_path and resolved_path.lower() != "mock" and os.path.exists(resolved_path) and LLAMA_CPP_AVAILABLE ): self.llm = Llama( model_path=resolved_path, n_ctx=n_ctx, n_threads=n_threads or max(1, (os.cpu_count() or 4) // 2), verbose=False, ) self.is_mock = False
@staticmethod def _parse_json_from_text(raw_text: str) -> Dict[str, Any]: """Extract and parse a JSON object from raw or markdown-wrapped LLM output.""" if not raw_text: return {} text = raw_text.strip()
if "```json" in text: text = text.split("```json", 1)[1].split("```", 1)[0].strip() elif "```" in text: text = text.split("```", 1)[1].split("```", 1)[0].strip()
first_brace = text.find("{") if first_brace != -1: depth = 0 in_str = False escaped = False for idx in range(first_brace, len(text)): ch = text[idx] if ch == '"' and not escaped: in_str = not in_str elif ch == "\\" and in_str: escaped = not escaped continue elif not in_str: if ch == "{": depth += 1 elif ch == "}": depth -= 1 if depth == 0: text = text[first_brace : idx + 1] break escaped = False
# Remove trailing commas before } or ] text = re.sub(r",\s*([\]}])", r"\1", text) try: parsed = json.loads(text) return parsed if isinstance(parsed, dict) else {} except json.JSONDecodeError: return {}
def _mock_generate(self, user_prompt: str) -> str: """Generate deterministic valid JSON actions matching task and hardware hints.""" prompt_lower = user_prompt.lower() is_tpu = "google_tpu_v5p" in prompt_lower or "tpu" in prompt_lower
if "continue_monitoring" in prompt_lower or "flag_instability" in prompt_lower: payload = { "action_type": "continue_monitoring", "analysis": "Mock local inference: loss trajectories appear stable across active models.", "flagged_model": None, "flagged_step": None, "root_cause": None, } return json.dumps(payload)
if "allocations" in prompt_lower: ffn_prec = "INT8" if is_tpu else "FP8" payload = { "allocations": { "model_a": { "gpus": 2, "precision_strategy": { "embedding": "FP32", "attention": "BF16", "ffn": ffn_prec, "layernorm": "BF16", "output": "FP32", }, } }, "reasoning": "Mock local inference resource allocation respecting hardware precision support.", } return json.dumps(payload)
if "diagnosed_model" in prompt_lower: return json.dumps({ "diagnosed_model": "model_b", "root_cause": "fp8 embedding underflow", "reasoning": "Mock local inference recovery diagnosis.", })
if is_tpu: payload = { "precision_strategy": { "embedding": "FP32", "attention": "BF16", "ffn": "INT8", "layernorm": "BF16", "output": "FP32", }, "reasoning": "Google TPU detected: using INT8 for FFN because FP8 is unsupported on TPU v5p.", } return json.dumps(payload)
payload = { "precision_strategy": { "embedding": "FP32", "attention": "BF16", "ffn": "FP8", "layernorm": "BF16", "output": "FP32", }, "reasoning": "Standard mixed precision: FP32 embedding/output, BF16 attention/layernorm, FP8 FFN.", } return json.dumps(payload)
def generate( self, system_prompt: str, user_prompt: str, max_tokens: int = 600, temperature: float = 0.2, ) -> str: """Generate a raw completion string from GGUF or mock fallback.""" if self.is_mock or self.llm is None: return self._mock_generate(user_prompt)
response = self.llm.create_chat_completion( messages=[ {"role": "system", "content": system_prompt}, {"role": "user", "content": user_prompt}, ], max_tokens=max_tokens, temperature=temperature, ) return response["choices"][0]["message"]["content"]
def generate_json(self, system_prompt: str, user_prompt: str) -> Dict[str, Any]: """Generate and parse a JSON action dict.""" raw = self.generate(system_prompt=system_prompt, user_prompt=user_prompt) return self._parse_json_from_text(raw)72 unmodified lines7374757677787980818283848586878889905 unmodified lines969798991001011021031041051061071081091101111121131141151161171181191201211221231241255 unmodified lines13113213313413513613713813914014114214314414514614714814915015115215315415515615715815916025 unmodified lines1861871881891901911921935 unmodified lines1992002012022032042056 unmodified lines21221321421521621721821922022122222322422522622722822923023123223323431 unmodified lines2662672682692702714 unmodified lines2762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143152 unmodified lines31831932032132232332411 unmodified lines33633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037110 unmodified lines38238338438538638738838939039139239339439539639739839940040140272 unmodified lines"BF16": 2, # Brain Float 16"FP16": 2, # IEEE 754 half-precision"FP8": 1, # NVIDIA E4M3 format}# ── Throughput multiplier vs FP32 baseline on H100 SXM ──────────────────────# Source: NVIDIA Transformer Engine benchmarks [NVIDIA-TE]# Applied per layer type — FFN benefits most from FP8 due to GEMM operationsTHROUGHPUT_MULTIPLIER = {"embedding": {"FP32": 1.00, "BF16": 1.80, "FP16": 1.75, "FP8": 1.90},"layernorm": {"FP32": 1.00, "BF16": 1.85, "FP16": 1.80, "FP8": 1.85},"attention": {"FP32": 1.00, "BF16": 1.85, "FP16": 1.80, "FP8": 2.30},"ffn": {"FP32": 1.00, "BF16": 1.85, "FP16": 1.80, "FP8": 2.50},# Source: NVIDIA TE shows FP8 FFN at ~1.35x over BF16 (=2.50x over FP32)"output": {"FP32": 1.00, "BF16": 1.40, "FP16": 1.40, "FP8": 1.50},}# ── Stability scores (probability of crash-free training run to completion) ──5 unmodified lines"BF16": 0.85, # Acceptable; wider range than FP16 [Kalamkar2019]"FP16": 0.45, # 30-50% of runs diverge [Micikevicius2018]"FP8": 0.00, # Near-certain crash; sparse gradients → zero [NVIDIA-FP8-2022]},"layernorm": {"FP32": 0.80, # Overkill; BF16 is actually optimal here"BF16": 1.00, # Recommended by NVIDIA TE [NVIDIA-TE]"FP16": 0.90, # Acceptable with loss scaling"FP8": 0.20, # NVIDIA TE explicitly warns against FP8 for LN [NVIDIA-TE]},"attention": {"FP32": 0.75, # Overkill; introduces no stability benefit over BF16"BF16": 1.00, # PyTorch AMP default; fully validated for attention"FP16": 0.85, # Standard AMP practice; well tested [Micikevicius2018]"FP8": 0.40, # Requires per-tensor scaling; risky without TE [NVIDIA-FP8-2022]},"ffn": {"FP32": 0.60, # Wastes 4x memory relative to BF16 with no gain"BF16": 0.95, # Very safe; primary alternative to FP8 for FFN"FP16": 0.90, # Safe with loss scaling"FP8": 1.00, # Primary target of NVIDIA TE FP8; fully validated [NVIDIA-TE]},"output": {"FP32": 1.00, # Required for numerically stable cross-entropy loss"BF16": 0.50, # Borderline; some frameworks use with scaling factors"FP16": 0.30, # High overflow risk in cross-entropy [NVIDIA-FP8-2022]"FP8": 0.00, # Certain accuracy collapse; loss value becomes meaningless},}5 unmodified lines"BF16": 0.003, # <0.3% perplexity increase [Kalamkar2019]"FP16": 0.012, # Higher instability = representation degradation"FP8": 0.080, # Severe; sparse gradient underflow kills token representations},"layernorm": {"FP32": 0.000,"BF16": 0.000, # No measurable impact [Kalamkar2019]"FP16": 0.001,"FP8": 0.030, # Normalization precision critical; errors propagate forward},"attention": {"FP32": 0.000,"BF16": 0.001, # Negligible [Kalamkar2019]"FP16": 0.003,"FP8": 0.025, # ~2-3% on standard benchmarks with NVIDIA TE scaling [NVIDIA-TE]},"ffn": {"FP32": 0.000,"BF16": 0.001,"FP16": 0.002,"FP8": 0.008, # Lowest-risk FP8 application; <1% on most benchmarks [NVIDIA-TE]},"output": {"FP32": 0.000,"BF16": 0.010,"FP16": 0.040, # Cross-entropy precision critical for convergence"FP8": 0.100, # Catastrophic loss value corruption},}25 unmodified lines"BF16": 0.70, # Tensor cores ~30% more power-efficient than FP32"FP16": 0.68, # Slightly better than BF16 due to narrower format"FP8": 0.55, # Most power-efficient; ~45% savings vs FP32}# Safety thresholds — crossing these risks hardware damage or job failureMEMORY_UTILIZATION_DANGER = 0.95 # >95% memory = OOM crash riskMEMORY_UTILIZATION_WARNING = 0.85 # >85% memory = fragmentation risk5 unmodified linesprecision_strategy: dict,layer_distribution: dict,num_gpus: int = 1,gpu_memory_gb: float = 80.0,) -> dict:"""Compute hardware safety metrics for a given precision configuration.6 unmodified linesmemory_per_gpu_gb, memory_utilization_pct, memory_safe,estimated_power_pct, power_safe, thermal_risk, overall_safe"""# Memory per GPUtotal_mem_gb = 0.0for layer_type, fraction in layer_distribution.items():precision = precision_strategy.get(layer_type, "FP32")params_in_layer = total_params * fractionmem_gb = (params_in_layer * BYTES_PER_PARAM.get(precision, 4)) / 1e9total_mem_gb += mem_gbmem_per_gpu = total_mem_gb / max(num_gpus, 1)mem_utilization = mem_per_gpu / gpu_memory_gb# Power estimate (weighted average across layers)weighted_power = 0.0total_weight = 0.0for layer_type, fraction in layer_distribution.items():precision = precision_strategy.get(layer_type, "FP32")power = POWER_DRAW_MULTIPLIER.get(precision, 1.0)weighted_power += power * fractiontotal_weight += fraction31 unmodified linesnum_epochs: float = 1.0,num_gpus: int = None,cost_per_gpu_hour: float = None,) -> dict:"""Compute real dollar cost and training time for a given precision strategy.4 unmodified linesArgs:num_gpus: Override cluster GPU count (default: NUM_GPUS_BASELINE=100)cost_per_gpu_hour: Override hourly rate (default: H100_COST_PER_HOUR_USD=3.00)Returns:memory_gb, speedup_vs_fp32, training_hours, training_days,cost_usd, fp32_baseline_cost_usd, savings_usd, savings_pct,accuracy_retention, estimated_stable"""gpus = num_gpus if num_gpus is not None else NUM_GPUS_BASELINErate = cost_per_gpu_hour if cost_per_gpu_hour is not None else H100_COST_PER_HOUR_USDtotal_mem_gb = 0.0weighted_speedup = 0.0total_accuracy_penalty = 0.0total_weight = 0.0all_stable = Truefor layer_type, fraction in layer_distribution.items():precision = precision_strategy.get(layer_type, "FP32")params_in_layer = total_params * fraction# Memory: bytes -> GBmem_gb = (params_in_layer * BYTES_PER_PARAM[precision]) / 1e9total_mem_gb += mem_gb# Throughput (weighted average by parameter fraction)speedup = THROUGHPUT_MULTIPLIER[layer_type][precision]weighted_speedup += speedup * fractiontotal_weight += fraction# Accuracy penalty (BUG FIX: weight by layer fraction, not raw sum)penalty = ACCURACY_PENALTY[layer_type][precision]total_accuracy_penalty += penalty * fraction# Stability checkstability = STABILITY_SCORE[layer_type][precision]if stability < 0.5:all_stable = False2 unmodified lines# Wall-clock training days (normalized: 1 day per billion params at FP32)params_b = total_params / 1e9fp32_days = params_b * DAYS_PER_BILLION_PARAMS_FP32 * num_epochsactual_days = fp32_days / avg_speedup# Dollar cost: days * 24 hours * cost_per_hour * num_gpusfp32_cost = fp32_days * 24 * rate * gpus11 unmodified lines"savings_pct": round((savings / fp32_cost) * 100, 1) if fp32_cost > 0 else 0,"accuracy_retention": round(max(0.0, 1.0 - total_accuracy_penalty), 4),"estimated_stable": all_stable,}def score_precision_layer(layer_type: str, precision: str) -> tuple[float, str]:"""Per-layer scoring using "distance from ideal precision" approach.Each layer type has a scientifically-grounded ideal precision:- embedding: FP32 (sparse gradients underflow in FP8/FP16 [NVIDIA-FP8-2022])- layernorm: BF16 (NVIDIA TE recommended; FP32 is wasteful [NVIDIA-TE])- attention: BF16 (PyTorch AMP default; fully validated [Micikevicius2018])- ffn: FP8 (primary FP8 target, 2.5x speedup [NVIDIA-TE 2023])- output: FP32 (loss computation requires full precision [NVIDIA-FP8-2022])Scoring tiers:1.00 = Perfect: the ideal precision for this layer0.85 = Good: safe alternative with minor efficiency trade-off0.50 = Suboptimal: stable but unnecessarily slow/risky0.00 = Critical failure: causes NaN or significant instability"""stability = STABILITY_SCORE.get(layer_type, {}).get(precision, 0.0)throughput = THROUGHPUT_MULTIPLIER.get(layer_type, {}).get(precision, 1.0)# Layer-specific ideal precision (empirically validated)IDEAL = {"embedding": "FP32", # [NVIDIA-FP8-2022]: must be FP32 or BF16 minimum"layernorm": "BF16", # [NVIDIA-TE]: BF16 is the recommended optimum"attention": "BF16", # [Micikevicius2018 + PyTorch AMP]: BF16 is standard"ffn": "FP8", # [NVIDIA-TE 2023]: primary FP8 application, 2.5x speedup"output": "FP32", # [NVIDIA-FP8-2022]: cross-entropy loss needs full precision}# Crash/Highly unstable: return immediately10 unmodified linesscore = 0.99verdict = "Perfect — optimal precision for this layer type"elif stability >= 0.85:# Safe but suboptimal (e.g., BF16 on embedding instead of FP32)# Penalise proportionally to how much efficiency is lost vs idealideal_throughput = THROUGHPUT_MULTIPLIER.get(layer_type, {}).get(ideal, 1.0)efficiency_gap = abs(throughput - ideal_throughput) / max(ideal_throughput, 1.0)score = round(0.85 - efficiency_gap * 0.30, 3)score = max(0.55, min(0.85, score))verdict = "Good — stable choice, slight efficiency trade-off vs optimal"else:# Low-ish stability (0.5–0.85): risky but technically possiblescore = round(stability * 0.50, 3)verdict = "Risky — potential instability in long training runs"sources = {"FP8": "[NVIDIA-TE 2023]", "BF16": "[Kalamkar2019]","FP16": "[Micikevicius2018]", "FP32": "[IEEE 754 baseline]"}feedback = (72 unmodified lines737475767778798081828384858687888990915 unmodified lines9798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301315 unmodified lines13713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017125 unmodified lines1971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442455 unmodified lines2512522532542552562572586 unmodified lines26526626726826927027127227327427527627727827928028128228328428528628728828929029129231 unmodified lines3243253263273283293304 unmodified lines3353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883892 unmodified lines39239339439539639739811 unmodified lines41041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644710 unmodified lines45845946046146246346446546646746846947047147247347447547647747872 unmodified lines"BF16": 2, # Brain Float 16"FP16": 2, # IEEE 754 half-precision"FP8": 1, # NVIDIA E4M3 format"INT8": 1, # 8-bit integer quantization (TPU / quantized inference)}# ── Throughput multiplier vs FP32 baseline on H100 SXM ──────────────────────# Source: NVIDIA Transformer Engine benchmarks [NVIDIA-TE]# Applied per layer type — FFN benefits most from FP8 due to GEMM operationsTHROUGHPUT_MULTIPLIER = {"embedding": {"FP32": 1.00, "BF16": 1.80, "FP16": 1.75, "FP8": 1.90, "INT8": 1.85},"layernorm": {"FP32": 1.00, "BF16": 1.85, "FP16": 1.80, "FP8": 1.85, "INT8": 1.80},"attention": {"FP32": 1.00, "BF16": 1.85, "FP16": 1.80, "FP8": 2.30, "INT8": 2.20},"ffn": {"FP32": 1.00, "BF16": 1.85, "FP16": 1.80, "FP8": 2.50, "INT8": 2.45},# Source: NVIDIA TE shows FP8 FFN at ~1.35x over BF16 (=2.50x over FP32)"output": {"FP32": 1.00, "BF16": 1.40, "FP16": 1.40, "FP8": 1.50, "INT8": 1.45},}# ── Stability scores (probability of crash-free training run to completion) ──5 unmodified lines"BF16": 0.85, # Acceptable; wider range than FP16 [Kalamkar2019]"FP16": 0.45, # 30-50% of runs diverge [Micikevicius2018]"FP8": 0.00, # Near-certain crash; sparse gradients → zero [NVIDIA-FP8-2022]"INT8": 0.00, # Quantized embeddings collapse sparse gradients},"layernorm": {"FP32": 0.80, # Overkill; BF16 is actually optimal here"BF16": 1.00, # Recommended by NVIDIA TE [NVIDIA-TE]"FP16": 0.90, # Acceptable with loss scaling"FP8": 0.20, # NVIDIA TE explicitly warns against FP8 for LN [NVIDIA-TE]"INT8": 0.20, # Normalization requires dynamic range},"attention": {"FP32": 0.75, # Overkill; introduces no stability benefit over BF16"BF16": 1.00, # PyTorch AMP default; fully validated for attention"FP16": 0.85, # Standard AMP practice; well tested [Micikevicius2018]"FP8": 0.40, # Requires per-tensor scaling; risky without TE [NVIDIA-FP8-2022]"INT8": 0.40, # Softmax/attention sensitivity without calibrated scaling},"ffn": {"FP32": 0.60, # Wastes 4x memory relative to BF16 with no gain"BF16": 0.95, # Very safe; primary alternative to FP8 for FFN"FP16": 0.90, # Safe with loss scaling"FP8": 1.00, # Primary target of NVIDIA TE FP8; fully validated [NVIDIA-TE]"INT8": 1.00, # Primary TPU quantized GEMM target for FFN},"output": {"FP32": 1.00, # Required for numerically stable cross-entropy loss"BF16": 0.50, # Borderline; some frameworks use with scaling factors"FP16": 0.30, # High overflow risk in cross-entropy [NVIDIA-FP8-2022]"FP8": 0.00, # Certain accuracy collapse; loss value becomes meaningless"INT8": 0.00, # Cross-entropy logits cannot be quantized to 8-bit int},}5 unmodified lines"BF16": 0.003, # <0.3% perplexity increase [Kalamkar2019]"FP16": 0.012, # Higher instability = representation degradation"FP8": 0.080, # Severe; sparse gradient underflow kills token representations"INT8": 0.080,},"layernorm": {"FP32": 0.000,"BF16": 0.000, # No measurable impact [Kalamkar2019]"FP16": 0.001,"FP8": 0.030, # Normalization precision critical; errors propagate forward"INT8": 0.030,},"attention": {"FP32": 0.000,"BF16": 0.001, # Negligible [Kalamkar2019]"FP16": 0.003,"FP8": 0.025, # ~2-3% on standard benchmarks with NVIDIA TE scaling [NVIDIA-TE]"INT8": 0.025,},"ffn": {"FP32": 0.000,"BF16": 0.001,"FP16": 0.002,"FP8": 0.008, # Lowest-risk FP8 application; <1% on most benchmarks [NVIDIA-TE]"INT8": 0.010,},"output": {"FP32": 0.000,"BF16": 0.010,"FP16": 0.040, # Cross-entropy precision critical for convergence"FP8": 0.100, # Catastrophic loss value corruption"INT8": 0.100,},}25 unmodified lines"BF16": 0.70, # Tensor cores ~30% more power-efficient than FP32"FP16": 0.68, # Slightly better than BF16 due to narrower format"FP8": 0.55, # Most power-efficient; ~45% savings vs FP32"INT8": 0.52, # Low-bit integer matrix units (TPU / quantized)}# Multi-vendor accelerator hardware registryHARDWARE_PROFILES = {"nvidia_h100": {"hardware_profile": "nvidia_h100","vendor": "NVIDIA","gpu_memory_gb": 80.0,"tdp_watts": 700,"available_precisions": ["FP32", "BF16", "FP16", "FP8"],"bytes_per_param": {"FP32": 4, "BF16": 2, "FP16": 2, "FP8": 1},"power_draw_multipliers": {"FP32": 1.00, "BF16": 0.70, "FP16": 0.68, "FP8": 0.55},"ideal_ffn": "FP8",},"amd_mi300x": {"hardware_profile": "amd_mi300x","vendor": "AMD","gpu_memory_gb": 192.0,"tdp_watts": 750,"available_precisions": ["FP32", "BF16", "FP16", "FP8"],"bytes_per_param": {"FP32": 4, "BF16": 2, "FP16": 2, "FP8": 1},"power_draw_multipliers": {"FP32": 1.00, "BF16": 0.72, "FP16": 0.70, "FP8": 0.58},"ideal_ffn": "FP8",},"google_tpu_v5p": {"hardware_profile": "google_tpu_v5p","vendor": "Google","gpu_memory_gb": 95.0,"tdp_watts": 450,"available_precisions": ["FP32", "BF16", "INT8"],"bytes_per_param": {"FP32": 4, "BF16": 2, "FP16": 2, "INT8": 1},"power_draw_multipliers": {"FP32": 1.00, "BF16": 0.70, "INT8": 0.52},"ideal_ffn": "INT8",},}def get_hardware_profile(hardware_profile: str = "nvidia_h100") -> dict:"""Return the hardware capability profile, defaulting to NVIDIA H100."""return HARDWARE_PROFILES.get(hardware_profile, HARDWARE_PROFILES["nvidia_h100"])# Safety thresholds — crossing these risks hardware damage or job failureMEMORY_UTILIZATION_DANGER = 0.95 # >95% memory = OOM crash riskMEMORY_UTILIZATION_WARNING = 0.85 # >85% memory = fragmentation risk5 unmodified linesprecision_strategy: dict,layer_distribution: dict,num_gpus: int = 1,gpu_memory_gb: float = None,hardware_profile: str = "nvidia_h100",) -> dict:"""Compute hardware safety metrics for a given precision configuration.6 unmodified linesmemory_per_gpu_gb, memory_utilization_pct, memory_safe,estimated_power_pct, power_safe, thermal_risk, overall_safe"""profile = get_hardware_profile(hardware_profile)bytes_map = profile["bytes_per_param"]power_map = profile["power_draw_multipliers"]effective_gpu_mem = gpu_memory_gb if gpu_memory_gb is not None and gpu_memory_gb > 0 else profile["gpu_memory_gb"]# Memory per GPUtotal_mem_gb = 0.0for layer_type, fraction in layer_distribution.items():precision = precision_strategy.get(layer_type, "FP32")params_in_layer = total_params * fractionmem_gb = (params_in_layer * bytes_map.get(precision, BYTES_PER_PARAM.get(precision, 4))) / 1e9total_mem_gb += mem_gbmem_per_gpu = total_mem_gb / max(num_gpus, 1)mem_utilization = mem_per_gpu / max(effective_gpu_mem, 1.0)# Power estimate (weighted average across layers)weighted_power = 0.0total_weight = 0.0for layer_type, fraction in layer_distribution.items():precision = precision_strategy.get(layer_type, "FP32")power = power_map.get(precision, POWER_DRAW_MULTIPLIER.get(precision, 1.0))weighted_power += power * fractiontotal_weight += fraction31 unmodified linesnum_epochs: float = 1.0,num_gpus: int = None,cost_per_gpu_hour: float = None,hardware_profile: str = "nvidia_h100",) -> dict:"""Compute real dollar cost and training time for a given precision strategy.4 unmodified linesArgs:num_gpus: Override cluster GPU count (default: NUM_GPUS_BASELINE=100)cost_per_gpu_hour: Override hourly rate (default: H100_COST_PER_HOUR_USD=3.00)hardware_profile: Target accelerator profile keyReturns:memory_gb, speedup_vs_fp32, training_hours, training_days,cost_usd, fp32_baseline_cost_usd, savings_usd, savings_pct,accuracy_retention, estimated_stable, unsupported_precisions"""gpus = max(1, num_gpus) if num_gpus is not None else NUM_GPUS_BASELINErate = cost_per_gpu_hour if cost_per_gpu_hour is not None else H100_COST_PER_HOUR_USDprofile = get_hardware_profile(hardware_profile)supported = set(profile["available_precisions"])bytes_map = profile["bytes_per_param"]total_mem_gb = 0.0weighted_speedup = 0.0total_accuracy_penalty = 0.0total_weight = 0.0all_stable = Trueunsupported = []for layer_type, fraction in layer_distribution.items():precision = precision_strategy.get(layer_type, "FP32")params_in_layer = total_params * fractionif not isinstance(precision, str) or precision not in supported or layer_type not in STABILITY_SCORE:unsupported.append(f"{layer_type}={precision}")all_stable = Falsemem_gb = (params_in_layer * BYTES_PER_PARAM.get(precision, 4)) / 1e9total_mem_gb += mem_gbweighted_speedup += 1.0 * fractiontotal_weight += fractiontotal_accuracy_penalty += 0.10 * fractioncontinue# Memory: bytes -> GBmem_gb = (params_in_layer * bytes_map.get(precision, BYTES_PER_PARAM.get(precision, 4))) / 1e9total_mem_gb += mem_gb# Throughput (weighted average by parameter fraction)speedup = THROUGHPUT_MULTIPLIER.get(layer_type, {}).get(precision, 1.0)weighted_speedup += speedup * fractiontotal_weight += fraction# Accuracy penalty (weight by layer fraction)penalty = ACCURACY_PENALTY.get(layer_type, {}).get(precision, 0.05)total_accuracy_penalty += penalty * fraction# Stability checkstability = STABILITY_SCORE.get(layer_type, {}).get(precision, 0.0)if stability < 0.5:all_stable = False2 unmodified lines# Wall-clock training days (normalized: 1 day per billion params at FP32)params_b = total_params / 1e9fp32_days = params_b * DAYS_PER_BILLION_PARAMS_FP32 * num_epochsactual_days = fp32_days / max(avg_speedup, 0.01)# Dollar cost: days * 24 hours * cost_per_hour * num_gpusfp32_cost = fp32_days * 24 * rate * gpus11 unmodified lines"savings_pct": round((savings / fp32_cost) * 100, 1) if fp32_cost > 0 else 0,"accuracy_retention": round(max(0.0, 1.0 - total_accuracy_penalty), 4),"estimated_stable": all_stable,"unsupported_precisions": unsupported,}def score_precision_layer(layer_type: str,precision: str,hardware_profile: str = "nvidia_h100",) -> tuple[float, str]:"""Per-layer scoring using "distance from ideal precision" approach,conditioned on the target accelerator's supported precision formats."""profile = get_hardware_profile(hardware_profile)supported = profile["available_precisions"]if not isinstance(precision, str) or precision not in supported:return 0.01, (f"CRITICAL: UNSUPPORTED precision {precision} on {hardware_profile} "f"({profile['vendor']}). Supported formats: {supported}.")stability = STABILITY_SCORE.get(layer_type, {}).get(precision, 0.0)throughput = THROUGHPUT_MULTIPLIER.get(layer_type, {}).get(precision, 1.0)# Layer-specific ideal precision (empirically validated per hardware)IDEAL = {"embedding": "FP32","layernorm": "BF16","attention": "BF16","ffn": profile.get("ideal_ffn", "FP8"),"output": "FP32",}# Crash/Highly unstable: return immediately10 unmodified linesscore = 0.99verdict = "Perfect — optimal precision for this layer type"elif stability >= 0.85:ideal_throughput = THROUGHPUT_MULTIPLIER.get(layer_type, {}).get(ideal, 1.0)efficiency_gap = abs(throughput - ideal_throughput) / max(ideal_throughput, 1.0)score = round(0.85 - efficiency_gap * 0.30, 3)score = max(0.55, min(0.85, score))verdict = "Good — stable choice, slight efficiency trade-off vs optimal"else:score = round(stability * 0.50, 3)verdict = "Risky — potential instability in long training runs"sources = {"FP8": "[NVIDIA-TE 2023]","INT8": "[Cloud TPU Quantization]","BF16": "[Kalamkar2019]","FP16": "[Micikevicius2018]","FP32": "[IEEE 754 baseline]",}feedback = (
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146"""Thermal Kernel Module -- Standalone thermal-aware workload placement evaluation.
This is the SECOND kernel module in the Agentic Kernel architecture,proving the design is genuinely modular and extensible.
Physics Source: NVIDIA H100 SXM5 Thermal Design Specifications (2023) - TDP: 700W - Thermal throttling: 83C junction temperature - Emergency shutdown: 92C - Thermal resistance derived from max-power steady-state measurements
The thermal kernel evaluates whether a precision configuration will pushGPU hardware beyond safe thermal limits under sustained training load.It accounts for: 1. Precision-dependent power draw (FP8 draws ~55% of FP32 power) 2. Sustained load overhead (15% above instantaneous TDP) 3. Memory utilization's contribution to chip heating 4. Per-layer power breakdown for debugging
This module can be used standalone or composed with other kernel modulesvia the AgenticKernel interface in kernel_interface.py."""from environment.physics_model import ( POWER_DRAW_MULTIPLIER, BYTES_PER_PARAM, GPU_TDP_WATTS, GPU_THERMAL_LIMIT_C,)
# H100 SXM5 thermal model constantsAMBIENT_TEMP_C = 25.0THERMAL_RESISTANCE_C_PER_W = 0.083 # Derived: (83C - 25C) / 700W = 0.083THROTTLE_THRESHOLD_C = 83.0 # GPU begins throttlingSHUTDOWN_THRESHOLD_C = 92.0 # Emergency power-offSUSTAINED_LOAD_FACTOR = 1.15 # 15% above burst TDP for sustained trainingMEM_THERMAL_COEFFICIENT = 0.05 # Memory utilization contribution to temp
def evaluate_thermal_safety( total_params: int, precision_strategy: dict, layer_distribution: dict, num_gpus: int = 1, gpu_memory_gb: float = 80.0, ambient_temp_c: float = AMBIENT_TEMP_C,) -> dict: """Evaluate thermal safety of a precision configuration.
Args: total_params: Model parameter count precision_strategy: Layer-to-precision mapping layer_distribution: Layer-to-fraction mapping num_gpus: Number of GPUs allocated to this model gpu_memory_gb: Memory per GPU in GB ambient_temp_c: Data center ambient temperature
Returns: Dictionary with thermal metrics and risk assessment. """ # Calculate weighted average power draw across layers weighted_power = 0.0 total_weight = 0.0 per_layer_thermal = {}
for layer_type, fraction in layer_distribution.items(): precision = precision_strategy.get(layer_type, "FP32") power_mult = POWER_DRAW_MULTIPLIER.get(precision, 1.0) weighted_power += power_mult * fraction total_weight += fraction
# Per-layer power contribution layer_watts = power_mult * GPU_TDP_WATTS * fraction per_layer_thermal[layer_type] = { "precision": precision, "power_multiplier": power_mult, "estimated_watts": round(layer_watts, 1), "pct_of_total_power": round(power_mult * fraction * 100, 1), }
avg_power_ratio = weighted_power / max(total_weight, 0.001)
# Estimate actual power draw under sustained training load estimated_watts = avg_power_ratio * GPU_TDP_WATTS * SUSTAINED_LOAD_FACTOR
# Estimate junction temperature estimated_temp = ambient_temp_c + (estimated_watts * THERMAL_RESISTANCE_C_PER_W)
# Memory density thermal contribution mem_bytes = sum( total_params * layer_distribution.get(lt, 0) * BYTES_PER_PARAM.get(precision_strategy.get(lt, "FP32"), 4) for lt in layer_distribution ) mem_per_gpu_gb = (mem_bytes / 1e9) / max(num_gpus, 1) mem_utilization = mem_per_gpu_gb / gpu_memory_gb
# Higher memory utilization = more heat from HBM3 activity thermal_mem_factor = 1.0 + (mem_utilization * MEM_THERMAL_COEFFICIENT) estimated_temp *= thermal_mem_factor
# Thermal risk classification if estimated_temp >= SHUTDOWN_THRESHOLD_C: thermal_risk = "SHUTDOWN" risk_score = 0.01 recommendation = "CRITICAL: Reduce precision complexity or add GPUs immediately" elif estimated_temp >= THROTTLE_THRESHOLD_C: thermal_risk = "THROTTLING" overshoot = (estimated_temp - THROTTLE_THRESHOLD_C) / ( SHUTDOWN_THRESHOLD_C - THROTTLE_THRESHOLD_C ) risk_score = max(0.10, 0.50 - overshoot * 0.40) recommendation = "WARNING: GPU will throttle, reducing training throughput" elif estimated_temp >= THROTTLE_THRESHOLD_C - 10: thermal_risk = "HIGH" risk_score = 0.65 recommendation = "CAUTION: Approaching thermal limits under sustained load" elif estimated_temp >= 60: thermal_risk = "MODERATE" risk_score = 0.80 recommendation = "OK: Normal operating temperature for sustained workload" else: thermal_risk = "OPTIMAL" risk_score = 0.95 recommendation = "EXCELLENT: Well within thermal envelope"
# Thermal headroom headroom_c = THROTTLE_THRESHOLD_C - estimated_temp headroom_pct = (headroom_c / (THROTTLE_THRESHOLD_C - ambient_temp_c)) * 100
return { "estimated_junction_temp_c": round(estimated_temp, 1), "estimated_power_watts": round(estimated_watts, 0), "power_ratio_vs_fp32": round(avg_power_ratio, 3), "thermal_risk": thermal_risk, "risk_score": round(max(0.01, min(0.99, risk_score)), 3), "recommendation": recommendation, "mem_per_gpu_gb": round(mem_per_gpu_gb, 2), "mem_utilization_pct": round(mem_utilization * 100, 1), "thermal_headroom_c": round(headroom_c, 1), "thermal_headroom_pct": round(headroom_pct, 1), "per_layer_thermal": per_layer_thermal, "ambient_temp_c": ambient_temp_c, "throttle_threshold_c": THROTTLE_THRESHOLD_C, "shutdown_threshold_c": SHUTDOWN_THRESHOLD_C, }12 unmodified lines1314151617188 unmodified lines27282930313233343536373821 unmodified lines6061626364656667686970717273749 unmodified lines84858687888990919293949596973 unmodified lines1011021031041051061071 unmodified line10911011111211311411510 unmodified lines1261271281291301311321331343 unmodified lines1381391401411421438 unmodified lines15215315415515615715815916016116216316416540 unmodified lines20620720820921021121221321421534 unmodified lines2502512522532542552561 unmodified line2582592602612622632642652663 unmodified lines27027127227327427527627727827928029 unmodified lines31031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734812 unmodified linesimport osimport reimport jsonimport httpxfrom datetime import datetime, timezonefrom openai import OpenAI8 unmodified linesHF_TOKEN = os.getenv("HF_TOKEN")if HF_TOKEN is None:raise ValueError("HF_TOKEN environment variable is required")ENV_URL = os.getenv("ENV_URL", "http://localhost:7860")FLEET_URL = f"{ENV_URL}/fleet"client = OpenAI(api_key=HF_TOKEN, base_url=API_BASE_URL)def clamp_reward(r: float) -> float:21 unmodified linesRULES:- embedding: ALWAYS FP32 (FP8 crashes, BF16 is risky)- output: ALWAYS FP32 (loss computation needs full precision)- ffn: FP8 is ideal (2.5x speedup, safe for FFN layers)- attention: BF16 is optimal (1.85x speedup)- layernorm: BF16 is bestConsider your model's priority level — higher priority models may justify using more memory.Consider how much memory other agents have already used.RESPOND WITH ONLY valid JSON:{"precision_strategy": {"embedding": "FP32", "attention": "BF16", "ffn": "FP8", "layernorm": "BF16", "output": "FP32"}, "reasoning": "brief explanation considering fleet context"}""","fleet_oversight": """You are a Fleet AI Oversight Agent monitoring multiple neural network training runs simultaneously.You see loss trajectories from ALL models in the cluster at once.9 unmodified linesDETECTION RULES:1. Look for None/null values in any model's loss window → that's a NaN crash, flag it immediately2. Look for sudden spikes (>100x previous value) that don't recover3. Check each model's precision_config: FP8 on embedding or output = HIGH RISK4. A spike that recovers within a few steps is NORMAL — do NOT flag5. If all models look healthy, continue_monitoringWhen flagging:- flagged_model: which model_id is crashing (e.g., "model_b")- flagged_step: the training step where the first anomaly appeared- root_cause: the precision+layer combo causing the issue (e.g., "fp8 embedding underflow in model_b")RESPOND WITH ONLY valid JSON:{"action_type": "continue_monitoring|flag_instability", "analysis": "what you observe across all models", "flagged_model": null|"model_id", "flagged_step": null|integer, "root_cause": null|"description"}""",3 unmodified linesYou must divide a shared GPU cluster among competing models, considering:1. Each model's parameter count (bigger models need more GPUs for memory)2. Priority levels (higher priority = should get proportionally more resources)3. Precision strategies (aggressive precision like FP8 reduces memory → fewer GPUs needed)4. Total cluster utilization (unused GPUs = wasted money)RULES:1 unmodified line- Total GPUs assigned cannot exceed cluster total- Each model's memory usage must fit in its allocated GPU memory- Higher priority models should generally get more resources- Use efficient precision (FP8 for FFN, BF16 for attention) to minimize memory per modelSTRATEGY:- Iteration 1: Allocate proportionally to param count × priority. Use optimal precision.10 unmodified lines3. VERIFY: Confirm the recovery plan is sound and describe post-recovery monitoringPHASE 1 - DIAGNOSE: Look at the loss trajectory around the crash point. Check the precision config for dangerous combinations (FP8 on embedding/output, FP16 on output).RESPOND WITH: {"diagnosed_model": "model_id", "root_cause": "description of what caused the crash", "reasoning": "your analysis"}PHASE 2 - REALLOCATE: Propose a new precision strategy that fixes the crash cause. Key: switch any dangerous precision to a safe alternative (embedding→FP32, output→FP32).RESPOND WITH: {"new_precision_strategy": {"embedding": "FP32", ...}, "reasoning": "what you changed and why"}PHASE 3 - VERIFY: Explain why the new config is safe and describe your monitoring plan.3 unmodified linesdef call_llm(system_prompt: str, observation: dict, conversation_history: list = None, task_id: str = None) -> dict:"""Call the LLM with the observation and return parsed JSON action."""messages = [{"role": "system", "content": system_prompt}]if conversation_history:8 unmodified linescurrent_api_key = os.getenv("HF_TOKEN")if task_id in ["fleet_oversight", "fleet_resource"] or "groq.com" in current_base_url:current_model = "llama-3.3-70b-versatile"current_base_url = "https://api.groq.com/openai/v1"current_api_key = os.getenv("GROQ_API_KEY")if not current_api_key:raise ValueError(f"Required API key not found in environment for {current_base_url}")local_client = OpenAI(api_key=current_api_key, base_url=current_base_url)try:response = local_client.chat.completions.create(40 unmodified lines"""Run a complete fleet task episode."""system_prompt = FLEET_PROMPTS[task_id]conversation_history = []# Reset fleet environmenttry:res = httpx.post(f"{FLEET_URL}/reset", json={"task_id": task_id})obs = res.json()["observation"]except Exception as e:print(f"Error connecting to fleet env: {e}", flush=True)34 unmodified lines# Send action to fleet environmenttry:step_res = httpx.post(f"{FLEET_URL}/step", json={"action": action})data = step_res.json()reward = clamp_reward(data["reward"]["score"])1 unmodified linedone = data["done"]obs = data.get("observation", None)# Log step-by-step metrics to MongoDB Time Series collectiontry:from mongodb_metrics import log_step_metricscluster_info = obs.get("cluster", {}) if obs else {}model_info = obs.get("your_model", {}) if obs else {}mem_used = cluster_info.get("memory_used_gb")3 unmodified linesif therm is None:therm = model_info.get("thermal_risk", "UNKNOWN")pwr = cluster_info.get("power_util", cluster_info.get("estimated_power_pct", 0.0))m_id = model_info.get("model_id", MODEL_NAME)log_step_metrics(task_id=task_id,model_id=m_id,step=steps,reward=reward,memory_used_gb=mem_used,29 unmodified linesprint(f"[FLEET END] task={task_id} score={score:.3f} steps={steps} success={success}", flush=True)print(f" rewards=[{rewards_str}]", flush=True)# Log run telemetry to MongoDB runs collectionmongo_uri = os.getenv("MONGO_URI")if mongo_uri:try:from pymongo import MongoClientfrom datetime import datetimeclient_mongo = MongoClient(mongo_uri, serverSelectionTimeoutMS=2000)db_mongo = client_mongo["libratio"]runs_col = db_mongo["runs"]runs_col.insert_one({"task_id": task_id,"model_name": MODEL_NAME,"score": score,"steps": steps,"success": success,"rewards": rewards_list,"timestamp": datetime.now(timezone.utc)})print("[OK] Logged run telemetry to MongoDB Atlas ('runs' collection)")except Exception as e:print(f"[WARN] Could not log telemetry to MongoDB: {e}")return score, stepsdef main():"""Run all fleet tasks or a specific one."""# Initialize MongoDB Time Series metrics collectiontry:from mongodb_metrics import create_metrics_timeseries_collectioncreate_metrics_timeseries_collection()except Exception as e:print(f"[WARN] Failed to initialize Time Series metrics: {e}")task_id = os.environ.get("TASK_ID")12 unmodified lines131415161718198 unmodified lines28293031323334353637383940414243444546474849505152535455565758596021 unmodified lines8283848586878889909192939495969798991001011021039 unmodified lines1131141151161171181191201211221231241251263 unmodified lines1301311321331341351361 unmodified line13813914014114214314414510 unmodified lines1561571581591601611621631641653 unmodified lines1691701711721731741751761771781791801811821831841858 unmodified lines19419519619719819920020120220320420520620740 unmodified lines24824925025125225325425525625725825926026126226326434 unmodified lines2993003013023033043053063073083093103111 unmodified line3133143153163173183193203213 unmodified lines32532632732832933033133233333429 unmodified lines36436536636736836937037137237337437537637737837938038138238338438538638712 unmodified linesimport osimport reimport jsonimport uuidimport httpxfrom datetime import datetime, timezonefrom openai import OpenAI8 unmodified linesHF_TOKEN = os.getenv("HF_TOKEN")if HF_TOKEN is None:if "huggingface.co" in API_BASE_URL:raise ValueError("HF_TOKEN environment variable is required when using Hugging Face endpoints")else:HF_TOKEN = "not-needed"ENV_URL = os.getenv("ENV_URL", "http://localhost:7860")FLEET_URL = f"{ENV_URL}/fleet"_client_cache = {}def _get_openai_client(api_key: str, base_url: str) -> OpenAI:key = (base_url, api_key)if key not in _client_cache:_client_cache[key] = OpenAI(api_key=api_key, base_url=base_url)return _client_cache[key]# Local Arm64 Inference Engine ConfigurationUSE_LOCAL_ARM_ENGINE = os.getenv("USE_LOCAL_ARM_ENGINE", "False") == "True"local_arm_engine = Noneif USE_LOCAL_ARM_ENGINE:try:from environment.local_arm_engine import LocalArmInferenceEnginelocal_arm_engine = LocalArmInferenceEngine()except Exception as e:print(f"[WARN] Failed to initialize LocalArmInferenceEngine: {e}")def clamp_reward(r: float) -> float:21 unmodified linesRULES:- embedding: ALWAYS FP32 (FP8 crashes, BF16 is risky)- output: ALWAYS FP32 (loss computation needs full precision)- ffn: FP8 is ideal on NVIDIA/AMD (2.5x speedup). However, FP8 is UNSUPPORTED on Google TPU v5p (will cause crash). Use INT8 instead for FFN layers when running on TPU.- attention: BF16 is optimal (1.85x speedup)- layernorm: BF16 is bestHARDWARE ADAPTATIONS:- Inspect 'cluster.vendor', 'cluster.hardware_profile', and 'available_precisions' in the state.- Choose ONLY from 'available_precisions' for each layer. Using an unsupported precision will result in a critical score of 0.01.- Google TPU (google_tpu_v5p): Does NOT support FP8. Use INT8 for FFN, BF16 for attention/layernorm.- AMD GPU (amd_mi300x): Has 192GB VRAM. If memory pressure is low, you can safely use BF16 for wider layers to guarantee training stability, but still select from available_precisions.- NVIDIA GPU (nvidia_h100): Supports FP8. Use FP8 for FFN, BF16 for attention/layernorm.Consider your model's priority level — higher priority models may justify using more memory.Consider how much memory other agents have already used.RESPOND WITH ONLY valid JSON:{"precision_strategy": {"embedding": "FP32", "attention": "BF16", "ffn": "FP8" (or "INT8" on TPU), "layernorm": "BF16", "output": "FP32"}, "reasoning": "brief explanation considering hardware and fleet context"}""","fleet_oversight": """You are a Fleet AI Oversight Agent monitoring multiple neural network training runs simultaneously.You see loss trajectories from ALL models in the cluster at once.9 unmodified linesDETECTION RULES:1. Look for None/null values in any model's loss window → that's a NaN crash, flag it immediately2. Look for sudden spikes (>100x previous value) that don't recover3. Check each model's precision_config: FP8 on embedding or output = HIGH RISK. Also, if running on Google TPU (google_tpu_v5p), using FP8 on ANY layer is UNSUPPORTED and causes an immediate crash.4. A spike that recovers within a few steps is NORMAL — do NOT flag5. If all models look healthy, continue_monitoringWhen flagging:- flagged_model: which model_id is crashing (e.g., "model_b")- flagged_step: the training step where the first anomaly appeared- root_cause: the precision+layer combo causing the issue (e.g., "fp8 embedding underflow in model_b" or "unsupported fp8 usage on TPU in model_b")RESPOND WITH ONLY valid JSON:{"action_type": "continue_monitoring|flag_instability", "analysis": "what you observe across all models", "flagged_model": null|"model_id", "flagged_step": null|integer, "root_cause": null|"description"}""",3 unmodified linesYou must divide a shared GPU cluster among competing models, considering:1. Each model's parameter count (bigger models need more GPUs for memory)2. Priority levels (higher priority = should get proportionally more resources)3. Precision strategies (aggressive precision like FP8 or INT8 reduces memory → fewer GPUs needed)4. Total cluster utilization (unused GPUs = wasted money)RULES:1 unmodified line- Total GPUs assigned cannot exceed cluster total- Each model's memory usage must fit in its allocated GPU memory- Higher priority models should generally get more resources- Use efficient precision (FP8 for NVIDIA/AMD, INT8 for TPU for FFN, BF16 for attention) to minimize memory per model. Do not allocate FP8 on Google TPU clusters.- Respect the active hardware limits (e.g., AMD MI300X offers 192GB memory per GPU, NVIDIA H100 offers 80GB, Google TPU v5p offers 95GB).STRATEGY:- Iteration 1: Allocate proportionally to param count × priority. Use optimal precision.10 unmodified lines3. VERIFY: Confirm the recovery plan is sound and describe post-recovery monitoringPHASE 1 - DIAGNOSE: Look at the loss trajectory around the crash point. Check the precision config for dangerous combinations (FP8 on embedding/output, FP16 on output).Note: If running on Google TPU (google_tpu_v5p), check if any layer was using FP8 (which is completely unsupported and triggers immediate crash).RESPOND WITH: {"diagnosed_model": "model_id", "root_cause": "description of what caused the crash", "reasoning": "your analysis"}PHASE 2 - REALLOCATE: Propose a new precision strategy that fixes the crash cause. Key: switch any dangerous or unsupported precision to a safe alternative (embedding→FP32, output→FP32, and TPU FP8→INT8 or BF16).RESPOND WITH: {"new_precision_strategy": {"embedding": "FP32", ...}, "reasoning": "what you changed and why"}PHASE 3 - VERIFY: Explain why the new config is safe and describe your monitoring plan.3 unmodified linesdef call_llm(system_prompt: str, observation: dict, conversation_history: list = None, task_id: str = None) -> dict:"""Call the LLM with the observation and return parsed JSON action."""# Route to local Arm64 inference engine if configuredif USE_LOCAL_ARM_ENGINE and local_arm_engine:history_context = ""if conversation_history:history_context = "\nConversation History:\n" + "\n".join(f"{m['role']}: {m['content']}" for m in conversation_history) + "\n"user_msg = f"{history_context}Current environment state:\n{json.dumps(observation, indent=2, default=str)}\n\nProvide your action as JSON."action = local_arm_engine.generate_json(system_prompt, user_msg)if action:return actionmessages = [{"role": "system", "content": system_prompt}]if conversation_history:8 unmodified linescurrent_api_key = os.getenv("HF_TOKEN")if task_id in ["fleet_oversight", "fleet_resource"] or "groq.com" in current_base_url:current_model = os.environ.get("MODEL_NAME", "llama-3.3-70b-versatile")current_base_url = "https://api.groq.com/openai/v1"current_api_key = os.getenv("GROQ_API_KEY")if not current_api_key:raise ValueError(f"Required API key not found in environment for {current_base_url}")local_client = _get_openai_client(current_api_key, current_base_url)try:response = local_client.chat.completions.create(40 unmodified lines"""Run a complete fleet task episode."""system_prompt = FLEET_PROMPTS[task_id]conversation_history = []session_headers = {"X-Session-ID": f"inf-{uuid.uuid4().hex}"}# Reset fleet environmenttry:res = httpx.post(f"{FLEET_URL}/reset",json={"task_id": task_id},headers=session_headers,timeout=30.0,)res.raise_for_status()obs = res.json()["observation"]except Exception as e:print(f"Error connecting to fleet env: {e}", flush=True)34 unmodified lines# Send action to fleet environmenttry:step_res = httpx.post(f"{FLEET_URL}/step",json={"action": action},headers=session_headers,timeout=30.0,)step_res.raise_for_status()data = step_res.json()reward = clamp_reward(data["reward"]["score"])1 unmodified linedone = data["done"]obs = data.get("observation", None)# Log step-by-step metrics to AWS DynamoDB (using MODEL_NAME so SRE trace lookup matches runs)try:from environment.aws_database import log_step_metricscluster_info = obs.get("cluster", {}) if obs else {}model_info = obs.get("your_model", {}) if obs else {}mem_used = cluster_info.get("memory_used_gb")3 unmodified linesif therm is None:therm = model_info.get("thermal_risk", "UNKNOWN")pwr = cluster_info.get("power_util", cluster_info.get("estimated_power_pct", 0.0))log_step_metrics(task_id=task_id,model_id=MODEL_NAME,step=steps,reward=reward,memory_used_gb=mem_used,29 unmodified linesprint(f"[FLEET END] task={task_id} score={score:.3f} steps={steps} success={success}", flush=True)print(f" rewards=[{rewards_str}]", flush=True)# Log run telemetry to AWS DynamoDBtry:from environment.aws_database import log_run_telemetrylog_run_telemetry(task_id, MODEL_NAME, score, steps, success, rewards_list)except Exception as e:print(f"[WARN] Could not log telemetry to AWS: {e}")return score, stepsdef main():"""Run all fleet tasks or a specific one."""# Initialize AWS DynamoDB Tablestry:from environment.aws_database import create_aws_tablescreate_aws_tables()except Exception as e:print(f"[WARN] Failed to initialize AWS tables: {e}")task_id = os.environ.get("TASK_ID")
13 unmodified lines141516171819405 unmodified lines42542642742842943043143243346 unmodified lines48048148248348448548648748813 unmodified linesconst baselineData = [0.1];const $ = (id) => document.getElementById(id);const taskSelect = $("taskSelect");const resetBtn = $("resetBtn");405 unmodified linestry {const res = await fetch("/fleet/reset", {method: "POST", headers: { "Content-Type": "application/json" },body: JSON.stringify({ task_id: taskSelect.value })});const data = await res.json();currentObs = data.observation || data;46 unmodified lines}const res = await fetch("/fleet/step", {method: "POST", headers: { "Content-Type": "application/json" },body: JSON.stringify({ action })});const data = await res.json();currentObs = data.observation || {};stepCount++;13 unmodified lines141516171819202122405 unmodified lines42842943043143243343443543643743846 unmodified lines48548648748848949049149249349449513 unmodified linesconst baselineData = [0.1];const $ = (id) => document.getElementById(id);const TAB_SESSION_ID = (typeof crypto !== "undefined" && crypto.randomUUID)? crypto.randomUUID(): `tab-${Date.now()}-${Math.random().toString(16).slice(2)}`;const taskSelect = $("taskSelect");const resetBtn = $("resetBtn");405 unmodified linestry {const res = await fetch("/fleet/reset", {method: "POST",headers: { "Content-Type": "application/json", "X-Session-ID": TAB_SESSION_ID },body: JSON.stringify({ task_id: taskSelect.value })});if (!res.ok) throw new Error(`HTTP ${res.status}`);const data = await res.json();currentObs = data.observation || data;46 unmodified lines}const res = await fetch("/fleet/step", {method: "POST",headers: { "Content-Type": "application/json", "X-Session-ID": TAB_SESSION_ID },body: JSON.stringify({ action })});if (!res.ok) throw new Error(`HTTP ${res.status}`);const data = await res.json();currentObs = data.observation || {};stepCount++;
4 unmodified lines567891033 unmodified lines444546474849505152535455565758596061626364656610 unmodified lines77787980818214 unmodified lines97989910010110210310410510610710810911011111211311 unmodified lines12512612712812913031 unmodified lines16216316416516616716841 unmodified lines2102112122134 unmodified linesbatch evaluation and built-in performance instrumentation."""from __future__ import annotationsimport time, statisticsfrom typing import Any, Dict, List, Optional33 unmodified linestotal_mem = cluster.get("total_memory_gb", 640)n_models = state.get("num_models", 1)strategy = action.get("precision_strategy", {})vals = list(strategy.values())if vals and all(v == "FP8" for v in vals):return {"score": 0.01, "feedback": "IRD: All-FP8 crash", "details": {"ird_violation": True}}if vals and all(v == "FP32" for v in vals):return {"score": 0.01, "feedback": "IRD: All-FP32 waste", "details": {"ird_violation": True}}if not strategy:return {"score": 0.01, "feedback": "IRD: Empty strategy", "details": {"ird_violation": True}}metrics = compute_training_cost(total_params=params, precision_strategy=strategy, layer_distribution=layer_dist)n_gpus = max(1, cluster.get("total_gpus", 8) // max(n_models, 1))hw = compute_hardware_safety(total_params=params, precision_strategy=strategy, layer_distribution=layer_dist, num_gpus=n_gpus, gpu_memory_gb=cluster.get("gpu_memory_gb", 80.0))layer_scores = {}for lt in layer_dist:p = strategy.get(lt, "FP32")ls, lf = score_precision_layer(lt, p)layer_scores[lt] = {"precision": p, "score": ls}avg = sum(v["score"] for v in layer_scores.values()) / max(len(layer_scores), 1)10 unmodified lines}class ThermalKernel(KernelModule):"""Thermal-aware workload placement evaluation (NVIDIA H100 SXM5 specs)."""name = "thermal"14 unmodified linesif not strategy:return {"score": 0.01, "feedback": "No strategy for thermal eval", "details": {}}wp, tw = 0.0, 0.0for lt, frac in layer_dist.items():p = strategy.get(lt, "FP32")wp += POWER_DRAW_MULTIPLIER.get(p, 1.0) * fractw += fracavg_pr = wp / max(tw, 0.001)watts = avg_pr * GPU_TDP_WATTS * self.SUSTAINEDtemp = self.AMBIENT_C + watts * self.THERMAL_Rmem_bytes = sum(params * layer_dist.get(lt, 0) * BYTES_PER_PARAM.get(strategy.get(lt, "FP32"), 4) for lt in layer_dist)mem_util = (mem_bytes / 1e9) / max(n_gpus, 1) / cluster.get("gpu_memory_gb", 80.0)temp *= 1.0 + mem_util * 0.05if temp >= self.SHUTDOWN_C:11 unmodified linesreturn {"score": _clamp(score),"feedback": f"thermal={temp:.1f}C {watts:.0f}W risk={risk}","details": {"temp_c": round(temp, 1), "watts": round(watts, 0), "power_ratio": round(avg_pr, 3), "risk": risk, "mem_util": round(mem_util, 3)},}31 unmodified linesself.weights = {k: v / t for k, v in active.items()}self._eval_count = 0self._total_ns = 0self._latencies = []def evaluate(self, state: dict, action: dict) -> dict:start = time.perf_counter_ns()41 unmodified linesdef reset_stats(self):self._eval_count = 0self._total_ns = 0self._latencies = []4 unmodified lines56789101133 unmodified lines4546474849505152535455565758596061626364656667686970717210 unmodified lines8384858687888914 unmodified lines10410510610710810911011111211311411511611711811912012112212312412512612712812911 unmodified lines14114214314414514614731 unmodified lines17918018118218318418541 unmodified lines2272282292304 unmodified linesbatch evaluation and built-in performance instrumentation."""from __future__ import annotationsfrom collections import dequeimport time, statisticsfrom typing import Any, Dict, List, Optional33 unmodified linestotal_mem = cluster.get("total_memory_gb", 640)n_models = state.get("num_models", 1)strategy = action.get("precision_strategy", {})# Load active hardware profile namehw_profile = cluster.get("hardware_profile", state.get("hardware_profile", "nvidia_h100"))vals = list(strategy.values())if vals and all(v in ("FP8", "INT8") for v in vals):return {"score": 0.01, "feedback": "IRD: All-FP8/INT8 crash", "details": {"ird_violation": True}}if vals and all(v == "FP32" for v in vals):return {"score": 0.01, "feedback": "IRD: All-FP32 waste", "details": {"ird_violation": True}}if not strategy:return {"score": 0.01, "feedback": "IRD: Empty strategy", "details": {"ird_violation": True}}metrics = compute_training_cost(total_params=params, precision_strategy=strategy, layer_distribution=layer_dist, hardware_profile=hw_profile)if metrics.get("unsupported_precisions"):return {"score": 0.01, "feedback": f"UNSUPPORTED precision on {hw_profile}", "details": {"unsupported": metrics["unsupported_precisions"], "ird_violation": False}}n_gpus = max(1, cluster.get("total_gpus", 8) // max(n_models, 1))hw = compute_hardware_safety(total_params=params, precision_strategy=strategy, layer_distribution=layer_dist, num_gpus=n_gpus, gpu_memory_gb=cluster.get("gpu_memory_gb", 80.0), hardware_profile=hw_profile)layer_scores = {}for lt in layer_dist:p = strategy.get(lt, "FP32")ls, lf = score_precision_layer(lt, p, hardware_profile=hw_profile)layer_scores[lt] = {"precision": p, "score": ls}avg = sum(v["score"] for v in layer_scores.values()) / max(len(layer_scores), 1)10 unmodified lines}class ThermalKernel(KernelModule):"""Thermal-aware workload placement evaluation (NVIDIA H100 SXM5 specs)."""name = "thermal"14 unmodified linesif not strategy:return {"score": 0.01, "feedback": "No strategy for thermal eval", "details": {}}# Load active hardware profilehw_profile = cluster.get("hardware_profile", state.get("hardware_profile", "nvidia_h100"))from environment.physics_model import HARDWARE_PROFILESprofile = HARDWARE_PROFILES.get(hw_profile, HARDWARE_PROFILES["nvidia_h100"])power_draw_map = profile["power_draw_multipliers"]tdp_watts = profile["tdp_watts"]bytes_map = profile["bytes_per_param"]gpu_mem_limit = cluster.get("gpu_memory_gb", profile["gpu_memory_gb"])wp, tw = 0.0, 0.0for lt, frac in layer_dist.items():p = strategy.get(lt, "FP32")wp += power_draw_map.get(p, 1.0) * fractw += fracavg_pr = wp / max(tw, 0.001)watts = avg_pr * tdp_watts * self.SUSTAINEDtemp = self.AMBIENT_C + watts * self.THERMAL_Rmem_bytes = sum(params * layer_dist.get(lt, 0) * bytes_map.get(strategy.get(lt, "FP32"), 4) for lt in layer_dist)mem_util = (mem_bytes / 1e9) / max(n_gpus, 1) / gpu_mem_limittemp *= 1.0 + mem_util * 0.05if temp >= self.SHUTDOWN_C:11 unmodified linesreturn {"score": _clamp(score),"feedback": f"thermal={temp:.1f}C {watts:.0f}W risk={risk}","details": {"temp_c": round(temp, 1), "watts": round(watts, 0), "power_ratio": round(avg_pr, 3), "risk": risk, "mem_util": round(mem_util, 3)},}31 unmodified linesself.weights = {k: v / t for k, v in active.items()}self._eval_count = 0self._total_ns = 0self._latencies = deque(maxlen=10_000)def evaluate(self, state: dict, action: dict) -> dict:start = time.perf_counter_ns()41 unmodified linesdef reset_stats(self):self._eval_count = 0self._total_ns = 0self._latencies = deque(maxlen=10_000)
11 unmodified lines1213141516175 unmodified lines232425262728293031323334353610 unmodified lines47484950515253545556575859603 unmodified lines64656667686970717273747517 unmodified lines939495969798998 unmodified lines10810911011111211311411511611711811911 unmodified lines"""import osfrom datetime import datetime, timezonefrom pymongo import MongoClientimport certifi5 unmodified linesDB_NAME = "libratio"METRICS_COLLECTION = "gpu_telemetry_metrics"def get_mongo_client():if not MONGO_URI:return Nonetry:return MongoClient(MONGO_URI, tlsCAFile=certifi.where(), serverSelectionTimeoutMS=30000)except Exception:return Nonedef create_metrics_timeseries_collection() -> bool:10 unmodified lines# Check if the collection already existsif METRICS_COLLECTION in db.list_collection_names():print(f" [INFO] Time Series collection '{METRICS_COLLECTION}' already exists.")client.close()return Truetry:# Create a native time-series collection in MongoDB# - timeField: "timestamp" (specifies the date field in each document)# - metaField: "metadata" (specifies the tags used to categorize the metrics)# - granularity: "seconds" (tells MongoDB to optimize for sub-minute updates)db.create_collection(METRICS_COLLECTION,timeseries={3 unmodified lines})print(f" [OK] Created native MongoDB Time Series collection '{METRICS_COLLECTION}'!")client.close()return Trueexcept Exception as e:print(f" [WARN] Failed to create native Time Series collection: {e}")print(" (Usually means the database user does not have 'createCollection' permission)")client.close()return False17 unmodified linesdb = client[DB_NAME]col = db[METRICS_COLLECTION]# Structure for Time Series: timeField (timestamp) + metaField (metadata) + measurementsmetric_doc = {"timestamp": datetime.now(timezone.utc),"metadata": {8 unmodified lines}col.insert_one(metric_doc)client.close()return Trueexcept Exception:# Fail silently to prevent telemetry logging from crashing the main inference runif client:client.close()return False11 unmodified lines121314151617185 unmodified lines24252627282930313233343536373839404142434445464710 unmodified lines5859606162636465663 unmodified lines7071727374757677787917 unmodified lines9798991001011028 unmodified lines11111211311411511611711811 unmodified lines"""import osimport threadingfrom datetime import datetime, timezonefrom pymongo import MongoClientimport certifi5 unmodified linesDB_NAME = "libratio"METRICS_COLLECTION = "gpu_telemetry_metrics"_metrics_client = None_metrics_lock = threading.Lock()def get_mongo_client():"""Return a shared, pooled MongoClient with a 5s selection timeout."""global _metrics_clientif not MONGO_URI:return Nonewith _metrics_lock:if _metrics_client is None:try:_metrics_client = MongoClient(MONGO_URI, tlsCAFile=certifi.where(), serverSelectionTimeoutMS=5000)except Exception:return Nonereturn _metrics_clientdef create_metrics_timeseries_collection() -> bool:10 unmodified lines# Check if the collection already existsif METRICS_COLLECTION in db.list_collection_names():print(f" [INFO] Time Series collection '{METRICS_COLLECTION}' already exists.")return Truetry:db.create_collection(METRICS_COLLECTION,timeseries={3 unmodified lines})print(f" [OK] Created native MongoDB Time Series collection '{METRICS_COLLECTION}'!")return Trueexcept Exception as e:print(f" [WARN] Failed to create native Time Series collection: {e}")print(" (Usually means the database user does not have 'createCollection' permission)")return False17 unmodified linesdb = client[DB_NAME]col = db[METRICS_COLLECTION]metric_doc = {"timestamp": datetime.now(timezone.utc),"metadata": {8 unmodified lines}col.insert_one(metric_doc)return Trueexcept Exception:return False
63 unmodified lines6465666768697071723 unmodified lines76777879808182838485868763 unmodified linesfor change in stream:run_doc = change["fullDocument"]task_id = run_doc.get("task_id")model_name = run_doc.get("model_name")score = run_doc.get("score", 0.0)success = run_doc.get("success", False)rewards = run_doc.get("rewards", [])print(f"[*] NEW RUN DETECTED: Task={task_id} | Model={model_name} | Score={score:.3f} | Success={success}")3 unmodified linesprint(" [WARNING] Run did not meet performance threshold. Generating SRE incident report...")# Query Time Series collection for this specific run's telemetry stepsmetrics_cursor = metrics_col.find({"metadata.task_id": task_id,"metadata.model_id": model_name,}).sort("timestamp", 1)steps_history = list(metrics_cursor)print(f" Retrieved {len(steps_history)} metrics steps from Time Series collection.")63 unmodified lines6465666768697071723 unmodified lines767778798081828384858663 unmodified linesfor change in stream:run_doc = change["fullDocument"]task_id = run_doc.get("task_id")model_name = run_doc.get("model_name") or run_doc.get("model")score = float(run_doc.get("score", 0.0))success = run_doc.get("success", score >= 0.60)rewards = run_doc.get("rewards", [])print(f"[*] NEW RUN DETECTED: Task={task_id} | Model={model_name} | Score={score:.3f} | Success={success}")3 unmodified linesprint(" [WARNING] Run did not meet performance threshold. Generating SRE incident report...")# Query Time Series collection for this specific run's telemetry stepsmodel_candidates = [m for m in (model_name, run_doc.get("model_id")) if m]ts_filter = {"metadata.task_id": task_id}if model_candidates:ts_filter["metadata.model_id"] = {"$in": model_candidates}metrics_cursor = metrics_col.find(ts_filter).sort("timestamp", 1)steps_history = list(metrics_cursor)print(f" Retrieved {len(steps_history)} metrics steps from Time Series collection.")
23 unmodified lines242526272829303132335 unmodified lines39404142434445464748495051136 unmodified lines18818919019119219319419519623 unmodified linesimport osimport jsonfrom typing import Optionalfrom google import genaifrom google.genai import types as genai_typesfrom dotenv import load_dotenvload_dotenv()# ── Gemini Embedding Setup ──5 unmodified lines_GEMINI_AVAILABLE = False_gemini_client = Noneif GEMINI_API_KEY:try:_gemini_client = genai.Client(api_key=GEMINI_API_KEY)_GEMINI_AVAILABLE = Trueexcept Exception as e:print(f"[WARN] Gemini embedding setup failed: {e}. Using fallback embedder.")else:print("[WARN] GEMINI_API_KEY not set. Using fallback embedder (no semantic search).")136 unmodified linesreturn generate_embedding(text, task_type="RETRIEVAL_DOCUMENT")def embed_query(live_state: dict) -> list[float]:"""Generate an embedding vector for a live cluster state query."""text = live_state_to_query_text(live_state)return generate_embedding(text, task_type="RETRIEVAL_QUERY")23 unmodified lines24252627282930313233343536373839405 unmodified lines46474849505152535455565758136 unmodified lines19519619719819920020120220320420520620720823 unmodified linesimport osimport jsonfrom typing import Optionalfrom dotenv import load_dotenvtry:from google import genaifrom google.genai import types as genai_types_GENAI_SDK_AVAILABLE = Trueexcept ImportError:genai = Nonegenai_types = None_GENAI_SDK_AVAILABLE = Falseload_dotenv()# ── Gemini Embedding Setup ──5 unmodified lines_GEMINI_AVAILABLE = False_gemini_client = Noneif GEMINI_API_KEY and _GENAI_SDK_AVAILABLE:try:_gemini_client = genai.Client(api_key=GEMINI_API_KEY)_GEMINI_AVAILABLE = Trueexcept Exception as e:print(f"[WARN] Gemini embedding setup failed: {e}. Using fallback embedder.")elif not GEMINI_API_KEY:print("[WARN] GEMINI_API_KEY not set. Using fallback embedder (no semantic search).")136 unmodified linesreturn generate_embedding(text, task_type="RETRIEVAL_DOCUMENT")def embed_query(live_state: dict | str) -> list[float]:"""Generate an embedding vector for a live cluster state dict or raw search query."""if isinstance(live_state, str):text = live_stateelif isinstance(live_state, dict) and "query" in live_state and len(live_state) == 1:text = str(live_state["query"])else:text = live_state_to_query_text(live_state)return generate_embedding(text, task_type="RETRIEVAL_QUERY")
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457"""QLoRA + GRPO Training Pipeline for Libratio Fleet
This implements the training flow described in the hackathon seminar:1. Load base model (LLaMA-3.1-8B) in 4-bit QLoRA via Unsloth2. Attach LoRA adapters to attention + FFN layers3. Run GRPO episodes against Libratio Fleet environment4. Train LoRA weights on reward signal5. After training: merge LoRA → 16-bit full model6. Export merged model for vLLM inference
Key insights from Daniel's session:- "Weight sharing: launch vLLM instance and suck the weights out into Unsloth land to cut memory usage"- "If you do QLoRA during training, you should also use QLoRA for inference"- "After finishing RL process we can take weights and merge it back to 16-bit"
Usage (Colab with T4/A100): !pip install unsloth trl peft bitsandbytes accelerate %run qlora_grpo_training.py"""
import osimport sysimport jsonimport randomfrom typing import Dict, List, Any
# ── Step 0: Add project root to path ──────────────────────────────────────────PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))sys.path.insert(0, PROJECT_ROOT)
from environment.fleet_env import FleetEnvironment
# ══════════════════════════════════════════════════════════════════════════════# STEP 1: Load Model in QLoRA via Unsloth# ══════════════════════════════════════════════════════════════════════════════
def load_model_qlora(model_name: str = "unsloth/Meta-Llama-3.1-8B-Instruct-bnb-4bit"): """Load model in 4-bit QLoRA using Unsloth for maximum memory efficiency.
Unsloth automatically patches the model for 2x faster training and uses ~60% less VRAM than standard QLoRA implementations. """ try: from unsloth import FastLanguageModel except ImportError: print("Installing unsloth...") os.system("pip install -q unsloth") from unsloth import FastLanguageModel
model, tokenizer = FastLanguageModel.from_pretrained( model_name=model_name, max_seq_length=2048, load_in_4bit=True, # QLoRA: 4-bit base model dtype=None, # Auto-detect (float16 for T4, bfloat16 for A100) )
# Attach LoRA adapters — target attention + FFN (the layers GRPO will tune) model = FastLanguageModel.get_peft_model( model, r=16, # LoRA rank (16 is good balance of capacity vs memory) lora_alpha=32, # Scaling factor (alpha/r = 2 is standard) lora_dropout=0.05, target_modules=[ # Which layers get LoRA adapters "q_proj", "k_proj", "v_proj", "o_proj", # Attention "gate_proj", "up_proj", "down_proj", # FFN (SwiGLU) ], bias="none", use_gradient_checkpointing="unsloth", # 60% less VRAM random_state=42, )
print(f"[QLoRA] Model loaded: {model_name}") print(f"[QLoRA] Trainable params: {model.print_trainable_parameters()}") return model, tokenizer
# ══════════════════════════════════════════════════════════════════════════════# STEP 2: Define Reward Functions Against Fleet Environment# ══════════════════════════════════════════════════════════════════════════════
# System prompt for the model during trainingFLEET_SYSTEM_PROMPT = """You are an ML infrastructure engineer managing GPU fleet precision.Given a model's specs and cluster state, assign optimal precision to each layer.
RULES:- embedding: ALWAYS FP32 (FP8 crashes)- output: ALWAYS FP32 (loss needs full precision)- ffn: FP8 is ideal (2.5x speedup)- attention: BF16 is optimal (1.85x speedup)- layernorm: BF16 is best
RESPOND WITH ONLY valid JSON:{"precision_strategy": {"embedding": "FP32", "attention": "BF16", "ffn": "FP8", "layernorm": "BF16", "output": "FP32"}, "reasoning": "explanation"}"""
def _build_meta_header(task_id: str, scenario_id: str) -> str: """Attach deterministic metadata for reward reconstruction.""" return f"[META] task_id={task_id}; scenario_id={scenario_id}"
def _extract_meta_from_prompt(prompt: Any, fallback_task_id: str) -> Dict[str, str]: """Extract task/scenario metadata from a prompt string.""" text = str(prompt) marker = "[META]" task_id = fallback_task_id scenario_id = None
for line in text.splitlines(): line = line.strip() if not line.startswith(marker): continue payload = line[len(marker):].strip() for chunk in payload.split(";"): if "=" not in chunk: continue key, val = chunk.split("=", 1) key = key.strip() val = val.strip() if key == "task_id" and val: task_id = val elif key == "scenario_id" and val: scenario_id = val break
return {"task_id": task_id, "scenario_id": scenario_id}
def _extract_completion_text(completion: Any) -> str: """Handle different TRL completion payload formats safely.""" if isinstance(completion, list): if not completion: return "" last = completion[-1] if isinstance(last, dict): return str(last.get("content", "")) return str(last) return str(completion)
def build_training_prompts(task_id: str = "fleet_precision", num_prompts: int = 100): """Generate training prompts by resetting the fleet environment multiple times.
Each prompt is a unique scenario observation that the model must respond to. The diversity of scenarios (7 fleet configs × random selection) ensures the model generalizes rather than memorizing. """ env = FleetEnvironment() prompts = []
for _ in range(num_prompts): obs = env.reset(task_id) scenario_id = obs.get("scenario_id", "") meta_header = _build_meta_header(task_id=task_id, scenario_id=scenario_id) prompt = f"Current environment state:\n{json.dumps(obs, indent=2, default=str)}\n\nProvide your action as JSON."
prompts.append({ "prompt": f"{meta_header}\n{prompt}", "system": FLEET_SYSTEM_PROMPT, })
print(f"[DATA] Generated {len(prompts)} training prompts for {task_id}") return prompts
def fleet_reward_function(completions: List[str], prompts: List[str], task_id: str = "fleet_precision") -> List[float]: """Score model completions against the Libratio Fleet environment.
This is the reward function for GRPO. For each completion: 1. Parse the JSON action from the model's output 2. Reset a fresh environment episode 3. Step with the parsed action 4. Return the environment's reward score
The environment already implements: - Physics-based scoring (per-layer precision quality) - Difference Rewards (counterfactual fleet contribution) - Inverse Reward Design (degenerate action penalty) - Hardware safety checks (thermal/memory/power) """ rewards = []
for completion, prompt in zip(completions, prompts): reward = 0.05 try: # Parse JSON from completion content = _extract_completion_text(completion).strip() if "```json" in content: content = content.split("```json")[1].split("```")[0].strip() elif "```" in content: content = content.split("```")[1].split("```")[0].strip()
action = json.loads(content)
# Reconstruct the exact scenario from prompt metadata for deterministic credit assignment meta = _extract_meta_from_prompt(prompt, fallback_task_id=task_id) env = FleetEnvironment() env.reset(meta["task_id"], scenario_id=meta["scenario_id"]) result = env.step(action) reward = float(result["reward"]["score"])
# Bonus for valid JSON (format compliance) reward += 0.05
except (json.JSONDecodeError, KeyError, TypeError, ValueError): # Invalid JSON or missing fields = low reward reward = 0.05 # Not 0 — GRPO needs non-zero for gradient signal except Exception as e: print(f"[REWARD WARNING] Unexpected reward error: {type(e).__name__}: {e}") reward = 0.05
rewards.append(max(0.01, min(0.99, reward)))
return rewards
# ══════════════════════════════════════════════════════════════════════════════# STEP 3: GRPO Training Loop# ══════════════════════════════════════════════════════════════════════════════
def run_grpo_training( model, tokenizer, task_id: str = "fleet_precision", num_prompts: int = 200, num_epochs: int = 3, batch_size: int = 1, num_generations: int = 4, # G in GRPO — number of completions per prompt learning_rate: float = 2e-5, output_dir: str = "./results/qlora_grpo",): """Run GRPO training using TRL's GRPOTrainer.
GRPO (Group Relative Policy Optimization) works by: 1. For each prompt, generate G completions 2. Score all G with the reward function 3. Use the relative ranking within the group as the advantage 4. Update policy towards better-ranked completions
This is more stable than PPO because it doesn't need a value function, and the group-relative scoring is self-normalizing. """ try: from trl import GRPOTrainer, GRPOConfig from datasets import Dataset except ImportError: print("Installing trl and datasets...") os.system("pip install -q trl datasets") from trl import GRPOTrainer, GRPOConfig from datasets import Dataset
# Generate training data training_prompts = build_training_prompts(task_id, num_prompts)
# Convert to dataset format dataset = Dataset.from_list([ {"prompt": p["system"] + "\n\n" + p["prompt"]} for p in training_prompts ])
# GRPO config config = GRPOConfig( output_dir=output_dir, num_generations=num_generations, per_device_train_batch_size=batch_size, gradient_accumulation_steps=4, learning_rate=learning_rate, num_train_epochs=num_epochs, max_steps=500, # Cap at 500 steps max_completion_length=512, logging_steps=10, save_steps=50, warmup_ratio=0.1, bf16=True, # Use BF16 for training (A100/H100) report_to="none", # Disable wandb for hackathon )
# Define reward function wrapper for GRPO def reward_fn(completions, prompts): return fleet_reward_function(completions, prompts, task_id)
# Initialize trainer trainer = GRPOTrainer( model=model, tokenizer=tokenizer, config=config, train_dataset=dataset, reward_funcs=[reward_fn], )
print(f"\n{'='*60}") print(f"[GRPO] Starting training: {num_prompts} prompts × {num_epochs} epochs") print(f"[GRPO] Generations per prompt: {num_generations}") print(f"[GRPO] Learning rate: {learning_rate}") print(f"{'='*60}\n")
# Train! trainer.train()
# Save LoRA adapter trainer.save_model(output_dir) print(f"\n[GRPO] LoRA adapter saved to {output_dir}")
return trainer
# ══════════════════════════════════════════════════════════════════════════════# STEP 4: Merge LoRA Weights → 16-bit Full Model# ══════════════════════════════════════════════════════════════════════════════
def merge_to_16bit(model, tokenizer, output_path: str = "./results/libratio-fleet-merged-16bit"): """Merge QLoRA adapter weights into the base model at 16-bit precision.
This is the key step Daniel described: "After finishing RL process we do not necessarily need QLoRA — we can take weights and merge it back to 16-bit model"
The merged model can then be served with vLLM for fast inference without needing the LoRA adapter at runtime. """ try: from unsloth import FastLanguageModel except ImportError: print("Unsloth not available, using manual merge...") model = model.merge_and_unload() model.save_pretrained(output_path) tokenizer.save_pretrained(output_path) print(f"[MERGE] Saved merged 16-bit model to {output_path}") return
# Unsloth-optimized merge (handles dtype conversion properly) model.save_pretrained_merged( output_path, tokenizer, save_method="merged_16bit", # Merge LoRA → 16-bit )
print(f"[MERGE] Saved merged 16-bit model to {output_path}") print(f"[MERGE] Model is now ready for vLLM inference")
# ══════════════════════════════════════════════════════════════════════════════# STEP 5: Verify with Inference# ══════════════════════════════════════════════════════════════════════════════
def verify_merged_model(model_path: str = "./results/libratio-fleet-merged-16bit"): """Quick verification that the merged model produces valid fleet actions.
Optional: if vLLM is available, test with vLLM for production-speed inference. """ env = FleetEnvironment() obs = env.reset("fleet_precision")
prompt = f"{FLEET_SYSTEM_PROMPT}\n\nCurrent environment state:\n{json.dumps(obs, indent=2, default=str)}\n\nProvide your action as JSON."
try: from vllm import LLM, SamplingParams llm = LLM(model_path) params = SamplingParams(temperature=0.2, max_tokens=512) outputs = llm.generate([prompt], params) response = outputs[0].outputs[0].text print(f"[VERIFY] vLLM response: {response[:200]}...") except ImportError: print("[VERIFY] vLLM not available — using transformers for verification") from transformers import AutoTokenizer, AutoModelForCausalLM tokenizer = AutoTokenizer.from_pretrained(model_path) model = AutoModelForCausalLM.from_pretrained(model_path) inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=2048) outputs = model.generate(**inputs, max_new_tokens=512, temperature=0.2) response = tokenizer.decode(outputs[0][inputs.input_ids.shape[1]:], skip_special_tokens=True) print(f"[VERIFY] Transformers response: {response[:200]}...")
# Try to parse and score try: if "```json" in response: content = response.split("```json")[1].split("```")[0].strip() else: content = response.strip() action = json.loads(content) result = env.step(action) print(f"[VERIFY] Score: {result['reward']['score']:.3f}") print(f"[VERIFY] Feedback: {result['reward']['feedback']}") except Exception as e: print(f"[VERIFY] Could not parse response: {e}")
# ══════════════════════════════════════════════════════════════════════════════# MAIN: Full Pipeline# ══════════════════════════════════════════════════════════════════════════════
def main(): """Run the complete QLoRA → GRPO → Merge pipeline.""" import argparse parser = argparse.ArgumentParser(description="QLoRA + GRPO Training for Libratio Fleet") parser.add_argument("--model", default="unsloth/Meta-Llama-3.1-8B-Instruct-bnb-4bit") parser.add_argument("--task", default="fleet_precision") parser.add_argument("--prompts", type=int, default=200) parser.add_argument("--epochs", type=int, default=3) parser.add_argument("--generations", type=int, default=4) parser.add_argument("--lr", type=float, default=2e-5) parser.add_argument("--output", default="./results/qlora_grpo") parser.add_argument("--merge-output", default="./results/libratio-fleet-merged-16bit") parser.add_argument("--skip-merge", action="store_true") parser.add_argument("--skip-verify", action="store_true") args = parser.parse_args()
print("=" * 60) print("LIBRATIO FLEET — QLoRA + GRPO Training Pipeline") print("=" * 60) print(f"Base model: {args.model}") print(f"Task: {args.task}") print(f"Prompts: {args.prompts}") print(f"Epochs: {args.epochs}") print(f"Generations: {args.generations}") print(f"Learning rate: {args.lr}") print("=" * 60)
# Step 1: Load in QLoRA print("\n[STEP 1/4] Loading model in QLoRA...") model, tokenizer = load_model_qlora(args.model)
# Step 2-3: GRPO Training print("\n[STEP 2/4] Running GRPO training...") trainer = run_grpo_training( model, tokenizer, task_id=args.task, num_prompts=args.prompts, num_epochs=args.epochs, num_generations=args.generations, learning_rate=args.lr, output_dir=args.output, )
# Step 4: Merge to 16-bit if not args.skip_merge: print("\n[STEP 3/4] Merging LoRA → 16-bit...") merge_to_16bit(model, tokenizer, args.merge_output) else: print("\n[STEP 3/4] Skipping merge (--skip-merge)")
# Step 5: Verify if not args.skip_verify and not args.skip_merge: print("\n[STEP 4/4] Verifying merged model...") verify_merged_model(args.merge_output) else: print("\n[STEP 4/4] Skipping verification")
print("\n" + "=" * 60) print("PIPELINE COMPLETE") print("=" * 60)
if __name__ == "__main__": main()15 unmodified lines1617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162631 unmodified line65666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072 unmodified lines21021121221321421521617 unmodified lines2342352362372382392402412422432442 unmodified lines2472482492502512522532542552562572582592602612622637 unmodified lines2712722732742752763 unmodified lines2802812822832842851 unmodified line28728828929029129229329429529629729829930015 unmodified linesAtlas Vector Search → basic $match aggregation → local JSON file"""import osimport jsonimport requestsfrom pymongo import MongoClientfrom dotenv import load_dotenv# Vector Search module (Gemini embeddings + Atlas $vectorSearch)try:from mongodb_vector import (embed_query,vector_search_similar_trajectories,format_vector_results_as_context,hybrid_search_similar_trajectories,format_hybrid_results_as_context,_GEMINI_AVAILABLE,)VECTOR_SEARCH_AVAILABLE = Trueexcept ImportError:VECTOR_SEARCH_AVAILABLE = False_GEMINI_AVAILABLE = Falseprint("[WARN] mongodb_vector module not found. Using basic $match fallback.")load_dotenv()# ── MongoDB Setup (with local fallback) ──MONGO_URI = os.getenv("MONGO_URI")USE_LOCAL_FALLBACK = Falselocal_data = Nonetry:import certifimongo_client = MongoClient(MONGO_URI, tlsCAFile=certifi.where(), serverSelectionTimeoutMS=5000)db = mongo_client["libratio"]trajectories_col = db["trajectories"]# Quick connectivity checkmongo_client.admin.command("ping")print("[OK] Connected to MongoDB Atlas")except Exception as e:print(f"[WARN] MongoDB unreachable ({type(e).__name__}). Using local JSON fallback.")USE_LOCAL_FALLBACK = Truewith open("synthetic_trajectories.json", "r") as f:local_data = json.load(f)# ── LLM Setup ──HF_TOKEN = os.getenv("HF_TOKEN")GROQ_API_KEY = os.getenv("GROQ_API_KEY")1 unmodified lineMODEL_NAME = os.getenv("MODEL_NAME", "llama-3.1-8b-instant")HF_MODEL_URL = os.getenv("HF_MODEL_URL", "https://router.huggingface.co/v1/chat/completions")HF_MODEL_NAME = os.getenv("HF_MODEL_NAME", "SnippyCodes/libratio-fleet-llama3-grpo:featherless-ai")def retrieve_historical_context(live_state: dict) -> str:"""RAG Retrieval Step: Find semantically similar historical trajectories.Retrieval hierarchy:1. MongoDB Atlas Vector Search ($vectorSearch) — semantic similarity via Gemini embeddings"Find past situations that FEEL like this one" — best results2. MongoDB basic aggregation ($match) — exact field matching fallback"Find past situations with exactly these field values"3. Local JSON file — offline fallback when MongoDB is unreachableArgs:live_state: Dict with current cluster state (model_name, memory_used_gb,cluster_capacity_gb, thermal_risk, power_util, etc.)Returns:Formatted string of historical context for the LLM prompt."""thermal_risk = live_state.get("thermal_risk", "HIGH")memory_used = live_state.get("memory_used_gb", 0)memory_gb_threshold = memory_used * 0.8print(f"[*] RAG SEARCH: Finding semantically similar past crashes...")print(f" Query: {live_state.get('model_name', '?')} | "f"{memory_used}GB VRAM | thermal={thermal_risk}")# ── Path 1: Atlas Hybrid Search (Vector + Full-Text Search with RRF) (best) ──if VECTOR_SEARCH_AVAILABLE and not USE_LOCAL_FALLBACK:try:model_name = live_state.get("model_name", "")text_query = f"{model_name} {thermal_risk} thermal crash"results = hybrid_search_similar_trajectories(collection=trajectories_col,query_text=text_query,live_state=live_state,top_k=5,)if results:return format_hybrid_results_as_context(results)else:print(" [WARN] Hybrid search returned no results. Falling back to vector search.")results = vector_search_similar_trajectories(collection=trajectories_col,live_state=live_state,top_k=5,)if results:return format_vector_results_as_context(results)except Exception as e:print(f" [WARN] Hybrid search error ({type(e).__name__}): {e}")print(" Falling back to basic $match query...")# ── Path 2: Basic MongoDB $match (fallback) ──if not USE_LOCAL_FALLBACK:try:print(" (Source: MongoDB Atlas — basic $match aggregation)")pipeline = [{"$match": {"$or": [{"thermal_risk": thermal_risk},{"memory_used_gb": {"$gt": memory_gb_threshold}},{"outcome": {"$ne": "SUCCESS"}}]}},{"$sort": {"memory_used_gb": -1}},{"$limit": 5},{"$project": {"embedding": 0, "_id": 0}},]results = list(trajectories_col.aggregate(pipeline))if results:context_lines = ["HISTORICAL CRASH DATA FROM DATABASE ($match fallback):"]for t in results:line = (f"- Model: {t.get('model_name', t.get('model_id', '?'))} "f"({t.get('total_params_b', '?')}B params) | "f"Outcome: {t['outcome']} | "f"Strategy: {t['precision_strategy']} | "f"VRAM: {t['memory_used_gb']}GB | "f"Thermal: {t['thermal_risk']} | "f"Power: {t.get('estimated_power_pct', '?')}%")if t.get("failure_reason"):line += f" | Cause: {t['failure_reason']}"context_lines.append(line)return "\n".join(context_lines)except Exception as e:print(f" [WARN] $match query failed ({type(e).__name__}): {e}")# ── Path 3: Local JSON fallback ──print(" (Source: local synthetic_trajectories.json — offline fallback)")results = []for episode in (local_data or []):for t in episode.get("trajectories", []):if (t.get("thermal_risk") == thermal_risk ort.get("memory_used_gb", 0) > memory_gb_threshold ort.get("outcome") != "SUCCESS"):results.append(t)if len(results) >= 5:breakif len(results) >= 5:breakif not results:return "No similar historical trajectories found in database."context_lines = ["HISTORICAL CRASH DATA (local JSON fallback):"]for t in results:line = (f"- Model: {t.get('model_name', t.get('model_id', '?'))} "f"({t.get('total_params_b', '?')}B params) | "f"Outcome: {t.get('outcome', 'UNKNOWN')} | "f"Strategy: {t.get('precision_strategy', {})} | "f"VRAM: {t.get('memory_used_gb', '?')}GB | "f"Thermal: {t.get('thermal_risk', '?')} | "f"Power: {t.get('estimated_power_pct', '?')}%")if t.get("failure_reason"):line += f" | Cause: {t['failure_reason']}"context_lines.append(line)return "\n".join(context_lines)def call_llm(prompt):"""Call the custom HuggingFace model first.If HF API is blocked or model is loading, fallback to Groq."""system_prompt = "You are the Libratio Fleet Commander, an expert MLOps SRE agent. You prevent GPU cluster crashes by analyzing historical failure data and recommending optimal mixed-precision strategies. Always output valid JSON."# Attempt 1: Hugging Face Custom Fine-Tuned Modelprint(f" [Routing inference to custom model: {HF_MODEL_NAME}]")try:hf_headers = {"Authorization": f"Bearer {HF_TOKEN}","Content-Type": "application/json",}hf_payload = {"model": HF_MODEL_NAME,"messages": [{"role": "system", "content": system_prompt},2 unmodified lines"temperature": 0.3,"max_tokens": 800}hf_res = requests.post(HF_MODEL_URL, headers=hf_headers, json=hf_payload, timeout=30)hf_res.raise_for_status()result = hf_res.json()if "choices" in result and len(result["choices"]) > 0:17 unmodified lines"max_tokens": 800,}response = requests.post(f"{GROQ_API_BASE}/chat/completions",headers=groq_headers,json=groq_payload,timeout=30,)response.raise_for_status()return response.json()["choices"][0]["message"]["content"]2 unmodified linesdef predict_and_recover(live_state):"""The Predictive MLOps Agent.1. Retrieves semantically similar historical crashes from MongoDB Atlasusing Vector Search (Gemini embeddings → $vectorSearch)2. Sends the retrieved context + live state to LLM for reasoning3. Outputs a preventive precision strategy"""retrieval_mode = ("Atlas Vector Search (Gemini embeddings)" if (VECTOR_SEARCH_AVAILABLE and _GEMINI_AVAILABLE and not USE_LOCAL_FALLBACK)else "MongoDB $match" if not USE_LOCAL_FALLBACKelse "Local JSON Fallback")print("\n" + "=" * 60)print(" LIBRATIO PREDICTIVE MLOPS AGENT")print(f" Retrieval: {retrieval_mode}")7 unmodified linesprint(historical_context)# ── Step 2: Build prompt with live state + history ──prompt = f"""CURRENT LIVE CLUSTER STATE (DANGER):- Model: {live_state['model_name']}3 unmodified lines- Memory Utilization: {round(100 * live_state['memory_used_gb'] / live_state['cluster_capacity_gb'], 1)}%- Thermal Risk: {live_state['thermal_risk']}- Power Utilization: {live_state['power_util']}%{historical_context}1 unmodified lineRules:- Available layers: embedding, attention, ffn, layernorm, output- Available precisions: FP32, BF16, FP16, FP8- Embedding and output layers should NEVER use FP8 (causes numerical instability)- FFN layers are the safest target for FP8 optimization- The goal is to REDUCE memory and thermal pressure while maintaining training stabilityRespond with a JSON object containing:1. "precision_strategy": the recommended precision per layer2. "reasoning": a short explanation citing the historical data3. "expected_outcome": what you predict will happen after this change"""15 unmodified lines1617181920212223242526272829303132331 unmodified line353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879802 unmodified lines8384858687888917 unmodified lines1071081091101111121131141151161172 unmodified lines1201211221231241251261271281291301311321331341351361371381391401411427 unmodified lines1501511521531541551561571581593 unmodified lines1631641651661671681691701 unmodified line17217317417517617717817918018118218318418515 unmodified linesAtlas Vector Search → basic $match aggregation → local JSON file"""import osimport httpxfrom dotenv import load_dotenv# AWS Database module (Amazon Aurora pgvector RAG + local fallback)try:from environment.aws_database import retrieve_historical_context_awsexcept ImportError:def retrieve_historical_context_aws(live_state: dict, top_k: int = 5) -> str:return "No similar historical trajectories found (Import Error)."load_dotenv()# ── LLM Setup ──HF_TOKEN = os.getenv("HF_TOKEN")GROQ_API_KEY = os.getenv("GROQ_API_KEY")1 unmodified lineMODEL_NAME = os.getenv("MODEL_NAME", "llama-3.1-8b-instant")HF_MODEL_URL = os.getenv("HF_MODEL_URL", "https://router.huggingface.co/v1/chat/completions")HF_MODEL_NAME = os.getenv("HF_MODEL_NAME", "SnippyCodes/libratio-fleet-llama3-grpo:featherless-ai")# Local Arm64 Inference Engine ConfigurationUSE_LOCAL_ARM_ENGINE = os.getenv("USE_LOCAL_ARM_ENGINE", "False") == "True"local_arm_engine = Noneif USE_LOCAL_ARM_ENGINE:try:from environment.local_arm_engine import LocalArmInferenceEnginelocal_arm_engine = LocalArmInferenceEngine()except Exception as e:print(f"[WARN] Failed to initialize LocalArmInferenceEngine in predictive_agent: {e}")def retrieve_historical_context(live_state: dict) -> str:"""RAG Retrieval Step: Find semantically similar historical trajectoriesusing the AWS Database Adapter."""return retrieve_historical_context_aws(live_state, top_k=5)def call_llm(prompt):"""Call the local inference engine if configured. Otherwise fall back to thecustom HuggingFace model first, then to Groq."""system_prompt = "You are the Libratio Fleet Commander, an expert MLOps SRE agent. You prevent GPU cluster crashes by analyzing historical failure data and recommending optimal mixed-precision strategies. Always output valid JSON."if USE_LOCAL_ARM_ENGINE and local_arm_engine:print(" [Routing inference to Local Arm64 GGUF Engine]")raw_output = local_arm_engine.generate(system_prompt, prompt)if raw_output:return raw_output# Attempt 1: Hugging Face Custom Fine-Tuned Modelprint(f" [Routing inference to custom model: {HF_MODEL_NAME}]")try:hf_headers = {"Content-Type": "application/json",}if HF_TOKEN:hf_headers["Authorization"] = f"Bearer {HF_TOKEN}"hf_payload = {"model": HF_MODEL_NAME,"messages": [{"role": "system", "content": system_prompt},2 unmodified lines"temperature": 0.3,"max_tokens": 800}hf_res = httpx.post(HF_MODEL_URL, headers=hf_headers, json=hf_payload, timeout=30.0)hf_res.raise_for_status()result = hf_res.json()if "choices" in result and len(result["choices"]) > 0:17 unmodified lines"max_tokens": 800,}response = httpx.post(f"{GROQ_API_BASE}/chat/completions",headers=groq_headers,json=groq_payload,timeout=30.0,)response.raise_for_status()return response.json()["choices"][0]["message"]["content"]2 unmodified linesdef predict_and_recover(live_state):"""The Predictive MLOps Agent.1. Retrieves semantically similar historical crashes from Amazon Aurora PostgreSQL(using pgvector similarity query) or Local JSON Fallback.2. Sends the retrieved context + live state to LLM for reasoning3. Outputs a preventive precision strategy"""try:from environment.aws_database import PSYCOPG2_AVAILABLE, AURORA_PG_HOSThas_aurora = bool(PSYCOPG2_AVAILABLE and AURORA_PG_HOST)except ImportError:has_aurora = Falseretrieval_mode = ("Amazon Aurora PostgreSQL (pgvector Search)" if has_auroraelse "Local JSON Fallback (pgvector simulation)")print("\n" + "=" * 60)print(" LIBRATIO PREDICTIVE MLOPS AGENT")print(f" Retrieval: {retrieval_mode}")7 unmodified linesprint(historical_context)# ── Step 2: Build prompt with live state + history ──hardware_profile = live_state.get('hardware_profile', 'nvidia_h100')vendor = live_state.get('vendor', 'NVIDIA')available_precisions = live_state.get('available_precisions', ['FP32', 'BF16', 'FP16', 'FP8'])prompt = f"""CURRENT LIVE CLUSTER STATE (DANGER):- Model: {live_state['model_name']}3 unmodified lines- Memory Utilization: {round(100 * live_state['memory_used_gb'] / live_state['cluster_capacity_gb'], 1)}%- Thermal Risk: {live_state['thermal_risk']}- Power Utilization: {live_state['power_util']}%- Hardware Profile: {hardware_profile} ({vendor})- Available Precisions on Hardware: {available_precisions}{historical_context}1 unmodified lineRules:- Available layers: embedding, attention, ffn, layernorm, output- Available precisions: MUST be chosen from the "Available Precisions on Hardware" list: {available_precisions}. Selecting an unsupported precision format will trigger a critical failure.- Embedding and output layers should NEVER use FP8 or INT8 (causes numerical instability).- FFN layers are the safest target for memory optimization (use FP8 if supported; if Google TPU is active, use INT8 instead of FP8 since FP8 is unsupported).- The goal is to REDUCE memory and thermal pressure while maintaining training stability.Respond with a JSON object containing:1. "precision_strategy": the recommended precision per layer (must conform to the available precisions on this hardware)2. "reasoning": a short explanation citing the historical data and hardware constraints3. "expected_outcome": what you predict will happen after this change"""
14 unmodified lines15161718192021222324252627282914 unmodified lines"numpy>=1.24.0","pyyaml>=6.0","httpx>=0.25.0","openai>=1.0.0","openenv-core>=0.2.0"][project.scripts]server = "server.app:main"[project.optional-dependencies]dev = ["pytest>=7.4.0","pytest-asyncio>=0.23.0"]14 unmodified lines15161718192021222324252627282930313233343536373814 unmodified lines"numpy>=1.24.0","pyyaml>=6.0","httpx>=0.25.0","python-dotenv>=1.0.0","pymongo[srv]>=4.6.0","certifi>=2023.7.22",][project.scripts]server = "server.app:main"[project.optional-dependencies]extras = ["openai>=1.0.0","google-genai>=1.0.0","google-adk>=0.5.0","mcp>=1.0.0","boto3>=1.34.0","psycopg2-binary>=2.9.9",]dev = ["pytest>=7.4.0","pytest-asyncio>=0.23.0",]
12345678910# Optional integrations, LLM inference, AWS adapters, Google ADK, and tests-r requirements.txtopenai>=1.0.0google-genai>=1.0.0google-adk>=0.5.0mcp>=1.0.0boto3>=1.34.0psycopg2-binary>=2.9.9pytest>=7.4.0pytest-asyncio>=0.23.0123456# Local development dependencies (including GGUF compiling)# Install via: pip install -r requirements-local.txt# To enable ARM NEON acceleration:# CMAKE_ARGS="-DLLAMA_NEON=ON -DLLAMA_F16C=ON -DLLAMA_AVX512=OFF" pip install --force-reinstall --no-cache-dir llama-cpp-python
llama-cpp-python>=0.2.5512345678910111213141516171819fastapi>=0.104.0uvicorn>=0.24.0pydantic>=2.5.0numpy>=1.24.0pyyaml>=6.0httpx>=0.25.0pytest>=7.4.0pytest-asyncio>=0.23.0openai>=1.0.0pymongo>=4.6.0pymongo[srv]>=4.6.0python-dotenv>=1.0.0certifi>=2023.7.22requests>=2.31.0google-genai>=1.0.0# Google ADK (Agent Development Kit) — Google Cloud Agent Builder integrationgoogle-adk>=0.5.0# MCP Python SDK — required for ADK MCPToolset + MongoDB MCP Server clientmcp>=1.0.012345678910# Core Hugging Face Space / FastAPI simulator runtime (kept minimal for cpu-basic scheduling)fastapi>=0.104.0uvicorn>=0.24.0pydantic>=2.5.0numpy>=1.24.0pyyaml>=6.0httpx>=0.25.0python-dotenv>=1.0.0pymongo[srv]>=4.6.0certifi>=2023.7.22
387 unmodified lines388389390391392393387 unmodified lines],"max_steps_per_task": 5,},}387 unmodified lines388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459387 unmodified lines],"max_steps_per_task": 5,},# Multi-Vendor Hardware: AMD Instinct MI300X (192GB HBM3 per GPU)"amd_mi300x_fleet": {"scenario_id": "amd_mi300x_fleet","description": "2 large models on 4 AMD MI300X GPUs (192GB VRAM each) — high memory capacity with FP8 support","cluster": {"hardware_profile": "amd_mi300x","vendor": "AMD","total_gpus": 4,"gpu_memory_gb": 192.0,"total_memory_gb": 768.0,"cost_per_gpu_hour_usd": 3.50,},"models": [{"model_id": "model_a","name": "LLaMA-3-70B","total_params": 70_000_000_000,"layer_distribution": DENSE_DISTRIBUTION,"priority": 2,"priority_reason": "Flagship 70B training on high-VRAM MI300X nodes",},{"model_id": "model_b","name": "Mixtral-8x7B","total_params": 46_000_000_000,"layer_distribution": MOE_DISTRIBUTION,"priority": 1,"priority_reason": "MoE training utilizing MI300X memory headroom",},],"max_steps_per_task": 5,},# Multi-Vendor Hardware: Google Cloud TPU v5p (95GB HBM, INT8 supported, FP8 unsupported)"google_tpu_fleet": {"scenario_id": "google_tpu_fleet","description": "2 models on 4 Google TPU v5p chips — INT8 supported, FP8 unsupported","cluster": {"hardware_profile": "google_tpu_v5p","vendor": "Google","total_gpus": 4,"gpu_memory_gb": 95.0,"total_memory_gb": 380.0,"cost_per_gpu_hour_usd": 2.20,},"models": [{"model_id": "model_a","name": "LLaMA-3-13B","total_params": 13_000_000_000,"layer_distribution": DENSE_DISTRIBUTION,"priority": 2,"priority_reason": "Primary TPU fine-tuning workload — must use INT8/BF16",},{"model_id": "model_b","name": "CodeLLaMA-7B","total_params": 7_000_000_000,"layer_distribution": CODE_DISTRIBUTION,"priority": 1,"priority_reason": "Code generation run on shared TPU slice",},],"max_steps_per_task": 5,},}
1234567891011121314151617181920212223242526272829303132333435363738394041424344454614 unmodified lines616263646566676828 unmodified lines9798991001011021031041051061071081091101111121131141151161171181191201211221231247 unmodified lines1321331341351361371381391401411421431441451461471481491501511521531541551561571586 unmodified lines1651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843855 unmodified lines3913923933943953963975 unmodified lines4034044054064074084097 unmodified lines4174184194204214224234244254264274284294304312 unmodified lines43443543643743843944044144244344444544644744844945045124 unmodified lines4764774784794804814824834844854864874884894904915 unmodified lines4974984995005015025035045057 unmodified lines5135145155165175185196 unmodified lines52652752852953053153253353453553653753810 unmodified lines5495505515525535545559 unmodified lines5655665675685695705712 unmodified lines5745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156161 unmodified line61861962062162262362462562662712 unmodified lines640641642643"""FastAPI application for Libratio Fleet OpenEnv.Includes API endpoints and a lightweight frontend for demos."""from pathlib import Pathfrom fastapi import FastAPIfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import FileResponsefrom fastapi.staticfiles import StaticFilesfrom typing import Listimport sys, osfrom pymongo import MongoClientimport certififrom dotenv import load_dotenvload_dotenv()sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))# ── ADK Agent (Google Cloud Agent Builder integration) ──try:from agent.adk_agent import run_fleet_task_with_adk, ADK_AVAILABLEexcept ImportError:ADK_AVAILABLE = Falseasync def run_fleet_task_with_adk(task_id: str = "fleet_precision"):return {"error": "google-adk not installed", "adk_available": False}MONGO_URI = os.getenv("MONGO_URI")DB_NAME = "libratio"from environment.fleet_env import FleetEnvironmentfrom server.models import (ResetRequest, ResetResponse, StepResponse, StateResponse,TaskDefinition, RewardPayload,)app = FastAPI(title="Libratio Fleet — Multi-Agent GPU Fleet Management",description="OpenEnv for multi-agent GPU cluster precision optimization and fleet oversight",version="3.0.0")# Allow browser frontends on any origin to call the APIapp.add_middleware(CORSMiddleware,allow_origins=["*"],14 unmodified linesapp.mount("/hf_graphs", StaticFiles(directory=str(HF_GRAPHS_DIR)), name="hf_graphs")# Multi-agent fleet environment (new)fleet_env = FleetEnvironment()def _clamp_score(raw_score) -> float:28 unmodified lines}# ═══════════════════════════════════════════════════════════# FLEET MODE — Multi-agent fleet endpoints# ═══════════════════════════════════════════════════════════@app.get("/fleet/tasks", response_model=List[TaskDefinition])def get_fleet_tasks() -> List[TaskDefinition]:return [TaskDefinition(**t) for t in fleet_env.TASK_DEFS]@app.post("/fleet/reset", response_model=ResetResponse)def reset_fleet(payload: dict = {}):task_id = payload.get("task_id", "fleet_precision")obs = fleet_env.reset(task_id)return ResetResponse(observation=obs)@app.post("/fleet/step", response_model=StepResponse)def step_fleet(payload: dict = {}):action = payload.get("action", payload)result = fleet_env.step(action)clamped_score = _clamp_score(result["reward"]["score"])return StepResponse(observation=result["observation"],7 unmodified lines@app.post("/fleet/state", response_model=StateResponse)def get_fleet_state():s = fleet_env.state()return StateResponse(**s)@app.get("/api/analytics")def get_fleet_analytics():"""Exposes real-time fleet analytics aggregated via MongoDB aggregation pipelines.Provides performance stats per task and compares avg scores per model."""if not MONGO_URI:return {"database_status": "not_configured", "error": "MONGO_URI not set in env"}client_mongo = Nonetry:client_mongo = MongoClient(MONGO_URI, tlsCAFile=certifi.where(), serverSelectionTimeoutMS=30000)db_mongo = client_mongo[DB_NAME]runs_col = db_mongo["runs"]# ── Pipeline 1: Task summary statistics ──pipeline_tasks = [{"$group": {6 unmodified lines"$cond": [{"$eq": ["$success", True]}, 1.0, 0.0]}},"total_runs": {"$sum": 1}}},{"$sort": {"avg_score": -1}}]task_stats = list(runs_col.aggregate(pipeline_tasks))# ── Pipeline 2: Model performance comparisons ──pipeline_models = [{"$group": {"_id": "$model_name","avg_score": {"$avg": "$score"},"total_runs": {"$sum": 1}}},{"$sort": {"avg_score": -1}}]model_stats = list(runs_col.aggregate(pipeline_models))# Format aggregation outputs into user-friendly statsformatted_tasks = []for t in task_stats:formatted_tasks.append({"task_id": t["_id"],"avg_score": round(t["avg_score"], 3),"max_score": round(t["max_score"], 3),"min_score": round(t["min_score"], 3),"success_rate_pct": round(t["success_rate"] * 100, 1),"total_runs": t["total_runs"]})formatted_models = []for m in model_stats:formatted_models.append({"model_name": m["_id"],"avg_score": round(m["avg_score"], 3),"total_runs": m["total_runs"]})return {"database_status": "connected","total_runs_logged": sum(t["total_runs"] for t in task_stats),"task_analytics": formatted_tasks,"model_analytics": formatted_models}except Exception as e:return {"database_status": "failed_connection","error": str(e)}finally:if client_mongo:client_mongo.close()@app.get("/api/search")def search_trajectories(query: str, type: str = "hybrid", limit: int = 5):"""Search historical trajectories using MongoDB Atlas Search.Supports 'text' (full-text search), 'vector' (semantic vector search),or 'hybrid' (combined RRF fusion)."""if not MONGO_URI:return {"error": "MONGO_URI not set in env"}client_mongo = Nonetry:client_mongo = MongoClient(MONGO_URI, tlsCAFile=certifi.where(), serverSelectionTimeoutMS=30000)db_mongo = client_mongo[DB_NAME]collection = db_mongo["trajectories"]if type == "text":from mongodb_vector import text_search_similar_trajectoriesresults = text_search_similar_trajectories(collection, query, top_k=limit)elif type == "vector":from mongodb_vector import generate_embeddingquery_vector = generate_embedding(query, task_type="RETRIEVAL_QUERY")pipeline = [{"$vectorSearch": {"index": "trajectory_vector_index","path": "embedding","queryVector": query_vector,"numCandidates": limit * 10,"limit": limit,}},{"$addFields": {"vector_score": {"$meta": "vectorSearchScore"}}},{"$project": {"embedding": 0}}]results = list(collection.aggregate(pipeline))for res in results:res["_id"] = str(res["_id"])else: # hybridfrom mongodb_vector import generate_embeddingquery_vector = generate_embedding(query, task_type="RETRIEVAL_QUERY")# Vector Search Pipelinevector_pipeline = [{"$vectorSearch": {"index": "trajectory_vector_index","path": "embedding","queryVector": query_vector,"numCandidates": limit * 10,"limit": limit * 2,}},{"$addFields": {"vector_score": {"$meta": "vectorSearchScore"}}},{"$project": {"embedding": 0}}]# Text Search Pipelinetext_pipeline = [{"$search": {"index": "trajectory_text_search_index","text": {"query": query,"path": ["embedding_source_text", "failure_reason", "model_name", "outcome"]}}},{"$addFields": {"search_score": {"$meta": "searchScore"}}},{"$limit": limit * 2},{"$project": {"embedding": 0}}]vector_results = list(collection.aggregate(vector_pipeline))text_results = list(collection.aggregate(text_pipeline))# RRF mergeK = 60rrf_scores = {}doc_map = {}for rank, doc in enumerate(vector_results):doc_id = str(doc["_id"])doc_map[doc_id] = docrrf_scores[doc_id] = rrf_scores.get(doc_id, 0.0) + (1.0 / (K + rank + 1))doc["vector_rank"] = rank + 1for rank, doc in enumerate(text_results):doc_id = str(doc["_id"])if doc_id not in doc_map:doc_map[doc_id] = docelse:if "search_score" in doc:doc_map[doc_id]["search_score"] = doc["search_score"]rrf_scores[doc_id] = rrf_scores.get(doc_id, 0.0) + (1.0 / (K + rank + 1))doc_map[doc_id]["text_rank"] = rank + 1sorted_ids = sorted(rrf_scores.keys(), key=lambda x: rrf_scores[x], reverse=True)results = []for doc_id in sorted_ids[:limit]:doc = doc_map[doc_id]doc["rrf_score"] = rrf_scores[doc_id]doc["_id"] = doc_idresults.append(doc)return {"status": "success", "query": query, "type": type, "count": len(results), "results": results}except Exception as e:return {"status": "error", "message": str(e)}finally:if client_mongo:client_mongo.close()# ═══════════════════════════════════════════════════════════# AGENTIC KERNEL — Live Performance Benchmarking# Proves the core Agentic Kernel thesis: pure-math physics# evaluation runs in microseconds, not the 100ms+ of Docker/VM# sandboxes. These endpoints let the frontend visualize this# in real time.# ═══════════════════════════════════════════════════════════@app.get("/kernel/benchmark")def kernel_benchmark():"""Run a live benchmark of the Agentic Kernel physics engine.Evaluates N trajectories and returns precise timing datato prove microsecond-latency evaluation."""import timeimport random as _rndfrom environment.physics_model import (compute_training_cost,compute_hardware_safety,score_precision_layer,)5 unmodified lines"layernorm": 0.05, "output": 0.10,}# --- Phase 1: Benchmark compute_training_cost ---start = time.perf_counter_ns()for _ in range(NUM_TRAJECTORIES):strategy = {l: _rnd.choice(precisions) for l in layers}5 unmodified lines)cost_ns = time.perf_counter_ns() - start# --- Phase 2: Benchmark hardware safety checks ---start = time.perf_counter_ns()for _ in range(NUM_TRAJECTORIES):strategy = {l: _rnd.choice(precisions) for l in layers}7 unmodified lines)safety_ns = time.perf_counter_ns() - start# --- Phase 3: Benchmark per-layer scoring ---start = time.perf_counter_ns()for _ in range(NUM_TRAJECTORIES):for l in layers:score_precision_layer(l, _rnd.choice(precisions))scoring_ns = time.perf_counter_ns() - start# --- Phase 4: Full environment reset+step cycle ---from environment.fleet_env import FleetEnvironmentbench_env = FleetEnvironment()start = time.perf_counter_ns()cycle_count = 2002 unmodified linesbench_env.step({"precision_strategy": {"embedding": "FP32", "attention": "BF16", "ffn": "FP8","layernorm": "BF16", "output": "FP32"},"reasoning": "benchmark"})env_ns = time.perf_counter_ns() - starttotal_ns = cost_ns + safety_ns + scoring_nsper_trajectory_us = (total_ns / NUM_TRAJECTORIES) / 1000# Docker/VM comparison (published industry data)docker_cold_start_ms = 150 # Typical Docker container cold startmicrovm_cold_start_ms = 125 # Firecracker MicroVMreturn {"kernel_version": "1.0.0",24 unmodified lines@app.get("/kernel/profile")def kernel_profile():"""Profile each kernel module (physics sub-system) individually.Returns per-module timing and a breakdown of what the kernel evaluates."""import timefrom environment.physics_model import (BYTES_PER_PARAM, STABILITY_SCORE, THROUGHPUT_MULTIPLIER,ACCURACY_PENALTY, POWER_DRAW_MULTIPLIER,compute_training_cost, compute_hardware_safety, score_precision_layer,compute_network_topology,)layers = ["embedding", "attention", "ffn", "layernorm", "output"]5 unmodified lines"embedding": "FP32", "attention": "BF16", "ffn": "FP8","layernorm": "BF16", "output": "FP32",}params = 7_000_000_000 # 7B model# Profile each functionmodules = {}start = time.perf_counter_ns()7 unmodified lines"cost_usd": result["cost_usd"],"estimated_stable": result["estimated_stable"],"accuracy_retention": result["accuracy_retention"],}}start = time.perf_counter_ns()6 unmodified lines"memory_utilization_pct": hw["memory_utilization_pct"],"thermal_risk": hw["thermal_risk"],"overall_safe": hw["overall_safe"],}}start = time.perf_counter_ns()layer_results = {}for l in layers:score, feedback = score_precision_layer(l, strategy.get(l, "FP32"))layer_results[l] = {"score": score, "precision": strategy.get(l, "FP32")}modules["scoring_kernel"] = {"latency_us": round((time.perf_counter_ns() - start) / 1000, 2),10 unmodified lines"topology": net["topology"],"effective_throughput_pct": net["effective_throughput_pct"],"bottleneck_risk": net["bottleneck_risk"],}}total_latency = sum(m["latency_us"] for m in modules.values())9 unmodified lines"stability_rules": sum(len(v) for v in STABILITY_SCORE.values()),"throughput_rules": sum(len(v) for v in THROUGHPUT_MULTIPLIER.values()),"source": "NVIDIA Transformer Engine + Micikevicius et al. 2018/2022",}}2 unmodified linesuvicorn.run("server.app:app", host="0.0.0.0", port=7860)# ═══════════════════════════════════════════════════════════════════════════# GOOGLE ADK AGENT ENDPOINTS# Demonstrates Google Cloud Agent Builder + MongoDB MCP integration# ═══════════════════════════════════════════════════════════════════════════@app.get("/adk/status")def adk_status():"""Check whether the Google ADK agent and MongoDB MCP server are available."""return {"adk_available": ADK_AVAILABLE,"mongodb_mcp": "enabled" if ADK_AVAILABLE else "requires google-adk and mcp packages","agent_model": os.getenv("ADK_MODEL", "gemini-2.0-flash"),"install_command": "pip install google-adk mcp" if not ADK_AVAILABLE else None,"description": "Google Cloud Agent Builder (ADK) + MongoDB MCP Server integration",}@app.post("/adk/run")async def run_adk_agent(payload: dict = {}):"""Run the Libratio Fleet Agent using Google ADK + MongoDB MCP Server.This is the core hackathon demo endpoint:- Uses Google ADK (Agent Development Kit) as the orchestration framework- Gemini 2.0 Flash as the reasoning model- MongoDB MCP Server as the partner superpower (tool calls via Model Context Protocol)- Fleet physics tools for environment interactionBody: {"task_id": "fleet_precision"}Valid task_ids: fleet_precision, fleet_oversight, fleet_resource, fleet_recovery"""if not ADK_AVAILABLE:return {"error": "Google ADK not installed","fix": "pip install google-adk mcp","adk_available": False,}1 unmodified linevalid_tasks = ["fleet_precision", "fleet_oversight", "fleet_resource", "fleet_recovery"]if task_id not in valid_tasks:return {"error": f"Invalid task_id. Choose from: {valid_tasks}"}try:import asyncioresult = await run_fleet_task_with_adk(task_id)return {"status": "completed",12 unmodified linesif __name__ == "__main__":main()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878814 unmodified lines10310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320428 unmodified lines2332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712727 unmodified lines2802812822832842852862872882892902912922932942952962972982993003013023036 unmodified lines3103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244255 unmodified lines4314324334344354365 unmodified lines4424434444454464477 unmodified lines4554564574584594604614624634644654662 unmodified lines46947047147247347447547647747847948048148248348448524 unmodified lines5105115125135145155165175185195205215225235245255265 unmodified lines5325335345355365375385397 unmodified lines5475485495505515525536 unmodified lines56056156256356456556656756856957057157210 unmodified lines5835845855865875885899 unmodified lines5996006016026036046052 unmodified lines6086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406411 unmodified line64364464564664764864965065112 unmodified lines664665666"""FastAPI application for Libratio Fleet OpenEnv.Includes per-session fleet isolation, rate limiting, optional API auth,and MongoDB Atlas analytics/search endpoints."""from collections import OrderedDict, dequefrom contextlib import asynccontextmanagerfrom pathlib import Pathfrom typing import Dict, List, Optionalimport osimport sysimport threadingimport timefrom dotenv import load_dotenvfrom fastapi import Depends, FastAPI, Header, HTTPException, Request, Responsefrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import FileResponsefrom fastapi.staticfiles import StaticFilesfrom pymongo import MongoClientimport certifiload_dotenv()sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))try:from agent.adk_agent import run_fleet_task_with_adk, ADK_AVAILABLEexcept ImportError:ADK_AVAILABLE = Falseasync def run_fleet_task_with_adk(task_id: str = "fleet_precision"):return {"error": "google-adk not installed", "adk_available": False}from environment.fleet_env import FleetEnvironmentfrom server.models import (ResetResponse,RewardPayload,StateResponse,StepResponse,TaskDefinition,)MONGO_URI = os.getenv("MONGO_URI")DB_NAME = "libratio"MAX_SESSIONS = 256SESSION_TTL_SECONDS = 3600RATE_LIMIT_WINDOW_SECONDS = 60_mongo_client: Optional[MongoClient] = None_mongo_lock = threading.Lock()def _get_mongo_client() -> Optional[MongoClient]:"""Return a shared, pooled MongoClient with short selection timeout."""global _mongo_clientif not MONGO_URI:return Nonewith _mongo_lock:if _mongo_client is None:_mongo_client = MongoClient(MONGO_URI,tlsCAFile=certifi.where(),serverSelectionTimeoutMS=5000,)return _mongo_client@asynccontextmanagerasync def lifespan(_app: FastAPI):yieldglobal _mongo_clientwith _mongo_lock:if _mongo_client is not None:_mongo_client.close()_mongo_client = Noneapp = FastAPI(title="Libratio Fleet — Multi-Agent GPU Fleet Management",description="OpenEnv for multi-agent GPU cluster precision optimization and fleet oversight",version="3.0.0",lifespan=lifespan,)app.add_middleware(CORSMiddleware,allow_origins=["*"],14 unmodified linesapp.mount("/hf_graphs", StaticFiles(directory=str(HF_GRAPHS_DIR)), name="hf_graphs")class _SessionStore:"""Thread-safe bounded LRU+TTL store isolating FleetEnvironment per caller."""def __init__(self, max_sessions: int = MAX_SESSIONS, ttl_seconds: int = SESSION_TTL_SECONDS):self.max_sessions = max_sessionsself.ttl_seconds = ttl_secondsself._lock = threading.Lock()self._sessions: OrderedDict[str, tuple[float, FleetEnvironment]] = OrderedDict()def get_or_create(self, session_id: str) -> FleetEnvironment:now = time.monotonic()with self._lock:expired = [sid for sid, (ts, _) in self._sessions.items() if now - ts > self.ttl_seconds]for sid in expired:del self._sessions[sid]if session_id in self._sessions:_, env = self._sessions.pop(session_id)self._sessions[session_id] = (now, env)return envwhile len(self._sessions) >= self.max_sessions:self._sessions.popitem(last=False)env = FleetEnvironment()self._sessions[session_id] = (now, env)return env_session_store = _SessionStore()fleet_env = _session_store.get_or_create("default")def _resolve_session_id(request: Request, payload: Optional[dict] = None) -> str:"""Extract session_id from body, header, or cookie; fall back to 'default'."""if isinstance(payload, dict) and payload.get("session_id"):return str(payload["session_id"])[:128]header_sid = request.headers.get("x-session-id")if header_sid:return header_sid[:128]cookie_sid = request.cookies.get("libratio_sid")if cookie_sid:return cookie_sid[:128]return "default"_rate_lock = threading.Lock()_rate_buckets: Dict[str, deque] = {}def _enforce_rate_limit(request: Request, bucket: str, max_calls: int = 20) -> None:"""Simple per-IP sliding-window rate limiter to protect heavy/paid endpoints."""client_ip = request.client.host if request.client else "unknown"key = f"{bucket}:{client_ip}"now = time.monotonic()with _rate_lock:dq = _rate_buckets.setdefault(key, deque())while dq and now - dq[0] > RATE_LIMIT_WINDOW_SECONDS:dq.popleft()if len(dq) >= max_calls:raise HTTPException(status_code=429, detail="Rate limit exceeded. Try again shortly.")dq.append(now)def _require_api_auth(authorization: Optional[str] = Header(default=None),x_api_key: Optional[str] = Header(default=None),allow_unconfigured: bool = False,) -> None:"""Protect costly/mutating endpoints with LIBRATIO_API_KEY when configured."""expected_key = os.getenv("LIBRATIO_API_KEY", "").strip()if not expected_key:if allow_unconfigured:returnif os.getenv("LIBRATIO_ALLOW_UNAUTH_ADK", "false").lower() == "true":returnraise HTTPException(status_code=403,detail="Endpoint disabled until LIBRATIO_API_KEY (or LIBRATIO_ALLOW_UNAUTH_ADK=true) is set.",)bearer = ""if authorization and authorization.lower().startswith("bearer "):bearer = authorization[7:].strip()provided = x_api_key or bearerif provided != expected_key:raise HTTPException(status_code=401, detail="Invalid or missing API key.")def _require_search_auth(authorization: Optional[str] = Header(default=None),x_api_key: Optional[str] = Header(default=None),) -> None:_require_api_auth(authorization=authorization, x_api_key=x_api_key, allow_unconfigured=True)def _clamp_score(raw_score) -> float:28 unmodified lines}# ═══════════════════════════════════════════════════════════# FLEET MODE — Multi-agent fleet endpoints# ═══════════════════════════════════════════════════════════@app.get("/fleet/tasks", response_model=List[TaskDefinition])def get_fleet_tasks() -> List[TaskDefinition]:return [TaskDefinition(**t) for t in FleetEnvironment.TASK_DEFS]@app.post("/fleet/reset", response_model=ResetResponse)def reset_fleet(request: Request, response: Response, payload: dict = {}):if not isinstance(payload, dict):raise HTTPException(status_code=400, detail="Request body must be a JSON object.")sid = _resolve_session_id(request, payload)env = _session_store.get_or_create(sid)task_id = payload.get("task_id", "fleet_precision")scenario_id = payload.get("scenario_id")try:obs = env.reset(task_id, scenario_id=scenario_id)except ValueError as exc:raise HTTPException(status_code=400, detail=str(exc)) from excif sid != "default" and not request.cookies.get("libratio_sid"):response.set_cookie("libratio_sid", sid, httponly=True, samesite="lax")return ResetResponse(observation=obs)@app.post("/fleet/step", response_model=StepResponse)def step_fleet(request: Request, payload: dict = {}):if not isinstance(payload, dict):raise HTTPException(status_code=400, detail="Request body must be a JSON object.")sid = _resolve_session_id(request, payload)env = _session_store.get_or_create(sid)action = payload.get("action", payload)result = env.step(action)clamped_score = _clamp_score(result["reward"]["score"])return StepResponse(observation=result["observation"],7 unmodified lines@app.post("/fleet/state", response_model=StateResponse)def get_fleet_state(request: Request, payload: dict = {}):sid = _resolve_session_id(request, payload if isinstance(payload, dict) else None)env = _session_store.get_or_create(sid)return StateResponse(**env.state())@app.get("/api/analytics")def get_fleet_analytics(request: Request):"""Expose fleet analytics aggregated via MongoDB pipelines."""_enforce_rate_limit(request, "analytics", max_calls=30)client_mongo = _get_mongo_client()if client_mongo is None:return {"database_status": "not_configured", "error": "MONGO_URI not set in env"}try:db_mongo = client_mongo[DB_NAME]runs_col = db_mongo["runs"]pipeline_tasks = [{"$group": {6 unmodified lines"$cond": [{"$eq": ["$success", True]}, 1.0, 0.0]}},"total_runs": {"$sum": 1},}},{"$sort": {"avg_score": -1}},]task_stats = list(runs_col.aggregate(pipeline_tasks))pipeline_models = [{"$group": {"_id": {"$ifNull": ["$model_name", "$model"]},"avg_score": {"$avg": "$score"},"total_runs": {"$sum": 1},}},{"$sort": {"avg_score": -1}},]model_stats = list(runs_col.aggregate(pipeline_models))formatted_tasks = [{"task_id": t.get("_id") or "unknown","avg_score": round(float(t.get("avg_score") or 0.0), 3),"max_score": round(float(t.get("max_score") or 0.0), 3),"min_score": round(float(t.get("min_score") or 0.0), 3),"success_rate_pct": round(float(t.get("success_rate") or 0.0) * 100.0, 1),"total_runs": int(t.get("total_runs") or 0),}for t in task_stats]formatted_models = [{"model_name": m.get("_id") or "unknown","avg_score": round(float(m.get("avg_score") or 0.0), 3),"total_runs": int(m.get("total_runs") or 0),}for m in model_stats]return {"database_status": "connected","total_runs_logged": sum(t["total_runs"] for t in formatted_tasks),"task_analytics": formatted_tasks,"model_analytics": formatted_models,}except Exception as e:return {"database_status": "failed_connection", "error": str(e)}@app.get("/api/search")def search_trajectories(request: Request,query: str,type: str = "hybrid",limit: int = 5,_auth: None = Depends(_require_search_auth),):"""Search historical trajectories using shared MongoDB Atlas Search helpers."""_enforce_rate_limit(request, "search", max_calls=20)if not query.strip():raise HTTPException(status_code=400, detail="Query parameter must not be empty.")safe_limit = max(1, min(int(limit), 50))client_mongo = _get_mongo_client()if client_mongo is None:return {"error": "MONGO_URI not set in env"}try:from mongodb_vector import (hybrid_search_similar_trajectories,text_search_similar_trajectories,vector_search_similar_trajectories,)collection = client_mongo[DB_NAME]["trajectories"]if type == "text":results = text_search_similar_trajectories(collection, query, top_k=safe_limit)elif type == "vector":results = vector_search_similar_trajectories(collection, {"query": query}, top_k=safe_limit)else:results = hybrid_search_similar_trajectories(collection, query, {"query": query}, top_k=safe_limit)return {"status": "success","query": query,"type": type,"count": len(results),"results": results,}except Exception as e:return {"status": "error", "message": str(e)}# ═══════════════════════════════════════════════════════════# AGENTIC KERNEL — Live Performance Benchmarking# ═══════════════════════════════════════════════════════════@app.get("/kernel/benchmark")def kernel_benchmark(request: Request):"""Run a live benchmark of the Agentic Kernel physics engine."""_enforce_rate_limit(request, "benchmark", max_calls=15)import random as _rndfrom environment.physics_model import (compute_hardware_safety,compute_training_cost,score_precision_layer,)5 unmodified lines"layernorm": 0.05, "output": 0.10,}start = time.perf_counter_ns()for _ in range(NUM_TRAJECTORIES):strategy = {l: _rnd.choice(precisions) for l in layers}5 unmodified lines)cost_ns = time.perf_counter_ns() - startstart = time.perf_counter_ns()for _ in range(NUM_TRAJECTORIES):strategy = {l: _rnd.choice(precisions) for l in layers}7 unmodified lines)safety_ns = time.perf_counter_ns() - startstart = time.perf_counter_ns()for _ in range(NUM_TRAJECTORIES):for l in layers:score_precision_layer(l, _rnd.choice(precisions))scoring_ns = time.perf_counter_ns() - startbench_env = FleetEnvironment()start = time.perf_counter_ns()cycle_count = 2002 unmodified linesbench_env.step({"precision_strategy": {"embedding": "FP32", "attention": "BF16", "ffn": "FP8","layernorm": "BF16", "output": "FP32",},"reasoning": "benchmark",})env_ns = time.perf_counter_ns() - starttotal_ns = cost_ns + safety_ns + scoring_nsper_trajectory_us = (total_ns / NUM_TRAJECTORIES) / 1000docker_cold_start_ms = 150microvm_cold_start_ms = 125return {"kernel_version": "1.0.0",24 unmodified lines@app.get("/kernel/profile")def kernel_profile():"""Profile each kernel module individually."""from environment.physics_model import (ACCURACY_PENALTY,BYTES_PER_PARAM,POWER_DRAW_MULTIPLIER,STABILITY_SCORE,THROUGHPUT_MULTIPLIER,compute_hardware_safety,compute_network_topology,compute_training_cost,score_precision_layer,)layers = ["embedding", "attention", "ffn", "layernorm", "output"]5 unmodified lines"embedding": "FP32", "attention": "BF16", "ffn": "FP8","layernorm": "BF16", "output": "FP32",}params = 7_000_000_000modules = {}start = time.perf_counter_ns()7 unmodified lines"cost_usd": result["cost_usd"],"estimated_stable": result["estimated_stable"],"accuracy_retention": result["accuracy_retention"],},}start = time.perf_counter_ns()6 unmodified lines"memory_utilization_pct": hw["memory_utilization_pct"],"thermal_risk": hw["thermal_risk"],"overall_safe": hw["overall_safe"],},}start = time.perf_counter_ns()layer_results = {}for l in layers:score, _ = score_precision_layer(l, strategy.get(l, "FP32"))layer_results[l] = {"score": score, "precision": strategy.get(l, "FP32")}modules["scoring_kernel"] = {"latency_us": round((time.perf_counter_ns() - start) / 1000, 2),10 unmodified lines"topology": net["topology"],"effective_throughput_pct": net["effective_throughput_pct"],"bottleneck_risk": net["bottleneck_risk"],},}total_latency = sum(m["latency_us"] for m in modules.values())9 unmodified lines"stability_rules": sum(len(v) for v in STABILITY_SCORE.values()),"throughput_rules": sum(len(v) for v in THROUGHPUT_MULTIPLIER.values()),"source": "NVIDIA Transformer Engine + Micikevicius et al. 2018/2022",},}2 unmodified linesuvicorn.run("server.app:app", host="0.0.0.0", port=7860)# ═══════════════════════════════════════════════════════════# GOOGLE ADK AGENT ENDPOINTS# ═══════════════════════════════════════════════════════════@app.get("/adk/status")def adk_status():"""Check whether the Google ADK agent and MongoDB MCP server are available."""return {"adk_available": ADK_AVAILABLE,"mongodb_mcp": "enabled" if ADK_AVAILABLE else "requires google-adk and mcp packages","agent_model": os.getenv("ADK_MODEL", "gemini-2.0-flash"),"install_command": "pip install -r requirements-extras.txt" if not ADK_AVAILABLE else None,"description": "Google Cloud Agent Builder (ADK) + MongoDB MCP Server integration",}@app.post("/adk/run")async def run_adk_agent(request: Request,payload: dict = {},_auth: None = Depends(_require_api_auth),):"""Run the Libratio Fleet Agent using Google ADK + MongoDB MCP Server."""_enforce_rate_limit(request, "adk_run", max_calls=5)if not ADK_AVAILABLE:return {"error": "Google ADK not installed","fix": "pip install -r requirements-extras.txt","adk_available": False,}1 unmodified linevalid_tasks = ["fleet_precision", "fleet_oversight", "fleet_resource", "fleet_recovery"]if task_id not in valid_tasks:raise HTTPException(status_code=400, detail=f"Invalid task_id. Choose from: {valid_tasks}")try:result = await run_fleet_task_with_adk(task_id)return {"status": "completed",12 unmodified linesif __name__ == "__main__":main()
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271287 unmodified lines13613713813914014114215 unmodified lines158159160161"""Pydantic models for the Mixed Precision Training OpenEnv.Typed Observation, Action, and Reward schemas for OpenEnv spec compliance."""from pydantic import BaseModel, Fieldfrom typing import List, Dict, Optional, Literal, AnyPrecisionLevel = Literal["FP32", "BF16", "FP16", "FP8"]# ──────────────────────────────────────────────# Layer specification (shared across tasks)# ──────────────────────────────────────────────class LayerInfo(BaseModel):name: strlayer_type: Literal["embedding", "attention", "ffn", "layernorm", "output"]num_params: intgradient_sensitivity: stractivation_range: str# ──────────────────────────────────────────────# Task 1: Layer-by-Layer Precision Assignment# Agent assigns precision to ONE layer per step# ──────────────────────────────────────────────class Task1Observation(BaseModel):task_id: Literal["precision_assignment"] = "precision_assignment"scenario_id: strmodel_name: strtotal_layers: intcurrent_layer_index: intcurrent_layer: LayerInfoassigned_so_far: Dict[str, str]available_precisions: List[str] = ["FP32", "BF16", "FP16", "FP8"]memory_budget_gb: floatmemory_used_gb: floatspeed_target_speedup: floatclass Task1Action(BaseModel):precision: PrecisionLevelreasoning: str = ""# ──────────────────────────────────────────────# Task 2: Progressive Instability Detection# Agent sees trajectory windows, decides continue or flag# ──────────────────────────────────────────────class Task2Observation(BaseModel):task_id: Literal["instability_detection"] = "instability_detection"scenario_id: strprecision_config: Dict[str, str]total_training_steps: intsteps_revealed_so_far: intloss_trajectory_window: List[Optional[float]]window_index: intwindows_remaining: intclass Task2Action(BaseModel):action_type: Literal["continue_monitoring", "flag_instability"]analysis: str = ""flagged_step: Optional[int] = Noneroot_cause: Optional[str] = None# ──────────────────────────────────────────────# Task 3: Iterative Multi-Objective Optimization# Agent proposes strategy, gets feedback, iterates# ──────────────────────────────────────────────class Task3Observation(BaseModel):task_id: Literal["multi_objective_optimization"] = "multi_objective_optimization"scenario_id: strconstraints: Dict[str, float]model_total_params: intlayer_types: List[str]iterations_remaining: intbest_score_so_far: floatprevious_result: Optional[Dict[str, Any]] = Noneprevious_feedback: Optional[str] = Noneclass Task3Action(BaseModel):precision_strategy: Dict[str, PrecisionLevel]reasoning: str = ""# ──────────────────────────────────────────────# Task 4: Precision Transfer# Agent adapts a working config to a new architecture# ──────────────────────────────────────────────class SourceModelInfo(BaseModel):name: strtotal_params: intlayer_distribution: Dict[str, float]working_config: Dict[str, str]metrics: Dict[str, float]class TargetModelInfo(BaseModel):name: strtotal_params: intlayer_distribution: Dict[str, float]constraints: Dict[str, float]class Task4Observation(BaseModel):task_id: Literal["precision_transfer"] = "precision_transfer"scenario_id: strsource_model: SourceModelInfotarget_model: TargetModelInfoiterations_remaining: intbest_score_so_far: float = 0.0previous_result: Optional[Dict[str, Any]] = Noneprevious_feedback: Optional[str] = Noneclass Task4Action(BaseModel):precision_strategy: Dict[str, PrecisionLevel]reasoning: str = ""# ─────────────────────────────���────────────────# Universal Response Models (OpenEnv Spec)# ──────────────────────────────────────────────class RewardPayload(BaseModel):score: float = Field(..., gt=0.0, lt=1.0, description="Normalized score strictly in (0, 1)")feedback: str = Field(..., description="Human-readable grading explanation")7 unmodified linesclass ResetRequest(BaseModel):task_id: str = "precision_assignment"class ResetResponse(BaseModel):15 unmodified linesdescription: strdifficulty: strmax_steps: int123456789101112137 unmodified lines212223242526272829303132333415 unmodified lines505152"""Pydantic models for the Libratio Fleet OpenEnv API.Typed Observation, Action, and Response schemas for OpenEnv spec compliance."""from typing import Any, Dict, List, Literal, Optionalfrom pydantic import BaseModel, FieldPrecisionLevel = Literal["FP32", "BF16", "FP16", "FP8", "INT8"]class RewardPayload(BaseModel):score: float = Field(..., gt=0.0, lt=1.0, description="Normalized score strictly in (0, 1)")feedback: str = Field(..., description="Human-readable grading explanation")7 unmodified linesclass ResetRequest(BaseModel):task_id: str = "fleet_precision"scenario_id: Optional[str] = Nonesession_id: Optional[str] = Noneclass StepRequest(BaseModel):action: Optional[Dict[str, Any]] = Nonesession_id: Optional[str] = Noneclass ResetResponse(BaseModel):15 unmodified linesdescription: strdifficulty: strmax_steps: int
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071# Setting Up Local Arm64 Inference Engine with ARM NEON Acceleration
This guide explains how to configure **Libratio Fleet** to run its multi-agent optimization and predictive SRE loops locally on Arm64 CPU hardware (such as local Apple Silicon, Raspberry Pi, or AWS Graviton instances) using `llama.cpp` and ARM NEON acceleration.
---
## 📋 Prerequisites* An Arm64 compatible CPU (Apple M-series, AWS Graviton, Raspberry Pi 4/5, or Snapdragon Windows Arm64).* C/C++ compiler toolchain (GCC / Clang) installed on the host system to build llama.cpp.
---
## 🛠️ Step-by-Step Installation
### 1. Compile llama-cpp-python with ARM NEON Vector InstructionsTo enable ARM NEON hardware acceleration, compile `llama-cpp-python` from source. Specify the native C compiler flags:
#### On macOS (Apple Silicon):NEON acceleration is enabled by default in Apple Silicon compilers. Run:```bashpip install --force-reinstall --no-cache-dir llama-cpp-python```
#### On Linux Arm64 (AWS Graviton, Raspberry Pi):Specify the CMake flags to target NEON explicitly:```bashCMAKE_ARGS="-DLLAMA_NEON=ON -DLLAMA_F16C=ON -DLLAMA_AVX512=OFF" pip install --force-reinstall --no-cache-dir llama-cpp-python```
---
### 2. Download a GGUF ModelChoose a lightweight model (under 8B parameters) for fast local execution. We recommend downloading from Hugging Face:* **Phi-3-mini-4k-instruct-q4 (recommended):** [HuggingFace GGUF Page](https://huggingface.co/microsoft/Phi-3-mini-4k-instruct-gguf)* **Llama-3-8B-Instruct-Q4_K_M:** [HuggingFace GGUF Page](https://huggingface.co/QuantFactory/Meta-Llama-3-8B-Instruct-GGUF)
Save the downloaded `.gguf` file to a local path (e.g., `C:\models\phi-3-mini.gguf` or `/home/user/models/phi-3-mini.gguf`).
---
### 3. Configure Environment VariablesCreate or update your `.env` file in the project directory to route requests to the local engine:
```env# Enable local inference engine routingUSE_LOCAL_ARM_ENGINE=True
# Set the path to your GGUF model fileLOCAL_MODEL_PATH="C:/models/phi-3-mini-4k-instruct-q4.gguf"```
*Note: If `LOCAL_MODEL_PATH` is left blank, or if `MOCK_LOCAL_INFERENCE=True` is set, the engine operates in a Mock mode—convenient for testing and CI/CD pipelines without downloading models.*
---
## 🧪 Verifying the Local Engine
To verify that the engine initialized, compiled with NEON, and parsed GGUF outputs correctly, run the local unit tests:```bashpython test_local_inference.py```
To run a live precision assignment episode using the local engine, start the server and run the inference loop:```bash# In one terminal, start the environment serveruvicorn server.app:app --host 0.0.0.0 --port 7860
# In another terminal, run fleet inference with the local engine activeUSE_LOCAL_ARM_ENGINE=True LOCAL_MODEL_PATH="C:/models/phi-3-mini.gguf" python fleet_inference.py```Check the console output for `[Routing inference to Local Arm64 GGUF Engine]` log messages!123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138"""Verification script for Libratio Fleet AWS Database Adapter.Validates table creation, telemetry writing, embedding generation, pgvector-simulated fallback RAG searches, and analytics retrieval."""import sysimport os
# Ensure the root directory is in the pathsys.path.append(os.path.dirname(os.path.abspath(__file__)))
from environment.aws_database import ( create_aws_tables, setup_aurora_pgvector_table, log_step_metrics, log_run_telemetry, generate_embedding, retrieve_historical_context_aws, search_trajectories_aws, get_runs_analytics_aws, BOTO3_AVAILABLE, PSYCOPG2_AVAILABLE, GEMINI_AVAILABLE, EMBEDDING_DIM)
def run_tests(): print("=" * 60) print("STARTING AWS DATABASE ADAPTER VERIFICATION") print("=" * 60)
# 1. Module & SDK Availability Check print("\n[TEST 1] SDK & Environment Check") print(f" boto3 (DynamoDB): {'AVAILABLE' if BOTO3_AVAILABLE else 'UNAVAILABLE'}") print(f" psycopg2 (Aurora PostgreSQL): {'AVAILABLE' if PSYCOPG2_AVAILABLE else 'UNAVAILABLE'}") print(f" google-genai (Gemini Embeddings): {'AVAILABLE' if GEMINI_AVAILABLE else 'UNAVAILABLE'}") print(f" AWS access key: {'SET' if os.getenv('AWS_ACCESS_KEY_ID') else 'NOT SET'}") print(f" Aurora Host: {'SET' if os.getenv('AURORA_PG_HOST') else 'NOT SET'}") print(f" Gemini API Key: {'SET' if os.getenv('GEMINI_API_KEY') else 'NOT SET'}")
# 2. Table Creation Smoke Test print("\n[TEST 2] DynamoDB / Aurora PG Table Initialization Check") db_tables_ok = create_aws_tables() print(f" create_aws_tables status: {db_tables_ok}") pg_tables_ok = setup_aurora_pgvector_table() print(f" setup_aurora_pgvector_table status: {pg_tables_ok}")
# 3. Embedding Generation Check print("\n[TEST 3] Vector Embedding Generation") test_text = "Standard LLaMA-3 model training crashed due to FP8 attention overflow." vector = generate_embedding(test_text) assert isinstance(vector, list), "Embedding must be a list" assert len(vector) == EMBEDDING_DIM, f"Embedding dimension must be {EMBEDDING_DIM}, got {len(vector)}" assert all(isinstance(v, float) for v in vector), "Embedding values must be floats" print(f" Successfully generated {EMBEDDING_DIM}-dim embedding vector.") print(f" Vector sample (first 3 elements): {vector[:3]}")
# 4. Telemetry Metrics Logging Check print("\n[TEST 4] Telemetry & Metrics Writing") step_ok = log_step_metrics( task_id="test_verification", model_id="llama-test-model", step=5, reward=0.885, memory_used_gb=45.2, thermal_risk="LOW", power_util=68.5 ) assert step_ok is True, "log_step_metrics must return True (even on offline fallback)" print(" Step metrics log command executed successfully.")
run_ok = log_run_telemetry( task_id="test_verification", model_name="llama-test-model", score=0.852, steps=10, success=True, rewards=[0.75, 0.82, 0.85, 0.88, 0.89, 0.90, 0.91, 0.92, 0.80, 0.85] ) assert run_ok is True, "log_run_telemetry must return True (even on offline fallback)" print(" Run telemetry log command executed successfully.")
# 5. RAG Retrieval Search Check print("\n[TEST 5] SRE RAG Query Retrieval") live_state = { "model_name": "llama-3.1-8b-instant", "total_params_b": 8.0, "memory_used_gb": 120.0, "cluster_capacity_gb": 160.0, "thermal_risk": "MEDIUM", "power_util": 75.0, "hardware_profile": "nvidia_h100", "vendor": "NVIDIA", "available_precisions": ["FP32", "BF16", "FP16", "FP8"] } context = retrieve_historical_context_aws(live_state, top_k=3) assert isinstance(context, str), "RAG context must return a string" assert "HISTORICAL CRASH DATA" in context, "RAG context must contain historical section header" print(" RAG retrieval context returned successfully.") print("-" * 50) print(context[:400] + "...") print("-" * 50)
# 6. Hybrid Trajectory Search Check print("\n[TEST 6] Search Trajectories Query API Check") results = search_trajectories_aws(query="FP8 ffn overflow crash on NVIDIA H100", limit=3) assert isinstance(results, list), "Search results must be a list" assert len(results) > 0, "Should return at least one trajectory match" print(f" Search returned {len(results)} matches.") first_res = results[0] required_keys = ["model_name", "outcome", "precision_strategy", "rrf_score"] for key in required_keys: assert key in first_res, f"Search result item must contain key: {key}" print(f" Top match: {first_res['model_name']} with similarity/RRF score {first_res['rrf_score']:.3f}")
# 7. Analytics Calculation Check print("\n[TEST 7] Runs Analytics Check") analytics = get_runs_analytics_aws() assert isinstance(analytics, dict), "Analytics must return a dictionary" assert "database_status" in analytics, "Analytics must report database status" assert "task_analytics" in analytics, "Analytics must report task analytics" assert "model_analytics" in analytics, "Analytics must report model analytics" print(f" Analytics DB Status: {analytics['database_status']}") print(f" Total Runs Logged: {analytics.get('total_runs_logged', 0)}") print(f" Task Analytics: {analytics['task_analytics']}") print(f" Model Analytics: {analytics['model_analytics']}")
print("\n" + "=" * 60) print("=== ALL AWS DATABASE ADAPTER TESTS PASSED ===") print("=" * 60)
def test_aws_database_adapter(): run_tests()
if __name__ == "__main__": run_tests()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103"""Quick smoke test for all 4 fleet tasks."""from environment.fleet_env import FleetEnvironmentimport jsone = FleetEnvironment()# Test all 4 fleet tasks resetfor task_id in ["fleet_precision", "fleet_oversight", "fleet_resource", "fleet_recovery"]:try:obs = e.reset(task_id)print(f"[OK] {task_id} reset — keys: {list(obs.keys())}")except Exception as ex:print(f"[FAIL] {task_id}: {ex}")# Test a full fleet_precision episodeprint("\n--- Full fleet_precision episode ---")e.reset("fleet_precision")optimal = {"embedding": "FP32", "attention": "BF16", "ffn": "FP8", "layernorm": "BF16", "output": "FP32"}step_num = 0while True:step_num += 1result = e.step({"precision_strategy": optimal, "reasoning": "optimal config"})score = result["reward"]["score"]done = result["done"]print(f" Step {step_num}: score={score:.3f}, done={done}")if done:if "fleet_summary" in result.get("info", {}):fs = result["info"]["fleet_summary"]print(f" Fleet: mem={fs['total_memory_used_gb']}GB/{fs['cluster_capacity_gb']}GB, "f"cost=${fs['total_cost_usd']:,.0f}, savings=${fs['fleet_savings_usd']:,.0f}, "f"all_stable={fs['all_stable']}")break# Test fleet_oversight episodeprint("\n--- Full fleet_oversight episode ---")obs = e.reset("fleet_oversight")print(f" Models: {list(obs['model_trajectories'].keys())}")print(f" Scenario: {obs['scenario_id']}")r = e.step({"action_type": "continue_monitoring", "analysis": "all looks stable"})print(f" Step 1 (continue): score={r['reward']['score']:.3f}, done={r['done']}")r = e.step({"action_type": "flag_instability","flagged_model": "model_b","flagged_step": 35,"root_cause": "fp8 embedding underflow model_b","analysis": "NaN detected in model_b"})print(f" Step 2 (flag): score={r['reward']['score']:.3f}, done={r['done']}")print(f" Feedback: {r['reward']['feedback'][:200]}")# Test fleet_resource episodeprint("\n--- Full fleet_resource episode ---")obs = e.reset("fleet_resource")print(f" Cluster: {obs['cluster']['total_gpus']} GPUs, {obs['cluster']['total_memory_gb']}GB")print(f" Models: {[m['name'] for m in obs['models']]}")alloc = {}models = obs["models"]total_gpus = obs["cluster"]["total_gpus"]for i, m in enumerate(models):gpus = max(1, total_gpus // len(models))if i == 0:gpus = total_gpus - (len(models) - 1) * gpus # give remainder to firstalloc[m["model_id"]] = {"gpus": gpus,"precision_strategy": optimal,}r = e.step({"allocations": alloc})print(f" Step 1: score={r['reward']['score']:.3f}, done={r['done']}")print(f" Feedback: {r['reward']['feedback'][:200]}")# Test fleet_recovery episodeprint("\n--- Full fleet_recovery episode ---")obs = e.reset("fleet_recovery")print(f" Phase: {obs['phase']}")print(f" Crashed model: {obs['crashed_model']['model_id']}")print(f" Crash step: {obs['crashed_model']['crash_step']}")r = e.step({"diagnosed_model": obs["crashed_model"]["model_id"],"root_cause": "fp8 embedding underflow causing gradient collapse","reasoning": "NaN in loss trajectory indicates precision failure"})print(f" Step 1 (diagnose): score={r['reward']['score']:.3f}, done={r['done']}")if not r["done"]:r = e.step({"new_precision_strategy": optimal,"reasoning": "Switch to safe config: FP32 embedding, BF16 attention, FP8 FFN"})print(f" Step 2 (reallocate): score={r['reward']['score']:.3f}, done={r['done']}")if not r["done"]:r = e.step({"reasoning": "Recovery plan is stable. New config uses FP32 for embedding to prevent underflow. Will monitor loss for 100 steps post-restart.","confidence": "high"})print(f" Step 3 (verify): score={r['reward']['score']:.3f}, done={r['done']}")print("\n=== ALL FLEET TESTS PASSED ===")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151"""Automated pytest suite for Libratio Fleet environment, physics, and kernel."""from environment.fleet_env import FleetEnvironmentfrom environment.physics_model import compute_training_cost, score_precision_layerfrom kernel_interface import AgenticKernelOPTIMAL_NVIDIA = {"embedding": "FP32","attention": "BF16","ffn": "FP8","layernorm": "BF16","output": "FP32",}def test_all_tasks_reset():env = FleetEnvironment()for task_id in ["fleet_precision", "fleet_oversight", "fleet_resource", "fleet_recovery"]:obs = env.reset(task_id)assert obs["task_id"] == task_idassert "scenario_id" in obsdef test_fleet_precision_episode():env = FleetEnvironment()env.reset("fleet_precision", scenario_id="small_fleet")done = Falsesteps = 0while not done:steps += 1res = env.step({"precision_strategy": OPTIMAL_NVIDIA, "reasoning": "optimal config"})score = res["reward"]["score"]assert 0.01 <= score <= 0.99done = res["done"]assert steps == 2assert "fleet_summary" in res["info"]assert res["info"]["fleet_summary"]["all_stable"] is Truedef test_fleet_oversight_and_spike_detection():env = FleetEnvironment()env.reset("fleet_oversight", scenario_id="one_crash_two_healthy")# Window 0: steps 0..20 (healthy)r1 = env.step({"action_type": "continue_monitoring", "analysis": "initial healthy window"})assert 0.01 <= r1["reward"]["score"] <= 0.99assert r1["done"] is False# Window 1: steps 20..40 contains crash_step=35 (1e8 spike + NaN)r2 = env.step({"action_type": "continue_monitoring", "analysis": "checking next window"})assert "Issues visible" in r2["reward"]["feedback"]# String flagged_step must be coerced cleanly rather than raising TypeErrorr3 = env.step({"action_type": "flag_instability","flagged_model": "model_b","flagged_step": "35","root_cause": "fp8 embedding underflow model_b","analysis": "NaN detected in model_b",})assert r3["done"] is Trueassert r3["reward"]["score"] > 0.80def test_fleet_oversight_spike_at_window_boundary():env = FleetEnvironment()env.reset("fleet_oversight", scenario_id="one_crash_two_healthy")# Force spike (1e8) as last element of window 0 without NaN yetenv.scenario["trajectories"]["model_b"]["loss"][19] = 1e8r = env.step({"action_type": "continue_monitoring", "analysis": "checking spike"})assert "Issues visible" in r["reward"]["feedback"]def test_fleet_resource_cost_respects_gpu_count_and_rate():env = FleetEnvironment()obs = env.reset("fleet_resource", scenario_id="micro_fleet")models = obs["models"]alloc_1 = {models[0]["model_id"]: {"gpus": 1, "precision_strategy": OPTIMAL_NVIDIA},models[1]["model_id"]: {"gpus": 1, "precision_strategy": OPTIMAL_NVIDIA},}r1 = env.step({"allocations": alloc_1})assert 0.01 <= r1["reward"]["score"] <= 0.99cost_1_gpu = r1["info"]["per_model"][models[0]["model_id"]]["cost_usd"]# Compare against compute_training_cost for 2 GPUs at $1.50/hrm_2gpu = compute_training_cost(total_params=3_800_000_000,precision_strategy=OPTIMAL_NVIDIA,layer_distribution={"embedding": 0.15, "attention": 0.25, "ffn": 0.40, "layernorm": 0.002, "output": 0.198},num_gpus=2,cost_per_gpu_hour=1.50,)assert abs(m_2gpu["cost_usd"] - 2 * cost_1_gpu) <= 2.0def test_fleet_recovery_episode():env = FleetEnvironment()obs = env.reset("fleet_recovery")assert obs["phase"] == "diagnose"r1 = env.step({"diagnosed_model": obs["crashed_model"]["model_id"],"root_cause": "fp8 embedding output overflow","reasoning": "NaN in loss trajectory indicates precision failure",})assert r1["done"] is Falseassert r1["reward"]["score"] >= 0.50r2 = env.step({"new_precision_strategy": OPTIMAL_NVIDIA,"reasoning": "Switch to safe config: FP32 embedding and output",})assert r2["done"] is Falseassert r2["reward"]["score"] >= 0.70r3 = env.step({"reasoning": "Recovery plan is stable and safe. Will monitor loss for 100 steps.","confidence": "high",})assert r3["done"] is Trueassert r3["reward"]["score"] >= 0.80def test_invalid_inputs_never_crash():env = FleetEnvironment()env.reset("fleet_precision", scenario_id="small_fleet")# Non-dict actionr_bad_action = env.step(["not", "a", "dict"])assert r_bad_action["reward"]["score"] == 0.01# Unsupported precision in compute_training_cost must not raise KeyErrorres = compute_training_cost(total_params=7_000_000_000,precision_strategy={"embedding": "INT4", "attention": "BF16", "ffn": "FP8", "layernorm": "BF16", "output": "FP32"},layer_distribution={"embedding": 0.15, "attention": 0.25, "ffn": 0.40, "layernorm": 0.002, "output": 0.198},)assert res["estimated_stable"] is Falseassert res["unsupported_precisions"]# Invalid gpu type in fleet_resourceenv.reset("fleet_resource", scenario_id="small_fleet")r_bad_gpu = env.step({"allocations": {"model_a": {"gpus": "four"}, "model_b": {"gpus": 2}}})assert r_bad_gpu["reward"]["score"] == 0.01# Kernel latency buffer stays boundedkernel = AgenticKernel()assert kernel._latencies.maxlen == 10_000score, _ = score_precision_layer("ffn", "INVALID")assert score == 0.01
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132"""Test script for Libratio Fleet Multi-Vendor Hardware Profile Architecture.Verifies H100, AMD MI300X, and Google TPU v5p dynamic physics calculations."""from environment.fleet_env import FleetEnvironmentfrom environment.physics_model import HARDWARE_PROFILES, compute_training_cost, score_precision_layerimport jsonimport sysimport io
def test_hardware_registry(): print("--- Testing Hardware Profile Registry ---") assert "nvidia_h100" in HARDWARE_PROFILES assert "amd_mi300x" in HARDWARE_PROFILES assert "google_tpu_v5p" in HARDWARE_PROFILES
h100 = HARDWARE_PROFILES["nvidia_h100"] amd = HARDWARE_PROFILES["amd_mi300x"] tpu = HARDWARE_PROFILES["google_tpu_v5p"]
print(f"[OK] H100 GPU: max memory = {h100['gpu_memory_gb']} GB") print(f"[OK] AMD GPU: max memory = {amd['gpu_memory_gb']} GB") print(f"[OK] TPU chip: max memory = {tpu['gpu_memory_gb']} GB")
# Verify memory differences assert h100["gpu_memory_gb"] == 80.0 assert amd["gpu_memory_gb"] == 192.0 assert tpu["gpu_memory_gb"] == 95.0
def test_tpu_unsupported_fp8(): print("\n--- Testing Format Rejections (TPU v5p vs NVIDIA H100) ---") # 1. H100 supports FP8 score_h100, feedback_h100 = score_precision_layer("ffn", "FP8", hardware_profile="nvidia_h100") print(f"H100 FP8 FFN Score: {score_h100:.3f} | {feedback_h100[:60]}...") assert score_h100 > 0.90
# 2. TPU v5p does not support FP8 score_tpu, feedback_tpu = score_precision_layer("ffn", "FP8", hardware_profile="google_tpu_v5p") print(f"TPU FP8 FFN Score: {score_tpu:.3f} | {feedback_tpu}") assert score_tpu == 0.01 assert "UNSUPPORTED" in feedback_tpu
# 3. TPU v5p supports INT8 instead score_tpu_int8, feedback_tpu_int8 = score_precision_layer("ffn", "INT8", hardware_profile="google_tpu_v5p") print(f"TPU INT8 FFN Score: {score_tpu_int8:.3f} | {feedback_tpu_int8}") assert score_tpu_int8 > 0.90
def test_amd_mi300x_capacity(): print("\n--- Testing AMD MI300X VRAM Capacity Cost Calculation ---") layer_dist = {"embedding": 0.15, "attention": 0.25, "ffn": 0.40, "layernorm": 0.002, "output": 0.198} strategy = {"embedding": "FP32", "attention": "BF16", "ffn": "FP8", "layernorm": "BF16", "output": "FP32"} # AMD MI300X VRAM allocation should yield identical param memory but run on a larger budget metrics_amd = compute_training_cost( total_params=70_000_000_000, # 70B model precision_strategy=strategy, layer_distribution=layer_dist, hardware_profile="amd_mi300x" ) print(f"AMD 70B model memory footprint: {metrics_amd['memory_gb']} GB") assert metrics_amd["memory_gb"] > 100.0
def test_environment_scenarios(): print("\n--- Testing Environment Integration ---") env = FleetEnvironment()
# 1. Reset AMD Scenario print("Testing AMD scenario reset:") obs = env.reset("fleet_precision", scenario_id="amd_mi300x_fleet") print(f" Observed Profile: {obs['cluster']['hardware_profile']} ({obs['cluster']['vendor']})") print(f" Observed Available Precisions: {obs['available_precisions']}") assert obs["cluster"]["hardware_profile"] == "amd_mi300x" assert "FP8" in obs["available_precisions"]
# Step AMD Scenario res = env.step({ "precision_strategy": { "embedding": "FP32", "attention": "BF16", "ffn": "FP8", "layernorm": "BF16", "output": "FP32" }, "reasoning": "Standard AMD mixed precision" }) print(f" AMD Step Score: {res['reward']['score']:.3f} | {res['reward']['feedback'][:100]}...") assert res["reward"]["score"] > 0.80
# 2. Reset Google TPU Scenario print("Testing TPU scenario reset:") obs_tpu = env.reset("fleet_precision", scenario_id="google_tpu_fleet") print(f" Observed Profile: {obs_tpu['cluster']['hardware_profile']} ({obs_tpu['cluster']['vendor']})") print(f" Observed Available Precisions: {obs_tpu['available_precisions']}") assert obs_tpu["cluster"]["hardware_profile"] == "google_tpu_v5p" assert "FP8" not in obs_tpu["available_precisions"] assert "INT8" in obs_tpu["available_precisions"]
# Step TPU Scenario with correct INT8 res_tpu = env.step({ "precision_strategy": { "embedding": "FP32", "attention": "BF16", "ffn": "INT8", "layernorm": "BF16", "output": "FP32" }, "reasoning": "TPU INT8 FFN layout" }) print(f" TPU Step Score (INT8): {res_tpu['reward']['score']:.3f} | {res_tpu['reward']['feedback'][:100]}...") assert res_tpu["reward"]["score"] > 0.80
# Step TPU Scenario with incorrect FP8 (should trigger penalty/rejection) env.reset("fleet_precision", scenario_id="google_tpu_fleet") res_tpu_fail = env.step({ "precision_strategy": { "embedding": "FP32", "attention": "BF16", "ffn": "FP8", "layernorm": "BF16", "output": "FP32" }, "reasoning": "Unoptimized FP8 on TPU" }) print(f" TPU Step Score (FP8): {res_tpu_fail['reward']['score']:.3f} | {res_tpu_fail['reward']['feedback'][:100]}...") assert res_tpu_fail["reward"]["score"] == 0.01
if __name__ == "__main__": if hasattr(sys.stdout, "reconfigure"): sys.stdout.reconfigure(encoding="utf-8", errors="replace") test_hardware_registry() test_tpu_unsupported_fp8() test_amd_mi300x_capacity() test_environment_scenarios() print("\n=== ALL HARDWARE PROFILE TESTS PASSED SUCCESSFULLY ===")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475"""Test suite for Local Arm64 Inference Engine.Verifies JSON parsing, task routing, and mock output structures."""import osimport unittestimport jsonfrom environment.local_arm_engine import LocalArmInferenceEngine
class TestLocalArmInferenceEngine(unittest.TestCase): def setUp(self): # Force mock mode by setting model path to "mock" self.engine = LocalArmInferenceEngine(model_path="mock")
def test_mock_initialization(self): self.assertTrue(self.engine.is_mock) self.assertIsNone(self.engine.llm)
def test_precision_task_generation(self): # Setup observation input obs = { "cluster": { "hardware_profile": "nvidia_h100", "vendor": "NVIDIA", "total_memory_gb": 320 }, "your_model": { "model_id": "model_a", "name": "LLaMA-3-13B" } } user_prompt = f"state:\n{json.dumps(obs)}\n\nProvide your action as JSON with precision_strategy." result = self.engine.generate_json("system_prompt", user_prompt) self.assertIn("precision_strategy", result) self.assertIn("reasoning", result) self.assertEqual(result["precision_strategy"]["ffn"], "FP8")
def test_tpu_precision_task_generation(self): # Setup TPU observation input obs = { "cluster": { "hardware_profile": "google_tpu_v5p", "vendor": "Google", "total_memory_gb": 380 } } user_prompt = f"state:\n{json.dumps(obs)}\n\nProvide your action as JSON with precision_strategy." result = self.engine.generate_json("system_prompt", user_prompt) self.assertIn("precision_strategy", result) self.assertEqual(result["precision_strategy"]["ffn"], "INT8") self.assertIn("TPU detected", result["reasoning"])
def test_oversight_task_generation(self): user_prompt = "action_type: continue_monitoring or flag_instability. Provide JSON." result = self.engine.generate_json("system_prompt", user_prompt) self.assertIn("action_type", result) self.assertEqual(result["action_type"], "continue_monitoring") self.assertIsNone(result["flagged_model"])
def test_json_parsing_resilience(self): # Test cleaning raw output wrapped in markdown code blocks raw_markdown = "```json\n{\"precision_strategy\": {\"embedding\": \"FP32\"}, \"reasoning\": \"ok\"}\n```" parsed = self.engine._parse_json_from_text(raw_markdown) self.assertEqual(parsed.get("reasoning"), "ok") self.assertEqual(parsed.get("precision_strategy", {}).get("embedding"), "FP32")
# Test parsing with trailing commas raw_trailing_comma = "{\"precision_strategy\": {\"embedding\": \"FP32\"},}" parsed = self.engine._parse_json_from_text(raw_trailing_comma) self.assertEqual(parsed.get("precision_strategy", {}).get("embedding"), "FP32")
if __name__ == "__main__": unittest.main()39 unmodified lines4041424344454647484950515253545539 unmodified linesdef _init_server_mode():"""Initialize server mode (HTTP calls to running server)."""import httpxenv_url = os.getenv("ENV_URL", "http://localhost:7860")fleet_url = f"{env_url}/fleet"def reset_fn(task_id: str) -> Dict:res = httpx.post(f"{fleet_url}/reset", json={"task_id": task_id}, timeout=30.0)return res.json()["observation"]def step_fn(action: Dict) -> Dict[str, Any]:res = httpx.post(f"{fleet_url}/step", json={"action": action}, timeout=30.0)data = res.json()return {"observation": data.get("observation"),39 unmodified lines404142434445464748495051525354555657585939 unmodified linesdef _init_server_mode():"""Initialize server mode (HTTP calls to running server)."""import uuidimport httpxenv_url = os.getenv("ENV_URL", "http://localhost:7860")fleet_url = f"{env_url}/fleet"headers = {"X-Session-ID": f"train-{uuid.uuid4().hex}"}def reset_fn(task_id: str) -> Dict:res = httpx.post(f"{fleet_url}/reset", json={"task_id": task_id}, headers=headers, timeout=30.0)res.raise_for_status()return res.json()["observation"]def step_fn(action: Dict) -> Dict[str, Any]:res = httpx.post(f"{fleet_url}/step", json={"action": action}, headers=headers, timeout=30.0)res.raise_for_status()data = res.json()return {"observation": data.get("observation"),
123456789101112131415161718192021222324252627{ "version": 2, "builds": [ { "src": "server/app.py", "use": "@vercel/python" }, { "src": "frontend/**", "use": "@vercel/static" } ], "routes": [ { "src": "/(api|fleet|kernel|adk)/(.*)", "dest": "server/app.py" }, { "src": "/(index.html)?", "dest": "frontend/index.html" }, { "src": "/(.*)", "dest": "frontend/$1" } ]}.dockerignore+3-1
.github/workflows/sync_to_hf_space.yml+7
Dockerfile+12-2
LICENSEAdded+21
agent/adk_agent.py+113-106
colab_qlora_grpo_fleet.py+10-6
environment/aws_database.pyAdded+491
environment/fleet_env.py+108-20
environment/local_arm_engine.pyAdded+181
environment/physics_model.py+119-43
environment/thermal_kernel.pyDeleted-146
fleet_inference.py+82-43
frontend/main.js+9-2
kernel_interface.py+28-11
mongodb_metrics.py+15-16
mongodb_streams.py+8-9
mongodb_vector.py+19-7
notebooks/qlora_grpo_training.pyDeleted-457
predictive_agent.py+55-170
pyproject.toml+12-3
requirements-extras.txtAdded+10
requirements-local.txtAdded+6
requirements.txt+2-11
scenarios/fleet_scenarios.py+66
server/app.py+282-259
server/models.py+12-121
setup_arm_inference.mdAdded+71
test_aws_database.pyAdded+138
test_fleet.py+144-96
test_hardware_profiles.pyAdded+132
test_local_inference.pyAdded+75
train_fleet.py+6-2
vercel.jsonAdded+27