mirror of
https://github.com/mulgadc/spinifex.git
synced 2026-10-16 01:22:00 +00:00
43fa6eae59
* feat: add GPU fields to NodeStatus and spx top nodes (mulga-996) - Add TotalGPUs/AllocGPUs to NodeStatusResponse (zero on non-GPU nodes) - Populate from gpuManager in handleNodeStatus - Show GPU (used/total) column in spx top nodes; "-" when no GPUs present * Fixed GPU passthrough and added test script * feat: always-probe GPU at startup, surface capability in NodeStatusResponse - Add gpuProbeResult struct and probeGPU() which runs at daemon startup regardless of gpu_passthrough config. Checks sysfs for GPUs, IOMMU groups, and vfio_pci module presence. - Store gpuProbe on Daemon struct; split NewDaemon into probe (always) and activate (opt-in) phases. - Populate GPUCapable, GPUPassthrough, GPUModels on NodeStatusResponse so operators can see hardware state before enabling passthrough. - Update 'spx top' GPU column: '-' = no hardware, '0/N*' = capable but passthrough not active, 'used/total' = passthrough active. * feat: SIGHUP hot-reload for GPU passthrough config (mulga-1001) - Export GenerateGPUTypes for use by the reload path - Add ResourceManager.reloadGPUTypes: mutates instanceTypes map in-place (preserves references held by instanceService) and updates NATS subscriptions without full daemon restart - Separate SIGHUP from SIGTERM/SIGINT: setupReload() listens for SIGHUP in a context-aware loop; setupShutdown no longer intercepts SIGHUP - Add reloadConfig() + applyGPUConfig(): re-reads spinifex.toml on signal, handles false→true (re-probe + activate) and true→false (refuse if instances running, otherwise deactivate) transitions * installer grub image fixes * made gpu-passthrough more user facing * vpcd fixes to set br-wan to promisc for public IP DHCP processes * fixed vpcd br-wan promisc and veth pair * ssh keygen fix * Fix: AMD GPU edge cases * script for running 8x instances on SMCI computer * fix: increase disk space on instances * feat: multi-GPU passthrough support for g7e.12xlarge (2× MI350X) - vm.VM: GPUPCIAddress string → GPUPCIAddresses []string for multi-GPU - instancetypes: add g7e.12xlarge (2 GPUs), GPUCountForType(), AMDmi350x model - instancetypes/generate: use GPUCountForType for GpuInfo.Count and TotalGpuMemoryInMiB - gpu/manager: Release() loops all pool entries for instanceID (not just first) - vm/lifecycle: loop over GPUPCIAddresses, emit gpu0/gpu1/... QEMU devices - daemon/handlers: claim N GPUs in loop for both RunInstances and StartStoppedInstance - daemon/vm_adapters: ReclaimByAddress loops GPUPCIAddresses; ReleaseGPU checks len > 0 - scripts/launch-gpu-fleet: fixed fleet — 6× g7e.4xlarge + 1× g7e.12xlarge * feat: per-instance-type disk size in GPU fleet (300 GB single, 600 GB dual) * fix: multi-gpu instance types * fix: kill QEMU synchronously when QMP handshake fails to free VFIO device When startQEMU succeeds but newQMPClientWithHandshake times out, the instance has not yet been inserted into the manager map so vmMgr.Delete in the rollback path is a no-op. QEMU keeps running and holds the VFIO group open. The GPU pool entry gets freed, the next Claim returns the same PCI address, and every subsequent QEMU fails with 'device or resource busy'. Fix: SIGKILL QEMU and wait for it to exit before returning the QMP error, ensuring the VFIO device is released before the caller recycles the GPU pool slot. * fix: quarantine GPU after QEMU launch failure to prevent re-assignment cascade When QEMU crashes during startup (e.g. pci_irq_handler assertion on a specific GPU), the pool Release frees that address and the next NATS request immediately re-claims the same broken device. Add MarkFailed() to gpu.Manager which sets Available=false for a PCI address after a launch failure, preventing re-assignment until the daemon restarts. Call MarkFailed for each GPU address in both RunInstances and StartStoppedInstance rollback paths after the Release succeeds. * fixed instance fleet launch script * remove known hosts and stagger provisioning * improvements to launch script * more upgrades * single instance gpu instance provisioning * fixed single instance provision * smci computer demo dashboard * fixes to launch script * updated smci dashboard_server * fixed demo dashboard * updated dashboard.py * feat: GPU Passthrough fixes to passthrough process - builds proper AMD or NVIDA ready images, generalised launch script * feat: gpu-passthrough updating image builder to include gpu-ready ubuntu images * fixing image builder process * fixed image builder to remove /tmp/ file before import to free space * fix: Updated COMMANDS.md to reflect new GPU management admin commands * Update docs, update internal launch script to work with new SGs, test tweaks * Updated Docs, fixed internal launch-gpu.sh script, test tweaks * fxing CI race due to GPU load
160 lines
4.8 KiB
Python
160 lines
4.8 KiB
Python
#!/usr/bin/env python3
|
|
"""YOLO inference server for the Spinifex demo.
|
|
|
|
Reads a video file, runs YOLO detection, and serves:
|
|
GET /video — MJPEG stream of annotated frames
|
|
GET /descriptions — SSE stream of qwen3-vl scene descriptions
|
|
GET /health — {"ok": true}
|
|
|
|
Environment variables:
|
|
VIDEO_PATH Path to input .mp4 (required)
|
|
QWEN_HOST Base URL of the qwen3-vl Ollama instance, e.g. http://10.0.0.5:11434
|
|
YOLO_MODEL Model name (default: yolo11n.pt)
|
|
YOLO_DEVICE GPU device index (default: 0)
|
|
DESCRIBE_INTERVAL Seconds between qwen3-vl calls (default: 5.0)
|
|
PORT Server port (default: 8080)
|
|
"""
|
|
|
|
import asyncio
|
|
import base64
|
|
import json
|
|
import os
|
|
import queue
|
|
import threading
|
|
import time
|
|
|
|
import cv2
|
|
import httpx
|
|
import uvicorn
|
|
from fastapi import FastAPI
|
|
from fastapi.responses import StreamingResponse
|
|
from ultralytics import YOLO
|
|
|
|
VIDEO_PATH = os.environ["VIDEO_PATH"]
|
|
QWEN_HOST = os.environ.get("QWEN_HOST", "")
|
|
YOLO_MODEL = os.environ.get("YOLO_MODEL", "yolo11x.pt")
|
|
YOLO_DEVICE = os.environ.get("YOLO_DEVICE", "0")
|
|
DESCRIBE_INTERVAL = float(os.environ.get("DESCRIBE_INTERVAL", "5.0"))
|
|
PORT = int(os.environ.get("PORT", "8080"))
|
|
|
|
app = FastAPI()
|
|
|
|
_frame_lock = threading.Lock()
|
|
_latest_frame: bytes | None = None
|
|
_desc_queue: queue.Queue = queue.Queue(maxsize=100)
|
|
|
|
|
|
def _encode(frame, quality: int = 80) -> bytes:
|
|
_, buf = cv2.imencode(".jpg", frame, [cv2.IMWRITE_JPEG_QUALITY, quality])
|
|
return buf.tobytes()
|
|
|
|
|
|
def _describe(img_b64: str) -> None:
|
|
if not QWEN_HOST:
|
|
return
|
|
try:
|
|
with httpx.Client(timeout=180) as client:
|
|
with client.stream(
|
|
"POST",
|
|
f"{QWEN_HOST}/api/generate",
|
|
json={
|
|
"model": "qwen3-vl:235b",
|
|
"prompt": "Briefly describe what is happening in this scene. Focus on the objects detected and any notable activity.",
|
|
"images": [img_b64],
|
|
"stream": True,
|
|
},
|
|
) as resp:
|
|
for line in resp.iter_lines():
|
|
if not line:
|
|
continue
|
|
try:
|
|
data = json.loads(line)
|
|
token = data.get("response", "")
|
|
if token and not _desc_queue.full():
|
|
_desc_queue.put(("token", token))
|
|
if data.get("done"):
|
|
_desc_queue.put(("end", ""))
|
|
except json.JSONDecodeError:
|
|
pass
|
|
except Exception as exc:
|
|
_desc_queue.put(("error", str(exc)))
|
|
|
|
|
|
def inference_loop() -> None:
|
|
model = YOLO(YOLO_MODEL)
|
|
cap = cv2.VideoCapture(VIDEO_PATH)
|
|
if not cap.isOpened():
|
|
raise RuntimeError(f"Cannot open video: {VIDEO_PATH}")
|
|
|
|
fps = cap.get(cv2.CAP_PROP_FPS) or 25.0
|
|
frame_delay = 1.0 / fps
|
|
last_describe = 0.0
|
|
|
|
while True:
|
|
ret, frame = cap.read()
|
|
if not ret:
|
|
cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
|
|
continue
|
|
|
|
results = model(frame, device=YOLO_DEVICE, verbose=False)
|
|
annotated = results[0].plot()
|
|
|
|
with _frame_lock:
|
|
global _latest_frame
|
|
_latest_frame = _encode(annotated)
|
|
|
|
now = time.monotonic()
|
|
if QWEN_HOST and now - last_describe >= DESCRIBE_INTERVAL:
|
|
last_describe = now
|
|
img_b64 = base64.b64encode(_encode(annotated, quality=60)).decode()
|
|
threading.Thread(target=_describe, args=(img_b64,), daemon=True).start()
|
|
|
|
time.sleep(frame_delay)
|
|
|
|
|
|
@app.on_event("startup")
|
|
async def startup() -> None:
|
|
threading.Thread(target=inference_loop, daemon=True).start()
|
|
|
|
|
|
@app.get("/health")
|
|
async def health():
|
|
return {"ok": True}
|
|
|
|
|
|
@app.get("/video")
|
|
async def video():
|
|
async def generate():
|
|
while True:
|
|
with _frame_lock:
|
|
frame = _latest_frame
|
|
if frame:
|
|
yield b"--frame\r\nContent-Type: image/jpeg\r\n\r\n" + frame + b"\r\n"
|
|
await asyncio.sleep(0.04)
|
|
|
|
return StreamingResponse(
|
|
generate(),
|
|
media_type="multipart/x-mixed-replace; boundary=frame",
|
|
)
|
|
|
|
|
|
@app.get("/descriptions")
|
|
async def descriptions():
|
|
async def generate():
|
|
yield 'data: {"type":"ready"}\n\n'
|
|
loop = asyncio.get_event_loop()
|
|
while True:
|
|
try:
|
|
kind, text = await loop.run_in_executor(
|
|
None, lambda: _desc_queue.get(timeout=30)
|
|
)
|
|
yield f"data: {json.dumps({'type': kind, 'text': text})}\n\n"
|
|
except queue.Empty:
|
|
yield 'data: {"type":"ping"}\n\n'
|
|
|
|
return StreamingResponse(generate(), media_type="text/event-stream")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
uvicorn.run(app, host="0.0.0.0", port=PORT)
|