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. from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import shutil import tempfile import mock import numpy as np from parameterized import parameterized import pytest import tensorflow as tf from nvidia_tao_tf1.blocks.multi_source_loader.sources.sqlite_data_source import ( SqliteDataSource, ) from nvidia_tao_tf1.blocks.multi_source_loader.types import ( Bbox2DLabel, FEATURE_CAMERA, FEATURE_SESSION, Images2DReference, LABEL_MAP, LABEL_OBJECT, Polygon2DLabel, ) from modulus.dataloader.testdata.db_test_builder import DbTestBuilder from nvidia_tao_tf1.core.coreobject import deserialize_tao_object def _expected_frames( schema_version, skip_empty=False, sequence_length=None, include_unlabeled=False ): sequence_length = sequence_length if schema_version < 8: return 24 # V8 example dataset has extra frames to exercise empty and unlabeled frame functionality. if skip_empty: num_frames = 24 elif include_unlabeled: num_frames = 27 else: num_frames = 26 if sequence_length: return (num_frames // sequence_length) * sequence_length return num_frames class SqliteDataSourceTest(tf.test.TestCase): @classmethod def setUpClass(cls): cls._db_builder = DbTestBuilder() @classmethod def tearDownClass(cls): cls._db_builder.cleanup() def _sqlite_path(self, schema=None): return self.__class__._db_builder.get_db("test_dataset", schema) def _split_path(self, schema=None): return self.__class__._db_builder.get_db("test_dataset_split", schema) def _mixed_res_path(self): return self.__class__._db_builder.get_db("test_dataset_mixed_res", 8) def setUp(self): self.export_path = tempfile.mkdtemp() def tearDown(self): shutil.rmtree(self.export_path) @parameterized.expand([[5], [8]]) def test_raises_on_when_image_dir_does_not_exist(self, schema): with pytest.raises(ValueError) as exception: SqliteDataSource( sqlite_path=self._sqlite_path(schema), image_dir="/no/such/image_dir", export_format=SqliteDataSource.FORMAT_RGB_HALF_DWSOFTISP, ) assert "/no/such/image_dir" in str(exception) def test_raises_on_when_database_does_not_exist(self): with pytest.raises(ValueError) as exception: SqliteDataSource( sqlite_path="/no/such/dataset.sqlite", image_dir=self.export_path, export_format=SqliteDataSource.FORMAT_RGB_HALF_DWSOFTISP, ) assert "/no/such/dataset.sqlite" in str(exception) @parameterized.expand( [ ( SqliteDataSource.FORMAT_RGB_HALF_DWSOFTISP, None, 142200, b"0ce4c786-92eb-5a2d-8e95-fffbc30ebd1a", (960,), (604,), (3,), (2,), 19, 5, False, ), ( SqliteDataSource.FORMAT_JPEG, 4, [142200, 33960, 101460, 222960], [ b"0ce4c786-92eb-5a2d-8e95-fffbc30ebd1a", b"2b3899b9-5d2c-50f4-8dab-0bf642bc4158", b"2b3899b9-5d2c-50f4-8dab-0bf642bc4158", b"418acd69-a14d-5486-a06e-ec2a349e06cd", ], (4, 960), (4, 604), (4,), (3,), 33, 5, False, ), ( SqliteDataSource.FORMAT_RGB_HALF_DWSOFTISP, None, 142200, b"0ce4c786-92eb-5a2d-8e95-fffbc30ebd1a", (960,), (604,), (3,), (2,), 19, 8, False, ), ( SqliteDataSource.FORMAT_JPEG, 4, [142200, 33960, 101460, 222960], [ b"0ce4c786-92eb-5a2d-8e95-fffbc30ebd1a", b"2b3899b9-5d2c-50f4-8dab-0bf642bc4158", b"2b3899b9-5d2c-50f4-8dab-0bf642bc4158", b"418acd69-a14d-5486-a06e-ec2a349e06cd", ], (4, 960), (4, 604), (4,), (3,), 33, 8, False, ), ( SqliteDataSource.FORMAT_RGB_HALF_DWSOFTISP, None, 142200, b"0ce4c786-92eb-5a2d-8e95-fffbc30ebd1a", (960,), (604,), (3,), (2,), 19, 8, True, ), ( SqliteDataSource.FORMAT_JPEG, 4, [142200, 33960, 101460, 222960], [ b"0ce4c786-92eb-5a2d-8e95-fffbc30ebd1a", b"2b3899b9-5d2c-50f4-8dab-0bf642bc4158", b"2b3899b9-5d2c-50f4-8dab-0bf642bc4158", b"418acd69-a14d-5486-a06e-ec2a349e06cd", ], (4, 960), (4, 604), (4,), (3,), 33, 8, True, ), ] ) def test_end_to_end( self, export_format, sequence_length, expected_frame_number, expected_sequence_id, expected_canvas_width, expected_canvas_height, expected_map_vertices_dims, expected_map_dims, expected_num_objects, schema, include_unlabeled, ): def _make_frame_id(sequence_id, frame_number): return os.path.join( sequence_id.decode(), "video_B0_FC_60", str(frame_number) ) source = SqliteDataSource( sqlite_path=self._sqlite_path(schema), image_dir=self.export_path, export_format=export_format, supported_labels=["POLYGON", "BOX"], include_unlabeled_frames=include_unlabeled, ) source.set_sequence_length(sequence_length) if sequence_length is None: expected_frame_id = [ _make_frame_id(expected_sequence_id, expected_frame_number) ] else: expected_frame_id = [ [ _make_frame_id(expected_sequence_id[i], expected_frame_number[i]) for i in range(sequence_length) ] ] dataset = source() iterator = tf.compat.v1.data.make_initializable_iterator(dataset) get_next = iterator.get_next() with self.test_session() as sess: sess.run([tf.compat.v1.tables_initializer(), iterator.initializer]) example = sess.run(get_next) image_references = example.instances[FEATURE_CAMERA] session = example.instances[FEATURE_SESSION] # Check image related portion. assert isinstance(image_references, Images2DReference) assert expected_canvas_height == image_references.canvas_shape.height.shape assert expected_canvas_width == image_references.canvas_shape.width.shape np.testing.assert_equal(session.uuid, expected_sequence_id) np.testing.assert_equal(session.frame_number, expected_frame_number) # Check LABEL_MAP. label_map = example.labels[LABEL_MAP] assert isinstance(label_map, Polygon2DLabel) assert ( expected_map_vertices_dims == label_map.vertices.coordinates.dense_shape.shape ) assert expected_map_dims == label_map.classes.dense_shape.shape assert expected_map_dims == label_map.attributes.dense_shape.shape assert (604,) == label_map.vertices.canvas_shape.height assert (960,) == label_map.vertices.canvas_shape.width # Check LABEL_OBJECT. label_object = example.labels[LABEL_OBJECT] assert isinstance(label_object, Bbox2DLabel) actual_frame_id = np.vectorize(lambda s: s.decode())(label_object.frame_id) np.testing.assert_equal(actual_frame_id, expected_frame_id) # Check that LTRB order is preserved, and no bounding boxes whose dimensions are less # than 1.0 pixels are included. ltrb_coords = label_object.vertices.coordinates.values.reshape([-1, 4]) self.assertAllGreaterEqual(ltrb_coords[:, 2] - ltrb_coords[:, 0], 1.0) self.assertAllGreaterEqual(ltrb_coords[:, 3] - ltrb_coords[:, 1], 1.0) # Check that the rest of the features have sane shapes. for feature_name in Bbox2DLabel.TARGET_FEATURES: feature_tensor = getattr(label_object, feature_name) if feature_name == "vertices": assert ( len(feature_tensor.coordinates.values) // 4 == expected_num_objects ) elif feature_name in {"world_bbox_z", "truncation"}: # These are features not directly found in HumanLoop exports, but that are # legacy that we carry around for BW compatibility's sake with DriveNet # TFRecords. assert isinstance(feature_tensor, np.ndarray) assert feature_tensor.size == 0 # Un-populated field. else: assert len(feature_tensor.values) == expected_num_objects @parameterized.expand([[1, 5], [4, 5], [5, 5], [1, 8], [4, 8], [5, 8]]) def test_length_and_image_size(self, sequence_length, schema): source = SqliteDataSource( sqlite_path=self._sqlite_path(schema), image_dir=self.export_path, export_format=SqliteDataSource.FORMAT_RGB_HALF_DWSOFTISP, supported_labels=["POLYLINE", "BOX"], ) source.set_sequence_length(sequence_length) source.initialize() assert _expected_frames( schema, sequence_length=sequence_length ) // sequence_length == len(source) assert 960 == source.max_image_width assert 604 == source.max_image_height @parameterized.expand( [ (4, 1, False, 5), (4, 1, True, 5), (3, 2, False, 5), (3, 0, True, 5), (4, 1, False, 8), (4, 1, True, 8), (3, 2, False, 8), (3, 0, True, 8), ] ) def test_pseudo_shard_setting(self, num_shards, shard_id, pseudo_sharding, schema): source = SqliteDataSource( sqlite_path=self._sqlite_path(schema), image_dir=self.export_path, export_format=SqliteDataSource.FORMAT_RGB_HALF_DWSOFTISP, supported_labels=["POLYLINE", "BOX"], ) source.set_shard(num_shards, shard_id, pseudo_sharding=pseudo_sharding) source.initialize() assert _expected_frames(schema) == len(source) assert source._dataset._num_shards == num_shards assert source._dataset._shard_id == shard_id assert source._dataset._pseudo_sharding == pseudo_sharding @parameterized.expand( [ (["train"], 19, 5), ([b"val0"], 2, 5), (["val1"], 3, 5), (["val0", "val1"], 5, 5), (["train", "val0", "val1"], 24, 5), (["train"], 21, 8), ([b"val0"], 2, 8), (["val1"], 3, 8), (["val0", "val1"], 5, 8), (["train", "val0", "val1"], 26, 8), ] ) def test_split(self, split_tags, expected_length, schema): source = SqliteDataSource( sqlite_path=self._sqlite_path(schema), image_dir=self.export_path, export_format=SqliteDataSource.FORMAT_RGB_HALF_DWSOFTISP, split_db_filename=self._split_path(), split_tags=split_tags, supported_labels=["POLYLINE", "BOX"], ) source.initialize() assert expected_length == len(source) assert 960 == source.max_image_width assert 604 == source.max_image_height @parameterized.expand([[5], [8]]) def test_zero_sampling_ratio_defaults_to_one(self, schema): source = SqliteDataSource( sqlite_path=self._sqlite_path(schema), image_dir=self.export_path, export_format=SqliteDataSource.FORMAT_RGB_HALF_DWSOFTISP, ) assert source.sample_ratio == 1.0 @parameterized.expand([[5], [8]]) def test_sampling_ratio_is_set(self, schema): sample_ratio = 0.2 source = SqliteDataSource( sqlite_path=self._sqlite_path(schema), image_dir=self.export_path, export_format=SqliteDataSource.FORMAT_RGB_HALF_DWSOFTISP, sample_ratio=sample_ratio, ) assert source.sample_ratio == sample_ratio def test_query_split_tags(self): tags = SqliteDataSource.query_split_tags(self._split_path()) assert tags == ["train", "val0", "val1"] @parameterized.expand( [[None, 5], [True, 5], [False, 5], [None, 8], [True, 8], [False, 8]] ) def test_skip_empty_frames_config(self, skip_empty_frames, schema): source = SqliteDataSource( sqlite_path=self._sqlite_path(schema), image_dir=self.export_path, export_format=SqliteDataSource.FORMAT_RGB_HALF_DWSOFTISP, sample_ratio=1.0, skip_empty_frames=skip_empty_frames, ) source.initialize() hldataset = source._dataset if skip_empty_frames: self.assertTrue(hldataset.skip_empty_frames) else: self.assertFalse(hldataset.skip_empty_frames) @parameterized.expand([[5], [8]]) def test_no_subset_size(self, schema): source = SqliteDataSource( sqlite_path=self._sqlite_path(schema), image_dir=self.export_path, export_format=SqliteDataSource.FORMAT_RGB_HALF_DWSOFTISP, supported_labels=["POLYGON", "BOX"], subset_size=None, ) source.initialize() assert source.num_samples == _expected_frames(schema) @parameterized.expand([[5], [8]]) def test_serialization_and_deserialization(self, schema): """Test TAOObject serialization and deserialization on SqliteDataSource.""" source = SqliteDataSource( sqlite_path=self._sqlite_path(schema), image_dir=self.export_path, export_format=SqliteDataSource.FORMAT_RGB_HALF_DWSOFTISP, sample_ratio=0.1, ) source.initialize() source_dict = source.serialize() deserialized_source = deserialize_tao_object(source_dict) self.assertEqual(source.sqlite_path, deserialized_source.sqlite_path) self.assertEqual(source.image_dir, deserialized_source.image_dir) self.assertEqual(source.export_format, deserialized_source.export_format) self.assertEqual(source.sample_ratio, deserialized_source.sample_ratio) self.assertEqual(source.sample_ratio, deserialized_source.sample_ratio) @parameterized.expand([[5], [8]]) def test_subset_size_positive_and_restricts(self, schema): source = SqliteDataSource( sqlite_path=self._sqlite_path(schema), image_dir=self.export_path, export_format=SqliteDataSource.FORMAT_RGB_HALF_DWSOFTISP, supported_labels=["POLYGON", "BOX"], subset_size=2, ) source.initialize() assert source.num_samples == 2 @parameterized.expand([[5], [8]]) def test_subset_size_positive_and_large(self, schema): source = SqliteDataSource( sqlite_path=self._sqlite_path(schema), image_dir=self.export_path, export_format=SqliteDataSource.FORMAT_RGB_HALF_DWSOFTISP, supported_labels=["POLYGON", "BOX"], subset_size=1024768, # > dataset's size (24) ) source.initialize() assert source.num_samples == _expected_frames(schema) @parameterized.expand([[5], [8]]) def test_subset_size_zero(self, schema): source = SqliteDataSource( sqlite_path=self._sqlite_path(schema), image_dir=self.export_path, export_format=SqliteDataSource.FORMAT_RGB_HALF_DWSOFTISP, supported_labels=["POLYGON", "BOX"], subset_size=0, ) source.initialize() assert source.num_samples == _expected_frames(schema) @parameterized.expand([[5], [8]]) def test_subset_size_negative(self, schema): with pytest.raises(ValueError): SqliteDataSource( sqlite_path=self._sqlite_path(schema), image_dir=self.export_path, export_format=SqliteDataSource.FORMAT_RGB_HALF_DWSOFTISP, supported_labels=["POLYGON", "BOX"], subset_size=-13, ) @parameterized.expand([[5], [8]]) def test_oversample_is_called(self, schema): oversampling_strategy = mock.Mock() oversampling_strategy.oversample.side_effect = ( lambda frame_groups, count_lookup: frame_groups ) sqlite_data_source = SqliteDataSource( sqlite_path=self._sqlite_path(schema), image_dir=self.export_path, export_format=SqliteDataSource.FORMAT_RGB_HALF_DWSOFTISP, supported_labels=["POLYGON", "BOX"], oversampling_strategy=oversampling_strategy, ) sqlite_data_source() oversampling_strategy.oversample.assert_called() @parameterized.expand([[5], [8]]) def test_raise_on_missing_split_tag(self, schema): with pytest.raises(ValueError) as value_error: source = SqliteDataSource( sqlite_path=self._sqlite_path(schema), image_dir=self.export_path, export_format=SqliteDataSource.FORMAT_RGB_HALF_DWSOFTISP, split_db_filename=self._split_path(), split_tags=["non-existent_tag"], supported_labels=["POLYLINE", "BOX"], ) source.initialize() self.assertIn("'non-existent_tag'] not in", str(value_error)) def test_raise_on_additional_conditions_referencing_multiple_tables(self): for bad_condition in [["sequences features"], ["no valid tables"]]: with pytest.raises(ValueError) as value_error: SqliteDataSource( sqlite_path=self._sqlite_path(8), image_dir=self.export_path, export_format=SqliteDataSource.FORMAT_RGB_HALF_DWSOFTISP, additional_conditions=bad_condition, ) self.assertIn("Each condition can only ", str(value_error)) # Valid test case SqliteDataSource( sqlite_path=self._sqlite_path(8), image_dir=self.export_path, export_format=SqliteDataSource.FORMAT_RGB_HALF_DWSOFTISP, additional_conditions=["sequences.id=1", "features.id=1", "features.id=2"], ) def test_additional_sequence_conditions(self): # Will default to biggest resolution. Whether or not we should raise an error is an open # question. source = SqliteDataSource( sqlite_path=self._mixed_res_path(), image_dir=self.export_path, export_format=SqliteDataSource.FORMAT_RGB_HALF_DWSOFTISP, ) assert source.max_image_width == 1924 assert source.max_image_height == 1084 # Will filter and only get the sequences that are the smaller dimension. source = SqliteDataSource( sqlite_path=self._mixed_res_path(), image_dir=self.export_path, export_format=SqliteDataSource.FORMAT_RGB_HALF_DWSOFTISP, additional_conditions=["sequences.width = 1920"], ) assert source.max_image_width == 960 assert source.max_image_height == 604
tao_tensorflow1_backend-main
nvidia_tao_tf1/blocks/multi_source_loader/sources/sqlite_data_source_test.py
# Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved. """Parser for 'BOX' type labels as provided via modulus's SqlDataset.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from nvidia_tao_tf1.blocks.multi_source_loader.types import Bbox2DLabel from nvidia_tao_tf1.blocks.multi_source_loader.types import ( Coordinates2DWithCounts, ) import modulus.dataloader.humanloop_sqlite_dataset as hl_sql from modulus.types import Canvas2D class BboxFeatureProcessor(hl_sql.FeatureProcessor): """Feature Processor used with humanloop_sqlite_dataset to augment BOX labels.""" def __init__(self, min_width=1.0, min_height=1.0): """Constructor: min_width and min_height refer to the minimum bounding box size.""" self._min_width = min_width self._min_height = min_height def add_fields(self, example): """Add auxiliary fields to the 'BOX' label.""" example.labels["BOX"]["is_cvip"] = hl_sql.create_derived_field( tf.int32, shape=None ) example.labels["BOX"]["non_facing"] = hl_sql.create_derived_field( tf.int32, shape=None ) def filter(self, example_col_idx, dtype, row): """Filter label rows by removing bounding boxes that are too small.""" if dtype == "BOX": vertices = row[example_col_idx.labels["BOX"]["vertices"]] if len(vertices) != 2: return False width = abs(vertices[1][0] - vertices[0][0]) height = abs(vertices[1][1] - vertices[0][1]) return width >= self._min_width and height >= self._min_height return True def map(self, example_col_idx, dtype, row): """ Populate non_facing and is_cvip attributes for BOX label. Args: example_col_idx (namedtuple): example data structure, where fields are integers that correspond to the index of the value in 'row' dtype (str): label type, such as 'BOX' or 'POLYGON'. row (list): flat list of values from the database for one label. Use example_col_idx to find which element corresponds to which field in the 'example'. Return: modified 'frame'. """ label_idx = example_col_idx.labels if dtype == "BOX": attrs = row[label_idx["BOX"]["attributes"]] row[label_idx["BOX"]["non_facing"]] = 1 if "non facing" in attrs else 0 row[label_idx["BOX"]["is_cvip"]] = ( 1 if ("cvip" in attrs or "cipo" in attrs) else 0 ) return row class SqliteBboxLabelParser(object): """Parser for converting Modulus Examples into DriveNet compatible Dlav/common Examples.""" def __init__(self): """Construct a parser for translating HumanLoop sqlite exports to Bbox2DLabel.""" pass def __call__(self, data): """Convert labels to DriveNet format. Args: data (modulus.types.Example): Modulus Example namedtuple. Returns: bbox_label (Bbox2DLabel). """ bbox_label_kwargs = {field_name: [] for field_name in Bbox2DLabel._fields} bbox_label_kwargs["frame_id"] = [data.instances["uri"]] width = data.instances["shape"].width height = data.instances["shape"].height box = data.labels["BOX"] # Parse bbox coordinates. bbox_label_kwargs["vertices"] = Coordinates2DWithCounts( coordinates=box["vertices"], canvas_shape=Canvas2D(height=height, width=width), vertices_count=box["num_vertices"], ) # Parse other fields guaranteed to exist for 'BOX'. bbox_label_kwargs["object_class"] = box["classifier"] bbox_label_kwargs["back"] = box["back"] bbox_label_kwargs["front"] = box["front"] # The end-to-end behavior of the DataLoader is quite 'unfortunate', for this case. # The fields in the `Example.labels` produced by the SQLite are declared 'statically' by # some predefined fields in the HumanloopSqliteDataset, and by each FrameProcessor's # add_fields() method. As such, their types are also declared, and used in the # rest of the TensorFlow graph. Therefore, one cannot replace an existing field such as # 'occlusion' with a data type different than what it might be used for by dependent ops. # E.g. for legacy reasons, DriveNet would like to consume 'occlusion' as an int (!), # but the field is a string in SQLite (e.g. 'leftBottom'). If DriveNetLegacyMapper were # to replace the pre-existing 'occlusion' field with one of dtype tf.int32, then all values # will default to 0. If one were to replace it with a tf.string entry, then, other parts of # the graph that assumed int values would raise errors (since the part that maps the string # values to ints happens at 'runtime' and is not known to the TF graph). occlusion_key = ( "occlusion" if "mapped_occlusion" not in box else "mapped_occlusion" ) bbox_label_kwargs["occlusion"] = box[occlusion_key] truncation_key = ( "truncation" if "mapped_truncation" not in box else "mapped_truncation" ) bbox_label_kwargs["truncation_type"] = box[truncation_key] bbox_label_kwargs["is_cvip"] = box["is_cvip"] bbox_label_kwargs["non_facing"] = box["non_facing"] # Parse the optional source_weight for each frame, which may not exist. if "source_weight" in data.instances: bbox_label_kwargs["source_weight"] = [data.instances["source_weight"]] bbox_label = Bbox2DLabel(**bbox_label_kwargs) return bbox_label
tao_tensorflow1_backend-main
nvidia_tao_tf1/blocks/multi_source_loader/sources/sqlite_bbox_label_parser.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. """Data source with synthetic data for testing.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from nvidia_tao_tf1.blocks.multi_source_loader.sources.data_source import ( DataSource, ) from nvidia_tao_tf1.core.coreobject import save_args class SyntheticDataSource(DataSource): """DataSource with synthetic data.""" @save_args def __init__( self, example_count, template=None, template_fn=None, tracker_dict=None, **kwargs ): """Initialize the empty Pipeline, the number of examples, and shape of the image. Args: example_count (int): number of examples to output by the dataset. template (T): Tensor or collection of nested tensors, copies of which will be generated by this data source. T must be a type supported by tf.data.Dataset. template_fn (function -> T): A function that returns a template. See `template` for description. When template is passed in via template_fn, it is guaranteed to be in the same graph as the tf.data.Dataset this source creates. tracker_dict (dict) (optional) dictionary. This data loader will set "call_count" field in the dictionary. Useful for tests. """ super(SyntheticDataSource, self).__init__(**kwargs) if template is None and template_fn is None: raise ValueError("Template value or template_fn not specified.") self._example_count = example_count self._template = template self._template_fn = template_fn self._tracker_dict = tracker_dict def __len__(self): """Return the number of synthetic examples.""" return self._example_count @property def parse_example(self): """Parse example.""" return lambda dataset: dataset def call(self): """ Return a tf.data.Dataset with synthetic data. Returns: (tf.data.Dataset<T>): Dataset that yields example_count copies of the template value provided in the constructor. """ if self._template_fn: ds = tf.data.Dataset.from_tensors(self._template_fn()) else: ds = tf.data.Dataset.from_tensors(self._template) def _update_tracker(): """Updated call_count field tracker_dict by 1.""" self._tracker_dict["call_count"] = ( self._tracker_dict.get("call_count", 0) + 1 ) return self._tracker_dict["call_count"] def _map(x): tf.compat.v1.py_func(_update_tracker, [], (tf.int64)) return x if self._tracker_dict is not None: ds = ds.map(_map) return ds.repeat(self._example_count) @property def image_dtype(self): """Return the default dtype of images.""" return tf.float32
tao_tensorflow1_backend-main
nvidia_tao_tf1/blocks/multi_source_loader/sources/synthetic_data_source.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. """Tests for DataSource.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import unittest import mock import pytest import tensorflow as tf from nvidia_tao_tf1.blocks.multi_source_loader.sources.data_source import ( DataSource, ) from nvidia_tao_tf1.core.coreobject import deserialize_tao_object class TestDataSource(DataSource): """Mocked DataSource class for testing.""" def __init__(self, sample_ratio=1.0, extension=".jpg"): super(TestDataSource, self).__init__( sample_ratio=sample_ratio, preprocessing=[], extension=extension ) def call(self): """Returns a Mock object for testing.""" return mock.Mock() def __len__(self): return 1 class JpegDataSource(DataSource): """Mocked Datasource with extension being .jpeg""" def __init__(self): super().__init__(extension=".jpeg") def call(self): """Returns a Mock object for testing.""" return mock.Mock() def __len__(self): return 1 class PNGDataSource(DataSource): """Mocked Datasource with extension being .jpeg""" def __init__(self): super().__init__(extension=".png") def call(self): """Returns a Mock object for testing.""" return mock.Mock() def __len__(self): return 1 class FP16DataSource(DataSource): """Mocked Datasource with extension being .fp16""" def __init__(self): super().__init__(extension=".fp16") def call(self): """Returns a Mock object for testing.""" return mock.Mock() def __len__(self): return 1 class FP32DataSource(DataSource): """Mocked Datasource with extension being .fp32""" def __init__(self): super().__init__(extension=".fp32") def call(self): """Returns a Mock object for testing.""" def __len__(self): return 1 class DataSourceTest(unittest.TestCase): def test_stringifies(self): source = TestDataSource() self.assertEqual( " - samples: 1\n" " - sample ratio: 1.0\n" " - extension: .jpg\n", str(source), ) @staticmethod @mock.patch( "nvidia_tao_tf1.blocks.multi_source_loader.sources.data_source.print" ) def test_summarizes_to_stdout(mocked_print): source = TestDataSource() source.summary() mocked_print.assert_has_calls( [ mock.call(" - samples: 1"), mock.call(" - sample ratio: 1.0"), mock.call(" - extension: .jpg"), ] ) @staticmethod def test_summarizes_using_print_fn(): source = TestDataSource() print_fn = mock.Mock() source.summary(print_fn=print_fn) print_fn.assert_has_calls( [ mock.call(" - samples: 1"), mock.call(" - sample ratio: 1.0"), mock.call(" - extension: .jpg"), ] ) def test_serialization_and_deserialization(self): """Test TAOObject serialization and deserialization on TestDataSource.""" source = TestDataSource() source_dict = source.serialize() deserialized_source = deserialize_tao_object(source_dict) self.assertEqual(str(source), str(deserialized_source)) def test_raises_error_with_negative_sample_ratio(self): with pytest.raises(ValueError) as exception: TestDataSource(sample_ratio=-1.0) assert str(exception.value) == "Sample ratio -1.0 cannot be < 0." @pytest.mark.parametrize( "data_source, expected_image_dtype", [ (JpegDataSource(), tf.uint8), (FP16DataSource(), tf.float16), (FP32DataSource(), tf.float32), (PNGDataSource(), tf.uint8), ], ) def test_image_dtype(data_source, expected_image_dtype): assert data_source.image_dtype == expected_image_dtype
tao_tensorflow1_backend-main
nvidia_tao_tf1/blocks/multi_source_loader/sources/data_source_test.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. """Data source for video files.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from functools import lru_cache import cv2 import tensorflow as tf from nvidia_tao_tf1.blocks.multi_source_loader import types from nvidia_tao_tf1.blocks.multi_source_loader.sources import data_source from nvidia_tao_tf1.core.coreobject import save_args class VideoDataSource(data_source.DataSource): """DataSource for reading frames from video files.""" @save_args def __init__(self, video_path, **kwargs): """ Initialize video path, and preprocessing Pipeline object. Args: video_path (str): Absolute path to the video file. """ super(VideoDataSource, self).__init__(**kwargs) self._video_path = video_path vid = cv2.VideoCapture(video_path) self._height = vid.get(cv2.CAP_PROP_FRAME_HEIGHT) self._width = vid.get(cv2.CAP_PROP_FRAME_WIDTH) self._fps = vid.get(cv2.CAP_PROP_FPS) vid.release() @lru_cache() def __len__(self): """Return the number of frames.""" frame_counter = 0 vid = cv2.VideoCapture(self._video_path) while vid.isOpened(): success, _ = vid.read() if not success: break frame_counter += 1 vid.release() return frame_counter def _generator(self): vid = cv2.VideoCapture(self._video_path) while True: success, frame = vid.read() if not success: break frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) frame = frame / 255.0 yield frame vid.release() @property def height(self): """Return video frame height.""" return self._height @property def width(self): """Return video frame width.""" return self._width def get_image_properties(self): """Returns the width and height of the frames within the video.""" return self.width, self.height @property def frames_per_second(self): """Return frames per second.""" return self._fps def call(self): """Return a tf.data.Dataset for this data source.""" dataset = tf.data.Dataset.from_generator( generator=self._generator, output_types=tf.float32, output_shapes=tf.TensorShape([self.height, self.width, 3]), ) return dataset.map( lambda frame: types.SequenceExample( instances={ types.FEATURE_CAMERA: types.Images2D( images=tf.transpose(a=frame, perm=[2, 0, 1]), canvas_shape=types.Canvas2D( height=self.height, width=self.width ), ), types.FEATURE_SESSION: types.Session( uuid=tf.constant("session_uuid"), camera_name=tf.constant("camera_name"), frame_number=tf.constant(0), ), }, labels={}, ) ) @property def image_dtype(self): """Return the dtype of this data source.""" return tf.float32
tao_tensorflow1_backend-main
nvidia_tao_tf1/blocks/multi_source_loader/sources/video_data_source.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. """Tests for ImbalanceOverSamplingStrategy.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import pytest from nvidia_tao_tf1.blocks.multi_source_loader.sources.imbalance_oversampling import ( ImbalanceOverSamplingStrategy, ) from modulus.dataloader.humanloop import example_template from modulus.dataloader.humanloop_sqlite_dataset import HumanloopSqliteDataset from modulus.dataloader.testdata.db_test_builder import DbTestBuilder class TestOverSamplingStrategy(object): """Tests for ImbalanceOverSamplingStrategy.""" @pytest.mark.parametrize( "count_lookup, minimum_target_class_imbalance, source_to_target_class_mapping," "num_duplicates, num_expected_duplicates", # Number of canines / number of cars = 2.0 > 1.0 => Should be duplicated. [ ( {"automobile": {"COUNT": 1}, "dog": {"COUNT": 2}}, 1.0, {"automobile": "car", "dog": "canine"}, 1, 2, ), # Number of canine / number of cars = 1.0 => Should not be duplicated. ( {"automobile": {"COUNT": 1}, "dog": {"COUNT": 1}}, 1.0, {"automobile": "car", "dog": "canine"}, 1, 1, ), # Number of canine / number of cars = 1.0 > 0.5 => Should be duplicated. ( {"automobile": {"COUNT": 1}, "dog": {"COUNT": 1}}, 0.5, {"automobile": "car", "dog": "canine"}, 2, 3, ), # Number of canine / number of cars = 0.33 < 0.5 => Should not be duplicated. ( {"automobile": {"COUNT": 3}, "dog": {"COUNT": 1}}, 0.5, {"automobile": "car", "dog": "canine"}, 1, 1, ), ], ) def test_oversample( self, count_lookup, minimum_target_class_imbalance, source_to_target_class_mapping, num_duplicates, num_expected_duplicates, ): """Test the oversample method.""" dominant_target_classes = ["car"] minimum_target_class_imbalance = { target_class_name: minimum_target_class_imbalance for target_class_name in set(source_to_target_class_mapping.values()) } oversampling_strategy = ImbalanceOverSamplingStrategy( dominant_target_classes=dominant_target_classes, minimum_target_class_imbalance=minimum_target_class_imbalance, num_duplicates=num_duplicates, source_to_target_class_mapping=source_to_target_class_mapping, ) # 0-th and 2nd frames should appear once, while 1st frame should be duplicated. count_lookup = {0: {}, 1: count_lookup, 2: {}} frame_groups = [[(0, False)], [(1, False)], [(2, False)]] repeated_groups = oversampling_strategy.oversample( frame_groups=frame_groups, count_lookup=count_lookup ) expected_groups = ( [[(0, False)]] + [[(1, False)]] * num_expected_duplicates + [[(2, False)]] ) assert expected_groups == repeated_groups @pytest.fixture def sqlite_path(self): db_test_builder = DbTestBuilder() sqlite_path = db_test_builder.get_db("test_dataset", 8) yield sqlite_path db_test_builder.cleanup() def test_interface(self, sqlite_path): """Smoke test that the interface is compatible with the HumanloopSqliteDataset.""" dominant_target_classes = ["person"] source_to_target_class_mapping = { "automobile": "car", "heavy_truck": "car", "heavy truck": "car", "rider": "person", } num_duplicates = 3 minimum_target_class_imbalance = {"car": 0.1} oversampling_strategy = ImbalanceOverSamplingStrategy( dominant_target_classes=dominant_target_classes, minimum_target_class_imbalance=minimum_target_class_imbalance, num_duplicates=num_duplicates, source_to_target_class_mapping=source_to_target_class_mapping, ) regular_dataset = HumanloopSqliteDataset( filename=sqlite_path, export_format="jpeg", example=example_template() ) oversampled_dataset = HumanloopSqliteDataset( filename=sqlite_path, export_format="jpeg", example=example_template(), oversampling_strategy=oversampling_strategy, ) regular_dataset.set_batch(1, slice_batch=True) oversampled_dataset.set_batch(1, slice_batch=True) regular_frames = regular_dataset.num_unsharded_frames() oversampled_frames = oversampled_dataset.num_unsharded_frames() assert oversampled_frames > regular_frames
tao_tensorflow1_backend-main
nvidia_tao_tf1/blocks/multi_source_loader/sources/imbalance_oversampling_test.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. """Data sources for ingesting datasets.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from nvidia_tao_tf1.blocks.multi_source_loader.sources.bbox_to_polygon import ( BboxToPolygon, ) from nvidia_tao_tf1.blocks.multi_source_loader.sources.data_source import ( DataSource, ) from nvidia_tao_tf1.blocks.multi_source_loader.sources.image_data_source import ( ImageDataSource, ) from nvidia_tao_tf1.blocks.multi_source_loader.sources.imbalance_oversampling import ( ImbalanceOverSamplingStrategy, ) from nvidia_tao_tf1.blocks.multi_source_loader.sources.synthetic_data_source import ( SyntheticDataSource, ) from nvidia_tao_tf1.blocks.multi_source_loader.sources.tfrecords_data_source import ( TFRecordsDataSource, ) from nvidia_tao_tf1.blocks.multi_source_loader.sources.video_data_source import ( VideoDataSource, ) __all__ = ( "DataSource", "ImageDataSource", "ImbalanceOverSamplingStrategy", "BboxToPolygon", "SyntheticDataSource", "VideoDataSource", "TFRecordsDataSource", )
tao_tensorflow1_backend-main
nvidia_tao_tf1/blocks/multi_source_loader/sources/__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. """Adapter for sqlite based HumanLoop datasets.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import logging import os import sqlite3 import six import tensorflow as tf from nvidia_tao_tf1.blocks.multi_source_loader.processors.source_weight_frame import ( SourceWeightSQLFrameProcessor, ) from nvidia_tao_tf1.blocks.multi_source_loader.sources.data_source import ( DataSource, ) from nvidia_tao_tf1.blocks.multi_source_loader.sources.sqlite_bbox_label_parser import ( BboxFeatureProcessor, SqliteBboxLabelParser, ) from nvidia_tao_tf1.blocks.multi_source_loader.types import ( Coordinates2DWithCounts, FEATURE_CAMERA, FEATURE_SESSION, Images2DReference, LABEL_MAP, LABEL_OBJECT, Polygon2DLabel, SequenceExample, Session, ) import modulus.dataloader.humanloop as hl import modulus.dataloader.humanloop_sqlite_dataset as hl_sql from nvidia_tao_tf1.core.coreobject import save_args from modulus.types import Canvas2D logger = logging.getLogger(__name__) class SqliteDataSource(DataSource): """SqliteDataSource for ingesting sqlite files conforming to the HumanLoop schema.""" FORMAT_RGB_HALF_DWSOFTISP = "rgb_half_dwsoftisp_v0.52b" FORMAT_JPEG = "jpeg" DEFAULT_SUPPORTED_LABELS = ["POLYGON"] @save_args def __init__( self, sqlite_path, image_dir, export_format, split_db_filename=None, split_tags=None, supported_labels=None, subset_size=None, skip_empty_frames=None, ignored_classifiers_for_skip=None, feature_processors=None, oversampling_strategy=None, frame_processors=None, include_unlabeled_frames=None, additional_conditions=None, **kwargs, ): """ Construct a SqliteDataSource. Args: sqlite_path (str): Path to sqlite file. image_dir (str): Path to directory where images referenced by examples are stored. export_format (str): Folder from where to load the images depending on their format. split_db_filename (str): Optional split database defining training/validation sets. split_tags (list of str): A list of split tags to choose a subset of sets (eg. ['val0', 'val1'] to iterate over two validation folds). supported_labels (list<str>): List of supported labels to be loaded by this source subset_size (int): Number of frames to use. If None, use all. skip_empty_frames (bool). Whether to ignore empty frames (i.e frames withou relevant features. By default, False, i.e all frames are returned. ignored_classifiers_for_skip (set or list or None): Names of classifiers to ignore when considering if frame is empty. I.e if frame only has these classes, it is still regarded as empty. oversampling_strategy (hl_sql.OverSamplingStrategy): OverSamplingStrategy child class by which to duplicate certain frames. frame_processors (list): list of func hook, which will be triggered in frame parsing. include_unlabeled_frames (bool): Whether to include unlabeled frames. Default False. additional_conditions (list): list of additional sql conditions for a 'where' clause. Each element in the list can only reference one of the following tables: 'features', 'frames', 'sequences'. """ super(SqliteDataSource, self).__init__(**kwargs) if not os.path.isfile(sqlite_path): raise ValueError( "No dataset sqlite file found at path: '{}'".format(sqlite_path) ) if not os.path.isdir(image_dir): raise ValueError( "No dataset image directory found at path: '{}'".format(image_dir) ) if split_db_filename is not None and not os.path.isfile(split_db_filename): raise ValueError( "No dataset split file found at path: '{}'".format(split_db_filename) ) if subset_size is not None and subset_size < 0: raise ValueError("subset_size can not be negative") if additional_conditions is not None: self._check_additional_conditions(additional_conditions) self.sqlite_path = sqlite_path self.image_dir = image_dir self.export_format = export_format self.split_db_filename = split_db_filename if split_tags is not None: split_tags = [ t.decode() if isinstance(t, six.binary_type) else t for t in split_tags ] if split_db_filename and split_tags: split_db_tags = set(self.query_split_tags(split_db_filename)) missing_tags = set(split_tags) - split_db_tags if missing_tags: raise ValueError( "Split tags {} not in split db '{}' with tags {}.".format( list(missing_tags), split_db_filename, list(split_db_tags) ) ) self.split_tags = split_tags self._include_unlabeled_frames = include_unlabeled_frames or False self.supported_labels = supported_labels or self.DEFAULT_SUPPORTED_LABELS self._num_shards = 1 self._shard_id = 0 self._pseudo_sharding = False self._sequence_length = None self._shuffle = False self._shuffle_buffer_size = 10000 self._dataset = None self._subset_size = subset_size self._skip_empty_frames = skip_empty_frames or False self._ignored_classifiers_for_skip = set() if ignored_classifiers_for_skip is not None: self._ignored_classifiers_for_skip.update(ignored_classifiers_for_skip) self._feature_processors = feature_processors self._oversampling_strategy = oversampling_strategy self._frame_processors = frame_processors self.num_samples = None self._additional_conditions = additional_conditions self.set_image_properties(*self.get_image_properties()) @staticmethod def query_split_tags(split_db_filename): """Query Sqlite split db for a list of split tags. Args: split_db_filename (str): Path to split db. Returns: A list of split tag strings. """ connection = sqlite3.connect(split_db_filename) tags_query = "SELECT DISTINCT tag FROM split" tags = connection.cursor().execute(tags_query).fetchall() return [tag[0] for tag in tags] def get_image_properties(self): """Returns the maximum width and height of images for this source.""" split_join = "" initial_statement = "" if self.split_db_filename: initial_statement = "ATTACH DATABASE '{filename}' AS {db_name}".format( filename=self.split_db_filename, db_name=hl_sql.SPLIT_DB_NAME ) tags = ", ".join(["'{}'".format(tag) for tag in self.split_tags]) split_join = ( "\tJOIN {db_name}.{table} ON {db_name}.{table}.id = sequences.session_uuid\n" "\t\tAND {db_name}.{table}.tag IN ({tags})\n" ) split_join = split_join.format( db_name=hl_sql.SPLIT_DB_NAME, table="split", tags=tags ) additional_sequence_conditions = "" if self._additional_conditions is not None: conditions = list( condition for condition in self._additional_conditions if "sequences" in condition ) if len(conditions) > 0: additional_sequence_conditions = " WHERE " + " AND ".join(conditions) connection = sqlite3.connect(self.sqlite_path) cursor = connection.cursor() cursor.execute(initial_statement) max_image_size_query = ( "SELECT MAX(width), MAX(height) FROM sequences" + split_join + additional_sequence_conditions ) max_image_width, max_image_height = cursor.execute( max_image_size_query ).fetchone() if max_image_height is None or max_image_width is None: max_image_height = 0 max_image_width = 0 export_params_query = ( "SELECT region_width, region_height, width, height, extension FROM" " formats WHERE name = ?" ) row = cursor.execute(export_params_query, (self.export_format,)).fetchall() if not row: raise ValueError( "export_format {} not found in database {}.".format( self.export_format, self.sqlite_path ) ) region_width, region_height, width_factor, height_factor, extension = row[0] region_width = region_width or 1.0 region_height = region_height or 1.0 width_factor = width_factor or 1.0 height_factor = height_factor or 1.0 max_image_width = int(round(max_image_width * region_width * width_factor)) max_image_height = int(round(max_image_height * region_height * height_factor)) self.extension = extension return max_image_width, max_image_height def set_image_properties(self, max_image_width, max_image_height): """Overrides the maximum image width and height of this source.""" self.max_image_width = max_image_width self.max_image_height = max_image_height def set_shard(self, num_shards, shard_id, pseudo_sharding=False): """ Sets the sharding configuration of this source. Args: num_shards (int): The number of shards. shard_id (int): Shard id from 0 to num_shards - 1. pseudo_sharding (bool) if True, then data is not actually sharded, but different shuffle seeds are used to differentiate shard batches. """ self._num_shards = num_shards self._shard_id = shard_id self._pseudo_sharding = pseudo_sharding def supports_sharding(self): """Whether this source can do its own sharding.""" return True def supports_shuffling(self): """Whether this source can do its own shuffling.""" return True def set_shuffle(self, buffer_size): """Enables shuffling on this data source.""" self._shuffle = True self._shuffle_buffer_size = buffer_size def set_sequence_length(self, sequence_length): """Sets the sequence length (number of frames in sequence).""" self._sequence_length = sequence_length def supports_temporal_batching(self): """Whether this source does its own temporal batching.""" return True def initialize(self): """Called by data loaders after all configuration is done.""" example = hl.example_template(label_names=self.supported_labels) # Prune fields we don't need. This has significant impact on # the tensorflow overhead of processing data. example.instances["sequence"]["dataset_name"].prune = True example.instances["sequence"]["id"].prune = True example.instances["sequence"]["recording_date"].prune = True example.instances["source"]["camera_lens"].prune = True example.instances["source"]["camera_location"].prune = True example.instances["source"]["width"].prune = True example.instances["source"]["height"].prune = True if self._skip_empty_frames: self._ignored_classifiers_for_skip.add("do_not_care") # It would be meaningless to specify classifiers for skipping but have skipping disabled, # so it would be likely a user error. if self._ignored_classifiers_for_skip and not self._skip_empty_frames: raise ValueError( "Cant specify ignored_classifiers_for_skip w/ skip_empty_frames=False" ) feature_processors = [] if "BOX" in self.supported_labels and ( self._feature_processors is None or not any( isinstance(f, BboxFeatureProcessor) for f in self._feature_processors ) ): feature_processors.append(BboxFeatureProcessor()) if self._feature_processors: feature_processors.extend(self._feature_processors) frame_processors = [] if "BOX" in self.supported_labels and ( self._frame_processors is None or not any( isinstance(f, SourceWeightSQLFrameProcessor) for f in self._frame_processors ) ): frame_processors.append(SourceWeightSQLFrameProcessor()) if self._frame_processors: frame_processors.extend(self._frame_processors) self._dataset = hl_sql.HumanloopSqliteDataset( filename=self.sqlite_path, export_format=self.export_format, split_db_filename=self.split_db_filename, split_tags=self.split_tags, example=example, order_by=hl_sql.ORDER_BY_SESSION_CAMERA_FRAME, export_path=self.image_dir, skip_empty_frames=self._skip_empty_frames, feature_processors=feature_processors, frame_processors=frame_processors, subset_size=self._subset_size, ignored_classifiers_for_skip=self._ignored_classifiers_for_skip, oversampling_strategy=self._oversampling_strategy, include_unlabeled_frames=self._include_unlabeled_frames, additional_conditions=self._additional_conditions, ) self._dataset.set_sequence_length(self._sequence_length) self._dataset.set_shard( self._num_shards, self._shard_id, pseudo_sharding=self._pseudo_sharding ) if self._shuffle: self._dataset.set_shuffle(buffer_size=self._shuffle_buffer_size) self.num_samples = self._dataset.num_unsharded_sequences() def call(self): """Return a tf.data.Dataset for this data source.""" # Note: currently batch is sliced to frames and batching is done externally. # TODO (vkallioniemi): do batching here. # NOTE: 512 is used to control how many frames the loader loads at once. Should be # replaced by the actual batch size when batching is moved to the source. JIRA ML-1553 if not self._dataset: self.initialize() self._dataset.set_batch(512, slice_batch=True) return self._dataset().map( _ExampleAdapter( supported_labels=self.supported_labels, max_image_width=self.max_image_width, max_image_height=self.max_image_height, sequence_length=self._sequence_length, include_unlabeled_frames=self._include_unlabeled_frames, ) ) def __len__(self): """Return the number of examples in the underlying sql query.""" assert self._dataset, "Need to call initialize before calling len()" return self.num_samples @staticmethod def _check_additional_conditions(additional_conditions): # Conditions are limited to the tables joined in the feature query in # modulus.dataloader.humanloop_sqlite_dataset.HumanloopSqliteDataset # see moduluspy/modulus/dataloader/humanloop_sqlite_dataset.py#306 # # Limit to a single table per condition is necessary because additional conditions need to # be used in get_image_properties so we need to be able to extract out conditions on # sequences. tables = ["features", "frames", "sequences"] for condition in additional_conditions: if list(table in condition for table in tables).count(True) != 1: raise (ValueError("Each condition can only reference one table.")) # TODO(vkallioniemi): Restructure this class to be either to be part of the SqliteDataSource or # move to a separate file. class _ExampleAdapter(object): """Extract examples from HumanLoop datasets.""" def __init__( self, supported_labels, max_image_width, max_image_height, sequence_length, include_unlabeled_frames, ): """ Constructs an _ExampleAdapter. Args: supported_labels (list<str>): List of supported labels max_image_width (int): Maximum image width to which (smaller) images will be padded to. max_image_width (int): Maximum image height to which (smaller) images will be padded to. include_unlabeled_frames(bool) Whether or not unlabeled frames will be included and need to be tracked. """ self.supported_labels = supported_labels self.max_image_width = max_image_width self.max_image_height = max_image_height self._sequence_length = sequence_length self._bbox_label_parser = None if "BOX" in self.supported_labels: self._bbox_label_parser = SqliteBboxLabelParser() def __call__(self, data): """ Transforms an sqlite specific Example to a normalized/canonical form. Args: data (Example): Example structure with instances and labels matching the schema used for the HumanLoop dataloader. Returns: (SequenceExample): Example structure with instances and labels matching the normalized/canonical schema used by all DataSources. """ return SequenceExample( instances={ FEATURE_CAMERA: self._extract_frame_paths(data.instances), FEATURE_SESSION: self._extract_session(data.instances), }, labels=self._extract_labels(data), ) def _extract_session(self, instances): return Session( uuid=instances["sequence"]["session_uuid"], camera_name=instances["source"]["camera_name"], frame_number=instances["number"], ) def _extract_frame_paths(self, instances): temporal_dim = [self._sequence_length] if self._sequence_length else [] canvas_shape = Canvas2D( height=tf.ones(temporal_dim + [self.max_image_height]), width=tf.ones(temporal_dim + [self.max_image_width]), ) input_height = instances["shape"].height input_width = instances["shape"].width return Images2DReference( path=instances["path"], extension=instances["export"]["extension"], canvas_shape=canvas_shape, input_height=input_height, input_width=input_width, ) def _extract_map_labels(self, labels, supported_labels): """Extract map labels.""" all_vertices = [] all_classes = [] all_attributes = [] for label_name in supported_labels: label = labels[label_name] vertices = label["vertices"] classes = label["classifier"] attributes = label["attributes"] all_vertices.append(vertices) all_classes.append(classes) all_attributes.append(attributes) # TODO(weich) Tensosrflow 2.x will deprecate expand_nonconcat_dim, but Tensorflow 1.14 # supports both expand_nonconcat_dims and expand_nonconcat_dim, and defaulting # expand_nonconcat_dim to be false. # So if we set expand_nonconcat_dims=True, tensorflow will complain. # We will switch expand_nonconcat_dim to expand_nonconcat_dims upon upgrading to # Tensorflow 2.x if len(all_vertices) > 1: axis = 1 if self._sequence_length else 0 vertices = tf.sparse.concat( axis=axis, sp_inputs=all_vertices, name="sqlite_cat_vertices", expand_nonconcat_dim=True, ) classes = tf.sparse.concat( axis=axis, sp_inputs=all_classes, name="sqlite_cat_classes", expand_nonconcat_dim=True, ) attributes = tf.sparse.concat( axis=axis, sp_inputs=all_attributes, name="sqlite_cat_attributes", expand_nonconcat_dim=True, ) # Expand classes to be of the same rank as attributes. This allows for multiple classes # per object. classes = tf.sparse.expand_dims(classes, axis=-1) return Polygon2DLabel( vertices=Coordinates2DWithCounts( coordinates=vertices, canvas_shape=Canvas2D( height=tf.constant(self.max_image_height, tf.int32), width=tf.constant(self.max_image_width, tf.int32), ), vertices_count=label["num_vertices"], ), classes=classes, attributes=attributes, ) def _extract_bbox_labels(self, labels): return self._bbox_label_parser(labels) def _extract_labels(self, example): labels = example.labels output_labels = dict() expected_labels = set(self.supported_labels) if "BOX" in expected_labels: output_labels[LABEL_OBJECT] = self._extract_bbox_labels(example) expected_labels.remove("BOX") map_labels = {"POLYGON", "POLYLINE"}.intersection(expected_labels) if map_labels: output_labels[LABEL_MAP] = self._extract_map_labels(labels, map_labels) expected_labels = expected_labels.difference(map_labels) # TODO(@williamz): Add unit tests that would have caught polyline support getting dropped. if expected_labels: raise ValueError( "This datasource was configured to support labels that there are " "currently no handlers for. Invalid label types: {}.".format( expected_labels ) ) return output_labels
tao_tensorflow1_backend-main
nvidia_tao_tf1/blocks/multi_source_loader/sources/sqlite_data_source.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. """Main test for image_data_source.py""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import numpy as np import PIL import pytest import tensorflow as tf from nvidia_tao_tf1.blocks.multi_source_loader import data_loader from nvidia_tao_tf1.blocks.multi_source_loader import frame_shape from nvidia_tao_tf1.blocks.multi_source_loader import types from nvidia_tao_tf1.blocks.multi_source_loader.sources import image_data_source from nvidia_tao_tf1.core.coreobject import deserialize_tao_object @pytest.fixture(scope="session") def _image_files(): return ["image1.jpg", "image2.jpg"] def _create_images(tmpdir, image_files): image_paths = [] tmp_dir = str(tmpdir.mkdir("images")) for i in range(len(image_files)): img = np.zeros((80, 128, 3), dtype=np.uint8) grad = np.linspace(0, 255, img.shape[1]) img[16:32, :, 0] = grad im = PIL.Image.fromarray(img) image_path = os.path.join(tmp_dir, image_files[i]) im.save(image_path) image_paths.append(image_path) return image_paths def test_len_image_data_source(_image_files): image_source = image_data_source.ImageDataSource( _image_files, ".jpg", frame_shape.FrameShape(height=80, width=128, channels=3) ) assert len(image_source) == 2 def test_image_data_source(tmpdir, _image_files): image_paths = _create_images(tmpdir, _image_files) image_source = image_data_source.ImageDataSource( image_paths, ".jpg", frame_shape.FrameShape(height=80, width=128, channels=3) ) data_loader_ = data_loader.DataLoader( [image_source], augmentation_pipeline=[], batch_size=1 ) data_loader_.set_shard() batch = data_loader_() assert len(data_loader_) == 2 with tf.compat.v1.Session() as sess: sess.run(tf.compat.v1.get_collection("iterator_init")) for _ in range(len(data_loader_)): example = sess.run(batch) image = example.instances[types.FEATURE_CAMERA].images scaled_pixels = np.argwhere(image > 1) assert image.shape == (1, 3, 80, 128) # To test that '_decode_function' was applied. assert not scaled_pixels def test__serialization_and_deserialization(_image_files): """Test TAOObject serialization and deserialization on ImageDataSource.""" source = image_data_source.ImageDataSource( image_paths=_image_files, extension=".jpg", image_shape=[10, 10, 3] ) source_dict = source.serialize() deserialized_source = deserialize_tao_object(source_dict) assert source._image_paths == deserialized_source._image_paths assert source.extension == deserialized_source.extension assert source._image_shape == deserialized_source._image_shape
tao_tensorflow1_backend-main
nvidia_tao_tf1/blocks/multi_source_loader/sources/image_data_source_test.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. """Data source for tfrecords based data files.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from functools import lru_cache import os import tensorflow as tf from nvidia_tao_tf1.blocks.multi_source_loader.sources.data_source import ( DataSource, ) from nvidia_tao_tf1.blocks.multi_source_loader.sources.lane_label_parser import ( LaneLabelParser, ) from nvidia_tao_tf1.core.coreobject import save_args class TFRecordsDataSource(DataSource): """DataSource for reading examples from TFRecords files.""" @save_args def __init__( self, tfrecord_path, image_dir, height, width, channels, subset_size, should_normalize_labels=True, **kwargs ): """ Construct a TFRecordsDataSource. Args: tfrecord_path (str): Path to a tfrecords file or a list of paths to tfrecords files. image_dir (str): Path to directory where images referenced by examples are stored. height (int): Height of images and labels stored in this dataset. width (int): Width of images and labels stored in this dataset. channels (int): Number of channels for images stored in this dataset. subset_size (int): Number of images from tfrecord_path to use. should_normalize_labels(bool): Whether or not the datasource should normalize the label coordinates. """ super(TFRecordsDataSource, self).__init__(**kwargs) if not isinstance(tfrecord_path, list): tfrecord_path = [tfrecord_path] for path in tfrecord_path: if not os.path.isfile(path): raise ValueError( "No dataset tfrecords file found at path: '{}'".format(path) ) if not os.path.isdir(image_dir): raise ValueError( "No dataset image directory found at path: '{}'".format(image_dir) ) self.tfrecord_path = tfrecord_path self.image_dir = image_dir # TODO(vkallioniemi): Remove channels - not used at the moment. self.channels = channels self.height = height self.width = width self.subset_size = subset_size self._num_shards = 1 self._shard_id = 0 self._pseudo_sharding = False self._shuffle = False self._shuffle_buffer_size = 10000 self._should_normalize_labels = should_normalize_labels self._max_height = height self._max_width = width @lru_cache() def __len__(self): """Return the number of examples in the underlying tfrecords file.""" count = 0 for path in self.tfrecord_path: for _ in tf.compat.v1.python_io.tf_record_iterator(path): count += 1 if self.subset_size is None: self.subset_size = count if self.subset_size > 0: return min(count, self.subset_size) return count def set_image_properties(self, max_image_width, max_image_height): """Overrides the maximum image width and height of this source.""" self._max_height = max_image_height self._max_width = max_image_width def get_image_properties(self): """Returns the maximum width and height of images for this source.""" return self._max_width, self._max_height def supports_shuffling(self): """Whether this source can do its own shuffling.""" return True def set_shuffle(self, buffer_size): """Enables shuffling on this data source.""" self._shuffle = True self._shuffle_buffer_size = buffer_size def supports_sharding(self): """Whether this source can do its own sharding.""" return True def set_shard(self, num_shards, shard_id, pseudo_sharding=False): """ Sets the sharding configuration of this source. Args: num_shards (int): The number of shards. shard_id (int): Shard id from 0 to num_shards - 1. pseudo_sharding (bool) if True, then data is not actually sharded, but different shuffle seeds are used to differentiate shard batches. """ self._num_shards = num_shards self._shard_id = shard_id self._pseudo_sharding = pseudo_sharding @property def parse_example(self): """Load features off disk.""" parser = LaneLabelParser( image_dir=self.image_dir, extension=self.extension, height=self.height, width=self.width, max_height=self._max_height, max_width=self._max_width, should_normalize_labels=self._should_normalize_labels, ) return lambda dataset: dataset.map(parser) def call(self): """Return a tf.data.Dataset for this data source.""" dataset = tf.data.TFRecordDataset(self.tfrecord_path) if self.subset_size > 0: dataset = dataset.take(self.subset_size) if not self._pseudo_sharding and self._num_shards > 1: dataset = dataset.shard(self._num_shards, self._shard_id) # Note: we do shuffling here, so that the shuffle buffer only needs to # store raw tfrecords data (instead of fully parsed examples) if self._shuffle: dataset = dataset.apply( tf.data.experimental.shuffle_and_repeat( buffer_size=min(len(self), self._shuffle_buffer_size), count=None ) ) return dataset
tao_tensorflow1_backend-main
nvidia_tao_tf1/blocks/multi_source_loader/sources/tfrecords_data_source.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. """Class for parsing labels produced by the lanenet json_converter.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import tensorflow as tf from nvidia_tao_tf1.blocks.multi_source_loader import types from nvidia_tao_tf1.core.processors import ParseExampleProto # TODO(vkallioniemi): Move (to lanenet?) once we've figured out what parts of TFRecordsDataSource # can be shared. class LaneLabelParser(object): """Parse tf.train.Example protos into lanenet Examples.""" def __init__( self, image_dir, extension, height, width, max_height, max_width, should_normalize_labels=True, ): """ Construct a parser for lane labels. Args: image_dir (str): Path to the directory where images are contained. extension (str): Image extension for images that get loaded ( ".fp16", ".png", ".jpg" or ".jpeg"). height (int): Height of images and labels. width (int): Width of images and labels. max_height (int): Height to pad image to if necessary. max_width (int): Width to pad image to if necessary. should_normalize_labels(bool): Whether or not the datasource should normalize the label coordinates. """ assert height > 0 assert width > 0 self._image_dir = image_dir self._height = height self._width = width self._extension = extension self._parse_example = self._make_example_parser() self._should_normalize = should_normalize_labels self._max_height = max_height self._max_width = max_width def __call__(self, tfrecord): """ Parse a tf.train.Example. Returns: (types.SequenceExample) Example compatible with Processors. """ return self._parse(tfrecord) def _parse_image_reference(self, image_dir, image_id, extension): directory = os.path.normpath(image_dir) file_name = tf.strings.join([image_id, extension]) frame_path = tf.strings.join([directory, file_name], os.sep) return frame_path def _parse(self, tfrecord): tfexample = self._parse_example(tfrecord) extension = self._extension frame_path = self._parse_image_reference( self._image_dir, tfexample["id"], extension ) return types.SequenceExample( instances={ types.FEATURE_CAMERA: types.Images2DReference( path=frame_path, extension=extension, canvas_shape=types.Canvas2D( height=tf.ones(self._max_height), width=tf.ones(self._max_width) ), input_height=[self._height], input_width=[self._width], ), types.FEATURE_SESSION: types.Session( uuid=tfexample["sequence_name"], camera_name=tfexample["camera_location"], frame_number=tfexample["frame_number"], ), }, labels={ types.LABEL_MAP: self._extract_polygon( tfexample, image_height=self._height, image_width=self._width ) }, ) def _make_example_parser(self): features = { "id": tf.io.FixedLenFeature([], dtype=tf.string), "width": tf.io.FixedLenFeature([], dtype=tf.int64), "height": tf.io.FixedLenFeature([], dtype=tf.int64), "target/classifier": tf.io.VarLenFeature(dtype=tf.string), "target/attributes": tf.io.VarLenFeature(dtype=tf.string), "target/polygon/length": tf.io.VarLenFeature(dtype=tf.int64), "target/polygon/x": tf.io.VarLenFeature(dtype=tf.float32), "target/polygon/y": tf.io.VarLenFeature(dtype=tf.float32), "target/polygonAttributes": tf.io.VarLenFeature(dtype=tf.string), "target/polygonAttributesCount": tf.io.VarLenFeature(dtype=tf.int64), "sequence_name": tf.io.FixedLenFeature([], dtype=tf.string), "frame_number": tf.io.FixedLenFeature([], dtype=tf.int64), "camera_location": tf.io.FixedLenFeature([], dtype=tf.string), } return ParseExampleProto(features=features, single=True) def _normalize_coordinates( self, x, y, polygon_width, polygon_height, image_width, image_height ): if self._should_normalize: x /= tf.cast(polygon_width, tf.float32) y /= tf.cast(polygon_height, tf.float32) x *= image_width y *= image_height return tf.stack([x, y], axis=1) def _extract_polygon(self, example, image_height, image_width): dense_coordinates = self._normalize_coordinates( x=example["target/polygon/x"], y=example["target/polygon/y"], polygon_width=example["width"], polygon_height=example["height"], image_height=image_height, image_width=image_width, ) coordinates_per_polygon = example["target/polygon/length"] num_polygons = tf.shape(input=coordinates_per_polygon)[0] # TODO(ehall): Eventually this part will be removed in favor of adding all attributes below. # TODO(mlehr): Switched the if/elif, it is not working for pathnet with 'polygonAttributes'. # modulus `PathGenerator` does not support multiple attributes per polyline. if "target/attributes" in example: dense_attribute_ids = example["target/attributes"] sparse_attributes = types.vector_and_counts_to_sparse_tensor( dense_attribute_ids, tf.ones_like(dense_attribute_ids, dtype=tf.int64) ) elif "target/polygonAttributes" in example: sparse_attributes = types.vector_and_counts_to_sparse_tensor( example["target/polygonAttributes"], example["target/polygonAttributesCount"], ) else: raise ValueError( "Invalid TFRecords - neither attributes or polygonAttributes present." ) dense_classes = example["target/classifier"] # Note: we rely on json converter script to ensure that each # polygon always contains a single class. # TODO(vkallioniemi): This can be done cheaper given the ^^ assumption. classes_per_polygon = tf.ones_like(dense_classes, dtype=tf.int64) sparse_classes = types.vector_and_counts_to_sparse_tensor( dense_classes, classes_per_polygon ) # Turn coordinates to 3D sparse tensors of shape [S, V, C] # where S=Shape/Polygon, V=Vertex and C=Coordinate sparse_coordinates = types.sparsify_dense_coordinates( dense_coordinates, coordinates_per_polygon ) return types.Polygon2DLabel( vertices=types.Coordinates2DWithCounts( coordinates=sparse_coordinates, canvas_shape=types.Canvas2D( height=tf.ones(self._max_height), width=tf.ones(self._max_width) ), vertices_count=tf.SparseTensor( indices=tf.reshape( tf.cast(tf.range(num_polygons), dtype=tf.int64), [-1, 1] ), values=coordinates_per_polygon, dense_shape=[num_polygons], ), ), classes=sparse_classes, attributes=sparse_attributes, )
tao_tensorflow1_backend-main
nvidia_tao_tf1/blocks/multi_source_loader/sources/lane_label_parser.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. """Main test for synthetic_data_source.py""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import pytest import tensorflow as tf from nvidia_tao_tf1.blocks.multi_source_loader.sources.synthetic_data_source import ( SyntheticDataSource, ) from nvidia_tao_tf1.blocks.multi_source_loader.types import FEATURE_CAMERA from nvidia_tao_tf1.blocks.multi_source_loader.types import test_fixtures from nvidia_tao_tf1.core.coreobject import deserialize_tao_object def test_length(): source = SyntheticDataSource(5, template=test_fixtures.make_example_3d(504, 960)) assert len(source) == 5 def test_yields_specified_shapes(): source = SyntheticDataSource(5, template=test_fixtures.make_example_3d(504, 960)) dataset = source() iterator = tf.compat.v1.data.make_one_shot_iterator(dataset) example = iterator.get_next() with tf.compat.v1.Session() as sess: count = 0 with pytest.raises(tf.errors.OutOfRangeError): while True: image = sess.run(example.instances[FEATURE_CAMERA].images) count += 1 assert image.shape == (3, 504, 960) assert count == 5 def test_with_tracker_dict(): tracker_dict = {} source = SyntheticDataSource( 5, template=test_fixtures.make_example_3d(504, 960), tracker_dict=tracker_dict ) dataset = source() iterator = tf.compat.v1.data.make_one_shot_iterator(dataset) getnext = iterator.get_next() with tf.compat.v1.Session() as sess: for _ in range(4): sess.run(getnext) assert "call_count" in tracker_dict assert tracker_dict["call_count"] == 4 def test_sampling_ratio_defaults_to_one(): source = SyntheticDataSource( example_count=1, template=test_fixtures.make_example_3d(504, 960) ) assert source.sample_ratio == 1.0 def test_sampling_ratio_is_set(): sample_ratio = 0.2 source = SyntheticDataSource( example_count=1, template=test_fixtures.make_example_3d(504, 960), sample_ratio=sample_ratio, ) assert source.sample_ratio == sample_ratio def test_serialization_and_deserialization(): """Test TAOObject serialization and deserialization on SyntheticDataSource.""" source = SyntheticDataSource( example_count=1, template=test_fixtures.make_example_3d(504, 960), sample_ratio=0.2, ) source_dict = source.serialize() deserialized_source = deserialize_tao_object(source_dict) assert source._example_count == deserialized_source._example_count assert source.sample_ratio == deserialized_source.sample_ratio
tao_tensorflow1_backend-main
nvidia_tao_tf1/blocks/multi_source_loader/sources/synthetic_data_source_test.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. """Main test for video_data_source.py""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import cv2 import numpy as np import tensorflow as tf from nvidia_tao_tf1.blocks.multi_source_loader import data_loader from nvidia_tao_tf1.blocks.multi_source_loader import types from nvidia_tao_tf1.blocks.multi_source_loader.sources.video_data_source import ( VideoDataSource, ) from nvidia_tao_tf1.core.coreobject import deserialize_tao_object def _create_h264_video(video_path, frame_count, fps, width, height): fourcc = cv2.VideoWriter_fourcc(*"H264") video_writer = cv2.VideoWriter(video_path, fourcc, fps, (width, height)) i = 0 while i < frame_count: x = np.random.randint(255, size=(480, 640, 3)).astype("uint8") video_writer.write(x) i = i + 1 def test_video_data_source(tmpdir_factory): tmp_dir = str(tmpdir_factory.mktemp("video")) video_path = os.path.join(tmp_dir, "video1.h264") _create_h264_video(video_path, 5, 25, 640, 480) video_source = VideoDataSource(video_path) assert len(video_source) == 5 assert video_source.height == 480 assert video_source.width == 640 assert video_source.frames_per_second == 25 data_loader_ = data_loader.DataLoader( [video_source], augmentation_pipeline=[], batch_size=1 ) data_loader_.set_shard() batch = data_loader_() assert len(data_loader_) == 5 with tf.compat.v1.Session() as sess: for _ in range(len(data_loader_)): sess.run(tf.compat.v1.get_collection("iterator_init")) example = sess.run(batch) image = example.instances[types.FEATURE_CAMERA].images assert image.shape == (1, 3, 480, 640) def test_serialization_and_deserialization(tmpdir_factory): tmp_dir = str(tmpdir_factory.mktemp("video")) video_path = os.path.join(tmp_dir, "video1.h264") _create_h264_video(video_path, 5, 25, 640, 480) source = VideoDataSource(video_path) source_dict = source.serialize() deserialized_source = deserialize_tao_object(source_dict) assert source._video_path == deserialized_source._video_path assert source._height == deserialized_source._height assert source._width == deserialized_source._width assert source._fps == deserialized_source._fps
tao_tensorflow1_backend-main
nvidia_tao_tf1/blocks/multi_source_loader/sources/video_data_source_test.py
# Copyright (c) 2019-2020, NVIDIA CORPORATION. All rights reserved. """Processor to convert 'BOX' type labels to 'POLYGON' type labels.""" import numpy as np from nvidia_tao_tf1.core.dataloader.dataset import FeatureProcessor class BboxToPolygon(FeatureProcessor): """Feature processor to convert 'BOX' type labels to 'POLYGON' labels. It also splits labels into several different labels based on the size of the object (needed for AhbNet). """ def __init__(self, size_buckets=None, labels_to_split=None, image_coordinates=None): """Constructor for the bbox to polygon label converter. It also splits labels into several different labels based on the size of the object, if labels_to_split is specified. Args: size_buckets (dict): Dictionary with the buckets (min, max) for each object size. For example: {"tiny": {"min": 0, "max": 10}, "small": {"min": 10, "max": 20}, "median: {"min": 20, "max": 30}, "large": {"min": 30},} labels_to_split (list[str]): List with the class keys that need to be split based on the size of the object. image_coordinates (dict): Dictionary with the x_min, y_min, x_max and y_max of the image. If the min values are not specified, they are default to 0.0. """ self._size_buckets = size_buckets if size_buckets else {} self._labels_to_split = labels_to_split if labels_to_split and not image_coordinates: raise ValueError( "When labels_to_split is specified, the image coordinates have to be specified too." ) if image_coordinates: if not ("x_max" in image_coordinates and "y_max" in image_coordinates): raise ValueError( "The x_max and y_max of the image need to be specified." ) if "x_min" not in image_coordinates: image_coordinates["x_min"] = 0.0 if "y_min" not in image_coordinates: image_coordinates["y_min"] = 0.0 self._image_coordinates = image_coordinates def add_fields(self, example): """Add new fields to the example data structure (labels). Args: example (namedtuple): Data structure that the loader returns. """ pass def filter(self, example_col_idx, dtype, feat_row): """Filter label rows. Args: example_col_idx (namedtuple): Example data structure, where fields are integers that correspond to the index of the value in 'row' dtype (str): Label type, such as 'BOX' or 'POLYGON'. row (list): Flat list of values from the database for one label. Use example_col_idx to find which element corresponds to which field in the 'example'. Returns: True or False, depending on wheter the row should be kept. """ return True def map(self, example_col_idx, dtype, feat_row): """Modify or inject values into the feature row. Args: example_col_idx (namedtuple): Example data structure, where fields are integers that correspond to the index of the value in 'row'. dtype (str): Label type, such as 'POLYGON'. feat_row (list): Flat list of values from the database for one label. Use example_col_idx. Returns: modified 'row'. """ if dtype == "POLYGON": label = example_col_idx.labels[dtype] verts = feat_row[label["vertices"]] if len(verts) > 0: if self._labels_to_split: all_x = [v[0] for v in verts] all_y = [v[1] for v in verts] image_x_min = self._image_coordinates["x_min"] image_y_min = self._image_coordinates["y_min"] image_x_max = self._image_coordinates["x_max"] image_y_max = self._image_coordinates["y_max"] all_x = np.clip(all_x, a_min=image_x_min, a_max=image_x_max) all_y = np.clip(all_y, a_min=image_y_min, a_max=image_y_max) if len(all_x) > 0 and len(all_y) > 0: max_x = np.max(all_x) min_x = np.min(all_x) diff_x = np.abs(max_x - min_x) max_y = np.max(all_y) min_y = np.min(all_y) diff_y = np.abs(max_y - min_y) if feat_row[label["classifier"]] in self._labels_to_split: # The cars larger than any size bucket will be tagged as # feat_row[label["classifier"]] for size_bucket in self._size_buckets: max_value = self._size_buckets[size_bucket]["max"] min_value = self._size_buckets[size_bucket]["min"] if (min_value < diff_y <= max_value) or ( min_value < diff_x <= max_value ): size_bucket = "_" + size_bucket feat_row[label["classifier"]] += size_bucket break if len(verts) == 2: # BBOX then we modify x0, y0 = verts[0][0], verts[0][1] x1, y1 = verts[1][0], verts[1][1] new_verts = [[x0, y0], [x1, y0], [x1, y1], [x0, y1]] feat_row[label["vertices"]] = new_verts feat_row[label["num_vertices"]] = 4 return feat_row
tao_tensorflow1_backend-main
nvidia_tao_tf1/blocks/multi_source_loader/sources/bbox_to_polygon.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. """Data source for image files.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from functools import lru_cache import os import tensorflow as tf from nvidia_tao_tf1.blocks.multi_source_loader import types from nvidia_tao_tf1.blocks.multi_source_loader.sources import data_source from nvidia_tao_tf1.core.coreobject import save_args class ImageDataSource(data_source.DataSource): """DataSource to read a list of images.""" @save_args def __init__(self, image_paths, extension, image_shape, **kwargs): """ Initialize the image paths, preprocessing Pipeline object, encoding and image shape. Args: image_paths (list(str)): List of paths to the image files. extension (str): Image file extension (encoding) ('.fp16' or '.jpg'). image_shape (`FrameShape`): Shape of the image in the form HWC. """ super(ImageDataSource, self).__init__(**kwargs) self.extension = extension self._image_paths = image_paths self._image_shape = image_shape # TODO(mlehr): refactor the method to ImageDecoder class. def _decode_function(self, image, image_id): if self.extension == ".fp16": # Raw images have pixels in the [0, 1] range and do not contain shape information. # Networks are optimized for GPUs and expect CHW ordered inputs. # Raw images are stored in CHW - no need to reorder dimensions. image_shape = [ self._image_shape.channels, self._image_shape.height, self._image_shape.width, ] decoded_image = tf.io.decode_raw(image, tf.float16, little_endian=None) casted_image = tf.cast(decoded_image, tf.float32) processed_image = tf.reshape(casted_image, image_shape) elif self.extension in [".jpg", ".jpeg"]: decoded_image = tf.image.decode_jpeg(image, channels=3) # (H, W, C) [C:RGB] decoded_image.set_shape( [ self._image_shape.height, self._image_shape.width, self._image_shape.channels, ] ) processed_image = tf.cast( tf.transpose(a=decoded_image, perm=[2, 0, 1]), tf.float32 ) processed_image /= 255.0 else: raise ValueError("Unrecognized image extension: {}".format(self.extension)) return processed_image, image_id @lru_cache() def __len__(self): """Return the number of images to visualize.""" return len(self._image_paths) def get_image_properties(self): """Returns the width and height of the images for this source.""" return self._image_shape.width, self._image_shape.height def call(self): """Return a tf.data.Dataset for this data source.""" def generator(): for image_path in self._image_paths: # image_path --> for reading the file. 2nd element is the frame id. yield image_path, os.path.splitext(os.path.basename(image_path))[0] dataset = tf.data.Dataset.from_generator( generator=generator, output_types=tf.string ) # x[0] = image_path, x[1] = frame_id dataset = dataset.map(map_func=lambda x: (tf.io.read_file(x[0]), x[1])) dataset = dataset.map(self._decode_function) return dataset.map( lambda frame, frame_id: types.SequenceExample( instances={ types.FEATURE_CAMERA: types.Images2D( images=frame, canvas_shape=types.Canvas2D( height=self._image_shape.height, width=self._image_shape.width, ), ), types.FEATURE_SESSION: types.Session( uuid=tf.constant("session_uuid"), camera_name=tf.constant("camera_name"), frame_number=tf.constant(0), ), }, labels={}, ) )
tao_tensorflow1_backend-main
nvidia_tao_tf1/blocks/multi_source_loader/sources/image_data_source.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. """Mean Squared Error Loss.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from nvidia_tao_tf1.blocks.losses.loss import Loss class SparseSoftmaxCrossEntropy(Loss): """Sparse softmax cross entropy.""" def __call__(self, labels, predictions): """__call__ method. Calculate the loss. Args: labels (tensor): labels. predictions (tensor): predictions. Returns: loss (tensor). """ loss = tf.compat.v1.losses.sparse_softmax_cross_entropy( labels=labels, logits=predictions ) tf.compat.v1.summary.scalar(name="xentropy_loss", tensor=loss) return loss
tao_tensorflow1_backend-main
nvidia_tao_tf1/blocks/losses/sparse_softmax_cross_entropy.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. """Mean Squared Error Loss.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from nvidia_tao_tf1.blocks.losses.loss import Loss class MseLoss(Loss): """Simple Mean Squared Error Loss.""" def __call__(self, labels, predictions): """__call__ method. Calculate the loss. Args: labels (tensor): labels. predictions (tensor): predictions. Returns: loss (tensor). """ loss = tf.compat.v1.losses.mean_squared_error( labels=labels, predictions=predictions ) tf.compat.v1.summary.scalar(name="mse_loss", tensor=loss) return loss
tao_tensorflow1_backend-main
nvidia_tao_tf1/blocks/losses/mse_loss.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. """Binary Crossentropy Error Loss.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from nvidia_tao_tf1.blocks.losses.loss import Loss from nvidia_tao_tf1.core.coreobject import save_args class BinaryCrossentropyLoss(Loss): """Simple Binary Crossentropy Error Loss.""" @save_args def __init__(self, output_summary=True, reduce_mean=True): """__init__ method. Args: output_summary (bool): Flag to toggle tf summary output (True to write). reduce_mean (bool): Flag to apply the mean of tensor elements (True to apply). """ self.__name__ = "binary_crossentropy" self._output_summary = output_summary self._reduce_mean = reduce_mean def __call__(self, labels, predictions): """__call__ method. Calculate the loss. Args: labels (tensor): Labels. predictions (tensor): Predictions. Returns: loss (tensor). """ losses = tf.keras.losses.binary_crossentropy(labels, predictions) if self._reduce_mean: loss = tf.reduce_mean(input_tensor=losses) else: loss = losses if self._output_summary: tf.compat.v1.summary.scalar( name="binary_crossentropy_loss", tensor=tf.reduce_mean(input_tensor=losses), ) return loss
tao_tensorflow1_backend-main
nvidia_tao_tf1/blocks/losses/binary_crossentropy_loss.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. """Modulus application building block: Losses.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from nvidia_tao_tf1.blocks.losses.absolute_difference_loss import AbsoluteDifferenceLoss from nvidia_tao_tf1.blocks.losses.binary_crossentropy_loss import BinaryCrossentropyLoss from nvidia_tao_tf1.blocks.losses.loss import Loss from nvidia_tao_tf1.blocks.losses.mse_loss import MseLoss from nvidia_tao_tf1.blocks.losses.sparse_softmax_cross_entropy import SparseSoftmaxCrossEntropy __all__ = ( "AbsoluteDifferenceLoss", "BinaryCrossentropyLoss", "Loss", "MseLoss", "SparseSoftmaxCrossEntropy", )
tao_tensorflow1_backend-main
nvidia_tao_tf1/blocks/losses/__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. """Base Loss.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from nvidia_tao_tf1.core.coreobject import TAOObject class Loss(TAOObject): """Loss class.""" def __call__(self, *args, **kwargs): """__call__ method. Compute the loss. Raises: NotImplementedError: should by implemented by subclass. """ raise NotImplementedError()
tao_tensorflow1_backend-main
nvidia_tao_tf1/blocks/losses/loss.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. """Absolute Difference Loss.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from nvidia_tao_tf1.blocks.losses.loss import Loss class AbsoluteDifferenceLoss(Loss): """Simple Absolute Difference Loss.""" def __call__(self, labels, predictions, weights=1.0): """__call__ method. Calculate the loss. Args: labels (tensor): labels. predictions (tensor): predictions. weights (tensor): weights. Default: 1.0. Returns: loss (tensor). """ loss = tf.compat.v1.losses.absolute_difference(labels, predictions, weights) tf.compat.v1.summary.scalar(name="absolute_difference_loss", tensor=loss) return loss
tao_tensorflow1_backend-main
nvidia_tao_tf1/blocks/losses/absolute_difference_loss.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. """Test for binary crossentropy loss function.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow as tf from nvidia_tao_tf1.blocks.losses.binary_crossentropy_loss import BinaryCrossentropyLoss from nvidia_tao_tf1.core.coreobject import deserialize_tao_object def test_serialization_and_deserialization(): """Test that class is a TAOObject that can be serialized and deserialized.""" bce = BinaryCrossentropyLoss() deserialized_bce = deserialize_tao_object(bce.serialize()) assert bce.__name__ == deserialized_bce.__name__ # Test the underlying loss_fn implementation gets serialized/deserialized correctly. y_true = tf.constant([1.0, 1.0, 0.0, 0.0], dtype=np.float32) y_pred = tf.constant([0.9, 0.6, 0.4, 0.7], dtype=np.float32) with tf.compat.v1.Session(): assert bce(y_true, y_pred).eval() == deserialized_bce(y_true, y_pred).eval()
tao_tensorflow1_backend-main
nvidia_tao_tf1/blocks/losses/test_binary_crossentropy_loss.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. """Modulus application building block: Models.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from nvidia_tao_tf1.blocks.models.keras_model import KerasModel from nvidia_tao_tf1.blocks.models.model import Model __all__ = ("KerasModel", "Model")
tao_tensorflow1_backend-main
nvidia_tao_tf1/blocks/models/__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. """Base Model.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from nvidia_tao_tf1.core.coreobject import TAOObject class Model(TAOObject): """Model class.""" pass
tao_tensorflow1_backend-main
nvidia_tao_tf1/blocks/models/model.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. """Base Keras Model.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from abc import abstractmethod from nvidia_tao_tf1.blocks.models.model import Model class KerasModel(Model): """Keras Model class.""" def __init__(self, weights_path=None, **kwargs): """__init__ method.""" super(KerasModel, self).__init__(**kwargs) self._keras_model = self._outputs = None self._weights_path = weights_path @property def keras_model(self): """Return the Keras model built. Returns: keras.Model: Keras model built through the `build` function call. """ return self._keras_model @abstractmethod def build(self, inputs): """ Create a Keras model. Args: inputs (tf.Tensor): input tensor to the model. """ raise NotImplementedError("KerasModel build not implemented") def __call__(self, inputs): """__call__ method. Enables calling KerasModel in a functional style similar to Keras. Calls `build(inputs)` if the Keras model has not been build. Loads weights to model if pretrained_weights_path is specified. Args: inputs (tf.Tensor): input tensor to the model. Returns: list of tf.Tensor: output tensors from the model. """ if not self._keras_model: outputs = self.build(inputs) if self._weights_path: self._keras_model.load_weights(self._weights_path, by_name=True) return outputs[0] if len(outputs) == 1 else outputs return self._keras_model(inputs) def save_model(self, model_file_path): """Save the model to disk. Args: model_file_path: full path to save model. """ self._keras_model.save(model_file_path)
tao_tensorflow1_backend-main
nvidia_tao_tf1/blocks/models/keras_model.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. """Adadelta Optimizer.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from nvidia_tao_tf1.blocks.optimizers.optimizer import Optimizer from nvidia_tao_tf1.core.coreobject import save_args class AdadeltaOptimizer(Optimizer): """AdadeltaOptimizer class.""" @save_args def __init__(self, learning_rate_schedule, rho=0.95, epsilon=1e-8, **kwargs): """__init__ method. learning_rate_schedule (LearningRateSchedule): the object from which we obtain the learning rate scalar tensor. rho (float): A float value or a constant float tensor. The exponential decay rate for the 1st moment estimates. epsilon (float): A small constant for numerical stability. """ super(AdadeltaOptimizer, self).__init__( learning_rate_schedule=learning_rate_schedule, **kwargs ) self._rho = rho self._epsilon = epsilon def build(self): """Build the optimizer. Instantiates the underlying optimizer object. """ self._learning_rate_tensor = self.learning_rate_schedule.learning_rate_tensor self._optimizer = tf.compat.v1.train.AdadeltaOptimizer( learning_rate=self._learning_rate_tensor, rho=self._rho, epsilon=self._epsilon, ) self._distribute()
tao_tensorflow1_backend-main
nvidia_tao_tf1/blocks/optimizers/adadelta_optimizer.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. """Momentum Optimizer.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from nvidia_tao_tf1.blocks.optimizers.optimizer import Optimizer from nvidia_tao_tf1.core.coreobject import save_args class MomentumOptimizer(Optimizer): """Momentum class.""" @save_args def __init__( self, learning_rate_schedule, momentum=0.9, use_nesterov=False, **kwargs ): """__init__ method. learning_rate_schedule (LearningRateSchedule): The object from which we obtain the learning rate scalar tensor. momentum (float): A float value or a constant float tensor. The momentum factor. The method falls back into gradient descend optimizer when momentum is set to 0. use_nesterov (bool): If True, use the Nesterov momentum. """ super(MomentumOptimizer, self).__init__( learning_rate_schedule=learning_rate_schedule, **kwargs ) self._momentum = momentum self._use_nesterov = use_nesterov def build(self): """Build the optimizer. Instantiates the underlying optimizer object. """ self._learning_rate_tensor = self.learning_rate_schedule.learning_rate_tensor self._optimizer = tf.compat.v1.train.MomentumOptimizer( learning_rate=self._learning_rate_tensor, momentum=self._momentum, use_nesterov=self._use_nesterov, ) self._distribute()
tao_tensorflow1_backend-main
nvidia_tao_tf1/blocks/optimizers/momentum_optimizer.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. """Adam Optimizer.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from nvidia_tao_tf1.blocks.optimizers.optimizer import Optimizer from nvidia_tao_tf1.core.coreobject import save_args class AdamOptimizer(Optimizer): """AdamOptimizer class.""" @save_args def __init__( self, learning_rate_schedule, beta1=0.9, beta2=0.999, epsilon=1e-8, **kwargs ): """__init__ method. learning_rate_schedule (LearningRateSchedule): the object from which we obtain the learning rate scalar tensor. beta1 (float): A float value or a constant float tensor. The exponential decay rate for the 1st moment estimates. beta2 (float): A float value or a constant float tensor. The exponential decay rate for the 2nd moment estimates. epsilon (float): A small constant for numerical stability. This epsilon is "epsilon hat" in the Kingma and Ba paper (in the formula just before Section 2.1), not the epsilon in Algorithm 1 of the paper. """ super(AdamOptimizer, self).__init__( learning_rate_schedule=learning_rate_schedule, **kwargs ) self._beta1 = beta1 self._beta2 = beta2 self._epsilon = epsilon def build(self): """Build the optimizer. Instantiates the underlying optimizer object. """ self._learning_rate_tensor = self.learning_rate_schedule.learning_rate_tensor self._optimizer = tf.compat.v1.train.AdamOptimizer( learning_rate=self._learning_rate_tensor, beta1=self._beta1, beta2=self._beta2, epsilon=self._epsilon, ) self._distribute()
tao_tensorflow1_backend-main
nvidia_tao_tf1/blocks/optimizers/adam_optimizer.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. """Optimizer that wraps another tf.Optimizer and applies gradient masks. Potential areas of improvement / TODO: * It would nice to be able to provide masks separately from the optimizer, as that would allow us to delegate potentially complex mask definitions (see the test file for an illustration of why this current design is slightly less geared towards this scenario). However, it is crucial that the (grad, var) pairs be correctly defined, which at this point is done in the `minimize` when we either get the `var_list` as input or just get all trainable variables in the graph. If this is done outside, then users have to make sure gradient masks and trainable variables are given in corresponding orders. * Come up with a way of capturing dependencies between different variables (and therefore masks) This is required when e.g. pruning channel-wise (instead of element-wise), and a layer has both kernel and bias, or is followed by a batch normalization layer. Note that it's also a little fuzzy at this point whether this responsibility belongs here or somewhere else (e.g. in the mechanism that actually does the pruning). """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow as tf from nvidia_tao_tf1.blocks.optimizers.optimizer import Optimizer from nvidia_tao_tf1.core.coreobject import save_args class MaskingOptimizer(Optimizer): """Optimizer that wraps another nvidia_tao_tf1.blocks.Optimizer and applies gradient masks.""" @save_args def __init__(self, optimizer, mask_initial_value=1.0): """Constructor. Args: optimizer (nvidia_tao_tf1.blocks.Optimizer): Original optimizer this one wraps. mask_initial_value (float): Initial value for the masks. The default of 1.0 amounts to the mask being a (mathematical) no-op. """ super(MaskingOptimizer, self).__init__( learning_rate_schedule=optimizer.learning_rate_schedule ) self._optimizer = optimizer self._mask_initial_value = mask_initial_value # These will be updated later on at graph building time. self._optimizer_built = False self._grad_masks = [] self._var_list = [] def build(self): """Build the optimizer.""" self._optimizer.build() self._optimizer_built = True @property def vars_and_grad_masks(self): """Return a handle on the trainable variables and their corresponding masks. Returns: (list): Returns a list of (variable, gradient_mask) tuples. Raises: RuntimeError: If the gradient masks / variables have yet to be defined. """ if len(self._grad_masks) == 0 or len(self._var_list) == 0: raise RuntimeError( "Please call `minimize` or `compute_gradients` beforehand." ) return list(zip(self._var_list, self._grad_masks)) def apply_gradients(self, grads_and_vars, global_step=None, name=None): """Apply gradients. Args: grads_and_vars (list): List of (gradient, variable) pairs as returned by `compute_gradients()`. global_step (tf.Variable): Optional variable to increment by one after the variables have been updated. name (str): Optional name for the returned operation. Default to the name passed to the constructor. Returns: (tf.Operation): An operation that applies the specified gradients. If `global_step` was not `None`, that operation also increments `global_step`. """ return self._optimizer.apply_gradients( grads_and_vars=grads_and_vars, global_step=global_step, name=name ) def compute_gradients(self, loss, var_list=None, **kwargs): """Compute gradients and apply gradient masks. Args: loss (tf.Tensor): A tensor containing the value to compute gradients for. var_list (list): Optional list or tuple of `tf.Variable` to compute gradients for. Defaults to the list of variables collected in the graph under the key `GraphKeys.TRAINABLE_VARIABLES`. gate_gradients: How to gate the computation of gradients. Can be `tf.compat.v1.<GATE_NONE, GATE_OP, GATE_GRAPH>`. aggregation_method: Specifies the method used to combine gradient terms. Valid values are defined in the class `AggregationMethod`. colocate_gradients_with_ops (bool): If `True`, try colocating gradients with the corresponding op. grad_loss (tf.Tensor): Optional. A tensor holding the gradient computed for loss. Returns: A list of (gradient, variable) pairs. Variable is always present, but gradient can be `None`. """ self._build_masks(var_list=var_list) if not self._optimizer_built: self.build() # Compute gradients as you would normally. grads_and_vars = self._optimizer.compute_gradients( loss=loss, var_list=var_list, **kwargs ) # Apply the masks. masked_grads_and_vars = [] for i, (grad, var) in enumerate(grads_and_vars): masked_grad = None if grad is not None: masked_grad = grad * self._grad_masks[i] masked_grads_and_vars.append((masked_grad, var)) self._grads_and_vars = grads_and_vars self._masked_grads_and_vars = masked_grads_and_vars return masked_grads_and_vars def minimize( self, loss, global_step=None, var_list=None, gate_gradients=tf.compat.v1.train.Optimizer.GATE_OP, aggregation_method=None, colocate_gradients_with_ops=False, name=None, grad_loss=None, ): """Minimize op. Args: loss (tf.Tensor): A tensor containing the value to minimize. global_step (tf.Variable): Optional variable to increment by one after the variables have been updated. var_list (list): Optional list or tuple of `tf.Variable` objects to update when minimizing the `loss`. Defaults to the list of variables collected in the graph under the key `GraphKeys.TRAINABLE_VARIABLES`. gate_gradients: How to gate the computation of gradients. Can be `tf.compat.v1.<GATE_NONE, GATE_OP, GATE_GRAPH>`. aggregation_method: Specifies the method used to combine gradient terms. Valid values are defined in the class `AggregationMethod`. colocate_gradients_with_ops (bool): If `True`, try colocating gradients with the corresponding op. name (str): Optional named for the returned operation. grad_loss (tf.Tensor): Optional. A tensor holding the gradient computed for loss. Returns: (tf.Operation): Op that updates the variables in `var_list`. If `global_step` was not `None`, that operation also increments `global_step`. """ # Compute the masked gradients. grads_and_vars = self.compute_gradients( loss=loss, var_list=var_list, gate_gradients=gate_gradients, aggregation_method=aggregation_method, colocate_gradients_with_ops=colocate_gradients_with_ops, grad_loss=grad_loss, ) # Apply the masked gradients. optimize_op = self.apply_gradients( grads_and_vars=grads_and_vars, global_step=global_step, name=name ) return optimize_op def _build_masks(self, var_list=None): """Helper that defines the masks associated with the variables' gradients.""" # Reset. self._grad_masks = [] if var_list is None: var_list = tf.compat.v1.get_collection( tf.compat.v1.GraphKeys.TRAINABLE_VARIABLES ) with tf.compat.v1.variable_scope("grad_mask", reuse=tf.compat.v1.AUTO_REUSE): # This scope allows us to reuse gradient masks that may already have been defined. # This is useful in e.g. the context of multi-task training, where each task may have # its own optimizer on a different set of variables, but some of which are common. For # those variables that are common (e.g. belong to the "feature extractor"), we want # to reuse the same gradient masks (which may also turn out to save on memory usage). # For those variables that are not common, the AUTO_REUSE results in the creation of # a new gradient mask. for var in var_list: initial_value = self._mask_initial_value * np.ones( var.shape.as_list(), dtype=var.dtype.as_numpy_dtype ) # Give the mask variable a name. The string manipulations are necessary for TF not # to complain. mask_name = var.name[: var.name.find(":")] self._grad_masks.append( tf.compat.v1.get_variable( name=mask_name, dtype=var.dtype.base_dtype, initializer=initial_value, trainable=False, ) ) self._var_list = var_list @property def learning_rate_tensor(self): """Handle on the learning rate tensor.""" return self._optimizer.learning_rate_tensor @property def learning_rate_schedule(self): """Handle on the learning rate schedule. Returns: (LearningRateSchedule) """ return self._optimizer.learning_rate_schedule
tao_tensorflow1_backend-main
nvidia_tao_tf1/blocks/optimizers/masking_optimizer.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. """Modulus application building block: Opimizers.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from nvidia_tao_tf1.blocks.optimizers.adadelta_optimizer import AdadeltaOptimizer from nvidia_tao_tf1.blocks.optimizers.adam_optimizer import AdamOptimizer from nvidia_tao_tf1.blocks.optimizers.gradient_descent_optimizer import ( GradientDescentOptimizer, ) from nvidia_tao_tf1.blocks.optimizers.masking_optimizer import MaskingOptimizer from nvidia_tao_tf1.blocks.optimizers.momentum_optimizer import MomentumOptimizer from nvidia_tao_tf1.blocks.optimizers.optimizer import Optimizer from nvidia_tao_tf1.blocks.optimizers.rms_prop_optimizer import RMSPropOptimizer __all__ = ( "AdadeltaOptimizer", "AdamOptimizer", "GradientDescentOptimizer", "MaskingOptimizer", "MomentumOptimizer", "Optimizer", "RMSPropOptimizer", )
tao_tensorflow1_backend-main
nvidia_tao_tf1/blocks/optimizers/__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. """Tests for the MaskingOptimizer.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import mock import numpy as np import pytest import tensorflow as tf from nvidia_tao_tf1.blocks.learning_rate_schedules import ConstantLearningRateSchedule from nvidia_tao_tf1.blocks.optimizers.gradient_descent_optimizer import ( GradientDescentOptimizer, ) from nvidia_tao_tf1.blocks.optimizers.masking_optimizer import MaskingOptimizer from nvidia_tao_tf1.blocks.optimizers.test_fixtures import get_random_boolean_mask from nvidia_tao_tf1.core.training import enable_deterministic_training @pytest.fixture(scope="module", autouse=True) def determinism(): enable_deterministic_training() def test_apply_gradients_forwards_args(): optimizer = mock.Mock() masking_optimizer = MaskingOptimizer(optimizer) grads_and_vars = mock.Mock() global_step = mock.Mock() name = mock.Mock() masking_optimizer.apply_gradients( grads_and_vars=grads_and_vars, global_step=global_step, name=name ) optimizer.apply_gradients.assert_called_once_with( grads_and_vars=grads_and_vars, global_step=global_step, name=name ) class EarlyExitException(Exception): pass def test_compute_gradients_forwards_args(): optimizer = mock.Mock() optimizer.compute_gradients.side_effect = EarlyExitException masking_optimizer = MaskingOptimizer(optimizer) loss = mock.Mock() var_list = mock.Mock() kwargs = {"some_keyword": mock.Mock()} with mock.patch.object(masking_optimizer, "_build_masks"), pytest.raises( EarlyExitException ): masking_optimizer.compute_gradients(loss=loss, var_list=var_list, **kwargs) optimizer.compute_gradients.assert_called_once_with( loss=loss, var_list=var_list, **kwargs ) def _get_optimizer(lr): return GradientDescentOptimizer( learning_rate_schedule=ConstantLearningRateSchedule(lr) ) class SimpleConvModel(object): """Simple 2-layer convolutional model to test with.""" def __init__(self, initial_value=0.125): """Constructor.""" self.initial_value = initial_value self._built = False self.W1 = None self.b1 = None self.W2 = None self.b2 = None @property def trainable_vars(self): return [self.W1, self.b1, self.W2, self.b2] def _build(self, x): if self._built: return # Build W1 and b1. in_channels = x.shape[1] # NCHW out_channels = 7 W1_initial_value = np.ones([3, 3, in_channels, out_channels], dtype=np.float32) W1_initial_value *= self.initial_value self.W1 = tf.Variable(initial_value=W1_initial_value, trainable=True) self.b1 = tf.Variable( initial_value=np.zeros([out_channels], dtype=np.float32), trainable=True ) # Build W2 and b2. in_channels = out_channels out_channels = 13 W2_initial_value = np.ones([5, 5, in_channels, out_channels], dtype=np.float32) W2_initial_value *= self.initial_value self.W2 = tf.Variable(initial_value=W2_initial_value, trainable=True) self.b2 = tf.Variable( initial_value=np.zeros([out_channels], dtype=np.float32), trainable=True ) def __call__(self, x): """Call method.""" self._build(x) # h = W1*x + b1 h = tf.nn.conv2d( input=x, filters=self.W1, strides=1, padding="VALID", data_format="NCHW" ) h = tf.nn.bias_add(value=h, bias=self.b1, data_format="NCHW") # y = W2*h + b2 y = tf.nn.conv2d( input=h, filters=self.W2, strides=1, padding="VALID", data_format="NCHW" ) y = tf.nn.bias_add(value=y, bias=self.b2, data_format="NCHW") return y class TestMaskingScenarios(object): """Tests with some masking happening.""" NUM_STEPS = 3 LEARNING_RATE = 1e-5 @staticmethod def get_loss(model): """Loss tensor to optimize.""" x = tf.ones([3, 5, 16, 32]) # NCHW. y = model(x) y_true = tf.ones_like(y) loss = tf.reduce_sum(input_tensor=tf.compat.v1.squared_difference(y_true, y)) return loss def test_mask_all_variables(self): """Test that if a null mask is applied to every variable, nothing changes.""" model = SimpleConvModel() loss = self.get_loss(model) optimizer = _get_optimizer(lr=self.LEARNING_RATE) masking_optimizer = MaskingOptimizer( optimizer=optimizer, mask_initial_value=0.0 ) min_op = masking_optimizer.minimize(loss=loss, var_list=None) model_var_fetches = model.trainable_vars with tf.compat.v1.Session() as session: session.run(tf.compat.v1.global_variables_initializer()) # Run training for a few steps. Variables should never be updated. initial_values = session.run(model_var_fetches) for _ in range(self.NUM_STEPS): session.run(min_op) final_values = session.run(model_var_fetches) for old, new in zip(initial_values, final_values): np.testing.assert_array_equal(old, new) assert not np.isnan(old).any() @pytest.fixture def regularly_optimized_values(self): """First train a model without any gradient masking.""" model = SimpleConvModel() loss = self.get_loss(model) optimizer = _get_optimizer(lr=self.LEARNING_RATE) min_op = optimizer.minimize(loss=loss, var_list=None) with tf.compat.v1.Session() as session: session.run(tf.compat.v1.global_variables_initializer()) # Run training for a few steps. for _ in range(self.NUM_STEPS): session.run(min_op) final_values = session.run(model.trainable_vars) tf.compat.v1.reset_default_graph() return final_values def test_training_with_no_op_masks_matches_maskless_training( self, regularly_optimized_values ): """Test training with masks set to 1.0.""" model = SimpleConvModel() loss = self.get_loss(model) optimizer = _get_optimizer(lr=self.LEARNING_RATE) masking_optimizer = MaskingOptimizer( optimizer=optimizer, mask_initial_value=1.0 ) min_op = masking_optimizer.minimize(loss=loss, var_list=None) with tf.compat.v1.Session() as session: session.run(tf.compat.v1.global_variables_initializer()) # Run training for a few steps. for _ in range(self.NUM_STEPS): session.run(min_op) masked_final_values = session.run(model.trainable_vars) for expected, actual in zip(regularly_optimized_values, masked_final_values): np.testing.assert_array_equal(expected, actual) assert not np.isnan(expected).any() def test_masks_are_applied_during_training(self): """Test masking at the element level.""" model = SimpleConvModel() loss = self.get_loss(model) optimizer = _get_optimizer(lr=self.LEARNING_RATE) masking_optimizer = MaskingOptimizer( optimizer=optimizer, mask_initial_value=1.0 ) min_op = masking_optimizer.minimize(loss=loss, var_list=None) trainable_vars, grad_masks = zip(*masking_optimizer.vars_and_grad_masks) # Define some explicit assign ops for the masks. assign_ops = [] fine_grained_masks = [] for mask in grad_masks: mask_value = get_random_boolean_mask(shape=mask.shape) fine_grained_masks.append(mask_value) mask_value = mask_value.astype(mask.dtype.as_numpy_dtype) assign_ops.append(tf.compat.v1.assign(mask, mask_value)) with tf.compat.v1.Session() as session: session.run(tf.compat.v1.global_variables_initializer()) initial_values = session.run(trainable_vars) # Set the gradient masks to the values defined above. session.run(assign_ops) # Train for a few steps. for _ in range(self.NUM_STEPS): session.run(min_op) final_values = session.run(trainable_vars) # Now, check that the variable elements whose corresponding mask element was 0 did not # budge, whereas those whose mask element was 1 did. for old, new, mask in zip(initial_values, final_values, fine_grained_masks): zero_indices = np.where(fine_grained_masks == 0.0) one_indices = np.where(fine_grained_masks == 1.0) # These should have been frozen. np.testing.assert_array_equal(old[zero_indices], new[zero_indices]) # These should have changed. assert not np.isclose(old[one_indices], new[one_indices]).any()
tao_tensorflow1_backend-main
nvidia_tao_tf1/blocks/optimizers/test_masking_optimizer.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. """Some test fixtures and utility functions.""" import numpy as np def get_random_boolean_mask(shape): """Get a random boolean mask. Args: shape (list or tuple): Ints indicating the shape of the returned array. Returns: mask (np.array): int32 array with 0s and 1s. """ num_values = np.prod(shape) mask = np.zeros(num_values, dtype=np.int32) # Set half of the values to True. mask[: num_values // 2] = True # In place shuffle. np.random.shuffle(mask) mask = mask.reshape(shape) # Sanity check there's at least one 0.0 and one 1.0. assert mask.min() == 0 assert mask.max() == 1 return mask
tao_tensorflow1_backend-main
nvidia_tao_tf1/blocks/optimizers/test_fixtures.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. """Base Optimizer.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from nvidia_tao_tf1.core.distribution import get_distributor from nvidia_tao_tf1.core.coreobject import TAOObject, save_args class Optimizer(TAOObject): """Optimizer class.""" @save_args def __init__(self, learning_rate_schedule, **kwargs): """__init__ method. learning_rate_schedule (LearningRateSchedule): the object from which we obtain the learning rate scalar tensor. """ super(Optimizer, self).__init__(**kwargs) self._learning_rate_schedule = learning_rate_schedule # This needs to be populated by child implementations of the `build()` method. self._optimizer = None self._learning_rate_tensor = None def build(self): """Build the optimizer. Raises: NotImplementedError: should be subclassed. """ # Note: this is expected to populate the `self._optimizer` field. raise NotImplementedError() def _distribute(self): # This helper can be called by child implementations after everything is # setup in their `build` methods. self._optimizer = get_distributor().distribute_optimizer(self._optimizer) def minimize(self, loss, increment_step=True, **kwargs): """Minimize the loss by computing and applying gradients. Args: loss (tensor): the loss to be minimized. Returns: A tensor operation to be run that performs the minimization. """ if self._optimizer is None: self.build() if "global_step" not in kwargs and increment_step: kwargs["global_step"] = tf.compat.v1.train.get_or_create_global_step() train_op = self._optimizer.minimize(loss=loss, **kwargs) return train_op def compute_gradients(self, *args, **kwargs): """Compute gradients.""" return self._optimizer.compute_gradients(*args, **kwargs) def apply_gradients(self, *args, **kwargs): """Apply gradients.""" return self._optimizer.apply_gradients(*args, **kwargs) @property def learning_rate_tensor(self): """Handle on the learning rate tensor.""" return self._learning_rate_tensor @property def learning_rate_schedule(self): """Handle on the learning rate schedule. Returns: (LearningRateSchedule) """ return self._learning_rate_schedule
tao_tensorflow1_backend-main
nvidia_tao_tf1/blocks/optimizers/optimizer.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. """RMSProp Optimizer.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from nvidia_tao_tf1.blocks.optimizers.optimizer import Optimizer from nvidia_tao_tf1.core.coreobject import save_args class RMSPropOptimizer(Optimizer): """RMSPropOptimizer class.""" @save_args def __init__( self, learning_rate_schedule, gradient_decay_factor, epsilon, **kwargs ): """__init__ method. learning_rate_schedule (LearningRateSchedule): The object from which we obtain the learning rate scalar tensor. gradient_decay_factor (float): Discounting factor for the history/coming gradient. epsilon (float): A small constant for numerical stability. """ super(RMSPropOptimizer, self).__init__( learning_rate_schedule=learning_rate_schedule, **kwargs ) self._gradient_decay_factor = gradient_decay_factor self._epsilon = epsilon def build(self): """Build the optimizer. Instantiates the underlying optimizer object. """ self._learning_rate_tensor = self.learning_rate_schedule.learning_rate_tensor self._optimizer = tf.compat.v1.train.RMSPropOptimizer( learning_rate=self._learning_rate_tensor, decay=self._gradient_decay_factor, epsilon=self._epsilon, ) self._distribute()
tao_tensorflow1_backend-main
nvidia_tao_tf1/blocks/optimizers/rms_prop_optimizer.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. """Gradient Descent Optimizer.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from nvidia_tao_tf1.blocks.optimizers.optimizer import Optimizer from nvidia_tao_tf1.core.coreobject import save_args class GradientDescentOptimizer(Optimizer): """GradientDescentOptimizer class.""" @save_args def __init__(self, learning_rate_schedule, **kwargs): """__init__ method. learning_rate_schedule (LearningRateSchedule): The object from which we obtain the learning rate scalar tensor. """ super(GradientDescentOptimizer, self).__init__( learning_rate_schedule=learning_rate_schedule, **kwargs ) def build(self): """Build the optimizer. Instantiates the underlying optimizer object. """ self._learning_rate_tensor = self.learning_rate_schedule.learning_rate_tensor self._optimizer = tf.compat.v1.train.GradientDescentOptimizer( learning_rate=self._learning_rate_tensor ) self._distribute()
tao_tensorflow1_backend-main
nvidia_tao_tf1/blocks/optimizers/gradient_descent_optimizer.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. """Constant Learning Rate Schedule.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from nvidia_tao_tf1.blocks.learning_rate_schedules.learning_rate_schedule import ( LearningRateSchedule, ) from nvidia_tao_tf1.core.coreobject import save_args class ConstantLearningRateSchedule(LearningRateSchedule): """ConstantLearningRateSchedule class.""" @save_args def __init__(self, learning_rate, **kwargs): """__init__ method. Args: learning_rate (float): learning_rate value to be used. """ super(ConstantLearningRateSchedule, self).__init__(**kwargs) self._learning_rate = learning_rate def get_tensor(self): """Get the learning rate tensor. Returns: scalar tensor (tf.float32) """ return tf.constant(self._learning_rate, dtype=tf.float32)
tao_tensorflow1_backend-main
nvidia_tao_tf1/blocks/learning_rate_schedules/constant_learning_rate_schedule.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. """Exponential Decay Learning Rate Schedule.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from nvidia_tao_tf1.blocks.learning_rate_schedules.learning_rate_schedule import ( LearningRateSchedule, ) from nvidia_tao_tf1.core.coreobject import save_args class ExponentialDecayLearningRateSchedule(LearningRateSchedule): """ExponentialDecayLearningRateSchedule class.""" @save_args def __init__( self, learning_rate, decay_steps, decay_rate, staircase=False, min_learning_rate=0.0, **kwargs ): """__init__ method. decayed_learning_rate = learning_rate * decay_rate ^ (global_step / decay_steps) Args: learning_rate (float): initial learning rate to be used. decay_steps (int): number of steps before next decay. decay_rate (float): the decay rate. staircase (bool): whether to apply decay in a discrete staircase as opposed to continuous fashion. min_learning_rate (float): the minimum learning rate to be used. """ super(ExponentialDecayLearningRateSchedule, self).__init__(**kwargs) self._learning_rate = learning_rate self._decay_steps = decay_steps self._decay_rate = decay_rate self._staircase = staircase self._min_learning_rate = min_learning_rate def get_tensor(self): """Get the learning rate tensor. Returns: scalar tensor (tf.float32) """ global_step = tf.compat.v1.train.get_global_step() lr = tf.compat.v1.train.exponential_decay( self._learning_rate, global_step, self._decay_steps, self._decay_rate, self._staircase, ) learning_rate_tensor = tf.maximum(lr, self._min_learning_rate) tf.compat.v1.summary.scalar(name="learning_rate", tensor=learning_rate_tensor) return learning_rate_tensor
tao_tensorflow1_backend-main
nvidia_tao_tf1/blocks/learning_rate_schedules/exponential_decay_schedule.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. from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from nvidia_tao_tf1.blocks.learning_rate_schedules.softstart_annealing_schedule import ( SoftstartAnnealingLearningRateSchedule, ) class TestSoftstartAnnealingSchedule(tf.test.TestCase): @tf.contrib.eager.run_test_in_graph_and_eager_modes def test_softstart_annealing_schedule(self): """ Test SoftstartAnnealingLearningRateSchedule class. """ base_learning_rate = 1.0 min_learning_rate = 0.1 last_step = 1000 soft_start = 0.05 annealing = 0.5 expected_steps = [1, 200, 400, 600, 800, 999] expected_values = [0.10471285, 1.0, 1.0, 0.63095725, 0.25118864, 0.100461565] schedule = SoftstartAnnealingLearningRateSchedule( base_learning_rate, min_learning_rate, soft_start, annealing, last_step=last_step, ) global_step_tensor = schedule.global_step if not tf.executing_eagerly(): increment_global_step_op = tf.compat.v1.assign( global_step_tensor, global_step_tensor + 1 ) initializer = tf.compat.v1.global_variables_initializer() lr_tensor = schedule.learning_rate_tensor if not tf.executing_eagerly(): self.evaluate(initializer) result_values = [] for _ in range(last_step): if not tf.executing_eagerly(): global_step = self.evaluate(increment_global_step_op) else: global_step = self.evaluate(global_step_tensor.assign_add(1)) lr = self.evaluate(lr_tensor) if global_step in expected_steps: result_values.append(lr) self.assertAllClose(result_values, expected_values)
tao_tensorflow1_backend-main
nvidia_tao_tf1/blocks/learning_rate_schedules/test_softstart_annealing_schedule.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. """Base Learning Rate Schedule.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from abc import abstractmethod import tensorflow as tf from nvidia_tao_tf1.core.coreobject import TAOObject class LearningRateSchedule(TAOObject): """LearningRateSchedule class.""" def __init__(self): """__init__ method. Initialize common private variables. """ self._steps_per_epoch = None @property @abstractmethod def last_step(self): """Gets the last step.""" raise NotImplementedError("Last step is not defined yet.") @property @abstractmethod def global_step(self): """Gets the global step.""" raise NotImplementedError("Global step is not defined yet.") @last_step.setter @abstractmethod def last_step(self, last_step): """Sets the last step. Args: last_step (int): Last step the schedule is made for. """ @global_step.setter @abstractmethod def global_step(self, global_step): """Sets the global step. Args: global_step (tensor): Step at which to get the value of the schedule. """ @property def learning_rate_tensor(self): """Returns a function for the eager mode and a tensor for graph mode.""" if tf.executing_eagerly(): return self.get_tensor return self.get_tensor() @property def steps_per_epoch(self): """Gets the steps per epoch.""" return self._steps_per_epoch @steps_per_epoch.setter def steps_per_epoch(self, steps_per_epoch): """Sets the steps per epoch. Args: steps_per_epoch (int): Number of steps required to consume dataset once. """ self._steps_per_epoch = steps_per_epoch def get_tensor(self, *args, **kwargs): """Get the learning rate tensor. Raises: NotImplementedError: method should be subclassed. """ raise NotImplementedError()
tao_tensorflow1_backend-main
nvidia_tao_tf1/blocks/learning_rate_schedules/learning_rate_schedule.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. """Modulus application building block: Learning Rate Schedules.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from nvidia_tao_tf1.blocks.learning_rate_schedules.constant_learning_rate_schedule import ( ConstantLearningRateSchedule, ) from nvidia_tao_tf1.blocks.learning_rate_schedules.exponential_decay_schedule import ( ExponentialDecayLearningRateSchedule, ) from nvidia_tao_tf1.blocks.learning_rate_schedules.learning_rate_schedule import ( LearningRateSchedule, ) from nvidia_tao_tf1.blocks.learning_rate_schedules.softstart_annealing_schedule import ( SoftstartAnnealingLearningRateSchedule, ) __all__ = ( "ConstantLearningRateSchedule", "ExponentialDecayLearningRateSchedule", "LearningRateSchedule", "SoftstartAnnealingLearningRateSchedule", )
tao_tensorflow1_backend-main
nvidia_tao_tf1/blocks/learning_rate_schedules/__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. """Softstart Annealing Learning Rate Schedule.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from nvidia_tao_tf1.blocks.learning_rate_schedules.learning_rate_schedule import ( LearningRateSchedule, ) import nvidia_tao_tf1.core.hooks.utils from nvidia_tao_tf1.core.coreobject import save_args class SoftstartAnnealingLearningRateSchedule(LearningRateSchedule): r"""SoftstartAnnealingLearningRateSchedule class. The learning rate schedule looks something like this: learning_rate ^ | ______________ <-- base_learning_rate | / | | / \ | / \ | / \ | / \ |- \___ -------------------------------------------> number of global steps taken ^ ^ soft_start annealing (The actual ramp up and ramp down portions are exponential curves). """ @save_args def __init__( self, base_learning_rate, min_learning_rate, soft_start, annealing, last_step=None, **kwargs ): """__init__ method. Args: base_learning_rate (float): Learning rate. min_learning_rate (float): Minimum value the learning rate will be set to. soft_start (float): Number between 0. and 1. indicating the fraction of `last_step` that will be taken before reaching the base_learning rate. annealing (float): Number between 0. and 1. indicating the fraction of `last_step` after which the learning rate ramps down from base_learning rate. last_step (int): Last step the schedule is made for. """ super(SoftstartAnnealingLearningRateSchedule, self).__init__(**kwargs) self._base_learning_rate = base_learning_rate self._min_learning_rate = min_learning_rate self._soft_start = soft_start self._annealing = annealing self._last_step = last_step self._global_step = ( tf.compat.v1.train.get_or_create_global_step() if not tf.executing_eagerly() else tf.Variable(0, dtype=tf.int64) ) @property def last_step(self): """Gets the last step.""" return self._last_step @property def global_step(self): """Gets the global step (tensor).""" if not tf.executing_eagerly(): return tf.compat.v1.train.get_global_step() return self._global_step @last_step.setter def last_step(self, last_step): """Sets the last step. Args: last_step (int): Last step the schedule is made for. """ self._last_step = last_step @global_step.setter def global_step(self, global_step): """Sets the global step. Args: global_step (tensor): Step at which to get the value of the schedule. """ self._global_step = global_step def get_tensor(self): """Get the learning rate tensor. Returns: scalar tensor (tf.float32) """ if not self._last_step: raise ValueError("last step must be > 0. It is {}".format(self._last_step)) learning_rate_tensor = nvidia_tao_tf1.core.hooks.utils.get_softstart_annealing_learning_rate( progress=tf.cast(self.global_step, dtype=tf.float32) / self._last_step, soft_start=self._soft_start, annealing=self._annealing, base_lr=self._base_learning_rate, min_lr=self._min_learning_rate, ) if not tf.executing_eagerly(): tf.compat.v1.summary.scalar( name="learning_rate", tensor=learning_rate_tensor ) return learning_rate_tensor
tao_tensorflow1_backend-main
nvidia_tao_tf1/blocks/learning_rate_schedules/softstart_annealing_schedule.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. from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import pytest import tensorflow as tf from nvidia_tao_tf1.blocks.learning_rate_schedules.exponential_decay_schedule import ( ExponentialDecayLearningRateSchedule, ) @pytest.mark.parametrize( "learning_rate, decay_steps, decay_rate, staircase, min_learning_rate," "expected_steps, expected_values", [ ( 1.0, 25, 0.1, False, 0.0, [26, 51, 71, 101], [0.1, 0.01, 0.0015848934, 0.0001], ), ( 1.0, 25, 0.1, False, 0.0005, [26, 51, 71, 101], [0.1, 0.01, 0.0015848934, 0.0005], ), (1.0, 25, 0.1, True, 0.0, [26, 51, 71, 101], [0.1, 0.01, 0.01, 0.0001]), (1.0, 25, 0.1, True, 0.0005, [26, 51, 71, 101], [0.1, 0.01, 0.01, 0.0005]), ], ) def test_exponential_decay_schedule( learning_rate, decay_steps, decay_rate, staircase, min_learning_rate, expected_steps, expected_values, ): """ Test ExponentialDecayLearningRateSchedule class. """ global_step_tensor = tf.compat.v1.train.get_or_create_global_step() increment_global_step_op = tf.compat.v1.assign( global_step_tensor, global_step_tensor + 1 ) initializer = tf.compat.v1.global_variables_initializer() schedule = ExponentialDecayLearningRateSchedule( learning_rate, decay_steps, decay_rate, staircase, min_learning_rate ) lr_tensor = schedule.get_tensor() result_values = [] sess = tf.compat.v1.Session() with sess.as_default(): sess.run(initializer) for _ in range(110): global_step, lr = sess.run([increment_global_step_op, lr_tensor]) if global_step in expected_steps: result_values.append(lr) assert np.allclose(result_values, expected_values)
tao_tensorflow1_backend-main
nvidia_tao_tf1/blocks/learning_rate_schedules/test_exponential_decay_schedule.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. """Module containing Trainer block for TAO.""" from nvidia_tao_tf1.blocks.trainer.data_loader_interface import DataLoaderInterface from nvidia_tao_tf1.blocks.trainer.trainer import Trainer __all__ = ( "DataLoaderInterface", "Trainer", )
tao_tensorflow1_backend-main
nvidia_tao_tf1/blocks/trainer/__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. """Data loader interface for use with Trainer.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from abc import abstractmethod, abstractproperty import io import sys from nvidia_tao_tf1.core.coreobject import AbstractTAOObject class DataLoaderInterface(AbstractTAOObject): """Interface that has to be implemented by data loaders to be used with Trainer.""" @abstractproperty def steps(self): """Return the number of steps.""" @abstractproperty def batch_size_per_gpu(self): """Return the number of examples each batch contains per gpu.""" @abstractmethod def __len__(self): """Return the total number of examples that will be produced.""" def set_shard(self, shard_count=1, shard_index=0, **kwargs): """ Configure the sharding for the current job. Args: shard_count (int): Number of shards that each dataset will be split into. shard_index (int): Index of shard to use [0, shard_count-1]. """ pass @abstractmethod def summary(self, print_fn=None): """ Print a summary of the contents of this data loader. Args: print_fn (function): Optional function that each line of the summary will be passed to. Prints to stdout if not specified. """ @abstractmethod def call(self): """Produce examples with input features (such as images) and labels. Returns: (Example / SequenceExample) """ @abstractproperty def label_names(self): """Get list of label names that this dataloader can produce. This set must be unique to this dataloader, it cannot overlap with any other dataloader that is being used for training. The purpose of this is to avoid multiple dataloaders accidentally feeding into the same task - if this is your goal, use a multi-source dataloader. Returns: (set<str>) """ def __call__(self): """Produce examples with input features (such as images) and labels. Returns: (Example / SequenceExample) """ return self.call() def __str__(self): """Returns a string summary of this dataloader.""" if sys.version_info >= (3, 0): out = io.StringIO() else: out = io.BytesIO() self.summary(print_fn=lambda string: print(string, file=out)) return out.getvalue()
tao_tensorflow1_backend-main
nvidia_tao_tf1/blocks/trainer/data_loader_interface.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. """Base trainer.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from functools import lru_cache import logging import tensorflow as tf import nvidia_tao_tf1.core as tao_core from nvidia_tao_tf1.core.coreobject import TAOObject, save_args logger = logging.getLogger(__name__) class Trainer(TAOObject): """Trainer class.""" @save_args def __init__(self, dataloader, model, optimizer, loss, hooks=None, **kwargs): """__init__ method. Args: dataloader (DataLoader). model (Model). optimizer (Optimizer). loss (Loss). """ super(Trainer, self).__init__(**kwargs) self._dataloader = dataloader self._model = model self._optimizer = optimizer self._loss = loss self._hooks = [] if hooks is None else hooks tf.compat.v1.train.get_or_create_global_step() def train(self): """Train method. Raises: NotImplementedError: method should be subclassed. """ raise NotImplementedError() @property @lru_cache() def local_init_op(self): """Initialize the local variables. Used with the scaffold. Returns: A tf.Operation that will perform the initialization when evaluated. """ return tf.group( tf.compat.v1.local_variables_initializer(), tf.compat.v1.tables_initializer(), *tf.compat.v1.get_collection("iterator_init") ) @property @lru_cache() def scaffold(self): """Create a Scaffold, used to create and gather parts used for our training loop. Returns: A tf.Scaffold object. """ return tf.compat.v1.train.Scaffold(local_init_op=self.local_init_op) def run_training_loop( self, train_op, hooks, checkpoint_dir=None, checkpoint_filename_with_path=None ): """Run the training loop in a tensorflow session. Args: train_op (tensor): Tensorflow op to be evaluated to take a training step. hooks (list of Hooks): List of Tensorflow Hooks to be used as callbacks while running training. checkpoint_dir (str): for resuming from a checkpoint. If this value is `None` it will not restore variables. If it points to a directory, it will find the latest variable snapshot and resume from there. Default None. checkpoint_filename_with_path (str): For resuming from a checkpoint file. If this value is `None` it will not restore variables. Default None. """ # Save checkpoints only on worker 0 to prevent other workers from corrupting them. # The SingularMonitoredSession takes care of session initialization, # restoring from a checkpoint, saving to a checkpoint, and closing when done # or an error occurs. # Notice we are not using the `MonitoredTrainingSession` variant because that automatically # adds unwanted hooks if a `checkpoint_dir` is provided: and if we do not provide it, # we cannot resume out checkpoint. config = tao_core.distribution.get_distributor().get_config() ignore_keras_values = checkpoint_dir is not None \ or checkpoint_filename_with_path is not None if self._model.keras_model is not None: # KerasModelHook takes care of initializing model variables. hooks.insert( 0, tao_core.hooks.hooks.KerasModelHook( self._model.keras_model, ignore_keras_values ) ) with tf.compat.v1.train.SingularMonitoredSession( hooks=hooks, scaffold=self.scaffold, checkpoint_dir=checkpoint_dir, config=config, checkpoint_filename_with_path=checkpoint_filename_with_path, ) as sess: try: while not sess.should_stop(): # Run training ops with the wrapped session. sess.run(train_op) except (KeyboardInterrupt, SystemExit): logger.info("Training interrupted.")
tao_tensorflow1_backend-main
nvidia_tao_tf1/blocks/trainer/trainer.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. """Tests for TFRecordsDataLoader.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import io import numpy as np from PIL import Image import pytest import tensorflow as tf from nvidia_tao_tf1.blocks.dataloader.tfrecords_dataloader import TFRecordsDataLoader IMAGE_SHAPE = [42, 42] TRAIN = "train" VAL = "val" def _process_record(record_example): feature = { "image": tf.io.FixedLenFeature([], tf.string), "label": tf.io.FixedLenFeature([], tf.float32), } example = tf.io.parse_single_example(serialized=record_example, features=feature) image = tf.image.decode_jpeg(example["image"], channels=3) return image, example["label"] def _get_image_and_label(dataloader, mode): tf_dataset = dataloader(mode) iterator = tf.compat.v1.data.make_one_shot_iterator(tf_dataset()) image, label = iterator.get_next() return image, label def _create_test_tfrecord(tmpdir): record_file = str(tmpdir.join("test.tfrecord")) writer = tf.io.TFRecordWriter(record_file) temp_img = Image.new("RGB", IMAGE_SHAPE) output = io.BytesIO() temp_img.save(output, format="JPEG") fake_image = output.getvalue() feature = { "image": tf.train.Feature(bytes_list=tf.train.BytesList(value=[fake_image])), "label": tf.train.Feature(float_list=tf.train.FloatList(value=[42])), } example = tf.train.Example(features=tf.train.Features(feature=feature)) writer.write(example.SerializeToString()) @pytest.mark.parametrize("mode", [TFRecordsDataLoader.TRAIN, TFRecordsDataLoader.VAL]) def test_tfrecords_dataloader(mode, tmpdir): """Test TFRecord dataloader using generated tfrecords and images.""" _create_test_tfrecord(tmpdir) if mode == TFRecordsDataLoader.TRAIN: dataloader = TFRecordsDataLoader(str(tmpdir), "", IMAGE_SHAPE, 1) else: dataloader = TFRecordsDataLoader("", str(tmpdir), IMAGE_SHAPE, 1) # Override process record method to handle features defined for the test case. dataloader._process_record = _process_record image, label = _get_image_and_label(dataloader, mode) with tf.compat.v1.Session() as sess: image_eval, label_eval = sess.run([tf.reduce_sum(input_tensor=image), label]) np.testing.assert_equal(image_eval, 0.0) np.testing.assert_equal(label_eval, 42.0)
tao_tensorflow1_backend-main
nvidia_tao_tf1/blocks/dataloader/test_tfrecords_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. """Modulus application building block: Data Loaders.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from nvidia_tao_tf1.blocks.dataloader.dataloader import DataLoader from nvidia_tao_tf1.blocks.dataloader.tfrecords_dataloader import TFRecordsDataLoader __all__ = ("DataLoader", "TFRecordsDataLoader")
tao_tensorflow1_backend-main
nvidia_tao_tf1/blocks/dataloader/__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. """Base Data Loader.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from nvidia_tao_tf1.core.coreobject import TAOObject class DataLoader(TAOObject): """DataLoader class.""" pass
tao_tensorflow1_backend-main
nvidia_tao_tf1/blocks/dataloader/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. """TFRecords Dataloader Example.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import tensorflow as tf from nvidia_tao_tf1.blocks.dataloader.dataloader import DataLoader class TFRecordsDataLoader(DataLoader): """Dataloader for loading TFRecords based datasets.""" TRAIN = "train" VAL = "val" SUPPORTED_MODES = [TRAIN, VAL] def __init__( self, train_records_folder, val_records_folder, input_shape, batch_size, buffer_size=None, repeats=1, ): """__init__ method. Args: train_records_folder (string): The path where the training TFRecords are. val_records_folder (string): The path where the validation TFRecords are. input_shape ([int, int]): The shape size expected to resize the images to. batch_size (int): Size of each batch to be fed for training. buffer_size (int): Size of the shuffle buffer for feeding in data. Default is 8 * batch_size. repeats (int): Number of times to repeat the dataset. Default 1. """ super(TFRecordsDataLoader, self).__init__() self._train_records_folder = train_records_folder self._val_records_folder = val_records_folder self._input_shape = input_shape self._batch_size = batch_size self._buffer_size = buffer_size self._repeats = repeats if not self._buffer_size: self._buffer_size = 8 * self._batch_size def __call__(self, mode): """__call__ method. Args: mode (string): Specifies whether to get the training or validation dataset. Must be one of 'train' or 'val' Returns: (function) The function associated with the dataset and split. """ if mode not in self.SUPPORTED_MODES: raise "Mode must be one of {}.".format(self.SUPPORTED_MODES) if mode == self.TRAIN: return self._get_train_content return self._get_val_content def _get_train_content(self): """Gets the training contents inside a TFDataset.""" dataset = self._create_dataset(self._train_records_folder) if self._repeats: dataset = dataset.repeat(self._repeats) return dataset def _get_val_content(self): """Gets the validation contents inside a TFDataset.""" return self._create_dataset(self._val_records_folder) def _create_dataset(self, folder): """Method to process the files and return a dataset object.""" files = [os.path.join(folder, x) for x in os.listdir(folder)] dataset = tf.data.TFRecordDataset(files) dataset = self._process_tfrecord_dataset(dataset) dataset = dataset.map(self._process_record) dataset = dataset.batch(self._batch_size) dataset = dataset.shuffle(self._buffer_size) return dataset def _process_tfrecord_dataset(self, dataset): """Method placeholder for dataset processing.""" return dataset def _process_record(self, record_example): """Method placeholder for single record processing.""" raise NotImplementedError("Implement me!")
tao_tensorflow1_backend-main
nvidia_tao_tf1/blocks/dataloader/tfrecords_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 TF1 core module.""" from nvidia_tao_tf1.core import decorators from nvidia_tao_tf1.core import distribution from nvidia_tao_tf1.core import export from nvidia_tao_tf1.core import hooks from nvidia_tao_tf1.core import models from nvidia_tao_tf1.core import processors from nvidia_tao_tf1.core import pruning from nvidia_tao_tf1.core import templates from nvidia_tao_tf1.core import utils __all__ = ( "decorators", "distribution", "export", "hooks", "models", "processors", "pruning", "templates", "utils", )
tao_tensorflow1_backend-main
nvidia_tao_tf1/core/__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. """Modulus standard types.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from nvidia_tao_tf1.core.types.types import Canvas2D from nvidia_tao_tf1.core.types.types import data_format from nvidia_tao_tf1.core.types.types import DataFormat from nvidia_tao_tf1.core.types.types import Example from nvidia_tao_tf1.core.types.types import set_data_format from nvidia_tao_tf1.core.types.types import Transform __all__ = ( "Canvas2D", "data_format", "DataFormat", "Example", "set_data_format", "Transform", )
tao_tensorflow1_backend-main
nvidia_tao_tf1/core/types/__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. """Modulus standard types.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from collections import namedtuple import tensorflow as tf Example = namedtuple("Example", ["instances", "labels"]) Canvas2D = namedtuple("Canvas2D", ["height", "width"]) Transform = namedtuple( "Transform", ["canvas_shape", "color_transform_matrix", "spatial_transform_matrix"] ) class DataFormat(object): """Structure to hold the dataformat types. NOTE: HumanLoop's export format of fp16 is typically CHW (channels first) and BGR, while OpenCV defaults to HWC (channels last) and BGR. """ CHANNELS_FIRST = "channels_first" CHANNELS_LAST = "channels_last" @staticmethod def convert(tensor, from_format, to_format): """Helper function for handling data format conversions for 3D and 4D tf tensors. Args: tensor (Tensor): A 4D or 3D input tensor. from_format (str): Data format of input tensor, can be either 'channels_first' (NCHW / CHW) or 'channels_last' (NHWC / HWC). to_format (str): Data format of output tensor, can be either 'channels_first' (NCHW / CHW) or 'channels_last' (NHWC / HWC). Returns: Tensor: Transposed input tensor with 'to_format' as the data format. """ assert from_format in [DataFormat.CHANNELS_FIRST, DataFormat.CHANNELS_LAST] assert to_format in [DataFormat.CHANNELS_FIRST, DataFormat.CHANNELS_LAST] ndims = tensor.shape.ndims if ndims not in [3, 4]: raise NotImplementedError( "Input tensor should be of rank 3 or 4, given {}.".format(ndims) ) if from_format == to_format: return tensor if ( from_format == DataFormat.CHANNELS_FIRST and to_format == DataFormat.CHANNELS_LAST ): if ndims == 4: return tf.transpose(a=tensor, perm=(0, 2, 3, 1)) return tf.transpose(a=tensor, perm=(1, 2, 0)) # Channels last to channels first case. if ndims == 4: return tf.transpose(a=tensor, perm=(0, 3, 1, 2)) return tf.transpose(a=tensor, perm=(2, 0, 1)) _DATA_FORMAT = DataFormat.CHANNELS_FIRST def set_data_format(data_format): """Set the default Modulus data format.""" global _DATA_FORMAT # pylint: disable=W0603 if data_format not in [DataFormat.CHANNELS_FIRST, DataFormat.CHANNELS_LAST]: raise ValueError("Data format `{}` not supported.".format(data_format)) _DATA_FORMAT = data_format def data_format(): """Get the default Modulus data format.""" global _DATA_FORMAT # pylint: disable=W0602,W0603 return _DATA_FORMAT
tao_tensorflow1_backend-main
nvidia_tao_tf1/core/types/types.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. from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import pytest import tensorflow as tf from nvidia_tao_tf1.core.types import Canvas2D from nvidia_tao_tf1.core.types import data_format from nvidia_tao_tf1.core.types import DataFormat from nvidia_tao_tf1.core.types import Example from nvidia_tao_tf1.core.types import set_data_format from nvidia_tao_tf1.core.types import Transform def test_Canvas2D(): """Test Canvas2D namedtuple.""" fields = ("height", "width") assert getattr(Canvas2D, "_fields") == fields def test_Example(): """Test Example namedtuple.""" fields = ("instances", "labels") assert getattr(Example, "_fields") == fields def test_Transform(): """Test Transform namedtuple.""" fields = ("canvas_shape", "color_transform_matrix", "spatial_transform_matrix") assert getattr(Transform, "_fields") == fields def test_default_data_format(): """Test modulus default data format.""" assert data_format() == "channels_first" @pytest.mark.repeat(3) @pytest.mark.parametrize( "data_fmt", [DataFormat.CHANNELS_FIRST, DataFormat.CHANNELS_LAST] ) def test_set_data_format(data_fmt): """Test for set data format.""" set_data_format(data_fmt) assert data_format() == data_fmt @pytest.mark.parametrize( "from_format", [DataFormat.CHANNELS_FIRST, DataFormat.CHANNELS_LAST] ) @pytest.mark.parametrize( "to_format", [DataFormat.CHANNELS_FIRST, DataFormat.CHANNELS_LAST] ) @pytest.mark.parametrize("input_shape", [(1, 2, 3, 4), (1, 2, 3), (1, 2)]) def test_data_format_convert(from_format, to_format, input_shape): """Test for convert tensor format""" t = tf.constant(np.ones(input_shape)) sess = tf.compat.v1.Session() input_dims = len(input_shape) if input_dims not in [3, 4]: with pytest.raises(NotImplementedError): sess.run(DataFormat.convert(t, from_format, to_format)) else: output_np = sess.run(DataFormat.convert(t, from_format, to_format)) if from_format == to_format: expected_shape = input_shape assert output_np.shape == expected_shape elif to_format == DataFormat.CHANNELS_LAST: expected_order = [0, 2, 3, 1] if input_dims == 4 else [1, 2, 0] expected_shape = [input_shape[i] for i in expected_order] assert list(output_np.shape) == expected_shape elif to_format == DataFormat.CHANNELS_FIRST: expected_order = [0, 3, 1, 2] if input_dims == 4 else [2, 0, 1] expected_shape = [input_shape[i] for i in expected_order] assert list(output_np.shape) == expected_shape
tao_tensorflow1_backend-main
nvidia_tao_tf1/core/types/types_test.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. from __future__ import absolute_import from __future__ import division from __future__ import print_function import pytest from nvidia_tao_tf1.core.decorators import override, subclass class Foo(object): """Dummy class to test @override decorator.""" def bar(self): pass class TestOverride(object): """Test that @override decorator works as expected.""" def test_invalid_override(self): # pylint: disable=unused-variable with pytest.raises(AssertionError): @subclass class FooChild(Foo): @override def barz(self): pass def test_valid_override(self): # pylint: disable=unused-variable @subclass class FooChild(Foo): @override def bar(self): pass
tao_tensorflow1_backend-main
nvidia_tao_tf1/core/decorators/test_decorators.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. """Modulus decorator APIs.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from nvidia_tao_tf1.core.decorators.arg_scope import add_arg_scope, arg_scope from nvidia_tao_tf1.core.decorators.decorators import override, subclass __all__ = ("add_arg_scope", "arg_scope", "override", "subclass")
tao_tensorflow1_backend-main
nvidia_tao_tf1/core/decorators/__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. from __future__ import absolute_import from __future__ import division from __future__ import print_function import pytest from nvidia_tao_tf1.core.decorators.arg_scope import add_arg_scope, arg_scope class FooBarClass(object): def get_foo_bar(self): return self.foo, self.bar class ScopedClass(FooBarClass): @add_arg_scope def __init__(self, foo=None, bar=None): self.foo = foo self.bar = bar class UnscopedClass(FooBarClass): def __init__(self, foo=None, bar=None): self.foo = foo self.bar = bar class MethodClass(FooBarClass): @add_arg_scope def scoped_set_foo_bar(self, foo=None, bar=None): self.foo = foo self.bar = bar return self def unscoped_set_foo_bar(self, foo=None, bar=None): self.foo = foo self.bar = bar return self @add_arg_scope def scoped_func(foo=None, bar=None): return foo, bar def unscoped_func(foo=None, bar=None): return foo, bar foo_arg = "spam" bar_arg = "eggs" @pytest.mark.parametrize("foo_arg", [None, "spam"]) @pytest.mark.parametrize("bar_arg", [None, "eggs"]) def test_init_scope(foo_arg, bar_arg): """Test argument scoping on (initializers of) objects.""" # Test unscoped case assert ScopedClass().get_foo_bar() == (None, None) assert UnscopedClass().get_foo_bar() == (None, None) kwargs = {} if foo_arg: kwargs.update({"foo": foo_arg}) if bar_arg: kwargs.update({"bar": bar_arg}) with arg_scope([ScopedClass], **kwargs): assert ScopedClass().get_foo_bar() == (foo_arg, bar_arg) assert UnscopedClass().get_foo_bar() == (None, None) # Test we can still override assert ScopedClass(foo="dog").get_foo_bar() == ("dog", bar_arg) assert ScopedClass(foo="dog", bar="cat").get_foo_bar() == ("dog", "cat") # Test unscoped case again to make sure the previous scoping has reset assert ScopedClass().get_foo_bar() == (None, None) assert UnscopedClass().get_foo_bar() == (None, None) @pytest.mark.parametrize("foo_arg", [None, "spam"]) @pytest.mark.parametrize("bar_arg", [None, "eggs"]) def test_method_scope(foo_arg, bar_arg): """Test argument scoping on methods.""" # Test unscoped case assert MethodClass().scoped_set_foo_bar().get_foo_bar() == (None, None) assert MethodClass().unscoped_set_foo_bar().get_foo_bar() == (None, None) kwargs = {} if foo_arg: kwargs.update({"foo": foo_arg}) if bar_arg: kwargs.update({"bar": bar_arg}) with arg_scope([MethodClass.scoped_set_foo_bar], **kwargs): assert MethodClass().scoped_set_foo_bar().get_foo_bar() == (foo_arg, bar_arg) assert MethodClass().unscoped_set_foo_bar().get_foo_bar() == (None, None) # Test we can still override assert MethodClass().scoped_set_foo_bar(foo="dog").get_foo_bar() == ( "dog", bar_arg, ) assert MethodClass().unscoped_set_foo_bar( foo="dog", bar="cat" ).get_foo_bar() == ("dog", "cat") # Test unscoped case again to make sure the previous scoping has reset assert MethodClass().scoped_set_foo_bar().get_foo_bar() == (None, None) assert MethodClass().unscoped_set_foo_bar().get_foo_bar() == (None, None) @pytest.mark.parametrize("foo_arg", [None, "spam"]) @pytest.mark.parametrize("bar_arg", [None, "eggs"]) def test_function_scope(foo_arg, bar_arg): """Test argument scoping on functions.""" # Test unscoped state assert scoped_func() == (None, None) assert unscoped_func() == (None, None) kwargs = {} if foo_arg: kwargs.update({"foo": foo_arg}) if bar_arg: kwargs.update({"bar": bar_arg}) with arg_scope([scoped_func], **kwargs): assert scoped_func() == (foo_arg, bar_arg) assert unscoped_func() == (None, None) # Test if we can override assert scoped_func(foo="dog") == ("dog", bar_arg) assert scoped_func(foo="dog", bar="cat") == ("dog", "cat") # Test unscoped state again to make sure the previous scope was reset assert scoped_func() == (None, None) assert unscoped_func() == (None, None) def test_kwargs(): """Test if we can pass in arbitrary kwargs, even if not explicitly defined.""" @add_arg_scope def scoped_func_kwarg(**kwargs): return kwargs expected = {"foo": "spam", "bar": "eggs"} with arg_scope([scoped_func_kwarg], **expected): assert scoped_func_kwarg() == expected def test_multiple_scope_targets(): """Test that we can scope multiple targets with the same kwargs.""" @add_arg_scope def scoped_func_a(foo=None, a=None): return foo @add_arg_scope def scoped_func_b(foo=None, b=None): return foo with arg_scope([scoped_func_a, scoped_func_b], foo=foo_arg): assert scoped_func_a() == foo_arg assert scoped_func_b() == foo_arg def test_unscoped_scope_fail(): """Test verification if the target has scoping when requested.""" with pytest.raises(ValueError): with arg_scope([unscoped_func], foo=foo_arg): pass
tao_tensorflow1_backend-main
nvidia_tao_tf1/core/decorators/test_arg_scope.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. # Below file has been copied and adapted for our purposes from the Tensorflow project # ============================================================================== # Copyright 2016 The TensorFlow Authors. 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. # ============================================================================== """Contains the arg_scope used for scoping arguments to methods or object initializers. Allows one to define methods and objects much more compactly by eliminating boilerplate code. This is accomplished through the use of argument scoping (arg_scope). Example of how to use arg_scope: With an object initializer: Setting the context manager arg scope target to a class is equivalent to setting it to its __init__ method. ``` class Foo(object): @add_arg_scope def __init__(self, backend=None): print('Foo(backend=%s)' % backend) with arg_scope([Foo], backend='tensorflow'): net = Foo() ``` With a method: ``` @add_arg_scope def foo(backend=None): print('foo(backend=%s)' % backend) with arg_scope([foo], backend='tensorflow'): net = foo() ``` """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import contextlib import functools import inspect _ARGSTACK = [{}] _DECORATED_OPS = {} def _get_arg_stack(): if _ARGSTACK: return _ARGSTACK _ARGSTACK.append({}) return _ARGSTACK def _current_arg_scope(): stack = _get_arg_stack() return stack[-1] def _key_op(op): return getattr(op, "_key_op", str(op)) def _name_op(op): return (op.__module__, op.__name__) def _kwarg_names(func): kwargs_length = len(func.__defaults__) if func.__defaults__ else 0 return func.__code__.co_varnames[-kwargs_length : func.__code__.co_argcount] def _add_op(op): key_op = _key_op(op) if key_op not in _DECORATED_OPS: _DECORATED_OPS[key_op] = _kwarg_names(op) @contextlib.contextmanager def arg_scope(list_ops_or_scope, **kwargs): """Store the default arguments for the given set of list_ops. For usage, please see examples at top of the file. Args: list_ops_or_scope: List or tuple of operations to set argument scope for or a dictionary containing the current scope. When list_ops_or_scope is a dict, kwargs must be empty. When list_ops_or_scope is a list or tuple, then every op in it need to be decorated with @add_arg_scope to work. **kwargs: keyword=value that will define the defaults for each op in list_ops. All the ops need to accept the given set of arguments. Yields: the current_scope, which is a dictionary of {op: {arg: value}} Raises: TypeError: if list_ops is not a list or a tuple. ValueError: if any op in list_ops has not be decorated with @add_arg_scope. """ if isinstance(list_ops_or_scope, dict): # Assumes that list_ops_or_scope is a scope that is being reused. if kwargs: raise ValueError( "When attempting to re-use a scope by suppling a" "dictionary, kwargs must be empty." ) current_scope = list_ops_or_scope.copy() try: _get_arg_stack().append(current_scope) yield current_scope finally: _get_arg_stack().pop() else: # Assumes that list_ops_or_scope is a list/tuple of ops with kwargs. if not isinstance(list_ops_or_scope, (list, tuple)): raise TypeError( "list_ops_or_scope must either be a list/tuple or reused" "scope (i.e. dict)" ) try: current_scope = _current_arg_scope().copy() for op in list_ops_or_scope: if inspect.isclass(op): # If we decorated a class, use the scope on the initializer op = op.__init__ key_op = _key_op(op) if not has_arg_scope(op): raise ValueError( "%s::%s is not decorated with @add_arg_scope" % _name_op(op) ) if key_op in current_scope: current_kwargs = current_scope[key_op].copy() current_kwargs.update(kwargs) current_scope[key_op] = current_kwargs else: current_scope[key_op] = kwargs.copy() _get_arg_stack().append(current_scope) yield current_scope finally: _get_arg_stack().pop() def add_arg_scope(func): """Decorate a function with args so it can be used within an arg_scope. Args: func: function to decorate. Returns: A tuple with the decorated function func_with_args(). """ @functools.wraps(func) def func_with_args(*args, **kwargs): current_scope = _current_arg_scope() current_args = kwargs key_func = _key_op(func) if key_func in current_scope: current_args = current_scope[key_func].copy() current_args.update(kwargs) return func(*args, **current_args) _add_op(func) setattr(func_with_args, "_key_op", _key_op(func)) setattr(func_with_args, "__doc__", func.__doc__) return func_with_args def has_arg_scope(func): """Check whether a func has been decorated with @add_arg_scope or not. Args: func: function to check. Returns: a boolean. """ return _key_op(func) in _DECORATED_OPS def arg_scoped_arguments(func): """Return the list kwargs that arg_scope can set for a func. Args: func: function which has been decorated with @add_arg_scope. Returns: a list of kwargs names. """ assert has_arg_scope(func) return _DECORATED_OPS[_key_op(func)]
tao_tensorflow1_backend-main
nvidia_tao_tf1/core/decorators/arg_scope.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. """Modulus decorators.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import inspect 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, '"%s.%s" not found in any base class' % ( class_object.__name__, name, ) return class_object
tao_tensorflow1_backend-main
nvidia_tao_tf1/core/decorators/decorators.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. from __future__ import absolute_import from __future__ import division from __future__ import print_function import unittest from nvidia_tao_tf1.core.coreobject import deserialize_tao_object, TAOObject, save_args from nvidia_tao_tf1.core.coreobject.corekeywordobject import TAOKeywordObject from nvidia_tao_tf1.core.coreobject.coreobject import _get_kwargs from nvidia_tao_tf1.core.coreobject.test_data import addressbook_pb2 class TAOAddressBookBuilder(TAOObject): @save_args def __init__(self, proto_obj, *args, **kwargs): # pylint: disable=W1113 super(TAOAddressBookBuilder, self).__init__(*args, **kwargs) self.addressBook = proto_obj class TestTAOKeywordObject(unittest.TestCase): def test_corekeywordobject_params(self): a = TAOKeywordObject(arg1="1", arg2="2", arg3="3") self.assertTrue(hasattr(a, "arg1")) self.assertTrue(hasattr(a, "arg2")) self.assertTrue(hasattr(a, "arg3")) self.assertEqual(a.arg1, "1") self.assertEqual(a.arg2, "2") self.assertEqual(a.arg3, "3") def test_corekeywordobject_serialization(self): a = TAOKeywordObject(arg1="1", arg2="2", arg3="3") data = a.serialize() config = _get_kwargs(data) self.assertIn("arg1", config.keys()) self.assertFalse( set(["arg1", "arg2", "arg3"]).difference(set(_get_kwargs(data).keys())) ) def _get_protobuf_for_test(self): # Create a protobuf object. addressbook = addressbook_pb2.MaglevAddressBook() person = addressbook.people.add() person.id = 1234 person.full_name = "John Doe" person.email = "[email protected]" phone = person.phones.add() phone.number = "555-4321" phone.type = addressbook_pb2.MaglevPerson.HOME return addressbook def test_protobuf_serialize(self): addressbook = self._get_protobuf_for_test() a = TAOAddressBookBuilder(addressbook) data = a.serialize() config = _get_kwargs(data) self.assertIn("proto_obj", config) proto_obj = config["proto_obj"] config = _get_kwargs(proto_obj) self.assertIn("people", config) people = config["people"] self.assertIsInstance(people, list) def test_protobuf_deserialize(self): addressbook = self._get_protobuf_for_test() a = TAOAddressBookBuilder(addressbook) data = a.serialize() o = deserialize_tao_object(data) self.assertIsInstance(o, TAOAddressBookBuilder) self.assertIsInstance(o.addressBook, TAOKeywordObject) ab = o.addressBook self.assertTrue(ab.people) self.assertIsInstance(ab.people[0], TAOKeywordObject) person = ab.people[0] self.assertEqual(person.full_name, "John Doe") self.assertIsInstance(person.phones[0], TAOKeywordObject) phone_number = person.phones[0] self.assertEqual(phone_number.number, "555-4321") self.assertEqual(phone_number.type, addressbook_pb2.MaglevPerson.HOME)
tao_tensorflow1_backend-main
nvidia_tao_tf1/core/coreobject/test_corekeywordobject.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. """ModulusObject APIs.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from nvidia_tao_tf1.core.coreobject.corekeywordobject import TAOKeywordObject from nvidia_tao_tf1.core.coreobject.coreobject import AbstractTAOObject from nvidia_tao_tf1.core.coreobject.coreobject import __doc__ # noqa pylint: disable=W0622 from nvidia_tao_tf1.core.coreobject.coreobject import deserialize_tao_object from nvidia_tao_tf1.core.coreobject.coreobject import TAOObject from nvidia_tao_tf1.core.coreobject.coreobject import MetaTAOObject from nvidia_tao_tf1.core.coreobject.coreobject import register_tao_function from nvidia_tao_tf1.core.coreobject.coreobject import save_args __all__ = ( "AbstractTAOObject", "deserialize_tao_object", "TAOObject", "MetaTAOObject", "TAOKeywordObject", "register_tao_function", "save_args", )
tao_tensorflow1_backend-main
nvidia_tao_tf1/core/coreobject/__init__.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import from __future__ import division from __future__ import print_function import json from parameterized import parameterized import pytest import yaml from nvidia_tao_tf1.core.coreobject import deserialize_tao_object, TAOObject, save_args from nvidia_tao_tf1.core.coreobject.test_fixtures import ( get_duplicated_tao_object_child_class, MY_RETURN_VALUE, my_test_function, ) class TAOObjectChild(TAOObject): @save_args def __init__( self, arg1, arg2="default_arg2_val", *args, **kwargs ): # pylint: disable=W1113 super(TAOObjectChild, self).__init__(*args, **kwargs) self.arg1 = arg1 self.arg2 = arg2 class TAOObjectGrandChild(TAOObjectChild): @save_args def __init__( self, arg3, arg4="default_arg4_val", *args, **kwargs ): # pylint: disable=W1113 super(TAOObjectGrandChild, self).__init__(*args, **kwargs) class TAOObjectGrandChildWithSameArg(TAOObjectChild): @save_args def __init__( self, arg1, arg3, arg4="default_arg4_val", *args, **kwargs ): # pylint: disable=W1113 super(TAOObjectGrandChildWithSameArg, self).__init__(arg1, *args, **kwargs) class TAOObjectGrandChildWithSameArgAndDifferentValue(TAOObjectChild): @save_args def __init__(self, arg1, arg2, *args, **kwargs): super(TAOObjectGrandChildWithSameArgAndDifferentValue, self).__init__( arg1, **kwargs ) class NonTAOObjectChild(object): @save_args def __init__( self, arg1, arg2="default_arg2_val", *args, **kwargs ): # pylint: disable=W1113 super(NonTAOObjectChild, self).__init__(*args, **kwargs) class TestTAOObjectSaveArgs(object): """Test class for @save_args decorator on TAOObject.""" def test_child(self): a = TAOObjectChild("arg1_val") data = a.serialize() assert "arg1" in data assert data["arg1"] == "arg1_val" assert "arg2" in data assert data["arg2"] == "default_arg2_val" def test_child_arg_is_maglev_obj(self): a = TAOObjectChild("arg1_val", arg2="arg2_val") b = TAOObjectChild(arg1=a) data = b.serialize() assert "arg1" in data b_arg1 = data["arg1"] # The child was defined in this module. assert b_arg1["__class_name__"] == __name__ + "." + "TAOObjectChild" assert b_arg1["arg1"] == "arg1_val" assert b_arg1["arg2"] == "arg2_val" assert "arg2" in data assert data["arg2"] == "default_arg2_val" def test_error_on_non_maglev_obj(self): with pytest.raises(ValueError): NonTAOObjectChild("arg1_val") def test_missing_required_argument_error(self): with pytest.raises(TypeError): TAOObjectChild() with pytest.raises(TypeError): TAOObjectChild(arg2="arg2_val") with pytest.raises(TypeError): TAOObjectGrandChild(arg3="arg3_val") def test_grand_child(self): a = TAOObjectGrandChild(arg1="arg1_val", arg2="arg2_val", arg3="arg3_val") data = a.serialize() assert "arg1" in data assert data["arg1"] == "arg1_val" assert "arg2" in data assert data["arg2"] == "arg2_val" assert "arg3" in data assert data["arg3"] == "arg3_val" assert "arg4" in data assert data["arg4"] == "default_arg4_val" def test_grand_child_with_same_arg(self): a = TAOObjectGrandChildWithSameArg(arg1="arg1_val", arg3="arg3_val") data = a.serialize() assert "arg1" in data assert data["arg1"] == "arg1_val" assert "arg2" in data assert data["arg2"] == "default_arg2_val" assert "arg3" in data assert data["arg3"] == "arg3_val" assert "arg4" in data assert data["arg4"] == "default_arg4_val" def test_grand_child_with_same_arg_and_different_value(self): with pytest.raises(ValueError): TAOObjectGrandChildWithSameArgAndDifferentValue( arg1="arg1_val", arg2="arg2_val" ) def test_object_in_object(self, val_a="val_a"): a = TAOObjectChild(arg1=val_a) b = TAOObjectChild(arg1=a) data = b.serialize() assert data["arg1"]["arg1"] == val_a def test_object_list_in_arg(self, val_a="val_a", val_b="val_b"): a = TAOObjectChild(arg1=val_a) b = TAOObjectChild(arg1=val_b) c = TAOObjectChild(arg1=[a, b]) data = c.serialize() assert len(data["arg1"]) == 2 assert data["arg1"][0]["arg1"] == val_a assert data["arg1"][1]["arg1"] == val_b def test_eq_with_maglev_object_same_arg(self, val_a="val_a"): a = TAOObjectChild(arg1=val_a) b = TAOObjectChild(arg1=val_a) assert a == b def test_eq_with_maglev_object_diff_arg(self): a = TAOObjectChild(arg1="val_a") b = TAOObjectChild(arg1="val_b") assert not a == b def test_eq_with_not_maglev_object(self, val_a="val_a"): a = TAOObjectChild(arg1=val_a) b = "string_value" assert not a == b class TestTAOObject(object): """Test expected behaviour of TAOObject class.""" @parameterized.expand( [ (1,), # int (1.337,), # float ("arg1_val",), # string ([1337, "1337", 1337],), # list ({"foo", 1337},), # dict (my_test_function,), # function. ({"my_func": my_test_function},), # Dict with a function as a value. ] ) def test_value_serialization(self, value): """Test proper serialization of different values and types.""" # create instance o = TAOObjectChild(value) # serialize d = o.serialize() # de-serialize o = deserialize_tao_object(d) assert isinstance(o, TAOObjectChild) assert o.arg1 == value def test_serialization_json(self): # create instance o = TAOObjectChild("arg1val_json") # serialize s = o.to_json() # make sure serialized string is a valid json d = json.loads(s) # de-serialize o = deserialize_tao_object(d) assert isinstance(o, TAOObjectChild) assert o.arg1 == "arg1val_json" def test_serialization_yaml(self): # create instance o = TAOObjectChild("arg1val_yaml") # serialize s = o.to_yaml() # make sure serialized string is a valid json d = yaml.load(s) # de-serialize o = deserialize_tao_object(d) assert isinstance(o, TAOObjectChild) assert o.arg1 == "arg1val_yaml" def test_serialization_recursive(self): # create instances o1 = TAOObjectChild("arg1val_recursive") o2 = TAOObjectChild(o1) # serialize d = o2.serialize() # de-serialize o = deserialize_tao_object(d) assert isinstance(o, TAOObjectChild) assert isinstance(o.arg1, TAOObjectChild) assert o.arg1.arg1 == "arg1val_recursive" def test_serialization_recursive_json(self): # create instances o1 = TAOObjectChild("arg1val_recursive_json") o2 = TAOObjectChild(o1) # serialize s = o2.to_json() # make sure serialized string is a valid json d = json.loads(s) # de-serialize o = deserialize_tao_object(d) assert isinstance(o, TAOObjectChild) assert isinstance(o.arg1, TAOObjectChild) assert o.arg1.arg1 == "arg1val_recursive_json" def test_serialization_list_yaml(self): # create instance o1 = TAOObjectChild(arg1="o1") o2 = TAOObjectChild(arg1="o2") o = TAOObjectChild(arg1=[o1, o2]) # serialize s = o.to_yaml() # make sure serialized string is a valid yaml. d = yaml.load(s) # de-serialize o = deserialize_tao_object(d) assert isinstance(o, TAOObjectChild) assert isinstance(o.arg1[0], TAOObjectChild) assert isinstance(o.arg1[1], TAOObjectChild) assert o.arg1[0].arg1 == "o1" assert o.arg1[1].arg1 == "o2" @pytest.mark.parametrize("file_format", ["yaml", "json"]) def test_serialization_dict(self, file_format): """Test serializing a dict whose values are TAOObject instances.""" o1 = TAOObjectChild(arg1="o1") o2 = TAOObjectChild(arg1="o2") o = TAOObjectChild(arg1={"kwarg1": o1, "kwarg2": o2}) if file_format == "yaml": s = o.to_yaml() d = yaml.load(s) o = deserialize_tao_object(d) elif file_format == "json": s = o.to_json() d = json.loads(s) o = deserialize_tao_object(d) assert isinstance(o, TAOObjectChild) assert isinstance(o.arg1["kwarg1"], TAOObjectChild) assert isinstance(o.arg1["kwarg2"], TAOObjectChild) assert o.arg1["kwarg1"].arg1 == "o1" assert o.arg1["kwarg2"].arg1 == "o2" @pytest.mark.parametrize("file_format", ["yaml", "json"]) def test_multiple_levels_of_recursion(self, file_format): """Test with multiple levels of recursion TAOObject instances.""" o1 = TAOObjectChild(arg1="o1") o2 = TAOObjectChild(arg1="o2") o = TAOObjectChild(arg1={"kwarg1": {"kwarg1_1": o1}}, arg2=[[o2]]) if file_format == "yaml": s = o.to_yaml() d = yaml.load(s) o = deserialize_tao_object(d) elif file_format == "json": s = o.to_json() d = json.loads(s) o = deserialize_tao_object(d) assert isinstance(o, TAOObjectChild) assert isinstance(o.arg1["kwarg1"]["kwarg1_1"], TAOObjectChild) assert isinstance(o.arg2[0][0], TAOObjectChild) assert o.arg1["kwarg1"]["kwarg1_1"].arg1 == "o1" assert o.arg2[0][0].arg1 == "o2" def test_function_serialization(self): """Test serialization of function.""" o1 = TAOObjectChild(arg1="o1") o2 = TAOObjectChild( arg1={"bogus_dict_key": my_test_function}, arg2=[None, my_test_function] ) o3 = TAOObjectChild(arg1=o1, arg2=o2) s = o3.serialize() o4 = deserialize_tao_object(s) # Now try __call__'ing the appropriate objects. assert o4.arg2.arg1["bogus_dict_key"]() == MY_RETURN_VALUE assert o4.arg2.arg2[1]() == MY_RETURN_VALUE def test_class_name_short_name(self): """Test that deserializing with the class name alone works.""" obj = TAOObjectChild(arg1="o1") s = obj.serialize() s["__class_name__"] = "TAOObjectChild" deserialize_tao_object(s) def test_name_collisions(self): """Test that an appropriate error is raised when there are name collisions.""" # Force the registration of another class with the same name as `TAOObjectChild` defined # above. get_duplicated_tao_object_child_class() obj = TAOObjectChild(arg1="rebel") s = obj.serialize() # Change the "__class_name__" field to the short hand to set up the collision. s["__class_name__"] = "TAOObjectChild" with pytest.raises(ValueError) as excinfo: deserialize_tao_object(s) assert ( "Found multiple class / function names matching 'TAOObjectChild'" in str(excinfo.value) )
tao_tensorflow1_backend-main
nvidia_tao_tf1/core/coreobject/test_coreobject.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. r"""TAOObject APIs. The :any:`TAOObject` is a baseclass meant to enable subclasses to easily and automatically serialize and deserialize their constructor arguments to a Python dict. Because two-way serialization between a dict and many serialization languages is trivial (e.g. YAML, JSON), the :any:`TAOObject` allows for serialization of your objects to such languages, and deserialization (a.k.a. 'building') from them. The :any:`TAOObject` does so by saving the input arguments to your object. The input arguments can be of any type that can be serializated to a dict (e.g. int, float, string, list, tuple, dict, etc), or a :any:`TAOObject` itself. Amongst types not supported are; any object not inheriting from :any:`TAOObject`, including ``namedtuple``, ``OrderedDict``, etc. The :any:`TAOObject` is currently used by several apps [#f1]_ to automate their spec-to-code conversion. Using the :any:`TAOObject` ----------------------------- * Inherit from :any:`TAOObject` * Add the :any:`save_args` around your ``__init__`` method. * Pass on ``**kwargs`` in your ``__init__`` method. * Call your parent object with ``**kwargs``. Example ------- .. code-block:: python from nvidia_tao_tf1.core.coreobject import deserialize_tao_object from nvidia_tao_tf1.core.coreobject import TAOObject from nvidia_tao_tf1.core.coreobject import save_args class MyTAOObjectChild(TAOObject): @save_args def __init__(self, my_arg, **kwargs): super(MyTAOObjectChild, self).__init__(**kwargs) self.my_arg = my_arg # Instantate your object. o = MyTAOObjectChild(my_arg=1337) # Serialize this TAOObject. d = o.serialize() # `d` is of type dict. o.to_yaml('spec.yaml') # Writes `o` to a YAML file. o.to_json('spec.json') # Writes `o` to a JSON file. # Deserialize o_from_d = deserialize_tao_object(d) # `o` is of type MyTAOObjectChild. print(o_from_d.my_arg) # Output: ``1337``. .. [#f1] `Python Constructor Spec (TAOObject) Design Doc <https://docs.google.com/document/d/1K2jZ02a7fFq2a1cWDbUkUhbAs2pd5RKd6EdOTrMnB3U>`_. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from abc import ABCMeta from collections import Hashable import inspect from io import open # Python 2/3 compatibility. pylint: disable=W0622 import logging import types import google.protobuf.message import simplejson as json from six import text_type, with_metaclass import yaml from nvidia_tao_tf1.core.coreobject import protobuf_to_dict logger = logging.getLogger(__name__) # Dictionary of registered classes. _MLOBJECT_REGISTRY = {} _CLASS_NAME_KEY = "__class_name__" _FUNCTION_NAME_KEY = "__function_name__" _IGNORE_KEYS = {_CLASS_NAME_KEY, _FUNCTION_NAME_KEY} def deserialize_tao_object(data): """ Deserialize a (child of) a :class:`.TAOObject`. The deserialization of *any* child class of this object is done in three steps. (1) Retrieving the actual MagLev object (pointer) through the value of the ``class_name`` key. (2) Initialization of the object through passing in the ``config`` of the class directly and entirely by converting it to keyword arguments to the initializer. Args: data (dict): A serialized structure containing the information to deserialize any child of TAOObject entirely. Returns: :class:`.TAOObject`: Any child object of a :class:`.TAOObject` that has been deserialized. """ is_class = _CLASS_NAME_KEY in data is_function = _FUNCTION_NAME_KEY in data if is_class is is_function: raise ValueError( "Exactly one of {} or {} must be present in data.".format( _CLASS_NAME_KEY, _FUNCTION_NAME_KEY ) ) _KEY = _CLASS_NAME_KEY if is_class else _FUNCTION_NAME_KEY name_handle = data[_KEY] if name_handle not in _MLOBJECT_REGISTRY: raise ValueError( "Trying to deserialize object / function of class `{}`, but it was not found " "in the registry. This can typically be solved by making sure the top-level script " "you are running has in its 'import tree' imported all the modules and classes " "you need.".format(name_handle) ) if isinstance(_MLOBJECT_REGISTRY[name_handle], list): if len(_MLOBJECT_REGISTRY[name_handle]) > 1: message = ( "Found multiple class / function names matching '{}', please update your input " "configuration's __class_name__ and / or __function_name__ entries to be in " "the format 'module.lib.package.MyClass'. Candidates include: ".format( name_handle ) ) message += ", ".join( [_get_registry_key(entry) for entry in _MLOBJECT_REGISTRY[name_handle]] ) raise ValueError(message) kwargs = _get_kwargs(data) def _deserialize_recursively(value): """Recursively deserializes modulusobjects.""" if isinstance(value, dict): if _CLASS_NAME_KEY in value or _FUNCTION_NAME_KEY in value: value = deserialize_tao_object(value) else: value = { key: _deserialize_recursively(val) for key, val in value.items() } elif isinstance(value, list): for i in range(len(value)): value[i] = _deserialize_recursively(value[i]) return value for key in kwargs: if key in _IGNORE_KEYS: continue kwargs[key] = _deserialize_recursively(value=kwargs[key]) obj_ptr = _MLOBJECT_REGISTRY[name_handle] if isinstance(obj_ptr, list): obj_ptr = obj_ptr[0] # We already checked for single entry above. if isinstance(obj_ptr, types.FunctionType): tao_object = obj_ptr else: tao_object = obj_ptr(**kwargs) return tao_object def register_tao_object(candidate): """ Register a tao object class or function. Args: candidate (class or function): Class or function to register. """ registry_key = _get_registry_key(candidate) if registry_key not in _MLOBJECT_REGISTRY: _MLOBJECT_REGISTRY[registry_key] = candidate else: raise RuntimeError( "Conflicting module and class names: %s already exists in the TAOObject registry. " "This probably means you are overriding a class definition that you should have left " "untouched." % registry_key ) # For backwards compatibility, since most class names were _already_ unique across the 'default' # NAME_SPACE (attribute since removed), we can register them by a shorter handle, and raise # an error at deserialization time if multiple definitions are found. obj_name = candidate.__name__ if obj_name not in _MLOBJECT_REGISTRY: _MLOBJECT_REGISTRY[obj_name] = [] _MLOBJECT_REGISTRY[obj_name].append(candidate) def register_tao_function(func): """Decorator that registers a function. Args: func (function): Function to be added to the registry. Returns: func (function). """ # Functions can be registered the same way as classes. register_tao_object(func) return func def _get_registry_key(candidate): # In practice, would look something like: modulus.some_lib.MyClass. return ".".join([candidate.__module__, candidate.__name__]) class MetaTAOObject(type): """ TAOObject meta class. See references to ``with_metaclass(MetaTAOObject, object)``. An instance of the meta class is created whenever a :class:`.TAOObject` class is defined. In the ``__init__`` method of the meta-class we register the newly defined class into a global registry of :class:`.TAOObject` descendants. Args: name (str): name of the newly defined class bases (list): list of base classes attr (dict): dictionary of attributes """ def __init__(cls, name, bases, attr): """init function.""" type.__init__(cls, name, bases, attr) register_tao_object(cls) class TAOObject(with_metaclass(MetaTAOObject, object)): """ Core TAOObject class. A Maglev Object is independently serializable and deserializable, and thus should contain a variable configuration obtainable by get_config(). """ def serialize(self): """ Serialization of the object. Returns: data (dict): A structure containing serialized information about this object """ data = {_CLASS_NAME_KEY: _get_registry_key(self.__class__)} data.update(self.get_config()) return data def get_config(self): """ Obtain this object's configuration. Returns: dict: A structure containing all information to configure this object. """ if hasattr(self, "_modulus_config"): # self._modulus_config is automatically populated by @save_args decorator. # _config seems to be a common member variable name for teams, # using _modulus_config to prevent name collisions. return self._modulus_config return {} def to_json(self, filename=None, indent=4, sort_keys=True, **kwargs): """ Serialize graph and write to json. Args: filename (str): If supplied, it will write a json file to the cwd. **kwargs: Keyword arguments that will passed on to `json.dumps()`. Returns: data (str): Serialized object (json). """ data = json.dumps( self.serialize(), indent=indent, sort_keys=sort_keys, **kwargs ) if filename: with open(filename, "w") as f: f.write(text_type(data)) return data def to_yaml( self, filename=None, encoding="utf-8", default_flow_style=False, **kwargs ): """ Serialize graph and write to yaml. Args: filename (str): If supplied, it will write a yaml file to the cwd. **kwargs: Keyword arguments that will passed on to `yaml.dump()`. Returns: data (str): Serialized object (yaml). """ data = yaml.safe_dump( self.serialize(), encoding=encoding, default_flow_style=default_flow_style, **kwargs ) if filename: with open(filename, "wb") as f: f.write(data) return data def __eq__(self, b): """ Loose check if two TAOObjects are equal. This function just compares the serialized form of the Objects for equality. Derived classes should implement stricter checks based on their implementation. Args: b (TAOObject): Instance of TAOObject class to compare with. Returns: true if objects' serialized representation match, false otherwise. """ if not isinstance(b, TAOObject): return False return self.serialize() == b.serialize() def __hash__(self): """Computes hash based on serialized dict contents.""" d = self.serialize() return sum( [ hash(key) + (hash(value) if isinstance(value, Hashable) else 0) for key, value in d.items() ] ) class AbstractMetaTAOObject(ABCMeta, MetaTAOObject): """Used multiple inheritance to forge two meta classes for building AbstractTAOObject.""" pass class AbstractTAOObject(with_metaclass(AbstractMetaTAOObject, TAOObject)): """TAOObject abstract base class for interfaces to inherit from.""" pass try: _BUILTIN_PYTHON_TYPES = ( int, str, unicode, bool, long, float, type(None), set, ) # noqa except NameError: # Python 3. _BUILTIN_PYTHON_TYPES = (int, str, bytes, bool, float, type(None), set) def _recursively_serialize(val): """Serializes a value, recursing through iterable structures (list or tuple).""" # Loop and serialize. if isinstance(val, (list, tuple)): val = [_recursively_serialize(v) for v in val] elif isinstance(val, dict): val = {key: _recursively_serialize(value) for key, value in val.items()} elif isinstance(val, TAOObject): val = val.serialize() elif isinstance(val, types.FunctionType): val = {_FUNCTION_NAME_KEY: _get_registry_key(val)} elif isinstance(val, google.protobuf.message.Message): val = protobuf_to_dict.protobuf_to_modulus_dict( val, add_class_metadata=True, overwrite_package_with_name="default", overwrite_class_with_name="TAOKeywordObject", ) return val def save_args(func): """ Decorator to put around initializer of TAOObject to save arguments. A decorator that saves named arguments (not ``*args`` or ``**kwargs``) into an object's config field. This decorator is meant to wrap the ``__init__`` method of a :class:`nvidia_tao_tf1.core.coreobject.TAOObject` class. Typical usage would be to define a class as:: class TAOObjectChild(TAOObject): @save_args def __init__(self, arg1, *args, **kwargs): super(TAOObjectChild, self).__init__(*args, **kwargs) Then on a call to this class's ``serialize`` method, the returned config will include the value of ``arg1`` that was specified on instantiation. If ``arg1`` is a :class:`nvidia_tao_tf1.core.coreobject.TAOObject` the argument is serialized recursively. """ def wrapper(*args, **kwargs): arg_spec = inspect.getargspec(func) # pylint: disable=W1505 # Check if we are missing any required arguments so we can throw a descriptive error. # Remove the ones with defaults. Defaults are counted from the end. n_defaults = 0 if arg_spec.defaults is None else len(arg_spec.defaults) required_args = arg_spec.args[:-n_defaults] # Remove the ones that have been provided as non-keyword args. required_args = required_args[len(args) :] # Remove the ones that have been given as kwargs required_args = list(set(required_args).difference(set(kwargs.keys()))) if required_args: raise TypeError( "{} missing required arguments: {}.".format(args[0], required_args) ) call_args = inspect.getcallargs(func, *args, **kwargs) # pylint: disable=W1505 f = func(*args, **kwargs) obj = call_args[arg_spec.args[0]] if not isinstance(obj, TAOObject): raise ValueError("This decorator only supports TAOObject instances.") if not hasattr(obj, "_modulus_config"): obj._modulus_config = {} def process_arg(arg, arg_map): val = _recursively_serialize(arg_map[arg]) if arg in obj._modulus_config: if obj._modulus_config[arg] != val: raise ValueError( "argument '%s' is already in config " "and values are different." % arg ) obj._modulus_config[arg] = val # Loop over object arguments (ignore first argument `self`). for arg in arg_spec.args[1:]: process_arg(arg, call_args) # process other kwargs if arg_spec.keywords: keywords = arg_spec.keywords other_kwargs = call_args[keywords].keys() for arg in other_kwargs: process_arg(arg, call_args[keywords]) return f return wrapper def _get_kwargs(data): return {key: val for key, val in data.items() if key not in _IGNORE_KEYS}
tao_tensorflow1_backend-main
nvidia_tao_tf1/core/coreobject/coreobject.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. from __future__ import absolute_import from __future__ import division from __future__ import print_function from nvidia_tao_tf1.core.coreobject import ( register_tao_function, save_args, TAOObject ) def get_duplicated_tao_object_child_class(): # This class is a copy of the one in test_modulusobject.py. It is here so that we can test # the handling of name collisions at deserialization time. class TAOObjectChild(TAOObject): @save_args def __init__( self, arg1, arg2="default_arg2_val", *args, **kwargs ): # pylint: disable=W1113 super(TAOObjectChild, self).__init__(*args, **kwargs) self.arg1 = arg1 self.arg2 = arg2 return TAOObjectChild MY_RETURN_VALUE = "takes skill to be real" @register_tao_function def my_test_function(): # Used for testing serialization of functions. return MY_RETURN_VALUE
tao_tensorflow1_backend-main
nvidia_tao_tf1/core/coreobject/test_fixtures.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. """Object that takes in a variable amount of arguments and sets its attributes accordingly.""" from nvidia_tao_tf1.core.coreobject.coreobject import TAOObject, save_args class TAOKeywordObject(TAOObject): """Class that takes kwargs into its __init__ method and maps them to its attributes.""" @save_args def __init__(self, **kwargs): """Init the object with a variable amount of arguments which are mapped to attrs.""" super(TAOKeywordObject, self).__init__() self.__dict__.update(kwargs)
tao_tensorflow1_backend-main
nvidia_tao_tf1/core/coreobject/corekeywordobject.py
"""Library to convert protobuf objects to python dicts.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from nvidia_tao_tf1.core.coreobject.protobuf_to_dict.protobuf_to_dict import ( dict_to_protobuf, protobuf_to_dict, protobuf_to_modulus_dict, REVERSE_TYPE_CALLABLE_MAP, TYPE_CALLABLE_MAP, ) __all__ = [ "dict_to_protobuf", "protobuf_to_modulus_dict", "protobuf_to_dict", "REVERSE_TYPE_CALLABLE_MAP", "TYPE_CALLABLE_MAP", ]
tao_tensorflow1_backend-main
nvidia_tao_tf1/core/coreobject/protobuf_to_dict/__init__.py
"""Class which converts protobuf objects to python dicts.""" from google.protobuf.descriptor import FieldDescriptor from google.protobuf.message import Message import six EXTENSION_CONTAINER = "___X" _CLASS_NAME_KEY = "__class_name__" _PACKAGE_KEY = "__name_space__" _DEFAULT_PACKAGE_NAME = "default" _PROTOBUF_KEY = "proto_obj" _IGNORE_FIELDS = {EXTENSION_CONTAINER, _PACKAGE_KEY, _CLASS_NAME_KEY} TYPE_CALLABLE_MAP = { FieldDescriptor.TYPE_DOUBLE: float, FieldDescriptor.TYPE_FLOAT: float, FieldDescriptor.TYPE_INT32: int, FieldDescriptor.TYPE_INT64: int if six.PY3 else six.integer_types[1], FieldDescriptor.TYPE_UINT32: int, FieldDescriptor.TYPE_UINT64: int if six.PY3 else six.integer_types[1], FieldDescriptor.TYPE_SINT32: int, FieldDescriptor.TYPE_SINT64: int if six.PY3 else six.integer_types[1], FieldDescriptor.TYPE_FIXED32: int, FieldDescriptor.TYPE_FIXED64: int if six.PY3 else six.integer_types[1], FieldDescriptor.TYPE_SFIXED32: int, FieldDescriptor.TYPE_SFIXED64: int if six.PY3 else six.integer_types[1], FieldDescriptor.TYPE_BOOL: bool, FieldDescriptor.TYPE_STRING: six.text_type, FieldDescriptor.TYPE_BYTES: six.binary_type, FieldDescriptor.TYPE_ENUM: int, } def _repeated(type_callable): return lambda value_list: [type_callable(value) for value in value_list] def _enum_label_name(field, value): return field.enum_type.values_by_number[int(value)].name def protobuf_to_modulus_dict( pb, use_enum_labels=False, add_class_metadata=False, overwrite_package_with_name=None, overwrite_class_with_name=None, ): """Recursively populate a dictionary with a protobuf object. Args: pb (google.protobuf.Message): a protobuf message class, or an protobuf instance use_enum_labels (bool): True if enums should be represented as their string labels, False for their ordinal value. add_class_metadata (bool): True to add class names and package names to the dictionary. overwrite_package_with_name (string): If set, will use the value as the package name for all objects. Only used if add_class_metadata is True. overwrite_class_with_name (string): If set, will use the value as the class name for all objects. Only used if add_class_metadata is True. """ type_callable_map = TYPE_CALLABLE_MAP result_dict = {} extensions = {} if add_class_metadata: result_dict[_CLASS_NAME_KEY] = pb.DESCRIPTOR.name if overwrite_class_with_name: result_dict[_CLASS_NAME_KEY] = overwrite_class_with_name # Overwrite the package name if we have a value to overwrite with. if overwrite_package_with_name is not None: result_dict[_PACKAGE_KEY] = overwrite_package_with_name else: result_dict[_PACKAGE_KEY] = pb.DESCRIPTOR.full_name.rpartition(".")[0] # Hack to get around the problem of ListFields not returning default fields (see # https://github.com/universe-proton/universe-topology/issues/1). Hack = use # pb.DESCRIPTOR.fields_by_name.items() instead of pb.ListFields(). for field_name, field in pb.DESCRIPTOR.fields_by_name.items(): value = getattr(pb, field_name) type_callable = _get_field_value_adaptor( pb, field, type_callable_map, use_enum_labels, add_class_metadata=add_class_metadata, overwrite_package_with_name=overwrite_package_with_name, message_type_func=protobuf_to_modulus_dict, overwrite_class_with_name=overwrite_class_with_name, ) if field.label == FieldDescriptor.LABEL_REPEATED: type_callable = _repeated(type_callable) if field.is_extension: extensions[str(field.number)] = type_callable(value) continue result_dict[field.name] = type_callable(value) if extensions: result_dict[EXTENSION_CONTAINER] = extensions return result_dict def protobuf_to_dict( pb, use_enum_labels=False, add_class_metadata=False, overwrite_package_with_name=None, overwrite_class_with_name=None, ): """Recursively populate a dictionary with a protobuf object. Args: pb (google.protobuf.Message): a protobuf message class, or an protobuf instance use_enum_labels (bool): True if enums should be represented as their string labels, False for their ordinal value. add_class_metadata (bool): True to add class names and package names to the dictionary. overwrite_package_with_name (string): If set, will use the value as the package name for all objects. Only used if add_class_metadata is True. """ type_callable_map = TYPE_CALLABLE_MAP result_dict = {} extensions = {} if add_class_metadata: result_dict[_CLASS_NAME_KEY] = pb.DESCRIPTOR.name if overwrite_class_with_name: result_dict[_CLASS_NAME_KEY] = overwrite_class_with_name # Overwrite the package name if we have a value to overwrite with. if overwrite_package_with_name is not None: result_dict[_PACKAGE_KEY] = overwrite_package_with_name else: result_dict[_PACKAGE_KEY] = pb.DESCRIPTOR.full_name.rpartition(".")[0] for field, value in pb.ListFields(): type_callable = _get_field_value_adaptor( pb, field, type_callable_map, use_enum_labels, add_class_metadata=add_class_metadata, overwrite_package_with_name=overwrite_package_with_name, ) if field.label == FieldDescriptor.LABEL_REPEATED: type_callable = _repeated(type_callable) if field.is_extension: extensions[str(field.number)] = type_callable(value) continue result_dict[field.name] = type_callable(value) if extensions: result_dict[EXTENSION_CONTAINER] = extensions return result_dict def _get_field_value_adaptor( pb, field, type_callable_map, use_enum_labels=False, add_class_metadata=False, overwrite_package_with_name=None, message_type_func=protobuf_to_dict, overwrite_class_with_name=None, ): if field.type == FieldDescriptor.TYPE_MESSAGE: # recursively encode protobuf sub-message return lambda pb: message_type_func( pb, use_enum_labels=use_enum_labels, add_class_metadata=add_class_metadata, overwrite_package_with_name=overwrite_package_with_name, overwrite_class_with_name=overwrite_class_with_name, ) if use_enum_labels and field.type == FieldDescriptor.TYPE_ENUM: return lambda value: _enum_label_name(field, value) if field.type in type_callable_map: return type_callable_map[field.type] raise TypeError( "Field %s.%s has unrecognised type id %d" % (pb.__class__.__name__, field.name, field.type) ) REVERSE_TYPE_CALLABLE_MAP = {} def dict_to_protobuf(pb_klass_or_instance, values, strict=True): """Populates a protobuf model from a dictionary. Args: pb_klass_or_instance (google.protobuf.Message): a protobuf message class, or an protobuf instance pb_klass_or_instance (google.prorobuf.Message): a type or instance of a subclass of google.protobuf.message.Message values (dict): a dictionary of values. Repeated and nested values are fully supported. type_callable_map (dict): a mapping of protobuf types to callables for setting values on the target instance. strict (bool): complain if keys in the map are not fields on the message. """ if isinstance(pb_klass_or_instance, Message): instance = pb_klass_or_instance else: instance = pb_klass_or_instance() return _dict_to_protobuf(instance, values, REVERSE_TYPE_CALLABLE_MAP, strict) def _get_field_mapping(pb, dict_value, strict): field_mapping = [] for key, value in dict_value.items(): if key in _IGNORE_FIELDS: continue if key not in pb.DESCRIPTOR.fields_by_name: if strict: raise KeyError("%s does not have a field called %s" % (pb, key)) continue field_mapping.append( (pb.DESCRIPTOR.fields_by_name[key], value, getattr(pb, key, None)) ) for ext_num, ext_val in dict_value.get(EXTENSION_CONTAINER, {}).items(): try: ext_num = int(ext_num) except ValueError: raise ValueError("Extension keys must be integers.") if ext_num not in pb._extensions_by_number: if strict: raise KeyError( "%s does not have a extension with number %s. Perhaps you forgot to import it?" % (pb, ext_num) ) continue ext_field = pb._extensions_by_number[ext_num] pb_val = None pb_val = pb.Extensions[ext_field] field_mapping.append((ext_field, ext_val, pb_val)) return field_mapping def _dict_to_protobuf(pb, value, type_callable_map, strict): fields = _get_field_mapping(pb, value, strict) for field, input_value, pb_value in fields: if field.label == FieldDescriptor.LABEL_REPEATED: for item in input_value: if field.type == FieldDescriptor.TYPE_MESSAGE: m = pb_value.add() _dict_to_protobuf(m, item, type_callable_map, strict) elif field.type == FieldDescriptor.TYPE_ENUM and isinstance(item, str): pb_value.append(_string_to_enum(field, item)) else: pb_value.append(item) continue if field.type == FieldDescriptor.TYPE_MESSAGE: _dict_to_protobuf(pb_value, input_value, type_callable_map, strict) continue if field.type in type_callable_map: input_value = type_callable_map[field.type](input_value) if field.is_extension: pb.Extensions[field] = input_value continue if field.type == FieldDescriptor.TYPE_ENUM and isinstance(input_value, str): input_value = _string_to_enum(field, input_value) setattr(pb, field.name, input_value) return pb def _string_to_enum(field, input_value): enum_dict = field.enum_type.values_by_name try: input_value = enum_dict[input_value].number except KeyError: raise KeyError( "`%s` is not a valid value for field `%s`" % (input_value, field.name) ) return input_value
tao_tensorflow1_backend-main
nvidia_tao_tf1/core/coreobject/protobuf_to_dict/protobuf_to_dict.py
import json import unittest from parameterized import parameterized from nvidia_tao_tf1.core.coreobject.protobuf_to_dict.protobuf_to_dict import ( _CLASS_NAME_KEY, _PACKAGE_KEY, dict_to_protobuf, protobuf_to_dict, ) from nvidia_tao_tf1.core.coreobject.protobuf_to_dict.tests.sample_pb2 import ( extDouble, extString, MessageOfTypes, NestedExtension, ) class Test(unittest.TestCase): @parameterized.expand( [([True], "default"), ([True], None), ([False], "default"), ([False], None)] ) def test_basics(self, add_class_metadata, overwrite_package_with_name): m = self.populate_MessageOfTypes() d = protobuf_to_dict( m, add_class_metadata=add_class_metadata, overwrite_package_with_name=overwrite_package_with_name, ) print("overwrite_package_with_name: %s" % overwrite_package_with_name) self.compare( m, d, ["nestedRepeated"], add_class_metadata=add_class_metadata, overwrite_package_with_name=overwrite_package_with_name, ) m2 = dict_to_protobuf(MessageOfTypes, d) assert m == m2 @parameterized.expand( [([True], "default"), ([True], None), ([False], "default"), ([False], None)] ) def test_use_enum_labels(self, add_class_metadata, overwrite_package_with_name): m = self.populate_MessageOfTypes() d = protobuf_to_dict( m, use_enum_labels=True, add_class_metadata=add_class_metadata, overwrite_package_with_name=overwrite_package_with_name, ) self.compare( m, d, ["enm", "enmRepeated", "nestedRepeated"], add_class_metadata=add_class_metadata, overwrite_package_with_name=overwrite_package_with_name, ) assert d["enm"] == "C" assert d["enmRepeated"] == ["A", "C"] m2 = dict_to_protobuf(MessageOfTypes, d) assert m == m2 d["enm"] = "MEOW" with self.assertRaises(KeyError): dict_to_protobuf(MessageOfTypes, d) d["enm"] = "A" d["enmRepeated"] = ["B"] dict_to_protobuf(MessageOfTypes, d) d["enmRepeated"] = ["CAT"] with self.assertRaises(KeyError): dict_to_protobuf(MessageOfTypes, d) @parameterized.expand( [([True], "default"), ([True], None), ([False], "default"), ([False], None)] ) def test_repeated_enum(self, add_class_metadata, overwrite_package_with_name): m = self.populate_MessageOfTypes() d = protobuf_to_dict( m, use_enum_labels=True, add_class_metadata=add_class_metadata, overwrite_package_with_name=overwrite_package_with_name, ) self.compare( m, d, ["enm", "enmRepeated", "nestedRepeated"], add_class_metadata=add_class_metadata, overwrite_package_with_name=overwrite_package_with_name, ) assert d["enmRepeated"] == ["A", "C"] m2 = dict_to_protobuf(MessageOfTypes, d) assert m == m2 d["enmRepeated"] = ["MEOW"] with self.assertRaises(KeyError): dict_to_protobuf(MessageOfTypes, d) @parameterized.expand( [([True], "default"), ([True], None), ([False], "default"), ([False], None)] ) def test_nested_repeated(self, add_class_metadata, overwrite_package_with_name): m = self.populate_MessageOfTypes() m.nestedRepeated.extend( [MessageOfTypes.NestedType(req=str(i)) for i in range(10)] ) d = protobuf_to_dict( m, add_class_metadata=add_class_metadata, overwrite_package_with_name=overwrite_package_with_name, ) self.compare( m, d, exclude=["nestedRepeated"], add_class_metadata=add_class_metadata, overwrite_package_with_name=overwrite_package_with_name, ) if not add_class_metadata: assert d["nestedRepeated"] == [{"req": str(i)} for i in range(10)] else: if overwrite_package_with_name is not None: assert d["nestedRepeated"] == [ { "req": str(i), _CLASS_NAME_KEY: "NestedType", _PACKAGE_KEY: overwrite_package_with_name, } for i in range(10) ] else: assert d["nestedRepeated"] == [ { "req": str(i), _CLASS_NAME_KEY: "NestedType", _PACKAGE_KEY: "tests.MessageOfTypes", } for i in range(10) ] m2 = dict_to_protobuf(MessageOfTypes, d) assert m == m2 @parameterized.expand( [([True], "default"), ([True], None), ([False], "default"), ([False], None)] ) def test_reverse(self, add_class_metadata, overwrite_package_with_name): m = self.populate_MessageOfTypes() m2 = dict_to_protobuf( MessageOfTypes, protobuf_to_dict( m, add_class_metadata=add_class_metadata, overwrite_package_with_name=overwrite_package_with_name, ), ) assert m == m2 m2.dubl = 0 assert m2 != m @parameterized.expand( [([True], "default"), ([True], None), ([False], "default"), ([False], None)] ) def test_incomplete(self, add_class_metadata, overwrite_package_with_name): m = self.populate_MessageOfTypes() d = protobuf_to_dict( m, add_class_metadata=add_class_metadata, overwrite_package_with_name=overwrite_package_with_name, ) d.pop("dubl") m2 = dict_to_protobuf(MessageOfTypes, d) assert m2.dubl == 0 assert m != m2 @parameterized.expand( [([True], "default"), ([True], None), ([False], "default"), ([False], None)] ) def test_pass_instance(self, add_class_metadata, overwrite_package_with_name): m = self.populate_MessageOfTypes() d = protobuf_to_dict( m, add_class_metadata=add_class_metadata, overwrite_package_with_name=overwrite_package_with_name, ) d["dubl"] = 1 m2 = dict_to_protobuf(m, d) assert m is m2 assert m.dubl == 1 @parameterized.expand( [([True], "default"), ([True], None), ([False], "default"), ([False], None)] ) def test_strict(self, add_class_metadata, overwrite_package_with_name): m = self.populate_MessageOfTypes() d = protobuf_to_dict( m, add_class_metadata=add_class_metadata, overwrite_package_with_name=overwrite_package_with_name, ) d["meow"] = 1 with self.assertRaises(KeyError): m2 = dict_to_protobuf(MessageOfTypes, d) m2 = dict_to_protobuf(MessageOfTypes, d, strict=False) assert m == m2 def populate_MessageOfTypes(self): m = MessageOfTypes() m.dubl = 1.7e308 m.flot = 3.4e038 m.i32 = 2 ** 31 - 1 # 2147483647 # m.i64 = 2 ** 63 - 1 # 0x7FFFFFFFFFFFFFFF m.ui32 = 2 ** 32 - 1 m.ui64 = 2 ** 64 - 1 m.si32 = -1 * m.i32 m.si64 = -1 * m.i64 m.f32 = m.i32 m.f64 = m.i64 m.sf32 = m.si32 m.sf64 = m.si64 m.bol = True m.strng = "string" m.byts = b"\n\x14\x1e" assert len(m.byts) == 3, len(m.byts) m.nested.req = "req" m.enm = MessageOfTypes.C # @UndefinedVariable m.enmRepeated.extend([MessageOfTypes.A, MessageOfTypes.C]) m.range.extend(range(10)) return m def compare( self, m, d, exclude=None, add_class_metadata=False, overwrite_package_with_name=None, ): i = 0 exclude = ["byts", "nested", _CLASS_NAME_KEY] + (exclude or []) for i, field in enumerate( MessageOfTypes.DESCRIPTOR.fields ): # @UndefinedVariable if field.name not in exclude: assert field.name in d, field.name assert d[field.name] == getattr(m, field.name), ( field.name, d[field.name], ) assert i > 0 assert len(m.byts) == 3, len(m.bytes) print(d["nested"]) if add_class_metadata: if overwrite_package_with_name is not None: assert d["nested"] == { "req": m.nested.req, _CLASS_NAME_KEY: "NestedType", _PACKAGE_KEY: overwrite_package_with_name, } else: assert d["nested"] == { "req": m.nested.req, _CLASS_NAME_KEY: "NestedType", _PACKAGE_KEY: "tests.MessageOfTypes", } else: assert d["nested"] == {"req": m.nested.req} @parameterized.expand( [([True], "default"), ([True], None), ([False], "default"), ([False], None)] ) def test_extensions(self, add_class_metadata, overwrite_package_with_name): m = MessageOfTypes() primitives = {extDouble: 123.4, extString: "string", NestedExtension.extInt: 4} for key, value in primitives.items(): m.Extensions[key] = value m.Extensions[NestedExtension.extNested].req = "nested" # Confirm compatibility with JSON serialization res = json.loads( json.dumps( protobuf_to_dict( m, add_class_metadata=add_class_metadata, overwrite_package_with_name=overwrite_package_with_name, ) ) ) assert "___X" in res exts = res["___X"] assert set(exts.keys()) == { str(f.number) for f, _ in m.ListFields() if f.is_extension } for key, value in primitives.items(): assert exts[str(key.number)] == value assert exts[str(NestedExtension.extNested.number)]["req"] == "nested" deser = dict_to_protobuf(MessageOfTypes, res) assert deser for key, value in primitives.items(): assert deser.Extensions[key] == m.Extensions[key] req1 = deser.Extensions[NestedExtension.extNested].req req2 = m.Extensions[NestedExtension.extNested].req assert req1 == req2
tao_tensorflow1_backend-main
nvidia_tao_tf1/core/coreobject/protobuf_to_dict/tests/test_proto_to_dict.py
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: nvidia_tao_tf1/core/coreobject/protobuf_to_dict/tests/sample.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_tf1/core/coreobject/protobuf_to_dict/tests/sample.proto', package='tests', syntax='proto2', serialized_options=None, serialized_pb=_b('\nBnvidia_tao_tf1/core/coreobject/protobuf_to_dict/tests/sample.proto\x12\x05tests\"\xf5\x03\n\x0eMessageOfTypes\x12\x0c\n\x04\x64ubl\x18\x01 \x02(\x01\x12\x0c\n\x04\x66lot\x18\x02 \x02(\x02\x12\x0b\n\x03i32\x18\x03 \x02(\x05\x12\x0b\n\x03i64\x18\x04 \x02(\x03\x12\x0c\n\x04ui32\x18\x05 \x02(\r\x12\x0c\n\x04ui64\x18\x06 \x02(\x04\x12\x0c\n\x04si32\x18\x07 \x02(\x11\x12\x0c\n\x04si64\x18\x08 \x02(\x12\x12\x0b\n\x03\x66\x33\x32\x18\t \x02(\x07\x12\x0b\n\x03\x66\x36\x34\x18\x11 \x02(\x06\x12\x0c\n\x04sf32\x18\n \x02(\x0f\x12\x0c\n\x04sf64\x18\x0b \x02(\x10\x12\x0b\n\x03\x62ol\x18\x0c \x02(\x08\x12\r\n\x05strng\x18\r \x02(\t\x12\x0c\n\x04\x62yts\x18\x0e \x02(\x0c\x12\x30\n\x06nested\x18\x0f \x02(\x0b\x32 .tests.MessageOfTypes.NestedType\x12\'\n\x03\x65nm\x18\x10 \x02(\x0e\x32\x1a.tests.MessageOfTypes.Enum\x12\r\n\x05range\x18\x12 \x03(\x05\x12\x38\n\x0enestedRepeated\x18\x13 \x03(\x0b\x32 .tests.MessageOfTypes.NestedType\x12/\n\x0b\x65nmRepeated\x18\x14 \x03(\x0e\x32\x1a.tests.MessageOfTypes.Enum\x1a\x19\n\nNestedType\x12\x0b\n\x03req\x18\x01 \x02(\t\"\x1b\n\x04\x45num\x12\x05\n\x01\x41\x10\x00\x12\x05\n\x01\x42\x10\x01\x12\x05\n\x01\x43\x10\x02*\x08\x08\x64\x10\x80\x80\x80\x80\x02\"\x84\x01\n\x0fNestedExtension2%\n\x06\x65xtInt\x12\x15.tests.MessageOfTypes\x18\x66 \x01(\x05\x32J\n\textNested\x12\x15.tests.MessageOfTypes\x18g \x01(\x0b\x32 .tests.MessageOfTypes.NestedType:(\n\textDouble\x12\x15.tests.MessageOfTypes\x18\x64 \x01(\x01:(\n\textString\x12\x15.tests.MessageOfTypes\x18\x65 \x01(\t') ) EXTDOUBLE_FIELD_NUMBER = 100 extDouble = _descriptor.FieldDescriptor( name='extDouble', full_name='tests.extDouble', index=0, number=100, 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=True, extension_scope=None, serialized_options=None, file=DESCRIPTOR) EXTSTRING_FIELD_NUMBER = 101 extString = _descriptor.FieldDescriptor( name='extString', full_name='tests.extString', index=1, number=101, 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=True, extension_scope=None, serialized_options=None, file=DESCRIPTOR) _MESSAGEOFTYPES_ENUM = _descriptor.EnumDescriptor( name='Enum', full_name='tests.MessageOfTypes.Enum', filename=None, file=DESCRIPTOR, values=[ _descriptor.EnumValueDescriptor( name='A', index=0, number=0, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='B', index=1, number=1, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='C', index=2, number=2, serialized_options=None, type=None), ], containing_type=None, serialized_options=None, serialized_start=542, serialized_end=569, ) _sym_db.RegisterEnumDescriptor(_MESSAGEOFTYPES_ENUM) _MESSAGEOFTYPES_NESTEDTYPE = _descriptor.Descriptor( name='NestedType', full_name='tests.MessageOfTypes.NestedType', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='req', full_name='tests.MessageOfTypes.NestedType.req', index=0, number=1, type=9, cpp_type=9, label=2, 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='proto2', extension_ranges=[], oneofs=[ ], serialized_start=515, serialized_end=540, ) _MESSAGEOFTYPES = _descriptor.Descriptor( name='MessageOfTypes', full_name='tests.MessageOfTypes', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='dubl', full_name='tests.MessageOfTypes.dubl', index=0, number=1, type=1, cpp_type=5, label=2, 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='flot', full_name='tests.MessageOfTypes.flot', index=1, number=2, type=2, cpp_type=6, label=2, 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='i32', full_name='tests.MessageOfTypes.i32', index=2, number=3, type=5, cpp_type=1, label=2, 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='i64', full_name='tests.MessageOfTypes.i64', index=3, number=4, type=3, cpp_type=2, label=2, 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='ui32', full_name='tests.MessageOfTypes.ui32', index=4, number=5, type=13, cpp_type=3, label=2, 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='ui64', full_name='tests.MessageOfTypes.ui64', index=5, number=6, type=4, cpp_type=4, label=2, 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='si32', full_name='tests.MessageOfTypes.si32', index=6, number=7, type=17, cpp_type=1, label=2, 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='si64', full_name='tests.MessageOfTypes.si64', index=7, number=8, type=18, cpp_type=2, label=2, 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='f32', full_name='tests.MessageOfTypes.f32', index=8, number=9, type=7, cpp_type=3, label=2, 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='f64', full_name='tests.MessageOfTypes.f64', index=9, number=17, type=6, cpp_type=4, label=2, 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='sf32', full_name='tests.MessageOfTypes.sf32', index=10, number=10, type=15, cpp_type=1, label=2, 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='sf64', full_name='tests.MessageOfTypes.sf64', index=11, number=11, type=16, cpp_type=2, label=2, 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='bol', full_name='tests.MessageOfTypes.bol', index=12, number=12, type=8, cpp_type=7, label=2, 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='strng', full_name='tests.MessageOfTypes.strng', index=13, number=13, type=9, cpp_type=9, label=2, 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='byts', full_name='tests.MessageOfTypes.byts', index=14, number=14, type=12, cpp_type=9, label=2, has_default_value=False, default_value=_b(""), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='nested', full_name='tests.MessageOfTypes.nested', index=15, number=15, type=11, cpp_type=10, label=2, 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='enm', full_name='tests.MessageOfTypes.enm', index=16, number=16, type=14, cpp_type=8, label=2, 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='range', full_name='tests.MessageOfTypes.range', index=17, number=18, type=5, cpp_type=1, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='nestedRepeated', full_name='tests.MessageOfTypes.nestedRepeated', index=18, number=19, 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='enmRepeated', full_name='tests.MessageOfTypes.enmRepeated', index=19, number=20, type=14, cpp_type=8, 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=[_MESSAGEOFTYPES_NESTEDTYPE, ], enum_types=[ _MESSAGEOFTYPES_ENUM, ], serialized_options=None, is_extendable=True, syntax='proto2', extension_ranges=[(100, 536870912), ], oneofs=[ ], serialized_start=78, serialized_end=579, ) _NESTEDEXTENSION = _descriptor.Descriptor( name='NestedExtension', full_name='tests.NestedExtension', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ ], extensions=[ _descriptor.FieldDescriptor( name='extInt', full_name='tests.NestedExtension.extInt', index=0, number=102, 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=True, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='extNested', full_name='tests.NestedExtension.extNested', index=1, number=103, 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=True, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto2', extension_ranges=[], oneofs=[ ], serialized_start=582, serialized_end=714, ) _MESSAGEOFTYPES_NESTEDTYPE.containing_type = _MESSAGEOFTYPES _MESSAGEOFTYPES.fields_by_name['nested'].message_type = _MESSAGEOFTYPES_NESTEDTYPE _MESSAGEOFTYPES.fields_by_name['enm'].enum_type = _MESSAGEOFTYPES_ENUM _MESSAGEOFTYPES.fields_by_name['nestedRepeated'].message_type = _MESSAGEOFTYPES_NESTEDTYPE _MESSAGEOFTYPES.fields_by_name['enmRepeated'].enum_type = _MESSAGEOFTYPES_ENUM _MESSAGEOFTYPES_ENUM.containing_type = _MESSAGEOFTYPES DESCRIPTOR.message_types_by_name['MessageOfTypes'] = _MESSAGEOFTYPES DESCRIPTOR.message_types_by_name['NestedExtension'] = _NESTEDEXTENSION DESCRIPTOR.extensions_by_name['extDouble'] = extDouble DESCRIPTOR.extensions_by_name['extString'] = extString _sym_db.RegisterFileDescriptor(DESCRIPTOR) MessageOfTypes = _reflection.GeneratedProtocolMessageType('MessageOfTypes', (_message.Message,), dict( NestedType = _reflection.GeneratedProtocolMessageType('NestedType', (_message.Message,), dict( DESCRIPTOR = _MESSAGEOFTYPES_NESTEDTYPE, __module__ = 'nvidia_tao_tf1.core.coreobject.protobuf_to_dict.tests.sample_pb2' # @@protoc_insertion_point(class_scope:tests.MessageOfTypes.NestedType) )) , DESCRIPTOR = _MESSAGEOFTYPES, __module__ = 'nvidia_tao_tf1.core.coreobject.protobuf_to_dict.tests.sample_pb2' # @@protoc_insertion_point(class_scope:tests.MessageOfTypes) )) _sym_db.RegisterMessage(MessageOfTypes) _sym_db.RegisterMessage(MessageOfTypes.NestedType) NestedExtension = _reflection.GeneratedProtocolMessageType('NestedExtension', (_message.Message,), dict( DESCRIPTOR = _NESTEDEXTENSION, __module__ = 'nvidia_tao_tf1.core.coreobject.protobuf_to_dict.tests.sample_pb2' # @@protoc_insertion_point(class_scope:tests.NestedExtension) )) _sym_db.RegisterMessage(NestedExtension) MessageOfTypes.RegisterExtension(extDouble) MessageOfTypes.RegisterExtension(extString) MessageOfTypes.RegisterExtension(_NESTEDEXTENSION.extensions_by_name['extInt']) _NESTEDEXTENSION.extensions_by_name['extNested'].message_type = _MESSAGEOFTYPES_NESTEDTYPE MessageOfTypes.RegisterExtension(_NESTEDEXTENSION.extensions_by_name['extNested']) # @@protoc_insertion_point(module_scope)
tao_tensorflow1_backend-main
nvidia_tao_tf1/core/coreobject/protobuf_to_dict/tests/sample_pb2.py
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: nvidia_tao_tf1/core/coreobject/test_data/addressbook.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_tf1/core/coreobject/test_data/addressbook.proto', package='modulus.modulusobject', syntax='proto3', serialized_options=None, serialized_pb=_b('\n:nvidia_tao_tf1/core/coreobject/test_data/addressbook.proto\x12\x15modulus.modulusobject\"\x9e\x02\n\x0cMaglevPerson\x12\x11\n\tfull_name\x18\x01 \x01(\t\x12\n\n\x02id\x18\x02 \x01(\x05\x12\r\n\x05\x65mail\x18\x03 \x01(\t\x12\x45\n\x06phones\x18\x04 \x03(\x0b\x32\x35.modulus.modulusobject.MaglevPerson.MaglevPhoneNumber\x1a\x66\n\x11MaglevPhoneNumber\x12\x0e\n\x06number\x18\x01 \x01(\t\x12\x41\n\x04type\x18\x02 \x01(\x0e\x32\x33.modulus.modulusobject.MaglevPerson.MaglevPhoneType\"1\n\x0fMaglevPhoneType\x12\n\n\x06MOBILE\x10\x00\x12\x08\n\x04HOME\x10\x01\x12\x08\n\x04WORK\x10\x02\"H\n\x11MaglevAddressBook\x12\x33\n\x06people\x18\x01 \x03(\x0b\x32#.modulus.modulusobject.MaglevPersonb\x06proto3') ) _MAGLEVPERSON_MAGLEVPHONETYPE = _descriptor.EnumDescriptor( name='MaglevPhoneType', full_name='modulus.modulusobject.MaglevPerson.MaglevPhoneType', filename=None, file=DESCRIPTOR, values=[ _descriptor.EnumValueDescriptor( name='MOBILE', index=0, number=0, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='HOME', index=1, number=1, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='WORK', index=2, number=2, serialized_options=None, type=None), ], containing_type=None, serialized_options=None, serialized_start=323, serialized_end=372, ) _sym_db.RegisterEnumDescriptor(_MAGLEVPERSON_MAGLEVPHONETYPE) _MAGLEVPERSON_MAGLEVPHONENUMBER = _descriptor.Descriptor( name='MaglevPhoneNumber', full_name='modulus.modulusobject.MaglevPerson.MaglevPhoneNumber', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='number', full_name='modulus.modulusobject.MaglevPerson.MaglevPhoneNumber.number', 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='type', full_name='modulus.modulusobject.MaglevPerson.MaglevPhoneNumber.type', index=1, number=2, type=14, cpp_type=8, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=219, serialized_end=321, ) _MAGLEVPERSON = _descriptor.Descriptor( name='MaglevPerson', full_name='modulus.modulusobject.MaglevPerson', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='full_name', full_name='modulus.modulusobject.MaglevPerson.full_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='id', full_name='modulus.modulusobject.MaglevPerson.id', 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='email', full_name='modulus.modulusobject.MaglevPerson.email', 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='phones', full_name='modulus.modulusobject.MaglevPerson.phones', 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), ], extensions=[ ], nested_types=[_MAGLEVPERSON_MAGLEVPHONENUMBER, ], enum_types=[ _MAGLEVPERSON_MAGLEVPHONETYPE, ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=86, serialized_end=372, ) _MAGLEVADDRESSBOOK = _descriptor.Descriptor( name='MaglevAddressBook', full_name='modulus.modulusobject.MaglevAddressBook', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='people', full_name='modulus.modulusobject.MaglevAddressBook.people', 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=374, serialized_end=446, ) _MAGLEVPERSON_MAGLEVPHONENUMBER.fields_by_name['type'].enum_type = _MAGLEVPERSON_MAGLEVPHONETYPE _MAGLEVPERSON_MAGLEVPHONENUMBER.containing_type = _MAGLEVPERSON _MAGLEVPERSON.fields_by_name['phones'].message_type = _MAGLEVPERSON_MAGLEVPHONENUMBER _MAGLEVPERSON_MAGLEVPHONETYPE.containing_type = _MAGLEVPERSON _MAGLEVADDRESSBOOK.fields_by_name['people'].message_type = _MAGLEVPERSON DESCRIPTOR.message_types_by_name['MaglevPerson'] = _MAGLEVPERSON DESCRIPTOR.message_types_by_name['MaglevAddressBook'] = _MAGLEVADDRESSBOOK _sym_db.RegisterFileDescriptor(DESCRIPTOR) MaglevPerson = _reflection.GeneratedProtocolMessageType('MaglevPerson', (_message.Message,), dict( MaglevPhoneNumber = _reflection.GeneratedProtocolMessageType('MaglevPhoneNumber', (_message.Message,), dict( DESCRIPTOR = _MAGLEVPERSON_MAGLEVPHONENUMBER, __module__ = 'nvidia_tao_tf1.core.coreobject.test_data.addressbook_pb2' # @@protoc_insertion_point(class_scope:modulus.modulusobject.MaglevPerson.MaglevPhoneNumber) )) , DESCRIPTOR = _MAGLEVPERSON, __module__ = 'nvidia_tao_tf1.core.coreobject.test_data.addressbook_pb2' # @@protoc_insertion_point(class_scope:modulus.modulusobject.MaglevPerson) )) _sym_db.RegisterMessage(MaglevPerson) _sym_db.RegisterMessage(MaglevPerson.MaglevPhoneNumber) MaglevAddressBook = _reflection.GeneratedProtocolMessageType('MaglevAddressBook', (_message.Message,), dict( DESCRIPTOR = _MAGLEVADDRESSBOOK, __module__ = 'nvidia_tao_tf1.core.coreobject.test_data.addressbook_pb2' # @@protoc_insertion_point(class_scope:modulus.modulusobject.MaglevAddressBook) )) _sym_db.RegisterMessage(MaglevAddressBook) # @@protoc_insertion_point(module_scope)
tao_tensorflow1_backend-main
nvidia_tao_tf1/core/coreobject/test_data/addressbook_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. """Modules related to TensorFlow training operation.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from nvidia_tao_tf1.core.training.features import ( enable_deterministic_training, enable_mixed_precision, ) from nvidia_tao_tf1.core.training.train_op_generator import TrainOpGenerator __all__ = ( "enable_deterministic_training", "enable_mixed_precision", "TrainOpGenerator", )
tao_tensorflow1_backend-main
nvidia_tao_tf1/core/training/__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. """Tests for TrainOpGenerator class.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow as tf from nvidia_tao_tf1.core.training.train_op_generator import TrainOpGenerator class TestTrainOpGenerator(object): """Test TrainOpGenerator class.""" INITIAL_VALUE = 10.0 INCREMENT = 0.1 DECREMENT = 1.0 def _get_generator(self, cost_scaling_enabled): """Setup a training op generator object.""" return TrainOpGenerator( cost_scaling_enabled=cost_scaling_enabled, cost_scaling_init=self.INITIAL_VALUE, cost_scaling_inc=self.INCREMENT, cost_scaling_dec=self.DECREMENT, ) def test_cost_scaling(self): """Verify dynamic cost scaling.""" # Create a minimal graph. data = tf.Variable( initial_value=100.0, dtype=tf.float32, name="data", trainable=False ) weight = tf.Variable(initial_value=1.0, dtype=tf.float32, name="weight") graph_out = weight * data target = 2.0 # Create L1 cost. cost = tf.abs(graph_out - target) # Create SGD optimizer. optimizer = tf.compat.v1.train.GradientDescentOptimizer(learning_rate=0.1) # Create the training op. generator = self._get_generator(cost_scaling_enabled=True) train_op = generator.get_train_op(optimizer, cost) # Create initializers. init_ops = [ var.initializer for var in tf.compat.v1.get_collection( tf.compat.v1.GraphKeys.GLOBAL_VARIABLES ) ] # Initialize and run training. with tf.compat.v1.Session() as session: # Initialize all variables. session.run(init_ops) # Verify that cost scaling is properly initialized. cost_scaling_exponent = session.run("cost_scaling_exponent:0") np.testing.assert_allclose(cost_scaling_exponent, self.INITIAL_VALUE) # Run one training iteration. session.run(train_op) # Verify that scaling exponent is increased. cost_scaling_exponent = session.run("cost_scaling_exponent:0") expected_value = self.INITIAL_VALUE + self.INCREMENT np.testing.assert_allclose(cost_scaling_exponent, expected_value) # Store the weight after 1st iteration. weight_step_1 = session.run(weight) # Make data non-finite, which triggers cost scaling backoff. session.run(tf.compat.v1.assign(data, np.inf)) # Run another step. session.run(train_op) # Verify that scaling exponent is decreased. cost_scaling_exponent = session.run("cost_scaling_exponent:0") expected_value = self.INITIAL_VALUE + self.INCREMENT - self.DECREMENT np.testing.assert_allclose(cost_scaling_exponent, expected_value) # Get the weight after 2nd iteration, make sure bad gradient was not applied. weight_step_2 = session.run(weight) np.testing.assert_allclose(weight_step_1, weight_step_2) def test_without_cost_scaling(self): """Verify that train op generator returns a good op, when cost scaling is disabled.""" # Create dummy optimizer and cost. optimizer = tf.compat.v1.train.GradientDescentOptimizer(learning_rate=0.1) cost = tf.Variable(initial_value=1.0, dtype=tf.float32, name="dummy_cost") # Create training op generator and the op itself. generator = self._get_generator(cost_scaling_enabled=False) train_op = generator.get_train_op(optimizer, cost) # Create initializers. init_ops = [ var.initializer for var in tf.compat.v1.get_collection( tf.compat.v1.GraphKeys.GLOBAL_VARIABLES ) ] # Initialize and make sure that the training op works OK. with tf.compat.v1.Session() as session: session.run(init_ops) cost_step_0 = session.run(cost) session.run(train_op) cost_step_1 = session.run(cost) assert cost_step_1 < cost_step_0, "Optimizer increased the cost"
tao_tensorflow1_backend-main
nvidia_tao_tf1/core/training/test_train_op_generator.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 for for determinism and mixed precision run-time env var setup.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os def enable_deterministic_training(): """Enable deterministic training.""" os.environ["TF_CUDNN_DETERMINISTIC"] = "true" os.environ["TF_DETERMINISTIC_OPS"] = "true" os.environ["HOROVOD_FUSION_THRESHOLD"] = "0" def enable_mixed_precision(): """Enable mixed precision for training.""" # Notes from Nvidia public guide # https://docs.nvidia.com/deeplearning/frameworks/tensorflow-user-guide/index.html#tfamp # Read the Caveats section carefully before enabling!!! # Multi-GPU: # Automatic mixed precision does not currently support TensorFlow # Distributed Strategies. Instead, multi-GPU training needs to be with Horovod # (or TensorFlow device primitives). We expect this restriction to be relaxed in # a future release. # For additional control, use flags: # TF_ENABLE_AUTO_MIXED_PRECISION_GRAPH_REWRITE=1 # TF_ENABLE_AUTO_MIXED_PRECISION_LOSS_SCALING=1 os.environ["TF_ENABLE_AUTO_MIXED_PRECISION"] = "1"
tao_tensorflow1_backend-main
nvidia_tao_tf1/core/training/features.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. """Test script for training a model in eager mode.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import os import random import numpy as np import tensorflow as tf tf.compat.v1.enable_eager_execution() from nvidia_tao_tf1.core.training.features import enable_deterministic_training # noqa: E402 from nvidia_tao_tf1.core.utils.path_utils import expand_path def _set_seeds(seed): random.seed(seed) np.random.seed(seed) tf.compat.v1.set_random_seed(seed) def _make_model(): return tf.keras.models.Sequential( [ tf.keras.layers.Flatten(input_shape=(28, 28)), tf.keras.layers.Dense(128, activation="relu"), tf.keras.layers.Dropout(0.2), tf.keras.layers.Dense(10, activation="softmax"), ] ) def _make_data_loaders(): mnist = tf.keras.datasets.mnist (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train, x_test = x_train / 255.0, x_test / 255.0 # Add a channels dimension x_train = x_train[..., tf.newaxis] x_test = x_test[..., tf.newaxis] train_ds = ( tf.data.Dataset.from_tensor_slices((x_train, y_train)).shuffle(10000).batch(32) ) test_ds = tf.data.Dataset.from_tensor_slices((x_test, y_test)).batch(32) return train_ds, test_ds def main(model_path, deterministic, seed): """Train a model in eager mode.""" if deterministic: enable_deterministic_training() _set_seeds(seed) results_dir = os.path.dirname(model_path) if not os.path.exists(expand_path(results_dir)): os.mkdir(expand_path(results_dir)) if os.path.exists(expand_path(model_path)): raise ValueError("Model already exists at path `{}`".format(model_path)) calculate_loss = tf.keras.losses.SparseCategoricalCrossentropy() optimizer = tf.keras.optimizers.Adam() model = _make_model() train_ds, test_ds = _make_data_loaders() train_loss = tf.keras.metrics.Mean(name="train_loss") train_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name="train_accuracy") test_loss = tf.keras.metrics.Mean(name="test_loss") test_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name="test_accuracy") @tf.function def train_step(images, labels): with tf.GradientTape() as tape: predictions = model(images) loss = calculate_loss(labels, predictions) gradients = tape.gradient(loss, model.trainable_variables) optimizer.apply_gradients(zip(gradients, model.trainable_variables)) train_loss(loss) train_accuracy(labels, predictions) @tf.function def test_step(images, labels): predictions = model(images) t_loss = calculate_loss(labels, predictions) test_loss(t_loss) test_accuracy(labels, predictions) EPOCHS = 2 for epoch in range(EPOCHS): for images, labels in train_ds: train_step(images, labels) for test_images, test_labels in test_ds: test_step(test_images, test_labels) template = "Epoch {}, Loss: {}, Accuracy: {}, Test Loss: {}, Test Accuracy: {}" print( template.format( epoch + 1, train_loss.result(), train_accuracy.result() * 100, test_loss.result(), test_accuracy.result() * 100, ) ) model.save(model_path) if __name__ == "__main__": parser = argparse.ArgumentParser( description="Tool for models.", formatter_class=argparse.ArgumentDefaultsHelpFormatter, ) parser.add_argument( "-d", "--deterministic", action="store_true", help="Use deterministic CuDNN kernels to produce the same results every time.", ) parser.add_argument( "-o", "--output_model", type=str, help="Model will be stored in the given path." ) parser.add_argument("-s", "--seed", type=int, default=42, help="Random seed.") args = parser.parse_args() main(model_path=args.output_model, deterministic=args.deterministic, seed=args.seed)
tao_tensorflow1_backend-main
nvidia_tao_tf1/core/training/train_eager.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. """Test for tensorflow add-on features.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import subprocess import tempfile import pytest def _execute_shell_cmd(cmd, debug=False, exit_on_return_code=True): """Execute the given command in a shell. Args: cmd(str): Complete command to execute debug(boolean): Debug mode; will log the commands and its output to the console. exit_on_return_code (bool): Will call exit with the return code of the subprocess. Returns: stdout(str): Command output captured from the console/stderr stream in case of error. """ if debug: print("Executing cmd: '{}'".format(cmd)) process = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True ) proc_out = process.communicate() proc_stdout = proc_out[0].strip() proc_stderr = proc_out[1].strip() if debug: print(proc_stdout) # Always print error message if any. if proc_stderr: print(proc_stderr) if exit_on_return_code and process.returncode: exit(process.returncode) if proc_stdout: return proc_stdout.decode("utf-8") return proc_stderr.decode("utf-8") _params = [ # No need to test for differences in models generated with non-deterministic # training for `train`; it might generate models that may differ, or may # match on different runs, hence we can't really test for that. ("nvidia_tao_tf1/core/training/train.py", False, True), # ("moduluspy/modulus/training/train_eager", True, False), ] @pytest.mark.parametrize("app, test_for_non_deterministic_diff, diff", _params) def test_determinism(app, test_for_non_deterministic_diff, diff): """Test determinism of generated models.""" temp_dir = tempfile.mkdtemp() # Generate two models with determinism ON and one with determinism OFF. model1_file = os.path.join(temp_dir, "model_1.hdf5") model2_file = os.path.join(temp_dir, "model_2.hdf5") model3_file = os.path.join(temp_dir, "model_3.hdf5") _execute_shell_cmd("{} -o {} --deterministic --seed=42".format(app, model1_file)) _execute_shell_cmd("{} -o {} --deterministic --seed=42".format(app, model2_file)) if test_for_non_deterministic_diff: _execute_shell_cmd("{} -o {} --seed=42".format(app, model3_file)) # Model 1 and 2 should be same. assert "" == _execute_shell_cmd("h5diff {} {}".format(model1_file, model2_file)) # Model 1 and 3 trained with determinism flag on/off respectively. # They might differ depending on eager-ness of TF and other conditions. # In case they differ, we expect the h5diff to return err code. if test_for_non_deterministic_diff: if diff: assert "Differences found" in _execute_shell_cmd( "h5diff {} {}".format(model1_file, model3_file), exit_on_return_code=False, ) else: assert "" == _execute_shell_cmd( "h5diff {} {}".format(model1_file, model3_file), exit_on_return_code=False, )
tao_tensorflow1_backend-main
nvidia_tao_tf1/core/training/features_test.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. """TrainOpGenerator class.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import logging from keras import backend as K import tensorflow as tf logger = logging.getLogger(__name__) class TrainOpGenerator(object): """TrainOpGenerator class. TrainOpGenerator contains parameters for dynamic cost scaling required in mixed-precision training. It creates a TF op that includes the adaptation logic for dynamic cost scaling. The cost scaling feature can be disabled through parameters and in this case the generator returns a plain train op by calling optimizer.minimize. """ def __init__( self, cost_scaling_enabled, cost_scaling_init, cost_scaling_inc, cost_scaling_dec, ): """Setup a train op generator. Args: cost_scaling_enabled (bool): Enable or disable dynamic cost scaling. cost_scaling_init (float): Initial value for cost scaling exponent. cost_scaling_inc (float): Added to scaling exponent if gradients are OK. cost_scaling_dec (float): Subtracted from scaling exponent if gradients overflow. """ # Store the parameters. self.cost_scaling_enabled = cost_scaling_enabled self.cost_scaling_init = cost_scaling_init self.cost_scaling_inc = cost_scaling_inc self.cost_scaling_dec = cost_scaling_dec # Sanity check: allow user to train float16 without cost scaling, but give a warning. if K.floatx() == "float16" and not self.cost_scaling_enabled: logger.warning( "Cost scaling is disabled while mixed-precision training is enabled." ) def get_train_op(self, optimizer, total_cost, var_list=None): """Return a train op with or without cost scaling. Args: optimizer (horovod.tensorflow.DistributedOptimizer): TF-compatible optimizer object. total_cost (float32 tf.Tensor): Scalar cost value used for computing gradients. var_list (list<tf.Variable>): Variables to update to minimize loss. If None, defaults to the list of variables collected in the graph under the key GraphKeys.TRAINABLE_VARIABLES. """ if self.cost_scaling_enabled: return self._get_train_op_with_cost_scaling(optimizer, total_cost, var_list) return self._get_train_op_without_cost_scaling(optimizer, total_cost, var_list) def _get_train_op_without_cost_scaling(self, optimizer, total_cost, var_list): """Return a train op without cost scaling. Args: optimizer (horovod.tensorflow.DistributedOptimizer): TF-compatible optimizer object. total_cost (float32 tf.Tensor): Scalar cost value used for computing gradients. var_list (list<tf.Variable>): Variables to update to minimize loss. If None, defaults to the list of variables collected in the graph under the key GraphKeys.TRAINABLE_VARIABLES. """ global_step = tf.compat.v1.train.get_or_create_global_step() return optimizer.minimize( loss=total_cost, global_step=global_step, var_list=var_list ) def _get_train_op_with_cost_scaling(self, optimizer, total_cost, var_list): """Return a train op with cost scaling. Args: optimizer (horovod.tensorflow.DistributedOptimizer): TF-compatible optimizer object. total_cost (float32 tf.Tensor): Scalar cost value used for computing gradients. var_list (list<tf.Variable>): Variables to update to minimize loss. If None, defaults to the list of variables collected in the graph under the key GraphKeys.TRAINABLE_VARIABLES. """ # Create a persistent cost scaling exponent. cost_scaling_exponent = tf.Variable( initial_value=self.cost_scaling_init, dtype=tf.float32, name="cost_scaling_exponent", trainable=False, ) # Log the number of discarded gradients. bad_grad_counter = tf.Variable( initial_value=0, dtype=tf.int64, name="bad_grad_counter", trainable=False ) # Multiply the total cost by 2^X. cost_multiplier = 2.0 ** cost_scaling_exponent inverse_multiplier = 1.0 / cost_multiplier scaled_total_cost = total_cost * cost_multiplier # Add tensorboard summaries. tf.compat.v1.summary.scalar("scaled_total_cost", scaled_total_cost) tf.compat.v1.summary.scalar("cost_scaling_exponent", cost_scaling_exponent) tf.compat.v1.summary.scalar("bad_grad_counter", bad_grad_counter) # Get the gradient tensors with the scaled cost. grads_and_vars = optimizer.compute_gradients( loss=scaled_total_cost, var_list=var_list ) # Bring the gradient scale back to original (divide by 2^X). grads_and_vars = [ (grad * inverse_multiplier, var) for grad, var in grads_and_vars if grad is not None ] # Check that gradients are finite. grad_ok = tf.reduce_all( input_tensor=tf.stack( [ tf.reduce_all(input_tensor=tf.math.is_finite(grad)) for grad, var in grads_and_vars ] ) ) # When gradients are not OK, apply zeros to maintain Horovod multi-GPU sync. zero_grads_and_vars = [ (tf.zeros_like(var), var) for grad, var in grads_and_vars ] # Get global step. global_step = tf.compat.v1.train.get_or_create_global_step() # Create a conditional training op. train_op = tf.cond( # Condition is the finiteness of the gradients. pred=grad_ok, # Finite gradients -> increase scaling and apply gradients. true_fn=lambda: tf.group( tf.compat.v1.assign_add(cost_scaling_exponent, self.cost_scaling_inc), optimizer.apply_gradients( grads_and_vars=grads_and_vars, global_step=global_step ), ), # Invalid gradients -> decrease scaling and apply zero-gradients. false_fn=lambda: tf.group( tf.compat.v1.assign_add(bad_grad_counter, 1), tf.compat.v1.assign_add(cost_scaling_exponent, -self.cost_scaling_dec), optimizer.apply_gradients( grads_and_vars=zero_grads_and_vars, global_step=global_step ), ), ) return train_op
tao_tensorflow1_backend-main
nvidia_tao_tf1/core/training/train_op_generator.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. """Test script for training a model.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import os import random import numpy as np import tensorflow as tf from nvidia_tao_tf1.core.training.features import enable_deterministic_training from nvidia_tao_tf1.core.utils.path_utils import expand_path def _set_seeds(seed): random.seed(seed) np.random.seed(seed) tf.compat.v1.set_random_seed(seed) def main(model_path, deterministic, seed): """Train a model.""" if deterministic: enable_deterministic_training() _set_seeds(seed) results_dir = os.path.dirname(model_path) if not os.path.exists(expand_path(results_dir)): os.mkdir(expand_path(results_dir)) if os.path.exists(expand_path(model_path)): raise ValueError("Model already exists at path `{}`".format(model_path)) mnist = tf.keras.datasets.mnist (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train, x_test = x_train / 255.0, x_test / 255.0 model = tf.keras.models.Sequential( [ tf.keras.layers.Flatten(input_shape=(28, 28)), tf.keras.layers.Dense(128, activation="relu"), tf.keras.layers.Dropout(0.2), tf.keras.layers.Dense(10, activation="softmax"), ] ) model.compile( optimizer="adam", loss="sparse_categorical_crossentropy", metrics=["accuracy"] ) model.fit(x_train, y_train, epochs=5) model.save(model_path) model.evaluate(x_test, y_test) if __name__ == "__main__": parser = argparse.ArgumentParser( description="Tool for models.", formatter_class=argparse.ArgumentDefaultsHelpFormatter, ) parser.add_argument( "-d", "--deterministic", action="store_true", help="Use deterministic CuDNN kernels to produce the same results every time.", ) parser.add_argument( "-o", "--output_model", type=str, help="Model will be stored in the given path." ) parser.add_argument("-s", "--seed", type=int, default=42, help="Random seed.") args = parser.parse_args() main(model_path=args.output_model, deterministic=args.deterministic, seed=args.seed)
tao_tensorflow1_backend-main
nvidia_tao_tf1/core/training/train.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. """ Graph package contains all graph related operations. It assumes implicitly that we're using Tensorflow graph. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from nvidia_tao_tf1.core.graph.initializers import get_init_ops __all__ = ("get_init_ops",)
tao_tensorflow1_backend-main
nvidia_tao_tf1/core/graph/__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. """Tensorflow Graph initializer functions.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf def get_init_ops(): """Return all ops required for initialization.""" return tf.group( tf.compat.v1.local_variables_initializer(), tf.compat.v1.tables_initializer(), *tf.compat.v1.get_collection("iterator_init") )
tao_tensorflow1_backend-main
nvidia_tao_tf1/core/graph/initializers.py
import mock from nvidia_tao_tf1.core import distribution import tensorflow as tf tf.compat.v1.enable_eager_execution() @mock.patch( "nvidia_tao_tf1.core.distribution.distribution.tf.config.experimental." "set_visible_devices" ) def test_tensorflow_eager_mode_init(mocked_set_visible_devices): # Eager mode based initialization uses explicit device set function. distribution.set_distributor(distribution.HorovodDistributor()) mocked_set_visible_devices.assert_called_once()
tao_tensorflow1_backend-main
nvidia_tao_tf1/core/distribution/test_distribution_eager.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. """Process-distribution functions.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from nvidia_tao_tf1.core.distribution.distribution import Distributor, HorovodDistributor, hvd from nvidia_tao_tf1.core.distribution.distribution import get_distributor, set_distributor __all__ = ( "Distributor", "hvd", "HorovodDistributor", "set_distributor", "get_distributor", )
tao_tensorflow1_backend-main
nvidia_tao_tf1/core/distribution/__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. """Process-distribution functions.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from functools import lru_cache import os import sys import tensorflow as tf if os.environ.get("TF_KERAS"): from tensorflow import keras # pylint: disable=C0412 else: import keras class Distributor(object): """Base distributor object. This base distributor object behaves as if only one process is running, without any actual distribution. """ def __init__(self, master_rank=0, per_process_gpu_memory_fraction=None): """__init__ method. Args: master_rank (int): specifies the intended rank of the master. per_process_gpu_memory_fraction (float): fraction of GPU memory to reserve for TensorFlow. Ignored if unset. """ if master_rank >= self.size(): raise ValueError( "Requested a master rank of {}, which should be smaller than " "the distribution size ({}).".format(master_rank, self.size()) ) self._master_rank = master_rank self._per_process_gpu_memory_fraction = per_process_gpu_memory_fraction def get_config(self): """Get configuration to pass to tf Session.""" config = tf.compat.v1.ConfigProto() config.gpu_options.visible_device_list = str(self.local_rank()) config.gpu_options.allow_growth = True if self._per_process_gpu_memory_fraction is not None: config.gpu_options.per_process_gpu_memory_fraction = ( self._per_process_gpu_memory_fraction ) return config def size(self): """Get the size. Returns: Total amount of processes. """ return 1 def local_size(self): """Get the local size. NOTE: 'local' is defined as 'inside the current node'. Returns: Total amount of distributed processes locally (int). """ return 1 def rank(self): """Get the rank. Returns: Global rank (index). """ return 0 def local_rank(self): """Get the local rank. NOTE: 'local' is defined as 'inside the current node'. Returns: Local rank (int). """ return 0 def is_multi_node(self): """Check if we are running distribution over multiple nodes. Returns: A boolean indicating if we have processes running on (True) multiple nodes or a single node (False). """ return self.size() != self.local_size() def is_master(self): """Check if the current process is the master process. Returns: A boolean indicating if the current process is the master process. """ return self._master_rank == self.rank() def is_distributed(self): """Check if we're running in distributed mode. Returns: A boolean indicating if we in a distributed setting. """ return self.size() > 1 def distributed_seed(self, seed): """Get a distributed seed, to avoid the same seed per process. Args: seed (int): the current fixed seed. Returns: A perturbed seed depending on rank, as a function of the input seed. """ if seed is None: return seed return seed + self.rank() def broadcast_global_variables(self): """Broadcast variables from master rank to all other processes.""" pass def distribute_optimizer(self, optimizer): """Distribute the input optimizer.""" return optimizer def allreduce(self, value): """Allreduce operation that sums value across GPUs. Args: value: value to be summed. Returns: Sum of value across all GPUs. """ return value def shutdown(self): """Shut the distribution strategy down.""" sys.exit("A request has been made to shutdown the distribution strategy.") def distributed_gradient_tape(self, tape): """Add distributed GradientTape for tensorflow eager mode. Args: tape (tf.GradientTape): Recorded operations of automatic differentiation. Returns: tape (tf.GradientTape): The input tape wrapped in a tape that takes care of the distribution. """ return tape def broadcast_variables(self, variables, root_rank=0): """Broadcast variables from root_rank to other ranks. Args: variables (tf.Variable): Tensorflow variables that need to be broadcast. root_rank (int): From which rank the variables need to be broadcast. """ pass @lru_cache() def hvd(): """Lazily load and return the (cached) horovod module.""" import horovod.tensorflow as hvd return hvd class HorovodDistributor(Distributor): """Horovod distributor object. This object wraps several horovod functions and provides some utilities. Notice that the horovod module is lazily loaded so that it is only a dependency to maglev when you want to use the HorovodDistributor object. The documentation of horovod is hosted on `<https://github.com/uber/horovod>`_. Horovod's core principles are based on `MPI <https://github.com/uber/horovod/blob/master/docs/concepts.md>`_. This distributor parallelizes your training script by using custom Tensorflow operations and leveraging MPI. The parallelization of your script is done through launching your script using ``MPI``, for example using OpenMPI's `mpirun`. So instead of:: python train.py One would launch 4 local processes using:: mpirun -np 4 python train.py Where ``train.py`` should use the current distributor and its methods. Horovod will then map each of the 4 local processes on different GPUs. If you do not want to use the horovod distributor, but want to have your code distributor-enabled, you can just use the base :any:`nvidia_tao_tf1.core.distribution.Distributor` class, that is undistributed by default and acts as a passthrough. """ def __init__(self, **kwargs): """__init__ method. Initializes horovod, and pins GPUs to the current session. This initialization should happen before any of the other distribution functions are imported, used or called. Args: **kwargs: arbitrary keyword arguments. """ hvd().init() super(HorovodDistributor, self).__init__(**kwargs) if not tf.executing_eagerly(): # Pin GPU to be used to process local rank (one GPU per process) session = tf.compat.v1.Session(config=self.get_config()) keras.backend.set_session(session) else: gpus = tf.config.experimental.list_physical_devices("GPU") if self.local_rank() >= len(gpus): raise ValueError( "Requesting a local rank {}, which should be" "smaller than the gpu count {}.".format( self.local_rank(), len(gpus) ) ) gpu = gpus[self.local_rank()] tf.config.experimental.set_memory_growth(gpu, True) tf.config.experimental.set_visible_devices(gpu, "GPU") def size(self): """Get the size. Returns: Total amount of distributed processes (int). """ return hvd().size() def local_size(self): """Get the local size. NOTE: 'local' is defined as 'inside the current node'. Returns: Total amount of distributed processes locally (int). """ return hvd().local_size() def rank(self): """Get the rank. The rank can be considered the current global unique rank (or index), where all nodes and all processes within a node are considered. Returns: Rank (int) """ return hvd().rank() def local_rank(self): """Get the local rank. NOTE: 'local' is defined as 'inside the current node'. Returns: Local rank (int). """ return hvd().local_rank() def broadcast_global_variables(self): """Broadcast variables from master rank to all other processes. This function should be called after all variables are created, but before evaluating any operations that require distribution, like allreduce or using the distributed optimizer. """ broadcast_ops = hvd().broadcast_global_variables(self._master_rank) keras.backend.get_session().run(broadcast_ops) def broadcast_global_variables_hook(self): """Broadcast variables from master rank to all other processes. BroadcastGlobalVariablesHook broadcasts initial variable states from rank 0 to all other processes. This is necessary to ensure consistent initialization of all workers when training is started with random weights or restored from a checkpoint. Returns: A instance that inherits from a `tf.estimator.SessionRunHook` object that takes care of variable initialization across processes. """ # Note that the class inherits from a lazy horovod import, which is why it is defined # inline. class _ScopedBroadcastGlobalVariablesHook(hvd().BroadcastGlobalVariablesHook): """Class that wraps the global variables broadcast hook into one with op scopes.""" def begin(self, *args, **kwargs): """Call begin by forwarding the begin call within a tf name scope.""" with tf.compat.v1.name_scope("horovod_broadcast"): super(_ScopedBroadcastGlobalVariablesHook, self).begin( *args, **kwargs ) return _ScopedBroadcastGlobalVariablesHook(0) def distribute_optimizer(self, optimizer): """Distribute the input optimizer. Args: optimizer: a tensorflow optimizer object to be distributed. Returns: The input optimizer wrapped in an optimizer that takes care of the distribution. """ hvd_optimizer = hvd().DistributedOptimizer(optimizer) return hvd_optimizer def allreduce(self, value): """Allreduce operation that sums value across GPUs. Args: value: value to be summed. Returns: Sum of value across all GPUs. """ return hvd().allreduce(value) def shutdown(self): """Shut horovod down. Note that while this does not exit the process, if, later down the line, another process sends tensors to be reduced / gathered through horovod, the latter will detect that it has been shutdown, and crash as (hopefully) appropriate. """ hvd().shutdown() def distributed_gradient_tape(self, tape): """Add Horovod Distributed GradientTape for tensorflow eager mode. Args: tape (tf.GradientTape): Recorded operations of automatic differentiation. Returns: tape (tf.GradientTape): The input tape wrapped in a tape that takes care of the distribution. """ return hvd().DistributedGradientTape(tape) def broadcast_variables(self, variables, root_rank=0): """Broadcast variables from root_rank to other ranks. Args: variables (tf.Variable): tensorflow variables that need to be broadcast. root_rank (int): From which rank the variables need to be broadcast. """ hvd().broadcast_variables(variables, root_rank=root_rank) # Define the distributor here so it's static. _DISTRIBUTOR = Distributor() def set_distributor(d): """Set the distributor. Args: d: an instance who's class derives from Distributor to serve as the new distribution object. """ global _DISTRIBUTOR # pylint: disable=W0603 _DISTRIBUTOR = d def get_distributor(): """Get the distributor.""" global _DISTRIBUTOR # pylint: disable=W0602,W0603 return _DISTRIBUTOR
tao_tensorflow1_backend-main
nvidia_tao_tf1/core/distribution/distribution.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. from __future__ import absolute_import from __future__ import division from __future__ import print_function from imp import reload # Python 2/3 support. pylint: disable=redefined-builtin, disable=W4901 import mock from nvidia_tao_tf1.core import distribution import pytest import tensorflow as tf def _has_hvd_support(): try: distribution.hvd() except ImportError: return False return True def test_get_and_set_distributor(): """Test the distributor.""" # Attempt to load Horovod at the beginning of the test # v.s. formerly during test collection. This is to avoid # Horovod getting in the way of our TensorFlow ungreedy # configuration in conftest.py. if not _has_hvd_support(): raise pytest.skip("requires horovod") default_distributor = distribution.get_distributor() assert isinstance(default_distributor, distribution.Distributor) # Set the horovod distributor. hvd_distributor = distribution.HorovodDistributor() distribution.set_distributor(hvd_distributor) # Get the distributor we just set. distributor = distribution.get_distributor() assert hvd_distributor == distributor # Make sure to reload after this test, as the distributor is static. reload(distribution) def test_master_rank(): """Test the default and setting of the master rank.""" distributor = distribution.Distributor() assert distributor._master_rank == 0 assert distributor.size() == 1 assert distributor.rank() == 0 assert distributor.local_rank() == 0 assert distributor.is_master() assert not distributor.is_multi_node() # Test that a master rank larger than the size throws an error. master_rank = 1 with pytest.raises(ValueError): distributor = distribution.Distributor(master_rank=master_rank) # Check that that a current rank different from the master rank is not the master. distributor = distribution.Distributor() distributor._master_rank = 3 assert not distributor.is_master() # Check the configuration returns the right object assert isinstance(distributor.get_config(), tf.compat.v1.ConfigProto) # def test_shutdown_default_distributor(): # """Test shutdown behavior for Distributor.""" # distributor = distribution.Distributor() # with pytest.raises(SystemExit, match=r"*shutdown the distribution strategy.*"): # distributor.shutdown() @pytest.mark.skipif(not _has_hvd_support(), reason="requires horovod") def test_shutdown_horovod_distributor(): """Test shutdown behavior for HorovodDistributor.""" distributor = distribution.HorovodDistributor() with mock.patch.object(distribution.hvd(), "shutdown") as mocked_shutdown: distributor.shutdown() mocked_shutdown.assert_called_once() # @mock.patch("nvidia_tao_tf1.core.distribution.distribution.tf.compat.v1.Session") # def test_tensorflow_graph_mode_init(mocked_session): # # Graph mode based initialization requires tf.Session. # distribution.set_distributor(distribution.HorovodDistributor()) # mocked_session.assert_called_once()
tao_tensorflow1_backend-main
nvidia_tao_tf1/core/distribution/test_distribution.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. from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import random import keras from keras import backend as K import numpy as np import pytest import tensorflow as tf import nvidia_tao_tf1.core.utils @pytest.mark.parametrize("model_prefix", ["model", "model_1", "super_model"]) def test_find_latest_keras_model_in_directory(tmpdir, model_prefix): """Test find latest Keras model in directory.""" fake_model_dir = tmpdir.mkdir("model_dir") mocked_files = [ "{}.keras-1.hdf5".format(model_prefix), "{}.keras-4.hdf5".format(model_prefix), "{}.keras-100.hdf5".format(model_prefix), ] for mocked_file in mocked_files: fake_model_dir.join(mocked_file).write("content") latest_model_file_path = nvidia_tao_tf1.core.utils.find_latest_keras_model_in_directory( fake_model_dir.strpath, model_prefix=model_prefix ) assert latest_model_file_path == os.path.join( fake_model_dir.strpath, "{}.keras-100.hdf5".format(model_prefix) ) latest_model_file_path = nvidia_tao_tf1.core.utils.find_latest_keras_model_in_directory( tmpdir.mkdir("empty_dir").strpath, model_prefix=model_prefix ) assert latest_model_file_path is None def test_get_uid(): # make a random name name = "".join(["%c" % (chr(ord("A") + random.randint(0, 25))) for _ in range(10)]) assert nvidia_tao_tf1.core.utils.get_uid_name(name) == "%s" % name assert nvidia_tao_tf1.core.utils.get_uid_name(name) == "%s_1" % name assert nvidia_tao_tf1.core.utils.get_uid_name(name) == "%s_2" % name def test_random_seed_determinism(seed=0): """Test random seeds results in deterministic results.""" def _get_random_numbers(): """Get random numbers from a few backends.""" # Keras weight RNG tf_rng_op = tf.random.normal([1]) layer = keras.layers.Dense(1) layer.build([10, 1]) keras_weight_val = layer.get_weights()[0] # Keras direct RNG keras_val = K.eval(K.random_normal([1])) # Tensorflow RNG tf_val = K.eval(tf_rng_op) # Numpy RNG np_val = np.random.rand() # Python RNG py_val = random.random() # Clear the backend state of the framework K.clear_session() return np.array([keras_weight_val, keras_val, tf_val, np_val, py_val]) a = _get_random_numbers() nvidia_tao_tf1.core.utils.set_random_seed(seed) b = _get_random_numbers() nvidia_tao_tf1.core.utils.set_random_seed(seed) c = _get_random_numbers() d = _get_random_numbers() np.testing.assert_equal((a == b).any(), False) np.testing.assert_array_equal(b, c) np.testing.assert_equal((c == d).any(), False) @pytest.mark.parametrize( "string_input, expected_output", [("test", "Test"), ("test_name", "TestName"), ("long_test_name", "LongTestName")], ) def test_to_camel_case(string_input, expected_output): assert nvidia_tao_tf1.core.utils.to_camel_case(string_input) == expected_output @pytest.mark.parametrize( "string_input, expected_output", [("Test", "test"), ("TestName", "test_name"), ("LongTestName", "long_test_name")], ) def test_to_snake_case(string_input, expected_output): assert nvidia_tao_tf1.core.utils.to_snake_case(string_input) == expected_output @pytest.mark.parametrize( "tag, simple_value", [("loss", 0.0003), ("lr", 0.0001), ("acc", 88.12)] ) def test_simple_values_from_event_file(tmpdir, tag, simple_value): """Test function to get simple values from event file.""" events_path = str(tmpdir) def summary_creator(tag, simple_value): summary = tf.compat.v1.Summary( value=[tf.compat.v1.Summary.Value(tag=str(tag), simple_value=simple_value)] ) return summary summary_writer = tf.compat.v1.summary.FileWriter(events_path) summary = summary_creator(tag, simple_value) summary_writer.add_summary(summary) summary_writer.flush() summary_writer.close() calculated_dict = nvidia_tao_tf1.core.utils.get_all_simple_values_from_event_file(events_path) calculated_values = [calculated_dict[key][0] for key in calculated_dict.keys()] assert list(calculated_dict.keys()) == [tag] assert np.allclose(calculated_values, [simple_value])
tao_tensorflow1_backend-main
nvidia_tao_tf1/core/utils/test_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 Core utils APIs.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from nvidia_tao_tf1.core.utils.utils import find_latest_keras_model_in_directory from nvidia_tao_tf1.core.utils.utils import get_all_simple_values_from_event_file from nvidia_tao_tf1.core.utils.utils import get_uid from nvidia_tao_tf1.core.utils.utils import get_uid_name from nvidia_tao_tf1.core.utils.utils import mkdir_p from nvidia_tao_tf1.core.utils.utils import recursive_map_dict from nvidia_tao_tf1.core.utils.utils import set_random_seed from nvidia_tao_tf1.core.utils.utils import summary_from_value from nvidia_tao_tf1.core.utils.utils import test_session from nvidia_tao_tf1.core.utils.utils import to_camel_case from nvidia_tao_tf1.core.utils.utils import to_snake_case __all__ = ( "find_latest_keras_model_in_directory", "get_all_simple_values_from_event_file", "get_uid", "get_uid_name", "mkdir_p", "recursive_map_dict", "set_random_seed", "summary_from_value", "test_session", "to_camel_case", "to_snake_case", )
tao_tensorflow1_backend-main
nvidia_tao_tf1/core/utils/__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. """Modulus utilities.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from collections import defaultdict import errno import glob import os import random import re import threading import numpy as np import tensorflow as tf from tensorflow.core.protobuf import rewriter_config_pb2 def find_latest_keras_model_in_directory(model_directory, model_prefix="model"): """Method to find the latest model in a given model directory. Args: model_directory (str): absolute path to the model directory. model_prefix (str): File prefix used to look up hdf5 files. Defaults to "model". """ def extract_model_number(files): s = re.findall(r"{}.keras-(\d+).hdf5".format(model_prefix), files) if not s: raise ValueError("No Keras model found in {}".format(model_directory)) return int(s[0]) if s else -1, files model_files = glob.glob(os.path.join(model_directory, "*.hdf5")) if not model_files: return None latest_model = max(model_files, key=extract_model_number) return latest_model def get_uid(base_name): """Return a unique ID.""" get_uid.lock.acquire() if base_name not in get_uid.seqn: get_uid.seqn[base_name] = 0 uid = get_uid.seqn[base_name] get_uid.seqn[base_name] += 1 get_uid.lock.release() return uid def get_uid_name(base_name): """ Get unique name. Get a unique name for an object, structured as the specified base name appended by an integer. Args: base_name (str): Base name. Returns: (str): Unique name for the given base name. """ uid = get_uid(base_name) return "%s%s" % (base_name, "_%s" % uid if uid > 0 else "") get_uid.seqn = {} get_uid.lock = threading.Lock() def set_random_seed(seed): """ Set random seeds. This sets the random seeds of Python, Numpy and TensorFlow. Args: seed (int): seed to use """ random.seed(seed) np.random.seed(seed) tf.compat.v1.set_random_seed(seed) def to_camel_case(snake_str): """Convert a name to camel case. For example ``test_name`` becomes ``TestName``. Args: name (str): name fo convert. """ components = snake_str.split("_") return "".join(x.title() for x in components) def to_snake_case(name): """Convert a name to snake case. For example ``TestName`` becomes ``test_name``. Args: name (str): name fo convert. """ s1 = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", name) return re.sub("([a-z0-9])([A-Z])", r"\1_\2", s1).lower() def test_session(allow_soft_placement=False, log_device_placement=False): """Get a tensorflow session with all graph optimizations turned off for deterministic testing. Using a regular session does not nessecarily guarantee explicit device placement to be placed on the requisted device. This test session makes sure placement is put on requested devices. Args: soft_device_placement (bool): Whether soft placement is allowed. log_device_placement (bool): Whether log out the device placement for each tensor. """ config = tf.compat.v1.ConfigProto() config.graph_options.optimizer_options.opt_level = -1 config.graph_options.rewrite_options.constant_folding = ( rewriter_config_pb2.RewriterConfig.OFF ) config.graph_options.rewrite_options.arithmetic_optimization = ( rewriter_config_pb2.RewriterConfig.OFF ) config.allow_soft_placement = allow_soft_placement config.log_device_placement = log_device_placement sess = tf.compat.v1.Session(config=config) return sess def summary_from_value(tag, value, scope=None): """Generate a manual simple summary object with a tag and a value.""" summary = tf.compat.v1.Summary() summary_value = summary.value.add() summary_value.simple_value = value if scope: summary_value.tag = "{}/{}".format(scope, tag) else: summary_value.tag = tag return summary def get_all_simple_values_from_event_file(event_path): """Retrieve all 'simple values' from event file into a nested dict. Args: event_path (str): path to a directory holding a `events.out.*` file. Returns: A nested dictionary containing all the simple values found in the events file, nesting first the tag (str) and then the step (int) as keys. """ event_files = glob.glob("%s/events.out.*" % event_path) assert len(event_files) == 1 values_dict = defaultdict(dict) for e in tf.compat.v1.train.summary_iterator(path=event_files[0]): for v in e.summary.value: if v.HasField("simple_value"): values_dict[v.tag][e.step] = v.simple_value return values_dict def recursive_map_dict(d, fn, exclude_fields=None): """Applies a function recursively on a dictionary's non-dict values. Note: no deep-copies take place: values are changed in-place, but the dict is returned regardless. Args: d (``dict`` or value): input dictionary or value. If it is not a ``dict``, ``fn`` will be applied to it. fn (function): function to be applied to ``d`` if ``d`` is not a ``dict``. exclude_fields (list): List of fields to exclude when mapping sparify operation to tensors i.e. not sparsify example.labels['field'] for field in exclude_fields. """ if exclude_fields is None: exclude_fields = [] if not isinstance(exclude_fields, list): raise ValueError("exclude_fields arg must be a list!") if isinstance(d, dict): for key in d: if key in exclude_fields: continue d[key] = recursive_map_dict(d[key], fn=fn) return d return fn(d) def mkdir_p(new_path): """Makedir, making also non-existing parent dirs.""" try: os.makedirs(new_path) except OSError as exc: if exc.errno == errno.EEXIST and os.path.isdir(new_path): pass else: raise
tao_tensorflow1_backend-main
nvidia_tao_tf1/core/utils/utils.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. """TAO common path utils used across all apps.""" import os def expand_path(path): """Function to resolve paths. This function takes in a path and returns the absolute path from the input string after expanding the tilde (~) character to the user's home directory to prevent path traversal vulnerability. Args: path (str): The path to expand and make absolute. Returns: str: The absolute path with expanded tilde. """ return os.path.abspath(os.path.expanduser(path))
tao_tensorflow1_backend-main
nvidia_tao_tf1/core/utils/path_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. """Modulus models.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from nvidia_tao_tf1.core.models import templates __all__ = ("templates",)
tao_tensorflow1_backend-main
nvidia_tao_tf1/core/models/__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 to import keras or tensorflow.keras.""" import os import tensorflow as tf def keras(): """Import keras.""" if os.environ.get("TF_KERAS") or tf.executing_eagerly(): from tensorflow import keras # pylint: disable=C0412 else: import keras return keras
tao_tensorflow1_backend-main
nvidia_tao_tf1/core/models/import_keras.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. """Create a Keras model for Quantization-Aware Training (QAT).""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import keras from keras.layers import ( Add, Average, Concatenate, Maximum, Minimum, Multiply, Permute, Subtract, ) from keras.layers import BatchNormalization, Conv2D, Conv2DTranspose, DepthwiseConv2D, Softmax from keras.layers import ELU, LeakyReLU, PReLU, ReLU from keras.layers.core import Activation from nvidia_tao_tf1.core.models.templates.qdq_layer import QDQ from nvidia_tao_tf1.core.models.templates.quantized_conv2d import QuantizedConv2D from nvidia_tao_tf1.core.models.templates.quantized_conv2dtranspose import QuantizedConv2DTranspose from nvidia_tao_tf1.core.models.templates.quantized_depthwiseconv2d import QuantizedDepthwiseConv2D output_types = [ Activation, ReLU, Softmax, Add, Subtract, Multiply, Average, Maximum, Minimum, Concatenate, Permute, ] def create_layer_from_config(layer, input_tensor): """Re-create a Keras layer from config.""" layer_config = layer.get_config() weights = layer.get_weights() new_layer = type(layer).from_config(layer_config) x = new_layer(input_tensor) new_layer.set_weights(weights) return x def _add_outputs(layer, output_layers): """Recursively find the output layers.""" for prev_layer in layer._inbound_nodes[0].inbound_layers: if prev_layer.name not in output_layers: output_layers.append(prev_layer.name) if type(prev_layer) in output_types: output_layers = _add_outputs(prev_layer, output_layers) return output_layers def create_quantized_keras_model(model): """Quantize a Keras model. This function replaces the Conv2D with QuantizedConv2D, ReLU with ReLU6 and adds QDQ layers as needed in the graph. It also uses the weights from original Keras model. Args: model (Keras model): The input Keras model. Returns: model (Keras model): A keras model prepared for Quantization-Aware Training. """ network_dict = {"input_layers_of": {}, "new_output_tensor_of": {}} # Set the input layers of each layer. for layer in model.layers: if len(layer._inbound_nodes) > 1: raise AttributeError( "Layers with multiple inbound nodes are not supported." ) inbound_node = layer._inbound_nodes[0] inbound_layers = [in_layer.name for in_layer in inbound_node.inbound_layers] if len(inbound_layers) > 0: network_dict["input_layers_of"].update({layer.name: inbound_layers}) input_layers = [ l for l in model.layers if len(l._inbound_nodes[0].inbound_layers) == 0 ] assert len(input_layers) > 0, "No input layer was found." assert len(input_layers) == len( model.inputs ), "Number of input layers does not match number of input tensors." for layer in input_layers: input_tensor = layer._inbound_nodes[0].input_tensors[0] assert input_tensor in model.inputs, "Input tensor not found in model inputs." input_tensor = QDQ(name=layer.name + "_qdq")(input_tensor) network_dict["new_output_tensor_of"].update({layer.name: input_tensor}) output_layers = [] for layer in model.layers: if len(layer._outbound_nodes) == 0: output_layers.append(layer.name) if type(layer) in output_types: output_layers = _add_outputs(layer, output_layers) output_tensors = [] for layer in model.layers: if layer.name not in network_dict["input_layers_of"]: # It's an input layer. continue # Determine input tensors. layer_input = [ network_dict["new_output_tensor_of"][layer_aux] for layer_aux in network_dict["input_layers_of"][layer.name] ] if len(layer_input) == 1: layer_input = layer_input[0] is_output = layer.name in output_layers if is_output: x = layer_input x = create_layer_from_config(layer, x) else: if type(layer) in [Conv2D, Conv2DTranspose, DepthwiseConv2D]: x = layer_input layer_config = layer.get_config() layer_config["quantize"] = False layer_config["bitwidth"] = 8 conv_act = layer_config["activation"] if conv_act != "linear": layer_config["activation"] = "linear" if type(layer) == Conv2D: new_layer = QuantizedConv2D.from_config(layer_config) elif type(layer) == Conv2DTranspose: new_layer = QuantizedConv2DTranspose.from_config(layer_config) elif type(layer) == DepthwiseConv2D: new_layer = QuantizedDepthwiseConv2D.from_config(layer_config) else: raise NotImplementedError( "Quantization for "+layer.__class__.__name__+" is not implemented" ) if layer.use_bias: kernels, biases = layer.get_weights() x = new_layer(x) new_layer.set_weights([kernels, biases]) else: kernels = layer.get_weights()[0] x = new_layer(x) new_layer.set_weights([kernels]) if conv_act == "linear": # TensorRT folds the BN into previous Conv. layer. # So if the output of this Conv. layer goes to only # a BN layer, then don't add a QDQ layer. if ( len(layer._outbound_nodes) != 1 or type(layer._outbound_nodes[0].outbound_layer) != BatchNormalization ): x = QDQ(name=layer.name + "_qdq")(x) else: # TensorRT fuses ReLU back into the Conv. layer. # Other activations are implemented as separate layers. # So we need to add QDQ layer unless the activation is ReLU if conv_act == "relu": x = ReLU(max_value=6.0)(x) else: x = QDQ(name=layer.name + "_qdq")(x) x = Activation(conv_act)(x) x = QDQ(name=layer.name + "_act_qdq")(x) elif type(layer) == Activation: # Need QDQ layer after every activation layers (except output layers.) x = layer_input layer_config = layer.get_config() if layer_config["activation"] == "relu": x = ReLU(max_value=6.0, name=layer.name)(x) else: x = create_layer_from_config(layer, x) x = QDQ(name=layer.name + "_qdq")(x) elif type(layer) in [ReLU, PReLU, ELU, LeakyReLU]: x = layer_input layer_config = layer.get_config() x = ReLU(max_value=6.0, name=layer.name)(x) x = QDQ(name=layer.name + "_qdq")(x) elif type(layer) == BatchNormalization: # TensorRT fuses Conv + BN + ReLU together. # So if previous layer is Conv. and next layer is # ReLU we should not add QDQ layers. x = layer_input x = create_layer_from_config(layer, x) next_layer_is_relu = False if len(layer._outbound_nodes) == 1: next_layer = layer._outbound_nodes[0].outbound_layer if type(next_layer) in [ReLU, PReLU, ELU, LeakyReLU]: next_layer_is_relu = True elif type(next_layer) == Activation: next_layer_cfg = next_layer.get_config() if next_layer_cfg["activation"] == "relu": next_layer_is_relu = True prev_layer_is_conv = ( len(layer._inbound_nodes[0].inbound_layers) == 1 and type(layer._inbound_nodes[0].inbound_layers[0]) in [Conv2D, Conv2DTranspose, DepthwiseConv2D] ) if not (next_layer_is_relu and prev_layer_is_conv): x = QDQ(name=layer.name + "_qdq")(x) else: x = layer_input x = create_layer_from_config(layer, x) x = QDQ(name=layer.name + "_qdq")(x) if len(layer._outbound_nodes) == 0: output_tensors.append(x) network_dict["new_output_tensor_of"].update({layer.name: x}) model = keras.models.Model(inputs=model.inputs, outputs=output_tensors) return model
tao_tensorflow1_backend-main
nvidia_tao_tf1/core/models/quantize_keras_model.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. from __future__ import absolute_import from __future__ import division from __future__ import print_function import keras from keras import backend as K from keras.layers import Activation from keras.layers import Add from keras.layers import Dense from keras.layers import ELU from keras.layers import Input from keras.layers import LeakyReLU from keras.layers import ReLU import numpy as np import nvidia_tao_tf1.core.models.templates.utils as utils import pytest cloning_tests = [ # no inputs --> return with placeholders ([(32,)], [], 1), # one input --> return with tensor ([(32,)], [(10, 32)], 0), # two inputs --> return with tensors ([(32,), (32,)], [(10, 32), (10, 32)], 0), # model has two inputs, but inputs only has one. --> throw error ([(32,), (32,)], [(10, 32)], None), # model has one input, but inputs has two. --> throw error ([(32,)], [(10, 32), (10, 32)], None), ] @pytest.mark.parametrize("copy_weights", [True, False]) @pytest.mark.parametrize( "model_inputs_shape, inputs_shape, expected_placeholders", cloning_tests ) def test_clone_model( copy_weights, model_inputs_shape, inputs_shape, expected_placeholders ): """Test cloning a model.""" # Add the first and last element of model_inputs. This ensures that whether there are # one or two inputs provided, all of them are used. model_inputs = [Input(shape=shape) for shape in model_inputs_shape] inputs = [ K.random_uniform_variable(shape=shape, low=0, high=1) for shape in inputs_shape ] if inputs == []: inputs = None middle_layer = Add()([model_inputs[0], model_inputs[-1]]) model = keras.models.Model(inputs=model_inputs, outputs=Dense(32)(middle_layer)) if expected_placeholders is not None: new_model = utils.clone_model(model, inputs=inputs, copy_weights=copy_weights) num_placeholders = len( [ l for l in new_model.layers if (("is_placeholder" in dir(l)) and (l.is_placeholder is True)) ] ) assert num_placeholders == expected_placeholders if copy_weights: for old_layer, new_layer in zip(model.layers, new_model.layers): old_weights = old_layer.get_weights() new_weights = new_layer.get_weights() for old_w, new_w in zip(old_weights, new_weights): np.testing.assert_array_equal(old_w, new_w) else: with pytest.raises(ValueError): new_model = utils.clone_model(model, inputs=inputs) activation_test_cases = [ ("relu", {}, Activation), ("relu-n", {"max_value": 6.0}, ReLU), ("lrelu", {"alpha": 0.2}, LeakyReLU), ("elu", {"alpha": 1.0}, ELU), ] @pytest.mark.parametrize( "activation_type, activation_kwargs, expected_object_type", activation_test_cases ) def test_add_activation(activation_type, activation_kwargs, expected_object_type): """Test that add_activation returns correct object instances.""" activation_layer = utils.add_activation(activation_type, **activation_kwargs) assert isinstance(activation_layer, expected_object_type) test_cases = [(27, "ab"), (201, "gt"), (0, "a")] @pytest.mark.parametrize("key, expected_id", test_cases) def test_SUBBLOCK_IDS(key, expected_id): """Test SUBBLOCK_IDS to return expected ID string.""" subblock_ids = utils.SUBBLOCK_IDS() assert subblock_ids[key] == expected_id def test_update_regularizers(): """Test that update_regularizers works as advertised.""" shape = (32,) inputs = Input(shape=shape) outputs = Dense( units=32, kernel_regularizer=keras.regularizers.l2(1.0), bias_regularizer=keras.regularizers.l1(2.0), )(inputs) model = keras.models.Model(inputs=inputs, outputs=outputs) assert len(model.losses) == 2 updated_model = utils.update_regularizers( model, kernel_regularizer=None, bias_regularizer=None ) assert updated_model.losses == []
tao_tensorflow1_backend-main
nvidia_tao_tf1/core/models/templates/test_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. """Input layer for non-temporal models that receive a temporal input.""" import keras class NonTemporalInput(keras.layers.Layer): """ Non-temporal input module. This model is compatible with the modulus export facility that deals with the difference in model architecture between training and inference. """ def __init__(self, is_export_mode=False, **kwargs): """ Initialization. Args: is_export_mode (bool) Whether or not this layer should behave in single-frame inference mode (e.g. driveworks). """ super(NonTemporalInput, self).__init__(**kwargs) self.is_export_mode = is_export_mode def call(self, x): """ Call function. Composes this part of the graph. If this layer is in export mode, then it will simply forward the input. If it's in training mode, then the final value in the 2nd dimension of the tensor will be selected. Args: x (tf.Tensor): The input tensor. """ if self.is_export_mode: return x return x[:, -1] def compute_output_shape(self, input_shape): """ Computes the output shape given the specified input shape. The behavior changes between training and export mode. Args: input_shape (tf.TensorShape): The shape of the input tensor. """ if self.is_export_mode: return input_shape return input_shape[:1] + input_shape[2:] def prepare_for_export(self): """Configures this layer for export mode if this didn't already happen in the init.""" self.is_export_mode = True
tao_tensorflow1_backend-main
nvidia_tao_tf1/core/models/templates/non_temporal_input.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. """Quantize and De-Quantize layer for Keras.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import logging import keras.backend as K from keras.layers import Layer import tensorflow as tf from tensorflow.python.ops import init_ops from tensorflow.python.ops import math_ops from tensorflow.python.training import moving_averages logger = logging.getLogger(__name__) class QDQ(Layer): """Quantize and de-Quantize layer. This layer simulates the quantization of the output tensor of its input layer. This layer calculates the Exponential Moving Average (EMA) of the input tensor and use it as dynamic range for simulation of the quantization. # Arguments bitwidth: Quantization precision that this layer simulates. Default value is 8-bits. # Input shape Tensor with arbitrary shape: This layer reduces the entire tensor to min/max. So the input shape does not matter. # Output shape The same as input shape """ def __init__(self, bitwidth=8, **kwargs): """Construct the QDQ layer.""" super(QDQ, self).__init__(**kwargs) self.bitwidth = bitwidth def call(self, inputs): """Keras layer call.""" # Quantize the input. assert tf.is_tensor(inputs), "The input to QDQ layer should be a tensor." x = inputs keras_learning_phase = K.learning_phase() if tf.is_tensor(keras_learning_phase): keras_learning_phase = 0 logger.warning( "QDQ: Keras learning_phase was not set. Assuming evaluation phase." ) if keras_learning_phase: batch_min = math_ops.reduce_min(x, name="BatchMin") batch_min = math_ops.minimum(batch_min, 0.0) batch_max = math_ops.reduce_max(x, name="BatchMax") batch_max = math_ops.maximum(batch_max, 0.0) abs_max = math_ops.maximum( math_ops.abs(batch_min), math_ops.abs(batch_max), name="tensor_scale" ) assign_max = moving_averages.assign_moving_average( self.scaling_factor, abs_max, 0.999, name="AssignMaxEma" ) else: assign_max = self.scaling_factor assign_min = math_ops.negative(assign_max) assert assign_min.get_shape() == [], "Unexpected shape for tensor minimum." assert assign_max.get_shape() == [], "Unexpected shape for tensor maximum." x = tf.quantization.quantize_and_dequantize( input=x, input_min=assign_min, input_max=assign_max, range_given=True, signed_input=True, num_bits=self.bitwidth, ) return x def build(self, input_shape): """Keras layer build.""" self.scaling_factor = self.add_weight( shape=[], initializer=init_ops.constant_initializer(6.0), name="scaling_factor", trainable=False, ) self.built = True def get_config(self): """Get the layer configuration for QDQ layer.""" config = {"bitwidth": self.bitwidth} base_config = super(QDQ, self).get_config() return dict(list(base_config.items()) + list(config.items())) def compute_output_shape(self, input_shape): """Compute the output shape of QDQ layer.""" return input_shape
tao_tensorflow1_backend-main
nvidia_tao_tf1/core/models/templates/qdq_layer.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. """Convolutional RNN Layer.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import logging import keras import keras.backend import tensorflow as tf from nvidia_tao_tf1.blocks.multi_source_loader.data_format import ( CHANNELS_FIRST, DataFormat, ) from nvidia_tao_tf1.core.decorators.arg_scope import add_arg_scope logger = logging.getLogger(__name__) def duple(t): """Returns `t` if it's a tuple, otherwise returns (`t`, `t`).""" if isinstance(t, (list, tuple)): if len(t) == 1: return t + t assert len(t) == 2 return t return (t, t) class RNNConv2dBase(keras.layers.Layer): """Base implementation of a recurrent convolutional layer.""" @add_arg_scope def __init__( self, filters, kernel_size, num_backprop_timesteps=None, state_scaling=1.0, is_stateful=False, activation_type="relu", data_format=CHANNELS_FIRST, kernel_regularizer=None, bias_regularizer=None, space_time_kernel=False, seq_length_schedule=None, name=None, is_export_mode=False, **kwargs ): """ Standard constructor for recurrent convolutional layers. This module expects the input to be either (B*T, C, H, W) or (B*T, H, W, C) depending on the value of `data_format`. Args: filters (int): The number of convolutional filters to produce as the output. kernel_size (int, tuple): The spatial size of the input filters. NOTE: If `space_time_kernel` is true, then this also applies to the recurrent convolution. num_backprop_timesteps (int): The number of sequence frames to backprop through time. state_scaling (float): Explicitly scale the input recurrent activations from the previous time step. Must be 0 < `state_scaling` <= 1.0. is_stateful (bool): Controls whether history is preserved across batches during training. activation_type (str): Where applicable, specifies the activation type of the model. data_format (nvidia_tao_tf1.blocks.multi_source_loader.DataFormat): The format of the input tensors. Must be either CHANNELS_FIRST or CHANNELS_LAST. kernel_regularizer (`regularizer`): regularizer for the kernels. bias_regularizer (`regularizer`): regularizer for the biases. space_time_kernel (bool): Whether the convolution over time also includes a spatial component. If true, `kernel_size` is used for this convolution operation too. seq_length_schedule (None, int, list): Provides a schedule mechanism for controlling the number of time steps that are processing. If `None` (default), then all time steps will be processed every batch. If `int`, the processed sequence length will increase by 1 for each multiple of iterations of the specified value until the full input length is processed. For example, if `seq_length_schedule = 100` and the full sequence length is 5, then for the first 100 iterations, only the last input will be processed. From iteration 100-199, the last two inputs will be processed. By step 400, all inputs will be processed. If `list`, the number of inputs that will be processed is equal to the number of elements in the list that the current iteration is greater than, plus 1. name (str): The name of the layer. is_export_mode (bool): Whether or not this layer operates in stateful inference mode. """ super(RNNConv2dBase, self).__init__(name=name) self.num_backprop_timesteps = num_backprop_timesteps self.state_scaling = state_scaling if state_scaling <= 0.0 or state_scaling > 1.0: raise ValueError("State scaling must be in the range (0, 1]") self.is_stateful = is_stateful self.filters = filters self.kernel_size = duple(kernel_size) self._kernel_regularizer = kernel_regularizer self._bias_regularizer = bias_regularizer self._data_format = data_format self._inital_state = None self.n_input_shape = None self.state_shape = None self.is_space_time_kernel = space_time_kernel self.activation_type = activation_type self.seq_length_schedule = seq_length_schedule self.is_export_mode = is_export_mode def get_config(self): """Get layer's configuration. Returns: dict: The layer configuration. """ config = super(RNNConv2dBase, self).get_config() self.build_config(config) return config def build_config(self, config): """ Appends configuration parameters for keras serialization. Args: config (dict): Dictionary to append parameters to. """ config["num_backprop_timesteps"] = self.num_backprop_timesteps config["state_scaling"] = self.state_scaling config["is_stateful"] = self.is_stateful config["filters"] = self.filters config["kernel_size"] = self.kernel_size config["kernel_regularizer"] = self.kernel_regularizer config["bias_regularizer"] = self.bias_regularizer config["data_format"] = str(self._data_format) config["n_input_shape"] = self.n_input_shape config["is_space_time_kernel"] = self.is_space_time_kernel config["activation_type"] = self.activation_type config["seq_length_schedule"] = self.seq_length_schedule config["state_shape"] = self.state_shape @property def state_input_name(self): """The name of the input state layer.""" return self.name + "/state_input" def prepare_for_export(self): """Configures the layer for export mode.""" print("Preparing RNN for export!!!") self.is_export_mode = True self.is_stateful = True if not self.state_shape: raise ValueError( "The state shape has not been initialized. Has this layer ever " "been built?" ) self._initial_state = tf.compat.v1.placeholder( keras.backend.floatx(), shape=[1] + self.state_shape[1:], name="state_input" ) @property def data_format(self): """ Returns the data format for this layer. This is preferred over `self._data_format` because that value may occasionally be a string. This method always ensures that the returned value is a `DataFormat` object. """ if not isinstance(self._data_format, DataFormat): self._data_format = DataFormat(self._data_format) return self._data_format @property def bias_regularizer(self): """Returns the bias regularizer for this layer.""" if isinstance(self._bias_regularizer, dict): return None return self._bias_regularizer @property def kernel_regularizer(self): """Returns the kernel regularizer for this layer.""" if isinstance(self._kernel_regularizer, dict): return None return self._kernel_regularizer def build(self, input_shapes): """Initializes internal parameters given the shape of the inputs.""" input_shape = input_shapes[0] n_input_shape = self._get_normalized_size(input_shape) self.n_input_shape = n_input_shape self.state_shape = self._cvt_to_df( [1, self.filters, n_input_shape[2], n_input_shape[3]] ) self._inital_state = tf.zeros(self.state_shape, dtype=keras.backend.floatx()) if self.is_stateful and not self.is_export_mode: self._inital_state = tf.Variable(self._initial_state, trainable=False) if self.is_export_mode: self.prepare_for_export() else: self.rnn = keras.layers.Lambda(self._do_work, self._rnn_output_shape) super(RNNConv2dBase, self).build(input_shapes) def compute_output_shape(self, input_shapes): """Computes the output shape for this layer.""" logger.info("Input Shapes: {}".format(input_shapes)) output_shape = list(input_shapes[0]) if not self.is_export_mode: output_shape[0] = None logger.info("Output Shape: {}".format(output_shape)) return type(input_shapes[0])(output_shape) def call(self, args): """ Construct the graph. Args: args (tuple<tf.Tensor,tf.Tensor>): The input tensor and temporal length tensor. Returns: tf.Tensor: The output tensor. """ x, temporal_length = args if self.is_export_mode: return self.iteration(x, self._initial_state) if self.is_stateful: state = tf.identity(self._initial_state) else: state = tf.zeros(self.state_shape, dtype=keras.backend.floatx()) ex_counter = tf.compat.v1.train.get_or_create_global_step() state = self.rnn([state, x, temporal_length, ex_counter]) if self.is_stateful and not self.is_export_mode: state = tf.compat.v1.assign( ref=self._initial_state, value=state, validate_shape=False ) return state def _do_work(self, args): initial_state = args[0] x = args[1] temporal_length = args[2] ex_counter = args[3] input_shape = tf.shape(input=x) temporal_shape = [ input_shape[0] // temporal_length, temporal_length, input_shape[1], input_shape[2], input_shape[3], ] temporal_x = tf.reshape(x, temporal_shape) time_first_x = tf.transpose(a=temporal_x, perm=[1, 0, 2, 3, 4]) temporal_length_int64 = tf.cast(temporal_length, tf.int64) start_offset = self._get_step_offset(ex_counter, temporal_length_int64) def should_continue(t, *args): return start_offset + t < temporal_length_int64 def _iteration(t, inputs, state): step = start_offset + t instant_input = inputs[step] state = self.iteration(instant_input, state) if self.num_backprop_timesteps: cond = tf.math.equal( step, temporal_length_int64 - self.num_backprop_timesteps - 1 ) state = tf.cond( pred=cond, true_fn=lambda: tf.stop_gradient(state), false_fn=lambda: state, ) return t + 1, inputs, state initial_t = tf.Variable(0, dtype=tf.int64, trainable=False) invariant_state_shape = list(initial_state.get_shape()) invariant_state_shape[0] = None invariant_state_shape = tf.TensorShape(invariant_state_shape) _, _, state = tf.while_loop( cond=should_continue, body=_iteration, loop_vars=(initial_t, time_first_x, initial_state), back_prop=True, parallel_iterations=1, swap_memory=False, shape_invariants=( initial_t.get_shape(), time_first_x.get_shape(), invariant_state_shape, ), ) return state def iteration(self, x, state): """ Implements the recurrent activation on a single timestep. Args: x (tf.Tensor): The input tensor for the current timestep. state (tf.Tensor): The state of the recurrent module, up to the current timestep. Returns: state (tf.Tensor): The state of the recurrent module after processing this timestep. """ raise NotImplementedError("This method must be implemented by derived classes.") def _get_hidden_shape(self): st_shape = self.kernel_size if self.is_space_time_kernel else (1, 1) return [st_shape[0], st_shape[1], self.filters, self.filters] def _get_normalized_size(self, input_shape): return [ v.value if isinstance(v, tf.compat.v1.Dimension) else v for v in self.data_format.convert_shape(input_shape, CHANNELS_FIRST) ] def _cvt_to_df(self, n_input_shape): return CHANNELS_FIRST.convert_shape(n_input_shape, self.data_format) def _get_step_offset(self, ex_counter, temporal_length): if self.seq_length_schedule is None: return tf.constant(0, dtype=tf.int64) if isinstance(self.seq_length_schedule, int): return tf.maximum( temporal_length - ex_counter // self.seq_length_schedule - 1, 0 ) if isinstance(self.seq_length_schedule, (list, tuple)): tf_schedule = tf.constant(self.seq_length_schedule, tf.int64) gt_schedule = tf.cast(tf.greater_equal(ex_counter, tf_schedule), tf.int64) gt_count = tf.reduce_sum(input_tensor=gt_schedule) + 1 return tf.maximum(temporal_length - gt_count, 0) raise ValueError( "Unsupported sequence length schedule parameter. " "Expected (None, int, list). Got: {}".format(type(self.seq_length_schedule)) ) @staticmethod def _rnn_output_shape(input_shapes): return input_shapes[1] def _conv2d(self, x, W, strides=1, padding="same"): """Convenience wrapper around 2d convolution.""" return keras.backend.conv2d( x, W, strides=duple(strides), padding=padding, data_format=str(self.data_format), ) def _bias_add(self, x, b): """Convenience wrapper around B.bias_add.""" return x + b
tao_tensorflow1_backend-main
nvidia_tao_tf1/core/models/templates/rnn_conv2d_base.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. """Test convolutional gated recurrent unit (GRU) custom Keras layer TRT export""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import keras import numpy as np from nvidia_tao_tf1.core.models.templates.conv_gru_2d_export import ConvGRU2DExport from parameterized import parameterized import pytest import tensorflow as tf # cases for is_stateful, sequence_length_in_frames test_cases_1 = [[True, 1], [False, 2]] # cases for is_stateful, sequence_length_in_frames, state_scaling state_scaling_cases = [0.9, 1.0] test_cases_2 = [ test_cases_1[i] + [state_scaling_cases[i]] for i in range(len(test_cases_1)) ] # cases for is_stateful, sequence_length_in_frames, state_scaling, expected output expected_output_cases = [0.99482181, 0.98481372] test_cases_3 = [ test_cases_2[i] + [expected_output_cases[i]] for i in range(len(test_cases_2)) ] class TestConvGRU2DExport(tf.test.TestCase): """Test convolutional gated recurrent unit (GRU) custom Keras TRT-export layer.""" def setUp(self): """Set up the test fixture: construct a ConvGRU2DExport object.""" super(TestConvGRU2DExport, self).setUp() # Shape: [channels, height, width] self.GRU_INPUT_SHAPE = [None, 3, 1, 2] # Set the initial state shape. # Shape: [number_channels in a state, height, width] self.INITIAL_STATE_SHAPE = [None, 4, 1, 2] self.SPATIAL_KERNEL_HEIGHT = 1 self.SPATIAL_KERNEL_WIDTH = 1 self.KERNEL_REGULARIZER = { "class_name": "L1L2", "config": {"l2": 0.1, "l1": 0.3}, } self.BIAS_REGULARIZER = {"class_name": "L1L2", "config": {"l2": 0.0, "l1": 0.1}} @parameterized.expand(test_cases_2) def test_convgru2d_export( self, is_stateful, sequence_length_in_frames, state_scaling ): """Test if convgru2dexport layer parameters are initialized as expected values.""" convgru2d = ConvGRU2DExport( model_sequence_length_in_frames=sequence_length_in_frames, input_sequence_length_in_frames=sequence_length_in_frames, is_stateful=is_stateful, state_scaling=state_scaling, input_shape=self.GRU_INPUT_SHAPE, initial_state_shape=self.INITIAL_STATE_SHAPE, spatial_kernel_height=self.SPATIAL_KERNEL_HEIGHT, spatial_kernel_width=self.SPATIAL_KERNEL_WIDTH, kernel_regularizer=self.KERNEL_REGULARIZER, bias_regularizer=self.BIAS_REGULARIZER, ) input_shape_expected = self.GRU_INPUT_SHAPE model_sequence_length_in_frames_expected = sequence_length_in_frames input_sequence_length_in_frames_expected = sequence_length_in_frames state_scaling_expected = state_scaling is_stateful_expected = is_stateful # Set the initial state shape. # Shape: [number_channels in a state, height, width]. initial_state_shape_expected = self.INITIAL_STATE_SHAPE spatial_kernel_height_expected = self.SPATIAL_KERNEL_HEIGHT spatial_kernel_width_expected = self.SPATIAL_KERNEL_WIDTH kernel_regularizer = self.KERNEL_REGULARIZER bias_regularizer = self.BIAS_REGULARIZER assert input_shape_expected == convgru2d.rnn_input_shape # Test intitial state shape except the batch dimension. assert initial_state_shape_expected[1:] == convgru2d.initial_state_shape[1:] assert spatial_kernel_height_expected == convgru2d.spatial_kernel_height assert spatial_kernel_width_expected == convgru2d.spatial_kernel_width assert ( model_sequence_length_in_frames_expected == convgru2d.model_sequence_length_in_frames ) assert ( input_sequence_length_in_frames_expected == convgru2d.input_sequence_length_in_frames ) assert np.isclose(state_scaling_expected, convgru2d.state_scaling) assert is_stateful_expected == convgru2d.is_stateful assert kernel_regularizer["config"]["l1"] == convgru2d.kernel_regularizer.l1 assert kernel_regularizer["config"]["l2"] == convgru2d.kernel_regularizer.l2 assert bias_regularizer["config"]["l1"] == convgru2d.bias_regularizer.l1 assert bias_regularizer["config"]["l2"] == convgru2d.bias_regularizer.l2 @parameterized.expand(test_cases_2) def test_convgru2dexport_variables( self, is_stateful, sequence_length_in_frames, state_scaling ): """Test the trainable variables of the ConvGRU2DExport Layer. 1) Test if the trainable variables are built with the correct shapes and names. 2) Test if the number of trainable variables are correct. 3) Test if the output shape is set correctly while upon calling the layer. """ convgru2d = ConvGRU2DExport( model_sequence_length_in_frames=sequence_length_in_frames, input_sequence_length_in_frames=sequence_length_in_frames, is_stateful=is_stateful, state_scaling=state_scaling, input_shape=self.GRU_INPUT_SHAPE, initial_state_shape=self.INITIAL_STATE_SHAPE, spatial_kernel_height=self.SPATIAL_KERNEL_HEIGHT, spatial_kernel_width=self.SPATIAL_KERNEL_WIDTH, kernel_regularizer=self.KERNEL_REGULARIZER, bias_regularizer=self.BIAS_REGULARIZER, ) variable_names_expected = set( [ "conv_gru_2d_export/W_z:0", "conv_gru_2d_export/W_r:0", "conv_gru_2d_export/W_h:0", "conv_gru_2d_export/U_z:0", "conv_gru_2d_export/U_r:0", "conv_gru_2d_export/U_h:0", "conv_gru_2d_export/b_z:0", "conv_gru_2d_export/b_r:0", "conv_gru_2d_export/b_h:0", ] ) inputs = keras.Input( shape=( self.GRU_INPUT_SHAPE[1], self.GRU_INPUT_SHAPE[2], self.GRU_INPUT_SHAPE[3], ) ) output = convgru2d(inputs) # Check variable names. weights_actual = convgru2d.weights variable_names_actual = {weight.name for weight in weights_actual} assert variable_names_expected == variable_names_actual # Check the number of trainable variables. This should be 9: 3 x U_, 3 X W_ and 3 X bias. assert len(convgru2d.trainable_weights) == 9 # Check the shapes of input to state projections. # Shape [height, width, in_channels, out_channels]. var_shape_expected = [ self.SPATIAL_KERNEL_HEIGHT, self.SPATIAL_KERNEL_WIDTH, self.GRU_INPUT_SHAPE[1], self.INITIAL_STATE_SHAPE[1], ] for local_var_name in ["W_z", "W_r", "W_h"]: var_shape_actual = getattr(convgru2d, local_var_name).shape.as_list() assert var_shape_expected == var_shape_actual # Check the shapes of state to state projections. # Shape [height, width, in_channels, out_channels]. var_shape_expected = [ self.SPATIAL_KERNEL_HEIGHT, self.SPATIAL_KERNEL_WIDTH, self.INITIAL_STATE_SHAPE[1], self.INITIAL_STATE_SHAPE[1], ] for local_var_name in ["U_z", "U_r", "U_h"]: var_shape_actual = getattr(convgru2d, local_var_name).shape.as_list() assert var_shape_expected == var_shape_actual # Check the shapes of bias variables. # Shape [out_channels]. var_shape_expected = [self.INITIAL_STATE_SHAPE[1]] for local_var_name in ["b_z", "b_r", "b_h"]: var_shape_actual = getattr(convgru2d, local_var_name).shape.as_list() assert var_shape_expected == var_shape_actual # Check the output shape. [batch_size, num_filters, grid_height, grid_width]. output_shape_expected = [None] + list(self.INITIAL_STATE_SHAPE[1:]) assert output_shape_expected == output.shape.as_list() @parameterized.expand(test_cases_3) def test_convgru2d_output_values_single_step( self, is_stateful, sequence_length_in_frames, state_scaling, expected_output ): """Test the value of the output tensor after calling a single step ConvGRU2DExport Layer.""" # Set test case variables in the model self.MODEL_SEQUENCE_LENGTH_IN_FRAMES = sequence_length_in_frames self.INPUT_SEQUENCE_LENGTH_IN_FRAMES = sequence_length_in_frames with self.test_session() as sess: # A close-to-minimum sized GRU export. # This GRU will implement 1x1 operations on 2x2 grid. in-channels:1, out-channels:1 . convgru2d_minimal = ConvGRU2DExport( model_sequence_length_in_frames=self.MODEL_SEQUENCE_LENGTH_IN_FRAMES, input_sequence_length_in_frames=self.INPUT_SEQUENCE_LENGTH_IN_FRAMES, state_scaling=1.0, is_stateful=is_stateful, input_shape=[None, 1, 2, 2], initial_state_shape=[None, 1, 2, 2], spatial_kernel_height=1, spatial_kernel_width=1, ) inputs = keras.Input(shape=(1, 2, 2)) convgru2d_minimal(inputs) # Manually set the weights to specific values. value_for_projections_variables = np.ones([1, 1, 1, 1], dtype=np.float32) # Set the bias variable to zero first. value_for_bias_variables = np.zeros([1], dtype=np.float32) # Weights have 6 projection variables and 3 bias variables. convgru2d_minimal.set_weights( 6 * [value_for_projections_variables] + 3 * [value_for_bias_variables] ) # Present a ones input to the network. input_tensor = tf.constant(np.ones([1, 1, 2, 2], dtype=np.float32)) if is_stateful: # First, we keep the state for the previous time step at 0. state_input_tensor = np.zeros([1, 1, 2, 2], dtype=np.float32) feed_dict = {convgru2d_minimal._initial_state: state_input_tensor} else: # For stateless model, there is no initial state but there are feature maps # from previous frames stored in _past_features past_features_tensor = np.zeros([1, 1, 2, 2], dtype=np.float32) feed_dict = {} for i in range(self.INPUT_SEQUENCE_LENGTH_IN_FRAMES - 1): feed_dict[ convgru2d_minimal._past_features[i] ] = past_features_tensor # 1) For the case of stateful (i.e. is_stateful==True): # The below sub-session should compute the value of # the GRU-operations output after time-step. # z will be 1x1x2x2 tensor, each element will equal sigmoid(1). # r will be 1x1x2x2 tensor, each element will equal sigmoid(1). # state_update_input will be 1x1x2x2 tensor, each element will equal tanh(1). # Then the output will be z * state_update_input, # a 1x1x2x2 tensor, each element will equal sigmoid(1) * tanh(1) ~ 0.55677 . # # 2) For the case of stateless (i.e. is_stateful==False): # Because the past feature equals zero, the output state from the first iteration would # be zero. The second iteration will be the same as the stateful case, so the output # is the same as the stateful case. output_tensor = convgru2d_minimal(input_tensor) output_value = sess.run(output_tensor, feed_dict=feed_dict) np.testing.assert_array_almost_equal( 0.55677 * np.ones((1, 1, 2, 2)), output_value ) # Now everything is the same as previous test, but the bias values will be 1. value_for_bias_variables = np.ones([1], dtype=np.float32) if is_stateful: # In addition, state for the previous time step will be 1. as well. state_input_tensor = np.ones([1, 1, 2, 2], dtype=np.float32) feed_dict = {convgru2d_minimal._initial_state: state_input_tensor} else: # For stateless model, there is no initial state but there are feature maps # from previous frames stored in _past_features past_features_tensor = np.ones([1, 1, 2, 2], dtype=np.float32) feed_dict = {} for i in range(self.INPUT_SEQUENCE_LENGTH_IN_FRAMES - 1): feed_dict[ convgru2d_minimal._past_features[i] ] = past_features_tensor # Weights have 6 projection variables and 3 bias variables. convgru2d_minimal.set_weights( 6 * [value_for_projections_variables] + 3 * [value_for_bias_variables] ) # 1) For the case of stateful (i.e. is_stateful==True): # The below sub-session should compute the value of # the GRU-operations output after time-step. # z will be 1x1x2x2 tensor, each element will equal sigmoid(1+1+1). # r will be 1x1x2x2 tensor, each element will equal sigmoid(1+1+1). # state_update_input will be 1x1x2x2 tensor, each element will equal: # tanh(1+sigmoid(3)+1) ~ 0.994564 # Then the output will be z * state_update_input, # a 1x1x2x2 tensor, each element will equal: # ( (1-sigmoid(3)) * 1. + sigmoid(3) * 0.994564 ) # = ( (1-0.95257413) * 1.) + 0.95257413 * 0.994564 # ~ 0.99482181 . # # 2) For the case of stateless (i.e. is_stateful==False): # In the first iteration, # z will be 1x1x2x2 tensor, each element will equal sigmoid(1+1) # r will be 1x1x2x2 tensor, each element will equal sigmoid(1+1) # h will be 1x1x2x2 tensor, each element will equal tanh(1+1) # state will be 1x1x2x2 tensor, each element will equal: sigmoid(2) * tanh(2) # In the second iteration, # z will be 1x1x2x2 tensor, each element will equal sigmoid(1+state+1) # r will be 1x1x2x2 tensor, each element will equal sigmoid(1+state+1) # h will be 1x1x2x2 tensor, each element will equal tanh(1+state*sigmoid(2+state)+1) # final state will be 1x1x2x2 tensor, each element will equal: # sigmoid(2+state)*math.tanh(2+state*sigmoid(2+state))+(1-sigmoid(2+state))*state # ~ 0.98481372 . output_value = sess.run(output_tensor, feed_dict=feed_dict) np.testing.assert_array_almost_equal( expected_output * np.ones((1, 1, 2, 2)), output_value ) @parameterized.expand(test_cases_1) def test_convgru2d_export_model(self, is_stateful, sequence_length_in_frames): """Test if ConvGRU2D is constructed with is_export_model flag as expected. Resulting object must have is_export_model flag set as True. It should be stateful. Its initial state must have proper placeholder name. """ keras.backend.clear_session() # Construct the layer with is_export_model flag. convgru2d_exporting = ConvGRU2DExport( model_sequence_length_in_frames=sequence_length_in_frames, input_sequence_length_in_frames=sequence_length_in_frames, state_scaling=1.0, input_shape=[None, 1, 2, 2], initial_state_shape=[None, 1, 2, 2], spatial_kernel_height=1, spatial_kernel_width=1, is_stateful=is_stateful, ) inputs = keras.Input(shape=(1, 2, 2)) convgru2d_exporting(inputs) # Test the corresponding boolean members. assert convgru2d_exporting.is_stateful == is_stateful assert convgru2d_exporting.is_export_model # Test the name of the state input for the export model. assert ( convgru2d_exporting._initial_state.name == "conv_gru_2d_export/state_placeholder:0" ) assert ( len(convgru2d_exporting._past_features) == convgru2d_exporting.input_sequence_length_in_frames - 1 ) # This test is only used for stateful model @parameterized.expand([[True], [False]]) def test_convgru2d_export_model_violations(self, is_stateful): """Test if the expected AssertionErrors are raised when tyring to construct improperly. An AssertionError will be raised if the constructed arguments are not compatible with is_export_model flag. """ # Test that AssertionError is raised if model_sequence_lenght is not 1. with pytest.raises(AssertionError): ConvGRU2DExport( model_sequence_length_in_frames=2, input_sequence_length_in_frames=1, state_scaling=1.0, input_shape=[None, 1, 2, 2], initial_state_shape=[None, 1, 2, 2], spatial_kernel_height=1, spatial_kernel_width=1, is_stateful=is_stateful, ) # Test that AssertionError is raised if input_sequence_lenght is not 1. with pytest.raises(AssertionError): ConvGRU2DExport( model_sequence_length_in_frames=1, input_sequence_length_in_frames=2, state_scaling=1.0, input_shape=[None, 1, 2, 2], initial_state_shape=[None, 1, 2, 2], spatial_kernel_height=1, spatial_kernel_width=1, is_stateful=is_stateful, )
tao_tensorflow1_backend-main
nvidia_tao_tf1/core/models/templates/test_conv_gru_2d_export.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. from __future__ import absolute_import from __future__ import division from __future__ import print_function import keras from keras.models import Model from nvidia_tao_tf1.core.models.templates.inception_v2_block import InceptionV2Block from nvidia_tao_tf1.core.models.templates.utils import count_layers_by_class_name import pytest topologies = [ # Test with/without bias ([32, [32, 32], [32, 32, 32], 32], True, True, "channels_first", 29152), ([32, [32, 32], [32, 32, 32], 32], True, False, "channels_first", 28928), # Test with/without BN ([32, [32, 32], [32, 32, 32], 32], True, None, "channels_first", 28928), ([32, [32, 32], [32, 32, 32], 32], False, None, "channels_first", 28256), # Test channel_last ([32, [32, 32], [32, 32, 32], 32], True, False, "channels_last", 28928), # Test network structure ([1, [2, 3], [4, 5, 6], 118], True, True, "channels_first", 1574), ([1, [2, 3], [4, 5, 6], 118], True, False, "channels_last", 1435), ([1, [2, 3], [4, 5, 6], 118], False, False, "channels_first", 879), ([1, [2, 3], [4, 5, 6], 118], False, None, "channels_last", 1018), ] @pytest.mark.parametrize( "subblocks,use_batch_norm,use_bias," "data_format,expected_params", topologies ) def test_inception_v2_block( subblocks, use_batch_norm, use_bias, data_format, expected_params ): """Test Inception_v2_block for a variety of topologies and parameters.""" w, h = 48, 16 expected_num_channel = 128 if data_format == "channels_last": shape = (w, h, 3) elif data_format == "channels_first": shape = (3, w, h) inputs = keras.layers.Input(shape=shape) outputs = InceptionV2Block( use_batch_norm=use_batch_norm, use_bias=use_bias, data_format=data_format, subblocks=subblocks, )(inputs) # Check output shape output_shape = outputs.get_shape()[1:4] if data_format == "channels_last": expected_spatial_shape = (w, h, expected_num_channel) assert tuple(s.value for s in output_shape) == expected_spatial_shape elif data_format == "channels_first": expected_spatial_shape = (expected_num_channel, w, h) assert tuple(s.value for s in output_shape) == expected_spatial_shape model = Model(inputs=inputs, outputs=outputs, name="inceptionv2") # Batchnorm check n_batchnorms = count_layers_by_class_name(model, ["BatchNormalization"]) if use_batch_norm: assert n_batchnorms > 0 else: assert n_batchnorms == 0 for layer in model.layers: if isinstance(layer, keras.layers.Conv2D): # There should be no bias if use_bias is None, and batch norm is on. if use_bias is None: assert layer.get_config()["use_bias"] == (not use_batch_norm) else: assert layer.get_config()["use_bias"] == use_bias # Layer count check (just check the number of conv layers, not able to check # the number of branches.) n_layers_counted = count_layers_by_class_name(model, ["Conv2D"]) expected_nlayers = 7 # each inception v2 block should have 7 convolutional layers. assert n_layers_counted == expected_nlayers # Total model parameters check. assert model.count_params() == expected_params
tao_tensorflow1_backend-main
nvidia_tao_tf1/core/models/templates/test_inception_v2_block.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. """Convolutional RNN Layer.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import keras import numpy as np from nvidia_tao_tf1.core.models.templates.rnn_conv2d_base import RNNConv2dBase import tensorflow as tf class RNNConv2d(RNNConv2dBase): """Convolutional RNN Module.""" TYPE_NAME = "RNN" def _get_id_init(self): return "glorot_uniform" def build(self, input_shapes): """Builds the RNN module. NOTE: Subclasses can modify the initial recurrent matrix by overriding `_get_id_init`. """ input_shape = input_shapes[0] n_input_shape = self._get_normalized_size(input_shape) self.W_x = self.add_weight( name="W_x", shape=[ self.kernel_size[0], self.kernel_size[1], n_input_shape[1], self.filters, ], initializer="glorot_uniform", trainable=True, regularizer=self.kernel_regularizer, ) self.W_h = self.add_weight( name="W_h", shape=self._get_hidden_shape(), initializer=self._get_id_init(), trainable=True, regularizer=self.kernel_regularizer, ) self.bias = self.add_weight( name="bias", shape=self._cvt_to_df([1, self.filters, 1, 1]), initializer="zeros", trainable=True, regularizer=self.bias_regularizer, ) super(RNNConv2d, self).build(input_shapes) def iteration(self, x, state): """ Implements the recurrent activation on a single timestep. Args: x (tf.Tensor): The input tensor for the current timestep. state (tf.Tensor): The state of the recurrent module, up to the current timestep. Returns: state (tf.Tensor): The state of the recurrent module after processing this timestep. """ state = state * self.state_scaling z = self._conv2d(x, self.W_x) + self._conv2d(state, self.W_h) z = self._bias_add(z, self.bias) z = self._activation(z, name="state_output" if self.is_export_mode else None) state = z return state def _activation(self, inputs, name=None): return keras.layers.Activation(self.activation_type, name=name)(inputs) class IRNNConv2d(RNNConv2d): """Convolutional RNN module with identity initialization.""" TYPE_NAME = "IRNN" def _get_id_init(self): shape = self._get_hidden_shape() np_init = 0.01 * np.random.randn(*shape) c_y = shape[0] // 2 c_x = shape[1] // 2 np_init[c_y, c_x, :, :] += np.identity(self.filters) return tf.compat.v1.initializers.constant(value=np_init) def _activation(self, inputs, name=None): return tf.nn.relu(inputs, name=name)
tao_tensorflow1_backend-main
nvidia_tao_tf1/core/models/templates/rnn_conv2d.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. """Modulus model templates.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from keras.utils import get_custom_objects from nvidia_tao_tf1.core.models.templates import inception_v2_block from nvidia_tao_tf1.core.models.templates import utils from nvidia_tao_tf1.core.models.templates.qdq_layer import QDQ from nvidia_tao_tf1.core.models.templates.quantized_conv2d import QuantizedConv2D from nvidia_tao_tf1.core.models.templates.quantized_conv2dtranspose import QuantizedConv2DTranspose from nvidia_tao_tf1.core.models.templates.quantized_dense import QuantizedDense from nvidia_tao_tf1.core.models.templates.quantized_depthwiseconv2d import QuantizedDepthwiseConv2D __all__ = ("inception_v2_block", "utils") get_custom_objects()["QuantizedConv2D"] = QuantizedConv2D get_custom_objects()["QuantizedConv2DTranspose"] = QuantizedConv2DTranspose get_custom_objects()["QuantizedDepthwiseConv2D"] = QuantizedDepthwiseConv2D get_custom_objects()["QuantizedDense"] = QuantizedDense get_custom_objects()["QDQ"] = QDQ
tao_tensorflow1_backend-main
nvidia_tao_tf1/core/models/templates/__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. """Quantized Conv2DTranspose for Keras.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import logging import keras.backend as K from keras.layers import Conv2DTranspose import tensorflow as tf from tensorflow.python.keras.utils import conv_utils from tensorflow.python.ops import init_ops from tensorflow.python.ops import math_ops from tensorflow.python.training import moving_averages logger = logging.getLogger(__name__) class QuantizedConv2DTranspose(Conv2DTranspose): """Quantized transposed convolution layer. When using this layer as the first layer in a model, provide the keyword argument `input_shape` (tuple of integers, does not include the sample axis), e.g. `input_shape=(128, 128, 3)` for 128x128 RGB pictures in `data_format="channels_last"`. # Arguments filters: Integer, the dimensionality of the output space (i.e. the number of output filters in the convolution). kernel_size: An integer or tuple/list of 2 integers, specifying the height and width of the 2D convolution window. Can be a single integer to specify the same value for all spatial dimensions. strides: An integer or tuple/list of 2 integers, specifying the strides of the convolution along the height and width. Can be a single integer to specify the same value for all spatial dimensions. Specifying any stride value != 1 is incompatible with specifying any `dilation_rate` value != 1. padding: one of `"valid"` or `"same"` (case-insensitive). output_padding: An integer or tuple/list of 2 integers, specifying the amount of padding along the height and width of the output tensor. Can be a single integer to specify the same value for all spatial dimensions. The amount of output padding along a given dimension must be lower than the stride along that same dimension. If set to `None` (default), the output shape is inferred. data_format: A string, one of `"channels_last"` or `"channels_first"`. The ordering of the dimensions in the inputs. `"channels_last"` corresponds to inputs with shape `(batch, height, width, channels)` while `"channels_first"` corresponds to inputs with shape `(batch, channels, height, width)`. It defaults to the `image_data_format` value found in your Keras config file at `~/.keras/keras.json`. If you never set it, then it will be "channels_last". dilation_rate: an integer or tuple/list of 2 integers, specifying the dilation rate to use for dilated convolution. Can be a single integer to specify the same value for all spatial dimensions. Currently, specifying any `dilation_rate` value != 1 is incompatible with specifying any stride value != 1. activation: Activation function to use. If you don't specify anything, no activation is applied (ie. "linear" activation: `a(x) = x`). use_bias: Boolean, whether the layer uses a bias vector. kernel_initializer: Initializer for the `kernel` weights matrix. bias_initializer: Initializer for the bias vector. kernel_regularizer: Regularizer function applied to the `kernel` weights matrix. bias_regularizer: Regularizer function applied to the bias vector. activity_regularizer: Regularizer function applied to the output of the layer (its "activation"). kernel_constraint: Constraint function applied to the kernel matrix. bias_constraint: Constraint function applied to the bias vector. quantize: Quantize the input in addition to weights. bitwidth: Quantization precision. # Input shape 4D tensor with shape: `(batch, channels, rows, cols)` if `data_format` is `"channels_first"` or 4D tensor with shape: `(batch, rows, cols, channels)` if `data_format` is `"channels_last"`. # Output shape 4D tensor with shape: `(batch, filters, new_rows, new_cols)` if `data_format` is `"channels_first"` or 4D tensor with shape: `(batch, new_rows, new_cols, filters)` if `data_format` is `"channels_last"`. `rows` and `cols` values might have changed due to padding. If `output_padding` is specified: ``` new_rows = ((rows - 1) * strides[0] + kernel_size[0] - 2 * padding[0] + output_padding[0]) new_cols = ((cols - 1) * strides[1] + kernel_size[1] - 2 * padding[1] + output_padding[1]) """ def __init__( self, filters, kernel_size, strides=(1, 1), padding='valid', output_padding=None, data_format=None, dilation_rate=(1, 1), activation=None, use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, quantize=True, bitwidth=8, **kwargs ): """init function.""" super(QuantizedConv2DTranspose, self).__init__( filters, kernel_size, strides=strides, padding=padding, output_padding=output_padding, data_format=data_format, dilation_rate=dilation_rate, activation=activation, use_bias=use_bias, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, kernel_regularizer=kernel_regularizer, bias_regularizer=bias_regularizer, activity_regularizer=activity_regularizer, kernel_constraint=kernel_constraint, bias_constraint=bias_constraint, **kwargs) self.quantize_input = quantize self.bitwidth = bitwidth def build(self, input_shape): """Keras layer build.""" # The parent class build function should be called first so quantize input is weights[-1] super(QuantizedConv2DTranspose, self).build(input_shape) if self.quantize_input: self.scaling_factor = self.add_weight( shape=[], initializer=init_ops.constant_initializer(6.0), name="scaling_factor", trainable=False, ) else: self.scaling_factor = None def call(self, inputs): """call function to apply QAT.""" inputs_shape = K.shape(inputs) batch_size = inputs_shape[0] if self.data_format == 'channels_first': h_axis, w_axis = 2, 3 else: h_axis, w_axis = 1, 2 height, width = inputs_shape[h_axis], inputs_shape[w_axis] kernel_h, kernel_w = self.kernel_size stride_h, stride_w = self.strides if self.output_padding is None: out_pad_h = out_pad_w = None else: out_pad_h, out_pad_w = self.output_padding # Infer the dynamic output shape: out_height = conv_utils.deconv_output_length(height, kernel_h, padding=self.padding, output_padding=out_pad_h, stride=stride_h, dilation=self.dilation_rate[0]) out_width = conv_utils.deconv_output_length(width, kernel_w, padding=self.padding, output_padding=out_pad_w, stride=stride_w, dilation=self.dilation_rate[1]) if self.data_format == 'channels_first': output_shape = (batch_size, self.filters, out_height, out_width) else: output_shape = (batch_size, out_height, out_width, self.filters) if self.quantize_input: assert ( self.scaling_factor is not None ), "Quantization enabled but scaling factor parameter not defined." # Quantize the input. keras_learning_phase = K.learning_phase() if tf.is_tensor(keras_learning_phase): keras_learning_phase = 0 logger.warning( "QuantizedConv2DTranspose: Keras learning_phase not set. Assuming evaluation." ) if keras_learning_phase: batch_min = math_ops.reduce_min(inputs, name="BatchMin") batch_min = math_ops.minimum(batch_min, 0.0) batch_max = math_ops.reduce_max(inputs, name="BatchMax") batch_max = math_ops.maximum(batch_max, 0.0) abs_max = math_ops.maximum( math_ops.abs(batch_min), math_ops.abs(batch_max), name="tensor_scale" ) assign_max = moving_averages.assign_moving_average( self.scaling_factor, abs_max, 0.999, name="AssignMaxEma" ) else: assign_max = self.scaling_factor assign_min = math_ops.negative(assign_max) assert assign_min.get_shape() == [], "Unexpected shape for tensor minimum." assert assign_max.get_shape() == [], "Unexpected shape for tensor maximum." inputs = tf.quantization.quantize_and_dequantize( input=inputs, input_min=assign_min, input_max=assign_max, range_given=True, signed_input=True, num_bits=self.bitwidth, ) # Quantizing the weights. kernel = tf.quantization.quantize_and_dequantize( input=self.kernel, input_min=0.0, input_max=0.0, range_given=False, signed_input=True, num_bits=self.bitwidth, ) outputs = K.conv2d_transpose( inputs, kernel, output_shape, strides=self.strides, padding=self.padding, data_format=self.data_format, dilation_rate=self.dilation_rate) if self.use_bias: outputs = K.bias_add( outputs, self.bias, data_format=self.data_format) if self.activation is not None: return self.activation(outputs) return outputs def get_config(self): """get config function.""" config = super(QuantizedConv2DTranspose, self).get_config() config["quantize"] = self.quantize_input config["bitwidth"] = self.bitwidth return config
tao_tensorflow1_backend-main
nvidia_tao_tf1/core/models/templates/quantized_conv2dtranspose.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. """Quantized Dense Layer for Keras.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import logging import keras.backend as K from keras.layers import Dense import tensorflow as tf from tensorflow.python.ops import init_ops from tensorflow.python.ops import math_ops from tensorflow.python.training import moving_averages logger = logging.getLogger(__name__) class QuantizedDense(Dense): """Quantized Dense layer in Keras for QAT. # Arguments units: Positive integer, dimensionality of the output space. activation: Activation function to use (see [activations](../activations.md)). If you don't specify anything, no activation is applied (ie. "linear" activation: `a(x) = x`). use_bias: Boolean, whether the layer uses a bias vector. kernel_initializer: Initializer for the `kernel` weights matrix (see [initializers](../initializers.md)). bias_initializer: Initializer for the bias vector (see [initializers](../initializers.md)). kernel_regularizer: Regularizer function applied to the `kernel` weights matrix (see [regularizer](../regularizers.md)). bias_regularizer: Regularizer function applied to the bias vector (see [regularizer](../regularizers.md)). activity_regularizer: Regularizer function applied to the output of the layer (its "activation"). (see [regularizer](../regularizers.md)). kernel_constraint: Constraint function applied to the `kernel` weights matrix (see [constraints](../constraints.md)). bias_constraint: Constraint function applied to the bias vector (see [constraints](../constraints.md)). quantize: Quantize the input in addition to weights. bitwidth: Quantization precision. # Input shape nD tensor with shape: `(batch_size, ..., input_dim)`. The most common situation would be a 2D input with shape `(batch_size, input_dim)`. # Output shape nD tensor with shape: `(batch_size, ..., units)`. For instance, for a 2D input with shape `(batch_size, input_dim)`, the output would have shape `(batch_size, units)`. """ def __init__(self, units, activation=None, use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, quantize=True, bitwidth=8, **kwargs): """Initialize QuantizedDense layer.""" super(QuantizedDense, self).__init__( units, activation=activation, use_bias=use_bias, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, kernel_regularizer=kernel_regularizer, bias_regularizer=bias_regularizer, activity_regularizer=activity_regularizer, kernel_constraint=kernel_constraint, bias_constraint=bias_constraint, **kwargs ) self.quantize_input = quantize self.bitwidth = bitwidth def build(self, input_shape): # The parent class build function should be called first so quantize input is weights[-1] """Allocate weights, etc to build the layer.""" super(QuantizedDense, self).build(input_shape) if self.quantize_input: self.scaling_factor = self.add_weight( shape=[], initializer=init_ops.constant_initializer(6.0), name="scaling_factor", trainable=False, ) else: self.scaling_factor = None def call(self, inputs): """quantization and inner product.""" if self.quantize_input: assert ( self.scaling_factor is not None ), "Quantization enabled but scaling factor parameter not defined." # Quantize the input. keras_learning_phase = K.learning_phase() if tf.is_tensor(keras_learning_phase): keras_learning_phase = 0 logger.warning( "QuantizedDense: Keras learning_phase not set. Assuming evaluation." ) if keras_learning_phase: batch_min = math_ops.reduce_min(inputs, name="BatchMin") batch_min = math_ops.minimum(batch_min, 0.0) batch_max = math_ops.reduce_max(inputs, name="BatchMax") batch_max = math_ops.maximum(batch_max, 0.0) abs_max = math_ops.maximum( math_ops.abs(batch_min), math_ops.abs(batch_max), name="tensor_scale" ) assign_max = moving_averages.assign_moving_average( self.scaling_factor, abs_max, 0.999, name="AssignMaxEma" ) else: assign_max = self.scaling_factor assign_min = math_ops.negative(assign_max) assert assign_min.get_shape() == [], "Unexpected shape for tensor minimum." assert assign_max.get_shape() == [], "Unexpected shape for tensor maximum." inputs = tf.quantization.quantize_and_dequantize( input=inputs, input_min=assign_min, input_max=assign_max, range_given=True, signed_input=True, num_bits=self.bitwidth, ) # Quantizing the weights. kernel = tf.quantization.quantize_and_dequantize( input=self.kernel, input_min=0.0, input_max=0.0, range_given=False, signed_input=True, num_bits=self.bitwidth, ) output = K.dot(inputs, kernel) if self.use_bias: output = K.bias_add(output, self.bias, data_format='channels_last') if self.activation is not None: output = self.activation(output) return output def get_config(self): """Get the config dict.""" config = super(QuantizedDense, self).get_config() config["quantize"] = self.quantize_input config["bitwidth"] = self.bitwidth return config
tao_tensorflow1_backend-main
nvidia_tao_tf1/core/models/templates/quantized_dense.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. """Maglev utilities for model templates.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from nvidia_tao_tf1.core.decorators.arg_scope import add_arg_scope, arg_scope from nvidia_tao_tf1.core.models.templates.utils import conv2D_bn_activation if os.environ.get("TF_KERAS"): from tensorflow import keras else: import keras bn_axis_map = {"channels_last": 3, "channels_first": 1} SUBBLOCK_IDS = [ "br0_1x1", ["br1_1x1", "br1_3x3"], ["br2_1x1", "br2_3x3a", "br2_3x3b"], ["br3_1x1", "br3_pool"], ] class InceptionV2Block(object): """A functor for creating a Inception v2 module.""" @add_arg_scope def __init__( self, use_batch_norm=False, data_format=None, kernel_regularizer=None, bias_regularizer=None, use_bias=None, subblocks=None, block_name_prefix=None, icp_block_index=None, activation_type="relu", ): """ Initialization of the block functor object. Args: use_batch_norm (bool): whether batchnorm should be added after each convolution. data_format (str): either 'channels_last' (NHWC) or 'channels_first' (NCHW). kernel_regularizer (float): regularizer to apply to kernels. bias_regularizer (float): regularizer to apply to biases. subblocks (list): A list of list with size 4, defining number of feature-maps for subbblocks in an inception v2 block. This is a slightly modified version of Inception v2 module: "Rethinking the Inception Architecture for Computer Vision" by Szegedy, Christian, et. al. Inception_v2: [[32], [32, 32], [32, 32, 32], 32] Define Inception block with following parallel branches 1) 32 outputs from 1x1 convolutions 2.1) 32 outputs from 1x1 convolutions --> 2.2) 32 outputs from 3x3 convolutions 3.1) 32 outputs from 1x1 convolutions --> 3.2) 32 outputs from 3x3 convolutions --> 3.3) 32 outputs from 3x3 convolutions 4.1) 32 outputs from 1x1 convolutions --> 4.2) Average pooling with 3x3 pooling The fourth branch is slightly different from the original model. The original model is 3x3 max pooling followed by 1x1 convolution; whereas this implementation performs 1x1 convolution followed by 3x3 average pooling. This change speeds up the inference run-time performance. The outputs of 1, 2.2, 3.3, and 4.2 are concatenated to produce final output. block_name_prefix (str): name prefix for the whole block. icp_block_index (int): the index of the block to be created. activation_type (str): activation function type. """ self.use_batch_norm = use_batch_norm self.data_format = data_format self.kernel_regularizer = kernel_regularizer self.bias_regularizer = bias_regularizer if use_bias is None: self.use_bias = not (use_batch_norm) else: self.use_bias = use_bias self.activation_type = activation_type self.subblocks = subblocks self.icp_block_index = 0 if icp_block_index is None else icp_block_index self.block_name_prefix = "" if block_name_prefix is None else block_name_prefix self.name = "%sicp%d" % (self.block_name_prefix, self.icp_block_index) def __call__(self, x): """Build the block. Args: x (tensor): input tensor. Returns: tensor: the output tensor after applying the block on top of input `x`. """ x = self._subblocks(x, name_prefix=self.name) return x def _subblocks(self, x, name_prefix=None): """ Stack several convolutions in a specific sequence given by a list of subblocks. Args: x (tensor): the input tensor. name_prefix (str): name prefix for all the layers created in this function. Returns: tensor: the output tensor after applying the ResNet block on top of input `x`. """ nblocks = len(self.subblocks) if nblocks != 4: print("Inception V2 block must have 4 subblocks/paralle_branches") return x with arg_scope( [conv2D_bn_activation], use_batch_norm=self.use_batch_norm, data_format=self.data_format, kernel_regularizer=self.kernel_regularizer, bias_regularizer=self.bias_regularizer, use_bias=self.use_bias, ): # The first branch is 1x1 conv with padding = 0, stride = 1. x1 = conv2D_bn_activation( x, filters=self.subblocks[0], kernel_size=(1, 1), strides=(1, 1), layer_name="%s_%s" % (name_prefix, SUBBLOCK_IDS[0]), ) # The second branch is 1x1 conv with padding = 0, stride = 1. x2 = conv2D_bn_activation( x, filters=self.subblocks[1][0], kernel_size=(1, 1), strides=(1, 1), layer_name="%s_%s" % (name_prefix, SUBBLOCK_IDS[1][0]), ) # This second branch is 1x1 conv with padding = 0, stride = 1 followed by 3x3 conv. x2 = conv2D_bn_activation( x2, filters=self.subblocks[1][1], kernel_size=(3, 3), strides=(1, 1), layer_name="%s_%s" % (name_prefix, SUBBLOCK_IDS[1][1]), ) # The third branch is 1x1 conv with stride = 1. x3 = conv2D_bn_activation( x, filters=self.subblocks[2][0], kernel_size=(1, 1), strides=(1, 1), layer_name="%s_%s" % (name_prefix, SUBBLOCK_IDS[2][0]), ) # The third branch is 1x1 conv with padding = 0, stride = 1 followed by 3x3 conv. x3 = conv2D_bn_activation( x3, filters=self.subblocks[2][1], kernel_size=(3, 3), strides=(1, 1), layer_name="%s_%s" % (name_prefix, SUBBLOCK_IDS[2][1]), ) x3 = conv2D_bn_activation( x3, filters=self.subblocks[2][2], kernel_size=(3, 3), strides=(1, 1), layer_name="%s_%s" % (name_prefix, SUBBLOCK_IDS[2][2]), ) # The fourth branch is a 1x1 conv followed by a 3x3 average pool stride = 1. # This is different from the original paper. The 1x1 can be performed in parallel # at inference time for all 4 branches. x4 = conv2D_bn_activation( x, filters=self.subblocks[3], kernel_size=(1, 1), strides=(1, 1), layer_name="%s_%s" % (name_prefix, SUBBLOCK_IDS[3][0]), ) x4 = keras.layers.AveragePooling2D( pool_size=(3, 3), strides=(1, 1), padding="same", name="%s_%s" % (name_prefix, SUBBLOCK_IDS[3][1]), )(x4) # Concat layer. if self.data_format == "channels_first": x = keras.layers.Concatenate( axis=1, name="%s_concatenated" % (name_prefix) )([x1, x2, x3, x4]) else: x = keras.layers.Concatenate( axis=-1, name="%s_concatenated" % (name_prefix) )([x1, x2, x3, x4]) return x
tao_tensorflow1_backend-main
nvidia_tao_tf1/core/models/templates/inception_v2_block.py