python_code
stringlengths 0
679k
| repo_name
stringlengths 9
41
| file_path
stringlengths 6
149
|
---|---|---|
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utility class for performing TensorRT image inference."""
import numpy as np
import tensorrt as trt
from nvidia_tao_deploy.inferencer.trt_inferencer import TRTInferencer
from nvidia_tao_deploy.inferencer.utils import allocate_buffers, do_inference
class LPRNetInferencer(TRTInferencer):
"""Manages TensorRT objects for model inference."""
def __init__(self, engine_path, input_shape=None, batch_size=None, data_format="channel_first"):
"""Initializes TensorRT objects needed for model inference.
Args:
engine_path (str): path where TensorRT engine should be stored
input_shape (tuple): (batch, channel, height, width) for dynamic shape engine
batch_size (int): batch size for dynamic shape engine
data_format (str): either channel_first or channel_last
"""
# Load TRT engine
super().__init__(engine_path)
self.max_batch_size = self.engine.max_batch_size
self.execute_v2 = False
# Execution context is needed for inference
self.context = None
# Allocate memory for multiple usage [e.g. multiple batch inference]
self._input_shape = []
for binding in range(self.engine.num_bindings):
if self.engine.binding_is_input(binding):
self._input_shape = self.engine.get_binding_shape(binding)[-3:]
assert len(self._input_shape) == 3, "Engine doesn't have valid input dimensions"
if data_format == "channel_first":
self.height = self._input_shape[1]
self.width = self._input_shape[2]
else:
self.height = self._input_shape[0]
self.width = self._input_shape[1]
# set binding_shape for dynamic input
if (input_shape is not None) or (batch_size is not None):
self.context = self.engine.create_execution_context()
if input_shape is not None:
self.context.set_binding_shape(0, input_shape)
self.max_batch_size = input_shape[0]
else:
self.context.set_binding_shape(0, [batch_size] + list(self._input_shape))
self.max_batch_size = batch_size
self.execute_v2 = True
# This allocates memory for network inputs/outputs on both CPU and GPU
self.inputs, self.outputs, self.bindings, self.stream = allocate_buffers(self.engine,
self.context)
if self.context is None:
self.context = self.engine.create_execution_context()
input_volume = trt.volume(self._input_shape)
self.numpy_array = np.zeros((self.max_batch_size, input_volume))
def infer(self, imgs):
"""Infers model on batch of same sized images resized to fit the model.
Args:
image_paths (str): paths to images, that will be packed into batch
and fed into model
"""
# Verify if the supplied batch size is not too big
max_batch_size = self.max_batch_size
actual_batch_size = len(imgs)
if actual_batch_size > max_batch_size:
raise ValueError(f"image_paths list bigger ({actual_batch_size}) than \
engine max batch size ({max_batch_size})")
self.numpy_array[:actual_batch_size] = imgs.reshape(actual_batch_size, -1)
# ...copy them into appropriate place into memory...
# (self.inputs was returned earlier by allocate_buffers())
np.copyto(self.inputs[0].host, self.numpy_array.ravel())
# ...fetch model outputs...
results = do_inference(
self.context, bindings=self.bindings, inputs=self.inputs,
outputs=self.outputs, stream=self.stream,
batch_size=max_batch_size,
execute_v2=self.execute_v2)
# ...and return results up to the actual batch size.
return [i.reshape(max_batch_size, -1)[:actual_batch_size] for i in results]
def __del__(self):
"""Clear things up on object deletion."""
# Clear session and buffer
if self.trt_runtime:
del self.trt_runtime
if self.context:
del self.context
if self.engine:
del self.engine
if self.stream:
del self.stream
# Loop through inputs and free inputs.
for inp in self.inputs:
inp.device.free()
# Loop through outputs and free them.
for out in self.outputs:
out.device.free()
| tao_deploy-main | nvidia_tao_deploy/cv/lprnet/inferencer.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""LPRNet TensorRT engine builder."""
import logging
import os
import sys
import onnx
import tensorrt as trt
from nvidia_tao_deploy.engine.builder import EngineBuilder
logging.basicConfig(format='%(asctime)s [TAO Toolkit] [%(levelname)s] %(name)s %(lineno)d: %(message)s',
level="INFO")
logger = logging.getLogger(__name__)
class LPRNetEngineBuilder(EngineBuilder):
"""Parses an ONNX graph and builds a TensorRT engine from it."""
def __init__(
self,
data_format="channels_first",
**kwargs
):
"""Init.
Args:
data_format (str): data_format.
"""
super().__init__(**kwargs)
self._data_format = data_format
def set_input_output_node_names(self):
"""Set input output node names."""
self._output_node_names = ["tf_op_layer_ArgMax", "tf_op_layer_Max"]
self._input_node_names = ["image_input"]
def get_onnx_input_dims(self, model_path):
"""Get input dimension of ONNX model."""
onnx_model = onnx.load(model_path)
onnx_inputs = onnx_model.graph.input
logger.info('List inputs:')
for i, inputs in enumerate(onnx_inputs):
logger.info('Input %s -> %s.', i, inputs.name)
logger.info('%s.', [i.dim_value for i in inputs.type.tensor_type.shape.dim][1:])
logger.info('%s.', [i.dim_value for i in inputs.type.tensor_type.shape.dim][0])
return [i.dim_value for i in inputs.type.tensor_type.shape.dim][:]
def create_network(self, model_path, file_format="onnx"):
"""Parse the UFF/ONNX graph and create the corresponding TensorRT network definition.
Args:
model_path: The path to the UFF/ONNX graph to load.
file_format: The file format of the decrypted etlt file (default: onnx).
"""
if file_format == "onnx":
logger.info("Parsing ONNX model")
self._input_dims = self.get_onnx_input_dims(model_path)
self.batch_size = self._input_dims[0]
self._input_dims = self._input_dims[1:]
network_flags = 1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)
network_flags = network_flags | (1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_PRECISION))
self.network = self.builder.create_network(network_flags)
self.parser = trt.OnnxParser(self.network, self.trt_logger)
model_path = os.path.realpath(model_path)
with open(model_path, "rb") as f:
if not self.parser.parse(f.read()):
logger.error("Failed to load ONNX file: %s", model_path)
for error in range(self.parser.num_errors):
logger.error(self.parser.get_error(error))
sys.exit(1)
inputs = [self.network.get_input(i) for i in range(self.network.num_inputs)]
outputs = [self.network.get_output(i) for i in range(self.network.num_outputs)]
logger.info("Network Description")
for input in inputs: # noqa pylint: disable=W0622
logger.info("Input '%s' with shape %s and dtype %s", input.name, input.shape, input.dtype)
for output in outputs:
logger.info("Output '%s' with shape %s and dtype %s", output.name, output.shape, output.dtype)
if self.batch_size <= 0: # dynamic batch size
logger.info("dynamic batch size handling")
opt_profile = self.builder.create_optimization_profile()
model_input = self.network.get_input(0)
input_shape = model_input.shape
input_name = model_input.name
real_shape_min = (self.min_batch_size, input_shape[1],
input_shape[2], input_shape[3])
real_shape_opt = (self.opt_batch_size, input_shape[1],
input_shape[2], input_shape[3])
real_shape_max = (self.max_batch_size, input_shape[1],
input_shape[2], input_shape[3])
opt_profile.set_shape(input=input_name,
min=real_shape_min,
opt=real_shape_opt,
max=real_shape_max)
self.config.add_optimization_profile(opt_profile)
else:
logger.info("Parsing UFF model")
raise NotImplementedError("UFF for LPRNet is not supported")
def create_engine(self, engine_path, precision,
calib_input=None, calib_cache=None, calib_num_images=5000,
calib_batch_size=8, calib_data_file=None):
"""Build the TensorRT engine and serialize it to disk.
Args:
engine_path: The path where to serialize the engine to.
precision: The datatype to use for the engine, either 'fp32', 'fp16' or 'int8'.
calib_input: The path to a directory holding the calibration images.
calib_cache: The path where to write the calibration cache to,
or if it already exists, load it from.
calib_num_images: The maximum number of images to use for calibration.
calib_batch_size: The batch size to use for the calibration process.
"""
engine_path = os.path.realpath(engine_path)
engine_dir = os.path.dirname(engine_path)
os.makedirs(engine_dir, exist_ok=True)
logger.debug("Building %s Engine in %s", precision, engine_path)
if self.batch_size is None:
self.batch_size = calib_batch_size
self.builder.max_batch_size = self.batch_size
if precision == "fp16":
if not self.builder.platform_has_fast_fp16:
logger.warning("FP16 is not supported natively on this platform/device")
else:
self.config.set_flag(trt.BuilderFlag.FP16)
elif precision == "int8":
raise NotImplementedError("INT8 is not supported for LPRNet!")
self._logger_info_IBuilderConfig()
with self.builder.build_engine(self.network, self.config) as engine, \
open(engine_path, "wb") as f:
logger.debug("Serializing engine to file: %s", engine_path)
f.write(engine.serialize())
def set_data_preprocessing_parameters(self, input_dims, image_mean=None):
"""Set data pre-processing parameters for the int8 calibration."""
num_channels = input_dims[0]
if num_channels == 3:
means = [0, 0, 0]
elif num_channels == 1:
means = [0]
else:
raise NotImplementedError(f"Invalid number of dimensions {num_channels}.")
self.preprocessing_arguments = {"scale": 1.0 / 255.0,
"means": means,
"flip_channel": True}
| tao_deploy-main | nvidia_tao_deploy/cv/lprnet/engine_builder.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""TAO Deploy LPRNet."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
| tao_deploy-main | nvidia_tao_deploy/cv/lprnet/__init__.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Helper function to decode ctc trained model's output."""
def decode_ctc_conf(pred,
classes,
blank_id):
"""Decode ctc trained model's output.
Return decoded license plate and confidence.
"""
pred_id = pred[0]
pred_conf = pred[1]
decoded_lp = []
decoded_conf = []
for idx_in_batch, seq in enumerate(pred_id):
seq_conf = pred_conf[idx_in_batch]
prev = seq[0]
tmp_seq = [prev]
tmp_conf = [seq_conf[0]]
for idx in range(1, len(seq)):
if seq[idx] != prev:
tmp_seq.append(seq[idx])
tmp_conf.append(seq_conf[idx])
prev = seq[idx]
lp = ""
output_conf = []
for index, i in enumerate(tmp_seq):
if i != blank_id:
lp += classes[i]
output_conf.append(tmp_conf[index])
decoded_lp.append(lp)
decoded_conf.append(output_conf)
return decoded_lp, decoded_conf
| tao_deploy-main | nvidia_tao_deploy/cv/lprnet/utils.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""LPRNet loader."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import cv2
from abc import ABC
import numpy as np
from nvidia_tao_deploy.cv.common.constants import VALID_IMAGE_EXTENSIONS
class LPRNetLoader(ABC):
"""LPRNet Dataloader."""
def __init__(self,
shape,
image_dirs,
label_dirs,
classes,
is_inference=False,
batch_size=10,
max_label_length=8,
dtype=None):
"""Init.
Args:
image_dirs (list): list of image directories.
label_dirs (list): list of label directories.
classes (list): list of classes
batch_size (int): size of the batch.
is_inference (bool): If True, no labels will be returned
image_mean (list): image mean used for preprocessing.
max_label_length (int): The maximum length of license plates in the dataset
dtype (str): data type to cast to
"""
assert len(image_dirs) == len(label_dirs), "Mismatch!"
self.image_paths = []
self.label_paths = []
self.is_inference = is_inference
for image_dir, label_dir in zip(image_dirs, label_dirs):
self._add_source(image_dir, label_dir)
self.image_paths = np.array(self.image_paths)
self.data_inds = np.arange(len(self.image_paths))
self.class_dict = {classes[index]: index for index in range(len(classes))}
self.classes = classes
self.max_label_length = max_label_length
self.num_channels, self.height, self.width = shape
self.batch_size = batch_size
self.n_samples = len(self.data_inds)
self.dtype = dtype
self.n_batches = int(len(self.image_paths) // self.batch_size)
assert self.n_batches > 0, "empty image dir or batch size too large!"
def _add_source(self, image_folder, label_folder):
"""Add image/label paths."""
img_files = os.listdir(image_folder)
if not self.is_inference:
label_files = set(os.listdir(label_folder))
else:
label_files = []
for img_file in img_files:
file_name, _ = os.path.splitext(img_file)
if img_file.lower().endswith(VALID_IMAGE_EXTENSIONS) and file_name + ".txt" in label_files:
self.image_paths.append(os.path.join(image_folder,
img_file))
self.label_paths.append(os.path.join(label_folder,
file_name + ".txt"))
elif img_file.lower().endswith(VALID_IMAGE_EXTENSIONS) and self.is_inference:
self.image_paths.append(os.path.join(image_folder,
img_file))
def __len__(self):
"""Get length of Sequence."""
return self.n_batches
def _load_gt_image(self, image_path):
"""Load GT image from file."""
read_flag = cv2.IMREAD_COLOR
if self.num_channels == 1:
read_flag = cv2.IMREAD_GRAYSCALE
img = cv2.imread(image_path, read_flag)
return img
def __iter__(self):
"""Iterate."""
self.n = 0
return self
def __next__(self):
"""Load a full batch."""
images = []
labels = []
if self.n < self.n_batches:
for idx in range(self.n * self.batch_size,
(self.n + 1) * self.batch_size):
image, label = self._get_single_processed_item(idx)
images.append(image)
labels.append(label)
self.n += 1
return self._batch_post_processing(images, labels)
raise StopIteration
def _batch_post_processing(self, images, labels):
"""Post processing for a batch."""
images = np.array(images)
# try to make labels a numpy array
is_make_array = True
x_shape = None
for x in labels:
if not isinstance(x, np.ndarray):
is_make_array = False
break
if x_shape is None:
x_shape = x.shape
elif x_shape != x.shape:
is_make_array = False
break
if is_make_array:
labels = np.array(labels)
return images, labels
def _get_single_processed_item(self, idx):
"""Load and process single image and its label."""
image, label = self._get_single_item_raw(idx)
image = self.preprocessing(image)
return image, label
def _get_single_item_raw(self, idx):
"""Load single image and its label.
Returns:
image (np.array): image object in original resolution
label (int): one-hot encoded class label
"""
image = self._load_gt_image(self.image_paths[self.data_inds[idx]])
if self.is_inference:
label = np.zeros((1, 7)) # Random array to label
else:
with open(self.label_paths[self.data_inds[idx]], "r", encoding="utf-8") as f:
label = f.readline().strip()
return image, label
def preprocessing(self, image):
"""The image preprocessor loads an image from disk and prepares it as needed for batching.
This includes padding, resizing, normalization, data type casting, and transposing.
Args:
image (np.array): The opencv image on disk to load.
Returns:
image (np.array): A numpy array holding the image sample, ready to be concatenated
into the rest of the batch
"""
image = cv2.resize(image, (self.width, self.height)) / 255.0
image = np.array(image, dtype=self.dtype)
if self.num_channels == 1:
image = image[..., np.newaxis]
# transpose image from HWC (0, 1, 2) to CHW (2, 0, 1)
image = image.transpose(2, 0, 1)
return image
| tao_deploy-main | nvidia_tao_deploy/cv/lprnet/dataloader.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nvidia_tao_deploy/cv/lprnet/proto/lpr_config.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor.FileDescriptor(
name='nvidia_tao_deploy/cv/lprnet/proto/lpr_config.proto',
package='',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\n2nvidia_tao_deploy/cv/lprnet/proto/lpr_config.proto\"\xa0\x01\n\x0cLPRNetConfig\x12\x17\n\x0fsequence_length\x18\x01 \x01(\r\x12\x14\n\x0chidden_units\x18\x02 \x01(\r\x12\x18\n\x10max_label_length\x18\x03 \x01(\r\x12\x0c\n\x04\x61rch\x18\x04 \x01(\t\x12\x0f\n\x07nlayers\x18\x05 \x01(\r\x12\x15\n\rfreeze_blocks\x18\x06 \x03(\r\x12\x11\n\tfreeze_bn\x18\x07 \x01(\x08\x62\x06proto3')
)
_LPRNETCONFIG = _descriptor.Descriptor(
name='LPRNetConfig',
full_name='LPRNetConfig',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='sequence_length', full_name='LPRNetConfig.sequence_length', index=0,
number=1, type=13, cpp_type=3, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='hidden_units', full_name='LPRNetConfig.hidden_units', index=1,
number=2, type=13, cpp_type=3, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='max_label_length', full_name='LPRNetConfig.max_label_length', index=2,
number=3, type=13, cpp_type=3, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='arch', full_name='LPRNetConfig.arch', index=3,
number=4, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='nlayers', full_name='LPRNetConfig.nlayers', index=4,
number=5, type=13, cpp_type=3, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='freeze_blocks', full_name='LPRNetConfig.freeze_blocks', index=5,
number=6, type=13, cpp_type=3, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='freeze_bn', full_name='LPRNetConfig.freeze_bn', index=6,
number=7, type=8, cpp_type=7, label=1,
has_default_value=False, default_value=False,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=55,
serialized_end=215,
)
DESCRIPTOR.message_types_by_name['LPRNetConfig'] = _LPRNETCONFIG
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
LPRNetConfig = _reflection.GeneratedProtocolMessageType('LPRNetConfig', (_message.Message,), dict(
DESCRIPTOR = _LPRNETCONFIG,
__module__ = 'nvidia_tao_deploy.cv.lprnet.proto.lpr_config_pb2'
# @@protoc_insertion_point(class_scope:LPRNetConfig)
))
_sym_db.RegisterMessage(LPRNetConfig)
# @@protoc_insertion_point(module_scope)
| tao_deploy-main | nvidia_tao_deploy/cv/lprnet/proto/lpr_config_pb2.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""TAO Deploy LPRNet Proto."""
| tao_deploy-main | nvidia_tao_deploy/cv/lprnet/proto/__init__.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nvidia_tao_deploy/cv/lprnet/proto/lp_sequence_dataset_config.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor.FileDescriptor(
name='nvidia_tao_deploy/cv/lprnet/proto/lp_sequence_dataset_config.proto',
package='',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\nBnvidia_tao_deploy/cv/lprnet/proto/lp_sequence_dataset_config.proto\"H\n\nDataSource\x12\x1c\n\x14label_directory_path\x18\x01 \x01(\t\x12\x1c\n\x14image_directory_path\x18\x02 \x01(\t\"\x80\x01\n\x0fLPDatasetConfig\x12!\n\x0c\x64\x61ta_sources\x18\x01 \x03(\x0b\x32\x0b.DataSource\x12\x1c\n\x14\x63haracters_list_file\x18\x02 \x01(\t\x12,\n\x17validation_data_sources\x18\x03 \x03(\x0b\x32\x0b.DataSourceb\x06proto3')
)
_DATASOURCE = _descriptor.Descriptor(
name='DataSource',
full_name='DataSource',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='label_directory_path', full_name='DataSource.label_directory_path', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='image_directory_path', full_name='DataSource.image_directory_path', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=70,
serialized_end=142,
)
_LPDATASETCONFIG = _descriptor.Descriptor(
name='LPDatasetConfig',
full_name='LPDatasetConfig',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='data_sources', full_name='LPDatasetConfig.data_sources', index=0,
number=1, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='characters_list_file', full_name='LPDatasetConfig.characters_list_file', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='validation_data_sources', full_name='LPDatasetConfig.validation_data_sources', index=2,
number=3, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=145,
serialized_end=273,
)
_LPDATASETCONFIG.fields_by_name['data_sources'].message_type = _DATASOURCE
_LPDATASETCONFIG.fields_by_name['validation_data_sources'].message_type = _DATASOURCE
DESCRIPTOR.message_types_by_name['DataSource'] = _DATASOURCE
DESCRIPTOR.message_types_by_name['LPDatasetConfig'] = _LPDATASETCONFIG
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
DataSource = _reflection.GeneratedProtocolMessageType('DataSource', (_message.Message,), dict(
DESCRIPTOR = _DATASOURCE,
__module__ = 'nvidia_tao_deploy.cv.lprnet.proto.lp_sequence_dataset_config_pb2'
# @@protoc_insertion_point(class_scope:DataSource)
))
_sym_db.RegisterMessage(DataSource)
LPDatasetConfig = _reflection.GeneratedProtocolMessageType('LPDatasetConfig', (_message.Message,), dict(
DESCRIPTOR = _LPDATASETCONFIG,
__module__ = 'nvidia_tao_deploy.cv.lprnet.proto.lp_sequence_dataset_config_pb2'
# @@protoc_insertion_point(class_scope:LPDatasetConfig)
))
_sym_db.RegisterMessage(LPDatasetConfig)
# @@protoc_insertion_point(module_scope)
| tao_deploy-main | nvidia_tao_deploy/cv/lprnet/proto/lp_sequence_dataset_config_pb2.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nvidia_tao_deploy/cv/lprnet/proto/augmentation_config.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor.FileDescriptor(
name='nvidia_tao_deploy/cv/lprnet/proto/augmentation_config.proto',
package='',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\n;nvidia_tao_deploy/cv/lprnet/proto/augmentation_config.proto\"\xf2\x01\n\x12\x41ugmentationConfig\x12\x14\n\x0coutput_width\x18\x01 \x01(\x05\x12\x15\n\routput_height\x18\x02 \x01(\x05\x12\x16\n\x0eoutput_channel\x18\x03 \x01(\x05\x12\x19\n\x11max_rotate_degree\x18\x04 \x01(\x05\x12\x13\n\x0brotate_prob\x18\x06 \x01(\x02\x12\x1c\n\x14gaussian_kernel_size\x18\x07 \x03(\x05\x12\x11\n\tblur_prob\x18\x08 \x01(\x02\x12\x1a\n\x12reverse_color_prob\x18\t \x01(\x02\x12\x1a\n\x12keep_original_prob\x18\x05 \x01(\x02\x62\x06proto3')
)
_AUGMENTATIONCONFIG = _descriptor.Descriptor(
name='AugmentationConfig',
full_name='AugmentationConfig',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='output_width', full_name='AugmentationConfig.output_width', index=0,
number=1, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='output_height', full_name='AugmentationConfig.output_height', index=1,
number=2, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='output_channel', full_name='AugmentationConfig.output_channel', index=2,
number=3, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='max_rotate_degree', full_name='AugmentationConfig.max_rotate_degree', index=3,
number=4, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='rotate_prob', full_name='AugmentationConfig.rotate_prob', index=4,
number=6, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='gaussian_kernel_size', full_name='AugmentationConfig.gaussian_kernel_size', index=5,
number=7, type=5, cpp_type=1, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='blur_prob', full_name='AugmentationConfig.blur_prob', index=6,
number=8, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='reverse_color_prob', full_name='AugmentationConfig.reverse_color_prob', index=7,
number=9, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='keep_original_prob', full_name='AugmentationConfig.keep_original_prob', index=8,
number=5, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=64,
serialized_end=306,
)
DESCRIPTOR.message_types_by_name['AugmentationConfig'] = _AUGMENTATIONCONFIG
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
AugmentationConfig = _reflection.GeneratedProtocolMessageType('AugmentationConfig', (_message.Message,), dict(
DESCRIPTOR = _AUGMENTATIONCONFIG,
__module__ = 'nvidia_tao_deploy.cv.lprnet.proto.augmentation_config_pb2'
# @@protoc_insertion_point(class_scope:AugmentationConfig)
))
_sym_db.RegisterMessage(AugmentationConfig)
# @@protoc_insertion_point(module_scope)
| tao_deploy-main | nvidia_tao_deploy/cv/lprnet/proto/augmentation_config_pb2.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nvidia_tao_deploy/cv/lprnet/proto/experiment.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
from nvidia_tao_deploy.cv.common.proto import training_config_pb2 as nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_training__config__pb2
from nvidia_tao_deploy.cv.lprnet.proto import lp_sequence_dataset_config_pb2 as nvidia__tao__deploy_dot_cv_dot_lprnet_dot_proto_dot_lp__sequence__dataset__config__pb2
from nvidia_tao_deploy.cv.lprnet.proto import augmentation_config_pb2 as nvidia__tao__deploy_dot_cv_dot_lprnet_dot_proto_dot_augmentation__config__pb2
from nvidia_tao_deploy.cv.lprnet.proto import eval_config_pb2 as nvidia__tao__deploy_dot_cv_dot_lprnet_dot_proto_dot_eval__config__pb2
from nvidia_tao_deploy.cv.lprnet.proto import lpr_config_pb2 as nvidia__tao__deploy_dot_cv_dot_lprnet_dot_proto_dot_lpr__config__pb2
DESCRIPTOR = _descriptor.FileDescriptor(
name='nvidia_tao_deploy/cv/lprnet/proto/experiment.proto',
package='',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\n2nvidia_tao_deploy/cv/lprnet/proto/experiment.proto\x1a\x37nvidia_tao_deploy/cv/common/proto/training_config.proto\x1a\x42nvidia_tao_deploy/cv/lprnet/proto/lp_sequence_dataset_config.proto\x1a;nvidia_tao_deploy/cv/lprnet/proto/augmentation_config.proto\x1a\x33nvidia_tao_deploy/cv/lprnet/proto/eval_config.proto\x1a\x32nvidia_tao_deploy/cv/lprnet/proto/lpr_config.proto\"\xec\x01\n\nExperiment\x12\x13\n\x0brandom_seed\x18\x01 \x01(\r\x12(\n\x0e\x64\x61taset_config\x18\x02 \x01(\x0b\x32\x10.LPDatasetConfig\x12\x30\n\x13\x61ugmentation_config\x18\x03 \x01(\x0b\x32\x13.AugmentationConfig\x12(\n\x0ftraining_config\x18\x04 \x01(\x0b\x32\x0f.TrainingConfig\x12 \n\x0b\x65val_config\x18\x05 \x01(\x0b\x32\x0b.EvalConfig\x12!\n\nlpr_config\x18\x06 \x01(\x0b\x32\r.LPRNetConfigb\x06proto3')
,
dependencies=[nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_training__config__pb2.DESCRIPTOR,nvidia__tao__deploy_dot_cv_dot_lprnet_dot_proto_dot_lp__sequence__dataset__config__pb2.DESCRIPTOR,nvidia__tao__deploy_dot_cv_dot_lprnet_dot_proto_dot_augmentation__config__pb2.DESCRIPTOR,nvidia__tao__deploy_dot_cv_dot_lprnet_dot_proto_dot_eval__config__pb2.DESCRIPTOR,nvidia__tao__deploy_dot_cv_dot_lprnet_dot_proto_dot_lpr__config__pb2.DESCRIPTOR,])
_EXPERIMENT = _descriptor.Descriptor(
name='Experiment',
full_name='Experiment',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='random_seed', full_name='Experiment.random_seed', index=0,
number=1, type=13, cpp_type=3, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='dataset_config', full_name='Experiment.dataset_config', index=1,
number=2, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='augmentation_config', full_name='Experiment.augmentation_config', index=2,
number=3, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='training_config', full_name='Experiment.training_config', index=3,
number=4, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='eval_config', full_name='Experiment.eval_config', index=4,
number=5, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='lpr_config', full_name='Experiment.lpr_config', index=5,
number=6, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=346,
serialized_end=582,
)
_EXPERIMENT.fields_by_name['dataset_config'].message_type = nvidia__tao__deploy_dot_cv_dot_lprnet_dot_proto_dot_lp__sequence__dataset__config__pb2._LPDATASETCONFIG
_EXPERIMENT.fields_by_name['augmentation_config'].message_type = nvidia__tao__deploy_dot_cv_dot_lprnet_dot_proto_dot_augmentation__config__pb2._AUGMENTATIONCONFIG
_EXPERIMENT.fields_by_name['training_config'].message_type = nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_training__config__pb2._TRAININGCONFIG
_EXPERIMENT.fields_by_name['eval_config'].message_type = nvidia__tao__deploy_dot_cv_dot_lprnet_dot_proto_dot_eval__config__pb2._EVALCONFIG
_EXPERIMENT.fields_by_name['lpr_config'].message_type = nvidia__tao__deploy_dot_cv_dot_lprnet_dot_proto_dot_lpr__config__pb2._LPRNETCONFIG
DESCRIPTOR.message_types_by_name['Experiment'] = _EXPERIMENT
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
Experiment = _reflection.GeneratedProtocolMessageType('Experiment', (_message.Message,), dict(
DESCRIPTOR = _EXPERIMENT,
__module__ = 'nvidia_tao_deploy.cv.lprnet.proto.experiment_pb2'
# @@protoc_insertion_point(class_scope:Experiment)
))
_sym_db.RegisterMessage(Experiment)
# @@protoc_insertion_point(module_scope)
| tao_deploy-main | nvidia_tao_deploy/cv/lprnet/proto/experiment_pb2.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""TAO Deploy Config Base Utilities."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import logging
from google.protobuf.text_format import Merge as merge_text_proto
from nvidia_tao_deploy.cv.lprnet.proto.experiment_pb2 import Experiment
logging.basicConfig(format='%(asctime)s [TAO Toolkit] [%(levelname)s] %(name)s %(lineno)d: %(message)s',
level="INFO")
logger = logging.getLogger(__name__)
def load_proto(config):
"""Load the experiment proto."""
proto = Experiment()
def _load_from_file(filename, pb2):
if not os.path.exists(filename):
raise IOError(f"Specfile not found at: {filename}")
with open(filename, "r", encoding="utf-8") as f:
merge_text_proto(f.read(), pb2)
_load_from_file(config, proto)
return proto
| tao_deploy-main | nvidia_tao_deploy/cv/lprnet/proto/utils.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nvidia_tao_deploy/cv/lprnet/proto/eval_config.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor.FileDescriptor(
name='nvidia_tao_deploy/cv/lprnet/proto/eval_config.proto',
package='',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\n3nvidia_tao_deploy/cv/lprnet/proto/eval_config.proto\"K\n\nEvalConfig\x12)\n!validation_period_during_training\x18\x01 \x01(\r\x12\x12\n\nbatch_size\x18\x02 \x01(\rb\x06proto3')
)
_EVALCONFIG = _descriptor.Descriptor(
name='EvalConfig',
full_name='EvalConfig',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='validation_period_during_training', full_name='EvalConfig.validation_period_during_training', index=0,
number=1, type=13, cpp_type=3, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='batch_size', full_name='EvalConfig.batch_size', index=1,
number=2, type=13, cpp_type=3, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=55,
serialized_end=130,
)
DESCRIPTOR.message_types_by_name['EvalConfig'] = _EVALCONFIG
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
EvalConfig = _reflection.GeneratedProtocolMessageType('EvalConfig', (_message.Message,), dict(
DESCRIPTOR = _EVALCONFIG,
__module__ = 'nvidia_tao_deploy.cv.lprnet.proto.eval_config_pb2'
# @@protoc_insertion_point(class_scope:EvalConfig)
))
_sym_db.RegisterMessage(EvalConfig)
# @@protoc_insertion_point(module_scope)
| tao_deploy-main | nvidia_tao_deploy/cv/lprnet/proto/eval_config_pb2.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""LPRNet convert etlt/onnx model to TRT engine."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import logging
import os
import tempfile
from nvidia_tao_deploy.cv.common.decorators import monitor_status
from nvidia_tao_deploy.cv.lprnet.engine_builder import LPRNetEngineBuilder
from nvidia_tao_deploy.utils.decoding import decode_model
logging.basicConfig(format='%(asctime)s [TAO Toolkit] [%(levelname)s] %(name)s %(lineno)d: %(message)s',
level="INFO")
logger = logging.getLogger(__name__)
DEFAULT_MAX_BATCH_SIZE = 1
DEFAULT_MIN_BATCH_SIZE = 1
DEFAULT_OPT_BATCH_SIZE = 1
@monitor_status(name='lprnet', mode='gen_trt_engine')
def main(args):
"""LPRNet convert."""
# decrypt etlt
tmp_onnx_file, file_format = decode_model(args.model_path, args.key)
if args.engine_file is not None or args.data_type == 'int8':
if args.engine_file is None:
engine_handle, temp_engine_path = tempfile.mkstemp()
os.close(engine_handle)
output_engine_path = temp_engine_path
else:
output_engine_path = args.engine_file
builder = LPRNetEngineBuilder(verbose=args.verbose,
workspace=args.max_workspace_size,
min_batch_size=args.min_batch_size,
opt_batch_size=args.opt_batch_size,
max_batch_size=args.max_batch_size)
builder.create_network(tmp_onnx_file, file_format)
builder.create_engine(
output_engine_path,
args.data_type)
logging.info("Export finished successfully.")
def build_command_line_parser(parser=None):
"""Build the command line parser using argparse.
Args:
parser (subparser): Provided from the wrapper script to build a chained
parser mechanism.
Returns:
parser
"""
if parser is None:
parser = argparse.ArgumentParser(prog='gen_trt_engine', description='Generate TRT engine of LPRNet model.')
parser.add_argument(
'-m',
'--model_path',
type=str,
required=True,
help='Path to a LPRNet .etlt or .onnx model file.'
)
parser.add_argument(
'-k',
'--key',
type=str,
required=False,
help='Key to save or load a .etlt model.')
parser.add_argument(
"--data_type",
type=str,
default="fp32",
help="Data type for the TensorRT export.",
choices=["fp32", "fp16"])
parser.add_argument(
"--engine_file",
type=str,
default=None,
help="Path to the exported TRT engine.")
parser.add_argument(
"--max_batch_size",
type=int,
default=DEFAULT_MAX_BATCH_SIZE,
help="Max batch size for TensorRT engine builder.")
parser.add_argument(
"--min_batch_size",
type=int,
default=DEFAULT_MIN_BATCH_SIZE,
help="Min batch size for TensorRT engine builder.")
parser.add_argument(
"--opt_batch_size",
type=int,
default=DEFAULT_OPT_BATCH_SIZE,
help="Opt batch size for TensorRT engine builder.")
parser.add_argument(
"--max_workspace_size",
type=int,
default=2,
help="Max memory workspace size to allow in Gb for TensorRT engine builder (default: 2).")
parser.add_argument(
"-v",
"--verbose",
action="store_true",
default=False,
help="Verbosity of the logger.")
parser.add_argument(
'-r',
'--results_dir',
type=str,
required=True,
default=None,
help='Output directory where the log is saved.'
)
return parser
def parse_command_line_arguments(args=None):
"""Simple function to parse command line arguments."""
parser = build_command_line_parser(args)
return parser.parse_args(args)
if __name__ == '__main__':
args = parse_command_line_arguments()
main(args)
| tao_deploy-main | nvidia_tao_deploy/cv/lprnet/scripts/gen_trt_engine.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""TAO Deploy LPRNet scripts module."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
| tao_deploy-main | nvidia_tao_deploy/cv/lprnet/scripts/__init__.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Standalone TensorRT inference."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import logging
import os
import numpy as np
from nvidia_tao_deploy.cv.common.decorators import monitor_status
from nvidia_tao_deploy.cv.lprnet.inferencer import LPRNetInferencer
from nvidia_tao_deploy.cv.lprnet.dataloader import LPRNetLoader
from nvidia_tao_deploy.cv.lprnet.utils import decode_ctc_conf
from nvidia_tao_deploy.cv.lprnet.proto.utils import load_proto
logging.getLogger('PIL').setLevel(logging.WARNING)
logging.basicConfig(format='%(asctime)s [TAO Toolkit] [%(levelname)s] %(name)s %(lineno)d: %(message)s',
level="INFO")
logger = logging.getLogger(__name__)
@monitor_status(name='lprnet', mode='inference')
def main(args):
"""LPRNet TRT inference."""
# Load from proto-based spec file
es = load_proto(args.experiment_spec)
data_format = "channels_first"
batch_size = args.batch_size if args.batch_size else es.eval_config.batch_size
max_label_length = es.lpr_config.max_label_length if es.lpr_config.max_label_length else 8
# Load image directories from validataion_data_sources
image_dirs = []
for data_source in es.dataset_config.validation_data_sources:
image_dirs.append(data_source.image_directory_path)
# Override the spec file if argument is passed
if args.image_dir:
image_dirs = [args.image_dir]
trt_infer = LPRNetInferencer(args.model_path, data_format=data_format, batch_size=batch_size)
characters_list_file = es.dataset_config.characters_list_file
if not os.path.exists(characters_list_file):
raise FileNotFoundError(f"{characters_list_file} does not exist!")
with open(characters_list_file, "r", encoding="utf-8") as f:
temp_list = f.readlines()
classes = [i.strip() for i in temp_list]
blank_id = len(classes)
dl = LPRNetLoader(
trt_infer._input_shape,
image_dirs,
[None],
classes=classes,
is_inference=True,
batch_size=batch_size,
max_label_length=max_label_length,
dtype=trt_infer.inputs[0].host.dtype)
for i, (imgs, _) in enumerate(dl):
y_pred = trt_infer.infer(imgs)
# decode prediction
decoded_lp, _ = decode_ctc_conf(y_pred,
classes=classes,
blank_id=blank_id)
image_paths = dl.image_paths[np.arange(args.batch_size) + args.batch_size * i]
for image_path, lp in zip(image_paths, decoded_lp):
print(f"{image_path}: {lp} ")
logging.info("Finished inference.")
def build_command_line_parser(parser=None):
"""Build the command line parser using argparse.
Args:
parser (subparser): Provided from the wrapper script to build a chained
parser mechanism.
Returns:
parser
"""
if parser is None:
parser = argparse.ArgumentParser(prog='eval', description='Evaluate with a LPRNet TRT model.')
parser.add_argument(
'-m',
'--model_path',
type=str,
required=True,
help='Path to the LPRNet TensorRT engine.'
)
parser.add_argument(
'-i',
'--image_dir',
type=str,
required=False,
default=None,
help='Input directory of images'
)
parser.add_argument(
'-e',
'--experiment_spec',
type=str,
required=True,
help='Path to the experiment spec file.'
)
parser.add_argument(
'-b',
'--batch_size',
type=int,
required=False,
default=1,
help='Batch size.'
)
parser.add_argument(
'-r',
'--results_dir',
type=str,
required=True,
default=None,
help='Output directory where the log is saved.'
)
return parser
def parse_command_line_arguments(args=None):
"""Simple function to parse command line arguments."""
parser = build_command_line_parser(args)
return parser.parse_args(args)
if __name__ == '__main__':
args = parse_command_line_arguments()
main(args)
| tao_deploy-main | nvidia_tao_deploy/cv/lprnet/scripts/inference.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Standalone TensorRT evaluation."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import logging
import os
import json
from tqdm.auto import tqdm
from nvidia_tao_deploy.cv.common.decorators import monitor_status
from nvidia_tao_deploy.cv.lprnet.inferencer import LPRNetInferencer
from nvidia_tao_deploy.cv.lprnet.dataloader import LPRNetLoader
from nvidia_tao_deploy.cv.lprnet.utils import decode_ctc_conf
from nvidia_tao_deploy.cv.lprnet.proto.utils import load_proto
logging.getLogger('PIL').setLevel(logging.WARNING)
logging.basicConfig(format='%(asctime)s [TAO Toolkit] [%(levelname)s] %(name)s %(lineno)d: %(message)s',
level="INFO")
logger = logging.getLogger(__name__)
@monitor_status(name='lprnet', mode='evaluation')
def main(args):
"""LPRNet TRT evaluation."""
# Load from proto-based spec file
es = load_proto(args.experiment_spec)
data_format = "channels_first"
batch_size = args.batch_size if args.batch_size else es.eval_config.batch_size
max_label_length = es.lpr_config.max_label_length if es.lpr_config.max_label_length else 8
# Load image and label directories from validataion_data_sources
image_dirs, label_dirs = [], []
for data_source in es.dataset_config.validation_data_sources:
image_dirs.append(data_source.image_directory_path)
label_dirs.append(data_source.label_directory_path)
trt_infer = LPRNetInferencer(args.model_path, data_format=data_format, batch_size=batch_size)
characters_list_file = es.dataset_config.characters_list_file
if not os.path.exists(characters_list_file):
raise FileNotFoundError(f"{characters_list_file} does not exist!")
with open(characters_list_file, "r", encoding="utf-8") as f:
temp_list = f.readlines()
classes = [i.strip() for i in temp_list]
blank_id = len(classes)
dl = LPRNetLoader(
trt_infer._input_shape,
image_dirs,
label_dirs,
classes=classes,
batch_size=batch_size,
max_label_length=max_label_length,
dtype=trt_infer.inputs[0].host.dtype)
correct = 0
for imgs, labels in tqdm(dl, total=len(dl), desc="Producing predictions"):
y_pred = trt_infer.infer(imgs)
# decode prediction
decoded_lp, _ = decode_ctc_conf(y_pred,
classes=classes,
blank_id=blank_id)
for idx, lp in enumerate(decoded_lp):
if lp == labels[idx]:
correct += 1
acc = float(correct) / float(dl.n_samples)
logger.info("Accuracy: %d / %d %f", correct, dl.n_samples, acc)
# Store evaluation results into JSON
eval_results = {"Accuracy": acc}
if args.results_dir is None:
results_dir = os.path.dirname(args.model_path)
else:
results_dir = args.results_dir
with open(os.path.join(results_dir, "results.json"), "w", encoding="utf-8") as f:
json.dump(eval_results, f)
logging.info("Finished evaluation.")
def build_command_line_parser(parser=None):
"""Build the command line parser using argparse.
Args:
parser (subparser): Provided from the wrapper script to build a chained
parser mechanism.
Returns:
parser
"""
if parser is None:
parser = argparse.ArgumentParser(prog='infer', description='Inference with a LPRNet TRT model.')
parser.add_argument(
'-m',
'--model_path',
type=str,
required=True,
help='Path to the LPRNet TensorRT engine.'
)
parser.add_argument(
'-e',
'--experiment_spec',
type=str,
required=True,
help='Path to the experiment spec file.'
)
parser.add_argument(
'-b',
'--batch_size',
type=int,
required=False,
default=1,
help='Batch size.'
)
parser.add_argument(
'-r',
'--results_dir',
type=str,
required=True,
default=None,
help='Output directory where the log is saved.'
)
return parser
def parse_command_line_arguments(args=None):
"""Simple function to parse command line arguments."""
parser = build_command_line_parser(args)
return parser.parse_args(args)
if __name__ == '__main__':
args = parse_command_line_arguments()
main(args)
| tao_deploy-main | nvidia_tao_deploy/cv/lprnet/scripts/evaluate.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""TAO Deploy command line wrapper to invoke CLI scripts."""
import sys
from nvidia_tao_deploy.cv.common.entrypoint.entrypoint_proto import launch_job
import nvidia_tao_deploy.cv.lprnet.scripts
def main():
"""Function to launch the job."""
launch_job(nvidia_tao_deploy.cv.lprnet.scripts, "lprnet", sys.argv[1:])
if __name__ == "__main__":
main()
| tao_deploy-main | nvidia_tao_deploy/cv/lprnet/entrypoint/lprnet.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Entrypoint module for lprnet."""
| tao_deploy-main | nvidia_tao_deploy/cv/lprnet/entrypoint/__init__.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utility class for performing TensorRT image inference."""
import numpy as np
import tensorrt as trt
from nvidia_tao_deploy.inferencer.trt_inferencer import TRTInferencer
from nvidia_tao_deploy.inferencer.utils import allocate_buffers, do_inference
def trt_output_process_fn(y_encoded, height, width):
"""function to process TRT model output."""
det_out, keep_k = y_encoded
result = []
for idx, k in enumerate(keep_k.reshape(-1)):
det = det_out[idx].reshape(-1, 7)[:k]
xmin = det[:, 3] * width
ymin = det[:, 4] * height
xmax = det[:, 5] * width
ymax = det[:, 6] * height
cls_id = det[:, 1]
conf = det[:, 2]
result.append(np.stack((cls_id, conf, xmin, ymin, xmax, ymax), axis=-1))
return result
class SSDInferencer(TRTInferencer):
"""Manages TensorRT objects for model inference."""
def __init__(self, engine_path, input_shape=None, batch_size=None, data_format="channel_first"):
"""Initializes TensorRT objects needed for model inference.
Args:
engine_path (str): path where TensorRT engine should be stored
input_shape (tuple): (batch, channel, height, width) for dynamic shape engine
batch_size (int): batch size for dynamic shape engine
data_format (str): either channel_first or channel_last
"""
# Load TRT engine
super().__init__(engine_path)
self.max_batch_size = self.engine.max_batch_size
self.execute_v2 = False
# Execution context is needed for inference
self.context = None
# Allocate memory for multiple usage [e.g. multiple batch inference]
self._input_shape = []
for binding in range(self.engine.num_bindings):
if self.engine.binding_is_input(binding):
binding_shape = self.engine.get_binding_shape(binding)
self._input_shape = binding_shape[-3:]
if len(binding_shape) == 4:
self.etlt_type = "onnx"
else:
self.etlt_type = "uff"
assert len(self._input_shape) == 3, "Engine doesn't have valid input dimensions"
if data_format == "channel_first":
self.height = self._input_shape[1]
self.width = self._input_shape[2]
else:
self.height = self._input_shape[0]
self.width = self._input_shape[1]
# do not override if the original model was uff
if (input_shape is not None or batch_size is not None) and (self.etlt_type != "uff"):
self.context = self.engine.create_execution_context()
if input_shape is not None:
self.context.set_binding_shape(0, input_shape)
self.max_batch_size = input_shape[0]
else:
self.context.set_binding_shape(0, [batch_size] + list(self._input_shape))
self.max_batch_size = batch_size
self.execute_v2 = True
# This allocates memory for network inputs/outputs on both CPU and GPU
self.inputs, self.outputs, self.bindings, self.stream = allocate_buffers(self.engine,
self.context)
if self.context is None:
self.context = self.engine.create_execution_context()
input_volume = trt.volume(self._input_shape)
self.numpy_array = np.zeros((self.max_batch_size, input_volume))
def infer(self, imgs):
"""Infers model on batch of same sized images resized to fit the model.
Args:
image_paths (str): paths to images, that will be packed into batch
and fed into model
"""
# Verify if the supplied batch size is not too big
max_batch_size = self.max_batch_size
actual_batch_size = len(imgs)
if actual_batch_size > max_batch_size:
raise ValueError(f"image_paths list bigger ({actual_batch_size}) than \
engine max batch size ({max_batch_size})")
self.numpy_array[:actual_batch_size] = imgs.reshape(actual_batch_size, -1)
# ...copy them into appropriate place into memory...
# (self.inputs was returned earlier by allocate_buffers())
np.copyto(self.inputs[0].host, self.numpy_array.ravel())
# ...fetch model outputs...
results = do_inference(
self.context, bindings=self.bindings, inputs=self.inputs,
outputs=self.outputs, stream=self.stream,
batch_size=max_batch_size,
execute_v2=self.execute_v2)
# ...and return results up to the actual batch size.
y_pred = [i.reshape(max_batch_size, -1)[:actual_batch_size] for i in results]
# Process TRT outputs to proper format
return trt_output_process_fn(y_pred, self.height, self.width)
def __del__(self):
"""Clear things up on object deletion."""
# Clear session and buffer
if self.trt_runtime:
del self.trt_runtime
if self.context:
del self.context
if self.engine:
del self.engine
if self.stream:
del self.stream
# Loop through inputs and free inputs.
for inp in self.inputs:
inp.device.free()
# Loop through outputs and free them.
for out in self.outputs:
out.device.free()
| tao_deploy-main | nvidia_tao_deploy/cv/ssd/inferencer.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""SSD TensorRT engine builder."""
import logging
import os
import random
from six.moves import xrange
import sys
import traceback
from tqdm import tqdm
try:
from uff.model.uff_pb2 import MetaGraph
except ImportError:
print("Loading uff directly from the package source code")
# @scha: To disable tensorflow import issue
import importlib
import types
import pkgutil
package = pkgutil.get_loader("uff")
# Returns __init__.py path
src_code = package.get_filename().replace('__init__.py', 'model/uff_pb2.py')
loader = importlib.machinery.SourceFileLoader('helper', src_code)
helper = types.ModuleType(loader.name)
loader.exec_module(helper)
MetaGraph = helper.MetaGraph
import numpy as np
import onnx
import tensorrt as trt
from nvidia_tao_deploy.engine.builder import EngineBuilder
from nvidia_tao_deploy.engine.tensorfile import TensorFile
from nvidia_tao_deploy.engine.tensorfile_calibrator import TensorfileCalibrator
from nvidia_tao_deploy.engine.utils import generate_random_tensorfile, prepare_chunk
logging.basicConfig(format='%(asctime)s [TAO Toolkit] [%(levelname)s] %(name)s %(lineno)d: %(message)s',
level="INFO")
logger = logging.getLogger(__name__)
class SSDEngineBuilder(EngineBuilder):
"""Parses an UFF graph and builds a TensorRT engine from it."""
def __init__(
self,
data_format="channels_first",
**kwargs
):
"""Init.
Args:
data_format (str): data_format.
"""
super().__init__(**kwargs)
self._data_format = data_format
def set_input_output_node_names(self):
"""Set input output node names."""
self._output_node_names = ["NMS"]
self._input_node_names = ["Input"]
def get_input_dims(self, model_path):
"""Get input dimension of UFF model."""
metagraph = MetaGraph()
with open(model_path, "rb") as f:
metagraph.ParseFromString(f.read())
for node in metagraph.graphs[0].nodes:
# if node.operation == "MarkOutput":
# print(f"Output: {node.inputs[0]}")
if node.operation == "Input":
return np.array(node.fields['shape'].i_list.val)[1:]
raise ValueError("Input dimension is not found in the UFF metagraph.")
def get_onnx_input_dims(self, model_path):
"""Get input dimension of ONNX model."""
onnx_model = onnx.load(model_path)
onnx_inputs = onnx_model.graph.input
logger.info('List inputs:')
for i, inputs in enumerate(onnx_inputs):
logger.info('Input %s -> %s.', i, inputs.name)
logger.info('%s.', [i.dim_value for i in inputs.type.tensor_type.shape.dim][1:])
logger.info('%s.', [i.dim_value for i in inputs.type.tensor_type.shape.dim][0])
return [i.dim_value for i in inputs.type.tensor_type.shape.dim][:]
def create_network(self, model_path, file_format="uff"):
"""Parse the ONNX graph and create the corresponding TensorRT network definition.
Args:
model_path: The path to the UFF/ONNX graph to load.
file_format: The file format of the decrypted etlt file (default: uff).
"""
if file_format == "uff":
self.network = self.builder.create_network()
self.parser = trt.UffParser()
self.set_input_output_node_names()
in_tensor_name = self._input_node_names[0]
self._input_dims = self.get_input_dims(model_path)
input_dict = {in_tensor_name: self._input_dims}
for key, value in input_dict.items():
if self._data_format == "channels_first":
self.parser.register_input(key, value, trt.UffInputOrder(0))
else:
self.parser.register_input(key, value, trt.UffInputOrder(1))
for name in self._output_node_names:
self.parser.register_output(name)
self.builder.max_batch_size = self.max_batch_size
try:
assert self.parser.parse(model_path, self.network, trt.DataType.FLOAT)
except AssertionError as e:
logger.error("Failed to parse UFF File")
_, _, tb = sys.exc_info()
traceback.print_tb(tb) # Fixed format
tb_info = traceback.extract_tb(tb)
_, line, _, text = tb_info[-1]
raise AssertionError(
f"UFF parsing failed on line {line} in statement {text}"
) from e
else:
logger.info("Parsing ONNX model")
self._input_dims = self.get_onnx_input_dims(model_path)
self.batch_size = self._input_dims[0]
self._input_dims = self._input_dims[1:]
network_flags = (1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH))
self.network = self.builder.create_network(network_flags)
self.parser = trt.OnnxParser(self.network, self.trt_logger)
model_path = os.path.realpath(model_path)
with open(model_path, "rb") as f:
if not self.parser.parse(f.read()):
logger.error("Failed to load ONNX file: %s", model_path)
for error in range(self.parser.num_errors):
logger.error(self.parser.get_error(error))
sys.exit(1)
inputs = [self.network.get_input(i) for i in range(self.network.num_inputs)]
outputs = [self.network.get_output(i) for i in range(self.network.num_outputs)]
logger.info("Network Description")
for input in inputs: # noqa pylint: disable=W0622
logger.info("Input '%s' with shape %s and dtype %s", input.name, input.shape, input.dtype)
for output in outputs:
logger.info("Output '%s' with shape %s and dtype %s", output.name, output.shape, output.dtype)
if self.batch_size <= 0: # dynamic batch size
logger.info("dynamic batch size handling")
opt_profile = self.builder.create_optimization_profile()
model_input = self.network.get_input(0)
input_shape = model_input.shape
input_name = model_input.name
real_shape_min = (self.min_batch_size, input_shape[1],
input_shape[2], input_shape[3])
real_shape_opt = (self.opt_batch_size, input_shape[1],
input_shape[2], input_shape[3])
real_shape_max = (self.max_batch_size, input_shape[1],
input_shape[2], input_shape[3])
opt_profile.set_shape(input=input_name,
min=real_shape_min,
opt=real_shape_opt,
max=real_shape_max)
self.config.add_optimization_profile(opt_profile)
def set_calibrator(self,
inputs=None,
calib_cache=None,
calib_input=None,
calib_num_images=5000,
calib_batch_size=8,
calib_data_file=None,
image_mean=None):
"""Simple function to set an Tensorfile based int8 calibrator.
Args:
calib_data_file: Path to the TensorFile. If the tensorfile doesn't exist
at this path, then one is created with either n_batches
of random tensors, images from the file in calib_input of dimensions
(batch_size,) + (input_dims).
calib_input: The path to a directory holding the calibration images.
calib_cache: The path where to write the calibration cache to,
or if it already exists, load it from.
calib_num_images: The maximum number of images to use for calibration.
calib_batch_size: The batch size to use for the calibration process.
image_mean: Image mean per channel.
Returns:
No explicit returns.
"""
logger.info("Calibrating using TensorfileCalibrator")
n_batches = calib_num_images // calib_batch_size
if not os.path.exists(calib_data_file):
self.generate_tensor_file(calib_data_file,
calib_input,
self._input_dims,
n_batches=n_batches,
batch_size=calib_batch_size,
image_mean=image_mean)
self.config.int8_calibrator = TensorfileCalibrator(calib_data_file,
calib_cache,
n_batches,
calib_batch_size)
def generate_tensor_file(self, data_file_name,
calibration_images_dir,
input_dims, n_batches=10,
batch_size=1, image_mean=None):
"""Generate calibration Tensorfile for int8 calibrator.
This function generates a calibration tensorfile from a directory of images, or dumps
n_batches of random numpy arrays of shape (batch_size,) + (input_dims).
Args:
data_file_name (str): Path to the output tensorfile to be saved.
calibration_images_dir (str): Path to the images to generate a tensorfile from.
input_dims (list): Input shape in CHW order.
n_batches (int): Number of batches to be saved.
batch_size (int): Number of images per batch.
image_mean (list): Image mean per channel.
Returns:
No explicit returns.
"""
if not os.path.exists(calibration_images_dir):
logger.info("Generating a tensorfile with random tensor images. This may work well as "
"a profiling tool, however, it may result in inaccurate results at "
"inference. Please generate a tensorfile using the tlt-int8-tensorfile, "
"or provide a custom directory of images for best performance.")
generate_random_tensorfile(data_file_name,
input_dims,
n_batches=n_batches,
batch_size=batch_size)
else:
# Preparing the list of images to be saved.
num_images = n_batches * batch_size
valid_image_ext = ['jpg', 'jpeg', 'png']
image_list = [os.path.join(calibration_images_dir, image)
for image in os.listdir(calibration_images_dir)
if image.split('.')[-1] in valid_image_ext]
if len(image_list) < num_images:
raise ValueError('Not enough number of images provided:'
f' {len(image_list)} < {num_images}')
image_idx = random.sample(xrange(len(image_list)), num_images)
self.set_data_preprocessing_parameters(input_dims, image_mean)
# Writing out processed dump.
with TensorFile(data_file_name, 'w') as f:
for chunk in tqdm(image_idx[x:x + batch_size] for x in xrange(0, len(image_idx),
batch_size)):
dump_data = prepare_chunk(chunk, image_list,
image_width=input_dims[2],
image_height=input_dims[1],
channels=input_dims[0],
batch_size=batch_size,
**self.preprocessing_arguments)
f.write(dump_data)
f.closed
def set_data_preprocessing_parameters(self, input_dims, image_mean=None):
"""Set data pre-processing parameters for the int8 calibration."""
num_channels = input_dims[0]
if num_channels == 3:
if not image_mean:
means = [103.939, 116.779, 123.68]
else:
assert len(image_mean) == 3, "Image mean should have 3 values for RGB inputs."
means = image_mean
elif num_channels == 1:
if not image_mean:
means = [117.3786]
else:
assert len(image_mean) == 1, "Image mean should have 1 value for grayscale inputs."
means = image_mean
else:
raise NotImplementedError(
f"Invalid number of dimensions {num_channels}.")
self.preprocessing_arguments = {"scale": 1.0,
"means": means,
"flip_channel": True}
| tao_deploy-main | nvidia_tao_deploy/cv/ssd/engine_builder.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""TAO Deploy SSD."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
| tao_deploy-main | nvidia_tao_deploy/cv/ssd/__init__.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""SSD loader."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from PIL import Image
from nvidia_tao_deploy.dataloader.kitti import KITTILoader
class SSDKITTILoader(KITTILoader):
"""SSD Dataloader."""
def __init__(self,
keep_aspect_ratio=False,
**kwargs):
"""Init.
Args:
keep_aspect_ratio (bool): keep aspect ratio of the image.
"""
super().__init__(**kwargs)
self.keep_aspect_ratio = keep_aspect_ratio
def preprocessing(self, image, label):
"""The image preprocessor loads an image from disk and prepares it as needed for batching.
This includes padding, resizing, normalization, data type casting, and transposing.
Args:
image (PIL.image): The Pillow image on disk to load.
label (np.array): labels
Returns:
image (np.array): A numpy array holding the image sample, ready to be concatenated
into the rest of the batch
label (np.array): labels
"""
def resize_pad(image, pad_color=(0, 0, 0)):
"""Resize and Pad.
A subroutine to implement padding and resizing. This will resize the image to fit
fully within the input size, and pads the remaining bottom-right portions with
the value provided.
Args:
image (PIL.Image): The PIL image object
pad_color (list): The RGB values to use for the padded area. Default: Black/Zeros.
Returns:
pad (PIL.Image): The PIL image object already padded and cropped,
scale (list): the resize scale used.
"""
width, height = image.size
width_scale = width / self.width
height_scale = height / self.height
if not self.keep_aspect_ratio:
image = image.resize(
(self.width, self.height),
resample=Image.BILINEAR)
return image, [height_scale, width_scale]
scale = 1.0 / max(width_scale, height_scale)
image = image.resize(
(round(width * scale), round(height * scale)),
resample=Image.BILINEAR)
if self.num_channels == 1:
pad = Image.new("L", (self.width, self.height))
pad.paste(0, [0, 0, self.width, self.height])
else:
pad = Image.new("RGB", (self.width, self.height))
pad.paste(pad_color, [0, 0, self.width, self.height])
pad.paste(image)
return pad, [scale, scale]
image, scale = resize_pad(image, (124, 116, 104))
image = np.asarray(image, dtype=self.dtype)
# Handle Grayscale
if self.num_channels == 1:
image = np.expand_dims(image, axis=2)
label[:, 2] /= scale[1]
label[:, 3] /= scale[0]
label[:, 4] /= scale[1]
label[:, 5] /= scale[0]
# Round
label = np.round(label, decimals=0)
# Filter out invalid labels
label = self._filter_invalid_labels(label)
return image, label
| tao_deploy-main | nvidia_tao_deploy/cv/ssd/dataloader.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""TAO Deploy SSD Proto."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
| tao_deploy-main | nvidia_tao_deploy/cv/ssd/proto/__init__.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nvidia_tao_deploy/cv/ssd/proto/augmentation_config.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor.FileDescriptor(
name='nvidia_tao_deploy/cv/ssd/proto/augmentation_config.proto',
package='',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\n8nvidia_tao_deploy/cv/ssd/proto/augmentation_config.proto\"\xcd\x03\n\x12\x41ugmentationConfig\x12\x14\n\x0coutput_width\x18\x01 \x01(\x05\x12\x15\n\routput_height\x18\x02 \x01(\x05\x12\x16\n\x0eoutput_channel\x18\x03 \x01(\x05\x12\x1d\n\x15random_crop_min_scale\x18\x04 \x01(\x02\x12\x1d\n\x15random_crop_max_scale\x18\x05 \x01(\x02\x12\x1a\n\x12random_crop_min_ar\x18\x06 \x01(\x02\x12\x1a\n\x12random_crop_max_ar\x18\x07 \x01(\x02\x12\x1a\n\x12zoom_out_min_scale\x18\x08 \x01(\x02\x12\x1a\n\x12zoom_out_max_scale\x18\t \x01(\x02\x12\x12\n\nbrightness\x18\n \x01(\x05\x12\x10\n\x08\x63ontrast\x18\x0b \x01(\x02\x12\x12\n\nsaturation\x18\x0c \x01(\x02\x12\x0b\n\x03hue\x18\r \x01(\x05\x12\x13\n\x0brandom_flip\x18\x0e \x01(\x02\x12\x36\n\nimage_mean\x18\x0f \x03(\x0b\x32\".AugmentationConfig.ImageMeanEntry\x1a\x30\n\x0eImageMeanEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\x02:\x02\x38\x01\x62\x06proto3')
)
_AUGMENTATIONCONFIG_IMAGEMEANENTRY = _descriptor.Descriptor(
name='ImageMeanEntry',
full_name='AugmentationConfig.ImageMeanEntry',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='key', full_name='AugmentationConfig.ImageMeanEntry.key', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='value', full_name='AugmentationConfig.ImageMeanEntry.value', index=1,
number=2, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=_b('8\001'),
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=474,
serialized_end=522,
)
_AUGMENTATIONCONFIG = _descriptor.Descriptor(
name='AugmentationConfig',
full_name='AugmentationConfig',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='output_width', full_name='AugmentationConfig.output_width', index=0,
number=1, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='output_height', full_name='AugmentationConfig.output_height', index=1,
number=2, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='output_channel', full_name='AugmentationConfig.output_channel', index=2,
number=3, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='random_crop_min_scale', full_name='AugmentationConfig.random_crop_min_scale', index=3,
number=4, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='random_crop_max_scale', full_name='AugmentationConfig.random_crop_max_scale', index=4,
number=5, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='random_crop_min_ar', full_name='AugmentationConfig.random_crop_min_ar', index=5,
number=6, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='random_crop_max_ar', full_name='AugmentationConfig.random_crop_max_ar', index=6,
number=7, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='zoom_out_min_scale', full_name='AugmentationConfig.zoom_out_min_scale', index=7,
number=8, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='zoom_out_max_scale', full_name='AugmentationConfig.zoom_out_max_scale', index=8,
number=9, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='brightness', full_name='AugmentationConfig.brightness', index=9,
number=10, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='contrast', full_name='AugmentationConfig.contrast', index=10,
number=11, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='saturation', full_name='AugmentationConfig.saturation', index=11,
number=12, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='hue', full_name='AugmentationConfig.hue', index=12,
number=13, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='random_flip', full_name='AugmentationConfig.random_flip', index=13,
number=14, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='image_mean', full_name='AugmentationConfig.image_mean', index=14,
number=15, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[_AUGMENTATIONCONFIG_IMAGEMEANENTRY, ],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=61,
serialized_end=522,
)
_AUGMENTATIONCONFIG_IMAGEMEANENTRY.containing_type = _AUGMENTATIONCONFIG
_AUGMENTATIONCONFIG.fields_by_name['image_mean'].message_type = _AUGMENTATIONCONFIG_IMAGEMEANENTRY
DESCRIPTOR.message_types_by_name['AugmentationConfig'] = _AUGMENTATIONCONFIG
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
AugmentationConfig = _reflection.GeneratedProtocolMessageType('AugmentationConfig', (_message.Message,), dict(
ImageMeanEntry = _reflection.GeneratedProtocolMessageType('ImageMeanEntry', (_message.Message,), dict(
DESCRIPTOR = _AUGMENTATIONCONFIG_IMAGEMEANENTRY,
__module__ = 'nvidia_tao_deploy.cv.ssd.proto.augmentation_config_pb2'
# @@protoc_insertion_point(class_scope:AugmentationConfig.ImageMeanEntry)
))
,
DESCRIPTOR = _AUGMENTATIONCONFIG,
__module__ = 'nvidia_tao_deploy.cv.ssd.proto.augmentation_config_pb2'
# @@protoc_insertion_point(class_scope:AugmentationConfig)
))
_sym_db.RegisterMessage(AugmentationConfig)
_sym_db.RegisterMessage(AugmentationConfig.ImageMeanEntry)
_AUGMENTATIONCONFIG_IMAGEMEANENTRY._options = None
# @@protoc_insertion_point(module_scope)
| tao_deploy-main | nvidia_tao_deploy/cv/ssd/proto/augmentation_config_pb2.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nvidia_tao_deploy/cv/ssd/proto/experiment.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
from nvidia_tao_deploy.cv.ssd.proto import augmentation_config_pb2 as nvidia__tao__deploy_dot_cv_dot_ssd_dot_proto_dot_augmentation__config__pb2
from nvidia_tao_deploy.cv.common.proto import detection_sequence_dataset_config_pb2 as nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_detection__sequence__dataset__config__pb2
from nvidia_tao_deploy.cv.common.proto import training_config_pb2 as nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_training__config__pb2
from nvidia_tao_deploy.cv.common.proto import nms_config_pb2 as nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_nms__config__pb2
from nvidia_tao_deploy.cv.ssd.proto import eval_config_pb2 as nvidia__tao__deploy_dot_cv_dot_ssd_dot_proto_dot_eval__config__pb2
from nvidia_tao_deploy.cv.ssd.proto import ssd_config_pb2 as nvidia__tao__deploy_dot_cv_dot_ssd_dot_proto_dot_ssd__config__pb2
DESCRIPTOR = _descriptor.FileDescriptor(
name='nvidia_tao_deploy/cv/ssd/proto/experiment.proto',
package='',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\n/nvidia_tao_deploy/cv/ssd/proto/experiment.proto\x1a\x38nvidia_tao_deploy/cv/ssd/proto/augmentation_config.proto\x1aInvidia_tao_deploy/cv/common/proto/detection_sequence_dataset_config.proto\x1a\x37nvidia_tao_deploy/cv/common/proto/training_config.proto\x1a\x32nvidia_tao_deploy/cv/common/proto/nms_config.proto\x1a\x30nvidia_tao_deploy/cv/ssd/proto/eval_config.proto\x1a/nvidia_tao_deploy/cv/ssd/proto/ssd_config.proto\"\xb7\x02\n\nExperiment\x12\x13\n\x0brandom_seed\x18\x01 \x01(\r\x12&\n\x0e\x64\x61taset_config\x18\x02 \x01(\x0b\x32\x0e.DatasetConfig\x12\x30\n\x13\x61ugmentation_config\x18\x03 \x01(\x0b\x32\x13.AugmentationConfig\x12(\n\x0ftraining_config\x18\x04 \x01(\x0b\x32\x0f.TrainingConfig\x12 \n\x0b\x65val_config\x18\x05 \x01(\x0b\x32\x0b.EvalConfig\x12\x1e\n\nnms_config\x18\x06 \x01(\x0b\x32\n.NMSConfig\x12 \n\nssd_config\x18\x07 \x01(\x0b\x32\n.SSDConfigH\x00\x12!\n\x0b\x64ssd_config\x18\x08 \x01(\x0b\x32\n.SSDConfigH\x00\x42\t\n\x07networkb\x06proto3')
,
dependencies=[nvidia__tao__deploy_dot_cv_dot_ssd_dot_proto_dot_augmentation__config__pb2.DESCRIPTOR,nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_detection__sequence__dataset__config__pb2.DESCRIPTOR,nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_training__config__pb2.DESCRIPTOR,nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_nms__config__pb2.DESCRIPTOR,nvidia__tao__deploy_dot_cv_dot_ssd_dot_proto_dot_eval__config__pb2.DESCRIPTOR,nvidia__tao__deploy_dot_cv_dot_ssd_dot_proto_dot_ssd__config__pb2.DESCRIPTOR,])
_EXPERIMENT = _descriptor.Descriptor(
name='Experiment',
full_name='Experiment',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='random_seed', full_name='Experiment.random_seed', index=0,
number=1, type=13, cpp_type=3, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='dataset_config', full_name='Experiment.dataset_config', index=1,
number=2, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='augmentation_config', full_name='Experiment.augmentation_config', index=2,
number=3, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='training_config', full_name='Experiment.training_config', index=3,
number=4, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='eval_config', full_name='Experiment.eval_config', index=4,
number=5, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='nms_config', full_name='Experiment.nms_config', index=5,
number=6, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='ssd_config', full_name='Experiment.ssd_config', index=6,
number=7, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='dssd_config', full_name='Experiment.dssd_config', index=7,
number=8, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
_descriptor.OneofDescriptor(
name='network', full_name='Experiment.network',
index=0, containing_type=None, fields=[]),
],
serialized_start=393,
serialized_end=704,
)
_EXPERIMENT.fields_by_name['dataset_config'].message_type = nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_detection__sequence__dataset__config__pb2._DATASETCONFIG
_EXPERIMENT.fields_by_name['augmentation_config'].message_type = nvidia__tao__deploy_dot_cv_dot_ssd_dot_proto_dot_augmentation__config__pb2._AUGMENTATIONCONFIG
_EXPERIMENT.fields_by_name['training_config'].message_type = nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_training__config__pb2._TRAININGCONFIG
_EXPERIMENT.fields_by_name['eval_config'].message_type = nvidia__tao__deploy_dot_cv_dot_ssd_dot_proto_dot_eval__config__pb2._EVALCONFIG
_EXPERIMENT.fields_by_name['nms_config'].message_type = nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_nms__config__pb2._NMSCONFIG
_EXPERIMENT.fields_by_name['ssd_config'].message_type = nvidia__tao__deploy_dot_cv_dot_ssd_dot_proto_dot_ssd__config__pb2._SSDCONFIG
_EXPERIMENT.fields_by_name['dssd_config'].message_type = nvidia__tao__deploy_dot_cv_dot_ssd_dot_proto_dot_ssd__config__pb2._SSDCONFIG
_EXPERIMENT.oneofs_by_name['network'].fields.append(
_EXPERIMENT.fields_by_name['ssd_config'])
_EXPERIMENT.fields_by_name['ssd_config'].containing_oneof = _EXPERIMENT.oneofs_by_name['network']
_EXPERIMENT.oneofs_by_name['network'].fields.append(
_EXPERIMENT.fields_by_name['dssd_config'])
_EXPERIMENT.fields_by_name['dssd_config'].containing_oneof = _EXPERIMENT.oneofs_by_name['network']
DESCRIPTOR.message_types_by_name['Experiment'] = _EXPERIMENT
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
Experiment = _reflection.GeneratedProtocolMessageType('Experiment', (_message.Message,), dict(
DESCRIPTOR = _EXPERIMENT,
__module__ = 'nvidia_tao_deploy.cv.ssd.proto.experiment_pb2'
# @@protoc_insertion_point(class_scope:Experiment)
))
_sym_db.RegisterMessage(Experiment)
# @@protoc_insertion_point(module_scope)
| tao_deploy-main | nvidia_tao_deploy/cv/ssd/proto/experiment_pb2.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""TAO Deploy Config Base Utilities."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from google.protobuf.text_format import Merge as merge_text_proto
from nvidia_tao_deploy.cv.ssd.proto.experiment_pb2 import Experiment
def load_proto(config):
"""Load the experiment proto."""
proto = Experiment()
def _load_from_file(filename, pb2):
if not os.path.exists(filename):
raise IOError(f"Specfile not found at: {filename}")
with open(filename, "r", encoding="utf-8") as f:
merge_text_proto(f.read(), pb2)
_load_from_file(config, proto)
return proto
| tao_deploy-main | nvidia_tao_deploy/cv/ssd/proto/utils.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nvidia_tao_deploy/cv/ssd/proto/ssd_config.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor.FileDescriptor(
name='nvidia_tao_deploy/cv/ssd/proto/ssd_config.proto',
package='',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\n/nvidia_tao_deploy/cv/ssd/proto/ssd_config.proto\"\xa6\x03\n\tSSDConfig\x12\x15\n\raspect_ratios\x18\x01 \x01(\t\x12\x1c\n\x14\x61spect_ratios_global\x18\x02 \x01(\t\x12\x0e\n\x06scales\x18\x03 \x01(\t\x12\x11\n\tmin_scale\x18\x04 \x01(\x02\x12\x11\n\tmax_scale\x18\x05 \x01(\x02\x12\x19\n\x11two_boxes_for_ar1\x18\x06 \x01(\x08\x12\r\n\x05steps\x18\x07 \x01(\t\x12\x12\n\nclip_boxes\x18\x08 \x01(\x08\x12\x11\n\tvariances\x18\t \x01(\t\x12\x0f\n\x07offsets\x18\n \x01(\t\x12\x12\n\nmean_color\x18\x0b \x01(\t\x12\x0c\n\x04\x61rch\x18\x0c \x01(\t\x12\x0f\n\x07nlayers\x18\r \x01(\r\x12\x19\n\x11pred_num_channels\x18\x0e \x01(\r\x12\r\n\x05\x61lpha\x18\x0f \x01(\x02\x12\x15\n\rneg_pos_ratio\x18\x10 \x01(\x02\x12\x16\n\x0epos_iou_thresh\x18\x11 \x01(\x02\x12\x16\n\x0eneg_iou_thresh\x18\x14 \x01(\x02\x12\x15\n\rfreeze_blocks\x18\x12 \x03(\r\x12\x11\n\tfreeze_bn\x18\x13 \x01(\x08\x62\x06proto3')
)
_SSDCONFIG = _descriptor.Descriptor(
name='SSDConfig',
full_name='SSDConfig',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='aspect_ratios', full_name='SSDConfig.aspect_ratios', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='aspect_ratios_global', full_name='SSDConfig.aspect_ratios_global', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='scales', full_name='SSDConfig.scales', index=2,
number=3, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='min_scale', full_name='SSDConfig.min_scale', index=3,
number=4, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='max_scale', full_name='SSDConfig.max_scale', index=4,
number=5, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='two_boxes_for_ar1', full_name='SSDConfig.two_boxes_for_ar1', index=5,
number=6, type=8, cpp_type=7, label=1,
has_default_value=False, default_value=False,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='steps', full_name='SSDConfig.steps', index=6,
number=7, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='clip_boxes', full_name='SSDConfig.clip_boxes', index=7,
number=8, type=8, cpp_type=7, label=1,
has_default_value=False, default_value=False,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='variances', full_name='SSDConfig.variances', index=8,
number=9, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='offsets', full_name='SSDConfig.offsets', index=9,
number=10, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='mean_color', full_name='SSDConfig.mean_color', index=10,
number=11, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='arch', full_name='SSDConfig.arch', index=11,
number=12, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='nlayers', full_name='SSDConfig.nlayers', index=12,
number=13, type=13, cpp_type=3, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='pred_num_channels', full_name='SSDConfig.pred_num_channels', index=13,
number=14, type=13, cpp_type=3, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='alpha', full_name='SSDConfig.alpha', index=14,
number=15, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='neg_pos_ratio', full_name='SSDConfig.neg_pos_ratio', index=15,
number=16, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='pos_iou_thresh', full_name='SSDConfig.pos_iou_thresh', index=16,
number=17, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='neg_iou_thresh', full_name='SSDConfig.neg_iou_thresh', index=17,
number=20, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='freeze_blocks', full_name='SSDConfig.freeze_blocks', index=18,
number=18, type=13, cpp_type=3, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='freeze_bn', full_name='SSDConfig.freeze_bn', index=19,
number=19, type=8, cpp_type=7, label=1,
has_default_value=False, default_value=False,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=52,
serialized_end=474,
)
DESCRIPTOR.message_types_by_name['SSDConfig'] = _SSDCONFIG
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
SSDConfig = _reflection.GeneratedProtocolMessageType('SSDConfig', (_message.Message,), dict(
DESCRIPTOR = _SSDCONFIG,
__module__ = 'nvidia_tao_deploy.cv.ssd.proto.ssd_config_pb2'
# @@protoc_insertion_point(class_scope:SSDConfig)
))
_sym_db.RegisterMessage(SSDConfig)
# @@protoc_insertion_point(module_scope)
| tao_deploy-main | nvidia_tao_deploy/cv/ssd/proto/ssd_config_pb2.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nvidia_tao_deploy/cv/ssd/proto/eval_config.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor.FileDescriptor(
name='nvidia_tao_deploy/cv/ssd/proto/eval_config.proto',
package='',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\n0nvidia_tao_deploy/cv/ssd/proto/eval_config.proto\"\xe2\x01\n\nEvalConfig\x12)\n!validation_period_during_training\x18\x01 \x01(\r\x12\x33\n\x16\x61verage_precision_mode\x18\x02 \x01(\x0e\x32\x13.EvalConfig.AP_MODE\x12\x12\n\nbatch_size\x18\x03 \x01(\r\x12\x1e\n\x16matching_iou_threshold\x18\x04 \x01(\x02\x12\x1a\n\x12visualize_pr_curve\x18\x05 \x01(\x08\"$\n\x07\x41P_MODE\x12\n\n\x06SAMPLE\x10\x00\x12\r\n\tINTEGRATE\x10\x01\x62\x06proto3')
)
_EVALCONFIG_AP_MODE = _descriptor.EnumDescriptor(
name='AP_MODE',
full_name='EvalConfig.AP_MODE',
filename=None,
file=DESCRIPTOR,
values=[
_descriptor.EnumValueDescriptor(
name='SAMPLE', index=0, number=0,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='INTEGRATE', index=1, number=1,
serialized_options=None,
type=None),
],
containing_type=None,
serialized_options=None,
serialized_start=243,
serialized_end=279,
)
_sym_db.RegisterEnumDescriptor(_EVALCONFIG_AP_MODE)
_EVALCONFIG = _descriptor.Descriptor(
name='EvalConfig',
full_name='EvalConfig',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='validation_period_during_training', full_name='EvalConfig.validation_period_during_training', index=0,
number=1, type=13, cpp_type=3, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='average_precision_mode', full_name='EvalConfig.average_precision_mode', index=1,
number=2, type=14, cpp_type=8, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='batch_size', full_name='EvalConfig.batch_size', index=2,
number=3, type=13, cpp_type=3, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='matching_iou_threshold', full_name='EvalConfig.matching_iou_threshold', index=3,
number=4, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='visualize_pr_curve', full_name='EvalConfig.visualize_pr_curve', index=4,
number=5, type=8, cpp_type=7, label=1,
has_default_value=False, default_value=False,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
_EVALCONFIG_AP_MODE,
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=53,
serialized_end=279,
)
_EVALCONFIG.fields_by_name['average_precision_mode'].enum_type = _EVALCONFIG_AP_MODE
_EVALCONFIG_AP_MODE.containing_type = _EVALCONFIG
DESCRIPTOR.message_types_by_name['EvalConfig'] = _EVALCONFIG
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
EvalConfig = _reflection.GeneratedProtocolMessageType('EvalConfig', (_message.Message,), dict(
DESCRIPTOR = _EVALCONFIG,
__module__ = 'nvidia_tao_deploy.cv.ssd.proto.eval_config_pb2'
# @@protoc_insertion_point(class_scope:EvalConfig)
))
_sym_db.RegisterMessage(EvalConfig)
# @@protoc_insertion_point(module_scope)
| tao_deploy-main | nvidia_tao_deploy/cv/ssd/proto/eval_config_pb2.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""SSD convert etlt/onnx model to TRT engine."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import logging
import os
import tempfile
from nvidia_tao_deploy.cv.common.decorators import monitor_status
from nvidia_tao_deploy.cv.ssd.proto.utils import load_proto
from nvidia_tao_deploy.cv.ssd.engine_builder import SSDEngineBuilder
from nvidia_tao_deploy.utils.decoding import decode_model
logging.basicConfig(format='%(asctime)s [TAO Toolkit] [%(levelname)s] %(name)s %(lineno)d: %(message)s',
level="INFO")
logger = logging.getLogger(__name__)
@monitor_status(name='ssd', mode='gen_trt_engine')
def main(args):
"""SSD TRT convert."""
# decrypt etlt
tmp_onnx_file, file_format = decode_model(args.model_path, args.key)
# Load from proto-based spec file
es = load_proto(args.experiment_spec)
if args.engine_file is not None or args.data_type == 'int8':
if args.engine_file is None:
engine_handle, temp_engine_path = tempfile.mkstemp()
os.close(engine_handle)
output_engine_path = temp_engine_path
else:
output_engine_path = args.engine_file
builder = SSDEngineBuilder(verbose=args.verbose,
is_qat=es.training_config.enable_qat,
workspace=args.max_workspace_size,
min_batch_size=args.min_batch_size,
opt_batch_size=args.opt_batch_size,
max_batch_size=args.max_batch_size,
strict_type_constraints=args.strict_type_constraints,
force_ptq=args.force_ptq)
builder.create_network(tmp_onnx_file, file_format)
builder.create_engine(
output_engine_path,
args.data_type,
calib_data_file=args.cal_data_file,
calib_input=args.cal_image_dir,
calib_cache=args.cal_cache_file,
calib_num_images=args.batch_size * args.batches,
calib_batch_size=args.batch_size,
calib_json_file=args.cal_json_file)
logging.info("Export finished successfully.")
def build_command_line_parser(parser=None):
"""Build the command line parser using argparse.
Args:
parser (subparser): Provided from the wrapper script to build a chained
parser mechanism.
Returns:
parser
"""
if parser is None:
parser = argparse.ArgumentParser(prog='gen_trt_engine', description='Generate TRT engine of SSD model.')
parser.add_argument(
'-m',
'--model_path',
type=str,
required=True,
help='Path to a SSD .etlt or .onnx model file.'
)
parser.add_argument(
'-k',
'--key',
type=str,
required=False,
help='Key to save or load a .etlt model.'
)
parser.add_argument(
'-e',
'--experiment_spec',
type=str,
required=True,
help='Path to the experiment spec file.'
)
parser.add_argument(
"--data_type",
type=str,
default="fp32",
help="Data type for the TensorRT export.",
choices=["fp32", "fp16", "int8"])
parser.add_argument(
"--cal_image_dir",
default="",
type=str,
help="Directory of images to run int8 calibration.")
parser.add_argument(
"--cal_data_file",
default="",
type=str,
help="Tensorfile to run calibration for int8 optimization.")
parser.add_argument(
'--cal_cache_file',
default=None,
type=str,
help='Calibration cache file to write to.')
parser.add_argument(
'--cal_json_file',
default=None,
type=str,
help='Dictionary containing tensor scale for QAT models.')
parser.add_argument(
"--engine_file",
type=str,
default=None,
help="Path to the exported TRT engine.")
parser.add_argument(
"--max_batch_size",
type=int,
default=1,
help="Max batch size for TensorRT engine builder.")
parser.add_argument(
"--opt_batch_size",
type=int,
default=1,
help="Optimal batch size for TensorRT engine builder.")
parser.add_argument(
"--min_batch_size",
type=int,
default=1,
help="Min batch size for TensorRT engine builder.")
parser.add_argument(
"--batch_size",
type=int,
default=1,
help="Number of images per batch for calibration.")
parser.add_argument(
"--batches",
type=int,
default=10,
help="Number of batches to calibrate over.")
parser.add_argument(
"--max_workspace_size",
type=int,
default=2,
help="Max memory workspace size to allow in Gb for TensorRT engine builder (default: 2).")
parser.add_argument(
"-s",
"--strict_type_constraints",
action="store_true",
default=False,
help="A Boolean flag indicating whether to apply the \
TensorRT strict type constraints when building the TensorRT engine.")
parser.add_argument(
"--force_ptq",
action="store_true",
default=False,
help="Flag to force post training quantization for QAT models.")
parser.add_argument(
"-v",
"--verbose",
action="store_true",
default=False,
help="Verbosity of the logger.")
parser.add_argument(
'-r',
'--results_dir',
type=str,
required=True,
default=None,
help='Output directory where the log is saved.'
)
return parser
def parse_command_line_arguments(args=None):
"""Simple function to parse command line arguments."""
parser = build_command_line_parser(args)
return parser.parse_args(args)
if __name__ == '__main__':
args = parse_command_line_arguments()
main(args)
| tao_deploy-main | nvidia_tao_deploy/cv/ssd/scripts/gen_trt_engine.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""TAO Deploy SSD scripts module."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
| tao_deploy-main | nvidia_tao_deploy/cv/ssd/scripts/__init__.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Standalone TensorRT Inference."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import os
import numpy as np
from PIL import Image
from tqdm.auto import tqdm
import logging
from nvidia_tao_deploy.cv.common.decorators import monitor_status
from nvidia_tao_deploy.cv.ssd.dataloader import SSDKITTILoader
from nvidia_tao_deploy.cv.ssd.inferencer import SSDInferencer
from nvidia_tao_deploy.cv.ssd.proto.utils import load_proto
logging.getLogger('PIL').setLevel(logging.WARNING)
logging.basicConfig(format='%(asctime)s [TAO Toolkit] [%(levelname)s] %(name)s %(lineno)d: %(message)s',
level="INFO")
logger = logging.getLogger(__name__)
@monitor_status(name='ssd', mode='inference')
def main(args):
"""SSD TRT inference."""
# Load from proto-based spec file
es = load_proto(args.experiment_spec)
batch_size = args.batch_size if args.batch_size else es.eval_config.batch_size
trt_infer = SSDInferencer(engine_path=args.model_path,
batch_size=batch_size)
c, h, w = trt_infer._input_shape
conf_thres = es.nms_config.confidence_threshold if es.nms_config.confidence_threshold else 0.01
img_mean = es.augmentation_config.image_mean
if c == 3:
if img_mean:
img_mean = [img_mean['b'], img_mean['g'], img_mean['r']]
else:
img_mean = [103.939, 116.779, 123.68]
else:
if img_mean:
img_mean = [img_mean['l']]
else:
img_mean = [117.3786]
# Override path if provided through command line args
if args.image_dir:
image_dirs = [args.image_dir]
else:
image_dirs = [d.image_directory_path for d in es.dataset_config.validation_data_sources]
# Load mapping_dict from the spec file
mapping_dict = dict(es.dataset_config.target_class_mapping)
dl = SSDKITTILoader(
shape=(c, h, w),
image_dirs=image_dirs,
label_dirs=[None],
mapping_dict=mapping_dict,
exclude_difficult=True,
batch_size=batch_size,
is_inference=True,
image_mean=img_mean,
keep_aspect_ratio=False,
dtype=trt_infer.inputs[0].host.dtype)
inv_classes = {v: k for k, v in dl.classes.items()}
if args.results_dir is None:
results_dir = os.path.dirname(args.model_path)
else:
results_dir = args.results_dir
os.makedirs(results_dir, exist_ok=True)
output_annotate_root = os.path.join(results_dir, "images_annotated")
output_label_root = os.path.join(results_dir, "labels")
os.makedirs(output_annotate_root, exist_ok=True)
os.makedirs(output_label_root, exist_ok=True)
for i, (imgs, _) in tqdm(enumerate(dl), total=len(dl), desc="Producing predictions"):
y_pred = trt_infer.infer(imgs)
image_paths = dl.image_paths[np.arange(batch_size) + batch_size * i]
for i in range(len(y_pred)):
# Load image
img = Image.open(image_paths[i])
orig_width, orig_height = img.size
width_scale = orig_width / trt_infer.width
height_scale = orig_height / trt_infer.height
# Filter and scale back to original image resolution
y_pred_valid = y_pred[i][y_pred[i][:, 1] > conf_thres]
y_pred_valid[..., 2] = np.clip(y_pred_valid[..., 2].round(), 0.0, w) * width_scale
y_pred_valid[..., 3] = np.clip(y_pred_valid[..., 3].round(), 0.0, h) * height_scale
y_pred_valid[..., 4] = np.clip(y_pred_valid[..., 4].round(), 0.0, w) * width_scale
y_pred_valid[..., 5] = np.clip(y_pred_valid[..., 5].round(), 0.0, h) * height_scale
# Store images
bbox_img, label_strings = trt_infer.draw_bbox(img, y_pred_valid, inv_classes, args.threshold)
img_filename = os.path.basename(image_paths[i])
bbox_img.save(os.path.join(output_annotate_root, img_filename))
# Store labels
filename, _ = os.path.splitext(img_filename)
label_file_name = os.path.join(output_label_root, filename + ".txt")
with open(label_file_name, "w", encoding="utf-8") as f:
for l_s in label_strings:
f.write(l_s)
logging.info("Finished inference.")
def build_command_line_parser(parser=None):
"""Build the command line parser using argparse.
Args:
parser (subparser): Provided from the wrapper script to build a chained
parser mechanism.
Returns:
parser
"""
if parser is None:
parser = argparse.ArgumentParser(prog='infer', description='Inference with a SSD TRT model.')
parser.add_argument(
'-i',
'--image_dir',
type=str,
required=False,
default=None,
help='Input directory of images')
parser.add_argument(
'-e',
'--experiment_spec',
type=str,
required=True,
help='Path to the experiment spec file.'
)
parser.add_argument(
'-m',
'--model_path',
type=str,
required=True,
help='Path to the SSD TensorRT engine.'
)
parser.add_argument(
'-b',
'--batch_size',
type=int,
required=False,
default=1,
help='Batch size.')
parser.add_argument(
'-t',
'--threshold',
type=float,
default=0.3,
help='Confidence threshold for inference.')
parser.add_argument(
'-r',
'--results_dir',
type=str,
required=True,
default=None,
help='Output directory where the log is saved.'
)
return parser
def parse_command_line_arguments(args=None):
"""Simple function to parse command line arguments."""
parser = build_command_line_parser(args)
return parser.parse_args(args)
if __name__ == '__main__':
args = parse_command_line_arguments()
main(args)
| tao_deploy-main | nvidia_tao_deploy/cv/ssd/scripts/inference.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Standalone TensorRT evaluation."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import os
import json
import numpy as np
from tqdm.auto import tqdm
import logging
from nvidia_tao_deploy.cv.common.decorators import monitor_status
from nvidia_tao_deploy.cv.ssd.dataloader import SSDKITTILoader
from nvidia_tao_deploy.cv.ssd.inferencer import SSDInferencer
from nvidia_tao_deploy.cv.ssd.proto.utils import load_proto
from nvidia_tao_deploy.metrics.kitti_metric import KITTIMetric
logging.getLogger('PIL').setLevel(logging.WARNING)
logging.basicConfig(format='%(asctime)s [TAO Toolkit] [%(levelname)s] %(name)s %(lineno)d: %(message)s',
level="INFO")
logger = logging.getLogger(__name__)
@monitor_status(name='ssd', mode='evaluation')
def main(args):
"""SSD TRT evaluation."""
# Load from proto-based spec file
es = load_proto(args.experiment_spec)
matching_iou_threshold = es.eval_config.matching_iou_threshold if es.eval_config.matching_iou_threshold else 0.5
conf_thres = es.nms_config.confidence_threshold if es.nms_config.confidence_threshold else 0.01
batch_size = args.batch_size if args.batch_size else es.eval_config.batch_size
trt_infer = SSDInferencer(args.model_path, batch_size=batch_size)
c, h, w = trt_infer._input_shape
ap_mode = es.eval_config.average_precision_mode
ap_mode_dict = {0: "sample", 1: "integrate"}
img_mean = es.augmentation_config.image_mean
if c == 3:
if img_mean:
img_mean = [img_mean['b'], img_mean['g'], img_mean['r']]
else:
img_mean = [103.939, 116.779, 123.68]
else:
if img_mean:
img_mean = [img_mean['l']]
else:
img_mean = [117.3786]
# Override path if provided through command line args
if args.image_dir:
image_dirs = [args.image_dir]
else:
image_dirs = [d.image_directory_path for d in es.dataset_config.validation_data_sources]
if args.label_dir:
label_dirs = [args.label_dir]
else:
label_dirs = [d.label_directory_path for d in es.dataset_config.validation_data_sources]
# Load mapping_dict from the spec file
mapping_dict = dict(es.dataset_config.target_class_mapping)
dl = SSDKITTILoader(
shape=(c, h, w),
image_dirs=image_dirs,
label_dirs=label_dirs,
mapping_dict=mapping_dict,
exclude_difficult=True,
batch_size=batch_size,
image_mean=img_mean,
keep_aspect_ratio=False,
dtype=trt_infer.inputs[0].host.dtype)
eval_metric = KITTIMetric(n_classes=len(dl.classes) + 1,
matching_iou_threshold=matching_iou_threshold,
conf_thres=conf_thres,
average_precision_mode=ap_mode_dict[ap_mode])
gt_labels = []
pred_labels = []
for i, (imgs, labels) in tqdm(enumerate(dl), total=len(dl), desc="Producing predictions"):
gt_labels.extend(labels)
y_pred = trt_infer.infer(imgs)
for i in range(len(y_pred)):
y_pred_valid = y_pred[i][y_pred[i][:, 1] > eval_metric.conf_thres]
y_pred_valid[..., 2] = np.clip(y_pred_valid[..., 2].round(), 0.0, w)
y_pred_valid[..., 3] = np.clip(y_pred_valid[..., 3].round(), 0.0, h)
y_pred_valid[..., 4] = np.clip(y_pred_valid[..., 4].round(), 0.0, w)
y_pred_valid[..., 5] = np.clip(y_pred_valid[..., 5].round(), 0.0, h)
pred_labels.append(y_pred_valid)
m_ap, ap = eval_metric(gt_labels, pred_labels, verbose=True)
m_ap = np.mean(ap[1:])
logging.info("*******************************")
class_mapping = {v: k for k, v in dl.classes.items()}
eval_results = {}
for i in range(len(dl.classes)):
eval_results['AP_' + class_mapping[i + 1]] = np.float64(ap[i + 1])
logging.info("{:<14}{:<6}{}".format(class_mapping[i + 1], 'AP', round(ap[i + 1], 5))) # noqa pylint: disable=C0209
eval_results['mAP'] = round(m_ap, 3)
logging.info("{:<14}{:<6}{}".format('', 'mAP', round(m_ap, 3))) # noqa pylint: disable=C0209
logging.info("*******************************")
# Store evaluation results into JSON
if args.results_dir is None:
results_dir = os.path.dirname(args.model_path)
else:
results_dir = args.results_dir
with open(os.path.join(results_dir, "results.json"), "w", encoding="utf-8") as f:
json.dump(eval_results, f)
logging.info("Finished evaluation.")
def build_command_line_parser(parser=None):
"""Build the command line parser using argparse.
Args:
parser (subparser): Provided from the wrapper script to build a chained
parser mechanism.
Returns:
parser
"""
if parser is None:
parser = argparse.ArgumentParser(prog='eval', description='Evaluate with a SSD TRT model.')
parser.add_argument(
'-i',
'--image_dir',
type=str,
required=False,
default=None,
help='Input directory of images')
parser.add_argument(
'-e',
'--experiment_spec',
type=str,
required=True,
help='Path to the experiment spec file.'
)
parser.add_argument(
'-m',
'--model_path',
type=str,
required=True,
help='Path to the SSD TensorRT engine.'
)
parser.add_argument(
'-l',
'--label_dir',
type=str,
required=False,
help='Label directory.')
parser.add_argument(
'-b',
'--batch_size',
type=int,
required=False,
default=1,
help='Batch size.')
parser.add_argument(
'-r',
'--results_dir',
type=str,
required=True,
default=None,
help='Output directory where the log is saved.'
)
return parser
def parse_command_line_arguments(args=None):
"""Simple function to parse command line arguments."""
parser = build_command_line_parser(args)
return parser.parse_args(args)
if __name__ == '__main__':
args = parse_command_line_arguments()
main(args)
| tao_deploy-main | nvidia_tao_deploy/cv/ssd/scripts/evaluate.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""TAO Deploy command line wrapper to invoke CLI scripts."""
import sys
from nvidia_tao_deploy.cv.common.entrypoint.entrypoint_proto import launch_job
import nvidia_tao_deploy.cv.ssd.scripts
def main():
"""Function to launch the job."""
launch_job(nvidia_tao_deploy.cv.ssd.scripts, "ssd", sys.argv[1:])
if __name__ == "__main__":
main()
| tao_deploy-main | nvidia_tao_deploy/cv/ssd/entrypoint/ssd.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Entrypoint module for ssd."""
| tao_deploy-main | nvidia_tao_deploy/cv/ssd/entrypoint/__init__.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""TAO Deploy PyTorch Classification."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
| tao_deploy-main | nvidia_tao_deploy/cv/classification_pyt/__init__.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""TAO Deploy Classification Hydra."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
| tao_deploy-main | nvidia_tao_deploy/cv/classification_pyt/hydra_config/__init__.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Classification Default config file"""
from typing import Optional, List, Dict, Any
from dataclasses import dataclass, field
from omegaconf import MISSING
@dataclass
class ImgNormConfig:
"""Configuration parameters for Img Normalization."""
mean: List[float] = field(default_factory=lambda: [123.675, 116.28, 103.53])
std: List[float] = field(default_factory=lambda: [58.395, 57.12, 57.375])
to_rgb: bool = True
@dataclass
class TrainData:
"""Train Data Dataclass"""
type: str = "ImageNet"
data_prefix: Optional[str] = None
pipeline: List[Any] = field(default_factory=lambda: [{"type": "RandomResizedCrop", "size": 224},
{"type": "RandomFlip", "flip_prob": 0.5, "direction": "horizontal"}])
classes: Optional[str] = None
@dataclass
class ValData:
"""Validation Data Dataclass"""
type: str = "ImageNet"
data_prefix: Optional[str] = None
ann_file: Optional[str] = None
pipeline: List[Any] = field(default_factory=lambda: [{"type": "Resize", "size": (256, -1)},
{"type": "CenterCrop", "crop_size": 224}])
classes: Optional[str] = None
@dataclass
class TestData:
"""Test Data Dataclass"""
type: str = "ImageNet"
data_prefix: Optional[str] = None
ann_file: Optional[str] = None
pipeline: List[Any] = field(default_factory=lambda: [{"type": "Resize", "size": (256, -1)},
{"type": "CenterCrop", "crop_size": 224}])
classes: Optional[str] = None
@dataclass
class DataConfig:
"""Data Config"""
samples_per_gpu: int = 1
workers_per_gpu: int = 2
train: TrainData = TrainData()
val: ValData = ValData()
test: TestData = TestData()
@dataclass
class DatasetConfig:
"""Dataset config."""
img_norm_cfg: ImgNormConfig = ImgNormConfig()
data: DataConfig = DataConfig()
sampler: Optional[Dict[Any, Any]] = None # Allowed sampler : RepeatAugSampler
@dataclass
class DistParams:
"""Distribution Parameters"""
backend: str = "nccl"
@dataclass
class RunnerConfig:
"""Configuration parameters for Runner."""
type: str = "TAOEpochBasedRunner" # Currently We support only Epochbased Runner - Non configurable
max_epochs: int = 20 # Set this if Epoch based runner
@dataclass
class CheckpointConfig:
"""Configuration parameters for Checkpointing."""
interval: int = 1 # Epochs or Iterations accordingly
by_epoch: bool = True # By default it trains by iters
# Default Runtime Config
@dataclass
class LogConfig:
"""Configuration parameters for Logging."""
interval: int = 1000
log_dir: str = "logs" # Make sure this directory is created
# Optim and Schedule Config
@dataclass
class ValidationConfig:
"""Validation Config."""
interval: int = 100
@dataclass
class ParamwiseConfig:
"""Configuration parameters for Parameters."""
pos_block: Dict[str, float] = field(default_factory=lambda: {"decay_mult": 0.0})
norm: Dict[str, float] = field(default_factory=lambda: {"decay_mult": 0.0})
head: Dict[str, float] = field(default_factory=lambda: {"lr_mult": 10.0})
@dataclass
class EvaluationConfig:
"""Evaluation Config."""
interval: int = 1
metric: str = "accuracy"
@dataclass
class TrainConfig:
"""Train Config."""
checkpoint_config: CheckpointConfig = CheckpointConfig()
optimizer: Dict[Any, Any] = field(default_factory=lambda: {"type": 'AdamW',
"lr": 10e-4,
"weight_decay": 0.05})
paramwise_cfg: Optional[Dict[Any, Any]] = None # Not a must - needs to be provided in yaml
optimizer_config: Dict[Any, Any] = field(default_factory=lambda: {'grad_clip': None}) # Gradient Accumulation and grad clip
lr_config: Dict[Any, Any] = field(default_factory=lambda: {"policy": 'CosineAnnealing',
"min_lr": 10e-4, "warmup": "linear",
"warmup_iters": 5,
"warmup_ratio": 0.01,
"warmup_by_epoch": True})
runner: RunnerConfig = RunnerConfig()
logging: LogConfig = LogConfig() # By default we add logging
evaluation: EvaluationConfig = EvaluationConfig() # Does not change
find_unused_parameters: bool = False # Does not change
resume_training_checkpoint_path: Optional[str] = None
validate: bool = False
# This param can be omitted if init_cfg is used in model_cfg. Both does same thing.
load_from: Optional[str] = None # If they want to load the weights till head
custom_hooks: List[Any] = field(default_factory=lambda: [])
# Experiment Common Configs
@dataclass
class ExpConfig:
"""Overall Exp Config for Cls."""
manual_seed: int = 47
# If needed, the next line can be commented
MASTER_ADDR: str = "127.0.0.1"
MASTER_PORT: int = 631
@dataclass
class TrainExpConfig:
"""Train experiment config."""
exp_config: ExpConfig = ExpConfig()
validate: bool = False
train_config: TrainConfig = TrainConfig() # Could change across networks
num_gpus: int = 1 # non configurable here
results_dir: Optional[str] = None
@dataclass
class InferenceExpConfig:
"""Inference experiment config."""
num_gpus: int = 1 # non configurable here
batch_size: int = 1
checkpoint: Optional[str] = None
trt_engine: Optional[str] = None
exp_config: ExpConfig = ExpConfig()
results_dir: Optional[str] = None
@dataclass
class EvalExpConfig:
"""Inference experiment config."""
num_gpus: int = 1 # non configurable here
batch_size: int = 1
checkpoint: Optional[str] = None
trt_engine: Optional[str] = None
exp_config: ExpConfig = ExpConfig()
topk: int = 1 # Configurable
results_dir: Optional[str] = None
@dataclass
class TrtConfig:
"""Trt config."""
data_type: str = "FP32"
workspace_size: int = 1024
min_batch_size: int = 1
opt_batch_size: int = 1
max_batch_size: int = 1
@dataclass
class ExportExpConfig:
"""Export experiment config."""
verify: bool = False
opset_version: int = 12
checkpoint: Optional[str] = None
input_channel: int = 3
input_width: int = 224
input_height: int = 224
onnx_file: Optional[str] = None
results_dir: Optional[str] = None
@dataclass
class HeadConfig:
"""Head Config"""
type: str = 'LinearClsHead'
num_classes: int = 1000
in_channels: int = 448 # Mapped to differenct channels based according to the backbone used in the fan_model.py
custom_args: Optional[Dict[Any, Any]] = None
loss: Dict[Any, Any] = field(default_factory=lambda: {"type": 'CrossEntropyLoss', "loss_weight": 1.0, "use_soft": False})
topk: List[int] = field(default_factory=lambda: [1, ])
@dataclass
class InitCfg:
"""Init Config"""
type: str = "Pretrained"
checkpoint: Optional[str] = None
prefix: Optional[str] = None # E.g., backbone
@dataclass
class BackboneConfig:
"""Configuration parameters for Backbone."""
type: str = "fan_tiny_8_p4_hybrid"
custom_args: Optional[Dict[Any, Any]] = None
@dataclass
class TrainAugCfg:
"""Arguments for Train Config"""
augments: Optional[List[Dict[Any, Any]]] = None
@dataclass
class ModelConfig:
"""Cls model config."""
type: str = "ImageClassifier"
backbone: BackboneConfig = BackboneConfig()
neck: Optional[Dict[Any, Any]] = None
head: HeadConfig = HeadConfig()
init_cfg: InitCfg = InitCfg() # No change
train_cfg: TrainAugCfg = TrainAugCfg()
@dataclass
class GenTrtEngineExpConfig:
"""Gen TRT Engine experiment config."""
results_dir: Optional[str] = None
gpu_id: int = 0
onnx_file: Optional[str] = None
trt_engine: Optional[str] = None
input_channel: int = 3
input_width: int = 224
input_height: int = 224
opset_version: int = 12
batch_size: int = -1
verbose: bool = False
tensorrt: TrtConfig = TrtConfig()
@dataclass
class ExperimentConfig:
"""Experiment config."""
model: ModelConfig = ModelConfig()
dataset: DatasetConfig = DatasetConfig()
train: TrainExpConfig = TrainExpConfig()
evaluate: EvalExpConfig = EvalExpConfig()
inference: InferenceExpConfig = InferenceExpConfig()
gen_trt_engine: GenTrtEngineExpConfig = GenTrtEngineExpConfig()
export: ExportExpConfig = ExportExpConfig()
results_dir: str = MISSING
| tao_deploy-main | nvidia_tao_deploy/cv/classification_pyt/hydra_config/default_config.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Classification convert etlt model to TRT engine."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import logging
import os
import tempfile
from nvidia_tao_deploy.utils.decoding import decode_model
from nvidia_tao_deploy.cv.classification_tf1.engine_builder import ClassificationEngineBuilder
from nvidia_tao_deploy.cv.common.decorators import monitor_status
from nvidia_tao_deploy.cv.common.hydra.hydra_runner import hydra_runner
from nvidia_tao_deploy.cv.classification_pyt.hydra_config.default_config import ExperimentConfig
from nvidia_tao_deploy.engine.builder import NV_TENSORRT_MAJOR, NV_TENSORRT_MINOR, NV_TENSORRT_PATCH
logging.basicConfig(format='%(asctime)s [TAO Toolkit] [%(levelname)s] %(name)s %(lineno)d: %(message)s',
level="INFO")
logger = logging.getLogger(__name__)
spec_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
@hydra_runner(
config_path=os.path.join(spec_root, "specs"),
config_name="gen_trt_engine", schema=ExperimentConfig
)
@monitor_status(name='classification_pyt', mode='gen_trt_engine')
def main(cfg: ExperimentConfig) -> None:
"""Classification TRT convert."""
# decrypt EFF or etlt
tmp_onnx_file, file_format = decode_model(cfg.gen_trt_engine.onnx_file)
data_type = cfg.gen_trt_engine.tensorrt.data_type.lower()
# TODO: TRT8.6.1 improves INT8 perf
if data_type == 'int8':
raise NotImplementedError("INT8 calibration for PyTorch classification models is not yet supported")
if cfg.gen_trt_engine.trt_engine is not None:
if cfg.gen_trt_engine.trt_engine is None:
engine_handle, temp_engine_path = tempfile.mkstemp()
os.close(engine_handle)
output_engine_path = temp_engine_path
else:
output_engine_path = cfg.gen_trt_engine.trt_engine
min_batch_size = cfg.gen_trt_engine.tensorrt.min_batch_size
opt_batch_size = cfg.gen_trt_engine.tensorrt.opt_batch_size
max_batch_size = cfg.gen_trt_engine.tensorrt.max_batch_size
# TODO: Remove this when we upgrade to DLFW 23.04+
trt_version_number = NV_TENSORRT_MAJOR * 1000 + NV_TENSORRT_MINOR * 100 + NV_TENSORRT_PATCH
if data_type == "fp16" and trt_version_number < 8600:
logger.warning("[WARNING]: LayerNorm has overflow issue in FP16 upto TensorRT version 8.5 "
"which can lead to accuracy drop compared to FP32.\n"
"[WARNING]: Please re-export ONNX using opset 17 and use TensorRT version 8.6.\n")
builder = ClassificationEngineBuilder(verbose=cfg.gen_trt_engine.verbose,
workspace=cfg.gen_trt_engine.tensorrt.workspace_size,
min_batch_size=min_batch_size,
opt_batch_size=opt_batch_size,
max_batch_size=max_batch_size,
is_qat=False,
data_format="channels_first",
preprocess_mode="torch")
builder.create_network(tmp_onnx_file, file_format)
builder.create_engine(
output_engine_path,
cfg.gen_trt_engine.tensorrt.data_type)
if cfg.gen_trt_engine.results_dir is not None:
results_dir = cfg.gen_trt_engine.results_dir
else:
results_dir = os.path.join(cfg.results_dir, "gen_trt_engine")
os.makedirs(results_dir, exist_ok=True)
logging.info("Export finished successfully.")
if __name__ == '__main__':
main()
| tao_deploy-main | nvidia_tao_deploy/cv/classification_pyt/scripts/gen_trt_engine.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""TAO Deploy Classification PyT scripts module."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
| tao_deploy-main | nvidia_tao_deploy/cv/classification_pyt/scripts/__init__.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Standalone TensorRT inference."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import logging
import os
import pandas as pd
import numpy as np
from tqdm.auto import tqdm
from nvidia_tao_deploy.cv.classification_tf1.inferencer import ClassificationInferencer
from nvidia_tao_deploy.cv.classification_tf1.dataloader import ClassificationLoader
from nvidia_tao_deploy.cv.common.decorators import monitor_status
from nvidia_tao_deploy.cv.common.hydra.hydra_runner import hydra_runner
from nvidia_tao_deploy.cv.classification_pyt.hydra_config.default_config import ExperimentConfig
logging.getLogger('PIL').setLevel(logging.WARNING)
logging.basicConfig(format='%(asctime)s [TAO Toolkit] [%(levelname)s] %(name)s %(lineno)d: %(message)s',
level="INFO")
logger = logging.getLogger(__name__)
spec_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
@hydra_runner(
config_path=os.path.join(spec_root, "specs"),
config_name="inference", schema=ExperimentConfig
)
@monitor_status(name='classification_pyt', mode='inference')
def main(cfg: ExperimentConfig) -> None:
"""Classification TRT inference."""
classmap = cfg.dataset.data.test.classes
if classmap:
# if classmap is provided, we explicitly set the mapping from the text file
if not os.path.exists(classmap):
raise FileNotFoundError(f"{classmap} does not exist!")
with open(classmap, "r", encoding="utf-8") as f:
mapping_dict = {line.rstrip(): idx for idx, line in enumerate(f.readlines())}
else:
# If not, the order of the classes are alphanumeric as defined by Keras
# Ref: https://github.com/keras-team/keras/blob/07e13740fd181fc3ddec7d9a594d8a08666645f6/keras/preprocessing/image.py#L507
mapping_dict = {}
for idx, subdir in enumerate(sorted(os.listdir(cfg.dataset.data.test.data_prefix))):
if os.path.isdir(os.path.join(cfg.dataset.data.test.data_prefix, subdir)):
mapping_dict[subdir] = idx
image_mean = [x / 255 for x in cfg.dataset.img_norm_cfg.mean]
img_std = [x / 255 for x in cfg.dataset.img_norm_cfg.std]
batch_size = cfg.inference.batch_size
trt_infer = ClassificationInferencer(cfg.inference.trt_engine, data_format="channels_first", batch_size=batch_size)
dl = ClassificationLoader(
trt_infer._input_shape,
[cfg.dataset.data.test.data_prefix],
mapping_dict,
is_inference=True,
data_format="channels_first",
mode="torch",
batch_size=batch_size,
image_mean=image_mean,
image_std=img_std,
dtype=trt_infer.inputs[0].host.dtype)
if cfg.inference.results_dir is not None:
results_dir = cfg.inference.results_dir
else:
results_dir = os.path.join(cfg.results_dir, "trt_inference")
os.makedirs(results_dir, exist_ok=True)
result_csv_path = os.path.join(results_dir, 'result.csv')
with open(result_csv_path, 'w', encoding="utf-8") as csv_f:
for i, (imgs, _) in tqdm(enumerate(dl), total=len(dl), desc="Producing predictions"):
image_paths = dl.image_paths[np.arange(batch_size) + batch_size * i]
y_pred = trt_infer.infer(imgs)
# Class output from softmax layer
class_indices = np.argmax(y_pred, axis=1)
# Map label index to label name
class_labels = map(lambda i: list(mapping_dict.keys())
[list(mapping_dict.values()).index(i)],
class_indices)
conf = np.max(y_pred, axis=1)
# Write predictions to file
df = pd.DataFrame(zip(image_paths, class_labels, conf))
df.to_csv(csv_f, header=False, index=False)
logging.info("Finished inference.")
if __name__ == '__main__':
main()
| tao_deploy-main | nvidia_tao_deploy/cv/classification_pyt/scripts/inference.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Standalone TensorRT evaluation."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import logging
import os
import json
import numpy as np
from tqdm.auto import tqdm
from sklearn.metrics import classification_report, confusion_matrix, top_k_accuracy_score
from nvidia_tao_deploy.cv.classification_tf1.inferencer import ClassificationInferencer
from nvidia_tao_deploy.cv.classification_tf1.dataloader import ClassificationLoader
from nvidia_tao_deploy.cv.common.decorators import monitor_status
from nvidia_tao_deploy.cv.common.hydra.hydra_runner import hydra_runner
from nvidia_tao_deploy.cv.classification_pyt.hydra_config.default_config import ExperimentConfig
logging.getLogger('PIL').setLevel(logging.WARNING)
logging.basicConfig(format='%(asctime)s [TAO Toolkit] [%(levelname)s] %(name)s %(lineno)d: %(message)s',
level="INFO")
logger = logging.getLogger(__name__)
spec_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
@hydra_runner(
config_path=os.path.join(spec_root, "specs"),
config_name="evaluate", schema=ExperimentConfig
)
@monitor_status(name='classification_pyt', mode='evaluation')
def main(cfg: ExperimentConfig) -> None:
"""Classification TRT evaluation."""
classmap = cfg.dataset.data.test.classes
if classmap:
# if classmap is provided, we explicitly set the mapping from the text file
if not os.path.exists(classmap):
raise FileNotFoundError(f"{classmap} does not exist!")
with open(classmap, "r", encoding="utf-8") as f:
mapping_dict = {line.rstrip(): idx for idx, line in enumerate(sorted(f.readlines()))}
else:
# If not, the order of the classes are alphanumeric as defined by Keras
# Ref: https://github.com/keras-team/keras/blob/07e13740fd181fc3ddec7d9a594d8a08666645f6/keras/preprocessing/image.py#L507
mapping_dict = {}
for idx, subdir in enumerate(sorted(os.listdir(cfg.dataset.data.test.data_prefix))):
if os.path.isdir(os.path.join(cfg.dataset.data.test.data_prefix, subdir)):
mapping_dict[subdir] = idx
# Load hparams
target_names = [c[0] for c in sorted(mapping_dict.items(), key=lambda x:x[1])]
top_k = cfg.evaluate.topk
image_mean = [x / 255 for x in cfg.dataset.img_norm_cfg.mean]
img_std = [x / 255 for x in cfg.dataset.img_norm_cfg.std]
batch_size = cfg.evaluate.batch_size
trt_infer = ClassificationInferencer(cfg.evaluate.trt_engine, data_format="channels_first", batch_size=batch_size)
dl = ClassificationLoader(
trt_infer._input_shape,
[cfg.dataset.data.test.data_prefix],
mapping_dict,
data_format="channels_first",
mode="torch",
batch_size=cfg.evaluate.batch_size,
image_mean=image_mean,
image_std=img_std,
dtype=trt_infer.inputs[0].host.dtype)
gt_labels = []
pred_labels = []
for imgs, labels in tqdm(dl, total=len(dl), desc="Producing predictions"):
gt_labels.extend(labels)
y_pred = trt_infer.infer(imgs)
pred_labels.extend(y_pred)
# Check output classes
output_num_classes = pred_labels[0].shape[0]
if len(mapping_dict) != output_num_classes:
raise ValueError(f"Provided class map has {len(mapping_dict)} classes while the engine expects {output_num_classes} classes.")
gt_labels = np.array(gt_labels)
pred_labels = np.array(pred_labels)
# Metric calculation
target_names = np.array([c[0] for c in sorted(mapping_dict.items(), key=lambda x:x[1])])
target_labels = np.array([c[1] for c in sorted(mapping_dict.items(), key=lambda x:x[1])])
if len(target_labels) == 2:
# If there are only two classes, sklearn perceive the problem as binary classification
# and requires predictions to be in (num_samples, ) rather than (num_samples, num_classes)
scores = top_k_accuracy_score(gt_labels, pred_labels[:, 1], k=top_k, labels=target_labels)
else:
scores = top_k_accuracy_score(gt_labels, pred_labels, k=top_k, labels=target_labels)
logging.info("Top %s scores: %s", top_k, scores)
logging.info("Confusion Matrix")
y_predictions = np.argmax(pred_labels, axis=1)
print(confusion_matrix(gt_labels, y_predictions))
logging.info("Classification Report")
print(classification_report(gt_labels, y_predictions, labels=target_labels, target_names=target_names))
# Store evaluation results into JSON
eval_results = {"top_k_accuracy": scores}
if cfg.evaluate.results_dir is not None:
results_dir = cfg.evaluate.results_dir
else:
results_dir = os.path.join(cfg.results_dir, "trt_evaluate")
os.makedirs(results_dir, exist_ok=True)
with open(os.path.join(results_dir, "results.json"), "w", encoding="utf-8") as f:
json.dump(eval_results, f)
logging.info("Finished evaluation.")
if __name__ == '__main__':
main()
| tao_deploy-main | nvidia_tao_deploy/cv/classification_pyt/scripts/evaluate.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""TAO Deploy command line wrapper to invoke CLI scripts."""
import argparse
from nvidia_tao_deploy.cv.classification_pyt import scripts
from nvidia_tao_deploy.cv.common.entrypoint.entrypoint_hydra import get_subtasks, launch
def main():
"""Main entrypoint wrapper."""
# Create parser for a given task.
parser = argparse.ArgumentParser(
"classification_pyt",
add_help=True,
description="Train Adapt Optimize Deploy entrypoint for PyTorch classification"
)
# Build list of subtasks by inspecting the scripts package.
subtasks = get_subtasks(scripts)
# Parse the arguments and launch the subtask.
launch(parser,
subtasks,
override_results_dir="results_dir",
override_threshold=None, # No threshold in Classification
override_key="key",
network="classification_pyt")
if __name__ == '__main__':
main()
| tao_deploy-main | nvidia_tao_deploy/cv/classification_pyt/entrypoint/classification_pyt.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Entrypoint module for classification."""
| tao_deploy-main | nvidia_tao_deploy/cv/classification_pyt/entrypoint/__init__.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utility class for performing TensorRT image inference."""
import numpy as np
import tensorrt as trt
from nvidia_tao_deploy.inferencer.trt_inferencer import TRTInferencer
from nvidia_tao_deploy.inferencer.utils import allocate_buffers, do_inference
def trt_output_process_fn(y_encoded, etlt_type="onnx"):
"""Function to process TRT model output."""
if etlt_type == "uff":
# UFF output node is in reverse order
y_encoded.reverse()
return y_encoded
class MClassificationInferencer(TRTInferencer):
"""Manages TensorRT objects for model inference."""
def __init__(self, engine_path, input_shape=None, batch_size=None, data_format="channel_first"):
"""Initializes TensorRT objects needed for model inference.
Args:
engine_path (str): path where TensorRT engine should be stored
input_shape (tuple): (batch, channel, height, width) for dynamic shape engine
batch_size (int): batch size for dynamic shape engine
data_format (str): either channel_first or channel_last
"""
# Load TRT engine
super().__init__(engine_path)
self.max_batch_size = self.engine.max_batch_size
self.execute_v2 = False
# Execution context is needed for inference
self.context = None
# Allocate memory for multiple usage [e.g. multiple batch inference]
self._input_shape = []
for binding in range(self.engine.num_bindings):
if self.engine.binding_is_input(binding):
binding_shape = self.engine.get_binding_shape(binding)
self._input_shape = binding_shape[-3:]
if len(binding_shape) == 4:
self.etlt_type = "onnx"
else:
self.etlt_type = "uff"
assert len(self._input_shape) == 3, "Engine doesn't have valid input dimensions"
if data_format == "channel_first":
self.height = self._input_shape[1]
self.width = self._input_shape[2]
else:
self.height = self._input_shape[0]
self.width = self._input_shape[1]
# set binding_shape for dynamic input
if (input_shape is not None) or (batch_size is not None):
self.context = self.engine.create_execution_context()
if input_shape is not None:
self.context.set_binding_shape(0, input_shape)
self.max_batch_size = input_shape[0]
else:
self.context.set_binding_shape(0, [batch_size] + list(self._input_shape))
self.max_batch_size = batch_size
self.execute_v2 = True
# This allocates memory for network inputs/outputs on both CPU and GPU
self.inputs, self.outputs, self.bindings, self.stream = allocate_buffers(self.engine,
self.context)
if self.context is None:
self.context = self.engine.create_execution_context()
input_volume = trt.volume(self._input_shape)
self.numpy_array = np.zeros((self.max_batch_size, input_volume))
def infer(self, imgs):
"""Infers model on batch of same sized images resized to fit the model.
Args:
image_paths (str): paths to images, that will be packed into batch
and fed into model
"""
# Verify if the supplied batch size is not too big
max_batch_size = self.max_batch_size
actual_batch_size = len(imgs)
if actual_batch_size > max_batch_size:
raise ValueError(f"image_paths list bigger ({actual_batch_size}) than \
engine max batch size ({max_batch_size})")
self.numpy_array[:actual_batch_size] = imgs.reshape(actual_batch_size, -1)
# ...copy them into appropriate place into memory...
# (self.inputs was returned earlier by allocate_buffers())
np.copyto(self.inputs[0].host, self.numpy_array.ravel())
# ...fetch model outputs...
results = do_inference(
self.context, bindings=self.bindings, inputs=self.inputs,
outputs=self.outputs, stream=self.stream,
batch_size=max_batch_size,
execute_v2=self.execute_v2)
# ...and return results up to the actual batch size.
y_pred = [i.reshape(max_batch_size, -1)[:actual_batch_size] for i in results]
# Process TRT outputs to proper format
return trt_output_process_fn(y_pred, etlt_type=self.etlt_type)
def __del__(self):
"""Clear things up on object deletion."""
# Clear session and buffer
if self.trt_runtime:
del self.trt_runtime
if self.context:
del self.context
if self.engine:
del self.engine
if self.stream:
del self.stream
# Loop through inputs and free inputs.
for inp in self.inputs:
inp.device.free()
# Loop through outputs and free them.
for out in self.outputs:
out.device.free()
| tao_deploy-main | nvidia_tao_deploy/cv/multitask_classification/inferencer.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Multitask Classification TensorRT engine builder."""
import logging
import os
import random
from six.moves import xrange
import sys
import onnx
import traceback
from tqdm import tqdm
try:
from uff.model.uff_pb2 import MetaGraph
except ImportError:
print("Loading uff directly from the package source code")
# @scha: To disable tensorflow import issue
import importlib
import types
import pkgutil
package = pkgutil.get_loader("uff")
# Returns __init__.py path
src_code = package.get_filename().replace('__init__.py', 'model/uff_pb2.py')
loader = importlib.machinery.SourceFileLoader('helper', src_code)
helper = types.ModuleType(loader.name)
loader.exec_module(helper)
MetaGraph = helper.MetaGraph
import numpy as np
import tensorrt as trt
from nvidia_tao_deploy.engine.builder import EngineBuilder
from nvidia_tao_deploy.engine.tensorfile import TensorFile
from nvidia_tao_deploy.engine.tensorfile_calibrator import TensorfileCalibrator
from nvidia_tao_deploy.engine.utils import generate_random_tensorfile, prepare_chunk
logging.basicConfig(format='%(asctime)s [TAO Toolkit] [%(levelname)s] %(name)s %(lineno)d: %(message)s',
level="INFO")
logger = logging.getLogger(__name__)
class MClassificationEngineBuilder(EngineBuilder):
"""Parses an UFF graph and builds a TensorRT engine from it."""
def __init__(
self,
output_tasks,
data_format="channels_first",
**kwargs
):
"""Init.
Args:
output_tasks (list): list of names of output tasks to be used
data_format (str): data_format.
"""
super().__init__(**kwargs)
self._data_format = data_format
self.output_tasks = output_tasks
def set_input_output_node_names(self):
"""Set input output node names."""
self._output_node_names = [n + "/Softmax" for n in self.output_tasks]
self._input_node_names = ["input_1"]
def get_uff_input_dims(self, model_path):
"""Get input dimension of UFF model."""
metagraph = MetaGraph()
with open(model_path, "rb") as f:
metagraph.ParseFromString(f.read())
for node in metagraph.graphs[0].nodes:
if node.operation == "Input":
return np.array(node.fields['shape'].i_list.val)[1:]
raise ValueError("Input dimension is not found in the UFF metagraph.")
def get_onnx_input_dims(self, model_path):
"""Get input dimension of ONNX model."""
onnx_model = onnx.load(model_path)
onnx_inputs = onnx_model.graph.input
logger.info('List inputs:')
for i, inputs in enumerate(onnx_inputs):
logger.info('Input %s -> %s.', i, inputs.name)
logger.info('%s.', [i.dim_value for i in inputs.type.tensor_type.shape.dim][1:])
logger.info('%s.', [i.dim_value for i in inputs.type.tensor_type.shape.dim][0])
return [i.dim_value for i in inputs.type.tensor_type.shape.dim][:]
def create_network(self, model_path, file_format="uff"):
"""Parse the UFF/ONNX graph and create the corresponding TensorRT network definition.
Args:
model_path: The path to the UFF/ONNX graph to load.
file_format: The file format of the decrypted etlt file (default: onnx).
"""
if file_format == "uff":
logger.info("Parsing UFF model")
self.network = self.builder.create_network()
self.parser = trt.UffParser()
self.set_input_output_node_names()
in_tensor_name = self._input_node_names[0]
self._input_dims = self.get_uff_input_dims(model_path)
input_dict = {in_tensor_name: self._input_dims}
for key, value in input_dict.items():
if self._data_format == "channels_first":
self.parser.register_input(key, value, trt.UffInputOrder(0))
else:
self.parser.register_input(key, value, trt.UffInputOrder(1))
for name in self._output_node_names:
self.parser.register_output(name)
try:
assert self.parser.parse(model_path, self.network, trt.DataType.FLOAT)
except AssertionError as e:
logger.error("Failed to parse UFF File")
_, _, tb = sys.exc_info()
traceback.print_tb(tb) # Fixed format
tb_info = traceback.extract_tb(tb)
_, line, _, text = tb_info[-1]
raise AssertionError(
f"UFF parsing failed on line {line} in statement {text}"
) from e
else:
logger.info("Parsing ONNX model")
self._input_dims = self.get_onnx_input_dims(model_path)
self.batch_size = self._input_dims[0]
self._input_dims = self._input_dims[1:]
network_flags = (1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH))
self.network = self.builder.create_network(network_flags)
self.parser = trt.OnnxParser(self.network, self.trt_logger)
model_path = os.path.realpath(model_path)
with open(model_path, "rb") as f:
if not self.parser.parse(f.read()):
logger.error("Failed to load ONNX file: %s", model_path)
for error in range(self.parser.num_errors):
logger.error(self.parser.get_error(error))
sys.exit(1)
inputs = [self.network.get_input(i) for i in range(self.network.num_inputs)]
outputs = [self.network.get_output(i) for i in range(self.network.num_outputs)]
logger.info("Network Description")
for input in inputs: # noqa pylint: disable=W0622
logger.info("Input '%s' with shape %s and dtype %s", input.name, input.shape, input.dtype)
for output in outputs:
logger.info("Output '%s' with shape %s and dtype %s", output.name, output.shape, output.dtype)
if self.batch_size <= 0: # dynamic batch size
logger.info("dynamic batch size handling")
opt_profile = self.builder.create_optimization_profile()
model_input = self.network.get_input(0)
input_shape = model_input.shape
input_name = model_input.name
real_shape_min = (self.min_batch_size, input_shape[1],
input_shape[2], input_shape[3])
real_shape_opt = (self.opt_batch_size, input_shape[1],
input_shape[2], input_shape[3])
real_shape_max = (self.max_batch_size, input_shape[1],
input_shape[2], input_shape[3])
opt_profile.set_shape(input=input_name,
min=real_shape_min,
opt=real_shape_opt,
max=real_shape_max)
self.config.add_optimization_profile(opt_profile)
def set_calibrator(self,
inputs=None,
calib_cache=None,
calib_input=None,
calib_num_images=5000,
calib_batch_size=8,
calib_data_file=None,
image_mean=None):
"""Simple function to set an Tensorfile based int8 calibrator.
Args:
calib_data_file: Path to the TensorFile. If the tensorfile doesn't exist
at this path, then one is created with either n_batches
of random tensors, images from the file in calib_input of dimensions
(batch_size,) + (input_dims).
calib_input: The path to a directory holding the calibration images.
calib_cache: The path where to write the calibration cache to,
or if it already exists, load it from.
calib_num_images: The maximum number of images to use for calibration.
calib_batch_size: The batch size to use for the calibration process.
image_mean: Image mean per channel.
Returns:
No explicit returns.
"""
logger.info("Calibrating using TensorfileCalibrator")
n_batches = calib_num_images // calib_batch_size
if not os.path.exists(calib_data_file):
self.generate_tensor_file(calib_data_file,
calib_input,
self._input_dims,
n_batches=n_batches,
batch_size=calib_batch_size,
image_mean=image_mean)
self.config.int8_calibrator = TensorfileCalibrator(calib_data_file,
calib_cache,
n_batches,
calib_batch_size)
def generate_tensor_file(self, data_file_name,
calibration_images_dir,
input_dims, n_batches=10,
batch_size=1, image_mean=None):
"""Generate calibration Tensorfile for int8 calibrator.
This function generates a calibration tensorfile from a directory of images, or dumps
n_batches of random numpy arrays of shape (batch_size,) + (input_dims).
Args:
data_file_name (str): Path to the output tensorfile to be saved.
calibration_images_dir (str): Path to the images to generate a tensorfile from.
input_dims (list): Input shape in CHW order.
n_batches (int): Number of batches to be saved.
batch_size (int): Number of images per batch.
image_mean (list): Image mean per channel.
Returns:
No explicit returns.
"""
if not os.path.exists(calibration_images_dir):
logger.info("Generating a tensorfile with random tensor images. This may work well as "
"a profiling tool, however, it may result in inaccurate results at "
"inference. Please generate a tensorfile using the tlt-int8-tensorfile, "
"or provide a custom directory of images for best performance.")
generate_random_tensorfile(data_file_name,
input_dims,
n_batches=n_batches,
batch_size=batch_size)
else:
# Preparing the list of images to be saved.
num_images = n_batches * batch_size
valid_image_ext = ('jpg', 'jpeg', 'png')
image_list = [os.path.join(calibration_images_dir, image)
for image in os.listdir(calibration_images_dir)
if image.lower().endswith(valid_image_ext)]
if len(image_list) < num_images:
raise ValueError('Not enough number of images provided:'
f' {len(image_list)} < {num_images}')
image_idx = random.sample(xrange(len(image_list)), num_images)
self.set_data_preprocessing_parameters(input_dims, image_mean)
# Writing out processed dump.
with TensorFile(data_file_name, 'w') as f:
for chunk in tqdm(image_idx[x:x + batch_size] for x in xrange(0, len(image_idx),
batch_size)):
dump_data = prepare_chunk(chunk, image_list,
image_width=input_dims[2],
image_height=input_dims[1],
channels=input_dims[0],
batch_size=batch_size,
**self.preprocessing_arguments)
f.write(dump_data)
f.closed
def set_data_preprocessing_parameters(self, input_dims, image_mean=None):
"""Set data pre-processing parameters for the int8 calibration."""
num_channels = input_dims[0]
if num_channels == 3:
if not image_mean:
means = [103.939, 116.779, 123.68]
else:
assert len(image_mean) == 3, "Image mean should have 3 values for RGB inputs."
means = image_mean
elif num_channels == 1:
if not image_mean:
means = [117.3786]
else:
assert len(image_mean) == 1, "Image mean should have 1 value for grayscale inputs."
means = image_mean
else:
raise NotImplementedError(
f"Invalid number of dimensions {num_channels}.")
self.preprocessing_arguments = {"scale": 1.0,
"means": means,
"flip_channel": True}
| tao_deploy-main | nvidia_tao_deploy/cv/multitask_classification/engine_builder.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""TAO Deploy Multitask Classification."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
| tao_deploy-main | nvidia_tao_deploy/cv/multitask_classification/__init__.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Multitask Classification loader."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from abc import ABC
import numpy as np
import pandas as pd
from collections import defaultdict
from PIL import Image
from nvidia_tao_deploy.inferencer.preprocess_input import preprocess_input
# padding size.
# We firstly resize to (target_width + CROP_PADDING, target_height + CROP_PADDING)
# , then crop to (target_width, target_height).
# for standard ImageNet size: 224x224 the ratio is 0.875(224 / (224 + 32)).
# but for EfficientNet B1-B7, larger resolution is used, hence this ratio
# is no longer 0.875
# ref:
# https://github.com/tensorflow/tpu/blob/r1.15/models/official/efficientnet/preprocessing.py#L110
CROP_PADDING = 32
class MClassificationLoader(ABC):
"""Multitask Classification Dataloader."""
def __init__(self,
shape,
image_dirs,
label_csv,
batch_size=10,
data_format="channels_first",
interpolation_method="bicubic",
dtype=None):
"""Init.
Args:
image_dirs (list): list of image directories.
label_dirs (list): list of label directories.
interpolation_method (str): Bilinear / Bicubic.
mode (str): caffe / torch
crop (str): random / center
batch_size (int): size of the batch.
image_mean (list): image mean used for preprocessing.
dtype (str): data type to cast to
"""
self.image_paths = []
self.data_df = pd.read_csv(label_csv)
self._generate_class_mapping(self.data_df)
self._add_source(image_dirs[0])
self.image_paths = np.array(self.image_paths)
self.data_inds = np.arange(len(self.image_paths))
self.resample = Image.BILINEAR if interpolation_method == "bilinear" else Image.BICUBIC
self.data_format = data_format
if self.data_format == "channels_first":
self.height, self.width = shape[1], shape[2]
else:
self.height, self.width = shape[0], shape[1]
self.batch_size = batch_size
self.n_samples = len(self.data_inds)
self.dtype = dtype
self.n_batches = int(len(self.image_paths) // self.batch_size)
assert self.n_batches > 0, "empty image dir or batch size too large!"
def _add_source(self, image_folder):
"""Add classification sources."""
supported_img_format = ('.jpg', '.jpeg', '.png', '.bmp', '.gif')
for filename in self.filenames:
# Only add valid items to paths
img_path = os.path.join(image_folder, filename)
if filename.lower().endswith(supported_img_format) and os.path.exists(img_path):
self.image_paths.append(os.path.join(image_folder, img_path))
def __len__(self):
"""Get length of Sequence."""
return self.n_batches
def _generate_class_mapping(self, class_table):
"""Prepare task dictionary and class mapping."""
self.filenames = class_table.iloc[:, 0].values
self.samples = len(self.filenames)
self.tasks_header = sorted(class_table.columns.tolist()[1:])
self.class_dict = {}
self.class_mapping = {}
for task in self.tasks_header:
unique_vals = sorted(class_table.loc[:, task].unique())
self.class_dict[task] = len(unique_vals)
self.class_mapping[task] = dict(zip(unique_vals, range(len(unique_vals))))
# convert class dictionary to a sorted tolist
self.class_dict_list_sorted = sorted(self.class_dict.items(), key=lambda x: x[0])
self.class_mapping_inv = {}
for key, val in self.class_mapping.items():
self.class_mapping_inv[key] = {v: k for k, v in val.items()}
def _load_gt_image(self, image_path):
"""Load GT image from file."""
img = Image.open(image_path).convert('RGB')
return img
def __iter__(self):
"""Iterate."""
self.n = 0
return self
def __next__(self):
"""Load a full batch."""
images = []
labels = defaultdict(list)
if self.n < self.n_batches:
for idx in range(self.n * self.batch_size,
(self.n + 1) * self.batch_size):
image, label = self._get_single_processed_item(idx)
images.append(image)
for k, v in label.items():
labels[k].append(v)
self.n += 1
return self._batch_post_processing(images, labels)
raise StopIteration
def _batch_post_processing(self, images, labels):
"""Post processing for a batch."""
images = np.array(images)
final_labels = []
for _, v in labels.items():
final_labels.append(np.array(v))
return images, final_labels
def _get_single_processed_item(self, idx):
"""Load and process single image and its label."""
image, label = self._get_single_item_raw(idx)
image, label = self.preprocessing(image, label)
return image, label
def _get_single_item_raw(self, idx):
"""Load single image and its label.
Returns:
image (PIL.image): image object in original resolution
label (int): one-hot encoded class label
"""
image = self._load_gt_image(self.image_paths[self.data_inds[idx]])
label = self.data_df.iloc[idx, :]
return image, label
def preprocessing(self, image, label):
"""The image preprocessor loads an image from disk and prepares it as needed for batching.
This includes padding, resizing, normalization, data type casting, and transposing.
Args:
image (PIL.image): The Pillow image on disk to load.
Returns:
image (np.array): A numpy array holding the image sample, ready to be concatenated
into the rest of the batch
"""
image = image.resize((self.width, self.height), self.resample)
image = np.asarray(image, dtype=self.dtype)
if self.data_format == "channels_first":
image = np.transpose(image, (2, 0, 1))
# Normalize and apply imag mean and std
image = preprocess_input(image, data_format=self.data_format)
# one-hot-encoding
batch_y = {}
for c, cls_cnt in self.class_dict_list_sorted:
batch_y[c] = np.zeros(cls_cnt, dtype=self.dtype)
for c, _ in self.class_dict_list_sorted:
batch_y[c][self.class_mapping[c][label[c]]] = 1
return image, batch_y
| tao_deploy-main | nvidia_tao_deploy/cv/multitask_classification/dataloader.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""TAO Deploy Multitask Classification Proto."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
| tao_deploy-main | nvidia_tao_deploy/cv/multitask_classification/proto/__init__.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nvidia_tao_deploy/cv/multitask_classification/proto/experiment.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
from nvidia_tao_deploy.cv.common.proto import training_config_pb2 as nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_training__config__pb2
from nvidia_tao_deploy.cv.classification_tf1.proto import model_config_pb2 as nvidia__tao__deploy_dot_cv_dot_classification__tf1_dot_proto_dot_model__config__pb2
from nvidia_tao_deploy.cv.multitask_classification.proto import dataset_config_pb2 as nvidia__tao__deploy_dot_cv_dot_multitask__classification_dot_proto_dot_dataset__config__pb2
DESCRIPTOR = _descriptor.FileDescriptor(
name='nvidia_tao_deploy/cv/multitask_classification/proto/experiment.proto',
package='',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\nDnvidia_tao_deploy/cv/multitask_classification/proto/experiment.proto\x1a\x37nvidia_tao_deploy/cv/common/proto/training_config.proto\x1a@nvidia_tao_deploy/cv/classification_tf1/proto/model_config.proto\x1aHnvidia_tao_deploy/cv/multitask_classification/proto/dataset_config.proto\"\x94\x01\n\nExperiment\x12#\n\x0e\x64\x61taset_config\x18\x01 \x01(\x0b\x32\x0b.DataSource\x12\"\n\x0cmodel_config\x18\x02 \x01(\x0b\x32\x0c.ModelConfig\x12(\n\x0ftraining_config\x18\x03 \x01(\x0b\x32\x0f.TrainingConfig\x12\x13\n\x0brandom_seed\x18\x04 \x01(\rb\x06proto3')
,
dependencies=[nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_training__config__pb2.DESCRIPTOR,nvidia__tao__deploy_dot_cv_dot_classification__tf1_dot_proto_dot_model__config__pb2.DESCRIPTOR,nvidia__tao__deploy_dot_cv_dot_multitask__classification_dot_proto_dot_dataset__config__pb2.DESCRIPTOR,])
_EXPERIMENT = _descriptor.Descriptor(
name='Experiment',
full_name='Experiment',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='dataset_config', full_name='Experiment.dataset_config', index=0,
number=1, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='model_config', full_name='Experiment.model_config', index=1,
number=2, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='training_config', full_name='Experiment.training_config', index=2,
number=3, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='random_seed', full_name='Experiment.random_seed', index=3,
number=4, type=13, cpp_type=3, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=270,
serialized_end=418,
)
_EXPERIMENT.fields_by_name['dataset_config'].message_type = nvidia__tao__deploy_dot_cv_dot_multitask__classification_dot_proto_dot_dataset__config__pb2._DATASOURCE
_EXPERIMENT.fields_by_name['model_config'].message_type = nvidia__tao__deploy_dot_cv_dot_classification__tf1_dot_proto_dot_model__config__pb2._MODELCONFIG
_EXPERIMENT.fields_by_name['training_config'].message_type = nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_training__config__pb2._TRAININGCONFIG
DESCRIPTOR.message_types_by_name['Experiment'] = _EXPERIMENT
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
Experiment = _reflection.GeneratedProtocolMessageType('Experiment', (_message.Message,), dict(
DESCRIPTOR = _EXPERIMENT,
__module__ = 'nvidia_tao_deploy.cv.multitask_classification.proto.experiment_pb2'
# @@protoc_insertion_point(class_scope:Experiment)
))
_sym_db.RegisterMessage(Experiment)
# @@protoc_insertion_point(module_scope)
| tao_deploy-main | nvidia_tao_deploy/cv/multitask_classification/proto/experiment_pb2.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""TAO Deploy Config Base Utilities."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import logging
from google.protobuf.text_format import Merge as merge_text_proto
from nvidia_tao_deploy.cv.multitask_classification.proto.experiment_pb2 import Experiment
logging.basicConfig(format='%(asctime)s [TAO Toolkit] [%(levelname)s] %(name)s %(lineno)d: %(message)s',
level="INFO")
logger = logging.getLogger(__name__)
def load_proto(config):
"""Load the experiment proto."""
proto = Experiment()
def _load_from_file(filename, pb2):
if not os.path.exists(filename):
raise IOError(f"Specfile not found at: {filename}")
with open(filename, "r", encoding="utf-8") as f:
merge_text_proto(f.read(), pb2)
_load_from_file(config, proto)
return proto
| tao_deploy-main | nvidia_tao_deploy/cv/multitask_classification/proto/utils.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nvidia_tao_deploy/cv/multitask_classification/proto/dataset_config.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor.FileDescriptor(
name='nvidia_tao_deploy/cv/multitask_classification/proto/dataset_config.proto',
package='',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\nHnvidia_tao_deploy/cv/multitask_classification/proto/dataset_config.proto\"X\n\nDataSource\x12\x16\n\x0etrain_csv_path\x18\x01 \x01(\t\x12\x1c\n\x14image_directory_path\x18\x02 \x01(\t\x12\x14\n\x0cval_csv_path\x18\x03 \x01(\tb\x06proto3')
)
_DATASOURCE = _descriptor.Descriptor(
name='DataSource',
full_name='DataSource',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='train_csv_path', full_name='DataSource.train_csv_path', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='image_directory_path', full_name='DataSource.image_directory_path', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='val_csv_path', full_name='DataSource.val_csv_path', index=2,
number=3, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=76,
serialized_end=164,
)
DESCRIPTOR.message_types_by_name['DataSource'] = _DATASOURCE
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
DataSource = _reflection.GeneratedProtocolMessageType('DataSource', (_message.Message,), dict(
DESCRIPTOR = _DATASOURCE,
__module__ = 'nvidia_tao_deploy.cv.multitask_classification.proto.dataset_config_pb2'
# @@protoc_insertion_point(class_scope:DataSource)
))
_sym_db.RegisterMessage(DataSource)
# @@protoc_insertion_point(module_scope)
| tao_deploy-main | nvidia_tao_deploy/cv/multitask_classification/proto/dataset_config_pb2.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Multitask Classification convert etlt/onnx model to TRT engine."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import logging
import os
import json
import tempfile
from nvidia_tao_deploy.cv.common.decorators import monitor_status
from nvidia_tao_deploy.cv.multitask_classification.engine_builder import MClassificationEngineBuilder
from nvidia_tao_deploy.utils.decoding import decode_model
logging.basicConfig(format='%(asctime)s [TAO Toolkit] [%(levelname)s] %(name)s %(lineno)d: %(message)s',
level="INFO")
logger = logging.getLogger(__name__)
DEFAULT_MAX_BATCH_SIZE = 1
DEFAULT_MIN_BATCH_SIZE = 1
DEFAULT_OPT_BATCH_SIZE = 1
@monitor_status(name='multitask_classification', mode='gen_trt_engine')
def main(args):
"""Multitask Classification TRT convert."""
# decrypt etlt
tmp_onnx_file, file_format = decode_model(args.model_path, args.key)
if args.engine_file is not None or args.data_type == 'int8':
if args.engine_file is None:
engine_handle, temp_engine_path = tempfile.mkstemp()
os.close(engine_handle)
output_engine_path = temp_engine_path
else:
output_engine_path = args.engine_file
with open(args.class_map, "r", encoding="utf-8") as f:
output_tasks = json.load(f)['tasks']
builder = MClassificationEngineBuilder(output_tasks=output_tasks,
verbose=args.verbose,
workspace=args.max_workspace_size,
min_batch_size=args.min_batch_size,
opt_batch_size=args.opt_batch_size,
max_batch_size=args.max_batch_size,
strict_type_constraints=args.strict_type_constraints)
builder.create_network(tmp_onnx_file, file_format)
builder.create_engine(
output_engine_path,
args.data_type,
calib_data_file=args.cal_data_file,
calib_input=args.cal_image_dir,
calib_cache=args.cal_cache_file,
calib_num_images=args.batch_size * args.batches,
calib_batch_size=args.batch_size)
logging.info("Export finished successfully.")
def build_command_line_parser(parser=None):
"""Build the command line parser using argparse.
Args:
parser (subparser): Provided from the wrapper script to build a chained
parser mechanism.
Returns:
parser
"""
if parser is None:
parser = argparse.ArgumentParser(prog='gen_trt_engine',
description='Generate TRT engine of multitask classification model.')
parser.add_argument(
'-m',
'--model_path',
type=str,
required=True,
help='Path to a multitask classification .etlt or .onnx model file.'
)
parser.add_argument(
'-k',
'--key',
type=str,
required=False,
help='Key to save or load a .etlt model.'
)
parser.add_argument(
"-cm",
"--class_map",
type=str,
help="Path to the classmap JSON file.")
parser.add_argument(
"--data_type",
type=str,
default="fp32",
help="Data type for the TensorRT export.",
choices=["fp32", "fp16", "int8"])
parser.add_argument(
"--cal_image_dir",
default="",
type=str,
help="Directory of images to run int8 calibration.")
parser.add_argument(
"--cal_data_file",
default=None,
type=str,
help="Tensorfile to run calibration for int8 optimization.")
parser.add_argument(
'--cal_cache_file',
default=None,
type=str,
help='Calibration cache file to write to.')
parser.add_argument(
"--engine_file",
type=str,
default=None,
help="Path to the exported TRT engine.")
parser.add_argument(
"--max_batch_size",
type=int,
default=DEFAULT_MAX_BATCH_SIZE,
help="Max batch size for TensorRT engine builder.")
parser.add_argument(
"--min_batch_size",
type=int,
default=DEFAULT_MIN_BATCH_SIZE,
help="Min batch size for TensorRT engine builder.")
parser.add_argument(
"--opt_batch_size",
type=int,
default=DEFAULT_OPT_BATCH_SIZE,
help="Opt batch size for TensorRT engine builder.")
parser.add_argument(
"--batch_size",
type=int,
default=1,
help="Number of images per batch for calibration.")
parser.add_argument(
"--batches",
type=int,
default=10,
help="Number of batches to calibrate over.")
parser.add_argument(
"--max_workspace_size",
type=int,
default=2,
help="Max memory workspace size to allow in Gb for TensorRT engine builder (default: 2).")
parser.add_argument(
"-s",
"--strict_type_constraints",
action="store_true",
default=False,
help="A Boolean flag indicating whether to apply the \
TensorRT strict type constraints when building the TensorRT engine.")
parser.add_argument(
"-v",
"--verbose",
action="store_true",
default=False,
help="Verbosity of the logger.")
parser.add_argument(
'-r',
'--results_dir',
type=str,
required=True,
default=None,
help='Output directory where the log is saved.'
)
return parser
def parse_command_line_arguments(args=None):
"""Simple function to parse command line arguments."""
parser = build_command_line_parser(args)
return parser.parse_args(args)
if __name__ == '__main__':
args = parse_command_line_arguments()
main(args)
| tao_deploy-main | nvidia_tao_deploy/cv/multitask_classification/scripts/gen_trt_engine.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""TAO Deploy Classification TF1 scripts module."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
| tao_deploy-main | nvidia_tao_deploy/cv/multitask_classification/scripts/__init__.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Standalone TensorRT inference."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import logging
import os
import pandas as pd
import numpy as np
from tqdm.auto import tqdm
from nvidia_tao_deploy.cv.common.decorators import monitor_status
from nvidia_tao_deploy.cv.multitask_classification.inferencer import MClassificationInferencer
from nvidia_tao_deploy.cv.multitask_classification.dataloader import MClassificationLoader
from nvidia_tao_deploy.cv.multitask_classification.proto.utils import load_proto
logging.getLogger('PIL').setLevel(logging.WARNING)
logging.basicConfig(format='%(asctime)s [TAO Toolkit] [%(levelname)s] %(name)s %(lineno)d: %(message)s',
level="INFO")
logger = logging.getLogger(__name__)
@monitor_status(name='multitask_classification', mode='inference')
def main(args):
"""Multitask Classification TRT inference."""
es = load_proto(args.experiment_spec)
interpolation = es.model_config.resize_interpolation_method if es.model_config.resize_interpolation_method else 0
interpolation_map = {
0: "bilinear",
1: "bicubic"
}
interpolation_method = interpolation_map[interpolation]
# Override spec file if argument is provided
image_dirs = args.image_dir if args.image_dir else es.dataset_config.image_directory_path
batch_size = 1 # Inference is set to 1
trt_infer = MClassificationInferencer(args.model_path, batch_size=batch_size)
if trt_infer._input_shape[0] in [1, 3]:
data_format = "channels_first"
else:
data_format = "channels_last"
dl = MClassificationLoader(
trt_infer._input_shape,
[image_dirs],
es.dataset_config.val_csv_path,
data_format=data_format,
interpolation_method=interpolation_method,
batch_size=batch_size,
dtype=trt_infer.inputs[0].host.dtype)
if args.results_dir is None:
results_dir = os.path.dirname(args.model_path)
else:
results_dir = args.results_dir
result_csv_path = os.path.join(results_dir, 'result.csv')
with open(result_csv_path, 'w', encoding="utf-8") as csv_f:
for i, (imgs, _) in tqdm(enumerate(dl), total=len(dl), desc="Producing predictions"):
y_pred = trt_infer.infer(imgs)
image_paths = dl.image_paths[np.arange(batch_size) + batch_size * i]
conf = [np.max(pred.reshape(-1)) for pred in y_pred]
class_labels = []
for (c, _), pred in zip(dl.class_dict_list_sorted, y_pred):
class_labels.extend([dl.class_mapping_inv[c][np.argmax(p)] for p in pred])
r = {"filename": image_paths}
for idx, (c, _) in enumerate(dl.class_dict_list_sorted):
r[c] = [f"{class_labels[idx]} ({conf[idx]:.4f})"]
# Write predictions to file
df = pd.DataFrame.from_dict(r)
# Add header only for the first item
df.to_csv(csv_f, header=bool(i == 0), index=False)
logging.info("Finished inference.")
def build_command_line_parser(parser=None):
"""Build the command line parser using argparse.
Args:
parser (subparser): Provided from the wrapper script to build a chained
parser mechanism.
Returns:
parser
"""
if parser is None:
parser = argparse.ArgumentParser(prog='infer', description='Inference with a Multitask Classification TRT model.')
parser.add_argument(
'-i',
'--image_dir',
type=str,
required=False,
default=None,
help='Input directory of images')
parser.add_argument(
'-m',
'--model_path',
type=str,
required=True,
help='Path to the Classification TensorRT engine.'
)
parser.add_argument(
'-e',
'--experiment_spec',
type=str,
required=True,
help='Path to the experiment spec file.'
)
parser.add_argument(
'-r',
'--results_dir',
type=str,
required=True,
default=None,
help='Output directory where the log is saved.'
)
return parser
def parse_command_line_arguments(args=None):
"""Simple function to parse command line arguments."""
parser = build_command_line_parser(args)
return parser.parse_args(args)
if __name__ == '__main__':
args = parse_command_line_arguments()
main(args)
| tao_deploy-main | nvidia_tao_deploy/cv/multitask_classification/scripts/inference.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Standalone TensorRT evaluation."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import logging
import os
import json
import numpy as np
from collections import defaultdict
from tqdm.auto import tqdm
from nvidia_tao_deploy.cv.common.decorators import monitor_status
from nvidia_tao_deploy.cv.multitask_classification.inferencer import MClassificationInferencer
from nvidia_tao_deploy.cv.multitask_classification.dataloader import MClassificationLoader
from nvidia_tao_deploy.cv.multitask_classification.proto.utils import load_proto
logging.getLogger('PIL').setLevel(logging.WARNING)
logging.basicConfig(format='%(asctime)s [TAO Toolkit] [%(levelname)s] %(name)s %(lineno)d: %(message)s',
level="INFO")
logger = logging.getLogger(__name__)
@monitor_status(name='multitask_classification', mode='evaluation')
def main(args):
"""Multitask Classification TRT evaluation."""
es = load_proto(args.experiment_spec)
interpolation = es.model_config.resize_interpolation_method if es.model_config.resize_interpolation_method else 0
interpolation_map = {
0: "bilinear",
1: "bicubic"
}
interpolation_method = interpolation_map[interpolation]
# Override spec file if argument is provided
image_dirs = args.image_dir if args.image_dir else es.dataset_config.image_directory_path
batch_size = args.batch_size if args.batch_size else es.eval_config.batch_size
trt_infer = MClassificationInferencer(args.model_path, batch_size=batch_size)
if trt_infer._input_shape[0] in [1, 3]:
data_format = "channels_first"
else:
data_format = "channels_last"
dl = MClassificationLoader(
trt_infer._input_shape,
[image_dirs],
es.dataset_config.val_csv_path,
data_format=data_format,
interpolation_method=interpolation_method,
batch_size=batch_size,
dtype=trt_infer.inputs[0].host.dtype)
tp = defaultdict(list)
for imgs, labels in tqdm(dl, total=len(dl), desc="Producing predictions"):
y_pred = trt_infer.infer(imgs)
assert len(dl.class_dict_list_sorted) == len(labels) == len(y_pred), "Output size mismatch!"
for (c, _), gt, pred in zip(dl.class_dict_list_sorted, labels, y_pred):
tp[c].append((np.argmax(gt, axis=1) == np.argmax(pred, axis=1)).sum())
# Get acc for each task
eval_results = {}
for k, v in tp.items():
acc = sum(v) / len(dl.image_paths)
logging.info("%s accuracy: %s", k, acc)
eval_results[k] = float(acc)
# Store evaluation results into JSON
if args.results_dir is None:
results_dir = os.path.dirname(args.model_path)
else:
results_dir = args.results_dir
with open(os.path.join(results_dir, "results.json"), "w", encoding="utf-8") as f:
json.dump(eval_results, f)
logging.info("Finished evaluation.")
def build_command_line_parser(parser=None):
"""Build the command line parser using argparse.
Args:
parser (subparser): Provided from the wrapper script to build a chained
parser mechanism.
Returns:
parser
"""
if parser is None:
parser = argparse.ArgumentParser(prog='eval', description='Evaluate with a Multitask Classification TRT model.')
parser.add_argument(
'-i',
'--image_dir',
type=str,
required=False,
default=None,
help='Input directory of images')
parser.add_argument(
'-m',
'--model_path',
type=str,
required=True,
help='Path to the Classification TensorRT engine.'
)
parser.add_argument(
'-e',
'--experiment_spec',
type=str,
required=True,
help='Path to the experiment spec file.'
)
parser.add_argument(
'-b',
'--batch_size',
type=int,
required=False,
default=1,
help='Batch size.')
parser.add_argument(
'-r',
'--results_dir',
type=str,
required=True,
default=None,
help='Output directory where the log is saved.'
)
return parser
def parse_command_line_arguments(args=None):
"""Simple function to parse command line arguments."""
parser = build_command_line_parser(args)
return parser.parse_args(args)
if __name__ == '__main__':
args = parse_command_line_arguments()
main(args)
| tao_deploy-main | nvidia_tao_deploy/cv/multitask_classification/scripts/evaluate.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Entrypoint module for multitask classification."""
| tao_deploy-main | nvidia_tao_deploy/cv/multitask_classification/entrypoint/__init__.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""TAO Deploy command line wrapper to invoke CLI scripts."""
import sys
from nvidia_tao_deploy.cv.common.entrypoint.entrypoint_proto import launch_job
import nvidia_tao_deploy.cv.multitask_classification.scripts
def main():
"""Function to launch the job."""
launch_job(nvidia_tao_deploy.cv.multitask_classification.scripts, "multitask_classification", sys.argv[1:])
if __name__ == "__main__":
main()
| tao_deploy-main | nvidia_tao_deploy/cv/multitask_classification/entrypoint/multitask_classification.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Inference module."""
import numpy as np
from tqdm.auto import tqdm
from sklearn.neighbors import KNeighborsClassifier
from sklearn.preprocessing import normalize
from nvidia_tao_deploy.cv.classification_tf1.inferencer import ClassificationInferencer
from nvidia_tao_deploy.inferencer.utils import do_inference
def trt_output_process_fn(y_encoded):
"""Function to process TRT model output."""
cls_out = y_encoded[0]
return np.copy(cls_out)
class MLRecogInferencer(ClassificationInferencer):
"""Manages TensorRT objects for model inference."""
def __init__(self, engine_path, input_shape=None, batch_size=None):
"""Initializes TensorRT objects needed for model inference.
Args:
engine_path (str): path where TensorRT engine should be stored
input_shape (tuple): (batch, channel, height, width) for dynamic shape engine
batch_size (int): batch size for dynamic shape engine
"""
# Load TRT engine
super().__init__(engine_path, input_shape, batch_size, "channel_first")
def train_knn(self, gallery_dl, k=1):
"""Trains KNN model on gallery dataset.
Args:
gallery_dl (MLRecogClassificationLoader): gallery dataset loader
k (int): number of nearest neighbors to use
"""
image_embeds = []
labels = []
for imgs, labs in tqdm(gallery_dl):
image_embeds.append(self.get_embeddings(imgs))
labels.append(labs)
image_embeds = np.concatenate(image_embeds)
labels = np.concatenate(labels)
self.knn = KNeighborsClassifier(n_neighbors=k, metric="l2")
self.knn.fit(image_embeds, labels)
def infer(self, imgs):
"""Infers model on batch of same sized images resized to fit the model.
Args:
query (numpy.ndarray): batch of image numpy arrays
Returns:
dists (numpy.ndarray): distances to the nearest neighbors
indices (numpy.ndarray): indices of the nearest neighbors
"""
query_emb = self.get_embeddings(imgs)
dists, indices = self.knn.kneighbors(query_emb)
return dists, indices
def get_embeddings(self, imgs):
"""Returns normalized embeddings for a batch of images.
Args:
imgs (np.ndarray): batch of numpy arrays of images
Returns:
x_emb (np.ndarray): normalized embeddings
"""
x_emb = self.get_embeddings_from_batch(imgs)
x_emb = normalize(x_emb, norm="l2", axis=1)
return x_emb
def get_embeddings_from_batch(self, imgs):
"""Infers model on batch of same sized images resized to fit the model.
Args:
imgs (np.ndarray): batch of numpy arrays of images
Returns:
x_emb (np.ndarray): embeddings output from trt engine
"""
# Verify if the supplied batch size is not too big
max_batch_size = self.max_batch_size
actual_batch_size = len(imgs)
if actual_batch_size > max_batch_size:
raise ValueError(f"image_paths list bigger ({actual_batch_size}) than \
engine max batch size ({max_batch_size})")
self.numpy_array[:actual_batch_size] = imgs.reshape(actual_batch_size, -1)
# ...copy them into appropriate place into memory...
# (self.inputs was returned earlier by allocate_buffers())
np.copyto(self.inputs[0].host, self.numpy_array.ravel())
# ...fetch model outputs...
results = do_inference(
self.context, bindings=self.bindings, inputs=self.inputs,
outputs=self.outputs, stream=self.stream,
batch_size=max_batch_size,
execute_v2=self.execute_v2)
# ...and return results up to the actual batch size.
y_pred = [i.reshape(max_batch_size, -1)[:actual_batch_size] for i in results]
# Process TRT outputs to proper format
return trt_output_process_fn(y_pred)
| tao_deploy-main | nvidia_tao_deploy/cv/metric_learning_recognition/inferencer.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Metric Learning Recognition TensorRT engine builder."""
import logging
import os
import sys
import onnx
import tensorrt as trt
from nvidia_tao_deploy.engine.builder import EngineBuilder
from nvidia_tao_deploy.engine.calibrator import EngineCalibrator
from nvidia_tao_deploy.utils.image_batcher import ImageBatcher
logging.basicConfig(format='%(asctime)s [TAO Toolkit] [%(levelname)s] %(name)s %(lineno)d: %(message)s',
level="INFO")
logger = logging.getLogger(__name__)
class MLRecogEngineBuilder(EngineBuilder):
"""Parses an ONNX graph and builds a TensorRT engine from it."""
def __init__(
self,
input_dims,
is_dynamic=False,
img_mean=[0.485, 0.456, 0.406],
img_std=[0.229, 0.224, 0.225],
**kwargs
):
"""Init.
Args:
TODO
"""
super().__init__(**kwargs)
self._input_dims = input_dims
self.is_dynamic = is_dynamic
self._img_std = img_std
self._img_mean = img_mean
def get_onnx_input_dims(self, model_path):
"""Get input dimension of ONNX model."""
onnx_model = onnx.load(model_path)
onnx_inputs = onnx_model.graph.input
logger.info('List inputs:')
for i, inputs in enumerate(onnx_inputs):
logger.info('Input %s -> %s.', i, inputs.name)
logger.info('%s.', [i.dim_value for i in inputs.type.tensor_type.shape.dim][1:])
logger.info('%s.', [i.dim_value for i in inputs.type.tensor_type.shape.dim][0])
return [i.dim_value for i in inputs.type.tensor_type.shape.dim][:]
def create_network(self, model_path, file_format="onnx"):
"""Parse the UFF/ONNX graph and create the corresponding TensorRT network definition.
Args:
model_path: The path to the UFF/ONNX graph to load.
file_format: The file format of the decrypte file (default: onnx).
"""
if file_format == "onnx":
logger.info("Parsing ONNX model")
self.batch_size = self._input_dims[0]
self._input_dims = self._input_dims[1:]
network_flags = 1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)
network_flags = network_flags | (1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_PRECISION))
self.network = self.builder.create_network(network_flags)
self.parser = trt.OnnxParser(self.network, self.trt_logger)
model_path = os.path.realpath(model_path)
with open(model_path, "rb") as f:
if not self.parser.parse(f.read()):
logger.error("Failed to load ONNX file: %s", model_path)
for error in range(self.parser.num_errors):
logger.error(self.parser.get_error(error))
sys.exit(1)
inputs = [self.network.get_input(i) for i in range(self.network.num_inputs)]
outputs = [self.network.get_output(i) for i in range(self.network.num_outputs)]
logger.info("Network Description")
for input in inputs: # noqa pylint: disable=W0622
logger.info("Input '%s' with shape %s and dtype %s", input.name, input.shape, input.dtype)
for output in outputs:
logger.info("Output '%s' with shape %s and dtype %s", output.name, output.shape, output.dtype)
if self.is_dynamic: # dynamic batch size
logger.info("dynamic batch size handling")
opt_profile = self.builder.create_optimization_profile()
model_input = self.network.get_input(0)
input_shape = model_input.shape
input_name = model_input.name
real_shape_min = (self.min_batch_size, input_shape[1],
input_shape[2], input_shape[3])
real_shape_opt = (self.opt_batch_size, input_shape[1],
input_shape[2], input_shape[3])
real_shape_max = (self.max_batch_size, input_shape[1],
input_shape[2], input_shape[3])
opt_profile.set_shape(input=input_name,
min=real_shape_min,
opt=real_shape_opt,
max=real_shape_max)
self.config.add_optimization_profile(opt_profile)
self.config.set_calibration_profile(opt_profile)
else:
logger.info("Parsing UFF model")
raise NotImplementedError("UFF for MLRecog is not supported")
def create_engine(self, engine_path, precision,
calib_input=None, calib_cache=None, calib_num_images=5000,
calib_batch_size=8):
"""Build the TensorRT engine and serialize it to disk.
Args:
engine_path: The path where to serialize the engine to.
precision: The datatype to use for the engine, either 'fp32', 'fp16' or 'int8'.
calib_input: The path to a directory holding the calibration images.
calib_cache: The path where to write the calibration cache to,
or if it already exists, load it from.
calib_num_images: The maximum number of images to use for calibration.
calib_batch_size: The batch size to use for the calibration process.
"""
engine_path = os.path.realpath(engine_path)
engine_dir = os.path.dirname(engine_path)
os.makedirs(engine_dir, exist_ok=True)
logger.debug("Building %s Engine in %s", precision, engine_path)
inputs = [self.network.get_input(i) for i in range(self.network.num_inputs)]
if self.batch_size is None:
self.batch_size = calib_batch_size
self.builder.max_batch_size = self.batch_size
if precision == "fp16":
if not self.builder.platform_has_fast_fp16:
logger.warning("FP16 is not supported natively on this platform/device")
else:
self.config.set_flag(trt.BuilderFlag.FP16)
elif precision == "int8":
if not self.builder.platform_has_fast_int8:
logger.warning("INT8 is not supported natively on this platform/device")
else:
logger.warning("Enabling INT8 builder")
if self.builder.platform_has_fast_fp16 and not self._strict_type:
# Also enable fp16, as some layers may be even more efficient in fp16 than int8
self.config.set_flag(trt.BuilderFlag.FP16)
else:
self.config.set_flag(trt.BuilderFlag.STRICT_TYPES)
self.config.set_flag(trt.BuilderFlag.INT8)
# Set ImageBatcher based calibrator
self.set_calibrator(inputs=inputs,
calib_cache=calib_cache,
calib_input=calib_input,
calib_num_images=calib_num_images,
calib_batch_size=calib_batch_size)
self._logger_info_IBuilderConfig()
with self.builder.build_engine(self.network, self.config) as engine, \
open(engine_path, "wb") as f:
logger.debug("Serializing engine to file: %s", engine_path)
f.write(engine.serialize())
def set_calibrator(self,
inputs=None,
calib_cache=None,
calib_input=None,
calib_num_images=5000,
calib_batch_size=8):
"""Simple function to set an int8 calibrator. (Default is ImageBatcher based)
Args:
inputs (list): Inputs to the network
calib_input (str): The path to a directory holding the calibration images.
calib_cache (str): The path where to write the calibration cache to,
or if it already exists, load it from.
calib_num_images (int): The maximum number of images to use for calibration.
calib_batch_size (int): The batch size to use for the calibration process.
"""
logger.info("Calibrating using ImageBatcher")
self.config.int8_calibrator = EngineCalibrator(calib_cache)
if not os.path.exists(calib_cache):
calib_shape = [calib_batch_size] + list(inputs[0].shape[1:])
calib_dtype = trt.nptype(inputs[0].dtype)
self.config.int8_calibrator.set_image_batcher(
ImageBatcher(calib_input, calib_shape, calib_dtype,
max_num_images=calib_num_images,
exact_batches=True,
preprocessor='MLRecog',
img_std=self._img_std,
img_mean=self._img_mean))
| tao_deploy-main | nvidia_tao_deploy/cv/metric_learning_recognition/engine_builder.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""TAO Deploy Metric Learning Recognition."""
| tao_deploy-main | nvidia_tao_deploy/cv/metric_learning_recognition/__init__.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Classification and inference datasets loaders."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from pathlib import Path
from abc import ABC, abstractmethod
import numpy as np
from PIL import Image
from nvidia_tao_deploy.cv.common.constants import VALID_IMAGE_EXTENSIONS
def center_crop(img, new_width, new_height):
"""Center crops the image with given width and height.
Args:
img (Pillow.Image): input Pillow opened image.
new_width (int): the target width to resize to.
new_height (int): the target height to resize to.
Returns:
img (Pillow.Image): output Pillow image.
"""
width, height = img.size # Get dimensions
left = (width - new_width) / 2
top = (height - new_height) / 2
right = (width + new_width) / 2
bottom = (height + new_height) / 2
# Crop the center of the image
img = img.crop((left, top, right, bottom))
return img
class MLRecogDataLoader(ABC):
"""A base class for MLRecog classification and inference data loader."""
def __init__(self,
shape,
batch_size=10,
image_mean=None,
image_std=None,
image_depth=8,
dtype=None):
"""Init.
Args:
shape (list): list of input dimension that is either (c, h, w) or (h, w, c) format.
batch_size (int): size of the batch.
image_mean (list): image mean used for preprocessing.
image_std (list): image std used for preprocessing.
image_depth(int): Bit depth of images(8 or 16).
dtype (str): data type to cast to
"""
self.image_paths = []
self.labels = []
self.num_channels, self.height, self.width = shape
self.image_depth = image_depth
self.batch_size = batch_size
self.n_batches = 0
self.image_mean = image_mean if image_mean is not None else [0.0] * self.num_channels
self.image_std = image_std if image_std is not None else [1.0] * self.num_channels
self.model_img_mode = 'rgb' if self.num_channels == 3 else 'grayscale'
self.dtype = dtype
def __len__(self):
"""Get length of Sequence."""
return self.n_batches
def __iter__(self):
"""Iterate."""
self.n = 0
return self
@abstractmethod
def __next__(self):
"""Next object in loader"""
pass
def preprocessing(self, image):
"""The image preprocessor loads an image from disk and prepares it as needed for batching.
This includes resizing, centercrop, normalization, data type casting, and transposing.
Args:
image (PIL.image): The Pillow image on disk to load.
Returns:
image (np.array): A numpy array holding the image sample, ready to be concatenated
into the rest of the batch
"""
init_size = (int(self.width * 1.14), int(self.height * 1.14))
image = image.resize(init_size, resample=Image.BILINEAR)
image = center_crop(image, self.width, self.height)
image = np.asarray(image, dtype=self.dtype)
image /= 255.
rgb_mean = np.array(self.image_mean)
image -= rgb_mean
image /= np.array(self.image_std)
# fixed to channel first
if image.ndim == 2 and self.model_img_mode == 'grayscale':
image = np.expand_dims(image, axis=2)
image = np.transpose(image, (2, 0, 1))
return image
class MLRecogClassificationLoader(MLRecogDataLoader):
"""Classification Dataloader."""
def __init__(self,
shape,
image_dir,
class_mapping,
batch_size=10,
image_mean=None,
image_std=None,
image_depth=8,
dtype=None):
"""Initiates the classification dataloader.
Args:
shape (list): list of input dimension that is either (c, h, w) or (h, w, c) format.
image_dir (str): path of input directory.
class_mapping (dict): class mapping. e.g. {'aeroplane': 0, 'car': 1}
batch_size (int): size of the batch.
image_mean (list): image mean used for preprocessing.
image_std (list): image std used for preprocessing.
image_depth(int): Bit depth of images(8 or 16).
dtype (str): data type to cast to
"""
super().__init__(shape, batch_size, image_mean, image_std, image_depth, dtype)
self.class_mapping = class_mapping
self._add_source(image_dir) # add both image paths and labels
self.image_paths = np.array(self.image_paths)
self.data_inds = np.arange(len(self.image_paths))
self.n_samples = len(self.data_inds)
self.n_batches = int(len(self.image_paths) // self.batch_size)
assert self.n_batches > 0, "empty image dir or batch size too large!"
def _add_source(self, image_folder):
"""Adds classification sources."""
images = [p.resolve() for p in Path(image_folder).glob("**/*") if p.suffix in VALID_IMAGE_EXTENSIONS]
images = sorted(images)
labels = [self.class_mapping[p.parent.name] for p in images]
self.image_paths = images
self.labels = labels
def _load_gt_image(self, image_path):
"""Loads GT image from file."""
img = Image.open(image_path)
if self.num_channels == 3:
img = img.convert('RGB') # Color Image
else:
if self.image_depth == 16:
img = img.convert('I') # PIL int32 mode for 16-bit images
else:
img = img.convert('L') # Grayscale Image
return img
def __next__(self):
"""Loads a full batch."""
images = []
labels = []
if self.n < self.n_batches:
for idx in range(self.n * self.batch_size,
(self.n + 1) * self.batch_size):
image, label = self._get_single_processed_item(idx)
images.append(image)
labels.append(label)
self.n += 1
return self._batch_post_processing(images, labels)
raise StopIteration
def _batch_post_processing(self, images, labels):
"""Posts processing for a batch."""
images = np.array(images)
# try to make labels a numpy array
is_make_array = True
x_shape = None
for x in labels:
if not isinstance(x, np.ndarray):
is_make_array = False
break
if x_shape is None:
x_shape = x.shape
elif x_shape != x.shape:
is_make_array = False
break
if is_make_array:
labels = np.array(labels)
return images, labels
def _get_single_processed_item(self, idx):
"""Load and process single image and its label."""
image, label = self._get_single_item_raw(idx)
image = self.preprocessing(image)
return image, label
def _get_single_item_raw(self, idx):
"""Load single image and its label.
Returns:
image (PIL.image): image object in original resolution
label (int): one-hot encoded class label
"""
image = self._load_gt_image(self.image_paths[self.data_inds[idx]])
label = self.labels[idx]
return image, label
class MLRecogInferenceLoader(MLRecogDataLoader):
"""Inference Dataloader."""
def __init__(self,
shape,
image_dir,
input_type,
batch_size=10,
image_mean=None,
image_std=None,
image_depth=8,
dtype=None):
"""Initiates the inference loader.
Args:
shape (list): list of input dimension that is either (c, h, w) or (h, w, c) format.
image_dirs (list): list of image directories.
input_type (str): input type of the `image_dir`. Can be [`image_folder`, `classification_folder`]
batch_size (int): size of the batch.
image_mean (list): image mean used for preprocessing.
image_std (list): image std used for preprocessing.
image_depth(int): Bit depth of images(8 or 16).
dtype (str): data type to cast to
"""
super().__init__(shape, batch_size, image_mean, image_std, image_depth, dtype)
self._add_source(image_dir, input_type)
self.image_paths = np.array(self.image_paths)
self.data_inds = np.arange(len(self.image_paths))
self.n_samples = len(self.data_inds)
self.n_batches = int(len(self.image_paths) // self.batch_size)
assert self.n_batches > 0, "empty image dir or batch size too large!"
def _add_source(self, image_folder, input_type):
"""Add classification sources."""
if input_type == 'classification_folder':
images = [p.resolve() for p in Path(image_folder).glob("**/*") if p.suffix in VALID_IMAGE_EXTENSIONS]
elif input_type == 'image_folder':
images = [p.resolve() for p in Path(image_folder).glob("*") if p.suffix in VALID_IMAGE_EXTENSIONS]
else:
raise ValueError(f"Invalid input type: {input_type}")
images = sorted(images)
self.image_paths = images
def _load_gt_image(self, image_path):
"""Load GT image from file."""
img = Image.open(image_path)
if self.num_channels == 3:
img = img.convert('RGB') # Color Image
else:
if self.image_depth == 16:
img = img.convert('I') # PIL int32 mode for 16-bit images
else:
img = img.convert('L') # Grayscale Image
return img
def __next__(self):
"""Load a full batch."""
images = []
if self.n < self.n_batches:
for idx in range(self.n * self.batch_size,
(self.n + 1) * self.batch_size):
image = self._get_single_processed_item(idx)
images.append(image)
self.n += 1
return np.array(images)
raise StopIteration
def _get_single_processed_item(self, idx):
"""Load and process single image and its label."""
image = self._load_gt_image(self.image_paths[self.data_inds[idx]])
image = self.preprocessing(image)
return image
| tao_deploy-main | nvidia_tao_deploy/cv/metric_learning_recognition/dataloader.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""TAO Deploy Metric Learning Recognition Hydra."""
| tao_deploy-main | nvidia_tao_deploy/cv/metric_learning_recognition/hydra_config/__init__.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Default config file."""
from typing import Optional, List, Dict
from dataclasses import dataclass, field
from omegaconf import MISSING
@dataclass
class GaussianBlur:
"""Gaussian Blur configuration template."""
enabled: bool = True
kernel: List[int] = field(default_factory=lambda: [15, 15])
sigma: List[float] = field(default_factory=lambda: [0.3, 0.7])
@dataclass
class ColorAugmentation:
"""Color Augmentation configuration template."""
enabled: bool = True
brightness: float = 0.5
contrast: float = 0.3
saturation: float = 0.1
hue: float = 0.1
@dataclass
class DatasetConfig:
"""Metric Learning Recognition Dataset configuration template."""
train_dataset: Optional[str] = None
val_dataset: Optional[Dict[str, str]] = None
workers: int = 8
class_map: Optional[str] = None # TODO: add class_map support
pixel_mean: List[float] = field(default_factory=lambda: [0.485, 0.456, 0.406])
pixel_std: List[float] = field(default_factory=lambda: [0.226, 0.226, 0.226])
prob: float = 0.5
re_prob: float = 0.5
gaussian_blur: GaussianBlur = GaussianBlur()
color_augmentation: ColorAugmentation = ColorAugmentation()
random_rotation: bool = False
num_instance: int = 4
@dataclass
class ModelConfig:
"""Metric Learning Recognition model configuration for training, testing & validation."""
backbone: str = "resnet_50"
pretrain_choice: str = "imagenet"
pretrained_model_path: Optional[str] = None
input_channels: int = 3
input_width: int = 224
input_height: int = 224
feat_dim: int = 256
@dataclass
class EvalConfig:
"""Evaluation experiment configuration template."""
trt_engine: Optional[str] = None
checkpoint: Optional[str] = None
gpu_id: int = 0
batch_size: int = 64
topk: int = 1
report_accuracy_per_class: bool = True
results_dir: Optional[str] = None
@dataclass
class InferenceConfig:
"""Inference experiment configuration template."""
trt_engine: Optional[str] = None
checkpoint: Optional[str] = None
input_path: str = MISSING # a image file or a folder
inference_input_type: str = "image_folder" # possible values are "image_folder" and "classification_foler"
gpu_id: int = 0
topk: int = 1
batch_size: int = 64
results_dir: Optional[str] = None
@dataclass
class CalibrationConfig:
"""Calibration config."""
cal_cache_file: Optional[str] = None
cal_batch_size: int = 1
cal_batches: int = 1
cal_image_dir: Optional[List[str]] = field(default_factory=lambda: [])
@dataclass
class TrtConfig:
"""Trt config."""
data_type: str = "FP32"
workspace_size: int = 1024
min_batch_size: int = 1
opt_batch_size: int = 1
max_batch_size: int = 1
calibration: CalibrationConfig = CalibrationConfig()
@dataclass
class TrtEngineConfig:
"""Gen TRT Engine experiment config."""
results_dir: Optional[str] = None
gpu_id: int = 0
onnx_file: str = MISSING
trt_engine: Optional[str] = None
batch_size: int = -1
verbose: bool = False
tensorrt: TrtConfig = TrtConfig()
@dataclass
class ExperimentConfig:
"""Experiment config."""
model: ModelConfig = ModelConfig()
evaluate: EvalConfig = EvalConfig()
dataset: DatasetConfig = DatasetConfig()
inference: InferenceConfig = InferenceConfig()
gen_trt_engine: TrtEngineConfig = TrtEngineConfig()
results_dir: Optional[str] = None
| tao_deploy-main | nvidia_tao_deploy/cv/metric_learning_recognition/hydra_config/default_config.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Metric Learning Recognition convert onnx model to TRT engine."""
import logging
import os
import tempfile
from nvidia_tao_deploy.cv.metric_learning_recognition.engine_builder import MLRecogEngineBuilder
from nvidia_tao_deploy.cv.common.hydra.hydra_runner import hydra_runner
from nvidia_tao_deploy.cv.metric_learning_recognition.hydra_config.default_config import ExperimentConfig
from nvidia_tao_deploy.cv.common.decorators import monitor_status
logging.basicConfig(format='%(asctime)s [TAO Toolkit] [%(levelname)s] %(name)s %(lineno)d: %(message)s',
level="INFO")
logger = logging.getLogger(__name__)
spec_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
@hydra_runner(
config_path=os.path.join(spec_root, "specs"),
config_name="export", schema=ExperimentConfig
)
@monitor_status(name='ml_recog', mode='gen_trt_engine')
def main(cfg: ExperimentConfig) -> None:
"""Convert encrypted uff or onnx model to TRT engine."""
if cfg.gen_trt_engine.results_dir is not None:
results_dir = cfg.gen_trt_engine.results_dir
else:
results_dir = os.path.join(cfg.results_dir, "gen_trt_engine")
os.makedirs(results_dir, exist_ok=True)
engine_file = cfg.gen_trt_engine.trt_engine
data_type = cfg.gen_trt_engine.tensorrt.data_type
workspace_size = cfg.gen_trt_engine.tensorrt.workspace_size
min_batch_size = cfg.gen_trt_engine.tensorrt.min_batch_size
opt_batch_size = cfg.gen_trt_engine.tensorrt.opt_batch_size
max_batch_size = cfg.gen_trt_engine.tensorrt.max_batch_size
batch_size = cfg.gen_trt_engine.batch_size
num_channels = cfg.model.input_channels
input_width = cfg.model.input_width
input_height = cfg.model.input_height
# INT8 related configs
img_std = cfg.dataset.pixel_std
img_mean = cfg.dataset.pixel_mean
calib_input = list(cfg.gen_trt_engine.tensorrt.calibration.get('cal_image_dir', []))
calib_cache = cfg.gen_trt_engine.tensorrt.calibration.get('cal_cache_file', None)
if batch_size is None or batch_size == -1:
input_batch_size = 1
is_dynamic = True
else:
input_batch_size = batch_size
is_dynamic = False
if engine_file is not None:
if engine_file is None:
engine_handle, temp_engine_path = tempfile.mkstemp()
os.close(engine_handle)
output_engine_path = temp_engine_path
else:
output_engine_path = engine_file
builder = MLRecogEngineBuilder(
workspace=workspace_size // 1024,
input_dims=(input_batch_size, num_channels, input_height, input_width),
is_dynamic=is_dynamic,
min_batch_size=min_batch_size,
opt_batch_size=opt_batch_size,
max_batch_size=max_batch_size,
img_std=img_std,
img_mean=img_mean)
builder.create_network(cfg.gen_trt_engine.onnx_file, "onnx")
builder.create_engine(
output_engine_path,
data_type,
calib_input=calib_input,
calib_cache=calib_cache,
calib_num_images=cfg.gen_trt_engine.tensorrt.calibration.cal_batch_size * cfg.gen_trt_engine.tensorrt.calibration.cal_batches,
calib_batch_size=cfg.gen_trt_engine.tensorrt.calibration.cal_batch_size
)
logging.info("Export finished successfully.")
if __name__ == '__main__':
main()
| tao_deploy-main | nvidia_tao_deploy/cv/metric_learning_recognition/scripts/gen_trt_engine.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""TAO Deploy Metric Learning Recognition scripts modules."""
| tao_deploy-main | nvidia_tao_deploy/cv/metric_learning_recognition/scripts/__init__.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Standalone TensorRT inference."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import logging
import os
import numpy as np
import pandas as pd
from tqdm.auto import tqdm
from nvidia_tao_deploy.cv.common.hydra.hydra_runner import hydra_runner
from nvidia_tao_deploy.cv.common.decorators import monitor_status
from nvidia_tao_deploy.cv.metric_learning_recognition.hydra_config.default_config import ExperimentConfig
from nvidia_tao_deploy.cv.metric_learning_recognition.inferencer import MLRecogInferencer
from nvidia_tao_deploy.cv.metric_learning_recognition.dataloader import MLRecogInferenceLoader, MLRecogClassificationLoader
from nvidia_tao_deploy.utils.path_utils import expand_path
logging.getLogger('PIL').setLevel(logging.WARNING)
logging.basicConfig(format='%(asctime)s [TAO Toolkit] [%(levelname)s] %(name)s %(lineno)d: %(message)s',
level="INFO")
logger = logging.getLogger(__name__)
spec_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
@hydra_runner(
config_path=os.path.join(spec_root, "specs"),
config_name="inference", schema=ExperimentConfig
)
@monitor_status(name='ml_recog', mode='inference')
def main(cfg: ExperimentConfig) -> None:
"""MLRecog TRT inference."""
classmap = cfg.dataset.class_map
if classmap:
# if classmap is provided, we explicitly set the mapping from the text file
if not os.path.exists(classmap):
raise FileNotFoundError(f"{classmap} does not exist!")
with open(classmap, "r", encoding="utf-8") as f:
mapping_dict = {line.rstrip(): idx for idx, line in enumerate(f.readlines())}
else:
# If not, the order of the classes are alphanumeric as defined by Keras
# Ref: https://github.com/keras-team/keras/blob/07e13740fd181fc3ddec7d9a594d8a08666645f6/keras/preprocessing/image.py#L507
mapping_dict = {}
for idx, subdir in enumerate(sorted(os.listdir(cfg.dataset.val_dataset["reference"]))):
if os.path.isdir(os.path.join(cfg.dataset.val_dataset["reference"], subdir)):
mapping_dict[subdir] = idx
top_k = cfg.inference.topk
img_mean = cfg.dataset.pixel_mean
img_std = cfg.dataset.pixel_std
batch_size = cfg.inference.batch_size
input_shape = (batch_size, cfg.model.input_channels, cfg.model.input_height, cfg.model.input_width)
trt_infer = MLRecogInferencer(cfg.inference.trt_engine,
input_shape=input_shape,
batch_size=batch_size)
gallery_dl = MLRecogClassificationLoader(
trt_infer._input_shape,
cfg.dataset.val_dataset["reference"],
mapping_dict,
batch_size=batch_size,
image_mean=img_mean,
image_std=img_std,
dtype=trt_infer.inputs[0].host.dtype)
query_dl = MLRecogInferenceLoader(
trt_infer._input_shape,
cfg.inference.input_path,
cfg.inference.inference_input_type,
batch_size=batch_size,
image_mean=img_mean,
image_std=img_std,
dtype=trt_infer.inputs[0].host.dtype)
logging.info("Loading gallery dataset...")
trt_infer.train_knn(gallery_dl, k=top_k)
if cfg.inference.results_dir is not None:
results_dir = cfg.inference.results_dir
else:
results_dir = os.path.join(cfg.results_dir, "trt_inference")
os.makedirs(results_dir, exist_ok=True)
result_csv_path = os.path.join(results_dir, 'trt_result.csv')
with open(expand_path(result_csv_path), 'w', encoding="utf-8") as csv_f:
for i, imgs in tqdm(enumerate(query_dl), total=len(query_dl), desc="Producing predictions"):
dists, indices = trt_infer.infer(imgs)
image_paths = query_dl.image_paths[np.arange(batch_size) + batch_size * i]
class_indices = []
class_labels = []
for ind in indices:
class_inds = [gallery_dl.labels[i] for i in ind]
class_indices.append(class_inds)
# Map label index to label name
class_lab = map(lambda i: list(mapping_dict.keys())
[list(mapping_dict.values()).index(i)],
class_inds)
class_labels.append(list(class_lab))
dist_list = []
for dist in dists:
dist_list.append([round(float(d)**2, 4) for d in dist]) # match tao distance outputs: L2 distance squared
# Write predictions to file
df = pd.DataFrame(zip(image_paths, class_labels, dist_list))
df.to_csv(csv_f, header=False, index=False)
logging.info("Finished inference.")
if __name__ == '__main__':
main()
| tao_deploy-main | nvidia_tao_deploy/cv/metric_learning_recognition/scripts/inference.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Standalone TensorRT evaluation."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import logging
import os
import json
import numpy as np
from tqdm.auto import tqdm
from sklearn.metrics import classification_report, confusion_matrix
from nvidia_tao_deploy.cv.metric_learning_recognition.inferencer import MLRecogInferencer
from nvidia_tao_deploy.cv.metric_learning_recognition.dataloader import MLRecogClassificationLoader
from nvidia_tao_deploy.cv.common.decorators import monitor_status
from nvidia_tao_deploy.cv.common.hydra.hydra_runner import hydra_runner
from nvidia_tao_deploy.cv.metric_learning_recognition.hydra_config.default_config import ExperimentConfig
logging.getLogger('PIL').setLevel(logging.WARNING)
logging.basicConfig(format='%(asctime)s [TAO Toolkit] [%(levelname)s] %(name)s %(lineno)d: %(message)s',
level="INFO")
logger = logging.getLogger(__name__)
spec_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
def top_k_accuracy(ground_truth, predicted_labels, k):
"""Calculates the top k accuracy given ground truth labels and predicted labels.
Args:
ground_truth (numpy.ndarray): Array of ground truth labels.
predicted_labels (numpy.ndarray): Array of predicted labels.
k (int): The value of k for top k accuracy.
Returns:
float: The top k accuracy.
"""
top_k = predicted_labels[:, :k]
correct = np.sum(np.any(top_k == ground_truth, axis=1))
return correct / len(predicted_labels)
def average_topk_accuracy_per_class(ground_truth, predicted_labels, k):
"""Calculates the average top k accuracy per class given ground truth labels and predicted labels.
Args:
ground_truth (numpy.ndarray): Array of ground truth labels.
predicted_labels (numpy.ndarray): Array of predicted labels.
k (int): The value of k for top k accuracy.
Returns:
accuracy (numpy.float64): The average top k accuracy per class.
"""
num_classes = len(np.unique(ground_truth))
class_acc = []
for i in range(num_classes):
class_indices = np.where(ground_truth == i)[0]
class_pred = predicted_labels[class_indices]
class_acc.append(top_k_accuracy(i, class_pred, k))
return np.mean(class_acc)
@hydra_runner(
config_path=os.path.join(spec_root, "specs"),
config_name="evaluate", schema=ExperimentConfig
)
@monitor_status(name='ml_recog', mode='evaluation')
def main(cfg: ExperimentConfig) -> None:
"""Mwteic Learning Recognition TRT evaluation."""
classmap = cfg.dataset.class_map
if classmap:
# if classmap is provided, we explicitly set the mapping from the text file
if not os.path.exists(classmap):
raise FileNotFoundError(f"{classmap} does not exist!")
with open(classmap, "r", encoding="utf-8") as f:
mapping_dict = {line.rstrip(): idx for idx, line in enumerate(f.readlines())}
else:
# If not, the order of the classes are alphanumeric as defined by Keras
# Ref: https://github.com/keras-team/keras/blob/07e13740fd181fc3ddec7d9a594d8a08666645f6/keras/preprocessing/image.py#L507
mapping_dict = {}
for idx, subdir in enumerate(sorted(os.listdir(cfg.dataset.val_dataset["reference"]))):
if os.path.isdir(os.path.join(cfg.dataset.val_dataset["reference"], subdir)):
mapping_dict[subdir] = idx
# Load hparams
target_names = [c[0] for c in sorted(mapping_dict.items(), key=lambda x:x[1])]
top_k = cfg.evaluate.topk
image_mean = cfg.dataset.pixel_mean
img_std = cfg.dataset.pixel_std
batch_size = cfg.evaluate.batch_size
input_shape = (batch_size, cfg.model.input_channels, cfg.model.input_height, cfg.model.input_width)
trt_infer = MLRecogInferencer(cfg.evaluate.trt_engine,
input_shape=input_shape,
batch_size=batch_size)
gallery_dl = MLRecogClassificationLoader(
trt_infer._input_shape,
cfg.dataset.val_dataset["reference"],
mapping_dict,
batch_size=batch_size,
image_mean=image_mean,
image_std=img_std,
dtype=trt_infer.inputs[0].host.dtype)
query_dl = MLRecogClassificationLoader(
trt_infer._input_shape,
cfg.dataset.val_dataset["query"],
mapping_dict,
batch_size=batch_size,
image_mean=image_mean,
image_std=img_std,
dtype=trt_infer.inputs[0].host.dtype)
logging.info("Loading gallery dataset...")
trt_infer.train_knn(gallery_dl, k=top_k)
gt_labels = []
pred_labels = []
for imgs, labels in tqdm(query_dl, total=len(query_dl), desc="Producing predictions"):
gt_labels.extend(labels)
_, indices = trt_infer.infer(imgs)
pred_y = []
for ind in indices:
pred_y.append([gallery_dl.labels[i] for i in ind])
pred_labels.extend(pred_y)
gt_labels = np.array(gt_labels)
pred_labels = np.array(pred_labels)
# Metric calculation
target_names = np.array([c[0] for c in sorted(mapping_dict.items(), key=lambda x:x[1])])
target_labels = np.array([c[1] for c in sorted(mapping_dict.items(), key=lambda x:x[1])])
# get the average of class accuracies:
scores = average_topk_accuracy_per_class(gt_labels, pred_labels, k=top_k)
scores_top1 = average_topk_accuracy_per_class(gt_labels, pred_labels, k=1)
logging.info("Top %s scores: %s", 1, scores_top1)
logging.info("Top %s scores: %s", top_k, scores)
logging.info("Confusion Matrix")
y_predictions = pred_labels[:, 0] # get the top 1 prediction
print(confusion_matrix(gt_labels, y_predictions))
logging.info("Classification Report")
print(classification_report(gt_labels, y_predictions, labels=target_labels, target_names=target_names))
# Store evaluation results into JSON
eval_results = {"top_k_accuracy": scores,
"top_1_accuracy": scores_top1}
if cfg.evaluate.results_dir is not None:
results_dir = cfg.evaluate.results_dir
else:
results_dir = os.path.join(cfg.results_dir, "trt_evaluate")
os.makedirs(results_dir, exist_ok=True)
with open(os.path.join(results_dir, "results.json"), "w", encoding="utf-8") as f:
json.dump(eval_results, f)
logging.info("Finished evaluation.")
if __name__ == '__main__':
main()
| tao_deploy-main | nvidia_tao_deploy/cv/metric_learning_recognition/scripts/evaluate.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""TAO Deploy command line wrapper to invoke CLI scripts."""
import argparse
from nvidia_tao_deploy.cv.metric_learning_recognition import scripts
from nvidia_tao_deploy.cv.common.entrypoint.entrypoint_hydra import get_subtasks, launch
def main():
"""Main entrypoint wrapper."""
# Create parser for a given task.
parser = argparse.ArgumentParser(
"ml_recog",
add_help=True,
description="Train Adapt Optimize Deploy entrypoint for Metric Learning Recognition model"
)
# Build list of subtasks by inspecting the scripts package.
subtasks = get_subtasks(scripts)
# Parse the arguments and launch the subtask.
launch(parser, subtasks, network="ml_recog")
if __name__ == '__main__':
main()
| tao_deploy-main | nvidia_tao_deploy/cv/metric_learning_recognition/entrypoint/metric_learning_recognition.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Entrypoint module for metric learning recognition."""
| tao_deploy-main | nvidia_tao_deploy/cv/metric_learning_recognition/entrypoint/__init__.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Post processing handler for TLT DetectNet_v2 models."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import logging
import operator
from time import time
import numpy as np
from six.moves import range
from nvidia_tao_deploy.cv.detectnet_v2.utils import cluster_bboxes
logging.basicConfig(format='%(asctime)s [TAO Toolkit] [%(levelname)s] %(name)s %(lineno)d: %(message)s',
level="INFO")
logger = logging.getLogger(__name__)
criterion = 'IOU'
scales = [(1.0, 'cc')]
CLUSTERING_ALGORITHM = {
0: "dbscan",
1: "nms",
2: "hybrid",
"dbscan": "dbscan",
"nms": "nms",
"hybrid": "hybrid",
}
class BboxHandler(object):
"""Class to handle bbox output from the inference script."""
def __init__(self, spec=None, **kwargs):
"""Setting up Bbox handler."""
self.spec = spec
self.cluster_params = {}
self.frame_height = kwargs.get('frame_height', 544)
self.frame_width = kwargs.get('frame_width', 960)
self.bbox_normalizer = kwargs.get('bbox_normalizer', 35)
self.bbox = kwargs.get('bbox', 'ltrb')
self.cluster_params = kwargs.get('cluster_params', None)
self.classwise_cluster_params = kwargs.get("classwise_cluster_params", None)
self.bbox_norm = (self.bbox_normalizer, ) * 2
self.stride = kwargs.get("stride", 16)
self.train_img_size = kwargs.get('train_img_size', None)
self.save_kitti = kwargs.get('save_kitti', True)
self.image_overlay = kwargs.get('image_overlay', True)
self.extract_crops = kwargs.get('extract_crops', True)
self.target_classes = kwargs.get('target_classes', None)
self.bbox_offset = kwargs.get("bbox_offset", 0.5)
self.clustering_criterion = kwargs.get("criterion", "IOU")
self.postproc_classes = kwargs.get('postproc_classes', self.target_classes)
confidence_threshold = {}
nms_confidence_threshold = {}
for key, value in list(self.classwise_cluster_params.items()):
confidence_threshold[key] = value.clustering_config.dbscan_confidence_threshold
if value.clustering_config.nms_confidence_threshold:
nms_confidence_threshold[key] = value.clustering_config.nms_confidence_threshold
self.state = {
'scales': scales,
'display_classes': self.target_classes,
'min_height': 0,
'criterion': criterion,
'confidence_th': {'car': 0.9, 'person': 0.1, 'truck': 0.1},
'nms_confidence_th': {'car': 0.9, 'person': 0.1, 'truck': 0.1},
'cluster_weights': (1.0, 1.0, 1.0, 1.0, 1.0, 1.0)
}
self.state['confidence_th'] = confidence_threshold
self.state['nms_confidence_th'] = nms_confidence_threshold
def bbox_preprocessing(self, input_cluster):
"""Function to perform inplace manipulation of prediction dicts before clustering.
Args:
input_cluster (Dict): prediction dictionary of output cov and bbox per class.
Returns:
input_cluster (Dict): shape manipulated prediction dictionary.
"""
for classes in self.target_classes:
input_cluster[classes]['bbox'] = self.abs_bbox_converter(input_cluster[classes]
['bbox'])
# Stack predictions
for keys in list(input_cluster[classes].keys()):
if 'bbox' in keys:
input_cluster[classes][keys] = \
input_cluster[classes][keys][np.newaxis, :, :, :, :]
input_cluster[classes][keys] = \
np.asarray(input_cluster[classes][keys]).transpose((1, 2, 3, 4, 0))
elif 'cov' in keys:
input_cluster[classes][keys] = input_cluster[classes][keys][np.newaxis,
np.newaxis,
:, :, :]
input_cluster[classes][keys] = \
np.asarray(input_cluster[classes][keys]).transpose((2, 1, 3, 4, 0))
return input_cluster
def abs_bbox_converter(self, bbox):
"""Convert the raw grid cell corrdinates to image space coordinates.
Args:
bbox (np.array): BBox coordinates blob per batch with shape [n, 4, h, w].
Returns:
bbox (np.array): BBox coordinates reconstructed from grid cell based coordinates
with the same dimensions.
"""
target_shape = bbox.shape[-2:]
# Define grid cell centers
gc_centers = [(np.arange(s) * self.stride + self.bbox_offset) for s in target_shape]
gc_centers = [s / n for s, n in zip(gc_centers, self.bbox_norm)]
# Mapping cluster output
if self.bbox == 'arxy':
assert not self.train_img_size, \
"ARXY bbox format needs same train and inference image shapes."
# reverse mapping of abs bbox to arxy
area = (bbox[:, 0, :, :] / 10.) ** 2.
width = np.sqrt(area * bbox[:, 1, :, :])
height = np.sqrt(area / bbox[:, 1, :, :])
cen_x = width * bbox[:, 2, :, :] + gc_centers[0][:, np.newaxis]
cen_y = height * bbox[:, 3, :, :] + gc_centers[1]
bbox[:, 0, :, :] = cen_x - width / 2.
bbox[:, 1, :, :] = cen_y - height / 2.
bbox[:, 2, :, :] = cen_x + width / 2.
bbox[:, 3, :, :] = cen_y + height / 2.
bbox[:, 0, :, :] *= self.bbox_norm[0]
bbox[:, 1, :, :] *= self.bbox_norm[1]
bbox[:, 2, :, :] *= self.bbox_norm[0]
bbox[:, 3, :, :] *= self.bbox_norm[1]
elif self.bbox == 'ltrb':
# Convert relative LTRB bboxes to absolute bboxes inplace.
# Input bbox in format (image, bbox_value,
# grid_cell_x, grid_cell_y).
# Ouput bboxes given in pixel coordinates in the source resolution.
if not self.train_img_size:
self.train_img_size = self.bbox_norm
# Compute scalers that allow using different resolution in
# inference and training
scale_w = self.bbox_norm[0] / self.train_img_size[0]
scale_h = self.bbox_norm[1] / self.train_img_size[1]
bbox[:, 0, :, :] -= gc_centers[0][:, np.newaxis] * scale_w
bbox[:, 1, :, :] -= gc_centers[1] * scale_h
bbox[:, 2, :, :] += gc_centers[0][:, np.newaxis] * scale_w
bbox[:, 3, :, :] += gc_centers[1] * scale_h
bbox[:, 0, :, :] *= -self.train_img_size[0]
bbox[:, 1, :, :] *= -self.train_img_size[1]
bbox[:, 2, :, :] *= self.train_img_size[0]
bbox[:, 3, :, :] *= self.train_img_size[1]
return bbox
def cluster_detections(self, preds):
"""Cluster detections and filter based on confidence.
Also determines false positives and missed detections based on the
clustered detections.
Args:
- spec: The experiment spec
- preds: Raw predictions, a Dict of Dicts
- state: The DetectNet_v2 viz state
Returns:
- classwise_detections (NamedTuple): DBSCan clustered detections.
"""
# Cluster
classwise_detections = {}
clustering_time = 0.
for object_type in preds:
start_time = time()
if object_type not in list(self.classwise_cluster_params.keys()):
logger.info("Object type %s not defined in cluster file. Falling back to default"
"values", object_type)
buffer_type = "default"
if buffer_type not in list(self.classwise_cluster_params.keys()):
raise ValueError("If the class-wise cluster params for an object isn't "
"there then please mention a default class.")
else:
buffer_type = object_type
logger.debug("Clustering bboxes %s", buffer_type)
classwise_params = self.classwise_cluster_params[buffer_type]
clustering_config = classwise_params.clustering_config
clustering_algorithm = CLUSTERING_ALGORITHM[clustering_config.clustering_algorithm]
# clustering_algorithm = clustering_config.clustering_algorithm
nms_iou_threshold = 0.3
if clustering_config.nms_iou_threshold:
nms_iou_threshold = clustering_config.nms_iou_threshold
confidence_threshold = self.state['confidence_th'].get(buffer_type, 0.1)
nms_confidence_threshold = self.state['nms_confidence_th'].get(buffer_type, 0.1)
detections = cluster_bboxes(preds[object_type],
criterion=self.clustering_criterion,
eps=classwise_params.clustering_config.dbscan_eps + 1e-12,
min_samples=clustering_config.dbscan_min_samples,
min_weight=clustering_config.coverage_threshold,
min_height=clustering_config.minimum_bounding_box_height,
confidence_model='aggregate_cov', # TODO: Not hardcode (evaluation doesn't have this option)
cluster_weights=self.state['cluster_weights'],
confidence_threshold=confidence_threshold,
clustering_algorithm=clustering_algorithm,
nms_iou_threshold=nms_iou_threshold,
nms_confidence_threshold=nms_confidence_threshold)
clustering_time += (time() - start_time) / len(preds)
classwise_detections[object_type] = detections
return classwise_detections
def postprocess(self, class_wise_detections, batch_size, image_size, resized_size, classes):
"""Reformat classwise detections into a single 2d-array for metric calculation.
Args:
class_wise_detections (dict): detections per target classes
batch_size (int): size of batches to process
image_size (list): list of tuples containing original image size
resized_size (tuple): a tuple containing the model input size
classes (list): list containing target classes in the correct order
"""
results = []
for image_idx in range(batch_size):
frame_width, frame_height = resized_size
scaling_factor = tuple(map(operator.truediv, image_size[image_idx], resized_size))
per_image_results = []
for key in class_wise_detections.keys():
bbox_list, confidence_list = _get_bbox_and_confs(class_wise_detections[key][image_idx],
scaling_factor,
key,
"aggregate_cov", # TODO: Not hard-code
frame_height,
frame_width)
bbox_list = np.array(bbox_list)
cls_id = [classes[key]] * len(bbox_list)
if not len(bbox_list):
continue
# each row: cls_id, conf, x1, y1, x2, y2
result = np.stack((cls_id, confidence_list, bbox_list[:, 0], bbox_list[:, 1], bbox_list[:, 2], bbox_list[:, 3]), axis=-1)
per_image_results.append(result)
# Handle cases when there was no detections made at all
if len(per_image_results) == 0:
null_prediction = np.zeros((1, 6))
null_prediction[0][0] = 1 # Dummy class which will be filtered out later.
results.append(null_prediction)
logger.debug("Adding null predictions as there were no predictions made.")
continue
per_image_results = np.concatenate(per_image_results)
results.append(per_image_results)
return results
def _get_bbox_and_confs(classwise_detections, scaling_factor,
key, confidence_model, frame_height,
frame_width):
"""Simple function to get bbox and confidence formatted list."""
bbox_list = []
confidence_list = []
for i in range(len(classwise_detections)):
bbox_object = classwise_detections[i]
coords_scaled = _scale_bbox(bbox_object.bbox, scaling_factor,
frame_height, frame_width)
if confidence_model == 'mlp':
confidence = bbox_object.confidence[0]
else:
confidence = bbox_object.confidence
bbox_list.append(coords_scaled)
confidence_list.append(confidence)
return bbox_list, confidence_list
def _scale_bbox(bbox, scaling_factor, frame_height, frame_width):
"""Scale bbox coordinates back to original image dimensions.
Args:
bbox (list): bbox coordinates ltrb
scaling factor (float): input_image size/model inference size
Returns:
bbox_scaled (list): list of scaled coordinates
"""
# Clipping and clamping coordinates.
x1 = min(max(0.0, float(bbox[0])), frame_width)
y1 = min(max(0.0, float(bbox[1])), frame_height)
x2 = max(min(float(bbox[2]), frame_width), x1)
y2 = max(min(float(bbox[3]), frame_height), y1)
# Rescaling center.
hx, hy = x2 - x1, y2 - y1
cx = x1 + hx / 2
cy = y1 + hy / 2
# Rescaling height, width
nx, ny = cx * scaling_factor[0], cy * scaling_factor[1]
nhx, nhy = hx * scaling_factor[0], hy * scaling_factor[1]
# Final bbox coordinates.
nx1, nx2 = nx - nhx / 2, nx + nhx / 2
ny1, ny2 = ny - nhy / 2, ny + nhy / 2
# Stacked coordinates.
bbox_scaled = np.asarray([nx1, ny1, nx2, ny2])
return bbox_scaled
| tao_deploy-main | nvidia_tao_deploy/cv/detectnet_v2/postprocessor.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utility class for performing TensorRT image inference."""
import numpy as np
from PIL import ImageDraw
import tensorrt as trt
from nvidia_tao_deploy.inferencer.trt_inferencer import TRTInferencer
from nvidia_tao_deploy.inferencer.utils import allocate_buffers, do_inference
def trt_output_process_fn(y_encoded,
target_classes,
dims,
batch_size=1):
"""Function to process TRT model output.
This function takes the raw output tensors from the detectnet_v2 model
and performs the following steps:
1. Denormalize the output bbox coordinates
2. Threshold the coverage output to get the valid indices for the bboxes.
3. Filter out the bboxes from the "output_bbox/BiasAdd" blob.
4. Cluster the filterred boxes using DBSCAN.
5. Render the outputs on images and save them to the output_path/images
6. Serialize the output bboxes to KITTI Format label files in output_path/labels.
"""
out2cluster = {}
for idx, out in enumerate(y_encoded):
# TF1 get_reshaped_outputs()
out_shape = [batch_size,] + list(dims[idx])[-3:]
out = np.reshape(out, out_shape)
# TF1 predictions_to_dict() & keras_output_map()
if out.shape[-3] == len(target_classes):
output_meta_cov = out.transpose(0, 1, 3, 2)
if out.shape[-3] == len(target_classes) * 4:
output_meta_bbox = out.transpose(0, 1, 3, 2)
# TF1 keras_output_map()
for i in range(len(target_classes)):
key = target_classes[i]
out2cluster[key] = {'cov': output_meta_cov[:, i, :, :],
'bbox': output_meta_bbox[:, 4 * i: 4 * i + 4, :, :]}
return out2cluster
class DetectNetInferencer(TRTInferencer):
"""Manages TensorRT objects for model inference."""
def __init__(self, engine_path, target_classes=None, input_shape=None, batch_size=None, data_format="channel_first"):
"""Initializes TensorRT objects needed for model inference.
Args:
engine_path (str): path where TensorRT engine should be stored
target_classes (list): list of target classes to be used
input_shape (tuple): (batch, channel, height, width) for dynamic shape engine
batch_size (int): batch size for dynamic shape engine
data_format (str): either channel_first or channel_last
"""
# Load TRT engine
super().__init__(engine_path)
self.max_batch_size = self.engine.max_batch_size
self.execute_v2 = False
self.target_classes = target_classes
# Execution context is needed for inference
self.context = None
# Allocate memory for multiple usage [e.g. multiple batch inference]
self._input_shape = []
for binding in range(self.engine.num_bindings):
if self.engine.binding_is_input(binding):
binding_shape = self.engine.get_binding_shape(binding)
self._input_shape = binding_shape[-3:]
if len(binding_shape) == 4:
self.etlt_type = "onnx"
else:
self.etlt_type = "uff"
assert len(self._input_shape) == 3, "Engine doesn't have valid input dimensions"
if data_format == "channel_first":
self.height = self._input_shape[1]
self.width = self._input_shape[2]
else:
self.height = self._input_shape[0]
self.width = self._input_shape[1]
# set binding_shape for dynamic input
# do not override if the original model was uff
if (input_shape is not None or batch_size is not None) and (self.etlt_type != "uff"):
self.context = self.engine.create_execution_context()
if input_shape is not None:
self.context.set_binding_shape(0, input_shape)
self.max_batch_size = input_shape[0]
else:
self.context.set_binding_shape(0, [batch_size] + list(self._input_shape))
self.max_batch_size = batch_size
self.execute_v2 = True
# This allocates memory for network inputs/outputs on both CPU and GPU
self.inputs, self.outputs, self.bindings, self.stream = allocate_buffers(self.engine,
self.context)
if self.context is None:
self.context = self.engine.create_execution_context()
input_volume = trt.volume(self._input_shape)
self.numpy_array = np.zeros((self.max_batch_size, input_volume))
def infer(self, imgs):
"""Infers model on batch of same sized images resized to fit the model.
Args:
image_paths (str): paths to images, that will be packed into batch
and fed into model
"""
# Verify if the supplied batch size is not too big
max_batch_size = self.max_batch_size
actual_batch_size = len(imgs)
if actual_batch_size > max_batch_size:
raise ValueError(f"image_paths list bigger ({actual_batch_size}) than \
engine max batch size ({max_batch_size})")
self.numpy_array[:actual_batch_size] = imgs.reshape(actual_batch_size, -1)
# ...copy them into appropriate place into memory...
# (self.inputs was returned earlier by allocate_buffers())
np.copyto(self.inputs[0].host, self.numpy_array.ravel())
# ...fetch model outputs...
results = do_inference(
self.context, bindings=self.bindings, inputs=self.inputs,
outputs=self.outputs, stream=self.stream,
batch_size=max_batch_size,
execute_v2=self.execute_v2,
return_raw=True)
dims = [out.numpy_shape for out in results]
outputs = [out.host for out in results]
# Process TRT outputs to proper format
return trt_output_process_fn(outputs, self.target_classes, dims, self.max_batch_size)
def __del__(self):
"""Clear things up on object deletion."""
# Clear session and buffer
if self.trt_runtime:
del self.trt_runtime
if self.context:
del self.context
if self.engine:
del self.engine
if self.stream:
del self.stream
# Loop through inputs and free inputs.
for inp in self.inputs:
inp.device.free()
# Loop through outputs and free them.
for out in self.outputs:
out.device.free()
def draw_bbox(self, img, prediction, class_mapping, threshold=None, color_map=None):
"""Draws bbox on image and dump prediction in KITTI format
Args:
img (numpy.ndarray): Preprocessed image
prediction (numpy.ndarray): (N x 6) predictions
class_mapping (dict): key is the class index and value is the class string
threshold (dict): dict containing class based threshold to filter predictions
color_map (dict): key is the class name and value is the RGB value to be used
"""
draw = ImageDraw.Draw(img)
label_strings = []
for i in prediction:
cls_name = class_mapping[int(i[0])]
if float(i[1]) < threshold[cls_name]:
continue
draw.rectangle(((i[2], i[3]), (i[4], i[5])),
outline=color_map[cls_name])
# txt pad
draw.rectangle(((i[2], i[3]), (i[2] + 75, i[3] + 10)),
fill=color_map[cls_name])
draw.text((i[2], i[3]), f"{cls_name}: {i[1]:.2f}")
# Dump predictions
x1, y1, x2, y2 = float(i[2]), float(i[3]), float(i[4]), float(i[5])
label_head = cls_name + " 0.00 0 0.00 "
bbox_string = f"{x1:.3f} {y1:.3f} {x2:.3f} {y2:.3f}"
label_tail = f" 0.00 0.00 0.00 0.00 0.00 0.00 0.00 {float(i[1]):.3f}\n"
label_string = label_head + bbox_string + label_tail
label_strings.append(label_string)
return img, label_strings
| tao_deploy-main | nvidia_tao_deploy/cv/detectnet_v2/inferencer.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""DetectNetv2 TensorRT engine builder."""
import logging
import os
import random
from six.moves import xrange
import sys
import traceback
from tqdm import tqdm
try:
from uff.model.uff_pb2 import MetaGraph
except ImportError:
print("Loading uff directly from the package source code")
# @scha: To disable tensorflow import issue
import importlib
import types
import pkgutil
package = pkgutil.get_loader("uff")
# Returns __init__.py path
src_code = package.get_filename().replace('__init__.py', 'model/uff_pb2.py')
loader = importlib.machinery.SourceFileLoader('helper', src_code)
helper = types.ModuleType(loader.name)
loader.exec_module(helper)
MetaGraph = helper.MetaGraph
import numpy as np
import onnx
import tensorrt as trt
from nvidia_tao_deploy.cv.common.constants import VALID_IMAGE_EXTENSIONS
from nvidia_tao_deploy.engine.builder import EngineBuilder
from nvidia_tao_deploy.engine.tensorfile import TensorFile
from nvidia_tao_deploy.engine.tensorfile_calibrator import TensorfileCalibrator
from nvidia_tao_deploy.engine.utils import generate_random_tensorfile, prepare_chunk
from nvidia_tao_deploy.engine.calibrator import EngineCalibrator
from nvidia_tao_deploy.utils.image_batcher import ImageBatcher
logging.basicConfig(format='%(asctime)s [TAO Toolkit] [%(levelname)s] %(name)s %(lineno)d: %(message)s',
level="INFO")
logger = logging.getLogger(__name__)
class DetectNetEngineBuilder(EngineBuilder):
"""Parses an UFF graph and builds a TensorRT engine from it."""
def __init__(
self,
data_format="channels_first",
**kwargs
):
"""Init.
Args:
data_format (str): data_format.
"""
super().__init__(**kwargs)
self._data_format = data_format
def set_input_output_node_names(self):
"""Set input output node names."""
self._output_node_names = ["output_cov/Sigmoid", "output_bbox/BiasAdd"]
self._input_node_names = ["input_1"]
def get_uff_input_dims(self, model_path):
"""Get input dimension of UFF model."""
metagraph = MetaGraph()
with open(model_path, "rb") as f:
metagraph.ParseFromString(f.read())
for node in metagraph.graphs[0].nodes:
# if node.operation == "MarkOutput":
# print(f"Output: {node.inputs[0]}")
if node.operation == "Input":
return np.array(node.fields['shape'].i_list.val)[1:]
raise ValueError("Input dimension is not found in the UFF metagraph.")
def get_onnx_input_dims(self, model_path):
"""Get input dimension of ONNX model."""
onnx_model = onnx.load(model_path)
onnx_inputs = onnx_model.graph.input
logger.info('List inputs:')
for i, inputs in enumerate(onnx_inputs):
logger.info('Input %s -> %s.', i, inputs.name)
logger.info('%s.', [i.dim_value for i in inputs.type.tensor_type.shape.dim][1:])
logger.info('%s.', [i.dim_value for i in inputs.type.tensor_type.shape.dim][0])
return [i.dim_value for i in inputs.type.tensor_type.shape.dim][:]
def create_network(self, model_path, file_format="uff"):
"""Parse the ONNX graph and create the corresponding TensorRT network definition.
Args:
model_path: The path to the UFF/ONNX graph to load.
file_format: The file format of the decrypted etlt file (default: uff).
"""
if file_format == "uff":
logger.info("Parsing UFF model")
self.network = self.builder.create_network()
self.parser = trt.UffParser()
self.set_input_output_node_names()
in_tensor_name = self._input_node_names[0]
self._input_dims = self.get_uff_input_dims(model_path)
input_dict = {in_tensor_name: self._input_dims}
for key, value in input_dict.items():
if self._data_format == "channels_first":
self.parser.register_input(key, value, trt.UffInputOrder(0))
else:
self.parser.register_input(key, value, trt.UffInputOrder(1))
for name in self._output_node_names:
self.parser.register_output(name)
self.builder.max_batch_size = self.max_batch_size
try:
assert self.parser.parse(model_path, self.network, trt.DataType.FLOAT)
except AssertionError as e:
logger.error("Failed to parse UFF File")
_, _, tb = sys.exc_info()
traceback.print_tb(tb) # Fixed format
tb_info = traceback.extract_tb(tb)
_, line, _, text = tb_info[-1]
raise AssertionError(
f"UFF parsing failed on line {line} in statement {text}"
) from e
else:
logger.info("Parsing ONNX model")
self._input_dims = self.get_onnx_input_dims(model_path)
self.batch_size = self._input_dims[0]
network_flags = (1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH))
self.network = self.builder.create_network(network_flags)
self.parser = trt.OnnxParser(self.network, self.trt_logger)
model_path = os.path.realpath(model_path)
with open(model_path, "rb") as f:
if not self.parser.parse(f.read()):
logger.error("Failed to load ONNX file: %s", model_path)
for error in range(self.parser.num_errors):
logger.error(self.parser.get_error(error))
sys.exit(1)
inputs = [self.network.get_input(i) for i in range(self.network.num_inputs)]
outputs = [self.network.get_output(i) for i in range(self.network.num_outputs)]
logger.info("Network Description")
for inp in inputs: # noqa pylint: disable=W0622
logger.info("Input '%s' with shape %s and dtype %s", inp.name, inp.shape, inp.dtype)
for output in outputs:
logger.info("Output '%s' with shape %s and dtype %s", output.name, output.shape, output.dtype)
if self.batch_size <= 0: # dynamic batch size
logger.info("dynamic batch size handling")
opt_profile = self.builder.create_optimization_profile()
model_input = self.network.get_input(0)
input_shape = model_input.shape
input_name = model_input.name
real_shape_min = (self.min_batch_size, input_shape[1],
input_shape[2], input_shape[3])
real_shape_opt = (self.opt_batch_size, input_shape[1],
input_shape[2], input_shape[3])
real_shape_max = (self.max_batch_size, input_shape[1],
input_shape[2], input_shape[3])
opt_profile.set_shape(input=input_name,
min=real_shape_min,
opt=real_shape_opt,
max=real_shape_max)
self.config.add_optimization_profile(opt_profile)
def set_calibrator(self,
inputs=None,
calib_cache=None,
calib_input=None,
calib_num_images=5000,
calib_batch_size=8,
calib_data_file=None,
image_mean=None):
"""Simple function to set an Tensorfile based int8 calibrator.
Args:
calib_data_file: Path to the TensorFile. If the tensorfile doesn't exist
at this path, then one is created with either n_batches
of random tensors, images from the file in calib_input of dimensions
(batch_size,) + (input_dims).
calib_input: The path to a directory holding the calibration images.
calib_cache: The path where to write the calibration cache to,
or if it already exists, load it from.
calib_num_images: The maximum number of images to use for calibration.
calib_batch_size: The batch size to use for the calibration process.
image_mean: Image mean per channel.
Returns:
No explicit returns.
"""
if not calib_data_file:
logger.info("Calibrating using ImageBatcher")
self.config.int8_calibrator = EngineCalibrator(calib_cache)
if not os.path.exists(calib_cache):
calib_shape = [calib_batch_size] + list(inputs[0].shape)[-3:]
calib_dtype = trt.nptype(inputs[0].dtype)
logger.info(calib_shape)
self.config.int8_calibrator.set_image_batcher(
ImageBatcher(calib_input, calib_shape, calib_dtype,
max_num_images=calib_num_images,
exact_batches=True,
preprocessor="DetectNetv2"))
else:
logger.info("Calibrating using TensorfileCalibrator")
n_batches = calib_num_images // calib_batch_size
if not os.path.exists(calib_data_file):
self.generate_tensor_file(calib_data_file,
calib_input,
self._input_dims[1:],
n_batches=n_batches,
batch_size=calib_batch_size,
image_mean=image_mean)
self.config.int8_calibrator = TensorfileCalibrator(calib_data_file,
calib_cache,
n_batches,
calib_batch_size)
def generate_tensor_file(self, data_file_name,
calibration_images_dir,
input_dims, n_batches=10,
batch_size=1, image_mean=None):
"""Generate calibration Tensorfile for int8 calibrator.
This function generates a calibration tensorfile from a directory of images, or dumps
n_batches of random numpy arrays of shape (batch_size,) + (input_dims).
Args:
data_file_name (str): Path to the output tensorfile to be saved.
calibration_images_dir (str): Path to the images to generate a tensorfile from.
input_dims (list): Input shape in CHW order.
n_batches (int): Number of batches to be saved.
batch_size (int): Number of images per batch.
image_mean (list): Image mean per channel.
Returns:
No explicit returns.
"""
if not os.path.exists(calibration_images_dir):
logger.info("Generating a tensorfile with random tensor images. This may work well as "
"a profiling tool, however, it may result in inaccurate results at "
"inference. Please provide a custom directory of images for best performance.")
generate_random_tensorfile(data_file_name,
input_dims,
n_batches=n_batches,
batch_size=batch_size)
else:
# Preparing the list of images to be saved.
num_images = n_batches * batch_size
image_list = [os.path.join(calibration_images_dir, image)
for image in os.listdir(calibration_images_dir)
if image.split('.')[-1] in VALID_IMAGE_EXTENSIONS]
if len(image_list) < num_images:
raise ValueError('Not enough number of images provided:'
f' {len(image_list)} < {num_images}')
image_idx = random.sample(xrange(len(image_list)), num_images)
self.set_data_preprocessing_parameters(input_dims, image_mean)
# Writing out processed dump.
with TensorFile(data_file_name, 'w') as f:
for chunk in tqdm(image_idx[x:x + batch_size] for x in xrange(0, len(image_idx),
batch_size)):
dump_data = prepare_chunk(chunk, image_list,
image_width=input_dims[2],
image_height=input_dims[1],
channels=input_dims[0],
batch_size=batch_size,
**self.preprocessing_arguments)
f.write(dump_data)
f.closed
def set_data_preprocessing_parameters(self, input_dims, image_mean=None):
"""Set data pre-processing parameters for the int8 calibration."""
logger.debug("Input dimensions: %s", input_dims)
num_channels = input_dims[0]
scale = 1.0 / 255.0
if num_channels == 3:
means = [0., 0., 0.]
elif num_channels == 1:
means = [0]
else:
raise NotImplementedError(f"Invalid number of dimensions {num_channels}.")
self.preprocessing_arguments = {"scale": scale,
"means": means,
"flip_channel": False}
| tao_deploy-main | nvidia_tao_deploy/cv/detectnet_v2/engine_builder.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""TAO Deploy DetectNetv2."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
| tao_deploy-main | nvidia_tao_deploy/cv/detectnet_v2/__init__.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utilities file containing helper functions to post process raw predictions."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import logging
import numpy as np
from collections import namedtuple
from sklearn.cluster import DBSCAN as dbscan
logging.basicConfig(format='%(asctime)s [TAO Toolkit] [%(levelname)s] %(name)s %(lineno)d: %(message)s',
level="INFO")
logger = logging.getLogger(__name__)
Detection = namedtuple('Detection', [
# Bounding box of the detection in the LTRB format: [left, top, right, bottom]
'bbox',
# Confidence of detection
'confidence',
# Weighted variance of the bounding boxes in this cluster, normalized for the size of the box
'cluster_cv',
# Number of raw bounding boxes that went into this cluster
'num_raw_boxes',
# Sum of of the raw bounding boxes' coverage values in this cluster
'sum_coverages',
# Maximum coverage value among bboxes
'max_cov_value',
# Minimum converage value among bboxes
'min_cov_value',
# Candidate coverages.
'candidate_covs',
# Candidate bbox coordinates.
'candidate_bboxes'
])
def cluster_bboxes(raw_detections,
criterion,
eps,
min_samples,
min_weight,
min_height,
confidence_model,
cluster_weights=(1.0, 0.0, 0.0, 0.0, 0.0, 0.0),
clustering_algorithm="dbscan",
confidence_threshold=0.01,
nms_iou_threshold=0.01,
nms_confidence_threshold=0.1):
"""Cluster the bboxes from the raw feature map to output boxes.
It works in two steps.
1. Obtain grid cell indices where coverage > min_weight.
2. Make a list of all bboxes from the grid cells short listed from 1.
3. Cluster this list of bboxes using a density based clustering algorithm..
Inputs:
raw_detections : dict with keys:
bbox: rectangle coordinates, (num_imgs, 4, W, H) array
cov: weights for the rectangles, (num_imgs, 1, W, H) array
criterion (str): clustering criterion ('MSE' or 'IOU')
eps (float): threshold for considering two rectangles as one
min_samples (int): minimum cumulative weight for output rectangle
min_weight (float): filter out bboxes with weight smaller than
min_weight prior to clustering
min_height (float): filter out bboxes with height smaller than
min_height after clustering
cluster_weights (dict): weighting of different distance components
(bbox, depth, orientation, bottom_vis, width_vis, orient_markers)
confidence_model (str): Dict of {kind: 'mlp' or 'aggregate_cov'
model: the expected model format or None}
clustering_algorithm (str): Algorithm used to cluster the raw predictions.
confidence_threshold (float): The final overlay threshold post clustering.
nms_iou_threshold (float): IOU overlap threshold to be used when running NMS.
Returns:
detections_per_image (list): A list of lists of Detection objects, one list
for each input frame.
"""
db = None
if clustering_algorithm in ["dbscan", "hybrid"]:
db = setup_dbscan_object(eps, min_samples, criterion)
num_images = len(raw_detections['cov'])
if confidence_model == 'mlp':
raise NotImplementedError("MLP confidence thresholding not supported.")
# Initialize output detections to empty lists
# DO NOT DO a=[[]]*num_images --> that means 'a[0] is a[1] == True' !!!
detections_per_image = [[] for _ in range(num_images)]
# Needed when doing keras confidence model.
# keras.backend.get_session().run(tf.initialize_all_variables())
# Loop images
logger.debug("Clustering bboxes")
for image_idx in range(num_images):
# Check if the input was empty.
if raw_detections['cov'][image_idx].size == 0:
continue
bboxes, covs = threshold_bboxes(raw_detections, image_idx, min_weight)
if covs.size == 0:
continue
# Cluster using DBSCAN.
if clustering_algorithm == "dbscan":
logger.debug("Clustering bboxes using dbscan.")
clustered_boxes_per_image = cluster_with_dbscan(bboxes,
covs,
criterion,
db,
confidence_model,
cluster_weights,
min_height,
threshold=confidence_threshold)
# Clustering detections with NMS.
elif clustering_algorithm == "nms":
logger.debug("Clustering using NMS")
clustered_boxes_per_image = cluster_with_nms(bboxes, covs,
min_height,
nms_iou_threshold=nms_iou_threshold,
threshold=nms_confidence_threshold)
elif clustering_algorithm == "hybrid":
logger.debug("Clustering with DBSCAN + NMS")
clustered_boxes_per_image = cluster_with_hybrid(
bboxes, covs,
criterion, db,
confidence_model,
cluster_weights,
min_height,
nms_iou_threshold=nms_iou_threshold,
confidence_threshold=confidence_threshold,
nms_confidence_threshold=nms_confidence_threshold
)
else:
raise NotImplementedError(f"Clustering with {clustering_algorithm} algorithm not supported.")
detections_per_image[image_idx].extend(clustered_boxes_per_image)
# Sort in descending order of cumulative weight
detections_per_image = [sorted(dets, key=lambda det: -det.confidence)
for dets in detections_per_image]
return detections_per_image
def get_keep_indices(dets, covs, min_height,
Nt=0.3, sigma=0.4, threshold=0.01,
method=4):
"""Perform NMS over raw detections.
This function implements clustering using multiple variants of NMS, namely,
Linear, Soft-NMS, D-NMS and NMS. It computes the indexes of the raw detections
that may be preserved post NMS.
Args:
dets (np.ndarray): Array of filtered bboxes.
scores (np.ndarray): Array of filtered scores (coverages).
min_height (int): Minimum height of the boxes to be retained.
Nt (float): Overlap threshold.
sigma (float): Variance using in the Gaussian soft nms.
threshold (float): Filtering threshold post bbox clustering.
method (int): Variant of nms to be used.
Returns:
keep (np.ndarray): Array of indices of boxes to be retained after clustering.
"""
N = dets.shape[0]
assert len(dets.shape) == 2 and dets.shape[1] == 4, \
f"BBox dimensions are invalid, {dets.shape}."
indexes = np.array([np.arange(N)])
assert len(covs.shape) == 1 and covs.shape[0] == N, \
f"Coverage dimensions are invalid. {covs.shape}"
# Convert to t, l, b, r representation for NMS.
l, t, r, b = dets.T
dets = np.asarray([t, l, b, r]).T
dets = np.concatenate((dets, indexes.T), axis=1)
scores = covs
# Compute box areas.
areas = (r - l + 1) * (b - t + 1)
for i in range(N):
# intermediate parameters for later parameters exchange
tBD = dets[i, :].copy()
tscore = scores[i].copy()
tarea = areas[i].copy()
pos = i + 1
if i != N - 1:
maxscore = np.max(scores[pos:], axis=0)
maxpos = np.argmax(scores[pos:], axis=0)
else:
maxscore = scores[-1]
maxpos = 0
if tscore < maxscore:
dets[i, :] = dets[maxpos + i + 1, :]
dets[maxpos + i + 1, :] = tBD
tBD = dets[i, :]
scores[i] = scores[maxpos + i + 1]
scores[maxpos + i + 1] = tscore
tscore = scores[i]
areas[i] = areas[maxpos + i + 1]
areas[maxpos + i + 1] = tarea
tarea = areas[i]
# IoU calculate
xx1 = np.maximum(dets[i, 1], dets[pos:, 1])
yy1 = np.maximum(dets[i, 0], dets[pos:, 0])
xx2 = np.minimum(dets[i, 3], dets[pos:, 3])
yy2 = np.minimum(dets[i, 2], dets[pos:, 2])
w = np.maximum(0.0, xx2 - xx1 + 1)
h = np.maximum(0.0, yy2 - yy1 + 1)
inter = w * h
ovr = inter / (areas[i] + areas[pos:] - inter)
# min_overlap_box
x1c = np.minimum(dets[i, 1], dets[pos:, 1])
y1c = np.minimum(dets[i, 0], dets[pos:, 0])
x2c = np.maximum(dets[i, 3], dets[pos:, 3])
y2c = np.maximum(dets[i, 2], dets[pos:, 2])
c1x, c1y = (dets[i, 1] + dets[i, 3]) / 2.0, (dets[i, 0] + dets[i, 2]) / 2.0
c2x, c2y = (dets[pos:, 1] + dets[pos:, 3]) / 2.0, (dets[pos:, 0] + dets[pos:, 2]) / 2.0
centre_dis = ((c1x - c2x) ** 2) + ((c1y - c2y) ** 2)
diag = ((x1c - x2c) ** 2) + ((y1c - y2c) ** 2)
ovr_dis = ovr - centre_dis / diag
# Four methods: 1.linear 2.gaussian soft NMS 3. D-NMS 4.original NMS
if method == 1:
# linear NMS
weight = np.ones(ovr.shape)
weight[ovr > Nt] = weight[ovr > Nt] - ovr[ovr > Nt]
elif method == 2: # gaussian
# Gaussian Soft NMS
weight = np.exp(-(ovr * ovr) / sigma)
elif method == 3:
# D-NMS
weight = np.ones(ovr.shape)
weight[ovr_dis > Nt] = 0
elif method == 4:
# original NMS
weight = np.ones(ovr.shape)
weight[ovr > Nt] = 0
else:
raise NotImplementedError("NMS variants can only be between [1 - 4] where \n"
"1. linear NMS\n2. Gaussian Soft NMS\n3. D-NMS\n4. "
"Original NMS")
scores[pos:] = weight * scores[pos:]
# Filtering based on confidence threshold.
inds = dets[:, 4][scores > threshold]
keep = inds.astype(int)
keep = np.array([[f] for f in keep])
return keep
def cluster_with_nms(bboxes, covs, min_height,
nms_iou_threshold=0.01,
threshold=0.01):
"""Cluster raw detections with NMS.
Args:
bboxes (np.ndarray): The raw bbox predictions from the network.
covs (np.ndarray): The raw coverage predictions from the network.
min_height (float): The minimum height to filter out bboxes post clustering.
nms_iou_threshold (float): The overlap threshold to be used when running NMS.
threshold (float): The final confidence threshold to filter out bboxes
after clustering.
Returns:
clustered_boxes_per_images (list): List of clustered and filtered detections.
"""
keep_indices = get_keep_indices(bboxes, covs, min_height,
threshold=threshold,
Nt=nms_iou_threshold)
logger.debug("Keep indices: shape: %s, type: %s", keep_indices.shape, type(keep_indices))
if keep_indices.size == 0:
return []
filterred_boxes = np.take_along_axis(bboxes, keep_indices, axis=0)
filterred_coverages = covs[keep_indices]
assert (filterred_boxes.shape[0] == filterred_coverages.shape[0])
clustered_boxes_per_image = []
for idx in range(len(filterred_boxes)):
clustered_boxes_per_image.append(Detection(
bbox=filterred_boxes[idx, :],
confidence=filterred_coverages[idx][0],
cluster_cv=None,
num_raw_boxes=None,
sum_coverages=None,
max_cov_value=None,
min_cov_value=None,
candidate_covs=filterred_coverages[idx],
candidate_bboxes=filterred_boxes[idx]))
return clustered_boxes_per_image
def cluster_with_dbscan(bboxes, covs, criterion, db,
confidence_model, cluster_weights,
min_height, threshold=0.01):
"""Cluster raw predictions using dbscan.
Args:
boxes (np.array): Thresholded raw bbox blob
covs (np.array): Thresholded raw covs blob
criterion (str): DBSCAN clustering criterion.
db: Instantiated dbscan object.
cluster_weights (dict): weighting of different distance components
(bbox, depth, orientation, bottom_vis, width_vis, orient_markers)
min_height (float): filter out bboxes with height smaller than
min_height after clustering
threshold (float): Final threshold to filter bboxes post
clustering.
Returns:
detections_per_image.
"""
detections_per_image = []
if criterion[:3] in ['MSE', 'IOU']:
if criterion[:3] == 'MSE':
data = bboxes
labeling = db.fit_predict(X=data, sample_weight=covs)
elif criterion[:3] == 'IOU':
pairwise_dist = \
cluster_weights[0] * (1.0 - iou_vectorized(bboxes))
labeling = db.fit_predict(X=pairwise_dist, sample_weight=covs)
labels = np.unique(labeling[labeling >= 0])
logger.debug("Number of boxes: %d", len(labels))
for label in labels:
w = covs[labeling == label]
aggregated_w = np.sum(w)
w_norm = w / aggregated_w
n = len(w)
w_max = np.max(w)
w_min = np.min(w)
# Mean bounding box
b = bboxes[labeling == label]
mean_bbox = np.sum((b.T * w_norm).T, axis=0)
# Compute coefficient of variation of the box coords
bbox_area = (mean_bbox[2] - mean_bbox[0]) * (mean_bbox[3] - mean_bbox[1])
# Calculate weighted bounding box variance normalized by
# bounding box size
cluster_cv = np.sum(w_norm.reshape((-1, 1)) * (b - mean_bbox) ** 2, axis=0)
cluster_cv = np.sqrt(np.mean(cluster_cv) / bbox_area)
# Update confidence output based on mode of confidence.
if confidence_model == 'aggregate_cov':
confidence = aggregated_w
elif confidence_model == 'mean_cov':
w_mean = aggregated_w / n
confidence = (w_mean - w_min) / (w_max - w_min)
else:
raise NotImplementedError(f"Unknown confidence kind {confidence_model.kind}!")
# Filter out too small bboxes
if mean_bbox[3] - mean_bbox[1] <= min_height:
continue
if confidence >= threshold:
detections_per_image += [Detection(
bbox=mean_bbox,
confidence=confidence,
cluster_cv=cluster_cv,
num_raw_boxes=n,
sum_coverages=aggregated_w,
max_cov_value=w_max,
min_cov_value=w_min,
candidate_covs=w,
candidate_bboxes=b
)]
return detections_per_image
raise NotImplementedError(f"DBSCAN for this criterion is not implemented. {criterion}")
def threshold_bboxes(raw_detections, image_idx, min_weight):
"""Threshold raw predictions based on coverages.
Args:
raw_detections (dict): Dictionary containing raw detections, cov
and bboxes.
Returns:
bboxes, covs: The filtered numpy array of bboxes and covs.
"""
# Get bbox coverage values, flatten (discard spatial and scale info)
covs = raw_detections['cov'][image_idx].flatten()
valid_indices = covs > min_weight
covs = covs[valid_indices]
# Flatten last three dimensions (discard spatial and scale info)
# assume bbox is always present
bboxes = raw_detections['bbox'][image_idx]
bboxes = bboxes.reshape(bboxes.shape[:1] + (-1,)).T[valid_indices]
return bboxes, covs
def setup_dbscan_object(eps, min_samples, criterion):
"""Instantiate dbscan object for clustering predictions with dbscan.
Args:
eps (float): DBSCAN epsilon value (search distance parameter)
min_samples (int): minimum cumulative weight for output rectangle
criterion (str): clustering criterion ('MSE' or 'IOU')
Returns:
db (dbscan object): DBSCAN object from scikit learn.
"""
min_samples = max(int(min_samples), 1)
if criterion[:3] == 'MSE':
# MSE between coordinates is used as the distance
# If depth and orientation are included, add them as
# additional coordinates
db = dbscan(eps=eps, min_samples=min_samples)
elif criterion[:3] == 'IOU':
# 1.-IOU is used as distance between bboxes
# For depth and orientation, use a normalized difference
# measure
# The final distance metric is a weighted sum of the above
db = dbscan(eps=eps, min_samples=min_samples, metric='precomputed')
else:
raise NotImplementedError("cluster_bboxes: Unknown bbox clustering criterion!")
return db
def cluster_with_hybrid(bboxes, covs,
criterion, db,
confidence_model,
cluster_weights,
min_height,
nms_iou_threshold=0.3,
confidence_threshold=0.1,
nms_confidence_threshold=0.1):
"""Cluster raw predictions with DBSCAN + NMS.
Args:
boxes (np.array): Thresholded raw bbox blob
covs (np.array): Thresholded raw covs blob
criterion (str): DBSCAN clustering criterion.
db: Instantiated dbscan object.
cluster_weights (dict): weighting of different distance components
(bbox, depth, orientation, bottom_vis, width_vis, orient_markers)
min_height (float): filter out bboxes with height smaller than
min_height after clustering
nms_iou_threshold (float): The overlap threshold to be used when running NMS.
confiedence_threshold (float): The confidence threshold to filter out bboxes
after clustering by dbscan.
nms_confidence_threshold (float): The confidence threshold to filter out bboxes
after clustering by NMS.
Returns:
nms_clustered_detection_per_image (list): List of clustered detections
after hybrid clustering.
"""
dbscan_clustered_detections_per_image = cluster_with_dbscan(
bboxes,
covs,
criterion,
db,
confidence_model,
cluster_weights,
min_height,
threshold=confidence_threshold
)
# Extract raw detections from clustered outputs.
nms_candidate_boxes = []
nms_candidate_covs = []
for detections in dbscan_clustered_detections_per_image:
nms_candidate_boxes.extend(detections.candidate_bboxes)
nms_candidate_covs.extend(detections.candidate_covs)
nms_candidate_boxes = np.asarray(nms_candidate_boxes).astype(np.float32)
nms_candidate_covs = np.asarray(nms_candidate_covs).astype(np.float32)
if nms_candidate_covs.size == 0:
return []
# Clustered candidates from dbscan to run NMS.
nms_clustered_detections_per_image = cluster_with_nms(
nms_candidate_boxes,
nms_candidate_covs,
min_height,
nms_iou_threshold=nms_iou_threshold,
threshold=nms_confidence_threshold
)
return nms_clustered_detections_per_image
def iou_vectorized(rects):
"""Intersection over union among a list of rectangles in LTRB format.
Args:
rects (np.array) : numpy array of shape (N, 4), LTRB format, assumes L<R and T<B
Returns::
d (np.array) : numpy array of shape (N, N) of the IOU between all pairs of rects
"""
# coordinates
l, t, r, b = rects.T
# form intersection coordinates
isect_l = np.maximum(l[:, None], l[None, :])
isect_t = np.maximum(t[:, None], t[None, :])
isect_r = np.minimum(r[:, None], r[None, :])
isect_b = np.minimum(b[:, None], b[None, :])
# form intersection area
isect_w = np.maximum(0, isect_r - isect_l)
isect_h = np.maximum(0, isect_b - isect_t)
area_isect = isect_w * isect_h
# original rect areas
areas = (r - l) * (b - t)
# Union area is area_a + area_b - intersection area
denom = (areas[:, None] + areas[None, :] - area_isect)
# Return IOU regularized with .01, to avoid outputing NaN in pathological
# cases (area_a = area_b = isect = 0)
return area_isect / (denom + .01)
| tao_deploy-main | nvidia_tao_deploy/cv/detectnet_v2/utils.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""DetectNetv2 loader."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from PIL import Image
from nvidia_tao_deploy.dataloader.kitti import KITTILoader
class DetectNetKITTILoader(KITTILoader):
"""DetectNetv2 Dataloader."""
def __init__(self,
**kwargs):
"""Init."""
super().__init__(**kwargs)
self.image_size = []
def _load_gt_image(self, image_path):
"""Load GT image from file."""
img = Image.open(image_path).convert('RGB')
return img, img.size # DNv2 requires original image size
def _get_single_item_raw(self, idx):
"""Load single image and its label.
Returns:
image (PIL.image): image object in original resolution
label (np.array): [class_idx, is_difficult, x_min, y_min, x_max, y_max]
with normalized coordinates
"""
image, image_size = self._load_gt_image(self.image_paths[self.data_inds[idx]])
if self.is_inference:
label = np.zeros((1, 6)) # Random array to label
else:
label = self._load_gt_label(self.label_paths[self.data_inds[idx]])
return image, label, image_size
def _get_single_processed_item(self, idx):
"""Load and process single image and its label."""
image, label, image_size = self._get_single_item_raw(idx)
image, label = self.preprocessing(image, label)
return image, label, image_size
def __next__(self):
"""Load a full batch."""
images = []
labels = []
image_sizes = []
if self.n < self.n_batches:
for idx in range(self.n * self.batch_size,
(self.n + 1) * self.batch_size):
image, label, image_size = self._get_single_processed_item(idx)
images.append(image)
labels.append(label)
image_sizes.append(image_size)
self.n += 1
self.image_size.append(image_sizes)
return self._batch_post_processing(images, labels)
raise StopIteration
def preprocessing(self, image, label):
"""The image preprocessor loads an image from disk and prepares it as needed for batching.
This includes padding, resizing, normalization, data type casting, and transposing.
Args:
image (PIL.image): The Pillow image on disk to load.
label (np.array): labels
Returns:
image (np.array): A numpy array holding the image sample, ready to be concatenated
into the rest of the batch
label (np.array): labels
"""
image = image.resize((self.width, self.height), Image.LANCZOS)
image = np.asarray(image, dtype=self.dtype) / 255.0
# Handle Grayscale
if self.num_channels == 1:
image = np.expand_dims(image, axis=2)
image = np.transpose(image, (2, 0, 1))
# Round
label = np.round(label, decimals=0)
# Filter out invalid labels
label = self._filter_invalid_labels(label)
return image, label
def _batch_post_processing(self, images, labels):
"""Post processing for a batch."""
images = np.array(images)
# try to make labels a numpy array
is_make_array = True
x_shape = None
for x in labels:
if not isinstance(x, np.ndarray):
is_make_array = False
break
if x_shape is None:
x_shape = x.shape
elif x_shape != x.shape:
is_make_array = False
break
if is_make_array:
labels = np.array(labels)
return images, labels
def _filter_invalid_labels(self, labels):
"""filter out invalid labels.
Arg:
labels: size (N, 6).
Returns:
labels: size (M, 6), filtered bboxes with clipped boxes.
"""
return labels
| tao_deploy-main | nvidia_tao_deploy/cv/detectnet_v2/dataloader.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nvidia_tao_deploy/cv/detectnet_v2/proto/optimizer_config.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
from nvidia_tao_deploy.cv.detectnet_v2.proto import adam_optimizer_config_pb2 as nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_adam__optimizer__config__pb2
DESCRIPTOR = _descriptor.FileDescriptor(
name='nvidia_tao_deploy/cv/detectnet_v2/proto/optimizer_config.proto',
package='',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\n>nvidia_tao_deploy/cv/detectnet_v2/proto/optimizer_config.proto\x1a\x43nvidia_tao_deploy/cv/detectnet_v2/proto/adam_optimizer_config.proto\"D\n\x0fOptimizerConfig\x12$\n\x04\x61\x64\x61m\x18\x01 \x01(\x0b\x32\x14.AdamOptimizerConfigH\x00\x42\x0b\n\toptimizerb\x06proto3')
,
dependencies=[nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_adam__optimizer__config__pb2.DESCRIPTOR,])
_OPTIMIZERCONFIG = _descriptor.Descriptor(
name='OptimizerConfig',
full_name='OptimizerConfig',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='adam', full_name='OptimizerConfig.adam', index=0,
number=1, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
_descriptor.OneofDescriptor(
name='optimizer', full_name='OptimizerConfig.optimizer',
index=0, containing_type=None, fields=[]),
],
serialized_start=135,
serialized_end=203,
)
_OPTIMIZERCONFIG.fields_by_name['adam'].message_type = nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_adam__optimizer__config__pb2._ADAMOPTIMIZERCONFIG
_OPTIMIZERCONFIG.oneofs_by_name['optimizer'].fields.append(
_OPTIMIZERCONFIG.fields_by_name['adam'])
_OPTIMIZERCONFIG.fields_by_name['adam'].containing_oneof = _OPTIMIZERCONFIG.oneofs_by_name['optimizer']
DESCRIPTOR.message_types_by_name['OptimizerConfig'] = _OPTIMIZERCONFIG
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
OptimizerConfig = _reflection.GeneratedProtocolMessageType('OptimizerConfig', (_message.Message,), dict(
DESCRIPTOR = _OPTIMIZERCONFIG,
__module__ = 'nvidia_tao_deploy.cv.detectnet_v2.proto.optimizer_config_pb2'
# @@protoc_insertion_point(class_scope:OptimizerConfig)
))
_sym_db.RegisterMessage(OptimizerConfig)
# @@protoc_insertion_point(module_scope)
| tao_deploy-main | nvidia_tao_deploy/cv/detectnet_v2/proto/optimizer_config_pb2.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Confidence config class that holds parameters for postprocessing confidence."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from nvidia_tao_deploy.cv.detectnet_v2.proto.postprocessing_config_pb2 import ConfidenceConfig as ConfidenceProto
def build_confidence_config(confidence_config):
"""Build ConfidenceConfig from a proto.
Args:
confidence_config: confidence_config proto message.
Returns:
ConfidenceConfig object.
"""
return ConfidenceConfig(confidence_config.confidence_model_filename,
confidence_config.confidence_threshold)
def build_confidence_proto(confidence_config):
"""Build proto from ConfidenceConfig.
Args:
confidence_config: ConfidenceConfig object.
Returns:
confidence_config: confidence_config proto.
"""
proto = ConfidenceProto()
proto.confidence_model_filename = confidence_config.confidence_model_filename
proto.confidence_threshold = confidence_config.confidence_threshold
return proto
class ConfidenceConfig(object):
"""Hold the parameters for postprocessing confidence."""
def __init__(self, confidence_model_filename, confidence_threshold):
"""Constructor.
Args:
confidence_model_filename (str): Absolute path to the confidence model hdf5.
confidence_threshold (float): Confidence threshold value. Must be >= 0.
Raises:
ValueError: If the input arg is not within the accepted range.
"""
if confidence_threshold < 0.0:
raise ValueError("ConfidenceConfig.confidence_threshold must be >= 0")
self.confidence_model_filename = confidence_model_filename
self.confidence_threshold = confidence_threshold
| tao_deploy-main | nvidia_tao_deploy/cv/detectnet_v2/proto/confidence_config.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nvidia_tao_deploy/cv/detectnet_v2/proto/objective_label_filter.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
from nvidia_tao_deploy.cv.detectnet_v2.proto import label_filter_pb2 as nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_label__filter__pb2
DESCRIPTOR = _descriptor.FileDescriptor(
name='nvidia_tao_deploy/cv/detectnet_v2/proto/objective_label_filter.proto',
package='',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\nDnvidia_tao_deploy/cv/detectnet_v2/proto/objective_label_filter.proto\x1a:nvidia_tao_deploy/cv/detectnet_v2/proto/label_filter.proto\"\x9f\x02\n\x14ObjectiveLabelFilter\x12X\n\x1eobjective_label_filter_configs\x18\x01 \x03(\x0b\x32\x30.ObjectiveLabelFilter.ObjectiveLabelFilterConfig\x12\x17\n\x0fmask_multiplier\x18\x02 \x01(\x02\x12\x1d\n\x15preserve_ground_truth\x18\x03 \x01(\x08\x1au\n\x1aObjectiveLabelFilterConfig\x12\"\n\x0clabel_filter\x18\x01 \x01(\x0b\x32\x0c.LabelFilter\x12\x1a\n\x12target_class_names\x18\x02 \x03(\t\x12\x17\n\x0fobjective_names\x18\x03 \x03(\tb\x06proto3')
,
dependencies=[nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_label__filter__pb2.DESCRIPTOR,])
_OBJECTIVELABELFILTER_OBJECTIVELABELFILTERCONFIG = _descriptor.Descriptor(
name='ObjectiveLabelFilterConfig',
full_name='ObjectiveLabelFilter.ObjectiveLabelFilterConfig',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='label_filter', full_name='ObjectiveLabelFilter.ObjectiveLabelFilterConfig.label_filter', index=0,
number=1, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='target_class_names', full_name='ObjectiveLabelFilter.ObjectiveLabelFilterConfig.target_class_names', index=1,
number=2, type=9, cpp_type=9, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='objective_names', full_name='ObjectiveLabelFilter.ObjectiveLabelFilterConfig.objective_names', index=2,
number=3, type=9, cpp_type=9, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=303,
serialized_end=420,
)
_OBJECTIVELABELFILTER = _descriptor.Descriptor(
name='ObjectiveLabelFilter',
full_name='ObjectiveLabelFilter',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='objective_label_filter_configs', full_name='ObjectiveLabelFilter.objective_label_filter_configs', index=0,
number=1, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='mask_multiplier', full_name='ObjectiveLabelFilter.mask_multiplier', index=1,
number=2, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='preserve_ground_truth', full_name='ObjectiveLabelFilter.preserve_ground_truth', index=2,
number=3, type=8, cpp_type=7, label=1,
has_default_value=False, default_value=False,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[_OBJECTIVELABELFILTER_OBJECTIVELABELFILTERCONFIG, ],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=133,
serialized_end=420,
)
_OBJECTIVELABELFILTER_OBJECTIVELABELFILTERCONFIG.fields_by_name['label_filter'].message_type = nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_label__filter__pb2._LABELFILTER
_OBJECTIVELABELFILTER_OBJECTIVELABELFILTERCONFIG.containing_type = _OBJECTIVELABELFILTER
_OBJECTIVELABELFILTER.fields_by_name['objective_label_filter_configs'].message_type = _OBJECTIVELABELFILTER_OBJECTIVELABELFILTERCONFIG
DESCRIPTOR.message_types_by_name['ObjectiveLabelFilter'] = _OBJECTIVELABELFILTER
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
ObjectiveLabelFilter = _reflection.GeneratedProtocolMessageType('ObjectiveLabelFilter', (_message.Message,), dict(
ObjectiveLabelFilterConfig = _reflection.GeneratedProtocolMessageType('ObjectiveLabelFilterConfig', (_message.Message,), dict(
DESCRIPTOR = _OBJECTIVELABELFILTER_OBJECTIVELABELFILTERCONFIG,
__module__ = 'nvidia_tao_deploy.cv.detectnet_v2.proto.objective_label_filter_pb2'
# @@protoc_insertion_point(class_scope:ObjectiveLabelFilter.ObjectiveLabelFilterConfig)
))
,
DESCRIPTOR = _OBJECTIVELABELFILTER,
__module__ = 'nvidia_tao_deploy.cv.detectnet_v2.proto.objective_label_filter_pb2'
# @@protoc_insertion_point(class_scope:ObjectiveLabelFilter)
))
_sym_db.RegisterMessage(ObjectiveLabelFilter)
_sym_db.RegisterMessage(ObjectiveLabelFilter.ObjectiveLabelFilterConfig)
# @@protoc_insertion_point(module_scope)
| tao_deploy-main | nvidia_tao_deploy/cv/detectnet_v2/proto/objective_label_filter_pb2.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nvidia_tao_deploy/cv/detectnet_v2/proto/adam_optimizer_config.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor.FileDescriptor(
name='nvidia_tao_deploy/cv/detectnet_v2/proto/adam_optimizer_config.proto',
package='',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\nCnvidia_tao_deploy/cv/detectnet_v2/proto/adam_optimizer_config.proto\"D\n\x13\x41\x64\x61mOptimizerConfig\x12\x0f\n\x07\x65psilon\x18\x01 \x01(\x02\x12\r\n\x05\x62\x65ta1\x18\x02 \x01(\x02\x12\r\n\x05\x62\x65ta2\x18\x03 \x01(\x02\x62\x06proto3')
)
_ADAMOPTIMIZERCONFIG = _descriptor.Descriptor(
name='AdamOptimizerConfig',
full_name='AdamOptimizerConfig',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='epsilon', full_name='AdamOptimizerConfig.epsilon', index=0,
number=1, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='beta1', full_name='AdamOptimizerConfig.beta1', index=1,
number=2, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='beta2', full_name='AdamOptimizerConfig.beta2', index=2,
number=3, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=71,
serialized_end=139,
)
DESCRIPTOR.message_types_by_name['AdamOptimizerConfig'] = _ADAMOPTIMIZERCONFIG
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
AdamOptimizerConfig = _reflection.GeneratedProtocolMessageType('AdamOptimizerConfig', (_message.Message,), dict(
DESCRIPTOR = _ADAMOPTIMIZERCONFIG,
__module__ = 'nvidia_tao_deploy.cv.detectnet_v2.proto.adam_optimizer_config_pb2'
# @@protoc_insertion_point(class_scope:AdamOptimizerConfig)
))
_sym_db.RegisterMessage(AdamOptimizerConfig)
# @@protoc_insertion_point(module_scope)
| tao_deploy-main | nvidia_tao_deploy/cv/detectnet_v2/proto/adam_optimizer_config_pb2.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nvidia_tao_deploy/cv/detectnet_v2/proto/training_config.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
from nvidia_tao_deploy.cv.detectnet_v2.proto import cost_scaling_config_pb2 as nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_cost__scaling__config__pb2
from nvidia_tao_deploy.cv.detectnet_v2.proto import learning_rate_config_pb2 as nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_learning__rate__config__pb2
from nvidia_tao_deploy.cv.detectnet_v2.proto import optimizer_config_pb2 as nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_optimizer__config__pb2
from nvidia_tao_deploy.cv.detectnet_v2.proto import regularizer_config_pb2 as nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_regularizer__config__pb2
from nvidia_tao_deploy.cv.detectnet_v2.proto import visualizer_config_pb2 as nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_visualizer__config__pb2
DESCRIPTOR = _descriptor.FileDescriptor(
name='nvidia_tao_deploy/cv/detectnet_v2/proto/training_config.proto',
package='',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\n=nvidia_tao_deploy/cv/detectnet_v2/proto/training_config.proto\x1a\x41nvidia_tao_deploy/cv/detectnet_v2/proto/cost_scaling_config.proto\x1a\x42nvidia_tao_deploy/cv/detectnet_v2/proto/learning_rate_config.proto\x1a>nvidia_tao_deploy/cv/detectnet_v2/proto/optimizer_config.proto\x1a@nvidia_tao_deploy/cv/detectnet_v2/proto/regularizer_config.proto\x1a?nvidia_tao_deploy/cv/detectnet_v2/proto/visualizer_config.proto\"\xbc\x02\n\x0eTrainingConfig\x12\x1a\n\x12\x62\x61tch_size_per_gpu\x18\x01 \x01(\r\x12\x12\n\nnum_epochs\x18\x02 \x01(\r\x12*\n\rlearning_rate\x18\x03 \x01(\x0b\x32\x13.LearningRateConfig\x12\'\n\x0bregularizer\x18\x04 \x01(\x0b\x32\x12.RegularizerConfig\x12#\n\toptimizer\x18\x05 \x01(\x0b\x32\x10.OptimizerConfig\x12(\n\x0c\x63ost_scaling\x18\x06 \x01(\x0b\x32\x12.CostScalingConfig\x12\x1b\n\x13\x63heckpoint_interval\x18\x07 \x01(\r\x12\x12\n\nenable_qat\x18\x08 \x01(\x08\x12%\n\nvisualizer\x18\t \x01(\x0b\x32\x11.VisualizerConfigb\x06proto3')
,
dependencies=[nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_cost__scaling__config__pb2.DESCRIPTOR,nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_learning__rate__config__pb2.DESCRIPTOR,nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_optimizer__config__pb2.DESCRIPTOR,nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_regularizer__config__pb2.DESCRIPTOR,nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_visualizer__config__pb2.DESCRIPTOR,])
_TRAININGCONFIG = _descriptor.Descriptor(
name='TrainingConfig',
full_name='TrainingConfig',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='batch_size_per_gpu', full_name='TrainingConfig.batch_size_per_gpu', index=0,
number=1, type=13, cpp_type=3, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='num_epochs', full_name='TrainingConfig.num_epochs', index=1,
number=2, type=13, cpp_type=3, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='learning_rate', full_name='TrainingConfig.learning_rate', index=2,
number=3, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='regularizer', full_name='TrainingConfig.regularizer', index=3,
number=4, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='optimizer', full_name='TrainingConfig.optimizer', index=4,
number=5, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='cost_scaling', full_name='TrainingConfig.cost_scaling', index=5,
number=6, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='checkpoint_interval', full_name='TrainingConfig.checkpoint_interval', index=6,
number=7, type=13, cpp_type=3, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='enable_qat', full_name='TrainingConfig.enable_qat', index=7,
number=8, type=8, cpp_type=7, label=1,
has_default_value=False, default_value=False,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='visualizer', full_name='TrainingConfig.visualizer', index=8,
number=9, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=396,
serialized_end=712,
)
_TRAININGCONFIG.fields_by_name['learning_rate'].message_type = nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_learning__rate__config__pb2._LEARNINGRATECONFIG
_TRAININGCONFIG.fields_by_name['regularizer'].message_type = nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_regularizer__config__pb2._REGULARIZERCONFIG
_TRAININGCONFIG.fields_by_name['optimizer'].message_type = nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_optimizer__config__pb2._OPTIMIZERCONFIG
_TRAININGCONFIG.fields_by_name['cost_scaling'].message_type = nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_cost__scaling__config__pb2._COSTSCALINGCONFIG
_TRAININGCONFIG.fields_by_name['visualizer'].message_type = nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_visualizer__config__pb2._VISUALIZERCONFIG
DESCRIPTOR.message_types_by_name['TrainingConfig'] = _TRAININGCONFIG
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
TrainingConfig = _reflection.GeneratedProtocolMessageType('TrainingConfig', (_message.Message,), dict(
DESCRIPTOR = _TRAININGCONFIG,
__module__ = 'nvidia_tao_deploy.cv.detectnet_v2.proto.training_config_pb2'
# @@protoc_insertion_point(class_scope:TrainingConfig)
))
_sym_db.RegisterMessage(TrainingConfig)
# @@protoc_insertion_point(module_scope)
| tao_deploy-main | nvidia_tao_deploy/cv/detectnet_v2/proto/training_config_pb2.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nvidia_tao_deploy/cv/detectnet_v2/proto/cost_scaling_config.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor.FileDescriptor(
name='nvidia_tao_deploy/cv/detectnet_v2/proto/cost_scaling_config.proto',
package='',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\nAnvidia_tao_deploy/cv/detectnet_v2/proto/cost_scaling_config.proto\"d\n\x11\x43ostScalingConfig\x12\x0f\n\x07\x65nabled\x18\x01 \x01(\x08\x12\x18\n\x10initial_exponent\x18\x02 \x01(\x01\x12\x11\n\tincrement\x18\x03 \x01(\x01\x12\x11\n\tdecrement\x18\x04 \x01(\x01\x62\x06proto3')
)
_COSTSCALINGCONFIG = _descriptor.Descriptor(
name='CostScalingConfig',
full_name='CostScalingConfig',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='enabled', full_name='CostScalingConfig.enabled', index=0,
number=1, type=8, cpp_type=7, label=1,
has_default_value=False, default_value=False,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='initial_exponent', full_name='CostScalingConfig.initial_exponent', index=1,
number=2, type=1, cpp_type=5, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='increment', full_name='CostScalingConfig.increment', index=2,
number=3, type=1, cpp_type=5, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='decrement', full_name='CostScalingConfig.decrement', index=3,
number=4, type=1, cpp_type=5, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=69,
serialized_end=169,
)
DESCRIPTOR.message_types_by_name['CostScalingConfig'] = _COSTSCALINGCONFIG
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
CostScalingConfig = _reflection.GeneratedProtocolMessageType('CostScalingConfig', (_message.Message,), dict(
DESCRIPTOR = _COSTSCALINGCONFIG,
__module__ = 'nvidia_tao_deploy.cv.detectnet_v2.proto.cost_scaling_config_pb2'
# @@protoc_insertion_point(class_scope:CostScalingConfig)
))
_sym_db.RegisterMessage(CostScalingConfig)
# @@protoc_insertion_point(module_scope)
| tao_deploy-main | nvidia_tao_deploy/cv/detectnet_v2/proto/cost_scaling_config_pb2.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nvidia_tao_deploy/cv/detectnet_v2/proto/early_stopping_annealing_schedule_config.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor.FileDescriptor(
name='nvidia_tao_deploy/cv/detectnet_v2/proto/early_stopping_annealing_schedule_config.proto',
package='',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\nVnvidia_tao_deploy/cv/detectnet_v2/proto/early_stopping_annealing_schedule_config.proto\"\xa9\x01\n$EarlyStoppingAnnealingScheduleConfig\x12\x19\n\x11min_learning_rate\x18\x01 \x01(\x02\x12\x19\n\x11max_learning_rate\x18\x02 \x01(\x02\x12\x19\n\x11soft_start_epochs\x18\x03 \x01(\r\x12\x18\n\x10\x61nnealing_epochs\x18\x04 \x01(\r\x12\x16\n\x0epatience_steps\x18\x05 \x01(\rb\x06proto3')
)
_EARLYSTOPPINGANNEALINGSCHEDULECONFIG = _descriptor.Descriptor(
name='EarlyStoppingAnnealingScheduleConfig',
full_name='EarlyStoppingAnnealingScheduleConfig',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='min_learning_rate', full_name='EarlyStoppingAnnealingScheduleConfig.min_learning_rate', index=0,
number=1, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='max_learning_rate', full_name='EarlyStoppingAnnealingScheduleConfig.max_learning_rate', index=1,
number=2, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='soft_start_epochs', full_name='EarlyStoppingAnnealingScheduleConfig.soft_start_epochs', index=2,
number=3, type=13, cpp_type=3, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='annealing_epochs', full_name='EarlyStoppingAnnealingScheduleConfig.annealing_epochs', index=3,
number=4, type=13, cpp_type=3, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='patience_steps', full_name='EarlyStoppingAnnealingScheduleConfig.patience_steps', index=4,
number=5, type=13, cpp_type=3, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=91,
serialized_end=260,
)
DESCRIPTOR.message_types_by_name['EarlyStoppingAnnealingScheduleConfig'] = _EARLYSTOPPINGANNEALINGSCHEDULECONFIG
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
EarlyStoppingAnnealingScheduleConfig = _reflection.GeneratedProtocolMessageType('EarlyStoppingAnnealingScheduleConfig', (_message.Message,), dict(
DESCRIPTOR = _EARLYSTOPPINGANNEALINGSCHEDULECONFIG,
__module__ = 'nvidia_tao_deploy.cv.detectnet_v2.proto.early_stopping_annealing_schedule_config_pb2'
# @@protoc_insertion_point(class_scope:EarlyStoppingAnnealingScheduleConfig)
))
_sym_db.RegisterMessage(EarlyStoppingAnnealingScheduleConfig)
# @@protoc_insertion_point(module_scope)
| tao_deploy-main | nvidia_tao_deploy/cv/detectnet_v2/proto/early_stopping_annealing_schedule_config_pb2.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nvidia_tao_deploy/cv/detectnet_v2/proto/regularizer_config.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor.FileDescriptor(
name='nvidia_tao_deploy/cv/detectnet_v2/proto/regularizer_config.proto',
package='',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\n@nvidia_tao_deploy/cv/detectnet_v2/proto/regularizer_config.proto\"\x8a\x01\n\x11RegularizerConfig\x12\x33\n\x04type\x18\x01 \x01(\x0e\x32%.RegularizerConfig.RegularizationType\x12\x0e\n\x06weight\x18\x02 \x01(\x02\"0\n\x12RegularizationType\x12\n\n\x06NO_REG\x10\x00\x12\x06\n\x02L1\x10\x01\x12\x06\n\x02L2\x10\x02\x62\x06proto3')
)
_REGULARIZERCONFIG_REGULARIZATIONTYPE = _descriptor.EnumDescriptor(
name='RegularizationType',
full_name='RegularizerConfig.RegularizationType',
filename=None,
file=DESCRIPTOR,
values=[
_descriptor.EnumValueDescriptor(
name='NO_REG', index=0, number=0,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='L1', index=1, number=1,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='L2', index=2, number=2,
serialized_options=None,
type=None),
],
containing_type=None,
serialized_options=None,
serialized_start=159,
serialized_end=207,
)
_sym_db.RegisterEnumDescriptor(_REGULARIZERCONFIG_REGULARIZATIONTYPE)
_REGULARIZERCONFIG = _descriptor.Descriptor(
name='RegularizerConfig',
full_name='RegularizerConfig',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='type', full_name='RegularizerConfig.type', index=0,
number=1, type=14, cpp_type=8, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='weight', full_name='RegularizerConfig.weight', index=1,
number=2, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
_REGULARIZERCONFIG_REGULARIZATIONTYPE,
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=69,
serialized_end=207,
)
_REGULARIZERCONFIG.fields_by_name['type'].enum_type = _REGULARIZERCONFIG_REGULARIZATIONTYPE
_REGULARIZERCONFIG_REGULARIZATIONTYPE.containing_type = _REGULARIZERCONFIG
DESCRIPTOR.message_types_by_name['RegularizerConfig'] = _REGULARIZERCONFIG
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
RegularizerConfig = _reflection.GeneratedProtocolMessageType('RegularizerConfig', (_message.Message,), dict(
DESCRIPTOR = _REGULARIZERCONFIG,
__module__ = 'nvidia_tao_deploy.cv.detectnet_v2.proto.regularizer_config_pb2'
# @@protoc_insertion_point(class_scope:RegularizerConfig)
))
_sym_db.RegisterMessage(RegularizerConfig)
# @@protoc_insertion_point(module_scope)
| tao_deploy-main | nvidia_tao_deploy/cv/detectnet_v2/proto/regularizer_config_pb2.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""TAO Deploy DetectNetv2 Proto."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
| tao_deploy-main | nvidia_tao_deploy/cv/detectnet_v2/proto/__init__.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nvidia_tao_deploy/cv/detectnet_v2/proto/augmentation_config.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor.FileDescriptor(
name='nvidia_tao_deploy/cv/detectnet_v2/proto/augmentation_config.proto',
package='',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\nAnvidia_tao_deploy/cv/detectnet_v2/proto/augmentation_config.proto\"\xb2\x07\n\x12\x41ugmentationConfig\x12\x38\n\rpreprocessing\x18\x01 \x01(\x0b\x32!.AugmentationConfig.Preprocessing\x12\x45\n\x14spatial_augmentation\x18\x02 \x01(\x0b\x32\'.AugmentationConfig.SpatialAugmentation\x12\x41\n\x12\x63olor_augmentation\x18\x03 \x01(\x0b\x32%.AugmentationConfig.ColorAugmentation\x1a\xe0\x02\n\rPreprocessing\x12\x1a\n\x12output_image_width\x18\x01 \x01(\r\x12\x1b\n\x13output_image_height\x18\x02 \x01(\r\x12\x18\n\x10output_image_min\x18\x0e \x01(\r\x12\x18\n\x10output_image_max\x18\x0f \x01(\r\x12\x1a\n\x12\x65nable_auto_resize\x18\x10 \x01(\x08\x12\x1c\n\x14output_image_channel\x18\r \x01(\r\x12\x11\n\tcrop_left\x18\x04 \x01(\r\x12\x10\n\x08\x63rop_top\x18\x05 \x01(\r\x12\x12\n\ncrop_right\x18\x06 \x01(\r\x12\x13\n\x0b\x63rop_bottom\x18\x07 \x01(\r\x12\x16\n\x0emin_bbox_width\x18\x08 \x01(\x02\x12\x17\n\x0fmin_bbox_height\x18\t \x01(\x02\x12\x13\n\x0bscale_width\x18\n \x01(\x02\x12\x14\n\x0cscale_height\x18\x0b \x01(\x02\x1a\xd5\x01\n\x13SpatialAugmentation\x12\x19\n\x11hflip_probability\x18\x01 \x01(\x02\x12\x19\n\x11vflip_probability\x18\x02 \x01(\x02\x12\x10\n\x08zoom_min\x18\x03 \x01(\x02\x12\x10\n\x08zoom_max\x18\x04 \x01(\x02\x12\x17\n\x0ftranslate_max_x\x18\x05 \x01(\x02\x12\x17\n\x0ftranslate_max_y\x18\x06 \x01(\x02\x12\x16\n\x0erotate_rad_max\x18\x07 \x01(\x02\x12\x1a\n\x12rotate_probability\x18\x08 \x01(\x02\x1a\x9c\x01\n\x11\x43olorAugmentation\x12\x1a\n\x12\x63olor_shift_stddev\x18\x01 \x01(\x02\x12\x18\n\x10hue_rotation_max\x18\x02 \x01(\x02\x12\x1c\n\x14saturation_shift_max\x18\x03 \x01(\x02\x12\x1a\n\x12\x63ontrast_scale_max\x18\x05 \x01(\x02\x12\x17\n\x0f\x63ontrast_center\x18\x08 \x01(\x02\x62\x06proto3')
)
_AUGMENTATIONCONFIG_PREPROCESSING = _descriptor.Descriptor(
name='Preprocessing',
full_name='AugmentationConfig.Preprocessing',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='output_image_width', full_name='AugmentationConfig.Preprocessing.output_image_width', index=0,
number=1, type=13, cpp_type=3, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='output_image_height', full_name='AugmentationConfig.Preprocessing.output_image_height', index=1,
number=2, type=13, cpp_type=3, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='output_image_min', full_name='AugmentationConfig.Preprocessing.output_image_min', index=2,
number=14, type=13, cpp_type=3, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='output_image_max', full_name='AugmentationConfig.Preprocessing.output_image_max', index=3,
number=15, type=13, cpp_type=3, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='enable_auto_resize', full_name='AugmentationConfig.Preprocessing.enable_auto_resize', index=4,
number=16, type=8, cpp_type=7, label=1,
has_default_value=False, default_value=False,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='output_image_channel', full_name='AugmentationConfig.Preprocessing.output_image_channel', index=5,
number=13, type=13, cpp_type=3, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='crop_left', full_name='AugmentationConfig.Preprocessing.crop_left', index=6,
number=4, type=13, cpp_type=3, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='crop_top', full_name='AugmentationConfig.Preprocessing.crop_top', index=7,
number=5, type=13, cpp_type=3, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='crop_right', full_name='AugmentationConfig.Preprocessing.crop_right', index=8,
number=6, type=13, cpp_type=3, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='crop_bottom', full_name='AugmentationConfig.Preprocessing.crop_bottom', index=9,
number=7, type=13, cpp_type=3, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='min_bbox_width', full_name='AugmentationConfig.Preprocessing.min_bbox_width', index=10,
number=8, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='min_bbox_height', full_name='AugmentationConfig.Preprocessing.min_bbox_height', index=11,
number=9, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='scale_width', full_name='AugmentationConfig.Preprocessing.scale_width', index=12,
number=10, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='scale_height', full_name='AugmentationConfig.Preprocessing.scale_height', index=13,
number=11, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=289,
serialized_end=641,
)
_AUGMENTATIONCONFIG_SPATIALAUGMENTATION = _descriptor.Descriptor(
name='SpatialAugmentation',
full_name='AugmentationConfig.SpatialAugmentation',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='hflip_probability', full_name='AugmentationConfig.SpatialAugmentation.hflip_probability', index=0,
number=1, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='vflip_probability', full_name='AugmentationConfig.SpatialAugmentation.vflip_probability', index=1,
number=2, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='zoom_min', full_name='AugmentationConfig.SpatialAugmentation.zoom_min', index=2,
number=3, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='zoom_max', full_name='AugmentationConfig.SpatialAugmentation.zoom_max', index=3,
number=4, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='translate_max_x', full_name='AugmentationConfig.SpatialAugmentation.translate_max_x', index=4,
number=5, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='translate_max_y', full_name='AugmentationConfig.SpatialAugmentation.translate_max_y', index=5,
number=6, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='rotate_rad_max', full_name='AugmentationConfig.SpatialAugmentation.rotate_rad_max', index=6,
number=7, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='rotate_probability', full_name='AugmentationConfig.SpatialAugmentation.rotate_probability', index=7,
number=8, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=644,
serialized_end=857,
)
_AUGMENTATIONCONFIG_COLORAUGMENTATION = _descriptor.Descriptor(
name='ColorAugmentation',
full_name='AugmentationConfig.ColorAugmentation',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='color_shift_stddev', full_name='AugmentationConfig.ColorAugmentation.color_shift_stddev', index=0,
number=1, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='hue_rotation_max', full_name='AugmentationConfig.ColorAugmentation.hue_rotation_max', index=1,
number=2, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='saturation_shift_max', full_name='AugmentationConfig.ColorAugmentation.saturation_shift_max', index=2,
number=3, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='contrast_scale_max', full_name='AugmentationConfig.ColorAugmentation.contrast_scale_max', index=3,
number=5, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='contrast_center', full_name='AugmentationConfig.ColorAugmentation.contrast_center', index=4,
number=8, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=860,
serialized_end=1016,
)
_AUGMENTATIONCONFIG = _descriptor.Descriptor(
name='AugmentationConfig',
full_name='AugmentationConfig',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='preprocessing', full_name='AugmentationConfig.preprocessing', index=0,
number=1, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='spatial_augmentation', full_name='AugmentationConfig.spatial_augmentation', index=1,
number=2, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='color_augmentation', full_name='AugmentationConfig.color_augmentation', index=2,
number=3, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[_AUGMENTATIONCONFIG_PREPROCESSING, _AUGMENTATIONCONFIG_SPATIALAUGMENTATION, _AUGMENTATIONCONFIG_COLORAUGMENTATION, ],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=70,
serialized_end=1016,
)
_AUGMENTATIONCONFIG_PREPROCESSING.containing_type = _AUGMENTATIONCONFIG
_AUGMENTATIONCONFIG_SPATIALAUGMENTATION.containing_type = _AUGMENTATIONCONFIG
_AUGMENTATIONCONFIG_COLORAUGMENTATION.containing_type = _AUGMENTATIONCONFIG
_AUGMENTATIONCONFIG.fields_by_name['preprocessing'].message_type = _AUGMENTATIONCONFIG_PREPROCESSING
_AUGMENTATIONCONFIG.fields_by_name['spatial_augmentation'].message_type = _AUGMENTATIONCONFIG_SPATIALAUGMENTATION
_AUGMENTATIONCONFIG.fields_by_name['color_augmentation'].message_type = _AUGMENTATIONCONFIG_COLORAUGMENTATION
DESCRIPTOR.message_types_by_name['AugmentationConfig'] = _AUGMENTATIONCONFIG
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
AugmentationConfig = _reflection.GeneratedProtocolMessageType('AugmentationConfig', (_message.Message,), dict(
Preprocessing = _reflection.GeneratedProtocolMessageType('Preprocessing', (_message.Message,), dict(
DESCRIPTOR = _AUGMENTATIONCONFIG_PREPROCESSING,
__module__ = 'nvidia_tao_deploy.cv.detectnet_v2.proto.augmentation_config_pb2'
# @@protoc_insertion_point(class_scope:AugmentationConfig.Preprocessing)
))
,
SpatialAugmentation = _reflection.GeneratedProtocolMessageType('SpatialAugmentation', (_message.Message,), dict(
DESCRIPTOR = _AUGMENTATIONCONFIG_SPATIALAUGMENTATION,
__module__ = 'nvidia_tao_deploy.cv.detectnet_v2.proto.augmentation_config_pb2'
# @@protoc_insertion_point(class_scope:AugmentationConfig.SpatialAugmentation)
))
,
ColorAugmentation = _reflection.GeneratedProtocolMessageType('ColorAugmentation', (_message.Message,), dict(
DESCRIPTOR = _AUGMENTATIONCONFIG_COLORAUGMENTATION,
__module__ = 'nvidia_tao_deploy.cv.detectnet_v2.proto.augmentation_config_pb2'
# @@protoc_insertion_point(class_scope:AugmentationConfig.ColorAugmentation)
))
,
DESCRIPTOR = _AUGMENTATIONCONFIG,
__module__ = 'nvidia_tao_deploy.cv.detectnet_v2.proto.augmentation_config_pb2'
# @@protoc_insertion_point(class_scope:AugmentationConfig)
))
_sym_db.RegisterMessage(AugmentationConfig)
_sym_db.RegisterMessage(AugmentationConfig.Preprocessing)
_sym_db.RegisterMessage(AugmentationConfig.SpatialAugmentation)
_sym_db.RegisterMessage(AugmentationConfig.ColorAugmentation)
# @@protoc_insertion_point(module_scope)
| tao_deploy-main | nvidia_tao_deploy/cv/detectnet_v2/proto/augmentation_config_pb2.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nvidia_tao_deploy/cv/detectnet_v2/proto/coco_config.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor.FileDescriptor(
name='nvidia_tao_deploy/cv/detectnet_v2/proto/coco_config.proto',
package='',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\n9nvidia_tao_deploy/cv/detectnet_v2/proto/coco_config.proto\"\x86\x01\n\nCOCOConfig\x12\x1b\n\x13root_directory_path\x18\x01 \x01(\t\x12\x15\n\rimg_dir_names\x18\x02 \x03(\t\x12\x18\n\x10\x61nnotation_files\x18\x03 \x03(\t\x12\x16\n\x0enum_partitions\x18\x04 \x01(\r\x12\x12\n\nnum_shards\x18\x05 \x03(\rb\x06proto3')
)
_COCOCONFIG = _descriptor.Descriptor(
name='COCOConfig',
full_name='COCOConfig',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='root_directory_path', full_name='COCOConfig.root_directory_path', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='img_dir_names', full_name='COCOConfig.img_dir_names', index=1,
number=2, type=9, cpp_type=9, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='annotation_files', full_name='COCOConfig.annotation_files', index=2,
number=3, type=9, cpp_type=9, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='num_partitions', full_name='COCOConfig.num_partitions', index=3,
number=4, type=13, cpp_type=3, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='num_shards', full_name='COCOConfig.num_shards', index=4,
number=5, type=13, cpp_type=3, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=62,
serialized_end=196,
)
DESCRIPTOR.message_types_by_name['COCOConfig'] = _COCOCONFIG
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
COCOConfig = _reflection.GeneratedProtocolMessageType('COCOConfig', (_message.Message,), dict(
DESCRIPTOR = _COCOCONFIG,
__module__ = 'nvidia_tao_deploy.cv.detectnet_v2.proto.coco_config_pb2'
# @@protoc_insertion_point(class_scope:COCOConfig)
))
_sym_db.RegisterMessage(COCOConfig)
# @@protoc_insertion_point(module_scope)
| tao_deploy-main | nvidia_tao_deploy/cv/detectnet_v2/proto/coco_config_pb2.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nvidia_tao_deploy/cv/detectnet_v2/proto/postprocessing_config.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor.FileDescriptor(
name='nvidia_tao_deploy/cv/detectnet_v2/proto/postprocessing_config.proto',
package='',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\nCnvidia_tao_deploy/cv/detectnet_v2/proto/postprocessing_config.proto\"\xfd\x02\n\x10\x43lusteringConfig\x12\x1a\n\x12\x63overage_threshold\x18\x01 \x01(\x02\x12#\n\x1bminimum_bounding_box_height\x18\x02 \x01(\x05\x12\x43\n\x14\x63lustering_algorithm\x18\x03 \x01(\x0e\x32%.ClusteringConfig.ClusteringAlgorithm\x12\x12\n\ndbscan_eps\x18\x04 \x01(\x02\x12\x1a\n\x12\x64\x62scan_min_samples\x18\x05 \x01(\x05\x12\x19\n\x11neighborhood_size\x18\x06 \x01(\x05\x12#\n\x1b\x64\x62scan_confidence_threshold\x18\x07 \x01(\x02\x12\x19\n\x11nms_iou_threshold\x18\x08 \x01(\x02\x12 \n\x18nms_confidence_threshold\x18\t \x01(\x02\"6\n\x13\x43lusteringAlgorithm\x12\n\n\x06\x44\x42SCAN\x10\x00\x12\x07\n\x03NMS\x10\x01\x12\n\n\x06HYBRID\x10\x02\"o\n\x10\x43onfidenceConfig\x12\x1c\n\x14\x63onfidence_threshold\x18\x01 \x01(\x02\x12!\n\x19\x63onfidence_model_filename\x18\x02 \x01(\t\x12\x1a\n\x12normalization_mode\x18\x03 \x01(\t\"\xb5\x02\n\x14PostProcessingConfig\x12I\n\x13target_class_config\x18\x01 \x03(\x0b\x32,.PostProcessingConfig.TargetClassConfigEntry\x1ao\n\x11TargetClassConfig\x12,\n\x11\x63lustering_config\x18\x01 \x01(\x0b\x32\x11.ClusteringConfig\x12,\n\x11\x63onfidence_config\x18\x02 \x01(\x0b\x32\x11.ConfidenceConfig\x1a\x61\n\x16TargetClassConfigEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x36\n\x05value\x18\x02 \x01(\x0b\x32\'.PostProcessingConfig.TargetClassConfig:\x02\x38\x01\x62\x06proto3')
)
_CLUSTERINGCONFIG_CLUSTERINGALGORITHM = _descriptor.EnumDescriptor(
name='ClusteringAlgorithm',
full_name='ClusteringConfig.ClusteringAlgorithm',
filename=None,
file=DESCRIPTOR,
values=[
_descriptor.EnumValueDescriptor(
name='DBSCAN', index=0, number=0,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='NMS', index=1, number=1,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='HYBRID', index=2, number=2,
serialized_options=None,
type=None),
],
containing_type=None,
serialized_options=None,
serialized_start=399,
serialized_end=453,
)
_sym_db.RegisterEnumDescriptor(_CLUSTERINGCONFIG_CLUSTERINGALGORITHM)
_CLUSTERINGCONFIG = _descriptor.Descriptor(
name='ClusteringConfig',
full_name='ClusteringConfig',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='coverage_threshold', full_name='ClusteringConfig.coverage_threshold', index=0,
number=1, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='minimum_bounding_box_height', full_name='ClusteringConfig.minimum_bounding_box_height', index=1,
number=2, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='clustering_algorithm', full_name='ClusteringConfig.clustering_algorithm', index=2,
number=3, type=14, cpp_type=8, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='dbscan_eps', full_name='ClusteringConfig.dbscan_eps', index=3,
number=4, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='dbscan_min_samples', full_name='ClusteringConfig.dbscan_min_samples', index=4,
number=5, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='neighborhood_size', full_name='ClusteringConfig.neighborhood_size', index=5,
number=6, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='dbscan_confidence_threshold', full_name='ClusteringConfig.dbscan_confidence_threshold', index=6,
number=7, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='nms_iou_threshold', full_name='ClusteringConfig.nms_iou_threshold', index=7,
number=8, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='nms_confidence_threshold', full_name='ClusteringConfig.nms_confidence_threshold', index=8,
number=9, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
_CLUSTERINGCONFIG_CLUSTERINGALGORITHM,
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=72,
serialized_end=453,
)
_CONFIDENCECONFIG = _descriptor.Descriptor(
name='ConfidenceConfig',
full_name='ConfidenceConfig',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='confidence_threshold', full_name='ConfidenceConfig.confidence_threshold', index=0,
number=1, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='confidence_model_filename', full_name='ConfidenceConfig.confidence_model_filename', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='normalization_mode', full_name='ConfidenceConfig.normalization_mode', index=2,
number=3, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=455,
serialized_end=566,
)
_POSTPROCESSINGCONFIG_TARGETCLASSCONFIG = _descriptor.Descriptor(
name='TargetClassConfig',
full_name='PostProcessingConfig.TargetClassConfig',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='clustering_config', full_name='PostProcessingConfig.TargetClassConfig.clustering_config', index=0,
number=1, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='confidence_config', full_name='PostProcessingConfig.TargetClassConfig.confidence_config', index=1,
number=2, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=668,
serialized_end=779,
)
_POSTPROCESSINGCONFIG_TARGETCLASSCONFIGENTRY = _descriptor.Descriptor(
name='TargetClassConfigEntry',
full_name='PostProcessingConfig.TargetClassConfigEntry',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='key', full_name='PostProcessingConfig.TargetClassConfigEntry.key', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='value', full_name='PostProcessingConfig.TargetClassConfigEntry.value', index=1,
number=2, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=_b('8\001'),
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=781,
serialized_end=878,
)
_POSTPROCESSINGCONFIG = _descriptor.Descriptor(
name='PostProcessingConfig',
full_name='PostProcessingConfig',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='target_class_config', full_name='PostProcessingConfig.target_class_config', index=0,
number=1, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[_POSTPROCESSINGCONFIG_TARGETCLASSCONFIG, _POSTPROCESSINGCONFIG_TARGETCLASSCONFIGENTRY, ],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=569,
serialized_end=878,
)
_CLUSTERINGCONFIG.fields_by_name['clustering_algorithm'].enum_type = _CLUSTERINGCONFIG_CLUSTERINGALGORITHM
_CLUSTERINGCONFIG_CLUSTERINGALGORITHM.containing_type = _CLUSTERINGCONFIG
_POSTPROCESSINGCONFIG_TARGETCLASSCONFIG.fields_by_name['clustering_config'].message_type = _CLUSTERINGCONFIG
_POSTPROCESSINGCONFIG_TARGETCLASSCONFIG.fields_by_name['confidence_config'].message_type = _CONFIDENCECONFIG
_POSTPROCESSINGCONFIG_TARGETCLASSCONFIG.containing_type = _POSTPROCESSINGCONFIG
_POSTPROCESSINGCONFIG_TARGETCLASSCONFIGENTRY.fields_by_name['value'].message_type = _POSTPROCESSINGCONFIG_TARGETCLASSCONFIG
_POSTPROCESSINGCONFIG_TARGETCLASSCONFIGENTRY.containing_type = _POSTPROCESSINGCONFIG
_POSTPROCESSINGCONFIG.fields_by_name['target_class_config'].message_type = _POSTPROCESSINGCONFIG_TARGETCLASSCONFIGENTRY
DESCRIPTOR.message_types_by_name['ClusteringConfig'] = _CLUSTERINGCONFIG
DESCRIPTOR.message_types_by_name['ConfidenceConfig'] = _CONFIDENCECONFIG
DESCRIPTOR.message_types_by_name['PostProcessingConfig'] = _POSTPROCESSINGCONFIG
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
ClusteringConfig = _reflection.GeneratedProtocolMessageType('ClusteringConfig', (_message.Message,), dict(
DESCRIPTOR = _CLUSTERINGCONFIG,
__module__ = 'nvidia_tao_deploy.cv.detectnet_v2.proto.postprocessing_config_pb2'
# @@protoc_insertion_point(class_scope:ClusteringConfig)
))
_sym_db.RegisterMessage(ClusteringConfig)
ConfidenceConfig = _reflection.GeneratedProtocolMessageType('ConfidenceConfig', (_message.Message,), dict(
DESCRIPTOR = _CONFIDENCECONFIG,
__module__ = 'nvidia_tao_deploy.cv.detectnet_v2.proto.postprocessing_config_pb2'
# @@protoc_insertion_point(class_scope:ConfidenceConfig)
))
_sym_db.RegisterMessage(ConfidenceConfig)
PostProcessingConfig = _reflection.GeneratedProtocolMessageType('PostProcessingConfig', (_message.Message,), dict(
TargetClassConfig = _reflection.GeneratedProtocolMessageType('TargetClassConfig', (_message.Message,), dict(
DESCRIPTOR = _POSTPROCESSINGCONFIG_TARGETCLASSCONFIG,
__module__ = 'nvidia_tao_deploy.cv.detectnet_v2.proto.postprocessing_config_pb2'
# @@protoc_insertion_point(class_scope:PostProcessingConfig.TargetClassConfig)
))
,
TargetClassConfigEntry = _reflection.GeneratedProtocolMessageType('TargetClassConfigEntry', (_message.Message,), dict(
DESCRIPTOR = _POSTPROCESSINGCONFIG_TARGETCLASSCONFIGENTRY,
__module__ = 'nvidia_tao_deploy.cv.detectnet_v2.proto.postprocessing_config_pb2'
# @@protoc_insertion_point(class_scope:PostProcessingConfig.TargetClassConfigEntry)
))
,
DESCRIPTOR = _POSTPROCESSINGCONFIG,
__module__ = 'nvidia_tao_deploy.cv.detectnet_v2.proto.postprocessing_config_pb2'
# @@protoc_insertion_point(class_scope:PostProcessingConfig)
))
_sym_db.RegisterMessage(PostProcessingConfig)
_sym_db.RegisterMessage(PostProcessingConfig.TargetClassConfig)
_sym_db.RegisterMessage(PostProcessingConfig.TargetClassConfigEntry)
_POSTPROCESSINGCONFIG_TARGETCLASSCONFIGENTRY._options = None
# @@protoc_insertion_point(module_scope)
| tao_deploy-main | nvidia_tao_deploy/cv/detectnet_v2/proto/postprocessing_config_pb2.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nvidia_tao_deploy/cv/detectnet_v2/proto/visualizer_config.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
from nvidia_tao_deploy.cv.common.proto import clearml_config_pb2 as nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_clearml__config__pb2
from nvidia_tao_deploy.cv.common.proto import wandb_config_pb2 as nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_wandb__config__pb2
DESCRIPTOR = _descriptor.FileDescriptor(
name='nvidia_tao_deploy/cv/detectnet_v2/proto/visualizer_config.proto',
package='',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\n?nvidia_tao_deploy/cv/detectnet_v2/proto/visualizer_config.proto\x1a\x36nvidia_tao_deploy/cv/common/proto/clearml_config.proto\x1a\x34nvidia_tao_deploy/cv/common/proto/wandb_config.proto\"\xa2\x03\n\x10VisualizerConfig\x12\x0f\n\x07\x65nabled\x18\x01 \x01(\x08\x12\x12\n\nnum_images\x18\x02 \x01(\r\x12 \n\x18scalar_logging_frequency\x18\x03 \x01(\r\x12$\n\x1cinfrequent_logging_frequency\x18\x04 \x01(\r\x12\x45\n\x13target_class_config\x18\x05 \x03(\x0b\x32(.VisualizerConfig.TargetClassConfigEntry\x12\"\n\x0cwandb_config\x18\x06 \x01(\x0b\x32\x0c.WandBConfig\x12&\n\x0e\x63learml_config\x18\x07 \x01(\x0b\x32\x0e.ClearMLConfig\x1a/\n\x11TargetClassConfig\x12\x1a\n\x12\x63overage_threshold\x18\x01 \x01(\x02\x1a]\n\x16TargetClassConfigEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x32\n\x05value\x18\x02 \x01(\x0b\x32#.VisualizerConfig.TargetClassConfig:\x02\x38\x01\x62\x06proto3')
,
dependencies=[nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_clearml__config__pb2.DESCRIPTOR,nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_wandb__config__pb2.DESCRIPTOR,])
_VISUALIZERCONFIG_TARGETCLASSCONFIG = _descriptor.Descriptor(
name='TargetClassConfig',
full_name='VisualizerConfig.TargetClassConfig',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='coverage_threshold', full_name='VisualizerConfig.TargetClassConfig.coverage_threshold', index=0,
number=1, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=454,
serialized_end=501,
)
_VISUALIZERCONFIG_TARGETCLASSCONFIGENTRY = _descriptor.Descriptor(
name='TargetClassConfigEntry',
full_name='VisualizerConfig.TargetClassConfigEntry',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='key', full_name='VisualizerConfig.TargetClassConfigEntry.key', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='value', full_name='VisualizerConfig.TargetClassConfigEntry.value', index=1,
number=2, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=_b('8\001'),
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=503,
serialized_end=596,
)
_VISUALIZERCONFIG = _descriptor.Descriptor(
name='VisualizerConfig',
full_name='VisualizerConfig',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='enabled', full_name='VisualizerConfig.enabled', index=0,
number=1, type=8, cpp_type=7, label=1,
has_default_value=False, default_value=False,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='num_images', full_name='VisualizerConfig.num_images', index=1,
number=2, type=13, cpp_type=3, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='scalar_logging_frequency', full_name='VisualizerConfig.scalar_logging_frequency', index=2,
number=3, type=13, cpp_type=3, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='infrequent_logging_frequency', full_name='VisualizerConfig.infrequent_logging_frequency', index=3,
number=4, type=13, cpp_type=3, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='target_class_config', full_name='VisualizerConfig.target_class_config', index=4,
number=5, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='wandb_config', full_name='VisualizerConfig.wandb_config', index=5,
number=6, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='clearml_config', full_name='VisualizerConfig.clearml_config', index=6,
number=7, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[_VISUALIZERCONFIG_TARGETCLASSCONFIG, _VISUALIZERCONFIG_TARGETCLASSCONFIGENTRY, ],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=178,
serialized_end=596,
)
_VISUALIZERCONFIG_TARGETCLASSCONFIG.containing_type = _VISUALIZERCONFIG
_VISUALIZERCONFIG_TARGETCLASSCONFIGENTRY.fields_by_name['value'].message_type = _VISUALIZERCONFIG_TARGETCLASSCONFIG
_VISUALIZERCONFIG_TARGETCLASSCONFIGENTRY.containing_type = _VISUALIZERCONFIG
_VISUALIZERCONFIG.fields_by_name['target_class_config'].message_type = _VISUALIZERCONFIG_TARGETCLASSCONFIGENTRY
_VISUALIZERCONFIG.fields_by_name['wandb_config'].message_type = nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_wandb__config__pb2._WANDBCONFIG
_VISUALIZERCONFIG.fields_by_name['clearml_config'].message_type = nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_clearml__config__pb2._CLEARMLCONFIG
DESCRIPTOR.message_types_by_name['VisualizerConfig'] = _VISUALIZERCONFIG
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
VisualizerConfig = _reflection.GeneratedProtocolMessageType('VisualizerConfig', (_message.Message,), dict(
TargetClassConfig = _reflection.GeneratedProtocolMessageType('TargetClassConfig', (_message.Message,), dict(
DESCRIPTOR = _VISUALIZERCONFIG_TARGETCLASSCONFIG,
__module__ = 'nvidia_tao_deploy.cv.detectnet_v2.proto.visualizer_config_pb2'
# @@protoc_insertion_point(class_scope:VisualizerConfig.TargetClassConfig)
))
,
TargetClassConfigEntry = _reflection.GeneratedProtocolMessageType('TargetClassConfigEntry', (_message.Message,), dict(
DESCRIPTOR = _VISUALIZERCONFIG_TARGETCLASSCONFIGENTRY,
__module__ = 'nvidia_tao_deploy.cv.detectnet_v2.proto.visualizer_config_pb2'
# @@protoc_insertion_point(class_scope:VisualizerConfig.TargetClassConfigEntry)
))
,
DESCRIPTOR = _VISUALIZERCONFIG,
__module__ = 'nvidia_tao_deploy.cv.detectnet_v2.proto.visualizer_config_pb2'
# @@protoc_insertion_point(class_scope:VisualizerConfig)
))
_sym_db.RegisterMessage(VisualizerConfig)
_sym_db.RegisterMessage(VisualizerConfig.TargetClassConfig)
_sym_db.RegisterMessage(VisualizerConfig.TargetClassConfigEntry)
_VISUALIZERCONFIG_TARGETCLASSCONFIGENTRY._options = None
# @@protoc_insertion_point(module_scope)
| tao_deploy-main | nvidia_tao_deploy/cv/detectnet_v2/proto/visualizer_config_pb2.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nvidia_tao_deploy/cv/detectnet_v2/proto/learning_rate_config.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
from nvidia_tao_deploy.cv.detectnet_v2.proto import soft_start_annealing_schedule_config_pb2 as nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_soft__start__annealing__schedule__config__pb2
from nvidia_tao_deploy.cv.detectnet_v2.proto import early_stopping_annealing_schedule_config_pb2 as nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_early__stopping__annealing__schedule__config__pb2
DESCRIPTOR = _descriptor.FileDescriptor(
name='nvidia_tao_deploy/cv/detectnet_v2/proto/learning_rate_config.proto',
package='',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\nBnvidia_tao_deploy/cv/detectnet_v2/proto/learning_rate_config.proto\x1aRnvidia_tao_deploy/cv/detectnet_v2/proto/soft_start_annealing_schedule_config.proto\x1aVnvidia_tao_deploy/cv/detectnet_v2/proto/early_stopping_annealing_schedule_config.proto\"\xc5\x01\n\x12LearningRateConfig\x12J\n\x1dsoft_start_annealing_schedule\x18\x01 \x01(\x0b\x32!.SoftStartAnnealingScheduleConfigH\x00\x12R\n!early_stopping_annealing_schedule\x18\x02 \x01(\x0b\x32%.EarlyStoppingAnnealingScheduleConfigH\x00\x42\x0f\n\rlearning_rateb\x06proto3')
,
dependencies=[nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_soft__start__annealing__schedule__config__pb2.DESCRIPTOR,nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_early__stopping__annealing__schedule__config__pb2.DESCRIPTOR,])
_LEARNINGRATECONFIG = _descriptor.Descriptor(
name='LearningRateConfig',
full_name='LearningRateConfig',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='soft_start_annealing_schedule', full_name='LearningRateConfig.soft_start_annealing_schedule', index=0,
number=1, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='early_stopping_annealing_schedule', full_name='LearningRateConfig.early_stopping_annealing_schedule', index=1,
number=2, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
_descriptor.OneofDescriptor(
name='learning_rate', full_name='LearningRateConfig.learning_rate',
index=0, containing_type=None, fields=[]),
],
serialized_start=243,
serialized_end=440,
)
_LEARNINGRATECONFIG.fields_by_name['soft_start_annealing_schedule'].message_type = nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_soft__start__annealing__schedule__config__pb2._SOFTSTARTANNEALINGSCHEDULECONFIG
_LEARNINGRATECONFIG.fields_by_name['early_stopping_annealing_schedule'].message_type = nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_early__stopping__annealing__schedule__config__pb2._EARLYSTOPPINGANNEALINGSCHEDULECONFIG
_LEARNINGRATECONFIG.oneofs_by_name['learning_rate'].fields.append(
_LEARNINGRATECONFIG.fields_by_name['soft_start_annealing_schedule'])
_LEARNINGRATECONFIG.fields_by_name['soft_start_annealing_schedule'].containing_oneof = _LEARNINGRATECONFIG.oneofs_by_name['learning_rate']
_LEARNINGRATECONFIG.oneofs_by_name['learning_rate'].fields.append(
_LEARNINGRATECONFIG.fields_by_name['early_stopping_annealing_schedule'])
_LEARNINGRATECONFIG.fields_by_name['early_stopping_annealing_schedule'].containing_oneof = _LEARNINGRATECONFIG.oneofs_by_name['learning_rate']
DESCRIPTOR.message_types_by_name['LearningRateConfig'] = _LEARNINGRATECONFIG
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
LearningRateConfig = _reflection.GeneratedProtocolMessageType('LearningRateConfig', (_message.Message,), dict(
DESCRIPTOR = _LEARNINGRATECONFIG,
__module__ = 'nvidia_tao_deploy.cv.detectnet_v2.proto.learning_rate_config_pb2'
# @@protoc_insertion_point(class_scope:LearningRateConfig)
))
_sym_db.RegisterMessage(LearningRateConfig)
# @@protoc_insertion_point(module_scope)
| tao_deploy-main | nvidia_tao_deploy/cv/detectnet_v2/proto/learning_rate_config_pb2.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nvidia_tao_deploy/cv/detectnet_v2/proto/inference.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
from nvidia_tao_deploy.cv.detectnet_v2.proto import inferencer_config_pb2 as nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_inferencer__config__pb2
from nvidia_tao_deploy.cv.detectnet_v2.proto import postprocessing_config_pb2 as nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_postprocessing__config__pb2
from nvidia_tao_deploy.cv.common.proto import wandb_config_pb2 as nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_wandb__config__pb2
DESCRIPTOR = _descriptor.FileDescriptor(
name='nvidia_tao_deploy/cv/detectnet_v2/proto/inference.proto',
package='',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\n7nvidia_tao_deploy/cv/detectnet_v2/proto/inference.proto\x1a?nvidia_tao_deploy/cv/detectnet_v2/proto/inferencer_config.proto\x1a\x43nvidia_tao_deploy/cv/detectnet_v2/proto/postprocessing_config.proto\x1a\x34nvidia_tao_deploy/cv/common/proto/wandb_config.proto\"\xe1\x01\n\x1a\x43lasswiseBboxHandlerConfig\x12,\n\x11\x63lustering_config\x18\x01 \x01(\x0b\x32\x11.ClusteringConfig\x12\x18\n\x10\x63onfidence_model\x18\x02 \x01(\t\x12\x12\n\noutput_map\x18\x03 \x01(\t\x12\x39\n\nbbox_color\x18\x07 \x01(\x0b\x32%.ClasswiseBboxHandlerConfig.BboxColor\x1a,\n\tBboxColor\x12\t\n\x01R\x18\x01 \x01(\x05\x12\t\n\x01G\x18\x02 \x01(\x05\x12\t\n\x01\x42\x18\x03 \x01(\x05\"\xd4\x02\n\x11\x42\x62oxHandlerConfig\x12\x12\n\nkitti_dump\x18\x01 \x01(\x08\x12\x17\n\x0f\x64isable_overlay\x18\x02 \x01(\x08\x12\x19\n\x11overlay_linewidth\x18\x03 \x01(\x05\x12Y\n\x1d\x63lasswise_bbox_handler_config\x18\x04 \x03(\x0b\x32\x32.BboxHandlerConfig.ClasswiseBboxHandlerConfigEntry\x12\x18\n\x10postproc_classes\x18\x05 \x03(\t\x12\"\n\x0cwandb_config\x18\x06 \x01(\x0b\x32\x0c.WandBConfig\x1a^\n\x1f\x43lasswiseBboxHandlerConfigEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12*\n\x05value\x18\x02 \x01(\x0b\x32\x1b.ClasswiseBboxHandlerConfig:\x02\x38\x01\"j\n\tInference\x12,\n\x11inferencer_config\x18\x01 \x01(\x0b\x32\x11.InferencerConfig\x12/\n\x13\x62\x62ox_handler_config\x18\x02 \x01(\x0b\x32\x12.BboxHandlerConfigb\x06proto3')
,
dependencies=[nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_inferencer__config__pb2.DESCRIPTOR,nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_postprocessing__config__pb2.DESCRIPTOR,nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_wandb__config__pb2.DESCRIPTOR,])
_CLASSWISEBBOXHANDLERCONFIG_BBOXCOLOR = _descriptor.Descriptor(
name='BboxColor',
full_name='ClasswiseBboxHandlerConfig.BboxColor',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='R', full_name='ClasswiseBboxHandlerConfig.BboxColor.R', index=0,
number=1, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='G', full_name='ClasswiseBboxHandlerConfig.BboxColor.G', index=1,
number=2, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='B', full_name='ClasswiseBboxHandlerConfig.BboxColor.B', index=2,
number=3, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=429,
serialized_end=473,
)
_CLASSWISEBBOXHANDLERCONFIG = _descriptor.Descriptor(
name='ClasswiseBboxHandlerConfig',
full_name='ClasswiseBboxHandlerConfig',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='clustering_config', full_name='ClasswiseBboxHandlerConfig.clustering_config', index=0,
number=1, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='confidence_model', full_name='ClasswiseBboxHandlerConfig.confidence_model', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='output_map', full_name='ClasswiseBboxHandlerConfig.output_map', index=2,
number=3, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='bbox_color', full_name='ClasswiseBboxHandlerConfig.bbox_color', index=3,
number=7, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[_CLASSWISEBBOXHANDLERCONFIG_BBOXCOLOR, ],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=248,
serialized_end=473,
)
_BBOXHANDLERCONFIG_CLASSWISEBBOXHANDLERCONFIGENTRY = _descriptor.Descriptor(
name='ClasswiseBboxHandlerConfigEntry',
full_name='BboxHandlerConfig.ClasswiseBboxHandlerConfigEntry',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='key', full_name='BboxHandlerConfig.ClasswiseBboxHandlerConfigEntry.key', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='value', full_name='BboxHandlerConfig.ClasswiseBboxHandlerConfigEntry.value', index=1,
number=2, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=_b('8\001'),
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=722,
serialized_end=816,
)
_BBOXHANDLERCONFIG = _descriptor.Descriptor(
name='BboxHandlerConfig',
full_name='BboxHandlerConfig',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='kitti_dump', full_name='BboxHandlerConfig.kitti_dump', index=0,
number=1, type=8, cpp_type=7, label=1,
has_default_value=False, default_value=False,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='disable_overlay', full_name='BboxHandlerConfig.disable_overlay', index=1,
number=2, type=8, cpp_type=7, label=1,
has_default_value=False, default_value=False,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='overlay_linewidth', full_name='BboxHandlerConfig.overlay_linewidth', index=2,
number=3, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='classwise_bbox_handler_config', full_name='BboxHandlerConfig.classwise_bbox_handler_config', index=3,
number=4, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='postproc_classes', full_name='BboxHandlerConfig.postproc_classes', index=4,
number=5, type=9, cpp_type=9, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='wandb_config', full_name='BboxHandlerConfig.wandb_config', index=5,
number=6, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[_BBOXHANDLERCONFIG_CLASSWISEBBOXHANDLERCONFIGENTRY, ],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=476,
serialized_end=816,
)
_INFERENCE = _descriptor.Descriptor(
name='Inference',
full_name='Inference',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='inferencer_config', full_name='Inference.inferencer_config', index=0,
number=1, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='bbox_handler_config', full_name='Inference.bbox_handler_config', index=1,
number=2, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=818,
serialized_end=924,
)
_CLASSWISEBBOXHANDLERCONFIG_BBOXCOLOR.containing_type = _CLASSWISEBBOXHANDLERCONFIG
_CLASSWISEBBOXHANDLERCONFIG.fields_by_name['clustering_config'].message_type = nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_postprocessing__config__pb2._CLUSTERINGCONFIG
_CLASSWISEBBOXHANDLERCONFIG.fields_by_name['bbox_color'].message_type = _CLASSWISEBBOXHANDLERCONFIG_BBOXCOLOR
_BBOXHANDLERCONFIG_CLASSWISEBBOXHANDLERCONFIGENTRY.fields_by_name['value'].message_type = _CLASSWISEBBOXHANDLERCONFIG
_BBOXHANDLERCONFIG_CLASSWISEBBOXHANDLERCONFIGENTRY.containing_type = _BBOXHANDLERCONFIG
_BBOXHANDLERCONFIG.fields_by_name['classwise_bbox_handler_config'].message_type = _BBOXHANDLERCONFIG_CLASSWISEBBOXHANDLERCONFIGENTRY
_BBOXHANDLERCONFIG.fields_by_name['wandb_config'].message_type = nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_wandb__config__pb2._WANDBCONFIG
_INFERENCE.fields_by_name['inferencer_config'].message_type = nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_inferencer__config__pb2._INFERENCERCONFIG
_INFERENCE.fields_by_name['bbox_handler_config'].message_type = _BBOXHANDLERCONFIG
DESCRIPTOR.message_types_by_name['ClasswiseBboxHandlerConfig'] = _CLASSWISEBBOXHANDLERCONFIG
DESCRIPTOR.message_types_by_name['BboxHandlerConfig'] = _BBOXHANDLERCONFIG
DESCRIPTOR.message_types_by_name['Inference'] = _INFERENCE
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
ClasswiseBboxHandlerConfig = _reflection.GeneratedProtocolMessageType('ClasswiseBboxHandlerConfig', (_message.Message,), dict(
BboxColor = _reflection.GeneratedProtocolMessageType('BboxColor', (_message.Message,), dict(
DESCRIPTOR = _CLASSWISEBBOXHANDLERCONFIG_BBOXCOLOR,
__module__ = 'nvidia_tao_deploy.cv.detectnet_v2.proto.inference_pb2'
# @@protoc_insertion_point(class_scope:ClasswiseBboxHandlerConfig.BboxColor)
))
,
DESCRIPTOR = _CLASSWISEBBOXHANDLERCONFIG,
__module__ = 'nvidia_tao_deploy.cv.detectnet_v2.proto.inference_pb2'
# @@protoc_insertion_point(class_scope:ClasswiseBboxHandlerConfig)
))
_sym_db.RegisterMessage(ClasswiseBboxHandlerConfig)
_sym_db.RegisterMessage(ClasswiseBboxHandlerConfig.BboxColor)
BboxHandlerConfig = _reflection.GeneratedProtocolMessageType('BboxHandlerConfig', (_message.Message,), dict(
ClasswiseBboxHandlerConfigEntry = _reflection.GeneratedProtocolMessageType('ClasswiseBboxHandlerConfigEntry', (_message.Message,), dict(
DESCRIPTOR = _BBOXHANDLERCONFIG_CLASSWISEBBOXHANDLERCONFIGENTRY,
__module__ = 'nvidia_tao_deploy.cv.detectnet_v2.proto.inference_pb2'
# @@protoc_insertion_point(class_scope:BboxHandlerConfig.ClasswiseBboxHandlerConfigEntry)
))
,
DESCRIPTOR = _BBOXHANDLERCONFIG,
__module__ = 'nvidia_tao_deploy.cv.detectnet_v2.proto.inference_pb2'
# @@protoc_insertion_point(class_scope:BboxHandlerConfig)
))
_sym_db.RegisterMessage(BboxHandlerConfig)
_sym_db.RegisterMessage(BboxHandlerConfig.ClasswiseBboxHandlerConfigEntry)
Inference = _reflection.GeneratedProtocolMessageType('Inference', (_message.Message,), dict(
DESCRIPTOR = _INFERENCE,
__module__ = 'nvidia_tao_deploy.cv.detectnet_v2.proto.inference_pb2'
# @@protoc_insertion_point(class_scope:Inference)
))
_sym_db.RegisterMessage(Inference)
_BBOXHANDLERCONFIG_CLASSWISEBBOXHANDLERCONFIGENTRY._options = None
# @@protoc_insertion_point(module_scope)
| tao_deploy-main | nvidia_tao_deploy/cv/detectnet_v2/proto/inference_pb2.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nvidia_tao_deploy/cv/detectnet_v2/proto/bbox_rasterizer_config.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor.FileDescriptor(
name='nvidia_tao_deploy/cv/detectnet_v2/proto/bbox_rasterizer_config.proto',
package='',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\nDnvidia_tao_deploy/cv/detectnet_v2/proto/bbox_rasterizer_config.proto\"\xe4\x02\n\x14\x42\x62oxRasterizerConfig\x12I\n\x13target_class_config\x18\x01 \x03(\x0b\x32,.BboxRasterizerConfig.TargetClassConfigEntry\x12\x17\n\x0f\x64\x65\x61\x64zone_radius\x18\x02 \x01(\x02\x1a\x84\x01\n\x11TargetClassConfig\x12\x14\n\x0c\x63ov_center_x\x18\x01 \x01(\x02\x12\x14\n\x0c\x63ov_center_y\x18\x02 \x01(\x02\x12\x14\n\x0c\x63ov_radius_x\x18\x03 \x01(\x02\x12\x14\n\x0c\x63ov_radius_y\x18\x04 \x01(\x02\x12\x17\n\x0f\x62\x62ox_min_radius\x18\x05 \x01(\x02\x1a\x61\n\x16TargetClassConfigEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x36\n\x05value\x18\x02 \x01(\x0b\x32\'.BboxRasterizerConfig.TargetClassConfig:\x02\x38\x01\x62\x06proto3')
)
_BBOXRASTERIZERCONFIG_TARGETCLASSCONFIG = _descriptor.Descriptor(
name='TargetClassConfig',
full_name='BboxRasterizerConfig.TargetClassConfig',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='cov_center_x', full_name='BboxRasterizerConfig.TargetClassConfig.cov_center_x', index=0,
number=1, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='cov_center_y', full_name='BboxRasterizerConfig.TargetClassConfig.cov_center_y', index=1,
number=2, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='cov_radius_x', full_name='BboxRasterizerConfig.TargetClassConfig.cov_radius_x', index=2,
number=3, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='cov_radius_y', full_name='BboxRasterizerConfig.TargetClassConfig.cov_radius_y', index=3,
number=4, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='bbox_min_radius', full_name='BboxRasterizerConfig.TargetClassConfig.bbox_min_radius', index=4,
number=5, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=198,
serialized_end=330,
)
_BBOXRASTERIZERCONFIG_TARGETCLASSCONFIGENTRY = _descriptor.Descriptor(
name='TargetClassConfigEntry',
full_name='BboxRasterizerConfig.TargetClassConfigEntry',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='key', full_name='BboxRasterizerConfig.TargetClassConfigEntry.key', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='value', full_name='BboxRasterizerConfig.TargetClassConfigEntry.value', index=1,
number=2, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=_b('8\001'),
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=332,
serialized_end=429,
)
_BBOXRASTERIZERCONFIG = _descriptor.Descriptor(
name='BboxRasterizerConfig',
full_name='BboxRasterizerConfig',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='target_class_config', full_name='BboxRasterizerConfig.target_class_config', index=0,
number=1, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='deadzone_radius', full_name='BboxRasterizerConfig.deadzone_radius', index=1,
number=2, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[_BBOXRASTERIZERCONFIG_TARGETCLASSCONFIG, _BBOXRASTERIZERCONFIG_TARGETCLASSCONFIGENTRY, ],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=73,
serialized_end=429,
)
_BBOXRASTERIZERCONFIG_TARGETCLASSCONFIG.containing_type = _BBOXRASTERIZERCONFIG
_BBOXRASTERIZERCONFIG_TARGETCLASSCONFIGENTRY.fields_by_name['value'].message_type = _BBOXRASTERIZERCONFIG_TARGETCLASSCONFIG
_BBOXRASTERIZERCONFIG_TARGETCLASSCONFIGENTRY.containing_type = _BBOXRASTERIZERCONFIG
_BBOXRASTERIZERCONFIG.fields_by_name['target_class_config'].message_type = _BBOXRASTERIZERCONFIG_TARGETCLASSCONFIGENTRY
DESCRIPTOR.message_types_by_name['BboxRasterizerConfig'] = _BBOXRASTERIZERCONFIG
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
BboxRasterizerConfig = _reflection.GeneratedProtocolMessageType('BboxRasterizerConfig', (_message.Message,), dict(
TargetClassConfig = _reflection.GeneratedProtocolMessageType('TargetClassConfig', (_message.Message,), dict(
DESCRIPTOR = _BBOXRASTERIZERCONFIG_TARGETCLASSCONFIG,
__module__ = 'nvidia_tao_deploy.cv.detectnet_v2.proto.bbox_rasterizer_config_pb2'
# @@protoc_insertion_point(class_scope:BboxRasterizerConfig.TargetClassConfig)
))
,
TargetClassConfigEntry = _reflection.GeneratedProtocolMessageType('TargetClassConfigEntry', (_message.Message,), dict(
DESCRIPTOR = _BBOXRASTERIZERCONFIG_TARGETCLASSCONFIGENTRY,
__module__ = 'nvidia_tao_deploy.cv.detectnet_v2.proto.bbox_rasterizer_config_pb2'
# @@protoc_insertion_point(class_scope:BboxRasterizerConfig.TargetClassConfigEntry)
))
,
DESCRIPTOR = _BBOXRASTERIZERCONFIG,
__module__ = 'nvidia_tao_deploy.cv.detectnet_v2.proto.bbox_rasterizer_config_pb2'
# @@protoc_insertion_point(class_scope:BboxRasterizerConfig)
))
_sym_db.RegisterMessage(BboxRasterizerConfig)
_sym_db.RegisterMessage(BboxRasterizerConfig.TargetClassConfig)
_sym_db.RegisterMessage(BboxRasterizerConfig.TargetClassConfigEntry)
_BBOXRASTERIZERCONFIG_TARGETCLASSCONFIGENTRY._options = None
# @@protoc_insertion_point(module_scope)
| tao_deploy-main | nvidia_tao_deploy/cv/detectnet_v2/proto/bbox_rasterizer_config_pb2.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nvidia_tao_deploy/cv/detectnet_v2/proto/soft_start_annealing_schedule_config.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor.FileDescriptor(
name='nvidia_tao_deploy/cv/detectnet_v2/proto/soft_start_annealing_schedule_config.proto',
package='',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\nRnvidia_tao_deploy/cv/detectnet_v2/proto/soft_start_annealing_schedule_config.proto\"\x7f\n SoftStartAnnealingScheduleConfig\x12\x19\n\x11min_learning_rate\x18\x01 \x01(\x02\x12\x19\n\x11max_learning_rate\x18\x02 \x01(\x02\x12\x12\n\nsoft_start\x18\x03 \x01(\x02\x12\x11\n\tannealing\x18\x04 \x01(\x02\x62\x06proto3')
)
_SOFTSTARTANNEALINGSCHEDULECONFIG = _descriptor.Descriptor(
name='SoftStartAnnealingScheduleConfig',
full_name='SoftStartAnnealingScheduleConfig',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='min_learning_rate', full_name='SoftStartAnnealingScheduleConfig.min_learning_rate', index=0,
number=1, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='max_learning_rate', full_name='SoftStartAnnealingScheduleConfig.max_learning_rate', index=1,
number=2, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='soft_start', full_name='SoftStartAnnealingScheduleConfig.soft_start', index=2,
number=3, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='annealing', full_name='SoftStartAnnealingScheduleConfig.annealing', index=3,
number=4, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=86,
serialized_end=213,
)
DESCRIPTOR.message_types_by_name['SoftStartAnnealingScheduleConfig'] = _SOFTSTARTANNEALINGSCHEDULECONFIG
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
SoftStartAnnealingScheduleConfig = _reflection.GeneratedProtocolMessageType('SoftStartAnnealingScheduleConfig', (_message.Message,), dict(
DESCRIPTOR = _SOFTSTARTANNEALINGSCHEDULECONFIG,
__module__ = 'nvidia_tao_deploy.cv.detectnet_v2.proto.soft_start_annealing_schedule_config_pb2'
# @@protoc_insertion_point(class_scope:SoftStartAnnealingScheduleConfig)
))
_sym_db.RegisterMessage(SoftStartAnnealingScheduleConfig)
# @@protoc_insertion_point(module_scope)
| tao_deploy-main | nvidia_tao_deploy/cv/detectnet_v2/proto/soft_start_annealing_schedule_config_pb2.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nvidia_tao_deploy/cv/detectnet_v2/proto/experiment.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
from nvidia_tao_deploy.cv.detectnet_v2.proto import augmentation_config_pb2 as nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_augmentation__config__pb2
from nvidia_tao_deploy.cv.detectnet_v2.proto import bbox_rasterizer_config_pb2 as nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_bbox__rasterizer__config__pb2
from nvidia_tao_deploy.cv.detectnet_v2.proto import cost_function_config_pb2 as nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_cost__function__config__pb2
from nvidia_tao_deploy.cv.detectnet_v2.proto import dataset_config_pb2 as nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_dataset__config__pb2
from nvidia_tao_deploy.cv.detectnet_v2.proto import evaluation_config_pb2 as nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_evaluation__config__pb2
from nvidia_tao_deploy.cv.detectnet_v2.proto import model_config_pb2 as nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_model__config__pb2
from nvidia_tao_deploy.cv.detectnet_v2.proto import objective_label_filter_pb2 as nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_objective__label__filter__pb2
from nvidia_tao_deploy.cv.detectnet_v2.proto import postprocessing_config_pb2 as nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_postprocessing__config__pb2
from nvidia_tao_deploy.cv.detectnet_v2.proto import training_config_pb2 as nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_training__config__pb2
from nvidia_tao_deploy.cv.detectnet_v2.proto import dataset_export_config_pb2 as nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_dataset__export__config__pb2
DESCRIPTOR = _descriptor.FileDescriptor(
name='nvidia_tao_deploy/cv/detectnet_v2/proto/experiment.proto',
package='',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\n8nvidia_tao_deploy/cv/detectnet_v2/proto/experiment.proto\x1a\x41nvidia_tao_deploy/cv/detectnet_v2/proto/augmentation_config.proto\x1a\x44nvidia_tao_deploy/cv/detectnet_v2/proto/bbox_rasterizer_config.proto\x1a\x42nvidia_tao_deploy/cv/detectnet_v2/proto/cost_function_config.proto\x1a<nvidia_tao_deploy/cv/detectnet_v2/proto/dataset_config.proto\x1a?nvidia_tao_deploy/cv/detectnet_v2/proto/evaluation_config.proto\x1a:nvidia_tao_deploy/cv/detectnet_v2/proto/model_config.proto\x1a\x44nvidia_tao_deploy/cv/detectnet_v2/proto/objective_label_filter.proto\x1a\x43nvidia_tao_deploy/cv/detectnet_v2/proto/postprocessing_config.proto\x1a=nvidia_tao_deploy/cv/detectnet_v2/proto/training_config.proto\x1a\x43nvidia_tao_deploy/cv/detectnet_v2/proto/dataset_export_config.proto\"\x83\x04\n\nExperiment\x12\x13\n\x0brandom_seed\x18\x01 \x01(\r\x12&\n\x0e\x64\x61taset_config\x18\x02 \x01(\x0b\x32\x0e.DatasetConfig\x12\x30\n\x13\x61ugmentation_config\x18\x03 \x01(\x0b\x32\x13.AugmentationConfig\x12\x34\n\x15postprocessing_config\x18\x04 \x01(\x0b\x32\x15.PostProcessingConfig\x12\"\n\x0cmodel_config\x18\x05 \x01(\x0b\x32\x0c.ModelConfig\x12,\n\x11\x65valuation_config\x18\x06 \x01(\x0b\x32\x11.EvaluationConfig\x12\x31\n\x14\x63ost_function_config\x18\x08 \x01(\x0b\x32\x13.CostFunctionConfig\x12(\n\x0ftraining_config\x18\t \x01(\x0b\x32\x0f.TrainingConfig\x12\x35\n\x16\x62\x62ox_rasterizer_config\x18\n \x01(\x0b\x32\x15.BboxRasterizerConfig\x12\x35\n\x16loss_mask_label_filter\x18\x0b \x01(\x0b\x32\x15.ObjectiveLabelFilter\x12\x33\n\x15\x64\x61taset_export_config\x18\x0c \x03(\x0b\x32\x14.DatasetExportConfigb\x06proto3')
,
dependencies=[nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_augmentation__config__pb2.DESCRIPTOR,nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_bbox__rasterizer__config__pb2.DESCRIPTOR,nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_cost__function__config__pb2.DESCRIPTOR,nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_dataset__config__pb2.DESCRIPTOR,nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_evaluation__config__pb2.DESCRIPTOR,nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_model__config__pb2.DESCRIPTOR,nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_objective__label__filter__pb2.DESCRIPTOR,nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_postprocessing__config__pb2.DESCRIPTOR,nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_training__config__pb2.DESCRIPTOR,nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_dataset__export__config__pb2.DESCRIPTOR,])
_EXPERIMENT = _descriptor.Descriptor(
name='Experiment',
full_name='Experiment',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='random_seed', full_name='Experiment.random_seed', index=0,
number=1, type=13, cpp_type=3, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='dataset_config', full_name='Experiment.dataset_config', index=1,
number=2, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='augmentation_config', full_name='Experiment.augmentation_config', index=2,
number=3, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='postprocessing_config', full_name='Experiment.postprocessing_config', index=3,
number=4, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='model_config', full_name='Experiment.model_config', index=4,
number=5, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='evaluation_config', full_name='Experiment.evaluation_config', index=5,
number=6, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='cost_function_config', full_name='Experiment.cost_function_config', index=6,
number=8, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='training_config', full_name='Experiment.training_config', index=7,
number=9, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='bbox_rasterizer_config', full_name='Experiment.bbox_rasterizer_config', index=8,
number=10, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='loss_mask_label_filter', full_name='Experiment.loss_mask_label_filter', index=9,
number=11, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='dataset_export_config', full_name='Experiment.dataset_export_config', index=10,
number=12, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=724,
serialized_end=1239,
)
_EXPERIMENT.fields_by_name['dataset_config'].message_type = nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_dataset__config__pb2._DATASETCONFIG
_EXPERIMENT.fields_by_name['augmentation_config'].message_type = nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_augmentation__config__pb2._AUGMENTATIONCONFIG
_EXPERIMENT.fields_by_name['postprocessing_config'].message_type = nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_postprocessing__config__pb2._POSTPROCESSINGCONFIG
_EXPERIMENT.fields_by_name['model_config'].message_type = nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_model__config__pb2._MODELCONFIG
_EXPERIMENT.fields_by_name['evaluation_config'].message_type = nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_evaluation__config__pb2._EVALUATIONCONFIG
_EXPERIMENT.fields_by_name['cost_function_config'].message_type = nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_cost__function__config__pb2._COSTFUNCTIONCONFIG
_EXPERIMENT.fields_by_name['training_config'].message_type = nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_training__config__pb2._TRAININGCONFIG
_EXPERIMENT.fields_by_name['bbox_rasterizer_config'].message_type = nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_bbox__rasterizer__config__pb2._BBOXRASTERIZERCONFIG
_EXPERIMENT.fields_by_name['loss_mask_label_filter'].message_type = nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_objective__label__filter__pb2._OBJECTIVELABELFILTER
_EXPERIMENT.fields_by_name['dataset_export_config'].message_type = nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_dataset__export__config__pb2._DATASETEXPORTCONFIG
DESCRIPTOR.message_types_by_name['Experiment'] = _EXPERIMENT
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
Experiment = _reflection.GeneratedProtocolMessageType('Experiment', (_message.Message,), dict(
DESCRIPTOR = _EXPERIMENT,
__module__ = 'nvidia_tao_deploy.cv.detectnet_v2.proto.experiment_pb2'
# @@protoc_insertion_point(class_scope:Experiment)
))
_sym_db.RegisterMessage(Experiment)
# @@protoc_insertion_point(module_scope)
| tao_deploy-main | nvidia_tao_deploy/cv/detectnet_v2/proto/experiment_pb2.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""PostProcessingConfig class that holds postprocessing parameters."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import six
from nvidia_tao_deploy.cv.detectnet_v2.proto.clustering_config import build_clustering_config
from nvidia_tao_deploy.cv.detectnet_v2.proto.clustering_config import build_clustering_proto
from nvidia_tao_deploy.cv.detectnet_v2.proto.confidence_config import build_confidence_config
from nvidia_tao_deploy.cv.detectnet_v2.proto.confidence_config import build_confidence_proto
from nvidia_tao_deploy.cv.detectnet_v2.proto.postprocessing_config_pb2 import PostProcessingConfig as\
PostProcessingProto
def build_postprocessing_config(postprocessing_proto):
"""Build PostProcessingConfig from a proto.
Args:
postprocessing_proto: proto.postprocessing_config proto message.
Returns:
configs: A dict of PostProcessingConfig instances indexed by target class name.
"""
configs = {}
for class_name, config in six.iteritems(postprocessing_proto.target_class_config):
clustering_config = build_clustering_config(config.clustering_config)
confidence_config = build_confidence_config(config.confidence_config)
configs[class_name] = PostProcessingConfig(clustering_config, confidence_config)
return configs
class PostProcessingConfig(object):
"""Hold the post-processing parameters for one class."""
def __init__(self, clustering_config, confidence_config):
"""Constructor.
Args:
clustering_config (ClusteringConfig object): Built clustering configuration object.
confidence_config (ConfidenceConfig object): Built confidence configuration object.
"""
self.clustering_config = clustering_config
self.confidence_config = confidence_config
def build_postprocessing_proto(postprocessing_config):
"""Build proto from a PostProcessingConfig dictionary.
Args:
postprocessing_config: A dict of PostProcessingConfig instances indexed by target class
name.
Returns:
postprocessing_proto: proto.postprocessing_config proto message.
"""
proto = PostProcessingProto()
for target_class_name, target_class in six.iteritems(postprocessing_config):
proto.target_class_config[target_class_name].clustering_config.CopyFrom(
build_clustering_proto(target_class.clustering_config))
proto.target_class_config[target_class_name].confidence_config.CopyFrom(
build_confidence_proto(target_class.confidence_config))
return proto
| tao_deploy-main | nvidia_tao_deploy/cv/detectnet_v2/proto/postprocessing_config.py |
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""TAO Deploy Config Base Utilities."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from google.protobuf.text_format import Merge as merge_text_proto
from nvidia_tao_deploy.cv.detectnet_v2.proto.experiment_pb2 import Experiment
from nvidia_tao_deploy.cv.detectnet_v2.proto.inference_pb2 import Inference
def load_proto(config, proto_type="experiment"):
"""Load the experiment proto."""
if proto_type == "experiment":
proto = Experiment()
else:
proto = Inference()
def _load_from_file(filename, pb2):
if not os.path.exists(filename):
raise IOError(f"Specfile not found at: {filename}")
with open(filename, "r", encoding="utf-8") as f:
merge_text_proto(f.read(), pb2)
_load_from_file(config, proto)
return proto
| tao_deploy-main | nvidia_tao_deploy/cv/detectnet_v2/proto/utils.py |
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
"""TAO Deploy Clustering Config."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from nvidia_tao_deploy.cv.detectnet_v2.proto.postprocessing_config_pb2 import ClusteringConfig as ClusteringProto
CLUSTERING_ALGORITHM = {
0: "dbscan",
1: "nms",
2: "hybrid"
}
def build_clustering_config(clustering_config):
"""Build ClusteringConfig from a proto.
Args:
clustering_config: clustering_config proto message.
Returns:
ClusteringConfig object.
"""
return ClusteringConfig(clustering_config.coverage_threshold,
clustering_config.dbscan_eps,
clustering_config.dbscan_min_samples,
clustering_config.minimum_bounding_box_height,
clustering_config.clustering_algorithm,
clustering_config.nms_iou_threshold,
clustering_config.nms_confidence_threshold,
clustering_config.dbscan_confidence_threshold)
def build_clustering_proto(clustering_config):
"""Build proto from ClusteringConfig.
Args:
clustering_config: ClusteringConfig object.
Returns:
clustering_config: clustering_config proto message.
"""
proto = ClusteringProto()
proto.coverage_threshold = clustering_config.coverage_threshold
proto.dbscan_eps = clustering_config.dbscan_eps
proto.dbscan_min_samples = clustering_config.dbscan_min_samples
proto.minimum_bounding_box_height = clustering_config.minimum_bounding_box_height
proto.clustering_algorithm = clustering_config.clustering_algorithm
proto.nms_iou_threshold = clustering_config.nms_iou_threshold
proto.nms_confidence_threshold = clustering_config.nms_confidence_threshold
proto.dbscan_confidence_threshold = clustering_config.dbscan_confidence_threshold
return proto
class ClusteringConfig(object):
"""Hold the parameters for clustering detections."""
def __init__(self, coverage_threshold, dbscan_eps, dbscan_min_samples,
minimum_bounding_box_height, clustering_algorithm,
nms_iou_threshold, nms_confidence_threshold,
dbscan_confidence_threshold):
"""Constructor.
Args:
coverage_threshold (float): Grid cells with coverage lower than this
threshold will be ignored. Valid range [0.0, 1.0].
dbscan_eps (float): DBSCAN eps parameter. The maximum distance between two samples
for them to be considered as in the same neighborhood. Valid range [0.0, 1.0].
dbscan_min_samples (float): DBSCAN min samples parameter. The number of samples (or
total weight) in a neighborhood for a point to be considered as a core point.
This includes the point itself. Must be >= 0.0.
minimum_bounding_box_height (int): Minimum bbox height. Must be >= 0.
clustering_algorithm (clustering_config.clustering_algorithm): The type of clustering
algorithm.
nms_iou_threshold (float): The iou threshold for NMS.
dbscan_confidence_threshold (float): The dbscan confidence threshold.
nms_confidence_threshold (float): The nms confidence threshold.
Raises:
ValueError: If the input arg is not within the accepted range.
"""
if coverage_threshold < 0.0 or coverage_threshold > 1.0:
raise ValueError("ClusteringConfig.coverage_threshold must be in [0.0, 1.0]")
clustering_algorithm = CLUSTERING_ALGORITHM[clustering_algorithm]
if clustering_algorithm not in ["dbscan", "nms"]:
raise NotImplementedError(
f"Invalid clustering algorithm: {clustering_algorithm}"
)
if clustering_algorithm == "dbscan":
if dbscan_eps < 0.0 or dbscan_eps > 1.0:
raise ValueError("ClusteringConfig.dbscan_eps must be in [0.0, 1.0]")
if dbscan_min_samples < 0.0:
raise ValueError("ClusteringConfig.dbscan_min_samples must be >= 0.0")
if minimum_bounding_box_height < 0:
raise ValueError(
"ClusteringConfig.minimum_bounding_box_height must be >= 0"
)
if clustering_algorithm == "nms":
if nms_iou_threshold < 0.0 or nms_iou_threshold > 1.0:
raise ValueError(
"ClusteringConfig.nms_iou_threshold must be in [0.0, 1.0]"
)
self.coverage_threshold = coverage_threshold
self.dbscan_eps = dbscan_eps
self.dbscan_min_samples = dbscan_min_samples
self.dbscan_confidence_threshold = dbscan_confidence_threshold
self.minimum_bounding_box_height = minimum_bounding_box_height
self.clustering_algorithm = clustering_algorithm
self.nms_iou_threshold = nms_iou_threshold
self.nms_confidence_threshold = nms_confidence_threshold
| tao_deploy-main | nvidia_tao_deploy/cv/detectnet_v2/proto/clustering_config.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nvidia_tao_deploy/cv/detectnet_v2/proto/label_filter.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor.FileDescriptor(
name='nvidia_tao_deploy/cv/detectnet_v2/proto/label_filter.proto',
package='',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\n:nvidia_tao_deploy/cv/detectnet_v2/proto/label_filter.proto\"\x88\x04\n\x0bLabelFilter\x12N\n\x1c\x62\x62ox_dimensions_label_filter\x18\x01 \x01(\x0b\x32&.LabelFilter.BboxDimensionsLabelFilterH\x00\x12\x42\n\x16\x62\x62ox_crop_label_filter\x18\x02 \x01(\x0b\x32 .LabelFilter.BboxCropLabelFilterH\x00\x12H\n\x19source_class_label_filter\x18\x03 \x01(\x0b\x32#.LabelFilter.SourceClassLabelFilterH\x00\x1ai\n\x19\x42\x62oxDimensionsLabelFilter\x12\x11\n\tmin_width\x18\x01 \x01(\x02\x12\x12\n\nmin_height\x18\x02 \x01(\x02\x12\x11\n\tmax_width\x18\x03 \x01(\x02\x12\x12\n\nmax_height\x18\x04 \x01(\x02\x1a\x63\n\x13\x42\x62oxCropLabelFilter\x12\x11\n\tcrop_left\x18\x01 \x01(\x02\x12\x12\n\ncrop_right\x18\x02 \x01(\x02\x12\x10\n\x08\x63rop_top\x18\x03 \x01(\x02\x12\x13\n\x0b\x63rop_bottom\x18\x04 \x01(\x02\x1a\x34\n\x16SourceClassLabelFilter\x12\x1a\n\x12source_class_names\x18\x04 \x03(\tB\x15\n\x13label_filter_paramsb\x06proto3')
)
_LABELFILTER_BBOXDIMENSIONSLABELFILTER = _descriptor.Descriptor(
name='BboxDimensionsLabelFilter',
full_name='LabelFilter.BboxDimensionsLabelFilter',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='min_width', full_name='LabelFilter.BboxDimensionsLabelFilter.min_width', index=0,
number=1, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='min_height', full_name='LabelFilter.BboxDimensionsLabelFilter.min_height', index=1,
number=2, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='max_width', full_name='LabelFilter.BboxDimensionsLabelFilter.max_width', index=2,
number=3, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='max_height', full_name='LabelFilter.BboxDimensionsLabelFilter.max_height', index=3,
number=4, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=300,
serialized_end=405,
)
_LABELFILTER_BBOXCROPLABELFILTER = _descriptor.Descriptor(
name='BboxCropLabelFilter',
full_name='LabelFilter.BboxCropLabelFilter',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='crop_left', full_name='LabelFilter.BboxCropLabelFilter.crop_left', index=0,
number=1, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='crop_right', full_name='LabelFilter.BboxCropLabelFilter.crop_right', index=1,
number=2, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='crop_top', full_name='LabelFilter.BboxCropLabelFilter.crop_top', index=2,
number=3, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='crop_bottom', full_name='LabelFilter.BboxCropLabelFilter.crop_bottom', index=3,
number=4, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=407,
serialized_end=506,
)
_LABELFILTER_SOURCECLASSLABELFILTER = _descriptor.Descriptor(
name='SourceClassLabelFilter',
full_name='LabelFilter.SourceClassLabelFilter',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='source_class_names', full_name='LabelFilter.SourceClassLabelFilter.source_class_names', index=0,
number=4, type=9, cpp_type=9, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=508,
serialized_end=560,
)
_LABELFILTER = _descriptor.Descriptor(
name='LabelFilter',
full_name='LabelFilter',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='bbox_dimensions_label_filter', full_name='LabelFilter.bbox_dimensions_label_filter', index=0,
number=1, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='bbox_crop_label_filter', full_name='LabelFilter.bbox_crop_label_filter', index=1,
number=2, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='source_class_label_filter', full_name='LabelFilter.source_class_label_filter', index=2,
number=3, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[_LABELFILTER_BBOXDIMENSIONSLABELFILTER, _LABELFILTER_BBOXCROPLABELFILTER, _LABELFILTER_SOURCECLASSLABELFILTER, ],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
_descriptor.OneofDescriptor(
name='label_filter_params', full_name='LabelFilter.label_filter_params',
index=0, containing_type=None, fields=[]),
],
serialized_start=63,
serialized_end=583,
)
_LABELFILTER_BBOXDIMENSIONSLABELFILTER.containing_type = _LABELFILTER
_LABELFILTER_BBOXCROPLABELFILTER.containing_type = _LABELFILTER
_LABELFILTER_SOURCECLASSLABELFILTER.containing_type = _LABELFILTER
_LABELFILTER.fields_by_name['bbox_dimensions_label_filter'].message_type = _LABELFILTER_BBOXDIMENSIONSLABELFILTER
_LABELFILTER.fields_by_name['bbox_crop_label_filter'].message_type = _LABELFILTER_BBOXCROPLABELFILTER
_LABELFILTER.fields_by_name['source_class_label_filter'].message_type = _LABELFILTER_SOURCECLASSLABELFILTER
_LABELFILTER.oneofs_by_name['label_filter_params'].fields.append(
_LABELFILTER.fields_by_name['bbox_dimensions_label_filter'])
_LABELFILTER.fields_by_name['bbox_dimensions_label_filter'].containing_oneof = _LABELFILTER.oneofs_by_name['label_filter_params']
_LABELFILTER.oneofs_by_name['label_filter_params'].fields.append(
_LABELFILTER.fields_by_name['bbox_crop_label_filter'])
_LABELFILTER.fields_by_name['bbox_crop_label_filter'].containing_oneof = _LABELFILTER.oneofs_by_name['label_filter_params']
_LABELFILTER.oneofs_by_name['label_filter_params'].fields.append(
_LABELFILTER.fields_by_name['source_class_label_filter'])
_LABELFILTER.fields_by_name['source_class_label_filter'].containing_oneof = _LABELFILTER.oneofs_by_name['label_filter_params']
DESCRIPTOR.message_types_by_name['LabelFilter'] = _LABELFILTER
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
LabelFilter = _reflection.GeneratedProtocolMessageType('LabelFilter', (_message.Message,), dict(
BboxDimensionsLabelFilter = _reflection.GeneratedProtocolMessageType('BboxDimensionsLabelFilter', (_message.Message,), dict(
DESCRIPTOR = _LABELFILTER_BBOXDIMENSIONSLABELFILTER,
__module__ = 'nvidia_tao_deploy.cv.detectnet_v2.proto.label_filter_pb2'
# @@protoc_insertion_point(class_scope:LabelFilter.BboxDimensionsLabelFilter)
))
,
BboxCropLabelFilter = _reflection.GeneratedProtocolMessageType('BboxCropLabelFilter', (_message.Message,), dict(
DESCRIPTOR = _LABELFILTER_BBOXCROPLABELFILTER,
__module__ = 'nvidia_tao_deploy.cv.detectnet_v2.proto.label_filter_pb2'
# @@protoc_insertion_point(class_scope:LabelFilter.BboxCropLabelFilter)
))
,
SourceClassLabelFilter = _reflection.GeneratedProtocolMessageType('SourceClassLabelFilter', (_message.Message,), dict(
DESCRIPTOR = _LABELFILTER_SOURCECLASSLABELFILTER,
__module__ = 'nvidia_tao_deploy.cv.detectnet_v2.proto.label_filter_pb2'
# @@protoc_insertion_point(class_scope:LabelFilter.SourceClassLabelFilter)
))
,
DESCRIPTOR = _LABELFILTER,
__module__ = 'nvidia_tao_deploy.cv.detectnet_v2.proto.label_filter_pb2'
# @@protoc_insertion_point(class_scope:LabelFilter)
))
_sym_db.RegisterMessage(LabelFilter)
_sym_db.RegisterMessage(LabelFilter.BboxDimensionsLabelFilter)
_sym_db.RegisterMessage(LabelFilter.BboxCropLabelFilter)
_sym_db.RegisterMessage(LabelFilter.SourceClassLabelFilter)
# @@protoc_insertion_point(module_scope)
| tao_deploy-main | nvidia_tao_deploy/cv/detectnet_v2/proto/label_filter_pb2.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nvidia_tao_deploy/cv/detectnet_v2/proto/kitti_config.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor.FileDescriptor(
name='nvidia_tao_deploy/cv/detectnet_v2/proto/kitti_config.proto',
package='',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\n:nvidia_tao_deploy/cv/detectnet_v2/proto/kitti_config.proto\"\xa5\x02\n\x0bKITTIConfig\x12\x1b\n\x13root_directory_path\x18\x01 \x01(\t\x12\x16\n\x0eimage_dir_name\x18\x02 \x01(\t\x12\x16\n\x0elabel_dir_name\x18\x03 \x01(\t\x12\x18\n\x10point_clouds_dir\x18\x04 \x01(\t\x12\x18\n\x10\x63\x61librations_dir\x18\x05 \x01(\t\x12%\n\x1dkitti_sequence_to_frames_file\x18\x06 \x01(\t\x12\x17\n\x0fimage_extension\x18\x07 \x01(\t\x12\x16\n\x0enum_partitions\x18\x08 \x01(\r\x12\x12\n\nnum_shards\x18\t \x01(\r\x12\x16\n\x0epartition_mode\x18\n \x01(\t\x12\x11\n\tval_split\x18\x0b \x01(\x02\x62\x06proto3')
)
_KITTICONFIG = _descriptor.Descriptor(
name='KITTIConfig',
full_name='KITTIConfig',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='root_directory_path', full_name='KITTIConfig.root_directory_path', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='image_dir_name', full_name='KITTIConfig.image_dir_name', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='label_dir_name', full_name='KITTIConfig.label_dir_name', index=2,
number=3, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='point_clouds_dir', full_name='KITTIConfig.point_clouds_dir', index=3,
number=4, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='calibrations_dir', full_name='KITTIConfig.calibrations_dir', index=4,
number=5, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='kitti_sequence_to_frames_file', full_name='KITTIConfig.kitti_sequence_to_frames_file', index=5,
number=6, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='image_extension', full_name='KITTIConfig.image_extension', index=6,
number=7, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='num_partitions', full_name='KITTIConfig.num_partitions', index=7,
number=8, type=13, cpp_type=3, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='num_shards', full_name='KITTIConfig.num_shards', index=8,
number=9, type=13, cpp_type=3, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='partition_mode', full_name='KITTIConfig.partition_mode', index=9,
number=10, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='val_split', full_name='KITTIConfig.val_split', index=10,
number=11, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=63,
serialized_end=356,
)
DESCRIPTOR.message_types_by_name['KITTIConfig'] = _KITTICONFIG
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
KITTIConfig = _reflection.GeneratedProtocolMessageType('KITTIConfig', (_message.Message,), dict(
DESCRIPTOR = _KITTICONFIG,
__module__ = 'nvidia_tao_deploy.cv.detectnet_v2.proto.kitti_config_pb2'
# @@protoc_insertion_point(class_scope:KITTIConfig)
))
_sym_db.RegisterMessage(KITTIConfig)
# @@protoc_insertion_point(module_scope)
| tao_deploy-main | nvidia_tao_deploy/cv/detectnet_v2/proto/kitti_config_pb2.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nvidia_tao_deploy/cv/detectnet_v2/proto/evaluation_config.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor.FileDescriptor(
name='nvidia_tao_deploy/cv/detectnet_v2/proto/evaluation_config.proto',
package='',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\n?nvidia_tao_deploy/cv/detectnet_v2/proto/evaluation_config.proto\"\xbe\x05\n\x10\x45valuationConfig\x12)\n!validation_period_during_training\x18\x01 \x01(\r\x12\x1e\n\x16\x66irst_validation_epoch\x18\x02 \x01(\r\x12%\n\x1d\x65\x61rly_stopping_patience_steps\x18\x06 \x01(\r\x12i\n&minimum_detection_ground_truth_overlap\x18\x03 \x03(\x0b\x32\x39.EvaluationConfig.MinimumDetectionGroundTruthOverlapEntry\x12I\n\x15\x65valuation_box_config\x18\x04 \x03(\x0b\x32*.EvaluationConfig.EvaluationBoxConfigEntry\x12\x39\n\x16\x61verage_precision_mode\x18\x05 \x01(\x0e\x32\x19.EvaluationConfig.AP_MODE\x1aI\n\'MinimumDetectionGroundTruthOverlapEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\x02:\x02\x38\x01\x1as\n\x13\x45valuationBoxConfig\x12\x16\n\x0eminimum_height\x18\x01 \x01(\x05\x12\x16\n\x0emaximum_height\x18\x02 \x01(\x05\x12\x15\n\rminimum_width\x18\x03 \x01(\x05\x12\x15\n\rmaximum_width\x18\x04 \x01(\x05\x1a\x61\n\x18\x45valuationBoxConfigEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x34\n\x05value\x18\x02 \x01(\x0b\x32%.EvaluationConfig.EvaluationBoxConfig:\x02\x38\x01\"$\n\x07\x41P_MODE\x12\n\n\x06SAMPLE\x10\x00\x12\r\n\tINTEGRATE\x10\x01\x62\x06proto3')
)
_EVALUATIONCONFIG_AP_MODE = _descriptor.EnumDescriptor(
name='AP_MODE',
full_name='EvaluationConfig.AP_MODE',
filename=None,
file=DESCRIPTOR,
values=[
_descriptor.EnumValueDescriptor(
name='SAMPLE', index=0, number=0,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='INTEGRATE', index=1, number=1,
serialized_options=None,
type=None),
],
containing_type=None,
serialized_options=None,
serialized_start=734,
serialized_end=770,
)
_sym_db.RegisterEnumDescriptor(_EVALUATIONCONFIG_AP_MODE)
_EVALUATIONCONFIG_MINIMUMDETECTIONGROUNDTRUTHOVERLAPENTRY = _descriptor.Descriptor(
name='MinimumDetectionGroundTruthOverlapEntry',
full_name='EvaluationConfig.MinimumDetectionGroundTruthOverlapEntry',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='key', full_name='EvaluationConfig.MinimumDetectionGroundTruthOverlapEntry.key', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='value', full_name='EvaluationConfig.MinimumDetectionGroundTruthOverlapEntry.value', index=1,
number=2, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=_b('8\001'),
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=443,
serialized_end=516,
)
_EVALUATIONCONFIG_EVALUATIONBOXCONFIG = _descriptor.Descriptor(
name='EvaluationBoxConfig',
full_name='EvaluationConfig.EvaluationBoxConfig',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='minimum_height', full_name='EvaluationConfig.EvaluationBoxConfig.minimum_height', index=0,
number=1, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='maximum_height', full_name='EvaluationConfig.EvaluationBoxConfig.maximum_height', index=1,
number=2, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='minimum_width', full_name='EvaluationConfig.EvaluationBoxConfig.minimum_width', index=2,
number=3, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='maximum_width', full_name='EvaluationConfig.EvaluationBoxConfig.maximum_width', index=3,
number=4, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=518,
serialized_end=633,
)
_EVALUATIONCONFIG_EVALUATIONBOXCONFIGENTRY = _descriptor.Descriptor(
name='EvaluationBoxConfigEntry',
full_name='EvaluationConfig.EvaluationBoxConfigEntry',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='key', full_name='EvaluationConfig.EvaluationBoxConfigEntry.key', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='value', full_name='EvaluationConfig.EvaluationBoxConfigEntry.value', index=1,
number=2, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=_b('8\001'),
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=635,
serialized_end=732,
)
_EVALUATIONCONFIG = _descriptor.Descriptor(
name='EvaluationConfig',
full_name='EvaluationConfig',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='validation_period_during_training', full_name='EvaluationConfig.validation_period_during_training', index=0,
number=1, type=13, cpp_type=3, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='first_validation_epoch', full_name='EvaluationConfig.first_validation_epoch', index=1,
number=2, type=13, cpp_type=3, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='early_stopping_patience_steps', full_name='EvaluationConfig.early_stopping_patience_steps', index=2,
number=6, type=13, cpp_type=3, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='minimum_detection_ground_truth_overlap', full_name='EvaluationConfig.minimum_detection_ground_truth_overlap', index=3,
number=3, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='evaluation_box_config', full_name='EvaluationConfig.evaluation_box_config', index=4,
number=4, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='average_precision_mode', full_name='EvaluationConfig.average_precision_mode', index=5,
number=5, type=14, cpp_type=8, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[_EVALUATIONCONFIG_MINIMUMDETECTIONGROUNDTRUTHOVERLAPENTRY, _EVALUATIONCONFIG_EVALUATIONBOXCONFIG, _EVALUATIONCONFIG_EVALUATIONBOXCONFIGENTRY, ],
enum_types=[
_EVALUATIONCONFIG_AP_MODE,
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=68,
serialized_end=770,
)
_EVALUATIONCONFIG_MINIMUMDETECTIONGROUNDTRUTHOVERLAPENTRY.containing_type = _EVALUATIONCONFIG
_EVALUATIONCONFIG_EVALUATIONBOXCONFIG.containing_type = _EVALUATIONCONFIG
_EVALUATIONCONFIG_EVALUATIONBOXCONFIGENTRY.fields_by_name['value'].message_type = _EVALUATIONCONFIG_EVALUATIONBOXCONFIG
_EVALUATIONCONFIG_EVALUATIONBOXCONFIGENTRY.containing_type = _EVALUATIONCONFIG
_EVALUATIONCONFIG.fields_by_name['minimum_detection_ground_truth_overlap'].message_type = _EVALUATIONCONFIG_MINIMUMDETECTIONGROUNDTRUTHOVERLAPENTRY
_EVALUATIONCONFIG.fields_by_name['evaluation_box_config'].message_type = _EVALUATIONCONFIG_EVALUATIONBOXCONFIGENTRY
_EVALUATIONCONFIG.fields_by_name['average_precision_mode'].enum_type = _EVALUATIONCONFIG_AP_MODE
_EVALUATIONCONFIG_AP_MODE.containing_type = _EVALUATIONCONFIG
DESCRIPTOR.message_types_by_name['EvaluationConfig'] = _EVALUATIONCONFIG
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
EvaluationConfig = _reflection.GeneratedProtocolMessageType('EvaluationConfig', (_message.Message,), dict(
MinimumDetectionGroundTruthOverlapEntry = _reflection.GeneratedProtocolMessageType('MinimumDetectionGroundTruthOverlapEntry', (_message.Message,), dict(
DESCRIPTOR = _EVALUATIONCONFIG_MINIMUMDETECTIONGROUNDTRUTHOVERLAPENTRY,
__module__ = 'nvidia_tao_deploy.cv.detectnet_v2.proto.evaluation_config_pb2'
# @@protoc_insertion_point(class_scope:EvaluationConfig.MinimumDetectionGroundTruthOverlapEntry)
))
,
EvaluationBoxConfig = _reflection.GeneratedProtocolMessageType('EvaluationBoxConfig', (_message.Message,), dict(
DESCRIPTOR = _EVALUATIONCONFIG_EVALUATIONBOXCONFIG,
__module__ = 'nvidia_tao_deploy.cv.detectnet_v2.proto.evaluation_config_pb2'
# @@protoc_insertion_point(class_scope:EvaluationConfig.EvaluationBoxConfig)
))
,
EvaluationBoxConfigEntry = _reflection.GeneratedProtocolMessageType('EvaluationBoxConfigEntry', (_message.Message,), dict(
DESCRIPTOR = _EVALUATIONCONFIG_EVALUATIONBOXCONFIGENTRY,
__module__ = 'nvidia_tao_deploy.cv.detectnet_v2.proto.evaluation_config_pb2'
# @@protoc_insertion_point(class_scope:EvaluationConfig.EvaluationBoxConfigEntry)
))
,
DESCRIPTOR = _EVALUATIONCONFIG,
__module__ = 'nvidia_tao_deploy.cv.detectnet_v2.proto.evaluation_config_pb2'
# @@protoc_insertion_point(class_scope:EvaluationConfig)
))
_sym_db.RegisterMessage(EvaluationConfig)
_sym_db.RegisterMessage(EvaluationConfig.MinimumDetectionGroundTruthOverlapEntry)
_sym_db.RegisterMessage(EvaluationConfig.EvaluationBoxConfig)
_sym_db.RegisterMessage(EvaluationConfig.EvaluationBoxConfigEntry)
_EVALUATIONCONFIG_MINIMUMDETECTIONGROUNDTRUTHOVERLAPENTRY._options = None
_EVALUATIONCONFIG_EVALUATIONBOXCONFIGENTRY._options = None
# @@protoc_insertion_point(module_scope)
| tao_deploy-main | nvidia_tao_deploy/cv/detectnet_v2/proto/evaluation_config_pb2.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nvidia_tao_deploy/cv/detectnet_v2/proto/dataset_export_config.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
from nvidia_tao_deploy.cv.detectnet_v2.proto import kitti_config_pb2 as nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_kitti__config__pb2
from nvidia_tao_deploy.cv.detectnet_v2.proto import coco_config_pb2 as nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_coco__config__pb2
DESCRIPTOR = _descriptor.FileDescriptor(
name='nvidia_tao_deploy/cv/detectnet_v2/proto/dataset_export_config.proto',
package='',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\nCnvidia_tao_deploy/cv/detectnet_v2/proto/dataset_export_config.proto\x1a:nvidia_tao_deploy/cv/detectnet_v2/proto/kitti_config.proto\x1a\x39nvidia_tao_deploy/cv/detectnet_v2/proto/coco_config.proto\"\xec\x06\n\x13\x44\x61tasetExportConfig\x12\"\n\x0b\x63oco_config\x18\x01 \x01(\x0b\x32\x0b.COCOConfigH\x00\x12$\n\x0ckitti_config\x18\x02 \x01(\x0b\x32\x0c.KITTIConfigH\x00\x12I\n\x16sample_modifier_config\x18\x05 \x01(\x0b\x32).DatasetExportConfig.SampleModifierConfig\x12\x1c\n\x14image_directory_path\x18\x06 \x01(\t\x12J\n\x14target_class_mapping\x18\x07 \x03(\x0b\x32,.DatasetExportConfig.TargetClassMappingEntry\x1a\x83\x04\n\x14SampleModifierConfig\x12&\n\x1e\x66ilter_samples_containing_only\x18\x01 \x03(\t\x12\x1f\n\x17\x64ominant_target_classes\x18\x02 \x03(\t\x12r\n\x1eminimum_target_class_imbalance\x18\x03 \x03(\x0b\x32J.DatasetExportConfig.SampleModifierConfig.MinimumTargetClassImbalanceEntry\x12\x16\n\x0enum_duplicates\x18\x04 \x01(\r\x12\x1c\n\x14max_training_samples\x18\x05 \x01(\r\x12q\n\x1esource_to_target_class_mapping\x18\x06 \x03(\x0b\x32I.DatasetExportConfig.SampleModifierConfig.SourceToTargetClassMappingEntry\x1a\x42\n MinimumTargetClassImbalanceEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\x02:\x02\x38\x01\x1a\x41\n\x1fSourceToTargetClassMappingEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\x1a\x39\n\x17TargetClassMappingEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\x42\x15\n\x13\x63onvert_config_typeb\x06proto3')
,
dependencies=[nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_kitti__config__pb2.DESCRIPTOR,nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_coco__config__pb2.DESCRIPTOR,])
_DATASETEXPORTCONFIG_SAMPLEMODIFIERCONFIG_MINIMUMTARGETCLASSIMBALANCEENTRY = _descriptor.Descriptor(
name='MinimumTargetClassImbalanceEntry',
full_name='DatasetExportConfig.SampleModifierConfig.MinimumTargetClassImbalanceEntry',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='key', full_name='DatasetExportConfig.SampleModifierConfig.MinimumTargetClassImbalanceEntry.key', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='value', full_name='DatasetExportConfig.SampleModifierConfig.MinimumTargetClassImbalanceEntry.value', index=1,
number=2, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=_b('8\001'),
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=852,
serialized_end=918,
)
_DATASETEXPORTCONFIG_SAMPLEMODIFIERCONFIG_SOURCETOTARGETCLASSMAPPINGENTRY = _descriptor.Descriptor(
name='SourceToTargetClassMappingEntry',
full_name='DatasetExportConfig.SampleModifierConfig.SourceToTargetClassMappingEntry',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='key', full_name='DatasetExportConfig.SampleModifierConfig.SourceToTargetClassMappingEntry.key', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='value', full_name='DatasetExportConfig.SampleModifierConfig.SourceToTargetClassMappingEntry.value', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=_b('8\001'),
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=920,
serialized_end=985,
)
_DATASETEXPORTCONFIG_SAMPLEMODIFIERCONFIG = _descriptor.Descriptor(
name='SampleModifierConfig',
full_name='DatasetExportConfig.SampleModifierConfig',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='filter_samples_containing_only', full_name='DatasetExportConfig.SampleModifierConfig.filter_samples_containing_only', index=0,
number=1, type=9, cpp_type=9, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='dominant_target_classes', full_name='DatasetExportConfig.SampleModifierConfig.dominant_target_classes', index=1,
number=2, type=9, cpp_type=9, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='minimum_target_class_imbalance', full_name='DatasetExportConfig.SampleModifierConfig.minimum_target_class_imbalance', index=2,
number=3, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='num_duplicates', full_name='DatasetExportConfig.SampleModifierConfig.num_duplicates', index=3,
number=4, type=13, cpp_type=3, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='max_training_samples', full_name='DatasetExportConfig.SampleModifierConfig.max_training_samples', index=4,
number=5, type=13, cpp_type=3, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='source_to_target_class_mapping', full_name='DatasetExportConfig.SampleModifierConfig.source_to_target_class_mapping', index=5,
number=6, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[_DATASETEXPORTCONFIG_SAMPLEMODIFIERCONFIG_MINIMUMTARGETCLASSIMBALANCEENTRY, _DATASETEXPORTCONFIG_SAMPLEMODIFIERCONFIG_SOURCETOTARGETCLASSMAPPINGENTRY, ],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=470,
serialized_end=985,
)
_DATASETEXPORTCONFIG_TARGETCLASSMAPPINGENTRY = _descriptor.Descriptor(
name='TargetClassMappingEntry',
full_name='DatasetExportConfig.TargetClassMappingEntry',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='key', full_name='DatasetExportConfig.TargetClassMappingEntry.key', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='value', full_name='DatasetExportConfig.TargetClassMappingEntry.value', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=_b('8\001'),
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=987,
serialized_end=1044,
)
_DATASETEXPORTCONFIG = _descriptor.Descriptor(
name='DatasetExportConfig',
full_name='DatasetExportConfig',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='coco_config', full_name='DatasetExportConfig.coco_config', index=0,
number=1, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='kitti_config', full_name='DatasetExportConfig.kitti_config', index=1,
number=2, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='sample_modifier_config', full_name='DatasetExportConfig.sample_modifier_config', index=2,
number=5, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='image_directory_path', full_name='DatasetExportConfig.image_directory_path', index=3,
number=6, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='target_class_mapping', full_name='DatasetExportConfig.target_class_mapping', index=4,
number=7, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[_DATASETEXPORTCONFIG_SAMPLEMODIFIERCONFIG, _DATASETEXPORTCONFIG_TARGETCLASSMAPPINGENTRY, ],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
_descriptor.OneofDescriptor(
name='convert_config_type', full_name='DatasetExportConfig.convert_config_type',
index=0, containing_type=None, fields=[]),
],
serialized_start=191,
serialized_end=1067,
)
_DATASETEXPORTCONFIG_SAMPLEMODIFIERCONFIG_MINIMUMTARGETCLASSIMBALANCEENTRY.containing_type = _DATASETEXPORTCONFIG_SAMPLEMODIFIERCONFIG
_DATASETEXPORTCONFIG_SAMPLEMODIFIERCONFIG_SOURCETOTARGETCLASSMAPPINGENTRY.containing_type = _DATASETEXPORTCONFIG_SAMPLEMODIFIERCONFIG
_DATASETEXPORTCONFIG_SAMPLEMODIFIERCONFIG.fields_by_name['minimum_target_class_imbalance'].message_type = _DATASETEXPORTCONFIG_SAMPLEMODIFIERCONFIG_MINIMUMTARGETCLASSIMBALANCEENTRY
_DATASETEXPORTCONFIG_SAMPLEMODIFIERCONFIG.fields_by_name['source_to_target_class_mapping'].message_type = _DATASETEXPORTCONFIG_SAMPLEMODIFIERCONFIG_SOURCETOTARGETCLASSMAPPINGENTRY
_DATASETEXPORTCONFIG_SAMPLEMODIFIERCONFIG.containing_type = _DATASETEXPORTCONFIG
_DATASETEXPORTCONFIG_TARGETCLASSMAPPINGENTRY.containing_type = _DATASETEXPORTCONFIG
_DATASETEXPORTCONFIG.fields_by_name['coco_config'].message_type = nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_coco__config__pb2._COCOCONFIG
_DATASETEXPORTCONFIG.fields_by_name['kitti_config'].message_type = nvidia__tao__deploy_dot_cv_dot_detectnet__v2_dot_proto_dot_kitti__config__pb2._KITTICONFIG
_DATASETEXPORTCONFIG.fields_by_name['sample_modifier_config'].message_type = _DATASETEXPORTCONFIG_SAMPLEMODIFIERCONFIG
_DATASETEXPORTCONFIG.fields_by_name['target_class_mapping'].message_type = _DATASETEXPORTCONFIG_TARGETCLASSMAPPINGENTRY
_DATASETEXPORTCONFIG.oneofs_by_name['convert_config_type'].fields.append(
_DATASETEXPORTCONFIG.fields_by_name['coco_config'])
_DATASETEXPORTCONFIG.fields_by_name['coco_config'].containing_oneof = _DATASETEXPORTCONFIG.oneofs_by_name['convert_config_type']
_DATASETEXPORTCONFIG.oneofs_by_name['convert_config_type'].fields.append(
_DATASETEXPORTCONFIG.fields_by_name['kitti_config'])
_DATASETEXPORTCONFIG.fields_by_name['kitti_config'].containing_oneof = _DATASETEXPORTCONFIG.oneofs_by_name['convert_config_type']
DESCRIPTOR.message_types_by_name['DatasetExportConfig'] = _DATASETEXPORTCONFIG
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
DatasetExportConfig = _reflection.GeneratedProtocolMessageType('DatasetExportConfig', (_message.Message,), dict(
SampleModifierConfig = _reflection.GeneratedProtocolMessageType('SampleModifierConfig', (_message.Message,), dict(
MinimumTargetClassImbalanceEntry = _reflection.GeneratedProtocolMessageType('MinimumTargetClassImbalanceEntry', (_message.Message,), dict(
DESCRIPTOR = _DATASETEXPORTCONFIG_SAMPLEMODIFIERCONFIG_MINIMUMTARGETCLASSIMBALANCEENTRY,
__module__ = 'nvidia_tao_deploy.cv.detectnet_v2.proto.dataset_export_config_pb2'
# @@protoc_insertion_point(class_scope:DatasetExportConfig.SampleModifierConfig.MinimumTargetClassImbalanceEntry)
))
,
SourceToTargetClassMappingEntry = _reflection.GeneratedProtocolMessageType('SourceToTargetClassMappingEntry', (_message.Message,), dict(
DESCRIPTOR = _DATASETEXPORTCONFIG_SAMPLEMODIFIERCONFIG_SOURCETOTARGETCLASSMAPPINGENTRY,
__module__ = 'nvidia_tao_deploy.cv.detectnet_v2.proto.dataset_export_config_pb2'
# @@protoc_insertion_point(class_scope:DatasetExportConfig.SampleModifierConfig.SourceToTargetClassMappingEntry)
))
,
DESCRIPTOR = _DATASETEXPORTCONFIG_SAMPLEMODIFIERCONFIG,
__module__ = 'nvidia_tao_deploy.cv.detectnet_v2.proto.dataset_export_config_pb2'
# @@protoc_insertion_point(class_scope:DatasetExportConfig.SampleModifierConfig)
))
,
TargetClassMappingEntry = _reflection.GeneratedProtocolMessageType('TargetClassMappingEntry', (_message.Message,), dict(
DESCRIPTOR = _DATASETEXPORTCONFIG_TARGETCLASSMAPPINGENTRY,
__module__ = 'nvidia_tao_deploy.cv.detectnet_v2.proto.dataset_export_config_pb2'
# @@protoc_insertion_point(class_scope:DatasetExportConfig.TargetClassMappingEntry)
))
,
DESCRIPTOR = _DATASETEXPORTCONFIG,
__module__ = 'nvidia_tao_deploy.cv.detectnet_v2.proto.dataset_export_config_pb2'
# @@protoc_insertion_point(class_scope:DatasetExportConfig)
))
_sym_db.RegisterMessage(DatasetExportConfig)
_sym_db.RegisterMessage(DatasetExportConfig.SampleModifierConfig)
_sym_db.RegisterMessage(DatasetExportConfig.SampleModifierConfig.MinimumTargetClassImbalanceEntry)
_sym_db.RegisterMessage(DatasetExportConfig.SampleModifierConfig.SourceToTargetClassMappingEntry)
_sym_db.RegisterMessage(DatasetExportConfig.TargetClassMappingEntry)
_DATASETEXPORTCONFIG_SAMPLEMODIFIERCONFIG_MINIMUMTARGETCLASSIMBALANCEENTRY._options = None
_DATASETEXPORTCONFIG_SAMPLEMODIFIERCONFIG_SOURCETOTARGETCLASSMAPPINGENTRY._options = None
_DATASETEXPORTCONFIG_TARGETCLASSMAPPINGENTRY._options = None
# @@protoc_insertion_point(module_scope)
| tao_deploy-main | nvidia_tao_deploy/cv/detectnet_v2/proto/dataset_export_config_pb2.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.