EVEprime commited on
Commit
fca95fc
·
verified ·
1 Parent(s): 9e3d731

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +188 -1
app.py CHANGED
@@ -1021,6 +1021,126 @@ 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
  # ============================================================================
@@ -2146,12 +2266,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,6 +2333,12 @@ 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():
@@ -2385,6 +2538,28 @@ 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 +2689,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 +2724,7 @@ 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
 
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 HyperbolicEngramMemory:
1050
+ def __init__(self, memory_dim, table_size=100000, curvature=1.0):
1051
+ """
1052
+ Hyperbolic Engram Memory - Part of ADAM's Shadow Manifold.
1053
+ """
1054
+ self.table_size = table_size
1055
+ self.memory_dim = memory_dim
1056
+ self.manifold = geoopt.manifolds.PoincareBall(c=curvature)
1057
+
1058
+ # Initialize table on CPU as coordinates in hyperbolic space
1059
+ # Xavier-style init but projected to Poincare ball
1060
+ raw_table = torch.randn(table_size, memory_dim) * 0.02
1061
+ self.memory_table = torch.nn.Parameter(
1062
+ self.manifold.expmap0(raw_table).to(torch.float16),
1063
+ requires_grad=False
1064
+ ).to('cpu')
1065
+
1066
+ device = "cuda" if torch.cuda.is_available() else "cpu"
1067
+ self.logic_gate = torch.nn.Linear(memory_dim, 1).to(device)
1068
+ torch.nn.init.constant_(self.logic_gate.bias, -2.0)
1069
+
1070
+ self.current_batch_memory = None
1071
+ self.memory_proj = None
1072
+
1073
+ print(f"✅ Hyperbolic Engram Memory initialized:")
1074
+ print(f" Table size: {table_size:,} slots")
1075
+ print(f" Memory dim: {memory_dim}")
1076
+ print(f" Manifold: Poincaré Ball (c={curvature})")
1077
+
1078
+ def lookup(self, keys):
1079
+ """O(1) lookup from CPU memory table."""
1080
+ if keys.dim() == 2:
1081
+ keys = keys[0]
1082
+
1083
+ indices = torch.remainder(keys, self.table_size)
1084
+ device = self.logic_gate.weight.device
1085
+ memory_vectors = self.memory_table[indices].to(device)
1086
+ return memory_vectors
1087
+
1088
+ def create_engram_hook(engram_mem):
1089
+ """Factory function for Engram injection hook."""
1090
+ def hook_fn(module, input_tuple, output):
1091
+ if isinstance(output, tuple):
1092
+ hidden_states = output[0]
1093
+ else:
1094
+ hidden_states = output
1095
+
1096
+ if engram_mem.current_batch_memory is None:
1097
+ return output
1098
+
1099
+ mem_vectors = engram_mem.current_batch_memory
1100
+ batch_size, seq_len, hidden_size = hidden_states.shape
1101
+ mem_seq_len = mem_vectors.shape[0]
1102
+
1103
+ if seq_len == 1:
1104
+ if mem_seq_len > 0:
1105
+ mem_vec = mem_vectors[-1:, :]
1106
+ else:
1107
+ return output
1108
+ elif seq_len == mem_seq_len:
1109
+ mem_vec = mem_vectors
1110
+ elif seq_len > mem_seq_len:
1111
+ padding = torch.zeros(seq_len - mem_seq_len, mem_vectors.shape[1], device=mem_vectors.device, dtype=mem_vectors.dtype)
1112
+ mem_vec = torch.cat([mem_vectors, padding], dim=0)
1113
+ else:
1114
+ mem_vec = mem_vectors[:seq_len, :]
1115
+
1116
+ if engram_mem.memory_proj is None:
1117
+ engram_mem.memory_proj = torch.nn.Linear(engram_mem.memory_dim, hidden_size).to(hidden_states.device)
1118
+ torch.nn.init.xavier_uniform_(engram_mem.memory_proj.weight, gain=0.1)
1119
+
1120
+ engram_mem.memory_proj = engram_mem.memory_proj.to(hidden_states.dtype)
1121
+ engram_mem.logic_gate = engram_mem.logic_gate.to(hidden_states.dtype)
1122
+ mem_vec = mem_vec.to(hidden_states.dtype)
1123
+
1124
+ mem_projected = engram_mem.memory_proj(mem_vec)
1125
+ gate_scores = torch.sigmoid(engram_mem.logic_gate(mem_vec))
1126
+
1127
+ mem_projected = mem_projected.unsqueeze(0)
1128
+ gate_scores = gate_scores.unsqueeze(0)
1129
+
1130
+ augmented_states = hidden_states + (gate_scores * mem_projected)
1131
+
1132
+ if isinstance(output, tuple):
1133
+ return (augmented_states,) + output[1:]
1134
+ else:
1135
+ return augmented_states
1136
+
1137
+ return hook_fn
1138
+
1139
+ # Global Engram Memory Initialization
1140
+ # Hidden size for Qwen3-4B is 2560
1141
+ engram_mem = HyperbolicEngramMemory(memory_dim=2560 // 4, table_size=100000)
1142
+
1143
+
1144
  # ============================================================================
1145
  # HYPERBOLIC NAVIGATOR - SHADOW PARAMETER GENERATION
1146
  # ============================================================================
 
2266
 
2267
 
2268
  def generate_discourse_turn(agent_name, context, max_tokens=10000):
2269
+ """Generate a discourse turn for a background agent with Engram Memory integration."""
2270
  global discourse_status
2271
 
2272
  agent = DISCOURSE_AGENTS[agent_name]
2273
  model = agent["model"]
2274
 
2275
+ # --- HYPERBOLIC ENGRAM ACTIVATION ---
2276
+ hooks = []
2277
+ try:
2278
+ # Extract keys from context
2279
+ context_ids = bg_tokenizer.encode(context, add_special_tokens=False)
2280
+ keys = get_engram_keys(context_ids, n=3)
2281
+
2282
+ # Hyperbolic memory lookup
2283
+ mem_vectors = engram_mem.lookup(keys)
2284
+ engram_mem.current_batch_memory = mem_vectors
2285
+
2286
+ # Register hooks for memory injection
2287
+ hook_fn = create_engram_hook(engram_mem)
2288
+ for layer_idx in [2, 15]:
2289
+ if hasattr(model, "model") and hasattr(model.model, "layers"):
2290
+ layer = model.model.layers[layer_idx]
2291
+ h = layer.register_forward_hook(hook_fn)
2292
+ hooks.append(h)
2293
+ elif hasattr(model, "transformer") and hasattr(model.transformer, "h"):
2294
+ layer = model.transformer.h[layer_idx]
2295
+ h = layer.register_forward_hook(hook_fn)
2296
+ hooks.append(h)
2297
+ except Exception as e:
2298
+ print(f"⚠️ [ENGRAM] Failed to activate memory for {agent_name}: {e}")
2299
+ engram_mem.current_batch_memory = None
2300
+ # ------------------------------------
2301
+
2302
  discourse_status["current_agent"] = agent_name
2303
  discourse_status["tokens_generated"] = 0
2304
  discourse_status["start_time"] = datetime.now()
 
2333
  discourse_status["tokens_generated"] = len(bg_tokenizer.encode(response))
2334
  discourse_status["last_update"] = datetime.now()
2335
 
2336
+ # --- HYPERBOLIC ENGRAM CLEANUP ---
2337
+ for h in hooks:
2338
+ h.remove()
2339
+ engram_mem.current_batch_memory = None
2340
+ # ---------------------------------
2341
+
2342
  return response
2343
 
2344
  def background_discourse_loop():
 
2538
  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."
2539
 
2540
  hooks = []
2541
+
2542
+ # --- HYPERBOLIC ENGRAM ACTIVATION ---
2543
+ try:
2544
+ # Extract keys from user message
2545
+ msg_ids = tokenizer.encode(message, add_special_tokens=False)
2546
+ keys = get_engram_keys(msg_ids, n=3)
2547
+
2548
+ # Hyperbolic memory lookup
2549
+ engram_mem.current_batch_memory = engram_mem.lookup(keys)
2550
+
2551
+ # Register hooks for memory injection on main model
2552
+ engram_hook_fn = create_engram_hook(engram_mem)
2553
+ for layer_idx in [2, 15]:
2554
+ layer = model.model.layers[layer_idx]
2555
+ h = layer.register_forward_hook(engram_hook_fn)
2556
+ hooks.append(h)
2557
+ print(f"✅ [ENGRAM] Memory activated for main model (Keys: {len(keys)})")
2558
+ except Exception as e:
2559
+ print(f"⚠️ [ENGRAM] Main model setup failed: {e}")
2560
+ engram_mem.current_batch_memory = None
2561
+ # ------------------------------------
2562
+
2563
  virtual_params_activated = 0
2564
  honeycomb_cell = 0
2565
 
 
2689
  for h in hooks: h.remove()
2690
  hooks = []
2691
 
2692
+ # Re-register Engram hooks first
2693
+ try:
2694
+ if engram_mem.current_batch_memory is not None:
2695
+ engram_hook_fn = create_engram_hook(engram_mem)
2696
+ for layer_idx in [2, 15]:
2697
+ layer = model.model.layers[layer_idx]
2698
+ h = layer.register_forward_hook(engram_hook_fn)
2699
+ hooks.append(h)
2700
+ except Exception as e:
2701
+ print(f"⚠️ [ENGRAM] Pulse re-registration failed: {e}")
2702
+
2703
  perturbation_map, _ = navigator.generate_continuous_perturbations(psyche_coord, model)
2704
  for layer_idx, p_list in perturbation_map.items():
2705
  layer = model.model.layers[layer_idx]
 
2724
  # Cleanup hooks
2725
  for h in hooks:
2726
  h.remove()
2727
+ engram_mem.current_batch_memory = None
2728
 
2729
  last_conversation["user"] = message
2730
  last_conversation["adam"] = partial_message