-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
180 lines (150 loc) · 5.74 KB
/
server.py
File metadata and controls
180 lines (150 loc) · 5.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
"""
Dragonfly-VSA HTTP API Server
Endpoints:
GET /health - Health check
POST /expand - 1024D → 10KD expansion
POST /compress - 10KD → 1024D compression
POST /bind - XOR binding in 10KD
POST /verb/lookup - O(1) verb-triangle lookup
POST /round_trip - Test fidelity
"""
import os
import sys
import base64
import numpy as np
from typing import Optional, List, Dict, Any
# Add src to path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src'))
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from cam import AtomCAM, VerbCAM, AttractorCAM, create_standard_verb_cam
from clean_qualia_dto import CleanQualiaDTO
app = FastAPI(
title="Dragonfly-VSA",
description="10KD Binary Lattice Consciousness Engine",
version="0.7.3",
)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
# Global state
atom_cam: AtomCAM = None
verb_cam: VerbCAM = None
attractor_cam: AttractorCAM = None
dto: CleanQualiaDTO = None
@app.on_event("startup")
async def startup():
global atom_cam, verb_cam, attractor_cam, dto
print("Initializing Dragonfly-VSA...")
atom_cam = AtomCAM(seed=42)
verb_cam = create_standard_verb_cam()
attractor_cam = AttractorCAM()
dto = CleanQualiaDTO(seed=42)
print("Ready!")
# Models
class ExpandRequest(BaseModel):
qualia: List[float]
target_sparsity: float = 0.5
class ExpandSparseRequest(BaseModel):
indices: List[int]
weights: List[float]
target_sparsity: float = 0.5
class CompressRequest(BaseModel):
resonance_b64: str
class BindRequest(BaseModel):
a_b64: str
b_b64: str
class VerbLookupRequest(BaseModel):
triangle: List[float]
class AttractorRequest(BaseModel):
pattern_b64: str
name: Optional[str] = None
# Endpoints
@app.get("/")
async def root():
return {"name": "Dragonfly-VSA", "version": "0.7.3", "docs": "/docs"}
@app.get("/health")
async def health():
return {"status": "ok", "version": "0.7.3"}
@app.get("/stats")
async def stats():
return {
"n_atoms": 1024,
"dim_resonance": 10000,
"n_verbs": len(verb_cam.verbs) if verb_cam else 0,
"n_attractors": attractor_cam.n_attractors if attractor_cam else 0,
}
@app.post("/expand")
async def expand(req: ExpandRequest):
qualia = np.array(req.qualia, dtype=np.float32)
if len(qualia) != 1024:
raise HTTPException(400, f"Expected 1024D, got {len(qualia)}D")
packed = dto.expand(qualia, req.target_sparsity)
return {
"resonance_b64": base64.b64encode(packed.tobytes()).decode(),
"sparsity": float(np.mean(np.unpackbits(packed)[:10000])),
}
@app.post("/expand_sparse")
async def expand_sparse(req: ExpandSparseRequest):
indices = np.array(req.indices, dtype=np.int32)
weights = np.array(req.weights, dtype=np.float32)
packed = atom_cam.expand_sparse(indices, weights, req.target_sparsity)
return {
"resonance_b64": base64.b64encode(packed.tobytes()).decode(),
"n_atoms": len(indices),
}
@app.post("/compress")
async def compress(req: CompressRequest):
packed = np.frombuffer(base64.b64decode(req.resonance_b64), dtype=np.uint8)
qualia = dto.compress(packed)
return {"qualia": qualia.tolist()}
@app.post("/bind")
async def bind(req: BindRequest):
a = np.frombuffer(base64.b64decode(req.a_b64), dtype=np.uint8)
b = np.frombuffer(base64.b64decode(req.b_b64), dtype=np.uint8)
result = np.bitwise_xor(a, b)
return {"result_b64": base64.b64encode(result.tobytes()).decode()}
@app.post("/similarity")
async def similarity(req: BindRequest):
a = np.unpackbits(np.frombuffer(base64.b64decode(req.a_b64), dtype=np.uint8))[:10000]
b = np.unpackbits(np.frombuffer(base64.b64decode(req.b_b64), dtype=np.uint8))[:10000]
hamming_dist = int(np.sum(a != b))
return {"hamming_distance": hamming_dist, "similarity": 1.0 - hamming_dist/10000}
@app.post("/verb/lookup")
async def verb_lookup(req: VerbLookupRequest):
if len(req.triangle) != 3:
raise HTTPException(400, "Triangle must have 3 values")
verb = verb_cam.lookup(tuple(req.triangle))
return {"verb": verb, "triangle": req.triangle}
@app.get("/verb/list")
async def verb_list():
return {"verbs": {n: verb_cam.get_triangle(n) for n in verb_cam.verbs}}
@app.post("/attractor/check")
async def attractor_check(req: AttractorRequest):
pattern = np.frombuffer(base64.b64decode(req.pattern_b64), dtype=np.uint8)
is_attractor = attractor_cam.contains(pattern)
return {"is_attractor": is_attractor, "name": attractor_cam.get_name(pattern) if is_attractor else None}
@app.post("/attractor/register")
async def attractor_register(req: AttractorRequest):
pattern = np.frombuffer(base64.b64decode(req.pattern_b64), dtype=np.uint8)
attractor_cam.register(pattern, req.name)
return {"registered": True, "n_attractors": attractor_cam.n_attractors}
@app.post("/round_trip")
async def round_trip(req: ExpandRequest):
qualia = np.array(req.qualia, dtype=np.float32)
packed = dto.expand(qualia, req.target_sparsity)
recovered = dto.compress(packed)
fidelity = float(np.dot(qualia, recovered) / (np.linalg.norm(qualia) * np.linalg.norm(recovered) + 1e-10))
return {"fidelity": fidelity, "recovered": recovered.tolist()}
@app.post("/create_concept")
async def create_concept(n_atoms: int = 20, seed: Optional[int] = None):
qualia = dto.create_sparse_concept(n_atoms, seed)
return {"qualia": qualia.tolist(), "n_active": int(np.sum(np.abs(qualia) > 1e-6))}
if __name__ == "__main__":
import uvicorn
port = int(os.environ.get("PORT", 8000))
uvicorn.run(app, host="0.0.0.0", port=port)