Repository navigation
feat(gpu): auto-detect CUDA by default via tri-state gpu_mode (v4.8.0 Fase 2) - #149
Conversation
|
Warning Review limit reached
Next review available in: 6 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the 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 configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (6)
📝 WalkthroughWalkthroughThe 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. ChangesGPU configuration and embedding loading
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
Suggested reviewers: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
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
📒 Files selected for processing (6)
README.mdconfig.example.yamldocs/gpu-setup.mdmcp_server/config.pymcp_server/server.pytests/test_gpu_auto.py
| 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") |
There was a problem hiding this comment.
🎯 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.
…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.
bb459d3 to
a6efe10
Compare
Summary
Fase 2 of the v4.8.0 roadmap — GPU auto-detect default.
Changes the default of
models.embedding.gpufromfalse(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
Configdataclass in different regions. Trivial rebase expected.What changes
mcp_server/config.pygpu_mode: strfield ("auto"|"true"|"false", default"auto"). Legacygpu_acceleration: boolderived in__post_init__. Legacy YAMLgpu: true/gpu: falsenormalized to the string form. Invalid values log WARN and fall back to"auto".mcp_server/server.py_load_modelnow routes through new_route_loadpergpu_mode. Extracted_load_with_providershelper. All three modes (false/auto/true) have explicit paths with clear fallback semantics.mcp_server/server.py_print_gpu_bannersignature changed to(status: Optional[GPUStatus], mode: str)and now runs on every startup path — including CPU-only and both fallback paths. Includes probefallback_reasonand a pip install hint on CPU paths.config.example.yamlgpu:block rewritten with tri-state docs, legacy bool note, full pip dependency chain (onnxruntime-gpu CUDA-12 variant + ninenvidia-*-cu12packages), driver requirement, verify-readiness one-liner, cross-link todocs/gpu-setup.md.docs/gpu-setup.mdnewtests/test_gpu_auto.pynewTestGpuModeNormalization(8) andTestLoadModelRouting(5). Mocksverify_gpu_readinessandTextEmbedding— runs in <2s on CI without a real GPU.README.mdBackwards compatibility
gpu: false(bool) — normalized to"false"string. Probe is skipped (zero startup overhead). Semantics preserved: CPU-only load.gpu: true(bool) — normalized to"true"string. Same behavior as before: force CUDA attempt, fall back to CPU on load failure.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.tests/test_backwards_compat.pystill green.config.gpu_acceleration: bool— still works. Field is derived fromgpu_mode(Truewhen mode is"true"or"auto").Perf note
verify_gpu_readiness()adds a 500ms–2s cold-start cost in theautopath 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 theskip-perf-gatelabel 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 passpytest 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)gpu: auto(default) → banner showsGPU STATUS: ACTIVE/Mode: auto-cudaGPU STATUS: UNAVAILABLE/Mode: auto-cpu-fallback/ reason line filledgpu: false→ banner showsMode: forced-cpu, no probe overhead in startup profilegpu: trueon machine without GPU → banner showsMode: forced-cuda-fallbackwith WARN in stderrCommits
feat(config)—gpu_modetri-state with legacy bool aliasrefactor(gpu)—_load_modelroutes viagpu_mode; banner covers every pathdocs(config)—config.example.yamldocumented gpu blockdocs(gpu)—docs/gpu-setup.mdsetup guide + troubleshootingtest(gpu)— 13 tests for tri-state routingdocs(changelog)— Unreleased entrySummary by CodeRabbit
New Features
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.
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
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]Reviews (3): Last reviewed commit: "ci: re-trigger workflows (F2 initial pus..." | Re-trigger Greptile