Instructions to use moonbox-dev/BiRefNet-TensorRT with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- TensorRT
How to use moonbox-dev/BiRefNet-TensorRT with TensorRT:
# No code snippets available yet for this library. # To use this model, check the repository files and the library's documentation. # Want to help? PRs adding snippets are welcome at: # https://github.com/huggingface/huggingface.js
- BiRefNet
How to use moonbox-dev/BiRefNet-TensorRT with BiRefNet:
# Option 1: use with transformers from transformers import AutoModelForImageSegmentation birefnet = AutoModelForImageSegmentation.from_pretrained("moonbox-dev/BiRefNet-TensorRT", trust_remote_code=True)# Option 2: use with BiRefNet # Install from https://github.com/ZhengPeng7/BiRefNet from models.birefnet import BiRefNet model = BiRefNet.from_pretrained("moonbox-dev/BiRefNet-TensorRT") - Notebooks
- Google Colab
- Kaggle
fp16 build of BiRefNet
Browse files- .gitattributes +1 -0
- fp16/config.json +4 -0
- fp16/cutout_trt.py +44 -0
- fp16/model.engine +3 -0
- fp16/trt_runner.py +58 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
fp16/model.engine filter=lfs diff=lfs merge=lfs -text
|
fp16/config.json
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"norm": "imagenet",
|
| 3 |
+
"minmax": false
|
| 4 |
+
}
|
fp16/cutout_trt.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Background removal with a TensorRT engine (BiRefNet, BiRefNet_lite, ORMBG): a picture -> the picture with the
|
| 2 |
+
matte as its alpha channel.
|
| 3 |
+
|
| 4 |
+
python cutout_trt.py photo.jpg cutout.png
|
| 5 |
+
|
| 6 |
+
The engine takes a 1024 x 1024 RGB picture [1, 3, 1024, 1024] (normalized as config.json says) and returns the matte
|
| 7 |
+
[1, 1, 1024, 1024]. config.json: "norm" ("imagenet" or "none") and "minmax" (rescale the matte to 0-1, as ORMBG's
|
| 8 |
+
inference does).
|
| 9 |
+
"""
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import json
|
| 13 |
+
import sys
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
|
| 16 |
+
import numpy as np
|
| 17 |
+
from PIL import Image
|
| 18 |
+
|
| 19 |
+
HERE = Path(__file__).resolve().parent
|
| 20 |
+
sys.path.insert(0, str(HERE))
|
| 21 |
+
from trt_runner import Engine # noqa: E402
|
| 22 |
+
|
| 23 |
+
MEAN_STD = {"imagenet": ([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]), "none": ([0.0, 0.0, 0.0], [1.0, 1.0, 1.0])}
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def matte(engine, img, cfg):
|
| 27 |
+
x = np.asarray(img.convert("RGB").resize((1024, 1024), Image.BILINEAR), np.float32) / 255
|
| 28 |
+
mean, std = MEAN_STD[cfg["norm"]]
|
| 29 |
+
x = ((x - np.array(mean, np.float32)) / np.array(std, np.float32)).transpose(2, 0, 1)[None].copy()
|
| 30 |
+
outs = engine({engine.inputs[0]: x})
|
| 31 |
+
y = next(o for o in outs.values() if o.ndim == 4 and o.shape[1] == 1 and o.shape[-1] == 1024)
|
| 32 |
+
y = y[0, 0].astype(np.float32)
|
| 33 |
+
if cfg.get("minmax"):
|
| 34 |
+
y = (y - y.min()) / max(float(y.max() - y.min()), 1e-6)
|
| 35 |
+
a = Image.fromarray((np.clip(y, 0, 1) * 255).astype(np.uint8)).resize(img.size, Image.BILINEAR)
|
| 36 |
+
return a
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
if __name__ == "__main__":
|
| 40 |
+
cfg = json.loads((HERE / "config.json").read_text())
|
| 41 |
+
e = Engine(HERE / "model.engine")
|
| 42 |
+
img = Image.open(sys.argv[1]).convert("RGB")
|
| 43 |
+
img.putalpha(matte(e, img, cfg))
|
| 44 |
+
img.save(sys.argv[2])
|
fp16/model.engine
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:04a22835cf6dcb52982892994c329e2c89627aa91326ea687e8b249c8b2c31ac
|
| 3 |
+
size 717750076
|
fp16/trt_runner.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""A minimal TensorRT engine runner: numpy in, numpy out (tensorrt-cu12 10.x and polygraphy; no torch).
|
| 2 |
+
|
| 3 |
+
from trt_runner import Engine
|
| 4 |
+
e = Engine("model.engine")
|
| 5 |
+
out = e({"input": x}) # dict of output name -> numpy array
|
| 6 |
+
"""
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
|
| 11 |
+
import numpy as np
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def lean_dlls():
|
| 15 |
+
"""Version-compatible engines are built against and run on TensorRT's lean runtime (pip tensorrt-lean-cu12):
|
| 16 |
+
put its DLL folder on the search path (Windows)."""
|
| 17 |
+
import importlib.util
|
| 18 |
+
import os
|
| 19 |
+
spec = importlib.util.find_spec("tensorrt_lean_libs")
|
| 20 |
+
if spec and spec.submodule_search_locations:
|
| 21 |
+
d = list(spec.submodule_search_locations)[0]
|
| 22 |
+
os.environ["PATH"] = d + os.pathsep + os.environ.get("PATH", "")
|
| 23 |
+
if hasattr(os, "add_dll_directory"):
|
| 24 |
+
os.add_dll_directory(d)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class Engine:
|
| 28 |
+
def __init__(self, path):
|
| 29 |
+
lean_dlls()
|
| 30 |
+
import tensorrt as trt
|
| 31 |
+
from polygraphy.backend.trt import TrtRunner
|
| 32 |
+
self.trt = trt
|
| 33 |
+
logger = trt.Logger(trt.Logger.WARNING)
|
| 34 |
+
runtime = trt.Runtime(logger)
|
| 35 |
+
runtime.engine_host_code_allowed = True # version-compatible engines carry their own lean runtime
|
| 36 |
+
engine = runtime.deserialize_cuda_engine(Path(path).read_bytes())
|
| 37 |
+
if engine is None:
|
| 38 |
+
raise RuntimeError(f"could not load {path} (TensorRT {trt.__version__}; the engine needs TensorRT 10.x "
|
| 39 |
+
"and an RTX 30-series or newer GPU)")
|
| 40 |
+
self.engine = engine
|
| 41 |
+
self.runner = TrtRunner(engine)
|
| 42 |
+
self.runner.activate()
|
| 43 |
+
self.inputs = [engine.get_tensor_name(i) for i in range(engine.num_io_tensors)
|
| 44 |
+
if engine.get_tensor_mode(engine.get_tensor_name(i)) == trt.TensorIOMode.INPUT]
|
| 45 |
+
|
| 46 |
+
def __call__(self, feed: dict) -> dict:
|
| 47 |
+
feed = {k: np.ascontiguousarray(v) for k, v in feed.items() if k in self.inputs}
|
| 48 |
+
out = self.runner.infer(feed, check_inputs=True)
|
| 49 |
+
return {k: np.array(v) for k, v in out.items()}
|
| 50 |
+
|
| 51 |
+
def close(self):
|
| 52 |
+
self.runner.deactivate()
|
| 53 |
+
|
| 54 |
+
def __del__(self):
|
| 55 |
+
try:
|
| 56 |
+
self.close()
|
| 57 |
+
except Exception:
|
| 58 |
+
pass
|