Skip to content

InferModel

InferModel Module

This module provides the InferModel class that allows loading, inference, and benchmark testing of models in a local environment. It supports detection and segmentation tasks, and utilizes various runtime backends including ONNXRuntime and TorchScript for model execution.

Classes:

Name Description
InferModel

A class for managing and interacting with local models.

Functions:

Name Description
__init__

Initializes the InferModel instance, loading the model, metadata, and setting up the runtime.

_read_metadata

Reads the model metadata from a JSON file.

_annotate

Annotates the input image with detection or segmentation results.

infer

Runs inference on an input image, with optional annotation.

benchmark

Benchmarks the model's inference performance over a specified number of iterations and input size.

InferModel #

Source code in focoos/infer/infer_model.py
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
class InferModel:
    def __init__(
        self,
        model_dir: Union[str, Path],
        runtime_type: Optional[RuntimeType] = None,
        device: Literal["cuda", "cpu", "auto"] = "auto",
    ):
        """
        Initialize a LocalModel instance.

        This class sets up a local model for inference by initializing the runtime environment,
        loading metadata, and preparing annotation utilities.

        Args:
            model_dir (Union[str, Path]): The path to the directory containing the model files.
            runtime_type (Optional[RuntimeTypes]): Specifies the runtime type to use for inference.
                Defaults to the value of `FOCOOS_CONFIG.runtime_type` if not provided.

        Raises:
            ValueError: If no runtime type is provided and `FOCOOS_CONFIG.runtime_type` is not set.
            FileNotFoundError: If the specified model directory does not exist.

        Attributes:
            model_dir (Union[str, Path]): Path to the model directory.
            metadata (ModelMetadata): Metadata information for the model.
            model_ref: Reference identifier for the model obtained from metadata.
            label_annotator (sv.LabelAnnotator): Utility for adding labels to the output,
                initialized with text padding and border radius.
            box_annotator (sv.BoxAnnotator): Utility for annotating bounding boxes.
            mask_annotator (sv.MaskAnnotator): Utility for annotating masks.
            runtime (ONNXRuntime): Inference runtime initialized with the specified runtime type,
                model path, metadata, and warmup iterations.

        The method verifies the existence of the model directory, reads the model metadata,
        and initializes the runtime for inference using the provided runtime type. Annotation
        utilities are also prepared for visualizing model outputs.
        """

        # Determine runtime type and model format
        runtime_type = runtime_type or FOCOOS_CONFIG.runtime_type
        extension = ModelExtension.from_runtime_type(runtime_type)
        if device == "auto":
            self.device = get_device_type()
        elif runtime_type == RuntimeType.ONNX_CPU:
            self.device = "cpu"
        else:
            self.device = device
        # Set model directory and path
        self.model_dir: Union[str, Path] = model_dir
        self.model_path = os.path.join(model_dir, f"model.{extension.value}")
        logger.debug(f"Runtime type: {runtime_type}, Loading model from {self.model_path}..")

        # Check if model path exists
        if not os.path.exists(self.model_path):
            raise FileNotFoundError(f"Model path not found: {self.model_path}")

        # Load metadata and set model reference
        # self.metadata: RemoteModelInfo = self._read_metadata()

        self.model_info: ModelInfo = self._read_model_info()

        try:
            from focoos.model_manager import ConfigManager

            model_config = ConfigManager.from_dict(self.model_info.model_family, self.model_info.config)
            self.processor = ProcessorManager.get_processor(
                self.model_info.model_family, model_config, self.model_info.im_size
            ).eval()
        except Exception as e:
            logger.error(f"Error creating model config: {e}")
            raise e

        # Initialize annotation utilities
        self.label_annotator = sv.LabelAnnotator(text_padding=10, border_radius=10)
        self.box_annotator = sv.BoxAnnotator()
        self.mask_annotator = sv.MaskAnnotator()

        # Load runtime for inference
        self.runtime: BaseRuntime = load_runtime(
            runtime_type=runtime_type,
            model_path=str(self.model_path),
            model_info=self.model_info,
            warmup_iter=FOCOOS_CONFIG.warmup_iter,
            device=self.device,
        )

    def _read_model_info(self) -> ModelInfo:
        """
        Reads the model info from a JSON file.
        """
        model_info_path = os.path.join(self.model_dir, "model_info.json")
        if not os.path.exists(model_info_path):
            raise FileNotFoundError(f"Model info file not found: {model_info_path}")
        return ModelInfo.from_json(model_info_path)

    def __call__(
        self, image: Union[bytes, str, Path, np.ndarray, Image.Image], threshold: float = 0.5, annotate: bool = False
    ) -> FocoosDetections:
        return self.infer(image, threshold, annotate)

    def infer(
        self,
        image: Union[bytes, str, Path, np.ndarray, Image.Image],
        threshold: float = 0.5,
        annotate: bool = False,
    ) -> FocoosDetections:
        """
        Perform inference on an input image and optionally return an annotated result.

        This method processes the input image, runs it through the model, and returns the detections.
        Optionally, it can also annotate the image with the detection results.

        Args:
            image: The input image to run inference on. Accepts a file path, bytes, PIL Image, or numpy array.
            threshold: Minimum confidence score for a detection to be included in the results. Default is 0.5.
            annotate: If True, annotate the image with detection results and include it in the output.

        Returns:
            FocoosDetections: An object containing the detection results, optional annotated image, and latency metrics.

        Raises:
            AssertionError: If the model runtime is not initialized.

        Usage:
            This method is intended for users who want to obtain detection results from a local model,
            with optional annotation for visualization or further processing.
        """
        assert self.runtime is not None, "Model is not deployed (locally)"

        t0 = perf_counter()
        im = image_loader(image)
        t1 = perf_counter()
        tensors, _ = self.processor.preprocess(inputs=im, device=self.device)
        # logger.debug(f"Input image size: {im.shape}")
        t2 = perf_counter()

        raw_detections = self.runtime(tensors)

        t3 = perf_counter()
        detections = self.processor.export_postprocess(
            raw_detections, im, threshold=threshold, class_names=self.model_info.classes
        )
        t4 = perf_counter()
        if annotate:
            skeleton = self.model_info.config.get("skeleton", None)
            detections[0].image = annotate_frame(
                im,
                detections[0],
                task=self.model_info.task,
                classes=self.model_info.classes,
                keypoints_skeleton=skeleton,
            )
        t5 = perf_counter()

        res = detections[0]  #!TODO  check for batching
        res.latency = InferLatency(
            imload=round(t1 - t0, 3),
            preprocess=round(t2 - t1, 3),
            inference=round(t3 - t2, 3),
            postprocess=round(t4 - t3, 3),
            annotate=round(t5 - t4, 3) if annotate else None,
        )

        res.infer_print()
        return res

    def benchmark(self, iterations: int = 50, size: Optional[Union[int, Tuple[int, int]]] = None) -> LatencyMetrics:
        """
        Benchmark the model's inference performance over multiple iterations.
        """
        if size is None:
            size = self.model_info.im_size
        if isinstance(size, int):
            size = (size, size)
        return self.runtime.benchmark(iterations, size)

    def end2end_benchmark(
        self, iterations: int = 50, size: Optional[Union[int, Tuple[int, int]]] = None
    ) -> LatencyMetrics:
        """
        Benchmark the model's inference performance over multiple iterations.

        Args:
            iterations (int): Number of iterations to run for benchmarking.
            size (int): The input size for each benchmark iteration.

        Returns:
            LatencyMetrics: Latency metrics including time taken for inference.

        Example:
            ```python
            from focoos import Focoos, LocalModel

            focoos = Focoos()
            model = focoos.get_local_model(model_ref="<model_ref>")
            metrics = model.end2end_benchmark(iterations=10, size=640)

            # Access latency metrics
            print(f"FPS: {metrics.fps}")
            print(f"Mean latency: {metrics.mean} ms")
            print(f"Engine: {metrics.engine}")
            print(f"Device: {metrics.device}")
            print(f"Input size: {metrics.im_size}x{metrics.im_size}")
            ```
        """
        if size is None:
            size = self.model_info.im_size
        if isinstance(size, int):
            size = (size, size)

        device = get_device_name()
        if self.runtime.__class__.__name__ == "ONNXRuntime":
            active_provider = self.runtime.active_provider or "cpu"  # type: ignore
            engine = f"onnx.{active_provider}"
            if active_provider in ["CPUExecutionProvider"]:
                device = get_cpu_name()
        else:
            engine = "torchscript"
            device = get_device_name()
        logger.info(f"⏱️ Benchmarking End-to-End latency on {device}, size: {size}x{size}..")

        np_input = (255 * np.random.random((size[0], size[1], 3))).astype(np.uint8)

        durations = []
        for step in range(iterations + 5):
            start = perf_counter()
            self.infer(np_input)
            end = perf_counter()

            if step >= 5:  # Skip first 5 iterations
                durations.append((end - start) * 1000)

        durations = np.array(durations)

        metrics = LatencyMetrics(
            fps=int(1000 / durations.mean()),
            engine=engine,
            mean=round(durations.mean().astype(float), 3),
            max=round(durations.max().astype(float), 3),
            min=round(durations.min().astype(float), 3),
            std=round(durations.std().astype(float), 3),
            im_size=size[0],  # FIXME: this is a hack to get the im_size as int, assuming it's a square
            device=device,
        )
        logger.info(f"🔥 FPS: {metrics.fps} Mean latency: {metrics.mean} ms ")
        return metrics

__init__(model_dir, runtime_type=None, device='auto') #

Initialize a LocalModel instance.

This class sets up a local model for inference by initializing the runtime environment, loading metadata, and preparing annotation utilities.

Parameters:

Name Type Description Default
model_dir Union[str, Path]

The path to the directory containing the model files.

required
runtime_type Optional[RuntimeTypes]

Specifies the runtime type to use for inference. Defaults to the value of FOCOOS_CONFIG.runtime_type if not provided.

None

Raises:

Type Description
ValueError

If no runtime type is provided and FOCOOS_CONFIG.runtime_type is not set.

FileNotFoundError

If the specified model directory does not exist.

Attributes:

Name Type Description
model_dir Union[str, Path]

Path to the model directory.

metadata ModelMetadata

Metadata information for the model.

model_ref ModelMetadata

Reference identifier for the model obtained from metadata.

label_annotator LabelAnnotator

Utility for adding labels to the output, initialized with text padding and border radius.

box_annotator BoxAnnotator

Utility for annotating bounding boxes.

mask_annotator MaskAnnotator

Utility for annotating masks.

runtime ONNXRuntime

Inference runtime initialized with the specified runtime type, model path, metadata, and warmup iterations.

The method verifies the existence of the model directory, reads the model metadata, and initializes the runtime for inference using the provided runtime type. Annotation utilities are also prepared for visualizing model outputs.

Source code in focoos/infer/infer_model.py
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
def __init__(
    self,
    model_dir: Union[str, Path],
    runtime_type: Optional[RuntimeType] = None,
    device: Literal["cuda", "cpu", "auto"] = "auto",
):
    """
    Initialize a LocalModel instance.

    This class sets up a local model for inference by initializing the runtime environment,
    loading metadata, and preparing annotation utilities.

    Args:
        model_dir (Union[str, Path]): The path to the directory containing the model files.
        runtime_type (Optional[RuntimeTypes]): Specifies the runtime type to use for inference.
            Defaults to the value of `FOCOOS_CONFIG.runtime_type` if not provided.

    Raises:
        ValueError: If no runtime type is provided and `FOCOOS_CONFIG.runtime_type` is not set.
        FileNotFoundError: If the specified model directory does not exist.

    Attributes:
        model_dir (Union[str, Path]): Path to the model directory.
        metadata (ModelMetadata): Metadata information for the model.
        model_ref: Reference identifier for the model obtained from metadata.
        label_annotator (sv.LabelAnnotator): Utility for adding labels to the output,
            initialized with text padding and border radius.
        box_annotator (sv.BoxAnnotator): Utility for annotating bounding boxes.
        mask_annotator (sv.MaskAnnotator): Utility for annotating masks.
        runtime (ONNXRuntime): Inference runtime initialized with the specified runtime type,
            model path, metadata, and warmup iterations.

    The method verifies the existence of the model directory, reads the model metadata,
    and initializes the runtime for inference using the provided runtime type. Annotation
    utilities are also prepared for visualizing model outputs.
    """

    # Determine runtime type and model format
    runtime_type = runtime_type or FOCOOS_CONFIG.runtime_type
    extension = ModelExtension.from_runtime_type(runtime_type)
    if device == "auto":
        self.device = get_device_type()
    elif runtime_type == RuntimeType.ONNX_CPU:
        self.device = "cpu"
    else:
        self.device = device
    # Set model directory and path
    self.model_dir: Union[str, Path] = model_dir
    self.model_path = os.path.join(model_dir, f"model.{extension.value}")
    logger.debug(f"Runtime type: {runtime_type}, Loading model from {self.model_path}..")

    # Check if model path exists
    if not os.path.exists(self.model_path):
        raise FileNotFoundError(f"Model path not found: {self.model_path}")

    # Load metadata and set model reference
    # self.metadata: RemoteModelInfo = self._read_metadata()

    self.model_info: ModelInfo = self._read_model_info()

    try:
        from focoos.model_manager import ConfigManager

        model_config = ConfigManager.from_dict(self.model_info.model_family, self.model_info.config)
        self.processor = ProcessorManager.get_processor(
            self.model_info.model_family, model_config, self.model_info.im_size
        ).eval()
    except Exception as e:
        logger.error(f"Error creating model config: {e}")
        raise e

    # Initialize annotation utilities
    self.label_annotator = sv.LabelAnnotator(text_padding=10, border_radius=10)
    self.box_annotator = sv.BoxAnnotator()
    self.mask_annotator = sv.MaskAnnotator()

    # Load runtime for inference
    self.runtime: BaseRuntime = load_runtime(
        runtime_type=runtime_type,
        model_path=str(self.model_path),
        model_info=self.model_info,
        warmup_iter=FOCOOS_CONFIG.warmup_iter,
        device=self.device,
    )

benchmark(iterations=50, size=None) #

Benchmark the model's inference performance over multiple iterations.

Source code in focoos/infer/infer_model.py
219
220
221
222
223
224
225
226
227
def benchmark(self, iterations: int = 50, size: Optional[Union[int, Tuple[int, int]]] = None) -> LatencyMetrics:
    """
    Benchmark the model's inference performance over multiple iterations.
    """
    if size is None:
        size = self.model_info.im_size
    if isinstance(size, int):
        size = (size, size)
    return self.runtime.benchmark(iterations, size)

end2end_benchmark(iterations=50, size=None) #

Benchmark the model's inference performance over multiple iterations.

Parameters:

Name Type Description Default
iterations int

Number of iterations to run for benchmarking.

50
size int

The input size for each benchmark iteration.

None

Returns:

Name Type Description
LatencyMetrics LatencyMetrics

Latency metrics including time taken for inference.

Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
from focoos import Focoos, LocalModel

focoos = Focoos()
model = focoos.get_local_model(model_ref="<model_ref>")
metrics = model.end2end_benchmark(iterations=10, size=640)

# Access latency metrics
print(f"FPS: {metrics.fps}")
print(f"Mean latency: {metrics.mean} ms")
print(f"Engine: {metrics.engine}")
print(f"Device: {metrics.device}")
print(f"Input size: {metrics.im_size}x{metrics.im_size}")
Source code in focoos/infer/infer_model.py
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
def end2end_benchmark(
    self, iterations: int = 50, size: Optional[Union[int, Tuple[int, int]]] = None
) -> LatencyMetrics:
    """
    Benchmark the model's inference performance over multiple iterations.

    Args:
        iterations (int): Number of iterations to run for benchmarking.
        size (int): The input size for each benchmark iteration.

    Returns:
        LatencyMetrics: Latency metrics including time taken for inference.

    Example:
        ```python
        from focoos import Focoos, LocalModel

        focoos = Focoos()
        model = focoos.get_local_model(model_ref="<model_ref>")
        metrics = model.end2end_benchmark(iterations=10, size=640)

        # Access latency metrics
        print(f"FPS: {metrics.fps}")
        print(f"Mean latency: {metrics.mean} ms")
        print(f"Engine: {metrics.engine}")
        print(f"Device: {metrics.device}")
        print(f"Input size: {metrics.im_size}x{metrics.im_size}")
        ```
    """
    if size is None:
        size = self.model_info.im_size
    if isinstance(size, int):
        size = (size, size)

    device = get_device_name()
    if self.runtime.__class__.__name__ == "ONNXRuntime":
        active_provider = self.runtime.active_provider or "cpu"  # type: ignore
        engine = f"onnx.{active_provider}"
        if active_provider in ["CPUExecutionProvider"]:
            device = get_cpu_name()
    else:
        engine = "torchscript"
        device = get_device_name()
    logger.info(f"⏱️ Benchmarking End-to-End latency on {device}, size: {size}x{size}..")

    np_input = (255 * np.random.random((size[0], size[1], 3))).astype(np.uint8)

    durations = []
    for step in range(iterations + 5):
        start = perf_counter()
        self.infer(np_input)
        end = perf_counter()

        if step >= 5:  # Skip first 5 iterations
            durations.append((end - start) * 1000)

    durations = np.array(durations)

    metrics = LatencyMetrics(
        fps=int(1000 / durations.mean()),
        engine=engine,
        mean=round(durations.mean().astype(float), 3),
        max=round(durations.max().astype(float), 3),
        min=round(durations.min().astype(float), 3),
        std=round(durations.std().astype(float), 3),
        im_size=size[0],  # FIXME: this is a hack to get the im_size as int, assuming it's a square
        device=device,
    )
    logger.info(f"🔥 FPS: {metrics.fps} Mean latency: {metrics.mean} ms ")
    return metrics

infer(image, threshold=0.5, annotate=False) #

Perform inference on an input image and optionally return an annotated result.

This method processes the input image, runs it through the model, and returns the detections. Optionally, it can also annotate the image with the detection results.

Parameters:

Name Type Description Default
image Union[bytes, str, Path, ndarray, Image]

The input image to run inference on. Accepts a file path, bytes, PIL Image, or numpy array.

required
threshold float

Minimum confidence score for a detection to be included in the results. Default is 0.5.

0.5
annotate bool

If True, annotate the image with detection results and include it in the output.

False

Returns:

Name Type Description
FocoosDetections FocoosDetections

An object containing the detection results, optional annotated image, and latency metrics.

Raises:

Type Description
AssertionError

If the model runtime is not initialized.

Usage

This method is intended for users who want to obtain detection results from a local model, with optional annotation for visualization or further processing.

Source code in focoos/infer/infer_model.py
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
def infer(
    self,
    image: Union[bytes, str, Path, np.ndarray, Image.Image],
    threshold: float = 0.5,
    annotate: bool = False,
) -> FocoosDetections:
    """
    Perform inference on an input image and optionally return an annotated result.

    This method processes the input image, runs it through the model, and returns the detections.
    Optionally, it can also annotate the image with the detection results.

    Args:
        image: The input image to run inference on. Accepts a file path, bytes, PIL Image, or numpy array.
        threshold: Minimum confidence score for a detection to be included in the results. Default is 0.5.
        annotate: If True, annotate the image with detection results and include it in the output.

    Returns:
        FocoosDetections: An object containing the detection results, optional annotated image, and latency metrics.

    Raises:
        AssertionError: If the model runtime is not initialized.

    Usage:
        This method is intended for users who want to obtain detection results from a local model,
        with optional annotation for visualization or further processing.
    """
    assert self.runtime is not None, "Model is not deployed (locally)"

    t0 = perf_counter()
    im = image_loader(image)
    t1 = perf_counter()
    tensors, _ = self.processor.preprocess(inputs=im, device=self.device)
    # logger.debug(f"Input image size: {im.shape}")
    t2 = perf_counter()

    raw_detections = self.runtime(tensors)

    t3 = perf_counter()
    detections = self.processor.export_postprocess(
        raw_detections, im, threshold=threshold, class_names=self.model_info.classes
    )
    t4 = perf_counter()
    if annotate:
        skeleton = self.model_info.config.get("skeleton", None)
        detections[0].image = annotate_frame(
            im,
            detections[0],
            task=self.model_info.task,
            classes=self.model_info.classes,
            keypoints_skeleton=skeleton,
        )
    t5 = perf_counter()

    res = detections[0]  #!TODO  check for batching
    res.latency = InferLatency(
        imload=round(t1 - t0, 3),
        preprocess=round(t2 - t1, 3),
        inference=round(t3 - t2, 3),
        postprocess=round(t4 - t3, 3),
        annotate=round(t5 - t4, 3) if annotate else None,
    )

    res.infer_print()
    return res