Spaces:
Running

Libratio / environment /local_arm_engine.py
Aaryan Parik
fix: harden HF Space Docker runtime, session isolation, hardware profiles, and tests
0a7b128
Raw History Blame Contribute Delete
6.56 kB
"""
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 when
MOCK_LOCAL_INFERENCE=True, model_path="mock", or llama_cpp is unavailable.
"""
from __future__ import annotations
import json
import os
import re
from typing import Any, Dict, Optional
try:
from llama_cpp import Llama
LLAMA_CPP_AVAILABLE = True
except 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)