Rembg is a tool to remove images background
fix: warn when a GPU provider silently falls back to CPU (#841, #849)
Daniel Gatis030a9ed79dbf
diff --git a/Dockerfile_nvidia_cuda_cudnn_gpu b/Dockerfile_nvidia_cuda_cudnn_gpuindex 6261bb7..efed861 100644--- a/Dockerfile_nvidia_cuda_cudnn_gpu+++ b/Dockerfile_nvidia_cuda_cudnn_gpu@@ -1,4 +1,7 @@-FROM nvidia/cuda:12.4.1-cudnn-devel-ubuntu22.04+# CUDA 13 to match onnxruntime-gpu >= 1.27, which links against+# libcublasLt.so.13. Ubuntu 24.04 for Python 3.12; 22.04 ships 3.10, below the+# >=3.11 this project requires.+FROM nvidia/cuda:13.0.1-cudnn-devel-ubuntu24.04WORKDIR /rembgdiff --git a/rembg/sessions/base.py b/rembg/sessions/base.pyindex 91b908a..806c9cb 100644--- a/rembg/sessions/base.py+++ b/rembg/sessions/base.py@@ -1,4 +1,5 @@import os+import warningsfrom typing import Dict, List, Tupleimport numpy as np@@ -39,6 +40,44 @@ class BaseSession:providers=providers,)+ self._warn_on_provider_fallback(providers)++ @staticmethod+ def _accelerated_providers(providers: List[str]) -> List[str]:+ return [p for p in providers if p != "CPUExecutionProvider"]++ def _warn_on_provider_fallback(self, requested: List[str]) -> None:+ """Warn when an accelerator was asked for but the session runs on CPU.++ `get_available_providers()` lists a provider whenever its shim ships+ with onnxruntime, even if the CUDA/cuDNN libraries it links against are+ absent. Session creation then logs to stderr and quietly falls back to+ CPU, so inference is 10-20x slower with no signal in Python. Compare+ what was asked for against what the session actually got.+ """+ wanted = self._accelerated_providers(requested)+ if not wanted:+ return++ try:+ active = self.inner_session.get_providers()+ except Exception: # pragma: no cover - defensive+ return++ if self._accelerated_providers(active):+ return++ warnings.warn(+ f"{', '.join(wanted)} was requested but the session is running on "+ "CPU. onnxruntime could not load the provider, usually because the "+ "matching CUDA/cuDNN runtime libraries are missing or are a "+ "different major version than the onnxruntime-gpu build. Inference "+ "will be slow. See the onnxruntime stderr output above for the "+ "specific library that failed to load.",+ RuntimeWarning,+ stacklevel=3,+ )+def normalize(self,img: PILImage,diff --git a/tests/test_provider_fallback.py b/tests/test_provider_fallback.pynew file mode 100644index 0000000..80edc0c--- /dev/null+++ b/tests/test_provider_fallback.py@@ -0,0 +1,91 @@+import warnings++import pytest++from rembg.sessions.base import BaseSession+++class FakeInner:+ def __init__(self, providers):+ self._providers = providers++ def get_providers(self):+ return self._providers+++def make_session(active):+ """A BaseSession whose session reports `active` as its providers.++ Built without __init__ so the check can be exercised without onnxruntime+ creating a real session or a model being downloaded.+ """+ session = BaseSession.__new__(BaseSession)+ session.inner_session = FakeInner(active)+ return session+++def test_warns_when_cuda_requested_but_cpu_active():+ """The silent CPU fallback reported in #841 now surfaces as a warning."""+ session = make_session(["CPUExecutionProvider"])++ with pytest.warns(RuntimeWarning, match="running on CPU"):+ session._warn_on_provider_fallback(+ ["CUDAExecutionProvider", "CPUExecutionProvider"]+ )+++def test_no_warning_when_cuda_is_active():+ session = make_session(["CUDAExecutionProvider", "CPUExecutionProvider"])++ with warnings.catch_warnings():+ warnings.simplefilter("error")+ session._warn_on_provider_fallback(+ ["CUDAExecutionProvider", "CPUExecutionProvider"]+ )+++def test_no_warning_when_cpu_was_what_was_asked_for():+ """A CPU-only install is not a fallback and must stay quiet."""+ session = make_session(["CPUExecutionProvider"])++ with warnings.catch_warnings():+ warnings.simplefilter("error")+ session._warn_on_provider_fallback(["CPUExecutionProvider"])+++ "provider",+ ["ROCMExecutionProvider", "OpenVINOExecutionProvider"],+)+def test_warns_for_other_accelerators(provider):+ """The check is not CUDA-specific."""+ session = make_session(["CPUExecutionProvider"])++ with pytest.warns(RuntimeWarning, match=provider):+ session._warn_on_provider_fallback([provider, "CPUExecutionProvider"])+++def test_partial_fallback_does_not_warn():+ """If any accelerator survived, the session is not on CPU alone."""+ session = make_session(["ROCMExecutionProvider", "CPUExecutionProvider"])++ with warnings.catch_warnings():+ warnings.simplefilter("error")+ session._warn_on_provider_fallback(+ ["CUDAExecutionProvider", "ROCMExecutionProvider", "CPUExecutionProvider"]+ )+++def test_survives_a_session_that_cannot_report_providers():+ """A backend without get_providers must not break session creation."""++ class Broken:+ def get_providers(self):+ raise RuntimeError("nope")++ session = BaseSession.__new__(BaseSession)+ session.inner_session = Broken()++ with warnings.catch_warnings():+ warnings.simplefilter("error")+ session._warn_on_provider_fallback(["CUDAExecutionProvider"])