Spaces:
Running
Running
File size: 8,387 Bytes
5655786 0a7b128 5655786 0a7b128 5655786 0a7b128 5655786 0a7b128 5655786 0a7b128 5655786 0a7b128 5655786 0a7b128 5655786 0a7b128 5655786 0a7b128 5655786 0a7b128 5655786 0a7b128 5655786 0a7b128 5655786 0a7b128 5655786 0a7b128 5655786 0a7b128 5655786 0a7b128 5655786 0a7b128 5655786 0a7b128 5655786 0a7b128 5655786 0a7b128 5655786 0a7b128 5655786 0a7b128 5655786 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 | """
Libratio Predictive MLOps Agent
================================
Uses MongoDB Atlas Vector Search + LLM reasoning to proactively
prevent GPU cluster crashes by recommending precision strategy changes.
Retrieval pipeline (RAG):
1. Live cluster state β Gemini text-embedding-004 β 768-dim query vector
2. MongoDB Atlas $vectorSearch β top-5 semantically similar past crashes
3. Historical context + live state β LLM reasoning β preventive action
This is true semantic RAG: instead of exact field matching, we find
historically similar situations by meaning β even if the exact numbers differ.
Fallback chain:
Atlas Vector Search β basic $match aggregation β local JSON file
"""
import os
import httpx
from dotenv import load_dotenv
# AWS Database module (Amazon Aurora pgvector RAG + local fallback)
try:
from environment.aws_database import retrieve_historical_context_aws
except 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")
GROQ_API_BASE = os.getenv("API_BASE_URL", "https://api.groq.com/openai/v1")
MODEL_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 Configuration
USE_LOCAL_ARM_ENGINE = os.getenv("USE_LOCAL_ARM_ENGINE", "False") == "True"
local_arm_engine = None
if USE_LOCAL_ARM_ENGINE:
try:
from environment.local_arm_engine import LocalArmInferenceEngine
local_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 trajectories
using 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 the
custom 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 Model
print(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},
{"role": "user", "content": prompt}
],
"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:
print(" [SUCCESS: Inference powered by Hugging Face Custom Model]")
return result["choices"][0]["message"]["content"]
except Exception as e:
print(f" [WARN] Hugging Face API unavailable or warming up ({type(e).__name__}). Falling back to Groq.")
# Attempt 2: Fallback to Groq (llama-3.1-8b base)
groq_headers = {
"Authorization": f"Bearer {GROQ_API_KEY}",
"Content-Type": "application/json",
}
groq_payload = {
"model": MODEL_NAME,
"messages": [
{"role": "system", "content": system_prompt},
{"role": "user", "content": prompt}
],
"temperature": 0.3,
"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"]
def 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 reasoning
3. Outputs a preventive precision strategy
"""
try:
from environment.aws_database import PSYCOPG2_AVAILABLE, AURORA_PG_HOST
has_aurora = bool(PSYCOPG2_AVAILABLE and AURORA_PG_HOST)
except ImportError:
has_aurora = False
retrieval_mode = (
"Amazon Aurora PostgreSQL (pgvector Search)" if has_aurora
else "Local JSON Fallback (pgvector simulation)"
)
print("\n" + "=" * 60)
print(" LIBRATIO PREDICTIVE MLOPS AGENT")
print(f" Retrieval: {retrieval_mode}")
print("=" * 60)
# ββ Step 1: RAG Retrieval from MongoDB (Vector Search) ββ
historical_context = retrieve_historical_context(live_state)
print("\n[STEP 1] RAG CONTEXT FROM MONGODB:")
print("-" * 40)
print(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']}
- Parameters: {live_state.get('total_params_b', '?')}B
- Current Memory Used: {live_state['memory_used_gb']} GB
- Cluster Total Memory: {live_state['cluster_capacity_gb']} GB
- 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}
Based on the historical crash data above, what precision strategy should we apply to this model RIGHT NOW to prevent a crash?
Rules:
- 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 constraints
3. "expected_outcome": what you predict will happen after this change
"""
print("\n[STEP 2] AGENT REASONING (via LLM)...")
print("-" * 40)
try:
response = call_llm(prompt)
print("\n[STEP 3] AGENT DECISION:")
print("=" * 60)
print(response)
print("=" * 60)
return response
except Exception as e:
print(f"\n[ERROR] LLM call failed: {e}")
return None
if __name__ == "__main__":
# Simulate a live cluster state that is heading toward a crash
live_danger_state = {
"model_name": "LLaMA-3-70B",
"total_params_b": 70.0,
"memory_used_gb": 220.0,
"cluster_capacity_gb": 320.0,
"thermal_risk": "HIGH",
"power_util": 88.0,
}
predict_and_recover(live_danger_state)
|