
Build precision variants of the SAM 2.1 encoder and Grounding DINO
Source:R/utils_dl_variants.R
pliman_build_model_variant.RdCreates alternative versions of the large foundation models used by
image_segment_dl() ("sam2.1", "persam", "grounded-sam") and stores them next to
the originals in pliman_model_dir(). The originals are never modified.
"sam2.1-encoder-int8"->sam2.1.encoder_int8.onnx: dynamic INT8 weights (28 MB instead of 109 MB). Select it withoptions(pliman.sam_encoder = "int8"). It is used only by CPU sessions."sam2.1-encoder-fp16"->sam2.1.encoder_fp16.onnx: FP16 weights with FP32 inputs/outputs (55 MB). Select it withoptions(pliman.sam_encoder = "fp16")."groundingdino-fp16"->groundingdino-tiny_fp16.onnx: FP16 Grounding DINO, built from the public FP16 export of the same model (onnx-community/grounding-dino-tiny-ONNX, about 360 MB download) with itsGridSampleoperators kept in FP32. It is picked automatically with the CUDA and TensorRT providers (seepliman_gpu_provider()), or explicitly withoptions(pliman.dino_model = "groundingdino-tiny_fp16.onnx").
Usage
pliman_build_model_variant(
variant = c("sam2.1-encoder-int8", "sam2.1-encoder-fp16", "groundingdino-fp16"),
dir = pliman_model_dir(),
overwrite = FALSE,
dino_fp16_url = NULL,
verbose = TRUE
)Arguments
- variant
One or more of
"sam2.1-encoder-int8","sam2.1-encoder-fp16","groundingdino-fp16".- dir
Model directory. Defaults to
pliman_model_dir().- overwrite
Logical. Rebuild variants that already exist. Defaults to
FALSE.- dino_fp16_url
Source of the FP16 Grounding DINO export.
- verbose
Logical. Show progress messages.
Measured effect (hardware dependent)
On an Intel i7 (12 threads) with a GTX 1650, where FP32 was the fastest SAM encoder everywhere:
| FP32 | INT8 | FP16 | |
| SAM encoder, CPU | 2.31 s | 2.31 s (mask IoU 0.995) | 5.75 s |
| SAM encoder, DirectML | 0.36 s | 38 s, wrong masks | 36.7 s |
| SAM encoder, CUDA | 0.39 s | 4.65 s | 1.52 s |
| Grounding DINO, CUDA | INT8: 3.2 s | 1.75 s | |
| Grounding DINO, DirectML | INT8: 0.8 s | 14.5 s |
INT8 accelerates only on CPUs with VNNI/AMX instructions (recent Intel/AMD), so it is
never used on the GPU (under DirectML it returned wrong masks). FP16 needs GPUs with
native half-precision throughput (NVIDIA Tensor Cores: RTX 20xx and newer, T4,
A-series); without them it can be many times slower because of casting. Measure on
your own machine before switching (for example timing image_segment_dl() after
onnx_clear_encoder_cache_cpp()).
Examples
if (FALSE) { # interactive()
library(pliman)
pliman_build_model_variant("sam2.1-encoder-int8")
options(pliman.sam_encoder = "int8")
img <- image_pliman("soybean_touch.jpg")
res <- image_segment_dl(img, model = "sam2.1", engine = "cpu", plot = FALSE)
options(pliman.sam_encoder = "fp32")
}