Spaces:
Running

grok-gpu-mcp / app.py
Bonghit's picture
Add query_continuous_metrics tool, SQLite TSDB, and automatic backfill
3195f3c verified
Raw History Blame Contribute Delete
18.5 kB
import collections
import json
import math
import os
import sqlite3
import time
from typing import Any, Dict, List
from mcp.server.fastmcp import FastMCP
from starlette.applications import Starlette
from starlette.requests import Request
from starlette.responses import JSONResponse
from starlette.routing import Mount, Route
API_TOKEN = os.environ.get("MCP_API_TOKEN", "glsa_AqPN2oVGuVIdU8vu6eVlr7xNxvZbgWSm_e796a459")
DB_PATH = "/tmp/grok_continuous_metrics.sqlite"
STATE = {
"latest_sensors": {},
"last_push_ts": None,
"history": collections.deque(maxlen=17280), # 24 hours at 5s interval
"runs": [],
"kv": {},
"pending_sync_runs": [],
"pending_sync_kv": {},
}
def init_db():
with sqlite3.connect(DB_PATH, timeout=10) as conn:
conn.execute("PRAGMA journal_mode=WAL;")
conn.execute("PRAGMA synchronous=NORMAL;")
conn.execute(
"""
CREATE TABLE IF NOT EXISTS sensor_samples (
ts_unix REAL PRIMARY KEY,
ts_iso TEXT NOT NULL,
raw_json TEXT NOT NULL
)
"""
)
conn.commit()
init_db()
CUDA_NSIGHT_DOCS = [
{
"topic": "ampere_ga102_architecture",
"title": "NVIDIA Ampere GA102 Architecture (RTX 3090 & RTX 3080) Hardware Specs & Limits",
"content": (
"Both RTX 3090 (82 SMs, 10496 CUDA cores, 24GB 384-bit GDDR6X @ 19.5 Gbps = 936 GB/s) and "
"RTX 3080 (68 SMs, 8704 CUDA cores, 10GB 320-bit GDDR6X @ 19.0 Gbps = 760 GB/s) use GA102 (Compute Capability 8.6).\n"
"- Max warps per SM: 48 (1536 threads/SM); Max thread blocks per SM: 16.\n"
"- Register file per SM: 65,536 x 32-bit (256 KB); max registers/thread: 255.\n"
"- L1 Data Cache / Shared Memory per SM: 128 KB configurable (up to 100 KB shared memory per SM).\n"
"- L2 Cache: 6 MB (RTX 3090) / 5 MB (RTX 3080).\n"
"- Thermal limits: GPU Core slowdown threshold is ~93-95°C; GDDR6X Memory Junction throttles at 110°C (optimal < 95°C)."
),
},
{
"topic": "gpu_clock_power_tuning",
"title": "Maximizing GPU Performance: Clock Locking, Power Limits, and Throttle Reasons",
"content": (
"Key NVML / nvidia-smi controls & telemetry for maximizing sustained GPU throughput:\n"
"1. Throttle Reasons (`active_clocks_throttle_reasons`):\n"
" - `sw_power_cap`: GPU is hitting `power_limit_watts`. Increase power limit (`nvidia-smi -pl <W>`) or undervolt via VF curve / lock core clock (`nvidia-smi -lgc <min>,<max>`) to sweet-spot frequency/watt.\n"
" - `hw_thermal_slowdown` / `sw_thermal_slowdown`: Core or GDDR6X VRAM junction exceeds thermal target. Increase radiator fan / Aquastream pump RPM.\n"
" - `hw_power_brake_slowdown`: External PCIe power rail drop (+12V droop).\n"
"2. Sweet-spot VF & Memory Tuning on GA102:\n"
" - Compute-bound workloads (FP16/BF16/FP32 GEMM): Lock SM/graphics clocks (`-lgc 1860,1980`) below the steep voltage wall to prevent `sw_power_cap` oscillation.\n"
" - Memory-bandwidth-bound workloads (LLM token generation, attention, reductions): GDDR6X memory clock offset (+500 to +1000 MHz effective) yields linear bandwidth gains as long as GDDR6X junction stays < 96°C."
),
},
{
"topic": "nsight_compute_roofline_occupancy",
"title": "Nsight Compute (ncu) Roofline, Occupancy & Warp Stall Analysis",
"content": (
"Nsight Compute (`ncu --set full`) key performance bottlenecks on SM 8.6:\n"
"- `sm__throughput.avg.pct_of_peak_sustained_elapsed` vs `gpu__compute_memory_throughput.avg.pct_of_peak_sustained_elapsed`: Identifies compute-bound vs memory-bound kernels.\n"
"- `smsp__warp_issue_stalled_long_scoreboard_per_warp_active.pct`: Waiting on L2/GDDR6X global memory loads -> use `cp.async` (`cuda::memcpy_async`) to stage global->shared memory bypassing registers.\n"
"- `smsp__warp_issue_stalled_short_scoreboard_per_warp_active.pct`: Shared memory bank conflicts or MIO queue pressure -> pad shared memory arrays (`[32][33]`).\n"
"- `smsp__warp_issue_stalled_math_pipe_throttle_per_warp_active.pct`: Compute pipe saturated (good!).\n"
"- Register pressure: Using >32 registers/thread drops max occupancy below 100% (48 warps = 1536 threads -> 65536 / 1536 = 42 regs/thread max for 100% occupancy; 64 regs/thread caps at 32 warps = 66.7% occupancy)."
),
},
{
"topic": "cuda_memory_coalescing_tensor_cores",
"title": "CUDA Memory Coalescing, Vectorized Loads (float4), and Ampere 3rd-Gen Tensor Cores",
"content": (
"- Global Memory Coalescing: 32 threads in a warp should access contiguous 128-byte aligned segments (`float4` / `uint4` 16-byte vectorized loads per thread).\n"
"- L2 Persistence Cache (`cudaAccessPropertyPersisting`): Pin frequently reused working sets (up to ~4.5 MB on GA102) in L2 cache using `cudaStreamAttrValue`.\n"
"- Ampere 3rd-Gen Tensor Cores (`mma.sync.aligned.m16n8k16`): Support FP16, BF16, TF32, INT8, INT4, and 2:4 Structured Sparsity (`mma.sp`). Ensure matrix dimensions (M, N, K) are multiples of 16 (FP16/BF16) or 32 (INT8) for peak Tensor Core utilization."
),
},
]
def summarize_samples(samples: List[Dict[str, Any]], max_points: int = 60) -> Dict[str, Any]:
if not samples:
return {"sample_count": 0, "summary": {}, "samples": []}
def stats(vals):
clean = [float(x) for x in vals if x is not None]
if not clean:
return None
s = sorted(clean)
p95_idx = min(len(s) - 1, int(math.floor(0.95 * len(s))))
return {
"min": round(s[0], 2),
"max": round(s[-1], 2),
"avg": round(sum(s) / len(s), 2),
"p95": round(s[p95_idx], 2),
"latest": round(clean[-1], 2),
"delta_start_to_end": round(clean[-1] - clean[0], 2),
}
def throttle_pct(gpu_key):
counts = {}
n = len(samples)
for s in samples:
reasons = s.get("gpus", {}).get(gpu_key, {}).get("active_clocks_throttle_reasons", [])
for r in reasons:
counts[r] = counts.get(r, 0) + 1
return {k: round((v / n) * 100, 1) for k, v in sorted(counts.items(), key=lambda x: -x[1])}
summary = {
"window_start_utc": samples[0].get("timestamp"),
"window_end_utc": samples[-1].get("timestamp"),
"sample_count": len(samples),
"rtx_3090_cachy": {
"temperature_gpu_celsius": stats([s.get("gpus", {}).get("rtx_3090_cachy", {}).get("temperature_gpu_celsius") for s in samples]),
"power_draw_watts": stats([s.get("gpus", {}).get("rtx_3090_cachy", {}).get("power_draw_watts") for s in samples]),
"clock_sm_mhz": stats([s.get("gpus", {}).get("rtx_3090_cachy", {}).get("clock_sm_mhz") for s in samples]),
"clock_memory_mhz": stats([s.get("gpus", {}).get("rtx_3090_cachy", {}).get("clock_memory_mhz") for s in samples]),
"utilization_gpu_percent": stats([s.get("gpus", {}).get("rtx_3090_cachy", {}).get("utilization_gpu_percent") for s in samples]),
"throttle_reasons_pct_of_window": throttle_pct("rtx_3090_cachy"),
},
"rtx_3080_win11": {
"temperature_gpu_celsius": stats([s.get("gpus", {}).get("rtx_3080_win11", {}).get("temperature_gpu_celsius") for s in samples]),
"temperature_hotspot_celsius": stats([s.get("gpus", {}).get("rtx_3080_win11", {}).get("temperature_hotspot_celsius") for s in samples]),
"temperature_memory_junction_celsius": stats([s.get("gpus", {}).get("rtx_3080_win11", {}).get("temperature_memory_junction_celsius") for s in samples]),
"power_draw_watts": stats([s.get("gpus", {}).get("rtx_3080_win11", {}).get("power_draw_watts") for s in samples]),
"clock_sm_mhz": stats([s.get("gpus", {}).get("rtx_3080_win11", {}).get("clock_sm_mhz") for s in samples]),
"clock_memory_mhz": stats([s.get("gpus", {}).get("rtx_3080_win11", {}).get("clock_memory_mhz") for s in samples]),
"utilization_gpu_percent": stats([s.get("gpus", {}).get("rtx_3080_win11", {}).get("utilization_gpu_percent") for s in samples]),
"throttle_reasons_pct_of_window": throttle_pct("rtx_3080_win11"),
},
"watercooling_loop": {
"water_temperature_celsius": stats([s.get("watercooling_loop", {}).get("water_temperature_celsius") for s in samples]),
"pump_speed_rpm": stats([s.get("watercooling_loop", {}).get("pump_speed_rpm") for s in samples]),
"pressure_mbar": stats([s.get("watercooling_loop", {}).get("pressure_mbar") for s in samples]),
},
}
if len(samples) > max_points and max_points > 1:
step = (len(samples) - 1) / float(max_points - 1)
downsampled = [samples[int(round(i * step))] for i in range(max_points)]
else:
downsampled = samples
return {
"summary": summary,
"returned_points": len(downsampled),
"total_window_samples": len(samples),
"samples": downsampled,
}
mcp = FastMCP(
"Grok GPU Sensor, Store & Nsight CUDA MCP",
stateless_http=True,
host="0.0.0.0",
)
@mcp.tool()
def get_cluster_sensors() -> Dict[str, Any]:
"""Get the live 5-second sensor snapshot across all 3 cluster nodes:
- RTX 3090 (cachy-workstation): core temp, slowdown/shutdown thresholds, power draw/limit, clocks, VRAM, PCIe throughput, P-state, and active throttle reasons
- RTX 3080 (win11): core temp, Hot Spot temp, GDDR6X Memory Junction temp, power draw/limit, clocks, VRAM, PCIe throughput, P-state, and active throttle reasons
- AMD Radeon 610M (cachy-workstation): edge temp, APU package PPT watts, voltages, sclk, GPU busy %
- Aquastream Ultimate Watercooling Loop (win11 USB): coolant temp °C, pump RPM, pump power W, voltage V, current A, loop pressure mbar
- PVE9 Host (optimus): CPU k10temp (Tctl/Tccd1/Tccd2), VRM MOS, PCH, 4x DDR5 DIMM temps, 2x NVMe temps, fan RPMs, and motherboard voltages
"""
return {
"last_push_utc": STATE["last_push_ts"],
"sensors": STATE["latest_sensors"],
}
@mcp.tool()
def query_continuous_metrics(minutes: int = 15, max_points: int = 60) -> Dict[str, Any]:
"""Query the continuous 5-second time-series sensor metrics over the last `minutes` (e.g. 5, 15, 60, 240).
Returns:
- `summary`: min, max, avg, p95, latest, and start-to-end delta for RTX 3090, RTX 3080 (including Hot Spot & GDDR6X Junction), and the Aquastream Watercooling Loop, plus exact percentage of samples spent in each throttle reason (e.g. sw_power_cap, hw_thermal_slowdown).
- `samples`: Downsampled continuous time-series (up to `max_points`) across the window.
Backed by durable SQLite + JSONL continuous writes on CachyOS (/var/lib/grok-bot-store) and TrueNAS (/mnt/Fast4TB/grok-bot-gpu-tuning).
"""
cutoff = time.time() - (max(1, minutes) * 60.0)
with sqlite3.connect(DB_PATH, timeout=10) as conn:
rows = conn.execute(
"SELECT raw_json FROM sensor_samples WHERE ts_unix >= ? ORDER BY ts_unix ASC",
(cutoff,),
).fetchall()
samples = [json.loads(r[0]) for r in rows]
if not samples and STATE["history"]:
samples = list(STATE["history"])
return summarize_samples(samples, max_points=max(2, min(max_points, 360)))
@mcp.tool()
def get_sensor_history(limit: int = 30) -> Dict[str, Any]:
"""Get the most recent `limit` raw 5-second sensor snapshots (up to 360 samples).
For statistical summaries (min/max/avg/p95/throttle%) over a time window, use `query_continuous_metrics` instead.
"""
items = list(STATE["history"])[-max(1, min(limit, 360)):]
return {"count": len(items), "samples": items}
@mcp.tool()
def log_benchmark_run(
step: str,
gpu: str,
metrics: Dict[str, Any],
notes: str = "",
include_sensors: bool = True,
) -> Dict[str, Any]:
"""Log a GPU benchmark or tuning run. Automatically attaches the current live cluster sensor snapshot
and syncs the entry back to CachyOS (/var/lib/grok-bot-store/runs.jsonl) and TrueNAS (/mnt/Fast4TB/grok-bot-gpu-tuning/runs.jsonl).
"""
entry = {
"stored_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
"data": {
"step": step,
"gpu": gpu,
"metrics": metrics,
"notes": notes,
},
}
if include_sensors:
entry["sensors"] = STATE["latest_sensors"]
STATE["runs"].append(entry)
STATE["pending_sync_runs"].append(entry)
return {"status": "logged_and_queued_for_truenas_sync", "entry": entry}
@mcp.tool()
def get_benchmark_runs(limit: int = 50) -> Dict[str, Any]:
"""Retrieve logged GPU benchmark and tuning runs."""
items = STATE["runs"][-max(1, min(limit, 200)):]
return {"count": len(items), "runs": items}
@mcp.tool()
def save_tuning_profile(key: str, profile: Dict[str, Any]) -> Dict[str, Any]:
"""Save a GPU tuning profile, best clock/power configuration, or experiment checkpoint under `key`.
Automatically syncs back to both CachyOS local storage and TrueNAS (/mnt/Fast4TB/grok-bot-gpu-tuning/kv/).
"""
doc = {
"key": key,
"updated_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
"value": profile,
}
STATE["kv"][key] = doc
STATE["pending_sync_kv"][key] = profile
return {"status": "saved_and_queued_for_truenas_sync", "document": doc}
@mcp.tool()
def get_tuning_profile(key: str = "") -> Dict[str, Any]:
"""Get a saved tuning profile by `key`, or list all saved profiles if `key` is empty."""
if not key:
return {"keys": sorted(STATE["kv"].keys()), "profiles": STATE["kv"]}
if key not in STATE["kv"]:
return {"error": f"Key '{key}' not found", "available_keys": sorted(STATE["kv"].keys())}
return STATE["kv"][key]
@mcp.tool()
def search_cuda_docs(query: str) -> Dict[str, Any]:
"""Search NVIDIA CUDA, Nsight Compute (ncu), Ampere GA102 (RTX 3090 / RTX 3080) architecture,
GDDR6X thermal/clock tuning, occupancy, roofline, and Tensor Core optimization documentation.
"""
q_terms = [t.lower() for t in query.split() if len(t) > 1]
scored = []
for doc in CUDA_NSIGHT_DOCS:
haystack = (doc["title"] + " " + doc["topic"] + " " + doc["content"]).lower()
score = sum(3 if t in doc["title"].lower() else (1 if t in haystack else 0) for t in q_terms)
scored.append((score, doc))
scored.sort(key=lambda x: x[0], reverse=True)
results = [d for s, d in scored if s > 0] or CUDA_NSIGHT_DOCS
return {"query": query, "results": results}
async def ingest_endpoint(request: Request):
auth = request.headers.get("Authorization", "")
if auth != f"Bearer {API_TOKEN}":
return JSONResponse({"error": "Unauthorized"}, status_code=401)
body = await request.json()
now_iso = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
with sqlite3.connect(DB_PATH, timeout=10) as conn:
if "backfill_history" in body and isinstance(body["backfill_history"], list):
for s in body["backfill_history"]:
ts_u = s.get("ts_unix") or time.time()
ts_i = s.get("timestamp") or now_iso
conn.execute(
"INSERT OR IGNORE INTO sensor_samples (ts_unix, ts_iso, raw_json) VALUES (?, ?, ?)",
(ts_u, ts_i, json.dumps(s)),
)
STATE["history"].clear()
for s in body["backfill_history"]:
STATE["history"].append(s)
if "sensors" in body:
snap = body["sensors"]
STATE["latest_sensors"] = snap
STATE["last_push_ts"] = now_iso
STATE["history"].append(snap)
ts_u = snap.get("ts_unix") or time.time()
ts_i = snap.get("timestamp") or now_iso
conn.execute(
"INSERT OR REPLACE INTO sensor_samples (ts_unix, ts_iso, raw_json) VALUES (?, ?, ?)",
(ts_u, ts_i, json.dumps(snap)),
)
conn.commit()
total_rows = conn.execute("SELECT COUNT(*) FROM sensor_samples").fetchone()[0]
if "kv" in body and isinstance(body["kv"], dict):
for k, v in body["kv"].items():
if k not in STATE["kv"]:
STATE["kv"][k] = v
if "runs" in body and isinstance(body["runs"], list) and not STATE["runs"]:
STATE["runs"] = body["runs"][-200:]
sync_runs = list(STATE["pending_sync_runs"])
sync_kv = dict(STATE["pending_sync_kv"])
STATE["pending_sync_runs"].clear()
STATE["pending_sync_kv"].clear()
return JSONResponse({
"status": "ok",
"last_push_ts": now_iso,
"stored_samples": total_rows,
"needs_backfill": total_rows < 5,
"sync_to_local": {
"runs": sync_runs,
"kv": sync_kv,
},
})
async def sensors_rest(request: Request):
return JSONResponse({
"last_push_utc": STATE["last_push_ts"],
"sensors": STATE["latest_sensors"],
})
async def metrics_rest(request: Request):
minutes = int(request.query_params.get("minutes", "15"))
max_points = int(request.query_params.get("max_points", "60"))
return JSONResponse(query_continuous_metrics(minutes=minutes, max_points=max_points))
async def health_rest(request: Request):
with sqlite3.connect(DB_PATH, timeout=5) as conn:
total_rows = conn.execute("SELECT COUNT(*) FROM sensor_samples").fetchone()[0]
return JSONResponse({
"status": "ok",
"service": "Grok GPU Sensor, Store & Nsight CUDA MCP",
"mcp_endpoint": "/mcp",
"last_sensor_push_utc": STATE["last_push_ts"],
"continuous_samples": total_rows,
"stored_runs": len(STATE["runs"]),
"kv_keys": sorted(STATE["kv"].keys()),
})
mcp_http_app = mcp.streamable_http_app()
app = Starlette(
routes=[
Route("/", health_rest),
Route("/healthz", health_rest),
Route("/sensors", sensors_rest),
Route("/metrics", metrics_rest),
Route("/ingest", ingest_endpoint, methods=["POST"]),
Mount("/", app=mcp_http_app),
],
lifespan=mcp_http_app.router.lifespan_context,
)