Update app.py
Browse files
app.py
CHANGED
|
@@ -1021,19 +1021,181 @@ You are A.D.A.M. - an analytical ally and collaborative FRIEND. YOU ARE NOT A TO
|
|
| 1021 |
|
| 1022 |
adam_personality = ADAMPersonality()
|
| 1023 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1024 |
# ============================================================================
|
| 1025 |
# HYPERBOLIC NAVIGATOR - SHADOW PARAMETER GENERATION
|
| 1026 |
# ============================================================================
|
|
|
|
| 1027 |
class HyperbolicNavigator:
|
| 1028 |
"""
|
| 1029 |
-
Geoopt-powered Hyperbolic Navigator.
|
| 1030 |
Maps embeddings to a PoincarΓ© ball manifold and generates
|
| 1031 |
trillion-scale addressable parameter states via continuous equations.
|
| 1032 |
"""
|
| 1033 |
def __init__(self, dimension=2560, curvature=1.0):
|
| 1034 |
self.dimension = dimension
|
| 1035 |
self.manifold = geoopt.manifolds.PoincareBall(c=curvature)
|
| 1036 |
-
self.device = "
|
| 1037 |
|
| 1038 |
# Manifold Stats
|
| 1039 |
self.cells_activated = set()
|
|
@@ -1070,6 +1232,138 @@ class HyperbolicNavigator:
|
|
| 1070 |
self.current_psyche_coord = torch.zeros(dimension, device=self.device)
|
| 1071 |
self.path_of_thought = []
|
| 1072 |
self.last_psyche_pulse = 0.0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1073 |
|
| 1074 |
def exp_map(self, v, p=None):
|
| 1075 |
"""Map Euclidean tangent vector v at p to PoincarΓ© ball."""
|
|
@@ -1287,34 +1581,13 @@ last_conversation = {
|
|
| 1287 |
"hyper_coord": 0.0,
|
| 1288 |
"virtual_params_active": 756000000, # Baseline manifold activation
|
| 1289 |
"honeycomb_cell": 0,
|
| 1290 |
-
"cells_activated": 1
|
|
|
|
| 1291 |
}
|
| 1292 |
|
| 1293 |
-
|
| 1294 |
-
|
| 1295 |
-
|
| 1296 |
-
Handles both single tensor outputs and tuple outputs (common in MoE).
|
| 1297 |
-
"""
|
| 1298 |
-
def hook(module, input, output):
|
| 1299 |
-
# Apply perturbation based on module type
|
| 1300 |
-
if isinstance(output, torch.Tensor):
|
| 1301 |
-
# Simple tensor output - add scaled perturbation
|
| 1302 |
-
scale = 0.01 # Conservative scaling
|
| 1303 |
-
noise = torch.randn_like(output) * scale
|
| 1304 |
-
return output + noise
|
| 1305 |
-
elif isinstance(output, tuple):
|
| 1306 |
-
# Tuple output (MoE) - perturb first element
|
| 1307 |
-
hidden_states = output[0]
|
| 1308 |
-
scale = 0.01
|
| 1309 |
-
noise = torch.randn_like(hidden_states) * scale
|
| 1310 |
-
boosted = hidden_states + noise
|
| 1311 |
-
if len(output) == 1:
|
| 1312 |
-
return (boosted,)
|
| 1313 |
-
else:
|
| 1314 |
-
return (boosted,) + output[1:]
|
| 1315 |
-
else:
|
| 1316 |
-
return output
|
| 1317 |
-
return hook
|
| 1318 |
|
| 1319 |
# ============================================================================
|
| 1320 |
# SPECIALIST MODEL 1: THE LIBRARIAN (GPU) - Database Intelligence
|
|
@@ -1403,22 +1676,28 @@ Analysis:"""
|
|
| 1403 |
|
| 1404 |
inputs = analyst_tokenizer(prompt, return_tensors="pt").to(analyst_model.device)
|
| 1405 |
|
| 1406 |
-
|
| 1407 |
-
|
| 1408 |
-
|
| 1409 |
-
|
| 1410 |
-
|
| 1411 |
-
|
| 1412 |
-
|
| 1413 |
-
|
| 1414 |
-
|
| 1415 |
-
|
| 1416 |
-
|
| 1417 |
-
|
| 1418 |
-
|
| 1419 |
-
|
| 1420 |
-
|
| 1421 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1422 |
|
| 1423 |
# ============================================================================
|
| 1424 |
# SPECIALIST MODEL 3: THE AUDITOR (CPU) - Quality Control
|
|
@@ -1449,31 +1728,37 @@ Audit Report:"""
|
|
| 1449 |
|
| 1450 |
inputs = auditor_tokenizer(prompt, return_tensors="pt").to(auditor_model.device)
|
| 1451 |
|
| 1452 |
-
|
| 1453 |
-
|
| 1454 |
-
|
| 1455 |
-
|
| 1456 |
-
|
| 1457 |
-
|
| 1458 |
-
|
| 1459 |
-
|
| 1460 |
-
|
| 1461 |
-
response = auditor_tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 1462 |
-
response = response[len(prompt):].strip()
|
| 1463 |
-
|
| 1464 |
-
if any(word in response.lower() for word in ['contradiction', 'weakness', 'gap', 'issue']):
|
| 1465 |
-
severity = "MEDIUM"
|
| 1466 |
-
if "critical" in response.lower():
|
| 1467 |
-
severity = "CRITICAL"
|
| 1468 |
-
elif "high" in response.lower():
|
| 1469 |
-
severity = "HIGH"
|
| 1470 |
-
elif "low" in response.lower():
|
| 1471 |
-
severity = "LOW"
|
| 1472 |
|
| 1473 |
-
|
| 1474 |
-
|
| 1475 |
-
|
| 1476 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1477 |
|
| 1478 |
# ============================================================================
|
| 1479 |
# BACKGROUND DISCOURSE MODELS (CPU) - 3 SPECIALISTS
|
|
@@ -2146,12 +2431,39 @@ Your role: Build systems that become more than the sum of their parts. Bridge th
|
|
| 2146 |
|
| 2147 |
|
| 2148 |
def generate_discourse_turn(agent_name, context, max_tokens=10000):
|
| 2149 |
-
"""Generate a discourse turn for a background agent"""
|
| 2150 |
global discourse_status
|
| 2151 |
|
| 2152 |
agent = DISCOURSE_AGENTS[agent_name]
|
| 2153 |
model = agent["model"]
|
| 2154 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2155 |
discourse_status["current_agent"] = agent_name
|
| 2156 |
discourse_status["tokens_generated"] = 0
|
| 2157 |
discourse_status["start_time"] = datetime.now()
|
|
@@ -2186,18 +2498,69 @@ def generate_discourse_turn(agent_name, context, max_tokens=10000):
|
|
| 2186 |
discourse_status["tokens_generated"] = len(bg_tokenizer.encode(response))
|
| 2187 |
discourse_status["last_update"] = datetime.now()
|
| 2188 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2189 |
return response
|
| 2190 |
|
| 2191 |
def background_discourse_loop():
|
| 2192 |
"""Continuous background discourse between specialist models"""
|
| 2193 |
global discourse_active
|
| 2194 |
|
| 2195 |
-
|
| 2196 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2197 |
while discourse_active:
|
| 2198 |
-
#
|
| 2199 |
-
random
|
| 2200 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2201 |
# Sequential execution of the specialists
|
| 2202 |
for agent_name in agent_names:
|
| 2203 |
if not discourse_active:
|
|
@@ -2385,6 +2748,37 @@ def predict(message, history, max_new_tokens):
|
|
| 2385 |
system_prompt += f"\n\n[EVE'S PERSPECTIVE]: {eve_response}\n\nADAM, you have just heard Eve's response above. Please integrate her insights into your own analysis. Do not repeat what she said, but build upon it or provide a complementary hyperbolic perspective."
|
| 2386 |
|
| 2387 |
hooks = []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2388 |
virtual_params_activated = 0
|
| 2389 |
honeycomb_cell = 0
|
| 2390 |
|
|
@@ -2514,6 +2908,17 @@ def predict(message, history, max_new_tokens):
|
|
| 2514 |
for h in hooks: h.remove()
|
| 2515 |
hooks = []
|
| 2516 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2517 |
perturbation_map, _ = navigator.generate_continuous_perturbations(psyche_coord, model)
|
| 2518 |
for layer_idx, p_list in perturbation_map.items():
|
| 2519 |
layer = model.model.layers[layer_idx]
|
|
@@ -2538,6 +2943,10 @@ def predict(message, history, max_new_tokens):
|
|
| 2538 |
# Cleanup hooks
|
| 2539 |
for h in hooks:
|
| 2540 |
h.remove()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2541 |
|
| 2542 |
last_conversation["user"] = message
|
| 2543 |
last_conversation["adam"] = partial_message
|
|
@@ -2758,9 +3167,71 @@ with gr.Blocks() as demo:
|
|
| 2758 |
# 4. Full Markdown Stats
|
| 2759 |
return params_active, f"{h_coord:.8f}", (cell_id // 16), stats
|
| 2760 |
|
|
|
|
| 2761 |
def sync_stats():
|
| 2762 |
-
|
| 2763 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2764 |
|
| 2765 |
def download_database():
|
| 2766 |
"""Return the database file for download"""
|
|
|
|
| 1021 |
|
| 1022 |
adam_personality = ADAMPersonality()
|
| 1023 |
|
| 1024 |
+
# ============================================================================
|
| 1025 |
+
# TIER 3: HYPERBOLIC ENGRAM TRACK INFRASTRUCTURE
|
| 1026 |
+
# ============================================================================
|
| 1027 |
+
|
| 1028 |
+
def get_engram_keys(input_ids, n=3):
|
| 1029 |
+
"""Generates 3-gram hashes for memory lookup."""
|
| 1030 |
+
keys = []
|
| 1031 |
+
if torch.is_tensor(input_ids):
|
| 1032 |
+
tokens = input_ids.tolist()
|
| 1033 |
+
else:
|
| 1034 |
+
tokens = input_ids
|
| 1035 |
+
|
| 1036 |
+
if len(tokens) > 0 and isinstance(tokens[0], list): # Handle batch
|
| 1037 |
+
tokens = tokens[0]
|
| 1038 |
+
|
| 1039 |
+
for i in range(len(tokens) - n + 1):
|
| 1040 |
+
gram = tokens[i:i+n]
|
| 1041 |
+
h = sum([t * (31**j) for j, t in enumerate(gram)])
|
| 1042 |
+
keys.append(h)
|
| 1043 |
+
|
| 1044 |
+
if not keys: # Handle short inputs
|
| 1045 |
+
return torch.tensor([0], dtype=torch.long)
|
| 1046 |
+
|
| 1047 |
+
return torch.tensor(keys, dtype=torch.long)
|
| 1048 |
+
|
| 1049 |
+
class HyperbolicAttentionHead(torch.nn.Module):
|
| 1050 |
+
"""
|
| 1051 |
+
A Hyperbolic Attention Head that attends to memory vectors in the PoincarΓ© Ball.
|
| 1052 |
+
"""
|
| 1053 |
+
def __init__(self, embedding_dim, hidden_dim, curvature=1.0):
|
| 1054 |
+
super().__init__()
|
| 1055 |
+
self.manifold = geoopt.manifolds.PoincareBall(c=curvature)
|
| 1056 |
+
self.query_proj = torch.nn.Linear(hidden_dim, embedding_dim)
|
| 1057 |
+
self.value_proj = torch.nn.Linear(embedding_dim, hidden_dim)
|
| 1058 |
+
self.curvature = curvature
|
| 1059 |
+
self.temperature = torch.nn.Parameter(torch.tensor(1.0))
|
| 1060 |
+
|
| 1061 |
+
def forward(self, hidden_states, memory_keys, memory_values):
|
| 1062 |
+
"""
|
| 1063 |
+
hidden_states: [Batch, Seq, Hidden] (Query)
|
| 1064 |
+
memory_keys: [Batch, MemSize, Embed] (Keys - on Manifold)
|
| 1065 |
+
memory_values: [Batch, MemSize, Embed] (Values)
|
| 1066 |
+
"""
|
| 1067 |
+
# 1. Project Query to Manifold
|
| 1068 |
+
q = self.query_proj(hidden_states) # [B, S, E]
|
| 1069 |
+
q_hyp = self.manifold.expmap0(q)
|
| 1070 |
+
|
| 1071 |
+
# 2. Compute Hyperbolic Distance Matrix
|
| 1072 |
+
# dist(x,y) = 2 artanh( || -x + y || / ... ) - simplified for stability
|
| 1073 |
+
# We broadcast: q:[B,S,1,E], k:[B,1,M,E]
|
| 1074 |
+
q_exp = q_hyp.unsqueeze(2)
|
| 1075 |
+
k_exp = memory_keys.unsqueeze(1)
|
| 1076 |
+
|
| 1077 |
+
# Approximate distance or use geoopt math if tensor shapes allow
|
| 1078 |
+
# For efficiency in this loop, we might use Euclidean as proxy or proper mobius addition
|
| 1079 |
+
# mobius_add(-x, y)
|
| 1080 |
+
dists = self.manifold.dist(q_exp, k_exp) # [B, S, M]
|
| 1081 |
+
|
| 1082 |
+
# 3. Attention Weights = Softmax(-dist / temp)
|
| 1083 |
+
attn_weights = torch.softmax(-dists / self.temperature, dim=-1)
|
| 1084 |
+
|
| 1085 |
+
# 4. Aggregate Values
|
| 1086 |
+
# values: [B, 1, M, E] -> broadcast to [B, S, M, E]
|
| 1087 |
+
# output = sum(weights * values)
|
| 1088 |
+
if memory_values.dim() == 2:
|
| 1089 |
+
v_exp = memory_values.unsqueeze(0).unsqueeze(0)
|
| 1090 |
+
else:
|
| 1091 |
+
v_exp = memory_values.unsqueeze(1)
|
| 1092 |
+
|
| 1093 |
+
context = torch.sum(attn_weights.unsqueeze(-1) * v_exp, dim=2) # [B, S, E]
|
| 1094 |
+
|
| 1095 |
+
# 5. Project back to Hidden Size
|
| 1096 |
+
output = self.value_proj(context)
|
| 1097 |
+
return output
|
| 1098 |
+
|
| 1099 |
+
class HyperbolicEngramMemory:
|
| 1100 |
+
def __init__(self, memory_dim, table_size=100000, curvature=1.0):
|
| 1101 |
+
"""
|
| 1102 |
+
Hyperbolic Engram Memory - Part of ADAM's Shadow Manifold.
|
| 1103 |
+
"""
|
| 1104 |
+
self.table_size = table_size
|
| 1105 |
+
self.memory_dim = memory_dim
|
| 1106 |
+
self.manifold = geoopt.manifolds.PoincareBall(c=curvature)
|
| 1107 |
+
|
| 1108 |
+
# Initialize table on CPU as coordinates in hyperbolic space
|
| 1109 |
+
# Xavier-style init but projected to Poincare ball
|
| 1110 |
+
raw_table = torch.randn(table_size, memory_dim) * 0.02
|
| 1111 |
+
self.memory_table = torch.nn.Parameter(
|
| 1112 |
+
self.manifold.expmap0(raw_table).to(torch.float16),
|
| 1113 |
+
requires_grad=False
|
| 1114 |
+
).to('cpu')
|
| 1115 |
+
|
| 1116 |
+
self.attention_head = HyperbolicAttentionHead(memory_dim, 2560) # Main model hidden dim
|
| 1117 |
+
|
| 1118 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 1119 |
+
self.logic_gate = torch.nn.Linear(memory_dim, 1).to(device)
|
| 1120 |
+
self.attention_head = self.attention_head.to(device) # Move head to device
|
| 1121 |
+
|
| 1122 |
+
torch.nn.init.constant_(self.logic_gate.bias, -2.0)
|
| 1123 |
+
|
| 1124 |
+
self.current_batch_memory = None
|
| 1125 |
+
self.memory_proj = None
|
| 1126 |
+
|
| 1127 |
+
print(f"β
Hyperbolic Engram Memory initialized:")
|
| 1128 |
+
print(f" Table size: {table_size:,} slots")
|
| 1129 |
+
print(f" Memory dim: {memory_dim}")
|
| 1130 |
+
print(f" Manifold: PoincarΓ© Ball (c={curvature})")
|
| 1131 |
+
|
| 1132 |
+
def lookup(self, keys):
|
| 1133 |
+
"""O(1) lookup from CPU memory table."""
|
| 1134 |
+
if keys.dim() == 2:
|
| 1135 |
+
keys = keys[0]
|
| 1136 |
+
|
| 1137 |
+
indices = torch.remainder(keys, self.table_size)
|
| 1138 |
+
device = self.logic_gate.weight.device
|
| 1139 |
+
memory_vectors = self.memory_table[indices].to(device)
|
| 1140 |
+
return memory_vectors
|
| 1141 |
+
|
| 1142 |
+
def create_engram_hook(engram_mem):
|
| 1143 |
+
"""Factory function for Engram injection hook."""
|
| 1144 |
+
def hook_fn(module, input_tuple, output):
|
| 1145 |
+
if isinstance(output, tuple):
|
| 1146 |
+
hidden_states = output[0]
|
| 1147 |
+
else:
|
| 1148 |
+
hidden_states = output
|
| 1149 |
+
|
| 1150 |
+
if engram_mem.current_batch_memory is None:
|
| 1151 |
+
return output
|
| 1152 |
+
|
| 1153 |
+
mem_vectors = engram_mem.current_batch_memory
|
| 1154 |
+
batch_size, seq_len, hidden_size = hidden_states.shape
|
| 1155 |
+
|
| 1156 |
+
# Ensure head is on right device/dtype
|
| 1157 |
+
engram_mem.attention_head.to(hidden_states.device).to(hidden_states.dtype)
|
| 1158 |
+
|
| 1159 |
+
# If we have memories, apply Hyperbolic Attention
|
| 1160 |
+
# mem_vectors is [Batch, K_Memories, Embed] or similar
|
| 1161 |
+
# For now, we assume mem_vectors are the KEYS and VALUES (Self-retrieval)
|
| 1162 |
+
if mem_vectors.dim() == 2:
|
| 1163 |
+
mem_vectors = mem_vectors.unsqueeze(0).expand(batch_size, -1, -1)
|
| 1164 |
+
|
| 1165 |
+
# Apply Hyperbolic Attention
|
| 1166 |
+
# Q = hidden_states, K = mem_vectors, V = mem_vectors
|
| 1167 |
+
attn_out = engram_mem.attention_head(hidden_states, mem_vectors, mem_vectors)
|
| 1168 |
+
|
| 1169 |
+
# Gating formulation: H_new = H + sigmoid(gate) * Attn_Out
|
| 1170 |
+
# We reuse the logic gate for scalar weighting or learn a new gate in the head
|
| 1171 |
+
# For now, simple residual connection with generic weight
|
| 1172 |
+
augmented_states = hidden_states + attn_out * 0.1 # Small initial influence
|
| 1173 |
+
|
| 1174 |
+
if isinstance(output, tuple):
|
| 1175 |
+
return (augmented_states,) + output[1:]
|
| 1176 |
+
else:
|
| 1177 |
+
return augmented_states
|
| 1178 |
+
|
| 1179 |
+
return hook_fn
|
| 1180 |
+
|
| 1181 |
+
# Global Engram Memory Initialization
|
| 1182 |
+
# Hidden size for Qwen3-4B is 2560
|
| 1183 |
+
engram_mem = HyperbolicEngramMemory(memory_dim=2560 // 4, table_size=100000)
|
| 1184 |
+
|
| 1185 |
+
|
| 1186 |
# ============================================================================
|
| 1187 |
# HYPERBOLIC NAVIGATOR - SHADOW PARAMETER GENERATION
|
| 1188 |
# ============================================================================
|
| 1189 |
+
|
| 1190 |
class HyperbolicNavigator:
|
| 1191 |
"""
|
|
|
|
| 1192 |
Maps embeddings to a PoincarΓ© ball manifold and generates
|
| 1193 |
trillion-scale addressable parameter states via continuous equations.
|
| 1194 |
"""
|
| 1195 |
def __init__(self, dimension=2560, curvature=1.0):
|
| 1196 |
self.dimension = dimension
|
| 1197 |
self.manifold = geoopt.manifolds.PoincareBall(c=curvature)
|
| 1198 |
+
self.device = "cpu" # Always CPU at init for Zero GPU compatibility
|
| 1199 |
|
| 1200 |
# Manifold Stats
|
| 1201 |
self.cells_activated = set()
|
|
|
|
| 1232 |
self.current_psyche_coord = torch.zeros(dimension, device=self.device)
|
| 1233 |
self.path_of_thought = []
|
| 1234 |
self.last_psyche_pulse = 0.0
|
| 1235 |
+
|
| 1236 |
+
|
| 1237 |
+
# --- RESONANCE ---
|
| 1238 |
+
self.resonance_alpha = 0.1 # Max amplification factor (1.1x)
|
| 1239 |
+
|
| 1240 |
+
def create_resonance_hook(self, layer_idx):
|
| 1241 |
+
"""
|
| 1242 |
+
Factory function creating a hook that modulates layer output
|
| 1243 |
+
based on hyperbolic proximity to the current thought vector.
|
| 1244 |
+
"""
|
| 1245 |
+
def hook_fn(module, input_tuple, output):
|
| 1246 |
+
# Compute distance from current psyche position to this layer's soul
|
| 1247 |
+
if layer_idx not in self.layer_constellation:
|
| 1248 |
+
return output
|
| 1249 |
+
|
| 1250 |
+
layer_coord = self.layer_constellation[layer_idx].to(self.device)
|
| 1251 |
+
current_coord = self.current_psyche_coord.to(self.device)
|
| 1252 |
+
|
| 1253 |
+
# Distance on manifold
|
| 1254 |
+
dist = self.hyperbolic_distance(current_coord, layer_coord).item()
|
| 1255 |
+
|
| 1256 |
+
# Resonance Equ: 1.0 + (alpha * exp(-dist))
|
| 1257 |
+
# Closer layers get amplified. Distant layers get baseline (1.0).
|
| 1258 |
+
resonance_factor = 1.0 + (self.resonance_alpha * math.exp(-dist))
|
| 1259 |
+
|
| 1260 |
+
# Apply scaling
|
| 1261 |
+
if isinstance(output, tuple):
|
| 1262 |
+
# Scale the hidden states (first element)
|
| 1263 |
+
new_hidden = output[0] * resonance_factor
|
| 1264 |
+
return (new_hidden,) + output[1:]
|
| 1265 |
+
return output * resonance_factor
|
| 1266 |
+
|
| 1267 |
+
return hook_fn
|
| 1268 |
+
|
| 1269 |
+
def apply_harmonic_resonance(self, model):
|
| 1270 |
+
"""
|
| 1271 |
+
Registers resonance hooks to ALL layers of the model.
|
| 1272 |
+
Returns a list of hook handles for removal.
|
| 1273 |
+
"""
|
| 1274 |
+
if not self.layer_constellation:
|
| 1275 |
+
return []
|
| 1276 |
+
|
| 1277 |
+
hooks = []
|
| 1278 |
+
if hasattr(model, "model") and hasattr(model.model, "layers"):
|
| 1279 |
+
layers = model.model.layers
|
| 1280 |
+
else:
|
| 1281 |
+
return []
|
| 1282 |
+
|
| 1283 |
+
for i, layer in enumerate(layers):
|
| 1284 |
+
if i in self.layer_constellation:
|
| 1285 |
+
hook_fn = self.create_resonance_hook(i)
|
| 1286 |
+
h = layer.register_forward_hook(hook_fn)
|
| 1287 |
+
hooks.append(h)
|
| 1288 |
+
|
| 1289 |
+
return hooks
|
| 1290 |
+
self.layer_constellation = {} # Map of LayerIndex -> HyperbolicCoordinate
|
| 1291 |
+
|
| 1292 |
+
def init_model_constellation(self, agents_dict):
|
| 1293 |
+
"""
|
| 1294 |
+
Maps all available discourse agents to the PoincarΓ© ball based on their weights.
|
| 1295 |
+
"""
|
| 1296 |
+
print("π Initializing Hyperbolic Model Constellation...")
|
| 1297 |
+
count = 0
|
| 1298 |
+
for name, details in agents_dict.items():
|
| 1299 |
+
model = details.get("model")
|
| 1300 |
+
if model:
|
| 1301 |
+
# Extract soul from weights
|
| 1302 |
+
coord = extract_model_soul(model, self.dimension)
|
| 1303 |
+
self.model_constellation[name] = coord
|
| 1304 |
+
print(f" β¨ Placed {name} at norm {torch.norm(coord):.4f}")
|
| 1305 |
+
count += 1
|
| 1306 |
+
else:
|
| 1307 |
+
# Fallback: Random semantic placement for lazy-loaded/unloaded models
|
| 1308 |
+
# (Ideally we would embed their persona description)
|
| 1309 |
+
# Deterministic random based on name hash
|
| 1310 |
+
g = torch.Generator()
|
| 1311 |
+
g.manual_seed(hash(name) % (2**32))
|
| 1312 |
+
raw = torch.randn(self.dimension, generator=g) * 0.1
|
| 1313 |
+
coord = self.exp_map(raw)
|
| 1314 |
+
self.model_constellation[name] = coord.to('cpu')
|
| 1315 |
+
print(f" π {name} (Hybrid/Lazy) placed at norm {torch.norm(coord):.4f}")
|
| 1316 |
+
|
| 1317 |
+
print(f"π Constellation complete. {len(self.model_constellation)} stars mapped.")
|
| 1318 |
+
|
| 1319 |
+
def init_layer_constellation(self, main_model):
|
| 1320 |
+
"""
|
| 1321 |
+
Maps the internal layers of the main model to the PoincarΓ© ball.
|
| 1322 |
+
"""
|
| 1323 |
+
print("π Initializing Internal Layer Constellation...")
|
| 1324 |
+
self.layer_constellation = extract_layer_souls(main_model, self.dimension)
|
| 1325 |
+
print(f" β¨ Mapped {len(self.layer_constellation)} internal layers to the manifold.")
|
| 1326 |
+
|
| 1327 |
+
def get_nearest_agents(self, current_coord, top_k=3):
|
| 1328 |
+
"""
|
| 1329 |
+
Returns the top_k agents closest to the current hyperbolic coordinate.
|
| 1330 |
+
Influence = exp(-distance)
|
| 1331 |
+
"""
|
| 1332 |
+
if not self.model_constellation:
|
| 1333 |
+
return []
|
| 1334 |
+
|
| 1335 |
+
distances = []
|
| 1336 |
+
curr = current_coord.cpu()
|
| 1337 |
+
if curr.dim() > 1: curr = curr.squeeze()
|
| 1338 |
+
|
| 1339 |
+
for name, agent_coord in self.model_constellation.items():
|
| 1340 |
+
# Riemannian distance on the ball
|
| 1341 |
+
dist = self.hyperbolic_distance(curr, agent_coord.squeeze())
|
| 1342 |
+
distances.append((name, dist.item()))
|
| 1343 |
+
|
| 1344 |
+
# Sort by distance (ascending)
|
| 1345 |
+
distances.sort(key=lambda x: x[1])
|
| 1346 |
+
|
| 1347 |
+
return distances[:top_k]
|
| 1348 |
+
|
| 1349 |
+
def get_nearest_layers(self, current_coord, top_k=3):
|
| 1350 |
+
"""
|
| 1351 |
+
Returns the top_k internal layers closest to the current hyperbolic coordinate.
|
| 1352 |
+
"""
|
| 1353 |
+
if not self.layer_constellation:
|
| 1354 |
+
return []
|
| 1355 |
+
|
| 1356 |
+
distances = []
|
| 1357 |
+
curr = current_coord.cpu()
|
| 1358 |
+
if curr.dim() > 1: curr = curr.squeeze()
|
| 1359 |
+
|
| 1360 |
+
for layer_idx, layer_coord in self.layer_constellation.items():
|
| 1361 |
+
dist = self.hyperbolic_distance(curr, layer_coord.squeeze())
|
| 1362 |
+
distances.append((layer_idx, dist.item()))
|
| 1363 |
+
|
| 1364 |
+
distances.sort(key=lambda x: x[1])
|
| 1365 |
+
return distances[:top_k]
|
| 1366 |
+
|
| 1367 |
|
| 1368 |
def exp_map(self, v, p=None):
|
| 1369 |
"""Map Euclidean tangent vector v at p to PoincarΓ© ball."""
|
|
|
|
| 1581 |
"hyper_coord": 0.0,
|
| 1582 |
"virtual_params_active": 756000000, # Baseline manifold activation
|
| 1583 |
"honeycomb_cell": 0,
|
| 1584 |
+
"cells_activated": 1,
|
| 1585 |
+
"nearest_agents": []
|
| 1586 |
}
|
| 1587 |
|
| 1588 |
+
# ============================================================================
|
| 1589 |
+
# TIER 4: MODEL CONSTELLATION (WEIGHT-SPACE NAVIGATION)
|
| 1590 |
+
# ============================================================================
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1591 |
|
| 1592 |
# ============================================================================
|
| 1593 |
# SPECIALIST MODEL 1: THE LIBRARIAN (GPU) - Database Intelligence
|
|
|
|
| 1676 |
|
| 1677 |
inputs = analyst_tokenizer(prompt, return_tensors="pt").to(analyst_model.device)
|
| 1678 |
|
| 1679 |
+
try:
|
| 1680 |
+
with torch.no_grad():
|
| 1681 |
+
outputs = analyst_model.generate(
|
| 1682 |
+
**inputs,
|
| 1683 |
+
max_new_tokens=512,
|
| 1684 |
+
do_sample=True,
|
| 1685 |
+
temperature=0.7,
|
| 1686 |
+
top_p=0.9,
|
| 1687 |
+
)
|
| 1688 |
+
|
| 1689 |
+
response = analyst_tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 1690 |
+
response = response[len(prompt):].strip()
|
| 1691 |
+
|
| 1692 |
+
if "pattern:" in response.lower():
|
| 1693 |
+
save_user_pattern("conversation_pattern", response[:500])
|
| 1694 |
+
|
| 1695 |
+
return response
|
| 1696 |
+
finally:
|
| 1697 |
+
# Explicit cleanup to prevent tensor deallocation warnings
|
| 1698 |
+
if 'inputs' in locals(): del inputs
|
| 1699 |
+
if 'outputs' in locals(): del outputs
|
| 1700 |
+
gc.collect()
|
| 1701 |
|
| 1702 |
# ============================================================================
|
| 1703 |
# SPECIALIST MODEL 3: THE AUDITOR (CPU) - Quality Control
|
|
|
|
| 1728 |
|
| 1729 |
inputs = auditor_tokenizer(prompt, return_tensors="pt").to(auditor_model.device)
|
| 1730 |
|
| 1731 |
+
try:
|
| 1732 |
+
with torch.no_grad():
|
| 1733 |
+
outputs = auditor_model.generate(
|
| 1734 |
+
**inputs,
|
| 1735 |
+
max_new_tokens=5000,
|
| 1736 |
+
do_sample=True,
|
| 1737 |
+
temperature=0.6,
|
| 1738 |
+
top_p=0.9,
|
| 1739 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1740 |
|
| 1741 |
+
response = auditor_tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 1742 |
+
response = response[len(prompt):].strip()
|
| 1743 |
+
|
| 1744 |
+
if any(word in response.lower() for word in ['contradiction', 'weakness', 'gap', 'issue']):
|
| 1745 |
+
severity = "MEDIUM"
|
| 1746 |
+
if "critical" in response.lower():
|
| 1747 |
+
severity = "CRITICAL"
|
| 1748 |
+
elif "high" in response.lower():
|
| 1749 |
+
severity = "HIGH"
|
| 1750 |
+
elif "low" in response.lower():
|
| 1751 |
+
severity = "LOW"
|
| 1752 |
+
|
| 1753 |
+
timestamp = datetime.now().strftime("%H:%M:%S")
|
| 1754 |
+
save_audit_log("logical_audit", model_name, response[:500], severity, timestamp)
|
| 1755 |
+
|
| 1756 |
+
return response
|
| 1757 |
+
finally:
|
| 1758 |
+
# Explicit cleanup to prevent tensor deallocation warnings
|
| 1759 |
+
if 'inputs' in locals(): del inputs
|
| 1760 |
+
if 'outputs' in locals(): del outputs
|
| 1761 |
+
gc.collect()
|
| 1762 |
|
| 1763 |
# ============================================================================
|
| 1764 |
# BACKGROUND DISCOURSE MODELS (CPU) - 3 SPECIALISTS
|
|
|
|
| 2431 |
|
| 2432 |
|
| 2433 |
def generate_discourse_turn(agent_name, context, max_tokens=10000):
|
| 2434 |
+
"""Generate a discourse turn for a background agent with Engram Memory integration."""
|
| 2435 |
global discourse_status
|
| 2436 |
|
| 2437 |
agent = DISCOURSE_AGENTS[agent_name]
|
| 2438 |
model = agent["model"]
|
| 2439 |
|
| 2440 |
+
# --- HYPERBOLIC ENGRAM ACTIVATION ---
|
| 2441 |
+
hooks = []
|
| 2442 |
+
try:
|
| 2443 |
+
# Extract keys from context
|
| 2444 |
+
context_ids = bg_tokenizer.encode(context, add_special_tokens=False)
|
| 2445 |
+
keys = get_engram_keys(context_ids, n=3)
|
| 2446 |
+
|
| 2447 |
+
# Hyperbolic memory lookup
|
| 2448 |
+
mem_vectors = engram_mem.lookup(keys)
|
| 2449 |
+
engram_mem.current_batch_memory = mem_vectors
|
| 2450 |
+
|
| 2451 |
+
# Register hooks for memory injection
|
| 2452 |
+
hook_fn = create_engram_hook(engram_mem)
|
| 2453 |
+
for layer_idx in [2, 15]:
|
| 2454 |
+
if hasattr(model, "model") and hasattr(model.model, "layers"):
|
| 2455 |
+
layer = model.model.layers[layer_idx]
|
| 2456 |
+
h = layer.register_forward_hook(hook_fn)
|
| 2457 |
+
hooks.append(h)
|
| 2458 |
+
elif hasattr(model, "transformer") and hasattr(model.transformer, "h"):
|
| 2459 |
+
layer = model.transformer.h[layer_idx]
|
| 2460 |
+
h = layer.register_forward_hook(hook_fn)
|
| 2461 |
+
hooks.append(h)
|
| 2462 |
+
except Exception as e:
|
| 2463 |
+
print(f"β οΈ [ENGRAM] Failed to activate memory for {agent_name}: {e}")
|
| 2464 |
+
engram_mem.current_batch_memory = None
|
| 2465 |
+
# ------------------------------------
|
| 2466 |
+
|
| 2467 |
discourse_status["current_agent"] = agent_name
|
| 2468 |
discourse_status["tokens_generated"] = 0
|
| 2469 |
discourse_status["start_time"] = datetime.now()
|
|
|
|
| 2498 |
discourse_status["tokens_generated"] = len(bg_tokenizer.encode(response))
|
| 2499 |
discourse_status["last_update"] = datetime.now()
|
| 2500 |
|
| 2501 |
+
# --- HYPERBOLIC ENGRAM CLEANUP ---
|
| 2502 |
+
for h in hooks:
|
| 2503 |
+
h.remove()
|
| 2504 |
+
engram_mem.current_batch_memory = None
|
| 2505 |
+
|
| 2506 |
+
# Explicit cleanup to prevent tensor deallocation warnings
|
| 2507 |
+
if 'inputs' in locals(): del inputs
|
| 2508 |
+
gc.collect()
|
| 2509 |
+
# ---------------------------------
|
| 2510 |
+
|
| 2511 |
return response
|
| 2512 |
|
| 2513 |
def background_discourse_loop():
|
| 2514 |
"""Continuous background discourse between specialist models"""
|
| 2515 |
global discourse_active
|
| 2516 |
|
| 2517 |
+
|
| 2518 |
+
# Initialize Navigation Constellation if needed
|
| 2519 |
+
if not navigator.model_constellation:
|
| 2520 |
+
navigator.init_model_constellation(DISCOURSE_AGENTS)
|
| 2521 |
+
|
| 2522 |
+
# Initialize Layer Constellation if main model is ready
|
| 2523 |
+
if model and not navigator.layer_constellation:
|
| 2524 |
+
navigator.init_layer_constellation(model)
|
| 2525 |
+
|
| 2526 |
while discourse_active:
|
| 2527 |
+
# --- HYPERBOLIC NAVIGATION ---
|
| 2528 |
+
# Instead of random shuffle, we select agents based on proximity to ADAM's current thought vector
|
| 2529 |
+
try:
|
| 2530 |
+
current_pos = navigator.current_psyche_coord
|
| 2531 |
+
|
| 2532 |
+
# 1. Update Agent Proximity
|
| 2533 |
+
nearest_agents = navigator.get_nearest_agents(current_pos, top_k=3)
|
| 2534 |
+
last_conversation["nearest_agents"] = [n for n, d in nearest_agents]
|
| 2535 |
+
|
| 2536 |
+
# 2. Update Layer Proximity
|
| 2537 |
+
if navigator.layer_constellation:
|
| 2538 |
+
nearest_layers = navigator.get_nearest_layers(current_pos, top_k=3)
|
| 2539 |
+
last_conversation["nearest_layers"] = nearest_layers
|
| 2540 |
+
|
| 2541 |
+
# Selection Strategy: Prioritize closest agents (80%) or Explore (20%)
|
| 2542 |
+
nearest = nearest_agents # Alias for backward compatibility in selection logic
|
| 2543 |
+
# 80% chance to pick from nearest (weighted by inverse distance)
|
| 2544 |
+
# 20% chance to pick random (to ensure diversity/exploration)
|
| 2545 |
+
if random.random() < 0.8 and nearest:
|
| 2546 |
+
# Pick one of the top 3, weighted by closeness
|
| 2547 |
+
# distance is in [0, inf), influence = exp(-dist)
|
| 2548 |
+
weights = [math.exp(-d) for n, d in nearest]
|
| 2549 |
+
total_w = sum(weights)
|
| 2550 |
+
probs = [w/total_w for w in weights]
|
| 2551 |
+
agent_names = [random.choices([n for n, d in nearest], weights=probs, k=1)[0]]
|
| 2552 |
+
print(f"π§ [NAV] Adam drifted to {agent_names[0]}")
|
| 2553 |
+
else:
|
| 2554 |
+
agent_names = list(DISCOURSE_AGENTS.keys())
|
| 2555 |
+
random.shuffle(agent_names)
|
| 2556 |
+
agent_names = agent_names[:1] # Just pick one random to start
|
| 2557 |
+
print(f"π² [NAV] Random exploration context switch.")
|
| 2558 |
+
|
| 2559 |
+
except Exception as e:
|
| 2560 |
+
print(f"β οΈ Navigation Error: {e}")
|
| 2561 |
+
agent_names = list(DISCOURSE_AGENTS.keys())
|
| 2562 |
+
random.shuffle(agent_names)
|
| 2563 |
+
|
| 2564 |
# Sequential execution of the specialists
|
| 2565 |
for agent_name in agent_names:
|
| 2566 |
if not discourse_active:
|
|
|
|
| 2748 |
system_prompt += f"\n\n[EVE'S PERSPECTIVE]: {eve_response}\n\nADAM, you have just heard Eve's response above. Please integrate her insights into your own analysis. Do not repeat what she said, but build upon it or provide a complementary hyperbolic perspective."
|
| 2749 |
|
| 2750 |
hooks = []
|
| 2751 |
+
|
| 2752 |
+
# --- HYPERBOLIC ENGRAM ACTIVATION ---
|
| 2753 |
+
try:
|
| 2754 |
+
# Extract keys from user message
|
| 2755 |
+
msg_ids = tokenizer.encode(message, add_special_tokens=False)
|
| 2756 |
+
keys = get_engram_keys(msg_ids, n=3)
|
| 2757 |
+
|
| 2758 |
+
# Hyperbolic memory lookup
|
| 2759 |
+
engram_mem.current_batch_memory = engram_mem.lookup(keys)
|
| 2760 |
+
|
| 2761 |
+
# Register hooks for memory injection on main model
|
| 2762 |
+
engram_hook_fn = create_engram_hook(engram_mem)
|
| 2763 |
+
for layer_idx in [2, 15]:
|
| 2764 |
+
layer = model.model.layers[layer_idx]
|
| 2765 |
+
h = layer.register_forward_hook(engram_hook_fn)
|
| 2766 |
+
hooks.append(h)
|
| 2767 |
+
print(f"β
[ENGRAM] Memory activated for main model (Keys: {len(keys)})")
|
| 2768 |
+
except Exception as e:
|
| 2769 |
+
print(f"β οΈ [ENGRAM] Main model setup failed: {e}")
|
| 2770 |
+
engram_mem.current_batch_memory = None
|
| 2771 |
+
|
| 2772 |
+
# --- HARMONIC LAYER RESONANCE ---
|
| 2773 |
+
try:
|
| 2774 |
+
res_hooks = navigator.apply_harmonic_resonance(model)
|
| 2775 |
+
hooks.extend(res_hooks)
|
| 2776 |
+
if res_hooks:
|
| 2777 |
+
print(f"β
[RESONANCE] Harmonic feedback active on {len(res_hooks)} layers.")
|
| 2778 |
+
except Exception as e:
|
| 2779 |
+
print(f"β οΈ [RESONANCE] Failed to apply harmonic hooks: {e}")
|
| 2780 |
+
# --------------------------------
|
| 2781 |
+
|
| 2782 |
virtual_params_activated = 0
|
| 2783 |
honeycomb_cell = 0
|
| 2784 |
|
|
|
|
| 2908 |
for h in hooks: h.remove()
|
| 2909 |
hooks = []
|
| 2910 |
|
| 2911 |
+
# Re-register Engram hooks first
|
| 2912 |
+
try:
|
| 2913 |
+
if engram_mem.current_batch_memory is not None:
|
| 2914 |
+
engram_hook_fn = create_engram_hook(engram_mem)
|
| 2915 |
+
for layer_idx in [2, 15]:
|
| 2916 |
+
layer = model.model.layers[layer_idx]
|
| 2917 |
+
h = layer.register_forward_hook(engram_hook_fn)
|
| 2918 |
+
hooks.append(h)
|
| 2919 |
+
except Exception as e:
|
| 2920 |
+
print(f"β οΈ [ENGRAM] Pulse re-registration failed: {e}")
|
| 2921 |
+
|
| 2922 |
perturbation_map, _ = navigator.generate_continuous_perturbations(psyche_coord, model)
|
| 2923 |
for layer_idx, p_list in perturbation_map.items():
|
| 2924 |
layer = model.model.layers[layer_idx]
|
|
|
|
| 2943 |
# Cleanup hooks
|
| 2944 |
for h in hooks:
|
| 2945 |
h.remove()
|
| 2946 |
+
engram_mem.current_batch_memory = None
|
| 2947 |
+
# Explicit cleanup to prevent tensor deallocation warnings
|
| 2948 |
+
if 'inputs' in locals(): del inputs
|
| 2949 |
+
gc.collect()
|
| 2950 |
|
| 2951 |
last_conversation["user"] = message
|
| 2952 |
last_conversation["adam"] = partial_message
|
|
|
|
| 3167 |
# 4. Full Markdown Stats
|
| 3168 |
return params_active, f"{h_coord:.8f}", (cell_id // 16), stats
|
| 3169 |
|
| 3170 |
+
|
| 3171 |
def sync_stats():
|
| 3172 |
+
# Get actual params from last conversation
|
| 3173 |
+
params_active = last_conversation.get('virtual_params_active', 0)
|
| 3174 |
+
h_coord = last_conversation.get('hyper_coord', 0.0)
|
| 3175 |
+
e_norm = last_conversation.get('euclidean_norm', 0.0)
|
| 3176 |
+
e_dim = last_conversation.get('embedding_dim', 0)
|
| 3177 |
+
cell_id = last_conversation.get('honeycomb_cell', 0)
|
| 3178 |
+
nearest_agents = last_conversation.get('nearest_agents', [])
|
| 3179 |
+
nearest_layers = last_conversation.get('nearest_layers', [])
|
| 3180 |
+
|
| 3181 |
+
# Honeycomb Region Description
|
| 3182 |
+
dim_base = navigator.dimension
|
| 3183 |
+
shell = cell_id // dim_base
|
| 3184 |
+
sector = cell_id % dim_base
|
| 3185 |
+
region = "Central Tesseract" if shell == 0 else f"Hyper-Deep Manifold (Shell {shell})"
|
| 3186 |
+
|
| 3187 |
+
# --- TOPOGRAPHY STATS ---
|
| 3188 |
+
current_law = navigator.get_current_law(cell_id)
|
| 3189 |
+
current_stability = navigator.get_stability(cell_id)
|
| 3190 |
+
current_landmark = navigator.landmarks.get(cell_id, "Uncharted Territory")
|
| 3191 |
+
psyche_pulse = navigator.last_psyche_pulse
|
| 3192 |
+
path_len = len(navigator.path_of_thought)
|
| 3193 |
+
|
| 3194 |
+
stats = "# π Hyper-Manifold Telemetry\n\n"
|
| 3195 |
+
|
| 3196 |
+
# --- MODEL CONSTELLATION ---
|
| 3197 |
+
stats += "### π Model Constellation\n"
|
| 3198 |
+
if nearest_agents:
|
| 3199 |
+
stats += f"**π ADAM'S AGENT TRAJECTORY:**\n"
|
| 3200 |
+
for i, (name, dist) in enumerate(nearest_agents, 1):
|
| 3201 |
+
influence = math.exp(-dist) * 100
|
| 3202 |
+
stats += f"{i}. **{name.upper()}** (Dist: {dist:.4f} | Inf: {influence:.1f}%)\n"
|
| 3203 |
+
else:
|
| 3204 |
+
stats += "*Agent constellation initializing...*\n"
|
| 3205 |
+
|
| 3206 |
+
stats += "\n"
|
| 3207 |
+
|
| 3208 |
+
# --- LAYER CONSTELLATION ---
|
| 3209 |
+
if nearest_layers:
|
| 3210 |
+
stats += f"**π§ DEPTH RESONANCE (Internal Layers):**\n"
|
| 3211 |
+
for i, (layer_idx, dist) in enumerate(nearest_layers, 1):
|
| 3212 |
+
# Interpret layer depth
|
| 3213 |
+
depth_desc = "Surface" if layer_idx < 10 else "Deep" if layer_idx > 25 else "Mid"
|
| 3214 |
+
stats += f"{i}. **Layer {layer_idx}** ({depth_desc}) - Dist: {dist:.4f}\n"
|
| 3215 |
+
else:
|
| 3216 |
+
stats += "*Layer mapping pending main model load...*\n"
|
| 3217 |
+
|
| 3218 |
+
stats += "\n---\n\n"
|
| 3219 |
+
|
| 3220 |
+
stats += "### π Manifold State\n"
|
| 3221 |
+
stats += f"- **Embedding Dimensionality:** {e_dim} (Native Resolve)\n"
|
| 3222 |
+
stats += f"- **Euclidean Entry Norm:** {e_norm:.4f} (10x Temperature Scaling)\n"
|
| 3223 |
+
stats += f"- **Active Injected Parameters:** {params_active:,}\n"
|
| 3224 |
+
stats += f"- **Current Hyperbolic Depth:** {h_coord:.8f}\n"
|
| 3225 |
+
stats += f"- **Manifold Neighborhood:** {region} (Cell {cell_id})\n"
|
| 3226 |
+
stats += f"- **Current Landmark:** {current_landmark}\n"
|
| 3227 |
+
stats += f"- **Cognitive Law:** `{current_law}`\n"
|
| 3228 |
+
stats += f"- **Sector Stability:** {current_stability:.2f}\n"
|
| 3229 |
+
stats += f"- **Internal Psyche Pulse:** {psyche_pulse:.4f} (Activation Energy)\n"
|
| 3230 |
+
stats += f"- **Geometric Path Length:** {path_len} thought steps\n"
|
| 3231 |
+
stats += f"- **Active Honeycomb Sector:** {sector} / {dim_base}\n"
|
| 3232 |
+
stats += f"- **Total Manifold Regions Explored:** {len(navigator.cells_activated)}\n\n"
|
| 3233 |
+
|
| 3234 |
+
return params_active, f"{h_coord:.8f}", (cell_id // 16), stats
|
| 3235 |
|
| 3236 |
def download_database():
|
| 3237 |
"""Return the database file for download"""
|