AnGrapicStudio/brain-x-stage2-simulation
0
1import os # Stable Downgrade v3 - FORCE_B52_SIM
2import time
3import ctypes
4import numpy as np
5from fastapi import FastAPI, HTTPException
6from pydantic import BaseModel
7from typing import List, Optional
8import uvicorn
9from fastapi.middleware.cors import CORSMiddleware
10
11# --- CONFIGURATION ---
12DLL_PATH = os.environ.get("VGPU_LIB_PATH", os.path.join(os.getcwd(), "libvgpu.so"))
13
14# --- DATA STRUCTURES ---
15class State(ctypes.Structure):
16 _fields_ = [
17 ("pat10", ctypes.c_int64),
18 ("patWin", ctypes.c_int64),
19 ("buf10", ctypes.c_int64),
20 ("bufWin", ctypes.c_int64),
21 ]
22
23# --- INITIALIZATION ---
24app = FastAPI(title="Brain-X Stage 2: Stable Nuclear Simulation")
25
26app.add_middleware(
27 CORSMiddleware,
28 allow_origins=["*"],
29 allow_methods=["*"],
30 allow_headers=["*"],
31)
32
33class PredictionRequest(BaseModel):
34 history: List[str]
35 window: int = 25
36 healthCheck: bool = False
37 warmUp: bool = False
38 forceSimulation: bool = True
39
40HAS_CPP = False
41
42# Try loading C++ Core (Primary)
43try:
44 if os.path.exists(DLL_PATH):
45 cpp_lib = ctypes.CDLL(DLL_PATH)
46 cpp_lib.run_simulation_cpp.argtypes = [
47 ctypes.c_int64, # total_rounds
48 ctypes.c_uint64, # seed
49 ctypes.c_int32, # window
50 ctypes.POINTER(ctypes.c_int64),
51 ctypes.c_void_p,
52 ctypes.c_void_p,
53 ctypes.c_uint64,
54 ctypes.c_void_p
55 ]
56 HAS_CPP = True
57 print("⚡ STABLE CPU CORE: Loaded successfully.")
58except Exception as e:
59 print(f"⚠️ C++ Core unavailable: {e}")
60
61def encode_pattern(history: List[str], window: int):
62 pattern = 0
63 for char in history[-window:]:
64 bits = 0 if char == 'B' else 1 if char == 'P' else 2
65 pattern = (pattern << 2) | bits
66 return pattern
67
68@app.get("/")
69def home():
70 mode = "STABLE NUCLEAR (CPU)" if HAS_CPP else "LEGACY FALLBACK"
71 return {
72 "status": "Brain-X Stage 2 Online",
73 "engine": "Stable-Nuclear-Simulation-v5.0",
74 "mode": mode,
75 "cpp_loaded": HAS_CPP,
76 "target_performance": "50M simulations @ 1.5s"
77 }
78
79@app.get("/health")
80def health():
81 return {"status": "ok", "cpp_loaded": HAS_CPP}
82
83@app.post("/predict")
84async def predict(request: PredictionRequest):
85 if request.healthCheck or request.warmUp:
86 return {"status": "ok", "warmup": True}
87
88 if HAS_CPP:
89 # Stable C++ core
90 counts10 = np.zeros(1048576 * 3, dtype=np.int64)
91 state = State()
92 state.pat10 = encode_pattern(request.history, 10)
93 state.buf10 = min(len(request.history), 10)
94 seed = int(time.time() * 1000)
95
96 start_time = time.time()
97
98 # Set to 50 Million for absolute stability on 2-core HF Free Tier
99 rounds = 50_000_000
100 cpp_lib.run_simulation_cpp(
101 rounds, seed, 10,
102 counts10.ctypes.data_as(ctypes.POINTER(ctypes.c_int64)),
103 None, None, 0, ctypes.byref(state)
104 )
105
106 latency = time.time() - start_time
107
108 # Result synthesis
109 idx = (state.pat10 & 0xFFFFF) * 3
110 b, p, t = int(counts10[idx]), int(counts10[idx+1]), int(counts10[idx+2])
111
112 # Fallback to index 0 if specific pattern is empty
113 if b + p + t == 0:
114 b, p, t = int(counts10[0]), int(counts10[1]), int(counts10[2])
115
116 total = b + p + t
117 b_prob = b/total if total > 0 else 0.5
118 p_prob = p/total if total > 0 else 0.5
119
120 return [
121 {
122 "label": "B",
123 "score": round(b_prob, 4),
124 "source": "STABLE_NUCLEAR_SIM",
125 "total_samples": total,
126 "latency": round(latency, 4),
127 "engine": "Optimized Scalar CPU"
128 },
129 {
130 "label": "P",
131 "score": round(p_prob, 4),
132 "source": "STABLE_NUCLEAR_SIM",
133 "total_samples": total,
134 "latency": round(latency, 4),
135 "engine": "Optimized Scalar CPU"
136 }
137 ]
138
139 else:
140 # Ultimate fallback - basic Python calculation
141 b_count = request.history.count('B')
142 p_count = request.history.count('P')
143 total = len(request.history)
144
145 b_prob = 0.5
146 p_prob = 0.5
147
148 return [
149 {"label": "B", "score": round(b_prob, 4), "source": "legacy_fallback", "engine": "Python Heuristic"},
150 {"label": "P", "score": round(p_prob, 4), "source": "legacy_fallback", "engine": "Python Heuristic"}
151 ]
152
153if __name__ == "__main__":
154 uvicorn.run(app, host="0.0.0.0", port=7860)
155# Force Update 2026-02-17-1510
156 