Rembg is a tool to remove images background
feat: add birefnet-general-fp16 session (#858)
Andrew Koskic5b48b0417a0
diff --git a/README.md b/README.mdindex 5c92860..d283535 100644--- a/README.md+++ b/README.md@@ -523,6 +523,7 @@ Sample results and benchmark scores for each model are hosted by [withoutBG](htt- isnet-anime ([download](https://github.com/danielgatis/rembg/releases/download/v0.0.0/isnet-anime.onnx), [source](https://github.com/SkyTNT/anime-segmentation)): A high-accuracy segmentation for anime character.- sam ([download encoder](https://github.com/danielgatis/rembg/releases/download/v0.0.0/vit_b-encoder-quant.onnx), [download decoder](https://github.com/danielgatis/rembg/releases/download/v0.0.0/vit_b-decoder-quant.onnx), [source](https://github.com/facebookresearch/segment-anything), [details](https://withoutbg.com/models/sam?ref=rembg&utm_medium=readme&utm_campaign=models&utm_content=sam)): A pre-trained model for any use cases.- birefnet-general ([download](https://github.com/danielgatis/rembg/releases/download/v0.0.0/BiRefNet-general-epoch_244.onnx), [source](https://github.com/ZhengPeng7/BiRefNet), [sample results](https://withoutbg.com/models/birefnet-general?ref=rembg&utm_medium=readme&utm_campaign=models&utm_content=birefnet-general)): A pre-trained model for general use cases.+- birefnet-general-fp16 ([source](https://github.com/ZhengPeng7/BiRefNet)): birefnet-general converted to float16 on first use (`pip install "rembg[fp16]"`). Roughly 30% faster on CUDA with near-identical masks; it does not reduce VRAM, and on CPU it is usually slower than birefnet-general.- birefnet-general-lite ([download](https://github.com/danielgatis/rembg/releases/download/v0.0.0/BiRefNet-general-bb_swin_v1_tiny-epoch_232.onnx), [source](https://github.com/ZhengPeng7/BiRefNet), [sample results](https://withoutbg.com/models/birefnet-general-lite?ref=rembg&utm_medium=readme&utm_campaign=models&utm_content=birefnet-general-lite)): A light pre-trained model for general use cases.- birefnet-portrait ([download](https://github.com/danielgatis/rembg/releases/download/v0.0.0/BiRefNet-portrait-epoch_150.onnx), [source](https://github.com/ZhengPeng7/BiRefNet), [sample results](https://withoutbg.com/models/birefnet-portrait?ref=rembg&utm_medium=readme&utm_campaign=models&utm_content=birefnet-portrait)): A pre-trained model for human portraits.- birefnet-dis ([download](https://github.com/danielgatis/rembg/releases/download/v0.0.0/BiRefNet-DIS-epoch_590.onnx), [source](https://github.com/ZhengPeng7/BiRefNet), [sample results](https://withoutbg.com/models/birefnet-dis?ref=rembg&utm_medium=readme&utm_campaign=models&utm_content=birefnet-dis)): A pre-trained model for dichotomous image segmentation (DIS).diff --git a/pyproject.toml b/pyproject.tomlindex a9a71c4..1a178c3 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -44,6 +44,10 @@ onnxruntime-gpu = {version = "^1.23.2", optional = true, markers = "sys_platform# ROCm backend (optional) - only available on Linux (latest is 1.22.x)onnxruntime-rocm = {version = "^1.22.0", optional = true, markers = "sys_platform == 'linux'"}+# float16 conversion for birefnet-general-fp16 (optional)+onnx = {version = "^1.17.0", optional = true}+onnxconverter-common = {version = "^1.14.0", optional = true}+# CLI dependencies (optional)aiohttp = {version = "^3.13.2", optional = true}asyncer = {version = "^0.0.12", optional = true}@@ -78,6 +82,7 @@ pytest = "^9.0.2"cpu = ["onnxruntime"]gpu = ["onnxruntime-gpu"]rocm = ["onnxruntime-rocm"]+fp16 = ["onnx", "onnxconverter-common"]cli = ["aiohttp", "asyncer", "click", "fastapi", "filetype", "gradio", "python-multipart", "sniffio", "uvicorn", "watchdog"]dev = ["bandit", "black", "flake8", "imagehash", "isort", "mypy", "pytest"]diff --git a/rembg/sessions/__init__.py b/rembg/sessions/__init__.pyindex 05a25c7..e0362a9 100644--- a/rembg/sessions/__init__.py+++ b/rembg/sessions/__init__.py@@ -14,6 +14,10 @@ from .birefnet_general_lite import BiRefNetSessionGeneralLitesessions[BiRefNetSessionGeneralLite.name()] = BiRefNetSessionGeneralLite+from .birefnet_general_fp16 import BiRefNetSessionGeneralFP16++sessions[BiRefNetSessionGeneralFP16.name()] = BiRefNetSessionGeneralFP16+from .birefnet_portrait import BiRefNetSessionPortraitsessions[BiRefNetSessionPortrait.name()] = BiRefNetSessionPortraitdiff --git a/rembg/sessions/birefnet_general_fp16.py b/rembg/sessions/birefnet_general_fp16.pynew file mode 100644index 0000000..a1937a0--- /dev/null+++ b/rembg/sessions/birefnet_general_fp16.py@@ -0,0 +1,72 @@+import os++from .birefnet_general import BiRefNetSessionGeneral+++class BiRefNetSessionGeneralFP16(BiRefNetSessionGeneral):+ """+ BiRefNet-General with its weights and activations in float16, for GPUs.++ The model is not downloaded separately: the float32 birefnet-general model is+ fetched (and checksummed) as usual, then converted once and cached. Inputs and+ outputs stay float32, so prediction is identical to BiRefNetSessionGeneral.++ On CUDA this is roughly 30% faster with masks that match float32 to an IoU of+ ~0.9996. It does not reduce VRAM, which is dominated by activations at+ 1024x1024. On CPU it is usually slower than float32, so use birefnet-general there.+ """++ @classmethod+ def download_models(cls, *args, **kwargs):+ """+ Returns the path to the float16 model, converting it on first use.++ Parameters:+ *args: Additional positional arguments.+ **kwargs: Additional keyword arguments.++ Returns:+ str: The path to the float16 model file.+ """+ fname = f"{cls.name(*args, **kwargs)}.onnx"+ existing = cls.resolve_existing(fname, *args, **kwargs)+ if existing is not None:+ return existing++ try:+ import onnx+ from onnxconverter_common import float16+ except ImportError as e:+ raise ImportError(+ "birefnet-general-fp16 converts the float32 model on first use and "+ "needs onnx and onnxconverter-common: pip install 'rembg[fp16]'"+ ) from e++ source = BiRefNetSessionGeneral.download_models(*args, **kwargs)+ model = float16.convert_float_to_float16(onnx.load(source), keep_io_types=True)++ model_dir = cls.model_dir(*args, **kwargs)+ os.makedirs(model_dir, exist_ok=True)+ path = os.path.join(model_dir, fname)++ # Write then rename, so an interrupted conversion never leaves a partial+ # file that resolve_existing would pick up next time.+ tmp = f"{path}.tmp"+ onnx.save(model, tmp)+ os.replace(tmp, path)++ return path++ @classmethod+ def name(cls, *args, **kwargs):+ """+ Returns the name of the BiRefNet-General-FP16 session.++ Parameters:+ *args: Additional positional arguments.+ **kwargs: Additional keyword arguments.++ Returns:+ str: The name of the session.+ """+ return "birefnet-general-fp16"diff --git a/tests/test_birefnet_fp16.py b/tests/test_birefnet_fp16.pynew file mode 100644index 0000000..c30423f--- /dev/null+++ b/tests/test_birefnet_fp16.py@@ -0,0 +1,70 @@+import numpy as np+import pytest++onnx = pytest.importorskip("onnx")+pytest.importorskip("onnxconverter_common")++from onnx import TensorProto, helper, numpy_helper++from rembg.sessions import sessions+from rembg.sessions.birefnet_general import BiRefNetSessionGeneral+from rembg.sessions.birefnet_general_fp16 import BiRefNetSessionGeneralFP16+++def _tiny_float32_model(path):+ """A one-Conv stand-in for the float32 BiRefNet, so no download is needed."""+ weight = numpy_helper.from_array(np.random.rand(1, 3, 3, 3).astype(np.float32), "w")+ graph = helper.make_graph(+ [helper.make_node("Conv", ["x", "w"], ["y"], pads=[1, 1, 1, 1])],+ "tiny",+ [helper.make_tensor_value_info("x", TensorProto.FLOAT, [1, 3, 8, 8])],+ [helper.make_tensor_value_info("y", TensorProto.FLOAT, [1, 1, 8, 8])],+ [weight],+ )+ onnx.save(helper.make_model(graph), path)+ return str(path)+++def home(monkeypatch, tmp_path):+ for var in ("U2NET_HOME", "XDG_DATA_HOME"):+ monkeypatch.delenv(var, raising=False)+ monkeypatch.setenv("REMBG_HOME", str(tmp_path / "home"))++ source = _tiny_float32_model(tmp_path / "fp32.onnx")+ calls = []++ def fake_download(*args, **kwargs):+ calls.append(1)+ return source++ monkeypatch.setattr(+ BiRefNetSessionGeneral,+ "download_models",+ classmethod(lambda cls, *a, **k: fake_download()),+ )+ return calls+++def test_registered():+ assert sessions["birefnet-general-fp16"] is BiRefNetSessionGeneralFP16+++def test_converts_weights_but_keeps_float32_io(home):+ path = BiRefNetSessionGeneralFP16.download_models()++ assert path == BiRefNetSessionGeneralFP16.resolve_existing(+ "birefnet-general-fp16.onnx"+ )+ model = onnx.load(path)+ assert {t.data_type for t in model.graph.initializer} == {TensorProto.FLOAT16}+ assert model.graph.input[0].type.tensor_type.elem_type == TensorProto.FLOAT+ assert model.graph.output[0].type.tensor_type.elem_type == TensorProto.FLOAT+++def test_conversion_is_cached(home):+ first = BiRefNetSessionGeneralFP16.download_models()+ second = BiRefNetSessionGeneralFP16.download_models()++ assert first == second+ assert len(home) == 1