Skip to content

feat(gpu): auto-detect CUDA by default via tri-state gpu_mode (v4.8.0 Fase 2) - #149

Merged
lyonzin merged 7 commits into
masterfrom
feat/v4.8.0-fase-2-gpu-auto
Aug 6, 2026
Merged

lyonzin merged 7 commits into
masterfrom
feat/v4.8.0-fase-2-gpu-auto

Conversation

@lyonzin

@lyonzin lyonzin commented Aug 6, 2026 •

Copy link
Copy Markdown
Owner

Summary

Fase 2 of the v4.8.0 roadmap — GPU auto-detect default.

Changes the default of models.embedding.gpu from false (opt-in CUDA) to "auto" (probe + decide). Users with a working GPU stack now get CUDA acceleration without touching config; users without one get a silent CPU fallback plus a diagnostic banner that says exactly what is missing.

Independent of PR #148 (Fase 1 embedding profile) — no shared code paths beyond both touching the Config dataclass in different regions. Trivial rebase expected.

What changes

File Change
mcp_server/config.py New tri-state gpu_mode: str field ("auto" | "true" | "false", default "auto"). Legacy gpu_acceleration: bool derived in __post_init__. Legacy YAML gpu: true/gpu: false normalized to the string form. Invalid values log WARN and fall back to "auto".
mcp_server/server.py _load_model now routes through new _route_load per gpu_mode. Extracted _load_with_providers helper. All three modes (false / auto / true) have explicit paths with clear fallback semantics.
mcp_server/server.py _print_gpu_banner signature changed to (status: Optional[GPUStatus], mode: str) and now runs on every startup path — including CPU-only and both fallback paths. Includes probe fallback_reason and a pip install hint on CPU paths.
config.example.yaml gpu: block rewritten with tri-state docs, legacy bool note, full pip dependency chain (onnxruntime-gpu CUDA-12 variant + nine nvidia-*-cu12 packages), driver requirement, verify-readiness one-liner, cross-link to docs/gpu-setup.md.
docs/gpu-setup.md new Full setup guide: TL;DR, mode table, auto-detect flow (four checks in order), pip chain, banner examples, six troubleshooting scenarios (cublasLt64 missing / nvidia-smi off PATH / driver too old / WSL2 / Docker / ORT silent fallback), performance table (17x speedup measured).
tests/test_gpu_auto.py new 13 AAA tests split into TestGpuModeNormalization (8) and TestLoadModelRouting (5). Mocks verify_gpu_readiness and TextEmbedding — runs in <2s on CI without a real GPU.
README.md Unreleased CHANGELOG entry at top of the section.

Backwards compatibility

  • YAML gpu: false (bool) — normalized to "false" string. Probe is skipped (zero startup overhead). Semantics preserved: CPU-only load.
  • YAML gpu: true (bool) — normalized to "true" string. Same behavior as before: force CUDA attempt, fall back to CPU on load failure.
  • New default gpu: "auto" — users who upgrade without touching config will start probing CUDA on startup. Overhead when GPU is absent: ~500ms–2s cold start (probe rejects quickly on the first failing check). Runtime perf unchanged.
  • MCP tool signatures — unchanged. tests/test_backwards_compat.py still green.
  • Callers of config.gpu_acceleration: bool — still works. Field is derived from gpu_mode (True when mode is "true" or "auto").

Perf note

verify_gpu_readiness() adds a 500ms–2s cold-start cost in the auto path on machines without a GPU (each of the four checks short-circuits fast on failure — usually the provider check trips first). Runtime latency is untouched. If Pillar 5 (perf gate) lights up on the cold-start metric, apply the skip-perf-gate label with justification: the trade-off (zero-config CUDA discovery vs. sub-2s probe on CPU-only setups) was the explicit goal of Fase 2 in the v4.8.0 roadmap.

Test plan

  • pytest tests/test_gpu_auto.py -v — 13/13 pass
  • pytest tests/test_backwards_compat.py -v — 5/5 pass (signatures frozen)
  • pytest tests/test_config.py -v — 17/17 pass (new field additive, no field removed)
  • pytest tests/test_lazy_embeddings.py -v — 14/14 pass (lazy-load contract unchanged)
  • Manual Windows local with RTX 3080 Ti: config with gpu: auto (default) → banner shows GPU STATUS: ACTIVE / Mode: auto-cuda
  • Manual CI Linux (no CUDA): default config → banner shows GPU STATUS: UNAVAILABLE / Mode: auto-cpu-fallback / reason line filled
  • Manual gpu: false → banner shows Mode: forced-cpu, no probe overhead in startup profile
  • Manual gpu: true on machine without GPU → banner shows Mode: forced-cuda-fallback with WARN in stderr

Commits

  1. feat(config) — gpu_mode tri-state with legacy bool alias
  2. refactor(gpu) — _load_model routes via gpu_mode; banner covers every path
  3. docs(config) — config.example.yaml documented gpu block
  4. docs(gpu) — docs/gpu-setup.md setup guide + troubleshooting
  5. test(gpu) — 13 tests for tri-state routing
  6. docs(changelog) — Unreleased entry

Summary by CodeRabbit

  • New Features

    • Added GPU embedding modes: auto, enabled, and disabled.
    • Automatic CUDA readiness detection now selects GPU when available and falls back to CPU when needed.
    • Startup messages show the active execution mode and explain GPU fallback reasons.
    • Legacy boolean GPU settings remain supported.
  • Documentation

    • Added GPU setup, installation, verification, troubleshooting, and performance guidance.
    • Updated configuration examples and changelog documentation.

Greptile Summary

The PR changes embedding GPU configuration to a normalized tri-state mode and routes lazy model loading through explicit automatic, forced-CUDA, and forced-CPU paths.

  • Defaults GPU selection to automatic CUDA readiness detection with CPU fallback.
  • Preserves legacy YAML booleans through configuration normalization and a derived boolean alias.
  • Adds startup diagnostics, setup documentation, and mocked routing tests.

Confidence Score: 5/5

The PR appears safe to merge.

No blocking failure remains within the eligible scope of this follow-up review.

Important Files Changed

Filename Overview
mcp_server/config.py Adds and normalizes the tri-state GPU mode while deriving the legacy boolean alias.
mcp_server/server.py Refactors lazy embedding initialization into mode-specific provider routing and emits a diagnostic banner for every completed load path.
tests/test_gpu_auto.py Covers configuration normalization and mocked CPU, automatic CUDA, and forced CUDA routing.
docs/gpu-setup.md Documents GPU modes, readiness checks, installation, startup diagnostics, and troubleshooting.
config.example.yaml Updates the example embedding configuration to use automatic GPU detection and documents legacy boolean compatibility.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A[Load embedding model] --> B{gpu_mode}
    B -->|false| C[Load CPU provider]
    B -->|auto| D[Probe CUDA readiness]
    B -->|true| E[Probe CUDA readiness]
    D -->|ready| F[Attempt CUDA load]
    D -->|unavailable| G[Load CPU fallback]
    F -->|load succeeds| H[auto-cuda]
    F -->|load fails| G
    E -->|ready| I[Attempt CUDA load]
    E -->|unavailable| J[Load CPU fallback]
    I -->|load succeeds| K[forced-cuda]
    I -->|load fails| J
    C --> L[forced-cpu]
    G --> M[auto-cpu-fallback]
    J --> N[forced-cuda-fallback]
Loading

Reviews (3): Last reviewed commit: "ci: re-trigger workflows (F2 initial pus..." | Re-trigger Greptile

@coderabbitai

coderabbitai Bot commented Aug 6, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@lyonzin, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 6 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 63339087-3b75-4ef1-ae1f-ba2614b9e7c0

📥 Commits

Reviewing files that changed from the base of the PR and between 8910c35 and a6efe10.

📒 Files selected for processing (6)
  • README.md
  • config.example.yaml
  • docs/gpu-setup.md
  • mcp_server/config.py
  • mcp_server/server.py
  • tests/test_gpu_auto.py
📝 Walkthrough

Walkthrough

The change adds tri-state GPU configuration with legacy boolean support. Embedding initialization probes CUDA when required, selects CUDA or CPU providers, reports execution status, and falls back to CPU when needed. Configuration examples, setup documentation, changelog content, and mocked tests cover the new behavior.

Changes

GPU configuration and embedding loading

Layer / File(s) Summary
GPU mode contract and normalization
mcp_server/config.py, config.example.yaml, tests/test_gpu_auto.py
Config supports "auto", "true", and "false", normalizes legacy values, validates input, and derives gpu_acceleration. Tests cover normalization and invalid values.
Embedding provider routing
mcp_server/server.py, tests/test_gpu_auto.py
Embedding loading routes CPU-only, automatic, and forced-CUDA modes. CUDA readiness and load failures trigger CPU fallback with status and reason reporting.
GPU setup and operational guidance
docs/gpu-setup.md, README.md
Documentation describes configuration modes, CUDA checks, startup statuses, troubleshooting, installation requirements, and performance expectations.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Config
  participant FastEmbedEmbeddings
  participant _route_load
  participant _load_with_providers
  participant TextEmbedding
  Config->>FastEmbedEmbeddings: provide gpu_mode
  FastEmbedEmbeddings->>_route_load: route embedding initialization
  _route_load->>_route_load: check CUDA readiness when required
  _route_load->>_load_with_providers: select CUDA or CPU providers
  _load_with_providers->>TextEmbedding: initialize embedding model
  TextEmbedding-->>_load_with_providers: return model or loading failure
  _load_with_providers-->>FastEmbedEmbeddings: return model and execution status
Loading

Suggested reviewers: hohlas

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: tri-state GPU configuration with CUDA auto-detection enabled by default.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/v4.8.0-fase-2-gpu-auto

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@config.example.yaml`:
- Around line 144-153: Constrain the GPU extra in pyproject.toml to the tested
fastembed-gpu and CUDA 12/cuDNN 9-compatible ONNX Runtime versions instead of
broad ranges or standard fastembed. Update the dependency commands and NVIDIA
driver guidance in config.example.yaml lines 144-153, README.md line 1417, and
docs/gpu-setup.md lines 32-60 to match those pinned versions and readiness
requirements. Keep all three documentation sites consistent with the GPU package
selection and CUDA 12 setup.

In `@mcp_server/server.py`:
- Around line 484-487: Update the forced-CUDA fallback documentation to state
that CPU fallback occurs after either readiness verification failure or CUDA
model-load failure. Apply this wording consistently in mcp_server/server.py
lines 484-487 and docs/gpu-setup.md lines 9-13, including the corresponding
mode-table entry.
- Around line 532-555: Update the forced-CUDA fallback flow around
_load_with_providers and _print_gpu_banner so gpu_status records the fallback
cause before CPU loading in both branches. When CUDA initialization raises, set
available to False and fallback_reason to the exception details; when
verify_gpu_readiness reports unavailable, ensure its fallback reason is
preserved or assigned before the CPU fallback. Keep the existing CPU load and
banner behavior unchanged.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: c467c70e-8c7e-47b0-ac5a-3c12df4160ba

📥 Commits

Reviewing files that changed from the base of the PR and between 1f4a685 and 98d864b.

📒 Files selected for processing (6)
  • README.md
  • config.example.yaml
  • docs/gpu-setup.md
  • mcp_server/config.py
  • mcp_server/server.py
  • tests/test_gpu_auto.py

Comment thread config.example.yaml Resolved
Comment thread mcp_server/server.py Resolved
Comment thread mcp_server/server.py
Comment on lines +532 to +555
except (ValueError, RuntimeError) as e:
print(f"[WARN] GPU probe passed but load failed ({e}); loading on CPU...")
self._load_with_providers(["CPUExecutionProvider"], label="CPU fallback")
self._print_gpu_banner(status=gpu_status, mode="auto-cpu-fallback")
return
# mode == "true" — force CUDA
self._setup_cuda_dll_paths()
gpu_status = self.verify_gpu_readiness()
if gpu_status.available:
try:
self._load_with_providers(
["CUDAExecutionProvider", "CPUExecutionProvider"], label="GPU forced"
)
self._print_gpu_banner(status=gpu_status, mode="forced-cuda")
return
except (ValueError, RuntimeError) as e:
print(f"[WARN] gpu: true but CUDA load failed ({e}); loading on CPU...")
else:
print(
f"[WARN] gpu: true but GPU not ready ({gpu_status.fallback_reason}); "
"loading on CPU"
)
self._load_with_providers(["CPUExecutionProvider"], label="CPU fallback")
self._print_gpu_banner(status=gpu_status, mode="forced-cuda-fallback")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Record the CUDA load failure before printing the fallback banner.

When CUDA model initialization raises, gpu_status.available remains True and gpu_status.fallback_reason remains empty. The CPU fallback banner then omits the reason that caused the fallback.

Set available to False and set fallback_reason before the CPU load in both branches.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@mcp_server/server.py` around lines 532 - 555, Update the forced-CUDA fallback
flow around _load_with_providers and _print_gpu_banner so gpu_status records the
fallback cause before CPU loading in both branches. When CUDA initialization
raises, set available to False and fallback_reason to the exception details;
when verify_gpu_readiness reports unavailable, ensure its fallback reason is
preserved or assigned before the CPU fallback. Keep the existing CPU load and
banner behavior unchanged.

lyonzin added 7 commits August 6, 2026 18:47
…ol alias

v4.8.0 Fase 2 — GPU auto-detect default (step 1/6).

Adds `gpu_mode: str = auto` to Config dataclass, backed by the existing
`models.embedding.gpu` YAML key. Accepts:

  * auto  — new default; probe CUDA at startup, fall back to CPU
  * true  — force CUDA; fall back to CPU only if load fails
  * false — never probe; CPU with zero startup overhead

Legacy bool `gpu: true/false` in YAML continues to work — normalized to
string form in __post_init__ so downstream code sees a single str type.

The legacy `gpu_acceleration: bool` field is preserved for backwards
compatibility with callers that check it as a bool; it is now DERIVED
(True when gpu_mode is true or auto, False when false).

Invalid values (non-str/non-bool, or unrecognized string) log a WARN and
fall back to auto.

Zero behavior change for callers of gpu_acceleration; new callers can
read gpu_mode directly for tri-state logic.
v4.8.0 Fase 2 — GPU auto-detect default (step 2/6).

_load_model now routes through _route_load(), which dispatches on
config.gpu_mode (tri-state introduced in step 1):

  false — CPU-only, no probe (zero startup overhead)
  auto  — probe verify_gpu_readiness(); CUDA if ready, CPU otherwise
  true  — force CUDA; fall back to CPU only if the actual load fails

Extracted _load_with_providers helper so both CUDA and CPU paths share
one TextEmbedding instantiation site, keeping each branch under the
30-line limit.

_print_gpu_banner now runs on EVERY startup path (including CPU-only and
fallback), not only when CUDA succeeds. New signature takes an explicit
mode string (forced-cpu | forced-cuda | forced-cuda-fallback |
auto-cuda | auto-cpu-fallback) plus an Optional[GPUStatus] (None when
gpu_mode=false so no probe ran). Fallback banners include the probe
reason plus a hint with the full pip install chain.

Behavior preserved for existing gpu: true/false configs — same effective
provider selection, same fallback semantics; just now with a diagnostic
banner on every path so operators can see which mode ran and why.

Verified: tests/test_lazy_embeddings.py, test_config.py,
test_backwards_compat.py — 36/36 pass, zero regression.
v4.8.0 Fase 2 — GPU auto-detect default (step 3/6).

Replaces the terse gpu: false default with a documented gpu: auto block
covering the three modes, the legacy bool alias, the pip install chain
(onnxruntime-gpu CUDA 12 variant + nvidia-cudnn-cu12 + siblings), the
driver requirement (>= 525 for CUDA 12), and a one-liner to verify
readiness manually via verify_gpu_readiness().

Explicitly notes that CUDA 13 is NOT supported by FastEmbed — this trips
up users who install onnxruntime-gpu without the extra-index-url and get
the CUDA 13 build silently.

Cross-links docs/gpu-setup.md for the full troubleshooting guide (added
in step 4).
…ting

v4.8.0 Fase 2 — GPU auto-detect default (step 4/6).

New docs/gpu-setup.md covers:

- TL;DR of the three modes and their cold-start cost when GPU is absent
- Full auto-detect flow (the four verify_gpu_readiness checks in order)
- CUDA 12 dependency chain via pip (onnxruntime-gpu with --extra-index-url,
  the nine nvidia-*-cu12 packages, driver requirement)
- One-liner to run verify_gpu_readiness() manually and interpret the output
- Startup banner examples for auto-cuda / auto-cpu-fallback / forced-cpu
- Troubleshooting for the six most common failures:
    * cublasLt64_12.dll missing (wrong onnxruntime-gpu variant, CUDA 13 vs 12)
    * nvidia-smi not on PATH
    * driver older than 525
    * WSL2 sees no GPU
    * Docker/Podman container has no GPU access
    * ORT silently fell back to CPU (version mismatch)
- Performance expectations (17x indexing speedup measured on 3865 docs)

Referenced from config.example.yaml gpu block.
v4.8.0 Fase 2 — GPU auto-detect default (step 5/6).

New tests/test_gpu_auto.py with 13 AAA tests split into two classes:

TestGpuModeNormalization (8 tests) — Config.__post_init__ tri-state:
  * legacy bool True/False normalize to "true"/"false"
  * string "auto"/"true"/"false" stay unchanged
  * case-insensitive and stripped ("  AUTO  " -> "auto")
  * invalid string falls back to "auto" with WARN
  * invalid type falls back to "auto" with WARN
  * gpu_acceleration alias correctly derived for each case

TestLoadModelRouting (5 tests) — _load_model routes per gpu_mode:
  * "false"  -> probe NEVER called; TextEmbedding gets CPU-only providers
  * "auto" + probe pass  -> TextEmbedding gets CUDA + CPU providers
  * "auto" + probe fail  -> CPU fallback, banner shows auto-cpu-fallback
                            plus the probe fallback_reason
  * "true" + probe fail  -> CPU fallback with WARN, banner shows
                            forced-cuda-fallback
  * "true" + CUDA load raises (probe passed but TextEmbedding blows up)
                         -> TWO TextEmbedding calls (CUDA fails, CPU works),
                            banner shows forced-cuda-fallback

All tests mock verify_gpu_readiness and TextEmbedding, so they:
  * do NOT require a real GPU
  * do NOT download the 33MB bge-small model
  * run in <2s on CI

Verified: 49/49 pass across test_gpu_auto + test_lazy_embeddings +
test_config + test_backwards_compat. Zero regression.
Documents the tri-state gpu_mode shipped across the previous 5 commits:

  * config.py — tri-state Config.gpu_mode with legacy bool alias
  * server.py — _load_model routes via _route_load per gpu_mode;
                _print_gpu_banner covers every startup path with mode +
                fallback_reason
  * config.example.yaml — documented gpu block with full pip chain
  * docs/gpu-setup.md — setup guide + troubleshooting
  * tests/test_gpu_auto.py — 13 mocked tests, no real GPU required

Entry inserted at the top of the Unreleased section of the CHANGELOG.
PR number placeholder in body — will be linked in the PR itself once
GitHub assigns it.
@lyonzin
lyonzin force-pushed the feat/v4.8.0-fase-2-gpu-auto branch from bb459d3 to a6efe10 Compare August 6, 2026 21:51
@lyonzin
lyonzin merged commit 8aa274d into master Aug 6, 2026
1 check was pending
@lyonzin
lyonzin deleted the feat/v4.8.0-fase-2-gpu-auto branch August 6, 2026 21:51
lyonzin added a commit that referenced this pull request Aug 6, 2026
Retriggering CI on master to validate the Actions billing kill-switch
was released. Master already carries #147 (security wire), #148 (embedding
profiles), and #149 (GPU auto). No code change here — this commit exists
only so quality-gate.yml, ci.yml, and security.yml fire on push to master.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant