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 functions used for mask visualization."""
import cv2
import numpy as np
import math
def get_color_id(num_classes):
"""Function to return a list of color values for each class."""
colors = []
for idx in range(num_classes):
np.random.seed(idx)
colors.append((np.random.randint(0, 255), np.random.randint(0, 255), np.random.randint(0, 255)))
return colors
def overlay_seg_image(inp_img, seg_img, resize_padding, resize_method):
"""The utility function to overlay mask on original image."""
resize_methods_mapping = {'BILINEAR': cv2.INTER_LINEAR, 'AREA': cv2.INTER_AREA,
'BICUBIC': cv2.INTER_CUBIC,
'NEAREST_NEIGHBOR': cv2.INTER_NEAREST}
rm = resize_methods_mapping[resize_method]
orininal_h = inp_img.shape[0]
orininal_w = inp_img.shape[1]
seg_h = seg_img.shape[0]
seg_w = seg_img.shape[1]
if resize_padding:
p_height_top, p_height_bottom, p_width_left, p_width_right = \
resize_with_pad(inp_img, seg_w, seg_h)
act_seg = seg_img[p_height_top:(seg_h - p_height_bottom), p_width_left:(seg_w - p_width_right)]
seg_img = cv2.resize(act_seg, (orininal_w, orininal_h), interpolation=rm)
else:
seg_img = cv2.resize(seg_img, (orininal_w, orininal_h), interpolation=rm)
fused_img = (inp_img / 2 + seg_img / 2).astype('uint8')
return fused_img
def resize_with_pad(image, f_target_width=None, f_target_height=None):
"""Function to determine the padding width in all the directions."""
(im_h, im_w) = image.shape[:2]
ratio = max(im_w / float(f_target_width), im_h / float(f_target_height))
resized_height_float = im_h / ratio
resized_width_float = im_w / ratio
resized_height = math.floor(resized_height_float)
resized_width = math.floor(resized_width_float)
padding_height = (f_target_height - resized_height_float) / 2
padding_width = (f_target_width - resized_width_float) / 2
f_padding_height = math.floor(padding_height)
f_padding_width = math.floor(padding_width)
p_height_top = max(0, f_padding_height)
p_width_left = max(0, f_padding_width)
p_height_bottom = max(0, f_target_height - (resized_height + p_height_top))
p_width_right = max(0, f_target_width - (resized_width + p_width_left))
return p_height_top, p_height_bottom, p_width_left, p_width_right
| tao_deploy-main | nvidia_tao_deploy/cv/unet/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.
"""UNet loader."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import logging
import os
from PIL import Image
from nvidia_tao_deploy.cv.common.constants import VALID_IMAGE_EXTENSIONS
from nvidia_tao_deploy.utils.path_utils import expand_path
import numpy as np
from abc import ABC
logging.basicConfig(format='%(asctime)s [%(levelname)s] %(name)s: %(message)s',
level="DEBUG")
logger = logging.getLogger(__name__)
class UNetLoader(ABC):
"""UNet Dataloader."""
def __init__(self,
shape,
image_data_source,
label_data_source,
num_classes,
batch_size=10,
is_inference=False,
resize_method='bilinear',
preprocess="min_max_-1_1",
model_arch="shufflenet",
resize_padding=False,
input_image_type="color",
dtype=None):
"""Init.
Args:
image_data_source (list): list of image directories.
label_data_source (list): list of label directories.
num_classes (int): number of classes
batch_size (int): size of the batch.
is_inference (bool): If True, no labels will be returned
resize_method (str): Bilinear / Bicubic.
preprocess (str): A way to normalize the image tensor. (Default: min_max_-1_1)
model_arch (str): Model architecture (Default: shufflenet).
resize_padding (bool): Whether to resize the image with padding.
input_image_type (str): color / grayscale.
dtype (str): data type to cast to
"""
self.image_paths, self.label_paths = [], []
self.is_inference = is_inference
self._add_source(image_data_source, label_data_source)
self.image_paths = np.array(self.image_paths)
self.data_inds = np.arange(len(self.image_paths))
self.num_classes = num_classes
self.resize_method = Image.BILINEAR if resize_method.lower() == "bilinear" else Image.BICUBIC
self.preprocess = preprocess
self.model_arch = model_arch
self.resize_padding = resize_padding
self.input_image_type = input_image_type
# Always assume channel first
self.num_channels, self.height, self.width = shape[0], shape[1], shape[2]
if self.num_channels == 1 and self.input_image_type != "grayscale":
raise ValueError("A network with channel size 1 expects grayscale input image type")
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_data_source, label_data_source):
"""Add Image and Mask sources."""
if image_data_source[0].endswith(".txt"):
if self.is_inference:
for imgs in image_data_source:
logger.debug("Reading Imgs : %s", imgs)
# Read image files
with open(imgs, encoding="utf-8") as f:
x_set = f.readlines()
for f_im in x_set:
# Ensuring all image files are present
f_im = f_im.strip()
if not os.path.exists(expand_path(f_im)):
raise FileNotFoundError(f"{f_im} does not exist!")
if f_im.lower().endswith(VALID_IMAGE_EXTENSIONS):
self.image_paths.append(f_im)
else:
for imgs, lbls in zip(image_data_source, label_data_source):
logger.debug("Reading Imgs : %s, Reading Lbls : %s", imgs, lbls)
# Read image files
with open(imgs, encoding="utf-8") as f:
x_set = f.readlines()
# Read label files
with open(lbls, encoding="utf-8") as f:
y_set = f.readlines()
for f_im, f_label in zip(x_set, y_set):
# Ensuring all image files are present
f_im = f_im.strip()
f_label = f_label.strip()
if not os.path.exists(expand_path(f_im)):
raise FileNotFoundError(f"{f_im} does not exist!")
if not os.path.exists(expand_path(f_label)):
raise FileNotFoundError(f"{f_label} does not exist!")
if f_im.lower().endswith(VALID_IMAGE_EXTENSIONS):
self.image_paths.append(f_im)
if f_label.lower().endswith(VALID_IMAGE_EXTENSIONS):
self.label_paths.append(f_label)
else:
self.image_paths = [os.path.join(image_data_source[0], f) for f in os.listdir(image_data_source[0])
if f.lower().endswith(VALID_IMAGE_EXTENSIONS)]
if self.is_inference:
self.label_paths = []
else:
self.label_paths = [os.path.join(label_data_source[0], f) for f in os.listdir(label_data_source[0])
if f.lower().endswith(VALID_IMAGE_EXTENSIONS)]
def __len__(self):
"""Get length of Sequence."""
return self.n_batches
def _load_gt_image(self, image_path):
"""Load GT image from file."""
if self.num_channels == 1: # Set to grayscale only when channel size is 1
img = Image.open(image_path).convert('L')
else:
img = Image.open(image_path).convert('RGB')
return img
def _load_gt_label(self, label_path):
"""Load mask labels."""
mask = Image.open(label_path).convert("L")
return mask
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, 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 (PIL.image): Mask
"""
image = self._load_gt_image(self.image_paths[self.data_inds[idx]])
if self.is_inference:
label = Image.fromarray(np.zeros(image.size)).convert("L") # Random image to label
else:
label = self._load_gt_label(self.label_paths[self.data_inds[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
"""
# resize based on different configs
if self.model_arch in ["vanilla_unet"]:
image = self.resize_image_with_crop_or_pad(image, self.height, self.width)
else:
if self.resize_padding:
image = self.resize_pad(image, self.height, self.width, pad_color=(0, 0, 0))
else:
image = image.resize((self.width, self.height), resample=self.resize_method)
image = np.asarray(image, dtype=self.dtype)
# Labels should be always nearest neighbour, as they are integers.
label = label.resize((self.width, self.height), resample=Image.NEAREST)
label = np.asarray(label, dtype=self.dtype)
# Grayscale can either have num_channels 1 or 3
if self.num_channels == 1:
image = np.expand_dims(image, axis=2)
if self.input_image_type == "grayscale":
label /= 255
image = image / 127.5 - 1
# rgb to bgr
if self.input_image_type != "grayscale":
image = image[..., ::-1]
# TF1: normalize_img_tf
if self.input_image_type != "grayscale":
if self.preprocess == "div_by_255":
# A way to normalize an image tensor by dividing them by 255.
# This assumes images with max pixel value of
# 255. It gives normalized image with pixel values in range of >=0 to <=1.
image /= 255.0
elif self.preprocess == "min_max_0_1":
image /= 255.0
elif self.preprocess == "min_max_-1_1":
image = image / 127.5 - 1
else:
raise NotImplementedError(f"{self.preprocess} is not a defined method.")
# convert to channel first
image = np.transpose(image, (2, 0, 1))
label = label.astype(np.uint8)
return image, label
def resize_image_with_crop_or_pad(self, img, target_height, target_width):
"""tf.image.resize_image_with_crop_or_pad() equivalent in Pillow.
TF1 center crops if desired size is smaller than image size and pad with 0 if larger than image size
Ref: https://github.com/tensorflow/tensorflow/blob/v2.9.1/tensorflow/python/ops/image_ops_impl.py#L1251-L1405
"""
img = self.resize_pad(img, target_height, target_width)
img = self.center_crop(img, target_height, target_width)
return img
def center_crop(self, img, target_height, target_width):
"""Center Crop."""
width, height = img.size # Get dimensions
# process crop width and height for max available dimension
crop_width = target_width if target_width < width else width
crop_height = target_height if target_height < height else height
mid_x, mid_y = int(width / 2), int(height / 2)
cw2, ch2 = int(crop_width / 2), int(crop_height / 2)
left = mid_x - ch2
top = mid_y - ch2
right = mid_x + cw2
bottom = mid_y + cw2
# Crop the center of the image
img = img.crop((left, top, right, bottom))
return img
def resize_pad(self, image, target_height, target_width, 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 / target_width
height_scale = height / target_height
scale = 1.0 / max(width_scale, height_scale)
image = image.resize(
(round(width * scale), round(height * scale)),
resample=Image.BILINEAR)
pad = Image.new("RGB", (target_width, target_height))
pad.paste(pad_color, [0, 0, target_width, target_height])
pad.paste(image)
return pad
| tao_deploy-main | nvidia_tao_deploy/cv/unet/dataloader.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nvidia_tao_deploy/cv/unet/proto/data_class_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/unet/proto/data_class_config.proto',
package='',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\n7nvidia_tao_deploy/cv/unet/proto/data_class_config.proto\"\xa3\x01\n\x0f\x44\x61taClassConfig\x12\x34\n\x0etarget_classes\x18\x01 \x03(\x0b\x32\x1c.DataClassConfig.TargetClass\x1aZ\n\x0bTargetClass\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x14\n\x0c\x63lass_weight\x18\x02 \x01(\x02\x12\x10\n\x08label_id\x18\x03 \x01(\x05\x12\x15\n\rmapping_class\x18\x04 \x01(\tb\x06proto3')
)
_DATACLASSCONFIG_TARGETCLASS = _descriptor.Descriptor(
name='TargetClass',
full_name='DataClassConfig.TargetClass',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='name', full_name='DataClassConfig.TargetClass.name', 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='class_weight', full_name='DataClassConfig.TargetClass.class_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),
_descriptor.FieldDescriptor(
name='label_id', full_name='DataClassConfig.TargetClass.label_id', 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='mapping_class', full_name='DataClassConfig.TargetClass.mapping_class', 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),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=133,
serialized_end=223,
)
_DATACLASSCONFIG = _descriptor.Descriptor(
name='DataClassConfig',
full_name='DataClassConfig',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='target_classes', full_name='DataClassConfig.target_classes', 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=[_DATACLASSCONFIG_TARGETCLASS, ],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=60,
serialized_end=223,
)
_DATACLASSCONFIG_TARGETCLASS.containing_type = _DATACLASSCONFIG
_DATACLASSCONFIG.fields_by_name['target_classes'].message_type = _DATACLASSCONFIG_TARGETCLASS
DESCRIPTOR.message_types_by_name['DataClassConfig'] = _DATACLASSCONFIG
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
DataClassConfig = _reflection.GeneratedProtocolMessageType('DataClassConfig', (_message.Message,), dict(
TargetClass = _reflection.GeneratedProtocolMessageType('TargetClass', (_message.Message,), dict(
DESCRIPTOR = _DATACLASSCONFIG_TARGETCLASS,
__module__ = 'nvidia_tao_deploy.cv.unet.proto.data_class_config_pb2'
# @@protoc_insertion_point(class_scope:DataClassConfig.TargetClass)
))
,
DESCRIPTOR = _DATACLASSCONFIG,
__module__ = 'nvidia_tao_deploy.cv.unet.proto.data_class_config_pb2'
# @@protoc_insertion_point(class_scope:DataClassConfig)
))
_sym_db.RegisterMessage(DataClassConfig)
_sym_db.RegisterMessage(DataClassConfig.TargetClass)
# @@protoc_insertion_point(module_scope)
| tao_deploy-main | nvidia_tao_deploy/cv/unet/proto/data_class_config_pb2.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nvidia_tao_deploy/cv/unet/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.unet.proto import adam_optimizer_config_pb2 as nvidia__tao__deploy_dot_cv_dot_unet_dot_proto_dot_adam__optimizer__config__pb2
DESCRIPTOR = _descriptor.FileDescriptor(
name='nvidia_tao_deploy/cv/unet/proto/optimizer_config.proto',
package='',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\n6nvidia_tao_deploy/cv/unet/proto/optimizer_config.proto\x1a;nvidia_tao_deploy/cv/unet/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_unet_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=119,
serialized_end=187,
)
_OPTIMIZERCONFIG.fields_by_name['adam'].message_type = nvidia__tao__deploy_dot_cv_dot_unet_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.unet.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/unet/proto/optimizer_config_pb2.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nvidia_tao_deploy/cv/unet/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/unet/proto/adam_optimizer_config.proto',
package='',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\n;nvidia_tao_deploy/cv/unet/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=63,
serialized_end=131,
)
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.unet.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/unet/proto/adam_optimizer_config_pb2.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nvidia_tao_deploy/cv/unet/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.unet.proto import optimizer_config_pb2 as nvidia__tao__deploy_dot_cv_dot_unet_dot_proto_dot_optimizer__config__pb2
from nvidia_tao_deploy.cv.unet.proto import regularizer_config_pb2 as nvidia__tao__deploy_dot_cv_dot_unet_dot_proto_dot_regularizer__config__pb2
from nvidia_tao_deploy.cv.unet.proto import visualizer_config_pb2 as nvidia__tao__deploy_dot_cv_dot_unet_dot_proto_dot_visualizer__config__pb2
DESCRIPTOR = _descriptor.FileDescriptor(
name='nvidia_tao_deploy/cv/unet/proto/training_config.proto',
package='',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\n5nvidia_tao_deploy/cv/unet/proto/training_config.proto\x1a\x36nvidia_tao_deploy/cv/unet/proto/optimizer_config.proto\x1a\x38nvidia_tao_deploy/cv/unet/proto/regularizer_config.proto\x1a\x37nvidia_tao_deploy/cv/unet/proto/visualizer_config.proto\"\xd9\x06\n\x0eTrainingConfig\x12\x12\n\nbatch_size\x18\x01 \x01(\r\x12\x12\n\nnum_epochs\x18\x02 \x01(\r\x12\'\n\x0bregularizer\x18\x04 \x01(\x0b\x32\x12.RegularizerConfig\x12#\n\toptimizer\x18\x05 \x01(\x0b\x32\x10.OptimizerConfig\x12\x1b\n\x13\x63heckpoint_interval\x18\x07 \x01(\r\x12\x11\n\tmax_steps\x18\x08 \x01(\r\x12\x0e\n\x06\x65pochs\x18\x13 \x01(\r\x12\x19\n\x11log_summary_steps\x18\t \x01(\r\x12\x0f\n\x07\x61ugment\x18\n \x01(\x08\x12\x0f\n\x07use_xla\x18\x0b \x01(\x08\x12\x14\n\x0cwarmup_steps\x18\x0c \x01(\r\x12\x0f\n\x07use_amp\x18\r \x01(\x08\x12\x15\n\rlearning_rate\x18\x0e \x01(\x02\x12\x14\n\x0cweight_decay\x18\x0f \x01(\x02\x12\x0f\n\x07use_trt\x18\x10 \x01(\x08\x12\x1b\n\x13\x63rossvalidation_idx\x18\x11 \x01(\x08\x12\x0c\n\x04loss\x18\x12 \x01(\t\x12\x17\n\x0fweights_monitor\x18\x17 \x01(\x08\x12\x37\n\x0clr_scheduler\x18\x19 \x01(\x0b\x32!.TrainingConfig.LRSchedulerConfig\x12%\n\nvisualizer\x18\x1b \x01(\x0b\x32\x11.VisualizerConfig\x12\x13\n\x0b\x62uffer_size\x18\x1c \x01(\r\x12\x14\n\x0c\x64\x61ta_options\x18\x1d \x01(\x08\x1a\x37\n\x11\x43osineDecayConfig\x12\r\n\x05\x61lpha\x18\x01 \x01(\x02\x12\x13\n\x0b\x64\x65\x63\x61y_steps\x18\x02 \x01(\x05\x1a\x41\n\x16\x45xponentialDecayConfig\x12\x12\n\ndecay_rate\x18\x01 \x01(\x02\x12\x13\n\x0b\x64\x65\x63\x61y_steps\x18\x02 \x01(\x05\x1a\xa3\x01\n\x11LRSchedulerConfig\x12\x43\n\x11\x65xponential_decay\x18\x01 \x01(\x0b\x32&.TrainingConfig.ExponentialDecayConfigH\x00\x12\x39\n\x0c\x63osine_decay\x18\x02 \x01(\x0b\x32!.TrainingConfig.CosineDecayConfigH\x00\x42\x0e\n\x0clr_schedulerb\x06proto3')
,
dependencies=[nvidia__tao__deploy_dot_cv_dot_unet_dot_proto_dot_optimizer__config__pb2.DESCRIPTOR,nvidia__tao__deploy_dot_cv_dot_unet_dot_proto_dot_regularizer__config__pb2.DESCRIPTOR,nvidia__tao__deploy_dot_cv_dot_unet_dot_proto_dot_visualizer__config__pb2.DESCRIPTOR,])
_TRAININGCONFIG_COSINEDECAYCONFIG = _descriptor.Descriptor(
name='CosineDecayConfig',
full_name='TrainingConfig.CosineDecayConfig',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='alpha', full_name='TrainingConfig.CosineDecayConfig.alpha', 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='decay_steps', full_name='TrainingConfig.CosineDecayConfig.decay_steps', 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),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=798,
serialized_end=853,
)
_TRAININGCONFIG_EXPONENTIALDECAYCONFIG = _descriptor.Descriptor(
name='ExponentialDecayConfig',
full_name='TrainingConfig.ExponentialDecayConfig',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='decay_rate', full_name='TrainingConfig.ExponentialDecayConfig.decay_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='decay_steps', full_name='TrainingConfig.ExponentialDecayConfig.decay_steps', 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),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=855,
serialized_end=920,
)
_TRAININGCONFIG_LRSCHEDULERCONFIG = _descriptor.Descriptor(
name='LRSchedulerConfig',
full_name='TrainingConfig.LRSchedulerConfig',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='exponential_decay', full_name='TrainingConfig.LRSchedulerConfig.exponential_decay', 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='cosine_decay', full_name='TrainingConfig.LRSchedulerConfig.cosine_decay', 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='lr_scheduler', full_name='TrainingConfig.LRSchedulerConfig.lr_scheduler',
index=0, containing_type=None, fields=[]),
],
serialized_start=923,
serialized_end=1086,
)
_TRAININGCONFIG = _descriptor.Descriptor(
name='TrainingConfig',
full_name='TrainingConfig',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='batch_size', full_name='TrainingConfig.batch_size', 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='regularizer', full_name='TrainingConfig.regularizer', index=2,
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=3,
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='checkpoint_interval', full_name='TrainingConfig.checkpoint_interval', index=4,
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='max_steps', full_name='TrainingConfig.max_steps', index=5,
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='epochs', full_name='TrainingConfig.epochs', index=6,
number=19, 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='log_summary_steps', full_name='TrainingConfig.log_summary_steps', index=7,
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='augment', full_name='TrainingConfig.augment', index=8,
number=10, 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='use_xla', full_name='TrainingConfig.use_xla', index=9,
number=11, 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='warmup_steps', full_name='TrainingConfig.warmup_steps', index=10,
number=12, 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='use_amp', full_name='TrainingConfig.use_amp', index=11,
number=13, 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='learning_rate', full_name='TrainingConfig.learning_rate', index=12,
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='weight_decay', full_name='TrainingConfig.weight_decay', index=13,
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='use_trt', full_name='TrainingConfig.use_trt', index=14,
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='crossvalidation_idx', full_name='TrainingConfig.crossvalidation_idx', index=15,
number=17, 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='loss', full_name='TrainingConfig.loss', index=16,
number=18, 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='weights_monitor', full_name='TrainingConfig.weights_monitor', index=17,
number=23, 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='lr_scheduler', full_name='TrainingConfig.lr_scheduler', index=18,
number=25, 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='visualizer', full_name='TrainingConfig.visualizer', index=19,
number=27, 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='buffer_size', full_name='TrainingConfig.buffer_size', index=20,
number=28, 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='data_options', full_name='TrainingConfig.data_options', index=21,
number=29, 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=[_TRAININGCONFIG_COSINEDECAYCONFIG, _TRAININGCONFIG_EXPONENTIALDECAYCONFIG, _TRAININGCONFIG_LRSCHEDULERCONFIG, ],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=229,
serialized_end=1086,
)
_TRAININGCONFIG_COSINEDECAYCONFIG.containing_type = _TRAININGCONFIG
_TRAININGCONFIG_EXPONENTIALDECAYCONFIG.containing_type = _TRAININGCONFIG
_TRAININGCONFIG_LRSCHEDULERCONFIG.fields_by_name['exponential_decay'].message_type = _TRAININGCONFIG_EXPONENTIALDECAYCONFIG
_TRAININGCONFIG_LRSCHEDULERCONFIG.fields_by_name['cosine_decay'].message_type = _TRAININGCONFIG_COSINEDECAYCONFIG
_TRAININGCONFIG_LRSCHEDULERCONFIG.containing_type = _TRAININGCONFIG
_TRAININGCONFIG_LRSCHEDULERCONFIG.oneofs_by_name['lr_scheduler'].fields.append(
_TRAININGCONFIG_LRSCHEDULERCONFIG.fields_by_name['exponential_decay'])
_TRAININGCONFIG_LRSCHEDULERCONFIG.fields_by_name['exponential_decay'].containing_oneof = _TRAININGCONFIG_LRSCHEDULERCONFIG.oneofs_by_name['lr_scheduler']
_TRAININGCONFIG_LRSCHEDULERCONFIG.oneofs_by_name['lr_scheduler'].fields.append(
_TRAININGCONFIG_LRSCHEDULERCONFIG.fields_by_name['cosine_decay'])
_TRAININGCONFIG_LRSCHEDULERCONFIG.fields_by_name['cosine_decay'].containing_oneof = _TRAININGCONFIG_LRSCHEDULERCONFIG.oneofs_by_name['lr_scheduler']
_TRAININGCONFIG.fields_by_name['regularizer'].message_type = nvidia__tao__deploy_dot_cv_dot_unet_dot_proto_dot_regularizer__config__pb2._REGULARIZERCONFIG
_TRAININGCONFIG.fields_by_name['optimizer'].message_type = nvidia__tao__deploy_dot_cv_dot_unet_dot_proto_dot_optimizer__config__pb2._OPTIMIZERCONFIG
_TRAININGCONFIG.fields_by_name['lr_scheduler'].message_type = _TRAININGCONFIG_LRSCHEDULERCONFIG
_TRAININGCONFIG.fields_by_name['visualizer'].message_type = nvidia__tao__deploy_dot_cv_dot_unet_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(
CosineDecayConfig = _reflection.GeneratedProtocolMessageType('CosineDecayConfig', (_message.Message,), dict(
DESCRIPTOR = _TRAININGCONFIG_COSINEDECAYCONFIG,
__module__ = 'nvidia_tao_deploy.cv.unet.proto.training_config_pb2'
# @@protoc_insertion_point(class_scope:TrainingConfig.CosineDecayConfig)
))
,
ExponentialDecayConfig = _reflection.GeneratedProtocolMessageType('ExponentialDecayConfig', (_message.Message,), dict(
DESCRIPTOR = _TRAININGCONFIG_EXPONENTIALDECAYCONFIG,
__module__ = 'nvidia_tao_deploy.cv.unet.proto.training_config_pb2'
# @@protoc_insertion_point(class_scope:TrainingConfig.ExponentialDecayConfig)
))
,
LRSchedulerConfig = _reflection.GeneratedProtocolMessageType('LRSchedulerConfig', (_message.Message,), dict(
DESCRIPTOR = _TRAININGCONFIG_LRSCHEDULERCONFIG,
__module__ = 'nvidia_tao_deploy.cv.unet.proto.training_config_pb2'
# @@protoc_insertion_point(class_scope:TrainingConfig.LRSchedulerConfig)
))
,
DESCRIPTOR = _TRAININGCONFIG,
__module__ = 'nvidia_tao_deploy.cv.unet.proto.training_config_pb2'
# @@protoc_insertion_point(class_scope:TrainingConfig)
))
_sym_db.RegisterMessage(TrainingConfig)
_sym_db.RegisterMessage(TrainingConfig.CosineDecayConfig)
_sym_db.RegisterMessage(TrainingConfig.ExponentialDecayConfig)
_sym_db.RegisterMessage(TrainingConfig.LRSchedulerConfig)
# @@protoc_insertion_point(module_scope)
| tao_deploy-main | nvidia_tao_deploy/cv/unet/proto/training_config_pb2.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nvidia_tao_deploy/cv/unet/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/unet/proto/regularizer_config.proto',
package='',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\n8nvidia_tao_deploy/cv/unet/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=151,
serialized_end=199,
)
_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=61,
serialized_end=199,
)
_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.unet.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/unet/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 UNet Proto."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
| tao_deploy-main | nvidia_tao_deploy/cv/unet/proto/__init__.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nvidia_tao_deploy/cv/unet/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/unet/proto/augmentation_config.proto',
package='',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\n9nvidia_tao_deploy/cv/unet/proto/augmentation_config.proto\"\xdc\x02\n\x12\x41ugmentationConfig\x12\x45\n\x14spatial_augmentation\x18\x02 \x01(\x0b\x32\'.AugmentationConfig.SpatialAugmentation\x12K\n\x17\x62rightness_augmentation\x18\x03 \x01(\x0b\x32*.AugmentationConfig.BrightnessAugmentation\x1a\x88\x01\n\x13SpatialAugmentation\x12\x19\n\x11hflip_probability\x18\x01 \x01(\x02\x12\x19\n\x11vflip_probability\x18\x02 \x01(\x02\x12\x1c\n\x14\x63rop_and_resize_prob\x18\x03 \x01(\x02\x12\x1d\n\x15\x63rop_and_resize_ratio\x18\x04 \x01(\x02\x1a\'\n\x16\x42rightnessAugmentation\x12\r\n\x05\x64\x65lta\x18\x01 \x01(\x02\x62\x06proto3')
)
_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='crop_and_resize_prob', full_name='AugmentationConfig.SpatialAugmentation.crop_and_resize_prob', 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_and_resize_ratio', full_name='AugmentationConfig.SpatialAugmentation.crop_and_resize_ratio', 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=233,
serialized_end=369,
)
_AUGMENTATIONCONFIG_BRIGHTNESSAUGMENTATION = _descriptor.Descriptor(
name='BrightnessAugmentation',
full_name='AugmentationConfig.BrightnessAugmentation',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='delta', full_name='AugmentationConfig.BrightnessAugmentation.delta', 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=371,
serialized_end=410,
)
_AUGMENTATIONCONFIG = _descriptor.Descriptor(
name='AugmentationConfig',
full_name='AugmentationConfig',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='spatial_augmentation', full_name='AugmentationConfig.spatial_augmentation', index=0,
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='brightness_augmentation', full_name='AugmentationConfig.brightness_augmentation', index=1,
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_SPATIALAUGMENTATION, _AUGMENTATIONCONFIG_BRIGHTNESSAUGMENTATION, ],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=62,
serialized_end=410,
)
_AUGMENTATIONCONFIG_SPATIALAUGMENTATION.containing_type = _AUGMENTATIONCONFIG
_AUGMENTATIONCONFIG_BRIGHTNESSAUGMENTATION.containing_type = _AUGMENTATIONCONFIG
_AUGMENTATIONCONFIG.fields_by_name['spatial_augmentation'].message_type = _AUGMENTATIONCONFIG_SPATIALAUGMENTATION
_AUGMENTATIONCONFIG.fields_by_name['brightness_augmentation'].message_type = _AUGMENTATIONCONFIG_BRIGHTNESSAUGMENTATION
DESCRIPTOR.message_types_by_name['AugmentationConfig'] = _AUGMENTATIONCONFIG
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
AugmentationConfig = _reflection.GeneratedProtocolMessageType('AugmentationConfig', (_message.Message,), dict(
SpatialAugmentation = _reflection.GeneratedProtocolMessageType('SpatialAugmentation', (_message.Message,), dict(
DESCRIPTOR = _AUGMENTATIONCONFIG_SPATIALAUGMENTATION,
__module__ = 'nvidia_tao_deploy.cv.unet.proto.augmentation_config_pb2'
# @@protoc_insertion_point(class_scope:AugmentationConfig.SpatialAugmentation)
))
,
BrightnessAugmentation = _reflection.GeneratedProtocolMessageType('BrightnessAugmentation', (_message.Message,), dict(
DESCRIPTOR = _AUGMENTATIONCONFIG_BRIGHTNESSAUGMENTATION,
__module__ = 'nvidia_tao_deploy.cv.unet.proto.augmentation_config_pb2'
# @@protoc_insertion_point(class_scope:AugmentationConfig.BrightnessAugmentation)
))
,
DESCRIPTOR = _AUGMENTATIONCONFIG,
__module__ = 'nvidia_tao_deploy.cv.unet.proto.augmentation_config_pb2'
# @@protoc_insertion_point(class_scope:AugmentationConfig)
))
_sym_db.RegisterMessage(AugmentationConfig)
_sym_db.RegisterMessage(AugmentationConfig.SpatialAugmentation)
_sym_db.RegisterMessage(AugmentationConfig.BrightnessAugmentation)
# @@protoc_insertion_point(module_scope)
| tao_deploy-main | nvidia_tao_deploy/cv/unet/proto/augmentation_config_pb2.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nvidia_tao_deploy/cv/unet/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()
DESCRIPTOR = _descriptor.FileDescriptor(
name='nvidia_tao_deploy/cv/unet/proto/visualizer_config.proto',
package='',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\n7nvidia_tao_deploy/cv/unet/proto/visualizer_config.proto\"f\n\x10VisualizerConfig\x12\x0f\n\x07\x65nabled\x18\x01 \x01(\x08\x12\x1a\n\x12save_summary_steps\x18\x02 \x01(\r\x12%\n\x1dinfrequent_save_summary_steps\x18\x03 \x01(\rb\x06proto3')
)
_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='save_summary_steps', full_name='VisualizerConfig.save_summary_steps', 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='infrequent_save_summary_steps', full_name='VisualizerConfig.infrequent_save_summary_steps', 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),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=59,
serialized_end=161,
)
DESCRIPTOR.message_types_by_name['VisualizerConfig'] = _VISUALIZERCONFIG
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
VisualizerConfig = _reflection.GeneratedProtocolMessageType('VisualizerConfig', (_message.Message,), dict(
DESCRIPTOR = _VISUALIZERCONFIG,
__module__ = 'nvidia_tao_deploy.cv.unet.proto.visualizer_config_pb2'
# @@protoc_insertion_point(class_scope:VisualizerConfig)
))
_sym_db.RegisterMessage(VisualizerConfig)
# @@protoc_insertion_point(module_scope)
| tao_deploy-main | nvidia_tao_deploy/cv/unet/proto/visualizer_config_pb2.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nvidia_tao_deploy/cv/unet/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.unet.proto import dataset_config_pb2 as nvidia__tao__deploy_dot_cv_dot_unet_dot_proto_dot_dataset__config__pb2
from nvidia_tao_deploy.cv.unet.proto import evaluation_config_pb2 as nvidia__tao__deploy_dot_cv_dot_unet_dot_proto_dot_evaluation__config__pb2
from nvidia_tao_deploy.cv.unet.proto import model_config_pb2 as nvidia__tao__deploy_dot_cv_dot_unet_dot_proto_dot_model__config__pb2
from nvidia_tao_deploy.cv.unet.proto import training_config_pb2 as nvidia__tao__deploy_dot_cv_dot_unet_dot_proto_dot_training__config__pb2
from nvidia_tao_deploy.cv.unet.proto import data_class_config_pb2 as nvidia__tao__deploy_dot_cv_dot_unet_dot_proto_dot_data__class__config__pb2
DESCRIPTOR = _descriptor.FileDescriptor(
name='nvidia_tao_deploy/cv/unet/proto/experiment.proto',
package='',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\n0nvidia_tao_deploy/cv/unet/proto/experiment.proto\x1a\x34nvidia_tao_deploy/cv/unet/proto/dataset_config.proto\x1a\x37nvidia_tao_deploy/cv/unet/proto/evaluation_config.proto\x1a\x32nvidia_tao_deploy/cv/unet/proto/model_config.proto\x1a\x35nvidia_tao_deploy/cv/unet/proto/training_config.proto\x1a\x37nvidia_tao_deploy/cv/unet/proto/data_class_config.proto\"\xf2\x01\n\nExperiment\x12\x13\n\x0brandom_seed\x18\x01 \x01(\r\x12\"\n\x0cmodel_config\x18\x05 \x01(\x0b\x32\x0c.ModelConfig\x12&\n\x0e\x64\x61taset_config\x18\x02 \x01(\x0b\x32\x0e.DatasetConfig\x12,\n\x11\x65valuation_config\x18\x06 \x01(\x0b\x32\x11.EvaluationConfig\x12(\n\x0ftraining_config\x18\t \x01(\x0b\x32\x0f.TrainingConfig\x12+\n\x11\x64\x61ta_class_config\x18\n \x01(\x0b\x32\x10.DataClassConfigb\x06proto3')
,
dependencies=[nvidia__tao__deploy_dot_cv_dot_unet_dot_proto_dot_dataset__config__pb2.DESCRIPTOR,nvidia__tao__deploy_dot_cv_dot_unet_dot_proto_dot_evaluation__config__pb2.DESCRIPTOR,nvidia__tao__deploy_dot_cv_dot_unet_dot_proto_dot_model__config__pb2.DESCRIPTOR,nvidia__tao__deploy_dot_cv_dot_unet_dot_proto_dot_training__config__pb2.DESCRIPTOR,nvidia__tao__deploy_dot_cv_dot_unet_dot_proto_dot_data__class__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='model_config', full_name='Experiment.model_config', index=1,
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='dataset_config', full_name='Experiment.dataset_config', index=2,
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='evaluation_config', full_name='Experiment.evaluation_config', index=3,
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='training_config', full_name='Experiment.training_config', index=4,
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='data_class_config', full_name='Experiment.data_class_config', index=5,
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),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=328,
serialized_end=570,
)
_EXPERIMENT.fields_by_name['model_config'].message_type = nvidia__tao__deploy_dot_cv_dot_unet_dot_proto_dot_model__config__pb2._MODELCONFIG
_EXPERIMENT.fields_by_name['dataset_config'].message_type = nvidia__tao__deploy_dot_cv_dot_unet_dot_proto_dot_dataset__config__pb2._DATASETCONFIG
_EXPERIMENT.fields_by_name['evaluation_config'].message_type = nvidia__tao__deploy_dot_cv_dot_unet_dot_proto_dot_evaluation__config__pb2._EVALUATIONCONFIG
_EXPERIMENT.fields_by_name['training_config'].message_type = nvidia__tao__deploy_dot_cv_dot_unet_dot_proto_dot_training__config__pb2._TRAININGCONFIG
_EXPERIMENT.fields_by_name['data_class_config'].message_type = nvidia__tao__deploy_dot_cv_dot_unet_dot_proto_dot_data__class__config__pb2._DATACLASSCONFIG
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.unet.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/unet/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
import numpy as np
from google.protobuf.text_format import Merge as merge_text_proto
from nvidia_tao_deploy.cv.unet.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
def initialize_params(experiment_spec, phase="val"):
"""Initialization of the params object to the estimator runtime config.
Args:
experiment_spec: Loaded Unet Experiment spec.
phase: Data source to load from.
"""
training_config = experiment_spec.training_config
dataset_config = experiment_spec.dataset_config
model_config = experiment_spec.model_config
target_classes = build_target_class_list(dataset_config.data_class_config)
num_classes = get_num_unique_train_ids(target_classes)
if not model_config.activation:
activation = "softmax"
elif model_config.activation == 'sigmoid' and num_classes > 2:
logging.warning("Sigmoid activation can only be used for binary segmentation. \
Defaulting to softmax activation.")
activation = 'softmax'
elif model_config.activation == 'sigmoid' and num_classes == 2:
num_classes = 1
activation = model_config.activation
else:
activation = model_config.activation
if phase == "val":
data_sources = dataset_config.val_data_sources.data_source
if data_sources:
images_list = []
masks_list = []
for data_source in data_sources:
image_path = data_source.image_path if data_source.image_path else None
mask_path = data_source.masks_path if data_source.masks_path else None
images_list.append(image_path)
masks_list.append(mask_path)
else:
images_list = [dataset_config.val_images_path]
masks_list = [dataset_config.val_masks_path]
else:
data_sources = dataset_config.train_data_sources.data_source
if data_sources:
images_list = []
masks_list = []
for data_source in data_sources:
image_path = data_source.image_path if data_source.image_path else None
mask_path = data_source.masks_path if data_source.masks_path else None
images_list.append(image_path)
masks_list.append(mask_path)
else:
images_list = [dataset_config.train_images_path]
masks_list = [dataset_config.train_masks_path]
return {
'batch_size': training_config.batch_size if training_config.batch_size else 1,
'resize_padding': dataset_config.resize_padding if
dataset_config.resize_padding else False,
'resize_method': dataset_config.resize_method.upper() if
dataset_config.resize_method else 'BILINEAR',
'activation': activation,
'augment': dataset_config.augment if dataset_config.augment else False,
'filter_data': dataset_config.filter_data if dataset_config.filter_data else False,
'num_classes': num_classes,
'num_conf_mat_classes': num_classes,
'train_id_name_mapping': get_train_class_mapping(target_classes),
'label_id_train_id_mapping': get_label_train_dic(target_classes),
'preprocess': dataset_config.preprocess if dataset_config.preprocess else "min_max_-1_1",
'input_image_type': dataset_config.input_image_type if dataset_config.input_image_type else "color",
'images_list': images_list,
'masks_list': masks_list,
'arch': model_config.arch if model_config.arch else "resnet",
'enable_qat': model_config.enable_qat if model_config.enable_qat else False,
}
def get_label_train_dic(target_classes):
"""Function to get mapping between class and train ids."""
label_train_dic = {}
for target in target_classes:
label_train_dic[target.label_id] = target.train_id
return label_train_dic
def get_train_class_mapping(target_classes):
"""Utility function that returns the mapping of the train id to orig class."""
train_id_name_mapping = {}
for target_class in target_classes:
if target_class.train_id not in train_id_name_mapping.keys():
train_id_name_mapping[target_class.train_id] = [target_class.name]
else:
train_id_name_mapping[target_class.train_id].append(target_class.name)
return train_id_name_mapping
def get_num_unique_train_ids(target_classes):
"""Return the final number classes used for training.
Arguments:
target_classes: The target classes object that contain the train_id and
label_id.
Returns:
Number of classes to be segmented.
"""
train_ids = [target.train_id for target in target_classes]
train_ids = np.array(train_ids)
train_ids_unique = np.unique(train_ids)
return len(train_ids_unique)
def build_target_class_list(data_class_config):
"""Build a list of TargetClasses based on proto.
Arguments:
cost_function_config: CostFunctionConfig.
Returns:
A list of TargetClass instances.
"""
target_classes = []
orig_class_label_id_map = {}
for target_class in data_class_config.target_classes:
orig_class_label_id_map[target_class.name] = target_class.label_id
class_label_id_calibrated_map = orig_class_label_id_map.copy()
for target_class in data_class_config.target_classes:
label_name = target_class.name
train_name = target_class.mapping_class
class_label_id_calibrated_map[label_name] = orig_class_label_id_map[train_name]
train_ids = sorted(list(set(class_label_id_calibrated_map.values())))
train_id_calibrated_map = {}
for idx, tr_id in enumerate(train_ids):
train_id_calibrated_map[tr_id] = idx
class_train_id_calibrated_map = {}
for label_name, train_id in class_label_id_calibrated_map.items():
class_train_id_calibrated_map[label_name] = train_id_calibrated_map[train_id]
for target_class in data_class_config.target_classes:
target_classes.append(
TargetClass(target_class.name, label_id=target_class.label_id,
train_id=class_train_id_calibrated_map[target_class.name]))
for target_class in target_classes:
logging.debug("Label Id %d: Train Id %d", target_class.label_id, target_class.train_id)
return target_classes
class TargetClass(object):
"""Target class parameters."""
def __init__(self, name, label_id, train_id=None):
"""Constructor.
Args:
name (str): Name of the target class.
label_id (str):original label id of every pixel of the mask
train_id (str): The mapped train id of every pixel in the mask
Raises:
ValueError: On invalid input args.
"""
self.name = name
self.train_id = train_id
self.label_id = label_id
| tao_deploy-main | nvidia_tao_deploy/cv/unet/proto/utils.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nvidia_tao_deploy/cv/unet/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/unet/proto/evaluation_config.proto',
package='',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\n7nvidia_tao_deploy/cv/unet/proto/evaluation_config.proto\"\x97\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\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=687,
serialized_end=723,
)
_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=396,
serialized_end=469,
)
_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=471,
serialized_end=586,
)
_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=588,
serialized_end=685,
)
_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='minimum_detection_ground_truth_overlap', full_name='EvaluationConfig.minimum_detection_ground_truth_overlap', 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='evaluation_box_config', full_name='EvaluationConfig.evaluation_box_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='average_precision_mode', full_name='EvaluationConfig.average_precision_mode', index=4,
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=60,
serialized_end=723,
)
_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.unet.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.unet.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.unet.proto.evaluation_config_pb2'
# @@protoc_insertion_point(class_scope:EvaluationConfig.EvaluationBoxConfigEntry)
))
,
DESCRIPTOR = _EVALUATIONCONFIG,
__module__ = 'nvidia_tao_deploy.cv.unet.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/unet/proto/evaluation_config_pb2.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nvidia_tao_deploy/cv/unet/proto/model_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/unet/proto/model_config.proto',
package='',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\n2nvidia_tao_deploy/cv/unet/proto/model_config.proto\"\xc1\x06\n\x0bModelConfig\x12\x1d\n\x15pretrained_model_file\x18\x01 \x01(\t\x12 \n\x18\x66reeze_pretrained_layers\x18\x02 \x01(\x08\x12\'\n\x1f\x61llow_loaded_model_modification\x18\x03 \x01(\x08\x12\x12\n\nnum_layers\x18\x04 \x01(\x05\x12\x13\n\x0buse_pooling\x18\x05 \x01(\x08\x12\x16\n\x0euse_batch_norm\x18\x06 \x01(\x08\x12\x13\n\x0bremove_head\x18# \x01(\x08\x12\x12\n\nbyom_model\x18\x1f \x01(\t\x12\x14\n\x0c\x64ropout_rate\x18\x07 \x01(\x02\x12\x12\n\nactivation\x18\x15 \x01(\t\x12:\n\x12training_precision\x18\n \x01(\x0b\x32\x1e.ModelConfig.TrainingPrecision\x12\x11\n\tfreeze_bn\x18\x0b \x01(\x08\x12\x15\n\rfreeze_blocks\x18\x0c \x03(\x02\x12\x0c\n\x04\x61rch\x18\r \x01(\t\x12\x12\n\nload_graph\x18\x0e \x01(\x08\x12\x17\n\x0f\x61ll_projections\x18\x0f \x01(\x08\x12\x12\n\nenable_qat\x18\x1d \x01(\x08\x12\x1a\n\x12model_input_height\x18\x10 \x01(\x05\x12\x19\n\x11model_input_width\x18\x11 \x01(\x05\x12\x1c\n\x14model_input_channels\x18\x13 \x01(\x05\x12\x19\n\x11pruned_model_path\x18\x14 \x01(\t\x12\x33\n\x0binitializer\x18\x17 \x01(\x0e\x32\x1e.ModelConfig.KernelInitializer\x1a\x91\x01\n\x11TrainingPrecision\x12\x44\n\x0e\x62\x61\x63kend_floatx\x18\x01 \x01(\x0e\x32,.ModelConfig.TrainingPrecision.BackendFloatx\"6\n\rBackendFloatx\x12\x0b\n\x07INVALID\x10\x00\x12\x0b\n\x07\x46LOAT16\x10\x01\x12\x0b\n\x07\x46LOAT32\x10\x02\"F\n\x11KernelInitializer\x12\x12\n\x0eGLOROT_UNIFORM\x10\x00\x12\r\n\tHE_NORMAL\x10\x01\x12\x0e\n\nHE_UNIFORM\x10\x02\x62\x06proto3')
)
_MODELCONFIG_TRAININGPRECISION_BACKENDFLOATX = _descriptor.EnumDescriptor(
name='BackendFloatx',
full_name='ModelConfig.TrainingPrecision.BackendFloatx',
filename=None,
file=DESCRIPTOR,
values=[
_descriptor.EnumValueDescriptor(
name='INVALID', index=0, number=0,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='FLOAT16', index=1, number=1,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='FLOAT32', index=2, number=2,
serialized_options=None,
type=None),
],
containing_type=None,
serialized_options=None,
serialized_start=762,
serialized_end=816,
)
_sym_db.RegisterEnumDescriptor(_MODELCONFIG_TRAININGPRECISION_BACKENDFLOATX)
_MODELCONFIG_KERNELINITIALIZER = _descriptor.EnumDescriptor(
name='KernelInitializer',
full_name='ModelConfig.KernelInitializer',
filename=None,
file=DESCRIPTOR,
values=[
_descriptor.EnumValueDescriptor(
name='GLOROT_UNIFORM', index=0, number=0,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='HE_NORMAL', index=1, number=1,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='HE_UNIFORM', index=2, number=2,
serialized_options=None,
type=None),
],
containing_type=None,
serialized_options=None,
serialized_start=818,
serialized_end=888,
)
_sym_db.RegisterEnumDescriptor(_MODELCONFIG_KERNELINITIALIZER)
_MODELCONFIG_TRAININGPRECISION = _descriptor.Descriptor(
name='TrainingPrecision',
full_name='ModelConfig.TrainingPrecision',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='backend_floatx', full_name='ModelConfig.TrainingPrecision.backend_floatx', 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),
],
extensions=[
],
nested_types=[],
enum_types=[
_MODELCONFIG_TRAININGPRECISION_BACKENDFLOATX,
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=671,
serialized_end=816,
)
_MODELCONFIG = _descriptor.Descriptor(
name='ModelConfig',
full_name='ModelConfig',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='pretrained_model_file', full_name='ModelConfig.pretrained_model_file', 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='freeze_pretrained_layers', full_name='ModelConfig.freeze_pretrained_layers', 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='allow_loaded_model_modification', full_name='ModelConfig.allow_loaded_model_modification', 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),
_descriptor.FieldDescriptor(
name='num_layers', full_name='ModelConfig.num_layers', 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='use_pooling', full_name='ModelConfig.use_pooling', 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),
_descriptor.FieldDescriptor(
name='use_batch_norm', full_name='ModelConfig.use_batch_norm', 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='remove_head', full_name='ModelConfig.remove_head', index=6,
number=35, 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='byom_model', full_name='ModelConfig.byom_model', index=7,
number=31, 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='dropout_rate', full_name='ModelConfig.dropout_rate', index=8,
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='activation', full_name='ModelConfig.activation', index=9,
number=21, 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='training_precision', full_name='ModelConfig.training_precision', index=10,
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='freeze_bn', full_name='ModelConfig.freeze_bn', index=11,
number=11, 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='freeze_blocks', full_name='ModelConfig.freeze_blocks', index=12,
number=12, type=2, cpp_type=6, 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='arch', full_name='ModelConfig.arch', index=13,
number=13, 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='load_graph', full_name='ModelConfig.load_graph', index=14,
number=14, 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='all_projections', full_name='ModelConfig.all_projections', index=15,
number=15, 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='enable_qat', full_name='ModelConfig.enable_qat', index=16,
number=29, 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='model_input_height', full_name='ModelConfig.model_input_height', index=17,
number=16, 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='model_input_width', full_name='ModelConfig.model_input_width', index=18,
number=17, 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='model_input_channels', full_name='ModelConfig.model_input_channels', index=19,
number=19, 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='pruned_model_path', full_name='ModelConfig.pruned_model_path', index=20,
number=20, 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='initializer', full_name='ModelConfig.initializer', index=21,
number=23, 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=[_MODELCONFIG_TRAININGPRECISION, ],
enum_types=[
_MODELCONFIG_KERNELINITIALIZER,
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=55,
serialized_end=888,
)
_MODELCONFIG_TRAININGPRECISION.fields_by_name['backend_floatx'].enum_type = _MODELCONFIG_TRAININGPRECISION_BACKENDFLOATX
_MODELCONFIG_TRAININGPRECISION.containing_type = _MODELCONFIG
_MODELCONFIG_TRAININGPRECISION_BACKENDFLOATX.containing_type = _MODELCONFIG_TRAININGPRECISION
_MODELCONFIG.fields_by_name['training_precision'].message_type = _MODELCONFIG_TRAININGPRECISION
_MODELCONFIG.fields_by_name['initializer'].enum_type = _MODELCONFIG_KERNELINITIALIZER
_MODELCONFIG_KERNELINITIALIZER.containing_type = _MODELCONFIG
DESCRIPTOR.message_types_by_name['ModelConfig'] = _MODELCONFIG
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
ModelConfig = _reflection.GeneratedProtocolMessageType('ModelConfig', (_message.Message,), dict(
TrainingPrecision = _reflection.GeneratedProtocolMessageType('TrainingPrecision', (_message.Message,), dict(
DESCRIPTOR = _MODELCONFIG_TRAININGPRECISION,
__module__ = 'nvidia_tao_deploy.cv.unet.proto.model_config_pb2'
# @@protoc_insertion_point(class_scope:ModelConfig.TrainingPrecision)
))
,
DESCRIPTOR = _MODELCONFIG,
__module__ = 'nvidia_tao_deploy.cv.unet.proto.model_config_pb2'
# @@protoc_insertion_point(class_scope:ModelConfig)
))
_sym_db.RegisterMessage(ModelConfig)
_sym_db.RegisterMessage(ModelConfig.TrainingPrecision)
# @@protoc_insertion_point(module_scope)
| tao_deploy-main | nvidia_tao_deploy/cv/unet/proto/model_config_pb2.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nvidia_tao_deploy/cv/unet/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()
from nvidia_tao_deploy.cv.unet.proto import data_class_config_pb2 as nvidia__tao__deploy_dot_cv_dot_unet_dot_proto_dot_data__class__config__pb2
from nvidia_tao_deploy.cv.unet.proto import augmentation_config_pb2 as nvidia__tao__deploy_dot_cv_dot_unet_dot_proto_dot_augmentation__config__pb2
DESCRIPTOR = _descriptor.FileDescriptor(
name='nvidia_tao_deploy/cv/unet/proto/dataset_config.proto',
package='',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\n4nvidia_tao_deploy/cv/unet/proto/dataset_config.proto\x1a\x37nvidia_tao_deploy/cv/unet/proto/data_class_config.proto\x1a\x39nvidia_tao_deploy/cv/unet/proto/augmentation_config.proto\"4\n\nDataSource\x12\x12\n\nimage_path\x18\x01 \x01(\t\x12\x12\n\nmasks_path\x18\x02 \x01(\t\"3\n\x0fTrainDataSource\x12 \n\x0b\x64\x61ta_source\x18\x01 \x03(\x0b\x32\x0b.DataSource\"1\n\rValDataSource\x12 \n\x0b\x64\x61ta_source\x18\x01 \x03(\x0b\x32\x0b.DataSource\"2\n\x0eTestDataSource\x12 \n\x0b\x64\x61ta_source\x18\x01 \x03(\x0b\x32\x0b.DataSource\"\xb3\x04\n\rDatasetConfig\x12\x0f\n\x07\x61ugment\x18\x03 \x01(\x08\x12\x13\n\x0b\x66ilter_data\x18\x1f \x01(\x08\x12\x0f\n\x07\x64\x61taset\x18\n \x01(\t\x12\x12\n\ndataloader\x18\x14 \x01(\t\x12\x12\n\npreprocess\x18\x19 \x01(\t\x12\x16\n\x0eresize_padding\x18\x1d \x01(\x08\x12\x15\n\rresize_method\x18\x1e \x01(\t\x12\x18\n\x10input_image_type\x18\x0b \x01(\t\x12,\n\x12train_data_sources\x18\x01 \x01(\x0b\x32\x10.TrainDataSource\x12(\n\x10val_data_sources\x18\x02 \x01(\x0b\x32\x0e.ValDataSource\x12*\n\x11test_data_sources\x18\x04 \x01(\x0b\x32\x0f.TestDataSource\x12+\n\x11\x64\x61ta_class_config\x18\x12 \x01(\x0b\x32\x10.DataClassConfig\x12\x30\n\x13\x61ugmentation_config\x18\x1c \x01(\x0b\x32\x13.AugmentationConfig\x12\x19\n\x11train_images_path\x18\x0c \x01(\t\x12\x18\n\x10train_masks_path\x18\r \x01(\t\x12\x17\n\x0fval_images_path\x18\x0e \x01(\t\x12\x16\n\x0eval_masks_path\x18\x0f \x01(\t\x12\x18\n\x10test_images_path\x18\x10 \x01(\t\x12\x17\n\x0ftest_masks_path\x18\x11 \x01(\tb\x06proto3')
,
dependencies=[nvidia__tao__deploy_dot_cv_dot_unet_dot_proto_dot_data__class__config__pb2.DESCRIPTOR,nvidia__tao__deploy_dot_cv_dot_unet_dot_proto_dot_augmentation__config__pb2.DESCRIPTOR,])
_DATASOURCE = _descriptor.Descriptor(
name='DataSource',
full_name='DataSource',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='image_path', full_name='DataSource.image_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='masks_path', full_name='DataSource.masks_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=172,
serialized_end=224,
)
_TRAINDATASOURCE = _descriptor.Descriptor(
name='TrainDataSource',
full_name='TrainDataSource',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='data_source', full_name='TrainDataSource.data_source', 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=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=226,
serialized_end=277,
)
_VALDATASOURCE = _descriptor.Descriptor(
name='ValDataSource',
full_name='ValDataSource',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='data_source', full_name='ValDataSource.data_source', 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=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=279,
serialized_end=328,
)
_TESTDATASOURCE = _descriptor.Descriptor(
name='TestDataSource',
full_name='TestDataSource',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='data_source', full_name='TestDataSource.data_source', 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=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=330,
serialized_end=380,
)
_DATASETCONFIG = _descriptor.Descriptor(
name='DatasetConfig',
full_name='DatasetConfig',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='augment', full_name='DatasetConfig.augment', index=0,
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),
_descriptor.FieldDescriptor(
name='filter_data', full_name='DatasetConfig.filter_data', index=1,
number=31, 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='dataset', full_name='DatasetConfig.dataset', index=2,
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='dataloader', full_name='DatasetConfig.dataloader', index=3,
number=20, 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='preprocess', full_name='DatasetConfig.preprocess', index=4,
number=25, 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='resize_padding', full_name='DatasetConfig.resize_padding', index=5,
number=29, 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='resize_method', full_name='DatasetConfig.resize_method', index=6,
number=30, 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='input_image_type', full_name='DatasetConfig.input_image_type', index=7,
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='train_data_sources', full_name='DatasetConfig.train_data_sources', index=8,
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='val_data_sources', full_name='DatasetConfig.val_data_sources', index=9,
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='test_data_sources', full_name='DatasetConfig.test_data_sources', index=10,
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='data_class_config', full_name='DatasetConfig.data_class_config', index=11,
number=18, 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='DatasetConfig.augmentation_config', index=12,
number=28, 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='train_images_path', full_name='DatasetConfig.train_images_path', index=13,
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='train_masks_path', full_name='DatasetConfig.train_masks_path', index=14,
number=13, 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_images_path', full_name='DatasetConfig.val_images_path', index=15,
number=14, 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_masks_path', full_name='DatasetConfig.val_masks_path', index=16,
number=15, 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='test_images_path', full_name='DatasetConfig.test_images_path', index=17,
number=16, 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='test_masks_path', full_name='DatasetConfig.test_masks_path', index=18,
number=17, 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=383,
serialized_end=946,
)
_TRAINDATASOURCE.fields_by_name['data_source'].message_type = _DATASOURCE
_VALDATASOURCE.fields_by_name['data_source'].message_type = _DATASOURCE
_TESTDATASOURCE.fields_by_name['data_source'].message_type = _DATASOURCE
_DATASETCONFIG.fields_by_name['train_data_sources'].message_type = _TRAINDATASOURCE
_DATASETCONFIG.fields_by_name['val_data_sources'].message_type = _VALDATASOURCE
_DATASETCONFIG.fields_by_name['test_data_sources'].message_type = _TESTDATASOURCE
_DATASETCONFIG.fields_by_name['data_class_config'].message_type = nvidia__tao__deploy_dot_cv_dot_unet_dot_proto_dot_data__class__config__pb2._DATACLASSCONFIG
_DATASETCONFIG.fields_by_name['augmentation_config'].message_type = nvidia__tao__deploy_dot_cv_dot_unet_dot_proto_dot_augmentation__config__pb2._AUGMENTATIONCONFIG
DESCRIPTOR.message_types_by_name['DataSource'] = _DATASOURCE
DESCRIPTOR.message_types_by_name['TrainDataSource'] = _TRAINDATASOURCE
DESCRIPTOR.message_types_by_name['ValDataSource'] = _VALDATASOURCE
DESCRIPTOR.message_types_by_name['TestDataSource'] = _TESTDATASOURCE
DESCRIPTOR.message_types_by_name['DatasetConfig'] = _DATASETCONFIG
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
DataSource = _reflection.GeneratedProtocolMessageType('DataSource', (_message.Message,), dict(
DESCRIPTOR = _DATASOURCE,
__module__ = 'nvidia_tao_deploy.cv.unet.proto.dataset_config_pb2'
# @@protoc_insertion_point(class_scope:DataSource)
))
_sym_db.RegisterMessage(DataSource)
TrainDataSource = _reflection.GeneratedProtocolMessageType('TrainDataSource', (_message.Message,), dict(
DESCRIPTOR = _TRAINDATASOURCE,
__module__ = 'nvidia_tao_deploy.cv.unet.proto.dataset_config_pb2'
# @@protoc_insertion_point(class_scope:TrainDataSource)
))
_sym_db.RegisterMessage(TrainDataSource)
ValDataSource = _reflection.GeneratedProtocolMessageType('ValDataSource', (_message.Message,), dict(
DESCRIPTOR = _VALDATASOURCE,
__module__ = 'nvidia_tao_deploy.cv.unet.proto.dataset_config_pb2'
# @@protoc_insertion_point(class_scope:ValDataSource)
))
_sym_db.RegisterMessage(ValDataSource)
TestDataSource = _reflection.GeneratedProtocolMessageType('TestDataSource', (_message.Message,), dict(
DESCRIPTOR = _TESTDATASOURCE,
__module__ = 'nvidia_tao_deploy.cv.unet.proto.dataset_config_pb2'
# @@protoc_insertion_point(class_scope:TestDataSource)
))
_sym_db.RegisterMessage(TestDataSource)
DatasetConfig = _reflection.GeneratedProtocolMessageType('DatasetConfig', (_message.Message,), dict(
DESCRIPTOR = _DATASETCONFIG,
__module__ = 'nvidia_tao_deploy.cv.unet.proto.dataset_config_pb2'
# @@protoc_insertion_point(class_scope:DatasetConfig)
))
_sym_db.RegisterMessage(DatasetConfig)
# @@protoc_insertion_point(module_scope)
| tao_deploy-main | nvidia_tao_deploy/cv/unet/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.
"""UNet 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.unet.engine_builder import UNetEngineBuilder
from nvidia_tao_deploy.cv.unet.proto.utils import load_proto, initialize_params
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='unet', mode='gen_trt_engine')
def main(args):
"""UNet TRT convert."""
# decrypt etlt
tmp_onnx_file, file_format = decode_model(args.model_path, args.key)
experiment_spec = load_proto(args.experiment_spec)
params = initialize_params(experiment_spec, phase="train")
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 = UNetEngineBuilder(verbose=args.verbose,
image_list=params['images_list'],
is_qat=params['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 UNet model.')
parser.add_argument(
'-m',
'--model_path',
type=str,
required=False,
help='Path to an UNet .etlt or .onnx model file.'
)
parser.add_argument(
'-e',
'--experiment_spec',
type=str,
required=True,
help='Path to the experiment spec.'
)
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", "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(
'--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=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.")
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/unet/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 UNet scripts module."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
| tao_deploy-main | nvidia_tao_deploy/cv/unet/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 numpy as np
import os
from tqdm.auto import tqdm
import logging
from nvidia_tao_deploy.cv.common.decorators import monitor_status
from nvidia_tao_deploy.cv.unet.dataloader import UNetLoader
from nvidia_tao_deploy.cv.unet.inferencer import UNetInferencer
from nvidia_tao_deploy.cv.unet.proto.utils import load_proto, initialize_params
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='unet', mode='inference')
def main(args):
"""UNet TRT inference."""
if not os.path.exists(args.experiment_spec):
raise FileNotFoundError(f"{args.experiment_spec} does not exist!")
experiment_spec = load_proto(args.experiment_spec)
params = initialize_params(experiment_spec)
# Override params if there are corresponding commandline args
params['batch_size'] = args.batch_size if args.batch_size else params['batch_size']
params['images_list'] = [args.image_dir] if args.image_dir else params['images_list']
params['masks_list'] = params['masks_list']
trt_infer = UNetInferencer(args.model_path, batch_size=args.batch_size, activation=params['activation'])
dl = UNetLoader(
trt_infer._input_shape,
params['images_list'],
[None],
params['num_classes'],
batch_size=args.batch_size,
is_inference=True,
resize_method=params['resize_method'],
preprocess=params['preprocess'],
resize_padding=params['resize_padding'],
model_arch=params['arch'],
input_image_type=params['input_image_type'],
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
os.makedirs(results_dir, 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(args.batch_size) + args.batch_size * i]
trt_infer.visualize_masks(image_paths,
y_pred, results_dir,
num_classes=params['num_classes'],
input_image_type=params['input_image_type'],
resize_padding=params['resize_padding'],
resize_method=params['resize_method'])
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 UNet 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 UNet TensorRT engine.'
)
parser.add_argument(
'-e',
'--experiment_spec',
type=str,
required=True,
help='Path to the experiment spec.'
)
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/unet/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
from tqdm.auto import tqdm
import logging
from nvidia_tao_deploy.cv.common.decorators import monitor_status
from nvidia_tao_deploy.cv.unet.dataloader import UNetLoader
from nvidia_tao_deploy.cv.unet.inferencer import UNetInferencer
from nvidia_tao_deploy.cv.unet.proto.utils import load_proto, initialize_params
from nvidia_tao_deploy.metrics.semantic_segmentation_metric import SemSegMetric
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='unet', mode='evaluation')
def main(args):
"""UNet TRT evaluation."""
if not os.path.exists(args.experiment_spec):
raise FileNotFoundError(f"{args.experiment_spec} does not exist!")
experiment_spec = load_proto(args.experiment_spec)
params = initialize_params(experiment_spec)
# Override params if there are corresponding commandline args
params['batch_size'] = args.batch_size if args.batch_size else params['batch_size']
params['images_list'] = [args.image_dir] if args.image_dir else params['images_list']
params['masks_list'] = [args.label_dir] if args.label_dir else params['masks_list']
trt_infer = UNetInferencer(args.model_path, batch_size=args.batch_size, activation=params['activation'])
dl = UNetLoader(
trt_infer._input_shape,
params['images_list'],
params['masks_list'],
params['num_classes'],
batch_size=args.batch_size,
resize_method=params['resize_method'],
preprocess=params['preprocess'],
resize_padding=params['resize_padding'],
model_arch=params['arch'],
input_image_type=params['input_image_type'],
dtype=trt_infer.inputs[0].host.dtype)
eval_metric = SemSegMetric(num_classes=params['num_classes'],
train_id_name_mapping=params['train_id_name_mapping'],
label_id_train_id_mapping=params['label_id_train_id_mapping'])
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)
metrices = eval_metric.get_evaluation_metrics(gt_labels, pred_labels)
# 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(str(metrices["results_dic"]), 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 UNet 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 UNet TensorRT engine.'
)
parser.add_argument(
'-e',
'--experiment_spec',
type=str,
required=True,
help='Path to the experiment spec.'
)
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/unet/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.unet.scripts
def main():
"""Function to launch the job."""
launch_job(nvidia_tao_deploy.cv.unet.scripts, "unet", sys.argv[1:])
if __name__ == "__main__":
main()
| tao_deploy-main | nvidia_tao_deploy/cv/unet/entrypoint/unet.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 unet."""
| tao_deploy-main | nvidia_tao_deploy/cv/unet/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):
"""Function to process TRT model output."""
keep_k, boxes, scores, cls_id = y_encoded
result = []
for idx, k in enumerate(keep_k.reshape(-1)):
loc = boxes[idx].reshape(-1, 4)[:k]
cid = cls_id[idx].reshape(-1, 1)[:k]
conf = scores[idx].reshape(-1, 1)[:k]
result.append(np.concatenate((cid, conf, loc), axis=-1))
return result
class YOLOv3Inferencer(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.
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)
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/yolo_v3/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.
"""YOLOv3 TensorRT engine builder."""
import logging
import os
import random
from six.moves import xrange
import sys
import onnx
from tqdm import tqdm
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 YOLOv3EngineBuilder(EngineBuilder):
"""Parses an UFF/ONNX graph and builds a TensorRT engine from it."""
def __init__(
self,
batch_size=None,
data_format="channels_first",
**kwargs
):
"""Init.
Args:
data_format (str): data_format.
"""
super().__init__(batch_size=batch_size, **kwargs)
self._data_format = data_format
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]
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)
else:
logger.info("Parsing UFF model")
raise NotImplementedError("UFF for YOLO_v3 is not supported")
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[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 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/yolo_v3/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 YOLOv3."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
| tao_deploy-main | nvidia_tao_deploy/cv/yolo_v3/__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.
"""YOLOv3 loader."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import logging
import cv2
import numpy as np
from nvidia_tao_deploy.dataloader.kitti import KITTILoader
logging.basicConfig(format='%(asctime)s [%(levelname)s] %(name)s: %(message)s',
level="DEBUG")
logger = logging.getLogger(__name__)
def aug_letterbox_resize(img, boxes, num_channels=3, resize_shape=(512, 512)):
"""Apply letter box. resize image to resize_shape, not changing aspect ratio.
Args:
img (PIL.Image): RGB image
boxes (np.array): (N, 4) numpy arrays (xmin, ymin, xmax, ymax) containing bboxes. {x,y}{min,max} is
in [0, 1] range.
resize_shape (int, int): (w, h) of new image
Returns:
aug_img: img after resize
aug_boxes: boxes after resize
"""
img = np.array(img).astype(np.float32)
if num_channels == 1:
new_img = np.zeros((resize_shape[1], resize_shape[0]), dtype=np.float)
else:
new_img = np.zeros((resize_shape[1], resize_shape[0], 3), dtype=np.float)
new_img += np.mean(img, axis=(0, 1), keepdims=True)
h, w = img.shape[0], img.shape[1]
ratio = min(float(resize_shape[1]) / h, float(resize_shape[0]) / w)
new_h = int(round(ratio * h))
new_w = int(round(ratio * w))
l_shift = (resize_shape[0] - new_w) // 2
t_shift = (resize_shape[1] - new_h) // 2
img = cv2.resize(img, (new_w, new_h), cv2.INTER_LINEAR)
new_img[t_shift: t_shift + new_h, l_shift: l_shift + new_w] = img.astype(np.float)
xmin = (boxes[:, 0] * new_w + l_shift) / float(resize_shape[0])
xmax = (boxes[:, 2] * new_w + l_shift) / float(resize_shape[0])
ymin = (boxes[:, 1] * new_h + t_shift) / float(resize_shape[1])
ymax = (boxes[:, 3] * new_h + t_shift) / float(resize_shape[1])
return new_img, np.stack([xmin, ymin, xmax, ymax], axis=-1), \
[l_shift, t_shift, l_shift + new_w, t_shift + new_h]
class YOLOv3KITTILoader(KITTILoader):
"""YOLOv3 Dataloader."""
def __init__(self,
**kwargs):
"""Init."""
super().__init__(**kwargs)
# YOLO series starts label index from 0
classes = sorted({str(x).lower() for x in self.mapping_dict.values()})
self.classes = dict(zip(classes, range(len(classes))))
self.class_mapping = {key.lower(): self.classes[str(val.lower())]
for key, val in self.mapping_dict.items()}
def _filter_invalid_labels(self, labels):
"""filter out invalid labels.
Arg:
labels: size (N, 6), where bboxes is normalized to 0~1.
Returns:
labels: size (M, 6), filtered bboxes with clipped boxes.
"""
labels[:, -4:] = np.clip(labels[:, -4:], 0, 1)
# exclude invalid boxes
difficult_cond = (labels[:, 1] < 0.5) | (not self.exclude_difficult)
if np.any(difficult_cond == 0):
logger.warning(
"Got label marked as difficult(occlusion > 0), "
"please set occlusion field in KITTI label to 0 "
"or set `dataset_config.include_difficult_in_training` to True "
"in spec file, if you want to include it in training."
)
x_cond = labels[:, 4] - labels[:, 2] > 1e-3
y_cond = labels[:, 5] - labels[:, 3] > 1e-3
return labels[difficult_cond & x_cond & y_cond]
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
"""
# change bbox to 0~1
w, h = image.size
label[:, 2] /= w
label[:, 3] /= h
label[:, 4] /= w
label[:, 5] /= h
bboxes = label[:, -4:]
image, bboxes, _ = aug_letterbox_resize(image,
bboxes,
num_channels=self.num_channels,
resize_shape=(self.width, self.height))
label[:, -4:] = bboxes
# Handle Grayscale
if self.num_channels == 1:
image = np.expand_dims(image, axis=2)
# Filter invalid labels
label = self._filter_invalid_labels(label)
return image, label
| tao_deploy-main | nvidia_tao_deploy/cv/yolo_v3/dataloader.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nvidia_tao_deploy/cv/yolo_v3/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.common.proto import cost_scaling_config_pb2 as nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_cost__scaling__config__pb2
from nvidia_tao_deploy.cv.common.proto import learning_rate_config_pb2 as nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_learning__rate__config__pb2
from nvidia_tao_deploy.cv.common.proto import optimizer_config_pb2 as nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_optimizer__config__pb2
from nvidia_tao_deploy.cv.common.proto import regularizer_config_pb2 as nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_regularizer__config__pb2
DESCRIPTOR = _descriptor.FileDescriptor(
name='nvidia_tao_deploy/cv/yolo_v3/proto/training_config.proto',
package='',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\n8nvidia_tao_deploy/cv/yolo_v3/proto/training_config.proto\x1a;nvidia_tao_deploy/cv/common/proto/cost_scaling_config.proto\x1a<nvidia_tao_deploy/cv/common/proto/learning_rate_config.proto\x1a\x38nvidia_tao_deploy/cv/common/proto/optimizer_config.proto\x1a:nvidia_tao_deploy/cv/common/proto/regularizer_config.proto\"\xc4\x03\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\x1b\n\x11resume_model_path\x18\t \x01(\tH\x00\x12\x1d\n\x13pretrain_model_path\x18\n \x01(\tH\x00\x12\x1b\n\x11pruned_model_path\x18\x0b \x01(\tH\x00\x12\x16\n\x0emax_queue_size\x18\x0c \x01(\r\x12\x11\n\tn_workers\x18\r \x01(\r\x12\x1b\n\x13use_multiprocessing\x18\x0e \x01(\x08\x42\x0c\n\nload_modelb\x06proto3')
,
dependencies=[nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_cost__scaling__config__pb2.DESCRIPTOR,nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_learning__rate__config__pb2.DESCRIPTOR,nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_optimizer__config__pb2.DESCRIPTOR,nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_regularizer__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='resume_model_path', full_name='TrainingConfig.resume_model_path', 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='pretrain_model_path', full_name='TrainingConfig.pretrain_model_path', 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='pruned_model_path', full_name='TrainingConfig.pruned_model_path', 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='max_queue_size', full_name='TrainingConfig.max_queue_size', index=11,
number=12, 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='n_workers', full_name='TrainingConfig.n_workers', 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='use_multiprocessing', full_name='TrainingConfig.use_multiprocessing', index=13,
number=14, 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=[
_descriptor.OneofDescriptor(
name='load_model', full_name='TrainingConfig.load_model',
index=0, containing_type=None, fields=[]),
],
serialized_start=302,
serialized_end=754,
)
_TRAININGCONFIG.fields_by_name['learning_rate'].message_type = nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_learning__rate__config__pb2._LEARNINGRATECONFIG
_TRAININGCONFIG.fields_by_name['regularizer'].message_type = nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_regularizer__config__pb2._REGULARIZERCONFIG
_TRAININGCONFIG.fields_by_name['optimizer'].message_type = nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_optimizer__config__pb2._OPTIMIZERCONFIG
_TRAININGCONFIG.fields_by_name['cost_scaling'].message_type = nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_cost__scaling__config__pb2._COSTSCALINGCONFIG
_TRAININGCONFIG.oneofs_by_name['load_model'].fields.append(
_TRAININGCONFIG.fields_by_name['resume_model_path'])
_TRAININGCONFIG.fields_by_name['resume_model_path'].containing_oneof = _TRAININGCONFIG.oneofs_by_name['load_model']
_TRAININGCONFIG.oneofs_by_name['load_model'].fields.append(
_TRAININGCONFIG.fields_by_name['pretrain_model_path'])
_TRAININGCONFIG.fields_by_name['pretrain_model_path'].containing_oneof = _TRAININGCONFIG.oneofs_by_name['load_model']
_TRAININGCONFIG.oneofs_by_name['load_model'].fields.append(
_TRAININGCONFIG.fields_by_name['pruned_model_path'])
_TRAININGCONFIG.fields_by_name['pruned_model_path'].containing_oneof = _TRAININGCONFIG.oneofs_by_name['load_model']
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.yolo_v3.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/yolo_v3/proto/training_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 YOLOv3 Proto."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
| tao_deploy-main | nvidia_tao_deploy/cv/yolo_v3/proto/__init__.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nvidia_tao_deploy/cv/yolo_v3/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/yolo_v3/proto/augmentation_config.proto',
package='',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\n<nvidia_tao_deploy/cv/yolo_v3/proto/augmentation_config.proto\"\xf2\x02\n\x12\x41ugmentationConfig\x12\x0b\n\x03hue\x18\x01 \x01(\x02\x12\x12\n\nsaturation\x18\x02 \x01(\x02\x12\x10\n\x08\x65xposure\x18\x03 \x01(\x02\x12\x15\n\rvertical_flip\x18\x04 \x01(\x02\x12\x17\n\x0fhorizontal_flip\x18\x05 \x01(\x02\x12\x0e\n\x06jitter\x18\x06 \x01(\x02\x12\x14\n\x0coutput_width\x18\x07 \x01(\x05\x12\x15\n\routput_height\x18\x08 \x01(\x05\x12\x16\n\x0eoutput_channel\x18\t \x01(\x05\x12\x14\n\x0coutput_depth\x18\x0c \x01(\r\x12$\n\x1crandomize_input_shape_period\x18\n \x01(\x05\x12\x36\n\nimage_mean\x18\x0b \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=387,
serialized_end=435,
)
_AUGMENTATIONCONFIG = _descriptor.Descriptor(
name='AugmentationConfig',
full_name='AugmentationConfig',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='hue', full_name='AugmentationConfig.hue', 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='saturation', full_name='AugmentationConfig.saturation', 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='exposure', full_name='AugmentationConfig.exposure', 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='vertical_flip', full_name='AugmentationConfig.vertical_flip', 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='horizontal_flip', full_name='AugmentationConfig.horizontal_flip', 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='jitter', full_name='AugmentationConfig.jitter', 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='output_width', full_name='AugmentationConfig.output_width', index=6,
number=7, 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=7,
number=8, 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=8,
number=9, 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_depth', full_name='AugmentationConfig.output_depth', index=9,
number=12, 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='randomize_input_shape_period', full_name='AugmentationConfig.randomize_input_shape_period', index=10,
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='image_mean', full_name='AugmentationConfig.image_mean', index=11,
number=11, 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=65,
serialized_end=435,
)
_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.yolo_v3.proto.augmentation_config_pb2'
# @@protoc_insertion_point(class_scope:AugmentationConfig.ImageMeanEntry)
))
,
DESCRIPTOR = _AUGMENTATIONCONFIG,
__module__ = 'nvidia_tao_deploy.cv.yolo_v3.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/yolo_v3/proto/augmentation_config_pb2.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nvidia_tao_deploy/cv/yolo_v3/proto/yolov3_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/yolo_v3/proto/yolov3_config.proto',
package='',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\n6nvidia_tao_deploy/cv/yolo_v3/proto/yolov3_config.proto\"\xca\x02\n\x0cYOLOv3Config\x12\x18\n\x10\x62ig_anchor_shape\x18\x01 \x01(\t\x12\x18\n\x10mid_anchor_shape\x18\x02 \x01(\t\x12\x1a\n\x12small_anchor_shape\x18\x03 \x01(\t\x12 \n\x18matching_neutral_box_iou\x18\x04 \x01(\x02\x12\x0c\n\x04\x61rch\x18\x05 \x01(\t\x12\x0f\n\x07nlayers\x18\x06 \x01(\r\x12\x18\n\x10\x61rch_conv_blocks\x18\x07 \x01(\r\x12\x17\n\x0floss_loc_weight\x18\x08 \x01(\x02\x12\x1c\n\x14loss_neg_obj_weights\x18\t \x01(\x02\x12\x1a\n\x12loss_class_weights\x18\n \x01(\x02\x12\x15\n\rfreeze_blocks\x18\x0b \x03(\x02\x12\x11\n\tfreeze_bn\x18\x0c \x01(\x08\x12\x12\n\nforce_relu\x18\r \x01(\x08\x62\x06proto3')
)
_YOLOV3CONFIG = _descriptor.Descriptor(
name='YOLOv3Config',
full_name='YOLOv3Config',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='big_anchor_shape', full_name='YOLOv3Config.big_anchor_shape', 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='mid_anchor_shape', full_name='YOLOv3Config.mid_anchor_shape', 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='small_anchor_shape', full_name='YOLOv3Config.small_anchor_shape', 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='matching_neutral_box_iou', full_name='YOLOv3Config.matching_neutral_box_iou', 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='arch', full_name='YOLOv3Config.arch', 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='nlayers', full_name='YOLOv3Config.nlayers', index=5,
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='arch_conv_blocks', full_name='YOLOv3Config.arch_conv_blocks', 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='loss_loc_weight', full_name='YOLOv3Config.loss_loc_weight', 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='loss_neg_obj_weights', full_name='YOLOv3Config.loss_neg_obj_weights', 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='loss_class_weights', full_name='YOLOv3Config.loss_class_weights', index=9,
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='freeze_blocks', full_name='YOLOv3Config.freeze_blocks', index=10,
number=11, type=2, cpp_type=6, 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='YOLOv3Config.freeze_bn', index=11,
number=12, 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='force_relu', full_name='YOLOv3Config.force_relu', index=12,
number=13, 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=59,
serialized_end=389,
)
DESCRIPTOR.message_types_by_name['YOLOv3Config'] = _YOLOV3CONFIG
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
YOLOv3Config = _reflection.GeneratedProtocolMessageType('YOLOv3Config', (_message.Message,), dict(
DESCRIPTOR = _YOLOV3CONFIG,
__module__ = 'nvidia_tao_deploy.cv.yolo_v3.proto.yolov3_config_pb2'
# @@protoc_insertion_point(class_scope:YOLOv3Config)
))
_sym_db.RegisterMessage(YOLOv3Config)
# @@protoc_insertion_point(module_scope)
| tao_deploy-main | nvidia_tao_deploy/cv/yolo_v3/proto/yolov3_config_pb2.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nvidia_tao_deploy/cv/yolo_v3/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.yolo_v3.proto import training_config_pb2 as nvidia__tao__deploy_dot_cv_dot_yolo__v3_dot_proto_dot_training__config__pb2
from nvidia_tao_deploy.cv.common.proto import eval_config_pb2 as nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_eval__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.yolo_v3.proto import yolov3_config_pb2 as nvidia__tao__deploy_dot_cv_dot_yolo__v3_dot_proto_dot_yolov3__config__pb2
from nvidia_tao_deploy.cv.yolo_v3.proto import augmentation_config_pb2 as nvidia__tao__deploy_dot_cv_dot_yolo__v3_dot_proto_dot_augmentation__config__pb2
from nvidia_tao_deploy.cv.yolo_v3.proto import dataset_config_pb2 as nvidia__tao__deploy_dot_cv_dot_yolo__v3_dot_proto_dot_dataset__config__pb2
DESCRIPTOR = _descriptor.FileDescriptor(
name='nvidia_tao_deploy/cv/yolo_v3/proto/experiment.proto',
package='',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\n3nvidia_tao_deploy/cv/yolo_v3/proto/experiment.proto\x1a\x38nvidia_tao_deploy/cv/yolo_v3/proto/training_config.proto\x1a\x33nvidia_tao_deploy/cv/common/proto/eval_config.proto\x1a\x32nvidia_tao_deploy/cv/common/proto/nms_config.proto\x1a\x36nvidia_tao_deploy/cv/yolo_v3/proto/yolov3_config.proto\x1a<nvidia_tao_deploy/cv/yolo_v3/proto/augmentation_config.proto\x1a\x37nvidia_tao_deploy/cv/yolo_v3/proto/dataset_config.proto\"\x93\x02\n\nExperiment\x12,\n\x0e\x64\x61taset_config\x18\x01 \x01(\x0b\x32\x14.YOLOv3DatasetConfig\x12\x30\n\x13\x61ugmentation_config\x18\x02 \x01(\x0b\x32\x13.AugmentationConfig\x12(\n\x0ftraining_config\x18\x03 \x01(\x0b\x32\x0f.TrainingConfig\x12 \n\x0b\x65val_config\x18\x04 \x01(\x0b\x32\x0b.EvalConfig\x12\x1e\n\nnms_config\x18\x05 \x01(\x0b\x32\n.NMSConfig\x12$\n\ryolov3_config\x18\x06 \x01(\x0b\x32\r.YOLOv3Config\x12\x13\n\x0brandom_seed\x18\x07 \x01(\rb\x06proto3')
,
dependencies=[nvidia__tao__deploy_dot_cv_dot_yolo__v3_dot_proto_dot_training__config__pb2.DESCRIPTOR,nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_eval__config__pb2.DESCRIPTOR,nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_nms__config__pb2.DESCRIPTOR,nvidia__tao__deploy_dot_cv_dot_yolo__v3_dot_proto_dot_yolov3__config__pb2.DESCRIPTOR,nvidia__tao__deploy_dot_cv_dot_yolo__v3_dot_proto_dot_augmentation__config__pb2.DESCRIPTOR,nvidia__tao__deploy_dot_cv_dot_yolo__v3_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='augmentation_config', full_name='Experiment.augmentation_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='eval_config', full_name='Experiment.eval_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='nms_config', full_name='Experiment.nms_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='yolov3_config', full_name='Experiment.yolov3_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='random_seed', full_name='Experiment.random_seed', 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),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=394,
serialized_end=669,
)
_EXPERIMENT.fields_by_name['dataset_config'].message_type = nvidia__tao__deploy_dot_cv_dot_yolo__v3_dot_proto_dot_dataset__config__pb2._YOLOV3DATASETCONFIG
_EXPERIMENT.fields_by_name['augmentation_config'].message_type = nvidia__tao__deploy_dot_cv_dot_yolo__v3_dot_proto_dot_augmentation__config__pb2._AUGMENTATIONCONFIG
_EXPERIMENT.fields_by_name['training_config'].message_type = nvidia__tao__deploy_dot_cv_dot_yolo__v3_dot_proto_dot_training__config__pb2._TRAININGCONFIG
_EXPERIMENT.fields_by_name['eval_config'].message_type = nvidia__tao__deploy_dot_cv_dot_common_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['yolov3_config'].message_type = nvidia__tao__deploy_dot_cv_dot_yolo__v3_dot_proto_dot_yolov3__config__pb2._YOLOV3CONFIG
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.yolo_v3.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/yolo_v3/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.yolo_v3.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/yolo_v3/proto/utils.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nvidia_tao_deploy/cv/yolo_v3/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/yolo_v3/proto/dataset_config.proto',
package='',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\n7nvidia_tao_deploy/cv/yolo_v3/proto/dataset_config.proto\"\xa5\x01\n\x10YOLOv3DataSource\x12\x1e\n\x14label_directory_path\x18\x01 \x01(\tH\x00\x12\x18\n\x0etfrecords_path\x18\x02 \x01(\tH\x00\x12\x1c\n\x14image_directory_path\x18\x03 \x01(\t\x12\x11\n\troot_path\x18\x04 \x01(\t\x12\x15\n\rsource_weight\x18\x05 \x01(\x02\x42\x0f\n\rlabels_format\"\xf7\x02\n\x13YOLOv3DatasetConfig\x12\'\n\x0c\x64\x61ta_sources\x18\x01 \x03(\x0b\x32\x11.YOLOv3DataSource\x12J\n\x14target_class_mapping\x18\x02 \x03(\x0b\x32,.YOLOv3DatasetConfig.TargetClassMappingEntry\x12\x17\n\x0fvalidation_fold\x18\x04 \x01(\r\x12\x32\n\x17validation_data_sources\x18\x03 \x03(\x0b\x32\x11.YOLOv3DataSource\x12%\n\x1dinclude_difficult_in_training\x18\x07 \x01(\x08\x12\x0c\n\x04type\x18\x05 \x01(\t\x12\x17\n\x0fimage_extension\x18\x06 \x01(\t\x12\x15\n\ris_monochrome\x18\x08 \x01(\x08\x1a\x39\n\x17TargetClassMappingEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\x62\x06proto3')
)
_YOLOV3DATASOURCE = _descriptor.Descriptor(
name='YOLOv3DataSource',
full_name='YOLOv3DataSource',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='label_directory_path', full_name='YOLOv3DataSource.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='tfrecords_path', full_name='YOLOv3DataSource.tfrecords_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='image_directory_path', full_name='YOLOv3DataSource.image_directory_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),
_descriptor.FieldDescriptor(
name='root_path', full_name='YOLOv3DataSource.root_path', 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='source_weight', full_name='YOLOv3DataSource.source_weight', 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=[
_descriptor.OneofDescriptor(
name='labels_format', full_name='YOLOv3DataSource.labels_format',
index=0, containing_type=None, fields=[]),
],
serialized_start=60,
serialized_end=225,
)
_YOLOV3DATASETCONFIG_TARGETCLASSMAPPINGENTRY = _descriptor.Descriptor(
name='TargetClassMappingEntry',
full_name='YOLOv3DatasetConfig.TargetClassMappingEntry',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='key', full_name='YOLOv3DatasetConfig.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='YOLOv3DatasetConfig.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=546,
serialized_end=603,
)
_YOLOV3DATASETCONFIG = _descriptor.Descriptor(
name='YOLOv3DatasetConfig',
full_name='YOLOv3DatasetConfig',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='data_sources', full_name='YOLOv3DatasetConfig.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='target_class_mapping', full_name='YOLOv3DatasetConfig.target_class_mapping', index=1,
number=2, 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='validation_fold', full_name='YOLOv3DatasetConfig.validation_fold', index=2,
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='validation_data_sources', full_name='YOLOv3DatasetConfig.validation_data_sources', 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='include_difficult_in_training', full_name='YOLOv3DatasetConfig.include_difficult_in_training', index=4,
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),
_descriptor.FieldDescriptor(
name='type', full_name='YOLOv3DatasetConfig.type', index=5,
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='image_extension', full_name='YOLOv3DatasetConfig.image_extension', index=6,
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='is_monochrome', full_name='YOLOv3DatasetConfig.is_monochrome', 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),
],
extensions=[
],
nested_types=[_YOLOV3DATASETCONFIG_TARGETCLASSMAPPINGENTRY, ],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=228,
serialized_end=603,
)
_YOLOV3DATASOURCE.oneofs_by_name['labels_format'].fields.append(
_YOLOV3DATASOURCE.fields_by_name['label_directory_path'])
_YOLOV3DATASOURCE.fields_by_name['label_directory_path'].containing_oneof = _YOLOV3DATASOURCE.oneofs_by_name['labels_format']
_YOLOV3DATASOURCE.oneofs_by_name['labels_format'].fields.append(
_YOLOV3DATASOURCE.fields_by_name['tfrecords_path'])
_YOLOV3DATASOURCE.fields_by_name['tfrecords_path'].containing_oneof = _YOLOV3DATASOURCE.oneofs_by_name['labels_format']
_YOLOV3DATASETCONFIG_TARGETCLASSMAPPINGENTRY.containing_type = _YOLOV3DATASETCONFIG
_YOLOV3DATASETCONFIG.fields_by_name['data_sources'].message_type = _YOLOV3DATASOURCE
_YOLOV3DATASETCONFIG.fields_by_name['target_class_mapping'].message_type = _YOLOV3DATASETCONFIG_TARGETCLASSMAPPINGENTRY
_YOLOV3DATASETCONFIG.fields_by_name['validation_data_sources'].message_type = _YOLOV3DATASOURCE
DESCRIPTOR.message_types_by_name['YOLOv3DataSource'] = _YOLOV3DATASOURCE
DESCRIPTOR.message_types_by_name['YOLOv3DatasetConfig'] = _YOLOV3DATASETCONFIG
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
YOLOv3DataSource = _reflection.GeneratedProtocolMessageType('YOLOv3DataSource', (_message.Message,), dict(
DESCRIPTOR = _YOLOV3DATASOURCE,
__module__ = 'nvidia_tao_deploy.cv.yolo_v3.proto.dataset_config_pb2'
# @@protoc_insertion_point(class_scope:YOLOv3DataSource)
))
_sym_db.RegisterMessage(YOLOv3DataSource)
YOLOv3DatasetConfig = _reflection.GeneratedProtocolMessageType('YOLOv3DatasetConfig', (_message.Message,), dict(
TargetClassMappingEntry = _reflection.GeneratedProtocolMessageType('TargetClassMappingEntry', (_message.Message,), dict(
DESCRIPTOR = _YOLOV3DATASETCONFIG_TARGETCLASSMAPPINGENTRY,
__module__ = 'nvidia_tao_deploy.cv.yolo_v3.proto.dataset_config_pb2'
# @@protoc_insertion_point(class_scope:YOLOv3DatasetConfig.TargetClassMappingEntry)
))
,
DESCRIPTOR = _YOLOV3DATASETCONFIG,
__module__ = 'nvidia_tao_deploy.cv.yolo_v3.proto.dataset_config_pb2'
# @@protoc_insertion_point(class_scope:YOLOv3DatasetConfig)
))
_sym_db.RegisterMessage(YOLOv3DatasetConfig)
_sym_db.RegisterMessage(YOLOv3DatasetConfig.TargetClassMappingEntry)
_YOLOV3DATASETCONFIG_TARGETCLASSMAPPINGENTRY._options = None
# @@protoc_insertion_point(module_scope)
| tao_deploy-main | nvidia_tao_deploy/cv/yolo_v3/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.
"""YOLOv3 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.yolo_v3.proto.utils import load_proto
from nvidia_tao_deploy.cv.yolo_v3.engine_builder import YOLOv3EngineBuilder
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='yolo_v3', mode='gen_trt_engine')
def main(args):
"""YOLOv3 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 = YOLOv3EngineBuilder(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 YOLOv3 model.')
parser.add_argument(
'-m',
'--model_path',
type=str,
required=True,
help='Path to a YOLOv3 .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=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(
'--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=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.")
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/yolo_v3/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 YOLOv3 scripts module."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
| tao_deploy-main | nvidia_tao_deploy/cv/yolo_v3/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
from PIL import Image
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.yolo_v3.dataloader import YOLOv3KITTILoader, aug_letterbox_resize
from nvidia_tao_deploy.cv.yolo_v3.inferencer import YOLOv3Inferencer
from nvidia_tao_deploy.cv.yolo_v3.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='yolo_v3', mode='inference')
def main(args):
"""YOLOv3 TRT inference."""
trt_infer = YOLOv3Inferencer(args.model_path, batch_size=args.batch_size)
c, h, w = trt_infer._input_shape
# Load from proto-based spec file
es = load_proto(args.experiment_spec)
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
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 = YOLOv3KITTILoader(
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,
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(args.batch_size) + args.batch_size * i]
for i in range(len(y_pred)):
y_pred_valid = y_pred[i][y_pred[i][:, 1] > conf_thres]
for i in range(len(y_pred)):
y_pred_valid = y_pred[i][y_pred[i][:, 1] > conf_thres]
target_size = np.array([w, h, w, h])
# Scale back bounding box coordinates
y_pred_valid[:, 2:6] *= target_size[None, :]
# Load image
img = Image.open(image_paths[i])
orig_width, orig_height = img.size
img, _, crop_coord = aug_letterbox_resize(img,
y_pred_valid[:, 2:6],
num_channels=c,
resize_shape=(trt_infer.width, trt_infer.height))
img = Image.fromarray(img.astype('uint8'))
# Store images
bbox_img, label_strings = trt_infer.draw_bbox(img, y_pred_valid, inv_classes, args.threshold)
bbox_img = bbox_img.crop((crop_coord[0], crop_coord[1], crop_coord[2], crop_coord[3]))
bbox_img = bbox_img.resize((orig_width, orig_height))
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 YOLOv3 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 YOLOv3 TensorRT engine.'
)
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.'
)
parser.add_argument(
'-t',
'--threshold',
type=float,
default=0.3,
help='Confidence threshold for inference.')
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/yolo_v3/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.yolo_v3.dataloader import YOLOv3KITTILoader
from nvidia_tao_deploy.cv.yolo_v3.inferencer import YOLOv3Inferencer
from nvidia_tao_deploy.cv.yolo_v3.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='yolo_v3', mode='evaluation')
def main(args):
"""YOLOv3 TRT evaluation."""
trt_infer = YOLOv3Inferencer(args.model_path, batch_size=args.batch_size)
c, h, w = trt_infer._input_shape
# 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
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 = YOLOv3KITTILoader(
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,
dtype=trt_infer.inputs[0].host.dtype)
eval_metric = KITTIMetric(n_classes=len(dl.classes),
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]
pred_labels.append(y_pred_valid)
m_ap, ap = eval_metric(gt_labels, pred_labels, verbose=True)
m_ap = np.mean(ap)
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]] = np.float64(ap[i])
logging.info("{:<14}{:<6}{}".format(class_mapping[i], 'AP', round(ap[i], 5))) # noqa pylint: disable=C0209
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 YOLOv3 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 YOLOv3 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/yolo_v3/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.yolo_v3.scripts
def main():
"""Function to launch the job."""
launch_job(nvidia_tao_deploy.cv.yolo_v3.scripts, "yolo_v3", sys.argv[1:])
if __name__ == "__main__":
main()
| tao_deploy-main | nvidia_tao_deploy/cv/yolo_v3/entrypoint/yolo_v3.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 yolo v3."""
| tao_deploy-main | nvidia_tao_deploy/cv/yolo_v3/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.
"""Set of constants commonly used across cv modules."""
# List of valid image extensions
VALID_IMAGE_EXTENSIONS = (".jpg", ".jpeg", ".png", ".bmp", ".JPEG", ".JPG", ".PNG")
| tao_deploy-main | nvidia_tao_deploy/cv/common/constants.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 Common Modules."""
| tao_deploy-main | nvidia_tao_deploy/cv/common/__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 functions."""
import logging
import os
logger = logging.getLogger(__name__)
def update_results_dir(cfg, task):
"""Update global results_dir based on task.results_dir.
This function should be called at the beginning of a pipeline script.
Args:
cfg (Hydra config): Config object loaded by Hydra
task (str): TAO pipeline name
Return:
Updated cfg
"""
if cfg[task]['results_dir']:
cfg.results_dir = cfg[task]['results_dir']
else:
cfg.results_dir = os.path.join(cfg.results_dir, task)
cfg[task]['results_dir'] = cfg.results_dir
logger.info(f"{task.capitalize()} results will be saved at: %s", cfg.results_dir)
return cfg
| tao_deploy-main | nvidia_tao_deploy/cv/common/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.
"""Common decorators used in TAO Toolkit."""
from functools import wraps
import inspect
import os
from nvidia_tao_deploy.cv.common.logging import status_logging
def monitor_status(name='efficientdet', mode='training'):
"""Status monitoring decorator."""
def inner(runner):
@wraps(runner)
def _func(cfg, **kwargs):
# set up status logger
if not os.path.exists(cfg.results_dir):
os.makedirs(cfg.results_dir)
status_file = os.path.join(cfg.results_dir, "status.json")
status_logging.set_status_logger(
status_logging.StatusLogger(
filename=status_file,
is_master=True,
verbosity=1,
append=True
)
)
s_logger = status_logging.get_status_logger()
try:
s_logger.write(
status_level=status_logging.Status.STARTED,
message=f"Starting {name} {mode}."
)
runner(cfg, **kwargs)
s_logger.write(
status_level=status_logging.Status.SUCCESS,
message=f"{mode.capitalize()} finished successfully."
)
except (KeyboardInterrupt, SystemError):
status_logging.get_status_logger().write(
message=f"{mode.capitalize()} was interrupted",
verbosity_level=status_logging.Verbosity.INFO,
status_level=status_logging.Status.FAILURE
)
except Exception as e:
status_logging.get_status_logger().write(
message=str(e),
status_level=status_logging.Status.FAILURE
)
raise e
return _func
return inner
def override(method):
"""Override decorator.
Decorator implementing method overriding in python
Must also use the @subclass class decorator
"""
method.override = True
return method
def subclass(class_object):
"""Subclass decorator.
Verify all @override methods
Use a class decorator to find the method's class
"""
for name, method in class_object.__dict__.items():
if hasattr(method, "override"):
found = False
for base_class in inspect.getmro(class_object)[1:]:
if name in base_class.__dict__:
if not method.__doc__:
# copy docstring
method.__doc__ = base_class.__dict__[name].__doc__
found = True
break
assert found, f'"{class_object.__name__}.{name}" not found in any base class'
return class_object
| tao_deploy-main | nvidia_tao_deploy/cv/common/decorators.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nvidia_tao_deploy/cv/common/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.common.proto import sgd_optimizer_config_pb2 as nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_sgd__optimizer__config__pb2
from nvidia_tao_deploy.cv.common.proto import adam_optimizer_config_pb2 as nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_adam__optimizer__config__pb2
from nvidia_tao_deploy.cv.common.proto import rmsprop_optimizer_config_pb2 as nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_rmsprop__optimizer__config__pb2
DESCRIPTOR = _descriptor.FileDescriptor(
name='nvidia_tao_deploy/cv/common/proto/optimizer_config.proto',
package='',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\n8nvidia_tao_deploy/cv/common/proto/optimizer_config.proto\x1a<nvidia_tao_deploy/cv/common/proto/sgd_optimizer_config.proto\x1a=nvidia_tao_deploy/cv/common/proto/adam_optimizer_config.proto\x1a@nvidia_tao_deploy/cv/common/proto/rmsprop_optimizer_config.proto\"\x94\x01\n\x0fOptimizerConfig\x12$\n\x04\x61\x64\x61m\x18\x01 \x01(\x0b\x32\x14.AdamOptimizerConfigH\x00\x12\"\n\x03sgd\x18\x02 \x01(\x0b\x32\x13.SGDOptimizerConfigH\x00\x12*\n\x07rmsprop\x18\x03 \x01(\x0b\x32\x17.RMSpropOptimizerConfigH\x00\x42\x0b\n\toptimizerb\x06proto3')
,
dependencies=[nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_sgd__optimizer__config__pb2.DESCRIPTOR,nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_adam__optimizer__config__pb2.DESCRIPTOR,nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_rmsprop__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),
_descriptor.FieldDescriptor(
name='sgd', full_name='OptimizerConfig.sgd', 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='rmsprop', full_name='OptimizerConfig.rmsprop', 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=[],
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=252,
serialized_end=400,
)
_OPTIMIZERCONFIG.fields_by_name['adam'].message_type = nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_adam__optimizer__config__pb2._ADAMOPTIMIZERCONFIG
_OPTIMIZERCONFIG.fields_by_name['sgd'].message_type = nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_sgd__optimizer__config__pb2._SGDOPTIMIZERCONFIG
_OPTIMIZERCONFIG.fields_by_name['rmsprop'].message_type = nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_rmsprop__optimizer__config__pb2._RMSPROPOPTIMIZERCONFIG
_OPTIMIZERCONFIG.oneofs_by_name['optimizer'].fields.append(
_OPTIMIZERCONFIG.fields_by_name['adam'])
_OPTIMIZERCONFIG.fields_by_name['adam'].containing_oneof = _OPTIMIZERCONFIG.oneofs_by_name['optimizer']
_OPTIMIZERCONFIG.oneofs_by_name['optimizer'].fields.append(
_OPTIMIZERCONFIG.fields_by_name['sgd'])
_OPTIMIZERCONFIG.fields_by_name['sgd'].containing_oneof = _OPTIMIZERCONFIG.oneofs_by_name['optimizer']
_OPTIMIZERCONFIG.oneofs_by_name['optimizer'].fields.append(
_OPTIMIZERCONFIG.fields_by_name['rmsprop'])
_OPTIMIZERCONFIG.fields_by_name['rmsprop'].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.common.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/common/proto/optimizer_config_pb2.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nvidia_tao_deploy/cv/common/proto/sgd_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/common/proto/sgd_optimizer_config.proto',
package='',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\n<nvidia_tao_deploy/cv/common/proto/sgd_optimizer_config.proto\"8\n\x12SGDOptimizerConfig\x12\x10\n\x08momentum\x18\x01 \x01(\x02\x12\x10\n\x08nesterov\x18\x02 \x01(\x08\x62\x06proto3')
)
_SGDOPTIMIZERCONFIG = _descriptor.Descriptor(
name='SGDOptimizerConfig',
full_name='SGDOptimizerConfig',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='momentum', full_name='SGDOptimizerConfig.momentum', 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='nesterov', full_name='SGDOptimizerConfig.nesterov', 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),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=64,
serialized_end=120,
)
DESCRIPTOR.message_types_by_name['SGDOptimizerConfig'] = _SGDOPTIMIZERCONFIG
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
SGDOptimizerConfig = _reflection.GeneratedProtocolMessageType('SGDOptimizerConfig', (_message.Message,), dict(
DESCRIPTOR = _SGDOPTIMIZERCONFIG,
__module__ = 'nvidia_tao_deploy.cv.common.proto.sgd_optimizer_config_pb2'
# @@protoc_insertion_point(class_scope:SGDOptimizerConfig)
))
_sym_db.RegisterMessage(SGDOptimizerConfig)
# @@protoc_insertion_point(module_scope)
| tao_deploy-main | nvidia_tao_deploy/cv/common/proto/sgd_optimizer_config_pb2.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nvidia_tao_deploy/cv/common/proto/wandb_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/common/proto/wandb_config.proto',
package='',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\n4nvidia_tao_deploy/cv/common/proto/wandb_config.proto\"\xea\x01\n\x0bWandBConfig\x12\x0f\n\x07\x65nabled\x18\x01 \x01(\x08\x12\x0b\n\x03key\x18\x02 \x01(\t\x12\x0f\n\x07project\x18\x03 \x01(\t\x12\x0e\n\x06\x65ntity\x18\x04 \x01(\t\x12\x0e\n\x06reinit\x18\x05 \x01(\x08\x12\x0c\n\x04name\x18\x06 \x01(\t\x12\x0c\n\x04tags\x18\x07 \x03(\t\x12\x11\n\twandb_dir\x18\x08 \x01(\t\x12\r\n\x05notes\x18\t \x01(\t\x12\x1f\n\x04mode\x18\n \x01(\x0e\x32\x11.WandBConfig.MODE\"-\n\x04MODE\x12\n\n\x06ONLINE\x10\x00\x12\x0b\n\x07OFFLINE\x10\x01\x12\x0c\n\x08\x44ISABLED\x10\x02\x62\x06proto3')
)
_WANDBCONFIG_MODE = _descriptor.EnumDescriptor(
name='MODE',
full_name='WandBConfig.MODE',
filename=None,
file=DESCRIPTOR,
values=[
_descriptor.EnumValueDescriptor(
name='ONLINE', index=0, number=0,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='OFFLINE', index=1, number=1,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='DISABLED', index=2, number=2,
serialized_options=None,
type=None),
],
containing_type=None,
serialized_options=None,
serialized_start=246,
serialized_end=291,
)
_sym_db.RegisterEnumDescriptor(_WANDBCONFIG_MODE)
_WANDBCONFIG = _descriptor.Descriptor(
name='WandBConfig',
full_name='WandBConfig',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='enabled', full_name='WandBConfig.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='key', full_name='WandBConfig.key', 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='project', full_name='WandBConfig.project', 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='entity', full_name='WandBConfig.entity', 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='reinit', full_name='WandBConfig.reinit', 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),
_descriptor.FieldDescriptor(
name='name', full_name='WandBConfig.name', 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='tags', full_name='WandBConfig.tags', index=6,
number=7, 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_dir', full_name='WandBConfig.wandb_dir', index=7,
number=8, 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='notes', full_name='WandBConfig.notes', 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='mode', full_name='WandBConfig.mode', index=9,
number=10, 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=[],
enum_types=[
_WANDBCONFIG_MODE,
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=57,
serialized_end=291,
)
_WANDBCONFIG.fields_by_name['mode'].enum_type = _WANDBCONFIG_MODE
_WANDBCONFIG_MODE.containing_type = _WANDBCONFIG
DESCRIPTOR.message_types_by_name['WandBConfig'] = _WANDBCONFIG
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
WandBConfig = _reflection.GeneratedProtocolMessageType('WandBConfig', (_message.Message,), dict(
DESCRIPTOR = _WANDBCONFIG,
__module__ = 'nvidia_tao_deploy.cv.common.proto.wandb_config_pb2'
# @@protoc_insertion_point(class_scope:WandBConfig)
))
_sym_db.RegisterMessage(WandBConfig)
# @@protoc_insertion_point(module_scope)
| tao_deploy-main | nvidia_tao_deploy/cv/common/proto/wandb_config_pb2.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nvidia_tao_deploy/cv/common/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/common/proto/adam_optimizer_config.proto',
package='',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\n=nvidia_tao_deploy/cv/common/proto/adam_optimizer_config.proto\"U\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\x12\x0f\n\x07\x61msgrad\x18\x04 \x01(\x08\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),
_descriptor.FieldDescriptor(
name='amsgrad', full_name='AdamOptimizerConfig.amsgrad', index=3,
number=4, 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=65,
serialized_end=150,
)
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.common.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/common/proto/adam_optimizer_config_pb2.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nvidia_tao_deploy/cv/common/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.common.proto import cost_scaling_config_pb2 as nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_cost__scaling__config__pb2
from nvidia_tao_deploy.cv.common.proto import learning_rate_config_pb2 as nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_learning__rate__config__pb2
from nvidia_tao_deploy.cv.common.proto import optimizer_config_pb2 as nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_optimizer__config__pb2
from nvidia_tao_deploy.cv.common.proto import regularizer_config_pb2 as nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_regularizer__config__pb2
from nvidia_tao_deploy.cv.common.proto import visualizer_config_pb2 as nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_visualizer__config__pb2
DESCRIPTOR = _descriptor.FileDescriptor(
name='nvidia_tao_deploy/cv/common/proto/training_config.proto',
package='',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\n7nvidia_tao_deploy/cv/common/proto/training_config.proto\x1a;nvidia_tao_deploy/cv/common/proto/cost_scaling_config.proto\x1a<nvidia_tao_deploy/cv/common/proto/learning_rate_config.proto\x1a\x38nvidia_tao_deploy/cv/common/proto/optimizer_config.proto\x1a:nvidia_tao_deploy/cv/common/proto/regularizer_config.proto\x1a\x39nvidia_tao_deploy/cv/common/proto/visualizer_config.proto\"E\n\rEarlyStopping\x12\x0f\n\x07monitor\x18\x01 \x01(\t\x12\x11\n\tmin_delta\x18\x02 \x01(\x02\x12\x10\n\x08patience\x18\x03 \x01(\r\"\xa6\x04\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\x1b\n\x11resume_model_path\x18\t \x01(\tH\x00\x12\x1d\n\x13pretrain_model_path\x18\n \x01(\tH\x00\x12\x1b\n\x11pruned_model_path\x18\x0b \x01(\tH\x00\x12\x16\n\x0emax_queue_size\x18\x0c \x01(\r\x12\x11\n\tn_workers\x18\r \x01(\r\x12\x1b\n\x13use_multiprocessing\x18\x0e \x01(\x08\x12&\n\x0e\x65\x61rly_stopping\x18\x0f \x01(\x0b\x32\x0e.EarlyStopping\x12%\n\nvisualizer\x18\x10 \x01(\x0b\x32\x11.VisualizerConfig\x12\x11\n\tmodel_ema\x18\x11 \x01(\x08\x42\x0c\n\nload_modelb\x06proto3')
,
dependencies=[nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_cost__scaling__config__pb2.DESCRIPTOR,nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_learning__rate__config__pb2.DESCRIPTOR,nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_optimizer__config__pb2.DESCRIPTOR,nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_regularizer__config__pb2.DESCRIPTOR,nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_visualizer__config__pb2.DESCRIPTOR,])
_EARLYSTOPPING = _descriptor.Descriptor(
name='EarlyStopping',
full_name='EarlyStopping',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='monitor', full_name='EarlyStopping.monitor', 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='min_delta', full_name='EarlyStopping.min_delta', 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='patience', full_name='EarlyStopping.patience', 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),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=359,
serialized_end=428,
)
_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='resume_model_path', full_name='TrainingConfig.resume_model_path', 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='pretrain_model_path', full_name='TrainingConfig.pretrain_model_path', 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='pruned_model_path', full_name='TrainingConfig.pruned_model_path', 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='max_queue_size', full_name='TrainingConfig.max_queue_size', index=11,
number=12, 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='n_workers', full_name='TrainingConfig.n_workers', 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='use_multiprocessing', full_name='TrainingConfig.use_multiprocessing', index=13,
number=14, 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='early_stopping', full_name='TrainingConfig.early_stopping', index=14,
number=15, 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='visualizer', full_name='TrainingConfig.visualizer', index=15,
number=16, 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_ema', full_name='TrainingConfig.model_ema', index=16,
number=17, 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=[
_descriptor.OneofDescriptor(
name='load_model', full_name='TrainingConfig.load_model',
index=0, containing_type=None, fields=[]),
],
serialized_start=431,
serialized_end=981,
)
_TRAININGCONFIG.fields_by_name['learning_rate'].message_type = nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_learning__rate__config__pb2._LEARNINGRATECONFIG
_TRAININGCONFIG.fields_by_name['regularizer'].message_type = nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_regularizer__config__pb2._REGULARIZERCONFIG
_TRAININGCONFIG.fields_by_name['optimizer'].message_type = nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_optimizer__config__pb2._OPTIMIZERCONFIG
_TRAININGCONFIG.fields_by_name['cost_scaling'].message_type = nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_cost__scaling__config__pb2._COSTSCALINGCONFIG
_TRAININGCONFIG.fields_by_name['early_stopping'].message_type = _EARLYSTOPPING
_TRAININGCONFIG.fields_by_name['visualizer'].message_type = nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_visualizer__config__pb2._VISUALIZERCONFIG
_TRAININGCONFIG.oneofs_by_name['load_model'].fields.append(
_TRAININGCONFIG.fields_by_name['resume_model_path'])
_TRAININGCONFIG.fields_by_name['resume_model_path'].containing_oneof = _TRAININGCONFIG.oneofs_by_name['load_model']
_TRAININGCONFIG.oneofs_by_name['load_model'].fields.append(
_TRAININGCONFIG.fields_by_name['pretrain_model_path'])
_TRAININGCONFIG.fields_by_name['pretrain_model_path'].containing_oneof = _TRAININGCONFIG.oneofs_by_name['load_model']
_TRAININGCONFIG.oneofs_by_name['load_model'].fields.append(
_TRAININGCONFIG.fields_by_name['pruned_model_path'])
_TRAININGCONFIG.fields_by_name['pruned_model_path'].containing_oneof = _TRAININGCONFIG.oneofs_by_name['load_model']
DESCRIPTOR.message_types_by_name['EarlyStopping'] = _EARLYSTOPPING
DESCRIPTOR.message_types_by_name['TrainingConfig'] = _TRAININGCONFIG
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
EarlyStopping = _reflection.GeneratedProtocolMessageType('EarlyStopping', (_message.Message,), dict(
DESCRIPTOR = _EARLYSTOPPING,
__module__ = 'nvidia_tao_deploy.cv.common.proto.training_config_pb2'
# @@protoc_insertion_point(class_scope:EarlyStopping)
))
_sym_db.RegisterMessage(EarlyStopping)
TrainingConfig = _reflection.GeneratedProtocolMessageType('TrainingConfig', (_message.Message,), dict(
DESCRIPTOR = _TRAININGCONFIG,
__module__ = 'nvidia_tao_deploy.cv.common.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/common/proto/training_config_pb2.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nvidia_tao_deploy/cv/common/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/common/proto/cost_scaling_config.proto',
package='',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\n;nvidia_tao_deploy/cv/common/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=63,
serialized_end=163,
)
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.common.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/common/proto/cost_scaling_config_pb2.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nvidia_tao_deploy/cv/common/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/common/proto/regularizer_config.proto',
package='',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\n:nvidia_tao_deploy/cv/common/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=153,
serialized_end=201,
)
_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=63,
serialized_end=201,
)
_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.common.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/common/proto/regularizer_config_pb2.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nvidia_tao_deploy/cv/common/proto/detection_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/common/proto/detection_sequence_dataset_config.proto',
package='',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\nInvidia_tao_deploy/cv/common/proto/detection_sequence_dataset_config.proto\"s\n\nDataSource\x12\x1c\n\x14label_directory_path\x18\x01 \x01(\t\x12\x1c\n\x14image_directory_path\x18\x02 \x01(\t\x12\x11\n\troot_path\x18\x03 \x01(\t\x12\x16\n\x0etfrecords_path\x18\x04 \x01(\t\"\x96\x02\n\rDatasetConfig\x12!\n\x0c\x64\x61ta_sources\x18\x01 \x03(\x0b\x32\x0b.DataSource\x12\x44\n\x14target_class_mapping\x18\x02 \x03(\x0b\x32&.DatasetConfig.TargetClassMappingEntry\x12,\n\x17validation_data_sources\x18\x03 \x03(\x0b\x32\x0b.DataSource\x12%\n\x1dinclude_difficult_in_training\x18\x04 \x01(\x08\x12\x0c\n\x04type\x18\x05 \x01(\t\x1a\x39\n\x17TargetClassMappingEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\x62\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),
_descriptor.FieldDescriptor(
name='root_path', full_name='DataSource.root_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),
_descriptor.FieldDescriptor(
name='tfrecords_path', full_name='DataSource.tfrecords_path', 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),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=77,
serialized_end=192,
)
_DATASETCONFIG_TARGETCLASSMAPPINGENTRY = _descriptor.Descriptor(
name='TargetClassMappingEntry',
full_name='DatasetConfig.TargetClassMappingEntry',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='key', full_name='DatasetConfig.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='DatasetConfig.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=416,
serialized_end=473,
)
_DATASETCONFIG = _descriptor.Descriptor(
name='DatasetConfig',
full_name='DatasetConfig',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='data_sources', full_name='DatasetConfig.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='target_class_mapping', full_name='DatasetConfig.target_class_mapping', index=1,
number=2, 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='validation_data_sources', full_name='DatasetConfig.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),
_descriptor.FieldDescriptor(
name='include_difficult_in_training', full_name='DatasetConfig.include_difficult_in_training', index=3,
number=4, 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='type', full_name='DatasetConfig.type', 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),
],
extensions=[
],
nested_types=[_DATASETCONFIG_TARGETCLASSMAPPINGENTRY, ],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=195,
serialized_end=473,
)
_DATASETCONFIG_TARGETCLASSMAPPINGENTRY.containing_type = _DATASETCONFIG
_DATASETCONFIG.fields_by_name['data_sources'].message_type = _DATASOURCE
_DATASETCONFIG.fields_by_name['target_class_mapping'].message_type = _DATASETCONFIG_TARGETCLASSMAPPINGENTRY
_DATASETCONFIG.fields_by_name['validation_data_sources'].message_type = _DATASOURCE
DESCRIPTOR.message_types_by_name['DataSource'] = _DATASOURCE
DESCRIPTOR.message_types_by_name['DatasetConfig'] = _DATASETCONFIG
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
DataSource = _reflection.GeneratedProtocolMessageType('DataSource', (_message.Message,), dict(
DESCRIPTOR = _DATASOURCE,
__module__ = 'nvidia_tao_deploy.cv.common.proto.detection_sequence_dataset_config_pb2'
# @@protoc_insertion_point(class_scope:DataSource)
))
_sym_db.RegisterMessage(DataSource)
DatasetConfig = _reflection.GeneratedProtocolMessageType('DatasetConfig', (_message.Message,), dict(
TargetClassMappingEntry = _reflection.GeneratedProtocolMessageType('TargetClassMappingEntry', (_message.Message,), dict(
DESCRIPTOR = _DATASETCONFIG_TARGETCLASSMAPPINGENTRY,
__module__ = 'nvidia_tao_deploy.cv.common.proto.detection_sequence_dataset_config_pb2'
# @@protoc_insertion_point(class_scope:DatasetConfig.TargetClassMappingEntry)
))
,
DESCRIPTOR = _DATASETCONFIG,
__module__ = 'nvidia_tao_deploy.cv.common.proto.detection_sequence_dataset_config_pb2'
# @@protoc_insertion_point(class_scope:DatasetConfig)
))
_sym_db.RegisterMessage(DatasetConfig)
_sym_db.RegisterMessage(DatasetConfig.TargetClassMappingEntry)
_DATASETCONFIG_TARGETCLASSMAPPINGENTRY._options = None
# @@protoc_insertion_point(module_scope)
| tao_deploy-main | nvidia_tao_deploy/cv/common/proto/detection_sequence_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.
"""TAO Deploy Common Proto Modules."""
| tao_deploy-main | nvidia_tao_deploy/cv/common/proto/__init__.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nvidia_tao_deploy/cv/common/proto/clearml_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/common/proto/clearml_config.proto',
package='',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\n6nvidia_tao_deploy/cv/common/proto/clearml_config.proto\"\x8b\x01\n\rClearMLConfig\x12\x0f\n\x07project\x18\x01 \x01(\t\x12\x0c\n\x04task\x18\x02 \x01(\t\x12\x0c\n\x04tags\x18\x03 \x03(\t\x12\x1a\n\x12reuse_last_task_id\x18\x04 \x01(\x08\x12\x1a\n\x12\x63ontinue_last_task\x18\x05 \x01(\x08\x12\x15\n\rdeferred_init\x18\x06 \x01(\x08\x62\x06proto3')
)
_CLEARMLCONFIG = _descriptor.Descriptor(
name='ClearMLConfig',
full_name='ClearMLConfig',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='project', full_name='ClearMLConfig.project', 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='task', full_name='ClearMLConfig.task', 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='tags', full_name='ClearMLConfig.tags', 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='reuse_last_task_id', full_name='ClearMLConfig.reuse_last_task_id', index=3,
number=4, 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='continue_last_task', full_name='ClearMLConfig.continue_last_task', 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),
_descriptor.FieldDescriptor(
name='deferred_init', full_name='ClearMLConfig.deferred_init', 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),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=59,
serialized_end=198,
)
DESCRIPTOR.message_types_by_name['ClearMLConfig'] = _CLEARMLCONFIG
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
ClearMLConfig = _reflection.GeneratedProtocolMessageType('ClearMLConfig', (_message.Message,), dict(
DESCRIPTOR = _CLEARMLCONFIG,
__module__ = 'nvidia_tao_deploy.cv.common.proto.clearml_config_pb2'
# @@protoc_insertion_point(class_scope:ClearMLConfig)
))
_sym_db.RegisterMessage(ClearMLConfig)
# @@protoc_insertion_point(module_scope)
| tao_deploy-main | nvidia_tao_deploy/cv/common/proto/clearml_config_pb2.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nvidia_tao_deploy/cv/common/proto/rmsprop_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/common/proto/rmsprop_optimizer_config.proto',
package='',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\n@nvidia_tao_deploy/cv/common/proto/rmsprop_optimizer_config.proto\"Z\n\x16RMSpropOptimizerConfig\x12\x0b\n\x03rho\x18\x01 \x01(\x02\x12\x10\n\x08momentum\x18\x02 \x01(\x02\x12\x0f\n\x07\x65psilon\x18\x03 \x01(\x02\x12\x10\n\x08\x63\x65ntered\x18\x04 \x01(\x08\x62\x06proto3')
)
_RMSPROPOPTIMIZERCONFIG = _descriptor.Descriptor(
name='RMSpropOptimizerConfig',
full_name='RMSpropOptimizerConfig',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='rho', full_name='RMSpropOptimizerConfig.rho', 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='momentum', full_name='RMSpropOptimizerConfig.momentum', 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='epsilon', full_name='RMSpropOptimizerConfig.epsilon', 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='centered', full_name='RMSpropOptimizerConfig.centered', index=3,
number=4, 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=68,
serialized_end=158,
)
DESCRIPTOR.message_types_by_name['RMSpropOptimizerConfig'] = _RMSPROPOPTIMIZERCONFIG
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
RMSpropOptimizerConfig = _reflection.GeneratedProtocolMessageType('RMSpropOptimizerConfig', (_message.Message,), dict(
DESCRIPTOR = _RMSPROPOPTIMIZERCONFIG,
__module__ = 'nvidia_tao_deploy.cv.common.proto.rmsprop_optimizer_config_pb2'
# @@protoc_insertion_point(class_scope:RMSpropOptimizerConfig)
))
_sym_db.RegisterMessage(RMSpropOptimizerConfig)
# @@protoc_insertion_point(module_scope)
| tao_deploy-main | nvidia_tao_deploy/cv/common/proto/rmsprop_optimizer_config_pb2.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nvidia_tao_deploy/cv/common/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 wandb_config_pb2 as nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_wandb__config__pb2
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
DESCRIPTOR = _descriptor.FileDescriptor(
name='nvidia_tao_deploy/cv/common/proto/visualizer_config.proto',
package='',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\n9nvidia_tao_deploy/cv/common/proto/visualizer_config.proto\x1a\x34nvidia_tao_deploy/cv/common/proto/wandb_config.proto\x1a\x36nvidia_tao_deploy/cv/common/proto/clearml_config.proto\"\x9e\x01\n\x10VisualizerConfig\x12\x0f\n\x07\x65nabled\x18\x01 \x01(\x08\x12\x12\n\nnum_images\x18\x02 \x01(\r\x12\x19\n\x11weight_histograms\x18\x03 \x01(\x08\x12\"\n\x0cwandb_config\x18\x04 \x01(\x0b\x32\x0c.WandBConfig\x12&\n\x0e\x63learml_config\x18\x05 \x01(\x0b\x32\x0e.ClearMLConfigb\x06proto3')
,
dependencies=[nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_wandb__config__pb2.DESCRIPTOR,nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_clearml__config__pb2.DESCRIPTOR,])
_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='weight_histograms', full_name='VisualizerConfig.weight_histograms', 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),
_descriptor.FieldDescriptor(
name='wandb_config', full_name='VisualizerConfig.wandb_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='clearml_config', full_name='VisualizerConfig.clearml_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),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=172,
serialized_end=330,
)
_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(
DESCRIPTOR = _VISUALIZERCONFIG,
__module__ = 'nvidia_tao_deploy.cv.common.proto.visualizer_config_pb2'
# @@protoc_insertion_point(class_scope:VisualizerConfig)
))
_sym_db.RegisterMessage(VisualizerConfig)
# @@protoc_insertion_point(module_scope)
| tao_deploy-main | nvidia_tao_deploy/cv/common/proto/visualizer_config_pb2.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nvidia_tao_deploy/cv/common/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.common.proto import soft_start_annealing_schedule_config_pb2 as nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_soft__start__annealing__schedule__config__pb2
from nvidia_tao_deploy.cv.common.proto import soft_start_cosine_annealing_schedule_config_pb2 as nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_soft__start__cosine__annealing__schedule__config__pb2
DESCRIPTOR = _descriptor.FileDescriptor(
name='nvidia_tao_deploy/cv/common/proto/learning_rate_config.proto',
package='',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\n<nvidia_tao_deploy/cv/common/proto/learning_rate_config.proto\x1aLnvidia_tao_deploy/cv/common/proto/soft_start_annealing_schedule_config.proto\x1aSnvidia_tao_deploy/cv/common/proto/soft_start_cosine_annealing_schedule_config.proto\"\xca\x01\n\x12LearningRateConfig\x12J\n\x1dsoft_start_annealing_schedule\x18\x01 \x01(\x0b\x32!.SoftStartAnnealingScheduleConfigH\x00\x12W\n$soft_start_cosine_annealing_schedule\x18\x02 \x01(\x0b\x32\'.SoftStartCosineAnnealingScheduleConfigH\x00\x42\x0f\n\rlearning_rateb\x06proto3')
,
dependencies=[nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_soft__start__annealing__schedule__config__pb2.DESCRIPTOR,nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_soft__start__cosine__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='soft_start_cosine_annealing_schedule', full_name='LearningRateConfig.soft_start_cosine_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=228,
serialized_end=430,
)
_LEARNINGRATECONFIG.fields_by_name['soft_start_annealing_schedule'].message_type = nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_soft__start__annealing__schedule__config__pb2._SOFTSTARTANNEALINGSCHEDULECONFIG
_LEARNINGRATECONFIG.fields_by_name['soft_start_cosine_annealing_schedule'].message_type = nvidia__tao__deploy_dot_cv_dot_common_dot_proto_dot_soft__start__cosine__annealing__schedule__config__pb2._SOFTSTARTCOSINEANNEALINGSCHEDULECONFIG
_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['soft_start_cosine_annealing_schedule'])
_LEARNINGRATECONFIG.fields_by_name['soft_start_cosine_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.common.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/common/proto/learning_rate_config_pb2.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nvidia_tao_deploy/cv/common/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/common/proto/soft_start_annealing_schedule_config.proto',
package='',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\nLnvidia_tao_deploy/cv/common/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=80,
serialized_end=207,
)
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.common.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/common/proto/soft_start_annealing_schedule_config_pb2.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nvidia_tao_deploy/cv/common/proto/soft_start_cosine_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/common/proto/soft_start_cosine_annealing_schedule_config.proto',
package='',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\nSnvidia_tao_deploy/cv/common/proto/soft_start_cosine_annealing_schedule_config.proto\"r\n&SoftStartCosineAnnealingScheduleConfig\x12\x19\n\x11max_learning_rate\x18\x01 \x01(\x02\x12\x12\n\nsoft_start\x18\x02 \x01(\x02\x12\x19\n\x11min_learning_rate\x18\x03 \x01(\x02\x62\x06proto3')
)
_SOFTSTARTCOSINEANNEALINGSCHEDULECONFIG = _descriptor.Descriptor(
name='SoftStartCosineAnnealingScheduleConfig',
full_name='SoftStartCosineAnnealingScheduleConfig',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='max_learning_rate', full_name='SoftStartCosineAnnealingScheduleConfig.max_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='soft_start', full_name='SoftStartCosineAnnealingScheduleConfig.soft_start', 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='min_learning_rate', full_name='SoftStartCosineAnnealingScheduleConfig.min_learning_rate', 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=87,
serialized_end=201,
)
DESCRIPTOR.message_types_by_name['SoftStartCosineAnnealingScheduleConfig'] = _SOFTSTARTCOSINEANNEALINGSCHEDULECONFIG
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
SoftStartCosineAnnealingScheduleConfig = _reflection.GeneratedProtocolMessageType('SoftStartCosineAnnealingScheduleConfig', (_message.Message,), dict(
DESCRIPTOR = _SOFTSTARTCOSINEANNEALINGSCHEDULECONFIG,
__module__ = 'nvidia_tao_deploy.cv.common.proto.soft_start_cosine_annealing_schedule_config_pb2'
# @@protoc_insertion_point(class_scope:SoftStartCosineAnnealingScheduleConfig)
))
_sym_db.RegisterMessage(SoftStartCosineAnnealingScheduleConfig)
# @@protoc_insertion_point(module_scope)
| tao_deploy-main | nvidia_tao_deploy/cv/common/proto/soft_start_cosine_annealing_schedule_config_pb2.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nvidia_tao_deploy/cv/common/proto/nms_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/common/proto/nms_config.proto',
package='',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\n2nvidia_tao_deploy/cv/common/proto/nms_config.proto\"\x8e\x01\n\tNMSConfig\x12\x1c\n\x14\x63onfidence_threshold\x18\x01 \x01(\x02\x12 \n\x18\x63lustering_iou_threshold\x18\x02 \x01(\x02\x12\r\n\x05top_k\x18\x03 \x01(\r\x12\x1c\n\x14infer_nms_score_bits\x18\x04 \x01(\r\x12\x14\n\x0c\x66orce_on_cpu\x18\x05 \x01(\x08\x62\x06proto3')
)
_NMSCONFIG = _descriptor.Descriptor(
name='NMSConfig',
full_name='NMSConfig',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='confidence_threshold', full_name='NMSConfig.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='clustering_iou_threshold', full_name='NMSConfig.clustering_iou_threshold', 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='top_k', full_name='NMSConfig.top_k', 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='infer_nms_score_bits', full_name='NMSConfig.infer_nms_score_bits', 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='force_on_cpu', full_name='NMSConfig.force_on_cpu', 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=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=55,
serialized_end=197,
)
DESCRIPTOR.message_types_by_name['NMSConfig'] = _NMSCONFIG
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
NMSConfig = _reflection.GeneratedProtocolMessageType('NMSConfig', (_message.Message,), dict(
DESCRIPTOR = _NMSCONFIG,
__module__ = 'nvidia_tao_deploy.cv.common.proto.nms_config_pb2'
# @@protoc_insertion_point(class_scope:NMSConfig)
))
_sym_db.RegisterMessage(NMSConfig)
# @@protoc_insertion_point(module_scope)
| tao_deploy-main | nvidia_tao_deploy/cv/common/proto/nms_config_pb2.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nvidia_tao_deploy/cv/common/proto/class_weighting_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/common/proto/class_weighting_config.proto',
package='',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\n>nvidia_tao_deploy/cv/common/proto/class_weighting_config.proto\"\xa6\x01\n\x14\x43lassWeightingConfig\x12\x42\n\x0f\x63lass_weighting\x18\x01 \x03(\x0b\x32).ClassWeightingConfig.ClassWeightingEntry\x12\x13\n\x0b\x65nable_auto\x18\x02 \x01(\x08\x1a\x35\n\x13\x43lassWeightingEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\x02:\x02\x38\x01\x62\x06proto3')
)
_CLASSWEIGHTINGCONFIG_CLASSWEIGHTINGENTRY = _descriptor.Descriptor(
name='ClassWeightingEntry',
full_name='ClassWeightingConfig.ClassWeightingEntry',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='key', full_name='ClassWeightingConfig.ClassWeightingEntry.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='ClassWeightingConfig.ClassWeightingEntry.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=180,
serialized_end=233,
)
_CLASSWEIGHTINGCONFIG = _descriptor.Descriptor(
name='ClassWeightingConfig',
full_name='ClassWeightingConfig',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='class_weighting', full_name='ClassWeightingConfig.class_weighting', 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='enable_auto', full_name='ClassWeightingConfig.enable_auto', 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),
],
extensions=[
],
nested_types=[_CLASSWEIGHTINGCONFIG_CLASSWEIGHTINGENTRY, ],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=67,
serialized_end=233,
)
_CLASSWEIGHTINGCONFIG_CLASSWEIGHTINGENTRY.containing_type = _CLASSWEIGHTINGCONFIG
_CLASSWEIGHTINGCONFIG.fields_by_name['class_weighting'].message_type = _CLASSWEIGHTINGCONFIG_CLASSWEIGHTINGENTRY
DESCRIPTOR.message_types_by_name['ClassWeightingConfig'] = _CLASSWEIGHTINGCONFIG
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
ClassWeightingConfig = _reflection.GeneratedProtocolMessageType('ClassWeightingConfig', (_message.Message,), dict(
ClassWeightingEntry = _reflection.GeneratedProtocolMessageType('ClassWeightingEntry', (_message.Message,), dict(
DESCRIPTOR = _CLASSWEIGHTINGCONFIG_CLASSWEIGHTINGENTRY,
__module__ = 'nvidia_tao_deploy.cv.common.proto.class_weighting_config_pb2'
# @@protoc_insertion_point(class_scope:ClassWeightingConfig.ClassWeightingEntry)
))
,
DESCRIPTOR = _CLASSWEIGHTINGCONFIG,
__module__ = 'nvidia_tao_deploy.cv.common.proto.class_weighting_config_pb2'
# @@protoc_insertion_point(class_scope:ClassWeightingConfig)
))
_sym_db.RegisterMessage(ClassWeightingConfig)
_sym_db.RegisterMessage(ClassWeightingConfig.ClassWeightingEntry)
_CLASSWEIGHTINGCONFIG_CLASSWEIGHTINGENTRY._options = None
# @@protoc_insertion_point(module_scope)
| tao_deploy-main | nvidia_tao_deploy/cv/common/proto/class_weighting_config_pb2.py |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nvidia_tao_deploy/cv/common/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/common/proto/eval_config.proto',
package='',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\n3nvidia_tao_deploy/cv/common/proto/eval_config.proto\"\xb7\x01\n\nEvalConfig\x12\x33\n\x16\x61verage_precision_mode\x18\x01 \x01(\x0e\x32\x13.EvalConfig.AP_MODE\x12\x12\n\nbatch_size\x18\x02 \x01(\r\x12\x1e\n\x16matching_iou_threshold\x18\x03 \x01(\x02\x12\x1a\n\x12visualize_pr_curve\x18\x04 \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=203,
serialized_end=239,
)
_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='average_precision_mode', full_name='EvalConfig.average_precision_mode', 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='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),
_descriptor.FieldDescriptor(
name='matching_iou_threshold', full_name='EvalConfig.matching_iou_threshold', 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='visualize_pr_curve', full_name='EvalConfig.visualize_pr_curve', index=3,
number=4, 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=56,
serialized_end=239,
)
_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.common.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/common/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.
"""Default config file"""
from typing import List, Optional
from dataclasses import dataclass, field
@dataclass
class WandBConfig:
"""Configuration element wandb client."""
project: str = "TAO Toolkit"
entity: Optional[str] = None
tags: List[str] = field(default_factory=lambda: [])
reinit: bool = False
sync_tensorboard: bool = True
save_code: bool = False
name: str = None
@dataclass
class ClearMLConfig:
"""Configration element for clearml client."""
project: str = "TAO Toolkit"
task: str = "train"
deferred_init: bool = False
reuse_last_task_id: bool = False
continue_last_task: bool = False
tags: List[str] = field(default_factory=lambda: [])
| tao_deploy-main | nvidia_tao_deploy/cv/common/config/mlops.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 Common Hydra Modules."""
| tao_deploy-main | nvidia_tao_deploy/cv/common/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.
"""TAO Deploy (TF1) command line wrapper to invoke CLI scripts."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import importlib
import logging
import os
import pkgutil
import shlex
import subprocess
import sys
from time import time
import pycuda.driver as cuda
from nvidia_tao_deploy.cv.common.telemetry.nvml_utils import get_device_details
from nvidia_tao_deploy.cv.common.telemetry.telemetry import send_telemetry_data
RELEASE = True
logger = logging.getLogger(__name__)
def get_modules(package):
"""Function to get module supported tasks.
This function lists out the modules in the iva.X.scripts package
where the module subtasks are listed, and walks through it to generate a dictionary
of tasks, parser_function and path to the executable.
Args:
No explicit args.
Returns:
modules (dict): Dictionary of modules.
"""
modules = {}
module_path = package.__path__
for _, task, _ in pkgutil.walk_packages(module_path):
module_name = package.__name__ + '.' + task
if hasattr(importlib.import_module(module_name), "build_command_line_parser"):
build_parser = getattr(importlib.import_module(module_name),
"build_command_line_parser")
else:
build_parser = None
module_details = {
"module_name": module_name,
"build_parser": build_parser,
"runner_path": os.path.abspath(
importlib.import_module(module_name).__file__
)
}
modules[task] = module_details
return modules
def build_command_line_parser(package_name, modules=None):
"""Simple function to build command line parsers.
This function scans the dictionary of modules determined by the
get_modules routine and builds a chained parser.
Args:
modules (dict): Dictionary of modules as returned by the get_modules function.
Returns:
parser (argparse.ArgumentParser): An ArgumentParser class with all the
subparser instantiated for chained parsing.
"""
parser = argparse.ArgumentParser(
package_name,
add_help=True,
description="Transfer Learning Toolkit"
)
parser.add_argument(
'--gpu_index',
type=int,
default=0,
help="The index of the GPU to be used.",
)
parser.add_argument(
'--log_file',
type=str,
default=None,
help="Path to the output log file.",
required=False,
)
# module subparser for the respective tasks.
module_subparsers = parser.add_subparsers(title="tasks")
for task, details in modules.items():
subparser = module_subparsers.add_parser(
task,
parents=[parser],
add_help=False)
subparser = details['build_parser'](subparser)
return parser
def format_command_line_args(args):
"""Format command line args from command line.
Args:
args (dict): Dictionary of parsed command line arguments.
Returns:
formatted_string (str): Formatted command line string.
"""
assert isinstance(args, dict), (
"The command line args should be formatted to a dictionary."
)
formatted_string = ""
for arg, value in args.items():
if arg in ["gpu_index", "log_file"]:
continue
# Fix arguments that defaults to None, so that they will
# not be converted to string "None". Simply drop args
# that have value None.
# For example, export output_file arg and engine_file arg
# same for "" for cal_image_dir in export.
if value in [None, ""]:
continue
if isinstance(value, bool):
if value:
formatted_string += f"--{arg} "
elif isinstance(value, list):
formatted_string += f"--{arg} {' '.join(value)} "
else:
formatted_string += f"--{arg} {value} "
return formatted_string
def check_valid_gpus(gpu_id):
"""Check if IDs is valid.
This function scans the machine using the nvidia-smi routine to find the
number of GPU's and matches the id's accordingly.
Once validated, it finally also sets the CUDA_VISIBLE_DEVICES env variable.
Args:
gpu_id (int): GPU index used by the user.
Returns:
No explicit returns
"""
cuda.init()
num_gpus_available = cuda.Device.count()
assert gpu_id >= 0, (
"GPU id cannot be negative."
)
assert gpu_id < num_gpus_available, (
"Checking for valid GPU ids and num_gpus."
)
os.environ['CUDA_VISIBLE_DEVICES'] = f"{gpu_id}"
def set_gpu_info_single_node(gpu_id):
"""Set gpu environment variable for single node."""
check_valid_gpus(gpu_id)
env_variable = ""
visible_devices = os.getenv("CUDA_VISIBLE_DEVICES", None)
if visible_devices is not None:
env_variable = f" CUDA_VISIBLE_DEVICES={visible_devices}"
return env_variable
def launch_job(package, package_name, cl_args=None):
"""Wrap CLI builders.
This function should be included inside package entrypoint/*.py
import sys
import nvidia_tao_deploy.cv.X.scripts
from nvidia_tao_deploy.cv.common.entrypoint import launch_job
if __name__ == "__main__":
launch_job(nvidia_tao_deploy.cv.X.scripts, "X", sys.argv[1:])
"""
# Configure the logger.
verbosity = "INFO"
if not RELEASE:
verbosity = "DEBUG"
logging.basicConfig(format='%(asctime)s [%(levelname)s] %(name)s: %(message)s',
level=verbosity)
# build modules
modules = get_modules(package)
parser = build_command_line_parser(package_name, modules)
# parse command line arguments to module entrypoint script.
args = vars(parser.parse_args(cl_args))
gpu_ids = args["gpu_index"]
log_file = None
if args['log_file'] is not None:
log_file = os.path.realpath(args['log_file'])
log_root = os.path.dirname(log_file)
if not os.path.exists(log_root):
os.makedirs(log_root)
# Get the task to be called from the raw command line arguments.
task = None
for arg in sys.argv[1:]:
if arg in list(modules.keys()):
task = arg
break
# Format final command.
env_variables = set_gpu_info_single_node(gpu_ids)
formatted_args = format_command_line_args(args)
task_command = f"python3 {modules[task]['runner_path']}"
run_command = f"bash -c '{env_variables} {task_command} {formatted_args}'"
logger.debug("Run command: %s", run_command)
process_passed = True
start = time()
try:
if isinstance(log_file, str):
with open(log_file, "a", encoding="utf-8") as lf:
subprocess.run(shlex.split(run_command),
shell=False,
stdout=lf,
stderr=lf,
check=True)
else:
subprocess.run(shlex.split(run_command),
shell=False,
stdout=sys.stdout,
stderr=sys.stdout,
check=True)
except (KeyboardInterrupt, SystemExit):
logger.info("Command was interrupted.")
except subprocess.CalledProcessError as e:
if e.output is not None:
print(f"TAO Deploy task: {task} failed with error:\n{e.output}")
process_passed = False
end = time()
time_lapsed = end - start
try:
gpu_data = []
for device in get_device_details():
gpu_data.append(device.get_config())
logger.info("Sending telemetry data.")
send_telemetry_data(
package_name,
task,
gpu_data,
num_gpus=1,
time_lapsed=time_lapsed,
pass_status=process_passed
)
except Exception as e:
logger.warning("Telemetry data couldn't be sent, but the command ran successfully.")
logger.warning("[Error]: {}".format(e)) # noqa pylint: disable=C0209
pass
if not process_passed:
logger.warning("Execution status: FAIL")
sys.exit(1) # returning non zero return code from the process.
logger.info("Execution status: PASS")
| tao_deploy-main | nvidia_tao_deploy/cv/common/entrypoint/entrypoint_proto.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 Entrypoint Modules."""
| tao_deploy-main | nvidia_tao_deploy/cv/common/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 (TF2) command line wrapper to invoke CLI scripts."""
import importlib
import os
import pkgutil
import shlex
import subprocess
import sys
from time import time
import pycuda.driver as cuda
from nvidia_tao_deploy.cv.common.telemetry.nvml_utils import get_device_details
from nvidia_tao_deploy.cv.common.telemetry.telemetry import send_telemetry_data
def get_subtasks(package):
"""Get supported subtasks for a given task.
This function lists out the python tasks in a folder.
Returns:
subtasks (dict): Dictionary of files.
"""
module_path = package.__path__
modules = {}
# Collect modules dynamically.
for _, task, is_package in pkgutil.walk_packages(module_path):
if is_package:
continue
module_name = package.__name__ + '.' + task
module_details = {
"module_name": module_name,
"runner_path": os.path.abspath(importlib.import_module(module_name).__file__),
}
modules[task] = module_details
return modules
def check_valid_gpus(gpu_id):
"""Check if IDs is valid.
This function scans the machine using the nvidia-smi routine to find the
number of GPU's and matches the id's accordingly.
Once validated, it finally also sets the CUDA_VISIBLE_DEVICES env variable.
Args:
gpu_id (int): GPU index used by the user.
Returns:
No explicit returns
"""
cuda.init()
num_gpus_available = cuda.Device.count()
assert gpu_id >= 0, (
"GPU id cannot be negative."
)
assert gpu_id < num_gpus_available, (
"Checking for valid GPU ids and num_gpus."
)
os.environ['CUDA_VISIBLE_DEVICES'] = f"{gpu_id}"
def set_gpu_info_single_node(gpu_id):
"""Set gpu environment variable for single node."""
check_valid_gpus(gpu_id)
env_variable = ""
visible_devices = os.getenv("CUDA_VISIBLE_DEVICES", None)
if visible_devices is not None:
env_variable = f" CUDA_VISIBLE_DEVICES={visible_devices}"
return env_variable
def command_line_parser(parser, subtasks):
"""Build command line parser."""
parser.add_argument(
'subtask',
default='gen_trt_engine',
choices=subtasks.keys(),
help="Subtask for a given task/model.",
)
parser.add_argument(
"-k",
"--key",
help="User specific encoding key to load an .etlt model."
)
# Add standard TLT arguments.
parser.add_argument(
"-r",
"--results_dir",
help="Path to a folder where the experiment outputs should be written. (DEFAULT: ./)",
)
parser.add_argument(
"-e",
"--experiment_spec_file",
help="Path to the experiment spec file.",
required=True,
default=None
)
parser.add_argument(
'--gpu_index',
type=int,
default=0,
help="The index of the GPU to be used.",
)
parser.add_argument(
'-t',
'--threshold',
type=float,
default=None,
help='Confidence threshold for inference.'
)
# Parse the arguments.
return parser
def launch(parser,
subtasks,
override_results_dir="result_dir",
override_threshold="evaluate.min_score_thresh",
override_key="encryption_key",
network="tao-deploy"):
"""Parse the command line and kick off the entrypoint.
Args:
parser (argparse.ArgumentParser): Parser object to define the command line args.
subtasks (list): List of subtasks.
"""
# Subtasks for a given model.
parser = command_line_parser(parser, subtasks)
cli_args = sys.argv[1:]
args, unknown_args = parser.parse_known_args(cli_args)
args = vars(args)
scripts_args = ""
assert args["experiment_spec_file"], (
f"Experiment spec file needs to be provided for this task: {args['subtask']}"
)
if not os.path.exists(args["experiment_spec_file"]):
raise FileNotFoundError(f"Experiment spec file doesn't exist at {args['experiment_spec_file']}")
path, name = os.path.split(args["experiment_spec_file"])
if path != "":
scripts_args += f" --config-path {path}"
scripts_args += f" --config-name {name}"
if args['subtask'] in ["evaluate", "inference"]:
if args['results_dir']:
scripts_args += f" {override_results_dir}={args['results_dir']}"
if args['subtask'] in ['inference']:
if args['threshold'] and override_threshold:
scripts_args += f" {override_threshold}={args['threshold']}"
# Add encryption key.
if args['subtask'] in ["gen_trt_engine"]:
if args['key']:
scripts_args += f" {override_key}={args['key']}"
gpu_ids = args["gpu_index"]
script = subtasks[args['subtask']]["runner_path"]
unknown_args_string = " ".join(unknown_args)
task_command = f"python {script} {scripts_args} {unknown_args_string}"
print(task_command)
env_variables = set_gpu_info_single_node(gpu_ids)
run_command = f"bash -c \'{env_variables} {task_command}\'"
process_passed = True
start = time()
try:
subprocess.run(
shlex.split(run_command),
stdout=sys.stdout,
stderr=sys.stderr,
check=True
)
except (KeyboardInterrupt, SystemExit):
print("Command was interrupted.")
except subprocess.CalledProcessError as e:
process_passed = False
if e.output is not None:
print(f"TAO Deploy task: {args['subtask']} failed with error:\n{e.output}")
end = time()
time_lapsed = end - start
try:
gpu_data = []
for device in get_device_details():
gpu_data.append(device.get_config())
print("Sending telemetry data.")
send_telemetry_data(
network,
args['subtask'],
gpu_data,
num_gpus=1,
time_lapsed=time_lapsed,
pass_status=process_passed
)
except Exception as e:
print("Telemetry data couldn't be sent, but the command ran successfully.")
print(f"[WARNING]: {e}")
pass
if not process_passed:
print("Execution status: FAIL")
sys.exit(1) # returning non zero return code from the process.
print("Execution status: PASS")
| tao_deploy-main | nvidia_tao_deploy/cv/common/entrypoint/entrypoint_hydra.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 using the NVML library for GPU devices."""
import json
import pynvml
BRAND_NAMES = {
pynvml.NVML_BRAND_UNKNOWN: "Unknown",
pynvml.NVML_BRAND_QUADRO: "Quadro",
pynvml.NVML_BRAND_TESLA: "Tesla",
pynvml.NVML_BRAND_NVS: "NVS",
pynvml.NVML_BRAND_GRID: "Grid",
pynvml.NVML_BRAND_TITAN: "Titan",
pynvml.NVML_BRAND_GEFORCE: "GeForce",
pynvml.NVML_BRAND_NVIDIA_VAPPS: "NVIDIA Virtual Applications",
pynvml.NVML_BRAND_NVIDIA_VPC: "NVIDIA Virtual PC",
pynvml.NVML_BRAND_NVIDIA_VCS: "NVIDIA Virtual Compute Server",
pynvml.NVML_BRAND_NVIDIA_VWS: "NVIDIA RTX Virtual Workstation",
pynvml.NVML_BRAND_NVIDIA_VGAMING: "NVIDIA Cloud Gaming",
pynvml.NVML_BRAND_QUADRO_RTX: "Quadro RTX",
pynvml.NVML_BRAND_NVIDIA_RTX: "NVIDIA RTX",
pynvml.NVML_BRAND_NVIDIA: "NVIDIA",
pynvml.NVML_BRAND_GEFORCE_RTX: "GeForce RTX",
pynvml.NVML_BRAND_TITAN_RTX: "TITAN RTX",
}
class GPUDevice:
"""Data structure to represent a GPU device."""
def __init__(self, pci_bus_id,
device_name,
device_brand,
memory,
cuda_compute_capability):
"""Data structure representing a GPU device.
Args:
pci_bus_id (hex): PCI bus ID of the GPU.
device_name (str): Name of the device GPU.
device_branch (int): Brand of the GPU.
"""
self.name = device_name
self.pci_bus_id = pci_bus_id
if device_brand in BRAND_NAMES.keys():
self.brand = BRAND_NAMES[device_brand]
else:
self.brand = None
self.defined = True
self.memory = memory
self.cuda_compute_capability = cuda_compute_capability
def get_config(self):
"""Get json config of the device.
Returns
device_dict (dict): Dictionary containing data about the device.
"""
assert self.defined, "Device wasn't defined."
config_dict = {}
config_dict["name"] = self.name.decode().replace(" ", "-")
config_dict["pci_bus_id"] = self.pci_bus_id
config_dict["brand"] = self.brand
config_dict["memory"] = self.memory
config_dict["cuda_compute_capability"] = self.cuda_compute_capability
return config_dict
def __str__(self):
"""Generate a printable representation of the device."""
config = self.get_config()
data_string = json.dumps(config, indent=2)
return data_string
def pynvml_context(fn):
"""Simple decorator to setup python nvml context.
Args:
f: Function pointer.
Returns:
output of f.
"""
def _fn_wrapper(*args, **kwargs):
"""Wrapper setting up nvml context."""
try:
pynvml.nvmlInit()
return fn(*args, **kwargs)
finally:
pynvml.nvmlShutdown()
return _fn_wrapper
@pynvml_context
def get_number_gpus_available():
"""Get the number of GPU's attached to the machine.
Returns:
num_gpus (int): Number of GPUs in the machine.
"""
num_gpus = pynvml.nvmlDeviceGetCount()
return num_gpus
@pynvml_context
def get_device_details():
"""Get details about each device.
Returns:
device_list (list): List of GPUDevice objects.
"""
num_gpus = pynvml.nvmlDeviceGetCount()
device_list = []
assert num_gpus > 0, "Atleast 1 GPU is required for TAO Toolkit to run."
for idx in range(num_gpus):
handle = pynvml.nvmlDeviceGetHandleByIndex(idx)
pci_info = pynvml.nvmlDeviceGetPciInfo(handle)
device_name = pynvml.nvmlDeviceGetName(handle)
brand_name = pynvml.nvmlDeviceGetBrand(handle)
memory = pynvml.nvmlDeviceGetMemoryInfo(handle)
cuda_compute_capability = pynvml.nvmlDeviceGetCudaComputeCapability(handle)
device_list.append(
GPUDevice(
pci_info.busId,
device_name,
brand_name,
memory.total,
cuda_compute_capability
)
)
return device_list
| tao_deploy-main | nvidia_tao_deploy/cv/common/telemetry/nvml_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.
"""TAO utils for uploading telemetry data."""
| tao_deploy-main | nvidia_tao_deploy/cv/common/telemetry/__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.
"""Utilties to send data to the TAO Toolkit Telemetry Remote Service."""
import os
import shutil
import subprocess
import sys
import tarfile
import tempfile
import urllib
import requests
import urllib3
TELEMETRY_TIMEOUT = int(os.getenv("TELEMETRY_TIMEOUT", "30"))
def get_url_from_variable(variable, default=None):
"""Get the Telemetry Server URL."""
url = os.getenv(variable, default)
return url
def url_exists(url):
"""Check if a URL exists.
Args:
url (str): String to be verified as a URL.
Returns:
valid (bool): True/Falso
"""
url_request = urllib.request.Request(url)
url_request.get_method = lambda: 'HEAD'
try:
urllib.request.urlopen(url_request) # noqa pylint: disable=R1732
return True
except urllib.request.URLError:
return False
def get_certificates():
"""Download the cacert.pem file and return the path.
Returns:
path (str): UNIX path to the certificates.
"""
certificates_url = get_url_from_variable("TAO_CERTIFICATES_URL")
if not url_exists(certificates_url):
raise urllib.request.URLError("Url for the certificates not found.")
tmp_dir = tempfile.mkdtemp()
download_command = f"wget {certificates_url} -P {tmp_dir} --quiet"
try:
subprocess.check_call(
download_command, shell=True, stdout=sys.stdout
)
except Exception as exc:
raise urllib.request.URLError("Download certificates.tar.gz failed.") from exc
tarfile_path = os.path.join(tmp_dir, "certificates.tar.gz")
assert tarfile.is_tarfile(tarfile_path), (
"The downloaded file isn't a tar file."
)
with tarfile.open(name=tarfile_path, mode="r:gz") as tar_file:
filenames = tar_file.getnames()
for memfile in filenames:
member = tar_file.getmember(memfile)
tar_file.extract(member, tmp_dir)
file_list = [item for item in os.listdir(tmp_dir) if item.endswith(".pem")]
assert file_list, (
f"Didn't get pem files. Directory contents {file_list}"
)
return tmp_dir
def send_telemetry_data(network, action, gpu_data, num_gpus=1, time_lapsed=None, pass_status=False):
"""Wrapper to send TAO telemetry data.
Args:
network (str): Name of the network being run.
action (str): Subtask of the network called.
gpu_data (dict): Dictionary containing data about the GPU's in the machine.
num_gpus (int): Number of GPUs used in the job.
time_lapsed (int): Time lapsed.
pass_status (bool): Job passed or failed.
Returns:
No explicit returns.
"""
urllib_major_version = int(urllib3.__version__.split(".", maxsplit=1)[0])
if urllib_major_version < 2:
urllib3.disable_warnings(urllib3.exceptions.SubjectAltNameWarning)
if os.getenv('TELEMETRY_OPT_OUT', "no").lower() in ["no", "false", "0"]:
url = get_url_from_variable("TAO_TELEMETRY_SERVER")
data = {
"version": os.getenv("TAO_TOOLKIT_VERSION", "4.0.0"),
"action": action,
"network": network,
"gpu": [device["name"] for device in gpu_data[:num_gpus]],
"success": pass_status
}
if time_lapsed is not None:
data["time_lapsed"] = time_lapsed
certificate_dir = get_certificates()
cert = ('client-cert.pem', 'client-key.pem')
requests.post(
url,
json=data,
cert=tuple([os.path.join(certificate_dir, item) for item in cert]), # noqa pylint: disable=R1728
timeout=TELEMETRY_TIMEOUT
)
shutil.rmtree(certificate_dir)
| tao_deploy-main | nvidia_tao_deploy/cv/common/telemetry/telemetry.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.
"""Logger class for TAO Deploy models."""
from abc import abstractmethod
import atexit
from datetime import datetime
import json
import logging
import os
logger = logging.getLogger(__name__)
class Verbosity():
"""Verbosity levels."""
DISABLE = 0
DEBUG = 10
INFO = 20
WARNING = 30
ERROR = 40
CRITICAL = 50
# Defining a log level to name dictionary.
log_level_to_name = {
Verbosity.DISABLE: "DISABLE",
Verbosity.DEBUG: 'DEBUG',
Verbosity.INFO: 'INFO',
Verbosity.WARNING: 'WARNING',
Verbosity.ERROR: 'ERROR',
Verbosity.CRITICAL: 'CRITICAL'
}
class Status():
"""Status levels."""
SUCCESS = 0
FAILURE = 1
STARTED = 2
RUNNING = 3
SKIPPED = 4
status_level_to_name = {
Status.SUCCESS: 'SUCCESS',
Status.FAILURE: 'FAILURE',
Status.STARTED: 'STARTED',
Status.RUNNING: 'RUNNING',
Status.SKIPPED: 'SKIPPED'
}
class BaseLogger(object):
"""File logger class."""
def __init__(self, is_master=False, verbosity=Verbosity.DISABLE):
"""Base logger class."""
self.is_master = is_master
self.verbosity = verbosity
self.categorical = {}
self.graphical = {}
self.kpi = {}
@property
def date(self):
"""Get date from the status."""
date_time = datetime.now()
date_object = date_time.date()
return "{}/{}/{}".format( # noqa pylint: disable=C0209
date_object.month,
date_object.day,
date_object.year
)
@property
def time(self):
"""Get date from the status."""
date_time = datetime.now()
time_object = date_time.time()
return "{}:{}:{}".format( # noqa pylint: disable=C0209
time_object.hour,
time_object.minute,
time_object.second
)
@property
def categorical(self):
"""Categorical data to be logged."""
return self._categorical
@categorical.setter
def categorical(self, value: dict):
"""Set categorical data to be logged."""
self._categorical = value
@property
def graphical(self):
"""Graphical data to be logged."""
return self._graphical
@graphical.setter
def graphical(self, value: dict):
"""Set graphical data to be logged."""
self._graphical = value
@property
def kpi(self):
"""Set KPI data."""
return self._kpi
@kpi.setter
def kpi(self, value: dict):
"""Set KPI data."""
self._kpi = value
def flush(self):
"""Flush the logger."""
pass
def format_data(self, data: dict):
"""Format the data."""
if isinstance(data, dict):
data_string = []
for key, value in data.items():
data_string.append(
f"{key}: {self.format_data(value)}"
if isinstance(value, dict) else value
)
return ", ".join(data_string)
def log(self, level, string):
"""Log the data string."""
if level >= self.verbosity:
logging.log(level, string)
@abstractmethod
def write(self, data=None,
status_level=Status.RUNNING,
verbosity_level=Verbosity.INFO,
message=None):
"""Write data out to the log file."""
if self.verbosity > Verbosity.DISABLE:
if not data:
data = {}
# Define generic data.
data["date"] = self.date
data["time"] = self.time
data["status"] = status_level_to_name.get(status_level, "RUNNING")
data["verbosity"] = log_level_to_name.get(verbosity_level, "INFO")
if message:
data["message"] = message
logging.log(verbosity_level, message)
if self.categorical:
data["categorical"] = self.categorical
if self.graphical:
data["graphical"] = self.graphical
if self.kpi:
data["kpi"] = self.kpi
data_string = self.format_data(data)
if self.is_master:
self.log(verbosity_level, data_string)
self.flush()
class StatusLogger(BaseLogger):
"""Simple logger to save the status file."""
def __init__(self, filename=None,
is_master=False,
verbosity=Verbosity.INFO,
append=True):
"""Logger to write out the status."""
super().__init__(is_master=is_master, verbosity=verbosity)
self.log_path = os.path.realpath(filename)
if os.path.exists(self.log_path):
logger.info("Log file already exists at %s", self.log_path)
if is_master:
self.l_file = open(self.log_path, "a" if append else "w", encoding='utf-8') # noqa pylint: disable=R1732
atexit.register(self.l_file.close)
def log(self, level, string):
"""Log the data string."""
if level >= self.verbosity:
self.l_file.write(string + "\n")
def flush(self):
"""Flush contents of the log file."""
if self.is_master:
self.l_file.flush()
@staticmethod
def format_data(data):
"""Format the dictionary data."""
if not isinstance(data, dict):
raise TypeError(f"Data must be a dictionary and not type {type(data)}.")
data_string = json.dumps(data)
return data_string
# Define the logger here so it's static.
_STATUS_LOGGER = BaseLogger()
def set_status_logger(status_logger):
"""Set the status logger.
Args:
status_logger: An instance of the logger class.
"""
global _STATUS_LOGGER # pylint: disable=W0603
_STATUS_LOGGER = status_logger
def get_status_logger():
"""Get the status logger."""
global _STATUS_LOGGER # pylint: disable=W0602,W0603
return _STATUS_LOGGER
| tao_deploy-main | nvidia_tao_deploy/cv/common/logging/status_logging.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 Common Logging Modules."""
| tao_deploy-main | nvidia_tao_deploy/cv/common/logging/__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 Common Hydra Modules."""
| tao_deploy-main | nvidia_tao_deploy/cv/common/hydra/__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 to work with hydra config files."""
import functools
import os
import sys
from typing import Any, Callable, Optional
from hydra._internal.utils import _run_hydra, get_args_parser
from hydra.core.config_store import ConfigStore
from hydra.types import TaskFunction
from omegaconf import DictConfig
def hydra_runner(
config_path: Optional[str] = None, config_name: Optional[str] = None, schema: Optional[Any] = None
) -> Callable[[TaskFunction], Any]:
"""Decorator used for passing the Config paths to main function.
Optionally registers a schema used for validation/providing default values.
Args:
config_path: Optional path that will be added to config search directory.
config_name: Pathname of the config file.
schema: Structured config type representing the schema used for validation/providing default values.
"""
def decorator(task_function: TaskFunction) -> Callable[[], None]:
@functools.wraps(task_function)
def wrapper(cfg_passthrough: Optional[DictConfig] = None) -> Any:
# Check it config was passed.
if cfg_passthrough is not None:
return task_function(cfg_passthrough)
args = get_args_parser()
# Parse arguments in order to retrieve overrides
parsed_args = args.parse_args()
# Get overriding args in dot string format
overrides = parsed_args.overrides # type: list
# Disable the creation of .hydra subdir
# https://hydra.cc/docs/tutorials/basic/running_your_app/working_directory
overrides.append("hydra.output_subdir=null")
# Hydra logging outputs only to stdout (no log file).
# https://hydra.cc/docs/configure_hydra/logging
overrides.append("hydra/job_logging=stdout")
# Set run.dir ONLY for ExpManager "compatibility" - to be removed.
overrides.append("hydra.run.dir=.")
# Check if user set the schema.
if schema is not None:
# Create config store.
cs = ConfigStore.instance()
# Get the correct ConfigStore "path name" to "inject" the schema.
if parsed_args.config_name is not None:
path, name = os.path.split(parsed_args.config_name)
# Make sure the path is not set - as this will disable validation scheme.
if path != '':
sys.stderr.write(
"ERROR Cannot set config file path using `--config-name` when "
"using schema. Please set path using `--config-path` and file name using "
"`--config-name` separately.\n"
)
sys.exit(1)
else:
name = config_name
# Register the configuration as a node under the name in the group.
cs.store(name=name, node=schema) # group=group,
# Wrap a callable object with name `parse_args`
# This is to mimic the ArgParser.parse_args() API.
class _argparse_wrapper:
def __init__(self, arg_parser):
self.arg_parser = arg_parser
self._actions = arg_parser._actions
def parse_args(self, args=None, namespace=None):
return parsed_args
# no return value from run_hydra() as it may sometime actually run the task_function
# multiple times (--multirun)
_run_hydra(
args=_argparse_wrapper(args).parse_args(),
args_parser=_argparse_wrapper(args),
task_function=task_function,
config_path=config_path,
config_name=config_name,
)
return wrapper
return decorator
| tao_deploy-main | nvidia_tao_deploy/cv/common/hydra/hydra_runner.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.
"""TensorRT Engine class for Deformable DETR."""
from nvidia_tao_deploy.inferencer.trt_inferencer import TRTInferencer
from nvidia_tao_deploy.inferencer.utils import allocate_buffers, do_inference
import numpy as np
from PIL import ImageDraw
import tensorrt as trt # pylint: disable=unused-import
def trt_output_process_fn(y_encoded, batch_size, num_classes):
"""Function to process TRT model output.
Args:
y_encoded (list): list of TRT outputs in numpy
batch_size (int): batch size from TRT engine
num_classes (int): number of classes that the model was trained on
Returns:
pred_logits (np.ndarray): (B x NQ x N) logits of the prediction
pred_boxes (np.ndarray): (B x NQ x 4) bounding boxes of the prediction
"""
pred_logits, pred_boxes = y_encoded
return pred_logits.reshape((batch_size, -1, num_classes)), pred_boxes.reshape((batch_size, -1, 4))
class DDETRInferencer(TRTInferencer):
"""Implements inference for the D-DETR TensorRT engine."""
def __init__(self, engine_path, num_classes, 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
num_classes (int): number of classes that the model was trained on
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]
self.num_classes = num_classes
# 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
results = trt_output_process_fn(y_pred, actual_batch_size, self.num_classes)
return 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()
def draw_bbox(self, img, prediction, class_mapping, threshold=0.3, color_map=None): # noqa pylint: disable=W0237
"""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 name
threshold (float): value to filter predictions
color_map (dict): key is the class name and value is the color to be used
"""
draw = ImageDraw.Draw(img)
label_strings = []
for i in prediction:
if int(i[0]) not in class_mapping:
continue
cls_name = class_mapping[int(i[0])]
if float(i[1]) < threshold:
continue
if cls_name in color_map:
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}")
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/deformable_detr/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.
"""D-DETR 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 DDETRDetEngineBuilder(EngineBuilder):
"""Parses an ONNX graph and builds a TensorRT engine from it."""
def __init__(
self,
input_dims,
is_dynamic=False,
data_format="channels_first",
img_std=[0.229, 0.224, 0.225],
**kwargs
):
"""Init.
Args:
data_format (str): data_format.
"""
super().__init__(**kwargs)
self._input_dims = input_dims
self._data_format = data_format
self.is_dynamic = is_dynamic
self._img_std = img_std
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.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 D-DETR 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)
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,
calib_data_file=calib_data_file)
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,
calib_data_file=None,
image_mean=None):
"""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.
Returns:
No explicit returns.
"""
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='DDETR',
img_std=self._img_std))
| tao_deploy-main | nvidia_tao_deploy/cv/deformable_detr/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 D-DETR."""
| tao_deploy-main | nvidia_tao_deploy/cv/deformable_detr/__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 functions to be used for D-DETR."""
import numpy as np
def box_cxcywh_to_xyxy(x):
"""Convert box from cxcywh to xyxy."""
x_c, y_c, w, h = x[..., 0], x[..., 1], x[..., 2], x[..., 3]
b = [(x_c - 0.5 * w), (y_c - 0.5 * h),
(x_c + 0.5 * w), (y_c + 0.5 * h)]
return np.stack(b, axis=-1)
def sigmoid(x):
"""Numpy-based sigmoid function."""
return 1 / (1 + np.exp(-x))
def post_process(pred_logits, pred_boxes, target_sizes, num_select=100):
"""Perform the post-processing. Scale back the boxes to the original size.
Args:
pred_logits (np.ndarray): (B x NQ x 4) logit values from TRT engine.
pred_boxes (np.ndarray): (B x NQ x 4) bbox values from TRT engine.
target_sizes (np.ndarray): (B x 4) [w, h, w, h] containing original image dimension.
num_select (int): Top-K proposals to choose from.
Returns:
labels (np.ndarray): (B x NS) class label of top num_select predictions.
scores (np.ndarray): (B x NS) class probability of top num_select predictions.
boxes (np.ndarray): (B x NS x 4) scaled back bounding boxes of top num_select predictions.
"""
# Sigmoid
prob = sigmoid(pred_logits).reshape((pred_logits.shape[0], -1))
# Get topk scores
topk_indices = np.argsort(prob, axis=1)[:, ::-1][:, :num_select]
scores = [per_batch_prob[ind] for per_batch_prob, ind in zip(prob, topk_indices)]
scores = np.array(scores)
# Get corresponding boxes
topk_boxes = topk_indices // pred_logits.shape[2]
# Get corresponding labels
labels = topk_indices % pred_logits.shape[2]
# Convert to x1, y1, x2, y2 format
boxes = box_cxcywh_to_xyxy(pred_boxes)
# Take corresponding topk boxes
boxes = np.take_along_axis(boxes, np.repeat(np.expand_dims(topk_boxes, -1), 4, axis=-1), axis=1)
# Scale back the bounding boxes to the original image size
target_sizes = np.array(target_sizes)
boxes = boxes * target_sizes[:, None, :]
# Clamp bounding box coordinates
for i, target_size in enumerate(target_sizes):
w, h = target_size[0], target_size[1]
boxes[i, :, 0::2] = np.clip(boxes[i, :, 0::2], 0.0, w)
boxes[i, :, 1::2] = np.clip(boxes[i, :, 1::2], 0.0, h)
return labels, scores, boxes
| tao_deploy-main | nvidia_tao_deploy/cv/deformable_detr/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.
"""D-DETR loader."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from PIL import Image
import cv2
from nvidia_tao_deploy.dataloader.coco import COCOLoader
from nvidia_tao_deploy.inferencer.preprocess_input import preprocess_input
def resize(image, target, size, max_size=None):
"""resize."""
# size can be min_size (scalar) or (w, h) tuple
def get_size_with_aspect_ratio(image_size, size, max_size=None):
"""get_size_with_aspect_ratio."""
w, h = image_size
if max_size is not None:
min_original_size = float(min((w, h)))
max_original_size = float(max((w, h)))
if max_original_size / min_original_size * size > max_size:
size = int(round(max_size * min_original_size / max_original_size))
if (w <= h and w == size) or (h <= w and h == size):
return (h, w)
if w < h:
ow = size
oh = int(size * h / w)
else:
oh = size
ow = int(size * w / h)
return (oh, ow)
def get_size(image_size, size, max_size=None):
"""get_size."""
# Size needs to be (width, height)
if isinstance(size, (list, tuple)):
return_size = size[::-1]
else:
return_size = get_size_with_aspect_ratio(image_size, size, max_size)
return return_size
size = get_size(image.size, size, max_size)
# PILLOW bilinear is not same as F.resize from torchvision
# PyTorch mimics OpenCV's behavior.
# Ref: https://tcapelle.github.io/pytorch/fastai/2021/02/26/image_resizing.html
rescaled_image = cv2.resize(image, size, interpolation=cv2.INTER_LINEAR)
if target is None:
return rescaled_image, None
ratios = tuple(float(s) / float(s_orig) for s, s_orig in zip(rescaled_image.size, image.size))
ratio_width, ratio_height = ratios
target = target.copy()
if "boxes" in target:
boxes = target["boxes"]
scaled_boxes = boxes * [ratio_width, ratio_height, ratio_width, ratio_height]
target["boxes"] = scaled_boxes
h, w = size
target["size"] = np.array([h, w])
return rescaled_image, target
class DDETRCOCOLoader(COCOLoader):
"""D-DETR DataLoader."""
def __init__(
self,
image_std=None,
**kwargs
):
"""Init.
Args:
image_std (list): image standard deviation.
"""
super().__init__(**kwargs)
self.image_std = image_std
def _get_single_processed_item(self, idx):
"""Load and process single image and its label."""
gt_image_info, image_id = self._load_gt_image(idx)
gt_image, gt_scale = gt_image_info
gt_label = self._load_gt_label(idx)
return gt_image, gt_scale, image_id, gt_label
def preprocess_image(self, image_path):
"""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.
This Image Batcher implements one algorithm for now:
* DDETR: Resizes and pads the image to fit the input size.
Args:
image_path(str): The path to the 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
scale (list): the resize scale used, if any.
"""
scale = None
image = Image.open(image_path)
image = image.convert(mode='RGB')
image = np.asarray(image, dtype=self.dtype)
image, _ = resize(image, None, size=(self.height, self.width))
if self.data_format == "channels_first":
image = np.transpose(image, (2, 0, 1))
image = preprocess_input(image,
data_format=self.data_format,
img_std=self.image_std,
mode='torch')
return image, scale
| tao_deploy-main | nvidia_tao_deploy/cv/deformable_detr/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 D-DETR Hydra."""
| tao_deploy-main | nvidia_tao_deploy/cv/deformable_detr/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 DDDatasetConvertConfig:
"""Dataset Convert config."""
input_source: Optional[str] = None
data_root: Optional[str] = None
results_dir: str = MISSING
image_dir_name: Optional[str] = None
label_dir_name: Optional[str] = None
val_split: int = 0
num_shards: int = 20
num_partitions: int = 1
partition_mode: Optional[str] = None
image_extension: str = ".jpg"
mapping_path: Optional[str] = None
@dataclass
class DDAugmentationConfig:
"""Augmentation config."""
scales: List[int] = field(default_factory=lambda: [480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800],
metadata={"description": "Random Scales for Augmentation"})
input_mean: List[float] = field(default_factory=lambda: [0.485, 0.456, 0.406],
metadata={"description": "Pixel mean value"})
input_std: List[float] = field(default_factory=lambda: [0.229, 0.224, 0.225],
metadata={"description": "Pixel Standard deviation value"})
train_random_resize: List[int] = field(default_factory=lambda: [400, 500, 600],
metadata={"description": "Training Random Resize"})
horizontal_flip_prob: float = 0.5
train_random_crop_min: int = 384
train_random_crop_max: int = 600
random_resize_max_size: int = 1333
test_random_resize: int = 800
fixed_padding: bool = True
@dataclass
class DDDatasetConfig:
"""Dataset config."""
train_sampler: str = "default_sampler"
train_data_sources: Optional[List[Dict[str, str]]] = None
val_data_sources: Optional[List[Dict[str, str]]] = None
test_data_sources: Optional[Dict[str, str]] = None
infer_data_sources: Optional[Dict[str, str]] = None
batch_size: int = 4
workers: int = 8
pin_memory: bool = True
num_classes: int = 91
dataset_type: str = "serialized"
eval_class_ids: Optional[List[int]] = None
augmentation: DDAugmentationConfig = DDAugmentationConfig()
@dataclass
class DDModelConfig:
"""Deformable DETR model config."""
pretrained_backbone_path: Optional[str] = None
backbone: str = "resnet_50"
num_queries: int = 300
num_feature_levels: int = 4
return_interm_indices: List[int] = field(default_factory=lambda: [1, 2, 3, 4],
metadata={"description": "Indices to return from backbone"})
with_box_refine: bool = True
cls_loss_coef: float = 2.0
bbox_loss_coef: float = 5.0
giou_loss_coef: float = 2.0
focal_alpha: float = 0.25
clip_max_norm: float = 0.1
dropout_ratio: float = 0.3
hidden_dim: int = 256
nheads: int = 8
enc_layers: int = 6
dec_layers: int = 6
dim_feedforward: int = 1024
dec_n_points: int = 4
enc_n_points: int = 4
aux_loss: bool = True
dilation: bool = False
train_backbone: bool = True
loss_types: List[str] = field(default_factory=lambda: ['labels', 'boxes'],
metadata={"description": "Losses to be used during training"})
backbone_names: List[str] = field(default_factory=lambda: ["backbone.0"],
metadata={"description": "Backbone name"})
linear_proj_names: List[str] = field(default_factory=lambda: ['reference_points', 'sampling_offsets'],
metadata={"description": "Linear Projection names"})
@dataclass
class OptimConfig:
"""Optimizer config."""
optimizer: str = "AdamW"
monitor_name: str = "val_loss" # {val_loss, train_loss}
lr: float = 2e-4
lr_backbone: float = 2e-5
lr_linear_proj_mult: float = 0.1
momentum: float = 0.9
weight_decay: float = 1e-4
lr_scheduler: str = "MultiStep"
lr_steps: List[int] = field(default_factory=lambda: [40],
metadata={"description": "learning rate decay steps"})
lr_step_size: int = 40
lr_decay: float = 0.1
@dataclass
class DDTrainExpConfig:
"""Train experiment config."""
num_gpus: int = 1
num_nodes: int = 1
resume_training_checkpoint_path: Optional[str] = None
pretrained_model_path: Optional[str] = None
validation_interval: int = 1
clip_grad_norm: float = 0.1
is_dry_run: bool = False
results_dir: Optional[str] = None
num_epochs: int = 50
checkpoint_interval: int = 1
optim: OptimConfig = OptimConfig()
precision: str = "fp32"
distributed_strategy: str = "ddp"
activation_checkpoint: bool = True
@dataclass
class DDInferenceExpConfig:
"""Inference experiment config."""
num_gpus: int = 1
results_dir: Optional[str] = None
checkpoint: Optional[str] = None
trt_engine: Optional[str] = None
color_map: Dict[str, str] = MISSING
conf_threshold: float = 0.5
is_internal: bool = False
input_width: Optional[int] = None
input_height: Optional[int] = None
@dataclass
class DDEvalExpConfig:
"""Evaluation experiment config."""
num_gpus: int = 1
results_dir: Optional[str] = None
input_width: Optional[int] = None
input_height: Optional[int] = None
checkpoint: Optional[str] = None
trt_engine: Optional[str] = None
conf_threshold: float = 0.0
@dataclass
class CalibrationConfig:
"""Calibration config."""
cal_image_dir: List[str] = MISSING
cal_cache_file: str = MISSING
cal_batch_size: int = 1
cal_batches: int = 1
@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 DDExportExpConfig:
"""Export experiment config."""
results_dir: Optional[str] = None
gpu_id: int = 0
checkpoint: str = MISSING
onnx_file: str = MISSING
on_cpu: bool = False
input_channel: int = 3
input_width: int = 960
input_height: int = 544
opset_version: int = 12
batch_size: int = -1
verbose: bool = False
@dataclass
class DDGenTrtEngineExpConfig:
"""Gen TRT Engine experiment config."""
results_dir: Optional[str] = None
gpu_id: int = 0
onnx_file: str = MISSING
trt_engine: Optional[str] = None
input_channel: int = 3
input_width: int = 960
input_height: int = 544
opset_version: int = 12
batch_size: int = -1
verbose: bool = False
tensorrt: TrtConfig = TrtConfig()
@dataclass
class ExperimentConfig:
"""Experiment config."""
model: DDModelConfig = DDModelConfig()
dataset: DDDatasetConfig = DDDatasetConfig()
train: DDTrainExpConfig = DDTrainExpConfig()
evaluate: DDEvalExpConfig = DDEvalExpConfig()
inference: DDInferenceExpConfig = DDInferenceExpConfig()
export: DDExportExpConfig = DDExportExpConfig()
gen_trt_engine: DDGenTrtEngineExpConfig = DDGenTrtEngineExpConfig()
encryption_key: Optional[str] = None
results_dir: str = MISSING
| tao_deploy-main | nvidia_tao_deploy/cv/deformable_detr/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.
"""D-DETR convert onnx model to TRT engine."""
import logging
import os
import tempfile
from nvidia_tao_deploy.cv.deformable_detr.engine_builder import DDETRDetEngineBuilder
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.deformable_detr.hydra_config.default_config import ExperimentConfig
from nvidia_tao_deploy.utils.decoding import decode_model
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='deformable_detr', 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)
# decrypt etlt
tmp_onnx_file, file_format = decode_model(cfg.gen_trt_engine.onnx_file, cfg.encryption_key)
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.gen_trt_engine.input_channel
input_width = cfg.gen_trt_engine.input_width
input_height = cfg.gen_trt_engine.input_height
# INT8 related configs
img_std = cfg.dataset.augmentation.input_std
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
# 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.lower() == "fp16" and trt_version_number < 8600:
logger.warning("[WARNING]: LayerNorm has overflow issue in FP16 upto TensorRT version 8.5 "
"which can lead to mAP drop compared to FP32.\n"
"[WARNING]: Please re-export ONNX using opset 17 and use TensorRT version 8.6.\n")
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 = DDETRDetEngineBuilder(workspace=workspace_size // 1024, # DD config is not in GB
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)
builder.create_network(tmp_onnx_file, file_format)
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/deformable_detr/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 D-DETR scripts module."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
| tao_deploy-main | nvidia_tao_deploy/cv/deformable_detr/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."""
import os
import logging
import numpy as np
from PIL import Image
from tqdm.auto import tqdm
from nvidia_tao_deploy.cv.deformable_detr.inferencer import DDETRInferencer
from nvidia_tao_deploy.cv.deformable_detr.utils import post_process
from nvidia_tao_deploy.cv.deformable_detr.hydra_config.default_config import ExperimentConfig
from nvidia_tao_deploy.utils.image_batcher import ImageBatcher
from nvidia_tao_deploy.cv.common.decorators import monitor_status
from nvidia_tao_deploy.cv.common.hydra.hydra_runner import hydra_runner
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="infer", schema=ExperimentConfig
)
@monitor_status(name='deformable_detr', mode='inference')
def main(cfg: ExperimentConfig) -> None:
"""D-DETR TRT Inference."""
if not os.path.exists(cfg.inference.trt_engine):
raise FileNotFoundError(f"Provided inference.trt_engine at {cfg.inference.trt_engine} does not exist!")
trt_infer = DDETRInferencer(cfg.inference.trt_engine,
batch_size=cfg.dataset.batch_size,
num_classes=cfg.dataset.num_classes)
c, h, w = trt_infer._input_shape
batcher = ImageBatcher(list(cfg.dataset.infer_data_sources.image_dir),
(cfg.dataset.batch_size, c, h, w),
trt_infer.inputs[0].host.dtype,
preprocessor="DDETR")
with open(cfg.dataset.infer_data_sources.classmap, "r", encoding="utf-8") as f:
classmap = [line.rstrip() for line in f.readlines()]
classes = {c: i + 1 for i, c in enumerate(classmap)}
# Create results directories
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)
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)
inv_classes = {v: k for k, v in classes.items()}
for batches, img_paths, scales in tqdm(batcher.get_batch(), total=batcher.num_batches, desc="Producing predictions"):
# Handle last batch as we artifically pad images for the last batch idx
if len(img_paths) != len(batches):
batches = batches[:len(img_paths)]
pred_logits, pred_boxes = trt_infer.infer(batches)
target_sizes = []
for batch, scale in zip(batches, scales):
_, new_h, new_w = batch.shape
orig_h, orig_w = int(scale[0] * new_h), int(scale[1] * new_w)
target_sizes.append([orig_w, orig_h, orig_w, orig_h])
class_labels, scores, boxes = post_process(pred_logits, pred_boxes, target_sizes)
y_pred_valid = np.concatenate([class_labels[..., None], scores[..., None], boxes], axis=-1)
for img_path, pred in zip(img_paths, y_pred_valid):
# Load Image
img = Image.open(img_path)
# Resize of the original input image is not required for D-DETR
# as the predictions are rescaled in post_process
bbox_img, label_strings = trt_infer.draw_bbox(img, pred, inv_classes, cfg.inference.conf_threshold, cfg.inference.color_map)
img_filename = os.path.basename(img_path)
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.")
if __name__ == '__main__':
main()
| tao_deploy-main | nvidia_tao_deploy/cv/deformable_detr/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 inference."""
import os
import operator
import copy
import logging
import json
import six
import numpy as np
from tqdm.auto import tqdm
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.deformable_detr.dataloader import DDETRCOCOLoader
from nvidia_tao_deploy.cv.deformable_detr.inferencer import DDETRInferencer
from nvidia_tao_deploy.cv.deformable_detr.utils import post_process
from nvidia_tao_deploy.cv.deformable_detr.hydra_config.default_config import ExperimentConfig
from nvidia_tao_deploy.metrics.coco_metric import EvaluationMetric
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='deformable_detr', mode='evaluation')
def main(cfg: ExperimentConfig) -> None:
"""D-DETR TRT evaluation."""
if not os.path.exists(cfg.evaluate.trt_engine):
raise FileNotFoundError(f"Provided evaluate.trt_engine at {cfg.evaluate.trt_engine} does not exist!")
eval_metric = EvaluationMetric(cfg.dataset.test_data_sources.json_file,
eval_class_ids=cfg.dataset.eval_class_ids,
include_mask=False)
trt_infer = DDETRInferencer(cfg.evaluate.trt_engine,
batch_size=cfg.dataset.batch_size,
num_classes=cfg.dataset.num_classes)
c, h, w = trt_infer._input_shape
dl = DDETRCOCOLoader(
val_json_file=cfg.dataset.test_data_sources.json_file,
shape=(cfg.dataset.batch_size, c, h, w),
dtype=trt_infer.inputs[0].host.dtype,
batch_size=cfg.dataset.batch_size,
data_format="channels_first",
image_std=cfg.dataset.augmentation.input_std,
image_dir=cfg.dataset.test_data_sources.image_dir,
eval_samples=None)
predictions = {
'detection_scores': [],
'detection_boxes': [],
'detection_classes': [],
'source_id': [],
'image_info': [],
'num_detections': []
}
def evaluation_preds(preds):
# Essential to avoid modifying the source dict
_preds = copy.deepcopy(preds)
for k, _ in six.iteritems(_preds):
_preds[k] = np.concatenate(_preds[k], axis=0)
eval_results = eval_metric.predict_metric_fn(_preds)
return eval_results
for imgs, scale, source_id, labels in tqdm(dl, total=len(dl), desc="Producing predictions"):
image = np.array(imgs)
image_info = []
target_sizes = []
for i, label in enumerate(labels):
image_info.append([label[-1][0], label[-1][1], scale[i], label[-1][2], label[-1][3]])
# target_sizes needs to [W, H, W, H]
target_sizes.append([label[-1][3], label[-1][2], label[-1][3], label[-1][2]])
image_info = np.array(image_info)
pred_logits, pred_boxes = trt_infer.infer(image)
class_labels, scores, boxes = post_process(pred_logits, pred_boxes, target_sizes)
# Convert to xywh
boxes[:, :, 2:] -= boxes[:, :, :2]
predictions['detection_classes'].append(class_labels)
predictions['detection_scores'].append(scores)
predictions['detection_boxes'].append(boxes)
predictions['num_detections'].append(np.array([100] * cfg.dataset.batch_size).astype(np.int32))
predictions['image_info'].append(image_info)
predictions['source_id'].append(source_id)
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)
eval_results = evaluation_preds(preds=predictions)
for key, value in sorted(eval_results.items(), key=operator.itemgetter(0)):
eval_results[key] = float(value)
logging.info("%s: %.9f", key, value)
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/deformable_detr/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 D-DETR."""
| tao_deploy-main | nvidia_tao_deploy/cv/deformable_detr/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 argparse
from nvidia_tao_deploy.cv.deformable_detr 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(
"deformable_detr",
add_help=True,
description="Train Adapt Optimize Deploy entrypoint for D-DETR"
)
# Build list of subtasks by inspecting the scripts package.
subtasks = get_subtasks(scripts)
# Parse the arguments and launch the subtask.
launch(parser, subtasks, network="deformable_detr")
if __name__ == '__main__':
main()
| tao_deploy-main | nvidia_tao_deploy/cv/deformable_detr/entrypoint/deformable_detr.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, model_output_width, model_output_height):
"""Function to process TRT model output."""
predictions_batch = []
for idx in range(y_encoded[0].shape[0]):
pred = np.reshape(y_encoded[0][idx, ...], (model_output_height,
model_output_width,
1))
pred = np.squeeze(pred, axis=-1)
predictions_batch.append(pred)
return np.array(predictions_batch)
class SegformerInferencer(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.
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.width, self.height)
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/segformer/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.
"""Segformer 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 SegformerEngineBuilder(EngineBuilder):
"""Parses an UFF/ONNX graph and builds a TensorRT engine from it."""
def __init__(
self,
input_dims,
is_dynamic=False,
data_format="channels_first",
**kwargs
):
"""Init.
Args:
data_format (str): data_format.
"""
super().__init__(**kwargs)
self._input_dims = input_dims
self._data_format = data_format
self.is_dynamic = is_dynamic
def get_onnx_input_dims(self, model_path):
"""Get input dimension of ONNX model."""
onnx_model = onnx.load(model_path)
try:
onnx.checker.check_model(onnx_model)
except onnx.checker.ValidationError as e:
logger.error('The ONNX model file is invalid: %s', e)
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.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)
else:
logger.info("Parsing UFF model")
raise NotImplementedError("UFF for Segformer 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 == "fp32" and self.builder.platform_has_tf32:
self.config.set_flag(trt.BuilderFlag.TF32)
elif precision == "int8":
raise NotImplementedError("INT8 is not supported for Segformer!")
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())
| tao_deploy-main | nvidia_tao_deploy/cv/segformer/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 Segformer."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
| tao_deploy-main | nvidia_tao_deploy/cv/segformer/__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.
"""MMCV image preprocessing."""
import cv2
from PIL import Image
import numpy as np
pillow_interp_codes = {
'nearest': Image.NEAREST,
'bilinear': Image.BILINEAR,
'bicubic': Image.BICUBIC,
'box': Image.BOX,
'lanczos': Image.LANCZOS,
'hamming': Image.HAMMING
}
cv2_interp_codes = {
'nearest': cv2.INTER_NEAREST,
'bilinear': cv2.INTER_LINEAR,
'bicubic': cv2.INTER_CUBIC,
'area': cv2.INTER_AREA,
'lanczos': cv2.INTER_LANCZOS4
}
def _scale_size(size, scale):
"""Rescale a size by a ratio.
Args:
size (tuple[int]): (w, h).
scale (float | tuple(float)): Scaling factor.
Returns:
tuple[int]: scaled size.
"""
if isinstance(scale, (float, int)):
scale = (scale, scale)
w, h = size
return int(w * float(scale[0]) + 0.5), int(h * float(scale[1]) + 0.5)
def rescale_size(old_size, scale, return_scale=False):
"""Calculate the new size to be rescaled to.
Args:
old_size (tuple[int]): The old size (w, h) of image.
scale (float | tuple[int]): The scaling factor or maximum size.
If it is a float number, then the image will be rescaled by this
factor, else if it is a tuple of 2 integers, then the image will
be rescaled as large as possible within the scale.
return_scale (bool): Whether to return the scaling factor besides the
rescaled image size.
Returns:
tuple[int]: The new rescaled image size.
"""
w, h = old_size
if isinstance(scale, (float, int)):
if scale <= 0:
raise ValueError(f'Invalid scale {scale}, must be positive.')
scale_factor = scale
elif isinstance(scale, tuple):
max_long_edge = max(scale)
max_short_edge = min(scale)
scale_factor = min(max_long_edge / max(h, w),
max_short_edge / min(h, w))
else:
raise TypeError(
f'Scale must be a number or tuple of int, but got {type(scale)}')
new_size = _scale_size((w, h), scale_factor)
if return_scale:
return new_size, scale_factor
return new_size
def imresize(img,
size,
return_scale=False,
interpolation='bilinear'):
"""Resize image to a given size.
Args:
img (ndarray): The input image.
size (tuple[int]): Target size (w, h).
return_scale (bool): Whether to return `w_scale` and `h_scale`.
interpolation (str): Interpolation method, accepted values are
"nearest", "bilinear", "bicubic", "area", "lanczos" for 'cv2'
backend, "nearest", "bilinear" for 'pillow' backend.
Returns:
tuple | ndarray: (`resized_img`, `w_scale`, `h_scale`) or
`resized_img`.
"""
h, w = img.shape[:2]
assert img.dtype == np.uint8, 'Pillow backend only support uint8 type'
pil_image = Image.fromarray(img)
pil_image = pil_image.resize(size, pillow_interp_codes[interpolation])
resized_img = np.array(pil_image)
if not return_scale:
return resized_img
w_scale = size[0] / w
h_scale = size[1] / h
return resized_img, w_scale, h_scale
def imrescale(img,
scale,
return_scale=False,
interpolation='bilinear'):
"""Resize image while keeping the aspect ratio.
Args:
img (ndarray): The input image.
scale (float | tuple[int]): The scaling factor or maximum size.
If it is a float number, then the image will be rescaled by this
factor, else if it is a tuple of 2 integers, then the image will
be rescaled as large as possible within the scale.
return_scale (bool): Whether to return the scaling factor besides the
rescaled image.
interpolation (str): Same as :func:`resize`.
Returns:
ndarray: The rescaled image.
"""
h, w = img.shape[:2]
new_size, scale_factor = rescale_size((w, h), scale, return_scale=True)
rescaled_img = imresize(
img, new_size, interpolation=interpolation)
if return_scale:
return rescaled_img, scale_factor
return rescaled_img
def impad(img, shape=None, padding=None, pad_val=None, padding_mode='constant'):
"""Pad the given image to a certain shape or pad on all sides with
specified padding mode and padding value.
Args:
img (ndarray): Image to be padded.
shape (tuple[int]): Expected padding shape (h, w). Default: None.
padding (int or tuple[int]): Padding on each border. If a single int is
provided this is used to pad all borders. If tuple of length 2 is
provided this is the padding on left/right and top/bottom
respectively. If a tuple of length 4 is provided this is the
padding for the left, top, right and bottom borders respectively.
Default: None. Note that `shape` and `padding` can not be both
set.
pad_val (Number | Sequence[Number]): Values to be filled in padding
areas when padding_mode is 'constant'. Default: 0.
padding_mode (str): Type of padding. Should be: constant, edge,
reflect or symmetric. Default: constant.
- constant: pads with a constant value, this value is specified
with pad_val.
- edge: pads with the last value at the edge of the image.
- reflect: pads with reflection of image without repeating the last
value on the edge. For example, padding [1, 2, 3, 4] with 2
elements on both sides in reflect mode will result in
[3, 2, 1, 2, 3, 4, 3, 2].
- symmetric: pads with reflection of image repeating the last value
on the edge. For example, padding [1, 2, 3, 4] with 2 elements on
both sides in symmetric mode will result in
[2, 1, 1, 2, 3, 4, 4, 3]
Returns:
ndarray: The padded image.
"""
assert (shape is not None) ^ (padding is not None)
if shape is not None:
width = max(shape[1] - img.shape[1], 0)
height = max(shape[0] - img.shape[0], 0)
padding = (0, 0, width, height)
# check padding
if isinstance(padding, tuple) and len(padding) in [2, 4]:
if len(padding) == 2:
padding = (padding[0], padding[1], padding[0], padding[1])
# check padding mode
assert padding_mode in ['constant', 'edge', 'reflect', 'symmetric']
border_type = {
'constant': cv2.BORDER_CONSTANT,
'edge': cv2.BORDER_REPLICATE,
'reflect': cv2.BORDER_REFLECT_101,
'symmetric': cv2.BORDER_REFLECT
}
img = cv2.copyMakeBorder(
img,
padding[1],
padding[3],
padding[0],
padding[2],
border_type[padding_mode],
value=pad_val)
return img, padding
| tao_deploy-main | nvidia_tao_deploy/cv/segformer/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.
"""Segformer loader."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from PIL import Image
import logging
import numpy as np
from nvidia_tao_deploy.cv.segformer.utils import imrescale, impad
from nvidia_tao_deploy.cv.unet.dataloader import UNetLoader
logging.basicConfig(format='%(asctime)s [%(levelname)s] %(name)s: %(message)s',
level="DEBUG")
logger = logging.getLogger(__name__)
class SegformerLoader(UNetLoader):
"""Segformer Dataloader."""
def __init__(self,
keep_ratio=True,
pad_val=0,
image_mean=None,
image_std=None,
**kwargs):
"""Init.
Args:
keep_ratio (bool): To keep the aspect ratio of image (padding will be used).
pad_val (int): Per-channel pixel value to pad for input image.
image_mean (list): image mean.
image_std (list): image standard deviation.
"""
super().__init__(**kwargs)
self.pad_val = pad_val
self.keep_ratio = keep_ratio
self.image_mean = image_mean
self.image_std = image_std
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
"""
if self.keep_ratio:
# mmcv style resize for image
image = np.asarray(image)
image = imrescale(image, (self.width, self.height))
image, _ = impad(image, shape=(self.height, self.width), pad_val=self.pad_val)
image = image.astype(self.dtype)
else:
image = image.resize((self.width, self.height), Image.BILINEAR)
image = np.asarray(image).astype(self.dtype)
# Segformer does not follow regular PyT preprocessing. No divide by 255
for i in range(len(self.image_mean)):
image[..., i] -= self.image_mean[i]
image[..., i] /= self.image_std[i]
image = np.transpose(image, (2, 0, 1))
if self.keep_ratio:
label = np.asarray(label)
label = imrescale(label, (self.width, self.height), interpolation='nearest')
# We always pad with 0 for labels
label, _ = impad(label, shape=(self.height, self.width), pad_val=0)
else:
label = label.resize((self.width, self.height), Image.BILINEAR)
label = np.asarray(label)
if self.input_image_type == "grayscale":
label = label / 255
label = np.where(label > 0.5, 1, 0)
label = label.astype(np.uint8)
return image, label
| tao_deploy-main | nvidia_tao_deploy/cv/segformer/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 Segformer Hydra."""
| tao_deploy-main | nvidia_tao_deploy/cv/segformer/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, Any
from dataclasses import dataclass, field
from omegaconf import MISSING
@dataclass
class NormConfig:
"""Configuration parameters for Normalization Preprocessing."""
type: str = "SyncBN" # Can be BN or SyncBN
requires_grad: bool = True # Whether to train the gamma beta parameters of BN
@dataclass
class TestModelConfig:
"""Configuration parameters for Inference."""
mode: str = "whole"
crop_size: Optional[List[int]] = None # Configurable
stride: Optional[List[int]] = None # Configurable
@dataclass
class LossDecodeConfig:
"""Configuration parameters for Loss."""
type: str = "CrossEntropyLoss"
use_sigmoid: bool = False
loss_weight: float = 1.0
@dataclass
class SegformerHeadConfig:
"""Configuration parameters for Segformer Head."""
# @subha TO DO: Look into align corners
in_channels: List[int] = field(default_factory=lambda: [64, 128, 320, 512]) # [64, 128, 320, 512], [32, 64, 160, 256]
in_index: List[int] = field(default_factory=lambda: [0, 1, 2, 3]) # No change
feature_strides: List[int] = field(default_factory=lambda: [4, 8, 16, 32]) # No change
channels: int = 128 # No change
dropout_ratio: float = 0.1
norm_cfg: NormConfig = NormConfig()
align_corners: bool = False
decoder_params: Dict[str, int] = field(default_factory=lambda: {"embed_dim": 768}) # 256, 512, 768 -> Configurable
loss_decode: LossDecodeConfig = LossDecodeConfig() # Non-configurable since there is only one loss
@dataclass
class MultiStepLRConfig:
"""Configuration parameters for Multi Step Optimizer."""
lr_steps: List[int] = field(default_factory=lambda: [15, 25])
lr_decay: float = 0.1
@dataclass
class PolyConfig:
"""Configuration parameters for Polynomial LR decay."""
# Check what is _delete_ is
policy: str = "poly"
warmup: str = 'linear'
warmup_iters: int = 1500
warmup_ratio: float = 1e-6
power: float = 1.0
min_lr: float = 0.0
by_epoch: bool = False
@dataclass
class LRConfig:
"""Configuration parameters for LR Scheduler."""
# Check what is _delete_ is
policy: str = "poly" # Non-configurable
warmup: str = 'linear' # Non-configurable
warmup_iters: int = 1500
warmup_ratio: float = 1e-6
power: float = 1.0
min_lr: float = 0.0
by_epoch: bool = False
@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 SFOptimConfig:
"""Optimizer config."""
type: str = "AdamW"
lr: float = 0.00006
betas: List[float] = field(default_factory=lambda: [0.9, 0.999])
weight_decay: float = 0.01
paramwise_cfg: ParamwiseConfig = ParamwiseConfig()
weight_decay: float = 5e-4
@dataclass
class BackboneConfig:
"""Configuration parameters for Backbone."""
type: str = "mit_b5"
@dataclass
class SFModelConfig:
"""SF model config."""
pretrained_model_path: Optional[str] = None
backbone: BackboneConfig = BackboneConfig()
decode_head: SegformerHeadConfig = SegformerHeadConfig()
test_cfg: TestModelConfig = TestModelConfig()
input_width: int = 512
input_height: int = 512
# Use the field parameter in order to define as dictionaries
@dataclass
class RandomCropCfg:
"""Configuration parameters for Random Crop Aug."""
crop_size: List[int] = field(default_factory=lambda: [512, 512]) # Non - configurable
cat_max_ratio: float = 0.75
@dataclass
class ResizeCfg:
"""Configuration parameters for Resize Preprocessing."""
img_scale: Optional[List[int]] = None # configurable
ratio_range: List[float] = field(default_factory=lambda: [0.5, 2.0])
keep_ratio: bool = True
@dataclass
class SFAugmentationConfig:
"""Augmentation config."""
# @subha: TO Do: Add some more augmentation configurations which were not used in Segformer (later)
random_crop: RandomCropCfg = RandomCropCfg()
resize: ResizeCfg = ResizeCfg()
random_flip: Dict[str, float] = field(default_factory=lambda: {'prob': 0.5})
color_aug: Dict[str, str] = field(default_factory=lambda: {'type': 'PhotoMetricDistortion'})
@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 PipelineConfig:
"""Configuration parameters for Validation Pipe."""
img_norm_cfg: ImgNormConfig = ImgNormConfig()
multi_scale: Optional[List[int]] = None
augmentation_config: SFAugmentationConfig = SFAugmentationConfig()
Pad: Dict[str, int] = field(default_factory=lambda: {'size_ht': 1024, 'size_wd': 1024, 'pad_val': 0, 'seg_pad_val': 255}) # Non-configurable. Set based on model_input
CollectKeys: List[str] = field(default_factory=lambda: ['img', 'gt_semantic_seg'])
@dataclass
class seg_class:
"""Indiv color."""
seg_class: str = "background"
mapping_class: str = "background"
label_id: int = 0
rgb: List[int] = field(default_factory=lambda: [255, 255, 255])
@dataclass
class SFDatasetConfig:
"""Dataset Config."""
img_dir: Any = MISSING
ann_dir: Any = MISSING
pipeline: PipelineConfig = PipelineConfig()
@dataclass
class SFDatasetExpConfig:
"""Dataset config."""
data_root: str = MISSING
img_norm_cfg: ImgNormConfig = ImgNormConfig()
train_dataset: SFDatasetConfig = SFDatasetConfig()
val_dataset: SFDatasetConfig = SFDatasetConfig()
test_dataset: SFDatasetConfig = SFDatasetConfig()
palette: Optional[List[seg_class]] = None
seg_class_default: seg_class = seg_class()
dataloader: str = "Dataloader"
img_suffix: Optional[str] = None
seg_map_suffix: Optional[str] = None
repeat_data_times: int = 2
batch_size: int = 2
workers_per_gpu: int = 2
shuffle: bool = True
input_type: str = "rgb"
@dataclass
class SFExpConfig:
"""Overall Exp Config for Segformer."""
manual_seed: int = 47
distributed: bool = True
# If needed, the next line can be commented
gpu_ids: List[int] = field(default_factory=lambda: [0])
MASTER_ADDR: str = "127.0.0.1"
MASTER_PORT: int = 631
@dataclass
class TrainerConfig:
"""Train Config."""
sf_optim: SFOptimConfig = SFOptimConfig()
lr_config: LRConfig = LRConfig()
grad_clip: float = 0.0
find_unused_parameters: bool = True
@dataclass
class SFTrainExpConfig:
"""Train experiment config."""
results_dir: Optional[str] = None
encryption_key: str = MISSING
exp_config: SFExpConfig = SFExpConfig()
trainer: TrainerConfig = TrainerConfig()
num_gpus: int = 1 # non configurable here
max_iters: int = 10
logging_interval: int = 1
checkpoint_interval: int = 1
resume_training_checkpoint_path: Optional[str] = None
validation_interval: Optional[int] = 1
validate: bool = False
@dataclass
class SFInferenceExpConfig:
"""Inference experiment config."""
encryption_key: str = MISSING
results_dir: Optional[str] = None
gpu_id: int = 0
checkpoint: Optional[str] = None
exp_config: SFExpConfig = SFExpConfig()
num_gpus: int = 1 # non configurable here
trt_engine: Optional[str] = None
@dataclass
class SFEvalExpConfig:
"""Inference experiment config."""
results_dir: Optional[str] = None
encryption_key: str = MISSING
gpu_id: int = 0
checkpoint: Optional[str] = None
exp_config: SFExpConfig = SFExpConfig()
num_gpus: int = 1 # non configurable here
trt_engine: 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 SFExportExpConfig:
"""Export experiment config."""
results_dir: Optional[str] = None
encryption_key: str = MISSING
verify: bool = True
simplify: bool = False
batch_size: int = 1
opset_version: int = 11
trt_engine: Optional[str] = None
checkpoint: Optional[str] = None
onnx_file: Optional[str] = None
exp_config: SFExpConfig = SFExpConfig()
trt_config: TrtConfig = TrtConfig()
num_gpus: int = 1 # non configurable here
input_channel: int = 3
input_width: int = 1024
input_height: int = 1024
@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 # Non-configurable
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: SFModelConfig = SFModelConfig()
dataset: SFDatasetExpConfig = SFDatasetExpConfig()
train: SFTrainExpConfig = SFTrainExpConfig()
evaluate: SFEvalExpConfig = SFEvalExpConfig()
inference: SFInferenceExpConfig = SFInferenceExpConfig()
gen_trt_engine: GenTrtEngineExpConfig = GenTrtEngineExpConfig()
export: SFExportExpConfig = SFExportExpConfig()
encryption_key: Optional[str] = None
results_dir: str = MISSING
| tao_deploy-main | nvidia_tao_deploy/cv/segformer/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.
"""Segformer 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.cv.segformer.engine_builder import SegformerEngineBuilder
from nvidia_tao_deploy.cv.common.hydra.hydra_runner import hydra_runner
from nvidia_tao_deploy.cv.segformer.hydra_config.default_config import ExperimentConfig
from nvidia_tao_deploy.cv.common.decorators import monitor_status
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__)
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='segformer', mode='gen_trt_engine')
def main(cfg: ExperimentConfig) -> None:
"""Convert encrypted uff or onnx model to TRT engine."""
trt_cfg = cfg.gen_trt_engine
# decrypt onnx or etlt
tmp_onnx_file, file_format = decode_model(trt_cfg['onnx_file'], cfg['encryption_key'])
engine_file = trt_cfg['trt_engine']
data_type = trt_cfg['tensorrt']['data_type']
workspace_size = trt_cfg['tensorrt']['workspace_size']
min_batch_size = trt_cfg['tensorrt']['min_batch_size']
opt_batch_size = trt_cfg['tensorrt']['opt_batch_size']
max_batch_size = trt_cfg['tensorrt']['max_batch_size']
batch_size = trt_cfg['batch_size']
num_channels = 3 # @scha: Segformer always has channel size 3
input_height, input_width = trt_cfg['input_height'], trt_cfg['input_width']
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 or data_type == 'int8':
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 = SegformerEngineBuilder(workspace=workspace_size,
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)
builder.create_network(tmp_onnx_file, file_format)
builder.create_engine(
output_engine_path,
data_type)
logging.info("Export finished successfully.")
if __name__ == '__main__':
main()
| tao_deploy-main | nvidia_tao_deploy/cv/segformer/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 Segformer scripts module."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
| tao_deploy-main | nvidia_tao_deploy/cv/segformer/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 os
import logging
import numpy as np
from PIL import Image
from tqdm.auto import tqdm
from nvidia_tao_deploy.cv.segformer.inferencer import SegformerInferencer
from nvidia_tao_deploy.cv.segformer.dataloader import SegformerLoader
from nvidia_tao_deploy.cv.segformer.utils import imrescale, impad
from nvidia_tao_deploy.cv.segformer.hydra_config.default_config import ExperimentConfig
from nvidia_tao_deploy.cv.unet.proto.utils import TargetClass, get_num_unique_train_ids
from nvidia_tao_deploy.cv.common.decorators import monitor_status
from nvidia_tao_deploy.cv.common.hydra.hydra_runner import hydra_runner
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 build_target_class_list(dataset):
"""Build a list of TargetClasses based on proto.
Arguments:
cost_function_config: CostFunctionConfig.
Returns:
A list of TargetClass instances.
"""
target_classes = []
orig_class_label_id_map = {}
for target_class in dataset.palette:
orig_class_label_id_map[target_class.seg_class] = target_class.label_id
class_label_id_calibrated_map = orig_class_label_id_map.copy()
for target_class in dataset.palette:
label_name = target_class.seg_class
train_name = target_class.mapping_class
class_label_id_calibrated_map[label_name] = orig_class_label_id_map[train_name]
train_ids = sorted(list(set(class_label_id_calibrated_map.values())))
train_id_calibrated_map = {}
for idx, tr_id in enumerate(train_ids):
train_id_calibrated_map[tr_id] = idx
class_train_id_calibrated_map = {}
for label_name, train_id in class_label_id_calibrated_map.items():
class_train_id_calibrated_map[label_name] = train_id_calibrated_map[train_id]
for target_class in dataset.palette:
target_classes.append(
TargetClass(target_class.seg_class, label_id=target_class.label_id,
train_id=class_train_id_calibrated_map[target_class.seg_class]))
for target_class in target_classes:
logging.debug("Label Id %d: Train Id %d", target_class.label_id, target_class.train_id)
return target_classes
@hydra_runner(
config_path=os.path.join(spec_root, "specs"),
config_name="infer", schema=ExperimentConfig
)
@monitor_status(name='segformer', mode='inference')
def main(cfg: ExperimentConfig) -> None:
"""Segformer TRT Inference."""
trt_infer = SegformerInferencer(cfg.inference.trt_engine, batch_size=cfg.dataset.batch_size)
c, h, w = trt_infer._input_shape
# Calculate number of classes from the spec file
target_classes = build_target_class_list(cfg.dataset)
num_classes = get_num_unique_train_ids(target_classes)
dl = SegformerLoader(
shape=(c, h, w),
image_data_source=[cfg.dataset.test_dataset.img_dir],
label_data_source=[cfg.dataset.test_dataset.ann_dir],
num_classes=num_classes,
dtype=trt_infer.inputs[0].host.dtype,
batch_size=cfg.dataset.batch_size,
is_inference=True,
input_image_type=cfg.dataset.input_type,
keep_ratio=cfg.dataset.test_dataset.pipeline.augmentation_config.resize.keep_ratio,
pad_val=cfg.dataset.test_dataset.pipeline.Pad['pad_val'],
image_mean=cfg.dataset.img_norm_cfg.mean,
image_std=cfg.dataset.img_norm_cfg.std)
# Create results directories
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)
vis_dir = os.path.join(results_dir, "vis_overlay")
os.makedirs(vis_dir, exist_ok=True)
mask_dir = os.path.join(results_dir, "mask_labels")
os.makedirs(mask_dir, exist_ok=True)
# Load classwise rgb value from palette
id_color_map = {}
for p in cfg.dataset.palette:
id_color_map[p['label_id']] = p['rgb']
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(cfg.dataset.batch_size) + cfg.dataset.batch_size * i]
for img_path, pred in zip(image_paths, y_pred):
img_file_name = os.path.basename(img_path)
# Store predictions as mask
output = Image.fromarray(pred.astype(np.uint8)).convert('P')
output.save(os.path.join(mask_dir, img_file_name))
output_palette = np.zeros((num_classes, 3), dtype=np.uint8)
for c_id, color in id_color_map.items():
output_palette[c_id] = color
output.putpalette(output_palette)
output = output.convert("RGB")
input_img = Image.open(img_path).convert('RGB')
orig_width, orig_height = input_img.size
input_img = np.asarray(input_img)
input_img = imrescale(input_img, (w, h))
input_img, padding = impad(input_img, shape=(h, w), pad_val=cfg.dataset.test_dataset.pipeline.Pad['pad_val'])
if cfg.dataset.input_type == "grayscale":
output = Image.fromarray(np.asarray(output).astype('uint8'))
else:
overlay_img = (np.asarray(input_img) / 2 + np.asarray(output) / 2).astype('uint8')
output = Image.fromarray(overlay_img)
# Crop out padded region and resize to original image
output = output.crop((0, 0, w - padding[2], h - padding[3]))
output = output.resize((orig_width, orig_height))
output = Image.fromarray(np.asarray(output).astype('uint8'))
output.save(os.path.join(vis_dir, img_file_name))
logging.info("Finished inference.")
if __name__ == '__main__':
main()
| tao_deploy-main | nvidia_tao_deploy/cv/segformer/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 os
import logging
import json
from tqdm.auto import tqdm
from collections import defaultdict
from nvidia_tao_deploy.cv.segformer.inferencer import SegformerInferencer
from nvidia_tao_deploy.cv.segformer.dataloader import SegformerLoader
from nvidia_tao_deploy.cv.segformer.hydra_config.default_config import ExperimentConfig
from nvidia_tao_deploy.cv.common.hydra.hydra_runner import hydra_runner
from nvidia_tao_deploy.cv.unet.proto.utils import TargetClass, get_num_unique_train_ids
from nvidia_tao_deploy.metrics.semantic_segmentation_metric import SemSegMetric
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__)))
def get_label_train_dic(target_classes):
"""Function to get mapping between class and train ids."""
label_train_dic = {}
for target in target_classes:
label_train_dic[target.label_id] = target.train_id
return label_train_dic
def build_target_class_list(dataset):
"""Build a list of TargetClasses based on proto.
Arguments:
cost_function_config: CostFunctionConfig.
Returns:
A list of TargetClass instances.
"""
target_classes = []
orig_class_label_id_map = {}
for target_class in dataset.palette:
orig_class_label_id_map[target_class.seg_class] = target_class.label_id
class_label_id_calibrated_map = orig_class_label_id_map.copy()
for target_class in dataset.palette:
label_name = target_class.seg_class
train_name = target_class.mapping_class
class_label_id_calibrated_map[label_name] = orig_class_label_id_map[train_name]
train_ids = sorted(list(set(class_label_id_calibrated_map.values())))
train_id_calibrated_map = {}
for idx, tr_id in enumerate(train_ids):
train_id_calibrated_map[tr_id] = idx
class_train_id_calibrated_map = {}
for label_name, train_id in class_label_id_calibrated_map.items():
class_train_id_calibrated_map[label_name] = train_id_calibrated_map[train_id]
for target_class in dataset.palette:
target_classes.append(
TargetClass(target_class.seg_class, label_id=target_class.label_id,
train_id=class_train_id_calibrated_map[target_class.seg_class]))
for target_class in target_classes:
logging.debug("Label Id %d: Train Id %d", target_class.label_id, target_class.train_id)
return target_classes
@hydra_runner(
config_path=os.path.join(spec_root, "specs"),
config_name="infer", schema=ExperimentConfig
)
@monitor_status(name='segformer', mode='evaluation')
def main(cfg: ExperimentConfig) -> None:
"""Segformer TRT Evaluation."""
trt_infer = SegformerInferencer(cfg.evaluate.trt_engine, batch_size=cfg.dataset.batch_size)
c, h, w = trt_infer._input_shape
# Calculate number of classes from the spec file
target_classes = build_target_class_list(cfg.dataset)
label_id_train_id_mapping = get_label_train_dic(target_classes)
num_classes = get_num_unique_train_ids(target_classes)
dl = SegformerLoader(
shape=(c, h, w),
image_data_source=[cfg.dataset.test_dataset.img_dir],
label_data_source=[cfg.dataset.test_dataset.ann_dir],
num_classes=num_classes,
dtype=trt_infer.inputs[0].host.dtype,
batch_size=cfg.dataset.batch_size,
is_inference=False,
input_image_type=cfg.dataset.input_type,
keep_ratio=cfg.dataset.test_dataset.pipeline.augmentation_config.resize.keep_ratio,
pad_val=cfg.dataset.test_dataset.pipeline.Pad['pad_val'],
image_mean=cfg.dataset.img_norm_cfg.mean,
image_std=cfg.dataset.img_norm_cfg.std)
# Create results directories
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)
# Load label mapping
label_mapping = defaultdict(list)
for p in cfg.dataset.palette:
label_mapping[p['label_id']].append(p['seg_class'])
eval_metric = SemSegMetric(num_classes=num_classes,
train_id_name_mapping=label_mapping,
label_id_train_id_mapping=label_id_train_id_mapping)
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)
metrices = eval_metric.get_evaluation_metrics(gt_labels, pred_labels)
with open(os.path.join(results_dir, "results.json"), "w", encoding="utf-8") as f:
json.dump(str(metrices["results_dic"]), f)
logging.info("Finished evaluation.")
if __name__ == '__main__':
main()
| tao_deploy-main | nvidia_tao_deploy/cv/segformer/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 segformer."""
| tao_deploy-main | nvidia_tao_deploy/cv/segformer/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 argparse
from nvidia_tao_deploy.cv.segformer 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(
"segformer",
add_help=True,
description="Train Adapt Optimize Deploy entrypoint for Segformer"
)
# Build list of subtasks by inspecting the scripts package.
subtasks = get_subtasks(scripts)
# Parse the arguments and launch the subtask.
launch(parser, subtasks, network="segformer")
if __name__ == '__main__':
main()
| tao_deploy-main | nvidia_tao_deploy/cv/segformer/entrypoint/segformer.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.
"""OCDNet 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 OCDNetEngineBuilder(EngineBuilder):
"""Parses an UFF/ONNX graph and builds a TensorRT engine from it."""
def __init__(
self,
width,
height,
img_mode,
batch_size=None,
data_format="channels_first",
**kwargs
):
"""Init.
Args:
data_format (str): data_format.
"""
super().__init__(batch_size=batch_size, **kwargs)
self._data_format = data_format
self.width = width
self.height = height
self.img_mode = img_mode
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
for i, inputs in enumerate(onnx_inputs):
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]
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],
self.height, self.width)
real_shape_opt = (self.opt_batch_size, input_shape[1],
self.height, self.width)
real_shape_max = (self.max_batch_size, input_shape[1],
self.height, self.width)
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 OCDNet is not supported")
def set_calibrator(self,
inputs=None,
calib_cache=None,
calib_input=None,
calib_num_images=1,
calib_batch_size=8,
calib_data_file=None,
image_mean=None):
"""Simple function to set an Tensorfile based int8 calibrator.
Args:
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] + [self.network.get_input(0).shape[1]] + [self.height] + [self.width]
calib_dtype = trt.nptype(inputs[0].dtype)
logger.info(calib_shape)
logger.info(calib_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="OCDNet"))
| tao_deploy-main | nvidia_tao_deploy/cv/ocdnet/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 OCDNet."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
| tao_deploy-main | nvidia_tao_deploy/cv/ocdnet/__init__.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.