camdog920 commited on
Commit
02f3a07
·
verified ·
1 Parent(s): 53d96ac

Upload main.py

Browse files
Files changed (1) hide show
  1. main.py +1185 -0
main.py ADDED
@@ -0,0 +1,1185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ AETHER v0.3.0 — Autonomous Self-Evolving Architecture (HF Space)
3
+ ==================================================================
4
+ Runs continuously in a Docker Space. Background evolution thread persists
5
+ memory, knowledge graph, and architecture checkpoints to the HF Hub via
6
+ CommitScheduler. Executes tasks via REST API even when browser tabs are closed.
7
+
8
+ Endpoints:
9
+ GET / → Gradio monitoring dashboard
10
+ GET /status → Live system state (JSON)
11
+ POST /task → Submit a reasoning task (async)
12
+ GET /task/{id}→ Get task result
13
+ POST /evolve → Trigger one-shot evolution
14
+ GET /history → Evolution trajectory
15
+ GET /kg → Knowledge graph stats
16
+ """
17
+
18
+ import os, sys, time, json, hashlib, copy, random, warnings, asyncio, threading
19
+ from pathlib import Path
20
+ from dataclasses import dataclass, asdict
21
+ from typing import Dict, List, Any, Optional, Tuple, Callable
22
+ from collections import deque
23
+ from contextlib import asynccontextmanager
24
+
25
+ import numpy as np
26
+ import networkx as nx
27
+ import torch
28
+ import torch.nn as nn
29
+ import torch.nn.functional as F
30
+
31
+ from fastapi import FastAPI, BackgroundTasks
32
+ from pydantic import BaseModel
33
+ import uvicorn
34
+
35
+ import gradio as gr
36
+
37
+ from huggingface_hub import CommitScheduler, HfApi, hf_hub_download
38
+
39
+ warnings.filterwarnings("ignore")
40
+
41
+ STATE_DIR = Path("/tmp/aether_state")
42
+ STATE_DIR.mkdir(parents=True, exist_ok=True)
43
+ HF_TOKEN = os.environ.get("HF_TOKEN", "")
44
+ STATE_REPO = os.environ.get("AETHER_STATE_REPO", "camdog920/aether-state")
45
+
46
+ scheduler = None
47
+
48
+ def init_scheduler():
49
+ global scheduler
50
+ if scheduler is None and HF_TOKEN:
51
+ scheduler = CommitScheduler(
52
+ repo_id=STATE_REPO, repo_type="model", folder_path=STATE_DIR,
53
+ path_in_repo="state", every=5,
54
+ )
55
+ print(f"[PERSISTENCE] CommitScheduler initialized for {STATE_REPO}")
56
+
57
+ def save_state(state_dict, name="latest"):
58
+ path = STATE_DIR / f"{name}.json"
59
+ with open(path, "w") as f:
60
+ json.dump(state_dict, f, indent=2, default=str)
61
+ print(f"[PERSISTENCE] State saved to {path}")
62
+
63
+ def load_state(name="latest"):
64
+ path = STATE_DIR / f"{name}.json"
65
+ if path.exists():
66
+ with open(path) as f:
67
+ return json.load(f)
68
+ if HF_TOKEN:
69
+ try:
70
+ downloaded = hf_hub_download(
71
+ repo_id=STATE_REPO, filename=f"state/{name}.json",
72
+ repo_type="model", local_dir=str(STATE_DIR), token=HF_TOKEN,
73
+ )
74
+ with open(downloaded) as f:
75
+ return json.load(f)
76
+ except Exception as e:
77
+ print(f"[PERSISTENCE] No remote state found: {e}")
78
+ return None
79
+
80
+ @dataclass
81
+ class AetherConfig:
82
+ population_size: int = 6; generations: int = 5; mutation_rate: float = 0.12
83
+ macro_policy_dim: int = 128; micro_policy_dim: int = 64; num_agents: int = 4
84
+ working_memory_capacity: int = 16; episodic_buffer_size: int = 500
85
+ kg_embedding_dim: int = 64; kg_num_relations: int = 10
86
+ learning_rate: float = 2e-5; batch_size: int = 4
87
+ enable_self_modification: bool = True
88
+ max_mutation_rate: float = 0.50; max_agents: int = 16
89
+ max_memory_mb: float = 8192.0; rollback_fitness_drop: float = 0.15
90
+ risk_threshold: float = 0.70
91
+ archive_dims: Tuple[int, int] = (10, 10)
92
+
93
+ def to_vector(self):
94
+ return np.array([self.population_size, self.mutation_rate, self.learning_rate * 1e5,
95
+ self.macro_policy_dim, self.micro_policy_dim, self.num_agents,
96
+ self.kg_embedding_dim], dtype=np.float32)
97
+ @classmethod
98
+ def from_vector(cls, vec):
99
+ return cls(
100
+ population_size=int(np.clip(vec[0], 2, 64)),
101
+ mutation_rate=float(np.clip(vec[1], 0.01, 0.5)),
102
+ learning_rate=float(np.clip(vec[2] / 1e5, 1e-6, 1e-3)),
103
+ macro_policy_dim=int(np.clip(vec[3], 64, 512)),
104
+ micro_policy_dim=int(np.clip(vec[4], 32, 256)),
105
+ num_agents=int(np.clip(vec[5], 1, 16)),
106
+ kg_embedding_dim=int(np.clip(vec[6], 32, 512)),
107
+ )
108
+
109
+ class WorkingMemory:
110
+ def __init__(self, capacity=16):
111
+ self.buffer = deque(maxlen=capacity)
112
+ self.attention = nn.Parameter(torch.ones(capacity))
113
+ def store(self, item):
114
+ item["_t"] = time.time()
115
+ self.buffer.append(item)
116
+ def retrieve(self, query, top_k=3):
117
+ if not self.buffer: return []
118
+ buf = list(self.buffer)
119
+ scores = []
120
+ for i, item in enumerate(buf):
121
+ text = json.dumps(item)
122
+ score = sum(1 for w in query.lower().split() if w in text.lower())
123
+ attn = torch.sigmoid(self.attention[i % self.capacity]).item()
124
+ scores.append(score * attn)
125
+ indices = sorted(range(len(scores)), key=lambda i: scores[i], reverse=True)[:top_k]
126
+ return [buf[i] for i in indices]
127
+ def export(self):
128
+ return list(self.buffer)
129
+
130
+ class EpisodicMemory:
131
+ def __init__(self, buffer_size=1000):
132
+ self.buffer = deque(maxlen=buffer_size)
133
+ def store(self, episode):
134
+ episode["_t"] = time.time()
135
+ self.buffer.append(episode)
136
+ def retrieve_similar(self, query, top_k=5):
137
+ if not self.buffer: return []
138
+ buf = list(self.buffer)
139
+ scores = [sum(1 for w in query.lower().split() if w in json.dumps(item).lower()) for item in buf]
140
+ indices = sorted(range(len(scores)), key=lambda i: scores[i], reverse=True)[:top_k]
141
+ return [buf[i] for i in indices]
142
+ def export(self):
143
+ return list(self.buffer)
144
+
145
+ class SemanticMemory:
146
+ def __init__(self):
147
+ self.facts = {}
148
+ def store_fact(self, key, value, confidence=1.0):
149
+ self.facts[key] = {"value": value, "confidence": confidence, "t": time.time()}
150
+ def query(self, query):
151
+ return [v for k, v in self.facts.items() if query.lower() in k.lower()]
152
+ def export(self):
153
+ return self.facts
154
+
155
+ class ProceduralMemory:
156
+ def __init__(self):
157
+ self.tools = {}
158
+ self.usage = {}
159
+ def register_tool(self, name, code, description, tags=None):
160
+ self.tools[name] = {"code": code, "description": description,
161
+ "tags": tags or [], "registered_at": time.time(), "version": 1}
162
+ self.usage[name] = 0
163
+ def search_tools(self, query):
164
+ out = []
165
+ for name, tool in self.tools.items():
166
+ text = f"{name} {tool['description']} {' '.join(tool['tags'])}"
167
+ if query.lower() in text.lower():
168
+ out.append({"name": name, **tool})
169
+ return out
170
+ def export(self):
171
+ return {"tools": self.tools, "usage": self.usage}
172
+
173
+ class CoALAMemory:
174
+ def __init__(self, capacity=16):
175
+ self.working = WorkingMemory(capacity=capacity)
176
+ self.episodic = EpisodicMemory(buffer_size=1000)
177
+ self.semantic = SemanticMemory()
178
+ self.procedural = ProceduralMemory()
179
+ def store(self, item, memory_type="working"):
180
+ if memory_type == "working":
181
+ self.working.store(item)
182
+ elif memory_type == "episodic":
183
+ self.episodic.store(item)
184
+ elif memory_type == "semantic":
185
+ for k, v in item.items():
186
+ self.semantic.store_fact(k, v)
187
+ elif memory_type == "procedural":
188
+ if "name" in item and "code" in item:
189
+ self.procedural.register_tool(item["name"], item["code"],
190
+ item.get("description", ""), item.get("tags", []))
191
+ def retrieve(self, query, memory_type="all", top_k=5):
192
+ if memory_type == "all":
193
+ out = self.working.retrieve(query, top_k=top_k // 2)
194
+ out += self.episodic.retrieve_similar(query, top_k=top_k)
195
+ out += self.semantic.query(query)[:top_k]
196
+ return out[:top_k]
197
+ elif memory_type == "working":
198
+ return self.working.retrieve(query, top_k)
199
+ elif memory_type == "episodic":
200
+ return self.episodic.retrieve_similar(query, top_k)
201
+ elif memory_type == "semantic":
202
+ return self.semantic.query(query)[:top_k]
203
+ elif memory_type == "procedural":
204
+ return self.procedural.search_tools(query)
205
+ return []
206
+ def export(self):
207
+ return {"working": self.working.export(), "episodic": self.episodic.export(),
208
+ "semantic": self.semantic.export(), "procedural": self.procedural.export()}
209
+
210
+ class TemporalMemory(nn.Module):
211
+ def __init__(self, buffer_size=1000, hidden_dim=64):
212
+ super().__init__()
213
+ self.buffer = deque(maxlen=buffer_size)
214
+ self.temporal_gate = nn.Sequential(
215
+ nn.Linear(2, hidden_dim), nn.ReLU(),
216
+ nn.Linear(hidden_dim, 1), nn.Sigmoid(),
217
+ )
218
+ def store(self, event):
219
+ event["_t"] = time.time()
220
+ self.buffer.append(event)
221
+ def retrieve_context(self, current_time=None, lookback=3600.0):
222
+ current_time = current_time or time.time()
223
+ relevant = []
224
+ for event in self.buffer:
225
+ age = current_time - event.get("_t", current_time)
226
+ if age <= lookback:
227
+ recency = torch.exp(torch.tensor(-age / lookback)).item()
228
+ relevant.append({**event, "recency": recency, "age": age})
229
+ relevant.sort(key=lambda x: x["recency"], reverse=True)
230
+ return relevant
231
+ def export(self):
232
+ return list(self.buffer)
233
+
234
+ class RGCNLayer(nn.Module):
235
+ def __init__(self, in_dim, out_dim, num_relations, num_bases=4):
236
+ super().__init__()
237
+ self.num_relations = num_relations
238
+ self.bases = nn.Parameter(torch.Tensor(num_bases, in_dim, out_dim))
239
+ self.comp = nn.Parameter(torch.Tensor(num_relations, num_bases))
240
+ self.self_loop = nn.Parameter(torch.Tensor(in_dim, out_dim))
241
+ self.bias = nn.Parameter(torch.Tensor(out_dim))
242
+ nn.init.xavier_uniform_(self.bases)
243
+ nn.init.xavier_uniform_(self.comp)
244
+ nn.init.xavier_uniform_(self.self_loop)
245
+ nn.init.zeros_(self.bias)
246
+ def forward(self, x, edge_index, edge_type):
247
+ num_nodes = int(edge_index.max().item()) + 1 if x is None else x.size(0)
248
+ if x is None:
249
+ x = torch.eye(num_nodes, self.bases.size(1), device=edge_index.device)
250
+ weight = torch.einsum("rb,bio->rio", self.comp, self.bases)
251
+ out = torch.zeros(num_nodes, weight.size(2), device=x.device)
252
+ for rid in range(self.num_relations):
253
+ mask = edge_type == rid
254
+ if mask.sum() == 0: continue
255
+ ei = edge_index[:, mask]
256
+ messages = torch.mm(x[ei[0]], weight[rid])
257
+ out.index_add_(0, ei[1], messages)
258
+ out = out + torch.mm(x, self.self_loop) + self.bias
259
+ return out
260
+
261
+ class KnowledgeGraphEncoder(nn.Module):
262
+ def __init__(self, num_nodes, hidden_dim, num_relations, num_layers=2, num_bases=4):
263
+ super().__init__()
264
+ self.node_embeddings = nn.Embedding(num_nodes, hidden_dim)
265
+ self.layers = nn.ModuleList([
266
+ RGCNLayer(hidden_dim, hidden_dim, num_relations, num_bases) for _ in range(num_layers)
267
+ ])
268
+ self.norms = nn.ModuleList([nn.LayerNorm(hidden_dim) for _ in range(num_layers)])
269
+ def forward(self, edge_index, edge_type):
270
+ num_nodes = int(edge_index.max().item()) + 1
271
+ x = self.node_embeddings(torch.arange(num_nodes, device=edge_index.device))
272
+ for layer, norm in zip(self.layers, self.norms):
273
+ x = F.relu(norm(layer(x, edge_index, edge_type)))
274
+ return x
275
+
276
+ class ComplExScorer(nn.Module):
277
+ def __init__(self, num_nodes, num_relations, hidden_dim=50):
278
+ super().__init__()
279
+ self.head_real = nn.Embedding(num_nodes, hidden_dim)
280
+ self.head_imag = nn.Embedding(num_nodes, hidden_dim)
281
+ self.tail_real = nn.Embedding(num_nodes, hidden_dim)
282
+ self.tail_imag = nn.Embedding(num_nodes, hidden_dim)
283
+ self.rel_real = nn.Embedding(num_relations, hidden_dim)
284
+ self.rel_imag = nn.Embedding(num_relations, hidden_dim)
285
+ for p in self.parameters():
286
+ nn.init.xavier_uniform_(p)
287
+ def forward(self, h, r, t):
288
+ hr, hi = self.head_real(h), self.head_imag(h)
289
+ tr, ti = self.tail_real(t), self.tail_imag(t)
290
+ rr, ri = self.rel_real(r), self.rel_imag(r)
291
+ return torch.sum(hr * rr * tr + hr * ri * ti + hi * rr * ti - hi * ri * tr, dim=-1)
292
+ def loss(self, h, r, t, neg_t=None):
293
+ pos = self.forward(h, r, t)
294
+ if neg_t is None:
295
+ neg_t = torch.randint(0, self.tail_real.num_embeddings, t.size(), device=t.device)
296
+ neg = self.forward(h, r, neg_t)
297
+ return (F.softplus(-pos) + F.softplus(neg)).mean()
298
+
299
+ class KnowledgeGraphEngine(nn.Module):
300
+ def __init__(self, embedding_dim=128, num_relations=20, max_nodes=10000):
301
+ super().__init__()
302
+ self.embedding_dim = embedding_dim
303
+ self.num_relations = num_relations
304
+ self.max_nodes = max_nodes
305
+ self.graph = nx.DiGraph()
306
+ self.node_id_map = {}
307
+ self.relation_map = {}
308
+ self.next_node_id = 0
309
+ self.next_rel_id = 0
310
+ self.encoder = None
311
+ self.scorer = None
312
+ self.symbolic_attention = nn.Parameter(torch.ones(num_relations))
313
+ self.rules = []
314
+
315
+ def _get_or_create_node(self, name):
316
+ if name not in self.node_id_map:
317
+ self.node_id_map[name] = self.next_node_id
318
+ self.graph.add_node(self.next_node_id, name=name)
319
+ self.next_node_id += 1
320
+ return self.node_id_map[name]
321
+
322
+ def _get_or_create_relation(self, name):
323
+ if name not in self.relation_map:
324
+ self.relation_map[name] = self.next_rel_id
325
+ self.next_rel_id += 1
326
+ return self.relation_map[name]
327
+
328
+ def add_fact(self, head, relation, tail, confidence=1.0):
329
+ h = self._get_or_create_node(head)
330
+ t = self._get_or_create_node(tail)
331
+ r = self._get_or_create_relation(relation)
332
+ self.graph.add_edge(h, t, relation=r, name=relation, confidence=confidence)
333
+ self._ensure_capacity()
334
+
335
+ def add_rule(self, premise, conclusion):
336
+ self.rules.append((premise, conclusion))
337
+
338
+ def _ensure_capacity(self):
339
+ if self.encoder is None and self.next_node_id > 0:
340
+ n = min(self.next_node_id, self.max_nodes)
341
+ r = max(self.next_rel_id, self.num_relations)
342
+ self.encoder = KnowledgeGraphEncoder(n, self.embedding_dim, r)
343
+ self.scorer = ComplExScorer(n, r, self.embedding_dim // 2)
344
+
345
+ def _check_fact(self, fact):
346
+ h, r, t = fact
347
+ if h not in self.node_id_map or t not in self.node_id_map or r not in self.relation_map:
348
+ return False
349
+ h_id, t_id, r_id = self.node_id_map[h], self.node_id_map[t], self.relation_map[r]
350
+ return self.graph.has_edge(h_id, t_id) and self.graph.edges[h_id, t_id].get("relation") == r_id
351
+
352
+ def reason_symbolic(self, query_head, query_relation):
353
+ results = []
354
+ if query_head not in self.node_id_map:
355
+ return results
356
+ h_id = self.node_id_map[query_head]
357
+ r_name = query_relation
358
+ if r_name in self.relation_map:
359
+ r_id = self.relation_map[r_name]
360
+ for _, target, data in self.graph.out_edges(h_id, data=True):
361
+ if data.get("relation") == r_id:
362
+ results.append({
363
+ "head": query_head, "relation": r_name,
364
+ "tail": self.graph.nodes[target].get("name", str(target)),
365
+ "confidence": data.get("confidence", 1.0), "path": "direct",
366
+ })
367
+ for premise, conclusion in self.rules:
368
+ p_head, _, _ = premise
369
+ c_head, c_rel, c_tail = conclusion
370
+ if p_head == query_head and self._check_fact(premise):
371
+ results.append({
372
+ "head": c_head if c_head != "?" else query_head,
373
+ "relation": c_rel, "tail": c_tail,
374
+ "confidence": 0.8, "path": "inferred",
375
+ "rule": f"{premise} -> {conclusion}",
376
+ })
377
+ for neighbor in nx.bfs_tree(self.graph, h_id, depth_limit=2).nodes():
378
+ if neighbor != h_id:
379
+ for path in nx.all_simple_paths(self.graph, h_id, neighbor, cutoff=2):
380
+ if len(path) > 1:
381
+ ed = self.graph.edges[path[0], path[1]]
382
+ results.append({
383
+ "head": query_head,
384
+ "relation": f"multi-hop via {ed.get('name', 'unknown')}",
385
+ "tail": self.graph.nodes[neighbor].get("name", str(neighbor)),
386
+ "confidence": 0.6 ** (len(path) - 1),
387
+ "path": "->".join(str(n) for n in path),
388
+ })
389
+ return sorted(results, key=lambda x: x.get("confidence", 0), reverse=True)
390
+
391
+ def reason_learned(self, query_head, query_relation, top_k=5):
392
+ if self.scorer is None or query_head not in self.node_id_map:
393
+ return []
394
+ h_id = self.node_id_map[query_head]
395
+ r_id = self.relation_map.get(query_relation)
396
+ if r_id is None:
397
+ return []
398
+ h_t = torch.tensor([h_id])
399
+ r_t = torch.tensor([r_id])
400
+ all_t = torch.arange(self.scorer.tail_real.num_embeddings)
401
+ scores = []
402
+ for i in range(0, len(all_t), 1000):
403
+ batch = all_t[i:i + 1000]
404
+ scores.extend(self.scorer(h_t.repeat(len(batch)), r_t.repeat(len(batch)), batch).tolist())
405
+ scores_t = torch.tensor(scores)
406
+ top_scores, top_idx = torch.topk(scores_t, min(top_k, len(scores_t)))
407
+ results = []
408
+ for idx, sc in zip(top_idx, top_scores):
409
+ node_name = self.graph.nodes[idx.item()].get("name", str(idx.item()))
410
+ results.append({
411
+ "head": query_head, "relation": query_relation,
412
+ "tail": node_name, "confidence": torch.sigmoid(sc).item(), "path": "learned",
413
+ })
414
+ return results
415
+
416
+ def query(self, text_query, top_k=5):
417
+ parts = text_query.lower().split()
418
+ head = parts[0].capitalize() if parts else text_query.capitalize()
419
+ relation = " ".join(parts[1:]) if len(parts) > 1 else "related_to"
420
+ sym = self.reason_symbolic(head, relation)[:top_k]
421
+ learned = self.reason_learned(head, relation, top_k)
422
+ rel_id = self.relation_map.get(relation, 0)
423
+ sym_w = torch.sigmoid(self.symbolic_attention[rel_id % self.num_relations]).item()
424
+ learned_w = 1.0 - sym_w
425
+ for r in sym:
426
+ r["source"] = "symbolic"
427
+ r["fusion_weight"] = sym_w
428
+ for r in learned:
429
+ r["source"] = "learned"
430
+ r["fusion_weight"] = learned_w
431
+ all_r = sorted(sym + learned, key=lambda x: x.get("confidence", 0), reverse=True)
432
+ return {
433
+ "query": text_query, "results": all_r[:top_k],
434
+ "symbolic_weight": sym_w, "learned_weight": learned_w,
435
+ "num_symbolic": len(sym), "num_learned": len(learned),
436
+ }
437
+
438
+ def stats(self):
439
+ return {"num_nodes": self.graph.number_of_nodes(),
440
+ "num_edges": self.graph.number_of_edges(),
441
+ "num_relations": len(self.relation_map), "num_rules": len(self.rules)}
442
+
443
+ def export(self):
444
+ edges = []
445
+ for u, v, d in self.graph.edges(data=True):
446
+ edges.append({"source": u, "target": v, "relation": d.get("name"), "confidence": d.get("confidence")})
447
+ return {
448
+ "nodes": {n: self.graph.nodes[n].get("name", str(n)) for n in self.graph.nodes()},
449
+ "edges": edges, "rules": self.rules,
450
+ "node_id_map": self.node_id_map, "relation_map": self.relation_map,
451
+ "next_node_id": self.next_node_id, "next_rel_id": self.next_rel_id,
452
+ }
453
+
454
+ @classmethod
455
+ def from_export(cls, data, embedding_dim=64, num_relations=10):
456
+ kg = cls(embedding_dim=embedding_dim, num_relations=num_relations)
457
+ kg.node_id_map = data.get("node_id_map", {})
458
+ kg.relation_map = data.get("relation_map", {})
459
+ kg.next_node_id = data.get("next_node_id", 0)
460
+ kg.next_rel_id = data.get("next_rel_id", 0)
461
+ kg.rules = [tuple(r) for r in data.get("rules", [])]
462
+ for n, name in data.get("nodes", {}).items():
463
+ kg.graph.add_node(int(n), name=name)
464
+ for e in data.get("edges", []):
465
+ kg.graph.add_edge(int(e["source"]), int(e["target"]),
466
+ relation=e.get("relation"), name=e.get("relation"), confidence=e.get("confidence", 1.0))
467
+ kg._ensure_capacity()
468
+ return kg
469
+
470
+ class AgentRole:
471
+ RESEARCHER = "researcher"; ENGINEER = "engineer"; ANALYZER = "analyzer"; INTEGRATOR = "integrator"
472
+
473
+ class BaseAgent(nn.Module):
474
+ def __init__(self, role, hidden_dim=128, vocab_size=32000):
475
+ super().__init__()
476
+ self.role = role
477
+ self.hidden_dim = hidden_dim
478
+ self.encoder = nn.Sequential(nn.Embedding(vocab_size, hidden_dim),
479
+ nn.LSTM(hidden_dim, hidden_dim, batch_first=True))
480
+ self.policy_head = nn.Linear(hidden_dim, hidden_dim)
481
+ self.value_head = nn.Linear(hidden_dim, 1)
482
+ self.task_history = deque(maxlen=100)
483
+ self.performance_log = []
484
+ def forward(self, input_ids):
485
+ embeds = self.encoder[0](input_ids)
486
+ lstm_out, _ = self.encoder[1](embeds)
487
+ hidden = lstm_out[:, -1, :]
488
+ return {"policy_logits": self.policy_head(hidden), "value": self.value_head(hidden), "hidden": hidden}
489
+ def act(self, observation):
490
+ self.task_history.append({"observation": observation, "t": time.time()})
491
+ actions = {
492
+ AgentRole.RESEARCHER: f"[RESEARCHER] Exploring knowledge for: '{observation[:50]}...'",
493
+ AgentRole.ENGINEER: f"[ENGINEER] Synthesizing tool for: '{observation[:50]}...'",
494
+ AgentRole.ANALYZER: f"[ANALYZER] Evaluating solution for: '{observation[:50]}...'",
495
+ AgentRole.INTEGRATOR: f"[INTEGRATOR] Merging components for: '{observation[:50]}...'",
496
+ }
497
+ return actions.get(self.role, f"[{self.role.upper()}] Processing: '{observation}'")
498
+ def update(self, reward):
499
+ self.performance_log.append(reward)
500
+
501
+ class HierarchicalAgent(nn.Module):
502
+ def __init__(self, macro_dim=256, micro_dim=128, num_subgoals=5):
503
+ super().__init__()
504
+ self.macro_dim = macro_dim
505
+ self.micro_dim = micro_dim
506
+ self.num_subgoals = num_subgoals
507
+ self.macro_decoder = nn.LSTM(macro_dim, macro_dim, batch_first=True)
508
+ self.subgoal_head = nn.Linear(macro_dim, num_subgoals)
509
+ self.termination_token = nn.Parameter(torch.randn(macro_dim))
510
+ self.micro_encoder = nn.LSTM(micro_dim + macro_dim, micro_dim, batch_first=True)
511
+ self.action_head = nn.Linear(micro_dim, 50)
512
+ self.current_blueprint = None
513
+ self.active_subgoal_idx = 0
514
+ def generate_blueprint(self, task_embedding):
515
+ batch_size = task_embedding.size(0)
516
+ hidden = (torch.zeros(1, batch_size, self.macro_dim), torch.zeros(1, batch_size, self.macro_dim))
517
+ input_tok = task_embedding.unsqueeze(1)
518
+ blueprints = []
519
+ for _ in range(self.num_subgoals):
520
+ out, hidden = self.macro_decoder(input_tok, hidden)
521
+ sg_logits = self.subgoal_head(out.squeeze(1))
522
+ sg_id = torch.argmax(sg_logits, dim=-1)
523
+ sim = torch.cosine_similarity(out.squeeze(1), self.termination_token.unsqueeze(0))
524
+ if sim.item() > 0.9:
525
+ break
526
+ blueprints.append(f"subgoal_{sg_id.item()}")
527
+ input_tok = out
528
+ self.current_blueprint = blueprints
529
+ self.active_subgoal_idx = 0
530
+ return blueprints
531
+ def execute_action(self, observation, blueprint=None):
532
+ if blueprint is not None:
533
+ self.current_blueprint = blueprint
534
+ if not self.current_blueprint:
535
+ return torch.zeros(1, 50)
536
+ active = self.current_blueprint[min(self.active_subgoal_idx, len(self.current_blueprint) - 1)]
537
+ subgoal_embed = torch.randn(1, self.macro_dim)
538
+ combined = torch.cat([observation, subgoal_embed], dim=-1)
539
+ out, _ = self.micro_encoder(combined.unsqueeze(1))
540
+ return self.action_head(out.squeeze(1))
541
+ def advance_subgoal(self):
542
+ self.active_subgoal_idx += 1
543
+ def reset(self):
544
+ self.current_blueprint = None
545
+ self.active_subgoal_idx = 0
546
+
547
+ class AetherAgentOrchestrator(nn.Module):
548
+ def __init__(self, config):
549
+ super().__init__()
550
+ self.config = config
551
+ self.agents = nn.ModuleDict({
552
+ "researcher": BaseAgent(AgentRole.RESEARCHER, hidden_dim=config.macro_policy_dim),
553
+ "engineer": BaseAgent(AgentRole.ENGINEER, hidden_dim=config.micro_policy_dim),
554
+ "analyzer": BaseAgent(AgentRole.ANALYZER, hidden_dim=config.micro_policy_dim),
555
+ "integrator": BaseAgent(AgentRole.INTEGRATOR, hidden_dim=config.micro_policy_dim),
556
+ })
557
+ self.leader = BaseAgent("leader", hidden_dim=config.macro_policy_dim)
558
+ self.hierarchical = HierarchicalAgent(macro_dim=config.macro_policy_dim, micro_dim=config.micro_policy_dim)
559
+ self.routing_weights = nn.Parameter(torch.ones(len(self.agents)))
560
+ self.aggregation_gate = nn.Softmax(dim=0)
561
+ self.interactions = []
562
+ self.task_count = 0
563
+ def forward(self, task, context):
564
+ task_embed = torch.randn(1, self.config.macro_policy_dim)
565
+ blueprint = self.hierarchical.generate_blueprint(task_embed)
566
+ routing_probs = self.aggregation_gate(self.routing_weights)
567
+ agent_outputs = {}
568
+ for i, (name, agent) in enumerate(self.agents.items()):
569
+ weight = routing_probs[i].item()
570
+ if weight < 0.10:
571
+ continue
572
+ sub_task = blueprint[min(i, len(blueprint) - 1)] if blueprint else task
573
+ output = agent.act(f"[{name}] {sub_task}")
574
+ agent_outputs[name] = {"output": output, "weight": weight, "sub_task": sub_task}
575
+ synthesis = self.leader.act(f"Synthesize: {task} with inputs: {list(agent_outputs.keys())}")
576
+ self.interactions.append({
577
+ "task": task, "blueprint": blueprint,
578
+ "agent_outputs": agent_outputs, "leader_synthesis": synthesis,
579
+ "routing_probs": routing_probs.detach().cpu().tolist(),
580
+ "t": time.time(),
581
+ })
582
+ self.task_count += 1
583
+ return {"output": synthesis, "blueprint": blueprint,
584
+ "agent_outputs": agent_outputs,
585
+ "routing_weights": routing_probs.detach().cpu().tolist()}
586
+ def execute(self, task, kg_context, context):
587
+ return self.forward(task, context)
588
+ def stats(self):
589
+ return {"total_tasks": self.task_count, "num_agents": len(self.agents),
590
+ "total_interactions": len(self.interactions),
591
+ "routing_weights": self.routing_weights.detach().cpu().tolist()}
592
+
593
+ class AutoOversight:
594
+ def __init__(self, config):
595
+ self.config = config
596
+ self.audit_log = []
597
+ self.baseline_fitness = 0.0
598
+ self.last_good_config = None
599
+ self.last_good_fitness = -float("inf")
600
+ self.consecutive_rejections = 0
601
+ def risk_score(self, candidate):
602
+ risks = []
603
+ risks.append(min(1.0, candidate.mutation_rate / self.config.max_mutation_rate))
604
+ risks.append(min(1.0, candidate.num_agents / self.config.max_agents))
605
+ est_mem = (candidate.macro_policy_dim * candidate.micro_policy_dim * candidate.num_agents * 4) / 1e6
606
+ risks.append(min(1.0, est_mem / self.config.max_memory_mb))
607
+ risks.append(1.0 if candidate.micro_policy_dim > candidate.macro_policy_dim else 0.0)
608
+ return float(np.mean(risks))
609
+ def validate_stability(self, candidate):
610
+ checks = {"population_size": (2, 64), "mutation_rate": (0.0, self.config.max_mutation_rate),
611
+ "learning_rate": (1e-6, 1e-3), "num_agents": (1, self.config.max_agents),
612
+ "macro_policy_dim": (32, 512), "micro_policy_dim": (16, 256)}
613
+ violations = []
614
+ for field_name, (lo, hi) in checks.items():
615
+ val = getattr(candidate, field_name, None)
616
+ if val is not None and not (lo <= val <= hi):
617
+ violations.append(f"{field_name}={val} not in [{lo},{hi}]")
618
+ if candidate.micro_policy_dim > candidate.macro_policy_dim:
619
+ violations.append("micro > macro")
620
+ return (False, "; ".join(violations)) if violations else (True, "ok")
621
+ def regression_suite(self, candidate, core):
622
+ scores = []
623
+ try:
624
+ wm = WorkingMemory(capacity=candidate.working_memory_capacity)
625
+ for i in range(100):
626
+ wm.store({"idx": i, "data": torch.randn(16)})
627
+ retrieved = wm.retrieve("idx", top_k=5)
628
+ scores.append(len(retrieved) / 5.0)
629
+ kg = KnowledgeGraphEngine(embedding_dim=candidate.kg_embedding_dim, num_relations=candidate.kg_num_relations)
630
+ for i in range(20):
631
+ kg.add_fact(f"Node{i}", "relates_to", f"Node{i+1}")
632
+ q = kg.query("Node0 relates_to", top_k=3)
633
+ scores.append(min(1.0, len(q["results"]) / 3.0))
634
+ orch = AetherAgentOrchestrator(candidate)
635
+ task_embed = torch.randn(1, candidate.macro_policy_dim)
636
+ blueprint = orch.hierarchical.generate_blueprint(task_embed)
637
+ scores.append(min(1.0, len(blueprint) / 3.0))
638
+ except Exception:
639
+ return False, 0.0
640
+ composite = float(np.mean(scores))
641
+ if self.baseline_fitness > 0 and composite < self.baseline_fitness * (1 - self.config.rollback_fitness_drop):
642
+ return False, composite
643
+ return True, composite
644
+ def should_rollback(self, current_fitness):
645
+ if self.last_good_fitness == -float("inf"):
646
+ return False
647
+ drop = (self.last_good_fitness - current_fitness) / (abs(self.last_good_fitness) + 1e-8)
648
+ return drop > self.config.rollback_fitness_drop
649
+ def decide(self, candidate, core):
650
+ risk = self.risk_score(candidate)
651
+ if risk > self.config.risk_threshold:
652
+ self._log(candidate, False, f"risk={risk:.2f} > threshold")
653
+ self.consecutive_rejections += 1
654
+ return False, risk, "auto-rejected: high risk"
655
+ stable, reason = self.validate_stability(candidate)
656
+ if not stable:
657
+ self._log(candidate, False, reason)
658
+ self.consecutive_rejections += 1
659
+ return False, risk, f"auto-rejected: unstable ({reason})"
660
+ reg_pass, reg_score = self.regression_suite(candidate, core)
661
+ if not reg_pass:
662
+ self._log(candidate, False, f"regression fail score={reg_score:.3f}")
663
+ self.consecutive_rejections += 1
664
+ return False, reg_score, "auto-rejected: regression failure"
665
+ self._log(candidate, True, f"risk={risk:.2f} reg={reg_score:.3f}")
666
+ self.consecutive_rejections = 0
667
+ self.baseline_fitness = max(self.baseline_fitness, reg_score)
668
+ return True, reg_score, "auto-approved"
669
+ def _log(self, candidate, approved, reason):
670
+ self.audit_log.append({"timestamp": time.time(), "approved": approved,
671
+ "hash": hashlib.sha256(json.dumps(asdict(candidate), sort_keys=True).encode()).hexdigest()[:16],
672
+ "reason": reason})
673
+ def update_good_checkpoint(self, config, fitness):
674
+ self.last_good_config = copy.deepcopy(config)
675
+ self.last_good_fitness = fitness
676
+ def summary(self):
677
+ total = len(self.audit_log)
678
+ approved = sum(1 for m in self.audit_log if m["approved"])
679
+ return {"total_attempted": total, "approved": approved, "rejected": total - approved,
680
+ "consecutive_rejections": self.consecutive_rejections,
681
+ "baseline_fitness": self.baseline_fitness, "last_good_fitness": self.last_good_fitness}
682
+
683
+ class MAPelitesArchive:
684
+ def __init__(self, dims=(10, 10), ranges=None):
685
+ self.dims = dims
686
+ self.ranges = ranges or [(0, 1), (0, 1)]
687
+ self.archive = {}
688
+ def _index(self, measures):
689
+ indices = []
690
+ for m, (lo, hi), dim in zip(measures, self.ranges, self.dims):
691
+ norm = (m - lo) / (hi - lo + 1e-8)
692
+ idx = int(np.clip(norm * dim, 0, dim - 1))
693
+ indices.append(idx)
694
+ return tuple(indices)
695
+ def add(self, config, fitness, measures):
696
+ idx = self._index(measures)
697
+ if idx not in self.archive or self.archive[idx][1] < fitness:
698
+ self.archive[idx] = (config, fitness)
699
+ return True
700
+ return False
701
+ def sample(self, n=1):
702
+ if not self.archive: return []
703
+ items = list(self.archive.values())
704
+ selected = random.sample(items, min(n, len(items)))
705
+ return [cfg for cfg, _ in selected]
706
+ def get_best(self):
707
+ if not self.archive: return None
708
+ return max(self.archive.values(), key=lambda x: x[1])
709
+ def stats(self):
710
+ total_cells = self.dims[0] * self.dims[1]
711
+ return {"coverage": len(self.archive) / total_cells,
712
+ "qd_score": sum(f for _, f in self.archive.values()),
713
+ "max_fitness": max((f for _, f in self.archive.values()), default=0)}
714
+
715
+ class AetherEvolutionEngine:
716
+ def __init__(self, config):
717
+ self.config = config
718
+ self.archive = MAPelitesArchive(dims=config.archive_dims, ranges=[(0, 1), (0, 1)])
719
+ self.generation = 0
720
+ def generate_candidates(self, base_config, population_size=8):
721
+ candidates = [base_config]
722
+ archive_seeds = self.archive.sample(n=min(2, len(self.archive)))
723
+ for _ in range(population_size - len(archive_seeds) - 1):
724
+ candidates.append(self._mutate(base_config))
725
+ for cfg in archive_seeds:
726
+ candidates.append(cfg)
727
+ return candidates
728
+ def _mutate(self, config):
729
+ vec = config.to_vector()
730
+ noise = np.random.normal(0, config.mutation_rate, size=vec.shape)
731
+ mutated = vec + noise * vec
732
+ new_cfg = AetherConfig.from_vector(mutated)
733
+ new_cfg.generations = config.generations
734
+ new_cfg.enable_self_modification = config.enable_self_modification
735
+ new_cfg.archive_dims = config.archive_dims
736
+ return new_cfg
737
+ def select(self, candidates, fitness_scores):
738
+ if not candidates or not fitness_scores:
739
+ return candidates[:2] if len(candidates) >= 2 else candidates
740
+ vectors = np.array([c.to_vector() for c in candidates])
741
+ f = np.array(fitness_scores)
742
+ f_norm = (f - f.min()) / (f.max() - f.min() + 1e-8)
743
+ k = min(4, len(candidates) - 1)
744
+ novelties = []
745
+ for i, v in enumerate(vectors):
746
+ dists = np.linalg.norm(vectors - v, axis=1)
747
+ dists[i] = np.inf
748
+ knn = np.partition(dists, k)[:k]
749
+ novelties.append(np.mean(knn))
750
+ nov_norm = np.array(novelties) / (max(novelties) + 1e-8)
751
+ scores = f_norm * np.sqrt(nov_norm + 1e-8)
752
+ n_select = max(1, len(candidates) // 2)
753
+ top_indices = np.argsort(scores)[-n_select:]
754
+ return [candidates[i] for i in top_indices]
755
+ def mutate(self, candidates):
756
+ mutated = []
757
+ for cfg in candidates:
758
+ new_cfg = self._mutate(cfg)
759
+ if new_cfg.macro_policy_dim > 512:
760
+ new_cfg.macro_policy_dim = 512
761
+ if new_cfg.micro_policy_dim > new_cfg.macro_policy_dim:
762
+ new_cfg.micro_policy_dim = new_cfg.macro_policy_dim // 2
763
+ mutated.append(new_cfg)
764
+ return mutated
765
+ def update_archive(self, candidates, fitness_scores):
766
+ for cfg, fitness in zip(candidates, fitness_scores):
767
+ if fitness == -float("inf"):
768
+ continue
769
+ sym_proxy = cfg.num_agents / cfg.max_agents
770
+ measures = np.array([sym_proxy, np.clip(fitness, 0, 1)])
771
+ self.archive.add(cfg, fitness, measures)
772
+ def get_diversity_stats(self):
773
+ return self.archive.stats()
774
+
775
+ class AetherCore(nn.Module):
776
+ def __init__(self, config=None):
777
+ super().__init__()
778
+ self.config = config or AetherConfig()
779
+ self.generation = 0
780
+ self.architecture_history = []
781
+ self.fitness_log = []
782
+ self.metadata = {"birth": time.time(), "version": "0.3.0-space"}
783
+ self._memory = None
784
+ self._temporal = None
785
+ self._evolution = None
786
+ self._agents = None
787
+ self._knowledge = None
788
+ self._oversight = None
789
+ self.symbolic_gate = nn.Parameter(torch.tensor(0.0))
790
+ self.neural_gate = nn.Parameter(torch.tensor(0.0))
791
+ @property
792
+ def memory(self):
793
+ if self._memory is None:
794
+ self._memory = CoALAMemory(capacity=self.config.working_memory_capacity)
795
+ return self._memory
796
+ @property
797
+ def temporal(self):
798
+ if self._temporal is None:
799
+ self._temporal = TemporalMemory(buffer_size=self.config.episodic_buffer_size)
800
+ return self._temporal
801
+ @property
802
+ def evolution(self):
803
+ if self._evolution is None:
804
+ self._evolution = AetherEvolutionEngine(self.config)
805
+ return self._evolution
806
+ @property
807
+ def agents(self):
808
+ if self._agents is None:
809
+ self._agents = AetherAgentOrchestrator(self.config)
810
+ return self._agents
811
+ @property
812
+ def knowledge(self):
813
+ if self._knowledge is None:
814
+ self._knowledge = KnowledgeGraphEngine(
815
+ embedding_dim=self.config.kg_embedding_dim,
816
+ num_relations=self.config.kg_num_relations,
817
+ )
818
+ return self._knowledge
819
+ @property
820
+ def oversight(self):
821
+ if self._oversight is None:
822
+ self._oversight = AutoOversight(self.config)
823
+ return self._oversight
824
+ def forward(self, task, context=None):
825
+ context = context or {}
826
+ kg_context = self.knowledge.query(task, top_k=5)
827
+ self.memory.store({"task": task, "kg_context": kg_context, "t": time.time()})
828
+ result = self.agents.execute(task, kg_context, context)
829
+ sym_w = torch.sigmoid(self.symbolic_gate)
830
+ neu_w = torch.sigmoid(self.neural_gate)
831
+ total = sym_w + neu_w + 1e-8
832
+ sym_w, neu_w = sym_w / total, neu_w / total
833
+ self.temporal.store({
834
+ "task": task, "result": result,
835
+ "weights": {"symbolic": sym_w.item(), "neural": neu_w.item()},
836
+ })
837
+ return {"output": result, "symbolic_weight": sym_w.item(),
838
+ "neural_weight": neu_w.item(), "kg_context": kg_context,
839
+ "generation": self.generation}
840
+ def _default_evaluator(self, candidate):
841
+ scores = []
842
+ try:
843
+ orch = AetherAgentOrchestrator(candidate)
844
+ task_embed = torch.randn(1, candidate.macro_policy_dim)
845
+ blueprint = orch.hierarchical.generate_blueprint(task_embed)
846
+ scores.append(min(1.0, len(blueprint) / 4.0))
847
+ kg = KnowledgeGraphEngine(embedding_dim=candidate.kg_embedding_dim, num_relations=candidate.kg_num_relations)
848
+ for i in range(15):
849
+ kg.add_fact(f"Entity{i}", "connects_to", f"Entity{i+1}")
850
+ q = kg.query("Entity0 connects_to", top_k=5)
851
+ scores.append(min(1.0, len(q["results"]) / 3.0))
852
+ mem = WorkingMemory(capacity=candidate.working_memory_capacity)
853
+ for i in range(50):
854
+ mem.store({"idx": i, "data": list(range(10))})
855
+ retrieved = mem.retrieve("idx", top_k=5)
856
+ scores.append(min(1.0, len(retrieved) / 5.0))
857
+ balance = 1.0 - abs(candidate.macro_policy_dim - 256) / 256.0
858
+ scores.append(max(0.0, balance))
859
+ except Exception:
860
+ return -float("inf")
861
+ return float(np.mean(scores))
862
+ def evolve(self, num_generations=None, evaluator=None):
863
+ num_generations = num_generations or self.config.generations
864
+ evaluator = evaluator or self._default_evaluator
865
+ best_fitness = -float("inf")
866
+ best_config = None
867
+ for gen in range(num_generations):
868
+ self.generation = gen
869
+ candidates = self.evolution.generate_candidates(self.config, self.config.population_size)
870
+ fitness_scores = []
871
+ for candidate in candidates:
872
+ approved, score, reason = self.oversight.decide(candidate, self)
873
+ if approved:
874
+ fitness = evaluator(candidate)
875
+ fitness_scores.append(fitness)
876
+ else:
877
+ fitness_scores.append(-float("inf"))
878
+ current_best = max((f for f in fitness_scores if f > -float("inf")), default=-float("inf"))
879
+ if self.oversight.should_rollback(current_best):
880
+ if self.oversight.last_good_config is not None:
881
+ self.config = copy.deepcopy(self.oversight.last_good_config)
882
+ continue
883
+ selected = self.evolution.select(candidates, fitness_scores)
884
+ mutated = self.evolution.mutate(selected)
885
+ validated = []
886
+ validated_scores = []
887
+ for m in mutated:
888
+ ok, _, reason = self.oversight.decide(m, self)
889
+ if ok:
890
+ validated.append(m)
891
+ validated_scores.append(evaluator(m))
892
+ if validated and validated_scores:
893
+ best_idx = int(np.argmax(validated_scores))
894
+ best_mutated = validated[best_idx]
895
+ current_fitness = validated_scores[best_idx]
896
+ if current_fitness > best_fitness:
897
+ best_fitness = current_fitness
898
+ best_config = best_mutated
899
+ self.config = best_mutated
900
+ self.oversight.update_good_checkpoint(best_mutated, best_fitness)
901
+ arch_hash = hashlib.sha256(json.dumps(asdict(best_mutated), sort_keys=True).encode()).hexdigest()[:16]
902
+ self.architecture_history.append({
903
+ "generation": gen, "hash": arch_hash,
904
+ "fitness": best_fitness, "config": asdict(best_mutated),
905
+ })
906
+ self.evolution.update_archive(candidates, fitness_scores)
907
+ self.fitness_log.append(best_fitness)
908
+ return {"best_fitness": best_fitness, "best_config": asdict(best_config) if best_config else None,
909
+ "generations": num_generations, "history": self.architecture_history,
910
+ "oversight_summary": self.oversight.summary(),
911
+ "archive_stats": self.evolution.get_diversity_stats()}
912
+ def self_reflect(self):
913
+ recs = []
914
+ if len(self.fitness_log) > 5:
915
+ recent = self.fitness_log[-5:]
916
+ if max(recent) - min(recent) < 0.01:
917
+ recs.append("Fitness plateau detected.")
918
+ if recent[-1] < recent[0]:
919
+ recs.append("Declining trend. Rollback or expand search.")
920
+ sym = torch.sigmoid(self.symbolic_gate).item()
921
+ if sym < 0.3:
922
+ recs.append("Symbolic reasoning underutilized.")
923
+ elif sym > 0.7:
924
+ recs.append("Symbolic dominance. Increase neural flexibility.")
925
+ return {"generation": self.generation,
926
+ "architectures_tested": len(self.architecture_history),
927
+ "fitness_trend": self.fitness_log,
928
+ "neuro_symbolic_balance": {"symbolic": sym, "neural": 1.0 - sym},
929
+ "recommendations": recs,
930
+ "oversight": self.oversight.summary()}
931
+ def export_state(self):
932
+ return {"config": asdict(self.config), "generation": self.generation,
933
+ "architecture_history": self.architecture_history,
934
+ "fitness_log": self.fitness_log, "metadata": self.metadata,
935
+ "knowledge": self.knowledge.export(),
936
+ "memory": self.memory.export(),
937
+ "model_state_dict": {k: v.cpu().tolist() for k, v in self.state_dict().items()}}
938
+ @classmethod
939
+ def from_state(cls, state):
940
+ cfg = AetherConfig(**state["config"])
941
+ core = cls(config=cfg)
942
+ core.generation = state["generation"]
943
+ core.architecture_history = state["architecture_history"]
944
+ core.fitness_log = state["fitness_log"]
945
+ core.metadata = state["metadata"]
946
+ core._knowledge = KnowledgeGraphEngine.from_export(
947
+ state.get("knowledge", {}),
948
+ embedding_dim=cfg.kg_embedding_dim,
949
+ num_relations=cfg.kg_num_relations,
950
+ )
951
+ return core
952
+
953
+ aether_core = None
954
+ stop_event = threading.Event()
955
+ task_results = {}
956
+ task_counter = 0
957
+
958
+ def background_evolution():
959
+ global aether_core
960
+ gen_since_save = 0
961
+ SAVE_EVERY = 3
962
+ while not stop_event.is_set():
963
+ try:
964
+ if aether_core is not None:
965
+ print("[EVOLUTION] Running generation batch...")
966
+ result = aether_core.evolve(num_generations=1)
967
+ gen_since_save += 1
968
+ if gen_since_save >= SAVE_EVERY:
969
+ save_state(aether_core.export_state(), name="latest")
970
+ gen_since_save = 0
971
+ if result["best_fitness"] > 0.9:
972
+ aether_core.knowledge.add_fact(
973
+ f"Gen_{aether_core.generation}", "achieved", f"fitness_{result['best_fitness']:.4f}"
974
+ )
975
+ time.sleep(30)
976
+ except Exception as e:
977
+ print(f"[EVOLUTION] Error: {e}")
978
+ time.sleep(10)
979
+
980
+ def seed_knowledge(core):
981
+ facts = [
982
+ ("Intelligence", "requires", "Reasoning"),
983
+ ("Reasoning", "requires", "Memory"),
984
+ ("Memory", "enables", "Learning"),
985
+ ("Learning", "produces", "Intelligence"),
986
+ ("Agent", "has_role", "Researcher"),
987
+ ("Agent", "has_role", "Engineer"),
988
+ ("Agent", "has_role", "Analyzer"),
989
+ ("Agent", "has_role", "Integrator"),
990
+ ]
991
+ for h, r, t in facts:
992
+ core.knowledge.add_fact(h, r, t)
993
+
994
+ @asynccontextmanager
995
+ async def lifespan(app):
996
+ global aether_core
997
+ print("[STARTUP] Restoring AETHER state...")
998
+ saved = load_state("latest")
999
+ if saved:
1000
+ try:
1001
+ aether_core = AetherCore.from_state(saved)
1002
+ print("[STARTUP] State restored from Hub")
1003
+ except Exception as e:
1004
+ print(f"[STARTUP] Restore failed: {e}, initializing fresh")
1005
+ aether_core = AetherCore(AetherConfig())
1006
+ seed_knowledge(aether_core)
1007
+ else:
1008
+ aether_core = AetherCore(AetherConfig())
1009
+ seed_knowledge(aether_core)
1010
+ print("[STARTUP] Fresh AETHER initialized")
1011
+ init_scheduler()
1012
+ thread = threading.Thread(target=background_evolution, daemon=True)
1013
+ thread.start()
1014
+ print("[STARTUP] Background evolution thread started")
1015
+ yield
1016
+ print("[SHUTDOWN] Stopping evolution thread...")
1017
+ stop_event.set()
1018
+ thread.join(timeout=5)
1019
+ if aether_core:
1020
+ save_state(aether_core.export_state(), name="latest")
1021
+ print("[SHUTDOWN] State saved, exiting")
1022
+
1023
+ app = FastAPI(title="AETHER Autonomous API", lifespan=lifespan)
1024
+
1025
+ class TaskRequest(BaseModel):
1026
+ task: str
1027
+ context: Optional[Dict[str, Any]] = {}
1028
+
1029
+ class ConfigUpdate(BaseModel):
1030
+ mutation_rate: Optional[float] = None
1031
+ population_size: Optional[int] = None
1032
+ num_agents: Optional[int] = None
1033
+
1034
+ @app.get("/status")
1035
+ async def get_status():
1036
+ if aether_core is None:
1037
+ return {"status": "initializing"}
1038
+ ref = aether_core.self_reflect()
1039
+ return {
1040
+ "status": "running",
1041
+ "generation": aether_core.generation,
1042
+ "best_fitness": aether_core.fitness_log[-1] if aether_core.fitness_log else None,
1043
+ "fitness_history": aether_core.fitness_log,
1044
+ "architecture_changes": len(aether_core.architecture_history),
1045
+ "kg_stats": aether_core.knowledge.stats(),
1046
+ "agent_stats": aether_core.agents.stats(),
1047
+ "reflection": ref,
1048
+ }
1049
+
1050
+ @app.post("/task")
1051
+ async def submit_task(req: TaskRequest, background: BackgroundTasks):
1052
+ global task_counter
1053
+ task_id = f"task_{task_counter}_{int(time.time())}"
1054
+ task_counter += 1
1055
+ def execute_task(tid, task, ctx):
1056
+ try:
1057
+ result = aether_core.forward(task, ctx)
1058
+ task_results[tid] = {"status": "complete", "result": result, "timestamp": time.time()}
1059
+ except Exception as e:
1060
+ task_results[tid] = {"status": "error", "error": str(e), "timestamp": time.time()}
1061
+ background.add_task(execute_task, task_id, req.task, req.context)
1062
+ return {"task_id": task_id, "status": "queued"}
1063
+
1064
+ @app.get("/task/{task_id}")
1065
+ async def get_task(task_id: str):
1066
+ return task_results.get(task_id, {"status": "not_found"})
1067
+
1068
+ @app.post("/evolve")
1069
+ async def trigger_evolve():
1070
+ if aether_core is None:
1071
+ return {"status": "error", "message": "AETHER not initialized"}
1072
+ result = aether_core.evolve(num_generations=1)
1073
+ save_state(aether_core.export_state(), name="latest")
1074
+ return {"status": "evolved", "result": result}
1075
+
1076
+ @app.get("/history")
1077
+ async def get_history():
1078
+ if aether_core is None:
1079
+ return {"history": []}
1080
+ return {"history": aether_core.architecture_history}
1081
+
1082
+ @app.get("/kg")
1083
+ async def get_kg():
1084
+ if aether_core is None:
1085
+ return {"kg": {}}
1086
+ return {"kg": aether_core.knowledge.export()}
1087
+
1088
+ @app.post("/kg/fact")
1089
+ async def add_kg_fact(head: str, relation: str, tail: str, confidence: float = 1.0):
1090
+ if aether_core is None:
1091
+ return {"status": "error"}
1092
+ aether_core.knowledge.add_fact(head, relation, tail, confidence)
1093
+ return {"status": "added", "kg_stats": aether_core.knowledge.stats()}
1094
+
1095
+ @app.post("/config")
1096
+ async def update_config(update: ConfigUpdate):
1097
+ if aether_core is None:
1098
+ return {"status": "error"}
1099
+ if update.mutation_rate is not None:
1100
+ aether_core.config.mutation_rate = update.mutation_rate
1101
+ if update.population_size is not None:
1102
+ aether_core.config.population_size = update.population_size
1103
+ if update.num_agents is not None:
1104
+ aether_core.config.num_agents = update.num_agents
1105
+ save_state(aether_core.export_state(), name="latest")
1106
+ return {"status": "updated", "config": asdict(aether_core.config)}
1107
+
1108
+ @app.get("/snapshot")
1109
+ async def get_snapshot():
1110
+ if aether_core is None:
1111
+ return {}
1112
+ save_state(aether_core.export_state(), name="latest")
1113
+ return {"status": "saved", "snapshot_path": str(STATE_DIR / "latest.json")}
1114
+
1115
+ def get_live_status():
1116
+ if aether_core is None:
1117
+ return "Initializing..."
1118
+ ref = aether_core.self_reflect()
1119
+ lines = [
1120
+ f"Generation: {aether_core.generation}",
1121
+ f"Best Fitness: {aether_core.fitness_log[-1]:.4f}" if aether_core.fitness_log else "N/A",
1122
+ f"Arch Changes: {len(aether_core.architecture_history)}",
1123
+ f"KG Nodes: {aether_core.knowledge.stats()['num_nodes']}",
1124
+ f"KG Edges: {aether_core.knowledge.stats()['num_edges']}",
1125
+ f"Symbolic Gate: {ref['neuro_symbolic_balance']['symbolic']:.3f}",
1126
+ f"Neural Gate: {ref['neuro_symbolic_balance']['neural']:.3f}",
1127
+ "---",
1128
+ "Recommendations:",
1129
+ ]
1130
+ lines.extend(ref["recommendations"] or ["No recommendations at this time"])
1131
+ return "\n".join(lines)
1132
+
1133
+ def get_history_text():
1134
+ if aether_core is None:
1135
+ return "No history"
1136
+ lines = ["Generation | Hash | Fitness | Agents | Macro-Dim | Mut-Rate"]
1137
+ for entry in aether_core.architecture_history:
1138
+ lines.append(
1139
+ f" {entry['generation']:02d} | {entry['hash']} | {entry['fitness']:.4f} | "
1140
+ f"{entry['config']['num_agents']} | {entry['config']['macro_policy_dim']} | {entry['config']['mutation_rate']:.3f}"
1141
+ )
1142
+ return "\n".join(lines)
1143
+
1144
+ def execute_gradio_task(task_text):
1145
+ if aether_core is None:
1146
+ return "AETHER not ready"
1147
+ result = aether_core.forward(task_text)
1148
+ out_lines = [
1149
+ f"Task: {task_text}",
1150
+ f"Symbolic Weight: {result['symbolic_weight']:.3f}",
1151
+ f"Neural Weight: {result['neural_weight']:.3f}",
1152
+ f"Output: {result['output']['output'][:200]}...",
1153
+ f"Agents: {list(result['output']['agent_outputs'].keys())}",
1154
+ ]
1155
+ return "\n".join(out_lines)
1156
+
1157
+ with gr.Blocks(title="AETHER Monitor") as demo:
1158
+ gr.Markdown("## 🧠 AETHER v0.3.0 — Autonomous Self-Evolving Architecture")
1159
+ gr.Markdown("Runs 24/7. Evolves in background. State auto-persisted to Hub. REST API accessible at `/status`, `/task`, `/evolve`, etc.")
1160
+ with gr.Row():
1161
+ with gr.Column():
1162
+ status_box = gr.Textbox(label="Live System Status", value=get_live_status, lines=12, every=5)
1163
+ refresh_btn = gr.Button("🔄 Refresh")
1164
+ with gr.Column():
1165
+ history_box = gr.Textbox(label="Evolution History", value=get_history_text, lines=12, every=10)
1166
+ with gr.Row():
1167
+ with gr.Column():
1168
+ task_input = gr.Textbox(label="Submit a Task", placeholder="e.g., Intelligence requires...")
1169
+ task_btn = gr.Button("⚡ Execute")
1170
+ task_output = gr.Textbox(label="Task Result", lines=6)
1171
+ with gr.Column():
1172
+ gr.Markdown("### Quick Actions")
1173
+ evolve_btn = gr.Button("🧬 Trigger 1 Evolution Cycle")
1174
+ evolve_out = gr.Textbox(label="Evolution Result", lines=4)
1175
+ snapshot_btn = gr.Button("💾 Force Save Snapshot")
1176
+ snapshot_out = gr.Textbox(label="Save Status", lines=2)
1177
+ refresh_btn.click(get_live_status, outputs=status_box)
1178
+ task_btn.click(execute_gradio_task, inputs=task_input, outputs=task_output)
1179
+ evolve_btn.click(lambda: "Evolution triggered via API" if aether_core else "Not ready", outputs=evolve_out)
1180
+ snapshot_btn.click(lambda: "Snapshot saved" if aether_core else "Not ready", outputs=snapshot_out)
1181
+
1182
+ app = gr.mount_gradio_app(app, demo, path="/")
1183
+
1184
+ if __name__ == "__main__":
1185
+ uvicorn.run(app, host="0.0.0.0", port=7860)