Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

feat: gpu stats in footer (#4777)

Myles Scolnick86656d9c6858
diff --git a/frontend/src/components/debug/indicator.tsx b/frontend/src/components/debug/indicator.tsx
index 05f816a399..a5623b1d6f 100644
--- a/frontend/src/components/debug/indicator.tsx
+++ b/frontend/src/components/debug/indicator.tsx
@@ -5,7 +5,7 @@ export const TailwindIndicator = () => {
}
return (
- <div className="fixed bottom-2 right-[300px] z-50 flex size-5 items-center justify-center rounded-lg bg-gray-800 py-3 px-4 font-mono text-xs text-white">
+ <div className="fixed bottom-10 right-0 z-50 flex items-center justify-center bg-gray-800 py-[2px] px-1 font-mono text-[10px] text-white font-semibold">
<div className="block sm:hidden">xs</div>
<div className="hidden sm:block md:hidden lg:hidden xl:hidden 2xl:hidden">
sm
diff --git a/frontend/src/components/editor/chrome/wrapper/machine-stats.tsx b/frontend/src/components/editor/chrome/wrapper/machine-stats.tsx
index 16c3a48172..c2765f1598 100644
--- a/frontend/src/components/editor/chrome/wrapper/machine-stats.tsx
+++ b/frontend/src/components/editor/chrome/wrapper/machine-stats.tsx
@@ -14,11 +14,13 @@ import {
CheckCircle2Icon,
CpuIcon,
MemoryStickIcon,
+ MicrochipIcon,
PowerOffIcon,
} from "lucide-react";
import type React from "react";
import { useState } from "react";
import { AIStatusIcon, CopilotStatusIcon } from "./copilot-status";
+import { cn } from "@/utils/cn";
export const MachineStats: React.FC = (props) => {
const [nonce, setNonce] = useState(0);
@@ -41,6 +43,7 @@ export const MachineStats: React.FC = (props) => {
return (
<div className="flex gap-2 items-center">
+ {data?.gpu && data.gpu.length > 0 && <GPUBar gpus={data.gpu} />}
{data && (
<MemoryUsageBar
memory={data.memory}
@@ -110,7 +113,7 @@ const MemoryUsageBar: React.FC<{
>
<div className="flex items-center gap-1">
<MemoryStickIcon className="w-4 h-4" />
- <Bar percent={roundedPercent} />
+ <Bar percent={roundedPercent} colorClassName="bg-primary" />
</div>
</Tooltip>
);
@@ -130,16 +133,63 @@ const CPUBar: React.FC<{ cpu: UsageResponse["cpu"] }> = ({ cpu }) => {
>
<div className="flex items-center gap-1">
<CpuIcon className="w-4 h-4" />
- <Bar percent={roundedPercent} />
+ <Bar percent={roundedPercent} colorClassName="bg-primary" />
</div>
</Tooltip>
);
};
-const Bar: React.FC<{ percent: number }> = ({ percent }) => {
+interface GPU {
+ index: number;
+ name: string;
+ memory: {
+ used: number;
+ total: number;
+ percent: number;
+ };
+}
+
+const GPUBar: React.FC<{ gpus: GPU[] }> = ({ gpus }) => {
+ const avgPercent = Math.round(
+ gpus.reduce((sum: number, gpu: GPU) => sum + gpu.memory.percent, 0) /
+ gpus.length,
+ );
+
+ return (
+ <Tooltip
+ delayDuration={200}
+ content={
+ <div className="flex flex-col gap-1">
+ {gpus.map((gpu) => (
+ <span key={gpu.index}>
+ <b>
+ GPU {gpu.index} ({gpu.name}):
+ </b>{" "}
+ {asGBorMB(gpu.memory.used)} / {asGBorMB(gpu.memory.total)} GB (
+ {Math.round(gpu.memory.percent)}%)
+ </span>
+ ))}
+ </div>
+ }
+ >
+ <div className="flex items-center gap-1">
+ <MicrochipIcon className="w-4 h-4" />
+ <Bar percent={avgPercent} colorClassName="bg-[var(--grass-9)]" />
+ </div>
+ </Tooltip>
+ );
+};
+
+const Bar: React.FC<{ percent: number; colorClassName?: string }> = ({
+ percent,
+ colorClassName,
+}) => {
return (
<div className="h-3 w-20 bg-[var(--slate-4)] rounded-lg overflow-hidden border">
- <div className="h-full bg-primary" style={{ width: `${percent}%` }} />
+ <div
+ className={cn("h-full bg-primary", colorClassName)}
+ style={{ width: `${percent}%` }}
+ />
</div>
);
};
diff --git a/marimo/_server/api/endpoints/health.py b/marimo/_server/api/endpoints/health.py
index 712876d2c7..de6353fb21 100644
--- a/marimo/_server/api/endpoints/health.py
+++ b/marimo/_server/api/endpoints/health.py
@@ -1,13 +1,15 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
+from functools import lru_cache
from multiprocessing import Process
-from typing import TYPE_CHECKING, Optional
+from typing import TYPE_CHECKING, Any, Optional
from starlette.authentication import requires
from starlette.responses import JSONResponse, PlainTextResponse
from marimo import __version__, _loggers
+from marimo._dependencies.dependencies import DependencyManager
from marimo._server.api.deps import AppState
from marimo._server.router import APIRouter
from marimo._utils.health import (
@@ -153,11 +155,42 @@ async def usage(request: Request) -> JSONResponse:
type: number
required:
- percent
+ gpu:
+ type: array
+ items:
+ type: object
+ properties:
+ index:
+ type: integer
+ name:
+ type: string
+ memory:
+ type: object
+ properties:
+ total:
+ type: integer
+ used:
+ type: integer
+ free:
+ type: integer
+ percent:
+ type: number
+ required:
+ - total
+ - used
+ - free
+ - percent
+ required:
+ - index
+ - memory
+ - name
required:
- memory
- cpu
""" # noqa: E501
+ import subprocess
+
import psutil
memory = psutil.virtual_memory()
@@ -188,6 +221,44 @@ async def usage(request: Request) -> JSONResponse:
except psutil.NoSuchProcess:
pass
+ # GPU stats
+ gpu_stats: list[dict[str, Any]] = []
+ if _is_gpu_available():
+ try:
+ result = subprocess.run( # noqa: ASYNC221
+ [
+ "nvidia-smi",
+ "--query-gpu=index,name,memory.total,memory.used,memory.free",
+ "--format=csv,noheader,nounits",
+ ],
+ capture_output=True,
+ text=True,
+ check=True,
+ )
+ for line in result.stdout.strip().split("\n"):
+ index_str, name, total_str, used_str, free_str = line.split(
+ ", "
+ )
+ total = int(total_str) * 1024 * 1024 # Convert MB to bytes
+ used = int(used_str) * 1024 * 1024
+ free = int(free_str) * 1024 * 1024
+ gpu_stats.append(
+ {
+ "index": int(index_str),
+ "name": name.strip(),
+ "memory": {
+ "total": total,
+ "used": used,
+ "free": free,
+ "percent": (used / total) * 100
+ if total > 0
+ else 0,
+ },
+ }
+ )
+ except (subprocess.SubprocessError, FileNotFoundError) as e:
+ LOGGER.warning("Failed to extract GPU stats: %s", e)
+
return JSONResponse(
{
# computer memory
@@ -209,6 +280,7 @@ async def usage(request: Request) -> JSONResponse:
"cpu": {
"percent": cpu,
},
+ "gpu": gpu_stats,
}
)
@@ -231,3 +303,8 @@ async def connections(request: Request) -> JSONResponse:
return JSONResponse(
{"active": app_state.session_manager.get_active_connection_count()}
)
+
+
+@lru_cache(maxsize=1)
+def _is_gpu_available() -> bool:
+ return DependencyManager.which("nvidia-smi")
diff --git a/openapi/api.yaml b/openapi/api.yaml
index 1fd9e89f4b..3d84e30b14 100644
--- a/openapi/api.yaml
+++ b/openapi/api.yaml
@@ -2502,7 +2502,7 @@ components:
type: object
info:
title: marimo API
- version: 0.13.2
+ version: 0.13.3
openapi: 3.1.0
paths:
/@file/{filename_and_length}:
@@ -3293,6 +3293,35 @@ paths:
required:
- percent
type: object
+ gpu:
+ items:
+ properties:
+ index:
+ type: integer
+ memory:
+ properties:
+ free:
+ type: integer
+ percent:
+ type: number
+ total:
+ type: integer
+ used:
+ type: integer
+ required:
+ - total
+ - used
+ - free
+ - percent
+ type: object
+ name:
+ type: string
+ required:
+ - index
+ - memory
+ - name
+ type: object
+ type: array
kernel:
properties:
memory:
diff --git a/openapi/src/api.ts b/openapi/src/api.ts
index 405fb3341b..b5b0e72983 100644
--- a/openapi/src/api.ts
+++ b/openapi/src/api.ts
@@ -2217,6 +2217,16 @@ export interface paths {
cpu: {
percent: number;
};
+ gpu?: {
+ index: number;
+ memory: {
+ free: number;
+ percent: number;
+ total: number;
+ used: number;
+ };
+ name: string;
+ }[];
kernel?: {
memory?: number;
};
diff --git a/tests/_server/api/endpoints/test_health.py b/tests/_server/api/endpoints/test_health.py
index 7469ca0c3c..4a368297bf 100644
--- a/tests/_server/api/endpoints/test_health.py
+++ b/tests/_server/api/endpoints/test_health.py
@@ -68,6 +68,9 @@ def test_memory(client: TestClient) -> None:
computer = response.json()["kernel"]
assert computer["memory"] is None
+ gpu = response.json()["gpu"]
+ assert len(gpu) == 0
+
def test_connections(client: TestClient) -> None:
response = client.get("/api/status/connections")