Instructions to use moonbox-dev/BEN2-TensorRT with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- TensorRT
How to use moonbox-dev/BEN2-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
- BEN2
How to use moonbox-dev/BEN2-TensorRT with BEN2:
import requests from PIL import Image from ben2 import AutoModel url = "https://huggingface.co/datasets/mishig/sample_images/resolve/main/teapot.jpg" image = Image.open(requests.get(url, stream=True).raw) model = AutoModel.from_pretrained("moonbox-dev/BEN2-TensorRT") model.to("cuda").eval() foreground = model.inference(image) - Notebooks
- Google Colab
- Kaggle
fp16 build of BEN2 Base
Browse filesFiles changed (5)
- .gitattributes+1
- fp16/config.jsonAdded+4
- fp16/cutout_trt.pyAdded+44
- fp16/model.engineAdded+3
- fp16/trt_runner.pyAdded+58
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines3334353632 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textfp16/model.engine filter=lfs diff=lfs merge=lfs -text
1234{
"norm": "none",
"minmax": true
}1234567891011121314151617181920212223242526272829303132333435363738394041424344"""Background removal with a TensorRT engine (BiRefNet, BiRefNet_lite, ORMBG): a picture -> the picture with thematte as its alpha channel.
python cutout_trt.py photo.jpg cutout.png
The engine takes a 1024 x 1024 RGB picture [1, 3, 1024, 1024] (normalized as config.json says) and returns the matte[1, 1, 1024, 1024]. config.json: "norm" ("imagenet" or "none") and "minmax" (rescale the matte to 0-1, as ORMBG'sinference does)."""from __future__ import annotations
import jsonimport sysfrom pathlib import Path
import numpy as npfrom PIL import Image
HERE = Path(__file__).resolve().parentsys.path.insert(0, str(HERE))from trt_runner import Engine # noqa: E402
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])}
def matte(engine, img, cfg): x = np.asarray(img.convert("RGB").resize((1024, 1024), Image.BILINEAR), np.float32) / 255 mean, std = MEAN_STD[cfg["norm"]] x = ((x - np.array(mean, np.float32)) / np.array(std, np.float32)).transpose(2, 0, 1)[None].copy() outs = engine({engine.inputs[0]: x}) y = next(o for o in outs.values() if o.ndim == 4 and o.shape[1] == 1 and o.shape[-1] == 1024) y = y[0, 0].astype(np.float32) if cfg.get("minmax"): y = (y - y.min()) / max(float(y.max() - y.min()), 1e-6) a = Image.fromarray((np.clip(y, 0, 1) * 255).astype(np.uint8)).resize(img.size, Image.BILINEAR) return a
if __name__ == "__main__": cfg = json.loads((HERE / "config.json").read_text()) e = Engine(HERE / "model.engine") img = Image.open(sys.argv[1]).convert("RGB") img.putalpha(matte(e, img, cfg)) img.save(sys.argv[2])123version https://git-lfs.github.com/spec/v1oid sha256:2d4ac960f6f33f26225458f59b226f3a8f9d5f113b88ef2136d727fa33c8bbfasize 49022822012345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758"""A minimal TensorRT engine runner: numpy in, numpy out (tensorrt-cu12 10.x and polygraphy; no torch).
from trt_runner import Engine e = Engine("model.engine") out = e({"input": x}) # dict of output name -> numpy array"""from __future__ import annotations
from pathlib import Path
import numpy as np
def lean_dlls(): """Version-compatible engines are built against and run on TensorRT's lean runtime (pip tensorrt-lean-cu12): put its DLL folder on the search path (Windows).""" import importlib.util import os spec = importlib.util.find_spec("tensorrt_lean_libs") if spec and spec.submodule_search_locations: d = list(spec.submodule_search_locations)[0] os.environ["PATH"] = d + os.pathsep + os.environ.get("PATH", "") if hasattr(os, "add_dll_directory"): os.add_dll_directory(d)
class Engine: def __init__(self, path): lean_dlls() import tensorrt as trt from polygraphy.backend.trt import TrtRunner self.trt = trt logger = trt.Logger(trt.Logger.WARNING) runtime = trt.Runtime(logger) runtime.engine_host_code_allowed = True # version-compatible engines carry their own lean runtime engine = runtime.deserialize_cuda_engine(Path(path).read_bytes()) if engine is None: raise RuntimeError(f"could not load {path} (TensorRT {trt.__version__}; the engine needs TensorRT 10.x " "and an RTX 30-series or newer GPU)") self.engine = engine self.runner = TrtRunner(engine) self.runner.activate() self.inputs = [engine.get_tensor_name(i) for i in range(engine.num_io_tensors) if engine.get_tensor_mode(engine.get_tensor_name(i)) == trt.TensorIOMode.INPUT]
def __call__(self, feed: dict) -> dict: feed = {k: np.ascontiguousarray(v) for k, v in feed.items() if k in self.inputs} out = self.runner.infer(feed, check_inputs=True) return {k: np.array(v) for k, v in out.items()}
def close(self): self.runner.deactivate()
def __del__(self): try: self.close() except Exception: pass.gitattributes+1
fp16/config.jsonAdded+4
fp16/cutout_trt.pyAdded+44
fp16/model.engineAdded+3
fp16/trt_runner.pyAdded+58