Spaces:
Running
Running
File size: 6,558 Bytes
0a7b128 | 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 | """
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)
|