Run this model with HF Jobs
Run moonbox-dev/MobileSAM-TensorRT on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/moonbox-dev/MobileSAM-TensorRT. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/moonbox-dev/MobileSAM-TensorRT on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Instructions to use moonbox-dev/MobileSAM-TensorRT with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- TensorRT
How to use moonbox-dev/MobileSAM-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
- Notebooks
- Google Colab
- Kaggle
fp16 build of MobileSAM v2
Browse filesFiles changed (6)
- .gitattributes+2
- fp16/decoder.engineAdded+3
- fp16/encoder.engineAdded+3
- fp16/pipeline.pyAdded+89
- fp16/pipeline_trt.pyAdded+86
- fp16/trt_runner.pyAdded+85
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 lines333435363732 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/decoder.engine filter=lfs diff=lfs merge=lfs -textfp16/encoder.engine filter=lfs diff=lfs merge=lfs -text
123version https://git-lfs.github.com/spec/v1oid sha256:553a0df66900e6ec067d4b105e56c7ad53976344547af97d8cd124fd884bffcfsize 75126060123version https://git-lfs.github.com/spec/v1oid sha256:2040ee2582d33ad3965603ccadb43f0e8a9d2d30b9cc5a8884a3f71ce5d611a3size 908099801234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889"""MobileSAM (the promptable segmenter of MobileSAM v2) with ONNX Runtime: the TinyViT image encoder and SAM's ONNXdecoder wrapper as graphs, numpy around them, following the repository's SamPredictor: the longest side resized to 1024(Pillow bilinear), SAM's pixel mean / std, padded bottom-right to 1024 x 1024; prompt coordinates scaled the same way;masks returned at the image size by the decoder (logits > 0). Multimask point prompts give masks 1-3, single-mask(box) prompts mask 0, as SamPredictor does. Needs numpy, onnxruntime (or onnxruntime-gpu) and Pillow.
python fp16/pipeline.py photo.jpg masks.npz --point 410 300 [--box x0 y0 x1 y1] [--cuda]"""
from __future__ import annotations
from pathlib import Path
import numpy as np
MEAN = np.array([123.675, 116.28, 103.53], np.float32)[:, None, None]STD = np.array([58.395, 57.12, 57.375], np.float32)[:, None, None]
class MobileSAM: def __init__(self, folder, provider="cpu"): import onnxruntime as ort folder = Path(folder) if provider != "cpu" and hasattr(ort, "preload_dlls"): try: ort.preload_dlls() except Exception: pass so = ort.SessionOptions() so.log_severity_level = 3 pv = ["CPUExecutionProvider"] if provider == "cpu" else [ ("CUDAExecutionProvider", {"arena_extend_strategy": "kSameAsRequested"}), "CPUExecutionProvider"] self.s = {n: ort.InferenceSession(str(folder / f"{n}.onnx"), so, providers=pv) for n in ("encoder", "decoder")}
@staticmethod def _scale(h, w, long=1024): s = long / max(h, w) return int(h * s + 0.5), int(w * s + 0.5)
def embed(self, rgb): """rgb: H x W x 3 uint8 -> (embeddings, (H, W)).""" from PIL import Image H, W = rgb.shape[:2] nh, nw = self._scale(H, W) x = np.asarray(Image.fromarray(rgb).resize((nw, nh), Image.BILINEAR), np.float32).transpose(2, 0, 1) x = (x - MEAN) / STD x = np.pad(x, ((0, 0), (0, 1024 - nh), (0, 1024 - nw)))[None].astype(np.float32) return self.s["encoder"].run(None, {"image": x})[0], (H, W)
def _coords(self, xy, size): H, W = size nh, nw = self._scale(H, W) return np.asarray(xy, np.float32) * np.array([nw / W, nh / H], np.float32)
def _run(self, emb, size, coords, labels): out = self.s["decoder"].run(None, { "image_embeddings": emb, "point_coords": coords[None].astype(np.float32), "point_labels": np.asarray(labels, np.float32)[None], "mask_input": np.zeros((1, 1, 256, 256), np.float32), "has_mask_input": np.zeros(1, np.float32), "orig_im_size": np.asarray(size, np.float32)}) return out[0][0] > 0, out[1][0]
def point(self, emb, size, points, labels=None): """points [[x, y], ...] (label 1 foreground, 0 background) -> 3 masks [3, H, W] and their scores.""" lab = [1] * len(points) if labels is None else list(labels) c = np.concatenate([self._coords(points, size), np.zeros((1, 2), np.float32)]) # + the padding point m, s = self._run(emb, size, c, lab + [-1]) return m[1:], s[1:]
def box(self, emb, size, box): m, s = self._run(emb, size, self._coords(np.asarray(box).reshape(2, 2), size), [2, 3]) return m[0], s[0]
if __name__ == "__main__": import argparse from PIL import Image ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("image"); ap.add_argument("output") ap.add_argument("--point", type=float, nargs=2); ap.add_argument("--box", type=float, nargs=4) ap.add_argument("--dir", default=str(Path(__file__).resolve().parent)); ap.add_argument("--cuda", action="store_true") a = ap.parse_args() sam = MobileSAM(a.dir, "cuda" if a.cuda else "cpu") emb, size = sam.embed(np.array(Image.open(a.image).convert("RGB"))) out = {} if a.point: out["point_masks"], out["point_scores"] = sam.point(emb, size, [a.point]) if a.box: out["box_mask"], out["box_score"] = sam.box(emb, size, a.box) np.savez_compressed(a.output, **out)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586"""MobileSAM (the promptable segmenter of MobileSAM v2) with TensorRT engines: the same pipeline as pipeline.py (therepository's SamPredictor: longest side to 1024, SAM's mean / std, padded to 1024 x 1024; multimask point promptsgive masks 1-3, box prompts mask 0), with- encoder.engine: image [1, 3, 1024, 1024] -> image_embeddings [1, 256, 64, 64];- decoder.engine: SAM's ONNX decoder wrapper up to its low-resolution masks (image_embeddings, point_coords [1, N, 2], N 1-10, point_labels, mask_input, has_mask_input -> iou_predictions, low_res_masks [1, 4, 256, 256]). The wrapper's last step, resizing to the picture (SamOnnxModel.mask_postprocessing), needs the picture size as a shape tensor, which TensorRT can't take as a float input, so it is done here (OpenCV or numpy) with the same bilinear arithmetic.Needs numpy, Pillow, tensorrt-cu12 / tensorrt-lean-cu12 10.x and polygraphy; opencv-python makes the mask resize fast.
python fp16/pipeline_trt.py photo.jpg masks.npz --point 410 300 [--box x0 y0 x1 y1]"""
from __future__ import annotations
import sysfrom pathlib import Path
import numpy as np
HERE = Path(__file__).resolve().parentsys.path.insert(0, str(HERE))from pipeline import MobileSAM # noqa: E402from trt_runner import OrtLike # noqa: E402
def resize_bilinear(x, oh, ow): """torch.nn.functional.interpolate(x, (oh, ow), mode="bilinear", align_corners=False) for x [..., H, W]: OpenCV's INTER_LINEAR (the same half-pixel sampling, no antialiasing) when it is installed, else numpy.""" try: import cv2 flat = x.reshape(-1, *x.shape[-2:]) out = np.stack([cv2.resize(m, (ow, oh), interpolation=cv2.INTER_LINEAR) for m in flat]) return out.reshape(*x.shape[:-2], oh, ow) except ImportError: pass
def axis(n_in, n_out): s = (np.arange(n_out, dtype=np.float64) + 0.5) * (n_in / n_out) - 0.5 s = np.maximum(s, 0) i0 = np.minimum(np.floor(s).astype(np.int64), n_in - 1) i1 = np.minimum(i0 + 1, n_in - 1) w = (s - i0).astype(np.float32) return i0, i1, w h, w = x.shape[-2:] r0, r1, wr = axis(h, oh) c0, c1, wc = axis(w, ow) y = x[..., r0, :] * (1 - wr)[:, None] + x[..., r1, :] * wr[:, None] return y[..., c0] * (1 - wc) + y[..., c1] * wc
class MobileSAMTrt(MobileSAM): def __init__(self, folder=HERE): folder = Path(folder) self.s = {"encoder": OrtLike(folder / "encoder.engine", ["image_embeddings"]), "decoder": OrtLike(folder / "decoder.engine", ["iou_predictions", "low_res_masks"])}
def _run(self, emb, size, coords, labels): iou, low = self.s["decoder"].run(None, { "image_embeddings": emb, "point_coords": coords[None].astype(np.float32), "point_labels": np.asarray(labels, np.float32)[None], "mask_input": np.zeros((1, 1, 256, 256), np.float32), "has_mask_input": np.zeros(1, np.float32)}) H, W = size nh, nw = self._scale(H, W) m = resize_bilinear(low.astype(np.float32), 1024, 1024)[..., :nh, :nw] m = resize_bilinear(m, H, W) return m[0] > 0, iou[0]
if __name__ == "__main__": import argparse from PIL import Image ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("image"); ap.add_argument("output") ap.add_argument("--point", type=float, nargs=2); ap.add_argument("--box", type=float, nargs=4) a = ap.parse_args() p = MobileSAMTrt() rgb = np.asarray(Image.open(a.image).convert("RGB")) emb, size = p.embed(rgb) out = {} if a.point: out["point_masks"], out["point_scores"] = p.point(emb, size, [a.point]) if a.box: out["box_mask"], out["box_score"] = p.box(emb, size, a.box) np.savez_compressed(a.output, **out) print({k: v.shape for k, v in out.items()})12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485"""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
class OrtLike: """An engine behind onnxruntime's InferenceSession calls (run / get_inputs / get_outputs / get_providers), so a pipeline.py written for ONNX Runtime runs its graphs on TensorRT unchanged. Outputs come back in the order the ONNX graph listed them (pass `outputs`), else in the engine's order."""
def __init__(self, path, outputs=None): self.e = Engine(path) eng = self.e.engine names = [eng.get_tensor_name(i) for i in range(eng.num_io_tensors)] self.outs = list(outputs) if outputs else [n for n in names if n not in self.e.inputs]
def get_inputs(self): from types import SimpleNamespace return [SimpleNamespace(name=n) for n in self.e.inputs]
def get_outputs(self): from types import SimpleNamespace return [SimpleNamespace(name=n) for n in self.outs]
def get_providers(self): return ["TensorRT"]
def run(self, names, feed, run_options=None): out = self.e(feed) return [out[n] for n in (names or self.outs)].gitattributes+2
fp16/decoder.engineAdded+3
fp16/encoder.engineAdded+3
fp16/pipeline.pyAdded+89
fp16/pipeline_trt.pyAdded+86
fp16/trt_runner.pyAdded+85