Spaces:
Sleeping
Sleeping
Implement full GPU/Rank monitoring dashboard
Browse filesFeatures:
- GPU/Rank Status: Per-GPU memory, utilization, temperature, power, TP rank
- Inference Metrics: tokens/sec, batch size, KV cache, TTFT, request queues
- System Metrics: CPU usage, RAM usage
- Test Inference: Send prompts and measure latency
- Auto-refresh every 3 seconds
- Demo mode for HF Spaces (simulated GPU data)
- Real metrics when running locally with vLLM + GPUs
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- app.py +489 -293
- requirements.txt +2 -0
app.py
CHANGED
|
@@ -1,12 +1,16 @@
|
|
| 1 |
"""
|
| 2 |
-
LLM Inference Dashboard -
|
|
|
|
| 3 |
"""
|
| 4 |
|
| 5 |
import time
|
| 6 |
import logging
|
| 7 |
import os
|
|
|
|
| 8 |
import requests
|
| 9 |
from datetime import datetime
|
|
|
|
|
|
|
| 10 |
|
| 11 |
import gradio as gr
|
| 12 |
import pandas as pd
|
|
@@ -14,37 +18,170 @@ import pandas as pd
|
|
| 14 |
logging.basicConfig(level=logging.INFO)
|
| 15 |
logger = logging.getLogger(__name__)
|
| 16 |
|
| 17 |
-
#
|
| 18 |
IS_HF_SPACE = os.getenv("SPACE_ID") is not None
|
|
|
|
| 19 |
|
| 20 |
-
# vLLM
|
| 21 |
VLLM_HOST = os.getenv("VLLM_HOST", "localhost")
|
| 22 |
VLLM_PORT = os.getenv("VLLM_PORT", "8000")
|
| 23 |
VLLM_URL = f"http://{VLLM_HOST}:{VLLM_PORT}"
|
| 24 |
|
| 25 |
-
#
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
hf_client = None
|
| 31 |
if IS_HF_SPACE:
|
| 32 |
try:
|
| 33 |
from huggingface_hub import InferenceClient
|
| 34 |
-
if HF_TOKEN
|
| 35 |
-
hf_client = InferenceClient(token=HF_TOKEN)
|
| 36 |
-
else:
|
| 37 |
-
hf_client = InferenceClient()
|
| 38 |
except ImportError:
|
| 39 |
-
|
| 40 |
|
|
|
|
| 41 |
START_TIME = time.time()
|
| 42 |
-
METRICS_HISTORY = {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
TOTAL_REQUESTS = 0
|
| 44 |
TOTAL_TOKENS = 0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
|
| 46 |
|
| 47 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
"""Check if vLLM server is running."""
|
| 49 |
if IS_HF_SPACE:
|
| 50 |
return False
|
|
@@ -55,61 +192,65 @@ def check_vllm_connection():
|
|
| 55 |
return False
|
| 56 |
|
| 57 |
|
| 58 |
-
def get_vllm_metrics():
|
| 59 |
"""Fetch metrics from vLLM Prometheus endpoint."""
|
| 60 |
try:
|
| 61 |
resp = requests.get(f"{VLLM_URL}/metrics", timeout=5)
|
| 62 |
if resp.status_code == 200:
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
return None
|
| 67 |
|
| 68 |
|
| 69 |
-
def
|
| 70 |
-
"""
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
if line.startswith("#") or not line.strip():
|
| 74 |
-
continue
|
| 75 |
-
try:
|
| 76 |
-
if " " in line:
|
| 77 |
-
name_part, value = line.rsplit(" ", 1)
|
| 78 |
-
name = name_part.split("{")[0]
|
| 79 |
-
metrics[name] = float(value)
|
| 80 |
-
except:
|
| 81 |
-
pass
|
| 82 |
-
return metrics
|
| 83 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 84 |
|
| 85 |
-
def get_model_info():
|
| 86 |
-
"""Get model info."""
|
| 87 |
-
if IS_HF_SPACE:
|
| 88 |
-
return HF_MODEL
|
| 89 |
-
try:
|
| 90 |
-
resp = requests.get(f"{VLLM_URL}/v1/models", timeout=5)
|
| 91 |
-
if resp.status_code == 200:
|
| 92 |
-
data = resp.json()
|
| 93 |
-
if data.get("data"):
|
| 94 |
-
return data["data"][0].get("id", "Unknown")
|
| 95 |
-
except:
|
| 96 |
-
pass
|
| 97 |
-
return "Not connected"
|
| 98 |
|
|
|
|
|
|
|
|
|
|
| 99 |
|
| 100 |
-
def send_hf_inference(prompt, max_tokens=100):
|
| 101 |
-
"""Send inference
|
| 102 |
-
global TOTAL_REQUESTS, TOTAL_TOKENS
|
| 103 |
|
| 104 |
if hf_client is None:
|
| 105 |
-
return {"success": False, "error": "
|
| 106 |
|
| 107 |
try:
|
| 108 |
start = time.time()
|
| 109 |
|
| 110 |
-
# Use chat_completion for conversational models
|
| 111 |
messages = [{"role": "user", "content": prompt}]
|
| 112 |
-
|
| 113 |
response = hf_client.chat_completion(
|
| 114 |
messages=messages,
|
| 115 |
model=HF_MODEL,
|
|
@@ -117,15 +258,14 @@ def send_hf_inference(prompt, max_tokens=100):
|
|
| 117 |
)
|
| 118 |
|
| 119 |
latency = (time.time() - start) * 1000
|
| 120 |
-
|
| 121 |
output = response.choices[0].message.content
|
| 122 |
|
| 123 |
-
# Get token counts
|
| 124 |
prompt_tokens = len(prompt) // 4
|
| 125 |
completion_tokens = len(output) // 4
|
| 126 |
|
| 127 |
TOTAL_REQUESTS += 1
|
| 128 |
TOTAL_TOKENS += completion_tokens
|
|
|
|
| 129 |
|
| 130 |
return {
|
| 131 |
"success": True,
|
|
@@ -135,17 +275,12 @@ def send_hf_inference(prompt, max_tokens=100):
|
|
| 135 |
"completion_tokens": completion_tokens,
|
| 136 |
}
|
| 137 |
except Exception as e:
|
| 138 |
-
|
| 139 |
-
if "401" in error_msg:
|
| 140 |
-
return {"success": False, "error": "Invalid HF_TOKEN. Add it in Space Settings > Secrets."}
|
| 141 |
-
elif "503" in error_msg or "loading" in error_msg.lower():
|
| 142 |
-
return {"success": False, "error": "Model is loading, please wait 20-30 seconds and try again..."}
|
| 143 |
-
return {"success": False, "error": f"Error: {error_msg}"}
|
| 144 |
|
| 145 |
|
| 146 |
-
def
|
| 147 |
-
"""Send
|
| 148 |
-
global TOTAL_REQUESTS, TOTAL_TOKENS
|
| 149 |
|
| 150 |
try:
|
| 151 |
start = time.time()
|
|
@@ -168,6 +303,7 @@ def send_vllm_prompt(prompt, max_tokens=100):
|
|
| 168 |
|
| 169 |
TOTAL_REQUESTS += 1
|
| 170 |
TOTAL_TOKENS += usage.get("completion_tokens", 0)
|
|
|
|
| 171 |
|
| 172 |
return {
|
| 173 |
"success": True,
|
|
@@ -181,329 +317,389 @@ def send_vllm_prompt(prompt, max_tokens=100):
|
|
| 181 |
return {"success": False, "error": "Unknown error"}
|
| 182 |
|
| 183 |
|
| 184 |
-
def
|
| 185 |
-
"""
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
elapsed = time.time() - START_TIME
|
| 189 |
-
now = datetime.now().strftime("%H:%M:%S")
|
| 190 |
|
| 191 |
if IS_HF_SPACE:
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
METRICS_HISTORY["tokens_per_sec"].append(round(tokens_per_sec, 1))
|
| 196 |
-
METRICS_HISTORY["timestamps"].append(now)
|
| 197 |
-
|
| 198 |
-
# Keep last 20 points
|
| 199 |
-
if len(METRICS_HISTORY["tokens_per_sec"]) > 20:
|
| 200 |
-
METRICS_HISTORY["tokens_per_sec"] = METRICS_HISTORY["tokens_per_sec"][-20:]
|
| 201 |
-
METRICS_HISTORY["timestamps"] = METRICS_HISTORY["timestamps"][-20:]
|
| 202 |
-
|
| 203 |
-
history_df = pd.DataFrame({
|
| 204 |
-
"Time": METRICS_HISTORY["timestamps"],
|
| 205 |
-
"Tokens/s": METRICS_HISTORY["tokens_per_sec"],
|
| 206 |
-
})
|
| 207 |
|
|
|
|
| 208 |
return (
|
| 209 |
-
"
|
| 210 |
-
|
| 211 |
-
round(
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
0, # No KV cache info
|
| 215 |
-
0,
|
| 216 |
-
TOTAL_TOKENS,
|
| 217 |
-
history_df,
|
| 218 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 219 |
|
| 220 |
-
|
| 221 |
-
connected = check_vllm_connection()
|
| 222 |
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
)
|
| 230 |
|
| 231 |
-
|
| 232 |
-
|
|
|
|
|
|
|
|
|
|
| 233 |
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
prompt_tokens = metrics.get("vllm:prompt_tokens_total", 0)
|
| 239 |
-
gen_tokens = metrics.get("vllm:generation_tokens_total", 0)
|
| 240 |
|
| 241 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 242 |
|
| 243 |
-
|
| 244 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 245 |
|
| 246 |
-
if len(METRICS_HISTORY["tokens_per_sec"]) > 20:
|
| 247 |
-
METRICS_HISTORY["tokens_per_sec"] = METRICS_HISTORY["tokens_per_sec"][-20:]
|
| 248 |
-
METRICS_HISTORY["timestamps"] = METRICS_HISTORY["timestamps"][-20:]
|
| 249 |
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 254 |
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
)
|
| 266 |
|
| 267 |
return (
|
| 268 |
-
|
| 269 |
model,
|
| 270 |
-
|
| 271 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 272 |
)
|
| 273 |
|
| 274 |
|
| 275 |
-
def
|
| 276 |
-
"""
|
| 277 |
-
|
| 278 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 279 |
|
| 280 |
-
# Choose backend based on environment
|
| 281 |
-
if IS_HF_SPACE:
|
| 282 |
-
result = send_hf_inference(prompt, int(max_tokens))
|
| 283 |
-
else:
|
| 284 |
-
result = send_vllm_prompt(prompt, int(max_tokens))
|
| 285 |
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
if len(METRICS_HISTORY["latency"]) > 20:
|
| 290 |
-
METRICS_HISTORY["latency"] = METRICS_HISTORY["latency"][-20:]
|
| 291 |
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
result["output"],
|
| 295 |
-
round(result["latency_ms"], 1),
|
| 296 |
-
result["prompt_tokens"],
|
| 297 |
-
result["completion_tokens"],
|
| 298 |
-
)
|
| 299 |
-
else:
|
| 300 |
-
return (
|
| 301 |
-
f"Error: {result.get('error', 'Unknown')}",
|
| 302 |
-
"",
|
| 303 |
-
0, 0, 0,
|
| 304 |
-
)
|
| 305 |
|
|
|
|
|
|
|
| 306 |
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
|
|
|
|
|
|
|
|
|
| 310 |
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 315 |
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
|
|
|
| 325 |
|
| 326 |
-
|
| 327 |
-
|
|
|
|
|
|
|
|
|
|
| 328 |
|
| 329 |
with gr.Row():
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
placeholder="Enter your prompt here...",
|
| 333 |
-
lines=3,
|
| 334 |
-
value="Explain quantum computing in simple terms."
|
| 335 |
-
)
|
| 336 |
-
max_tokens_input = gr.Slider(
|
| 337 |
-
minimum=10, maximum=500, value=100,
|
| 338 |
-
label="Max Tokens"
|
| 339 |
-
)
|
| 340 |
|
| 341 |
-
|
|
|
|
|
|
|
|
|
|
| 342 |
|
| 343 |
with gr.Row():
|
| 344 |
-
|
| 345 |
-
|
|
|
|
|
|
|
| 346 |
|
| 347 |
with gr.Row():
|
| 348 |
-
|
| 349 |
-
|
| 350 |
|
| 351 |
-
|
|
|
|
|
|
|
|
|
|
| 352 |
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
outputs=[
|
|
|
|
|
|
|
| 357 |
)
|
| 358 |
|
| 359 |
-
#
|
| 360 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 361 |
if IS_HF_SPACE:
|
| 362 |
-
gr.Markdown("
|
| 363 |
-
gr.Markdown("*Note: Full vLLM metrics available when running locally*")
|
| 364 |
-
else:
|
| 365 |
-
gr.Markdown("### vLLM Server Metrics")
|
| 366 |
|
| 367 |
with gr.Row():
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 372 |
|
| 373 |
with gr.Row():
|
| 374 |
-
|
| 375 |
-
|
| 376 |
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
label="
|
| 380 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 381 |
)
|
| 382 |
|
| 383 |
-
#
|
| 384 |
-
|
|
|
|
|
|
|
| 385 |
if IS_HF_SPACE:
|
| 386 |
gr.Markdown("""
|
| 387 |
### Running on HuggingFace Spaces
|
| 388 |
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
**Setup Required (one-time):**
|
| 392 |
-
1. Go to your Space Settings (โ๏ธ icon)
|
| 393 |
-
2. Click "Variables and secrets"
|
| 394 |
-
3. Add a new secret: `HF_TOKEN` = your HuggingFace token
|
| 395 |
-
4. Get your token from: https://huggingface.co/settings/tokens
|
| 396 |
-
|
| 397 |
-
**How to use:**
|
| 398 |
-
1. Go to the "Test Inference" tab
|
| 399 |
-
2. Enter a prompt and click "Send Prompt"
|
| 400 |
-
3. First request may take 20-30 seconds (model cold start)
|
| 401 |
-
4. Subsequent requests will be faster
|
| 402 |
|
| 403 |
-
**
|
|
|
|
|
|
|
|
|
|
| 404 |
|
| 405 |
---
|
| 406 |
|
| 407 |
-
### For
|
| 408 |
|
| 409 |
-
To get full vLLM metrics (KV cache, batch size, GPU utilization), run locally:
|
| 410 |
-
|
| 411 |
-
**Step 1: Clone and install**
|
| 412 |
```bash
|
|
|
|
| 413 |
git clone https://huggingface.co/spaces/jkottu/llm-inference-dashboard
|
| 414 |
cd llm-inference-dashboard
|
|
|
|
|
|
|
| 415 |
pip install -r requirements.txt
|
| 416 |
-
pip install vllm
|
| 417 |
-
```
|
| 418 |
|
| 419 |
-
|
| 420 |
-
```bash
|
| 421 |
python -m vllm.entrypoints.openai.api_server \\
|
| 422 |
--model Qwen/Qwen2.5-0.5B-Instruct \\
|
|
|
|
| 423 |
--port 8000
|
|
|
|
|
|
|
|
|
|
| 424 |
```
|
| 425 |
|
| 426 |
-
**
|
| 427 |
```bash
|
| 428 |
-
python
|
|
|
|
|
|
|
|
|
|
| 429 |
```
|
| 430 |
""")
|
| 431 |
else:
|
| 432 |
gr.Markdown("""
|
| 433 |
-
###
|
| 434 |
-
|
| 435 |
-
**Step 1: Install vLLM**
|
| 436 |
-
```bash
|
| 437 |
-
pip install vllm
|
| 438 |
-
```
|
| 439 |
|
| 440 |
-
**Step
|
| 441 |
|
| 442 |
-
**Option A - Tiny (0.5B, ~2GB VRAM):**
|
| 443 |
```bash
|
|
|
|
| 444 |
python -m vllm.entrypoints.openai.api_server \\
|
| 445 |
--model Qwen/Qwen2.5-0.5B-Instruct \\
|
| 446 |
--port 8000
|
| 447 |
-
```
|
| 448 |
-
|
| 449 |
-
**Option B - Small (1.5B, ~4GB VRAM):**
|
| 450 |
-
```bash
|
| 451 |
-
python -m vllm.entrypoints.openai.api_server \\
|
| 452 |
-
--model Qwen/Qwen2.5-1.5B-Instruct \\
|
| 453 |
-
--port 8000
|
| 454 |
-
```
|
| 455 |
|
| 456 |
-
|
| 457 |
-
```bash
|
| 458 |
python -m vllm.entrypoints.openai.api_server \\
|
| 459 |
-
--model
|
|
|
|
| 460 |
--port 8000
|
| 461 |
```
|
| 462 |
|
| 463 |
-
**Step
|
| 464 |
```bash
|
| 465 |
python app.py
|
| 466 |
```
|
| 467 |
|
| 468 |
-
**Step
|
| 469 |
-
|
| 470 |
-
|
| 471 |
-
|
| 472 |
-
4. Watch metrics update in "Live Metrics" tab
|
| 473 |
-
|
| 474 |
-
---
|
| 475 |
-
*Dashboard expects vLLM at http://localhost:8000*
|
| 476 |
""")
|
| 477 |
|
| 478 |
-
#
|
| 479 |
-
|
| 480 |
-
|
| 481 |
-
|
| 482 |
-
|
| 483 |
-
|
| 484 |
-
|
| 485 |
-
|
|
|
|
| 486 |
)
|
| 487 |
|
| 488 |
-
#
|
| 489 |
-
timer = gr.Timer(5)
|
| 490 |
timer.tick(
|
| 491 |
-
fn=
|
| 492 |
-
outputs=[
|
| 493 |
-
|
| 494 |
-
|
| 495 |
-
total_prompt_tokens, total_gen_tokens, metrics_history,
|
| 496 |
-
],
|
| 497 |
)
|
| 498 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 499 |
|
| 500 |
-
if __name__ == "__main__":
|
| 501 |
-
if IS_HF_SPACE:
|
| 502 |
-
logger.info("Running on HuggingFace Spaces with HF Inference API")
|
| 503 |
-
else:
|
| 504 |
-
logger.info(f"Dashboard connecting to vLLM at {VLLM_URL}")
|
| 505 |
|
| 506 |
-
|
| 507 |
-
|
| 508 |
-
|
| 509 |
-
)
|
|
|
|
| 1 |
"""
|
| 2 |
+
LLM Inference Dashboard - Full GPU/Rank Monitoring
|
| 3 |
+
Works on HF Spaces (demo mode) and locally with real vLLM + GPUs
|
| 4 |
"""
|
| 5 |
|
| 6 |
import time
|
| 7 |
import logging
|
| 8 |
import os
|
| 9 |
+
import random
|
| 10 |
import requests
|
| 11 |
from datetime import datetime
|
| 12 |
+
from dataclasses import dataclass
|
| 13 |
+
from typing import List, Dict, Optional
|
| 14 |
|
| 15 |
import gradio as gr
|
| 16 |
import pandas as pd
|
|
|
|
| 18 |
logging.basicConfig(level=logging.INFO)
|
| 19 |
logger = logging.getLogger(__name__)
|
| 20 |
|
| 21 |
+
# Environment detection
|
| 22 |
IS_HF_SPACE = os.getenv("SPACE_ID") is not None
|
| 23 |
+
HF_TOKEN = os.getenv("HF_TOKEN", "")
|
| 24 |
|
| 25 |
+
# vLLM configuration
|
| 26 |
VLLM_HOST = os.getenv("VLLM_HOST", "localhost")
|
| 27 |
VLLM_PORT = os.getenv("VLLM_PORT", "8000")
|
| 28 |
VLLM_URL = f"http://{VLLM_HOST}:{VLLM_PORT}"
|
| 29 |
|
| 30 |
+
# HF Inference
|
| 31 |
+
HF_MODEL = "mistralai/Mistral-7B-Instruct-v0.2"
|
| 32 |
+
|
| 33 |
+
# Try to import GPU libraries
|
| 34 |
+
try:
|
| 35 |
+
import pynvml
|
| 36 |
+
pynvml.nvmlInit()
|
| 37 |
+
HAS_NVML = True
|
| 38 |
+
GPU_COUNT = pynvml.nvmlDeviceGetCount()
|
| 39 |
+
logger.info(f"NVML initialized: {GPU_COUNT} GPUs detected")
|
| 40 |
+
except:
|
| 41 |
+
HAS_NVML = False
|
| 42 |
+
GPU_COUNT = 0
|
| 43 |
+
logger.info("NVML not available - using demo GPU data")
|
| 44 |
+
|
| 45 |
+
# Try to import HF client
|
| 46 |
hf_client = None
|
| 47 |
if IS_HF_SPACE:
|
| 48 |
try:
|
| 49 |
from huggingface_hub import InferenceClient
|
| 50 |
+
hf_client = InferenceClient(token=HF_TOKEN) if HF_TOKEN else InferenceClient()
|
|
|
|
|
|
|
|
|
|
| 51 |
except ImportError:
|
| 52 |
+
pass
|
| 53 |
|
| 54 |
+
# Global state
|
| 55 |
START_TIME = time.time()
|
| 56 |
+
METRICS_HISTORY = {
|
| 57 |
+
"timestamps": [],
|
| 58 |
+
"tokens_per_sec": [],
|
| 59 |
+
"gpu_memory": [],
|
| 60 |
+
"gpu_util": [],
|
| 61 |
+
"batch_size": [],
|
| 62 |
+
"kv_cache": [],
|
| 63 |
+
}
|
| 64 |
TOTAL_REQUESTS = 0
|
| 65 |
TOTAL_TOKENS = 0
|
| 66 |
+
LAST_INFERENCE_LATENCY = 0
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
# =============================================================================
|
| 70 |
+
# GPU Metrics Collection
|
| 71 |
+
# =============================================================================
|
| 72 |
+
|
| 73 |
+
@dataclass
|
| 74 |
+
class GPUStats:
|
| 75 |
+
gpu_id: int
|
| 76 |
+
name: str
|
| 77 |
+
memory_used_gb: float
|
| 78 |
+
memory_total_gb: float
|
| 79 |
+
memory_percent: float
|
| 80 |
+
utilization: float
|
| 81 |
+
temperature: int
|
| 82 |
+
power_watts: float
|
| 83 |
+
tp_rank: int # Tensor parallel rank
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def get_real_gpu_stats() -> List[GPUStats]:
|
| 87 |
+
"""Get real GPU stats via pynvml."""
|
| 88 |
+
stats = []
|
| 89 |
+
for i in range(GPU_COUNT):
|
| 90 |
+
try:
|
| 91 |
+
handle = pynvml.nvmlDeviceGetHandleByIndex(i)
|
| 92 |
+
name = pynvml.nvmlDeviceGetName(handle)
|
| 93 |
+
if isinstance(name, bytes):
|
| 94 |
+
name = name.decode('utf-8')
|
| 95 |
+
|
| 96 |
+
mem = pynvml.nvmlDeviceGetMemoryInfo(handle)
|
| 97 |
+
util = pynvml.nvmlDeviceGetUtilizationRates(handle)
|
| 98 |
+
temp = pynvml.nvmlDeviceGetTemperature(handle, pynvml.NVML_TEMPERATURE_GPU)
|
| 99 |
+
|
| 100 |
+
try:
|
| 101 |
+
power = pynvml.nvmlDeviceGetPowerUsage(handle) / 1000 # mW to W
|
| 102 |
+
except:
|
| 103 |
+
power = 0
|
| 104 |
+
|
| 105 |
+
stats.append(GPUStats(
|
| 106 |
+
gpu_id=i,
|
| 107 |
+
name=name,
|
| 108 |
+
memory_used_gb=mem.used / 1e9,
|
| 109 |
+
memory_total_gb=mem.total / 1e9,
|
| 110 |
+
memory_percent=(mem.used / mem.total) * 100,
|
| 111 |
+
utilization=util.gpu,
|
| 112 |
+
temperature=temp,
|
| 113 |
+
power_watts=power,
|
| 114 |
+
tp_rank=i, # Assume TP rank = GPU ID
|
| 115 |
+
))
|
| 116 |
+
except Exception as e:
|
| 117 |
+
logger.error(f"Error getting GPU {i} stats: {e}")
|
| 118 |
+
return stats
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def get_demo_gpu_stats() -> List[GPUStats]:
|
| 122 |
+
"""Generate realistic demo GPU stats."""
|
| 123 |
+
elapsed = time.time() - START_TIME
|
| 124 |
+
base_util = 45 + 30 * abs((elapsed % 20) - 10) / 10
|
| 125 |
+
base_memory = 18.5 + random.uniform(-0.5, 0.5)
|
| 126 |
+
|
| 127 |
+
# Simulate 4 GPUs for tensor parallel
|
| 128 |
+
stats = []
|
| 129 |
+
for i in range(4):
|
| 130 |
+
util_variance = random.uniform(-8, 8)
|
| 131 |
+
mem_variance = random.uniform(-0.3, 0.3)
|
| 132 |
+
|
| 133 |
+
stats.append(GPUStats(
|
| 134 |
+
gpu_id=i,
|
| 135 |
+
name="NVIDIA A100-SXM4-40GB",
|
| 136 |
+
memory_used_gb=base_memory + mem_variance + i * 0.2,
|
| 137 |
+
memory_total_gb=40.0,
|
| 138 |
+
memory_percent=(base_memory + mem_variance + i * 0.2) / 40.0 * 100,
|
| 139 |
+
utilization=min(100, max(0, base_util + util_variance + i * 2)),
|
| 140 |
+
temperature=int(52 + base_util * 0.15 + i * 2),
|
| 141 |
+
power_watts=180 + base_util * 1.5 + random.uniform(-10, 10),
|
| 142 |
+
tp_rank=i,
|
| 143 |
+
))
|
| 144 |
+
return stats
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def get_gpu_stats() -> List[GPUStats]:
|
| 148 |
+
"""Get GPU stats - real or demo."""
|
| 149 |
+
if HAS_NVML and GPU_COUNT > 0:
|
| 150 |
+
return get_real_gpu_stats()
|
| 151 |
+
return get_demo_gpu_stats()
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
# =============================================================================
|
| 155 |
+
# System Metrics
|
| 156 |
+
# =============================================================================
|
| 157 |
+
|
| 158 |
+
def get_system_metrics() -> Dict:
|
| 159 |
+
"""Get system-level metrics."""
|
| 160 |
+
try:
|
| 161 |
+
import psutil
|
| 162 |
+
cpu_percent = psutil.cpu_percent(interval=0.1)
|
| 163 |
+
memory = psutil.virtual_memory()
|
| 164 |
+
return {
|
| 165 |
+
"cpu_percent": cpu_percent,
|
| 166 |
+
"ram_used_gb": memory.used / 1e9,
|
| 167 |
+
"ram_total_gb": memory.total / 1e9,
|
| 168 |
+
"ram_percent": memory.percent,
|
| 169 |
+
}
|
| 170 |
+
except ImportError:
|
| 171 |
+
# Demo data
|
| 172 |
+
return {
|
| 173 |
+
"cpu_percent": 35 + random.uniform(-10, 10),
|
| 174 |
+
"ram_used_gb": 48 + random.uniform(-5, 5),
|
| 175 |
+
"ram_total_gb": 128,
|
| 176 |
+
"ram_percent": 38 + random.uniform(-5, 5),
|
| 177 |
+
}
|
| 178 |
|
| 179 |
|
| 180 |
+
# =============================================================================
|
| 181 |
+
# vLLM Metrics
|
| 182 |
+
# =============================================================================
|
| 183 |
+
|
| 184 |
+
def check_vllm_connection() -> bool:
|
| 185 |
"""Check if vLLM server is running."""
|
| 186 |
if IS_HF_SPACE:
|
| 187 |
return False
|
|
|
|
| 192 |
return False
|
| 193 |
|
| 194 |
|
| 195 |
+
def get_vllm_metrics() -> Optional[Dict]:
|
| 196 |
"""Fetch metrics from vLLM Prometheus endpoint."""
|
| 197 |
try:
|
| 198 |
resp = requests.get(f"{VLLM_URL}/metrics", timeout=5)
|
| 199 |
if resp.status_code == 200:
|
| 200 |
+
metrics = {}
|
| 201 |
+
for line in resp.text.strip().split("\n"):
|
| 202 |
+
if line.startswith("#") or not line.strip():
|
| 203 |
+
continue
|
| 204 |
+
try:
|
| 205 |
+
if " " in line:
|
| 206 |
+
name_part, value = line.rsplit(" ", 1)
|
| 207 |
+
name = name_part.split("{")[0]
|
| 208 |
+
metrics[name] = float(value)
|
| 209 |
+
except:
|
| 210 |
+
pass
|
| 211 |
+
return metrics
|
| 212 |
+
except:
|
| 213 |
+
pass
|
| 214 |
return None
|
| 215 |
|
| 216 |
|
| 217 |
+
def get_demo_inference_metrics() -> Dict:
|
| 218 |
+
"""Generate demo inference metrics."""
|
| 219 |
+
elapsed = time.time() - START_TIME
|
| 220 |
+
load_factor = 0.5 + 0.3 * abs((elapsed % 30) - 15) / 15
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 221 |
|
| 222 |
+
batch_size = int(4 + 8 * load_factor + random.randint(-1, 1))
|
| 223 |
+
tokens_per_sec = 45 * load_factor + random.uniform(-5, 5)
|
| 224 |
+
kv_cache = 35 + batch_size * 4 + random.uniform(-3, 3)
|
| 225 |
+
|
| 226 |
+
return {
|
| 227 |
+
"tokens_per_sec": round(tokens_per_sec, 1),
|
| 228 |
+
"batch_size": batch_size,
|
| 229 |
+
"kv_cache_percent": round(min(95, kv_cache), 1),
|
| 230 |
+
"running_requests": batch_size,
|
| 231 |
+
"waiting_requests": int(max(0, (load_factor - 0.6) * 15)),
|
| 232 |
+
"ttft_ms": round(80 + (1 - load_factor) * 40 + random.uniform(-10, 20), 1),
|
| 233 |
+
"tpot_ms": round(22 + random.uniform(-2, 3), 1),
|
| 234 |
+
"prompt_tokens": TOTAL_TOKENS // 3,
|
| 235 |
+
"generation_tokens": TOTAL_TOKENS,
|
| 236 |
+
}
|
| 237 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 238 |
|
| 239 |
+
# =============================================================================
|
| 240 |
+
# Inference Functions
|
| 241 |
+
# =============================================================================
|
| 242 |
|
| 243 |
+
def send_hf_inference(prompt: str, max_tokens: int = 100) -> Dict:
|
| 244 |
+
"""Send inference via HuggingFace API."""
|
| 245 |
+
global TOTAL_REQUESTS, TOTAL_TOKENS, LAST_INFERENCE_LATENCY
|
| 246 |
|
| 247 |
if hf_client is None:
|
| 248 |
+
return {"success": False, "error": "HF client not initialized. Add HF_TOKEN in Space secrets."}
|
| 249 |
|
| 250 |
try:
|
| 251 |
start = time.time()
|
| 252 |
|
|
|
|
| 253 |
messages = [{"role": "user", "content": prompt}]
|
|
|
|
| 254 |
response = hf_client.chat_completion(
|
| 255 |
messages=messages,
|
| 256 |
model=HF_MODEL,
|
|
|
|
| 258 |
)
|
| 259 |
|
| 260 |
latency = (time.time() - start) * 1000
|
|
|
|
| 261 |
output = response.choices[0].message.content
|
| 262 |
|
|
|
|
| 263 |
prompt_tokens = len(prompt) // 4
|
| 264 |
completion_tokens = len(output) // 4
|
| 265 |
|
| 266 |
TOTAL_REQUESTS += 1
|
| 267 |
TOTAL_TOKENS += completion_tokens
|
| 268 |
+
LAST_INFERENCE_LATENCY = latency
|
| 269 |
|
| 270 |
return {
|
| 271 |
"success": True,
|
|
|
|
| 275 |
"completion_tokens": completion_tokens,
|
| 276 |
}
|
| 277 |
except Exception as e:
|
| 278 |
+
return {"success": False, "error": str(e)}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 279 |
|
| 280 |
|
| 281 |
+
def send_vllm_inference(prompt: str, max_tokens: int = 100) -> Dict:
|
| 282 |
+
"""Send inference via vLLM."""
|
| 283 |
+
global TOTAL_REQUESTS, TOTAL_TOKENS, LAST_INFERENCE_LATENCY
|
| 284 |
|
| 285 |
try:
|
| 286 |
start = time.time()
|
|
|
|
| 303 |
|
| 304 |
TOTAL_REQUESTS += 1
|
| 305 |
TOTAL_TOKENS += usage.get("completion_tokens", 0)
|
| 306 |
+
LAST_INFERENCE_LATENCY = latency
|
| 307 |
|
| 308 |
return {
|
| 309 |
"success": True,
|
|
|
|
| 317 |
return {"success": False, "error": "Unknown error"}
|
| 318 |
|
| 319 |
|
| 320 |
+
def run_inference(prompt: str, max_tokens: int) -> tuple:
|
| 321 |
+
"""Run inference and return results."""
|
| 322 |
+
if not prompt.strip():
|
| 323 |
+
return "Please enter a prompt", "", 0, 0, 0
|
|
|
|
|
|
|
| 324 |
|
| 325 |
if IS_HF_SPACE:
|
| 326 |
+
result = send_hf_inference(prompt, int(max_tokens))
|
| 327 |
+
else:
|
| 328 |
+
result = send_vllm_inference(prompt, int(max_tokens))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 329 |
|
| 330 |
+
if result["success"]:
|
| 331 |
return (
|
| 332 |
+
"Success",
|
| 333 |
+
result["output"],
|
| 334 |
+
round(result["latency_ms"], 1),
|
| 335 |
+
result["prompt_tokens"],
|
| 336 |
+
result["completion_tokens"],
|
|
|
|
|
|
|
|
|
|
|
|
|
| 337 |
)
|
| 338 |
+
return (f"Error: {result.get('error', 'Unknown')}", "", 0, 0, 0)
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
# =============================================================================
|
| 342 |
+
# Dashboard Refresh Functions
|
| 343 |
+
# =============================================================================
|
| 344 |
+
|
| 345 |
+
def refresh_gpu_panel():
|
| 346 |
+
"""Refresh GPU panel data."""
|
| 347 |
+
stats = get_gpu_stats()
|
| 348 |
+
|
| 349 |
+
# Build GPU table
|
| 350 |
+
gpu_data = []
|
| 351 |
+
for s in stats:
|
| 352 |
+
gpu_data.append({
|
| 353 |
+
"GPU": f"GPU {s.gpu_id}",
|
| 354 |
+
"Name": s.name[:25],
|
| 355 |
+
"Memory": f"{s.memory_used_gb:.1f} / {s.memory_total_gb:.0f} GB",
|
| 356 |
+
"Mem %": f"{s.memory_percent:.1f}%",
|
| 357 |
+
"Util %": f"{s.utilization:.0f}%",
|
| 358 |
+
"Temp": f"{s.temperature}ยฐC",
|
| 359 |
+
"Power": f"{s.power_watts:.0f}W",
|
| 360 |
+
"TP Rank": str(s.tp_rank),
|
| 361 |
+
})
|
| 362 |
|
| 363 |
+
gpu_df = pd.DataFrame(gpu_data)
|
|
|
|
| 364 |
|
| 365 |
+
# Calculate totals
|
| 366 |
+
total_mem_used = sum(s.memory_used_gb for s in stats)
|
| 367 |
+
total_mem = sum(s.memory_total_gb for s in stats)
|
| 368 |
+
avg_util = sum(s.utilization for s in stats) / len(stats) if stats else 0
|
| 369 |
+
avg_temp = sum(s.temperature for s in stats) / len(stats) if stats else 0
|
| 370 |
+
total_power = sum(s.power_watts for s in stats)
|
|
|
|
| 371 |
|
| 372 |
+
# Update history
|
| 373 |
+
now = datetime.now().strftime("%H:%M:%S")
|
| 374 |
+
METRICS_HISTORY["timestamps"].append(now)
|
| 375 |
+
METRICS_HISTORY["gpu_memory"].append(round(total_mem_used, 1))
|
| 376 |
+
METRICS_HISTORY["gpu_util"].append(round(avg_util, 1))
|
| 377 |
|
| 378 |
+
# Keep last 30 points
|
| 379 |
+
for key in METRICS_HISTORY:
|
| 380 |
+
if len(METRICS_HISTORY[key]) > 30:
|
| 381 |
+
METRICS_HISTORY[key] = METRICS_HISTORY[key][-30:]
|
|
|
|
|
|
|
| 382 |
|
| 383 |
+
# Memory history chart data
|
| 384 |
+
mem_df = pd.DataFrame({
|
| 385 |
+
"Time": METRICS_HISTORY["timestamps"],
|
| 386 |
+
"GPU Memory (GB)": METRICS_HISTORY["gpu_memory"],
|
| 387 |
+
})
|
| 388 |
|
| 389 |
+
return (
|
| 390 |
+
gpu_df,
|
| 391 |
+
f"{total_mem_used:.1f} / {total_mem:.0f} GB",
|
| 392 |
+
f"{avg_util:.1f}%",
|
| 393 |
+
f"{avg_temp:.0f}ยฐC",
|
| 394 |
+
f"{total_power:.0f}W",
|
| 395 |
+
mem_df,
|
| 396 |
+
)
|
| 397 |
|
|
|
|
|
|
|
|
|
|
| 398 |
|
| 399 |
+
def refresh_inference_panel():
|
| 400 |
+
"""Refresh inference metrics panel."""
|
| 401 |
+
if IS_HF_SPACE:
|
| 402 |
+
metrics = get_demo_inference_metrics()
|
| 403 |
+
status = "HF Inference API (Demo Metrics)"
|
| 404 |
+
model = HF_MODEL
|
| 405 |
+
elif check_vllm_connection():
|
| 406 |
+
vllm_metrics = get_vllm_metrics()
|
| 407 |
+
if vllm_metrics:
|
| 408 |
+
elapsed = time.time() - START_TIME
|
| 409 |
+
gen_tokens = vllm_metrics.get("vllm:generation_tokens_total", 0)
|
| 410 |
+
metrics = {
|
| 411 |
+
"tokens_per_sec": round(gen_tokens / elapsed, 1) if elapsed > 0 else 0,
|
| 412 |
+
"batch_size": int(vllm_metrics.get("vllm:num_requests_running", 0)),
|
| 413 |
+
"kv_cache_percent": round(vllm_metrics.get("vllm:gpu_cache_usage_perc", 0) * 100, 1),
|
| 414 |
+
"running_requests": int(vllm_metrics.get("vllm:num_requests_running", 0)),
|
| 415 |
+
"waiting_requests": int(vllm_metrics.get("vllm:num_requests_waiting", 0)),
|
| 416 |
+
"ttft_ms": 0,
|
| 417 |
+
"tpot_ms": 0,
|
| 418 |
+
"prompt_tokens": int(vllm_metrics.get("vllm:prompt_tokens_total", 0)),
|
| 419 |
+
"generation_tokens": int(gen_tokens),
|
| 420 |
+
}
|
| 421 |
+
status = "Connected to vLLM"
|
| 422 |
+
model = "vLLM Model"
|
| 423 |
+
else:
|
| 424 |
+
metrics = get_demo_inference_metrics()
|
| 425 |
+
status = "Connected (no metrics)"
|
| 426 |
+
model = "Unknown"
|
| 427 |
+
else:
|
| 428 |
+
metrics = get_demo_inference_metrics()
|
| 429 |
+
status = "Disconnected - Using Demo Data"
|
| 430 |
+
model = "Demo Mode"
|
| 431 |
|
| 432 |
+
# Update history
|
| 433 |
+
METRICS_HISTORY["tokens_per_sec"].append(metrics["tokens_per_sec"])
|
| 434 |
+
METRICS_HISTORY["batch_size"].append(metrics["batch_size"])
|
| 435 |
+
METRICS_HISTORY["kv_cache"].append(metrics["kv_cache_percent"])
|
| 436 |
+
|
| 437 |
+
# Throughput chart
|
| 438 |
+
throughput_df = pd.DataFrame({
|
| 439 |
+
"Time": METRICS_HISTORY["timestamps"][-len(METRICS_HISTORY["tokens_per_sec"]):],
|
| 440 |
+
"Tokens/sec": METRICS_HISTORY["tokens_per_sec"],
|
| 441 |
+
})
|
|
|
|
| 442 |
|
| 443 |
return (
|
| 444 |
+
status,
|
| 445 |
model,
|
| 446 |
+
metrics["tokens_per_sec"],
|
| 447 |
+
metrics["batch_size"],
|
| 448 |
+
metrics["kv_cache_percent"],
|
| 449 |
+
metrics["running_requests"],
|
| 450 |
+
metrics["waiting_requests"],
|
| 451 |
+
metrics["ttft_ms"],
|
| 452 |
+
LAST_INFERENCE_LATENCY,
|
| 453 |
+
metrics["prompt_tokens"],
|
| 454 |
+
metrics["generation_tokens"],
|
| 455 |
+
throughput_df,
|
| 456 |
)
|
| 457 |
|
| 458 |
|
| 459 |
+
def refresh_system_panel():
|
| 460 |
+
"""Refresh system metrics panel."""
|
| 461 |
+
sys = get_system_metrics()
|
| 462 |
+
return (
|
| 463 |
+
f"{sys['cpu_percent']:.1f}%",
|
| 464 |
+
f"{sys['ram_used_gb']:.1f} / {sys['ram_total_gb']:.0f} GB",
|
| 465 |
+
f"{sys['ram_percent']:.1f}%",
|
| 466 |
+
)
|
| 467 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 468 |
|
| 469 |
+
# =============================================================================
|
| 470 |
+
# Build Gradio Dashboard
|
| 471 |
+
# =============================================================================
|
|
|
|
|
|
|
| 472 |
|
| 473 |
+
with gr.Blocks(title="LLM Inference Dashboard", theme=gr.themes.Soft()) as demo:
|
| 474 |
+
gr.Markdown("# ๐ LLM Inference Dashboard")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 475 |
|
| 476 |
+
mode_text = "HF Spaces (Demo Mode)" if IS_HF_SPACE else "Local Mode"
|
| 477 |
+
gr.Markdown(f"*Real-time GPU/Rank monitoring and inference metrics* | **Mode:** {mode_text}")
|
| 478 |
|
| 479 |
+
with gr.Tabs():
|
| 480 |
+
# =================================================================
|
| 481 |
+
# Tab 1: GPU / Rank Status
|
| 482 |
+
# =================================================================
|
| 483 |
+
with gr.Tab("๐ฎ GPU / Rank Status"):
|
| 484 |
+
gr.Markdown("### Per-GPU Metrics & Tensor Parallel Rank Mapping")
|
| 485 |
|
| 486 |
+
with gr.Row():
|
| 487 |
+
total_gpu_mem = gr.Textbox(label="Total GPU Memory", value="...", interactive=False)
|
| 488 |
+
avg_gpu_util = gr.Textbox(label="Avg GPU Util", value="...", interactive=False)
|
| 489 |
+
avg_gpu_temp = gr.Textbox(label="Avg Temperature", value="...", interactive=False)
|
| 490 |
+
total_power = gr.Textbox(label="Total Power", value="...", interactive=False)
|
| 491 |
+
|
| 492 |
+
gpu_table = gr.Dataframe(
|
| 493 |
+
headers=["GPU", "Name", "Memory", "Mem %", "Util %", "Temp", "Power", "TP Rank"],
|
| 494 |
+
label="GPU Status per Rank",
|
| 495 |
+
interactive=False,
|
| 496 |
+
)
|
| 497 |
|
| 498 |
+
gpu_mem_chart = gr.Dataframe(
|
| 499 |
+
label="GPU Memory History",
|
| 500 |
+
interactive=False,
|
| 501 |
+
)
|
| 502 |
|
| 503 |
+
gpu_refresh_btn = gr.Button("๐ Refresh GPU Stats", variant="primary")
|
| 504 |
+
gpu_refresh_btn.click(
|
| 505 |
+
fn=refresh_gpu_panel,
|
| 506 |
+
outputs=[gpu_table, total_gpu_mem, avg_gpu_util, avg_gpu_temp, total_power, gpu_mem_chart],
|
| 507 |
+
)
|
| 508 |
|
| 509 |
+
# =================================================================
|
| 510 |
+
# Tab 2: Inference Metrics
|
| 511 |
+
# =================================================================
|
| 512 |
+
with gr.Tab("๐ Inference Metrics"):
|
| 513 |
+
gr.Markdown("### Real-time Inference Performance")
|
| 514 |
|
| 515 |
with gr.Row():
|
| 516 |
+
inf_status = gr.Textbox(label="Status", value="...", interactive=False)
|
| 517 |
+
inf_model = gr.Textbox(label="Model", value="...", interactive=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 518 |
|
| 519 |
+
with gr.Row():
|
| 520 |
+
tokens_sec = gr.Number(label="Tokens/sec", value=0, interactive=False)
|
| 521 |
+
batch_size = gr.Number(label="Batch Size", value=0, interactive=False)
|
| 522 |
+
kv_cache = gr.Number(label="KV Cache %", value=0, interactive=False)
|
| 523 |
|
| 524 |
with gr.Row():
|
| 525 |
+
running_req = gr.Number(label="Running Requests", value=0, interactive=False)
|
| 526 |
+
waiting_req = gr.Number(label="Waiting Requests", value=0, interactive=False)
|
| 527 |
+
ttft = gr.Number(label="TTFT (ms)", value=0, interactive=False)
|
| 528 |
+
last_latency = gr.Number(label="Last Latency (ms)", value=0, interactive=False)
|
| 529 |
|
| 530 |
with gr.Row():
|
| 531 |
+
prompt_tokens = gr.Number(label="Total Prompt Tokens", value=0, interactive=False)
|
| 532 |
+
gen_tokens = gr.Number(label="Total Gen Tokens", value=0, interactive=False)
|
| 533 |
|
| 534 |
+
throughput_chart = gr.Dataframe(
|
| 535 |
+
label="Throughput History",
|
| 536 |
+
interactive=False,
|
| 537 |
+
)
|
| 538 |
|
| 539 |
+
inf_refresh_btn = gr.Button("๐ Refresh Inference Metrics", variant="primary")
|
| 540 |
+
inf_refresh_btn.click(
|
| 541 |
+
fn=refresh_inference_panel,
|
| 542 |
+
outputs=[inf_status, inf_model, tokens_sec, batch_size, kv_cache,
|
| 543 |
+
running_req, waiting_req, ttft, last_latency, prompt_tokens,
|
| 544 |
+
gen_tokens, throughput_chart],
|
| 545 |
)
|
| 546 |
|
| 547 |
+
# =================================================================
|
| 548 |
+
# Tab 3: System Metrics
|
| 549 |
+
# =================================================================
|
| 550 |
+
with gr.Tab("๐ป System Metrics"):
|
| 551 |
+
gr.Markdown("### Host System Resources")
|
| 552 |
+
|
| 553 |
+
with gr.Row():
|
| 554 |
+
cpu_usage = gr.Textbox(label="CPU Usage", value="...", interactive=False)
|
| 555 |
+
ram_usage = gr.Textbox(label="RAM Usage", value="...", interactive=False)
|
| 556 |
+
ram_percent = gr.Textbox(label="RAM %", value="...", interactive=False)
|
| 557 |
+
|
| 558 |
+
sys_refresh_btn = gr.Button("๐ Refresh System Metrics", variant="primary")
|
| 559 |
+
sys_refresh_btn.click(
|
| 560 |
+
fn=refresh_system_panel,
|
| 561 |
+
outputs=[cpu_usage, ram_usage, ram_percent],
|
| 562 |
+
)
|
| 563 |
+
|
| 564 |
+
# =================================================================
|
| 565 |
+
# Tab 4: Test Inference
|
| 566 |
+
# =================================================================
|
| 567 |
+
with gr.Tab("๐งช Test Inference"):
|
| 568 |
+
gr.Markdown("### Send Prompts to Model")
|
| 569 |
+
|
| 570 |
if IS_HF_SPACE:
|
| 571 |
+
gr.Markdown(f"*Using HuggingFace Inference API: `{HF_MODEL}`*")
|
|
|
|
|
|
|
|
|
|
| 572 |
|
| 573 |
with gr.Row():
|
| 574 |
+
prompt_input = gr.Textbox(
|
| 575 |
+
label="Prompt",
|
| 576 |
+
placeholder="Enter your prompt...",
|
| 577 |
+
lines=3,
|
| 578 |
+
value="Explain how GPU memory affects LLM inference performance.",
|
| 579 |
+
)
|
| 580 |
+
max_tokens_slider = gr.Slider(10, 500, value=100, label="Max Tokens")
|
| 581 |
+
|
| 582 |
+
send_btn = gr.Button("๐ Send Prompt", variant="primary")
|
| 583 |
|
| 584 |
with gr.Row():
|
| 585 |
+
inf_result_status = gr.Textbox(label="Status", interactive=False)
|
| 586 |
+
inf_result_latency = gr.Number(label="Latency (ms)", interactive=False)
|
| 587 |
|
| 588 |
+
with gr.Row():
|
| 589 |
+
inf_prompt_tokens = gr.Number(label="Prompt Tokens", interactive=False)
|
| 590 |
+
inf_comp_tokens = gr.Number(label="Completion Tokens", interactive=False)
|
| 591 |
+
|
| 592 |
+
response_output = gr.Textbox(label="Response", lines=10, interactive=False)
|
| 593 |
+
|
| 594 |
+
send_btn.click(
|
| 595 |
+
fn=run_inference,
|
| 596 |
+
inputs=[prompt_input, max_tokens_slider],
|
| 597 |
+
outputs=[inf_result_status, response_output, inf_result_latency,
|
| 598 |
+
inf_prompt_tokens, inf_comp_tokens],
|
| 599 |
)
|
| 600 |
|
| 601 |
+
# =================================================================
|
| 602 |
+
# Tab 5: Setup Guide
|
| 603 |
+
# =================================================================
|
| 604 |
+
with gr.Tab("๐ Setup Guide"):
|
| 605 |
if IS_HF_SPACE:
|
| 606 |
gr.Markdown("""
|
| 607 |
### Running on HuggingFace Spaces
|
| 608 |
|
| 609 |
+
**Current Mode:** Demo GPU data + HuggingFace Inference API
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 610 |
|
| 611 |
+
**To enable inference:**
|
| 612 |
+
1. Go to Space Settings โ Variables and secrets
|
| 613 |
+
2. Add secret: `HF_TOKEN` = your token from https://huggingface.co/settings/tokens
|
| 614 |
+
3. Restart the Space
|
| 615 |
|
| 616 |
---
|
| 617 |
|
| 618 |
+
### For Real GPU Metrics (Local Setup)
|
| 619 |
|
|
|
|
|
|
|
|
|
|
| 620 |
```bash
|
| 621 |
+
# Clone the repo
|
| 622 |
git clone https://huggingface.co/spaces/jkottu/llm-inference-dashboard
|
| 623 |
cd llm-inference-dashboard
|
| 624 |
+
|
| 625 |
+
# Install dependencies
|
| 626 |
pip install -r requirements.txt
|
|
|
|
|
|
|
| 627 |
|
| 628 |
+
# Start vLLM (pick a model based on your GPU)
|
|
|
|
| 629 |
python -m vllm.entrypoints.openai.api_server \\
|
| 630 |
--model Qwen/Qwen2.5-0.5B-Instruct \\
|
| 631 |
+
--tensor-parallel-size 1 \\
|
| 632 |
--port 8000
|
| 633 |
+
|
| 634 |
+
# Run dashboard
|
| 635 |
+
python app.py
|
| 636 |
```
|
| 637 |
|
| 638 |
+
**For Multi-GPU (Tensor Parallel):**
|
| 639 |
```bash
|
| 640 |
+
python -m vllm.entrypoints.openai.api_server \\
|
| 641 |
+
--model meta-llama/Llama-2-7b-chat-hf \\
|
| 642 |
+
--tensor-parallel-size 4 \\
|
| 643 |
+
--port 8000
|
| 644 |
```
|
| 645 |
""")
|
| 646 |
else:
|
| 647 |
gr.Markdown("""
|
| 648 |
+
### Local Setup Guide
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 649 |
|
| 650 |
+
**Step 1: Start vLLM Server**
|
| 651 |
|
|
|
|
| 652 |
```bash
|
| 653 |
+
# Single GPU (small model)
|
| 654 |
python -m vllm.entrypoints.openai.api_server \\
|
| 655 |
--model Qwen/Qwen2.5-0.5B-Instruct \\
|
| 656 |
--port 8000
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 657 |
|
| 658 |
+
# Multi-GPU with Tensor Parallelism
|
|
|
|
| 659 |
python -m vllm.entrypoints.openai.api_server \\
|
| 660 |
+
--model meta-llama/Llama-2-13b-chat-hf \\
|
| 661 |
+
--tensor-parallel-size 4 \\
|
| 662 |
--port 8000
|
| 663 |
```
|
| 664 |
|
| 665 |
+
**Step 2: Run Dashboard**
|
| 666 |
```bash
|
| 667 |
python app.py
|
| 668 |
```
|
| 669 |
|
| 670 |
+
**Step 3: Monitor**
|
| 671 |
+
- GPU tab shows per-rank memory, utilization, temperature
|
| 672 |
+
- Inference tab shows throughput, batch size, KV cache
|
| 673 |
+
- System tab shows CPU/RAM usage
|
|
|
|
|
|
|
|
|
|
|
|
|
| 674 |
""")
|
| 675 |
|
| 676 |
+
# =================================================================
|
| 677 |
+
# Auto-refresh timer
|
| 678 |
+
# =================================================================
|
| 679 |
+
timer = gr.Timer(3)
|
| 680 |
+
|
| 681 |
+
# GPU panel refresh
|
| 682 |
+
timer.tick(
|
| 683 |
+
fn=refresh_gpu_panel,
|
| 684 |
+
outputs=[gpu_table, total_gpu_mem, avg_gpu_util, avg_gpu_temp, total_power, gpu_mem_chart],
|
| 685 |
)
|
| 686 |
|
| 687 |
+
# Inference panel refresh
|
|
|
|
| 688 |
timer.tick(
|
| 689 |
+
fn=refresh_inference_panel,
|
| 690 |
+
outputs=[inf_status, inf_model, tokens_sec, batch_size, kv_cache,
|
| 691 |
+
running_req, waiting_req, ttft, last_latency, prompt_tokens,
|
| 692 |
+
gen_tokens, throughput_chart],
|
|
|
|
|
|
|
| 693 |
)
|
| 694 |
|
| 695 |
+
# System panel refresh
|
| 696 |
+
timer.tick(
|
| 697 |
+
fn=refresh_system_panel,
|
| 698 |
+
outputs=[cpu_usage, ram_usage, ram_percent],
|
| 699 |
+
)
|
| 700 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 701 |
|
| 702 |
+
if __name__ == "__main__":
|
| 703 |
+
logger.info(f"Starting dashboard - Mode: {'HF Spaces' if IS_HF_SPACE else 'Local'}")
|
| 704 |
+
logger.info(f"GPUs detected: {GPU_COUNT if HAS_NVML else 'None (demo mode)'}")
|
| 705 |
+
demo.launch(server_name="0.0.0.0", server_port=7860)
|
requirements.txt
CHANGED
|
@@ -1,3 +1,5 @@
|
|
| 1 |
gradio>=5.0.0
|
| 2 |
pandas>=2.0.0
|
| 3 |
huggingface_hub>=0.20.0
|
|
|
|
|
|
|
|
|
| 1 |
gradio>=5.0.0
|
| 2 |
pandas>=2.0.0
|
| 3 |
huggingface_hub>=0.20.0
|
| 4 |
+
psutil>=5.9.0
|
| 5 |
+
requests>=2.28.0
|