baseball-engine / docs /GPU_API_DEPLOYMENT.md
github-actions[bot]
Automated Deploy: 3ea2037ab7d55d5b498f7e2ea0336818fc24f725
fe40b87
|
Raw History Blame Contribute Delete
11.9 kB

Deploy the GPU measurement API

This service accepts batting recordings and returns body/foot points and estimated swing measurements for the separate coach agent. The API always uses CUDA for pose/person inference; measurement arithmetic uses the resulting 2D points. Lightweight RTMW3D is optional per request. SAM can be added in a separate worker/image; temporal fitting, OpenSim, bat 3D and coaching do not run. The Colab notebook remains available separately.

The four-field Load and timing output is available at GET /v1/analyses/{job_id}/load-timing. Use the 2d backend and POST /v1/load-timing/analyses for settings validation before queuing. The image includes separate BaseballCV bat/ball ONNX models; no SAM reconstruction runs on this route. New jobs save checksummed default 3.0 and opt-in 3.1 evidence payloads; older jobs need resubmission. Physical misses and timing correction require calibrated synchronized views. See LOAD_TIMING_API.md and current validation limits.

Automatic rep/event detection is a versioned 2D heuristic, and all computed measurements remain est pending independent validation. Weak events and unsupported angles are withheld. See API_FOR_COACH.md for the handoff and BATTING_2D_MEASUREMENTS.md for definitions and limitations.

GPU server with Docker

Use a Linux x86-64 NVIDIA GPU server. A T4 is the GPU already used successfully for this project's 2D models in Colab. Have sufficient RAM and disk for the three model files, their temporary downloads, uploads, and results; start with 8 GB host RAM and 20 GB free disk, then size storage for your workload. These are deployment starting points, not a tested throughput guarantee.

Install Docker with Compose and the NVIDIA Container Toolkit. Configure the Docker runtime for GPU access as described there. The host driver must support the CUDA libraries used by ONNX Runtime 1.26.0; see ONNX CUDA requirements. The final image installs the GPU runtime and NVIDIA CUDA/cuDNN pip extras without PyTorch or SAM. A separate build stage installs CPU PyTorch/Ultralytics to export the pinned bat/ball checkpoints.

Clone your repository, enter its directory, then create your private configuration:

cp .env.example .env

Generate a random API key:

python3 -c 'import secrets; print(secrets.token_urlsafe(32))'

Put that value after BASEBALL_API_KEY= in .env. Keep the key in your friend's backend configuration. The real .env is ignored by Git and excluded from the Docker build context.

Build and start:

docker compose up -d --build
curl --fail http://127.0.0.1:8000/readyz

The image build downloads the RTMW-x, HumanArt person and optional RTMW3D models plus pinned BaseballCV bat/ball checkpoints and verifies their SHA-256 values. It records the hash of each exported ONNX model. A build fails if a required download or checksum fails. Startup runs actual pose, person, bat and ball inference on CUDA; /readyz returns 503 until it passes and reports bat_ball_tracking_ready. A missing GPU or broken CUDA setup prevents video jobs from being accepted. This confirms GPU execution, not measurement accuracy. Existing body-only installations may still accept the old upload route, but the dedicated timing route returns 503 until tracking passes preflight.

RTMLib is installed with --no-deps for its preprocessing and decoder helpers. Its metadata asks for CPU ONNX and two GUI OpenCV distributions; this service uses GPU ONNX and headless OpenCV. Consequently pip check reports those distribution mismatches. The image checks the actual helper imports, and startup checks actual model execution.

The default Compose setup binds port 8000 to localhost. For internet access, use your existing HTTPS proxy or the supplied Caddy configuration:

  1. Point a hostname at your server and allow inbound ports 80 and 443.
  2. Set BASEBALL_DOMAIN=your-api-hostname in .env.
  3. Start the HTTPS overlay:
docker compose -f compose.yaml -f deploy/compose.https.yaml up -d --build

Your API and interactive documentation are then at https://your-api-hostname and https://your-api-hostname/docs. Caddy handles certificates; its reverse proxy forwards to the API. Its fixed 537,919,488-byte (513 MiB) request limit covers the default upload size plus multipart overhead; adjust it if you raise the API's upload limit.

Other GPU hosting services

Build and publish the same Linux x86-64 image in your private container registry, then deploy it on a GPU container host. Give the container NVIDIA GPU access, expose HTTP port 8000 behind the platform's HTTPS endpoint, and set BASEBALL_API_KEY as a platform secret.

Mount a persistent writable volume at /data. The image runs as UID/GID 1000, matching the user Hugging Face Docker Spaces run containers as, so a bind-mounted directory must be writable by that user. /tmp must be writable for multipart uploads and ONNX profiling. Leave the image command in place: it starts one Uvicorn process and one GPU queue. A managed GPU pod can run this long-lived service; this image is not a platform-specific serverless handler.

For a plain Docker host without Compose:

docker build --platform linux/amd64 -t baseball-engine-api:local .
docker run -d --name baseball-api --gpus all --restart unless-stopped \
  --env-file .env -p 127.0.0.1:8000:8000 \
  -v baseball-data:/data baseball-engine-api:local

Queue, limits, and retention

One recording runs at a time. The default limit is eight active jobs, including queued jobs and uploads. Requests beyond that return 429; clients can retry after 30 seconds. Only two uploads are parsed concurrently. Processing is in an isolated subprocess, so cancelling or timing out a job releases its GPU allocations.

Defaults are 512 MB per recording, 120 playback seconds, 7,200 decoded frames, and 8,294,400 pixels per frame. Slow-motion recordings can hit the frame limit before the duration limit. Jobs time out after 30 minutes. .env.example lists configurable limits; BASEBALL_MAX_PIXELS and BASEBALL_DISK_RESERVE_MB are also supported environment variables for direct/container deployment. The Compose setup keeps the pixel limit at its default.

Uploads are removed after a completed, failed, or cancelled job. Queued jobs retain their uploads. On a normal restart, an interrupted job returns to the queue and reuses verified chunks. Incomplete uploads are discarded. Job records and remaining artifacts expire 24 hours after a terminal status; cleanup runs while the healthy service is active. DELETE /v1/analyses/{job_id} cancels processing and removes the job directory once its subprocess stops.

Keep the persistent volume when updating:

docker compose up -d --build

Use one Uvicorn worker and one service replica per data directory. A file lock prevents a second service from using the same queue. Scaling across several machines needs separate volumes and an external job router; that is outside this deployment.

Diagnose startup or a failed job

Analysis jobs print concise progress to the server terminal (Docker/container stdout): job ID, stage changes, progress counts when available, a heartbeat every 15 seconds during long steps, and final status with elapsed time. Motion jobs also summarize the up and pitcher directions, or the reason they are unknown. For rejected body-direction estimates, pitcher_checks lists candidate counts and the three most common failed checks. Up to two pitcher_check lines show source frame numbers and numeric evidence when available. The generic no_clear_setup_and_swing means different candidates failed different checks; the detailed rows are already saved in coordinates.pitcher_estimation.candidates in the motion result JSON, including results created before this logging change. Accepted body estimates print one pitcher_evidence line with the selected setup, movement-peak and extension frame indices, plus the setup's angular spread. Full model output stays in each job's worker.log; payloads and uploads are not dumped to the terminal. Use docker compose logs -f api to follow live progress.

docker compose logs --tail=100 api
docker compose exec api cat /data/gpu-preflight.log

For a failed recording, inspect /data/jobs/JOB_ID/worker.log inside the container. /v1/analyses/JOB_ID returns the public error code without exposing server paths or a traceback. Jobs return progress for decoding, 2D pose inference, measurement calculation and completion. Frame totals become known after decoding. stage_progress applies to the current stage; it is not a promised remaining-time estimate.

Errors include invalid_video_or_capture, inference_failed, job_timeout, and worker_error. Check recording format, frame/duration limits, rotation, timing evidence, and server logs. There is no automatic CPU fallback.

Validation before calling the deployment live

Automated tests cover the HTTP/job lifecycle, authorization, size limits, cancellation, timeout, retention, restart recovery, output mapping, null points, and physical timing. CPU inference can exercise the data path locally. The deployment still needs its real CUDA startup check and one real uploaded recording to finish on the target GPU.

The service returns validation: reference_validation_pending and estimated_only: true. Pose scores and measurement estimates have not been calibrated against baseball reference labels. Missing events and null metrics carry reasons. The separate coach payload is checksummed and excludes pose data; jobs completed with the older pose-only image have no coach payload and must be resubmitted after updating the image.

Optional SAM on Docker

The standard image already supports measurement_backend: "rtmw3d". To offer SAM as well, obtain the normally approved SAM snapshot (model.ckpt, model_config.yaml, assets/mhr_model.pt) on your server and set BASEBALL_SAM_ASSET_DIRECTORY to that directory. Keep it outside Git. Credentials are not passed into Docker builds.

Build the base image first, then the SAM overlay:

docker compose build api
docker compose -f compose.yaml -f deploy/compose.sam.yaml build api

Register the installed runtime and mounted assets once. This records checksums without loading the model:

docker compose -f compose.yaml -f deploy/compose.sam.yaml run --rm --no-deps --entrypoint python api \
  -m tools.register_sam_api_worker \
  --worker-python /opt/sam-runtime/bin/python --sam-repo /opt/sam-source \
  --sam-checkpoint /opt/sam-assets/model.ckpt --sam-config /opt/sam-assets/model_config.yaml \
  --mhr-path /opt/sam-assets/assets/mhr_model.pt --output /data/sam-api-worker.json
docker compose -f compose.yaml -f deploy/compose.sam.yaml up -d api

The overlay mounts assets read-only and reads /data/sam-api-worker.json. SAM is loaded only when a request selects sam3d. Lightweight/2D jobs do not load PyTorch. The optional image needs more build time, RAM, disk and GPU memory; its target-GPU inference still needs testing. No OpenSim or temporal fitting is installed/run by this path.

/v1/capabilities lists configured measurement backends. /readyz verifies the required 2D CUDA worker; optional 3D CUDA execution is verified during the selected inference. A failed optional backend returns partial measurements with a reason, not silent CPU/model fallback. See NINE_MEASUREMENTS.md for selection and experimental accuracy status.