jennyxue commited on
Commit
53a8cb3
·
verified ·
1 Parent(s): ac846f9

fp32 build of EfficientViT-SAM

Browse files
.gitattributes CHANGED
@@ -33,3 +33,5 @@ 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
+ fp32/decoder.engine filter=lfs diff=lfs merge=lfs -text
37
+ fp32/encoder.engine filter=lfs diff=lfs merge=lfs -text
fp32/decoder.engine ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a2e0a324e55b5530784f9add50f32cc07e4afe93a9599c2843a5c290d76e6120
3
+ size 75081796
fp32/encoder.engine ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:75711f129358d27db1ed30bd1b7c917cc596a439967ed74e6af1b6c60596f862
3
+ size 293555428
fp32/pipeline.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """EfficientViT-SAM L2 with ONNX Runtime: the EfficientViT-L2 image encoder and SAM's ONNX decoder wrapper as graphs,
2
+ numpy around them, following the repository's EfficientViTSamPredictor: the longest side resized to 512 (Pillow
3
+ bilinear), SAM's pixel mean / std, padded bottom-right to 512 x 512; prompt coordinates in the 1024 frame;
4
+ masks returned at the image size by the decoder (logits > 0). Multimask point prompts give masks 1-3, single-mask
5
+ (box) prompts mask 0, as SamPredictor does. Needs numpy, onnxruntime (or onnxruntime-gpu) and Pillow.
6
+
7
+ python fp16/pipeline.py photo.jpg masks.npz --point 410 300 [--box x0 y0 x1 y1] [--cuda]
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from pathlib import Path
13
+
14
+ import numpy as np
15
+
16
+ MEAN = np.array([123.675, 116.28, 103.53], np.float32)[:, None, None]
17
+ STD = np.array([58.395, 57.12, 57.375], np.float32)[:, None, None]
18
+
19
+
20
+ class EfficientViTSAM:
21
+ def __init__(self, folder, provider="cpu"):
22
+ import onnxruntime as ort
23
+ folder = Path(folder)
24
+ if provider != "cpu" and hasattr(ort, "preload_dlls"):
25
+ try:
26
+ ort.preload_dlls()
27
+ except Exception:
28
+ pass
29
+ so = ort.SessionOptions()
30
+ so.log_severity_level = 3
31
+ pv = ["CPUExecutionProvider"] if provider == "cpu" else [
32
+ ("CUDAExecutionProvider", {"arena_extend_strategy": "kSameAsRequested"}), "CPUExecutionProvider"]
33
+ self.s = {n: ort.InferenceSession(str(folder / f"{n}.onnx"), so, providers=pv) for n in ("encoder", "decoder")}
34
+
35
+ @staticmethod
36
+ def _scale(h, w, long=1024):
37
+ s = long / max(h, w)
38
+ return int(h * s + 0.5), int(w * s + 0.5)
39
+
40
+ def embed(self, rgb):
41
+ """rgb: H x W x 3 uint8 -> (embeddings, (H, W))."""
42
+ from PIL import Image
43
+ H, W = rgb.shape[:2]
44
+ nh, nw = self._scale(H, W, 512)
45
+ x = np.asarray(Image.fromarray(rgb).resize((nw, nh), Image.BILINEAR), np.float32).transpose(2, 0, 1)
46
+ x = (x - MEAN) / STD
47
+ x = np.pad(x, ((0, 0), (0, 512 - nh), (0, 512 - nw)))[None].astype(np.float32)
48
+ return self.s["encoder"].run(None, {"image": x})[0], (H, W)
49
+
50
+ def _coords(self, xy, size):
51
+ H, W = size
52
+ nh, nw = self._scale(H, W)
53
+ return np.asarray(xy, np.float32) * np.array([nw / W, nh / H], np.float32)
54
+
55
+ def _run(self, emb, size, coords, labels):
56
+ out = self.s["decoder"].run(None, {
57
+ "image_embeddings": emb, "point_coords": coords[None].astype(np.float32),
58
+ "point_labels": np.asarray(labels, np.float32)[None], "mask_input": np.zeros((1, 1, 256, 256), np.float32),
59
+ "has_mask_input": np.zeros(1, np.float32), "orig_im_size": np.asarray(size, np.float32)})
60
+ return out[0][0] > 0, out[1][0]
61
+
62
+ def point(self, emb, size, points, labels=None):
63
+ """points [[x, y], ...] (label 1 foreground, 0 background) -> 3 masks [3, H, W] and their scores."""
64
+ lab = [1] * len(points) if labels is None else list(labels)
65
+ c = np.concatenate([self._coords(points, size), np.zeros((1, 2), np.float32)]) # + the padding point
66
+ m, s = self._run(emb, size, c, lab + [-1])
67
+ return m[1:], s[1:]
68
+
69
+ def box(self, emb, size, box):
70
+ m, s = self._run(emb, size, self._coords(np.asarray(box).reshape(2, 2), size), [2, 3])
71
+ return m[0], s[0]
72
+
73
+
74
+ if __name__ == "__main__":
75
+ import argparse
76
+ from PIL import Image
77
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
78
+ ap.add_argument("image"); ap.add_argument("output")
79
+ ap.add_argument("--point", type=float, nargs=2); ap.add_argument("--box", type=float, nargs=4)
80
+ ap.add_argument("--dir", default=str(Path(__file__).resolve().parent)); ap.add_argument("--cuda", action="store_true")
81
+ a = ap.parse_args()
82
+ sam = EfficientViTSAM(a.dir, "cuda" if a.cuda else "cpu")
83
+ emb, size = sam.embed(np.array(Image.open(a.image).convert("RGB")))
84
+ out = {}
85
+ if a.point:
86
+ out["point_masks"], out["point_scores"] = sam.point(emb, size, [a.point])
87
+ if a.box:
88
+ out["box_mask"], out["box_score"] = sam.box(emb, size, a.box)
89
+ np.savez_compressed(a.output, **out)
fp32/pipeline_trt.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """EfficientViT-SAM (L0) with TensorRT engines: the same pipeline as pipeline.py (the repository's
2
+ EfficientViTSamPredictor: longest side to 512, SAM's mean / std, padded to 512 x 512, prompts in the 1024 frame;
3
+ multimask point prompts give masks 1-3, box prompts mask 0), with
4
+ - encoder.engine: image [1, 3, 512, 512] -> image_embeddings [1, 256, 64, 64];
5
+ - decoder.engine: SAM's ONNX decoder wrapper up to its low-resolution masks (image_embeddings, point_coords [1, N, 2],
6
+ N 1-10, point_labels, mask_input, has_mask_input -> iou_predictions, low_res_masks [1, 4, 256, 256]). The wrapper's
7
+ last step, resizing to the picture (SamOnnxModel.mask_postprocessing), needs the picture size as a shape tensor,
8
+ which TensorRT can't take as a float input, so it is done here (OpenCV or numpy) with the same bilinear arithmetic.
9
+ Needs numpy, Pillow, tensorrt-cu12 / tensorrt-lean-cu12 10.x and polygraphy; opencv-python makes the mask resize fast.
10
+
11
+ python fp32/pipeline_trt.py photo.jpg masks.npz --point 410 300 [--box x0 y0 x1 y1]
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import sys
17
+ from pathlib import Path
18
+
19
+ import numpy as np
20
+
21
+ HERE = Path(__file__).resolve().parent
22
+ sys.path.insert(0, str(HERE))
23
+ from pipeline import EfficientViTSAM # noqa: E402
24
+ from trt_runner import OrtLike # noqa: E402
25
+
26
+
27
+ def resize_bilinear(x, oh, ow):
28
+ """torch.nn.functional.interpolate(x, (oh, ow), mode="bilinear", align_corners=False) for x [..., H, W]: OpenCV's
29
+ INTER_LINEAR (the same half-pixel sampling, no antialiasing) when it is installed, else numpy."""
30
+ try:
31
+ import cv2
32
+ flat = x.reshape(-1, *x.shape[-2:])
33
+ out = np.stack([cv2.resize(m, (ow, oh), interpolation=cv2.INTER_LINEAR) for m in flat])
34
+ return out.reshape(*x.shape[:-2], oh, ow)
35
+ except ImportError:
36
+ pass
37
+
38
+ def axis(n_in, n_out):
39
+ s = (np.arange(n_out, dtype=np.float64) + 0.5) * (n_in / n_out) - 0.5
40
+ s = np.maximum(s, 0)
41
+ i0 = np.minimum(np.floor(s).astype(np.int64), n_in - 1)
42
+ i1 = np.minimum(i0 + 1, n_in - 1)
43
+ w = (s - i0).astype(np.float32)
44
+ return i0, i1, w
45
+ h, w = x.shape[-2:]
46
+ r0, r1, wr = axis(h, oh)
47
+ c0, c1, wc = axis(w, ow)
48
+ y = x[..., r0, :] * (1 - wr)[:, None] + x[..., r1, :] * wr[:, None]
49
+ return y[..., c0] * (1 - wc) + y[..., c1] * wc
50
+
51
+
52
+ class EfficientViTSAMTrt(EfficientViTSAM):
53
+ def __init__(self, folder=HERE):
54
+ folder = Path(folder)
55
+ self.s = {"encoder": OrtLike(folder / "encoder.engine", ["image_embeddings"]),
56
+ "decoder": OrtLike(folder / "decoder.engine", ["iou_predictions", "low_res_masks"])}
57
+
58
+ def _run(self, emb, size, coords, labels):
59
+ iou, low = self.s["decoder"].run(None, {
60
+ "image_embeddings": emb, "point_coords": coords[None].astype(np.float32),
61
+ "point_labels": np.asarray(labels, np.float32)[None], "mask_input": np.zeros((1, 1, 256, 256), np.float32),
62
+ "has_mask_input": np.zeros(1, np.float32)})
63
+ H, W = size
64
+ nh, nw = self._scale(H, W)
65
+ m = resize_bilinear(low.astype(np.float32), 1024, 1024)[..., :nh, :nw]
66
+ m = resize_bilinear(m, H, W)
67
+ return m[0] > 0, iou[0]
68
+
69
+
70
+ if __name__ == "__main__":
71
+ import argparse
72
+ from PIL import Image
73
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
74
+ ap.add_argument("image"); ap.add_argument("output")
75
+ ap.add_argument("--point", type=float, nargs=2); ap.add_argument("--box", type=float, nargs=4)
76
+ a = ap.parse_args()
77
+ p = EfficientViTSAMTrt()
78
+ rgb = np.asarray(Image.open(a.image).convert("RGB"))
79
+ emb, size = p.embed(rgb)
80
+ out = {}
81
+ if a.point:
82
+ out["point_masks"], out["point_scores"] = p.point(emb, size, [a.point])
83
+ if a.box:
84
+ out["box_mask"], out["box_score"] = p.box(emb, size, a.box)
85
+ np.savez_compressed(a.output, **out)
86
+ print({k: v.shape for k, v in out.items()})
fp32/trt_runner.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
59
+
60
+
61
+ class OrtLike:
62
+ """An engine behind onnxruntime's InferenceSession calls (run / get_inputs / get_outputs / get_providers), so a
63
+ pipeline.py written for ONNX Runtime runs its graphs on TensorRT unchanged. Outputs come back in the order the
64
+ ONNX graph listed them (pass `outputs`), else in the engine's order."""
65
+
66
+ def __init__(self, path, outputs=None):
67
+ self.e = Engine(path)
68
+ eng = self.e.engine
69
+ names = [eng.get_tensor_name(i) for i in range(eng.num_io_tensors)]
70
+ self.outs = list(outputs) if outputs else [n for n in names if n not in self.e.inputs]
71
+
72
+ def get_inputs(self):
73
+ from types import SimpleNamespace
74
+ return [SimpleNamespace(name=n) for n in self.e.inputs]
75
+
76
+ def get_outputs(self):
77
+ from types import SimpleNamespace
78
+ return [SimpleNamespace(name=n) for n in self.outs]
79
+
80
+ def get_providers(self):
81
+ return ["TensorRT"]
82
+
83
+ def run(self, names, feed, run_options=None):
84
+ out = self.e(feed)
85
+ return [out[n] for n in (names or self.outs)]