arbyazra123 commited on
Commit ·
d1a85d8
1
Parent(s): 3e32121
add vdb
Browse files- vdb/.gitignore +3 -0
- vdb/api.py +514 -0
- vdb/docker-compose.yml +68 -0
- vdb/import_data.py +40 -0
- vdb/query_actions.py +25 -0
- vdb/setup_milvus.py +58 -0
vdb/.gitignore
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
volumes
|
| 2 |
+
minio_data
|
| 3 |
+
milvus_data
|
vdb/api.py
ADDED
|
@@ -0,0 +1,514 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
FastAPI server for Sumobot with Milvus Vector Search
|
| 3 |
+
Real-time action retrieval using similarity search
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import re
|
| 7 |
+
import platform
|
| 8 |
+
import time
|
| 9 |
+
from typing import Dict, Optional, List
|
| 10 |
+
from fastapi import FastAPI, HTTPException
|
| 11 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 12 |
+
from pydantic import BaseModel
|
| 13 |
+
import uvicorn
|
| 14 |
+
import numpy as np
|
| 15 |
+
from pymilvus import connections, Collection
|
| 16 |
+
|
| 17 |
+
# ==================== Configuration ====================
|
| 18 |
+
MILVUS_HOST = "127.0.0.1"
|
| 19 |
+
MILVUS_PORT = "19530"
|
| 20 |
+
COLLECTION_NAME = "sumobot_states"
|
| 21 |
+
TOP_K = 1 # Number of similar states to retrieve
|
| 22 |
+
NPROBE = 16 # Search parameter for IVF_FLAT index
|
| 23 |
+
|
| 24 |
+
print("="*70)
|
| 25 |
+
print("🤖 Sumobot Milvus Vector Search API Server")
|
| 26 |
+
print("="*70)
|
| 27 |
+
print(f"Platform: {platform.system()} {platform.machine()}")
|
| 28 |
+
print(f"Milvus: {MILVUS_HOST}:{MILVUS_PORT}")
|
| 29 |
+
print(f"Collection: {COLLECTION_NAME}")
|
| 30 |
+
print("="*70)
|
| 31 |
+
|
| 32 |
+
# ==================== Connect to Milvus ====================
|
| 33 |
+
print("\n⏳ Connecting to Milvus...")
|
| 34 |
+
start_time = time.time()
|
| 35 |
+
|
| 36 |
+
try:
|
| 37 |
+
connections.connect("default", host=MILVUS_HOST, port=MILVUS_PORT)
|
| 38 |
+
col = Collection(COLLECTION_NAME)
|
| 39 |
+
col.load()
|
| 40 |
+
|
| 41 |
+
load_time = time.time() - start_time
|
| 42 |
+
num_entities = col.num_entities
|
| 43 |
+
|
| 44 |
+
print(f"✅ Connected to Milvus in {load_time:.2f}s")
|
| 45 |
+
print(f"📊 Collection has {num_entities} entities\n")
|
| 46 |
+
|
| 47 |
+
except Exception as e:
|
| 48 |
+
print(f"❌ Failed to connect to Milvus: {e}")
|
| 49 |
+
print("\nMake sure:")
|
| 50 |
+
print(f" 1. Milvus is running at {MILVUS_HOST}:{MILVUS_PORT}")
|
| 51 |
+
print(f" 2. Collection '{COLLECTION_NAME}' exists")
|
| 52 |
+
print(" 3. pymilvus is installed: pip install pymilvus")
|
| 53 |
+
exit(1)
|
| 54 |
+
|
| 55 |
+
# ==================== State Encoding ====================
|
| 56 |
+
def encode_state(angle: float, angle_score: float, dist_score: float,
|
| 57 |
+
near_score: float, facing: float) -> np.ndarray:
|
| 58 |
+
"""
|
| 59 |
+
Encode game state into 5D vector
|
| 60 |
+
|
| 61 |
+
Args:
|
| 62 |
+
angle: AngleToEnemy (degrees, normalized to [-1, 1])
|
| 63 |
+
angle_score: AngleToEnemyScore [0, 1]
|
| 64 |
+
dist_score: DistanceToEnemyScore [0, 1]
|
| 65 |
+
near_score: NearBorderArenaScore [0, 1]
|
| 66 |
+
facing: FacingToArena [-1, 1]
|
| 67 |
+
|
| 68 |
+
Returns:
|
| 69 |
+
5D numpy array [angle_normalized, angle_score, dist_score, near_score, facing]
|
| 70 |
+
"""
|
| 71 |
+
# Normalize angle from [-180, 180] to [-1, 1]
|
| 72 |
+
angle_normalized = angle / 180.0
|
| 73 |
+
|
| 74 |
+
return np.array([
|
| 75 |
+
angle_normalized,
|
| 76 |
+
angle_score,
|
| 77 |
+
dist_score,
|
| 78 |
+
near_score,
|
| 79 |
+
facing
|
| 80 |
+
], dtype=np.float32)
|
| 81 |
+
|
| 82 |
+
def parse_state_string(state_str: str) -> Dict[str, float]:
|
| 83 |
+
"""
|
| 84 |
+
Parse state string into dictionary
|
| 85 |
+
|
| 86 |
+
Example input: "AngleToEnemy=7.77, AngleToEnemyScore=0.99, DistanceToEnemyScore=0.76, NearBorderArenaScore=0.81, FacingToArena=-0.99"
|
| 87 |
+
Returns: {"AngleToEnemy": 7.77, "AngleToEnemyScore": 0.99, ...}
|
| 88 |
+
"""
|
| 89 |
+
state_dict = {}
|
| 90 |
+
|
| 91 |
+
# Remove trailing punctuation from entire string
|
| 92 |
+
state_str = state_str.rstrip('.,;')
|
| 93 |
+
|
| 94 |
+
for part in state_str.split(","):
|
| 95 |
+
part = part.strip()
|
| 96 |
+
if "=" in part:
|
| 97 |
+
key, value = part.split("=", 1) # Split only on first '='
|
| 98 |
+
# Clean up value: remove trailing periods, spaces, etc.
|
| 99 |
+
value_clean = value.strip().rstrip('.')
|
| 100 |
+
try:
|
| 101 |
+
state_dict[key.strip()] = float(value_clean)
|
| 102 |
+
except ValueError as e:
|
| 103 |
+
raise ValueError(f"Cannot parse '{key.strip()}={value}' - invalid float value: {e}")
|
| 104 |
+
|
| 105 |
+
return state_dict
|
| 106 |
+
|
| 107 |
+
# ==================== Action Parser ====================
|
| 108 |
+
def parse_action(output: str) -> Dict[str, Optional[float]]:
|
| 109 |
+
"""
|
| 110 |
+
Parse action string into dictionary
|
| 111 |
+
|
| 112 |
+
Expected format: "FWD 1.5, TR 0.8" or "SK, DS 2.0"
|
| 113 |
+
Returns: {"Accelerate": 1.5, "TurnRight": 0.8} or {"Skill": None, "Dash": 2.0}
|
| 114 |
+
"""
|
| 115 |
+
action_map = {
|
| 116 |
+
"SK": "Skill",
|
| 117 |
+
"DS": "Dash",
|
| 118 |
+
"FWD": "Accelerate",
|
| 119 |
+
"TL": "TurnLeft",
|
| 120 |
+
"TR": "TurnRight",
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
actions: Dict[str, Optional[float]] = {}
|
| 124 |
+
|
| 125 |
+
# Split by comma and process each action
|
| 126 |
+
for part in [p.strip() for p in output.split(",")]:
|
| 127 |
+
if not part:
|
| 128 |
+
continue
|
| 129 |
+
|
| 130 |
+
name = part
|
| 131 |
+
duration = None
|
| 132 |
+
|
| 133 |
+
# Try to extract duration (e.g., "FWD 1.5" -> name="FWD", duration=1.5)
|
| 134 |
+
direct_match = re.match(r"^([A-Za-z]+)\s*([\d.]+)$", part)
|
| 135 |
+
if direct_match:
|
| 136 |
+
name = direct_match.group(1).strip()
|
| 137 |
+
duration = float(direct_match.group(2))
|
| 138 |
+
|
| 139 |
+
# Normalize shorthand to full action name
|
| 140 |
+
for short, full in action_map.items():
|
| 141 |
+
if name.upper().startswith(short):
|
| 142 |
+
name = full
|
| 143 |
+
break
|
| 144 |
+
|
| 145 |
+
actions[name] = duration
|
| 146 |
+
|
| 147 |
+
return actions
|
| 148 |
+
|
| 149 |
+
# ==================== Vector Search Function ====================
|
| 150 |
+
def query_action(angle: float, angle_score: float, dist_score: float,
|
| 151 |
+
near_score: float, facing: float, top_k: int = TOP_K) -> dict:
|
| 152 |
+
"""
|
| 153 |
+
Query action from Milvus using vector similarity search
|
| 154 |
+
|
| 155 |
+
Args:
|
| 156 |
+
angle: AngleToEnemy (degrees)
|
| 157 |
+
angle_score: AngleToEnemyScore [0, 1]
|
| 158 |
+
dist_score: DistanceToEnemyScore [0, 1]
|
| 159 |
+
near_score: NearBorderArenaScore [0, 1]
|
| 160 |
+
facing: FacingToArena [-1, 1]
|
| 161 |
+
top_k: Number of similar states to retrieve
|
| 162 |
+
|
| 163 |
+
Returns:
|
| 164 |
+
{
|
| 165 |
+
"raw_output": "FWD 1.5, TR 0.8",
|
| 166 |
+
"action": {"Accelerate": 1.5, "TurnRight": 0.8},
|
| 167 |
+
"search_time_ms": 2.5,
|
| 168 |
+
"distance": 0.123,
|
| 169 |
+
"top_k_results": [...] # Only if top_k > 1
|
| 170 |
+
}
|
| 171 |
+
"""
|
| 172 |
+
# Encode state into vector
|
| 173 |
+
vec = encode_state(angle, angle_score, dist_score, near_score, facing)
|
| 174 |
+
|
| 175 |
+
# Perform vector search
|
| 176 |
+
start = time.time()
|
| 177 |
+
|
| 178 |
+
result = col.search(
|
| 179 |
+
data=[vec.tolist()],
|
| 180 |
+
anns_field="state_vec",
|
| 181 |
+
param={"nprobe": NPROBE},
|
| 182 |
+
limit=top_k,
|
| 183 |
+
output_fields=["action"],
|
| 184 |
+
)
|
| 185 |
+
|
| 186 |
+
search_time = (time.time() - start) * 1000 # Convert to ms
|
| 187 |
+
|
| 188 |
+
# Extract results
|
| 189 |
+
if len(result[0]) == 0:
|
| 190 |
+
raise ValueError("No similar states found in database")
|
| 191 |
+
|
| 192 |
+
top_hit = result[0][0]
|
| 193 |
+
action_str = top_hit.entity.get("action")
|
| 194 |
+
distance = top_hit.distance
|
| 195 |
+
|
| 196 |
+
# Parse action
|
| 197 |
+
parsed_actions = parse_action(action_str)
|
| 198 |
+
|
| 199 |
+
response = {
|
| 200 |
+
"raw_output": action_str,
|
| 201 |
+
"action": parsed_actions,
|
| 202 |
+
"search_time_ms": round(search_time, 2),
|
| 203 |
+
"distance": round(distance, 4)
|
| 204 |
+
}
|
| 205 |
+
|
| 206 |
+
# Include all results if top_k > 1
|
| 207 |
+
if top_k > 1:
|
| 208 |
+
response["top_k_results"] = [
|
| 209 |
+
{
|
| 210 |
+
"action": hit.entity.get("action"),
|
| 211 |
+
"distance": round(hit.distance, 4)
|
| 212 |
+
}
|
| 213 |
+
for hit in result[0]
|
| 214 |
+
]
|
| 215 |
+
|
| 216 |
+
return response
|
| 217 |
+
|
| 218 |
+
def query_action_from_string(state_str: str, top_k: int = TOP_K) -> dict:
|
| 219 |
+
"""
|
| 220 |
+
Query action from state string
|
| 221 |
+
|
| 222 |
+
Args:
|
| 223 |
+
state_str: "AngleToEnemy=7.77, AngleToEnemyScore=0.99, DistanceToEnemyScore=0.76, NearBorderArenaScore=0.81, FacingToArena=-0.99"
|
| 224 |
+
top_k: Number of similar states to retrieve
|
| 225 |
+
|
| 226 |
+
Returns:
|
| 227 |
+
Same as query_action()
|
| 228 |
+
"""
|
| 229 |
+
# Parse state string
|
| 230 |
+
state_dict = parse_state_string(state_str)
|
| 231 |
+
|
| 232 |
+
# Extract required fields
|
| 233 |
+
required_fields = [
|
| 234 |
+
"AngleToEnemy",
|
| 235 |
+
"AngleToEnemyScore",
|
| 236 |
+
"DistanceToEnemyScore",
|
| 237 |
+
"NearBorderArenaScore",
|
| 238 |
+
"FacingToArena"
|
| 239 |
+
]
|
| 240 |
+
|
| 241 |
+
missing_fields = [f for f in required_fields if f not in state_dict]
|
| 242 |
+
if missing_fields:
|
| 243 |
+
raise ValueError(f"Missing required fields: {missing_fields}")
|
| 244 |
+
|
| 245 |
+
# Query action
|
| 246 |
+
return query_action(
|
| 247 |
+
angle=state_dict["AngleToEnemy"],
|
| 248 |
+
angle_score=state_dict["AngleToEnemyScore"],
|
| 249 |
+
dist_score=state_dict["DistanceToEnemyScore"],
|
| 250 |
+
near_score=state_dict["NearBorderArenaScore"],
|
| 251 |
+
facing=state_dict["FacingToArena"],
|
| 252 |
+
top_k=top_k
|
| 253 |
+
)
|
| 254 |
+
|
| 255 |
+
# ==================== FastAPI Setup ====================
|
| 256 |
+
app = FastAPI(
|
| 257 |
+
title="Sumobot Milvus Vector Search API",
|
| 258 |
+
description="Real-time Sumobot action retrieval using vector similarity search",
|
| 259 |
+
version="1.0.0"
|
| 260 |
+
)
|
| 261 |
+
|
| 262 |
+
# Add CORS middleware
|
| 263 |
+
app.add_middleware(
|
| 264 |
+
CORSMiddleware,
|
| 265 |
+
allow_origins=["*"],
|
| 266 |
+
allow_credentials=True,
|
| 267 |
+
allow_methods=["*"],
|
| 268 |
+
allow_headers=["*"],
|
| 269 |
+
)
|
| 270 |
+
|
| 271 |
+
# ==================== Request/Response Models ====================
|
| 272 |
+
class QueryInput(BaseModel):
|
| 273 |
+
state: str
|
| 274 |
+
top_k: Optional[int] = 1
|
| 275 |
+
|
| 276 |
+
class Config:
|
| 277 |
+
json_schema_extra = {
|
| 278 |
+
"example": {
|
| 279 |
+
"state": "AngleToEnemy=7.77, AngleToEnemyScore=0.99, DistanceToEnemyScore=0.76, NearBorderArenaScore=0.81, FacingToArena=-0.99",
|
| 280 |
+
"top_k": 1
|
| 281 |
+
}
|
| 282 |
+
}
|
| 283 |
+
|
| 284 |
+
class QueryResponse(BaseModel):
|
| 285 |
+
raw_output: str
|
| 286 |
+
action: Dict[str, Optional[float]]
|
| 287 |
+
search_time_ms: float
|
| 288 |
+
distance: float
|
| 289 |
+
top_k_results: Optional[List[Dict]] = None
|
| 290 |
+
|
| 291 |
+
class BatchQueryInput(BaseModel):
|
| 292 |
+
states: List[str]
|
| 293 |
+
top_k: Optional[int] = 1
|
| 294 |
+
|
| 295 |
+
class HealthResponse(BaseModel):
|
| 296 |
+
status: str
|
| 297 |
+
milvus_host: str
|
| 298 |
+
collection: str
|
| 299 |
+
num_entities: int
|
| 300 |
+
platform: str
|
| 301 |
+
|
| 302 |
+
# ==================== API Endpoints ====================
|
| 303 |
+
|
| 304 |
+
@app.get("/", tags=["Info"])
|
| 305 |
+
def root():
|
| 306 |
+
"""Root endpoint with API information"""
|
| 307 |
+
return {
|
| 308 |
+
"message": "Sumobot Milvus Vector Search API",
|
| 309 |
+
"endpoints": {
|
| 310 |
+
"health": "/health",
|
| 311 |
+
"query": "/query (POST)",
|
| 312 |
+
"batch": "/batch (POST)",
|
| 313 |
+
"benchmark": "/benchmark (GET)",
|
| 314 |
+
"stats": "/stats (GET)"
|
| 315 |
+
}
|
| 316 |
+
}
|
| 317 |
+
|
| 318 |
+
@app.get("/health", response_model=HealthResponse, tags=["Info"])
|
| 319 |
+
def health_check():
|
| 320 |
+
"""Health check endpoint"""
|
| 321 |
+
return {
|
| 322 |
+
"status": "healthy",
|
| 323 |
+
"milvus_host": f"{MILVUS_HOST}:{MILVUS_PORT}",
|
| 324 |
+
"collection": COLLECTION_NAME,
|
| 325 |
+
"num_entities": col.num_entities,
|
| 326 |
+
"platform": f"{platform.system()} {platform.machine()}"
|
| 327 |
+
}
|
| 328 |
+
|
| 329 |
+
@app.get("/stats", tags=["Info"])
|
| 330 |
+
def collection_stats():
|
| 331 |
+
"""Get collection statistics"""
|
| 332 |
+
return {
|
| 333 |
+
"collection": COLLECTION_NAME,
|
| 334 |
+
"num_entities": col.num_entities,
|
| 335 |
+
"schema": {
|
| 336 |
+
"fields": [
|
| 337 |
+
{
|
| 338 |
+
"name": field.name,
|
| 339 |
+
"type": str(field.dtype),
|
| 340 |
+
"params": field.params
|
| 341 |
+
}
|
| 342 |
+
for field in col.schema.fields
|
| 343 |
+
]
|
| 344 |
+
},
|
| 345 |
+
"indexes": [
|
| 346 |
+
{
|
| 347 |
+
"field": index.field_name,
|
| 348 |
+
"type": index.params.get("index_type"),
|
| 349 |
+
"metric": index.params.get("metric_type")
|
| 350 |
+
}
|
| 351 |
+
for index in col.indexes
|
| 352 |
+
]
|
| 353 |
+
}
|
| 354 |
+
|
| 355 |
+
@app.post("/query", response_model=QueryResponse, tags=["Search"])
|
| 356 |
+
def query(input: QueryInput):
|
| 357 |
+
"""
|
| 358 |
+
Get action prediction for a single game state
|
| 359 |
+
|
| 360 |
+
Example:
|
| 361 |
+
```json
|
| 362 |
+
{
|
| 363 |
+
"state": "AngleToEnemy=7.77, AngleToEnemyScore=0.99, DistanceToEnemyScore=0.76, NearBorderArenaScore=0.81, FacingToArena=-0.99",
|
| 364 |
+
"top_k": 1
|
| 365 |
+
}
|
| 366 |
+
```
|
| 367 |
+
"""
|
| 368 |
+
|
| 369 |
+
try:
|
| 370 |
+
result = query_action_from_string(input.state, input.top_k)
|
| 371 |
+
return result
|
| 372 |
+
except Exception as e:
|
| 373 |
+
print(input.state)
|
| 374 |
+
print(f"Error query:\nInput: {input.state}\nDetail: {e.with_traceback()}")
|
| 375 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 376 |
+
|
| 377 |
+
@app.post("/batch", tags=["Search"])
|
| 378 |
+
def batch_query(input: BatchQueryInput):
|
| 379 |
+
"""
|
| 380 |
+
Get action predictions for multiple game states
|
| 381 |
+
|
| 382 |
+
Example:
|
| 383 |
+
```json
|
| 384 |
+
{
|
| 385 |
+
"states": [
|
| 386 |
+
"AngleToEnemy=7.77, AngleToEnemyScore=0.99, DistanceToEnemyScore=0.76, NearBorderArenaScore=0.81, FacingToArena=-0.99",
|
| 387 |
+
"AngleToEnemy=2.31, AngleToEnemyScore=0.45, DistanceToEnemyScore=0.92, NearBorderArenaScore=0.12, FacingToArena=0.67"
|
| 388 |
+
],
|
| 389 |
+
"top_k": 1
|
| 390 |
+
}
|
| 391 |
+
```
|
| 392 |
+
"""
|
| 393 |
+
try:
|
| 394 |
+
results = []
|
| 395 |
+
total_time = 0
|
| 396 |
+
|
| 397 |
+
for state in input.states:
|
| 398 |
+
result = query_action_from_string(state, input.top_k)
|
| 399 |
+
results.append(result)
|
| 400 |
+
total_time += result["search_time_ms"]
|
| 401 |
+
|
| 402 |
+
return {
|
| 403 |
+
"results": results,
|
| 404 |
+
"total_search_time_ms": round(total_time, 2),
|
| 405 |
+
"avg_search_time_ms": round(total_time / len(results), 2)
|
| 406 |
+
}
|
| 407 |
+
except Exception as e:
|
| 408 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 409 |
+
|
| 410 |
+
@app.get("/benchmark", tags=["Diagnostics"])
|
| 411 |
+
def benchmark():
|
| 412 |
+
"""
|
| 413 |
+
Benchmark vector search performance
|
| 414 |
+
|
| 415 |
+
Runs 100 searches and returns statistics
|
| 416 |
+
"""
|
| 417 |
+
test_state = "AngleToEnemy=7.77, AngleToEnemyScore=0.99, DistanceToEnemyScore=0.76, NearBorderArenaScore=0.81, FacingToArena=-0.99"
|
| 418 |
+
|
| 419 |
+
print("\n🔥 Running benchmark...")
|
| 420 |
+
|
| 421 |
+
# Warmup
|
| 422 |
+
query_action_from_string(test_state)
|
| 423 |
+
|
| 424 |
+
# Benchmark
|
| 425 |
+
times = []
|
| 426 |
+
outputs = []
|
| 427 |
+
|
| 428 |
+
num_runs = 100
|
| 429 |
+
for i in range(num_runs):
|
| 430 |
+
result = query_action_from_string(test_state)
|
| 431 |
+
times.append(result["search_time_ms"])
|
| 432 |
+
outputs.append(result["raw_output"])
|
| 433 |
+
|
| 434 |
+
if (i + 1) % 20 == 0:
|
| 435 |
+
print(f" Run {i+1}/{num_runs}: {result['search_time_ms']:.2f}ms")
|
| 436 |
+
|
| 437 |
+
times_sorted = sorted(times)
|
| 438 |
+
|
| 439 |
+
return {
|
| 440 |
+
"runs": num_runs,
|
| 441 |
+
"test_state": test_state,
|
| 442 |
+
"stats": {
|
| 443 |
+
"avg_latency_ms": round(sum(times) / len(times), 2),
|
| 444 |
+
"min_latency_ms": round(min(times), 2),
|
| 445 |
+
"max_latency_ms": round(max(times), 2),
|
| 446 |
+
"p50_latency_ms": round(times_sorted[len(times) // 2], 2),
|
| 447 |
+
"p95_latency_ms": round(times_sorted[int(len(times) * 0.95)], 2),
|
| 448 |
+
"p99_latency_ms": round(times_sorted[int(len(times) * 0.99)], 2),
|
| 449 |
+
},
|
| 450 |
+
"platform": {
|
| 451 |
+
"system": platform.system(),
|
| 452 |
+
"machine": platform.machine(),
|
| 453 |
+
"milvus": f"{MILVUS_HOST}:{MILVUS_PORT}",
|
| 454 |
+
"collection_size": col.num_entities
|
| 455 |
+
},
|
| 456 |
+
"sample_outputs": list(set(outputs[:10])) # First 10 unique outputs
|
| 457 |
+
}
|
| 458 |
+
|
| 459 |
+
# ==================== Main ====================
|
| 460 |
+
if __name__ == "__main__":
|
| 461 |
+
port = 9999
|
| 462 |
+
print("\n🚀 Starting Sumobot Milvus API server...")
|
| 463 |
+
print(f"📡 Server will be available at: http://0.0.0.0:{port}")
|
| 464 |
+
print(f"📚 API docs: http://0.0.0.0:{port}/docs")
|
| 465 |
+
print(f"🔍 Health check: http://0.0.0.0:{port}/health")
|
| 466 |
+
print(f"📊 Stats: http://0.0.0.0:{port}/stats")
|
| 467 |
+
print("\n" + "="*70 + "\n")
|
| 468 |
+
|
| 469 |
+
uvicorn.run(
|
| 470 |
+
app,
|
| 471 |
+
host="0.0.0.0",
|
| 472 |
+
port=port,
|
| 473 |
+
log_level="info"
|
| 474 |
+
)
|
| 475 |
+
|
| 476 |
+
# ==================== Test Commands ====================
|
| 477 |
+
f"""
|
| 478 |
+
# Health check
|
| 479 |
+
curl http://localhost:9999/health
|
| 480 |
+
|
| 481 |
+
# Collection stats
|
| 482 |
+
curl http://localhost:9999/stats
|
| 483 |
+
|
| 484 |
+
# Single query
|
| 485 |
+
curl -X POST http://localhost:9999/query \
|
| 486 |
+
-H "Content-Type: application/json" \
|
| 487 |
+
-d '{
|
| 488 |
+
"state": "AngleToEnemy=7.77, AngleToEnemyScore=0.99, DistanceToEnemyScore=0.76, NearBorderArenaScore=0.81, FacingToArena=-0.99"
|
| 489 |
+
}'
|
| 490 |
+
|
| 491 |
+
# Query with top-k results
|
| 492 |
+
curl -X POST http://localhost:9999/query \
|
| 493 |
+
-H "Content-Type: application/json" \
|
| 494 |
+
-d '{
|
| 495 |
+
"state": "AngleToEnemy=7.77, AngleToEnemyScore=0.99, DistanceToEnemyScore=0.76, NearBorderArenaScore=0.81, FacingToArena=-0.99",
|
| 496 |
+
"top_k": 3
|
| 497 |
+
}'
|
| 498 |
+
|
| 499 |
+
# Batch query
|
| 500 |
+
curl -X POST http://localhost:9999/batch \
|
| 501 |
+
-H "Content-Type: application/json" \
|
| 502 |
+
-d '{
|
| 503 |
+
"states": [
|
| 504 |
+
"AngleToEnemy=7.77, AngleToEnemyScore=0.99, DistanceToEnemyScore=0.76, NearBorderArenaScore=0.81, FacingToArena=-0.99",
|
| 505 |
+
"AngleToEnemy=2.31, AngleToEnemyScore=0.45, DistanceToEnemyScore=0.92, NearBorderArenaScore=0.12, FacingToArena=0.67"
|
| 506 |
+
]
|
| 507 |
+
}'
|
| 508 |
+
|
| 509 |
+
# Benchmark
|
| 510 |
+
curl http://localhost:9999/benchmark
|
| 511 |
+
|
| 512 |
+
# Interactive API docs
|
| 513 |
+
# Open in browser: http://localhost:9999/docs
|
| 514 |
+
"""
|
vdb/docker-compose.yml
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
services:
|
| 2 |
+
etcd:
|
| 3 |
+
container_name: etcd
|
| 4 |
+
image: quay.io/coreos/etcd:v3.5.5
|
| 5 |
+
environment:
|
| 6 |
+
- ETCD_AUTO_COMPACTION_MODE=revision
|
| 7 |
+
- ETCD_AUTO_COMPACTION_RETENTION=1000
|
| 8 |
+
- ETCD_QUOTA_BACKEND_BYTES=4294967296
|
| 9 |
+
- ETCD_SNAPSHOT_COUNT=50000
|
| 10 |
+
command: >
|
| 11 |
+
etcd
|
| 12 |
+
-name etcd
|
| 13 |
+
-advertise-client-urls http://etcd:2379
|
| 14 |
+
-listen-client-urls http://0.0.0.0:2379
|
| 15 |
+
-listen-peer-urls http://0.0.0.0:2380
|
| 16 |
+
-initial-advertise-peer-urls http://etcd:2380
|
| 17 |
+
-initial-cluster etcd=http://etcd:2380
|
| 18 |
+
-data-dir /etcd
|
| 19 |
+
volumes:
|
| 20 |
+
- ./volumes/etcd:/etcd
|
| 21 |
+
networks:
|
| 22 |
+
- milvus
|
| 23 |
+
|
| 24 |
+
minio:
|
| 25 |
+
container_name: minio
|
| 26 |
+
image: minio/minio:RELEASE.2023-03-20T20-16-18Z
|
| 27 |
+
environment:
|
| 28 |
+
- MINIO_ACCESS_KEY=minioadmin
|
| 29 |
+
- MINIO_SECRET_KEY=minioadmin
|
| 30 |
+
command: server /minio_data
|
| 31 |
+
volumes:
|
| 32 |
+
- ./volumes/minio:/minio_data
|
| 33 |
+
ports:
|
| 34 |
+
- "9000:9000"
|
| 35 |
+
networks:
|
| 36 |
+
- milvus
|
| 37 |
+
|
| 38 |
+
milvus-standalone:
|
| 39 |
+
container_name: milvus-standalone
|
| 40 |
+
image: milvusdb/milvus:v2.4.4
|
| 41 |
+
command: ["milvus", "run", "standalone"]
|
| 42 |
+
environment:
|
| 43 |
+
- ETCD_ENDPOINTS=etcd:2379
|
| 44 |
+
- MINIO_ADDRESS=minio:9000
|
| 45 |
+
ports:
|
| 46 |
+
- "19530:19530"
|
| 47 |
+
- "9091:9091"
|
| 48 |
+
depends_on:
|
| 49 |
+
- etcd
|
| 50 |
+
- minio
|
| 51 |
+
networks:
|
| 52 |
+
- milvus
|
| 53 |
+
|
| 54 |
+
attu:
|
| 55 |
+
container_name: attu
|
| 56 |
+
image: zilliz/attu:latest
|
| 57 |
+
environment:
|
| 58 |
+
- MILVUS_URL=milvus-standalone:19530
|
| 59 |
+
ports:
|
| 60 |
+
- "1233:3000"
|
| 61 |
+
depends_on:
|
| 62 |
+
- milvus-standalone
|
| 63 |
+
networks:
|
| 64 |
+
- milvus
|
| 65 |
+
|
| 66 |
+
networks:
|
| 67 |
+
milvus:
|
| 68 |
+
driver: bridge
|
vdb/import_data.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import numpy as np
|
| 3 |
+
from tqdm import tqdm
|
| 4 |
+
from pymilvus import connections, Collection
|
| 5 |
+
|
| 6 |
+
connections.connect("default", host="127.0.0.1", port="19530")
|
| 7 |
+
col = Collection("sumobot_states")
|
| 8 |
+
|
| 9 |
+
def encode_state(state_str):
|
| 10 |
+
# Parse numeric values from your formatted string
|
| 11 |
+
parts = dict(item.split('=') for item in state_str.strip('.').split(', '))
|
| 12 |
+
return np.array([
|
| 13 |
+
float(parts["AngleToEnemy"]) / 180.0, # normalize angle
|
| 14 |
+
float(parts["AngleToEnemyScore"]),
|
| 15 |
+
float(parts["DistanceToEnemyScore"]),
|
| 16 |
+
float(parts["NearBorderArenaScore"]),
|
| 17 |
+
float(parts["FacingToArena"]),
|
| 18 |
+
], dtype=np.float32)
|
| 19 |
+
|
| 20 |
+
BATCH_SIZE = 5000
|
| 21 |
+
DATA_PATH = "../dataset/temp.jsonl"
|
| 22 |
+
|
| 23 |
+
batch_vecs, batch_actions = [], []
|
| 24 |
+
with open(DATA_PATH, "r") as f:
|
| 25 |
+
for line in tqdm(f, desc="Reading dataset"):
|
| 26 |
+
item = json.loads(line)
|
| 27 |
+
vec = encode_state(item["state"])
|
| 28 |
+
batch_vecs.append(vec.tolist())
|
| 29 |
+
batch_actions.append(item["action"])
|
| 30 |
+
|
| 31 |
+
if len(batch_vecs) >= BATCH_SIZE:
|
| 32 |
+
col.insert([batch_vecs, batch_actions])
|
| 33 |
+
batch_vecs, batch_actions = [], []
|
| 34 |
+
|
| 35 |
+
# Insert remainder
|
| 36 |
+
if batch_vecs:
|
| 37 |
+
col.insert([batch_vecs, batch_actions])
|
| 38 |
+
|
| 39 |
+
col.flush()
|
| 40 |
+
print("✅ All data inserted & flushed to Milvus.")
|
vdb/query_actions.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
from pymilvus import connections, Collection
|
| 3 |
+
|
| 4 |
+
connections.connect("default", host="127.0.0.1", port="19530")
|
| 5 |
+
col = Collection("sumobot_states")
|
| 6 |
+
col.load()
|
| 7 |
+
|
| 8 |
+
def encode_state(angle, angle_score, dist_score, near_score, facing):
|
| 9 |
+
return np.array([angle / 180.0, angle_score, dist_score, near_score, facing], dtype=np.float32)
|
| 10 |
+
|
| 11 |
+
def query_action(angle, angle_score, dist_score, near_score, facing, top_k=1):
|
| 12 |
+
vec = encode_state(angle, angle_score, dist_score, near_score, facing)
|
| 13 |
+
result = col.search(
|
| 14 |
+
data=[vec],
|
| 15 |
+
anns_field="state_vec",
|
| 16 |
+
param={"nprobe": 16},
|
| 17 |
+
limit=top_k,
|
| 18 |
+
output_fields=["action"],
|
| 19 |
+
)
|
| 20 |
+
actions = [hit.entity.get("action") for hit in result[0]]
|
| 21 |
+
return actions[0] if top_k == 1 else actions
|
| 22 |
+
|
| 23 |
+
# Example use
|
| 24 |
+
action = query_action(63.55, 0.45, 0.81, 0.18, -0.48)
|
| 25 |
+
print(f"🎮 Suggested Action: {action}")
|
vdb/setup_milvus.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pymilvus import connections, FieldSchema, CollectionSchema, DataType, Collection, utility
|
| 2 |
+
|
| 3 |
+
# --------------------------
|
| 4 |
+
# 1️⃣ Connect to Milvus
|
| 5 |
+
# --------------------------
|
| 6 |
+
connections.connect(alias="default", host="127.0.0.1", port="19530")
|
| 7 |
+
print("✅ Connected to Milvus")
|
| 8 |
+
|
| 9 |
+
# --------------------------
|
| 10 |
+
# 2️⃣ Collection setup
|
| 11 |
+
# --------------------------
|
| 12 |
+
col_name = "sumobot_states"
|
| 13 |
+
|
| 14 |
+
# Check if collection exists
|
| 15 |
+
if col_name in utility.list_collections():
|
| 16 |
+
print(f"⚠️ Collection '{col_name}' already exists.")
|
| 17 |
+
col = Collection(col_name)
|
| 18 |
+
|
| 19 |
+
# Print existing schema to debug
|
| 20 |
+
print(f"Existing schema fields: {[field.name for field in col.schema.fields]}")
|
| 21 |
+
|
| 22 |
+
# Drop the old collection to recreate with correct schema
|
| 23 |
+
print(f"🗑️ Dropping existing collection to recreate...")
|
| 24 |
+
col.drop()
|
| 25 |
+
|
| 26 |
+
# Define fields
|
| 27 |
+
fields = [
|
| 28 |
+
FieldSchema(name="id", dtype=DataType.INT64, is_primary=True, auto_id=True),
|
| 29 |
+
FieldSchema(name="state_vec", dtype=DataType.FLOAT_VECTOR, dim=5), # 5 = vector dimension
|
| 30 |
+
FieldSchema(name="action", dtype=DataType.VARCHAR, max_length=64),
|
| 31 |
+
]
|
| 32 |
+
schema = CollectionSchema(fields, description="Sumobot state → action mapping")
|
| 33 |
+
col = Collection(name=col_name, schema=schema)
|
| 34 |
+
print(f"✅ Created collection '{col_name}'")
|
| 35 |
+
|
| 36 |
+
# --------------------------
|
| 37 |
+
# 3️⃣ Create vector index
|
| 38 |
+
# --------------------------
|
| 39 |
+
index_params = {
|
| 40 |
+
"index_type": "IVF_FLAT", # or "AUTOINDEX" if you want Milvus to choose automatically
|
| 41 |
+
"metric_type": "L2", # or "IP" (inner product)
|
| 42 |
+
"params": {"nlist": 128}, # depends on index type
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
# Create index
|
| 46 |
+
col.create_index(field_name="state_vec", index_params=index_params)
|
| 47 |
+
print("⚙️ Created index on 'state_vec'")
|
| 48 |
+
|
| 49 |
+
# --------------------------
|
| 50 |
+
# 4️⃣ Load collection into memory
|
| 51 |
+
# --------------------------
|
| 52 |
+
col.load()
|
| 53 |
+
print("🚀 Collection loaded into memory")
|
| 54 |
+
|
| 55 |
+
# --------------------------
|
| 56 |
+
# Optional: release when done
|
| 57 |
+
# --------------------------
|
| 58 |
+
# col.release()
|