""" 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)