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
 50
 51
 52
 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
class InferModel:
    def __init__(
        self,
        model_dir: Union[str, Path],
        runtime_type: Optional[RuntimeType] = None,
    ):
        """
        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)

        # 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)
        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,
            str(self.model_path),
            self.model_info,
            FOCOOS_CONFIG.warmup_iter,
        )

    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: Optional[float] = None
    ) -> FocoosDetections:
        return self.infer(image, threshold)

    def infer(
        self,
        image: Union[bytes, str, Path, np.ndarray, Image.Image],
        threshold: Optional[float] = None,
    ) -> FocoosDetections:
        """
        Run inference on an input image and optionally annotate the results.

        Args:
            image (Union[bytes, str, Path, np.ndarray, Image.Image]): The input image to infer on.
                This can be a byte array, file path, or a PIL Image object, or a NumPy array representing the image.
            threshold (float, optional): The confidence threshold for detections. Defaults to 0.5.
                Detections with confidence scores below this threshold will be discarded.

        Returns:
            FocoosDetections: The detections from the inference, represented as a custom object (`FocoosDetections`).

        Raises:
            ValueError: If the model is not deployed locally (i.e., `self.runtime` is `None`).

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

            focoos = Focoos()
            model = focoos.get_local_model(model_ref="<model_ref>")
            detections = model.infer(image, threshold=0.5)
            ```
        """
        assert self.runtime is not None, "Model is not deployed (locally)"

        t0 = perf_counter()
        im1, im0 = image_preprocess(image)
        tensors, _ = self.processor.preprocess(inputs=im1, device="cuda", image_size=self.model_info.im_size)
        logger.debug(f"Input image size: {im0.shape}")
        t1 = perf_counter()

        raw_detections = self.runtime(tensors)

        t2 = perf_counter()
        detections = self.processor.export_postprocess(
            raw_detections, im0, threshold=threshold, class_names=self.model_info.classes
        )
        t3 = perf_counter()
        latency = {
            "inference": round(t2 - t1, 3),
            "preprocess": round(t1 - t0, 3),
            "postprocess": round(t3 - t2, 3),
        }
        res = detections[0]  #!TODO  check for batching
        res.latency = latency

        logger.debug(
            f"Found {len(res)} detections. Inference time: {(t2 - t1) * 1000:.0f}ms, preprocess: {(t1 - t0) * 1000:.0f}ms, postprocess: {(t3 - t2) * 1000:.0f}ms"
        )
        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)

        engine, device = self.runtime.get_info()
        logger.info(f"⏱️ Benchmarking 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(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) #

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
 51
 52
 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
def __init__(
    self,
    model_dir: Union[str, Path],
    runtime_type: Optional[RuntimeType] = None,
):
    """
    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)

    # 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)
    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,
        str(self.model_path),
        self.model_info,
        FOCOOS_CONFIG.warmup_iter,
    )

benchmark(iterations=50, size=None) #

Benchmark the model's inference performance over multiple iterations.

Source code in focoos/infer/infer_model.py
198
199
200
201
202
203
204
205
206
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
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
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)

    engine, device = self.runtime.get_info()
    logger.info(f"⏱️ Benchmarking 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(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=None) #

Run inference on an input image and optionally annotate the results.

Parameters:

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

The input image to infer on. This can be a byte array, file path, or a PIL Image object, or a NumPy array representing the image.

required
threshold float

The confidence threshold for detections. Defaults to 0.5. Detections with confidence scores below this threshold will be discarded.

None

Returns:

Name Type Description
FocoosDetections FocoosDetections

The detections from the inference, represented as a custom object (FocoosDetections).

Raises:

Type Description
ValueError

If the model is not deployed locally (i.e., self.runtime is None).

Example
1
2
3
4
5
from focoos import Focoos, LocalModel

focoos = Focoos()
model = focoos.get_local_model(model_ref="<model_ref>")
detections = model.infer(image, threshold=0.5)
Source code in focoos/infer/infer_model.py
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
def infer(
    self,
    image: Union[bytes, str, Path, np.ndarray, Image.Image],
    threshold: Optional[float] = None,
) -> FocoosDetections:
    """
    Run inference on an input image and optionally annotate the results.

    Args:
        image (Union[bytes, str, Path, np.ndarray, Image.Image]): The input image to infer on.
            This can be a byte array, file path, or a PIL Image object, or a NumPy array representing the image.
        threshold (float, optional): The confidence threshold for detections. Defaults to 0.5.
            Detections with confidence scores below this threshold will be discarded.

    Returns:
        FocoosDetections: The detections from the inference, represented as a custom object (`FocoosDetections`).

    Raises:
        ValueError: If the model is not deployed locally (i.e., `self.runtime` is `None`).

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

        focoos = Focoos()
        model = focoos.get_local_model(model_ref="<model_ref>")
        detections = model.infer(image, threshold=0.5)
        ```
    """
    assert self.runtime is not None, "Model is not deployed (locally)"

    t0 = perf_counter()
    im1, im0 = image_preprocess(image)
    tensors, _ = self.processor.preprocess(inputs=im1, device="cuda", image_size=self.model_info.im_size)
    logger.debug(f"Input image size: {im0.shape}")
    t1 = perf_counter()

    raw_detections = self.runtime(tensors)

    t2 = perf_counter()
    detections = self.processor.export_postprocess(
        raw_detections, im0, threshold=threshold, class_names=self.model_info.classes
    )
    t3 = perf_counter()
    latency = {
        "inference": round(t2 - t1, 3),
        "preprocess": round(t1 - t0, 3),
        "postprocess": round(t3 - t2, 3),
    }
    res = detections[0]  #!TODO  check for batching
    res.latency = latency

    logger.debug(
        f"Found {len(res)} detections. Inference time: {(t2 - t1) * 1000:.0f}ms, preprocess: {(t1 - t0) * 1000:.0f}ms, postprocess: {(t3 - t2) * 1000:.0f}ms"
    )
    return res