repo
stringlengths
1
99
file
stringlengths
13
215
code
stringlengths
12
59.2M
file_length
int64
12
59.2M
avg_line_length
float64
3.82
1.48M
max_line_length
int64
12
2.51M
extension_type
stringclasses
1 value
models
models-master/official/modeling/optimization/lamb_test.py
# Copyright 2023 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. """Tests for LAMB Optimizer.""" import numpy as np from numpy import linalg import tensorflow as tf from official.modeling.optimization import lamb def lamb_update_numpy(param, g_t, t, m, v, lr=0.001, lamb_wd=0.0, beta1=0.9, beta2=0.999, epsilon=1e-6): m_t = beta1 * m + (1 - beta1) * g_t v_t = beta2 * v + (1 - beta2) * g_t * g_t m_t_hat = m_t / (1 - beta1**(t + 1)) v_t_hat = v_t / (1 - beta2**(t + 1)) update = m_t_hat / (np.sqrt(v_t_hat) + epsilon) update += lamb_wd * param w_norm = linalg.norm(param, ord=2) g_norm = linalg.norm(update, ord=2) ratio = np.where(w_norm > 0, np.where(g_norm > 0, (w_norm / g_norm), 1.0), 1.0) param_t = param - ratio * lr * update return param_t, m_t, v_t def get_beta_accumulators(opt, dtype): local_step = tf.cast(opt.iterations + 1, dtype) beta_1_t = tf.cast(opt._get_hyper("beta_1"), dtype) beta_1_power = tf.math.pow(beta_1_t, local_step) beta_2_t = tf.cast(opt._get_hyper("beta_2"), dtype) beta_2_power = tf.math.pow(beta_2_t, local_step) return (beta_1_power, beta_2_power) class LAMBTest(tf.test.TestCase): def test_sparse(self): dtype = tf.float32 # Initialize tf for numpy implementation. m0, v0, m1, v1 = 0.0, 0.0, 0.0, 0.0 var0_np = np.array([1.0, 1.0, 2.0], dtype=dtype.as_numpy_dtype) grads0_np = np.array([0.1, 0.0, 0.1], dtype=dtype.as_numpy_dtype) var1_np = np.array([3.0, 3.0, 4.0], dtype=dtype.as_numpy_dtype) grads1_np = np.array([0.01, 0.0, 0.01], dtype=dtype.as_numpy_dtype) var0 = tf.Variable(var0_np) var1 = tf.Variable(var1_np) grads0_np_indices = np.array([0, 2], dtype=np.int32) grads0 = tf.IndexedSlices( tf.constant(grads0_np[grads0_np_indices]), tf.constant(grads0_np_indices), tf.constant([3]), ) grads1_np_indices = np.array([0, 2], dtype=np.int32) grads1 = tf.IndexedSlices( tf.constant(grads1_np[grads1_np_indices]), tf.constant(grads1_np_indices), tf.constant([3]), ) opt = lamb.LAMB() # Fetch params to validate initial values np.testing.assert_allclose(np.asanyarray([1.0, 1.0, 2.0]), var0.numpy()) np.testing.assert_allclose(np.asanyarray([3.0, 3.0, 4.0]), var1.numpy()) # Run 3 steps of LAMB for t in range(3): beta_1_power, beta_2_power = get_beta_accumulators(opt, dtype) self.assertAllClose(0.9 ** (t + 1), beta_1_power) self.assertAllClose(0.999 ** (t + 1), beta_2_power) opt.apply_gradients(zip([grads0, grads1], [var0, var1])) var0_np, m0, v0 = lamb_update_numpy(var0_np, grads0_np, t, m0, v0) var1_np, m1, v1 = lamb_update_numpy(var1_np, grads1_np, t, m1, v1) # Validate updated params self.assertAllClose(var0_np, var0.numpy()) self.assertAllClose(var1_np, var1.numpy()) def test_basic_with_learning_rate_decay(self): dtype = tf.float32 # Initialize variables for numpy implementation. m0, v0, m1, v1 = 0.0, 0.0, 0.0, 0.0 var0_np = np.array([1.0, 2.0], dtype=dtype.as_numpy_dtype) grads0_np = np.array([0.1, 0.1], dtype=dtype.as_numpy_dtype) var1_np = np.array([3.0, 4.0], dtype=dtype.as_numpy_dtype) grads1_np = np.array([0.01, 0.01], dtype=dtype.as_numpy_dtype) var0 = tf.Variable(var0_np, name="var0") var1 = tf.Variable(var1_np, name="var1") grads0 = tf.constant(grads0_np) grads1 = tf.constant(grads1_np) learning_rate = 0.001 beta_1 = 0.9 beta_2 = 0.999 epsilon = 1e-7 decay = 0.5 lamb_wd = 0.01 opt = lamb.LAMB( learning_rate=learning_rate, beta_1=beta_1, beta_2=beta_2, epsilon=epsilon, weight_decay_rate=lamb_wd, decay=decay, ) # Run 3 steps of LAMB for t in range(3): opt.apply_gradients(zip([grads0, grads1], [var0, var1])) lr_np = learning_rate / (1 + decay * t) var0_np, m0, v0 = lamb_update_numpy( var0_np, grads0_np, t, m0, v0, lr=lr_np, lamb_wd=lamb_wd) var1_np, m1, v1 = lamb_update_numpy( var1_np, grads1_np, t, m1, v1, lr=lr_np, lamb_wd=lamb_wd) # Validate updated params self.assertAllClose(var0_np, var0.numpy()) self.assertAllClose(var1_np, var1.numpy()) def test_exclude_weight_decay(self): opt = lamb.LAMB( 0.01, weight_decay_rate=0.01, exclude_from_weight_decay=["var1"] ) assert opt._do_use_weight_decay("var0") assert not opt._do_use_weight_decay("var1") assert not opt._do_use_weight_decay("var1_weight") def test_exclude_layer_adaptation(self): opt = lamb.LAMB(0.01, exclude_from_layer_adaptation=["var1"]) assert opt._do_layer_adaptation("var0") assert not opt._do_layer_adaptation("var1") assert not opt._do_layer_adaptation("var1_weight") def test_serialization(self): optimizer = lamb.LAMB(1e-4) config = tf.keras.optimizers.serialize(optimizer, use_legacy_format=True) new_optimizer = tf.keras.optimizers.deserialize( config, use_legacy_format=True ) assert new_optimizer.get_config() == optimizer.get_config() if __name__ == "__main__": tf.test.main()
5,928
32.308989
77
py
models
models-master/official/modeling/optimization/optimizer_factory_test.py
# Copyright 2023 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. """Tests for optimizer_factory.py.""" from absl.testing import parameterized import numpy as np import tensorflow as tf from official.modeling.optimization import optimizer_factory from official.modeling.optimization.configs import optimization_config class OptimizerFactoryTest(tf.test.TestCase, parameterized.TestCase): @parameterized.parameters(('sgd'), ('rmsprop'), ('adam'), ('adamw'), ('lamb'), ('lars'), ('adagrad')) def test_optimizers(self, optimizer_type): params = { 'optimizer': { 'type': optimizer_type }, 'learning_rate': { 'type': 'constant', 'constant': { 'learning_rate': 0.1 } } } optimizer_cls = optimizer_factory.LEGACY_OPTIMIZERS_CLS[optimizer_type] expected_optimizer_config = optimizer_cls().get_config() expected_optimizer_config['learning_rate'] = 0.1 opt_config = optimization_config.OptimizationConfig(params) opt_factory = optimizer_factory.OptimizerFactory(opt_config) lr = opt_factory.build_learning_rate() optimizer = opt_factory.build_optimizer(lr, postprocessor=lambda x: x) self.assertIsInstance(optimizer, optimizer_cls) self.assertEqual(expected_optimizer_config, optimizer.get_config()) @parameterized.parameters(('sgd'), ('rmsprop'), ('adam'), ('adamw'), ('lamb'), ('lars'), ('adagrad')) def test_new_optimizers(self, optimizer_type): params = { 'optimizer': { 'type': optimizer_type }, 'learning_rate': { 'type': 'constant', 'constant': { 'learning_rate': 0.1 } } } optimizer_cls = optimizer_factory.NEW_OPTIMIZERS_CLS[optimizer_type] expected_optimizer_config = optimizer_cls().get_config() expected_optimizer_config['learning_rate'] = 0.1 opt_config = optimization_config.OptimizationConfig(params) if optimizer_type == 'sgd': # Delete unsupported arg `decay` from SGDConfig. delattr(opt_config.optimizer.sgd, 'decay') opt_factory = optimizer_factory.OptimizerFactory(opt_config) lr = opt_factory.build_learning_rate() optimizer = opt_factory.build_optimizer( lr, postprocessor=lambda x: x, use_legacy_optimizer=False) self.assertIsInstance(optimizer, optimizer_cls) self.assertEqual(expected_optimizer_config, optimizer.get_config()) def test_gradient_aggregator(self): params = { 'optimizer': { 'type': 'adam', }, 'learning_rate': { 'type': 'constant', 'constant': { 'learning_rate': 1.0 } } } opt_config = optimization_config.OptimizationConfig(params) opt_factory = optimizer_factory.OptimizerFactory(opt_config) lr = opt_factory.build_learning_rate() # Dummy function to zero out gradients. zero_grads = lambda gv: [(tf.zeros_like(g), v) for g, v in gv] optimizer = opt_factory.build_optimizer(lr, gradient_aggregator=zero_grads) if isinstance(optimizer, tf.keras.optimizers.experimental.Optimizer): self.skipTest('New Keras optimizer does not support ' '`gradient_aggregator` arg.') var0 = tf.Variable([1.0, 2.0]) var1 = tf.Variable([3.0, 4.0]) grads0 = tf.constant([1.0, 1.0]) grads1 = tf.constant([1.0, 1.0]) grads_and_vars = list(zip([grads0, grads1], [var0, var1])) optimizer.apply_gradients(grads_and_vars) self.assertAllClose(np.array([1.0, 2.0]), var0.numpy()) self.assertAllClose(np.array([3.0, 4.0]), var1.numpy()) @parameterized.parameters((None, None), (1.0, None), (None, 1.0)) def test_gradient_clipping(self, clipnorm, clipvalue): params = { 'optimizer': { 'type': 'sgd', 'sgd': { 'clipnorm': clipnorm, 'clipvalue': clipvalue } }, 'learning_rate': { 'type': 'constant', 'constant': { 'learning_rate': 1.0 } } } opt_config = optimization_config.OptimizationConfig(params) opt_factory = optimizer_factory.OptimizerFactory(opt_config) lr = opt_factory.build_learning_rate() optimizer = opt_factory.build_optimizer(lr) var0 = tf.Variable([1.0, 2.0]) var1 = tf.Variable([3.0, 4.0]) grads0 = tf.constant([0.1, 0.1]) grads1 = tf.constant([2.0, 3.0]) grads_and_vars = list(zip([grads0, grads1], [var0, var1])) optimizer.apply_gradients(grads_and_vars) self.assertAllClose(np.array([0.9, 1.9]), var0.numpy()) if clipvalue is not None: self.assertAllClose(np.array([2.0, 3.0]), var1.numpy()) elif clipnorm is not None: self.assertAllClose(np.array([2.4452999, 3.1679497]), var1.numpy()) else: self.assertAllClose(np.array([1.0, 1.0]), var1.numpy()) def test_missing_types(self): params = {'optimizer': {'type': 'sgd', 'sgd': {'momentum': 0.9}}} with self.assertRaises(ValueError): optimizer_factory.OptimizerFactory( optimization_config.OptimizationConfig(params)) params = { 'learning_rate': { 'type': 'stepwise', 'stepwise': { 'boundaries': [10000, 20000], 'values': [0.1, 0.01, 0.001] } } } with self.assertRaises(ValueError): optimizer_factory.OptimizerFactory( optimization_config.OptimizationConfig(params)) def test_wrong_return_type(self): optimizer_type = 'sgd' params = { 'optimizer': { 'type': optimizer_type }, 'learning_rate': { 'type': 'constant', 'constant': { 'learning_rate': 0.1 } } } opt_config = optimization_config.OptimizationConfig(params) opt_factory = optimizer_factory.OptimizerFactory(opt_config) with self.assertRaises(TypeError): _ = opt_factory.build_optimizer(0.1, postprocessor=lambda x: None) # TODO(b/187559334) refactor lr_schedule tests into `lr_schedule_test.py`. def test_stepwise_lr_schedule(self): params = { 'optimizer': { 'type': 'sgd', 'sgd': { 'momentum': 0.9 } }, 'learning_rate': { 'type': 'stepwise', 'stepwise': { 'boundaries': [10000, 20000], 'values': [0.1, 0.01, 0.001] } } } expected_lr_step_values = [[0, 0.1], [5000, 0.1], [10000, 0.1], [10001, 0.01], [20000, 0.01], [20001, 0.001]] opt_config = optimization_config.OptimizationConfig(params) opt_factory = optimizer_factory.OptimizerFactory(opt_config) lr = opt_factory.build_learning_rate() for step, value in expected_lr_step_values: self.assertAlmostEqual(lr(step).numpy(), value) def test_stepwise_lr_with_warmup_schedule(self): params = { 'optimizer': { 'type': 'sgd', 'sgd': { 'momentum': 0.9 } }, 'learning_rate': { 'type': 'stepwise', 'stepwise': { 'boundaries': [10000, 20000], 'values': [0.1, 0.01, 0.001] } }, 'warmup': { 'type': 'linear', 'linear': { 'warmup_steps': 500, 'warmup_learning_rate': 0.01 } } } expected_lr_step_values = [[0, 0.01], [250, 0.055], [500, 0.1], [5500, 0.1], [10000, 0.1], [10001, 0.01], [20000, 0.01], [20001, 0.001]] opt_config = optimization_config.OptimizationConfig(params) opt_factory = optimizer_factory.OptimizerFactory(opt_config) lr = opt_factory.build_learning_rate() for step, value in expected_lr_step_values: self.assertAlmostEqual(lr(step).numpy(), value) def test_exponential_lr_schedule(self): params = { 'optimizer': { 'type': 'sgd', 'sgd': { 'momentum': 0.9 } }, 'learning_rate': { 'type': 'exponential', 'exponential': { 'initial_learning_rate': 0.1, 'decay_steps': 1000, 'decay_rate': 0.96, 'staircase': True } } } expected_lr_step_values = [ [0, 0.1], [999, 0.1], [1000, 0.096], [1999, 0.096], [2000, 0.09216], ] opt_config = optimization_config.OptimizationConfig(params) opt_factory = optimizer_factory.OptimizerFactory(opt_config) lr = opt_factory.build_learning_rate() for step, value in expected_lr_step_values: self.assertAlmostEqual(lr(step).numpy(), value) def test_polynomial_lr_schedule(self): params = { 'optimizer': { 'type': 'sgd', 'sgd': { 'momentum': 0.9 } }, 'learning_rate': { 'type': 'polynomial', 'polynomial': { 'initial_learning_rate': 0.1, 'decay_steps': 1000, 'end_learning_rate': 0.001 } } } expected_lr_step_values = [[0, 0.1], [500, 0.0505], [1000, 0.001]] opt_config = optimization_config.OptimizationConfig(params) opt_factory = optimizer_factory.OptimizerFactory(opt_config) lr = opt_factory.build_learning_rate() for step, value in expected_lr_step_values: self.assertAlmostEqual(lr(step).numpy(), value) def test_cosine_lr_schedule(self): params = { 'optimizer': { 'type': 'sgd', 'sgd': { 'momentum': 0.9 } }, 'learning_rate': { 'type': 'cosine', 'cosine': { 'initial_learning_rate': 0.1, 'decay_steps': 1000 } } } expected_lr_step_values = [[0, 0.1], [250, 0.08535534], [500, 0.04999999], [750, 0.01464466], [1000, 0]] opt_config = optimization_config.OptimizationConfig(params) opt_factory = optimizer_factory.OptimizerFactory(opt_config) lr = opt_factory.build_learning_rate() for step, value in expected_lr_step_values: self.assertAlmostEqual(lr(step).numpy(), value) def test_constant_lr_with_warmup_schedule(self): params = { 'optimizer': { 'type': 'sgd', 'sgd': { 'momentum': 0.9 } }, 'learning_rate': { 'type': 'constant', 'constant': { 'learning_rate': 0.1 } }, 'warmup': { 'type': 'linear', 'linear': { 'warmup_steps': 500, 'warmup_learning_rate': 0.01 } } } expected_lr_step_values = [[0, 0.01], [250, 0.055], [500, 0.1], [5000, 0.1], [10000, 0.1], [20000, 0.1]] opt_config = optimization_config.OptimizationConfig(params) opt_factory = optimizer_factory.OptimizerFactory(opt_config) lr = opt_factory.build_learning_rate() for step, value in expected_lr_step_values: self.assertAlmostEqual(lr(step).numpy(), value) def test_stepwise_lr_with_polynomial_warmup_schedule(self): params = { 'optimizer': { 'type': 'sgd', 'sgd': { 'momentum': 0.9 } }, 'learning_rate': { 'type': 'stepwise', 'stepwise': { 'boundaries': [10000, 20000], 'values': [0.1, 0.01, 0.001] } }, 'warmup': { 'type': 'polynomial', 'polynomial': { 'warmup_steps': 500, 'power': 2. } } } expected_lr_step_values = [[0, 0.0], [250, 0.025], [500, 0.1], [5500, 0.1], [10000, 0.1], [10001, 0.01], [20000, 0.01], [20001, 0.001]] opt_config = optimization_config.OptimizationConfig(params) opt_factory = optimizer_factory.OptimizerFactory(opt_config) lr = opt_factory.build_learning_rate() for step, value in expected_lr_step_values: self.assertAlmostEqual(lr(step).numpy(), value, places=6) def test_power_lr_schedule(self): params = { 'optimizer': { 'type': 'sgd', 'sgd': { 'momentum': 0.9 } }, 'learning_rate': { 'type': 'power', 'power': { 'initial_learning_rate': 1.0, 'power': -1.0 } } } expected_lr_step_values = [[0, 1.0], [1, 1.0], [250, 1. / 250.]] opt_config = optimization_config.OptimizationConfig(params) opt_factory = optimizer_factory.OptimizerFactory(opt_config) lr = opt_factory.build_learning_rate() for step, value in expected_lr_step_values: self.assertAlmostEqual(lr(step).numpy(), value) def test_power_linear_lr_schedule(self): params = { 'optimizer': { 'type': 'sgd', 'sgd': { 'momentum': 0.9 } }, 'learning_rate': { 'type': 'power_linear', 'power_linear': { 'initial_learning_rate': 1.0, 'power': -1.0, 'linear_decay_fraction': 0.5, 'total_decay_steps': 100, 'offset': 0, } } } expected_lr_step_values = [[0, 1.0], [1, 1.0], [40, 1. / 40.], [60, 1. / 60. * 0.8]] opt_config = optimization_config.OptimizationConfig(params) opt_factory = optimizer_factory.OptimizerFactory(opt_config) lr = opt_factory.build_learning_rate() for step, value in expected_lr_step_values: self.assertAlmostEqual(lr(step).numpy(), value) def test_power_with_offset_lr_schedule(self): params = { 'optimizer': { 'type': 'sgd', 'sgd': { 'momentum': 0.9 } }, 'learning_rate': { 'type': 'power_with_offset', 'power_with_offset': { 'initial_learning_rate': 1.0, 'power': -1.0, 'offset': 10, 'pre_offset_learning_rate': 3.0, } } } expected_lr_step_values = [[1, 3.0], [10, 3.0], [20, 1. / 10.]] opt_config = optimization_config.OptimizationConfig(params) opt_factory = optimizer_factory.OptimizerFactory(opt_config) lr = opt_factory.build_learning_rate() for step, value in expected_lr_step_values: self.assertAlmostEqual(lr(step).numpy(), value) def test_step_cosine_lr_schedule_with_warmup(self): params = { 'optimizer': { 'type': 'sgd', 'sgd': { 'momentum': 0.9 } }, 'learning_rate': { 'type': 'step_cosine_with_offset', 'step_cosine_with_offset': { 'values': (0.0001, 0.00005), 'boundaries': (0, 500000), 'offset': 10000, } }, 'warmup': { 'type': 'linear', 'linear': { 'warmup_steps': 10000, 'warmup_learning_rate': 0.0 } } } expected_lr_step_values = [[0, 0.0], [5000, 1e-4 / 2.0], [10000, 1e-4], [20000, 9.994863e-05], [499999, 5e-05]] opt_config = optimization_config.OptimizationConfig(params) opt_factory = optimizer_factory.OptimizerFactory(opt_config) lr = opt_factory.build_learning_rate() for step, value in expected_lr_step_values: self.assertAlmostEqual(lr(step).numpy(), value) class OptimizerFactoryRegistryTest(tf.test.TestCase): def test_registry(self): class MyClass(): pass optimizer_factory.register_optimizer_cls('test', MyClass) self.assertIn('test', optimizer_factory.LEGACY_OPTIMIZERS_CLS) with self.assertRaisesRegex(ValueError, 'test already registered.*'): optimizer_factory.register_optimizer_cls('test', MyClass) if __name__ == '__main__': tf.test.main()
17,015
31.045198
80
py
models
models-master/official/modeling/optimization/legacy_adamw.py
# Copyright 2023 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. """Adam optimizer with weight decay that exactly matches the original BERT.""" import re from absl import logging import tensorflow as tf class AdamWeightDecay(tf.keras.optimizers.legacy.Adam): """Adam enables L2 weight decay and clip_by_global_norm on gradients. [Warning!]: Keras optimizer supports gradient clipping and has an AdamW implementation. Please consider evaluating the choice in Keras package. Just adding the square of the weights to the loss function is *not* the correct way of using L2 regularization/weight decay with Adam, since that will interact with the m and v parameters in strange ways. Instead we want to decay the weights in a manner that doesn't interact with the m/v parameters. This is equivalent to adding the square of the weights to the loss with plain (non-momentum) SGD. """ def __init__(self, learning_rate=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-7, amsgrad=False, weight_decay_rate=0.0, include_in_weight_decay=None, exclude_from_weight_decay=None, gradient_clip_norm=1.0, name='AdamWeightDecay', **kwargs): super(AdamWeightDecay, self).__init__(learning_rate, beta_1, beta_2, epsilon, amsgrad, name, **kwargs) self.weight_decay_rate = weight_decay_rate self.gradient_clip_norm = gradient_clip_norm self._include_in_weight_decay = include_in_weight_decay self._exclude_from_weight_decay = exclude_from_weight_decay logging.info('AdamWeightDecay gradient_clip_norm=%f', gradient_clip_norm) def _prepare_local(self, var_device, var_dtype, apply_state): super(AdamWeightDecay, self)._prepare_local(var_device, var_dtype, # pytype: disable=attribute-error # typed-keras apply_state) apply_state[(var_device, var_dtype)]['weight_decay_rate'] = tf.constant( self.weight_decay_rate, name='adam_weight_decay_rate') def _decay_weights_op(self, var, learning_rate, apply_state): do_decay = self._do_use_weight_decay(var.name) if do_decay: return var.assign_sub( learning_rate * var * apply_state[(var.device, var.dtype.base_dtype)]['weight_decay_rate'], use_locking=self._use_locking) return tf.no_op() def apply_gradients(self, grads_and_vars, name=None, experimental_aggregate_gradients=True): grads, tvars = list(zip(*grads_and_vars)) if experimental_aggregate_gradients and self.gradient_clip_norm > 0.0: # when experimental_aggregate_gradients = False, apply_gradients() no # longer implicitly allreduce gradients, users manually allreduce gradient # and passed the allreduced grads_and_vars. For now, the # clip_by_global_norm will be moved to before the explicit allreduce to # keep the math the same as TF 1 and pre TF 2.2 implementation. (grads, _) = tf.clip_by_global_norm( grads, clip_norm=self.gradient_clip_norm) return super(AdamWeightDecay, self).apply_gradients( zip(grads, tvars), name=name, experimental_aggregate_gradients=experimental_aggregate_gradients) def _get_lr(self, var_device, var_dtype, apply_state): """Retrieves the learning rate with the given state.""" if apply_state is None: return self._decayed_lr_t[var_dtype], {} apply_state = apply_state or {} coefficients = apply_state.get((var_device, var_dtype)) if coefficients is None: coefficients = self._fallback_apply_state(var_device, var_dtype) apply_state[(var_device, var_dtype)] = coefficients return coefficients['lr_t'], dict(apply_state=apply_state) def _resource_apply_dense(self, grad, var, apply_state=None): lr_t, kwargs = self._get_lr(var.device, var.dtype.base_dtype, apply_state) decay = self._decay_weights_op(var, lr_t, apply_state) with tf.control_dependencies([decay]): return super(AdamWeightDecay, self)._resource_apply_dense(grad, var, **kwargs) # pytype: disable=attribute-error # typed-keras def _resource_apply_sparse(self, grad, var, indices, apply_state=None): lr_t, kwargs = self._get_lr(var.device, var.dtype.base_dtype, apply_state) decay = self._decay_weights_op(var, lr_t, apply_state) with tf.control_dependencies([decay]): return super(AdamWeightDecay, self)._resource_apply_sparse(grad, var, indices, **kwargs) # pytype: disable=attribute-error # typed-keras def get_config(self): config = super(AdamWeightDecay, self).get_config() config.update({ 'weight_decay_rate': self.weight_decay_rate, }) return config def _do_use_weight_decay(self, param_name): """Whether to use L2 weight decay for `param_name`.""" if self.weight_decay_rate == 0: return False if self._include_in_weight_decay: for r in self._include_in_weight_decay: if re.search(r, param_name) is not None: return True if self._exclude_from_weight_decay: for r in self._exclude_from_weight_decay: if re.search(r, param_name) is not None: return False return True
5,953
41.528571
127
py
models
models-master/official/modeling/optimization/lr_schedule.py
# Copyright 2023 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. """Learning rate schedule classes.""" import math from typing import Mapping, Any, Union, Optional import tensorflow as tf def _make_offset_wrapper(new_class_name: str, base_lr_class): """Generates a offset wrapper of learning rate schedule. It will returns a subclass of the `base_lr_class`, the subclass takes an `offset` argument in the constructor. When the new class instance is called, the behavior is: new_class_object(step) = base_lr_class_object(step - offset) Example: CosineDecayWithOffset = _make_offset_wrapper( 'CosineDecayWithOffset', tf.keras.experimental.CosineDecay) # Use the lr: lr = CosineDecayWithOffset(offset=100, initial_learning_rate=0.1, decay_steps=1000) lr(101) # equals to tf.keras.experimental.CosineDecay(...)(101-100) Args: new_class_name: the name of the new class. base_lr_class: the base learning rate schedule class. Should be subclass of tf.keras.optimizers.schedules.LearningRateSchedule Returns: A new class (subclass of the base_lr_class) that can take an offset. """ assert issubclass(base_lr_class, tf.keras.optimizers.schedules.LearningRateSchedule), ( "base_lr_class should be subclass of keras " f"LearningRateSchedule, got {base_lr_class}") # pylint: disable=protected-access,pointless-statement def offset_learning_rate_init(self, offset=0, **kwargs): """Construct learning rate schedule object. When this object is called, its behavior is self.__call__(step) == base_lr_class.__call__(step - offset) Args: self: this object. offset: The offset when computing the learning rate schedule. **kwargs: Pass through to base learning rate class constructor. """ base_lr_class.__init__(self, **kwargs) self._offset = offset def offset_learning_rate_call(self, step): step = tf.cast(step - self._offset, tf.float32) return base_lr_class.__call__(self, step) # pylint: enable=protected-access,pointless-statement return type( new_class_name, (base_lr_class,), { "base_lr_class": base_lr_class, "__init__": offset_learning_rate_init, "__call__": offset_learning_rate_call }) PiecewiseConstantDecayWithOffset = _make_offset_wrapper( "PiecewiseConstantDecayWithOffset", tf.keras.optimizers.schedules.PiecewiseConstantDecay) PolynomialDecayWithOffset = _make_offset_wrapper( "PolynomialDecayWithOffset", tf.keras.optimizers.schedules.PolynomialDecay) ExponentialDecayWithOffset = _make_offset_wrapper( "ExponentialDecayWithOffset", tf.keras.optimizers.schedules.ExponentialDecay) CosineDecayWithOffset = _make_offset_wrapper("CosineDecayWithOffset", tf.keras.experimental.CosineDecay) class LinearWarmup(tf.keras.optimizers.schedules.LearningRateSchedule): """Linear warmup schedule.""" def __init__(self, after_warmup_lr_sched: Union[ tf.keras.optimizers.schedules.LearningRateSchedule, float], warmup_steps: int, warmup_learning_rate: float, name: Optional[str] = None): """Add linear warmup schedule to a learning rate schedule. warmup_lr is the initial learning rate, the final learning rate of the init_warmup period is the initial learning rate of lr_schedule in use. The learning rate at each step linearly increased according to the following formula: learning_rate = warmup_lr + step / warmup_steps * (final_warmup_lr - warmup_lr). Using warmup overrides the learning rate schedule by the number of warmup steps. Args: after_warmup_lr_sched: tf.keras.optimizers.schedules .LearningRateSchedule or a constant. warmup_steps: Number of the warmup steps. warmup_learning_rate: Initial learning rate for the warmup. name: Optional, name of warmup schedule. """ super().__init__() self._name = name self._after_warmup_lr_sched = after_warmup_lr_sched self._warmup_steps = warmup_steps self._init_warmup_lr = warmup_learning_rate if isinstance(after_warmup_lr_sched, tf.keras.optimizers.schedules.LearningRateSchedule): self._final_warmup_lr = after_warmup_lr_sched(warmup_steps) else: self._final_warmup_lr = tf.cast(after_warmup_lr_sched, dtype=tf.float32) def __call__(self, step: int): global_step = tf.cast(step, dtype=tf.float32) linear_warmup_lr = ( self._init_warmup_lr + global_step / self._warmup_steps * (self._final_warmup_lr - self._init_warmup_lr)) if isinstance(self._after_warmup_lr_sched, tf.keras.optimizers.schedules.LearningRateSchedule): after_warmup_lr = self._after_warmup_lr_sched(step) else: after_warmup_lr = tf.cast(self._after_warmup_lr_sched, dtype=tf.float32) lr = tf.cond(global_step < self._warmup_steps, lambda: linear_warmup_lr, lambda: after_warmup_lr) return lr def get_config(self) -> Mapping[str, Any]: if isinstance(self._after_warmup_lr_sched, tf.keras.optimizers.schedules.LearningRateSchedule): config = { "after_warmup_lr_sched": self._after_warmup_lr_sched.get_config()} # pytype: disable=attribute-error else: config = {"after_warmup_lr_sched": self._after_warmup_lr_sched} # pytype: disable=attribute-error config.update({ "warmup_steps": self._warmup_steps, "warmup_learning_rate": self._init_warmup_lr, "name": self._name }) return config class PolynomialWarmUp(tf.keras.optimizers.schedules.LearningRateSchedule): """Applies polynomial warmup schedule on a given learning rate decay schedule.""" def __init__(self, after_warmup_lr_sched: Union[ tf.keras.optimizers.schedules.LearningRateSchedule, float], warmup_steps: int, power: float = 1.0, name: str = "PolynomialWarmup"): super().__init__() if isinstance(after_warmup_lr_sched, tf.keras.optimizers.schedules.LearningRateSchedule): self._initial_learning_rate = after_warmup_lr_sched(warmup_steps) else: self._initial_learning_rate = tf.cast( after_warmup_lr_sched, dtype=tf.float32) self._warmup_steps = warmup_steps self._power = power self._after_warmup_lr_sched = after_warmup_lr_sched self._name = name def __call__(self, step): with tf.name_scope(self._name or "PolynomialWarmUp") as name: # Implements polynomial warmup. i.e., if global_step < warmup_steps, the # learning rate will be `global_step/num_warmup_steps * init_lr`. global_step_float = tf.cast(step, tf.float32) warmup_steps_float = tf.cast(self._warmup_steps, tf.float32) if self._warmup_steps <= 0: warmup_percent_done = 1.0 else: # A zero `step` may cause Inf. So make `step` positive. step_non_zero = tf.math.maximum(global_step_float, 1.0) warmup_percent_done = step_non_zero / warmup_steps_float warmup_learning_rate = ( self._initial_learning_rate * tf.math.pow(warmup_percent_done, self._power)) if isinstance(self._after_warmup_lr_sched, tf.keras.optimizers.schedules.LearningRateSchedule): after_warmup_lr = self._after_warmup_lr_sched(step) else: after_warmup_lr = tf.cast(self._after_warmup_lr_sched, dtype=tf.float32) return tf.cond( global_step_float < warmup_steps_float, lambda: warmup_learning_rate, lambda: after_warmup_lr, name=name) def get_config(self) -> Mapping[str, Any]: if isinstance(self._after_warmup_lr_sched, tf.keras.optimizers.schedules.LearningRateSchedule): config = { "after_warmup_lr_sched": self._after_warmup_lr_sched.get_config()} # pytype: disable=attribute-error else: config = {"after_warmup_lr_sched": self._after_warmup_lr_sched} # pytype: disable=attribute-error config.update({ "warmup_steps": self._warmup_steps, "power": self._power, "name": self._name }) return config class DirectPowerDecay(tf.keras.optimizers.schedules.LearningRateSchedule): """Learning rate schedule follows lr * (step)^power.""" def __init__(self, initial_learning_rate: float, power: float = 1.0, name: str = "DirectPowerDecay"): """Initialize configuration of the learning rate schedule. Args: initial_learning_rate: The initial learning rate. power: The order of the polynomial. name: Optional, name of learning rate schedule. """ super().__init__() self._initial_learning_rate = initial_learning_rate self._power = power self._name = name def __call__(self, step): with tf.name_scope(self._name or "DirectPowerDecay"): step = tf.cast(step, tf.float32) learning_rate = self._initial_learning_rate # A zero `step` may cause Inf. So make `step` positive. step_non_zero = tf.math.maximum(step, 1.0) learning_rate *= tf.math.pow(step_non_zero, self._power) return learning_rate def get_config(self): """Get the configuration of the learning rate schedule.""" return { "initial_learning_rate": self._initial_learning_rate, "power": self._power, "name": self._name, } class PowerAndLinearDecay(tf.keras.optimizers.schedules.LearningRateSchedule): """Learning rate schedule with multiplied by linear decay at the end. The schedule has the following behavoir. Let offset_step = step - offset. 1) offset_step < 0, the actual learning rate equals initial_learning_rate. 2) offset_step <= total_decay_steps * (1 - linear_decay_fraction), the actual learning rate equals lr * offset_step^power. 3) total_decay_steps * (1 - linear_decay_fraction) <= offset_step < total_decay_steps, the actual learning rate equals lr * offset_step^power * (total_decay_steps - offset_step) / (total_decay_steps * linear_decay_fraction). 4) offset_step >= total_decay_steps, the actual learning rate equals zero. """ def __init__(self, initial_learning_rate: float, total_decay_steps: int, power: float = 1.0, linear_decay_fraction: float = 0.1, offset: int = 0, name: str = "PowerAndLinearDecay"): """Initialize configuration of the learning rate schedule. Args: initial_learning_rate: The initial learning rate. total_decay_steps: The total number of steps for power + linear decay. power: The order of the polynomial. linear_decay_fraction: In the last `linear_decay_fraction` steps, the learning rate will be multiplied by a linear decay. offset: The offset applied to steps. name: Optional, name of learning rate schedule. """ super().__init__() self._initial_learning_rate = initial_learning_rate self._total_decay_steps = total_decay_steps self._power = power self._linear_decay_fraction = linear_decay_fraction self._offset = offset self._name = name def __call__(self, step): with tf.name_scope(self._name or "PowerAndLinearDecay"): step = tf.cast(step - self._offset, tf.float32) learning_rate = self._initial_learning_rate # A zero `step` may cause Inf. So make `step` positive. step_non_zero = tf.math.maximum(step, 1.0) learning_rate *= tf.math.pow(step_non_zero, self._power) if self._total_decay_steps * self._linear_decay_fraction > 0: learning_rate *= tf.minimum( 1.0, (self._total_decay_steps - step) / (self._total_decay_steps * self._linear_decay_fraction)) learning_rate = tf.maximum(0.0, learning_rate) return learning_rate def get_config(self): """Get the configuration of the learning rate schedule.""" return { "initial_learning_rate": self._initial_learning_rate, "total_decay_steps": self._total_decay_steps, "power": self._power, "linear_decay_fraction": self._linear_decay_fraction, "offset": self._offset, "name": self._name, } class PowerDecayWithOffset(tf.keras.optimizers.schedules.LearningRateSchedule): """Power learning rate decay with offset. Learning rate equals to `pre_offset_learning_rate` if `step` < `offset`. Otherwise, learning rate equals to lr * (step - offset)^power. """ def __init__(self, initial_learning_rate: float, power: float = 1.0, offset: int = 0, pre_offset_learning_rate: float = 1.0e6, name: str = "PowerDecayWithOffset"): """Initialize configuration of the learning rate schedule. Args: initial_learning_rate: The initial learning rate. power: The order of the polynomial. offset: The offset when computing the power decay. pre_offset_learning_rate: The maximum learning rate we'll use. name: Optional, name of learning rate schedule. """ super().__init__() self._initial_learning_rate = initial_learning_rate self._power = power self._offset = offset self._pre_offset_lr = pre_offset_learning_rate self._name = name def __call__(self, step): with tf.name_scope(self._name or "PowerDecayWithOffset"): step = tf.cast(step, tf.float32) lr_after_offset = tf.math.pow( tf.math.maximum(step - self._offset, 1.0), self._power) * ( self._initial_learning_rate) sign = tf.cast(step > self._offset, tf.float32) lr_combined = (1.0 - sign) * self._pre_offset_lr + sign * lr_after_offset # Power may give infinitely large LR. So cap it with pre_offset_lr. return tf.math.minimum(lr_combined, self._pre_offset_lr) def get_config(self): """Get the configuration of the learning rate schedule.""" return { "initial_learning_rate": self._initial_learning_rate, "power": self._power, "offset": self._offset, "pre_offset_learning_rate": self._pre_offset_lr, "name": self._name, } class StepCosineDecayWithOffset( tf.keras.optimizers.schedules.LearningRateSchedule): """Stepwise cosine learning rate decay with offset. Learning rate is equivalent to one or more cosine decay(s) starting and ending at each interval. ExampleL ```python boundaries: [100000, 110000] values: [1.0, 0.5] lr_decayed_fn = ( lr_schedule.StepCosineDecayWithOffset( boundaries, values)) ``` from 0 to 100000 step, it will cosine decay from 1.0 to 0.5 from 100000 to 110000 step, it cosine decay from 0.5 to 0.0 """ def __init__(self, boundaries, values, offset: int = 0, name: str = "StepCosineDecayWithOffset"): """Initialize configuration of the learning rate schedule. Args: boundaries: A list of `Tensor`s or `int`s with strictly increasing entries, and with all elements having the same type as the optimizer step. values: A list of `Tensor`s or `float`s that specifies the values for the intervals defined by `boundaries`. It should have one more element than `boundaries`, and all elements should have the same type. offset: The offset when computing the power decay. name: Optional, name of learning rate schedule. """ super().__init__() self.values = values self.boundaries = boundaries self.offset = offset self.name = name if len(self.values) < 1: raise ValueError(f"Expect non empty {self.values}") if len(self.boundaries) != len(self.values): raise ValueError( "Boundaries length is equal to learning rate levels length" f"{len(self.boundaries)} != {len(self.values)}") self.total_steps = ( [boundaries[i + 1] - boundaries[i] for i in range(len(boundaries) - 1) ] + [0]) def __call__(self, global_step): with tf.name_scope(self.name or "StepCosineDecayWithOffset"): global_step = tf.cast(global_step - self.offset, tf.float32) lr_levels = self.values lr_steps = self.boundaries level_total_steps = self.total_steps num_levels = len(lr_levels) init_lr = lr_levels[0] next_init_lr = lr_levels[1] if num_levels > 1 else 0. init_total_steps = level_total_steps[0] cosine_learning_rate = ((init_lr - next_init_lr) * (tf.cos( tf.constant(math.pi) * (global_step) / (init_total_steps)) + 1.0) / 2.0 + next_init_lr) learning_rate = cosine_learning_rate for i in range(1, num_levels): next_init_lr = lr_levels[i] next_start_step = lr_steps[i] next_total_steps = level_total_steps[i] next_next_init_lr = lr_levels[i + 1] if num_levels > i + 1 else 0. next_cosine_learning_rate = ((next_init_lr - next_next_init_lr) * (tf.cos( tf.constant(math.pi) * (global_step - next_start_step) / (next_total_steps)) + 1.0) / 2.0 + next_next_init_lr) learning_rate = tf.where(global_step >= next_start_step, next_cosine_learning_rate, learning_rate) return learning_rate def get_config(self): return { "boundaries": self.boundaries, "values": self.values, "offset": self.offset, "name": self.name }
18,498
36.907787
111
py
models
models-master/official/modeling/optimization/ema_optimizer.py
# Copyright 2023 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. """Exponential moving average optimizer.""" from typing import List, Optional import tensorflow as tf # pylint: disable=protected-access def maybe_merge_call(fn, strategy, *args, **kwargs): """Maybe invoke `fn` via `merge_call` which may or may not be fulfilled. The caller of this utility function requests to invoke `fn` via `merge_call` at `tf.distribute.Strategy`'s best efforts. It is `tf.distribute`'s internal whether the request is honored, depending on the `Strategy`. See `tf.distribute.ReplicaContext.merge_call()` for more information. This is adapted from tensorflow/python/distribute/merge_call_interim.py. Args: fn: the function to be invoked. strategy: the `tf.distribute.Strategy` to call `fn` with. *args: the positional arguments to be passed in to `fn`. **kwargs: the keyword arguments to be passed in to `fn`. Returns: The return value of the `fn` call. """ if strategy.extended._use_merge_call(): return tf.distribute.get_replica_context().merge_call( fn, args=args, kwargs=kwargs ) else: return fn(strategy, *args, **kwargs) class ExponentialMovingAverage(tf.keras.optimizers.legacy.Optimizer): """Optimizer that computes an exponential moving average of the variables. Empirically it has been found that using the moving average of the trained parameters of a deep network is better than using its trained parameters directly. This optimizer allows you to compute this moving average and swap the variables at save time so that any code outside of the training loop will use by default the average values instead of the original ones. Example of usage for training: ```python opt = tf.keras.optimizers.SGD(learning_rate) opt = ExponentialMovingAverage(opt) opt.shadow_copy(model) ``` At test time, swap the shadow variables to evaluate on the averaged weights: ```python opt.swap_weights() # Test eval the model here opt.swap_weights() ``` """ def __init__(self, optimizer: tf.keras.optimizers.Optimizer, trainable_weights_only: bool = True, average_decay: float = 0.99, start_step: int = 0, dynamic_decay: bool = True, name: str = 'ExponentialMovingAverage', **kwargs): """Construct a new ExponentialMovingAverage optimizer. Args: optimizer: `tf.keras.optimizers.Optimizer` that will be used to compute and apply gradients. trainable_weights_only: 'bool', if True, only model trainable weights will be updated. Otherwise, all model weights will be updated. This mainly affects batch normalization parameters. average_decay: float. Decay to use to maintain the moving averages of trained variables. start_step: int. What step to start the moving average. dynamic_decay: bool. Whether to change the decay based on the number of optimizer updates. Decay will start at 0.1 and gradually increase up to `average_decay` after each optimizer update. This behavior is similar to `tf.train.ExponentialMovingAverage` in TF 1.x. name: Optional name for the operations created when applying gradients. Defaults to "moving_average". **kwargs: keyword arguments. Allowed to be {`clipnorm`, `clipvalue`, `lr`, `decay`}. """ super().__init__(name, **kwargs) self._average_decay = average_decay self._trainable_weights_only = trainable_weights_only self._start_step = tf.constant(start_step, tf.float32) self._dynamic_decay = dynamic_decay self._optimizer = optimizer self._track_trackable(self._optimizer, 'ema_base_optimizer') self._average_weights = None self._model_weights = None def shadow_copy(self, model: tf.keras.Model): """Creates shadow variables for the given model weights.""" if self._trainable_weights_only: self._model_weights = model.trainable_variables else: self._model_weights = model.variables for var in self._model_weights: self.add_slot(var, 'average', initializer='zeros') self._average_weights = [ self.get_slot(var, 'average') for var in self._model_weights ] @property def has_shadow_copy(self): """Whether this optimizer has created shadow variables.""" return self._model_weights is not None and self._average_weights is not None def _create_slots(self, var_list): self._optimizer._create_slots(var_list=var_list) # pylint: disable=protected-access def apply_gradients(self, grads_and_vars, name: Optional[str] = None): result = self._optimizer.apply_gradients(grads_and_vars, name) maybe_merge_call(self.update_average, tf.distribute.get_strategy()) return result @tf.function def update_average(self, strategy): # Compute current decay value. step = tf.cast(self.iterations, tf.float32) if step < self._start_step: decay = tf.constant(0., tf.float32) elif self._dynamic_decay: decay = step - self._start_step decay = tf.minimum(self._average_decay, (1. + decay) / (10. + decay)) else: decay = self._average_decay def _apply_moving(average, normal): diff = average - normal average.assign_sub(tf.cast(1.0 - decay, average.dtype) * diff) return average # Update moving average with the latest value. for average, normal in zip(self._average_weights, self._model_weights): strategy.extended.update( average, _apply_moving, args=(normal,), group=False ) def swap_weights(self): """Swap the average and moving weights. This is a convenience method to allow one to evaluate the averaged weights at test time. Loads the weights stored in `self._average` into the model, keeping a copy of the original model weights. Swapping twice will return the original weights. """ if tf.distribute.in_cross_replica_context(): strategy = tf.distribute.get_strategy() strategy.run(self._swap_weights, args=()) else: raise ValueError( 'Swapping weights must occur under a tf.distribute.Strategy.' ) @tf.function def _swap_weights(self): def fn_0(a, b): a.assign_add(b) return a def fn_1(b, a): b.assign(a - b) return b def fn_2(a, b): a.assign_sub(b) return a def _swap(strategy, a_and_b): """Swap `a` and `b` and mirror to all devices.""" for a, b in a_and_b: strategy.extended.update(a, fn_0, args=(b,)) # a = a + b strategy.extended.update(b, fn_1, args=(a,)) # b = a - b strategy.extended.update(a, fn_2, args=(b,)) # a = a - b # Use merge_call if requested by strategy and always for TPUStrategy as # the use of merge_call is not recommended and deprecated for other # strategies such as mirrored strategy (MS) and multi-worker mirrored # strategy (MWMS) if nccl/collective_ops are used, which can operate in # pure replica context. strategy = tf.distribute.get_strategy() if isinstance(strategy, tf.distribute.TPUStrategy): maybe_merge_call( _swap, strategy, zip(self._average_weights, self._model_weights), ) else: _swap( strategy, zip(self._average_weights, self._model_weights), ) def assign_average_vars(self, var_list: List[tf.Variable]): """Assign variables in var_list with their respective averages. Args: var_list: List of model variables to be assigned to their average. Returns: assign_op: The op corresponding to the assignment operation of variables to their average. """ assign_op = tf.group([ var.assign(self.get_slot(var, 'average')) for var in var_list if var.trainable ]) return assign_op def _create_hypers(self): self._optimizer._create_hypers() # pylint: disable=protected-access def _prepare(self, var_list): return self._optimizer._prepare(var_list=var_list) # pylint: disable=protected-access @property def iterations(self): return self._optimizer.iterations @iterations.setter def iterations(self, variable): self._optimizer.iterations = variable @property def weights(self): # return self._weights + self._optimizer.weights return self._optimizer.weights def variables(self): return self._weights + [self.iterations] @property def lr(self): return self._optimizer._get_hyper('learning_rate') @lr.setter def lr(self, lr): self._optimizer._set_hyper('learning_rate', lr) @property def learning_rate(self): return self._optimizer._get_hyper('learning_rate') @learning_rate.setter def learning_rate(self, learning_rate): # pylint: disable=redefined-outer-name self._optimizer._set_hyper('learning_rate', learning_rate) def _resource_apply_dense(self, grad, var): return self._optimizer._resource_apply_dense(grad, var) def _resource_apply_sparse(self, grad, var, indices): return self._optimizer._resource_apply_sparse(grad, var, indices) def _resource_apply_sparse_duplicate_indices(self, grad, var, indices): return self._optimizer._resource_apply_sparse_duplicate_indices( grad, var, indices) def get_config(self): config = { 'optimizer': tf.keras.optimizers.serialize(self._optimizer), 'average_decay': self._average_decay, 'start_step': self._start_step, 'dynamic_decay': self._dynamic_decay, } base_config = super(ExponentialMovingAverage, self).get_config() return dict(list(base_config.items()) + list(config.items())) @classmethod def from_config(cls, config, custom_objects=None): optimizer = tf.keras.optimizers.deserialize( config.pop('optimizer'), custom_objects=custom_objects, ) return cls(optimizer, **config)
10,508
34.383838
90
py
models
models-master/official/modeling/optimization/lars.py
# Copyright 2023 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. """Layer-wise adaptive rate scaling optimizer.""" import re from typing import Text, List, Optional import tensorflow as tf # pylint: disable=protected-access class LARS(tf.keras.optimizers.legacy.Optimizer): """Layer-wise Adaptive Rate Scaling for large batch training. Introduced by "Large Batch Training of Convolutional Networks" by Y. You, I. Gitman, and B. Ginsburg. (https://arxiv.org/abs/1708.03888) """ def __init__(self, learning_rate: float = 0.01, momentum: float = 0.9, weight_decay_rate: float = 0.0, eeta: float = 0.001, nesterov: bool = False, classic_momentum: bool = True, exclude_from_weight_decay: Optional[List[Text]] = None, exclude_from_layer_adaptation: Optional[List[Text]] = None, name: Text = "LARS", **kwargs): """Constructs a LARSOptimizer. Args: learning_rate: `float` for learning rate. Defaults to 0.01. momentum: `float` hyperparameter >= 0 that accelerates gradient descent in the relevant direction and dampens oscillations. Defaults to 0.9. weight_decay_rate: `float` for weight decay. eeta: `float` LARS coefficient as used in the paper. Default set to LARS coefficient from the paper. (eeta / weight_decay) determines the highest scaling factor in LARS.. nesterov: 'boolean' for whether to use nesterov momentum. classic_momentum: `boolean` for whether to use classic (or popular) momentum. The learning rate is applied during momentum update in classic momentum, but after momentum for popular momentum. exclude_from_weight_decay: A list of `string` for variable screening, if any of the string appears in a variable's name, the variable will be excluded for computing weight decay. For example, one could specify the list like ['batch_normalization', 'bias'] to exclude BN and bias from weight decay. exclude_from_layer_adaptation: Similar to exclude_from_weight_decay, but for layer adaptation. If it is None, it will be defaulted the same as exclude_from_weight_decay. name: `Text` as optional name for the operations created when applying gradients. Defaults to "LARS". **kwargs: keyword arguments. Allowed to be {`clipnorm`, `clipvalue`, `lr`, `decay`}. `clipnorm` is clip gradients by norm; `clipvalue` is clip gradients by value, `decay` is included for backward compatibility to allow time inverse decay of learning rate. `lr` is included for backward compatibility, recommended to use `learning_rate` instead. """ super(LARS, self).__init__(name, **kwargs) self._set_hyper("learning_rate", learning_rate) self._set_hyper("decay", self._initial_decay) self.momentum = momentum self.weight_decay_rate = weight_decay_rate self.eeta = eeta self.nesterov = nesterov self.classic_momentum = classic_momentum self.exclude_from_weight_decay = exclude_from_weight_decay # exclude_from_layer_adaptation is set to exclude_from_weight_decay if the # arg is None. if exclude_from_layer_adaptation: self.exclude_from_layer_adaptation = exclude_from_layer_adaptation else: self.exclude_from_layer_adaptation = exclude_from_weight_decay def _create_slots(self, var_list): for v in var_list: self.add_slot(v, "momentum") def _resource_apply_dense(self, grad, param, apply_state=None): if grad is None or param is None: return tf.no_op() var_device, var_dtype = param.device, param.dtype.base_dtype coefficients = ((apply_state or {}).get((var_device, var_dtype)) or self._fallback_apply_state(var_device, var_dtype)) learning_rate = coefficients["lr_t"] param_name = param.name v = self.get_slot(param, "momentum") if self._use_weight_decay(param_name): grad += self.weight_decay_rate * param if self.classic_momentum: trust_ratio = 1.0 if self._do_layer_adaptation(param_name): w_norm = tf.norm(param, ord=2) g_norm = tf.norm(grad, ord=2) trust_ratio = tf.where( tf.greater(w_norm, 0), tf.where(tf.greater(g_norm, 0), (self.eeta * w_norm / g_norm), 1.0), 1.0) scaled_lr = learning_rate * trust_ratio next_v = tf.multiply(self.momentum, v) + scaled_lr * grad if self.nesterov: update = tf.multiply(self.momentum, next_v) + scaled_lr * grad else: update = next_v next_param = param - update else: next_v = tf.multiply(self.momentum, v) + grad if self.nesterov: update = tf.multiply(self.momentum, next_v) + grad else: update = next_v trust_ratio = 1.0 if self._do_layer_adaptation(param_name): w_norm = tf.norm(param, ord=2) v_norm = tf.norm(update, ord=2) trust_ratio = tf.where( tf.greater(w_norm, 0), tf.where(tf.greater(v_norm, 0), (self.eeta * w_norm / v_norm), 1.0), 1.0) scaled_lr = trust_ratio * learning_rate next_param = param - scaled_lr * update return tf.group(*[ param.assign(next_param, use_locking=False), v.assign(next_v, use_locking=False) ]) def _resource_apply_sparse(self, grad, handle, indices, apply_state): raise NotImplementedError("Applying sparse gradients is not implemented.") def _use_weight_decay(self, param_name): """Whether to use L2 weight decay for `param_name`.""" if not self.weight_decay_rate: return False if self.exclude_from_weight_decay: for r in self.exclude_from_weight_decay: if re.search(r, param_name) is not None: return False return True def _do_layer_adaptation(self, param_name): """Whether to do layer-wise learning rate adaptation for `param_name`.""" if self.exclude_from_layer_adaptation: for r in self.exclude_from_layer_adaptation: if re.search(r, param_name) is not None: return False return True def get_config(self): config = super(LARS, self).get_config() config.update({ "learning_rate": self._serialize_hyperparameter("learning_rate"), "decay": self._serialize_hyperparameter("decay"), "momentum": self.momentum, "classic_momentum": self.classic_momentum, "weight_decay_rate": self.weight_decay_rate, "eeta": self.eeta, "nesterov": self.nesterov, }) return config @classmethod def from_config(cls, config, custom_objects=None): return cls(**config)
7,338
38.245989
80
py
models
models-master/official/modeling/optimization/lamb.py
# Copyright 2023 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. """Layer-wise Adaptive Moments (LAMB) optimizer. See paper [Large Batch Optimization for Deep Learning: Training BERT in 76 minutes](https://arxiv.org/abs/1904.00962). """ import re from typing import Optional, Union, Callable, List import numpy as np import tensorflow as tf FloatTensorLike = Union[tf.Tensor, float, np.float16, np.float32] @tf.keras.utils.register_keras_serializable(package="Addons") class LAMB(tf.keras.optimizers.legacy.Optimizer): """Optimizer that implements the Layer-wise Adaptive Moments (LAMB). See paper [Large Batch Optimization for Deep Learning: Training BERT in 76 minutes](https://arxiv.org/abs/1904.00962). """ def __init__( self, learning_rate: Union[FloatTensorLike, Callable] = 0.001, beta_1: FloatTensorLike = 0.9, beta_2: FloatTensorLike = 0.999, epsilon: FloatTensorLike = 1e-6, weight_decay_rate: FloatTensorLike = 0.0, exclude_from_weight_decay: Optional[List[str]] = None, exclude_from_layer_adaptation: Optional[List[str]] = None, name: str = "LAMB", **kwargs, ): """Construct a new LAMB optimizer. Args: learning_rate: A `Tensor` or a floating point value. or a schedule that is a `tf.keras.optimizers.schedules.LearningRateSchedule` The learning rate. beta_1: A `float` value or a constant `float` tensor. The exponential decay rate for the 1st moment estimates. beta_2: A `float` value or a constant `float` tensor. The exponential decay rate for the 2nd moment estimates. epsilon: A small constant for numerical stability. weight_decay_rate: weight decay rate. exclude_from_weight_decay: List of regex patterns of variables excluded from weight decay. Variables whose name contain a substring matching the pattern will be excluded. exclude_from_layer_adaptation: List of regex patterns of variables excluded from layer adaptation. Variables whose name contain a substring matching the pattern will be excluded. name: Optional name for the operations created when applying gradients. Defaults to "LAMB". **kwargs: keyword arguments. Allowed to be {`clipnorm`, `clipvalue`, `lr`, `decay`}. `clipnorm` is clip gradients by norm; `clipvalue` is clip gradients by value, `decay` is included for backward compatibility to allow time inverse decay of learning rate. `lr` is included for backward compatibility, recommended to use `learning_rate` instead. """ super().__init__(name, **kwargs) # Just adding the square of the weights to the loss function is *not* # the correct way of using L2 regularization/weight decay with Adam, # since that will interact with the m and v parameters in strange ways. # # Instead we want to decay the weights in a manner that doesn't interact # with the m/v parameters. self._set_hyper("weight_decay_rate", weight_decay_rate) self._set_hyper("learning_rate", kwargs.get("lr", learning_rate)) # This is learning rate decay for using keras learning rate schedule. self._set_hyper("decay", self._initial_decay) self._set_hyper("beta_1", beta_1) self._set_hyper("beta_2", beta_2) self.epsilon = epsilon or tf.backend_config.epsilon() self.exclude_from_weight_decay = exclude_from_weight_decay # exclude_from_layer_adaptation is set to exclude_from_weight_decay if # the arg is None. if exclude_from_layer_adaptation: self.exclude_from_layer_adaptation = exclude_from_layer_adaptation else: self.exclude_from_layer_adaptation = exclude_from_weight_decay def _create_slots(self, var_list): # Create slots for the first and second moments. # Separate for-loops to respect the ordering of slot variables from v1. for var in var_list: self.add_slot(var, "m") for var in var_list: self.add_slot(var, "v") def _prepare_local(self, var_device, var_dtype, apply_state): super()._prepare_local(var_device, var_dtype, apply_state) local_step = tf.cast(self.iterations + 1, var_dtype) beta_1_t = tf.identity(self._get_hyper("beta_1", var_dtype)) beta_2_t = tf.identity(self._get_hyper("beta_2", var_dtype)) weight_decay_rate = tf.identity( self._get_hyper("weight_decay_rate", var_dtype) ) beta_1_power = tf.pow(beta_1_t, local_step) beta_2_power = tf.pow(beta_2_t, local_step) apply_state[(var_device, var_dtype)].update( dict( weight_decay_rate=weight_decay_rate, epsilon=tf.convert_to_tensor(self.epsilon, var_dtype), beta_1_t=beta_1_t, beta_1_power=beta_1_power, one_minus_beta_1_t=1 - beta_1_t, beta_2_t=beta_2_t, beta_2_power=beta_2_power, one_minus_beta_2_t=1 - beta_2_t, ) ) def _resource_apply_dense(self, grad, var, apply_state=None): var_device, var_dtype = var.device, var.dtype.base_dtype coefficients = (apply_state or {}).get( (var_device, var_dtype) ) or self._fallback_apply_state(var_device, var_dtype) # m_t = beta1 * m + (1 - beta1) * g_t m = self.get_slot(var, "m") m_scaled_g_values = grad * coefficients["one_minus_beta_1_t"] m_t = m * coefficients["beta_1_t"] + m_scaled_g_values m_t = m.assign(m_t, use_locking=self._use_locking) # v_t = beta2 * v + (1 - beta2) * (g_t * g_t) v = self.get_slot(var, "v") v_scaled_g_values = (grad * grad) * coefficients["one_minus_beta_2_t"] v_t = v * coefficients["beta_2_t"] + v_scaled_g_values v_t = v.assign(v_t, use_locking=self._use_locking) m_t_hat = m_t / (1.0 - coefficients["beta_1_power"]) v_t_hat = v_t / (1.0 - coefficients["beta_2_power"]) v_sqrt = tf.sqrt(v_t_hat) update = m_t_hat / (v_sqrt + coefficients["epsilon"]) var_name = self._get_variable_name(var.name) if self._do_use_weight_decay(var_name): update += coefficients["weight_decay_rate"] * var ratio = 1.0 if self._do_layer_adaptation(var_name): w_norm = tf.norm(var, ord=2) g_norm = tf.norm(update, ord=2) ratio = tf.where( tf.greater(w_norm, 0), tf.where(tf.greater(g_norm, 0), (w_norm / g_norm), 1.0), 1.0, ) var_update = var - ratio * coefficients["lr_t"] * update return var.assign(var_update, use_locking=self._use_locking) def _resource_apply_sparse(self, grad, var, indices, apply_state=None): var_device, var_dtype = var.device, var.dtype.base_dtype coefficients = (apply_state or {}).get( (var_device, var_dtype) ) or self._fallback_apply_state(var_device, var_dtype) # m_t = beta1 * m + (1 - beta1) * g_t m = self.get_slot(var, "m") m_scaled_g_values = grad * coefficients["one_minus_beta_1_t"] m_t = m.assign(m * coefficients["beta_1_t"], use_locking=self._use_locking) with tf.control_dependencies([m_t]): m_t = self._resource_scatter_add(m, indices, m_scaled_g_values) # v_t = beta2 * v + (1 - beta2) * (g_t * g_t) v = self.get_slot(var, "v") v_scaled_g_values = (grad * grad) * coefficients["one_minus_beta_2_t"] v_t = v.assign(v * coefficients["beta_2_t"], use_locking=self._use_locking) with tf.control_dependencies([v_t]): v_t = self._resource_scatter_add(v, indices, v_scaled_g_values) m_t_hat = m_t / (1.0 - coefficients["beta_1_power"]) v_t_hat = v_t / (1.0 - coefficients["beta_2_power"]) v_sqrt = tf.sqrt(v_t_hat) update = m_t_hat / (v_sqrt + coefficients["epsilon"]) var_name = self._get_variable_name(var.name) if self._do_use_weight_decay(var_name): update += coefficients["weight_decay_rate"] * var ratio = 1.0 if self._do_layer_adaptation(var_name): w_norm = tf.norm(var, ord=2) g_norm = tf.norm(update, ord=2) ratio = tf.where( tf.greater(w_norm, 0), tf.where(tf.greater(g_norm, 0), (w_norm / g_norm), 1.0), 1.0, ) var_update = var.assign_sub( ratio * coefficients["lr_t"] * update, use_locking=self._use_locking ) return tf.group(*[var_update, m_t, v_t]) def get_config(self): config = super().get_config() config.update({ "learning_rate": self._serialize_hyperparameter("learning_rate"), "weight_decay_rate": self._serialize_hyperparameter( "weight_decay_rate" ), "decay": self._serialize_hyperparameter("decay"), "beta_1": self._serialize_hyperparameter("beta_1"), "beta_2": self._serialize_hyperparameter("beta_2"), "epsilon": self.epsilon, }) return config def _do_use_weight_decay(self, param_name): """Whether to use L2 weight decay for `param_name`.""" if self.exclude_from_weight_decay: for r in self.exclude_from_weight_decay: if re.search(r, param_name) is not None: return False return True def _do_layer_adaptation(self, param_name): """Whether to do layer-wise learning rate adaptation for `param_name`.""" if self.exclude_from_layer_adaptation: for r in self.exclude_from_layer_adaptation: if re.search(r, param_name) is not None: return False return True def _get_variable_name(self, param_name): """Get the variable name from the tensor name.""" m = re.match("^(.*):\\d+$", param_name) if m is not None: param_name = m.group(1) return param_name
10,137
39.071146
80
py
models
models-master/official/modeling/optimization/configs/optimizer_config.py
# Copyright 2023 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. """Dataclasses for optimizer configs.""" from typing import List, Optional import dataclasses from official.modeling.hyperparams import base_config @dataclasses.dataclass class BaseOptimizerConfig(base_config.Config): """Base optimizer config. Attributes: clipnorm: float >= 0 or None. If not None, Gradients will be clipped when their L2 norm exceeds this value. clipvalue: float >= 0 or None. If not None, Gradients will be clipped when their absolute value exceeds this value. global_clipnorm: float >= 0 or None. If not None, gradient of all weights is clipped so that their global norm is no higher than this value """ clipnorm: Optional[float] = None clipvalue: Optional[float] = None global_clipnorm: Optional[float] = None @dataclasses.dataclass class SGDConfig(BaseOptimizerConfig): """Configuration for SGD optimizer. The attributes for this class matches the arguments of tf.keras.optimizer.SGD. Attributes: name: name of the optimizer. decay: decay rate for SGD optimizer. nesterov: nesterov for SGD optimizer. momentum: momentum for SGD optimizer. """ name: str = "SGD" decay: float = 0.0 nesterov: bool = False momentum: float = 0.0 # TODO(b/216129465): Merge this config with SGDConfig after the experimental # optimizer graduates. @dataclasses.dataclass class SGDExperimentalConfig(BaseOptimizerConfig): """Configuration for SGD optimizer. The attributes for this class matches the arguments of `tf.keras.optimizer.experimental.SGD`. Attributes: name: name of the optimizer. nesterov: nesterov for SGD optimizer. momentum: momentum for SGD optimizer. jit_compile: if True, jit compile will be used. """ name: str = "SGD" nesterov: bool = False momentum: float = 0.0 jit_compile: bool = False @dataclasses.dataclass class RMSPropConfig(BaseOptimizerConfig): """Configuration for RMSProp optimizer. The attributes for this class matches the arguments of tf.keras.optimizers.RMSprop. Attributes: name: name of the optimizer. rho: discounting factor for RMSprop optimizer. momentum: momentum for RMSprop optimizer. epsilon: epsilon value for RMSprop optimizer, help with numerical stability. centered: Whether to normalize gradients or not. """ name: str = "RMSprop" rho: float = 0.9 momentum: float = 0.0 epsilon: float = 1e-7 centered: bool = False @dataclasses.dataclass class AdagradConfig(BaseOptimizerConfig): """Configuration for Adagrad optimizer. The attributes of this class match the arguments of tf.keras.optimizer.Adagrad. Attributes: name: name of the optimizer. initial_accumulator_value: A floating point value. Starting value for the accumulators, must be non-negative. epsilon: A small floating point value to avoid zero denominator. """ name: str = "Adagrad" initial_accumulator_value: float = 0.1 epsilon: float = 1e-07 @dataclasses.dataclass class AdamConfig(BaseOptimizerConfig): """Configuration for Adam optimizer. The attributes for this class matches the arguments of tf.keras.optimizer.Adam. Attributes: name: name of the optimizer. beta_1: decay rate for 1st order moments. beta_2: decay rate for 2st order moments. epsilon: epsilon value used for numerical stability in Adam optimizer. amsgrad: boolean. Whether to apply AMSGrad variant of this algorithm from the paper "On the Convergence of Adam and beyond". """ name: str = "Adam" beta_1: float = 0.9 beta_2: float = 0.999 epsilon: float = 1e-07 amsgrad: bool = False @dataclasses.dataclass class AdamExperimentalConfig(BaseOptimizerConfig): """Configuration for experimental Adam optimizer. The attributes for this class matches the arguments of `tf.keras.optimizer.experimental.Adam`. Attributes: name: name of the optimizer. beta_1: decay rate for 1st order moments. beta_2: decay rate for 2st order moments. epsilon: epsilon value used for numerical stability in Adam optimizer. amsgrad: boolean. Whether to apply AMSGrad variant of this algorithm from the paper "On the Convergence of Adam and beyond". jit_compile: if True, jit compile will be used. """ name: str = "Adam" beta_1: float = 0.9 beta_2: float = 0.999 epsilon: float = 1e-07 amsgrad: bool = False jit_compile: bool = False @dataclasses.dataclass class AdamWeightDecayConfig(BaseOptimizerConfig): """Configuration for Adam optimizer with weight decay. Attributes: name: name of the optimizer. beta_1: decay rate for 1st order moments. beta_2: decay rate for 2st order moments. epsilon: epsilon value used for numerical stability in the optimizer. amsgrad: boolean. Whether to apply AMSGrad variant of this algorithm from the paper "On the Convergence of Adam and beyond". weight_decay_rate: float. Weight decay rate. Default to 0. include_in_weight_decay: list[str], or None. List of weight names to include in weight decay. exclude_from_weight_decay: list[str], or None. List of weight names to not include in weight decay. gradient_clip_norm: A positive float. Clips the gradients to this maximum L2-norm. Default to 1.0. """ name: str = "AdamWeightDecay" beta_1: float = 0.9 beta_2: float = 0.999 epsilon: float = 1e-07 amsgrad: bool = False weight_decay_rate: float = 0.0 include_in_weight_decay: Optional[List[str]] = None exclude_from_weight_decay: Optional[List[str]] = None gradient_clip_norm: float = 1.0 @dataclasses.dataclass class AdamWeightDecayExperimentalConfig(BaseOptimizerConfig): """Configuration for Adam optimizer with weight decay. Attributes: name: name of the optimizer. beta_1: decay rate for 1st order moments. beta_2: decay rate for 2st order moments. epsilon: epsilon value used for numerical stability in the optimizer. amsgrad: boolean. Whether to apply AMSGrad variant of this algorithm from the paper "On the Convergence of Adam and beyond". weight_decay: float. Weight decay rate. Default to 0. global_clipnorm: A positive float. Clips the gradients to this maximum L2-norm. Default to 1.0. jit_compile: if True, jit compile will be used. """ name: str = "AdamWeightDecayExperimental" beta_1: float = 0.9 beta_2: float = 0.999 epsilon: float = 1e-07 amsgrad: bool = False weight_decay: float = 0.0 global_clipnorm: float = 1.0 jit_compile: bool = False @dataclasses.dataclass class LAMBConfig(BaseOptimizerConfig): """Configuration for LAMB optimizer. The attributes for this class matches the arguments of LAMB optimizer. Attributes: name: name of the optimizer. beta_1: decay rate for 1st order moments. beta_2: decay rate for 2st order moments. epsilon: epsilon value used for numerical stability in LAMB optimizer. weight_decay_rate: float. Weight decay rate. Default to 0. exclude_from_weight_decay: List of regex patterns of variables excluded from weight decay. Variables whose name contain a substring matching the pattern will be excluded. exclude_from_layer_adaptation: List of regex patterns of variables excluded from layer adaptation. Variables whose name contain a substring matching the pattern will be excluded. """ name: str = "LAMB" beta_1: float = 0.9 beta_2: float = 0.999 epsilon: float = 1e-6 weight_decay_rate: float = 0.0 exclude_from_weight_decay: Optional[List[str]] = None exclude_from_layer_adaptation: Optional[List[str]] = None @dataclasses.dataclass class EMAConfig(BaseOptimizerConfig): """Exponential moving average optimizer config. Attributes: name: 'str', name of the optimizer. trainable_weights_only: 'bool', if True, only model trainable weights will be updated. Otherwise, all model weights will be updated. This mainly affects batch normalization parameters. average_decay: 'float', average decay value. start_step: 'int', start step to apply moving average. dynamic_decay: 'bool', whether to apply dynamic decay or not. """ name: str = "ExponentialMovingAverage" trainable_weights_only: bool = True average_decay: float = 0.99 start_step: int = 0 dynamic_decay: bool = True @dataclasses.dataclass class LARSConfig(BaseOptimizerConfig): """Layer-wise adaptive rate scaling config. Attributes: name: 'str', name of the optimizer. momentum: `float` hyperparameter >= 0 that accelerates gradient descent in the relevant direction and dampens oscillations. Defaults to 0.9. eeta: `float` LARS coefficient as used in the paper. Default set to LARS coefficient from the paper. (eeta / weight_decay) determines the highest scaling factor in LARS.. weight_decay_rate: `float` for weight decay. nesterov: 'boolean' for whether to use nesterov momentum. classic_momentum: `boolean` for whether to use classic (or popular) momentum. The learning rate is applied during momentum update in classic momentum, but after momentum for popular momentum. exclude_from_weight_decay: A list of `string` for variable screening, if any of the string appears in a variable's name, the variable will be excluded for computing weight decay. For example, one could specify the list like ['batch_normalization', 'bias'] to exclude BN and bias from weight decay. exclude_from_layer_adaptation: Similar to exclude_from_weight_decay, but for layer adaptation. If it is None, it will be defaulted the same as exclude_from_weight_decay. """ name: str = "LARS" momentum: float = 0.9 eeta: float = 0.001 weight_decay_rate: float = 0.0 nesterov: bool = False classic_momentum: bool = True exclude_from_weight_decay: Optional[List[str]] = None exclude_from_layer_adaptation: Optional[List[str]] = None @dataclasses.dataclass class SLIDEConfig(BaseOptimizerConfig): """Configuration for SLIDE optimizer. Details coming soon. """ name: str = "SLIDE" beta_1: float = 0.9 beta_2: float = 0.999 epsilon: float = 1e-6 weight_decay_rate: float = 0.0 weight_decay_type: str = "inner" exclude_from_weight_decay: Optional[List[str]] = None exclude_from_layer_adaptation: Optional[List[str]] = None include_in_sparse_layer_adaptation: Optional[List[str]] = None sparse_layer_learning_rate: float = 0.1 do_gradient_rescaling: bool = True norm_type: str = "layer" ratio_clip_norm: float = 1e5 @dataclasses.dataclass class AdafactorConfig(BaseOptimizerConfig): """Configuration for Adafactor optimizer. The attributes for this class matches the arguments of the Adafactor implementation. """ name: str = "Adafactor" factored: bool = True multiply_by_parameter_scale: bool = True beta1: Optional[float] = None decay_rate: float = 0.8 step_offset: int = 0 clipping_threshold: float = 1.0 min_dim_size_to_factor: int = 128 epsilon1: float = 1e-30 epsilon2: float = 1e-3 weight_decay: Optional[float] = None include_in_weight_decay: Optional[str] = None
11,724
33.384164
80
py
models
models-master/official/modeling/optimization/configs/learning_rate_config.py
# Copyright 2023 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. """Dataclasses for learning rate schedule config.""" from typing import List, Optional import dataclasses from official.modeling.hyperparams import base_config @dataclasses.dataclass class ConstantLrConfig(base_config.Config): """Configuration for constant learning rate. This class is a containers for the constant learning rate decay configs. Attributes: name: The name of the learning rate schedule. Defaults to Constant. learning_rate: A float. The learning rate. Defaults to 0.1. """ name: str = 'Constant' learning_rate: float = 0.1 @dataclasses.dataclass class StepwiseLrConfig(base_config.Config): """Configuration for stepwise learning rate decay. This class is a container for the piecewise constant learning rate scheduling configs. It will configure an instance of PiecewiseConstantDecay keras learning rate schedule. An example (from keras docs): use a learning rate that's 1.0 for the first 100001 steps, 0.5 for the next 10000 steps, and 0.1 for any additional steps. ```python boundaries: [100000, 110000] values: [1.0, 0.5, 0.1] Attributes: name: The name of the learning rate schedule. Defaults to PiecewiseConstant. boundaries: A list of ints of strictly increasing entries. Defaults to None. values: A list of floats that specifies the values for the intervals defined by `boundaries`. It should have one more element than `boundaries`. The learning rate is computed as follows: [0, boundaries[0]] -> values[0] [boundaries[0], boundaries[1]] -> values[1] [boundaries[n-1], boundaries[n]] -> values[n] [boundaries[n], end] -> values[n+1] Defaults to None. offset: An int. The offset applied to steps. Defaults to 0. """ name: str = 'PiecewiseConstantDecay' boundaries: Optional[List[int]] = None values: Optional[List[float]] = None offset: int = 0 @dataclasses.dataclass class ExponentialLrConfig(base_config.Config): """Configuration for exponential learning rate decay. This class is a containers for the exponential learning rate decay configs. Attributes: name: The name of the learning rate schedule. Defaults to ExponentialDecay. initial_learning_rate: A float. The initial learning rate. Defaults to None. decay_steps: A positive integer that is used for decay computation. Defaults to None. decay_rate: A float. Defaults to None. staircase: A boolean, if true, learning rate is decreased at discreate intervals. Defaults to False. offset: An int. The offset applied to steps. Defaults to 0. """ name: str = 'ExponentialDecay' initial_learning_rate: Optional[float] = None decay_steps: Optional[int] = None decay_rate: Optional[float] = None staircase: Optional[bool] = None offset: int = 0 @dataclasses.dataclass class PolynomialLrConfig(base_config.Config): """Configuration for polynomial learning rate decay. This class is a containers for the polynomial learning rate decay configs. Attributes: name: The name of the learning rate schedule. Defaults to PolynomialDecay. initial_learning_rate: A float. The initial learning rate. Defaults to None. decay_steps: A positive integer that is used for decay computation. Defaults to None. end_learning_rate: A float. The minimal end learning rate. power: A float. The power of the polynomial. Defaults to linear, 1.0. cycle: A boolean, whether or not it should cycle beyond decay_steps. Defaults to False. offset: An int. The offset applied to steps. Defaults to 0. """ name: str = 'PolynomialDecay' initial_learning_rate: Optional[float] = None decay_steps: Optional[int] = None end_learning_rate: float = 0.0001 power: float = 1.0 cycle: bool = False offset: int = 0 @dataclasses.dataclass class CosineLrConfig(base_config.Config): """Configuration for Cosine learning rate decay. This class is a containers for the cosine learning rate decay configs, tf.keras.experimental.CosineDecay. Attributes: name: The name of the learning rate schedule. Defaults to CosineDecay. initial_learning_rate: A float. The initial learning rate. Defaults to None. decay_steps: A positive integer that is used for decay computation. Defaults to None. alpha: A float. Minimum learning rate value as a fraction of initial_learning_rate. offset: An int. The offset applied to steps. Defaults to 0. """ name: str = 'CosineDecay' initial_learning_rate: Optional[float] = None decay_steps: Optional[int] = None alpha: float = 0.0 offset: int = 0 @dataclasses.dataclass class DirectPowerLrConfig(base_config.Config): """Configuration for DirectPower learning rate decay. This class configures a schedule following follows lr * (step)^power. Attributes: name: The name of the learning rate schedule. Defaults to DirectPowerDecay. initial_learning_rate: A float. The initial learning rate. Defaults to None. power: A float. Defaults to -0.5, for sqrt decay. """ name: str = 'DirectPowerDecay' initial_learning_rate: Optional[float] = None power: float = -0.5 @dataclasses.dataclass class PowerAndLinearDecayLrConfig(base_config.Config): """Configuration for DirectPower learning rate decay. The schedule has the following behavoir. Let offset_step = step - offset. 1) offset_step < 0, the actual learning rate equals initial_learning_rate. 2) offset_step <= total_decay_steps * (1 - linear_decay_fraction), the actual learning rate equals lr * offset_step^power. 3) total_decay_steps * (1 - linear_decay_fraction) <= offset_step < total_decay_steps, the actual learning rate equals lr * offset_step^power * (total_decay_steps - offset_step) / (total_decay_steps * linear_decay_fraction). 4) offset_step >= total_decay_steps, the actual learning rate equals zero. Attributes: name: The name of the learning rate schedule. Defaults to PowerAndLinearDecay. initial_learning_rate: A float. The initial learning rate. Defaults to None. total_decay_steps: An int. The total number of steps for power + linear decay. Defaults to None. power: A float. The order of the polynomial. Defaults to -0.5, for sqrt decay. linear_decay_fraction: A float. In the last `linear_decay_fraction` steps, the learning rate will be multiplied by a linear decay. Defaults to 0.1. offset: An int. The offset applied to steps. Defaults to 0. """ name: str = 'PowerAndLinearDecay' initial_learning_rate: Optional[float] = None total_decay_steps: Optional[int] = None power: float = -0.5 linear_decay_fraction: float = 0.1 offset: int = 0 @dataclasses.dataclass class PowerDecayWithOffsetLrConfig(base_config.Config): """Configuration for power learning rate decay with step offset. Learning rate equals to `pre_offset_learning_rate` if `step` < `offset`. Otherwise, learning rate equals to lr * (step - offset)^power. Attributes: name: The name of the learning rate schedule. Defaults to PowerDecayWithOffset. initial_learning_rate: A float. The initial learning rate. Defaults to None. power: A float. Defaults to -0.5, for sqrt decay. offset: An integer. Power decay happens after `offset` steps. pre_offset_learning_rate: A float. The constant learning rate before `offset` steps. """ name: str = 'PowerDecayWithOffset' initial_learning_rate: Optional[float] = None power: float = -0.5 offset: int = 0 pre_offset_learning_rate: float = 1.0e6 @dataclasses.dataclass class StepCosineLrConfig(base_config.Config): """Configuration for stepwise learning rate decay. This class is a container for the piecewise cosine learning rate scheduling configs. It will configure an instance of StepCosineDecayWithOffset keras learning rate schedule. ```python boundaries: [100000, 110000] values: [1.0, 0.5] lr_decayed_fn = ( lr_schedule.StepCosineDecayWithOffset( boundaries, values)) ``` from 0 to 100000 step, it will cosine decay from 1.0 to 0.5 from 100000 to 110000 step, it cosine decay from 0.5 to 0.0 Attributes: name: The name of the learning rate schedule. Defaults to PiecewiseConstant. boundaries: A list of ints of strictly increasing entries. Defaults to None. values: A list of floats that specifies the values for the intervals defined by `boundaries`. It should have one more element than `boundaries`. The learning rate is computed as follows: [0, boundaries[0]] -> cosine from values[0] to values[1] [boundaries[0], boundaries[1]] -> values[1] to values[2] ... [boundaries[n-1], boundaries[n]] -> values[n] to values[n+1] [boundaries[n], end] -> values[n+1] to 0. offset: An int. The offset applied to steps. Defaults to 0. """ name: str = 'StepCosineDecayWithOffset' boundaries: Optional[List[int]] = None values: Optional[List[float]] = None offset: int = 0 @dataclasses.dataclass class LinearWarmupConfig(base_config.Config): """Configuration for linear warmup schedule config. This class is a container for the linear warmup schedule configs. Warmup_learning_rate is the initial learning rate, the final learning rate of the warmup period is the learning_rate of the optimizer in use. The learning rate at each step linearly increased according to the following formula: warmup_learning_rate = warmup_learning_rate + step / warmup_steps * (final_learning_rate - warmup_learning_rate). Using warmup overrides the learning rate schedule by the number of warmup steps. Attributes: name: The name of warmup schedule. Defaults to linear. warmup_learning_rate: Initial learning rate for the warmup. Defaults to 0. warmup_steps: Warmup steps. Defaults to None. """ name: str = 'linear' warmup_learning_rate: float = 0 warmup_steps: Optional[int] = None @dataclasses.dataclass class PolynomialWarmupConfig(base_config.Config): """Configuration for linear warmup schedule config. This class is a container for the polynomial warmup schedule configs. Attributes: name: The name of warmup schedule. Defaults to Polynomial. power: Polynomial power. Defaults to 1. warmup_steps: Warmup steps. Defaults to None. """ name: str = 'polynomial' power: float = 1 warmup_steps: Optional[int] = None
11,122
37.487889
80
py
models
models-master/official/modeling/multitask/base_model.py
# Copyright 2023 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. """Abstraction of multi-task model.""" from typing import Text, Dict import tensorflow as tf class MultiTaskBaseModel(tf.Module): """Base class that holds multi-task model computation.""" def __init__(self, **kwargs): super().__init__(**kwargs) self._sub_tasks = self._instantiate_sub_tasks() def _instantiate_sub_tasks(self) -> Dict[Text, tf.keras.Model]: """Abstract function that sets up the computation for each sub-task. Returns: A map from task name (as string) to a tf.keras.Model object that represents the sub-task in the multi-task pool. """ raise NotImplementedError( "_instantiate_sub_task_models() is not implemented.") @property def sub_tasks(self): """Fetch a map of task name (string) to task model (tf.keras.Model).""" return self._sub_tasks def initialize(self): """Optional function that loads a pre-train checkpoint.""" return def build(self): """Builds the networks for tasks to make sure variables are created.""" # Try to build all sub tasks. for task_model in self._sub_tasks.values(): # Assumes all the tf.Module models are built because we don't have any # way to check them. if isinstance(task_model, tf.keras.Model) and not task_model.built: _ = task_model(task_model.inputs)
1,936
34.218182
76
py
models
models-master/official/modeling/multitask/base_trainer.py
# Copyright 2023 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. """Multitask base trainer implementation. The trainer derives from the Orbit `StandardTrainer` class. """ from typing import Union import gin import orbit import tensorflow as tf from official.modeling import optimization from official.modeling.multitask import base_model from official.modeling.multitask import multitask @gin.configurable class MultiTaskBaseTrainer(orbit.StandardTrainer): """Multitask base trainer.""" def __init__(self, multi_task: multitask.MultiTask, multi_task_model: Union[tf.keras.Model, base_model.MultiTaskBaseModel], optimizer: tf.optimizers.Optimizer, trainer_options=None, train_datasets=None): self._strategy = tf.distribute.get_strategy() self._multi_task = multi_task self._multi_task_model = multi_task_model self._optimizer = optimizer self._training_losses = None self._training_metrics = None self._global_step = orbit.utils.create_global_step() # Creates a shadow copy of the weights to store weights moving average. if isinstance(self._optimizer, optimization.ExponentialMovingAverage ) and not self._optimizer.has_shadow_copy: self._optimizer.shadow_copy(multi_task_model) if hasattr(self.multi_task_model, "checkpoint_items"): checkpoint_items = self.multi_task_model.checkpoint_items else: checkpoint_items = {} self._checkpoint = tf.train.Checkpoint( model=self.multi_task_model, optimizer=self.optimizer, global_step=self.global_step, **checkpoint_items) if train_datasets is None: train_datasets = {} for name, task in self.multi_task.tasks.items(): train_datasets[name] = orbit.utils.make_distributed_dataset( self.strategy, task.build_inputs, task.task_config.train_data) super().__init__( train_dataset=train_datasets, options=trainer_options or orbit.StandardTrainerOptions()) def train_loop_begin(self): """Clean up states that hold losses and metrics.""" for _, train_loss_metric in self.training_losses.items(): train_loss_metric.reset_states() for _, metrics in self.training_metrics.items(): for metric in metrics: metric.reset_states() def train_loop_end(self): """Record loss and metric values per task.""" result = {} for task_name, loss in self.training_losses.items(): result[task_name] = {loss.name: loss.result()} for task_name, task_metrics in self.training_metrics.items(): result[task_name].update( {metric.name: metric.result() for metric in task_metrics}) # Note that, the learning rate schedule is managed by the keras optimizer # internally, which respects the number of backward pass as `iterations`. # The learning rate schedule does not follow the trainer logical global # step of multiple tasks. if callable(self.optimizer.learning_rate): result["learning_rate"] = self.optimizer.learning_rate( self.optimizer.iterations) else: result["learning_rate"] = self.optimizer.learning_rate return result @property def checkpoint(self): """Accesses the training checkpoint.""" return self._checkpoint @property def training_losses(self): """Access training loss metric objects for all tasks.""" if self._training_losses is None: # Builds the per-task metrics and losses. # This the total summed training loss of tasks in the joint training. self._training_losses = dict( total_loss=tf.keras.metrics.Mean("training_loss", dtype=tf.float32)) for name in self.multi_task.tasks: self._training_losses[name] = tf.keras.metrics.Mean( "training_loss", dtype=tf.float32) return self._training_losses @property def training_metrics(self): """Access training metric metric objects for all tasks.""" if self._training_metrics is None: # Builds the per-task metrics and losses. self._training_metrics = {} for name, task in self.multi_task.tasks.items(): self._training_metrics[name] = task.build_metrics(training=True) return self._training_metrics @property def strategy(self): return self._strategy @property def multi_task(self): return self._multi_task @property def multi_task_model(self): return self._multi_task_model @property def optimizer(self): return self._optimizer @property def global_step(self): return self._global_step def train_step(self, iterator_map): """The default train step calling the multi-task train step. Args: iterator_map: a dictionary of task names and per-task dataset iterators. """ def step_fn(inputs): losses = self.multi_task.joint_train_step( inputs, multi_task_model=self.multi_task_model, optimizer=self.optimizer, task_metrics=self.training_metrics) for key, loss in losses.items(): self.training_losses[key].update_state(loss) self.strategy.run( step_fn, args=(tf.nest.map_structure(next, iterator_map),)) self.global_step.assign_add(1)
5,846
33.192982
78
py
models
models-master/official/modeling/multitask/interleaving_trainer.py
# Copyright 2023 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. """Multitask trainer that interleaves each task's train step.""" from typing import Union import gin import orbit import tensorflow as tf from official.modeling.multitask import base_model from official.modeling.multitask import base_trainer from official.modeling.multitask import multitask from official.modeling.multitask import task_sampler as sampler @gin.configurable class MultiTaskInterleavingTrainer(base_trainer.MultiTaskBaseTrainer): """MultiTask trainer that interleaves task update.""" def __init__(self, multi_task: multitask.MultiTask, multi_task_model: Union[tf.keras.Model, base_model.MultiTaskBaseModel], optimizer: Union[tf.optimizers.Optimizer, tf.keras.optimizers.experimental.Optimizer, tf.keras.optimizers.legacy.Optimizer], task_sampler: sampler.TaskSampler, trainer_options=None): super().__init__( multi_task=multi_task, multi_task_model=multi_task_model, optimizer=optimizer, trainer_options=trainer_options) self._task_sampler = task_sampler # Build per task train step. def _get_task_step(task_name, task): def step_fn(inputs): if isinstance(self.multi_task_model, base_model.MultiTaskBaseModel): task_model = self.multi_task_model.sub_tasks[task_name] else: task_model = self.multi_task_model task_logs = task.train_step( inputs, model=task_model, optimizer=self.optimizer, metrics=self.training_metrics[task_name]) self.training_losses[task_name].update_state(task_logs[task.loss]) return step_fn self._task_train_step_map = { name: _get_task_step(name, task) for name, task in self.multi_task.tasks.items() } # TODO(haozhangthu): Add taskwise step counter to train_loop_end for logging # on TensorBoard. self._task_step_counters = { name: orbit.utils.create_global_step() for name in self.multi_task.tasks } # If the new Keras optimizer is used, we require all model variables are # created before the training and let the optimizer to create the slot # variable all together. if isinstance(optimizer, tf.keras.optimizers.experimental.Optimizer): multi_task_model.build() optimizer.build(multi_task_model.trainable_variables) def task_step_counter(self, name): return self._task_step_counters[name] def train_step(self, iterator_map): # Sample one task to train according to a multinomial distribution rn = tf.random.stateless_uniform(shape=[], seed=(0, self.global_step)) cumulative_sample_distribution = self._task_sampler.task_cumulative_distribution( self.global_step) # Prepend a [0.0] for indexing convenience. cumulative_sample_distribution = tf.concat( [tf.constant([0.0], dtype=tf.float32), cumulative_sample_distribution], axis=0) for idx, (name, _) in enumerate(self.multi_task.tasks.items()): begin = cumulative_sample_distribution[idx] end = cumulative_sample_distribution[idx + 1] if rn >= begin and rn < end: self._strategy.run( self._task_train_step_map[name], args=(next(iterator_map[name]),)) self.global_step.assign_add(1) self.task_step_counter(name).assign_add(1) def train_loop_end(self): """Record loss and metric values per task.""" result = super().train_loop_end() # Interleaving training does not have a good semantic for `total_loss`. In # fact, it is always zero. To avoid confusion, we filter the `total_loss` # from the result logs. if 'total_loss' in result: result.pop('total_loss') return result
4,448
38.723214
85
py
models
models-master/official/modeling/multitask/multitask.py
# Copyright 2023 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. """Experimental MultiTask base class for multi-task training/evaluation.""" import abc from typing import Dict, List, Optional, Text, Union import tensorflow as tf from official.core import base_task from official.core import config_definitions from official.core import task_factory from official.modeling import optimization from official.modeling.multitask import base_model from official.modeling.multitask import configs from official.modeling.privacy import configs as dp_configs OptimizationConfig = optimization.OptimizationConfig RuntimeConfig = config_definitions.RuntimeConfig DifferentialPrivacyConfig = dp_configs.DifferentialPrivacyConfig class MultiTask(tf.Module, metaclass=abc.ABCMeta): """A multi-task class to manage multiple tasks.""" def __init__(self, tasks: Union[Dict[Text, base_task.Task], List[base_task.Task]], task_weights: Optional[Dict[str, Union[float, int]]] = None, task_eval_steps: Optional[Dict[str, int]] = None, name: Optional[str] = None): """MultiTask initialization. Args: tasks: a list or a flat dict of Task. task_weights: a dict of (task, task weight), task weight can be applied directly during loss summation in a joint backward step, or it can be used to sample task among interleaved backward step. task_eval_steps: a dict of (task, eval steps). name: the instance name of a MultiTask object. """ super().__init__(name=name) if isinstance(tasks, list): self._tasks = {} for task in tasks: if task.name in self._tasks: raise ValueError("Duplicated tasks found, task.name is %s" % task.name) self._tasks[task.name] = task elif isinstance(tasks, dict): self._tasks = tasks else: raise ValueError("The tasks argument has an invalid type: %s" % type(tasks)) self.task_eval_steps = task_eval_steps or {} self._task_weights = task_weights or {} self._task_weights = dict([ (name, self._task_weights.get(name, 1.0)) for name in self.tasks ]) @classmethod def from_config(cls, config: configs.MultiTaskConfig, logging_dir=None): tasks = {} task_eval_steps = {} task_weights = {} for task_routine in config.task_routines: task_name = task_routine.task_name or task_routine.task_config.name tasks[task_name] = task_factory.get_task( task_routine.task_config, logging_dir=logging_dir, name=task_name) task_eval_steps[task_name] = task_routine.eval_steps task_weights[task_name] = task_routine.task_weight return cls( tasks, task_eval_steps=task_eval_steps, task_weights=task_weights) @property def tasks(self): return self._tasks def task_weight(self, task_name): return self._task_weights[task_name] @property def task_weights(self): return self._task_weights @classmethod def create_optimizer(cls, optimizer_config: OptimizationConfig, runtime_config: Optional[RuntimeConfig] = None, dp_config: Optional[DifferentialPrivacyConfig] = None): return base_task.Task.create_optimizer( optimizer_config=optimizer_config, runtime_config=runtime_config, dp_config=dp_config) def joint_train_step(self, task_inputs, multi_task_model: base_model.MultiTaskBaseModel, optimizer: tf.keras.optimizers.Optimizer, task_metrics, **kwargs): """The joint train step. Args: task_inputs: a dictionary of task names and per-task features. multi_task_model: a MultiTaskBaseModel instance. optimizer: a tf.optimizers.Optimizer. task_metrics: a dictionary of task names and per-task metrics. **kwargs: other arguments to pass through. Returns: A dictionary of losses, inculding per-task losses and their weighted sum. """ losses = {} with tf.GradientTape() as tape: total_loss = 0.0 for name, model in multi_task_model.sub_tasks.items(): inputs = task_inputs[name] if isinstance(inputs, tuple) and len(inputs) == 2: features, labels = inputs elif isinstance(inputs, dict): features, labels = inputs, inputs else: raise ValueError("The iterator output is neither a tuple nor a " "dictionary. It is not implemented to support " "such outputs.") outputs = model(features, training=True) task_loss = self.tasks[name].build_losses(labels, outputs) task_weight = self.task_weight(name) total_loss += task_weight * task_loss losses[name] = task_loss self.tasks[name].process_metrics(task_metrics[name], labels, outputs, **kwargs) # Scales loss as the default gradients allreduce performs sum inside # the optimizer. scaled_loss = total_loss / tf.distribute.get_strategy( ).num_replicas_in_sync tvars = multi_task_model.trainable_variables grads = tape.gradient(scaled_loss, tvars) optimizer.apply_gradients(list(zip(grads, tvars))) losses["total_loss"] = total_loss return losses
5,938
38.593333
79
py
models
models-master/official/modeling/multitask/evaluator.py
# Copyright 2023 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. """Multitask Evaluator implementation. The evaluator implements the Orbit `AbstractEvaluator` interface. """ from typing import Dict, List, Optional, Union import gin import orbit import tensorflow as tf from official.core import base_task from official.core import train_utils from official.modeling.multitask import base_model @gin.configurable class MultiTaskEvaluator(orbit.AbstractEvaluator): """Implements the common trainer shared for TensorFlow models.""" def __init__( self, eval_tasks: List[base_task.Task], model: Union[tf.keras.Model, base_model.MultiTaskBaseModel], global_step: Optional[tf.Variable] = None, eval_steps: Optional[Dict[str, int]] = None, checkpoint_exporter: Optional[train_utils.BestCheckpointExporter] = None): """Initialize common trainer for TensorFlow models. Args: eval_tasks: A list of tasks to evaluate. model: tf.keras.Model instance. global_step: the global step variable. eval_steps: a dictionary of steps to run eval keyed by task names. checkpoint_exporter: an object that has the `maybe_export_checkpoint` interface. """ # Gets the current distribution strategy. If not inside any strategy scope, # it gets a single-replica no-op strategy. self._strategy = tf.distribute.get_strategy() self._tasks = eval_tasks self._model = model self._global_step = global_step or orbit.utils.create_global_step() self._checkpoint_exporter = checkpoint_exporter if hasattr(self.model, "checkpoint_items"): checkpoint_items = self.model.checkpoint_items else: checkpoint_items = {} self._checkpoint = tf.train.Checkpoint( model=self.model, global_step=self.global_step, **checkpoint_items) self._validation_losses = None self._validation_metrics = None # Builds per-task datasets. self.eval_datasets = {} self.eval_steps = eval_steps or {} for task in self.tasks: self.eval_datasets[task.name] = orbit.utils.make_distributed_dataset( self.strategy, task.build_inputs, task.task_config.validation_data) # Builds per-task validation loops. def get_function(task_name, task): task_metrics = self.validation_metrics[task_name] task_loss = self.validation_losses[task_name] if isinstance(self.model, base_model.MultiTaskBaseModel): model = self.model.sub_tasks[task_name] else: model = self.model def step_fn(inputs): logs = task.validation_step(inputs, model=model, metrics=task_metrics) task_loss.update_state(logs[task.loss]) return logs @tf.function def eval_step_fn(iterator): distributed_outputs = self.strategy.run(step_fn, args=(next(iterator),)) return tf.nest.map_structure(self.strategy.experimental_local_results, distributed_outputs) return orbit.utils.create_loop_fn(eval_step_fn) self.task_fns = { task.name: get_function(task.name, task) for task in self.tasks } @property def strategy(self): return self._strategy @property def tasks(self): return self._tasks @property def model(self): return self._model @property def global_step(self): return self._global_step @property def validation_losses(self): """Accesses the validation loss metric object.""" if self._validation_losses is None: # Builds the per-task metrics and losses. self._validation_losses = {} for task in self.tasks: self._validation_losses[task.name] = tf.keras.metrics.Mean( "validation_loss", dtype=tf.float32) return self._validation_losses @property def validation_metrics(self): """Accesses all validation metric metric objects.""" if self._validation_metrics is None: # Builds the per-task metrics and losses. self._validation_metrics = {} for task in self.tasks: self._validation_metrics[task.name] = task.build_metrics(training=False) return self._validation_metrics @property def checkpoint(self): """Accesses the training checkpoint.""" return self._checkpoint def evaluate(self, num_steps: tf.Tensor): """Performs evaluation for each `EvalTask`.""" for metric in self.validation_losses.values(): metric.reset_states() for metrics in self.validation_metrics.values(): for metric in metrics: metric.reset_states() results = {} eval_iters = tf.nest.map_structure(iter, self.eval_datasets) for task in self.tasks: outputs = None name = task.name eval_iter = eval_iters[name] task_eval_steps = self.eval_steps.get(name, None) or num_steps outputs = self.task_fns[name]( eval_iter, task_eval_steps, state=outputs, reduce_fn=task.aggregate_logs) task_metrics = self.validation_metrics[name] task_loss = self.validation_losses[name] logs = {} for metric in task_metrics + [task_loss]: logs[metric.name] = metric.result() if outputs: metrics = task.reduce_aggregated_logs( outputs, global_step=self.global_step) logs.update(metrics) results[name] = logs if self._checkpoint_exporter: self._checkpoint_exporter.maybe_export_checkpoint( self.checkpoint, results, self.global_step.numpy()) return results
6,068
32.530387
80
py
models
models-master/official/modeling/multitask/evaluator_test.py
# Copyright 2023 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. """Tests for multitask.evaluator.""" from absl.testing import parameterized import numpy as np import tensorflow as tf from tensorflow.python.distribute import combinations from tensorflow.python.distribute import strategy_combinations from official.core import base_task from official.core import config_definitions as cfg from official.modeling.multitask import evaluator def all_strategy_combinations(): return combinations.combine( distribution=[ strategy_combinations.default_strategy, strategy_combinations.cloud_tpu_strategy, strategy_combinations.one_device_strategy_gpu, ], mode="eager", ) class MockModel(tf.keras.Model): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.dense = tf.keras.layers.Dense(1) def call(self, inputs): print(inputs, type(inputs)) if "y" in inputs: self.add_loss(tf.zeros((1,), dtype=tf.float32)) else: self.add_loss(tf.ones((1,), dtype=tf.float32)) return self.dense(inputs["x"]) class MockTask(base_task.Task): """Mock task object for testing.""" def build_metrics(self, training: bool = True): del training return [tf.keras.metrics.Accuracy(name="acc")] def build_inputs(self, params): def generate_data(_): x = tf.zeros(shape=(2,), dtype=tf.float32) label = tf.zeros([1], dtype=tf.int32) if self.name == "bar": return dict(x=x, y=x), label else: return dict(x=x), label dataset = tf.data.Dataset.range(1) dataset = dataset.repeat() dataset = dataset.map( generate_data, num_parallel_calls=tf.data.experimental.AUTOTUNE) return dataset.prefetch(buffer_size=1).batch(2, drop_remainder=True) def validation_step(self, inputs, model: tf.keras.Model, metrics=None): logs = super().validation_step(inputs, model, metrics) logs["counter"] = tf.ones((1,), dtype=tf.float32) return logs def aggregate_logs(self, state, step_outputs): if state is None: state = {} for key, value in step_outputs.items(): if key not in state: state[key] = [] state[key].append( np.concatenate([np.expand_dims(v.numpy(), axis=0) for v in value])) return state def reduce_aggregated_logs(self, aggregated_logs, global_step=None): for k, v in aggregated_logs.items(): aggregated_logs[k] = np.sum(np.stack(v, axis=0)) return aggregated_logs class EvaluatorTest(tf.test.TestCase, parameterized.TestCase): @combinations.generate(all_strategy_combinations()) def test_multitask_evaluator(self, distribution): with distribution.scope(): tasks = [ MockTask(params=cfg.TaskConfig(), name="bar"), MockTask(params=cfg.TaskConfig(), name="foo") ] model = MockModel() test_evaluator = evaluator.MultiTaskEvaluator( eval_tasks=tasks, model=model) results = test_evaluator.evaluate(tf.convert_to_tensor(1, dtype=tf.int32)) self.assertContainsSubset(["validation_loss", "acc"], results["bar"].keys()) self.assertContainsSubset(["validation_loss", "acc"], results["foo"].keys()) self.assertEqual(results["bar"]["validation_loss"], 0.0) self.assertEqual(results["foo"]["validation_loss"], 1.0) @combinations.generate(all_strategy_combinations()) def test_multitask_evaluator_numpy_metrics(self, distribution): with distribution.scope(): tasks = [ MockTask(params=cfg.TaskConfig(), name="bar"), MockTask(params=cfg.TaskConfig(), name="foo") ] model = MockModel() test_evaluator = evaluator.MultiTaskEvaluator( eval_tasks=tasks, model=model) results = test_evaluator.evaluate(tf.convert_to_tensor(5, dtype=tf.int32)) self.assertEqual(results["bar"]["counter"], 5. * distribution.num_replicas_in_sync) self.assertEqual(results["foo"]["counter"], 5. * distribution.num_replicas_in_sync) if __name__ == "__main__": tf.test.main()
4,633
33.58209
80
py
models
models-master/official/modeling/multitask/train_lib.py
# Copyright 2023 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. """Multitask training driver library.""" # pytype: disable=attribute-error import os from typing import Any, List, Mapping, Optional, Tuple, Union from absl import logging import orbit import tensorflow as tf from official.core import base_task from official.core import base_trainer as core_lib from official.core import train_utils from official.modeling.multitask import base_model from official.modeling.multitask import base_trainer from official.modeling.multitask import configs from official.modeling.multitask import evaluator as evaluator_lib from official.modeling.multitask import interleaving_trainer from official.modeling.multitask import multitask from official.modeling.multitask import task_sampler TRAINERS = { 'interleaving': interleaving_trainer.MultiTaskInterleavingTrainer, 'joint': base_trainer.MultiTaskBaseTrainer } def run_experiment( *, distribution_strategy: tf.distribute.Strategy, task: multitask.MultiTask, model: base_model.MultiTaskBaseModel, mode: str, params: configs.MultiTaskExperimentConfig, model_dir: str, run_post_eval: bool = False, trainer: base_trainer.MultiTaskBaseTrainer = None, best_ckpt_exporter_creator: Optional[Any] = train_utils .maybe_create_best_ckpt_exporter ) -> Union[base_model.MultiTaskBaseModel, Tuple[base_model.MultiTaskBaseModel, Mapping[Any, Any]]]: """Runs train/eval configured by the experiment params. Args: distribution_strategy: A distribution distribution_strategy. task: A MultiTaskTask instance. model: A MultiTaskBaseModel instance. mode: A 'str', specifying the mode. Can be 'train', 'eval', 'train_and_eval' or 'continuous_eval'. params: ExperimentConfig instance. model_dir: A 'str', a path to store model checkpoints and summaries. run_post_eval: Whether to run post eval once after training, metrics logs are returned. trainer: (optional) A multi-task trainer to use. If none is provided, a default one will be created based on `params`. best_ckpt_exporter_creator: A functor for creating best checkpoint exporter. Returns: model: `base_model.MultiTaskBaseModel` instance. """ is_training = 'train' in mode is_eval = 'eval' in mode with distribution_strategy.scope(): optimizer = train_utils.create_optimizer(task, params) kwargs = dict(multi_task=task, multi_task_model=model, optimizer=optimizer) if params.trainer.trainer_type == 'interleaving': sampler = task_sampler.get_task_sampler(params.trainer.task_sampler, task.task_weights) kwargs.update(dict(task_sampler=sampler)) if trainer is None: trainer = TRAINERS[params.trainer.trainer_type]( **kwargs) if is_training else None if is_eval: eval_steps = task.task_eval_steps evaluator = evaluator_lib.MultiTaskEvaluator( eval_tasks=task.tasks.values(), model=model, eval_steps=eval_steps, global_step=trainer.global_step if is_training else None, checkpoint_exporter=best_ckpt_exporter_creator(params, model_dir)) else: evaluator = None if trainer: checkpoint = trainer.checkpoint global_step = trainer.global_step else: checkpoint = evaluator.checkpoint global_step = evaluator.global_step checkpoint_manager = tf.train.CheckpointManager( checkpoint, directory=model_dir, max_to_keep=params.trainer.max_to_keep, step_counter=global_step, checkpoint_interval=params.trainer.checkpoint_interval, init_fn=model.initialize) controller = orbit.Controller( strategy=distribution_strategy, trainer=trainer, evaluator=evaluator, global_step=global_step, steps_per_loop=params.trainer.steps_per_loop, checkpoint_manager=checkpoint_manager, summary_dir=os.path.join(model_dir, 'train'), eval_summary_dir=os.path.join(model_dir, 'validation'), summary_interval=params.trainer.summary_interval) logging.info('Starts to execute mode: %s', mode) with distribution_strategy.scope(): if mode == 'train': controller.train(steps=params.trainer.train_steps) elif mode == 'train_and_eval': controller.train_and_evaluate( train_steps=params.trainer.train_steps, eval_steps=params.trainer.validation_steps, eval_interval=params.trainer.validation_interval) elif mode == 'eval': controller.evaluate(steps=params.trainer.validation_steps) elif mode == 'continuous_eval': def timeout_fn(): if evaluator.global_step.numpy() >= params.trainer.train_steps: return True return False controller.evaluate_continuously( steps=params.trainer.validation_steps, timeout=params.trainer.continuous_eval_timeout, timeout_fn=timeout_fn) else: raise NotImplementedError('The mode is not implemented: %s' % mode) if run_post_eval: return model, evaluator.evaluate( tf.convert_to_tensor(params.trainer.validation_steps)) # pytype: disable=bad-return-type # typed-keras else: return model def run_experiment_with_multitask_eval( *, distribution_strategy: tf.distribute.Strategy, train_task: base_task.Task, eval_tasks: List[base_task.Task], mode: str, params: configs.MultiEvalExperimentConfig, model_dir: str, run_post_eval: bool = False, save_summary: bool = True, trainer: Optional[core_lib.Trainer] = None, best_ckpt_exporter_creator: Optional[Any] = train_utils .maybe_create_best_ckpt_exporter, ) -> Tuple[Any, Any]: """Runs train/eval configured by the experiment params. Args: distribution_strategy: A distribution distribution_strategy. train_task: A base_task.Task instance. eval_tasks: A list of evaluation tasks. mode: A 'str', specifying the mode. Can be 'train', 'eval', 'train_and_eval' or 'continuous_eval'. params: MultiEvalExperimentConfig instance. model_dir: A 'str', a path to store model checkpoints and summaries. run_post_eval: Whether to run post eval once after training, metrics logs are returned. save_summary: Whether to save train and validation summary. trainer: the core_lib.Trainer instance. It should be created within the strategy.scope(). If not provided, an instance will be created by default if `mode` contains 'train'. best_ckpt_exporter_creator: A functor for creating best checkpoint exporter. Returns: model: `tf.keras.Model` instance. """ is_training = 'train' in mode is_eval = 'eval' in mode with distribution_strategy.scope(): if is_training: trainer = trainer or core_lib.Trainer( config=params, task=train_task, model=train_task.build_model(), optimizer=train_utils.create_optimizer(train_task, params), train=True, evaluate=False) else: trainer = None # Build the model or fetch the pre-cached one (which could be either # multi-task model or single task model). model = None if trainer is None: if isinstance(train_task, multitask.MultiTask): model = train_task.build_multitask_model() else: model = train_task.build_model() else: if isinstance(trainer, base_trainer.MultiTaskBaseTrainer): model = trainer.multi_task_model else: model = trainer.model if is_eval: eval_steps = dict([(task_routine.task_config.name, task_routine.eval_steps) for task_routine in params.eval_tasks]) evaluator = evaluator_lib.MultiTaskEvaluator( eval_tasks=eval_tasks, model=model, global_step=trainer.global_step if is_training else None, eval_steps=eval_steps, checkpoint_exporter=best_ckpt_exporter_creator(params, model_dir)) else: evaluator = None if trainer: checkpoint = trainer.checkpoint global_step = trainer.global_step else: checkpoint = evaluator.checkpoint global_step = evaluator.global_step checkpoint_manager = tf.train.CheckpointManager( checkpoint, directory=model_dir, max_to_keep=params.trainer.max_to_keep, step_counter=global_step, checkpoint_interval=params.trainer.checkpoint_interval, init_fn=trainer.initialize if trainer else None) controller = orbit.Controller( strategy=distribution_strategy, trainer=trainer, evaluator=evaluator, global_step=global_step, steps_per_loop=params.trainer.steps_per_loop, checkpoint_manager=checkpoint_manager, summary_dir=os.path.join(model_dir, 'train') if save_summary else None, eval_summary_dir=os.path.join(model_dir, 'validation') if (save_summary) else None, summary_interval=params.trainer.summary_interval if (save_summary) else None) logging.info('Starts to execute mode: %s', mode) with distribution_strategy.scope(): if mode == 'train': controller.train(steps=params.trainer.train_steps) elif mode == 'train_and_eval': controller.train_and_evaluate( train_steps=params.trainer.train_steps, eval_steps=params.trainer.validation_steps, eval_interval=params.trainer.validation_interval) elif mode == 'eval': controller.evaluate(steps=params.trainer.validation_steps) elif mode == 'continuous_eval': def timeout_fn(): if evaluator.global_step.numpy() >= params.trainer.train_steps: return True return False controller.evaluate_continuously( steps=params.trainer.validation_steps, timeout=params.trainer.continuous_eval_timeout, timeout_fn=timeout_fn) else: raise NotImplementedError('The mode is not implemented: %s' % mode) if run_post_eval: return model, evaluator.evaluate( tf.convert_to_tensor(params.trainer.validation_steps)) # pytype: disable=bad-return-type # typed-keras else: return model, {} # pytype: disable=bad-return-type # typed-keras
10,832
36.484429
114
py
models
models-master/official/modeling/multitask/base_trainer_test.py
# Copyright 2023 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. """Tests for multitask.base_trainer.""" from absl.testing import parameterized import tensorflow as tf from tensorflow.python.distribute import combinations from tensorflow.python.distribute import strategy_combinations from official.modeling.multitask import base_trainer from official.modeling.multitask import configs from official.modeling.multitask import multitask from official.modeling.multitask import test_utils def all_strategy_combinations(): return combinations.combine( distribution=[ strategy_combinations.default_strategy, strategy_combinations.cloud_tpu_strategy, strategy_combinations.one_device_strategy_gpu, ], mode="eager", ) class BaseTrainerTest(tf.test.TestCase, parameterized.TestCase): @combinations.generate(all_strategy_combinations()) def test_multitask_joint_trainer(self, distribution): with distribution.scope(): tasks = [ test_utils.MockFooTask(params=test_utils.FooConfig(), name="foo"), test_utils.MockBarTask(params=test_utils.BarConfig(), name="bar") ] task_weights = {"foo": 1.0, "bar": 1.0} test_multitask = multitask.MultiTask( tasks=tasks, task_weights=task_weights) test_optimizer = tf.keras.optimizers.SGD(0.1) model = test_utils.MockMultiTaskModel() test_trainer = base_trainer.MultiTaskBaseTrainer( multi_task=test_multitask, multi_task_model=model, optimizer=test_optimizer) results = test_trainer.train(tf.convert_to_tensor(5, dtype=tf.int32)) self.assertContainsSubset(["training_loss", "bar_acc"], results["bar"].keys()) self.assertContainsSubset(["training_loss", "foo_acc"], results["foo"].keys()) def test_trainer_with_configs(self): config = configs.MultiTaskConfig( task_routines=(configs.TaskRoutine( task_name="foo", task_config=test_utils.FooConfig(), task_weight=0.5), configs.TaskRoutine( task_name="bar", task_config=test_utils.BarConfig(), task_weight=0.5))) test_multitask = multitask.MultiTask.from_config(config) test_optimizer = tf.keras.optimizers.SGD(0.1) model = test_utils.MockMultiTaskModel() test_trainer = base_trainer.MultiTaskBaseTrainer( multi_task=test_multitask, multi_task_model=model, optimizer=test_optimizer) results = test_trainer.train(tf.convert_to_tensor(5, dtype=tf.int32)) self.assertContainsSubset(["training_loss", "bar_acc"], results["bar"].keys()) self.assertContainsSubset(["training_loss", "foo_acc"], results["foo"].keys()) self.assertEqual(test_multitask.task_weight("foo"), 0.5) self.assertEqual(test_trainer.global_step.numpy(), 5) self.assertIn("learning_rate", results) if __name__ == "__main__": tf.test.main()
3,653
39.153846
76
py
models
models-master/official/modeling/multitask/interleaving_trainer_test.py
# Copyright 2023 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. """Tests for multitask.interleaving_trainer.""" from absl.testing import parameterized import tensorflow as tf from tensorflow.python.distribute import combinations from tensorflow.python.distribute import strategy_combinations from official.modeling.multitask import configs from official.modeling.multitask import interleaving_trainer from official.modeling.multitask import multitask from official.modeling.multitask import task_sampler from official.modeling.multitask import test_utils def all_strategy_combinations(): return combinations.combine( distribution=[ strategy_combinations.default_strategy, strategy_combinations.cloud_tpu_strategy, strategy_combinations.one_device_strategy_gpu, ], mode="eager", ) class InterleavingTrainerTest(tf.test.TestCase, parameterized.TestCase): @combinations.generate(all_strategy_combinations()) def test_multitask_interleaving_trainer(self, distribution): with distribution.scope(): tasks = [ test_utils.MockFooTask(params=test_utils.FooConfig(), name="foo"), test_utils.MockBarTask(params=test_utils.BarConfig(), name="bar") ] test_multitask = multitask.MultiTask(tasks=tasks) test_optimizer = tf.keras.optimizers.SGD(0.1) model = test_utils.MockMultiTaskModel() sampler = task_sampler.UniformTaskSampler( task_weights=test_multitask.task_weights) test_trainer = interleaving_trainer.MultiTaskInterleavingTrainer( multi_task=test_multitask, multi_task_model=model, optimizer=test_optimizer, task_sampler=sampler) results = test_trainer.train(tf.convert_to_tensor(5, dtype=tf.int32)) self.assertContainsSubset(["training_loss", "bar_acc"], results["bar"].keys()) self.assertContainsSubset(["training_loss", "foo_acc"], results["foo"].keys()) self.assertNotIn("total_loss", results) @combinations.generate(all_strategy_combinations()) def test_trainer_with_configs(self, distribution): config = configs.MultiTaskConfig( task_routines=(configs.TaskRoutine( task_name="foo", task_config=test_utils.FooConfig(), task_weight=3.0), configs.TaskRoutine( task_name="bar", task_config=test_utils.BarConfig(), task_weight=1.0))) with distribution.scope(): test_multitask = multitask.MultiTask.from_config(config) test_optimizer = tf.keras.optimizers.SGD(0.1) model = test_utils.MockMultiTaskModel() num_step = 1000 sampler = task_sampler.AnnealingTaskSampler( task_weights=test_multitask.task_weights, steps_per_epoch=num_step/5, total_steps=num_step) test_trainer = interleaving_trainer.MultiTaskInterleavingTrainer( multi_task=test_multitask, multi_task_model=model, optimizer=test_optimizer, task_sampler=sampler) results = test_trainer.train(tf.convert_to_tensor(num_step, dtype=tf.int32)) self.assertContainsSubset(["training_loss", "bar_acc"], results["bar"].keys()) self.assertContainsSubset(["training_loss", "foo_acc"], results["foo"].keys()) self.assertEqual(test_trainer.global_step.numpy(), num_step) bar_sampled_step = test_trainer.task_step_counter("bar").numpy() foo_sampled_step = test_trainer.task_step_counter("foo").numpy() self.assertEqual(bar_sampled_step + foo_sampled_step, num_step) if __name__ == "__main__": tf.test.main()
4,295
40.708738
80
py
models
models-master/official/modeling/multitask/test_utils.py
# Copyright 2023 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. """Testing utils for mock models and tasks.""" from typing import Dict, Text import tensorflow as tf from official.core import base_task from official.core import config_definitions as cfg from official.core import task_factory from official.modeling.multitask import base_model class MockFooModel(tf.keras.Model): """A mock model can consume 'foo' and 'bar' inputs.""" def __init__(self, shared_layer, *args, **kwargs): super().__init__(*args, **kwargs) self._share_layer = shared_layer self._foo_specific_layer = tf.keras.layers.Dense(1) self.inputs = {"foo": tf.keras.Input(shape=(2,), dtype=tf.float32), "bar": tf.keras.Input(shape=(2,), dtype=tf.float32)} def call(self, inputs): # pytype: disable=signature-mismatch # overriding-parameter-count-checks self.add_loss(tf.zeros((1,), dtype=tf.float32)) if "foo" in inputs: input_tensor = inputs["foo"] else: input_tensor = inputs["bar"] return self._foo_specific_layer(self._share_layer(input_tensor)) class MockBarModel(tf.keras.Model): """A mock model can only consume 'bar' inputs.""" def __init__(self, shared_layer, *args, **kwargs): super().__init__(*args, **kwargs) self._share_layer = shared_layer self._bar_specific_layer = tf.keras.layers.Dense(1) self.inputs = {"bar": tf.keras.Input(shape=(2,), dtype=tf.float32)} def call(self, inputs): # pytype: disable=signature-mismatch # overriding-parameter-count-checks self.add_loss(tf.zeros((2,), dtype=tf.float32)) return self._bar_specific_layer(self._share_layer(inputs["bar"])) class MockMultiTaskModel(base_model.MultiTaskBaseModel): def __init__(self, *args, **kwargs): self._shared_dense = tf.keras.layers.Dense(1) super().__init__(*args, **kwargs) def _instantiate_sub_tasks(self) -> Dict[Text, tf.keras.Model]: return { "foo": MockFooModel(self._shared_dense), "bar": MockBarModel(self._shared_dense) } def mock_data(feature_name): """Mock dataset function.""" def _generate_data(_): x = tf.zeros(shape=(2,), dtype=tf.float32) label = tf.zeros([1], dtype=tf.int32) return {feature_name: x}, label dataset = tf.data.Dataset.range(1) dataset = dataset.repeat() dataset = dataset.map( _generate_data, num_parallel_calls=tf.data.experimental.AUTOTUNE) return dataset.prefetch(buffer_size=1).batch(2, drop_remainder=True) class FooConfig(cfg.TaskConfig): pass class BarConfig(cfg.TaskConfig): pass @task_factory.register_task_cls(FooConfig) class MockFooTask(base_task.Task): """Mock foo task object for testing.""" def build_metrics(self, training: bool = True): del training return [tf.keras.metrics.Accuracy(name="foo_acc")] def build_inputs(self, params): return mock_data("foo") def build_model(self) -> tf.keras.Model: return MockFooModel(shared_layer=tf.keras.layers.Dense(1)) def build_losses(self, labels, model_outputs, aux_losses=None) -> tf.Tensor: loss = tf.keras.losses.mean_squared_error(labels, model_outputs) if aux_losses: loss += tf.add_n(aux_losses) return tf.reduce_mean(loss) @task_factory.register_task_cls(BarConfig) class MockBarTask(base_task.Task): """Mock bar task object for testing.""" def build_metrics(self, training: bool = True): del training return [tf.keras.metrics.Accuracy(name="bar_acc")] def build_inputs(self, params): return mock_data("bar") def build_losses(self, labels, model_outputs, aux_losses=None) -> tf.Tensor: loss = tf.keras.losses.mean_squared_error(labels, model_outputs) if aux_losses: loss += tf.add_n(aux_losses) return tf.reduce_mean(loss)
4,305
32.123077
100
py
models
models-master/official/modeling/activations/gelu.py
# Copyright 2023 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. """Gaussian error linear unit.""" import tensorflow as tf @tf.keras.utils.register_keras_serializable(package='Text') def gelu(x): """Gaussian Error Linear Unit. This is a smoother version of the RELU. Original paper: https://arxiv.org/abs/1606.08415 Args: x: float Tensor to perform activation. Returns: `x` with the GELU activation applied. """ return tf.keras.activations.gelu(x, approximate=True)
1,037
30.454545
74
py
models
models-master/official/modeling/activations/swish.py
# Copyright 2023 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. """Customized Swish activation.""" import tensorflow as tf @tf.keras.utils.register_keras_serializable(package='Text') def simple_swish(features): """Computes the Swish activation function. The tf.nn.swish operation uses a custom gradient to reduce memory usage. Since saving custom gradients in SavedModel is currently not supported, and one would not be able to use an exported TF-Hub module for fine-tuning, we provide this wrapper that can allow to select whether to use the native TensorFlow swish operation, or whether to use a customized operation that has uses default TensorFlow gradient computation. Args: features: A `Tensor` representing preactivation values. Returns: The activation value. """ features = tf.convert_to_tensor(features) return features * tf.nn.sigmoid(features) @tf.keras.utils.register_keras_serializable(package='Text') def hard_swish(features): """Computes a hard version of the swish function. This operation can be used to reduce computational cost and improve quantization for edge devices. Args: features: A `Tensor` representing preactivation values. Returns: The activation value. """ features = tf.convert_to_tensor(features) fdtype = features.dtype return features * tf.nn.relu6(features + tf.cast(3., fdtype)) * (1. / 6.) @tf.keras.utils.register_keras_serializable(package='Text') def identity(features): """Computes the identity function. Useful for helping in quantization. Args: features: A `Tensor` representing preactivation values. Returns: The activation value. """ features = tf.convert_to_tensor(features) return tf.identity(features)
2,291
30.39726
77
py
models
models-master/official/modeling/activations/relu.py
# Copyright 2023 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. """Customized Relu activation.""" import tensorflow as tf @tf.keras.utils.register_keras_serializable(package='Text') def relu6(features): """Computes the Relu6 activation function. Args: features: A `Tensor` representing preactivation values. Returns: The activation value. """ features = tf.convert_to_tensor(features) return tf.nn.relu6(features)
984
29.78125
74
py
models
models-master/official/modeling/activations/mish.py
# Copyright 2023 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. """Self Regularized Non-Monotonic Activation Function.""" import tensorflow as tf @tf.keras.utils.register_keras_serializable(package='Text') def mish(x) -> tf.Tensor: """Mish activation function. Mish: A Self Regularized Non-Monotonic Activation Function https://arxiv.org/pdf/1908.08681.pdf Mish(x) = x * tanh(ln(1+e^x)) Args: x: A `Tensor` representing preactivation values. Returns: The activation value. """ x = tf.convert_to_tensor(x) return x * tf.tanh(tf.nn.softplus(x))
1,130
29.567568
74
py
models
models-master/official/modeling/activations/sigmoid.py
# Copyright 2023 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. """Customized Sigmoid activation.""" import tensorflow as tf @tf.keras.utils.register_keras_serializable(package='Text') def hard_sigmoid(features): """Computes the hard sigmoid activation function. Args: features: A `Tensor` representing preactivation values. Returns: The activation value. """ features = tf.convert_to_tensor(features) return tf.nn.relu6(features + tf.cast(3., features.dtype)) * 0.16667
1,041
31.5625
74
py
models
models-master/official/legacy/xlnet/optimization.py
# Copyright 2023 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. """Functions and classes related to optimization (weight updates).""" from absl import logging import tensorflow as tf from official.nlp import optimization class WarmUp(tf.keras.optimizers.schedules.LearningRateSchedule): """Applys a warmup schedule on a given learning rate decay schedule.""" def __init__(self, initial_learning_rate, decay_schedule_fn, warmup_steps, power=1.0, name=None): super(WarmUp, self).__init__() self.initial_learning_rate = initial_learning_rate self.warmup_steps = warmup_steps self.power = power self.decay_schedule_fn = decay_schedule_fn self.name = name def __call__(self, step): with tf.name_scope(self.name or "WarmUp") as name: # Implements polynomial warmup. i.e., if global_step < warmup_steps, the # learning rate will be `global_step/num_warmup_steps * init_lr`. global_step_float = tf.cast(step, tf.float32) warmup_steps_float = tf.cast(self.warmup_steps, tf.float32) warmup_percent_done = global_step_float / warmup_steps_float warmup_learning_rate = ( self.initial_learning_rate * tf.math.pow(warmup_percent_done, self.power)) return tf.cond( global_step_float < warmup_steps_float, lambda: warmup_learning_rate, lambda: self.decay_schedule_fn(step - self.warmup_steps), name=name) def get_config(self): return { "initial_learning_rate": self.initial_learning_rate, "decay_schedule_fn": self.decay_schedule_fn, "warmup_steps": self.warmup_steps, "power": self.power, "name": self.name } def create_optimizer(init_lr, num_train_steps, num_warmup_steps, min_lr_ratio=0.0, adam_epsilon=1e-8, weight_decay_rate=0.0): """Creates an optimizer with learning rate schedule.""" # Implements linear decay of the learning rate. learning_rate_fn = tf.keras.optimizers.schedules.PolynomialDecay( initial_learning_rate=init_lr, decay_steps=num_train_steps - num_warmup_steps, end_learning_rate=init_lr * min_lr_ratio) if num_warmup_steps: learning_rate_fn = WarmUp( initial_learning_rate=init_lr, decay_schedule_fn=learning_rate_fn, warmup_steps=num_warmup_steps) if weight_decay_rate > 0.0: logging.info( "Using AdamWeightDecay with adam_epsilon=%.9f weight_decay_rate=%.3f", adam_epsilon, weight_decay_rate) optimizer = optimization.AdamWeightDecay( learning_rate=learning_rate_fn, weight_decay_rate=weight_decay_rate, beta_1=0.9, beta_2=0.999, epsilon=adam_epsilon, exclude_from_weight_decay=["LayerNorm", "layer_norm", "bias"], include_in_weight_decay=["r_s_bias", "r_r_bias", "r_w_bias"]) else: logging.info("Using Adam with adam_epsilon=%.9f", (adam_epsilon)) optimizer = tf.keras.optimizers.legacy.Adam( learning_rate=learning_rate_fn, epsilon=adam_epsilon) return optimizer, learning_rate_fn
3,769
37.080808
78
py
models
models-master/official/legacy/xlnet/run_squad.py
# Copyright 2023 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. """XLNet SQUAD finetuning runner in tf2.0.""" import functools import json import os import pickle # Import libraries from absl import app from absl import flags from absl import logging import tensorflow as tf # pylint: disable=unused-import import sentencepiece as spm from official.common import distribute_utils from official.legacy.xlnet import common_flags from official.legacy.xlnet import data_utils from official.legacy.xlnet import optimization from official.legacy.xlnet import squad_utils from official.legacy.xlnet import training_utils from official.legacy.xlnet import xlnet_config from official.legacy.xlnet import xlnet_modeling as modeling flags.DEFINE_string( "test_feature_path", default=None, help="Path to feature of test set.") flags.DEFINE_integer("query_len", default=64, help="Max query length.") flags.DEFINE_integer("start_n_top", default=5, help="Beam size for span start.") flags.DEFINE_integer("end_n_top", default=5, help="Beam size for span end.") flags.DEFINE_string( "predict_dir", default=None, help="Path to write predictions.") flags.DEFINE_string( "predict_file", default=None, help="Path to json file of test set.") flags.DEFINE_integer( "n_best_size", default=5, help="n best size for predictions.") flags.DEFINE_integer("max_answer_length", default=64, help="Max answer length.") # Data preprocessing config flags.DEFINE_string( "spiece_model_file", default=None, help="Sentence Piece model path.") flags.DEFINE_integer("max_seq_length", default=512, help="Max sequence length.") flags.DEFINE_integer("max_query_length", default=64, help="Max query length.") flags.DEFINE_integer("doc_stride", default=128, help="Doc stride.") FLAGS = flags.FLAGS class InputFeatures(object): """A single set of features of data.""" def __init__(self, unique_id, example_index, doc_span_index, tok_start_to_orig_index, tok_end_to_orig_index, token_is_max_context, input_ids, input_mask, p_mask, segment_ids, paragraph_len, cls_index, start_position=None, end_position=None, is_impossible=None): self.unique_id = unique_id self.example_index = example_index self.doc_span_index = doc_span_index self.tok_start_to_orig_index = tok_start_to_orig_index self.tok_end_to_orig_index = tok_end_to_orig_index self.token_is_max_context = token_is_max_context self.input_ids = input_ids self.input_mask = input_mask self.p_mask = p_mask self.segment_ids = segment_ids self.paragraph_len = paragraph_len self.cls_index = cls_index self.start_position = start_position self.end_position = end_position self.is_impossible = is_impossible # pylint: disable=unused-argument def run_evaluation(strategy, test_input_fn, eval_examples, eval_features, original_data, eval_steps, input_meta_data, model, current_step, eval_summary_writer): """Run evaluation for SQUAD task. Args: strategy: distribution strategy. test_input_fn: input function for evaluation data. eval_examples: tf.Examples of the evaluation set. eval_features: Feature objects of the evaluation set. original_data: The original json data for the evaluation set. eval_steps: total number of evaluation steps. input_meta_data: input meta data. model: keras model object. current_step: current training step. eval_summary_writer: summary writer used to record evaluation metrics. Returns: A float metric, F1 score. """ def _test_step_fn(inputs): """Replicated validation step.""" inputs["mems"] = None res = model(inputs, training=False) return res, inputs["unique_ids"] @tf.function def _run_evaluation(test_iterator): """Runs validation steps.""" res, unique_ids = strategy.run( _test_step_fn, args=(next(test_iterator),)) return res, unique_ids test_iterator = data_utils.get_input_iterator(test_input_fn, strategy) cur_results = [] for _ in range(eval_steps): results, unique_ids = _run_evaluation(test_iterator) unique_ids = strategy.experimental_local_results(unique_ids) for result_key in results: results[result_key] = ( strategy.experimental_local_results(results[result_key])) for core_i in range(strategy.num_replicas_in_sync): bsz = int(input_meta_data["test_batch_size"] / strategy.num_replicas_in_sync) for j in range(bsz): result = {} for result_key in results: result[result_key] = results[result_key][core_i].numpy()[j] result["unique_ids"] = unique_ids[core_i].numpy()[j] # We appended a fake example into dev set to make data size can be # divided by test_batch_size. Ignores this fake example during # evaluation. if result["unique_ids"] == 1000012047: continue unique_id = int(result["unique_ids"]) start_top_log_probs = ([ float(x) for x in result["start_top_log_probs"].flat ]) start_top_index = [int(x) for x in result["start_top_index"].flat] end_top_log_probs = ([ float(x) for x in result["end_top_log_probs"].flat ]) end_top_index = [int(x) for x in result["end_top_index"].flat] cls_logits = float(result["cls_logits"].flat[0]) cur_results.append( squad_utils.RawResult( unique_id=unique_id, start_top_log_probs=start_top_log_probs, start_top_index=start_top_index, end_top_log_probs=end_top_log_probs, end_top_index=end_top_index, cls_logits=cls_logits)) if len(cur_results) % 1000 == 0: logging.info("Processing example: %d", len(cur_results)) output_prediction_file = os.path.join(input_meta_data["predict_dir"], "predictions.json") output_nbest_file = os.path.join(input_meta_data["predict_dir"], "nbest_predictions.json") output_null_log_odds_file = os.path.join(input_meta_data["predict_dir"], "null_odds.json") results = squad_utils.write_predictions( eval_examples, eval_features, cur_results, input_meta_data["n_best_size"], input_meta_data["max_answer_length"], output_prediction_file, output_nbest_file, output_null_log_odds_file, original_data, input_meta_data["start_n_top"], input_meta_data["end_n_top"]) # Log current results. log_str = "Result | " for key, val in results.items(): log_str += "{} {} | ".format(key, val) logging.info(log_str) with eval_summary_writer.as_default(): tf.summary.scalar("best_f1", results["best_f1"], step=current_step) tf.summary.scalar("best_exact", results["best_exact"], step=current_step) eval_summary_writer.flush() return results["best_f1"] def get_qaxlnet_model(model_config, run_config, start_n_top, end_n_top): model = modeling.QAXLNetModel( model_config, run_config, start_n_top=start_n_top, end_n_top=end_n_top, name="model") return model def main(unused_argv): del unused_argv strategy = distribute_utils.get_distribution_strategy( distribution_strategy=FLAGS.strategy_type, tpu_address=FLAGS.tpu) if strategy: logging.info("***** Number of cores used : %d", strategy.num_replicas_in_sync) train_input_fn = functools.partial(data_utils.get_squad_input_data, FLAGS.train_batch_size, FLAGS.seq_len, FLAGS.query_len, strategy, True, FLAGS.train_tfrecord_path) test_input_fn = functools.partial(data_utils.get_squad_input_data, FLAGS.test_batch_size, FLAGS.seq_len, FLAGS.query_len, strategy, False, FLAGS.test_tfrecord_path) total_training_steps = FLAGS.train_steps steps_per_loop = FLAGS.iterations eval_steps = int(FLAGS.test_data_size / FLAGS.test_batch_size) optimizer, learning_rate_fn = optimization.create_optimizer( FLAGS.learning_rate, total_training_steps, FLAGS.warmup_steps, adam_epsilon=FLAGS.adam_epsilon) model_config = xlnet_config.XLNetConfig(FLAGS) run_config = xlnet_config.create_run_config(True, False, FLAGS) input_meta_data = {} input_meta_data["start_n_top"] = FLAGS.start_n_top input_meta_data["end_n_top"] = FLAGS.end_n_top input_meta_data["lr_layer_decay_rate"] = FLAGS.lr_layer_decay_rate input_meta_data["predict_dir"] = FLAGS.predict_dir input_meta_data["n_best_size"] = FLAGS.n_best_size input_meta_data["max_answer_length"] = FLAGS.max_answer_length input_meta_data["test_batch_size"] = FLAGS.test_batch_size input_meta_data["batch_size_per_core"] = int(FLAGS.train_batch_size / strategy.num_replicas_in_sync) input_meta_data["mem_len"] = FLAGS.mem_len model_fn = functools.partial(get_qaxlnet_model, model_config, run_config, FLAGS.start_n_top, FLAGS.end_n_top) eval_examples = squad_utils.read_squad_examples( FLAGS.predict_file, is_training=False) if FLAGS.test_feature_path: logging.info("start reading pickle file...") with tf.io.gfile.GFile(FLAGS.test_feature_path, "rb") as f: eval_features = pickle.load(f) logging.info("finishing reading pickle file...") else: sp_model = spm.SentencePieceProcessor() sp_model.LoadFromSerializedProto( tf.io.gfile.GFile(FLAGS.spiece_model_file, "rb").read()) spm_basename = os.path.basename(FLAGS.spiece_model_file) eval_features = squad_utils.create_eval_data( spm_basename, sp_model, eval_examples, FLAGS.max_seq_length, FLAGS.max_query_length, FLAGS.doc_stride, FLAGS.uncased) with tf.io.gfile.GFile(FLAGS.predict_file) as f: original_data = json.load(f)["data"] eval_fn = functools.partial(run_evaluation, strategy, test_input_fn, eval_examples, eval_features, original_data, eval_steps, input_meta_data) training_utils.train( strategy=strategy, model_fn=model_fn, input_meta_data=input_meta_data, eval_fn=eval_fn, metric_fn=None, train_input_fn=train_input_fn, init_checkpoint=FLAGS.init_checkpoint, init_from_transformerxl=FLAGS.init_from_transformerxl, total_training_steps=total_training_steps, steps_per_loop=steps_per_loop, optimizer=optimizer, learning_rate_fn=learning_rate_fn, model_dir=FLAGS.model_dir, save_steps=FLAGS.save_steps) if __name__ == "__main__": app.run(main)
11,597
38.182432
80
py
models
models-master/official/legacy/xlnet/run_classifier.py
# Copyright 2023 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. """XLNet classification finetuning runner in tf2.0.""" import functools # Import libraries from absl import app from absl import flags from absl import logging import numpy as np import tensorflow as tf # pylint: disable=unused-import from official.common import distribute_utils from official.legacy.xlnet import common_flags from official.legacy.xlnet import data_utils from official.legacy.xlnet import optimization from official.legacy.xlnet import training_utils from official.legacy.xlnet import xlnet_config from official.legacy.xlnet import xlnet_modeling as modeling flags.DEFINE_integer("n_class", default=2, help="Number of classes.") flags.DEFINE_string( "summary_type", default="last", help="Method used to summarize a sequence into a vector.") FLAGS = flags.FLAGS def get_classificationxlnet_model(model_config, run_config, n_class, summary_type="last"): model = modeling.ClassificationXLNetModel( model_config, run_config, n_class, summary_type, name="model") return model def run_evaluation(strategy, test_input_fn, eval_steps, model, step, eval_summary_writer=None): """Run evaluation for classification task. Args: strategy: distribution strategy. test_input_fn: input function for evaluation data. eval_steps: total number of evaluation steps. model: keras model object. step: current train step. eval_summary_writer: summary writer used to record evaluation metrics. As there are fake data samples in validation set, we use mask to get rid of them when calculating the accuracy. For the reason that there will be dynamic-shape tensor, we first collect logits, labels and masks from TPU and calculate the accuracy via numpy locally. Returns: A float metric, accuracy. """ def _test_step_fn(inputs): """Replicated validation step.""" inputs["mems"] = None _, logits = model(inputs, training=False) return logits, inputs["label_ids"], inputs["is_real_example"] @tf.function def _run_evaluation(test_iterator): """Runs validation steps.""" logits, labels, masks = strategy.run( _test_step_fn, args=(next(test_iterator),)) return logits, labels, masks test_iterator = data_utils.get_input_iterator(test_input_fn, strategy) correct = 0 total = 0 for _ in range(eval_steps): logits, labels, masks = _run_evaluation(test_iterator) logits = strategy.experimental_local_results(logits) labels = strategy.experimental_local_results(labels) masks = strategy.experimental_local_results(masks) merged_logits = [] merged_labels = [] merged_masks = [] for i in range(strategy.num_replicas_in_sync): merged_logits.append(logits[i].numpy()) merged_labels.append(labels[i].numpy()) merged_masks.append(masks[i].numpy()) merged_logits = np.vstack(np.array(merged_logits)) merged_labels = np.hstack(np.array(merged_labels)) merged_masks = np.hstack(np.array(merged_masks)) real_index = np.where(np.equal(merged_masks, 1)) correct += np.sum( np.equal( np.argmax(merged_logits[real_index], axis=-1), merged_labels[real_index])) total += np.shape(real_index)[-1] accuracy = float(correct) / float(total) logging.info("Train step: %d / acc = %d/%d = %f", step, correct, total, accuracy) if eval_summary_writer: with eval_summary_writer.as_default(): tf.summary.scalar("eval_acc", float(correct) / float(total), step=step) eval_summary_writer.flush() return accuracy def get_metric_fn(): train_acc_metric = tf.keras.metrics.SparseCategoricalAccuracy( "acc", dtype=tf.float32) return train_acc_metric def main(unused_argv): del unused_argv strategy = distribute_utils.get_distribution_strategy( distribution_strategy=FLAGS.strategy_type, tpu_address=FLAGS.tpu) if strategy: logging.info("***** Number of cores used : %d", strategy.num_replicas_in_sync) train_input_fn = functools.partial(data_utils.get_classification_input_data, FLAGS.train_batch_size, FLAGS.seq_len, strategy, True, FLAGS.train_tfrecord_path) test_input_fn = functools.partial(data_utils.get_classification_input_data, FLAGS.test_batch_size, FLAGS.seq_len, strategy, False, FLAGS.test_tfrecord_path) total_training_steps = FLAGS.train_steps steps_per_loop = FLAGS.iterations eval_steps = int(FLAGS.test_data_size / FLAGS.test_batch_size) eval_fn = functools.partial(run_evaluation, strategy, test_input_fn, eval_steps) optimizer, learning_rate_fn = optimization.create_optimizer( FLAGS.learning_rate, total_training_steps, FLAGS.warmup_steps, adam_epsilon=FLAGS.adam_epsilon) model_config = xlnet_config.XLNetConfig(FLAGS) run_config = xlnet_config.create_run_config(True, False, FLAGS) model_fn = functools.partial(get_classificationxlnet_model, model_config, run_config, FLAGS.n_class, FLAGS.summary_type) input_meta_data = {} input_meta_data["d_model"] = FLAGS.d_model input_meta_data["mem_len"] = FLAGS.mem_len input_meta_data["batch_size_per_core"] = int(FLAGS.train_batch_size / strategy.num_replicas_in_sync) input_meta_data["n_layer"] = FLAGS.n_layer input_meta_data["lr_layer_decay_rate"] = FLAGS.lr_layer_decay_rate input_meta_data["n_class"] = FLAGS.n_class training_utils.train( strategy=strategy, model_fn=model_fn, input_meta_data=input_meta_data, eval_fn=eval_fn, metric_fn=get_metric_fn, train_input_fn=train_input_fn, init_checkpoint=FLAGS.init_checkpoint, init_from_transformerxl=FLAGS.init_from_transformerxl, total_training_steps=total_training_steps, steps_per_loop=steps_per_loop, optimizer=optimizer, learning_rate_fn=learning_rate_fn, model_dir=FLAGS.model_dir, save_steps=FLAGS.save_steps) if __name__ == "__main__": app.run(main)
6,976
36.111702
79
py
models
models-master/official/legacy/xlnet/xlnet_modeling.py
# Copyright 2023 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. """Keras layers of XLNet model in TF 2.0.""" import copy import warnings import tensorflow as tf from official.legacy.xlnet import data_utils from official.nlp.modeling import networks def gelu(x): return tf.keras.activations.gelu(x, approximate=True) def _get_initializer(flags): """Get variable initializer.""" if flags.init_method == "uniform": initializer = tf.keras.initializers.RandomUniform( minval=-flags.init_range, maxval=flags.init_range) elif flags.init_method == "normal": initializer = tf.keras.initializers.RandomNormal(stddev=flags.init_std) else: raise ValueError("Initializer {} not supported".format(flags.init_method)) return initializer def rel_shift(x, klen=-1): """Performs relative shift to form the relative attention score.""" x_size = tf.shape(x) x = tf.reshape(x, [x_size[1], x_size[0], x_size[2], x_size[3]]) x = tf.slice(x, [1, 0, 0, 0], [-1, -1, -1, -1]) x = tf.reshape(x, [x_size[0], x_size[1] - 1, x_size[2], x_size[3]]) x = tf.slice(x, [0, 0, 0, 0], [-1, klen, -1, -1]) return x def _create_mask(qlen, mlen, dtype=tf.float32, same_length=False): """Creates attention mask when single-side context allowed only.""" attn_mask = tf.ones([qlen, qlen], dtype=dtype) mask_u = tf.linalg.band_part(attn_mask, 0, -1) mask_dia = tf.linalg.band_part(attn_mask, 0, 0) attn_mask_pad = tf.zeros([qlen, mlen], dtype=dtype) ret = tf.concat([attn_mask_pad, mask_u - mask_dia], 1) if same_length: mask_l = tf.linalg.band_part(attn_mask, -1, 0) ret = tf.concat([ret[:, :qlen] + mask_l - mask_dia, ret[:, qlen:]], 1) return ret def _cache_mem(curr_out, prev_mem, mem_len, reuse_len=None): """cache hidden states into memory.""" if mem_len is None or mem_len == 0: return None else: if reuse_len is not None and reuse_len > 0: curr_out = curr_out[:reuse_len] if prev_mem is None: new_mem = curr_out[-mem_len:] else: new_mem = tf.concat([prev_mem, curr_out], 0)[-mem_len:] return tf.keras.backend.stop_gradient(new_mem) def is_special_none_tensor(tensor): """Checks if a tensor is a special None Tensor.""" return tensor.shape.ndims == 0 and tensor.dtype == tf.int32 @tf.keras.utils.register_keras_serializable(package="Text") class RelativePositionEncoding(tf.keras.layers.Layer): """Creates a relative positional encoding. This layer creates a relative positional encoding as described in "Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context" (https://arxiv.org/abs/1901.02860). Rather than an absolute position embedding as in Transformer, this formulation represents position as the relative distance between tokens using sinusoidal positional embeddings. Note: This layer is currently experimental. Attributes: hidden_size: The dimensionality of the input embeddings. """ def __init__(self, hidden_size, **kwargs): super(RelativePositionEncoding, self).__init__(**kwargs) self._hidden_size = hidden_size self._inv_freq = 1.0 / (10000.0**( tf.range(0, self._hidden_size, 2.0) / self._hidden_size)) def call(self, pos_seq, batch_size=None): """Implements call() for the layer. Args: pos_seq: A 1-D `Tensor` batch_size: The optionally provided batch size that tiles the relative positional encoding. Returns: The relative positional encoding of shape: [len(pos_seq), batch_size, hidden_size] if batch_size is provided, else [len(pos_seq), 1, hidden_size]. """ sinusoid_input = tf.einsum("i,d->id", pos_seq, self._inv_freq) pos_emb = tf.concat([tf.sin(sinusoid_input), tf.cos(sinusoid_input)], -1) pos_emb = pos_emb[:, None, :] if batch_size is not None: pos_emb = tf.tile(pos_emb, [1, batch_size, 1]) return pos_emb class RelativeAttention(tf.keras.layers.Layer): """Core calculations for relative attention.""" def __init__(self, dropout_att, scale): super(RelativeAttention, self).__init__() self.scale = scale self.dropout_att = dropout_att def build(self, unused_input_shapes): """Implements build() for the layer.""" self.attention_probs_dropout = tf.keras.layers.Dropout( rate=self.dropout_att) super(RelativeAttention, self).build(unused_input_shapes) def call(self, q_head, k_head_h, v_head_h, k_head_r, seg_embed, seg_mat, r_w_bias, r_r_bias, r_s_bias, attn_mask): """Implements call() for the layer.""" # content based attention score ac = tf.einsum("ibnd,jbnd->ijbn", q_head + r_w_bias, k_head_h) # position based attention score bd = tf.einsum("ibnd,jbnd->ijbn", q_head + r_r_bias, k_head_r) bd = rel_shift(bd, klen=tf.shape(ac)[1]) # segment-based attention score if seg_mat is None: ef = 0 else: ef = tf.einsum("ibnd,snd->isbn", q_head + r_s_bias, seg_embed) tgt_shape = tf.shape(bd) ef = tf.where( tf.broadcast_to(tf.expand_dims(seg_mat, 3), tgt_shape), tf.broadcast_to(ef[:, 1:, :, :], tgt_shape), tf.broadcast_to(ef[:, :1, :, :], tgt_shape)) # merges attention scores and performs masking attn_score = (ac + bd + ef) * self.scale if attn_mask is not None: attn_score = attn_score - 1e30 * attn_mask # attention probability attn_prob = tf.nn.softmax(attn_score, 1) attn_prob = self.attention_probs_dropout(attn_prob) # attention output attn_vec = tf.einsum("ijbn,jbnd->ibnd", attn_prob, v_head_h) return attn_vec class PositionwiseFF(tf.keras.layers.Layer): """Positionwise feed-forward layer.""" def __init__(self, d_model, d_inner, dropout, kernel_initializer, activation_type, **kwargs): super(PositionwiseFF, self).__init__(**kwargs) self.d_model = d_model self.d_inner = d_inner self.dropout = dropout self.activation_type = activation_type self.kernel_initializer = kernel_initializer def build(self, unused_input_shapes): """Implements build() for the layer.""" if self.activation_type == "relu": activation = tf.nn.relu elif self.activation_type == "gelu": activation = gelu else: raise (ValueError("Unsupported activation type {}".format( self.activation_type))) self.inner_projection_layer = ( tf.keras.layers.Dense( units=self.d_inner, activation=activation, kernel_initializer=self.kernel_initializer, name="layer_1")) self.output_projection_layer = ( tf.keras.layers.Dense( units=self.d_model, kernel_initializer=self.kernel_initializer, name="layer_2")) self.output_dropout = tf.keras.layers.Dropout( rate=self.dropout, name="drop_2") self.output_layer_norm = ( tf.keras.layers.LayerNormalization( name="LayerNorm", axis=-1, epsilon=1e-12)) super(PositionwiseFF, self).build(unused_input_shapes) def call(self, inp): """Implements call() for the layer.""" output = self.inner_projection_layer(inp) output = self.output_projection_layer(output) output = self.output_dropout(output) output = self.output_layer_norm(output + inp) return output class EmbeddingLookup(tf.keras.layers.Layer): """Looks up words embeddings for id tensor.""" def __init__(self, n_token, d_embed, initializer, **kwargs): super(EmbeddingLookup, self).__init__(**kwargs) self.n_token = n_token self.d_embed = d_embed self.initializer = initializer def build(self, unused_input_shapes): """Implements build() for the layer.""" self.lookup_table = self.add_weight( "lookup_table", shape=[self.n_token, self.d_embed], initializer=self.initializer, dtype=self.dtype) super(EmbeddingLookup, self).build(unused_input_shapes) def call(self, inputs): return tf.nn.embedding_lookup(self.lookup_table, inputs) class RelativeMultiheadAttention(tf.keras.layers.Layer): """Multi-head attention with relative embedding.""" def __init__(self, d_model, n_head, d_head, dropout, dropout_att, kernel_initializer, **kwargs): super(RelativeMultiheadAttention, self).__init__(**kwargs) self.d_model = d_model self.n_head = n_head self.d_head = d_head self.dropout = dropout self.dropout_att = dropout_att self.initializer = kernel_initializer def build(self, unused_input_shapes): """Implements build() for the layer.""" self.scale = 1.0 / (self.d_head**0.5) self.output_layer_norm = tf.keras.layers.LayerNormalization( name="LayerNorm", axis=-1, epsilon=1e-12) self.kh_projection_layer = self.add_weight( "k/kernel", shape=[self.d_model, self.n_head, self.d_head], initializer=self.initializer) self.vh_projection_layer = self.add_weight( "v/kernel", shape=[self.d_model, self.n_head, self.d_head], initializer=self.initializer) self.kr_projection_layer = self.add_weight( "r/kernel", shape=[self.d_model, self.n_head, self.d_head], initializer=self.initializer) self.qh_projection_layer = self.add_weight( "q/kernel", shape=[self.d_model, self.n_head, self.d_head], initializer=self.initializer) self.relative_attention_layer = RelativeAttention( dropout_att=self.dropout_att, scale=self.scale) self.proj_o = self.add_weight( "o/kernel", shape=[self.d_model, self.n_head, self.d_head], initializer=self.initializer) self.attention_dropout = tf.keras.layers.Dropout(rate=self.dropout) super(RelativeMultiheadAttention, self).build(unused_input_shapes) def call(self, h, g, r, r_w_bias, r_r_bias, seg_mat, r_s_bias, seg_embed, attn_mask_h, attn_mask_g, mems, target_mapping): """Implements call() for the layer.""" if mems is not None and mems.shape.ndims > 1: cat = tf.concat([mems, h], 0) else: cat = h # content heads q_head_h = tf.einsum("ibh,hnd->ibnd", h, self.qh_projection_layer) k_head_h = tf.einsum("ibh,hnd->ibnd", cat, self.kh_projection_layer) v_head_h = tf.einsum("ibh,hnd->ibnd", cat, self.vh_projection_layer) # positional heads k_head_r = tf.einsum("ibh,hnd->ibnd", r, self.kr_projection_layer) # core attention ops attn_vec_h = self.relative_attention_layer(q_head_h, k_head_h, v_head_h, k_head_r, seg_embed, seg_mat, r_w_bias, r_r_bias, r_s_bias, attn_mask_h) # post processing output_h = tf.einsum("ibnd,hnd->ibh", attn_vec_h, self.proj_o) output_h = self.attention_dropout(output_h) output_h = self.output_layer_norm(output_h + h) output_g = None if g is not None: # enable two-stream attention # g-stream q_head_g = tf.einsum("ibh,hnd->ibnd", g, self.qh_projection_layer) if target_mapping is not None: q_head_g = tf.einsum("mbnd,mlb->lbnd", q_head_g, target_mapping) attn_vec_g = self.relative_attention_layer(q_head_g, k_head_h, v_head_h, k_head_r, seg_embed, seg_mat, r_w_bias, r_r_bias, r_s_bias, attn_mask_g) attn_vec_g = tf.einsum("lbnd,mlb->mbnd", attn_vec_g, target_mapping) else: attn_vec_g = self.relative_attention_layer(q_head_g, k_head_h, v_head_h, k_head_r, seg_embed, seg_mat, r_w_bias, r_r_bias, r_s_bias, attn_mask_g) # post processing output_g = tf.einsum("ibnd,hnd->ibh", attn_vec_g, self.proj_o) output_g = self.attention_dropout(output_g) output_g = self.output_layer_norm(output_g + g) return (output_h, output_g) class TransformerXLModel(tf.keras.layers.Layer): """Defines a Transformer-XL computation graph with additional support for XLNet.""" def __init__(self, n_token, n_layer, d_model, n_head, d_head, d_inner, dropout, dropout_att, attn_type, bi_data, is_training, initializer, mem_len=None, same_length=False, clamp_len=-1, untie_r=False, use_tpu=True, reuse_len=None, ff_activation="relu", use_cls_mask=False, **kwargs): """Initializes TransformerXLModel. Args: n_token: int, the number of tokens in vocabulary. n_layer: int, the number of layers. d_model: int, the hidden size. n_head: int, the number of attention heads. d_head: int, the dimension size of each attention head. d_inner: int, the hidden size in feed-forward layers. dropout: float, dropout rate. dropout_att: float, dropout rate on attention probabilities. attn_type: str, "uni" or "bi". bi_data: bool, whether to use bidirectional input pipeline. Usually set to True during pretraining and False during finetuning. is_training: bool, whether in training mode. initializer: A tf initializer. mem_len: int, the number of tokens to cache. same_length: bool, whether to use the same attention length for each token. clamp_len: int, clamp all relative distances larger than clamp_len. -1 means no clamping. untie_r: bool, whether to untie the biases in attention. use_tpu: bool, whether TPUs are used. reuse_len: int, the number of tokens in the currect batch to be cached and reused in the future. ff_activation: str, "relu" or "gelu". use_cls_mask: bool, whether to introduce cls mask. **kwargs: Other parameters. """ super(TransformerXLModel, self).__init__(**kwargs) warnings.warn( "`TransformerXLModel` is deprecated, please use `XLNetBase` instead", DeprecationWarning, stacklevel=2) self.n_token = n_token self.initializer = initializer self.attn_type = attn_type self.n_layer = n_layer self.d_model = d_model self.n_head = n_head self.d_head = d_head self.d_inner = d_inner self.ff_activation = ff_activation self.untie_r = untie_r self.use_tpu = use_tpu self.dropout = dropout self.dropout_att = dropout_att self.mem_len = mem_len self.reuse_len = reuse_len self.bi_data = bi_data self.clamp_len = clamp_len self.same_length = same_length self.use_cls_mask = use_cls_mask def build(self, unused_input_shapes): """Implements build() for the layer.""" self.tf_float = tf.float32 self.embedding_lookup = EmbeddingLookup( n_token=self.n_token, d_embed=self.d_model, initializer=self.initializer, dtype=self.tf_float, name="word_embedding") self.h_dropout = tf.keras.layers.Dropout(rate=self.dropout) self.g_dropout = tf.keras.layers.Dropout(rate=self.dropout) if self.untie_r: self.r_w_bias = ( self.add_weight( "r_w_bias", shape=[self.n_layer, self.n_head, self.d_head], dtype=self.tf_float, initializer=self.initializer)) self.r_r_bias = ( self.add_weight( "r_r_bias", shape=[self.n_layer, self.n_head, self.d_head], dtype=self.tf_float, initializer=self.initializer)) self.r_s_bias = ( self.add_weight( "r_s_bias", shape=[self.n_layer, self.n_head, self.d_head], dtype=self.tf_float, initializer=self.initializer)) else: self.r_w_bias = ( self.add_weight( "r_w_bias", shape=[self.n_head, self.d_head], dtype=self.tf_float, initializer=self.initializer)) self.r_r_bias = ( self.add_weight( "r_r_bias", shape=[self.n_head, self.d_head], dtype=self.tf_float, initializer=self.initializer)) self.r_s_bias = ( self.add_weight( "r_s_bias", [self.n_head, self.d_head], dtype=self.tf_float, initializer=self.initializer)) self.seg_embed = self.add_weight( "seg_embed", [self.n_layer, 2, self.n_head, self.d_head], dtype=self.tf_float, initializer=self.initializer) self.mask_emb = self.add_weight( "mask_emb/mask_emb", shape=[1, 1, self.d_model], dtype=self.tf_float) self.emb_dropout = tf.keras.layers.Dropout(rate=self.dropout) self.fwd_position_embedding = RelativePositionEncoding(self.d_model) self.bwd_position_embedding = RelativePositionEncoding(self.d_model) self.rel_multihead_layers = [] self.h_positionwise_ffn_layers = [] for i in range(self.n_layer): self.rel_multihead_layers.append( RelativeMultiheadAttention( d_model=self.d_model, dropout=self.dropout, n_head=self.n_head, d_head=self.d_head, dropout_att=self.dropout_att, kernel_initializer=self.initializer, name="layer_%d/rel_attn" % (i))) self.h_positionwise_ffn_layers.append( PositionwiseFF( d_model=self.d_model, d_inner=self.d_inner, dropout=self.dropout, kernel_initializer=self.initializer, activation_type=self.ff_activation, name="layer_%d/ff" % (i))) self.output_dropout = tf.keras.layers.Dropout(rate=self.dropout) super(TransformerXLModel, self).build(unused_input_shapes) def __call__(self, inp_k, seg_id=None, input_mask=None, mems=None, perm_mask=None, target_mapping=None, inp_q=None, **kwargs): # Uses dict to feed inputs into call() in order to keep mems as a python # list. inputs = { "inp_k": inp_k, "seg_id": seg_id, "input_mask": input_mask, "mems": mems, "perm_mask": perm_mask, "target_mapping": target_mapping, "inp_q": inp_q } return super(TransformerXLModel, self).__call__(inputs, **kwargs) def call(self, inputs): """Implements call() for the layer.""" inp_k = inputs["inp_k"] seg_id = inputs["seg_id"] input_mask = inputs["input_mask"] mems = inputs["mems"] perm_mask = inputs["perm_mask"] target_mapping = inputs["target_mapping"] inp_q = inputs["inp_q"] new_mems = [] bsz = tf.shape(inp_k)[1] qlen = inp_k.shape.as_list()[0] mlen = mems[0].shape.as_list()[0] if mems is not None else 0 klen = mlen + qlen ##### Attention mask # causal attention mask if self.attn_type == "uni": attn_mask = _create_mask(qlen, mlen, self.tf_float, self.same_length) # pylint: enable=protected-access attn_mask = attn_mask[:, :, None, None] elif self.attn_type == "bi": attn_mask = None else: raise ValueError("Unsupported attention type: {}".format(self.attn_type)) # data mask: input mask & perm mask if input_mask is not None and perm_mask is not None: data_mask = input_mask[None] + perm_mask elif input_mask is not None and perm_mask is None: data_mask = input_mask[None] elif input_mask is None and perm_mask is not None: data_mask = perm_mask else: data_mask = None if data_mask is not None: # all mems can be attended to mems_mask = tf.zeros([tf.shape(data_mask)[0], mlen, bsz], dtype=self.tf_float) data_mask = tf.concat([mems_mask, data_mask], 1) if attn_mask is None: attn_mask = data_mask[:, :, :, None] else: attn_mask += data_mask[:, :, :, None] if attn_mask is not None: attn_mask = tf.cast(attn_mask > 0, dtype=self.tf_float) if attn_mask is not None: non_tgt_mask = -tf.eye(qlen, dtype=self.tf_float) non_tgt_mask = tf.concat( [tf.zeros([qlen, mlen], dtype=self.tf_float), non_tgt_mask], axis=-1) non_tgt_mask = tf.cast( (attn_mask + non_tgt_mask[:, :, None, None]) > 0, dtype=self.tf_float) else: non_tgt_mask = None word_emb_k = self.embedding_lookup(inp_k) if inp_q is not None: if target_mapping is not None: word_emb_q = tf.tile(self.mask_emb, [tf.shape(target_mapping)[0], bsz, 1]) else: inp_q_ext = inp_q[:, :, None] word_emb_q = inp_q_ext * self.mask_emb + (1 - inp_q_ext) * word_emb_k output_h = self.h_dropout(word_emb_k) output_g = None if inp_q is not None: output_g = self.g_dropout(word_emb_q) ##### Segment embedding if seg_id is not None: # Convert `seg_id` to one-hot `seg_mat` mem_pad = tf.zeros([mlen, bsz], dtype=tf.int32) cat_id = tf.concat([mem_pad, seg_id], 0) if self.use_cls_mask: # `1` indicates not in the same segment [qlen x klen x bsz] # seg_id: [qlen x bsz] & cat_id: [klen x bsz] cls_mat = tf.logical_or( tf.equal(seg_id, tf.constant([data_utils.SEG_ID_CLS]))[:, None], tf.equal(cat_id, tf.constant([data_utils.SEG_ID_CLS]))[None, :]) seg_mat = tf.equal(seg_id[:, None], cat_id[None, :]) seg_mat = tf.logical_or(cls_mat, seg_mat) else: seg_mat = tf.logical_not(tf.equal(seg_id[:, None], cat_id[None, :])) else: seg_mat = None dtype = self.tf_float freq_seq = tf.range(0, self.d_model, 2.0) if dtype is not None and dtype != tf.float32: freq_seq = tf.cast(freq_seq, dtype=self.dtype) if self.attn_type == "bi": beg, end = klen, -qlen elif self.attn_type == "uni": beg, end = klen, -1 else: raise ValueError("Unknown `attn_type` {}.".format(self.attn_type)) if self.bi_data: fwd_pos_seq = tf.range(beg, end, -1.0) bwd_pos_seq = tf.range(-beg, -end, 1.0) if dtype is not None and dtype != tf.float32: fwd_pos_seq = tf.cast(fwd_pos_seq, dtype=dtype) bwd_pos_seq = tf.cast(bwd_pos_seq, dtype=dtype) if self.clamp_len > 0: fwd_pos_seq = tf.clip_by_value(fwd_pos_seq, -self.clamp_len, self.clamp_len) bwd_pos_seq = tf.clip_by_value(bwd_pos_seq, -self.clamp_len, self.clamp_len) if bsz is not None: fwd_pos_emb = self.fwd_position_embedding(fwd_pos_seq, bsz // 2) bwd_pos_emb = self.bwd_position_embedding(bwd_pos_seq, bsz // 2) else: fwd_pos_emb = self.fwd_position_embedding(fwd_pos_seq, None) bwd_pos_emb = self.bwd_position_embedding(bwd_pos_seq, None) pos_emb = tf.concat([fwd_pos_emb, bwd_pos_emb], axis=1) else: fwd_pos_seq = tf.range(beg, end, -1.0) if dtype is not None and dtype != tf.float32: fwd_pos_seq = tf.cast(fwd_pos_seq, dtype=dtype) if self.clamp_len > 0: fwd_pos_seq = tf.clip_by_value(fwd_pos_seq, -self.clamp_len, self.lamp_len) pos_emb = self.fwd_position_embedding(fwd_pos_seq, bsz) pos_emb = self.emb_dropout(pos_emb) if mems is None: mems = [None] * self.n_layer for i in range(self.n_layer): # cache new mems new_mems.append( _cache_mem(output_h, mems[i], self.mem_len, self.reuse_len)) # pylint: enable=protected-access # segment bias if seg_id is None: r_s_bias_i = None seg_embed_i = None else: r_s_bias_i = self.r_s_bias if not self.untie_r else self.r_s_bias[i] seg_embed_i = self.seg_embed[i] ffn_layer = self.h_positionwise_ffn_layers[i] attention_layer = self.rel_multihead_layers[i] output_h, output_g = attention_layer( h=output_h, g=output_g, r=pos_emb, r_w_bias=self.r_w_bias if not self.untie_r else self.r_w_bias[i], r_r_bias=self.r_r_bias if not self.untie_r else self.r_r_bias[i], seg_mat=seg_mat, r_s_bias=r_s_bias_i, seg_embed=seg_embed_i, attn_mask_h=non_tgt_mask, attn_mask_g=attn_mask, mems=mems[i], target_mapping=target_mapping) output_h = ffn_layer(output_h) if output_g is not None: output_g = ffn_layer(output_g) if inp_q is not None: output = output_g else: output = output_h return output, new_mems, None class PretrainingXLNetModel(tf.keras.Model): """XLNet keras model combined with pretraining LM loss layer. See the original paper: https://arxiv.org/pdf/1906.08237.pdf """ def __init__(self, use_proj, xlnet_config, run_config, use_legacy_mask=True, **kwargs): super(PretrainingXLNetModel, self).__init__(**kwargs) self.run_config = run_config self.initializer = _get_initializer(run_config) self.xlnet_config = copy.deepcopy(xlnet_config) self._use_legacy_mask = use_legacy_mask self.xlnet_model = networks.XLNetBase( vocab_size=self.xlnet_config.n_token, initializer=self.initializer, attention_type="bi", num_layers=self.xlnet_config.n_layer, hidden_size=self.xlnet_config.d_model, num_attention_heads=self.xlnet_config.n_head, head_size=self.xlnet_config.d_head, inner_size=self.xlnet_config.d_inner, two_stream=True, tie_attention_biases=not self.xlnet_config.untie_r, inner_activation=self.xlnet_config.ff_activation, dropout_rate=self.run_config.dropout, attention_dropout_rate=self.run_config.dropout_att, memory_length=self.run_config.mem_len, reuse_length=self.run_config.reuse_len, bi_data=self.run_config.bi_data, clamp_length=self.run_config.clamp_len, use_cls_mask=self.run_config.use_cls_mask, name="xlnet_model") self.lmloss_layer = LMLossLayer( vocab_size=self.xlnet_config.n_token, hidden_size=self.xlnet_config.d_model, initializer=self.initializer, tie_weight=True, bi_data=self.run_config.bi_data, use_one_hot=self.run_config.use_tpu, use_proj=use_proj, name="lm_loss") def call(self, features): """Implements call() for the layer.""" input_ids = features["input_ids"] masked_tokens = features["input_q"] seg_ids = features["seg_id"] if self._use_legacy_mask: # Legacy input mask assumes `real` values are 0 and `padding` # values are 1. perm_mask = 1 - features["perm_mask"] else: perm_mask = features["perm_mask"] target_mapping = features["target_mapping"] # target for LM loss target = features["target"] # target mask for LM loss tgt_mask = features["target_mask"] mems = features.get("mems", None) model_output, self.new_mems = self.xlnet_model( input_ids=input_ids, segment_ids=seg_ids, input_mask=None, state=mems, permutation_mask=perm_mask, target_mapping=target_mapping, masked_tokens=masked_tokens) lm_loss, _ = self.lmloss_layer( hidden=model_output, target=target, lookup_table=self.xlnet_model.get_embedding_lookup_table(), target_mask=tgt_mask) self.add_loss(lm_loss) return self.new_mems, model_output class ClassificationXLNetModel(tf.keras.Model): """XLNet keras model combined with classification loss layer. See the original paper: https://arxiv.org/pdf/1906.08237.pdf """ def __init__(self, xlnet_config, run_config, n_class, summary_type, use_legacy_mask=True, **kwargs): super(ClassificationXLNetModel, self).__init__(**kwargs) warnings.warn( "`ClassificationXLNetModel` is deprecated, please use `XLNetClassifier`" "instead.", DeprecationWarning, stacklevel=2) self.run_config = run_config self.initializer = _get_initializer(run_config) self.xlnet_config = copy.deepcopy(xlnet_config) self._use_legacy_mask = use_legacy_mask self.xlnet_model = networks.XLNetBase( vocab_size=self.xlnet_config.n_token, initializer=self.initializer, attention_type="bi", num_layers=self.xlnet_config.n_layer, hidden_size=self.xlnet_config.d_model, num_attention_heads=self.xlnet_config.n_head, head_size=self.xlnet_config.d_head, inner_size=self.xlnet_config.d_inner, two_stream=False, tie_attention_biases=not self.xlnet_config.untie_r, inner_activation=self.xlnet_config.ff_activation, dropout_rate=self.run_config.dropout, attention_dropout_rate=self.run_config.dropout_att, memory_length=self.run_config.mem_len, reuse_length=self.run_config.reuse_len, bi_data=self.run_config.bi_data, clamp_length=self.run_config.clamp_len, use_cls_mask=False, name="xlnet_model") self.summarization_layer = Summarization( hidden_size=self.xlnet_config.d_model, num_attention_heads=self.xlnet_config.n_head, head_size=self.xlnet_config.d_head, dropout_rate=self.run_config.dropout, attention_dropout_rate=self.run_config.dropout_att, initializer=self.initializer, use_proj=True, summary_type=summary_type, name="sequence_summary") self.cl_loss_layer = ClassificationLossLayer( n_class=n_class, initializer=self.initializer, name="classification") def call(self, features): """Implements call() for the layer.""" batch_size_per_core = tf.shape(features["input_ids"])[0] input_ids = features["input_ids"] segment_ids = features["segment_ids"] if self._use_legacy_mask: # Legacy input mask assumes `real` values are 0 and `padding` # values are 1. input_mask = 1 - features["input_mask"] else: input_mask = features["input_mask"] label = tf.reshape(features["label_ids"], [batch_size_per_core]) mems = features.get("mems", None) attention_output, new_mems = ( self.xlnet_model(input_ids, segment_ids, input_mask, mems)) summary = self.summarization_layer(attention_output) per_example_loss, logits = self.cl_loss_layer(hidden=summary, labels=label) self.add_loss(tf.keras.backend.mean(per_example_loss)) return new_mems, logits class LMLossLayer(tf.keras.layers.Layer): """Layer computing cross entropy loss for language modeling.""" def __init__(self, vocab_size, hidden_size, initializer, tie_weight=False, bi_data=True, use_one_hot=False, use_proj=False, **kwargs): """Constructs LMLoss layer. Args: vocab_size: Number of tokens in vocabulary. hidden_size: The dimension of model hidden state. initializer: Initializer used for parameters. tie_weight: Whether to share weights between embedding lookup layer and next-token prediction layer. bi_data: Whether to use bidirectional input pipeline. Usually set to True during pretraining and False during finetuning. use_one_hot: bool, whether to use one hot encodings. This should be used when TPUs are used. use_proj: bool, whether to add a projection layer before LM prediction. **kwargs: Other parameters. """ super(LMLossLayer, self).__init__(**kwargs) self.vocab_size = vocab_size self.hidden_size = hidden_size self.initializer = initializer self.tie_weight = tie_weight self.bi_data = bi_data self.use_one_hot = use_one_hot self.use_proj = use_proj def build(self, unused_input_shapes): """Implements build() for the layer.""" if self.use_proj: self.proj_layer = tf.keras.layers.Dense( units=self.hidden_size, kernel_initializer=self.initializer, activation=gelu, name="lm_projection/dense") self.proj_layer_norm = tf.keras.layers.LayerNormalization( axis=-1, epsilon=1e-12, name="lm_projection/LayerNorm") if not self.tie_weight: self.softmax_w = self.add_weight( "weight", shape=[self.vocab_size, self.hidden_size], initializer=self.initializer) self.softmax_b = self.add_weight( "bias", shape=[self.vocab_size], initializer=tf.zeros_initializer()) super(LMLossLayer, self).build(unused_input_shapes) def call(self, hidden, target, lookup_table, target_mask): """Implements call() for the layer.""" if self.use_proj: hidden = self.proj_layer_norm(self.proj_layer(hidden)) if self.tie_weight: logits = tf.einsum("ibd,nd->ibn", hidden, lookup_table) + self.softmax_b else: logits = tf.einsum("ibd,nd->ibn", hidden, self.softmax_w) + self.softmax_b if self.use_one_hot: one_hot_target = tf.one_hot(target, self.vocab_size, dtype=logits.dtype) loss = -tf.reduce_sum(tf.nn.log_softmax(logits) * one_hot_target, -1) else: loss = tf.nn.sparse_softmax_cross_entropy_with_logits( labels=target, logits=logits) total_loss = tf.reduce_sum(loss * target_mask) / tf.reduce_sum(target_mask) return total_loss, logits class Summarization(tf.keras.layers.Layer): """The layer to pool the output from XLNet model into a vector.""" def __init__(self, hidden_size, num_attention_heads, head_size, dropout_rate, attention_dropout_rate, initializer, use_proj=True, summary_type="last", **kwargs): """Constructs Summarization layer. Args: hidden_size: int, the dimension of model hidden state. num_attention_heads: int, the number of attention heads. head_size: int, the dimension size of each attention head. dropout_rate: float, dropout rate. attention_dropout_rate: float, dropout rate on attention probabilities. initializer: Initializer used for parameters. use_proj: bool, whether to use projection layer for summarization. summary_type: Method used to summarize a sequence into a compact vector. **kwargs: Other parameters. """ super(Summarization, self).__init__(**kwargs) self.hidden_size = hidden_size self.num_attention_heads = num_attention_heads self.head_size = head_size self.initializer = initializer self.dropout_rate = dropout_rate self.attention_dropout_rate = attention_dropout_rate self.use_proj = use_proj self.summary_type = summary_type def build(self, unused_input_shapes): """Implements build() for the layer.""" if self.use_proj: self.proj_layer = tf.keras.layers.Dense( units=self.hidden_size, kernel_initializer=self.initializer, activation=tf.nn.tanh, name="summary") self.dropout_layer = tf.keras.layers.Dropout(rate=self.dropout_rate) super(Summarization, self).build(unused_input_shapes) def call(self, inputs): """Implements call() for the layer.""" if self.summary_type == "last": summary = inputs[:, -1, :] elif self.summary_type == "first": summary = inputs[:, 0, :] else: raise ValueError("Invalid summary type provided: %s" % self.summary_type) if self.use_proj: summary = self.proj_layer(summary) summary = self.dropout_layer(summary) return summary class ClassificationLossLayer(tf.keras.layers.Layer): """Layer computing cross entropy loss for classification task.""" def __init__(self, n_class, initializer, **kwargs): """Constructs Summarization layer. Args: n_class: Number of tokens in vocabulary. initializer: Initializer used for parameters. **kwargs: Other parameters. """ super(ClassificationLossLayer, self).__init__(**kwargs) self.n_class = n_class self.initializer = initializer def build(self, unused_input_shapes): """Implements build() for the layer.""" self.proj_layer = tf.keras.layers.Dense( units=self.n_class, kernel_initializer=self.initializer, name="logit") super(ClassificationLossLayer, self).build(unused_input_shapes) def call(self, hidden, labels): """Implements call() for the layer.""" logits = self.proj_layer(hidden) one_hot_target = tf.one_hot(labels, self.n_class, dtype=hidden.dtype) # pytype: disable=attribute-error loss = -tf.reduce_sum(tf.nn.log_softmax(logits) * one_hot_target, -1) return loss, logits class QAXLNetModel(tf.keras.Model): """XLNet keras model combined with question answering loss layer. See the original paper: https://arxiv.org/pdf/1906.08237.pdf """ def __init__(self, xlnet_config, run_config, start_n_top, end_n_top, use_legacy_mask=True, **kwargs): super(QAXLNetModel, self).__init__(**kwargs) warnings.warn( "`QAXLNetModel` is deprecated, please use `XLNetSpanLabeler` instead.", DeprecationWarning, stacklevel=2) self.run_config = run_config self.initializer = _get_initializer(run_config) self.xlnet_config = copy.deepcopy(xlnet_config) self._use_legacy_mask = use_legacy_mask self.xlnet_model = networks.XLNetBase( vocab_size=self.xlnet_config.n_token, initializer=self.initializer, attention_type="bi", num_layers=self.xlnet_config.n_layer, hidden_size=self.xlnet_config.d_model, num_attention_heads=self.xlnet_config.n_head, head_size=self.xlnet_config.d_head, inner_size=self.xlnet_config.d_inner, tie_attention_biases=not self.xlnet_config.untie_r, inner_activation=self.xlnet_config.ff_activation, dropout_rate=self.run_config.dropout, attention_dropout_rate=self.run_config.dropout_att, two_stream=False, memory_length=self.run_config.mem_len, reuse_length=self.run_config.reuse_len, bi_data=self.run_config.bi_data, clamp_length=self.run_config.clamp_len, use_cls_mask=False, name="xlnet_model") self.qa_loss_layer = QALossLayer( hidden_size=self.xlnet_config.d_model, start_n_top=start_n_top, end_n_top=end_n_top, initializer=self.initializer, dropout_rate=self.run_config.dropout, name="qa_loss_layer") def call(self, features, training=False): """Implements call() for the layer.""" input_ids = features["input_ids"] segment_ids = features["segment_ids"] if self._use_legacy_mask: # Legacy input mask assumes `real` values are 0 and `padding` # values are 1. input_mask = 1 - features["input_mask"] else: input_mask = features["input_mask"] cls_index = tf.reshape(features["cls_index"], [-1]) p_mask = features["p_mask"] attention_output, new_mems = ( self.xlnet_model(input_ids, segment_ids, input_mask)) if training: loss, logits = self.qa_loss_layer( hidden=attention_output, p_mask=p_mask, cls_index=cls_index, start_positions=features["start_positions"], end_positions=features["end_positions"], is_impossible=features["is_impossible"]) self.add_loss(loss) return new_mems, logits else: results = self.qa_loss_layer( hidden=attention_output, p_mask=p_mask, cls_index=cls_index) return results class QALossLayer(tf.keras.layers.Layer): """Layer computing position and regression loss for question answering task.""" def __init__(self, hidden_size, start_n_top, end_n_top, initializer, dropout_rate, **kwargs): """Constructs Summarization layer. Args: hidden_size: Int, the hidden size. start_n_top: Beam size for span start. end_n_top: Beam size for span end. initializer: Initializer used for parameters. dropout_rate: float, dropout rate. **kwargs: Other parameters. """ super(QALossLayer, self).__init__(**kwargs) self.hidden_size = hidden_size self.start_n_top = start_n_top self.end_n_top = end_n_top self.initializer = initializer self.dropout_rate = dropout_rate def build(self, unused_input_shapes): """Implements build() for the layer.""" self.start_logits_proj_layer = tf.keras.layers.Dense( units=1, kernel_initializer=self.initializer, name="start_logits/dense") self.end_logits_proj_layer0 = tf.keras.layers.Dense( units=self.hidden_size, kernel_initializer=self.initializer, activation=tf.nn.tanh, name="end_logits/dense_0") self.end_logits_proj_layer1 = tf.keras.layers.Dense( units=1, kernel_initializer=self.initializer, name="end_logits/dense_1") self.end_logits_layer_norm = tf.keras.layers.LayerNormalization( axis=-1, epsilon=1e-12, name="end_logits/LayerNorm") self.answer_class_proj_layer0 = tf.keras.layers.Dense( units=self.hidden_size, kernel_initializer=self.initializer, activation=tf.nn.tanh, name="answer_class/dense_0") self.answer_class_proj_layer1 = tf.keras.layers.Dense( units=1, kernel_initializer=self.initializer, use_bias=False, name="answer_class/dense_1") self.ans_feature_dropout = tf.keras.layers.Dropout(rate=self.dropout_rate) super(QALossLayer, self).build(unused_input_shapes) def __call__(self, hidden, p_mask, cls_index, **kwargs): return super(QALossLayer, self).__call__( (hidden, p_mask, cls_index, kwargs)) def call(self, inputs, training=False): """Implements call() for the layer.""" hidden, p_mask, cls_index, kwargs = inputs return_dict = {} seq_len = tf.shape(hidden)[1] hidden = tf.transpose(hidden, [1, 0, 2]) start_logits = self.start_logits_proj_layer(hidden) start_logits = tf.transpose(tf.squeeze(start_logits, -1), [1, 0]) start_logits_masked = start_logits * (1 - p_mask) - 1e30 * p_mask start_log_probs = tf.nn.log_softmax(start_logits_masked, -1) if training: start_positions = kwargs["start_positions"] end_positions = kwargs["end_positions"] is_impossible = kwargs["is_impossible"] start_positions = tf.reshape(start_positions, [-1]) start_index = tf.one_hot( start_positions, depth=seq_len, axis=-1, dtype=tf.float32) start_features = tf.einsum("lbh,bl->bh", hidden, start_index) start_features = tf.tile(start_features[None], [seq_len, 1, 1]) end_logits = self.end_logits_proj_layer0( tf.concat([hidden, start_features], axis=-1)) end_logits = self.end_logits_layer_norm(end_logits) end_logits = self.end_logits_proj_layer1(end_logits) end_logits = tf.transpose(tf.squeeze(end_logits, -1), [1, 0]) end_logits_masked = end_logits * (1 - p_mask) - 1e30 * p_mask end_log_probs = tf.nn.log_softmax(end_logits_masked, -1) else: # during inference, compute the end logits based on beam search start_top_log_probs, start_top_index = tf.nn.top_k( start_log_probs, k=self.start_n_top) start_index = tf.one_hot( start_top_index, depth=seq_len, axis=-1, dtype=tf.float32) start_features = tf.einsum("lbh,bkl->bkh", hidden, start_index) end_input = tf.tile(hidden[:, :, None], [1, 1, self.start_n_top, 1]) start_features = tf.tile(start_features[None], [seq_len, 1, 1, 1]) end_input = tf.concat([end_input, start_features], axis=-1) end_logits = self.end_logits_proj_layer0(end_input) end_logits = tf.reshape(end_logits, [seq_len, -1, self.hidden_size]) end_logits = self.end_logits_layer_norm(end_logits) end_logits = tf.reshape(end_logits, [seq_len, -1, self.start_n_top, self.hidden_size]) end_logits = self.end_logits_proj_layer1(end_logits) end_logits = tf.reshape(end_logits, [seq_len, -1, self.start_n_top]) end_logits = tf.transpose(end_logits, [1, 2, 0]) end_logits_masked = end_logits * ( 1 - p_mask[:, None]) - 1e30 * p_mask[:, None] end_log_probs = tf.nn.log_softmax(end_logits_masked, -1) end_top_log_probs, end_top_index = tf.nn.top_k( end_log_probs, k=self.end_n_top) end_top_log_probs = tf.reshape(end_top_log_probs, [-1, self.start_n_top * self.end_n_top]) end_top_index = tf.reshape(end_top_index, [-1, self.start_n_top * self.end_n_top]) if training: return_dict["start_log_probs"] = start_log_probs return_dict["end_log_probs"] = end_log_probs else: return_dict["start_top_log_probs"] = start_top_log_probs return_dict["start_top_index"] = start_top_index return_dict["end_top_log_probs"] = end_top_log_probs return_dict["end_top_index"] = end_top_index # an additional layer to predict answerability # get the representation of CLS cls_index = tf.one_hot(cls_index, seq_len, axis=-1, dtype=tf.float32) cls_feature = tf.einsum("lbh,bl->bh", hidden, cls_index) # get the representation of START start_p = tf.nn.softmax(start_logits_masked, axis=-1, name="softmax_start") start_feature = tf.einsum("lbh,bl->bh", hidden, start_p) ans_feature = tf.concat([start_feature, cls_feature], -1) ans_feature = self.answer_class_proj_layer0(ans_feature) ans_feature = self.ans_feature_dropout(ans_feature) cls_logits = self.answer_class_proj_layer1(ans_feature) cls_logits = tf.squeeze(cls_logits, -1) return_dict["cls_logits"] = cls_logits if not training: return return_dict def compute_loss(log_probs, positions): one_hot_positions = tf.one_hot(positions, depth=seq_len, dtype=tf.float32) loss = -tf.reduce_sum(one_hot_positions * log_probs, axis=-1) loss = tf.reduce_mean(loss) return loss start_loss = compute_loss(start_log_probs, start_positions) end_loss = compute_loss(end_log_probs, end_positions) total_loss = (start_loss + end_loss) * 0.5 is_impossible = tf.reshape(is_impossible, [-1]) regression_loss = tf.nn.sigmoid_cross_entropy_with_logits( labels=is_impossible, logits=cls_logits) regression_loss = tf.reduce_mean(regression_loss) total_loss += regression_loss * 0.5 return total_loss, cls_logits
47,595
34.975813
108
py
models
models-master/official/legacy/xlnet/data_utils.py
# Copyright 2023 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. """Utilities used for data preparation.""" import collections import json import os from absl import logging import numpy as np import tensorflow as tf special_symbols = { "<unk>": 0, "<s>": 1, "</s>": 2, "<cls>": 3, "<sep>": 4, "<pad>": 5, "<mask>": 6, "<eod>": 7, "<eop>": 8, } VOCAB_SIZE = 32000 UNK_ID = special_symbols["<unk>"] CLS_ID = special_symbols["<cls>"] SEP_ID = special_symbols["<sep>"] MASK_ID = special_symbols["<mask>"] EOD_ID = special_symbols["<eod>"] SEG_ID_P = 0 SEG_ID_Q = 1 SEG_ID_CLS = 2 SEG_ID_PAD = 3 OnlineMaskingConfig = collections.namedtuple("OnlineMaskingConfig", [ "sample_strategy", "max_num_tokens", "min_num_tokens", "max_num_words", "min_num_words" ]) def file_based_input_fn_builder(input_file, name_to_features, batch_size, is_training): """Creates an `input_fn` closure.""" logging.info("Input tfrecord file %s", input_file) def _decode_record(record, name_to_features): """Decodes a record to a TensorFlow example.""" example = tf.io.parse_single_example(record, name_to_features) # tf.Example only supports tf.int64, but the TPU only supports tf.int32. # So cast all int64 to int32. for name in list(example.keys()): t = example[name] if t.dtype == tf.int64: t = tf.cast(t, tf.int32) example[name] = t return example def input_fn(): """Returns dataset for training/evaluation.""" num_threads = 8 if isinstance(input_file, str): d = tf.data.TFRecordDataset(input_file) # For training, we want a lot of parallel reading and shuffling. # For eval, we want no shuffling and parallel reading doesn't matter. if is_training: d = d.shuffle(2048) d = d.repeat() else: cycle_length = min(num_threads, len(input_file)) d = tf.data.Dataset.from_tensor_slices(input_file) # file level shuffle d = d.shuffle(len(input_file)).repeat() d = d.interleave( tf.data.TFRecordDataset, cycle_length=cycle_length) if is_training: # sample level shuffle d = d.shuffle(buffer_size=2048) d = d.map( lambda record: _decode_record(record, name_to_features), num_parallel_calls=tf.data.experimental.AUTOTUNE) d = d.batch(batch_size, drop_remainder=is_training) # When `input_file` is a path to a single file or a list # containing a single path, disable auto sharding so that # same input file is sent to all workers. if isinstance(input_file, str) or len(input_file) == 1: options = tf.data.Options() options.experimental_distribute.auto_shard_policy = ( tf.data.experimental.AutoShardPolicy.OFF) d = d.with_options(options) d = d.prefetch(tf.data.experimental.AUTOTUNE) return d return input_fn def create_classification_dataset(file_path, seq_length, batch_size, is_training): """Creates input dataset from (tf)records files for pretraining.""" name_to_features = { "input_ids": tf.io.FixedLenFeature([seq_length], tf.int64), "input_mask": tf.io.FixedLenFeature([seq_length], tf.float32), "segment_ids": tf.io.FixedLenFeature([seq_length], tf.int64), "label_ids": tf.io.FixedLenFeature([], tf.int64), "is_real_example": tf.io.FixedLenFeature([], tf.int64), } input_fn = file_based_input_fn_builder(file_path, name_to_features, batch_size, is_training) dataset = input_fn() return dataset def create_squad_dataset(file_path, seq_length, batch_size, is_training): """Creates input dataset from (tf)records files for pretraining.""" name_to_features = { "unique_ids": tf.io.FixedLenFeature([], tf.int64), "input_ids": tf.io.FixedLenFeature([seq_length], tf.int64), "input_mask": tf.io.FixedLenFeature([seq_length], tf.float32), "segment_ids": tf.io.FixedLenFeature([seq_length], tf.int64), "cls_index": tf.io.FixedLenFeature([], tf.int64), "p_mask": tf.io.FixedLenFeature([seq_length], tf.float32) } if is_training: name_to_features["start_positions"] = tf.io.FixedLenFeature([], tf.int64) name_to_features["end_positions"] = tf.io.FixedLenFeature([], tf.int64) name_to_features["is_impossible"] = tf.io.FixedLenFeature([], tf.float32) input_fn = file_based_input_fn_builder(file_path, name_to_features, batch_size, is_training) dataset = input_fn() return dataset def get_input_iterator(input_fn, strategy): """Returns distributed dataset iterator.""" # When training with TPU pods, datasets needs to be cloned across # workers. Since Dataset instance cannot be cloned in eager mode, we instead # pass callable that returns a dataset. input_data = input_fn() if callable(input_data): iterator = iter(strategy.distribute_datasets_from_function(input_data)) else: iterator = iter(strategy.experimental_distribute_dataset(input_data)) return iterator def get_classification_input_data(batch_size, seq_len, strategy, is_training, file_path): """Returns input dataset from input file string.""" # When using TPU pods, we need to clone dataset across # workers and need to pass in function that returns the dataset rather # than passing dataset instance itself. use_dataset_fn = isinstance(strategy, tf.distribute.TPUStrategy) if use_dataset_fn: if batch_size % strategy.num_replicas_in_sync != 0: raise ValueError( "Batch size must be divisible by number of replicas : {}".format( strategy.num_replicas_in_sync)) # As auto rebatching is not supported in # `distribute_datasets_from_function()` API, which is # required when cloning dataset to multiple workers in eager mode, # we use per-replica batch size. batch_size = int(batch_size / strategy.num_replicas_in_sync) def _dataset_fn(ctx=None): del ctx train_dataset = create_classification_dataset( file_path=file_path, seq_length=seq_len, batch_size=batch_size, is_training=is_training) return train_dataset return _dataset_fn if use_dataset_fn else _dataset_fn() def get_squad_input_data(batch_size, seq_len, q_len, strategy, is_training, file_path): """Returns input dataset from input file string.""" # When using TPU pods, we need to clone dataset across # workers and need to pass in function that returns the dataset rather # than passing dataset instance itself. use_dataset_fn = isinstance(strategy, tf.distribute.TPUStrategy) if use_dataset_fn: if batch_size % strategy.num_replicas_in_sync != 0: raise ValueError( "Batch size must be divisible by number of replicas : {}".format( strategy.num_replicas_in_sync)) # As auto rebatching is not supported in # `distribute_datasets_from_function()` API, which is # required when cloning dataset to multiple workers in eager mode, # we use per-replica batch size. batch_size = int(batch_size / strategy.num_replicas_in_sync) if is_training: input_glob = os.path.join( file_path, "spiece.model.*.slen-{}.qlen-{}.train.tf_record".format(seq_len, q_len)) global_input_paths = tf.io.gfile.glob(input_glob) else: global_input_paths = file_path def _dataset_fn(ctx=None): del ctx train_dataset = create_squad_dataset( file_path=global_input_paths, seq_length=seq_len, batch_size=batch_size, is_training=is_training) return train_dataset return _dataset_fn if use_dataset_fn else _dataset_fn() def _idx_pair_to_mask(beg_indices, end_indices, inputs, tgt_len, num_predict): """Turn beg and end indices into actual mask.""" non_func_mask = tf.logical_and( tf.not_equal(inputs, SEP_ID), tf.not_equal(inputs, CLS_ID)) all_indices = tf.where(non_func_mask, tf.range(tgt_len, dtype=tf.int64), tf.constant(-1, shape=[tgt_len], dtype=tf.int64)) candidate_matrix = tf.cast( tf.logical_and(all_indices[None, :] >= beg_indices[:, None], all_indices[None, :] < end_indices[:, None]), tf.float32) cumsum_matrix = tf.reshape( tf.cumsum(tf.reshape(candidate_matrix, [-1])), [-1, tgt_len]) masked_matrix = tf.cast(cumsum_matrix <= num_predict, tf.float32) target_mask = tf.reduce_sum(candidate_matrix * masked_matrix, axis=0) is_masked = tf.cast(target_mask, tf.bool) return is_masked, target_mask def _word_span_mask(inputs, tgt_len, num_predict, min_num_words, max_num_words, boundary): """Sample whole word spans as prediction targets.""" # Note: 1.2 is the token-to-word ratio mask_alpha = tgt_len / num_predict / 1.2 round_to_int = lambda x: tf.cast(tf.round(x), tf.int64) # Sample span lengths from a zipf distribution span_len_seq = np.arange(min_num_words, max_num_words + 1) probs = np.array([1.0 / (i + 1) for i in span_len_seq]) probs /= np.sum(probs) logits = tf.constant(np.log(probs), dtype=tf.float32) # Sample `num_predict` words here: note that this is over sampling span_lens = tf.random.categorical( logits=logits[None], num_samples=num_predict, dtype=tf.int64, )[0] + min_num_words # Sample the ratio [0.0, 1.0) of left context lengths span_lens_float = tf.cast(span_lens, tf.float32) left_ratio = tf.random.uniform(shape=[num_predict], minval=0.0, maxval=1.0) left_ctx_len = left_ratio * span_lens_float * (mask_alpha - 1) left_ctx_len = round_to_int(left_ctx_len) right_offset = round_to_int(span_lens_float * mask_alpha) - left_ctx_len beg_indices = ( tf.cumsum(left_ctx_len) + tf.cumsum(right_offset, exclusive=True)) end_indices = beg_indices + span_lens # Remove out of range indices max_boundary_index = tf.cast(tf.shape(boundary)[0] - 1, tf.int64) valid_idx_mask = end_indices < max_boundary_index beg_indices = tf.boolean_mask(beg_indices, valid_idx_mask) end_indices = tf.boolean_mask(end_indices, valid_idx_mask) beg_indices = tf.gather(boundary, beg_indices) end_indices = tf.gather(boundary, end_indices) # Shuffle valid indices num_valid = tf.cast(tf.shape(beg_indices)[0], tf.int64) order = tf.random.shuffle(tf.range(num_valid, dtype=tf.int64)) beg_indices = tf.gather(beg_indices, order) end_indices = tf.gather(end_indices, order) return _idx_pair_to_mask(beg_indices, end_indices, inputs, tgt_len, num_predict) def _token_span_mask(inputs, tgt_len, num_predict, min_num_tokens, max_num_tokens): """Sample token spans as prediction targets.""" mask_alpha = tgt_len / num_predict round_to_int = lambda x: tf.cast(tf.round(x), tf.int64) # Sample span lengths from a zipf distribution span_len_seq = np.arange(min_num_tokens, max_num_tokens + 1) probs = np.array([1.0 / (i + 1) for i in span_len_seq]) probs /= np.sum(probs) logits = tf.constant(np.log(probs), dtype=tf.float32) span_lens = tf.random.categorical( logits=logits[None], num_samples=num_predict, dtype=tf.int64, )[0] + min_num_tokens # Sample the ratio [0.0, 1.0) of left context lengths span_lens_float = tf.cast(span_lens, tf.float32) left_ratio = tf.random.uniform(shape=[num_predict], minval=0.0, maxval=1.0) left_ctx_len = left_ratio * span_lens_float * (mask_alpha - 1) left_ctx_len = round_to_int(left_ctx_len) # Compute the offset from left start to the right end right_offset = round_to_int(span_lens_float * mask_alpha) - left_ctx_len # Get the actual begin and end indices beg_indices = ( tf.cumsum(left_ctx_len) + tf.cumsum(right_offset, exclusive=True)) end_indices = beg_indices + span_lens # Remove out of range indices valid_idx_mask = end_indices < tgt_len beg_indices = tf.boolean_mask(beg_indices, valid_idx_mask) end_indices = tf.boolean_mask(end_indices, valid_idx_mask) # Shuffle valid indices num_valid = tf.cast(tf.shape(beg_indices)[0], tf.int64) order = tf.random.shuffle(tf.range(num_valid, dtype=tf.int64)) beg_indices = tf.gather(beg_indices, order) end_indices = tf.gather(end_indices, order) return _idx_pair_to_mask(beg_indices, end_indices, inputs, tgt_len, num_predict) def _whole_word_mask(inputs, tgt_len, num_predict, boundary): """Sample whole words as prediction targets.""" pair_indices = tf.concat([boundary[:-1, None], boundary[1:, None]], axis=1) cand_pair_indices = tf.random.shuffle(pair_indices)[:num_predict] beg_indices = cand_pair_indices[:, 0] end_indices = cand_pair_indices[:, 1] return _idx_pair_to_mask(beg_indices, end_indices, inputs, tgt_len, num_predict) def _single_token_mask(inputs, tgt_len, num_predict): """Sample individual tokens as prediction targets.""" all_indices = tf.range(tgt_len, dtype=tf.int64) non_func_mask = tf.logical_and( tf.not_equal(inputs, SEP_ID), tf.not_equal(inputs, CLS_ID)) non_func_indices = tf.boolean_mask(all_indices, non_func_mask) masked_pos = tf.random.shuffle(non_func_indices) masked_pos = tf.sort(masked_pos[:num_predict]) target_mask = tf.sparse_to_dense( sparse_indices=masked_pos, output_shape=[tgt_len], sparse_values=1.0, default_value=0.0) is_masked = tf.cast(target_mask, tf.bool) return is_masked, target_mask def _online_sample_masks(inputs, tgt_len, num_predict, online_masking_config, boundary=None): """Sample target positions to predict.""" logging.info("Online sample with strategy: `%s`.", online_masking_config.sample_strategy) if online_masking_config.sample_strategy == "single_token": return _single_token_mask(inputs, tgt_len, num_predict) elif online_masking_config.sample_strategy == "whole_word": assert boundary is not None, "whole word sampling requires `boundary`" return _whole_word_mask(inputs, tgt_len, num_predict, boundary) elif online_masking_config.sample_strategy == "token_span": return _token_span_mask(inputs, tgt_len, num_predict, online_masking_config.min_num_tokens, online_masking_config.max_num_tokens) elif online_masking_config.sample_strategy == "word_span": assert boundary is not None, "word span sampling requires `boundary`" return _word_span_mask(inputs, tgt_len, num_predict, online_masking_config.min_num_words, online_masking_config.max_num_words, boundary) else: raise NotImplementedError def create_pretrain_dataset(file_names, bsz_per_core, seq_len, reuse_len, perm_size, leak_ratio, online_masking_config, num_predict=None, input_pipeline_context=None): """Creates pretrain dataset.""" def parser(record): """Function used to parse tfrecord.""" record_spec = { "input": tf.io.FixedLenFeature([seq_len], tf.int64), "seg_id": tf.io.FixedLenFeature([seq_len], tf.int64), "label": tf.io.FixedLenFeature([1], tf.int64), } if online_masking_config.sample_strategy in ["whole_word", "word_span"]: logging.info("Add `boundary` spec for %s", online_masking_config.sample_strategy) record_spec["boundary"] = tf.io.VarLenFeature(tf.int64) # retrieve serialized example example = tf.io.parse_single_example( serialized=record, features=record_spec) inputs = example.pop("input") if online_masking_config.sample_strategy in ["whole_word", "word_span"]: boundary = tf.sparse.to_dense(example.pop("boundary")) else: boundary = None is_masked, _ = _online_sample_masks( inputs, seq_len, num_predict, online_masking_config, boundary=boundary) if reuse_len > 0: ##### Use memory # permutate the reuse and non-reuse parts separately non_reuse_len = seq_len - reuse_len assert reuse_len % perm_size == 0 and non_reuse_len % perm_size == 0 # Creates permutation mask and target mask for the first reuse_len tokens. # The tokens in this part are reused from the last sequence. perm_mask_0, target_mask_0, input_k_0, input_q_0 = _local_perm( inputs[:reuse_len], is_masked[:reuse_len], perm_size, reuse_len, leak_ratio) # Creates permutation mask and target mask for the rest of tokens in # current example, which are concatentation of two new segments. perm_mask_1, target_mask_1, input_k_1, input_q_1 = _local_perm( inputs[reuse_len:], is_masked[reuse_len:], perm_size, non_reuse_len, leak_ratio) perm_mask_0 = tf.concat( [perm_mask_0, tf.ones([reuse_len, non_reuse_len])], axis=1) perm_mask_1 = tf.concat( [tf.zeros([non_reuse_len, reuse_len]), perm_mask_1], axis=1) perm_mask = tf.concat([perm_mask_0, perm_mask_1], axis=0) target_mask = tf.concat([target_mask_0, target_mask_1], axis=0) input_k = tf.concat([input_k_0, input_k_1], axis=0) input_q = tf.concat([input_q_0, input_q_1], axis=0) else: ##### Do not use memory assert seq_len % perm_size == 0 # permutate the entire sequence together perm_mask, target_mask, input_k, input_q = _local_perm( inputs, is_masked, perm_size, seq_len, leak_ratio) # reshape back to fixed shape example["perm_mask"] = tf.reshape(perm_mask, [seq_len, seq_len]) example["input_ids"] = tf.reshape(input_k, [seq_len]) example["input_q"] = tf.reshape(input_q, [seq_len]) # Directly use raw inputs as the target target = inputs if num_predict is not None: indices = tf.range(seq_len, dtype=tf.int64) bool_target_mask = tf.cast(target_mask, tf.bool) indices = tf.boolean_mask(indices, bool_target_mask) ##### extra padding due to CLS/SEP introduced after prepro actual_num_predict = tf.shape(indices)[0] pad_len = num_predict - actual_num_predict ##### target_mapping target_mapping = tf.one_hot(indices, seq_len, dtype=tf.float32) paddings = tf.zeros([pad_len, seq_len], dtype=target_mapping.dtype) target_mapping = tf.concat([target_mapping, paddings], axis=0) example["target_mapping"] = tf.reshape(target_mapping, [num_predict, seq_len]) ##### target target = tf.boolean_mask(target, bool_target_mask) paddings = tf.zeros([pad_len], dtype=target.dtype) target = tf.concat([target, paddings], axis=0) example["target"] = tf.reshape(target, [num_predict]) ##### target mask target_mask = tf.concat([ tf.ones([actual_num_predict], dtype=tf.float32), tf.zeros([pad_len], dtype=tf.float32) ], axis=0) example["target_mask"] = tf.reshape(target_mask, [num_predict]) else: example["target"] = tf.reshape(target, [seq_len]) example["target_mask"] = tf.reshape(target_mask, [seq_len]) for key in list(example.keys()): val = example[key] if tf.keras.backend.is_sparse(val): val = tf.sparse.to_dense(val) if val.dtype == tf.int64: val = tf.cast(val, tf.int32) example[key] = val for k, v in example.items(): logging.info("%s: %s", k, v) return example dataset = parse_files_to_dataset( parser=parser, file_paths=file_names, bsz_per_core=bsz_per_core, sequential=reuse_len > 0, input_pipeline_context=input_pipeline_context) return dataset def format_filename(prefix, suffix, bsz_per_host, seq_len, reuse_len=None, uncased=False): """Generates input file name pattern.""" if reuse_len is not None and reuse_len > 0: reuse_str = "reuse-{}.".format(reuse_len) bsz_str = "hostbsz-{}.".format(bsz_per_host) else: reuse_str = "" bsz_str = "" if not uncased: case_str = "" else: case_str = "uncased." file_name = "{}.seq-{}.{}{}{}{}".format(prefix, seq_len, reuse_str, bsz_str, case_str, suffix) return file_name def get_pretrain_input_data(batch_size, seq_len, strategy, file_path, reuse_len, perm_size, leak_ratio, num_predict, uncased, online_masking_config, num_hosts=1): """Returns input dataset from input file string.""" # When using TPU pods, we need to clone dataset across # workers and need to pass in function that returns the dataset rather # than passing dataset instance itself. use_dataset_fn = isinstance(strategy, tf.distribute.TPUStrategy) split = "train" bsz_per_host = int(batch_size / num_hosts) record_glob_base = format_filename( prefix="meta.{}.pass-*".format(split), suffix="json*", bsz_per_host=bsz_per_host, seq_len=seq_len, reuse_len=reuse_len, uncased=uncased) def _get_num_batch(info): if "num_batch" in info: return info["num_batch"] elif "num_example" in info: return info["num_example"] / bsz_per_host else: raise ValueError("Do not have sample info.") if use_dataset_fn: if batch_size % strategy.num_replicas_in_sync != 0: raise ValueError( "Batch size must be divisible by number of replicas : {}".format( strategy.num_replicas_in_sync)) # As auto rebatching is not supported in # `distribute_datasets_from_function()` API, which is # required when cloning dataset to multiple workers in eager mode, # we use per-replica batch size. batch_size = int(batch_size / strategy.num_replicas_in_sync) record_info = {"num_batch": 0, "filenames": []} tfrecord_dirs = file_path.split(",") logging.info("Use the following tfrecord dirs: %s", tfrecord_dirs) for idx, record_dir in enumerate(tfrecord_dirs): record_glob = os.path.join(record_dir, record_glob_base) logging.info("[%d] Record glob: %s", idx, record_glob) record_paths = sorted(tf.io.gfile.glob(record_glob)) logging.info("[%d] Num of record info path: %d", idx, len(record_paths)) cur_record_info = {"num_batch": 0, "filenames": []} for record_info_path in record_paths: with tf.io.gfile.GFile(record_info_path, "r") as fp: info = json.load(fp) cur_record_info["num_batch"] += int(_get_num_batch(info)) cur_record_info["filenames"] += info["filenames"] # overwrite directory for `cur_record_info` new_filenames = [] for filename in cur_record_info["filenames"]: basename = os.path.basename(filename) new_filename = os.path.join(record_dir, basename) new_filenames.append(new_filename) cur_record_info["filenames"] = new_filenames logging.info("[Dir %d] Number of chosen batches: %s", idx, cur_record_info["num_batch"]) logging.info("[Dir %d] Number of chosen files: %s", idx, len(cur_record_info["filenames"])) logging.info(cur_record_info["filenames"]) # add `cur_record_info` to global `record_info` record_info["num_batch"] += cur_record_info["num_batch"] record_info["filenames"] += cur_record_info["filenames"] logging.info("Total number of batches: %d", record_info["num_batch"]) logging.info("Total number of files: %d", len(record_info["filenames"])) logging.info(record_info["filenames"]) def _dataset_fn(ctx=None): """Function that can create a pretrain dataset.""" train_dataset = create_pretrain_dataset( file_names=record_info["filenames"], bsz_per_core=batch_size, seq_len=seq_len, reuse_len=reuse_len, perm_size=perm_size, leak_ratio=leak_ratio, online_masking_config=online_masking_config, num_predict=num_predict, input_pipeline_context=ctx) return train_dataset return _dataset_fn if use_dataset_fn else _dataset_fn() def parse_files_to_dataset(parser, file_paths, bsz_per_core, sequential, input_pipeline_context=None): """Creates the dataset given file paths.""" dataset = tf.data.Dataset.from_tensor_slices(file_paths) # Note: we cannot perform sample-level shuffle here because this will violate # the consecutive requirement of data stream. if input_pipeline_context and input_pipeline_context.num_input_pipelines > 1: dataset = dataset.shard(input_pipeline_context.num_input_pipelines, input_pipeline_context.input_pipeline_id) # file-level shuffle if len(file_paths) > 1: dataset = dataset.shuffle(len(file_paths)) if sequential: # Note: cannot perform sample-level shuffle here because this will violate # the consecutive requirement of data stream. dataset = tf.data.TFRecordDataset(dataset) else: # `cycle_length` is the number of parallel files that get read. cycle_length = min(8, len(file_paths)) logging.info("Interleave %d files", cycle_length) dataset = dataset.apply( tf.data.experimental.parallel_interleave( tf.data.TFRecordDataset, cycle_length=cycle_length)) buffer_size = 2048 logging.info("Perform sample-level shuffle with size %d", buffer_size) dataset = dataset.shuffle(buffer_size=buffer_size) dataset = dataset.cache().repeat().map(parser) dataset = dataset.batch(bsz_per_core, drop_remainder=True) dataset = dataset.prefetch(tf.data.experimental.AUTOTUNE) return dataset def _local_perm(inputs, is_masked, perm_size, seq_len, leak_ratio): """Samples a permutation of the factorization order. Creates perm_mask and target_mask accordingly. Args: inputs: int64 Tensor in shape [seq_len], input ids. is_masked: bool Tensor in shape [seq_len]. True means being selected for partial prediction. perm_size: the length of longest permutation. Could be set to be reuse_len. Should not be larger than reuse_len or there will be data leaks. seq_len: int, sequence length. leak_ratio: float, percent of masked tokens that are leaked. Returns: perm_mask: float32 Tensor in shape [seq_len, seq_len] consisted of 0 and 1. If perm_mask[i][j] == 1, it means the ith token (in original order) cannot attend to the jth token (in original order). This case will happen only when the ith token's permutated position <= the jth token's permutated position, and the jth token is masked or is func token. If perm_mask[i][j] == 0, it means the ith token (in original order) can attend to the jth token (in original order). Note that non-masked tokens can be attended by all other tokens, which is different from the description in original paper. target_mask: float32 Tensor in shape [seq_len] consisted of 0 and 1. If target_mask[i] == 1, the ith token needs to be predicted and mask will be used as input. This token will count for loss. If target_mask[i] == 0, token (or [SEP], [CLS]) will be used as input. This token will not count for loss. inputs_k: int64 Tensor in shape [seq_len], input ids. inputs_q: float32 Tensor in shape [seq_len], the same as target_mask. """ # Generate permutation indices index = tf.range(seq_len, dtype=tf.int64) index = tf.transpose(tf.reshape(index, [-1, perm_size])) index = tf.random.shuffle(index) index = tf.reshape(tf.transpose(index), [-1]) # non-functional tokens non_func_tokens = tf.logical_not( tf.logical_or(tf.equal(inputs, SEP_ID), tf.equal(inputs, CLS_ID))) masked_tokens = tf.logical_and(is_masked, non_func_tokens) non_masked_or_func_tokens = tf.logical_not(masked_tokens) smallest_index = -2 * tf.ones([seq_len], dtype=tf.int64) # Similar to BERT, randomly leak some masked tokens if leak_ratio > 0: leak_tokens = tf.logical_and( masked_tokens, tf.random.uniform([seq_len], maxval=1.0) < leak_ratio) can_attend_self = tf.logical_or(non_masked_or_func_tokens, leak_tokens) else: can_attend_self = non_masked_or_func_tokens to_index = tf.where(can_attend_self, smallest_index, index) from_index = tf.where(can_attend_self, to_index + 1, to_index) # For masked tokens, can attend if i > j # For context tokens, always can attend each other can_attend = from_index[:, None] > to_index[None, :] # In modeling, 1 indicates cannot attend. Hence, reverse the value here. perm_mask = 1.0 - tf.cast(can_attend, tf.float32) # Only masked tokens are included in the loss target_mask = tf.cast(masked_tokens, tf.float32) # construct inputs_k inputs_k = inputs # construct inputs_q inputs_q = masked_tokens return perm_mask, target_mask, inputs_k, inputs_q
30,095
36.386335
80
py
models
models-master/official/legacy/xlnet/training_utils.py
# Copyright 2023 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. """XLNet training utils.""" import os import re from typing import Any, Callable, Dict, Optional, Text from absl import logging import tensorflow as tf from official.legacy.bert import model_training_utils from official.legacy.xlnet import data_utils # pytype: disable=attribute-error # pylint: disable=g-bare-generic,unused-import _MIN_SUMMARY_STEPS = 10 def _save_checkpoint(checkpoint, model_dir, checkpoint_prefix): """Saves model to with provided checkpoint prefix.""" checkpoint_path = os.path.join(model_dir, checkpoint_prefix) saved_path = checkpoint.save(checkpoint_path) logging.info("Saving model as TF checkpoint: %s", saved_path) return def _float_metric_value(metric): """Gets the value of a float-value keras metric.""" return metric.result().numpy().astype(float) def train( strategy: tf.distribute.Strategy, model_fn: Callable, input_meta_data: Dict, train_input_fn: Callable, total_training_steps: int, steps_per_loop: int, optimizer: tf.keras.optimizers.Optimizer, learning_rate_fn: tf.keras.optimizers.schedules.LearningRateSchedule, eval_fn: Optional[Callable[[tf.keras.Model, int, tf.summary.SummaryWriter], Any]] = None, metric_fn: Optional[Callable[[], tf.keras.metrics.Metric]] = None, init_checkpoint: Optional[Text] = None, init_from_transformerxl: Optional[bool] = False, model_dir: Optional[Text] = None, save_steps: Optional[int] = None, run_eagerly: Optional[bool] = False): """Runs customized training. Args: strategy: Distribution strategy on which to run low level training loop. model_fn: The function returns a keras.Model. input_meta_data: A dictionary of params: `mem_len`, `lr_layer_decay_rate`, `n_layer`, `batch_size_per_core` and `d_model`. train_input_fn: Function returns a tf.data.Dataset used for training. total_training_steps: Number of steps to train in total. steps_per_loop: Number of steps per graph-mode loop. In order to reduce communication in eager context, training logs are printed every steps_per_loop. optimizer: The optimizer for model. learning_rate_fn: the learning rate schedule. eval_fn: A callback of evaluation function, that takes a keras.Model, current step and evaluation summary writer. metric_fn: A metrics function returns a Keras Metric object to record evaluation result using evaluation dataset or with training dataset after every epoch. init_checkpoint: Optional checkpoint to load to `sub_model` returned by `model_fn`. init_from_transformerxl: Whether to load to `transformerxl_model` of `model_fn`. model_dir: The directory of model (checkpoints, summaries). save_steps: The frequency to save checkpoints. Every save_steps, we save a model checkpoint. Model checkpoint will be saved and evaluation will be conducted if evaluation dataset is provided. run_eagerly: Whether to run training eagerly. Returns: Last training step logits if training happens, otherwise returns None. Raises: TypeError: if model directory is not specified. """ required_arguments = [ train_input_fn, total_training_steps, steps_per_loop, optimizer, learning_rate_fn, save_steps ] if [arg for arg in required_arguments if arg is None]: raise ValueError("`train_input_fn`, `total_training_steps`, " "`steps_per_loop`, `optimizer`, `save_steps` and " "`learning_rate_fn` are required parameters.") if not model_dir: raise TypeError("Model directory must be specified.") train_iterator = data_utils.get_input_iterator(train_input_fn, strategy) if not tf.io.gfile.exists(model_dir): tf.io.gfile.mkdir(model_dir) # Create summary writers summary_dir = os.path.join(model_dir, "summaries") if not tf.io.gfile.exists(summary_dir): tf.io.gfile.mkdir(summary_dir) train_summary_writer = None eval_summary_writer = None if eval_fn: eval_summary_writer = tf.summary.create_file_writer( os.path.join(summary_dir, "eval")) if steps_per_loop >= _MIN_SUMMARY_STEPS: # Only writes summary when the stats are collected sufficiently over # enough steps. train_summary_writer = tf.summary.create_file_writer( os.path.join(summary_dir, "train")) with strategy.scope(): model = model_fn() if init_checkpoint: logging.info("restore from %s", init_checkpoint) if init_from_transformerxl: checkpoint = tf.train.Checkpoint( transformer_xl=model.transformerxl_model) else: checkpoint = tf.train.Checkpoint(model=model) checkpoint.restore(init_checkpoint) model.optimizer = optimizer if not hasattr(model, "optimizer"): raise ValueError("User should set optimizer attribute to model.") train_loss_metric = tf.keras.metrics.Mean("training_loss", dtype=tf.float32) train_metric = None if metric_fn: train_metric = metric_fn() def _replicated_step(inputs, mem=None): """Replicated training step.""" inputs["mems"] = mem with tf.GradientTape() as tape: mem, logits = model(inputs, training=True) loss = model.losses train_loss_metric.update_state(loss) if train_metric: train_metric.update_state(inputs["label_ids"], logits) scaled_loss = loss[0] * 1.0 / float(strategy.num_replicas_in_sync) # Collects training variables. tvars = model.trainable_variables grads = tape.gradient(scaled_loss, tvars) clipped, _ = tf.clip_by_global_norm(grads, clip_norm=1.0) if input_meta_data["lr_layer_decay_rate"] != 1.0: n_layer = 0 for i in range(len(clipped)): m = re.search(r"model/transformer/layer_(\d+?)/", tvars[i].name) if not m: continue n_layer = max(n_layer, int(m.group(1)) + 1) for i in range(len(clipped)): for l in range(n_layer): if "model/transformer/layer_{}/".format(l) in tvars[i].name: abs_rate = input_meta_data["lr_layer_decay_rate"]**( n_layer - 1 - l) clipped[i] *= abs_rate logging.info("Apply mult {:.4f} to layer-{} grad of {}".format( abs_rate, l, tvars[i].name)) break optimizer.apply_gradients(zip(clipped, tvars)) if input_meta_data["mem_len"] > 0: return mem def train_steps(iterator, steps): """Performs distributed training steps in a loop. Args: iterator: the distributed iterator of training datasets. steps: an tf.int32 integer tensor to specify number of steps to run inside host training loop. Raises: ValueError: Any of the arguments or tensor shapes are invalid. Returns: logits: logits computed. """ if not isinstance(steps, tf.Tensor): raise ValueError("steps should be an Tensor. Python object may cause " "retracing.") def cache_fn(): """Initializes memory tensor used in XLNet pretraining.""" mems = [] if input_meta_data["mem_len"] > 0: for _ in range(input_meta_data["n_layer"]): zeros = tf.zeros([ input_meta_data["batch_size_per_core"], input_meta_data["mem_len"], input_meta_data["d_model"] ], dtype=tf.float32) mems.append(zeros) return mems if input_meta_data["mem_len"] > 0: mem = strategy.run(cache_fn) for _ in tf.range(steps): mem = strategy.run( _replicated_step, args=( next(iterator), mem, )) else: for _ in tf.range(steps): strategy.run(_replicated_step, args=(next(iterator),)) if not run_eagerly: train_steps = tf.function(train_steps) logging.info("Start training...") checkpoint = tf.train.Checkpoint(model=model, optimizer=optimizer) latest_checkpoint_file = tf.train.latest_checkpoint(model_dir) if latest_checkpoint_file: logging.info("Checkpoint file %s found and restoring from checkpoint", latest_checkpoint_file) checkpoint.restore(latest_checkpoint_file) logging.info("Loading from checkpoint file completed") current_step = optimizer.iterations.numpy() checkpoint_name = "xlnet_step_{step}.ckpt" while current_step < total_training_steps: train_loss_metric.reset_states() if train_metric: train_metric.reset_states() steps = model_training_utils.steps_to_run(current_step, save_steps, steps_per_loop) train_steps(train_iterator, tf.convert_to_tensor(steps, dtype=tf.int32)) current_step += steps train_loss = _float_metric_value(train_loss_metric) log_stream = "Train step: %d/%d / lr = %.9f / loss = %.7f" % ( current_step, total_training_steps, learning_rate_fn(current_step), train_loss) if train_metric: log_stream += " / %s = %f" % (train_metric.name, _float_metric_value(train_metric)) logging.info(log_stream) if train_summary_writer: with train_summary_writer.as_default(): tf.summary.scalar( "learning_rate", learning_rate_fn(current_step), step=current_step) tf.summary.scalar( train_loss_metric.name, train_loss, step=current_step) if train_metric: tf.summary.scalar( train_metric.name, _float_metric_value(train_metric), step=current_step) train_summary_writer.flush() if model_dir and current_step % save_steps == 0: _save_checkpoint(checkpoint, model_dir, checkpoint_name.format(step=current_step)) if eval_fn and current_step % save_steps == 0: logging.info("Running evaluation after step: %s.", current_step) eval_fn(model, current_step, eval_summary_writer) if model_dir: _save_checkpoint(checkpoint, model_dir, checkpoint_name.format(step=current_step)) if eval_fn: logging.info("Running final evaluation after training is complete.") eval_metric = eval_fn(model, current_step, eval_summary_writer) training_summary = { "total_training_steps": total_training_steps, "train_loss": _float_metric_value(train_loss_metric), } if train_metric: training_summary["last_train_metrics"] = _float_metric_value(train_metric) if eval_fn: # eval_metric is supposed to be a float. training_summary["eval_metrics"] = eval_metric model_training_utils.write_txt_summary(training_summary, summary_dir) return model
11,664
37.120915
80
py
models
models-master/official/legacy/xlnet/preprocess_pretrain_data.py
# Copyright 2023 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. # -*- coding: utf-8 -*- """Script to pre-process pre-training data into tfrecords.""" import json import os import random # Import libraries from absl import app from absl import flags from absl import logging import numpy as np import tensorflow.compat.v1 as tf import sentencepiece as spm from official.legacy.xlnet import preprocess_utils FLAGS = flags.FLAGS special_symbols = { "<unk>": 0, "<s>": 1, "</s>": 2, "<cls>": 3, "<sep>": 4, "<pad>": 5, "<mask>": 6, "<eod>": 7, "<eop>": 8, } VOCAB_SIZE = 32000 UNK_ID = special_symbols["<unk>"] CLS_ID = special_symbols["<cls>"] SEP_ID = special_symbols["<sep>"] MASK_ID = special_symbols["<mask>"] EOD_ID = special_symbols["<eod>"] def _int64_feature(values): return tf.train.Feature(int64_list=tf.train.Int64List(value=values)) def _float_feature(values): return tf.train.Feature(float_list=tf.train.FloatList(value=values)) def format_filename(prefix, bsz_per_host, seq_len, bi_data, suffix, mask_alpha=5, mask_beta=1, reuse_len=None, uncased=False, fixed_num_predict=None): """docs.""" if reuse_len is None: reuse_len_str = "" else: reuse_len_str = "reuse-{}.".format(reuse_len) if not uncased: uncased_str = "" else: uncased_str = "uncased." if bi_data: bi_data_str = "bi" else: bi_data_str = "uni" if fixed_num_predict is not None: fnp_str = "fnp-{}.".format(fixed_num_predict) else: fnp_str = "" file_name = "{}.bsz-{}.seqlen-{}.{}{}{}.alpha-{}.beta-{}.{}{}".format( prefix, bsz_per_host, seq_len, reuse_len_str, uncased_str, bi_data_str, mask_alpha, mask_beta, fnp_str, suffix) return file_name def _create_data(idx, input_paths): """Creates data.""" # Load sentence-piece model sp = spm.SentencePieceProcessor() sp.Load(FLAGS.sp_path) input_shards = [] total_line_cnt = 0 for input_path in input_paths: input_data, sent_ids = [], [] sent_id, line_cnt = True, 0 logging.info("Processing %s", input_path) for line in tf.gfile.Open(input_path): if line_cnt % 100000 == 0: logging.info("Loading line %d", line_cnt) line_cnt += 1 if not line.strip(): if FLAGS.use_eod: sent_id = not sent_id cur_sent = [EOD_ID] else: continue else: if FLAGS.from_raw_text: cur_sent = preprocess_utils.preprocess_text( line.strip(), lower=FLAGS.uncased) cur_sent = preprocess_utils.encode_ids(sp, cur_sent) else: cur_sent = list(map(int, line.strip().split())) input_data.extend(cur_sent) sent_ids.extend([sent_id] * len(cur_sent)) sent_id = not sent_id logging.info("Finish with line %d", line_cnt) if line_cnt == 0: continue input_data = np.array(input_data, dtype=np.int64) sent_ids = np.array(sent_ids, dtype=bool) total_line_cnt += line_cnt input_shards.append((input_data, sent_ids)) logging.info("[Task %d] Total number line: %d", idx, total_line_cnt) tfrecord_dir = os.path.join(FLAGS.save_dir, "tfrecords") filenames, num_batch = [], 0 # Randomly shuffle input shards (with a fixed but distinct random seed) np.random.seed(100 * FLAGS.task + FLAGS.pass_id) perm_indices = np.random.permutation(len(input_shards)) logging.info("Using perm indices %s for pass %d", perm_indices.tolist(), FLAGS.pass_id) input_data_list, sent_ids_list = [], [] prev_sent_id = None for perm_idx in perm_indices: input_data, sent_ids = input_shards[perm_idx] # make sure the `send_ids[0] == not prev_sent_id` if prev_sent_id is not None and sent_ids[0] == prev_sent_id: sent_ids = np.logical_not(sent_ids) # append to temporary list input_data_list.append(input_data) sent_ids_list.append(sent_ids) # update `prev_sent_id` prev_sent_id = sent_ids[-1] input_data = np.concatenate(input_data_list) sent_ids = np.concatenate(sent_ids_list) file_name, cur_num_batch = create_tfrecords( save_dir=tfrecord_dir, basename="{}-{}-{}".format(FLAGS.split, idx, FLAGS.pass_id), data=[input_data, sent_ids], bsz_per_host=FLAGS.bsz_per_host, seq_len=FLAGS.seq_len, bi_data=FLAGS.bi_data, sp=sp, ) filenames.append(file_name) num_batch += cur_num_batch record_info = { "filenames": filenames, "num_batch": num_batch } return record_info def create_data(_): """Creates pretrain data.""" # Validate FLAGS assert FLAGS.bsz_per_host % FLAGS.num_core_per_host == 0 if not FLAGS.use_tpu: FLAGS.num_core_per_host = 1 # forced to be one # Make workdirs if not tf.gfile.Exists(FLAGS.save_dir): tf.gfile.MakeDirs(FLAGS.save_dir) tfrecord_dir = os.path.join(FLAGS.save_dir, "tfrecords") if not tf.gfile.Exists(tfrecord_dir): tf.gfile.MakeDirs(tfrecord_dir) # Create and dump corpus_info from task 0 if FLAGS.task == 0 and FLAGS.pass_id == 0: corpus_info = { "vocab_size": VOCAB_SIZE, "bsz_per_host": FLAGS.bsz_per_host, "num_core_per_host": FLAGS.num_core_per_host, "seq_len": FLAGS.seq_len, "reuse_len": FLAGS.reuse_len, "uncased": FLAGS.uncased, "bi_data": FLAGS.bi_data, "mask_alpha": FLAGS.mask_alpha, "mask_beta": FLAGS.mask_beta, "num_predict": FLAGS.num_predict, "use_eod": FLAGS.use_eod, "sp_path": FLAGS.sp_path, "input_glob": FLAGS.input_glob, } corpus_info_path = os.path.join(FLAGS.save_dir, "corpus_info.json") with tf.gfile.Open(corpus_info_path, "w") as fp: json.dump(corpus_info, fp) # Interleavely split the work into FLAGS.num_task splits file_paths = sorted(tf.gfile.Glob(FLAGS.input_glob)) logging.info("Use glob: %s", FLAGS.input_glob) logging.info("Find %d files: %s", len(file_paths), file_paths) task_file_paths = file_paths[FLAGS.task::FLAGS.num_task] if not task_file_paths: logging.info("Exit: task %d has no file to process.", FLAGS.task) return logging.info("Task %d process %d files: %s", FLAGS.task, len(task_file_paths), task_file_paths) record_info = _create_data(FLAGS.task, task_file_paths) record_prefix = "record_info-{}-{}-{}".format( FLAGS.split, FLAGS.task, FLAGS.pass_id) record_name = format_filename( prefix=record_prefix, bsz_per_host=FLAGS.bsz_per_host, seq_len=FLAGS.seq_len, mask_alpha=FLAGS.mask_alpha, mask_beta=FLAGS.mask_beta, reuse_len=FLAGS.reuse_len, bi_data=FLAGS.bi_data, suffix="json", uncased=FLAGS.uncased, fixed_num_predict=FLAGS.num_predict) record_info_path = os.path.join(tfrecord_dir, record_name) with tf.gfile.Open(record_info_path, "w") as fp: json.dump(record_info, fp) def batchify(data, bsz_per_host, sent_ids=None): """Creates batches.""" num_step = len(data) // bsz_per_host data = data[:bsz_per_host * num_step] data = data.reshape(bsz_per_host, num_step) if sent_ids is not None: sent_ids = sent_ids[:bsz_per_host * num_step] sent_ids = sent_ids.reshape(bsz_per_host, num_step) if sent_ids is not None: return data, sent_ids return data def _split_a_and_b(data, sent_ids, begin_idx, tot_len, extend_target=False): """Split two segments from `data` starting from the index `begin_idx`.""" data_len = data.shape[0] if begin_idx + tot_len >= data_len: logging.info("[_split_a_and_b] returns None: " "begin_idx %d + tot_len %d >= data_len %d", begin_idx, tot_len, data_len) return None end_idx = begin_idx + 1 cut_points = [] while end_idx < data_len: if sent_ids[end_idx] != sent_ids[end_idx - 1]: if end_idx - begin_idx >= tot_len: break cut_points.append(end_idx) end_idx += 1 a_begin = begin_idx if len(cut_points) == 0 or random.random() < 0.5: # pylint:disable=g-explicit-length-test label = 0 if len(cut_points) == 0: # pylint:disable=g-explicit-length-test a_end = end_idx else: a_end = random.choice(cut_points) b_len = max(1, tot_len - (a_end - a_begin)) # (zihangd): `data_len - 1` to account for extend_target b_begin = random.randint(0, data_len - 1 - b_len) b_end = b_begin + b_len while b_begin > 0 and sent_ids[b_begin - 1] == sent_ids[b_begin]: b_begin -= 1 # (zihangd): `data_len - 1` to account for extend_target while b_end < data_len - 1 and sent_ids[b_end - 1] == sent_ids[b_end]: b_end += 1 new_begin = a_end else: label = 1 a_end = random.choice(cut_points) b_begin = a_end b_end = end_idx new_begin = b_end while a_end - a_begin + b_end - b_begin > tot_len: if a_end - a_begin > b_end - b_begin: # delete the right side only for the LM objective a_end -= 1 else: b_end -= 1 ret = [data[a_begin: a_end], data[b_begin: b_end], label, new_begin] if extend_target: if a_end >= data_len or b_end >= data_len: logging.info("[_split_a_and_b] returns None: " "a_end %d or b_end %d >= data_len %d", a_end, b_end, data_len) return None a_target = data[a_begin + 1: a_end + 1] b_target = data[b_begin: b_end + 1] ret.extend([a_target, b_target]) return ret def _is_start_piece(piece): special_pieces = set(list('!"#$%&\"()*+,-./:;?@[\\]^_`{|}~')) if (piece.startswith("▁") or piece.startswith("<") or piece in special_pieces): return True else: return False def _sample_mask(sp, seg, reverse=False, max_gram=5, goal_num_predict=None): """Samples `goal_num_predict` tokens for partial prediction.""" seg_len = len(seg) mask = np.array([False] * seg_len, dtype=bool) num_predict = 0 ngrams = np.arange(1, max_gram + 1, dtype=np.int64) pvals = 1. / np.arange(1, max_gram + 1) pvals /= pvals.sum(keepdims=True) if reverse: seg = np.flip(seg, 0) cur_len = 0 while cur_len < seg_len: if goal_num_predict is not None and num_predict >= goal_num_predict: break n = np.random.choice(ngrams, p=pvals) if goal_num_predict is not None: n = min(n, goal_num_predict - num_predict) ctx_size = (n * FLAGS.mask_alpha) // FLAGS.mask_beta l_ctx = np.random.choice(ctx_size) r_ctx = ctx_size - l_ctx # Find the start position of a complete token beg = cur_len + l_ctx while beg < seg_len and not _is_start_piece(sp.IdToPiece(seg[beg].item())): beg += 1 if beg >= seg_len: break # Find the end position of the n-gram (start pos of the n+1-th gram) end = beg + 1 cnt_ngram = 1 while end < seg_len: cnt_ngram += 1 if cnt_ngram > n: break end += 1 if end >= seg_len: break # Update mask[beg:end] = True num_predict += end - beg cur_len = end + r_ctx while goal_num_predict is not None and num_predict < goal_num_predict: i = np.random.randint(seg_len) if not mask[i]: mask[i] = True num_predict += 1 if reverse: mask = np.flip(mask, 0) return mask def _sample_mask_ngram(sp, seg, reverse=False, max_gram=5, goal_num_predict=None): """Sample `goal_num_predict` tokens for partial prediction.""" seg_len = len(seg) mask = np.array([False] * seg_len, dtype=bool) num_predict = 0 ngrams = np.arange(1, max_gram + 1, dtype=np.int64) pvals = 1. / np.arange(1, max_gram + 1) pvals /= pvals.sum(keepdims=True) if reverse: seg = np.flip(seg, 0) cur_len = 0 while cur_len < seg_len: if goal_num_predict is not None and num_predict >= goal_num_predict: break n = np.random.choice(ngrams, p=pvals) if goal_num_predict is not None: n = min(n, goal_num_predict - num_predict) ctx_size = (n * FLAGS.mask_alpha) // FLAGS.mask_beta l_ctx = np.random.choice(ctx_size) r_ctx = ctx_size - l_ctx # Find the start position of a complete token beg = cur_len + l_ctx while beg < seg_len and not _is_start_piece(sp.IdToPiece(seg[beg].item())): beg += 1 if beg >= seg_len: break # Find the end position of the n-gram (start pos of the n+1-th gram) end = beg cnt_ngram = 0 while end < seg_len: if _is_start_piece(sp.IdToPiece(seg[end].item())): cnt_ngram += 1 if cnt_ngram > n: break # select current piece mask[end] = True # update the end pointer and increment num_predict end += 1 num_predict += 1 if goal_num_predict is not None and num_predict >= goal_num_predict: break cur_len = end + r_ctx while goal_num_predict is not None and num_predict < goal_num_predict: i = np.random.randint(seg_len) if not mask[i]: mask[i] = True num_predict += 1 if reverse: mask = np.flip(mask, 0) return mask def create_tfrecords(save_dir, basename, data, bsz_per_host, seq_len, bi_data, sp): """Creates TFRecords.""" data, sent_ids = data[0], data[1] num_core = FLAGS.num_core_per_host bsz_per_core = bsz_per_host // num_core if bi_data: assert bsz_per_host % (2 * FLAGS.num_core_per_host) == 0 fwd_data, fwd_sent_ids = batchify(data, bsz_per_host // 2, sent_ids) fwd_data = fwd_data.reshape(num_core, 1, bsz_per_core // 2, -1) fwd_sent_ids = fwd_sent_ids.reshape(num_core, 1, bsz_per_core // 2, -1) bwd_data = fwd_data[:, :, :, ::-1] bwd_sent_ids = fwd_sent_ids[:, :, :, ::-1] data = np.concatenate( [fwd_data, bwd_data], 1).reshape(bsz_per_host, -1) sent_ids = np.concatenate( [fwd_sent_ids, bwd_sent_ids], 1).reshape(bsz_per_host, -1) else: data, sent_ids = batchify(data, bsz_per_host, sent_ids) logging.info("Raw data shape %s.", data.shape) file_name = format_filename( prefix=basename, bsz_per_host=bsz_per_host, seq_len=seq_len, bi_data=bi_data, suffix="tfrecords", mask_alpha=FLAGS.mask_alpha, mask_beta=FLAGS.mask_beta, reuse_len=FLAGS.reuse_len, uncased=FLAGS.uncased, fixed_num_predict=FLAGS.num_predict ) save_path = os.path.join(save_dir, file_name) record_writer = tf.python_io.TFRecordWriter(save_path) logging.info("Start writing %s.", save_path) num_batch = 0 reuse_len = FLAGS.reuse_len # [sep] x 2 + [cls] assert reuse_len < seq_len - 3 data_len = data.shape[1] sep_array = np.array([SEP_ID], dtype=np.int64) cls_array = np.array([CLS_ID], dtype=np.int64) i = 0 while i + seq_len <= data_len: if num_batch % 500 == 0: logging.info("Processing batch %d", num_batch) all_ok = True features = [] for idx in range(bsz_per_host): inp = data[idx, i: i + reuse_len] tgt = data[idx, i + 1: i + reuse_len + 1] results = _split_a_and_b( data[idx], sent_ids[idx], begin_idx=i + reuse_len, tot_len=seq_len - reuse_len - 3, extend_target=True) if results is None: logging.info("Break out with seq idx %d", i) all_ok = False break # unpack the results (a_data, b_data, label, _, a_target, b_target) = tuple(results) # sample ngram spans to predict reverse = bi_data and (idx // (bsz_per_core // 2)) % 2 == 1 if FLAGS.num_predict is None: num_predict_0 = num_predict_1 = None else: num_predict_1 = FLAGS.num_predict // 2 num_predict_0 = FLAGS.num_predict - num_predict_1 mask_0 = _sample_mask(sp, inp, reverse=reverse, goal_num_predict=num_predict_0) mask_1 = _sample_mask(sp, np.concatenate([a_data, sep_array, b_data, sep_array, cls_array]), reverse=reverse, goal_num_predict=num_predict_1) # concatenate data cat_data = np.concatenate([inp, a_data, sep_array, b_data, sep_array, cls_array]) seg_id = ([0] * (reuse_len + a_data.shape[0]) + [0] + [1] * b_data.shape[0] + [1] + [2]) assert cat_data.shape[0] == seq_len assert mask_0.shape[0] == seq_len // 2 assert mask_1.shape[0] == seq_len // 2 # the last two CLS's are not used, just for padding purposes tgt = np.concatenate([tgt, a_target, b_target, cls_array, cls_array]) assert tgt.shape[0] == seq_len is_masked = np.concatenate([mask_0, mask_1], 0) if FLAGS.num_predict is not None: assert np.sum(is_masked) == FLAGS.num_predict feature = { "input": _int64_feature(cat_data), "is_masked": _int64_feature(is_masked), "target": _int64_feature(tgt), "seg_id": _int64_feature(seg_id), "label": _int64_feature([label]), } features.append(feature) if all_ok: assert len(features) == bsz_per_host for feature in features: example = tf.train.Example(features=tf.train.Features(feature=feature)) record_writer.write(example.SerializeToString()) num_batch += 1 else: break i += reuse_len record_writer.close() logging.info("Done writing %s. Num of batches: %d", save_path, num_batch) return save_path, num_batch ################ # get_input_fn # ################ def _convert_example(example, use_bfloat16): """Cast int64 into int32 and float32 to bfloat16 if use_bfloat16.""" for key in list(example.keys()): val = example[key] if tf.keras.backend.is_sparse(val): val = tf.sparse.to_dense(val) if val.dtype == tf.int64: val = tf.cast(val, tf.int32) if use_bfloat16 and val.dtype == tf.float32: val = tf.cast(val, tf.bfloat16) example[key] = val def parse_files_to_dataset(parser, file_names, split, num_batch, num_hosts, host_id, num_core_per_host, bsz_per_core): """Parses files to a dataset.""" del num_batch # list of file pathes num_files = len(file_names) num_files_per_host = num_files // num_hosts my_start_file_id = host_id * num_files_per_host my_end_file_id = (host_id + 1) * num_files_per_host if host_id == num_hosts - 1: my_end_file_id = num_files file_paths = file_names[my_start_file_id: my_end_file_id] logging.info("Host %d handles %d files", host_id, len(file_paths)) assert split == "train" dataset = tf.data.Dataset.from_tensor_slices(file_paths) # file-level shuffle if len(file_paths) > 1: dataset = dataset.shuffle(len(file_paths)) # Note: we cannot perform sample-level shuffle here because this will violate # the consecutive requirement of data stream. dataset = tf.data.TFRecordDataset(dataset) # Note: since we are doing online preprocessing, the parsed result of # the same input at each time will be different. Thus, cache processed data # is not helpful. It will use a lot of memory and lead to contrainer OOM. # So, change to cache non-parsed raw data instead. dataset = dataset.cache().map(parser).repeat() dataset = dataset.batch(bsz_per_core, drop_remainder=True) dataset = dataset.prefetch(num_core_per_host * bsz_per_core) return dataset def _local_perm(inputs, targets, is_masked, perm_size, seq_len): """Samples a permutation of the factorization order, and create a mask. Args: inputs: int64 Tensor in shape [seq_len], input ids. targets: int64 Tensor in shape [seq_len], target ids. is_masked: bool Tensor in shape [seq_len]. True means being selected for partial prediction. perm_size: the length of longest permutation. Could be set to be reuse_len. Should not be larger than reuse_len or there will be data leaks. seq_len: int, sequence length. Returns: The permutation mask, new targets, target mask, and new inputs. """ # Generate permutation indices index = tf.range(seq_len, dtype=tf.int64) index = tf.transpose(tf.reshape(index, [-1, perm_size])) index = tf.random_shuffle(index) index = tf.reshape(tf.transpose(index), [-1]) # `perm_mask` and `target_mask` # non-functional tokens non_func_tokens = tf.logical_not(tf.logical_or( tf.equal(inputs, SEP_ID), tf.equal(inputs, CLS_ID))) non_mask_tokens = tf.logical_and(tf.logical_not(is_masked), non_func_tokens) masked_or_func_tokens = tf.logical_not(non_mask_tokens) # Set the permutation indices of non-masked (& non-funcional) tokens to the # smallest index (-1): # (1) they can be seen by all other positions # (2) they cannot see masked positions, so there won"t be information leak smallest_index = -tf.ones([seq_len], dtype=tf.int64) rev_index = tf.where(non_mask_tokens, smallest_index, index) # Create `target_mask`: non-funcional and maksed tokens # 1: use mask as input and have loss # 0: use token (or [SEP], [CLS]) as input and do not have loss target_tokens = tf.logical_and(masked_or_func_tokens, non_func_tokens) target_mask = tf.cast(target_tokens, tf.float32) # Create `perm_mask` # `target_tokens` cannot see themselves self_rev_index = tf.where(target_tokens, rev_index, rev_index + 1) # 1: cannot attend if i <= j and j is not non-masked (masked_or_func_tokens) # 0: can attend if i > j or j is non-masked perm_mask = tf.logical_and( self_rev_index[:, None] <= rev_index[None, :], masked_or_func_tokens) perm_mask = tf.cast(perm_mask, tf.float32) # new target: [next token] for LM and [curr token] (self) for PLM new_targets = tf.concat([inputs[0: 1], targets[: -1]], axis=0) # construct inputs_k inputs_k = inputs # construct inputs_q inputs_q = target_mask return perm_mask, new_targets, target_mask, inputs_k, inputs_q def get_dataset(params, num_hosts, num_core_per_host, split, file_names, num_batch, seq_len, reuse_len, perm_size, mask_alpha, mask_beta, use_bfloat16=False, num_predict=None): """Gets the dataset.""" del mask_alpha del mask_beta bsz_per_core = params["batch_size"] if num_hosts > 1: host_id = params["context"].current_host else: host_id = 0 #### Function used to parse tfrecord def parser(record): """function used to parse tfrecord.""" record_spec = { "input": tf.FixedLenFeature([seq_len], tf.int64), "target": tf.FixedLenFeature([seq_len], tf.int64), "seg_id": tf.FixedLenFeature([seq_len], tf.int64), "label": tf.FixedLenFeature([1], tf.int64), "is_masked": tf.FixedLenFeature([seq_len], tf.int64), } # retrieve serialized example example = tf.parse_single_example( serialized=record, features=record_spec) inputs = example.pop("input") target = example.pop("target") is_masked = tf.cast(example.pop("is_masked"), tf.bool) non_reuse_len = seq_len - reuse_len assert perm_size <= reuse_len and perm_size <= non_reuse_len perm_mask_0, target_0, target_mask_0, input_k_0, input_q_0 = _local_perm( inputs[:reuse_len], target[:reuse_len], is_masked[:reuse_len], perm_size, reuse_len) perm_mask_1, target_1, target_mask_1, input_k_1, input_q_1 = _local_perm( inputs[reuse_len:], target[reuse_len:], is_masked[reuse_len:], perm_size, non_reuse_len) perm_mask_0 = tf.concat([perm_mask_0, tf.ones([reuse_len, non_reuse_len])], axis=1) perm_mask_1 = tf.concat([tf.zeros([non_reuse_len, reuse_len]), perm_mask_1], axis=1) perm_mask = tf.concat([perm_mask_0, perm_mask_1], axis=0) target = tf.concat([target_0, target_1], axis=0) target_mask = tf.concat([target_mask_0, target_mask_1], axis=0) input_k = tf.concat([input_k_0, input_k_1], axis=0) input_q = tf.concat([input_q_0, input_q_1], axis=0) if num_predict is not None: indices = tf.range(seq_len, dtype=tf.int64) bool_target_mask = tf.cast(target_mask, tf.bool) indices = tf.boolean_mask(indices, bool_target_mask) ##### extra padding due to CLS/SEP introduced after prepro actual_num_predict = tf.shape(indices)[0] pad_len = num_predict - actual_num_predict ##### target_mapping target_mapping = tf.one_hot(indices, seq_len, dtype=tf.float32) paddings = tf.zeros([pad_len, seq_len], dtype=target_mapping.dtype) target_mapping = tf.concat([target_mapping, paddings], axis=0) example["target_mapping"] = tf.reshape(target_mapping, [num_predict, seq_len]) ##### target target = tf.boolean_mask(target, bool_target_mask) paddings = tf.zeros([pad_len], dtype=target.dtype) target = tf.concat([target, paddings], axis=0) example["target"] = tf.reshape(target, [num_predict]) ##### target mask target_mask = tf.concat( [tf.ones([actual_num_predict], dtype=tf.float32), tf.zeros([pad_len], dtype=tf.float32)], axis=0) example["target_mask"] = tf.reshape(target_mask, [num_predict]) else: example["target"] = tf.reshape(target, [seq_len]) example["target_mask"] = tf.reshape(target_mask, [seq_len]) # reshape back to fixed shape example["perm_mask"] = tf.reshape(perm_mask, [seq_len, seq_len]) example["input_k"] = tf.reshape(input_k, [seq_len]) example["input_q"] = tf.reshape(input_q, [seq_len]) _convert_example(example, use_bfloat16) for k, v in example.items(): logging.info("%s: %s", k, v) return example # Get dataset dataset = parse_files_to_dataset( parser=parser, file_names=file_names, split=split, num_batch=num_batch, num_hosts=num_hosts, host_id=host_id, num_core_per_host=num_core_per_host, bsz_per_core=bsz_per_core) return dataset def get_input_fn( tfrecord_dir, split, bsz_per_host, seq_len, reuse_len, bi_data, num_hosts=1, num_core_per_host=1, perm_size=None, mask_alpha=None, mask_beta=None, uncased=False, num_passes=None, use_bfloat16=False, num_predict=None): """Gets the input function.""" # Merge all record infos into a single one record_glob_base = format_filename( prefix="record_info-{}-*".format(split), bsz_per_host=bsz_per_host, seq_len=seq_len, bi_data=bi_data, suffix="json", mask_alpha=mask_alpha, mask_beta=mask_beta, reuse_len=reuse_len, uncased=uncased, fixed_num_predict=num_predict) record_info = {"num_batch": 0, "filenames": []} tfrecord_dirs = tfrecord_dir.split(",") logging.info("Use the following tfrecord dirs: %s", tfrecord_dirs) for idx, record_dir in enumerate(tfrecord_dirs): record_glob = os.path.join(record_dir, record_glob_base) logging.info("[%d] Record glob: %s", idx, record_glob) record_paths = sorted(tf.gfile.Glob(record_glob)) logging.info("[%d] Num of record info path: %d", idx, len(record_paths)) cur_record_info = {"num_batch": 0, "filenames": []} for record_info_path in record_paths: if num_passes is not None: record_info_name = os.path.basename(record_info_path) fields = record_info_name.split(".")[0].split("-") pass_id = int(fields[-1]) if len(fields) == 5 and pass_id >= num_passes: logging.info("Skip pass %d: %s", pass_id, record_info_name) continue with tf.gfile.Open(record_info_path, "r") as fp: info = json.load(fp) if num_passes is not None: eff_num_passes = min(num_passes, len(info["filenames"])) ratio = eff_num_passes / len(info["filenames"]) cur_record_info["num_batch"] += int(info["num_batch"] * ratio) cur_record_info["filenames"] += info["filenames"][:eff_num_passes] else: cur_record_info["num_batch"] += info["num_batch"] cur_record_info["filenames"] += info["filenames"] # overwrite directory for `cur_record_info` new_filenames = [] for filename in cur_record_info["filenames"]: basename = os.path.basename(filename) new_filename = os.path.join(record_dir, basename) new_filenames.append(new_filename) cur_record_info["filenames"] = new_filenames logging.info("[Dir %d] Number of chosen batches: %s", idx, cur_record_info["num_batch"]) logging.info("[Dir %d] Number of chosen files: %s", idx, len(cur_record_info["filenames"])) logging.info(cur_record_info["filenames"]) # add `cur_record_info` to global `record_info` record_info["num_batch"] += cur_record_info["num_batch"] record_info["filenames"] += cur_record_info["filenames"] logging.info("Total number of batches: %d", record_info["num_batch"]) logging.info("Total number of files: %d", len(record_info["filenames"])) logging.info(record_info["filenames"]) def input_fn(params): """docs.""" assert params["batch_size"] * num_core_per_host == bsz_per_host dataset = get_dataset( params=params, num_hosts=num_hosts, num_core_per_host=num_core_per_host, split=split, file_names=record_info["filenames"], num_batch=record_info["num_batch"], seq_len=seq_len, reuse_len=reuse_len, perm_size=perm_size, mask_alpha=mask_alpha, mask_beta=mask_beta, use_bfloat16=use_bfloat16, num_predict=num_predict) return dataset return input_fn, record_info def define_flags(): """Defines relevant flags.""" flags.DEFINE_bool("use_tpu", True, help="whether to use TPUs") flags.DEFINE_integer("bsz_per_host", 32, help="batch size per host.") flags.DEFINE_integer("num_core_per_host", 8, help="num TPU cores per host.") flags.DEFINE_integer("seq_len", 512, help="Sequence length.") flags.DEFINE_integer("reuse_len", 256, help="Number of token that can be reused as memory. " "Could be half of `seq_len`.") flags.DEFINE_bool("uncased", False, help="Use uncased inputs or not.") flags.DEFINE_bool("bi_data", True, help="whether to create bidirectional data") flags.DEFINE_integer("mask_alpha", default=6, help="How many tokens to form a group.") flags.DEFINE_integer("mask_beta", default=1, help="How many tokens to mask within each group.") flags.DEFINE_bool("use_eod", True, help="whether to append EOD at the end of a doc.") flags.DEFINE_bool("from_raw_text", True, help="Whether the input is raw text or encoded ids.") flags.DEFINE_integer("num_predict", default=85, help="Num of tokens to predict.") flags.DEFINE_string("input_glob", "data/example/*.txt", help="Input file glob.") flags.DEFINE_string("sp_path", "", help="Path to the sentence piece model.") flags.DEFINE_string("save_dir", "proc_data/example", help="Directory for saving the processed data.") flags.DEFINE_enum("split", "train", ["train", "dev", "test"], help="Save the data as which split.") flags.DEFINE_integer("pass_id", 0, help="ID of the current pass." "Different passes sample different negative segment.") flags.DEFINE_integer("num_task", 1, help="Number of total tasks.") flags.DEFINE_integer("task", 0, help="The Task ID. This value is used when " "using multiple workers to identify each worker.") if __name__ == "__main__": define_flags() logging.set_verbosity(logging.INFO) app.run(create_data)
32,389
31.196819
92
py
models
models-master/official/legacy/bert/export_tfhub.py
# Copyright 2023 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. """A script to export BERT as a TF-Hub SavedModel. This script is **DEPRECATED** for exporting BERT encoder models; see the error message in by main() for details. """ from typing import Text # Import libraries from absl import app from absl import flags from absl import logging import tensorflow as tf from official.legacy.bert import bert_models from official.legacy.bert import configs FLAGS = flags.FLAGS flags.DEFINE_string("bert_config_file", None, "Bert configuration file to define core bert layers.") flags.DEFINE_string("model_checkpoint_path", None, "File path to TF model checkpoint.") flags.DEFINE_string("export_path", None, "TF-Hub SavedModel destination path.") flags.DEFINE_string("vocab_file", None, "The vocabulary file that the BERT model was trained on.") flags.DEFINE_bool( "do_lower_case", None, "Whether to lowercase. If None, " "do_lower_case will be enabled if 'uncased' appears in the " "name of --vocab_file") flags.DEFINE_enum("model_type", "encoder", ["encoder", "squad"], "What kind of BERT model to export.") def create_bert_model(bert_config: configs.BertConfig) -> tf.keras.Model: """Creates a BERT keras core model from BERT configuration. Args: bert_config: A `BertConfig` to create the core model. Returns: A keras model. """ # Adds input layers just as placeholders. input_word_ids = tf.keras.layers.Input( shape=(None,), dtype=tf.int32, name="input_word_ids") input_mask = tf.keras.layers.Input( shape=(None,), dtype=tf.int32, name="input_mask") input_type_ids = tf.keras.layers.Input( shape=(None,), dtype=tf.int32, name="input_type_ids") transformer_encoder = bert_models.get_transformer_encoder( bert_config, sequence_length=None) sequence_output, pooled_output = transformer_encoder( [input_word_ids, input_mask, input_type_ids]) # To keep consistent with legacy hub modules, the outputs are # "pooled_output" and "sequence_output". return tf.keras.Model( inputs=[input_word_ids, input_mask, input_type_ids], outputs=[pooled_output, sequence_output]), transformer_encoder def export_bert_tfhub(bert_config: configs.BertConfig, model_checkpoint_path: Text, hub_destination: Text, vocab_file: Text, do_lower_case: bool = None): """Restores a tf.keras.Model and saves for TF-Hub.""" # If do_lower_case is not explicit, default to checking whether "uncased" is # in the vocab file name if do_lower_case is None: do_lower_case = "uncased" in vocab_file logging.info("Using do_lower_case=%s based on name of vocab_file=%s", do_lower_case, vocab_file) core_model, encoder = create_bert_model(bert_config) checkpoint = tf.train.Checkpoint( model=encoder, # Legacy checkpoints. encoder=encoder) checkpoint.restore(model_checkpoint_path).assert_existing_objects_matched() core_model.vocab_file = tf.saved_model.Asset(vocab_file) core_model.do_lower_case = tf.Variable(do_lower_case, trainable=False) core_model.save(hub_destination, include_optimizer=False, save_format="tf") def export_bert_squad_tfhub(bert_config: configs.BertConfig, model_checkpoint_path: Text, hub_destination: Text, vocab_file: Text, do_lower_case: bool = None): """Restores a tf.keras.Model for BERT with SQuAD and saves for TF-Hub.""" # If do_lower_case is not explicit, default to checking whether "uncased" is # in the vocab file name if do_lower_case is None: do_lower_case = "uncased" in vocab_file logging.info("Using do_lower_case=%s based on name of vocab_file=%s", do_lower_case, vocab_file) span_labeling, _ = bert_models.squad_model(bert_config, max_seq_length=None) checkpoint = tf.train.Checkpoint(model=span_labeling) checkpoint.restore(model_checkpoint_path).assert_existing_objects_matched() span_labeling.vocab_file = tf.saved_model.Asset(vocab_file) span_labeling.do_lower_case = tf.Variable(do_lower_case, trainable=False) span_labeling.save(hub_destination, include_optimizer=False, save_format="tf") def main(_): bert_config = configs.BertConfig.from_json_file(FLAGS.bert_config_file) if FLAGS.model_type == "encoder": deprecation_note = ( "nlp/bert/export_tfhub is **DEPRECATED** for exporting BERT encoder " "models. Please switch to nlp/tools/export_tfhub for exporting BERT " "(and other) encoders with dict inputs/outputs conforming to " "https://www.tensorflow.org/hub/common_saved_model_apis/text#transformer-encoders" ) logging.error(deprecation_note) print("\n\nNOTICE:", deprecation_note, "\n") export_bert_tfhub(bert_config, FLAGS.model_checkpoint_path, FLAGS.export_path, FLAGS.vocab_file, FLAGS.do_lower_case) elif FLAGS.model_type == "squad": export_bert_squad_tfhub(bert_config, FLAGS.model_checkpoint_path, FLAGS.export_path, FLAGS.vocab_file, FLAGS.do_lower_case) else: raise ValueError("Unsupported model_type %s." % FLAGS.model_type) if __name__ == "__main__": app.run(main)
5,966
41.621429
90
py
models
models-master/official/legacy/bert/serving.py
# Copyright 2023 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. """Examples of SavedModel export for tf-serving.""" from absl import app from absl import flags import tensorflow as tf from official.legacy.bert import bert_models from official.legacy.bert import configs flags.DEFINE_integer( "sequence_length", None, "Sequence length to parse the tf.Example. If " "sequence_length > 0, add a signature for serialized " "tf.Example and define the parsing specification by the " "sequence_length.") flags.DEFINE_string("bert_config_file", None, "Bert configuration file to define core bert layers.") flags.DEFINE_string("model_checkpoint_path", None, "File path to TF model checkpoint.") flags.DEFINE_string("export_path", None, "Destination folder to export the serving SavedModel.") FLAGS = flags.FLAGS class BertServing(tf.keras.Model): """Bert transformer encoder model for serving.""" def __init__(self, bert_config, name_to_features=None, name="serving_model"): super(BertServing, self).__init__(name=name) self.encoder = bert_models.get_transformer_encoder( bert_config, sequence_length=None) self.name_to_features = name_to_features def call(self, inputs): input_word_ids = inputs["input_ids"] input_mask = inputs["input_mask"] input_type_ids = inputs["segment_ids"] encoder_outputs, _ = self.encoder( [input_word_ids, input_mask, input_type_ids]) return encoder_outputs def serve_body(self, input_ids, input_mask=None, segment_ids=None): if segment_ids is None: # Requires CLS token is the first token of inputs. segment_ids = tf.zeros_like(input_ids) if input_mask is None: # The mask has 1 for real tokens and 0 for padding tokens. input_mask = tf.where( tf.equal(input_ids, 0), tf.zeros_like(input_ids), tf.ones_like(input_ids)) inputs = dict( input_ids=input_ids, input_mask=input_mask, segment_ids=segment_ids) return self.call(inputs) @tf.function def serve(self, input_ids, input_mask=None, segment_ids=None): outputs = self.serve_body(input_ids, input_mask, segment_ids) # Returns a dictionary to control SignatureDef output signature. return {"outputs": outputs[-1]} @tf.function def serve_examples(self, inputs): features = tf.io.parse_example(inputs, self.name_to_features) for key in list(features.keys()): t = features[key] if t.dtype == tf.int64: t = tf.cast(t, tf.int32) features[key] = t return self.serve( features["input_ids"], input_mask=features["input_mask"] if "input_mask" in features else None, segment_ids=features["segment_ids"] if "segment_ids" in features else None) @classmethod def export(cls, model, export_dir): if not isinstance(model, cls): raise ValueError("Invalid model instance: %s, it should be a %s" % (model, cls)) signatures = { "serving_default": model.serve.get_concrete_function( input_ids=tf.TensorSpec( shape=[None, None], dtype=tf.int32, name="inputs")), } if model.name_to_features: signatures[ "serving_examples"] = model.serve_examples.get_concrete_function( tf.TensorSpec(shape=[None], dtype=tf.string, name="examples")) tf.saved_model.save(model, export_dir=export_dir, signatures=signatures) def main(_): sequence_length = FLAGS.sequence_length if sequence_length is not None and sequence_length > 0: name_to_features = { "input_ids": tf.io.FixedLenFeature([sequence_length], tf.int64), "input_mask": tf.io.FixedLenFeature([sequence_length], tf.int64), "segment_ids": tf.io.FixedLenFeature([sequence_length], tf.int64), } else: name_to_features = None bert_config = configs.BertConfig.from_json_file(FLAGS.bert_config_file) serving_model = BertServing( bert_config=bert_config, name_to_features=name_to_features) checkpoint = tf.train.Checkpoint(model=serving_model.encoder) checkpoint.restore(FLAGS.model_checkpoint_path ).assert_existing_objects_matched().run_restore_ops() BertServing.export(serving_model, FLAGS.export_path) if __name__ == "__main__": flags.mark_flag_as_required("bert_config_file") flags.mark_flag_as_required("model_checkpoint_path") flags.mark_flag_as_required("export_path") app.run(main)
5,054
36.723881
80
py
models
models-master/official/legacy/bert/run_squad.py
# Copyright 2023 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. """Run BERT on SQuAD 1.1 and SQuAD 2.0 in TF 2.x.""" import json import os import time # Import libraries from absl import app from absl import flags from absl import logging import gin import tensorflow as tf from official.common import distribute_utils from official.legacy.bert import configs as bert_configs from official.legacy.bert import run_squad_helper from official.nlp.data import squad_lib as squad_lib_wp from official.nlp.tools import tokenization from official.utils.misc import keras_utils flags.DEFINE_string('vocab_file', None, 'The vocabulary file that the BERT model was trained on.') # More flags can be found in run_squad_helper. run_squad_helper.define_common_squad_flags() FLAGS = flags.FLAGS def train_squad(strategy, input_meta_data, custom_callbacks=None, run_eagerly=False, init_checkpoint=None, sub_model_export_name=None): """Run bert squad training.""" bert_config = bert_configs.BertConfig.from_json_file(FLAGS.bert_config_file) init_checkpoint = init_checkpoint or FLAGS.init_checkpoint run_squad_helper.train_squad(strategy, input_meta_data, bert_config, custom_callbacks, run_eagerly, init_checkpoint, sub_model_export_name=sub_model_export_name) def predict_squad(strategy, input_meta_data): """Makes predictions for the squad dataset.""" bert_config = bert_configs.BertConfig.from_json_file(FLAGS.bert_config_file) tokenizer = tokenization.FullTokenizer( vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case) run_squad_helper.predict_squad( strategy, input_meta_data, tokenizer, bert_config, squad_lib_wp) def eval_squad(strategy, input_meta_data): """Evaluate on the squad dataset.""" bert_config = bert_configs.BertConfig.from_json_file(FLAGS.bert_config_file) tokenizer = tokenization.FullTokenizer( vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case) eval_metrics = run_squad_helper.eval_squad( strategy, input_meta_data, tokenizer, bert_config, squad_lib_wp) return eval_metrics def export_squad(model_export_path, input_meta_data): """Exports a trained model as a `SavedModel` for inference. Args: model_export_path: a string specifying the path to the SavedModel directory. input_meta_data: dictionary containing meta data about input and model. Raises: Export path is not specified, got an empty string or None. """ bert_config = bert_configs.BertConfig.from_json_file(FLAGS.bert_config_file) run_squad_helper.export_squad(model_export_path, input_meta_data, bert_config) def main(_): gin.parse_config_files_and_bindings(FLAGS.gin_file, FLAGS.gin_param) with tf.io.gfile.GFile(FLAGS.input_meta_data_path, 'rb') as reader: input_meta_data = json.loads(reader.read().decode('utf-8')) if FLAGS.mode == 'export_only': export_squad(FLAGS.model_export_path, input_meta_data) return # Configures cluster spec for multi-worker distribution strategy. if FLAGS.num_gpus > 0: _ = distribute_utils.configure_cluster(FLAGS.worker_hosts, FLAGS.task_index) strategy = distribute_utils.get_distribution_strategy( distribution_strategy=FLAGS.distribution_strategy, num_gpus=FLAGS.num_gpus, all_reduce_alg=FLAGS.all_reduce_alg, tpu_address=FLAGS.tpu) if 'train' in FLAGS.mode: if FLAGS.log_steps: custom_callbacks = [keras_utils.TimeHistory( batch_size=FLAGS.train_batch_size, log_steps=FLAGS.log_steps, logdir=FLAGS.model_dir, )] else: custom_callbacks = None train_squad( strategy, input_meta_data, custom_callbacks=custom_callbacks, run_eagerly=FLAGS.run_eagerly, sub_model_export_name=FLAGS.sub_model_export_name, ) if 'predict' in FLAGS.mode: predict_squad(strategy, input_meta_data) if 'eval' in FLAGS.mode: eval_metrics = eval_squad(strategy, input_meta_data) f1_score = eval_metrics['final_f1'] logging.info('SQuAD eval F1-score: %f', f1_score) summary_dir = os.path.join(FLAGS.model_dir, 'summaries', 'eval') summary_writer = tf.summary.create_file_writer(summary_dir) with summary_writer.as_default(): # TODO(lehou): write to the correct step number. tf.summary.scalar('F1-score', f1_score, step=0) summary_writer.flush() # Also write eval_metrics to json file. squad_lib_wp.write_to_json_files( eval_metrics, os.path.join(summary_dir, 'eval_metrics.json')) time.sleep(60) if __name__ == '__main__': flags.mark_flag_as_required('bert_config_file') flags.mark_flag_as_required('model_dir') app.run(main)
5,366
35.020134
80
py
models
models-master/official/legacy/bert/export_tfhub_test.py
# Copyright 2023 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. """Tests official.nlp.bert.export_tfhub.""" import os from absl.testing import parameterized import numpy as np import tensorflow as tf import tensorflow_hub as hub from official.legacy.bert import configs from official.legacy.bert import export_tfhub class ExportTfhubTest(tf.test.TestCase, parameterized.TestCase): @parameterized.parameters("model", "encoder") def test_export_tfhub(self, ckpt_key_name): # Exports a savedmodel for TF-Hub hidden_size = 16 bert_config = configs.BertConfig( vocab_size=100, hidden_size=hidden_size, intermediate_size=32, max_position_embeddings=128, num_attention_heads=2, num_hidden_layers=1) bert_model, encoder = export_tfhub.create_bert_model(bert_config) model_checkpoint_dir = os.path.join(self.get_temp_dir(), "checkpoint") checkpoint = tf.train.Checkpoint(**{ckpt_key_name: encoder}) checkpoint.save(os.path.join(model_checkpoint_dir, "test")) model_checkpoint_path = tf.train.latest_checkpoint(model_checkpoint_dir) vocab_file = os.path.join(self.get_temp_dir(), "uncased_vocab.txt") with tf.io.gfile.GFile(vocab_file, "w") as f: f.write("dummy content") hub_destination = os.path.join(self.get_temp_dir(), "hub") export_tfhub.export_bert_tfhub(bert_config, model_checkpoint_path, hub_destination, vocab_file) # Restores a hub KerasLayer. hub_layer = hub.KerasLayer(hub_destination, trainable=True) if hasattr(hub_layer, "resolved_object"): # Checks meta attributes. self.assertTrue(hub_layer.resolved_object.do_lower_case.numpy()) with tf.io.gfile.GFile( hub_layer.resolved_object.vocab_file.asset_path.numpy()) as f: self.assertEqual("dummy content", f.read()) # Checks the hub KerasLayer. for source_weight, hub_weight in zip(bert_model.trainable_weights, hub_layer.trainable_weights): self.assertAllClose(source_weight.numpy(), hub_weight.numpy()) seq_length = 10 dummy_ids = np.zeros((2, seq_length), dtype=np.int32) hub_outputs = hub_layer([dummy_ids, dummy_ids, dummy_ids]) source_outputs = bert_model([dummy_ids, dummy_ids, dummy_ids]) # The outputs of hub module are "pooled_output" and "sequence_output", # while the outputs of encoder is in reversed order, i.e., # "sequence_output" and "pooled_output". encoder_outputs = reversed(encoder([dummy_ids, dummy_ids, dummy_ids])) self.assertEqual(hub_outputs[0].shape, (2, hidden_size)) self.assertEqual(hub_outputs[1].shape, (2, seq_length, hidden_size)) for source_output, hub_output, encoder_output in zip( source_outputs, hub_outputs, encoder_outputs): self.assertAllClose(source_output.numpy(), hub_output.numpy()) self.assertAllClose(source_output.numpy(), encoder_output.numpy()) # Test that training=True makes a difference (activates dropout). def _dropout_mean_stddev(training, num_runs=20): input_ids = np.array([[14, 12, 42, 95, 99]], np.int32) inputs = [input_ids, np.ones_like(input_ids), np.zeros_like(input_ids)] outputs = np.concatenate( [hub_layer(inputs, training=training)[0] for _ in range(num_runs)]) return np.mean(np.std(outputs, axis=0)) self.assertLess(_dropout_mean_stddev(training=False), 1e-6) self.assertGreater(_dropout_mean_stddev(training=True), 1e-3) # Test propagation of seq_length in shape inference. input_word_ids = tf.keras.layers.Input(shape=(seq_length,), dtype=tf.int32) input_mask = tf.keras.layers.Input(shape=(seq_length,), dtype=tf.int32) input_type_ids = tf.keras.layers.Input(shape=(seq_length,), dtype=tf.int32) pooled_output, sequence_output = hub_layer( [input_word_ids, input_mask, input_type_ids]) self.assertEqual(pooled_output.shape.as_list(), [None, hidden_size]) self.assertEqual(sequence_output.shape.as_list(), [None, seq_length, hidden_size]) if __name__ == "__main__": tf.test.main()
4,688
42.018349
79
py
models
models-master/official/legacy/bert/run_classifier.py
# Copyright 2023 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. """BERT classification or regression finetuning runner in TF 2.x.""" import functools import json import math import os # Import libraries from absl import app from absl import flags from absl import logging import gin import tensorflow as tf from official.common import distribute_utils from official.legacy.bert import bert_models from official.legacy.bert import common_flags from official.legacy.bert import configs as bert_configs from official.legacy.bert import input_pipeline from official.legacy.bert import model_saving_utils from official.modeling import performance from official.nlp import optimization from official.utils.misc import keras_utils flags.DEFINE_enum( 'mode', 'train_and_eval', ['train_and_eval', 'export_only', 'predict'], 'One of {"train_and_eval", "export_only", "predict"}. `train_and_eval`: ' 'trains the model and evaluates in the meantime. ' '`export_only`: will take the latest checkpoint inside ' 'model_dir and export a `SavedModel`. `predict`: takes a checkpoint and ' 'restores the model to output predictions on the test set.') flags.DEFINE_string('train_data_path', None, 'Path to training data for BERT classifier.') flags.DEFINE_string('eval_data_path', None, 'Path to evaluation data for BERT classifier.') flags.DEFINE_string( 'input_meta_data_path', None, 'Path to file that contains meta data about input ' 'to be used for training and evaluation.') flags.DEFINE_integer('train_data_size', None, 'Number of training samples ' 'to use. If None, uses the full train data. ' '(default: None).') flags.DEFINE_string('predict_checkpoint_path', None, 'Path to the checkpoint for predictions.') flags.DEFINE_integer( 'num_eval_per_epoch', 1, 'Number of evaluations per epoch. The purpose of this flag is to provide ' 'more granular evaluation scores and checkpoints. For example, if original ' 'data has N samples and num_eval_per_epoch is n, then each epoch will be ' 'evaluated every N/n samples.') flags.DEFINE_integer('train_batch_size', 32, 'Batch size for training.') flags.DEFINE_integer('eval_batch_size', 32, 'Batch size for evaluation.') common_flags.define_common_bert_flags() FLAGS = flags.FLAGS LABEL_TYPES_MAP = {'int': tf.int64, 'float': tf.float32} def get_loss_fn(num_classes): """Gets the classification loss function.""" def classification_loss_fn(labels, logits): """Classification loss.""" labels = tf.reshape(labels, [-1]) log_probs = tf.nn.log_softmax(logits, axis=-1) one_hot_labels = tf.one_hot( tf.cast(labels, dtype=tf.int32), depth=num_classes, dtype=tf.float32) per_example_loss = -tf.reduce_sum( tf.cast(one_hot_labels, dtype=tf.float32) * log_probs, axis=-1) return tf.reduce_mean(per_example_loss) return classification_loss_fn def get_dataset_fn(input_file_pattern, max_seq_length, global_batch_size, is_training, label_type=tf.int64, include_sample_weights=False, num_samples=None): """Gets a closure to create a dataset.""" def _dataset_fn(ctx=None): """Returns tf.data.Dataset for distributed BERT pretraining.""" batch_size = ctx.get_per_replica_batch_size( global_batch_size) if ctx else global_batch_size dataset = input_pipeline.create_classifier_dataset( tf.io.gfile.glob(input_file_pattern), max_seq_length, batch_size, is_training=is_training, input_pipeline_context=ctx, label_type=label_type, include_sample_weights=include_sample_weights, num_samples=num_samples) return dataset return _dataset_fn def run_bert_classifier(strategy, bert_config, input_meta_data, model_dir, epochs, steps_per_epoch, steps_per_loop, eval_steps, warmup_steps, initial_lr, init_checkpoint, train_input_fn, eval_input_fn, training_callbacks=True, custom_callbacks=None, custom_metrics=None): """Run BERT classifier training using low-level API.""" max_seq_length = input_meta_data['max_seq_length'] num_classes = input_meta_data.get('num_labels', 1) is_regression = num_classes == 1 def _get_classifier_model(): """Gets a classifier model.""" classifier_model, core_model = ( bert_models.classifier_model( bert_config, num_classes, max_seq_length, hub_module_url=FLAGS.hub_module_url, hub_module_trainable=FLAGS.hub_module_trainable)) optimizer = optimization.create_optimizer(initial_lr, steps_per_epoch * epochs, warmup_steps, FLAGS.end_lr, FLAGS.optimizer_type) classifier_model.optimizer = performance.configure_optimizer( optimizer, use_float16=common_flags.use_float16()) return classifier_model, core_model # tf.keras.losses objects accept optional sample_weight arguments (eg. coming # from the dataset) to compute weighted loss, as used for the regression # tasks. The classification tasks, using the custom get_loss_fn don't accept # sample weights though. loss_fn = (tf.keras.losses.MeanSquaredError() if is_regression else get_loss_fn(num_classes)) # Defines evaluation metrics function, which will create metrics in the # correct device and strategy scope. if custom_metrics: metric_fn = custom_metrics elif is_regression: metric_fn = functools.partial( tf.keras.metrics.MeanSquaredError, 'mean_squared_error', dtype=tf.float32) else: metric_fn = functools.partial( tf.keras.metrics.SparseCategoricalAccuracy, 'accuracy', dtype=tf.float32) # Start training using Keras compile/fit API. logging.info('Training using TF 2.x Keras compile/fit API with ' 'distribution strategy.') return run_keras_compile_fit( model_dir, strategy, _get_classifier_model, train_input_fn, eval_input_fn, loss_fn, metric_fn, init_checkpoint, epochs, steps_per_epoch, steps_per_loop, eval_steps, training_callbacks=training_callbacks, custom_callbacks=custom_callbacks) def run_keras_compile_fit(model_dir, strategy, model_fn, train_input_fn, eval_input_fn, loss_fn, metric_fn, init_checkpoint, epochs, steps_per_epoch, steps_per_loop, eval_steps, training_callbacks=True, custom_callbacks=None): """Runs BERT classifier model using Keras compile/fit API.""" with strategy.scope(): training_dataset = train_input_fn() evaluation_dataset = eval_input_fn() if eval_input_fn else None bert_model, sub_model = model_fn() optimizer = bert_model.optimizer if init_checkpoint: checkpoint = tf.train.Checkpoint(model=sub_model, encoder=sub_model) checkpoint.read(init_checkpoint).assert_existing_objects_matched() if not isinstance(metric_fn, (list, tuple)): metric_fn = [metric_fn] bert_model.compile( optimizer=optimizer, loss=loss_fn, metrics=[fn() for fn in metric_fn], steps_per_execution=steps_per_loop) summary_dir = os.path.join(model_dir, 'summaries') summary_callback = tf.keras.callbacks.TensorBoard(summary_dir) checkpoint = tf.train.Checkpoint(model=bert_model, optimizer=optimizer) checkpoint_manager = tf.train.CheckpointManager( checkpoint, directory=model_dir, max_to_keep=None, step_counter=optimizer.iterations, checkpoint_interval=0) checkpoint_callback = keras_utils.SimpleCheckpoint(checkpoint_manager) if training_callbacks: if custom_callbacks is not None: custom_callbacks += [summary_callback, checkpoint_callback] else: custom_callbacks = [summary_callback, checkpoint_callback] history = bert_model.fit( x=training_dataset, validation_data=evaluation_dataset, steps_per_epoch=steps_per_epoch, epochs=epochs, validation_steps=eval_steps, callbacks=custom_callbacks) stats = {'total_training_steps': steps_per_epoch * epochs} if 'loss' in history.history: stats['train_loss'] = history.history['loss'][-1] if 'val_accuracy' in history.history: stats['eval_metrics'] = history.history['val_accuracy'][-1] return bert_model, stats def get_predictions_and_labels(strategy, trained_model, eval_input_fn, is_regression=False, return_probs=False): """Obtains predictions of trained model on evaluation data. Note that list of labels is returned along with the predictions because the order changes on distributing dataset over TPU pods. Args: strategy: Distribution strategy. trained_model: Trained model with preloaded weights. eval_input_fn: Input function for evaluation data. is_regression: Whether it is a regression task. return_probs: Whether to return probabilities of classes. Returns: predictions: List of predictions. labels: List of gold labels corresponding to predictions. """ @tf.function def test_step(iterator): """Computes predictions on distributed devices.""" def _test_step_fn(inputs): """Replicated predictions.""" inputs, labels = inputs logits = trained_model(inputs, training=False) if not is_regression: probabilities = tf.nn.softmax(logits) return probabilities, labels else: return logits, labels outputs, labels = strategy.run(_test_step_fn, args=(next(iterator),)) # outputs: current batch logits as a tuple of shard logits outputs = tf.nest.map_structure(strategy.experimental_local_results, outputs) labels = tf.nest.map_structure(strategy.experimental_local_results, labels) return outputs, labels def _run_evaluation(test_iterator): """Runs evaluation steps.""" preds, golds = list(), list() try: with tf.experimental.async_scope(): while True: probabilities, labels = test_step(test_iterator) for cur_probs, cur_labels in zip(probabilities, labels): if return_probs: preds.extend(cur_probs.numpy().tolist()) else: preds.extend(tf.math.argmax(cur_probs, axis=1).numpy()) golds.extend(cur_labels.numpy().tolist()) except (StopIteration, tf.errors.OutOfRangeError): tf.experimental.async_clear_error() return preds, golds test_iter = iter(strategy.distribute_datasets_from_function(eval_input_fn)) predictions, labels = _run_evaluation(test_iter) return predictions, labels def export_classifier(model_export_path, input_meta_data, bert_config, model_dir): """Exports a trained model as a `SavedModel` for inference. Args: model_export_path: a string specifying the path to the SavedModel directory. input_meta_data: dictionary containing meta data about input and model. bert_config: Bert configuration file to define core bert layers. model_dir: The directory where the model weights and training/evaluation summaries are stored. Raises: Export path is not specified, got an empty string or None. """ if not model_export_path: raise ValueError('Export path is not specified: %s' % model_export_path) if not model_dir: raise ValueError('Export path is not specified: %s' % model_dir) # Export uses float32 for now, even if training uses mixed precision. tf.keras.mixed_precision.set_global_policy('float32') classifier_model = bert_models.classifier_model( bert_config, input_meta_data.get('num_labels', 1), hub_module_url=FLAGS.hub_module_url, hub_module_trainable=False)[0] model_saving_utils.export_bert_model( model_export_path, model=classifier_model, checkpoint_dir=model_dir) def run_bert(strategy, input_meta_data, model_config, train_input_fn=None, eval_input_fn=None, init_checkpoint=None, custom_callbacks=None, custom_metrics=None): """Run BERT training.""" # Enables XLA in Session Config. Should not be set for TPU. keras_utils.set_session_config(FLAGS.enable_xla) performance.set_mixed_precision_policy(common_flags.dtype()) epochs = FLAGS.num_train_epochs * FLAGS.num_eval_per_epoch train_data_size = ( input_meta_data['train_data_size'] // FLAGS.num_eval_per_epoch) if FLAGS.train_data_size: train_data_size = min(train_data_size, FLAGS.train_data_size) logging.info('Updated train_data_size: %s', train_data_size) steps_per_epoch = int(train_data_size / FLAGS.train_batch_size) warmup_steps = int(epochs * train_data_size * 0.1 / FLAGS.train_batch_size) eval_steps = int( math.ceil(input_meta_data['eval_data_size'] / FLAGS.eval_batch_size)) if not strategy: raise ValueError('Distribution strategy has not been specified.') if not custom_callbacks: custom_callbacks = [] if FLAGS.log_steps: custom_callbacks.append( keras_utils.TimeHistory( batch_size=FLAGS.train_batch_size, log_steps=FLAGS.log_steps, logdir=FLAGS.model_dir)) trained_model, _ = run_bert_classifier( strategy, model_config, input_meta_data, FLAGS.model_dir, epochs, steps_per_epoch, FLAGS.steps_per_loop, eval_steps, warmup_steps, FLAGS.learning_rate, init_checkpoint or FLAGS.init_checkpoint, train_input_fn, eval_input_fn, custom_callbacks=custom_callbacks, custom_metrics=custom_metrics) if FLAGS.model_export_path: model_saving_utils.export_bert_model( FLAGS.model_export_path, model=trained_model) return trained_model def custom_main(custom_callbacks=None, custom_metrics=None): """Run classification or regression. Args: custom_callbacks: list of tf.keras.Callbacks passed to training loop. custom_metrics: list of metrics passed to the training loop. """ gin.parse_config_files_and_bindings(FLAGS.gin_file, FLAGS.gin_param) with tf.io.gfile.GFile(FLAGS.input_meta_data_path, 'rb') as reader: input_meta_data = json.loads(reader.read().decode('utf-8')) label_type = LABEL_TYPES_MAP[input_meta_data.get('label_type', 'int')] include_sample_weights = input_meta_data.get('has_sample_weights', False) if not FLAGS.model_dir: FLAGS.model_dir = '/tmp/bert20/' bert_config = bert_configs.BertConfig.from_json_file(FLAGS.bert_config_file) if FLAGS.mode == 'export_only': export_classifier(FLAGS.model_export_path, input_meta_data, bert_config, FLAGS.model_dir) return strategy = distribute_utils.get_distribution_strategy( distribution_strategy=FLAGS.distribution_strategy, num_gpus=FLAGS.num_gpus, tpu_address=FLAGS.tpu) eval_input_fn = get_dataset_fn( FLAGS.eval_data_path, input_meta_data['max_seq_length'], FLAGS.eval_batch_size, is_training=False, label_type=label_type, include_sample_weights=include_sample_weights) if FLAGS.mode == 'predict': num_labels = input_meta_data.get('num_labels', 1) with strategy.scope(): classifier_model = bert_models.classifier_model( bert_config, num_labels)[0] checkpoint = tf.train.Checkpoint(model=classifier_model) latest_checkpoint_file = ( FLAGS.predict_checkpoint_path or tf.train.latest_checkpoint(FLAGS.model_dir)) assert latest_checkpoint_file logging.info('Checkpoint file %s found and restoring from ' 'checkpoint', latest_checkpoint_file) checkpoint.restore( latest_checkpoint_file).assert_existing_objects_matched() preds, _ = get_predictions_and_labels( strategy, classifier_model, eval_input_fn, is_regression=(num_labels == 1), return_probs=True) output_predict_file = os.path.join(FLAGS.model_dir, 'test_results.tsv') with tf.io.gfile.GFile(output_predict_file, 'w') as writer: logging.info('***** Predict results *****') for probabilities in preds: output_line = '\t'.join( str(class_probability) for class_probability in probabilities) + '\n' writer.write(output_line) return if FLAGS.mode != 'train_and_eval': raise ValueError('Unsupported mode is specified: %s' % FLAGS.mode) train_input_fn = get_dataset_fn( FLAGS.train_data_path, input_meta_data['max_seq_length'], FLAGS.train_batch_size, is_training=True, label_type=label_type, include_sample_weights=include_sample_weights, num_samples=FLAGS.train_data_size) run_bert( strategy, input_meta_data, bert_config, train_input_fn, eval_input_fn, custom_callbacks=custom_callbacks, custom_metrics=custom_metrics) def main(_): custom_main(custom_callbacks=None, custom_metrics=None) if __name__ == '__main__': flags.mark_flag_as_required('bert_config_file') flags.mark_flag_as_required('input_meta_data_path') flags.mark_flag_as_required('model_dir') app.run(main)
18,826
35.486434
80
py
models
models-master/official/legacy/bert/model_training_utils.py
# Copyright 2023 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. """A light weight utilities to train NLP models.""" import json import os import tempfile from absl import logging import tensorflow as tf from tensorflow.python.util import deprecation from official.common import distribute_utils from official.modeling import grad_utils _SUMMARY_TXT = 'training_summary.txt' _MIN_SUMMARY_STEPS = 10 def _should_export_checkpoint(strategy): return (not strategy) or strategy.extended.should_checkpoint def _should_export_summary(strategy): return (not strategy) or strategy.extended.should_save_summary def _save_checkpoint(strategy, checkpoint, model_dir, checkpoint_prefix): """Saves model to with provided checkpoint prefix.""" if _should_export_checkpoint(strategy): checkpoint_path = os.path.join(model_dir, checkpoint_prefix) saved_path = checkpoint.save(checkpoint_path) logging.info('Saving model as TF checkpoint: %s', saved_path) else: # In multi worker training we need every worker to save checkpoint, because # variables can trigger synchronization on read and synchronization needs # all workers to participate. To avoid workers overriding each other we save # to a temporary directory on non-chief workers. tmp_dir = tempfile.mkdtemp() checkpoint.save(os.path.join(tmp_dir, 'ckpt')) tf.io.gfile.rmtree(tmp_dir) return def _get_input_iterator(input_fn, strategy): """Returns distributed dataset iterator.""" # When training with TPU pods, datasets needs to be cloned across # workers. Since Dataset instance cannot be cloned in eager mode, we instead # pass callable that returns a dataset. if not callable(input_fn): raise ValueError('`input_fn` should be a closure that returns a dataset.') iterator = iter(strategy.distribute_datasets_from_function(input_fn)) return iterator def _float_metric_value(metric): """Gets the value of a float-value keras metric.""" return metric.result().numpy().astype(float) def clip_by_global_norm_callback(grads_and_vars): """Performs gradient clipping.""" grads, variables = zip(*grads_and_vars) (clipped_grads, _) = tf.clip_by_global_norm(grads, clip_norm=1.0) return zip(clipped_grads, variables) def steps_to_run(current_step, steps_per_epoch, steps_per_loop): """Calculates steps to run on device.""" if steps_per_loop <= 0: raise ValueError('steps_per_loop should be positive integer.') if steps_per_loop == 1: return steps_per_loop remainder_in_epoch = current_step % steps_per_epoch if remainder_in_epoch != 0: return min(steps_per_epoch - remainder_in_epoch, steps_per_loop) else: return steps_per_loop def write_txt_summary(training_summary, summary_dir): """Writes a summary text file to record stats.""" if not tf.io.gfile.exists(summary_dir): tf.io.gfile.mkdir(summary_dir) summary_path = os.path.join(summary_dir, _SUMMARY_TXT) with tf.io.gfile.GFile(summary_path, 'wb') as f: logging.info('Training Summary: \n%s', str(training_summary)) f.write(json.dumps(training_summary, indent=4)) @deprecation.deprecated( None, 'This function is deprecated and we do not expect adding new ' 'functionalities. Please do not have your code depending ' 'on this library.') def run_customized_training_loop( # pylint: disable=invalid-name _sentinel=None, # pylint: enable=invalid-name strategy=None, model_fn=None, loss_fn=None, scale_loss=True, model_dir=None, train_input_fn=None, steps_per_epoch=None, num_eval_per_epoch=1, steps_per_loop=None, epochs=1, eval_input_fn=None, eval_steps=None, metric_fn=None, init_checkpoint=None, custom_callbacks=None, run_eagerly=False, sub_model_export_name=None, explicit_allreduce=False, pre_allreduce_callbacks=None, post_allreduce_callbacks=None, train_summary_interval=0, allreduce_bytes_per_pack=0): """Run BERT pretrain model training using low-level API. Args: _sentinel: Used to prevent positional parameters. Internal, do not use. strategy: Distribution strategy on which to run low level training loop. model_fn: Function that returns a tuple (model, sub_model). Caller of this function should add optimizer to the `model` via calling `model.compile()` API or manually setting `model.optimizer` attribute. Second element of the returned tuple(sub_model) is an optional sub model to be used for initial checkpoint -- if provided. loss_fn: Function with signature func(labels, logits) and returns a loss tensor. scale_loss: Whether to divide the raw loss by number of replicas before gradients calculation. model_dir: Model directory used during training for restoring/saving model weights. train_input_fn: Function that returns a tf.data.Dataset used for training. steps_per_epoch: Number of steps to run per epoch. At the end of each epoch, model checkpoint will be saved and evaluation will be conducted if evaluation dataset is provided. num_eval_per_epoch: Number of evaluations per epoch. steps_per_loop: Number of steps per graph-mode loop. In order to reduce communication in eager context, training logs are printed every steps_per_loop. epochs: Number of epochs to train. eval_input_fn: Function that returns evaluation dataset. If none, evaluation is skipped. eval_steps: Number of steps to run evaluation. Required if `eval_input_fn` is not none. metric_fn: A metrics function that returns either a Keras Metric object or a list of Keras Metric objects to record evaluation result using evaluation dataset or with training dataset after every epoch. init_checkpoint: Optional checkpoint to load to `sub_model` returned by `model_fn`. custom_callbacks: A list of Keras Callbacks objects to run during training. More specifically, `on_train_begin(), on_train_end(), on_batch_begin()`, `on_batch_end()`, `on_epoch_begin()`, `on_epoch_end()` methods are invoked during training. Note that some metrics may be missing from `logs`. run_eagerly: Whether to run model training in pure eager execution. This should be disable for TPUStrategy. sub_model_export_name: If not None, will export `sub_model` returned by `model_fn` into checkpoint files. The name of intermediate checkpoint file is {sub_model_export_name}_step_{step}.ckpt and the last checkpint's name is {sub_model_export_name}.ckpt; if None, `sub_model` will not be exported as checkpoint. explicit_allreduce: Whether to explicitly perform gradient allreduce, instead of relying on implicit allreduce in optimizer.apply_gradients(). default is False. For now, if training using FP16 mixed precision, explicit allreduce will aggregate gradients in FP16 format. For TPU and GPU training using FP32, explicit allreduce will aggregate gradients in FP32 format. pre_allreduce_callbacks: A list of callback functions that takes gradients and model variables pairs as input, manipulate them, and returns a new gradients and model variables paris. The callback functions will be invoked in the list order and before gradients are allreduced. With mixed precision training, the pre_allreduce_allbacks will be applied on scaled_gradients. Default is no callbacks. Only used when explicit_allreduce=True. post_allreduce_callbacks: A list of callback functions that takes gradients and model variables pairs as input, manipulate them, and returns a new gradients and model variables paris. The callback functions will be invoked in the list order and right before gradients are applied to variables for updates. Default is no callbacks. Only used when explicit_allreduce=True. train_summary_interval: Step interval for training summaries. If the value is a negative number, then training summaries are not enabled. allreduce_bytes_per_pack: A non-negative integer. Breaks collective operations into packs of certain size. If it's zero, all gradients are in one pack. Breaking gradient into packs could enable overlap between allreduce and backprop computation. This flag only takes effect when explicit_allreduce is set to True.' Returns: Trained model. Raises: ValueError: (1) When model returned by `model_fn` does not have optimizer attribute or when required parameters are set to none. (2) eval args are not specified correctly. (3) metric_fn must be a callable if specified. (4) sub_model_checkpoint_name is specified, but `sub_model` returned by `model_fn` is None. """ if _sentinel is not None: raise ValueError('only call `run_customized_training_loop()` ' 'with named arguments.') required_arguments = [ strategy, model_fn, loss_fn, model_dir, steps_per_epoch, train_input_fn ] steps_between_evals = int(steps_per_epoch / num_eval_per_epoch) if [arg for arg in required_arguments if arg is None]: raise ValueError('`strategy`, `model_fn`, `loss_fn`, `model_dir`, ' '`steps_per_epoch` and `train_input_fn` are required ' 'parameters.') if not steps_per_loop: if tf.config.list_logical_devices('TPU'): # One can't fully utilize a TPU with steps_per_loop=1, so in this case # default users to a more useful value. steps_per_loop = min(1000, steps_between_evals) else: steps_per_loop = 1 logging.info('steps_per_loop not specified. Using steps_per_loop=%d', steps_per_loop) if steps_per_loop > steps_between_evals: logging.warning( 'steps_per_loop: %d is specified to be greater than ' ' steps_between_evals: %d, we will use steps_between_evals as' ' steps_per_loop.', steps_per_loop, steps_between_evals) steps_per_loop = steps_between_evals assert tf.executing_eagerly() if run_eagerly: if isinstance( strategy, (tf.distribute.TPUStrategy, tf.distribute.experimental.TPUStrategy)): raise ValueError( 'TPUStrategy should not run eagerly as it heavily relies on graph' ' optimization for the distributed system.') if eval_input_fn and eval_steps is None: raise ValueError( '`eval_step` is required when `eval_input_fn ` is not none.') if metric_fn and not callable(metric_fn): raise ValueError( 'if `metric_fn` is specified, metric_fn must be a callable.') total_training_steps = steps_per_epoch * epochs train_iterator = _get_input_iterator(train_input_fn, strategy) eval_loss_metric = tf.keras.metrics.Mean('training_loss', dtype=tf.float32) with distribute_utils.get_strategy_scope(strategy): # To correctly place the model weights on accelerators, # model and optimizer should be created in scope. model, sub_model = model_fn() if not hasattr(model, 'optimizer'): raise ValueError('User should set optimizer attribute to model ' 'inside `model_fn`.') if sub_model_export_name and sub_model is None: raise ValueError('sub_model_export_name is specified as %s, but ' 'sub_model is None.' % sub_model_export_name) callback_list = tf.keras.callbacks.CallbackList( callbacks=custom_callbacks, model=model) optimizer = model.optimizer if init_checkpoint: logging.info( 'Checkpoint file %s found and restoring from ' 'initial checkpoint for core model.', init_checkpoint) checkpoint = tf.train.Checkpoint(model=sub_model, encoder=sub_model) checkpoint.read(init_checkpoint).assert_existing_objects_matched() logging.info('Loading from checkpoint file completed') train_loss_metric = tf.keras.metrics.Mean('training_loss', dtype=tf.float32) eval_metrics = metric_fn() if metric_fn else [] if not isinstance(eval_metrics, list): eval_metrics = [eval_metrics] # If evaluation is required, make a copy of metric as it will be used by # both train and evaluation. train_metrics = [ metric.__class__.from_config(metric.get_config()) for metric in eval_metrics ] # Create summary writers if _should_export_summary(strategy): summary_dir = os.path.join(model_dir, 'summaries') else: # In multi worker training we need every worker to write summary, because # variables can trigger synchronization on read and synchronization needs # all workers to participate. summary_dir = tempfile.mkdtemp() eval_summary_writer = tf.summary.create_file_writer( os.path.join(summary_dir, 'eval')) last_summary_step = 0 if steps_per_loop >= _MIN_SUMMARY_STEPS and train_summary_interval >= 0: # Only writes summary when the stats are collected sufficiently over # enough steps. train_summary_writer = tf.summary.create_file_writer( os.path.join(summary_dir, 'train')) else: train_summary_writer = tf.summary.create_noop_writer() # Collects training variables. training_vars = model.trainable_variables def _replicated_step(inputs): """Replicated training step.""" inputs, labels = inputs with tf.GradientTape() as tape: model_outputs = model(inputs, training=True) loss = loss_fn(labels, model_outputs) # Raw loss is used for reporting in metrics/logs. raw_loss = loss if scale_loss: # Scales down the loss for gradients to be invariant from replicas. loss = loss / strategy.num_replicas_in_sync if explicit_allreduce: grad_utils.minimize_using_explicit_allreduce(tape, optimizer, loss, training_vars, pre_allreduce_callbacks, post_allreduce_callbacks, allreduce_bytes_per_pack) else: if isinstance(optimizer, tf.keras.mixed_precision.LossScaleOptimizer): with tape: scaled_loss = optimizer.get_scaled_loss(loss) scaled_grads = tape.gradient(scaled_loss, training_vars) grads = optimizer.get_unscaled_gradients(scaled_grads) else: grads = tape.gradient(loss, training_vars) optimizer.apply_gradients(zip(grads, training_vars)) # For reporting, the metric takes the mean of losses. train_loss_metric.update_state(raw_loss) for metric in train_metrics: metric.update_state(labels, model_outputs) @tf.function def train_steps(iterator, steps): """Performs distributed training steps in a loop. Args: iterator: the distributed iterator of training datasets. steps: an tf.int32 integer tensor to specify number of steps to run inside host training loop. Raises: ValueError: Any of the arguments or tensor shapes are invalid. """ if not isinstance(steps, tf.Tensor): raise ValueError('steps should be an Tensor. Python object may cause ' 'retracing.') for _ in tf.range(steps): strategy.run(_replicated_step, args=(next(iterator),)) def train_single_step(iterator): """Performs a distributed training step. Args: iterator: the distributed iterator of training datasets. Raises: ValueError: Any of the arguments or tensor shapes are invalid. """ strategy.run(_replicated_step, args=(next(iterator),)) def test_step(iterator): """Calculates evaluation metrics on distributed devices.""" def _test_step_fn(inputs): """Replicated accuracy calculation.""" inputs, labels = inputs model_outputs = model(inputs, training=False) for metric in eval_metrics: metric.update_state(labels, model_outputs) return model_outputs, labels outputs, labels = strategy.run(_test_step_fn, args=(next(iterator),)) outputs = tf.nest.map_structure(strategy.experimental_local_results, outputs) labels = tf.nest.map_structure(strategy.experimental_local_results, labels) return outputs, labels if not run_eagerly: train_single_step = tf.function(train_single_step) test_step = tf.function(test_step) def _run_evaluation(current_training_step, test_iterator): """Runs validation steps and aggregate metrics. Args: current_training_step: tf.int32 tensor containing the current step. test_iterator: distributed iterator of test datasets. Returns: A dict of metic names and values. """ # The last batch of the evaluation is often smaller than previous ones. # Moreover, in some distributed pieces it might even be empty. Therefore, # different from the way training_loss is calculated, it is needed to # gather all the logits and labels here to calculate the evaluation loss # outside. loss_list, loss_weights = list(), list() for _ in range(eval_steps): outputs, labels = test_step(test_iterator) for cur_logits, cur_labels in zip(outputs, labels): # This is to handle cases when cur_labels is not a single tensor, # but a dict of tensors. cur_weight = tf.shape(tf.nest.flatten(cur_labels)[0])[0] if cur_weight != 0: loss_list.append(loss_fn(cur_labels, cur_logits).numpy()) loss_weights.append(cur_weight) # The sample_weights are the actual number of examples in each batch, # a summation of numbers of examples in each replica if using # distributed training. eval_loss_metric.update_state(loss_list, sample_weight=loss_weights) logs = {} with eval_summary_writer.as_default(): for metric in [eval_loss_metric] + eval_metrics + model.metrics: metric_value = _float_metric_value(metric) logs[metric.name] = metric_value logging.info('Step: [%d] Validation %s = %f', current_training_step, metric.name, metric_value) tf.summary.scalar( metric.name, metric_value, step=current_training_step) eval_summary_writer.flush() return logs # Training loop starts here. checkpoint = tf.train.Checkpoint( model=model, optimizer=optimizer, global_step=optimizer.iterations) sub_model_checkpoint = tf.train.Checkpoint( model=sub_model, global_step=optimizer.iterations) if sub_model_export_name else None latest_checkpoint_file = tf.train.latest_checkpoint(model_dir) if latest_checkpoint_file: logging.info('Checkpoint file %s found and restoring from ' 'checkpoint', latest_checkpoint_file) checkpoint.restore(latest_checkpoint_file) logging.info('Loading from checkpoint file completed') current_step = optimizer.iterations.numpy() checkpoint_name = 'ctl_step_{step}.ckpt' logs = {} callback_list.on_train_begin() while current_step < total_training_steps and not model.stop_training: if current_step % steps_per_epoch == 0: callback_list.on_epoch_begin(int(current_step / steps_per_epoch) + 1) # Training loss/metric are taking average over steps inside micro # training loop. We reset the their values before each round. train_loss_metric.reset_states() for metric in train_metrics + model.metrics: metric.reset_states() callback_list.on_batch_begin(current_step) # Runs several steps in the host while loop. steps = steps_to_run(current_step, steps_between_evals, steps_per_loop) if tf.config.list_physical_devices('GPU'): # TODO(zongweiz): merge with train_steps once tf.while_loop # GPU performance bugs are fixed. for _ in range(steps): train_single_step(train_iterator) else: # Converts steps to a Tensor to avoid tf.function retracing. train_steps(train_iterator, tf.convert_to_tensor(steps, dtype=tf.int32)) train_loss = _float_metric_value(train_loss_metric) current_step += steps # Updates training logging. training_status = 'Train Step: %d/%d / loss = %s' % ( current_step, total_training_steps, train_loss) if current_step >= last_summary_step + train_summary_interval: summary_writer = train_summary_writer last_summary_step = current_step else: summary_writer = tf.summary.create_noop_writer() with summary_writer.as_default(): if callable(optimizer.learning_rate): tf.summary.scalar( 'learning_rate', optimizer.learning_rate(current_step), step=current_step) tf.summary.scalar(train_loss_metric.name, train_loss, step=current_step) for metric in train_metrics + model.metrics: metric_value = _float_metric_value(metric) training_status += ' %s = %f' % (metric.name, metric_value) tf.summary.scalar(metric.name, metric_value, step=current_step) summary_writer.flush() logging.info(training_status) # If no need for evaluation, we only call on_batch_end with train_loss, # this is to ensure we get granular global_step/sec on Tensorboard. if current_step % steps_between_evals: callback_list.on_batch_end(current_step - 1, {'loss': train_loss}) else: # Save a submodel with the step in the file name after each epoch. if sub_model_export_name: _save_checkpoint( strategy, sub_model_checkpoint, model_dir, '%s_step_%d.ckpt' % (sub_model_export_name, current_step)) # Save model checkpoints and run validation steps after each epoch # (with the exception of the final epoch which is handled after the # training loop). if current_step < total_training_steps: _save_checkpoint(strategy, checkpoint, model_dir, checkpoint_name.format(step=current_step)) if eval_input_fn: # Re-initialize evaluation metric. eval_loss_metric.reset_states() for metric in eval_metrics + model.metrics: metric.reset_states() logging.info('Running evaluation after step: %s.', current_step) logs = _run_evaluation(current_step, _get_input_iterator(eval_input_fn, strategy)) # We add train_loss here rather than call on_batch_end twice to make # sure that no duplicated values are generated. logs['loss'] = train_loss callback_list.on_batch_end(current_step - 1, logs) # Calls on_epoch_end after each real epoch ends to prevent mis-calculation # of training steps. if current_step % steps_per_epoch == 0: callback_list.on_epoch_end(int(current_step / steps_per_epoch), logs) if sub_model_export_name: _save_checkpoint(strategy, sub_model_checkpoint, model_dir, '%s.ckpt' % sub_model_export_name) _save_checkpoint(strategy, checkpoint, model_dir, checkpoint_name.format(step=current_step)) if eval_input_fn: # Re-initialize evaluation metric. eval_loss_metric.reset_states() for metric in eval_metrics + model.metrics: metric.reset_states() logging.info('Running final evaluation after training is complete.') logs = _run_evaluation(current_step, _get_input_iterator(eval_input_fn, strategy)) callback_list.on_epoch_end(int(current_step / steps_per_epoch), logs) training_summary = { 'total_training_steps': total_training_steps, 'train_loss': _float_metric_value(train_loss_metric), } for metric in model.metrics: training_summary[metric.name] = _float_metric_value(metric) if eval_metrics: training_summary['last_train_metrics'] = _float_metric_value( train_metrics[0]) training_summary['eval_metrics'] = _float_metric_value(eval_metrics[0]) write_txt_summary(training_summary, summary_dir) if not _should_export_summary(strategy): tf.io.gfile.rmtree(summary_dir) callback_list.on_train_end() return model
25,317
41.839255
80
py
models
models-master/official/legacy/bert/bert_models.py
# Copyright 2023 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. """BERT models that are compatible with TF 2.0.""" import gin import tensorflow as tf import tensorflow_hub as hub from official.legacy.albert import configs as albert_configs from official.legacy.bert import configs from official.modeling import tf_utils from official.nlp.modeling import models from official.nlp.modeling import networks class BertPretrainLossAndMetricLayer(tf.keras.layers.Layer): """Returns layer that computes custom loss and metrics for pretraining.""" def __init__(self, vocab_size, **kwargs): super(BertPretrainLossAndMetricLayer, self).__init__(**kwargs) self._vocab_size = vocab_size self.config = { 'vocab_size': vocab_size, } def _add_metrics(self, lm_output, lm_labels, lm_label_weights, lm_example_loss, sentence_output, sentence_labels, next_sentence_loss): """Adds metrics.""" masked_lm_accuracy = tf.keras.metrics.sparse_categorical_accuracy( lm_labels, lm_output) numerator = tf.reduce_sum(masked_lm_accuracy * lm_label_weights) denominator = tf.reduce_sum(lm_label_weights) + 1e-5 masked_lm_accuracy = numerator / denominator self.add_metric( masked_lm_accuracy, name='masked_lm_accuracy', aggregation='mean') self.add_metric(lm_example_loss, name='lm_example_loss', aggregation='mean') if sentence_labels is not None: next_sentence_accuracy = tf.keras.metrics.sparse_categorical_accuracy( sentence_labels, sentence_output) self.add_metric( next_sentence_accuracy, name='next_sentence_accuracy', aggregation='mean') if next_sentence_loss is not None: self.add_metric( next_sentence_loss, name='next_sentence_loss', aggregation='mean') def call(self, lm_output_logits, sentence_output_logits, lm_label_ids, lm_label_weights, sentence_labels=None): """Implements call() for the layer.""" lm_label_weights = tf.cast(lm_label_weights, tf.float32) lm_output_logits = tf.cast(lm_output_logits, tf.float32) lm_prediction_losses = tf.keras.losses.sparse_categorical_crossentropy( lm_label_ids, lm_output_logits, from_logits=True) lm_numerator_loss = tf.reduce_sum(lm_prediction_losses * lm_label_weights) lm_denominator_loss = tf.reduce_sum(lm_label_weights) mask_label_loss = tf.math.divide_no_nan(lm_numerator_loss, lm_denominator_loss) if sentence_labels is not None: sentence_output_logits = tf.cast(sentence_output_logits, tf.float32) sentence_loss = tf.keras.losses.sparse_categorical_crossentropy( sentence_labels, sentence_output_logits, from_logits=True) sentence_loss = tf.reduce_mean(sentence_loss) loss = mask_label_loss + sentence_loss else: sentence_loss = None loss = mask_label_loss batch_shape = tf.slice(tf.shape(lm_label_ids), [0], [1]) # TODO(hongkuny): Avoids the hack and switches add_loss. final_loss = tf.fill(batch_shape, loss) self._add_metrics(lm_output_logits, lm_label_ids, lm_label_weights, mask_label_loss, sentence_output_logits, sentence_labels, sentence_loss) return final_loss @gin.configurable def get_transformer_encoder(bert_config, sequence_length=None, transformer_encoder_cls=None, output_range=None): """Gets a 'TransformerEncoder' object. Args: bert_config: A 'modeling.BertConfig' or 'modeling.AlbertConfig' object. sequence_length: [Deprecated]. transformer_encoder_cls: A EncoderScaffold class. If it is None, uses the default BERT encoder implementation. output_range: the sequence output range, [0, output_range). Default setting is to return the entire sequence output. Returns: A encoder object. """ del sequence_length if transformer_encoder_cls is not None: # TODO(hongkuny): evaluate if it is better to put cfg definition in gin. embedding_cfg = dict( vocab_size=bert_config.vocab_size, type_vocab_size=bert_config.type_vocab_size, hidden_size=bert_config.hidden_size, max_seq_length=bert_config.max_position_embeddings, initializer=tf.keras.initializers.TruncatedNormal( stddev=bert_config.initializer_range), dropout_rate=bert_config.hidden_dropout_prob, ) hidden_cfg = dict( num_attention_heads=bert_config.num_attention_heads, intermediate_size=bert_config.intermediate_size, intermediate_activation=tf_utils.get_activation(bert_config.hidden_act), dropout_rate=bert_config.hidden_dropout_prob, attention_dropout_rate=bert_config.attention_probs_dropout_prob, kernel_initializer=tf.keras.initializers.TruncatedNormal( stddev=bert_config.initializer_range), ) kwargs = dict( embedding_cfg=embedding_cfg, hidden_cfg=hidden_cfg, num_hidden_instances=bert_config.num_hidden_layers, pooled_output_dim=bert_config.hidden_size, pooler_layer_initializer=tf.keras.initializers.TruncatedNormal( stddev=bert_config.initializer_range)) # Relies on gin configuration to define the Transformer encoder arguments. return transformer_encoder_cls(**kwargs) kwargs = dict( vocab_size=bert_config.vocab_size, hidden_size=bert_config.hidden_size, num_layers=bert_config.num_hidden_layers, num_attention_heads=bert_config.num_attention_heads, intermediate_size=bert_config.intermediate_size, activation=tf_utils.get_activation(bert_config.hidden_act), dropout_rate=bert_config.hidden_dropout_prob, attention_dropout_rate=bert_config.attention_probs_dropout_prob, max_sequence_length=bert_config.max_position_embeddings, type_vocab_size=bert_config.type_vocab_size, embedding_width=bert_config.embedding_size, initializer=tf.keras.initializers.TruncatedNormal( stddev=bert_config.initializer_range)) if isinstance(bert_config, albert_configs.AlbertConfig): return networks.AlbertEncoder(**kwargs) else: assert isinstance(bert_config, configs.BertConfig) kwargs['output_range'] = output_range return networks.BertEncoder(**kwargs) def pretrain_model(bert_config, seq_length, max_predictions_per_seq, initializer=None, use_next_sentence_label=True, return_core_pretrainer_model=False): """Returns model to be used for pre-training. Args: bert_config: Configuration that defines the core BERT model. seq_length: Maximum sequence length of the training data. max_predictions_per_seq: Maximum number of tokens in sequence to mask out and use for pretraining. initializer: Initializer for weights in BertPretrainer. use_next_sentence_label: Whether to use the next sentence label. return_core_pretrainer_model: Whether to also return the `BertPretrainer` object. Returns: A Tuple of (1) Pretraining model, (2) core BERT submodel from which to save weights after pretraining, and (3) optional core `BertPretrainer` object if argument `return_core_pretrainer_model` is True. """ input_word_ids = tf.keras.layers.Input( shape=(seq_length,), name='input_word_ids', dtype=tf.int32) input_mask = tf.keras.layers.Input( shape=(seq_length,), name='input_mask', dtype=tf.int32) input_type_ids = tf.keras.layers.Input( shape=(seq_length,), name='input_type_ids', dtype=tf.int32) masked_lm_positions = tf.keras.layers.Input( shape=(max_predictions_per_seq,), name='masked_lm_positions', dtype=tf.int32) masked_lm_ids = tf.keras.layers.Input( shape=(max_predictions_per_seq,), name='masked_lm_ids', dtype=tf.int32) masked_lm_weights = tf.keras.layers.Input( shape=(max_predictions_per_seq,), name='masked_lm_weights', dtype=tf.int32) if use_next_sentence_label: next_sentence_labels = tf.keras.layers.Input( shape=(1,), name='next_sentence_labels', dtype=tf.int32) else: next_sentence_labels = None transformer_encoder = get_transformer_encoder(bert_config, seq_length) if initializer is None: initializer = tf.keras.initializers.TruncatedNormal( stddev=bert_config.initializer_range) pretrainer_model = models.BertPretrainer( network=transformer_encoder, embedding_table=transformer_encoder.get_embedding_table(), num_classes=2, # The next sentence prediction label has two classes. activation=tf_utils.get_activation(bert_config.hidden_act), num_token_predictions=max_predictions_per_seq, initializer=initializer, output='logits') outputs = pretrainer_model( [input_word_ids, input_mask, input_type_ids, masked_lm_positions]) lm_output = outputs['masked_lm'] sentence_output = outputs['classification'] pretrain_loss_layer = BertPretrainLossAndMetricLayer( vocab_size=bert_config.vocab_size) output_loss = pretrain_loss_layer(lm_output, sentence_output, masked_lm_ids, masked_lm_weights, next_sentence_labels) inputs = { 'input_word_ids': input_word_ids, 'input_mask': input_mask, 'input_type_ids': input_type_ids, 'masked_lm_positions': masked_lm_positions, 'masked_lm_ids': masked_lm_ids, 'masked_lm_weights': masked_lm_weights, } if use_next_sentence_label: inputs['next_sentence_labels'] = next_sentence_labels keras_model = tf.keras.Model(inputs=inputs, outputs=output_loss) if return_core_pretrainer_model: return keras_model, transformer_encoder, pretrainer_model else: return keras_model, transformer_encoder def squad_model(bert_config, max_seq_length, initializer=None, hub_module_url=None, hub_module_trainable=True): """Returns BERT Squad model along with core BERT model to import weights. Args: bert_config: BertConfig, the config defines the core Bert model. max_seq_length: integer, the maximum input sequence length. initializer: Initializer for the final dense layer in the span labeler. Defaulted to TruncatedNormal initializer. hub_module_url: TF-Hub path/url to Bert module. hub_module_trainable: True to finetune layers in the hub module. Returns: A tuple of (1) keras model that outputs start logits and end logits and (2) the core BERT transformer encoder. """ if initializer is None: initializer = tf.keras.initializers.TruncatedNormal( stddev=bert_config.initializer_range) if not hub_module_url: bert_encoder = get_transformer_encoder(bert_config, max_seq_length) return models.BertSpanLabeler( network=bert_encoder, initializer=initializer), bert_encoder input_word_ids = tf.keras.layers.Input( shape=(max_seq_length,), dtype=tf.int32, name='input_word_ids') input_mask = tf.keras.layers.Input( shape=(max_seq_length,), dtype=tf.int32, name='input_mask') input_type_ids = tf.keras.layers.Input( shape=(max_seq_length,), dtype=tf.int32, name='input_type_ids') core_model = hub.KerasLayer(hub_module_url, trainable=hub_module_trainable) pooled_output, sequence_output = core_model( [input_word_ids, input_mask, input_type_ids]) bert_encoder = tf.keras.Model( inputs={ 'input_word_ids': input_word_ids, 'input_mask': input_mask, 'input_type_ids': input_type_ids, }, outputs=[sequence_output, pooled_output], name='core_model') return models.BertSpanLabeler( network=bert_encoder, initializer=initializer), bert_encoder def classifier_model(bert_config, num_labels, max_seq_length=None, final_layer_initializer=None, hub_module_url=None, hub_module_trainable=True): """BERT classifier model in functional API style. Construct a Keras model for predicting `num_labels` outputs from an input with maximum sequence length `max_seq_length`. Args: bert_config: BertConfig or AlbertConfig, the config defines the core BERT or ALBERT model. num_labels: integer, the number of classes. max_seq_length: integer, the maximum input sequence length. final_layer_initializer: Initializer for final dense layer. Defaulted TruncatedNormal initializer. hub_module_url: TF-Hub path/url to Bert module. hub_module_trainable: True to finetune layers in the hub module. Returns: Combined prediction model (words, mask, type) -> (one-hot labels) BERT sub-model (words, mask, type) -> (bert_outputs) """ if final_layer_initializer is not None: initializer = final_layer_initializer else: initializer = tf.keras.initializers.TruncatedNormal( stddev=bert_config.initializer_range) if not hub_module_url: bert_encoder = get_transformer_encoder( bert_config, max_seq_length, output_range=1) return models.BertClassifier( bert_encoder, num_classes=num_labels, dropout_rate=bert_config.hidden_dropout_prob, initializer=initializer), bert_encoder input_word_ids = tf.keras.layers.Input( shape=(max_seq_length,), dtype=tf.int32, name='input_word_ids') input_mask = tf.keras.layers.Input( shape=(max_seq_length,), dtype=tf.int32, name='input_mask') input_type_ids = tf.keras.layers.Input( shape=(max_seq_length,), dtype=tf.int32, name='input_type_ids') bert_model = hub.KerasLayer(hub_module_url, trainable=hub_module_trainable) pooled_output, _ = bert_model([input_word_ids, input_mask, input_type_ids]) output = tf.keras.layers.Dropout(rate=bert_config.hidden_dropout_prob)( pooled_output) output = tf.keras.layers.Dense( num_labels, kernel_initializer=initializer, name='output')( output) return tf.keras.Model( inputs={ 'input_word_ids': input_word_ids, 'input_mask': input_mask, 'input_type_ids': input_type_ids }, outputs=output), bert_model
14,931
39.797814
80
py
models
models-master/official/legacy/bert/bert_models_test.py
# Copyright 2023 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. import tensorflow as tf from official.legacy.bert import bert_models from official.legacy.bert import configs as bert_configs from official.nlp.modeling import networks class BertModelsTest(tf.test.TestCase): def setUp(self): super(BertModelsTest, self).setUp() self._bert_test_config = bert_configs.BertConfig( attention_probs_dropout_prob=0.0, hidden_act='gelu', hidden_dropout_prob=0.0, hidden_size=16, initializer_range=0.02, intermediate_size=32, max_position_embeddings=128, num_attention_heads=2, num_hidden_layers=2, type_vocab_size=2, vocab_size=30522) def test_pretrain_model(self): model, encoder = bert_models.pretrain_model( self._bert_test_config, seq_length=5, max_predictions_per_seq=2, initializer=None, use_next_sentence_label=True) self.assertIsInstance(model, tf.keras.Model) self.assertIsInstance(encoder, networks.BertEncoder) # model has one scalar output: loss value. self.assertEqual(model.output.shape.as_list(), [ None, ]) # Expect two output from encoder: sequence and classification output. self.assertIsInstance(encoder.output, list) self.assertLen(encoder.output, 2) # shape should be [batch size, hidden_size] self.assertEqual(encoder.output[1].shape.as_list(), [None, 16]) def test_squad_model(self): model, core_model = bert_models.squad_model( self._bert_test_config, max_seq_length=5, initializer=None, hub_module_url=None, hub_module_trainable=None) self.assertIsInstance(model, tf.keras.Model) self.assertIsInstance(core_model, tf.keras.Model) # Expect two output from model: start positions and end positions self.assertIsInstance(model.output, list) self.assertLen(model.output, 2) # Expect two output from core_model: sequence and classification output. self.assertIsInstance(core_model.output, list) self.assertLen(core_model.output, 2) # shape should be [batch size, None, hidden_size] self.assertEqual(core_model.output[0].shape.as_list(), [None, None, 16]) # shape should be [batch size, hidden_size] self.assertEqual(core_model.output[1].shape.as_list(), [None, 16]) def test_classifier_model(self): model, core_model = bert_models.classifier_model( self._bert_test_config, num_labels=3, max_seq_length=5, final_layer_initializer=None, hub_module_url=None, hub_module_trainable=None) self.assertIsInstance(model, tf.keras.Model) self.assertIsInstance(core_model, tf.keras.Model) # model has one classification output with num_labels=3. self.assertEqual(model.output.shape.as_list(), [None, 3]) # Expect two output from core_model: sequence and classification output. self.assertIsInstance(core_model.output, list) self.assertLen(core_model.output, 2) # shape should be [batch size, None, hidden_size] self.assertEqual(core_model.output[0].shape.as_list(), [None, None, 16]) # shape should be [batch size, hidden_size] self.assertEqual(core_model.output[1].shape.as_list(), [None, 16]) if __name__ == '__main__': tf.test.main()
3,883
35.299065
76
py
models
models-master/official/legacy/bert/common_flags.py
# Copyright 2023 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. """Defining common flags used across all BERT models/applications.""" from absl import flags import tensorflow as tf from official.utils import hyperparams_flags from official.utils.flags import core as flags_core def define_common_bert_flags(): """Define common flags for BERT tasks.""" flags_core.define_base( data_dir=False, model_dir=True, clean=False, train_epochs=False, epochs_between_evals=False, stop_threshold=False, batch_size=False, num_gpu=True, export_dir=False, distribution_strategy=True, run_eagerly=True) flags_core.define_distribution() flags.DEFINE_string('bert_config_file', None, 'Bert configuration file to define core bert layers.') flags.DEFINE_string( 'model_export_path', None, 'Path to the directory, where trainined model will be ' 'exported.') flags.DEFINE_string('tpu', '', 'TPU address to connect to.') flags.DEFINE_string( 'init_checkpoint', None, 'Initial checkpoint (usually from a pre-trained BERT model).') flags.DEFINE_integer('num_train_epochs', 3, 'Total number of training epochs to perform.') flags.DEFINE_integer( 'steps_per_loop', None, 'Number of steps per graph-mode loop. Only training step ' 'happens inside the loop. Callbacks will not be called ' 'inside. If not set the value will be configured depending on the ' 'devices available.') flags.DEFINE_float('learning_rate', 5e-5, 'The initial learning rate for Adam.') flags.DEFINE_float('end_lr', 0.0, 'The end learning rate for learning rate decay.') flags.DEFINE_string('optimizer_type', 'adamw', 'The type of optimizer to use for training (adamw|lamb)') flags.DEFINE_boolean( 'scale_loss', False, 'Whether to divide the loss by number of replica inside the per-replica ' 'loss function.') flags.DEFINE_boolean( 'use_keras_compile_fit', False, 'If True, uses Keras compile/fit() API for training logic. Otherwise ' 'use custom training loop.') flags.DEFINE_string( 'hub_module_url', None, 'TF-Hub path/url to Bert module. ' 'If specified, init_checkpoint flag should not be used.') flags.DEFINE_bool('hub_module_trainable', True, 'True to make keras layers in the hub module trainable.') flags.DEFINE_string( 'sub_model_export_name', None, 'If set, `sub_model` checkpoints are exported into ' 'FLAGS.model_dir/FLAGS.sub_model_export_name.') flags.DEFINE_bool('explicit_allreduce', False, 'True to use explicit allreduce instead of the implicit ' 'allreduce in optimizer.apply_gradients(). If fp16 mixed ' 'precision training is used, this also enables allreduce ' 'gradients in fp16.') flags.DEFINE_integer('allreduce_bytes_per_pack', 0, 'Number of bytes of a gradient pack for allreduce. ' 'Should be positive integer, if set to 0, all ' 'gradients are in one pack. Breaking gradient into ' 'packs could enable overlap between allreduce and ' 'backprop computation. This flag only takes effect ' 'when explicit_allreduce is set to True.') flags_core.define_log_steps() # Adds flags for mixed precision and multi-worker training. flags_core.define_performance( num_parallel_calls=False, inter_op=False, intra_op=False, synthetic_data=False, max_train_steps=False, dtype=True, loss_scale=True, all_reduce_alg=True, num_packs=False, tf_gpu_thread_mode=True, datasets_num_private_threads=True, enable_xla=True, fp16_implementation=True, ) # Adds gin configuration flags. hyperparams_flags.define_gin_flags() def dtype(): return flags_core.get_tf_dtype(flags.FLAGS) def use_float16(): return flags_core.get_tf_dtype(flags.FLAGS) == tf.float16 def get_loss_scale(): return flags_core.get_loss_scale(flags.FLAGS, default_for_fp16='dynamic')
4,832
37.357143
79
py
models
models-master/official/legacy/bert/model_training_utils_test.py
# Copyright 2023 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. """Tests for official.modeling.training.model_training_utils.""" import os from absl import logging from absl.testing import flagsaver from absl.testing import parameterized from absl.testing.absltest import mock import numpy as np import tensorflow as tf from tensorflow.python.distribute import combinations from tensorflow.python.distribute import strategy_combinations from official.legacy.bert import common_flags from official.legacy.bert import model_training_utils common_flags.define_common_bert_flags() def eager_strategy_combinations(): return combinations.combine( distribution=[ strategy_combinations.default_strategy, strategy_combinations.cloud_tpu_strategy, strategy_combinations.one_device_strategy_gpu, strategy_combinations.mirrored_strategy_with_gpu_and_cpu, strategy_combinations.mirrored_strategy_with_two_gpus, ],) def eager_gpu_strategy_combinations(): return combinations.combine( distribution=[ strategy_combinations.default_strategy, strategy_combinations.one_device_strategy_gpu, strategy_combinations.mirrored_strategy_with_gpu_and_cpu, strategy_combinations.mirrored_strategy_with_two_gpus, ],) def create_fake_data_input_fn(batch_size, features_shape, num_classes): """Creates a dummy input function with the given feature and label shapes. Args: batch_size: integer. features_shape: list[int]. Feature shape for an individual example. num_classes: integer. Number of labels. Returns: An input function that is usable in the executor. """ def _dataset_fn(input_context=None): """An input function for generating fake data.""" local_batch_size = input_context.get_per_replica_batch_size(batch_size) features = np.random.rand(64, *features_shape) labels = np.random.randint(2, size=[64, num_classes]) # Convert the inputs to a Dataset. dataset = tf.data.Dataset.from_tensor_slices((features, labels)) dataset = dataset.shard(input_context.num_input_pipelines, input_context.input_pipeline_id) def _assign_dtype(features, labels): features = tf.cast(features, tf.float32) labels = tf.cast(labels, tf.float32) return features, labels # Shuffle, repeat, and batch the examples. dataset = dataset.map(_assign_dtype) dataset = dataset.shuffle(64).repeat() dataset = dataset.batch(local_batch_size, drop_remainder=True) dataset = dataset.prefetch(buffer_size=64) return dataset return _dataset_fn def create_model_fn(input_shape, num_classes, use_float16=False): def _model_fn(): """A one-layer softmax model suitable for testing.""" input_layer = tf.keras.layers.Input(shape=input_shape) x = tf.keras.layers.Dense(num_classes, activation='relu')(input_layer) output_layer = tf.keras.layers.Dense(num_classes, activation='softmax')(x) sub_model = tf.keras.models.Model(input_layer, x, name='sub_model') model = tf.keras.models.Model(input_layer, output_layer, name='model') model.add_metric( tf.reduce_mean(input_layer), name='mean_input', aggregation='mean') model.optimizer = tf.keras.optimizers.SGD(learning_rate=0.1, momentum=0.9) if use_float16: model.optimizer = tf.keras.mixed_precision.LossScaleOptimizer( model.optimizer) return model, sub_model return _model_fn def metric_fn(): """Gets a tf.keras metric object.""" return tf.keras.metrics.CategoricalAccuracy(name='accuracy', dtype=tf.float32) def summaries_with_matching_keyword(keyword, summary_dir): """Yields summary protos matching given keyword from event file.""" event_paths = tf.io.gfile.glob(os.path.join(summary_dir, 'events*')) for event in tf.compat.v1.train.summary_iterator(event_paths[-1]): if event.summary is not None: for value in event.summary.value: if keyword in value.tag: logging.error(event) yield event.summary def check_eventfile_for_keyword(keyword, summary_dir): """Checks event files for the keyword.""" return any(summaries_with_matching_keyword(keyword, summary_dir)) class RecordingCallback(tf.keras.callbacks.Callback): def __init__(self): self.batch_begin = [] # (batch, logs) self.batch_end = [] # (batch, logs) self.epoch_begin = [] # (epoch, logs) self.epoch_end = [] # (epoch, logs) def on_batch_begin(self, batch, logs=None): self.batch_begin.append((batch, logs)) def on_batch_end(self, batch, logs=None): self.batch_end.append((batch, logs)) def on_epoch_begin(self, epoch, logs=None): self.epoch_begin.append((epoch, logs)) def on_epoch_end(self, epoch, logs=None): self.epoch_end.append((epoch, logs)) class ModelTrainingUtilsTest(tf.test.TestCase, parameterized.TestCase): def setUp(self): super(ModelTrainingUtilsTest, self).setUp() self._model_fn = create_model_fn(input_shape=[128], num_classes=3) @flagsaver.flagsaver def run_training(self, strategy, model_dir, steps_per_loop, run_eagerly): input_fn = create_fake_data_input_fn( batch_size=8, features_shape=[128], num_classes=3) model_training_utils.run_customized_training_loop( strategy=strategy, model_fn=self._model_fn, loss_fn=tf.keras.losses.categorical_crossentropy, model_dir=model_dir, steps_per_epoch=20, steps_per_loop=steps_per_loop, epochs=2, train_input_fn=input_fn, eval_input_fn=input_fn, eval_steps=10, init_checkpoint=None, sub_model_export_name='my_submodel_name', metric_fn=metric_fn, custom_callbacks=None, run_eagerly=run_eagerly) @combinations.generate(eager_strategy_combinations()) def test_train_eager_single_step(self, distribution): model_dir = self.create_tempdir().full_path if isinstance( distribution, (tf.distribute.TPUStrategy, tf.distribute.experimental.TPUStrategy)): with self.assertRaises(ValueError): self.run_training( distribution, model_dir, steps_per_loop=1, run_eagerly=True) else: self.run_training( distribution, model_dir, steps_per_loop=1, run_eagerly=True) @combinations.generate(eager_gpu_strategy_combinations()) def test_train_eager_mixed_precision(self, distribution): model_dir = self.create_tempdir().full_path tf.keras.mixed_precision.set_global_policy('mixed_float16') self._model_fn = create_model_fn( input_shape=[128], num_classes=3, use_float16=True) self.run_training( distribution, model_dir, steps_per_loop=1, run_eagerly=True) @combinations.generate(eager_strategy_combinations()) def test_train_check_artifacts(self, distribution): model_dir = self.create_tempdir().full_path self.run_training( distribution, model_dir, steps_per_loop=10, run_eagerly=False) # Two checkpoints should be saved after two epochs. files = map(os.path.basename, tf.io.gfile.glob(os.path.join(model_dir, 'ctl_step_*index'))) self.assertCountEqual( ['ctl_step_20.ckpt-1.index', 'ctl_step_40.ckpt-2.index'], files) # Three submodel checkpoints should be saved after two epochs (one after # each epoch plus one final). files = map( os.path.basename, tf.io.gfile.glob(os.path.join(model_dir, 'my_submodel_name*index'))) self.assertCountEqual([ 'my_submodel_name.ckpt-3.index', 'my_submodel_name_step_20.ckpt-1.index', 'my_submodel_name_step_40.ckpt-2.index' ], files) self.assertNotEmpty( tf.io.gfile.glob( os.path.join(model_dir, 'summaries/training_summary*'))) # Loss and accuracy values should be written into summaries. self.assertTrue( check_eventfile_for_keyword('loss', os.path.join(model_dir, 'summaries/train'))) self.assertTrue( check_eventfile_for_keyword('accuracy', os.path.join(model_dir, 'summaries/train'))) self.assertTrue( check_eventfile_for_keyword('mean_input', os.path.join(model_dir, 'summaries/train'))) self.assertTrue( check_eventfile_for_keyword('accuracy', os.path.join(model_dir, 'summaries/eval'))) self.assertTrue( check_eventfile_for_keyword('mean_input', os.path.join(model_dir, 'summaries/eval'))) @combinations.generate(eager_strategy_combinations()) def test_train_check_callbacks(self, distribution): model_dir = self.create_tempdir().full_path callback = RecordingCallback() callbacks = [callback] input_fn = create_fake_data_input_fn( batch_size=8, features_shape=[128], num_classes=3) model_training_utils.run_customized_training_loop( strategy=distribution, model_fn=self._model_fn, loss_fn=tf.keras.losses.categorical_crossentropy, model_dir=model_dir, steps_per_epoch=20, num_eval_per_epoch=4, steps_per_loop=10, epochs=2, train_input_fn=input_fn, eval_input_fn=input_fn, eval_steps=10, init_checkpoint=None, metric_fn=metric_fn, custom_callbacks=callbacks, run_eagerly=False) self.assertEqual(callback.epoch_begin, [(1, {}), (2, {})]) epoch_ends, epoch_end_infos = zip(*callback.epoch_end) self.assertEqual(list(epoch_ends), [1, 2, 2]) for info in epoch_end_infos: self.assertIn('accuracy', info) self.assertEqual(callback.batch_begin, [(0, {}), (5, {}), (10, {}), (15, {}), (20, {}), (25, {}), (30, {}), (35, {})]) batch_ends, batch_end_infos = zip(*callback.batch_end) self.assertEqual(list(batch_ends), [4, 9, 14, 19, 24, 29, 34, 39]) for info in batch_end_infos: self.assertIn('loss', info) @combinations.generate( combinations.combine( distribution=[ strategy_combinations.one_device_strategy_gpu, ],)) def test_train_check_artifacts_non_chief(self, distribution): # We shouldn't export artifacts on non-chief workers. Since there's no easy # way to test with real MultiWorkerMirroredStrategy, we patch the strategy # to make it as if it's MultiWorkerMirroredStrategy on non-chief workers. extended = distribution.extended with mock.patch.object(extended.__class__, 'should_checkpoint', new_callable=mock.PropertyMock, return_value=False), \ mock.patch.object(extended.__class__, 'should_save_summary', new_callable=mock.PropertyMock, return_value=False): model_dir = self.create_tempdir().full_path self.run_training( distribution, model_dir, steps_per_loop=10, run_eagerly=False) self.assertEmpty(tf.io.gfile.listdir(model_dir)) if __name__ == '__main__': tf.test.main()
11,705
37.130293
81
py
models
models-master/official/legacy/bert/run_squad_helper.py
# Copyright 2023 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. """Library for running BERT family models on SQuAD 1.1/2.0 in TF 2.x.""" import collections import json import os from absl import flags from absl import logging import tensorflow as tf from official.legacy.bert import bert_models from official.legacy.bert import common_flags from official.legacy.bert import input_pipeline from official.legacy.bert import model_saving_utils from official.legacy.bert import model_training_utils from official.modeling import performance from official.nlp import optimization from official.nlp.data import squad_lib_sp from official.nlp.tools import squad_evaluate_v1_1 from official.nlp.tools import squad_evaluate_v2_0 from official.utils.misc import keras_utils def define_common_squad_flags(): """Defines common flags used by SQuAD tasks.""" flags.DEFINE_enum( 'mode', 'train_and_eval', [ 'train_and_eval', 'train_and_predict', 'train', 'eval', 'predict', 'export_only' ], 'One of {"train_and_eval", "train_and_predict", ' '"train", "eval", "predict", "export_only"}. ' '`train_and_eval`: train & predict to json files & compute eval metrics. ' '`train_and_predict`: train & predict to json files. ' '`train`: only trains the model. ' '`eval`: predict answers from squad json file & compute eval metrics. ' '`predict`: predict answers from the squad json file. ' '`export_only`: will take the latest checkpoint inside ' 'model_dir and export a `SavedModel`.') flags.DEFINE_string('train_data_path', '', 'Training data path with train tfrecords.') flags.DEFINE_string( 'input_meta_data_path', None, 'Path to file that contains meta data about input ' 'to be used for training and evaluation.') # Model training specific flags. flags.DEFINE_integer('train_batch_size', 32, 'Total batch size for training.') # Predict processing related. flags.DEFINE_string( 'predict_file', None, 'SQuAD prediction json file path. ' '`predict` mode supports multiple files: one can use ' 'wildcard to specify multiple files and it can also be ' 'multiple file patterns separated by comma. Note that ' '`eval` mode only supports a single predict file.') flags.DEFINE_bool( 'do_lower_case', True, 'Whether to lower case the input text. Should be True for uncased ' 'models and False for cased models.') flags.DEFINE_float( 'null_score_diff_threshold', 0.0, 'If null_score - best_non_null is greater than the threshold, ' 'predict null. This is only used for SQuAD v2.') flags.DEFINE_bool( 'verbose_logging', False, 'If true, all of the warnings related to data processing will be ' 'printed. A number of warnings are expected for a normal SQuAD ' 'evaluation.') flags.DEFINE_integer('predict_batch_size', 8, 'Total batch size for prediction.') flags.DEFINE_integer( 'n_best_size', 20, 'The total number of n-best predictions to generate in the ' 'nbest_predictions.json output file.') flags.DEFINE_integer( 'max_answer_length', 30, 'The maximum length of an answer that can be generated. This is needed ' 'because the start and end predictions are not conditioned on one ' 'another.') common_flags.define_common_bert_flags() FLAGS = flags.FLAGS def squad_loss_fn(start_positions, end_positions, start_logits, end_logits): """Returns sparse categorical crossentropy for start/end logits.""" start_loss = tf.keras.losses.sparse_categorical_crossentropy( start_positions, start_logits, from_logits=True) end_loss = tf.keras.losses.sparse_categorical_crossentropy( end_positions, end_logits, from_logits=True) total_loss = (tf.reduce_mean(start_loss) + tf.reduce_mean(end_loss)) / 2 return total_loss def get_loss_fn(): """Gets a loss function for squad task.""" def _loss_fn(labels, model_outputs): start_positions = labels['start_positions'] end_positions = labels['end_positions'] start_logits, end_logits = model_outputs return squad_loss_fn(start_positions, end_positions, start_logits, end_logits) return _loss_fn RawResult = collections.namedtuple('RawResult', ['unique_id', 'start_logits', 'end_logits']) def get_raw_results(predictions): """Converts multi-replica predictions to RawResult.""" for unique_ids, start_logits, end_logits in zip(predictions['unique_ids'], predictions['start_logits'], predictions['end_logits']): for values in zip(unique_ids.numpy(), start_logits.numpy(), end_logits.numpy()): yield RawResult( unique_id=values[0], start_logits=values[1].tolist(), end_logits=values[2].tolist()) def get_dataset_fn(input_file_pattern, max_seq_length, global_batch_size, is_training): """Gets a closure to create a dataset..""" def _dataset_fn(ctx=None): """Returns tf.data.Dataset for distributed BERT pretraining.""" batch_size = ctx.get_per_replica_batch_size( global_batch_size) if ctx else global_batch_size dataset = input_pipeline.create_squad_dataset( input_file_pattern, max_seq_length, batch_size, is_training=is_training, input_pipeline_context=ctx) return dataset return _dataset_fn def get_squad_model_to_predict(strategy, bert_config, checkpoint_path, input_meta_data): """Gets a squad model to make predictions.""" with strategy.scope(): # Prediction always uses float32, even if training uses mixed precision. tf.keras.mixed_precision.set_global_policy('float32') squad_model, _ = bert_models.squad_model( bert_config, input_meta_data['max_seq_length'], hub_module_url=FLAGS.hub_module_url) if checkpoint_path is None: checkpoint_path = tf.train.latest_checkpoint(FLAGS.model_dir) logging.info('Restoring checkpoints from %s', checkpoint_path) checkpoint = tf.train.Checkpoint(model=squad_model) checkpoint.restore(checkpoint_path).expect_partial() return squad_model def predict_squad_customized(strategy, input_meta_data, predict_tfrecord_path, num_steps, squad_model): """Make predictions using a Bert-based squad model.""" predict_dataset_fn = get_dataset_fn( predict_tfrecord_path, input_meta_data['max_seq_length'], FLAGS.predict_batch_size, is_training=False) predict_iterator = iter( strategy.distribute_datasets_from_function(predict_dataset_fn)) @tf.function def predict_step(iterator): """Predicts on distributed devices.""" def _replicated_step(inputs): """Replicated prediction calculation.""" x, _ = inputs unique_ids = x.pop('unique_ids') start_logits, end_logits = squad_model(x, training=False) return dict( unique_ids=unique_ids, start_logits=start_logits, end_logits=end_logits) outputs = strategy.run(_replicated_step, args=(next(iterator),)) return tf.nest.map_structure(strategy.experimental_local_results, outputs) all_results = [] for _ in range(num_steps): predictions = predict_step(predict_iterator) for result in get_raw_results(predictions): all_results.append(result) if len(all_results) % 100 == 0: logging.info('Made predictions for %d records.', len(all_results)) return all_results def train_squad(strategy, input_meta_data, bert_config, custom_callbacks=None, run_eagerly=False, init_checkpoint=None, sub_model_export_name=None): """Run bert squad training.""" if strategy: logging.info('Training using customized training loop with distribution' ' strategy.') # Enables XLA in Session Config. Should not be set for TPU. keras_utils.set_session_config(FLAGS.enable_xla) performance.set_mixed_precision_policy(common_flags.dtype()) epochs = FLAGS.num_train_epochs num_train_examples = input_meta_data['train_data_size'] max_seq_length = input_meta_data['max_seq_length'] steps_per_epoch = int(num_train_examples / FLAGS.train_batch_size) warmup_steps = int(epochs * num_train_examples * 0.1 / FLAGS.train_batch_size) train_input_fn = get_dataset_fn( FLAGS.train_data_path, max_seq_length, FLAGS.train_batch_size, is_training=True) def _get_squad_model(): """Get Squad model and optimizer.""" squad_model, core_model = bert_models.squad_model( bert_config, max_seq_length, hub_module_url=FLAGS.hub_module_url, hub_module_trainable=FLAGS.hub_module_trainable) optimizer = optimization.create_optimizer(FLAGS.learning_rate, steps_per_epoch * epochs, warmup_steps, FLAGS.end_lr, FLAGS.optimizer_type) squad_model.optimizer = performance.configure_optimizer( optimizer, use_float16=common_flags.use_float16()) return squad_model, core_model # Only when explicit_allreduce = True, post_allreduce_callbacks and # allreduce_bytes_per_pack will take effect. optimizer.apply_gradients() no # longer implicitly allreduce gradients, users manually allreduce gradient and # pass the allreduced grads_and_vars to apply_gradients(). # With explicit_allreduce = True, clip_by_global_norm is moved to after # allreduce. model_training_utils.run_customized_training_loop( strategy=strategy, model_fn=_get_squad_model, loss_fn=get_loss_fn(), model_dir=FLAGS.model_dir, steps_per_epoch=steps_per_epoch, steps_per_loop=FLAGS.steps_per_loop, epochs=epochs, train_input_fn=train_input_fn, init_checkpoint=init_checkpoint or FLAGS.init_checkpoint, sub_model_export_name=sub_model_export_name, run_eagerly=run_eagerly, custom_callbacks=custom_callbacks, explicit_allreduce=FLAGS.explicit_allreduce, pre_allreduce_callbacks=[ model_training_utils.clip_by_global_norm_callback ], allreduce_bytes_per_pack=FLAGS.allreduce_bytes_per_pack) def prediction_output_squad(strategy, input_meta_data, tokenizer, squad_lib, predict_file, squad_model): """Makes predictions for a squad dataset.""" doc_stride = input_meta_data['doc_stride'] max_query_length = input_meta_data['max_query_length'] # Whether data should be in Ver 2.0 format. version_2_with_negative = input_meta_data.get('version_2_with_negative', False) eval_examples = squad_lib.read_squad_examples( input_file=predict_file, is_training=False, version_2_with_negative=version_2_with_negative) eval_writer = squad_lib.FeatureWriter( filename=os.path.join(FLAGS.model_dir, 'eval.tf_record'), is_training=False) eval_features = [] def _append_feature(feature, is_padding): if not is_padding: eval_features.append(feature) eval_writer.process_feature(feature) # TPU requires a fixed batch size for all batches, therefore the number # of examples must be a multiple of the batch size, or else examples # will get dropped. So we pad with fake examples which are ignored # later on. kwargs = dict( examples=eval_examples, tokenizer=tokenizer, max_seq_length=input_meta_data['max_seq_length'], doc_stride=doc_stride, max_query_length=max_query_length, is_training=False, output_fn=_append_feature, batch_size=FLAGS.predict_batch_size) # squad_lib_sp requires one more argument 'do_lower_case'. if squad_lib == squad_lib_sp: kwargs['do_lower_case'] = FLAGS.do_lower_case dataset_size = squad_lib.convert_examples_to_features(**kwargs) eval_writer.close() logging.info('***** Running predictions *****') logging.info(' Num orig examples = %d', len(eval_examples)) logging.info(' Num split examples = %d', len(eval_features)) logging.info(' Batch size = %d', FLAGS.predict_batch_size) num_steps = int(dataset_size / FLAGS.predict_batch_size) all_results = predict_squad_customized(strategy, input_meta_data, eval_writer.filename, num_steps, squad_model) all_predictions, all_nbest_json, scores_diff_json = ( squad_lib.postprocess_output( eval_examples, eval_features, all_results, FLAGS.n_best_size, FLAGS.max_answer_length, FLAGS.do_lower_case, version_2_with_negative=version_2_with_negative, null_score_diff_threshold=FLAGS.null_score_diff_threshold, verbose=FLAGS.verbose_logging)) return all_predictions, all_nbest_json, scores_diff_json def dump_to_files(all_predictions, all_nbest_json, scores_diff_json, squad_lib, version_2_with_negative, file_prefix=''): """Save output to json files.""" output_prediction_file = os.path.join(FLAGS.model_dir, '%spredictions.json' % file_prefix) output_nbest_file = os.path.join(FLAGS.model_dir, '%snbest_predictions.json' % file_prefix) output_null_log_odds_file = os.path.join(FLAGS.model_dir, file_prefix, '%snull_odds.json' % file_prefix) logging.info('Writing predictions to: %s', (output_prediction_file)) logging.info('Writing nbest to: %s', (output_nbest_file)) squad_lib.write_to_json_files(all_predictions, output_prediction_file) squad_lib.write_to_json_files(all_nbest_json, output_nbest_file) if version_2_with_negative: squad_lib.write_to_json_files(scores_diff_json, output_null_log_odds_file) def _get_matched_files(input_path): """Returns all files that matches the input_path.""" input_patterns = input_path.strip().split(',') all_matched_files = [] for input_pattern in input_patterns: input_pattern = input_pattern.strip() if not input_pattern: continue matched_files = tf.io.gfile.glob(input_pattern) if not matched_files: raise ValueError('%s does not match any files.' % input_pattern) else: all_matched_files.extend(matched_files) return sorted(all_matched_files) def predict_squad(strategy, input_meta_data, tokenizer, bert_config, squad_lib, init_checkpoint=None): """Get prediction results and evaluate them to hard drive.""" if init_checkpoint is None: init_checkpoint = tf.train.latest_checkpoint(FLAGS.model_dir) all_predict_files = _get_matched_files(FLAGS.predict_file) squad_model = get_squad_model_to_predict(strategy, bert_config, init_checkpoint, input_meta_data) for idx, predict_file in enumerate(all_predict_files): all_predictions, all_nbest_json, scores_diff_json = prediction_output_squad( strategy, input_meta_data, tokenizer, squad_lib, predict_file, squad_model) if len(all_predict_files) == 1: file_prefix = '' else: # if predict_file is /path/xquad.ar.json, the `file_prefix` may be # "xquad.ar-0-" file_prefix = '%s-' % os.path.splitext( os.path.basename(all_predict_files[idx]))[0] dump_to_files(all_predictions, all_nbest_json, scores_diff_json, squad_lib, input_meta_data.get('version_2_with_negative', False), file_prefix) def eval_squad(strategy, input_meta_data, tokenizer, bert_config, squad_lib, init_checkpoint=None): """Get prediction results and evaluate them against ground truth.""" if init_checkpoint is None: init_checkpoint = tf.train.latest_checkpoint(FLAGS.model_dir) all_predict_files = _get_matched_files(FLAGS.predict_file) if len(all_predict_files) != 1: raise ValueError('`eval_squad` only supports one predict file, ' 'but got %s' % all_predict_files) squad_model = get_squad_model_to_predict(strategy, bert_config, init_checkpoint, input_meta_data) all_predictions, all_nbest_json, scores_diff_json = prediction_output_squad( strategy, input_meta_data, tokenizer, squad_lib, all_predict_files[0], squad_model) dump_to_files(all_predictions, all_nbest_json, scores_diff_json, squad_lib, input_meta_data.get('version_2_with_negative', False)) with tf.io.gfile.GFile(FLAGS.predict_file, 'r') as reader: dataset_json = json.load(reader) pred_dataset = dataset_json['data'] if input_meta_data.get('version_2_with_negative', False): eval_metrics = squad_evaluate_v2_0.evaluate(pred_dataset, all_predictions, scores_diff_json) else: eval_metrics = squad_evaluate_v1_1.evaluate(pred_dataset, all_predictions) return eval_metrics def export_squad(model_export_path, input_meta_data, bert_config): """Exports a trained model as a `SavedModel` for inference. Args: model_export_path: a string specifying the path to the SavedModel directory. input_meta_data: dictionary containing meta data about input and model. bert_config: Bert configuration file to define core bert layers. Raises: Export path is not specified, got an empty string or None. """ if not model_export_path: raise ValueError('Export path is not specified: %s' % model_export_path) # Export uses float32 for now, even if training uses mixed precision. tf.keras.mixed_precision.set_global_policy('float32') squad_model, _ = bert_models.squad_model(bert_config, input_meta_data['max_seq_length']) model_saving_utils.export_bert_model( model_export_path, model=squad_model, checkpoint_dir=FLAGS.model_dir)
18,945
39.139831
80
py
models
models-master/official/legacy/bert/model_saving_utils.py
# Copyright 2023 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. """Utilities to save models.""" import os import typing from absl import logging import tensorflow as tf def export_bert_model(model_export_path: typing.Text, model: tf.keras.Model, checkpoint_dir: typing.Optional[typing.Text] = None, restore_model_using_load_weights: bool = False) -> None: """Export BERT model for serving which does not include the optimizer. Args: model_export_path: Path to which exported model will be saved. model: Keras model object to export. checkpoint_dir: Path from which model weights will be loaded, if specified. restore_model_using_load_weights: Whether to use checkpoint.restore() API for custom checkpoint or to use model.load_weights() API. There are 2 different ways to save checkpoints. One is using tf.train.Checkpoint and another is using Keras model.save_weights(). Custom training loop implementation uses tf.train.Checkpoint API and Keras ModelCheckpoint callback internally uses model.save_weights() API. Since these two API's cannot be used toghether, model loading logic must be take into account how model checkpoint was saved. Raises: ValueError when either model_export_path or model is not specified. """ if not model_export_path: raise ValueError('model_export_path must be specified.') if not isinstance(model, tf.keras.Model): raise ValueError('model must be a tf.keras.Model object.') if checkpoint_dir: if restore_model_using_load_weights: model_weight_path = os.path.join(checkpoint_dir, 'checkpoint') assert tf.io.gfile.exists(model_weight_path) model.load_weights(model_weight_path) else: checkpoint = tf.train.Checkpoint(model=model) # Restores the model from latest checkpoint. latest_checkpoint_file = tf.train.latest_checkpoint(checkpoint_dir) assert latest_checkpoint_file logging.info('Checkpoint file %s found and restoring from ' 'checkpoint', latest_checkpoint_file) checkpoint.restore( latest_checkpoint_file).assert_existing_objects_matched() model.save(model_export_path, include_optimizer=False, save_format='tf')
2,875
41.294118
80
py
models
models-master/official/legacy/image_classification/callbacks.py
# Copyright 2023 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. """Common modules for callbacks.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from typing import Any, List, MutableMapping, Optional, Text from absl import logging import tensorflow as tf from official.modeling import optimization from official.utils.misc import keras_utils def get_callbacks( model_checkpoint: bool = True, include_tensorboard: bool = True, time_history: bool = True, track_lr: bool = True, write_model_weights: bool = True, apply_moving_average: bool = False, initial_step: int = 0, batch_size: int = 0, log_steps: int = 0, model_dir: Optional[str] = None, backup_and_restore: bool = False) -> List[tf.keras.callbacks.Callback]: """Get all callbacks.""" model_dir = model_dir or '' callbacks = [] if model_checkpoint: ckpt_full_path = os.path.join(model_dir, 'model.ckpt-{epoch:04d}') callbacks.append( tf.keras.callbacks.ModelCheckpoint( ckpt_full_path, save_weights_only=True, verbose=1)) if backup_and_restore: backup_dir = os.path.join(model_dir, 'tmp') callbacks.append( tf.keras.callbacks.experimental.BackupAndRestore(backup_dir)) if include_tensorboard: callbacks.append( CustomTensorBoard( log_dir=model_dir, track_lr=track_lr, initial_step=initial_step, write_images=write_model_weights, profile_batch=0)) if time_history: callbacks.append( keras_utils.TimeHistory( batch_size, log_steps, logdir=model_dir if include_tensorboard else None)) if apply_moving_average: # Save moving average model to a different file so that # we can resume training from a checkpoint ckpt_full_path = os.path.join(model_dir, 'average', 'model.ckpt-{epoch:04d}') callbacks.append( AverageModelCheckpoint( update_weights=False, filepath=ckpt_full_path, save_weights_only=True, verbose=1)) callbacks.append(MovingAverageCallback()) return callbacks def get_scalar_from_tensor(t: tf.Tensor) -> int: """Utility function to convert a Tensor to a scalar.""" t = tf.keras.backend.get_value(t) if callable(t): return t() else: return t class CustomTensorBoard(tf.keras.callbacks.TensorBoard): """A customized TensorBoard callback that tracks additional datapoints. Metrics tracked: - Global learning rate Attributes: log_dir: the path of the directory where to save the log files to be parsed by TensorBoard. track_lr: `bool`, whether or not to track the global learning rate. initial_step: the initial step, used for preemption recovery. **kwargs: Additional arguments for backwards compatibility. Possible key is `period`. """ # TODO(b/146499062): track params, flops, log lr, l2 loss, # classification loss def __init__(self, log_dir: str, track_lr: bool = False, initial_step: int = 0, **kwargs): super(CustomTensorBoard, self).__init__(log_dir=log_dir, **kwargs) self.step = initial_step self._track_lr = track_lr def on_batch_begin(self, epoch: int, logs: Optional[MutableMapping[str, Any]] = None) -> None: self.step += 1 if logs is None: logs = {} logs.update(self._calculate_metrics()) super(CustomTensorBoard, self).on_batch_begin(epoch, logs) def on_epoch_begin(self, epoch: int, logs: Optional[MutableMapping[str, Any]] = None) -> None: if logs is None: logs = {} metrics = self._calculate_metrics() logs.update(metrics) for k, v in metrics.items(): logging.info('Current %s: %f', k, v) super(CustomTensorBoard, self).on_epoch_begin(epoch, logs) def on_epoch_end(self, epoch: int, logs: Optional[MutableMapping[str, Any]] = None) -> None: if logs is None: logs = {} metrics = self._calculate_metrics() logs.update(metrics) super(CustomTensorBoard, self).on_epoch_end(epoch, logs) def _calculate_metrics(self) -> MutableMapping[str, Any]: logs = {} # TODO(b/149030439): disable LR reporting. # if self._track_lr: # logs['learning_rate'] = self._calculate_lr() return logs def _calculate_lr(self) -> int: """Calculates the learning rate given the current step.""" return get_scalar_from_tensor( self._get_base_optimizer()._decayed_lr(var_dtype=tf.float32)) # pylint:disable=protected-access def _get_base_optimizer(self) -> tf.keras.optimizers.Optimizer: """Get the base optimizer used by the current model.""" optimizer = self.model.optimizer # The optimizer might be wrapped by another class, so unwrap it while hasattr(optimizer, '_optimizer'): optimizer = optimizer._optimizer # pylint:disable=protected-access return optimizer class MovingAverageCallback(tf.keras.callbacks.Callback): """A Callback to be used with a `ExponentialMovingAverage` optimizer. Applies moving average weights to the model during validation time to test and predict on the averaged weights rather than the current model weights. Once training is complete, the model weights will be overwritten with the averaged weights (by default). Attributes: overwrite_weights_on_train_end: Whether to overwrite the current model weights with the averaged weights from the moving average optimizer. **kwargs: Any additional callback arguments. """ def __init__(self, overwrite_weights_on_train_end: bool = False, **kwargs): super(MovingAverageCallback, self).__init__(**kwargs) self.overwrite_weights_on_train_end = overwrite_weights_on_train_end def set_model(self, model: tf.keras.Model): super(MovingAverageCallback, self).set_model(model) assert isinstance(self.model.optimizer, optimization.ExponentialMovingAverage) self.model.optimizer.shadow_copy(self.model) def on_test_begin(self, logs: Optional[MutableMapping[Text, Any]] = None): self.model.optimizer.swap_weights() def on_test_end(self, logs: Optional[MutableMapping[Text, Any]] = None): self.model.optimizer.swap_weights() def on_train_end(self, logs: Optional[MutableMapping[Text, Any]] = None): if self.overwrite_weights_on_train_end: self.model.optimizer.assign_average_vars(self.model.variables) class AverageModelCheckpoint(tf.keras.callbacks.ModelCheckpoint): """Saves and, optionally, assigns the averaged weights. Taken from tfa.callbacks.AverageModelCheckpoint. Attributes: update_weights: If True, assign the moving average weights to the model, and save them. If False, keep the old non-averaged weights, but the saved model uses the average weights. See `tf.keras.callbacks.ModelCheckpoint` for the other args. """ def __init__(self, update_weights: bool, filepath: str, monitor: str = 'val_loss', verbose: int = 0, save_best_only: bool = False, save_weights_only: bool = False, mode: str = 'auto', save_freq: str = 'epoch', **kwargs): self.update_weights = update_weights super().__init__(filepath, monitor, verbose, save_best_only, save_weights_only, mode, save_freq, **kwargs) def set_model(self, model): if not isinstance(model.optimizer, optimization.ExponentialMovingAverage): raise TypeError('AverageModelCheckpoint is only used when training' 'with MovingAverage') return super().set_model(model) def _save_model(self, epoch, logs): assert isinstance(self.model.optimizer, optimization.ExponentialMovingAverage) if self.update_weights: self.model.optimizer.assign_average_vars(self.model.variables) return super()._save_model(epoch, logs) # pytype: disable=attribute-error # typed-keras else: # Note: `model.get_weights()` gives us the weights (non-ref) # whereas `model.variables` returns references to the variables. non_avg_weights = self.model.get_weights() self.model.optimizer.assign_average_vars(self.model.variables) # result is currently None, since `super._save_model` doesn't # return anything, but this may change in the future. result = super()._save_model(epoch, logs) # pytype: disable=attribute-error # typed-keras self.model.set_weights(non_avg_weights) return result
9,355
35.546875
104
py
models
models-master/official/legacy/image_classification/optimizer_factory.py
# Copyright 2023 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. """Optimizer factory for vision tasks.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from typing import Any, Dict, Optional, Text, Union from absl import logging import numpy as np import tensorflow as tf from official.legacy.image_classification import learning_rate from official.legacy.image_classification.configs import base_configs from official.modeling import optimization from official.modeling.optimization import legacy_adamw # pylint: disable=protected-access FloatTensorLike = Union[tf.Tensor, float, np.float16, np.float32, np.float64] class Lookahead(tf.keras.optimizers.legacy.Optimizer): """This class allows to extend optimizers with the lookahead mechanism. The mechanism is proposed by Michael R. Zhang et.al in the paper [Lookahead Optimizer: k steps forward, 1 step back] (https://arxiv.org/abs/1907.08610v1). The optimizer iteratively updates two sets of weights: the search directions for weights are chosen by the inner optimizer, while the "slow weights" are updated each `k` steps based on the directions of the "fast weights" and the two sets of weights are synchronized. This method improves the learning stability and lowers the variance of its inner optimizer. Example of usage: ```python opt = tf.keras.optimizers.SGD(learning_rate) opt = tfa.optimizers.Lookahead(opt) ``` """ def __init__( self, optimizer: tf.keras.optimizers.Optimizer, sync_period: int = 6, slow_step_size: FloatTensorLike = 0.5, name: str = 'Lookahead', **kwargs, ): """Wrap optimizer with the lookahead mechanism. Args: optimizer: The original optimizer that will be used to compute and apply the gradients. sync_period: An integer. The synchronization period of lookahead. Enable lookahead mechanism by setting it with a positive value. slow_step_size: A floating point value. The ratio for updating the slow weights. name: Optional name for the operations created when applying gradients. Defaults to "Lookahead". **kwargs: keyword arguments. Allowed to be {`clipnorm`, `clipvalue`, `lr`, `decay`}. `clipnorm` is clip gradients by norm; `clipvalue` is clip gradients by value, `decay` is included for backward compatibility to allow time inverse decay of learning rate. `lr` is included for backward compatibility, recommended to use `learning_rate` instead. """ super().__init__(name, **kwargs) if isinstance(optimizer, str): optimizer = tf.keras.optimizers.get(optimizer) if not isinstance( optimizer, (tf.keras.optimizers.Optimizer, tf.keras.optimizers.legacy.Optimizer), ): raise TypeError( 'optimizer is not an object of tf.keras.optimizers.Optimizer' ) self._optimizer = optimizer self._set_hyper('sync_period', sync_period) self._set_hyper('slow_step_size', slow_step_size) self._initialized = False self._track_trackable(self._optimizer, 'lh_base_optimizer') def _create_slots(self, var_list): self._optimizer._create_slots(var_list=var_list) # pylint: disable=protected-access for var in var_list: self.add_slot(var, 'slow', initializer=var) def _create_hypers(self): self._optimizer._create_hypers() # pylint: disable=protected-access def _prepare(self, var_list): return self._optimizer._prepare(var_list=var_list) # pylint: disable=protected-access def apply_gradients( self, grads_and_vars, name=None, skip_gradients_aggregation=None, **kwargs ): self._optimizer._iterations = self.iterations # pylint: disable=protected-access return super().apply_gradients(grads_and_vars, name, **kwargs) def _look_ahead_op(self, var): var_dtype = var.dtype.base_dtype slow_var = self.get_slot(var, 'slow') local_step = tf.cast(self.iterations + 1, tf.dtypes.int64) sync_period = self._get_hyper('sync_period', tf.dtypes.int64) slow_step_size = self._get_hyper('slow_step_size', var_dtype) step_back = slow_var + slow_step_size * (var - slow_var) sync_cond = tf.equal( tf.math.floordiv(local_step, sync_period) * sync_period, local_step ) with tf.control_dependencies([step_back]): slow_update = slow_var.assign( tf.where(sync_cond, step_back, slow_var), use_locking=self._use_locking, ) var_update = var.assign( tf.where(sync_cond, step_back, var), use_locking=self._use_locking ) return tf.group(slow_update, var_update) @property def weights(self): return self._weights + self._optimizer.weights def _resource_apply_dense(self, grad, var): train_op = self._optimizer._resource_apply_dense(grad, var) # pylint: disable=protected-access with tf.control_dependencies([train_op]): look_ahead_op = self._look_ahead_op(var) return tf.group(train_op, look_ahead_op) def _resource_apply_sparse(self, grad, var, indices): train_op = self._optimizer._resource_apply_sparse( # pylint: disable=protected-access grad, var, indices ) with tf.control_dependencies([train_op]): look_ahead_op = self._look_ahead_op(var) return tf.group(train_op, look_ahead_op) def get_config(self): config = { 'optimizer': tf.keras.optimizers.serialize(self._optimizer), 'sync_period': self._serialize_hyperparameter('sync_period'), 'slow_step_size': self._serialize_hyperparameter('slow_step_size'), } base_config = super().get_config() return {**base_config, **config} @property def learning_rate(self): return self._optimizer._get_hyper('learning_rate') @learning_rate.setter def learning_rate(self, value): self._optimizer._set_hyper('learning_rate', value) @property def lr(self): return self.learning_rate @lr.setter def lr(self, lr): self.learning_rate = lr @classmethod def from_config(cls, config, custom_objects=None): optimizer = tf.keras.optimizers.deserialize( config.pop('optimizer'), custom_objects=custom_objects ) return cls(optimizer, **config) def build_optimizer( optimizer_name: Text, base_learning_rate: tf.keras.optimizers.schedules.LearningRateSchedule, params: Dict[Text, Any], model: Optional[tf.keras.Model] = None): """Build the optimizer based on name. Args: optimizer_name: String representation of the optimizer name. Examples: sgd, momentum, rmsprop. base_learning_rate: `tf.keras.optimizers.schedules.LearningRateSchedule` base learning rate. params: String -> Any dictionary representing the optimizer params. This should contain optimizer specific parameters such as `base_learning_rate`, `decay`, etc. model: The `tf.keras.Model`. This is used for the shadow copy if using `ExponentialMovingAverage`. Returns: A tf.keras.optimizers.legacy.Optimizer. Raises: ValueError if the provided optimizer_name is not supported. """ optimizer_name = optimizer_name.lower() logging.info('Building %s optimizer with params %s', optimizer_name, params) if optimizer_name == 'sgd': logging.info('Using SGD optimizer') nesterov = params.get('nesterov', False) optimizer = tf.keras.optimizers.legacy.SGD( learning_rate=base_learning_rate, nesterov=nesterov) elif optimizer_name == 'momentum': logging.info('Using momentum optimizer') nesterov = params.get('nesterov', False) optimizer = tf.keras.optimizers.legacy.SGD( learning_rate=base_learning_rate, momentum=params['momentum'], nesterov=nesterov) elif optimizer_name == 'rmsprop': logging.info('Using RMSProp') rho = params.get('decay', None) or params.get('rho', 0.9) momentum = params.get('momentum', 0.9) epsilon = params.get('epsilon', 1e-07) optimizer = tf.keras.optimizers.legacy.RMSprop( learning_rate=base_learning_rate, rho=rho, momentum=momentum, epsilon=epsilon) elif optimizer_name == 'adam': logging.info('Using Adam') beta_1 = params.get('beta_1', 0.9) beta_2 = params.get('beta_2', 0.999) epsilon = params.get('epsilon', 1e-07) optimizer = tf.keras.optimizers.legacy.Adam( learning_rate=base_learning_rate, beta_1=beta_1, beta_2=beta_2, epsilon=epsilon) elif optimizer_name == 'adamw': logging.info('Using AdamW') weight_decay = params.get('weight_decay', 0.01) beta_1 = params.get('beta_1', 0.9) beta_2 = params.get('beta_2', 0.999) epsilon = params.get('epsilon', 1e-07) optimizer = legacy_adamw.AdamWeightDecay( learning_rate=base_learning_rate, weight_decay_rate=weight_decay, beta_1=beta_1, beta_2=beta_2, epsilon=epsilon, ) else: raise ValueError('Unknown optimizer %s' % optimizer_name) if params.get('lookahead', None): logging.info('Using lookahead optimizer.') optimizer = Lookahead(optimizer) # Moving average should be applied last, as it's applied at test time moving_average_decay = params.get('moving_average_decay', 0.) if moving_average_decay is not None and moving_average_decay > 0.: if model is None: raise ValueError( '`model` must be provided if using `ExponentialMovingAverage`.') logging.info('Including moving average decay.') optimizer = optimization.ExponentialMovingAverage( optimizer=optimizer, average_decay=moving_average_decay) optimizer.shadow_copy(model) return optimizer def build_learning_rate(params: base_configs.LearningRateConfig, batch_size: Optional[int] = None, train_epochs: Optional[int] = None, train_steps: Optional[int] = None): """Build the learning rate given the provided configuration.""" decay_type = params.name base_lr = params.initial_lr decay_rate = params.decay_rate if params.decay_epochs is not None: decay_steps = params.decay_epochs * train_steps else: decay_steps = 0 if params.warmup_epochs is not None: warmup_steps = params.warmup_epochs * train_steps else: warmup_steps = 0 lr_multiplier = params.scale_by_batch_size if lr_multiplier and lr_multiplier > 0: # Scale the learning rate based on the batch size and a multiplier base_lr *= lr_multiplier * batch_size logging.info( 'Scaling the learning rate based on the batch size ' 'multiplier. New base_lr: %f', base_lr) if decay_type == 'exponential': logging.info( 'Using exponential learning rate with: ' 'initial_learning_rate: %f, decay_steps: %d, ' 'decay_rate: %f', base_lr, decay_steps, decay_rate) lr = tf.keras.optimizers.schedules.ExponentialDecay( initial_learning_rate=base_lr, decay_steps=decay_steps, decay_rate=decay_rate, staircase=params.staircase) elif decay_type == 'stepwise': steps_per_epoch = params.examples_per_epoch // batch_size boundaries = [boundary * steps_per_epoch for boundary in params.boundaries] multipliers = [batch_size * multiplier for multiplier in params.multipliers] logging.info( 'Using stepwise learning rate. Parameters: ' 'boundaries: %s, values: %s', boundaries, multipliers) lr = tf.keras.optimizers.schedules.PiecewiseConstantDecay( boundaries=boundaries, values=multipliers) elif decay_type == 'cosine_with_warmup': lr = learning_rate.CosineDecayWithWarmup( batch_size=batch_size, total_steps=train_epochs * train_steps, warmup_steps=warmup_steps) if warmup_steps > 0: if decay_type not in ['cosine_with_warmup']: logging.info('Applying %d warmup steps to the learning rate', warmup_steps) lr = learning_rate.WarmupDecaySchedule( lr, warmup_steps, warmup_lr=base_lr) return lr
12,603
36.511905
99
py
models
models-master/official/legacy/image_classification/classifier_trainer_util_test.py
# Copyright 2023 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. """Unit tests for the classifier trainer models.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import copy import os from absl.testing import parameterized import tensorflow as tf from official.legacy.image_classification import classifier_trainer from official.legacy.image_classification import dataset_factory from official.legacy.image_classification import test_utils from official.legacy.image_classification.configs import base_configs def get_trivial_model(num_classes: int) -> tf.keras.Model: """Creates and compiles trivial model for ImageNet dataset.""" model = test_utils.trivial_model(num_classes=num_classes) lr = 0.01 optimizer = tf.keras.optimizers.SGD(learning_rate=lr) loss_obj = tf.keras.losses.SparseCategoricalCrossentropy() model.compile(optimizer=optimizer, loss=loss_obj, run_eagerly=True) return model def get_trivial_data() -> tf.data.Dataset: """Gets trivial data in the ImageNet size.""" def generate_data(_) -> tf.data.Dataset: image = tf.zeros(shape=(224, 224, 3), dtype=tf.float32) label = tf.zeros([1], dtype=tf.int32) return image, label dataset = tf.data.Dataset.range(1) dataset = dataset.repeat() dataset = dataset.map( generate_data, num_parallel_calls=tf.data.experimental.AUTOTUNE) dataset = dataset.prefetch(buffer_size=1).batch(1) return dataset class UtilTests(parameterized.TestCase, tf.test.TestCase): """Tests for individual utility functions within classifier_trainer.py.""" @parameterized.named_parameters( ('efficientnet-b0', 'efficientnet', 'efficientnet-b0', 224), ('efficientnet-b1', 'efficientnet', 'efficientnet-b1', 240), ('efficientnet-b2', 'efficientnet', 'efficientnet-b2', 260), ('efficientnet-b3', 'efficientnet', 'efficientnet-b3', 300), ('efficientnet-b4', 'efficientnet', 'efficientnet-b4', 380), ('efficientnet-b5', 'efficientnet', 'efficientnet-b5', 456), ('efficientnet-b6', 'efficientnet', 'efficientnet-b6', 528), ('efficientnet-b7', 'efficientnet', 'efficientnet-b7', 600), ('resnet', 'resnet', '', None), ) def test_get_model_size(self, model, model_name, expected): config = base_configs.ExperimentConfig( model_name=model, model=base_configs.ModelConfig( model_params={ 'model_name': model_name, },)) size = classifier_trainer.get_image_size_from_model(config) self.assertEqual(size, expected) @parameterized.named_parameters( ('dynamic', 'dynamic', None, 'dynamic'), ('scalar', 128., None, 128.), ('float32', None, 'float32', 1), ('float16', None, 'float16', 128), ) def test_get_loss_scale(self, loss_scale, dtype, expected): config = base_configs.ExperimentConfig( runtime=base_configs.RuntimeConfig(loss_scale=loss_scale), train_dataset=dataset_factory.DatasetConfig(dtype=dtype)) ls = classifier_trainer.get_loss_scale(config, fp16_default=128) self.assertEqual(ls, expected) @parameterized.named_parameters(('float16', 'float16'), ('bfloat16', 'bfloat16')) def test_initialize(self, dtype): config = base_configs.ExperimentConfig( runtime=base_configs.RuntimeConfig( run_eagerly=False, enable_xla=False, per_gpu_thread_count=1, gpu_thread_mode='gpu_private', num_gpus=1, dataset_num_private_threads=1, ), train_dataset=dataset_factory.DatasetConfig(dtype=dtype), model=base_configs.ModelConfig(), ) class EmptyClass: pass fake_ds_builder = EmptyClass() fake_ds_builder.dtype = dtype fake_ds_builder.config = EmptyClass() classifier_trainer.initialize(config, fake_ds_builder) def test_resume_from_checkpoint(self): """Tests functionality for resuming from checkpoint.""" # Set the keras policy tf.keras.mixed_precision.set_global_policy('mixed_bfloat16') # Get the model, datasets, and compile it. model = get_trivial_model(10) # Create the checkpoint model_dir = self.create_tempdir().full_path train_epochs = 1 train_steps = 10 ds = get_trivial_data() callbacks = [ tf.keras.callbacks.ModelCheckpoint( os.path.join(model_dir, 'model.ckpt-{epoch:04d}'), save_weights_only=True) ] model.fit( ds, callbacks=callbacks, epochs=train_epochs, steps_per_epoch=train_steps) # Test load from checkpoint clean_model = get_trivial_model(10) weights_before_load = copy.deepcopy(clean_model.get_weights()) initial_epoch = classifier_trainer.resume_from_checkpoint( model=clean_model, model_dir=model_dir, train_steps=train_steps) self.assertEqual(initial_epoch, 1) self.assertNotAllClose(weights_before_load, clean_model.get_weights()) tf.io.gfile.rmtree(model_dir) def test_serialize_config(self): """Tests functionality for serializing data.""" config = base_configs.ExperimentConfig() model_dir = self.create_tempdir().full_path classifier_trainer.serialize_config(params=config, model_dir=model_dir) saved_params_path = os.path.join(model_dir, 'params.yaml') self.assertTrue(os.path.exists(saved_params_path)) tf.io.gfile.rmtree(model_dir) if __name__ == '__main__': tf.test.main()
6,047
35.433735
76
py
models
models-master/official/legacy/image_classification/optimizer_factory_test.py
# Copyright 2023 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. """Tests for optimizer_factory.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl.testing import parameterized import tensorflow as tf from official.legacy.image_classification import optimizer_factory from official.legacy.image_classification.configs import base_configs class OptimizerFactoryTest(tf.test.TestCase, parameterized.TestCase): def build_toy_model(self) -> tf.keras.Model: """Creates a toy `tf.Keras.Model`.""" model = tf.keras.Sequential() model.add(tf.keras.layers.Dense(1, input_shape=(1,))) return model @parameterized.named_parameters( ('sgd', 'sgd', 0., False), ('momentum', 'momentum', 0., False), ('rmsprop', 'rmsprop', 0., False), ('adam', 'adam', 0., False), ('adamw', 'adamw', 0., False), ('momentum_lookahead', 'momentum', 0., True), ('sgd_ema', 'sgd', 0.999, False), ('momentum_ema', 'momentum', 0.999, False), ('rmsprop_ema', 'rmsprop', 0.999, False)) def test_optimizer(self, optimizer_name, moving_average_decay, lookahead): """Smoke test to be sure no syntax errors.""" model = self.build_toy_model() params = { 'learning_rate': 0.001, 'rho': 0.09, 'momentum': 0., 'epsilon': 1e-07, 'moving_average_decay': moving_average_decay, 'lookahead': lookahead, } optimizer = optimizer_factory.build_optimizer( optimizer_name=optimizer_name, base_learning_rate=params['learning_rate'], params=params, model=model) self.assertTrue( issubclass(type(optimizer), tf.keras.optimizers.legacy.Optimizer) ) def test_unknown_optimizer(self): with self.assertRaises(ValueError): optimizer_factory.build_optimizer( optimizer_name='this_optimizer_does_not_exist', base_learning_rate=None, params=None) def test_learning_rate_without_decay_or_warmups(self): params = base_configs.LearningRateConfig( name='exponential', initial_lr=0.01, decay_rate=0.01, decay_epochs=None, warmup_epochs=None, scale_by_batch_size=0.01, examples_per_epoch=1, boundaries=[0], multipliers=[0, 1]) batch_size = 1 train_steps = 1 lr = optimizer_factory.build_learning_rate( params=params, batch_size=batch_size, train_steps=train_steps) self.assertTrue( issubclass( type(lr), tf.keras.optimizers.schedules.LearningRateSchedule)) @parameterized.named_parameters(('exponential', 'exponential'), ('cosine_with_warmup', 'cosine_with_warmup')) def test_learning_rate_with_decay_and_warmup(self, lr_decay_type): """Basic smoke test for syntax.""" params = base_configs.LearningRateConfig( name=lr_decay_type, initial_lr=0.01, decay_rate=0.01, decay_epochs=1, warmup_epochs=1, scale_by_batch_size=0.01, examples_per_epoch=1, boundaries=[0], multipliers=[0, 1]) batch_size = 1 train_epochs = 1 train_steps = 1 lr = optimizer_factory.build_learning_rate( params=params, batch_size=batch_size, train_epochs=train_epochs, train_steps=train_steps) self.assertTrue( issubclass( type(lr), tf.keras.optimizers.schedules.LearningRateSchedule)) if __name__ == '__main__': tf.test.main()
4,088
32.793388
79
py
models
models-master/official/legacy/image_classification/learning_rate_test.py
# Copyright 2023 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. """Tests for learning_rate.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from official.legacy.image_classification import learning_rate class LearningRateTests(tf.test.TestCase): def test_warmup_decay(self): """Basic computational test for warmup decay.""" initial_lr = 0.01 decay_steps = 100 decay_rate = 0.01 warmup_steps = 10 base_lr = tf.keras.optimizers.schedules.ExponentialDecay( initial_learning_rate=initial_lr, decay_steps=decay_steps, decay_rate=decay_rate) lr = learning_rate.WarmupDecaySchedule( lr_schedule=base_lr, warmup_steps=warmup_steps) for step in range(warmup_steps - 1): config = lr.get_config() self.assertEqual(config['warmup_steps'], warmup_steps) self.assertAllClose( self.evaluate(lr(step)), step / warmup_steps * initial_lr) def test_cosine_decay_with_warmup(self): """Basic computational test for cosine decay with warmup.""" expected_lrs = [0.0, 0.1, 0.05, 0.0] lr = learning_rate.CosineDecayWithWarmup( batch_size=256, total_steps=3, warmup_steps=1) for step in [0, 1, 2, 3]: self.assertAllClose(lr(step), expected_lrs[step]) if __name__ == '__main__': tf.test.main()
1,941
30.836066
74
py
models
models-master/official/legacy/image_classification/classifier_trainer.py
# Copyright 2023 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. """Runs an Image Classification model.""" import os import pprint from typing import Any, Mapping, Optional, Text, Tuple from absl import app from absl import flags from absl import logging import tensorflow as tf from official.common import distribute_utils from official.legacy.image_classification import callbacks as custom_callbacks from official.legacy.image_classification import dataset_factory from official.legacy.image_classification import optimizer_factory from official.legacy.image_classification.configs import base_configs from official.legacy.image_classification.configs import configs from official.legacy.image_classification.efficientnet import efficientnet_model from official.legacy.image_classification.resnet import common from official.legacy.image_classification.resnet import resnet_model from official.legacy.image_classification.vgg import vgg_model from official.modeling import hyperparams from official.modeling import performance from official.utils import hyperparams_flags from official.utils.misc import keras_utils def get_models() -> Mapping[str, tf.keras.Model]: """Returns the mapping from model type name to Keras model.""" return { 'efficientnet': efficientnet_model.EfficientNet.from_name, 'resnet': resnet_model.resnet50, 'vgg': vgg_model.vgg16, } def get_dtype_map() -> Mapping[str, tf.dtypes.DType]: """Returns the mapping from dtype string representations to TF dtypes.""" return { 'float32': tf.float32, 'bfloat16': tf.bfloat16, 'float16': tf.float16, 'fp32': tf.float32, 'bf16': tf.bfloat16, } def _get_metrics(one_hot: bool) -> Mapping[Text, Any]: """Get a dict of available metrics to track.""" if one_hot: return { # (name, metric_fn) 'acc': tf.keras.metrics.CategoricalAccuracy(name='accuracy'), 'accuracy': tf.keras.metrics.CategoricalAccuracy(name='accuracy'), 'top_1': tf.keras.metrics.CategoricalAccuracy(name='accuracy'), 'top_5': tf.keras.metrics.TopKCategoricalAccuracy( k=5, name='top_5_accuracy'), } else: return { # (name, metric_fn) 'acc': tf.keras.metrics.SparseCategoricalAccuracy(name='accuracy'), 'accuracy': tf.keras.metrics.SparseCategoricalAccuracy(name='accuracy'), 'top_1': tf.keras.metrics.SparseCategoricalAccuracy(name='accuracy'), 'top_5': tf.keras.metrics.SparseTopKCategoricalAccuracy( k=5, name='top_5_accuracy'), } def get_image_size_from_model( params: base_configs.ExperimentConfig) -> Optional[int]: """If the given model has a preferred image size, return it.""" if params.model_name == 'efficientnet': efficientnet_name = params.model.model_params.model_name if efficientnet_name in efficientnet_model.MODEL_CONFIGS: return efficientnet_model.MODEL_CONFIGS[efficientnet_name].resolution return None def _get_dataset_builders(params: base_configs.ExperimentConfig, strategy: tf.distribute.Strategy, one_hot: bool) -> Tuple[Any, Any]: """Create and return train and validation dataset builders.""" if one_hot: logging.warning('label_smoothing > 0, so datasets will be one hot encoded.') else: logging.warning('label_smoothing not applied, so datasets will not be one ' 'hot encoded.') num_devices = strategy.num_replicas_in_sync if strategy else 1 image_size = get_image_size_from_model(params) dataset_configs = [params.train_dataset, params.validation_dataset] builders = [] for config in dataset_configs: if config is not None and config.has_data: builder = dataset_factory.DatasetBuilder( config, image_size=image_size or config.image_size, num_devices=num_devices, one_hot=one_hot) else: builder = None builders.append(builder) return builders def get_loss_scale(params: base_configs.ExperimentConfig, fp16_default: float = 128.) -> float: """Returns the loss scale for initializations.""" loss_scale = params.runtime.loss_scale if loss_scale == 'dynamic': return loss_scale elif loss_scale is not None: return float(loss_scale) elif (params.train_dataset.dtype == 'float32' or params.train_dataset.dtype == 'bfloat16'): return 1. else: assert params.train_dataset.dtype == 'float16' return fp16_default def _get_params_from_flags(flags_obj: flags.FlagValues): """Get ParamsDict from flags.""" model = flags_obj.model_type.lower() dataset = flags_obj.dataset.lower() params = configs.get_config(model=model, dataset=dataset) flags_overrides = { 'model_dir': flags_obj.model_dir, 'mode': flags_obj.mode, 'model': { 'name': model, }, 'runtime': { 'run_eagerly': flags_obj.run_eagerly, 'tpu': flags_obj.tpu, }, 'train_dataset': { 'data_dir': flags_obj.data_dir, }, 'validation_dataset': { 'data_dir': flags_obj.data_dir, }, 'train': { 'time_history': { 'log_steps': flags_obj.log_steps, }, }, } overriding_configs = (flags_obj.config_file, flags_obj.params_override, flags_overrides) pp = pprint.PrettyPrinter() logging.info('Base params: %s', pp.pformat(params.as_dict())) for param in overriding_configs: logging.info('Overriding params: %s', param) params = hyperparams.override_params_dict(params, param, is_strict=True) params.validate() params.lock() logging.info('Final model parameters: %s', pp.pformat(params.as_dict())) return params def resume_from_checkpoint(model: tf.keras.Model, model_dir: str, train_steps: int) -> int: """Resumes from the latest checkpoint, if possible. Loads the model weights and optimizer settings from a checkpoint. This function should be used in case of preemption recovery. Args: model: The model whose weights should be restored. model_dir: The directory where model weights were saved. train_steps: The number of steps to train. Returns: The epoch of the latest checkpoint, or 0 if not restoring. """ logging.info('Load from checkpoint is enabled.') latest_checkpoint = tf.train.latest_checkpoint(model_dir) logging.info('latest_checkpoint: %s', latest_checkpoint) if not latest_checkpoint: logging.info('No checkpoint detected.') return 0 logging.info('Checkpoint file %s found and restoring from ' 'checkpoint', latest_checkpoint) model.load_weights(latest_checkpoint) initial_epoch = model.optimizer.iterations // train_steps logging.info('Completed loading from checkpoint.') logging.info('Resuming from epoch %d', initial_epoch) return int(initial_epoch) def initialize(params: base_configs.ExperimentConfig, dataset_builder: dataset_factory.DatasetBuilder): """Initializes backend related initializations.""" keras_utils.set_session_config(enable_xla=params.runtime.enable_xla) performance.set_mixed_precision_policy(dataset_builder.dtype) if tf.config.list_physical_devices('GPU'): data_format = 'channels_first' else: data_format = 'channels_last' tf.keras.backend.set_image_data_format(data_format) if params.runtime.run_eagerly: # Enable eager execution to allow step-by-step debugging tf.config.experimental_run_functions_eagerly(True) if tf.config.list_physical_devices('GPU'): if params.runtime.gpu_thread_mode: keras_utils.set_gpu_thread_mode_and_count( per_gpu_thread_count=params.runtime.per_gpu_thread_count, gpu_thread_mode=params.runtime.gpu_thread_mode, num_gpus=params.runtime.num_gpus, datasets_num_private_threads=params.runtime .dataset_num_private_threads) # pylint:disable=line-too-long if params.runtime.batchnorm_spatial_persistent: os.environ['TF_USE_CUDNN_BATCHNORM_SPATIAL_PERSISTENT'] = '1' def define_classifier_flags(): """Defines common flags for image classification.""" hyperparams_flags.initialize_common_flags() flags.DEFINE_string( 'data_dir', default=None, help='The location of the input data.') flags.DEFINE_string( 'mode', default=None, help='Mode to run: `train`, `eval`, `train_and_eval` or `export`.') flags.DEFINE_bool( 'run_eagerly', default=None, help='Use eager execution and disable autograph for debugging.') flags.DEFINE_string( 'model_type', default=None, help='The type of the model, e.g. EfficientNet, etc.') flags.DEFINE_string( 'dataset', default=None, help='The name of the dataset, e.g. ImageNet, etc.') flags.DEFINE_integer( 'log_steps', default=100, help='The interval of steps between logging of batch level stats.') def serialize_config(params: base_configs.ExperimentConfig, model_dir: str): """Serializes and saves the experiment config.""" params_save_path = os.path.join(model_dir, 'params.yaml') logging.info('Saving experiment configuration to %s', params_save_path) tf.io.gfile.makedirs(model_dir) hyperparams.save_params_dict_to_yaml(params, params_save_path) def train_and_eval( params: base_configs.ExperimentConfig, strategy_override: tf.distribute.Strategy) -> Mapping[str, Any]: """Runs the train and eval path using compile/fit.""" logging.info('Running train and eval.') distribute_utils.configure_cluster(params.runtime.worker_hosts, params.runtime.task_index) # Note: for TPUs, strategy and scope should be created before the dataset strategy = strategy_override or distribute_utils.get_distribution_strategy( distribution_strategy=params.runtime.distribution_strategy, all_reduce_alg=params.runtime.all_reduce_alg, num_gpus=params.runtime.num_gpus, tpu_address=params.runtime.tpu) strategy_scope = distribute_utils.get_strategy_scope(strategy) logging.info('Detected %d devices.', strategy.num_replicas_in_sync if strategy else 1) label_smoothing = params.model.loss.label_smoothing one_hot = label_smoothing and label_smoothing > 0 builders = _get_dataset_builders(params, strategy, one_hot) datasets = [ builder.build(strategy) if builder else None for builder in builders ] # Unpack datasets and builders based on train/val/test splits train_builder, validation_builder = builders # pylint: disable=unbalanced-tuple-unpacking train_dataset, validation_dataset = datasets train_epochs = params.train.epochs train_steps = params.train.steps or train_builder.num_steps validation_steps = params.evaluation.steps or validation_builder.num_steps initialize(params, train_builder) logging.info('Global batch size: %d', train_builder.global_batch_size) with strategy_scope: model_params = params.model.model_params.as_dict() model = get_models()[params.model.name](**model_params) learning_rate = optimizer_factory.build_learning_rate( params=params.model.learning_rate, batch_size=train_builder.global_batch_size, train_epochs=train_epochs, train_steps=train_steps) optimizer = optimizer_factory.build_optimizer( optimizer_name=params.model.optimizer.name, base_learning_rate=learning_rate, params=params.model.optimizer.as_dict(), model=model) optimizer = performance.configure_optimizer( optimizer, use_float16=train_builder.dtype == 'float16', loss_scale=get_loss_scale(params)) metrics_map = _get_metrics(one_hot) metrics = [metrics_map[metric] for metric in params.train.metrics] steps_per_loop = train_steps if params.train.set_epoch_loop else 1 if one_hot: loss_obj = tf.keras.losses.CategoricalCrossentropy( label_smoothing=params.model.loss.label_smoothing) else: loss_obj = tf.keras.losses.SparseCategoricalCrossentropy() model.compile( optimizer=optimizer, loss=loss_obj, metrics=metrics, steps_per_execution=steps_per_loop) initial_epoch = 0 if params.train.resume_checkpoint: initial_epoch = resume_from_checkpoint( model=model, model_dir=params.model_dir, train_steps=train_steps) callbacks = custom_callbacks.get_callbacks( model_checkpoint=params.train.callbacks.enable_checkpoint_and_export, include_tensorboard=params.train.callbacks.enable_tensorboard, time_history=params.train.callbacks.enable_time_history, track_lr=params.train.tensorboard.track_lr, write_model_weights=params.train.tensorboard.write_model_weights, initial_step=initial_epoch * train_steps, batch_size=train_builder.global_batch_size, log_steps=params.train.time_history.log_steps, model_dir=params.model_dir, backup_and_restore=params.train.callbacks.enable_backup_and_restore) serialize_config(params=params, model_dir=params.model_dir) if params.evaluation.skip_eval: validation_kwargs = {} else: validation_kwargs = { 'validation_data': validation_dataset, 'validation_steps': validation_steps, 'validation_freq': params.evaluation.epochs_between_evals, } history = model.fit( train_dataset, epochs=train_epochs, steps_per_epoch=train_steps, initial_epoch=initial_epoch, callbacks=callbacks, verbose=2, **validation_kwargs) validation_output = None if not params.evaluation.skip_eval: validation_output = model.evaluate( validation_dataset, steps=validation_steps, verbose=2) # TODO(dankondratyuk): eval and save final test accuracy stats = common.build_stats(history, validation_output, callbacks) return stats def export(params: base_configs.ExperimentConfig): """Runs the model export functionality.""" logging.info('Exporting model.') model_params = params.model.model_params.as_dict() model = get_models()[params.model.name](**model_params) checkpoint = params.export.checkpoint if checkpoint is None: logging.info('No export checkpoint was provided. Using the latest ' 'checkpoint from model_dir.') checkpoint = tf.train.latest_checkpoint(params.model_dir) model.load_weights(checkpoint) model.save(params.export.destination) def run(flags_obj: flags.FlagValues, strategy_override: tf.distribute.Strategy = None) -> Mapping[str, Any]: """Runs Image Classification model using native Keras APIs. Args: flags_obj: An object containing parsed flag values. strategy_override: A `tf.distribute.Strategy` object to use for model. Returns: Dictionary of training/eval stats """ params = _get_params_from_flags(flags_obj) if params.mode == 'train_and_eval': return train_and_eval(params, strategy_override) elif params.mode == 'export_only': export(params) else: raise ValueError('{} is not a valid mode.'.format(params.mode)) def main(_): stats = run(flags.FLAGS) if stats: logging.info('Run stats:\n%s', stats) if __name__ == '__main__': logging.set_verbosity(logging.INFO) define_classifier_flags() flags.mark_flag_as_required('data_dir') flags.mark_flag_as_required('mode') flags.mark_flag_as_required('model_type') flags.mark_flag_as_required('dataset') app.run(main)
16,195
34.362445
92
py
models
models-master/official/legacy/image_classification/mnist_main.py
# Copyright 2023 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. """Runs a simple model on the MNIST dataset.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os # Import libraries from absl import app from absl import flags from absl import logging import tensorflow as tf import tensorflow_datasets as tfds from official.common import distribute_utils from official.legacy.image_classification.resnet import common from official.utils.flags import core as flags_core from official.utils.misc import model_helpers FLAGS = flags.FLAGS def build_model(): """Constructs the ML model used to predict handwritten digits.""" image = tf.keras.layers.Input(shape=(28, 28, 1)) y = tf.keras.layers.Conv2D(filters=32, kernel_size=5, padding='same', activation='relu')(image) y = tf.keras.layers.MaxPooling2D(pool_size=(2, 2), strides=(2, 2), padding='same')(y) y = tf.keras.layers.Conv2D(filters=32, kernel_size=5, padding='same', activation='relu')(y) y = tf.keras.layers.MaxPooling2D(pool_size=(2, 2), strides=(2, 2), padding='same')(y) y = tf.keras.layers.Flatten()(y) y = tf.keras.layers.Dense(1024, activation='relu')(y) y = tf.keras.layers.Dropout(0.4)(y) probs = tf.keras.layers.Dense(10, activation='softmax')(y) model = tf.keras.models.Model(image, probs, name='mnist') return model @tfds.decode.make_decoder(output_dtype=tf.float32) def decode_image(example, feature): """Convert image to float32 and normalize from [0, 255] to [0.0, 1.0].""" return tf.cast(feature.decode_example(example), dtype=tf.float32) / 255 def run(flags_obj, datasets_override=None, strategy_override=None): """Run MNIST model training and eval loop using native Keras APIs. Args: flags_obj: An object containing parsed flag values. datasets_override: A pair of `tf.data.Dataset` objects to train the model, representing the train and test sets. strategy_override: A `tf.distribute.Strategy` object to use for model. Returns: Dictionary of training and eval stats. """ # Start TF profiler server. tf.profiler.experimental.server.start(flags_obj.profiler_port) strategy = strategy_override or distribute_utils.get_distribution_strategy( distribution_strategy=flags_obj.distribution_strategy, num_gpus=flags_obj.num_gpus, tpu_address=flags_obj.tpu) strategy_scope = distribute_utils.get_strategy_scope(strategy) mnist = tfds.builder('mnist', data_dir=flags_obj.data_dir) if flags_obj.download: mnist.download_and_prepare() mnist_train, mnist_test = datasets_override or mnist.as_dataset( split=['train', 'test'], decoders={'image': decode_image()}, # pylint: disable=no-value-for-parameter as_supervised=True) train_input_dataset = mnist_train.cache().repeat().shuffle( buffer_size=50000).batch(flags_obj.batch_size) eval_input_dataset = mnist_test.cache().repeat().batch(flags_obj.batch_size) with strategy_scope: lr_schedule = tf.keras.optimizers.schedules.ExponentialDecay( 0.05, decay_steps=100000, decay_rate=0.96) optimizer = tf.keras.optimizers.SGD(learning_rate=lr_schedule) model = build_model() model.compile( optimizer=optimizer, loss='sparse_categorical_crossentropy', metrics=['sparse_categorical_accuracy']) num_train_examples = mnist.info.splits['train'].num_examples train_steps = num_train_examples // flags_obj.batch_size train_epochs = flags_obj.train_epochs ckpt_full_path = os.path.join(flags_obj.model_dir, 'model.ckpt-{epoch:04d}') callbacks = [ tf.keras.callbacks.ModelCheckpoint( ckpt_full_path, save_weights_only=True), tf.keras.callbacks.TensorBoard(log_dir=flags_obj.model_dir), ] num_eval_examples = mnist.info.splits['test'].num_examples num_eval_steps = num_eval_examples // flags_obj.batch_size history = model.fit( train_input_dataset, epochs=train_epochs, steps_per_epoch=train_steps, callbacks=callbacks, validation_steps=num_eval_steps, validation_data=eval_input_dataset, validation_freq=flags_obj.epochs_between_evals) export_path = os.path.join(flags_obj.model_dir, 'saved_model') model.save(export_path, include_optimizer=False) eval_output = model.evaluate( eval_input_dataset, steps=num_eval_steps, verbose=2) stats = common.build_stats(history, eval_output, callbacks) return stats def define_mnist_flags(): """Define command line flags for MNIST model.""" flags_core.define_base( clean=True, num_gpu=True, train_epochs=True, epochs_between_evals=True, distribution_strategy=True) flags_core.define_device() flags_core.define_distribution() flags.DEFINE_bool('download', True, 'Whether to download data to `--data_dir`.') flags.DEFINE_integer('profiler_port', 9012, 'Port to start profiler server on.') FLAGS.set_default('batch_size', 1024) def main(_): model_helpers.apply_clean(FLAGS) stats = run(flags.FLAGS) logging.info('Run stats:\n%s', stats) if __name__ == '__main__': logging.set_verbosity(logging.INFO) define_mnist_flags() app.run(main)
6,114
33.548023
83
py
models
models-master/official/legacy/image_classification/learning_rate.py
# Copyright 2023 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. """Learning rate utilities for vision tasks.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from typing import Any, Mapping, Optional import numpy as np import tensorflow as tf BASE_LEARNING_RATE = 0.1 class WarmupDecaySchedule(tf.keras.optimizers.schedules.LearningRateSchedule): """A wrapper for LearningRateSchedule that includes warmup steps.""" def __init__(self, lr_schedule: tf.keras.optimizers.schedules.LearningRateSchedule, warmup_steps: int, warmup_lr: Optional[float] = None): """Add warmup decay to a learning rate schedule. Args: lr_schedule: base learning rate scheduler warmup_steps: number of warmup steps warmup_lr: an optional field for the final warmup learning rate. This should be provided if the base `lr_schedule` does not contain this field. """ super(WarmupDecaySchedule, self).__init__() self._lr_schedule = lr_schedule self._warmup_steps = warmup_steps self._warmup_lr = warmup_lr def __call__(self, step: int): lr = self._lr_schedule(step) if self._warmup_steps: if self._warmup_lr is not None: initial_learning_rate = tf.convert_to_tensor( self._warmup_lr, name="initial_learning_rate") else: initial_learning_rate = tf.convert_to_tensor( self._lr_schedule.initial_learning_rate, name="initial_learning_rate") dtype = initial_learning_rate.dtype global_step_recomp = tf.cast(step, dtype) warmup_steps = tf.cast(self._warmup_steps, dtype) warmup_lr = initial_learning_rate * global_step_recomp / warmup_steps lr = tf.cond(global_step_recomp < warmup_steps, lambda: warmup_lr, lambda: lr) return lr def get_config(self) -> Mapping[str, Any]: config = self._lr_schedule.get_config() config.update({ "warmup_steps": self._warmup_steps, "warmup_lr": self._warmup_lr, }) return config class CosineDecayWithWarmup(tf.keras.optimizers.schedules.LearningRateSchedule): """Class to generate learning rate tensor.""" def __init__(self, batch_size: int, total_steps: int, warmup_steps: int): """Creates the cosine learning rate tensor with linear warmup. Args: batch_size: The training batch size used in the experiment. total_steps: Total training steps. warmup_steps: Steps for the warm up period. """ super(CosineDecayWithWarmup, self).__init__() base_lr_batch_size = 256 self._total_steps = total_steps self._init_learning_rate = BASE_LEARNING_RATE * batch_size / base_lr_batch_size self._warmup_steps = warmup_steps def __call__(self, global_step: int): global_step = tf.cast(global_step, dtype=tf.float32) warmup_steps = self._warmup_steps init_lr = self._init_learning_rate total_steps = self._total_steps linear_warmup = global_step / warmup_steps * init_lr cosine_learning_rate = init_lr * (tf.cos(np.pi * (global_step - warmup_steps) / (total_steps - warmup_steps)) + 1.0) / 2.0 learning_rate = tf.where(global_step < warmup_steps, linear_warmup, cosine_learning_rate) return learning_rate def get_config(self): return { "total_steps": self._total_steps, "warmup_learning_rate": self._warmup_learning_rate, "warmup_steps": self._warmup_steps, "init_learning_rate": self._init_learning_rate, }
4,272
35.521368
83
py
models
models-master/official/legacy/image_classification/test_utils.py
# Copyright 2023 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. """Test utilities for image classification tasks.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf def trivial_model(num_classes): """Trivial model for ImageNet dataset.""" input_shape = (224, 224, 3) img_input = tf.keras.layers.Input(shape=input_shape) x = tf.keras.layers.Lambda( lambda x: tf.keras.backend.reshape(x, [-1, 224 * 224 * 3]), name='reshape')(img_input) x = tf.keras.layers.Dense(1, name='fc1')(x) x = tf.keras.layers.Dense(num_classes, name='fc1000')(x) x = tf.keras.layers.Activation('softmax', dtype='float32')(x) return tf.keras.models.Model(img_input, x, name='trivial')
1,322
33.815789
74
py
models
models-master/official/legacy/image_classification/vgg/vgg_model.py
# Copyright 2023 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. """VGG16 model for Keras. Adapted from tf.keras.applications.vgg16.VGG16(). Related papers/blogs: - https://arxiv.org/abs/1409.1556 """ import tensorflow as tf layers = tf.keras.layers def _gen_l2_regularizer(use_l2_regularizer=True, l2_weight_decay=1e-4): return tf.keras.regularizers.L2( l2_weight_decay) if use_l2_regularizer else None def vgg16(num_classes, batch_size=None, use_l2_regularizer=True, batch_norm_decay=0.9, batch_norm_epsilon=1e-5): """Instantiates the VGG16 architecture. Args: num_classes: `int` number of classes for image classification. batch_size: Size of the batches for each step. use_l2_regularizer: whether to use L2 regularizer on Conv/Dense layer. batch_norm_decay: Moment of batch norm layers. batch_norm_epsilon: Epsilon of batch borm layers. Returns: A Keras model instance. """ input_shape = (224, 224, 3) img_input = layers.Input(shape=input_shape, batch_size=batch_size) x = img_input if tf.keras.backend.image_data_format() == 'channels_first': x = layers.Permute((3, 1, 2))(x) bn_axis = 1 else: # channels_last bn_axis = 3 # Block 1 x = layers.Conv2D( 64, (3, 3), padding='same', kernel_regularizer=_gen_l2_regularizer(use_l2_regularizer), name='block1_conv1')( x) x = layers.BatchNormalization( axis=bn_axis, momentum=batch_norm_decay, epsilon=batch_norm_epsilon, name='bn_conv1')( x) x = layers.Activation('relu')(x) x = layers.Conv2D( 64, (3, 3), padding='same', kernel_regularizer=_gen_l2_regularizer(use_l2_regularizer), name='block1_conv2')( x) x = layers.BatchNormalization( axis=bn_axis, momentum=batch_norm_decay, epsilon=batch_norm_epsilon, name='bn_conv2')( x) x = layers.Activation('relu')(x) x = layers.MaxPooling2D((2, 2), strides=(2, 2), name='block1_pool')(x) # Block 2 x = layers.Conv2D( 128, (3, 3), padding='same', kernel_regularizer=_gen_l2_regularizer(use_l2_regularizer), name='block2_conv1')( x) x = layers.BatchNormalization( axis=bn_axis, momentum=batch_norm_decay, epsilon=batch_norm_epsilon, name='bn_conv3')( x) x = layers.Activation('relu')(x) x = layers.Conv2D( 128, (3, 3), padding='same', kernel_regularizer=_gen_l2_regularizer(use_l2_regularizer), name='block2_conv2')( x) x = layers.BatchNormalization( axis=bn_axis, momentum=batch_norm_decay, epsilon=batch_norm_epsilon, name='bn_conv4')( x) x = layers.Activation('relu')(x) x = layers.MaxPooling2D((2, 2), strides=(2, 2), name='block2_pool')(x) # Block 3 x = layers.Conv2D( 256, (3, 3), padding='same', kernel_regularizer=_gen_l2_regularizer(use_l2_regularizer), name='block3_conv1')( x) x = layers.BatchNormalization( axis=bn_axis, momentum=batch_norm_decay, epsilon=batch_norm_epsilon, name='bn_conv5')( x) x = layers.Activation('relu')(x) x = layers.Conv2D( 256, (3, 3), padding='same', kernel_regularizer=_gen_l2_regularizer(use_l2_regularizer), name='block3_conv2')( x) x = layers.BatchNormalization( axis=bn_axis, momentum=batch_norm_decay, epsilon=batch_norm_epsilon, name='bn_conv6')( x) x = layers.Activation('relu')(x) x = layers.Conv2D( 256, (3, 3), padding='same', kernel_regularizer=_gen_l2_regularizer(use_l2_regularizer), name='block3_conv3')( x) x = layers.BatchNormalization( axis=bn_axis, momentum=batch_norm_decay, epsilon=batch_norm_epsilon, name='bn_conv7')( x) x = layers.Activation('relu')(x) x = layers.MaxPooling2D((2, 2), strides=(2, 2), name='block3_pool')(x) # Block 4 x = layers.Conv2D( 512, (3, 3), padding='same', kernel_regularizer=_gen_l2_regularizer(use_l2_regularizer), name='block4_conv1')( x) x = layers.BatchNormalization( axis=bn_axis, momentum=batch_norm_decay, epsilon=batch_norm_epsilon, name='bn_conv8')( x) x = layers.Activation('relu')(x) x = layers.Conv2D( 512, (3, 3), padding='same', kernel_regularizer=_gen_l2_regularizer(use_l2_regularizer), name='block4_conv2')( x) x = layers.BatchNormalization( axis=bn_axis, momentum=batch_norm_decay, epsilon=batch_norm_epsilon, name='bn_conv9')( x) x = layers.Activation('relu')(x) x = layers.Conv2D( 512, (3, 3), padding='same', kernel_regularizer=_gen_l2_regularizer(use_l2_regularizer), name='block4_conv3')( x) x = layers.BatchNormalization( axis=bn_axis, momentum=batch_norm_decay, epsilon=batch_norm_epsilon, name='bn_conv10')( x) x = layers.Activation('relu')(x) x = layers.MaxPooling2D((2, 2), strides=(2, 2), name='block4_pool')(x) # Block 5 x = layers.Conv2D( 512, (3, 3), padding='same', kernel_regularizer=_gen_l2_regularizer(use_l2_regularizer), name='block5_conv1')( x) x = layers.BatchNormalization( axis=bn_axis, momentum=batch_norm_decay, epsilon=batch_norm_epsilon, name='bn_conv11')( x) x = layers.Activation('relu')(x) x = layers.Conv2D( 512, (3, 3), padding='same', kernel_regularizer=_gen_l2_regularizer(use_l2_regularizer), name='block5_conv2')( x) x = layers.BatchNormalization( axis=bn_axis, momentum=batch_norm_decay, epsilon=batch_norm_epsilon, name='bn_conv12')( x) x = layers.Activation('relu')(x) x = layers.Conv2D( 512, (3, 3), padding='same', kernel_regularizer=_gen_l2_regularizer(use_l2_regularizer), name='block5_conv3')( x) x = layers.BatchNormalization( axis=bn_axis, momentum=batch_norm_decay, epsilon=batch_norm_epsilon, name='bn_conv13')( x) x = layers.Activation('relu')(x) x = layers.MaxPooling2D((2, 2), strides=(2, 2), name='block5_pool')(x) x = layers.Flatten(name='flatten')(x) x = layers.Dense( 4096, kernel_regularizer=_gen_l2_regularizer(use_l2_regularizer), name='fc1')( x) x = layers.Activation('relu')(x) x = layers.Dropout(0.5)(x) x = layers.Dense( 4096, kernel_regularizer=_gen_l2_regularizer(use_l2_regularizer), name='fc2')( x) x = layers.Activation('relu')(x) x = layers.Dropout(0.5)(x) x = layers.Dense( num_classes, kernel_regularizer=_gen_l2_regularizer(use_l2_regularizer), name='fc1000')( x) x = layers.Activation('softmax', dtype='float32')(x) # Create model. return tf.keras.Model(img_input, x, name='vgg16')
7,607
27.177778
74
py
models
models-master/official/legacy/image_classification/efficientnet/efficientnet_model.py
# Copyright 2023 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 definitions for EfficientNet model. [1] Mingxing Tan, Quoc V. Le EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks. ICML'19, https://arxiv.org/abs/1905.11946 """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import dataclasses import math from typing import Any, Dict, Optional, Text, Tuple from absl import logging import tensorflow as tf from official.legacy.image_classification import preprocessing from official.legacy.image_classification.efficientnet import common_modules from official.modeling import tf_utils from official.modeling.hyperparams import base_config @dataclasses.dataclass class BlockConfig(base_config.Config): """Config for a single MB Conv Block.""" input_filters: int = 0 output_filters: int = 0 kernel_size: int = 3 num_repeat: int = 1 expand_ratio: int = 1 strides: Tuple[int, int] = (1, 1) se_ratio: Optional[float] = None id_skip: bool = True fused_conv: bool = False conv_type: str = 'depthwise' @dataclasses.dataclass class ModelConfig(base_config.Config): """Default Config for Efficientnet-B0.""" width_coefficient: float = 1.0 depth_coefficient: float = 1.0 resolution: int = 224 dropout_rate: float = 0.2 blocks: Tuple[BlockConfig, ...] = ( # (input_filters, output_filters, kernel_size, num_repeat, # expand_ratio, strides, se_ratio) # pylint: disable=bad-whitespace BlockConfig.from_args(32, 16, 3, 1, 1, (1, 1), 0.25), BlockConfig.from_args(16, 24, 3, 2, 6, (2, 2), 0.25), BlockConfig.from_args(24, 40, 5, 2, 6, (2, 2), 0.25), BlockConfig.from_args(40, 80, 3, 3, 6, (2, 2), 0.25), BlockConfig.from_args(80, 112, 5, 3, 6, (1, 1), 0.25), BlockConfig.from_args(112, 192, 5, 4, 6, (2, 2), 0.25), BlockConfig.from_args(192, 320, 3, 1, 6, (1, 1), 0.25), # pylint: enable=bad-whitespace ) stem_base_filters: int = 32 top_base_filters: int = 1280 activation: str = 'simple_swish' batch_norm: str = 'default' bn_momentum: float = 0.99 bn_epsilon: float = 1e-3 # While the original implementation used a weight decay of 1e-5, # tf.nn.l2_loss divides it by 2, so we halve this to compensate in Keras weight_decay: float = 5e-6 drop_connect_rate: float = 0.2 depth_divisor: int = 8 min_depth: Optional[int] = None use_se: bool = True input_channels: int = 3 num_classes: int = 1000 model_name: str = 'efficientnet' rescale_input: bool = True data_format: str = 'channels_last' dtype: str = 'float32' MODEL_CONFIGS = { # (width, depth, resolution, dropout) 'efficientnet-b0': ModelConfig.from_args(1.0, 1.0, 224, 0.2), 'efficientnet-b1': ModelConfig.from_args(1.0, 1.1, 240, 0.2), 'efficientnet-b2': ModelConfig.from_args(1.1, 1.2, 260, 0.3), 'efficientnet-b3': ModelConfig.from_args(1.2, 1.4, 300, 0.3), 'efficientnet-b4': ModelConfig.from_args(1.4, 1.8, 380, 0.4), 'efficientnet-b5': ModelConfig.from_args(1.6, 2.2, 456, 0.4), 'efficientnet-b6': ModelConfig.from_args(1.8, 2.6, 528, 0.5), 'efficientnet-b7': ModelConfig.from_args(2.0, 3.1, 600, 0.5), 'efficientnet-b8': ModelConfig.from_args(2.2, 3.6, 672, 0.5), 'efficientnet-l2': ModelConfig.from_args(4.3, 5.3, 800, 0.5), } CONV_KERNEL_INITIALIZER = { 'class_name': 'VarianceScaling', 'config': { 'scale': 2.0, 'mode': 'fan_out', # Note: this is a truncated normal distribution 'distribution': 'normal' } } DENSE_KERNEL_INITIALIZER = { 'class_name': 'VarianceScaling', 'config': { 'scale': 1 / 3.0, 'mode': 'fan_out', 'distribution': 'uniform' } } def round_filters(filters: int, config: ModelConfig) -> int: """Round number of filters based on width coefficient.""" width_coefficient = config.width_coefficient min_depth = config.min_depth divisor = config.depth_divisor orig_filters = filters if not width_coefficient: return filters filters *= width_coefficient min_depth = min_depth or divisor new_filters = max(min_depth, int(filters + divisor / 2) // divisor * divisor) # Make sure that round down does not go down by more than 10%. if new_filters < 0.9 * filters: new_filters += divisor logging.info('round_filter input=%s output=%s', orig_filters, new_filters) return int(new_filters) def round_repeats(repeats: int, depth_coefficient: float) -> int: """Round number of repeats based on depth coefficient.""" return int(math.ceil(depth_coefficient * repeats)) def conv2d_block(inputs: tf.Tensor, conv_filters: Optional[int], config: ModelConfig, kernel_size: Any = (1, 1), strides: Any = (1, 1), use_batch_norm: bool = True, use_bias: bool = False, activation: Optional[Any] = None, depthwise: bool = False, name: Optional[Text] = None): """A conv2d followed by batch norm and an activation.""" batch_norm = common_modules.get_batch_norm(config.batch_norm) bn_momentum = config.bn_momentum bn_epsilon = config.bn_epsilon data_format = tf.keras.backend.image_data_format() weight_decay = config.weight_decay name = name or '' # Collect args based on what kind of conv2d block is desired init_kwargs = { 'kernel_size': kernel_size, 'strides': strides, 'use_bias': use_bias, 'padding': 'same', 'name': name + '_conv2d', 'kernel_regularizer': tf.keras.regularizers.l2(weight_decay), 'bias_regularizer': tf.keras.regularizers.l2(weight_decay), } if depthwise: conv2d = tf.keras.layers.DepthwiseConv2D init_kwargs.update({'depthwise_initializer': CONV_KERNEL_INITIALIZER}) else: conv2d = tf.keras.layers.Conv2D init_kwargs.update({ 'filters': conv_filters, 'kernel_initializer': CONV_KERNEL_INITIALIZER }) x = conv2d(**init_kwargs)(inputs) if use_batch_norm: bn_axis = 1 if data_format == 'channels_first' else -1 x = batch_norm( axis=bn_axis, momentum=bn_momentum, epsilon=bn_epsilon, name=name + '_bn')( x) if activation is not None: x = tf.keras.layers.Activation(activation, name=name + '_activation')(x) return x def mb_conv_block(inputs: tf.Tensor, block: BlockConfig, config: ModelConfig, prefix: Optional[Text] = None): """Mobile Inverted Residual Bottleneck. Args: inputs: the Keras input to the block block: BlockConfig, arguments to create a Block config: ModelConfig, a set of model parameters prefix: prefix for naming all layers Returns: the output of the block """ use_se = config.use_se activation = tf_utils.get_activation(config.activation) drop_connect_rate = config.drop_connect_rate data_format = tf.keras.backend.image_data_format() use_depthwise = block.conv_type != 'no_depthwise' prefix = prefix or '' filters = block.input_filters * block.expand_ratio x = inputs if block.fused_conv: # If we use fused mbconv, skip expansion and use regular conv. x = conv2d_block( x, filters, config, kernel_size=block.kernel_size, strides=block.strides, activation=activation, name=prefix + 'fused') else: if block.expand_ratio != 1: # Expansion phase kernel_size = (1, 1) if use_depthwise else (3, 3) x = conv2d_block( x, filters, config, kernel_size=kernel_size, activation=activation, name=prefix + 'expand') # Depthwise Convolution if use_depthwise: x = conv2d_block( x, conv_filters=None, config=config, kernel_size=block.kernel_size, strides=block.strides, activation=activation, depthwise=True, name=prefix + 'depthwise') # Squeeze and Excitation phase if use_se: assert block.se_ratio is not None assert 0 < block.se_ratio <= 1 num_reduced_filters = max(1, int(block.input_filters * block.se_ratio)) if data_format == 'channels_first': se_shape = (filters, 1, 1) else: se_shape = (1, 1, filters) se = tf.keras.layers.GlobalAveragePooling2D(name=prefix + 'se_squeeze')(x) se = tf.keras.layers.Reshape(se_shape, name=prefix + 'se_reshape')(se) se = conv2d_block( se, num_reduced_filters, config, use_bias=True, use_batch_norm=False, activation=activation, name=prefix + 'se_reduce') se = conv2d_block( se, filters, config, use_bias=True, use_batch_norm=False, activation='sigmoid', name=prefix + 'se_expand') x = tf.keras.layers.multiply([x, se], name=prefix + 'se_excite') # Output phase x = conv2d_block( x, block.output_filters, config, activation=None, name=prefix + 'project') # Add identity so that quantization-aware training can insert quantization # ops correctly. x = tf.keras.layers.Activation( tf_utils.get_activation('identity'), name=prefix + 'id')( x) if (block.id_skip and all(s == 1 for s in block.strides) and block.input_filters == block.output_filters): if drop_connect_rate and drop_connect_rate > 0: # Apply dropconnect # The only difference between dropout and dropconnect in TF is scaling by # drop_connect_rate during training. See: # https://github.com/keras-team/keras/pull/9898#issuecomment-380577612 x = tf.keras.layers.Dropout( drop_connect_rate, noise_shape=(None, 1, 1, 1), name=prefix + 'drop')( x) x = tf.keras.layers.add([x, inputs], name=prefix + 'add') return x def efficientnet(image_input: tf.keras.layers.Input, config: ModelConfig): # pytype: disable=invalid-annotation # typed-keras """Creates an EfficientNet graph given the model parameters. This function is wrapped by the `EfficientNet` class to make a tf.keras.Model. Args: image_input: the input batch of images config: the model config Returns: the output of efficientnet """ depth_coefficient = config.depth_coefficient blocks = config.blocks stem_base_filters = config.stem_base_filters top_base_filters = config.top_base_filters activation = tf_utils.get_activation(config.activation) dropout_rate = config.dropout_rate drop_connect_rate = config.drop_connect_rate num_classes = config.num_classes input_channels = config.input_channels rescale_input = config.rescale_input data_format = tf.keras.backend.image_data_format() dtype = config.dtype weight_decay = config.weight_decay x = image_input if data_format == 'channels_first': # Happens on GPU/TPU if available. x = tf.keras.layers.Permute((3, 1, 2))(x) if rescale_input: x = preprocessing.normalize_images( x, num_channels=input_channels, dtype=dtype, data_format=data_format) # Build stem x = conv2d_block( x, round_filters(stem_base_filters, config), config, kernel_size=[3, 3], strides=[2, 2], activation=activation, name='stem') # Build blocks num_blocks_total = sum( round_repeats(block.num_repeat, depth_coefficient) for block in blocks) block_num = 0 for stack_idx, block in enumerate(blocks): assert block.num_repeat > 0 # Update block input and output filters based on depth multiplier block = block.replace( input_filters=round_filters(block.input_filters, config), output_filters=round_filters(block.output_filters, config), num_repeat=round_repeats(block.num_repeat, depth_coefficient)) # The first block needs to take care of stride and filter size increase drop_rate = drop_connect_rate * float(block_num) / num_blocks_total config = config.replace(drop_connect_rate=drop_rate) block_prefix = 'stack_{}/block_0/'.format(stack_idx) x = mb_conv_block(x, block, config, block_prefix) block_num += 1 if block.num_repeat > 1: block = block.replace(input_filters=block.output_filters, strides=[1, 1]) for block_idx in range(block.num_repeat - 1): drop_rate = drop_connect_rate * float(block_num) / num_blocks_total config = config.replace(drop_connect_rate=drop_rate) block_prefix = 'stack_{}/block_{}/'.format(stack_idx, block_idx + 1) x = mb_conv_block(x, block, config, prefix=block_prefix) block_num += 1 # Build top x = conv2d_block( x, round_filters(top_base_filters, config), config, activation=activation, name='top') # Build classifier x = tf.keras.layers.GlobalAveragePooling2D(name='top_pool')(x) if dropout_rate and dropout_rate > 0: x = tf.keras.layers.Dropout(dropout_rate, name='top_dropout')(x) x = tf.keras.layers.Dense( num_classes, kernel_initializer=DENSE_KERNEL_INITIALIZER, kernel_regularizer=tf.keras.regularizers.l2(weight_decay), bias_regularizer=tf.keras.regularizers.l2(weight_decay), name='logits')( x) x = tf.keras.layers.Activation('softmax', name='probs')(x) return x class EfficientNet(tf.keras.Model): """Wrapper class for an EfficientNet Keras model. Contains helper methods to build, manage, and save metadata about the model. """ def __init__(self, config: Optional[ModelConfig] = None, overrides: Optional[Dict[Text, Any]] = None): """Create an EfficientNet model. Args: config: (optional) the main model parameters to create the model overrides: (optional) a dict containing keys that can override config """ overrides = overrides or {} config = config or ModelConfig() self.config = config.replace(**overrides) input_channels = self.config.input_channels model_name = self.config.model_name input_shape = (None, None, input_channels) # Should handle any size image image_input = tf.keras.layers.Input(shape=input_shape) output = efficientnet(image_input, self.config) # Cast to float32 in case we have a different model dtype output = tf.cast(output, tf.float32) logging.info('Building model %s with params %s', model_name, self.config) super(EfficientNet, self).__init__( inputs=image_input, outputs=output, name=model_name) @classmethod def from_name(cls, model_name: Text, model_weights_path: Optional[Text] = None, weights_format: Text = 'saved_model', overrides: Optional[Dict[Text, Any]] = None): """Construct an EfficientNet model from a predefined model name. E.g., `EfficientNet.from_name('efficientnet-b0')`. Args: model_name: the predefined model name model_weights_path: the path to the weights (h5 file or saved model dir) weights_format: the model weights format. One of 'saved_model', 'h5', or 'checkpoint'. overrides: (optional) a dict containing keys that can override config Returns: A constructed EfficientNet instance. """ model_configs = dict(MODEL_CONFIGS) overrides = dict(overrides) if overrides else {} # One can define their own custom models if necessary model_configs.update(overrides.pop('model_config', {})) if model_name not in model_configs: raise ValueError('Unknown model name {}'.format(model_name)) config = model_configs[model_name] model = cls(config=config, overrides=overrides) if model_weights_path: common_modules.load_weights( model, model_weights_path, weights_format=weights_format) return model
16,417
32.100806
127
py
models
models-master/official/legacy/image_classification/efficientnet/tfhub_export.py
# Copyright 2023 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. """A script to export TF-Hub SavedModel.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from absl import app from absl import flags import tensorflow as tf from official.legacy.image_classification.efficientnet import efficientnet_model FLAGS = flags.FLAGS flags.DEFINE_string("model_name", None, "EfficientNet model name.") flags.DEFINE_string("model_path", None, "File path to TF model checkpoint.") flags.DEFINE_string("export_path", None, "TF-Hub SavedModel destination path to export.") def export_tfhub(model_path, hub_destination, model_name): """Restores a tf.keras.Model and saves for TF-Hub.""" model_configs = dict(efficientnet_model.MODEL_CONFIGS) config = model_configs[model_name] image_input = tf.keras.layers.Input( shape=(None, None, 3), name="image_input", dtype=tf.float32) x = image_input * 255.0 outputs = efficientnet_model.efficientnet(x, config) hub_model = tf.keras.Model(image_input, outputs) ckpt = tf.train.Checkpoint(model=hub_model) ckpt.restore(model_path).assert_existing_objects_matched() hub_model.save( os.path.join(hub_destination, "classification"), include_optimizer=False) feature_vector_output = hub_model.get_layer(name="top_pool").get_output_at(0) hub_model2 = tf.keras.Model(image_input, feature_vector_output) hub_model2.save( os.path.join(hub_destination, "feature-vector"), include_optimizer=False) def main(argv): if len(argv) > 1: raise app.UsageError("Too many command-line arguments.") export_tfhub(FLAGS.model_path, FLAGS.export_path, FLAGS.model_name) if __name__ == "__main__": app.run(main)
2,319
33.117647
80
py
models
models-master/official/legacy/image_classification/efficientnet/common_modules.py
# Copyright 2023 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. """Common modeling utilities.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from typing import Optional, Text import numpy as np import tensorflow as tf import tensorflow.compat.v1 as tf1 from tensorflow.python.tpu import tpu_function @tf.keras.utils.register_keras_serializable(package='Vision') class TpuBatchNormalization(tf.keras.layers.BatchNormalization): """Cross replica batch normalization.""" def __init__(self, fused: Optional[bool] = False, **kwargs): if fused in (True, None): raise ValueError('TpuBatchNormalization does not support fused=True.') super(TpuBatchNormalization, self).__init__(fused=fused, **kwargs) def _cross_replica_average(self, t: tf.Tensor, num_shards_per_group: int): """Calculates the average value of input tensor across TPU replicas.""" num_shards = tpu_function.get_tpu_context().number_of_shards group_assignment = None if num_shards_per_group > 1: if num_shards % num_shards_per_group != 0: raise ValueError( 'num_shards: %d mod shards_per_group: %d, should be 0' % (num_shards, num_shards_per_group)) num_groups = num_shards // num_shards_per_group group_assignment = [[ x for x in range(num_shards) if x // num_shards_per_group == y ] for y in range(num_groups)] return tf1.tpu.cross_replica_sum(t, group_assignment) / tf.cast( num_shards_per_group, t.dtype) def _moments(self, inputs: tf.Tensor, reduction_axes: int, keep_dims: int): """Compute the mean and variance: it overrides the original _moments.""" shard_mean, shard_variance = super(TpuBatchNormalization, self)._moments( inputs, reduction_axes, keep_dims=keep_dims) num_shards = tpu_function.get_tpu_context().number_of_shards or 1 if num_shards <= 8: # Skip cross_replica for 2x2 or smaller slices. num_shards_per_group = 1 else: num_shards_per_group = max(8, num_shards // 8) if num_shards_per_group > 1: # Compute variance using: Var[X]= E[X^2] - E[X]^2. shard_square_of_mean = tf.math.square(shard_mean) shard_mean_of_square = shard_variance + shard_square_of_mean group_mean = self._cross_replica_average(shard_mean, num_shards_per_group) group_mean_of_square = self._cross_replica_average( shard_mean_of_square, num_shards_per_group) group_variance = group_mean_of_square - tf.math.square(group_mean) return (group_mean, group_variance) else: return (shard_mean, shard_variance) def get_batch_norm(batch_norm_type: Text) -> tf.keras.layers.BatchNormalization: """A helper to create a batch normalization getter. Args: batch_norm_type: The type of batch normalization layer implementation. `tpu` will use `TpuBatchNormalization`. Returns: An instance of `tf.keras.layers.BatchNormalization`. """ if batch_norm_type == 'tpu': return TpuBatchNormalization return tf.keras.layers.BatchNormalization # pytype: disable=bad-return-type # typed-keras def count_params(model, trainable_only=True): """Returns the count of all model parameters, or just trainable ones.""" if not trainable_only: return model.count_params() else: return int( np.sum([ tf.keras.backend.count_params(p) for p in model.trainable_weights ])) def load_weights(model: tf.keras.Model, model_weights_path: Text, weights_format: Text = 'saved_model'): """Load model weights from the given file path. Args: model: the model to load weights into model_weights_path: the path of the model weights weights_format: the model weights format. One of 'saved_model', 'h5', or 'checkpoint'. """ if weights_format == 'saved_model': loaded_model = tf.keras.models.load_model(model_weights_path) model.set_weights(loaded_model.get_weights()) else: model.load_weights(model_weights_path)
4,609
38.401709
93
py
models
models-master/official/legacy/image_classification/resnet/resnet_ctl_imagenet_main.py
# Copyright 2023 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. """Runs a ResNet model on the ImageNet dataset using custom training loops.""" import math import os # Import libraries from absl import app from absl import flags from absl import logging import orbit import tensorflow as tf from official.common import distribute_utils from official.legacy.image_classification.resnet import common from official.legacy.image_classification.resnet import imagenet_preprocessing from official.legacy.image_classification.resnet import resnet_runnable from official.modeling import performance from official.utils.flags import core as flags_core from official.utils.misc import keras_utils from official.utils.misc import model_helpers flags.DEFINE_boolean(name='use_tf_function', default=True, help='Wrap the train and test step inside a ' 'tf.function.') flags.DEFINE_boolean(name='single_l2_loss_op', default=False, help='Calculate L2_loss on concatenated weights, ' 'instead of using Keras per-layer L2 loss.') def build_stats(runnable, time_callback): """Normalizes and returns dictionary of stats. Args: runnable: The module containing all the training and evaluation metrics. time_callback: Time tracking callback instance. Returns: Dictionary of normalized results. """ stats = {} if not runnable.flags_obj.skip_eval: stats['eval_loss'] = runnable.test_loss.result().numpy() stats['eval_acc'] = runnable.test_accuracy.result().numpy() stats['train_loss'] = runnable.train_loss.result().numpy() stats['train_acc'] = runnable.train_accuracy.result().numpy() if time_callback: timestamp_log = time_callback.timestamp_log stats['step_timestamp_log'] = timestamp_log stats['train_finish_time'] = time_callback.train_finish_time if time_callback.epoch_runtime_log: stats['avg_exp_per_second'] = time_callback.average_examples_per_second return stats def get_num_train_iterations(flags_obj): """Returns the number of training steps, train and test epochs.""" train_steps = ( imagenet_preprocessing.NUM_IMAGES['train'] // flags_obj.batch_size) train_epochs = flags_obj.train_epochs if flags_obj.train_steps: train_steps = min(flags_obj.train_steps, train_steps) train_epochs = 1 eval_steps = math.ceil(1.0 * imagenet_preprocessing.NUM_IMAGES['validation'] / flags_obj.batch_size) return train_steps, train_epochs, eval_steps def run(flags_obj): """Run ResNet ImageNet training and eval loop using custom training loops. Args: flags_obj: An object containing parsed flag values. Raises: ValueError: If fp16 is passed as it is not currently supported. Returns: Dictionary of training and eval stats. """ keras_utils.set_session_config() performance.set_mixed_precision_policy(flags_core.get_tf_dtype(flags_obj)) if tf.config.list_physical_devices('GPU'): if flags_obj.tf_gpu_thread_mode: keras_utils.set_gpu_thread_mode_and_count( per_gpu_thread_count=flags_obj.per_gpu_thread_count, gpu_thread_mode=flags_obj.tf_gpu_thread_mode, num_gpus=flags_obj.num_gpus, datasets_num_private_threads=flags_obj.datasets_num_private_threads) common.set_cudnn_batchnorm_mode() data_format = flags_obj.data_format if data_format is None: data_format = ('channels_first' if tf.config.list_physical_devices('GPU') else 'channels_last') tf.keras.backend.set_image_data_format(data_format) strategy = distribute_utils.get_distribution_strategy( distribution_strategy=flags_obj.distribution_strategy, num_gpus=flags_obj.num_gpus, all_reduce_alg=flags_obj.all_reduce_alg, num_packs=flags_obj.num_packs, tpu_address=flags_obj.tpu) per_epoch_steps, train_epochs, eval_steps = get_num_train_iterations( flags_obj) if flags_obj.steps_per_loop is None: steps_per_loop = per_epoch_steps elif flags_obj.steps_per_loop > per_epoch_steps: steps_per_loop = per_epoch_steps logging.warn('Setting steps_per_loop to %d to respect epoch boundary.', steps_per_loop) else: steps_per_loop = flags_obj.steps_per_loop logging.info( 'Training %d epochs, each epoch has %d steps, ' 'total steps: %d; Eval %d steps', train_epochs, per_epoch_steps, train_epochs * per_epoch_steps, eval_steps) time_callback = keras_utils.TimeHistory( flags_obj.batch_size, flags_obj.log_steps, logdir=flags_obj.model_dir if flags_obj.enable_tensorboard else None) with distribute_utils.get_strategy_scope(strategy): runnable = resnet_runnable.ResnetRunnable(flags_obj, time_callback, per_epoch_steps) eval_interval = flags_obj.epochs_between_evals * per_epoch_steps checkpoint_interval = ( steps_per_loop * 5 if flags_obj.enable_checkpoint_and_export else None) summary_interval = steps_per_loop if flags_obj.enable_tensorboard else None checkpoint_manager = tf.train.CheckpointManager( runnable.checkpoint, directory=flags_obj.model_dir, max_to_keep=10, step_counter=runnable.global_step, checkpoint_interval=checkpoint_interval) resnet_controller = orbit.Controller( strategy=strategy, trainer=runnable, evaluator=runnable if not flags_obj.skip_eval else None, global_step=runnable.global_step, steps_per_loop=steps_per_loop, checkpoint_manager=checkpoint_manager, summary_interval=summary_interval, summary_dir=flags_obj.model_dir, eval_summary_dir=os.path.join(flags_obj.model_dir, 'eval')) time_callback.on_train_begin() if not flags_obj.skip_eval: resnet_controller.train_and_evaluate( train_steps=per_epoch_steps * train_epochs, eval_steps=eval_steps, eval_interval=eval_interval) else: resnet_controller.train(steps=per_epoch_steps * train_epochs) time_callback.on_train_end() stats = build_stats(runnable, time_callback) return stats def main(_): model_helpers.apply_clean(flags.FLAGS) stats = run(flags.FLAGS) logging.info('Run stats:\n%s', stats) if __name__ == '__main__': logging.set_verbosity(logging.INFO) common.define_keras_flags() app.run(main)
6,916
34.290816
80
py
models
models-master/official/legacy/image_classification/resnet/imagenet_preprocessing.py
# Copyright 2023 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. """Provides utilities to preprocess images. Training images are sampled using the provided bounding boxes, and subsequently cropped to the sampled bounding box. Images are additionally flipped randomly, then resized to the target output size (without aspect-ratio preservation). Images used during evaluation are resized (with aspect-ratio preservation) and centrally cropped. All images undergo mean color subtraction. Note that these steps are colloquially referred to as "ResNet preprocessing," and they differ from "VGG preprocessing," which does not use bounding boxes and instead does an aspect-preserving resize followed by random crop during training. (These both differ from "Inception preprocessing," which introduces color distortion steps.) """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from absl import logging import tensorflow as tf DEFAULT_IMAGE_SIZE = 224 NUM_CHANNELS = 3 NUM_CLASSES = 1001 NUM_IMAGES = { 'train': 1281167, 'validation': 50000, } _NUM_TRAIN_FILES = 1024 _SHUFFLE_BUFFER = 10000 _R_MEAN = 123.68 _G_MEAN = 116.78 _B_MEAN = 103.94 CHANNEL_MEANS = [_R_MEAN, _G_MEAN, _B_MEAN] # The lower bound for the smallest side of the image for aspect-preserving # resizing. For example, if an image is 500 x 1000, it will be resized to # _RESIZE_MIN x (_RESIZE_MIN * 2). _RESIZE_MIN = 256 def process_record_dataset(dataset, is_training, batch_size, shuffle_buffer, parse_record_fn, dtype=tf.float32, datasets_num_private_threads=None, drop_remainder=False, tf_data_experimental_slack=False): """Given a Dataset with raw records, return an iterator over the records. Args: dataset: A Dataset representing raw records is_training: A boolean denoting whether the input is for training. batch_size: The number of samples per batch. shuffle_buffer: The buffer size to use when shuffling records. A larger value results in better randomness, but smaller values reduce startup time and use less memory. parse_record_fn: A function that takes a raw record and returns the corresponding (image, label) pair. dtype: Data type to use for images/features. datasets_num_private_threads: Number of threads for a private threadpool created for all datasets computation. drop_remainder: A boolean indicates whether to drop the remainder of the batches. If True, the batch dimension will be static. tf_data_experimental_slack: Whether to enable tf.data's `experimental_slack` option. Returns: Dataset of (image, label) pairs ready for iteration. """ # Defines a specific size thread pool for tf.data operations. if datasets_num_private_threads: options = tf.data.Options() options.experimental_threading.private_threadpool_size = ( datasets_num_private_threads) dataset = dataset.with_options(options) logging.info('datasets_num_private_threads: %s', datasets_num_private_threads) if is_training: # Shuffles records before repeating to respect epoch boundaries. dataset = dataset.shuffle(buffer_size=shuffle_buffer) # Repeats the dataset for the number of epochs to train. dataset = dataset.repeat() # Parses the raw records into images and labels. dataset = dataset.map( lambda value: parse_record_fn(value, is_training, dtype), num_parallel_calls=tf.data.experimental.AUTOTUNE) dataset = dataset.batch(batch_size, drop_remainder=drop_remainder) # Operations between the final prefetch and the get_next call to the iterator # will happen synchronously during run time. We prefetch here again to # background all of the above processing work and keep it out of the # critical training path. Setting buffer_size to tf.data.experimental.AUTOTUNE # allows DistributionStrategies to adjust how many batches to fetch based # on how many devices are present. dataset = dataset.prefetch(buffer_size=tf.data.experimental.AUTOTUNE) options = tf.data.Options() options.experimental_slack = tf_data_experimental_slack dataset = dataset.with_options(options) return dataset def get_filenames(is_training, data_dir): """Return filenames for dataset.""" if is_training: return [ os.path.join(data_dir, 'train-%05d-of-01024' % i) for i in range(_NUM_TRAIN_FILES) ] else: return [ os.path.join(data_dir, 'validation-%05d-of-00128' % i) for i in range(128) ] def parse_example_proto(example_serialized): """Parses an Example proto containing a training example of an image. The output of the build_image_data.py image preprocessing script is a dataset containing serialized Example protocol buffers. Each Example proto contains the following fields (values are included as examples): image/height: 462 image/width: 581 image/colorspace: 'RGB' image/channels: 3 image/class/label: 615 image/class/synset: 'n03623198' image/class/text: 'knee pad' image/object/bbox/xmin: 0.1 image/object/bbox/xmax: 0.9 image/object/bbox/ymin: 0.2 image/object/bbox/ymax: 0.6 image/object/bbox/label: 615 image/format: 'JPEG' image/filename: 'ILSVRC2012_val_00041207.JPEG' image/encoded: <JPEG encoded string> Args: example_serialized: scalar Tensor tf.string containing a serialized Example protocol buffer. Returns: image_buffer: Tensor tf.string containing the contents of a JPEG file. label: Tensor tf.int32 containing the label. bbox: 3-D float Tensor of bounding boxes arranged [1, num_boxes, coords] where each coordinate is [0, 1) and the coordinates are arranged as [ymin, xmin, ymax, xmax]. """ # Dense features in Example proto. feature_map = { 'image/encoded': tf.io.FixedLenFeature([], dtype=tf.string, default_value=''), 'image/class/label': tf.io.FixedLenFeature([], dtype=tf.int64, default_value=-1), 'image/class/text': tf.io.FixedLenFeature([], dtype=tf.string, default_value=''), } sparse_float32 = tf.io.VarLenFeature(dtype=tf.float32) # Sparse features in Example proto. feature_map.update({ k: sparse_float32 for k in [ 'image/object/bbox/xmin', 'image/object/bbox/ymin', 'image/object/bbox/xmax', 'image/object/bbox/ymax' ] }) features = tf.io.parse_single_example( serialized=example_serialized, features=feature_map) label = tf.cast(features['image/class/label'], dtype=tf.int32) xmin = tf.expand_dims(features['image/object/bbox/xmin'].values, 0) ymin = tf.expand_dims(features['image/object/bbox/ymin'].values, 0) xmax = tf.expand_dims(features['image/object/bbox/xmax'].values, 0) ymax = tf.expand_dims(features['image/object/bbox/ymax'].values, 0) # Note that we impose an ordering of (y, x) just to make life difficult. bbox = tf.concat([ymin, xmin, ymax, xmax], 0) # Force the variable number of bounding boxes into the shape # [1, num_boxes, coords]. bbox = tf.expand_dims(bbox, 0) bbox = tf.transpose(a=bbox, perm=[0, 2, 1]) return features['image/encoded'], label, bbox def parse_record(raw_record, is_training, dtype): """Parses a record containing a training example of an image. The input record is parsed into a label and image, and the image is passed through preprocessing steps (cropping, flipping, and so on). Args: raw_record: scalar Tensor tf.string containing a serialized Example protocol buffer. is_training: A boolean denoting whether the input is for training. dtype: data type to use for images/features. Returns: Tuple with processed image tensor in a channel-last format and one-hot-encoded label tensor. """ image_buffer, label, bbox = parse_example_proto(raw_record) image = preprocess_image( image_buffer=image_buffer, bbox=bbox, output_height=DEFAULT_IMAGE_SIZE, output_width=DEFAULT_IMAGE_SIZE, num_channels=NUM_CHANNELS, is_training=is_training) image = tf.cast(image, dtype) # Subtract one so that labels are in [0, 1000), and cast to float32 for # Keras model. label = tf.cast( tf.cast(tf.reshape(label, shape=[1]), dtype=tf.int32) - 1, dtype=tf.float32) return image, label def get_parse_record_fn(use_keras_image_data_format=False): """Get a function for parsing the records, accounting for image format. This is useful by handling different types of Keras models. For instance, the current resnet_model.resnet50 input format is always channel-last, whereas the keras_applications mobilenet input format depends on tf.keras.backend.image_data_format(). We should set use_keras_image_data_format=False for the former and True for the latter. Args: use_keras_image_data_format: A boolean denoting whether data format is keras backend image data format. If False, the image format is channel-last. If True, the image format matches tf.keras.backend.image_data_format(). Returns: Function to use for parsing the records. """ def parse_record_fn(raw_record, is_training, dtype): image, label = parse_record(raw_record, is_training, dtype) if use_keras_image_data_format: if tf.keras.backend.image_data_format() == 'channels_first': image = tf.transpose(image, perm=[2, 0, 1]) return image, label return parse_record_fn def input_fn(is_training, data_dir, batch_size, dtype=tf.float32, datasets_num_private_threads=None, parse_record_fn=parse_record, input_context=None, drop_remainder=False, tf_data_experimental_slack=False, training_dataset_cache=False, filenames=None): """Input function which provides batches for train or eval. Args: is_training: A boolean denoting whether the input is for training. data_dir: The directory containing the input data. batch_size: The number of samples per batch. dtype: Data type to use for images/features datasets_num_private_threads: Number of private threads for tf.data. parse_record_fn: Function to use for parsing the records. input_context: A `tf.distribute.InputContext` object passed in by `tf.distribute.Strategy`. drop_remainder: A boolean indicates whether to drop the remainder of the batches. If True, the batch dimension will be static. tf_data_experimental_slack: Whether to enable tf.data's `experimental_slack` option. training_dataset_cache: Whether to cache the training dataset on workers. Typically used to improve training performance when training data is in remote storage and can fit into worker memory. filenames: Optional field for providing the file names of the TFRecords. Returns: A dataset that can be used for iteration. """ if filenames is None: filenames = get_filenames(is_training, data_dir) dataset = tf.data.Dataset.from_tensor_slices(filenames) if input_context: logging.info( 'Sharding the dataset: input_pipeline_id=%d num_input_pipelines=%d', input_context.input_pipeline_id, input_context.num_input_pipelines) dataset = dataset.shard(input_context.num_input_pipelines, input_context.input_pipeline_id) if is_training: # Shuffle the input files dataset = dataset.shuffle(buffer_size=_NUM_TRAIN_FILES) # Convert to individual records. # cycle_length = 10 means that up to 10 files will be read and deserialized in # parallel. You may want to increase this number if you have a large number of # CPU cores. dataset = dataset.interleave( tf.data.TFRecordDataset, cycle_length=10, num_parallel_calls=tf.data.experimental.AUTOTUNE) if is_training and training_dataset_cache: # Improve training performance when training data is in remote storage and # can fit into worker memory. dataset = dataset.cache() return process_record_dataset( dataset=dataset, is_training=is_training, batch_size=batch_size, shuffle_buffer=_SHUFFLE_BUFFER, parse_record_fn=parse_record_fn, dtype=dtype, datasets_num_private_threads=datasets_num_private_threads, drop_remainder=drop_remainder, tf_data_experimental_slack=tf_data_experimental_slack, ) def _decode_crop_and_flip(image_buffer, bbox, num_channels): """Crops the given image to a random part of the image, and randomly flips. We use the fused decode_and_crop op, which performs better than the two ops used separately in series, but note that this requires that the image be passed in as an un-decoded string Tensor. Args: image_buffer: scalar string Tensor representing the raw JPEG image buffer. bbox: 3-D float Tensor of bounding boxes arranged [1, num_boxes, coords] where each coordinate is [0, 1) and the coordinates are arranged as [ymin, xmin, ymax, xmax]. num_channels: Integer depth of the image buffer for decoding. Returns: 3-D tensor with cropped image. """ # A large fraction of image datasets contain a human-annotated bounding box # delineating the region of the image containing the object of interest. We # choose to create a new bounding box for the object which is a randomly # distorted version of the human-annotated bounding box that obeys an # allowed range of aspect ratios, sizes and overlap with the human-annotated # bounding box. If no box is supplied, then we assume the bounding box is # the entire image. sample_distorted_bounding_box = tf.image.sample_distorted_bounding_box( tf.image.extract_jpeg_shape(image_buffer), bounding_boxes=bbox, min_object_covered=0.1, aspect_ratio_range=[0.75, 1.33], area_range=[0.05, 1.0], max_attempts=100, use_image_if_no_bounding_boxes=True) bbox_begin, bbox_size, _ = sample_distorted_bounding_box # Reassemble the bounding box in the format the crop op requires. offset_y, offset_x, _ = tf.unstack(bbox_begin) target_height, target_width, _ = tf.unstack(bbox_size) crop_window = tf.stack([offset_y, offset_x, target_height, target_width]) # Use the fused decode and crop op here, which is faster than each in series. cropped = tf.image.decode_and_crop_jpeg( image_buffer, crop_window, channels=num_channels) # Flip to add a little more random distortion in. cropped = tf.image.random_flip_left_right(cropped) return cropped def _central_crop(image, crop_height, crop_width): """Performs central crops of the given image list. Args: image: a 3-D image tensor crop_height: the height of the image following the crop. crop_width: the width of the image following the crop. Returns: 3-D tensor with cropped image. """ shape = tf.shape(input=image) height, width = shape[0], shape[1] amount_to_be_cropped_h = (height - crop_height) crop_top = amount_to_be_cropped_h // 2 amount_to_be_cropped_w = (width - crop_width) crop_left = amount_to_be_cropped_w // 2 return tf.slice(image, [crop_top, crop_left, 0], [crop_height, crop_width, -1]) def _mean_image_subtraction(image, means, num_channels): """Subtracts the given means from each image channel. For example: means = [123.68, 116.779, 103.939] image = _mean_image_subtraction(image, means) Note that the rank of `image` must be known. Args: image: a tensor of size [height, width, C]. means: a C-vector of values to subtract from each channel. num_channels: number of color channels in the image that will be distorted. Returns: the centered image. Raises: ValueError: If the rank of `image` is unknown, if `image` has a rank other than three or if the number of channels in `image` doesn't match the number of values in `means`. """ if image.get_shape().ndims != 3: raise ValueError('Input must be of size [height, width, C>0]') if len(means) != num_channels: raise ValueError('len(means) must match the number of channels') # We have a 1-D tensor of means; convert to 3-D. # Note(b/130245863): we explicitly call `broadcast` instead of simply # expanding dimensions for better performance. means = tf.broadcast_to(means, tf.shape(image)) return image - means def _smallest_size_at_least(height, width, resize_min): """Computes new shape with the smallest side equal to `smallest_side`. Computes new shape with the smallest side equal to `smallest_side` while preserving the original aspect ratio. Args: height: an int32 scalar tensor indicating the current height. width: an int32 scalar tensor indicating the current width. resize_min: A python integer or scalar `Tensor` indicating the size of the smallest side after resize. Returns: new_height: an int32 scalar tensor indicating the new height. new_width: an int32 scalar tensor indicating the new width. """ resize_min = tf.cast(resize_min, tf.float32) # Convert to floats to make subsequent calculations go smoothly. height, width = tf.cast(height, tf.float32), tf.cast(width, tf.float32) smaller_dim = tf.minimum(height, width) scale_ratio = resize_min / smaller_dim # Convert back to ints to make heights and widths that TF ops will accept. new_height = tf.cast(height * scale_ratio, tf.int32) new_width = tf.cast(width * scale_ratio, tf.int32) return new_height, new_width def _aspect_preserving_resize(image, resize_min): """Resize images preserving the original aspect ratio. Args: image: A 3-D image `Tensor`. resize_min: A python integer or scalar `Tensor` indicating the size of the smallest side after resize. Returns: resized_image: A 3-D tensor containing the resized image. """ shape = tf.shape(input=image) height, width = shape[0], shape[1] new_height, new_width = _smallest_size_at_least(height, width, resize_min) return _resize_image(image, new_height, new_width) def _resize_image(image, height, width): """Simple wrapper around tf.resize_images. This is primarily to make sure we use the same `ResizeMethod` and other details each time. Args: image: A 3-D image `Tensor`. height: The target height for the resized image. width: The target width for the resized image. Returns: resized_image: A 3-D tensor containing the resized image. The first two dimensions have the shape [height, width]. """ return tf.compat.v1.image.resize( image, [height, width], method=tf.image.ResizeMethod.BILINEAR, align_corners=False) def preprocess_image(image_buffer, bbox, output_height, output_width, num_channels, is_training=False): """Preprocesses the given image. Preprocessing includes decoding, cropping, and resizing for both training and eval images. Training preprocessing, however, introduces some random distortion of the image to improve accuracy. Args: image_buffer: scalar string Tensor representing the raw JPEG image buffer. bbox: 3-D float Tensor of bounding boxes arranged [1, num_boxes, coords] where each coordinate is [0, 1) and the coordinates are arranged as [ymin, xmin, ymax, xmax]. output_height: The height of the image after preprocessing. output_width: The width of the image after preprocessing. num_channels: Integer depth of the image buffer for decoding. is_training: `True` if we're preprocessing the image for training and `False` otherwise. Returns: A preprocessed image. """ if is_training: # For training, we want to randomize some of the distortions. image = _decode_crop_and_flip(image_buffer, bbox, num_channels) image = _resize_image(image, output_height, output_width) else: # For validation, we want to decode, resize, then just crop the middle. image = tf.image.decode_jpeg(image_buffer, channels=num_channels) image = _aspect_preserving_resize(image, _RESIZE_MIN) image = _central_crop(image, output_height, output_width) image.set_shape([output_height, output_width, num_channels]) return _mean_image_subtraction(image, CHANNEL_MEANS, num_channels)
21,168
35.815652
80
py
models
models-master/official/legacy/image_classification/resnet/tfhub_export.py
# Copyright 2023 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. """A script to export TF-Hub SavedModel.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os # Import libraries from absl import app from absl import flags import tensorflow as tf from official.legacy.image_classification.resnet import imagenet_preprocessing from official.legacy.image_classification.resnet import resnet_model FLAGS = flags.FLAGS flags.DEFINE_string("model_path", None, "File path to TF model checkpoint or H5 file.") flags.DEFINE_string("export_path", None, "TF-Hub SavedModel destination path to export.") def export_tfhub(model_path, hub_destination): """Restores a tf.keras.Model and saves for TF-Hub.""" model = resnet_model.resnet50( num_classes=imagenet_preprocessing.NUM_CLASSES, rescale_inputs=True) model.load_weights(model_path) model.save( os.path.join(hub_destination, "classification"), include_optimizer=False) # Extracts a sub-model to use pooling feature vector as model output. image_input = model.get_layer(index=0).get_output_at(0) feature_vector_output = model.get_layer(name="reduce_mean").get_output_at(0) hub_model = tf.keras.Model(image_input, feature_vector_output) # Exports a SavedModel. hub_model.save( os.path.join(hub_destination, "feature-vector"), include_optimizer=False) def main(argv): if len(argv) > 1: raise app.UsageError("Too many command-line arguments.") export_tfhub(FLAGS.model_path, FLAGS.export_path) if __name__ == "__main__": app.run(main)
2,189
31.686567
79
py
models
models-master/official/legacy/image_classification/resnet/common.py
# Copyright 2023 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. """Common util functions and classes used by both keras cifar and imagenet.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from absl import flags import tensorflow as tf import tensorflow_model_optimization as tfmot from official.utils.flags import core as flags_core from official.utils.misc import keras_utils FLAGS = flags.FLAGS BASE_LEARNING_RATE = 0.1 # This matches Jing's version. TRAIN_TOP_1 = 'training_accuracy_top_1' LR_SCHEDULE = [ # (multiplier, epoch to start) tuples (1.0, 5), (0.1, 30), (0.01, 60), (0.001, 80) ] class PiecewiseConstantDecayWithWarmup( tf.keras.optimizers.schedules.LearningRateSchedule): """Piecewise constant decay with warmup schedule.""" def __init__(self, batch_size, epoch_size, warmup_epochs, boundaries, multipliers, compute_lr_on_cpu=True, name=None): super(PiecewiseConstantDecayWithWarmup, self).__init__() if len(boundaries) != len(multipliers) - 1: raise ValueError('The length of boundaries must be 1 less than the ' 'length of multipliers') base_lr_batch_size = 256 steps_per_epoch = epoch_size // batch_size self.rescaled_lr = BASE_LEARNING_RATE * batch_size / base_lr_batch_size self.step_boundaries = [float(steps_per_epoch) * x for x in boundaries] self.lr_values = [self.rescaled_lr * m for m in multipliers] self.warmup_steps = warmup_epochs * steps_per_epoch self.compute_lr_on_cpu = compute_lr_on_cpu self.name = name self.learning_rate_ops_cache = {} def __call__(self, step): if tf.executing_eagerly(): return self._get_learning_rate(step) # In an eager function or graph, the current implementation of optimizer # repeatedly call and thus create ops for the learning rate schedule. To # avoid this, we cache the ops if not executing eagerly. graph = tf.compat.v1.get_default_graph() if graph not in self.learning_rate_ops_cache: if self.compute_lr_on_cpu: with tf.device('/device:CPU:0'): self.learning_rate_ops_cache[graph] = self._get_learning_rate(step) else: self.learning_rate_ops_cache[graph] = self._get_learning_rate(step) return self.learning_rate_ops_cache[graph] def _get_learning_rate(self, step): """Compute learning rate at given step.""" step = tf.cast(step, dtype=tf.float32) warmup_steps = tf.cast(self.warmup_steps, dtype=tf.float32) with tf.name_scope('PiecewiseConstantDecayWithWarmup'): def warmup_lr(step): return self.rescaled_lr * (step / warmup_steps) def piecewise_lr(step): return tf.compat.v1.train.piecewise_constant(step, self.step_boundaries, self.lr_values) return tf.cond(step < warmup_steps, lambda: warmup_lr(step), lambda: piecewise_lr(step)) def get_config(self): return { 'rescaled_lr': self.rescaled_lr, 'step_boundaries': self.step_boundaries, 'lr_values': self.lr_values, 'warmup_steps': self.warmup_steps, 'compute_lr_on_cpu': self.compute_lr_on_cpu, 'name': self.name } def get_optimizer(learning_rate=0.1, use_legacy_optimizer=True): """Returns optimizer to use.""" # The learning_rate is overwritten at the beginning of each step by callback. if use_legacy_optimizer: return tf.keras.optimizers.legacy.SGD( learning_rate=learning_rate, momentum=0.9) else: return tf.keras.optimizers.SGD(learning_rate=learning_rate, momentum=0.9) def get_callbacks(pruning_method=None, enable_checkpoint_and_export=False, model_dir=None): """Returns common callbacks.""" time_callback = keras_utils.TimeHistory( FLAGS.batch_size, FLAGS.log_steps, logdir=FLAGS.model_dir if FLAGS.enable_tensorboard else None) callbacks = [time_callback] if FLAGS.enable_tensorboard: tensorboard_callback = tf.keras.callbacks.TensorBoard( log_dir=FLAGS.model_dir, profile_batch=FLAGS.profile_steps) callbacks.append(tensorboard_callback) is_pruning_enabled = pruning_method is not None if is_pruning_enabled: callbacks.append(tfmot.sparsity.keras.UpdatePruningStep()) if model_dir is not None: callbacks.append( tfmot.sparsity.keras.PruningSummaries( log_dir=model_dir, profile_batch=0)) if enable_checkpoint_and_export: if model_dir is not None: ckpt_full_path = os.path.join(model_dir, 'model.ckpt-{epoch:04d}') callbacks.append( tf.keras.callbacks.ModelCheckpoint( ckpt_full_path, save_weights_only=True)) return callbacks def build_stats(history, eval_output, callbacks): """Normalizes and returns dictionary of stats. Args: history: Results of the training step. Supports both categorical_accuracy and sparse_categorical_accuracy. eval_output: Output of the eval step. Assumes first value is eval_loss and second value is accuracy_top_1. callbacks: a list of callbacks which might include a time history callback used during keras.fit. Returns: Dictionary of normalized results. """ stats = {} if eval_output: stats['accuracy_top_1'] = float(eval_output[1]) stats['eval_loss'] = float(eval_output[0]) if history and history.history: train_hist = history.history # Gets final loss from training. stats['loss'] = float(train_hist['loss'][-1]) # Gets top_1 training accuracy. if 'categorical_accuracy' in train_hist: stats[TRAIN_TOP_1] = float(train_hist['categorical_accuracy'][-1]) elif 'sparse_categorical_accuracy' in train_hist: stats[TRAIN_TOP_1] = float(train_hist['sparse_categorical_accuracy'][-1]) elif 'accuracy' in train_hist: stats[TRAIN_TOP_1] = float(train_hist['accuracy'][-1]) if not callbacks: return stats # Look for the time history callback which was used during keras.fit for callback in callbacks: if isinstance(callback, keras_utils.TimeHistory): timestamp_log = callback.timestamp_log stats['step_timestamp_log'] = timestamp_log stats['train_finish_time'] = callback.train_finish_time if callback.epoch_runtime_log: stats['avg_exp_per_second'] = callback.average_examples_per_second return stats def define_keras_flags(model=False, optimizer=False, pretrained_filepath=False): """Define flags for Keras models.""" flags_core.define_base( clean=True, num_gpu=True, run_eagerly=True, train_epochs=True, epochs_between_evals=True, distribution_strategy=True) flags_core.define_performance( num_parallel_calls=False, synthetic_data=True, dtype=True, all_reduce_alg=True, num_packs=True, tf_gpu_thread_mode=True, datasets_num_private_threads=True, loss_scale=True, fp16_implementation=True, tf_data_experimental_slack=True, enable_xla=True, training_dataset_cache=True) flags_core.define_image() flags_core.define_benchmark() flags_core.define_distribution() flags.adopt_module_key_flags(flags_core) flags.DEFINE_boolean(name='enable_eager', default=False, help='Enable eager?') flags.DEFINE_boolean(name='skip_eval', default=False, help='Skip evaluation?') # TODO(b/135607288): Remove this flag once we understand the root cause of # slowdown when setting the learning phase in Keras backend. flags.DEFINE_boolean( name='set_learning_phase_to_train', default=True, help='If skip eval, also set Keras learning phase to 1 (training).') flags.DEFINE_boolean( name='explicit_gpu_placement', default=False, help='If not using distribution strategy, explicitly set device scope ' 'for the Keras training loop.') flags.DEFINE_boolean( name='use_trivial_model', default=False, help='Whether to use a trivial Keras model.') flags.DEFINE_boolean( name='report_accuracy_metrics', default=True, help='Report metrics during training and evaluation.') flags.DEFINE_boolean( name='use_tensor_lr', default=True, help='Use learning rate tensor instead of a callback.') flags.DEFINE_boolean( name='enable_tensorboard', default=False, help='Whether to enable TensorBoard callback.') flags.DEFINE_string( name='profile_steps', default=None, help='Save profiling data to model dir at given range of global steps. The ' 'value must be a comma separated pair of positive integers, specifying ' 'the first and last step to profile. For example, "--profile_steps=2,4" ' 'triggers the profiler to process 3 steps, starting from the 2nd step. ' 'Note that profiler has a non-trivial performance overhead, and the ' 'output file can be gigantic if profiling many steps.') flags.DEFINE_integer( name='train_steps', default=None, help='The number of steps to run for training. If it is larger than ' '# batches per epoch, then use # batches per epoch. This flag will be ' 'ignored if train_epochs is set to be larger than 1. ') flags.DEFINE_boolean( name='batchnorm_spatial_persistent', default=True, help='Enable the spacial persistent mode for CuDNN batch norm kernel.') flags.DEFINE_boolean( name='enable_get_next_as_optional', default=False, help='Enable get_next_as_optional behavior in DistributedIterator.') flags.DEFINE_boolean( name='enable_checkpoint_and_export', default=False, help='Whether to enable a checkpoint callback and export the savedmodel.') flags.DEFINE_string(name='tpu', default='', help='TPU address to connect to.') flags.DEFINE_integer( name='steps_per_loop', default=None, help='Number of steps per training loop. Only training step happens ' 'inside the loop. Callbacks will not be called inside. Will be capped at ' 'steps per epoch.') flags.DEFINE_boolean( name='use_tf_while_loop', default=True, help='Whether to build a tf.while_loop inside the training loop on the ' 'host. Setting it to True is critical to have peak performance on ' 'TPU.') if model: flags.DEFINE_string('model', 'resnet50_v1.5', 'Name of model preset. (mobilenet, resnet50_v1.5)') if optimizer: flags.DEFINE_string( 'optimizer', 'resnet50_default', 'Name of optimizer preset. ' '(mobilenet_default, resnet50_default)') # TODO(kimjaehong): Replace as general hyper-params not only for mobilenet. flags.DEFINE_float( 'initial_learning_rate_per_sample', 0.00007, 'Initial value of learning rate per sample for ' 'mobilenet_default.') flags.DEFINE_float('lr_decay_factor', 0.94, 'Learning rate decay factor for mobilenet_default.') flags.DEFINE_float('num_epochs_per_decay', 2.5, 'Number of epochs per decay for mobilenet_default.') if pretrained_filepath: flags.DEFINE_string('pretrained_filepath', '', 'Pretrained file path.') def get_synth_data(height, width, num_channels, num_classes, dtype): """Creates a set of synthetic random data. Args: height: Integer height that will be used to create a fake image tensor. width: Integer width that will be used to create a fake image tensor. num_channels: Integer depth that will be used to create a fake image tensor. num_classes: Number of classes that should be represented in the fake labels tensor dtype: Data type for features/images. Returns: A tuple of tensors representing the inputs and labels. """ # Synthetic input should be within [0, 255]. inputs = tf.random.truncated_normal([height, width, num_channels], dtype=dtype, mean=127, stddev=60, name='synthetic_inputs') labels = tf.random.uniform([1], minval=0, maxval=num_classes - 1, dtype=tf.int32, name='synthetic_labels') return inputs, labels def define_pruning_flags(): """Define flags for pruning methods.""" flags.DEFINE_string( 'pruning_method', None, 'Pruning method.' 'None (no pruning) or polynomial_decay.') flags.DEFINE_float('pruning_initial_sparsity', 0.0, 'Initial sparsity for pruning.') flags.DEFINE_float('pruning_final_sparsity', 0.5, 'Final sparsity for pruning.') flags.DEFINE_integer('pruning_begin_step', 0, 'Begin step for pruning.') flags.DEFINE_integer('pruning_end_step', 100000, 'End step for pruning.') flags.DEFINE_integer('pruning_frequency', 100, 'Frequency for pruning.') def define_clustering_flags(): """Define flags for clustering methods.""" flags.DEFINE_string('clustering_method', None, 'None (no clustering) or selective_clustering ' '(cluster last three Conv2D layers of the model).') def get_synth_input_fn(height, width, num_channels, num_classes, dtype=tf.float32, drop_remainder=True): """Returns an input function that returns a dataset with random data. This input_fn returns a data set that iterates over a set of random data and bypasses all preprocessing, e.g. jpeg decode and copy. The host to device copy is still included. This used to find the upper throughput bound when tuning the full input pipeline. Args: height: Integer height that will be used to create a fake image tensor. width: Integer width that will be used to create a fake image tensor. num_channels: Integer depth that will be used to create a fake image tensor. num_classes: Number of classes that should be represented in the fake labels tensor dtype: Data type for features/images. drop_remainder: A boolean indicates whether to drop the remainder of the batches. If True, the batch dimension will be static. Returns: An input_fn that can be used in place of a real one to return a dataset that can be used for iteration. """ # pylint: disable=unused-argument def input_fn(is_training, data_dir, batch_size, *args, **kwargs): """Returns dataset filled with random data.""" inputs, labels = get_synth_data( height=height, width=width, num_channels=num_channels, num_classes=num_classes, dtype=dtype) # Cast to float32 for Keras model. labels = tf.cast(labels, dtype=tf.float32) data = tf.data.Dataset.from_tensors((inputs, labels)).repeat() # `drop_remainder` will make dataset produce outputs with known shapes. data = data.batch(batch_size, drop_remainder=drop_remainder) data = data.prefetch(buffer_size=tf.data.experimental.AUTOTUNE) return data return input_fn def set_cudnn_batchnorm_mode(): """Set CuDNN batchnorm mode for better performance. Note: Spatial Persistent mode may lead to accuracy losses for certain models. """ if FLAGS.batchnorm_spatial_persistent: os.environ['TF_USE_CUDNN_BATCHNORM_SPATIAL_PERSISTENT'] = '1' else: os.environ.pop('TF_USE_CUDNN_BATCHNORM_SPATIAL_PERSISTENT', None)
16,294
37.431604
82
py
models
models-master/official/legacy/image_classification/resnet/resnet_runnable.py
# Copyright 2023 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. """Runs a ResNet model on the ImageNet dataset using custom training loops.""" import orbit import tensorflow as tf from official.legacy.image_classification.resnet import common from official.legacy.image_classification.resnet import imagenet_preprocessing from official.legacy.image_classification.resnet import resnet_model from official.modeling import grad_utils from official.modeling import performance from official.utils.flags import core as flags_core class ResnetRunnable(orbit.StandardTrainer, orbit.StandardEvaluator): """Implements the training and evaluation APIs for Resnet model.""" def __init__(self, flags_obj, time_callback, epoch_steps): self.strategy = tf.distribute.get_strategy() self.flags_obj = flags_obj self.dtype = flags_core.get_tf_dtype(flags_obj) self.time_callback = time_callback # Input pipeline related batch_size = flags_obj.batch_size if batch_size % self.strategy.num_replicas_in_sync != 0: raise ValueError( 'Batch size must be divisible by number of replicas : {}'.format( self.strategy.num_replicas_in_sync)) # As auto rebatching is not supported in # `distribute_datasets_from_function()` API, which is # required when cloning dataset to multiple workers in eager mode, # we use per-replica batch size. self.batch_size = int(batch_size / self.strategy.num_replicas_in_sync) if self.flags_obj.use_synthetic_data: self.input_fn = common.get_synth_input_fn( height=imagenet_preprocessing.DEFAULT_IMAGE_SIZE, width=imagenet_preprocessing.DEFAULT_IMAGE_SIZE, num_channels=imagenet_preprocessing.NUM_CHANNELS, num_classes=imagenet_preprocessing.NUM_CLASSES, dtype=self.dtype, drop_remainder=True) else: self.input_fn = imagenet_preprocessing.input_fn self.model = resnet_model.resnet50( num_classes=imagenet_preprocessing.NUM_CLASSES, use_l2_regularizer=not flags_obj.single_l2_loss_op) lr_schedule = common.PiecewiseConstantDecayWithWarmup( batch_size=flags_obj.batch_size, epoch_size=imagenet_preprocessing.NUM_IMAGES['train'], warmup_epochs=common.LR_SCHEDULE[0][1], boundaries=list(p[1] for p in common.LR_SCHEDULE[1:]), multipliers=list(p[0] for p in common.LR_SCHEDULE), compute_lr_on_cpu=True) self.optimizer = common.get_optimizer(lr_schedule) # Make sure iterations variable is created inside scope. self.global_step = self.optimizer.iterations self.optimizer = performance.configure_optimizer( self.optimizer, use_float16=self.dtype == tf.float16, loss_scale=flags_core.get_loss_scale(flags_obj, default_for_fp16=128)) self.train_loss = tf.keras.metrics.Mean('train_loss', dtype=tf.float32) self.train_accuracy = tf.keras.metrics.SparseCategoricalAccuracy( 'train_accuracy', dtype=tf.float32) self.test_loss = tf.keras.metrics.Mean('test_loss', dtype=tf.float32) self.test_accuracy = tf.keras.metrics.SparseCategoricalAccuracy( 'test_accuracy', dtype=tf.float32) self.checkpoint = tf.train.Checkpoint( model=self.model, optimizer=self.optimizer) # Handling epochs. self.epoch_steps = epoch_steps self.epoch_helper = orbit.utils.EpochHelper(epoch_steps, self.global_step) train_dataset = orbit.utils.make_distributed_dataset( self.strategy, self.input_fn, is_training=True, data_dir=self.flags_obj.data_dir, batch_size=self.batch_size, parse_record_fn=imagenet_preprocessing.parse_record, datasets_num_private_threads=self.flags_obj .datasets_num_private_threads, dtype=self.dtype, drop_remainder=True, training_dataset_cache=self.flags_obj.training_dataset_cache) orbit.StandardTrainer.__init__( self, train_dataset, options=orbit.StandardTrainerOptions( use_tf_while_loop=flags_obj.use_tf_while_loop, use_tf_function=flags_obj.use_tf_function)) if not flags_obj.skip_eval: eval_dataset = orbit.utils.make_distributed_dataset( self.strategy, self.input_fn, is_training=False, data_dir=self.flags_obj.data_dir, batch_size=self.batch_size, parse_record_fn=imagenet_preprocessing.parse_record, dtype=self.dtype) orbit.StandardEvaluator.__init__( self, eval_dataset, options=orbit.StandardEvaluatorOptions( use_tf_function=flags_obj.use_tf_function)) def train_loop_begin(self): """See base class.""" # Reset all metrics self.train_loss.reset_states() self.train_accuracy.reset_states() self._epoch_begin() self.time_callback.on_batch_begin(self.epoch_helper.batch_index) def train_step(self, iterator): """See base class.""" def step_fn(inputs): """Function to run on the device.""" images, labels = inputs with tf.GradientTape() as tape: logits = self.model(images, training=True) prediction_loss = tf.keras.losses.sparse_categorical_crossentropy( labels, logits) loss = tf.reduce_sum(prediction_loss) * (1.0 / self.flags_obj.batch_size) num_replicas = self.strategy.num_replicas_in_sync l2_weight_decay = 1e-4 if self.flags_obj.single_l2_loss_op: l2_loss = l2_weight_decay * 2 * tf.add_n([ tf.nn.l2_loss(v) for v in self.model.trainable_variables if 'bn' not in v.name ]) loss += (l2_loss / num_replicas) else: loss += (tf.reduce_sum(self.model.losses) / num_replicas) grad_utils.minimize_using_explicit_allreduce( tape, self.optimizer, loss, self.model.trainable_variables) self.train_loss.update_state(loss) self.train_accuracy.update_state(labels, logits) if self.flags_obj.enable_xla: step_fn = tf.function(step_fn, jit_compile=True) self.strategy.run(step_fn, args=(next(iterator),)) def train_loop_end(self): """See base class.""" metrics = { 'train_loss': self.train_loss.result(), 'train_accuracy': self.train_accuracy.result(), } self.time_callback.on_batch_end(self.epoch_helper.batch_index - 1) self._epoch_end() return metrics def eval_begin(self): """See base class.""" self.test_loss.reset_states() self.test_accuracy.reset_states() def eval_step(self, iterator): """See base class.""" def step_fn(inputs): """Function to run on the device.""" images, labels = inputs logits = self.model(images, training=False) loss = tf.keras.losses.sparse_categorical_crossentropy(labels, logits) loss = tf.reduce_sum(loss) * (1.0 / self.flags_obj.batch_size) self.test_loss.update_state(loss) self.test_accuracy.update_state(labels, logits) self.strategy.run(step_fn, args=(next(iterator),)) def eval_end(self): """See base class.""" return { 'test_loss': self.test_loss.result(), 'test_accuracy': self.test_accuracy.result() } def _epoch_begin(self): if self.epoch_helper.epoch_begin(): self.time_callback.on_epoch_begin(self.epoch_helper.current_epoch) def _epoch_end(self): if self.epoch_helper.epoch_end(): self.time_callback.on_epoch_end(self.epoch_helper.current_epoch)
8,124
37.507109
78
py
models
models-master/official/legacy/image_classification/resnet/resnet_model.py
# Copyright 2023 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. """ResNet50 model for Keras. Adapted from tf.keras.applications.resnet50.ResNet50(). This is ResNet model version 1.5. Related papers/blogs: - https://arxiv.org/abs/1512.03385 - https://arxiv.org/pdf/1603.05027v2.pdf - http://torch.ch/blog/2016/02/04/resnets.html """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from official.legacy.image_classification.resnet import imagenet_preprocessing layers = tf.keras.layers def _gen_l2_regularizer(use_l2_regularizer=True, l2_weight_decay=1e-4): return tf.keras.regularizers.L2( l2_weight_decay) if use_l2_regularizer else None def identity_block(input_tensor, kernel_size, filters, stage, block, use_l2_regularizer=True, batch_norm_decay=0.9, batch_norm_epsilon=1e-5): """The identity block is the block that has no conv layer at shortcut. Args: input_tensor: input tensor kernel_size: default 3, the kernel size of middle conv layer at main path filters: list of integers, the filters of 3 conv layer at main path stage: integer, current stage label, used for generating layer names block: 'a','b'..., current block label, used for generating layer names use_l2_regularizer: whether to use L2 regularizer on Conv layer. batch_norm_decay: Moment of batch norm layers. batch_norm_epsilon: Epsilon of batch borm layers. Returns: Output tensor for the block. """ filters1, filters2, filters3 = filters if tf.keras.backend.image_data_format() == 'channels_last': bn_axis = 3 else: bn_axis = 1 conv_name_base = 'res' + str(stage) + block + '_branch' bn_name_base = 'bn' + str(stage) + block + '_branch' x = layers.Conv2D( filters1, (1, 1), use_bias=False, kernel_initializer='he_normal', kernel_regularizer=_gen_l2_regularizer(use_l2_regularizer), name=conv_name_base + '2a')( input_tensor) x = layers.BatchNormalization( axis=bn_axis, momentum=batch_norm_decay, epsilon=batch_norm_epsilon, name=bn_name_base + '2a')( x) x = layers.Activation('relu')(x) x = layers.Conv2D( filters2, kernel_size, padding='same', use_bias=False, kernel_initializer='he_normal', kernel_regularizer=_gen_l2_regularizer(use_l2_regularizer), name=conv_name_base + '2b')( x) x = layers.BatchNormalization( axis=bn_axis, momentum=batch_norm_decay, epsilon=batch_norm_epsilon, name=bn_name_base + '2b')( x) x = layers.Activation('relu')(x) x = layers.Conv2D( filters3, (1, 1), use_bias=False, kernel_initializer='he_normal', kernel_regularizer=_gen_l2_regularizer(use_l2_regularizer), name=conv_name_base + '2c')( x) x = layers.BatchNormalization( axis=bn_axis, momentum=batch_norm_decay, epsilon=batch_norm_epsilon, name=bn_name_base + '2c')( x) x = layers.add([x, input_tensor]) x = layers.Activation('relu')(x) return x def conv_block(input_tensor, kernel_size, filters, stage, block, strides=(2, 2), use_l2_regularizer=True, batch_norm_decay=0.9, batch_norm_epsilon=1e-5): """A block that has a conv layer at shortcut. Note that from stage 3, the second conv layer at main path is with strides=(2, 2) And the shortcut should have strides=(2, 2) as well Args: input_tensor: input tensor kernel_size: default 3, the kernel size of middle conv layer at main path filters: list of integers, the filters of 3 conv layer at main path stage: integer, current stage label, used for generating layer names block: 'a','b'..., current block label, used for generating layer names strides: Strides for the second conv layer in the block. use_l2_regularizer: whether to use L2 regularizer on Conv layer. batch_norm_decay: Moment of batch norm layers. batch_norm_epsilon: Epsilon of batch borm layers. Returns: Output tensor for the block. """ filters1, filters2, filters3 = filters if tf.keras.backend.image_data_format() == 'channels_last': bn_axis = 3 else: bn_axis = 1 conv_name_base = 'res' + str(stage) + block + '_branch' bn_name_base = 'bn' + str(stage) + block + '_branch' x = layers.Conv2D( filters1, (1, 1), use_bias=False, kernel_initializer='he_normal', kernel_regularizer=_gen_l2_regularizer(use_l2_regularizer), name=conv_name_base + '2a')( input_tensor) x = layers.BatchNormalization( axis=bn_axis, momentum=batch_norm_decay, epsilon=batch_norm_epsilon, name=bn_name_base + '2a')( x) x = layers.Activation('relu')(x) x = layers.Conv2D( filters2, kernel_size, strides=strides, padding='same', use_bias=False, kernel_initializer='he_normal', kernel_regularizer=_gen_l2_regularizer(use_l2_regularizer), name=conv_name_base + '2b')( x) x = layers.BatchNormalization( axis=bn_axis, momentum=batch_norm_decay, epsilon=batch_norm_epsilon, name=bn_name_base + '2b')( x) x = layers.Activation('relu')(x) x = layers.Conv2D( filters3, (1, 1), use_bias=False, kernel_initializer='he_normal', kernel_regularizer=_gen_l2_regularizer(use_l2_regularizer), name=conv_name_base + '2c')( x) x = layers.BatchNormalization( axis=bn_axis, momentum=batch_norm_decay, epsilon=batch_norm_epsilon, name=bn_name_base + '2c')( x) shortcut = layers.Conv2D( filters3, (1, 1), strides=strides, use_bias=False, kernel_initializer='he_normal', kernel_regularizer=_gen_l2_regularizer(use_l2_regularizer), name=conv_name_base + '1')( input_tensor) shortcut = layers.BatchNormalization( axis=bn_axis, momentum=batch_norm_decay, epsilon=batch_norm_epsilon, name=bn_name_base + '1')( shortcut) x = layers.add([x, shortcut]) x = layers.Activation('relu')(x) return x def resnet50(num_classes, batch_size=None, use_l2_regularizer=True, rescale_inputs=False, batch_norm_decay=0.9, batch_norm_epsilon=1e-5): """Instantiates the ResNet50 architecture. Args: num_classes: `int` number of classes for image classification. batch_size: Size of the batches for each step. use_l2_regularizer: whether to use L2 regularizer on Conv/Dense layer. rescale_inputs: whether to rescale inputs from 0 to 1. batch_norm_decay: Moment of batch norm layers. batch_norm_epsilon: Epsilon of batch borm layers. Returns: A Keras model instance. """ input_shape = (224, 224, 3) img_input = layers.Input(shape=input_shape, batch_size=batch_size) if rescale_inputs: # Hub image modules expect inputs in the range [0, 1]. This rescales these # inputs to the range expected by the trained model. x = layers.Lambda( lambda x: x * 255.0 - tf.keras.backend.constant( # pylint: disable=g-long-lambda imagenet_preprocessing.CHANNEL_MEANS, shape=[1, 1, 3], dtype=x.dtype), name='rescale')( img_input) else: x = img_input if tf.keras.backend.image_data_format() == 'channels_first': x = layers.Permute((3, 1, 2))(x) bn_axis = 1 else: # channels_last bn_axis = 3 block_config = dict( use_l2_regularizer=use_l2_regularizer, batch_norm_decay=batch_norm_decay, batch_norm_epsilon=batch_norm_epsilon) x = layers.ZeroPadding2D(padding=(3, 3), name='conv1_pad')(x) x = layers.Conv2D( 64, (7, 7), strides=(2, 2), padding='valid', use_bias=False, kernel_initializer='he_normal', kernel_regularizer=_gen_l2_regularizer(use_l2_regularizer), name='conv1')( x) x = layers.BatchNormalization( axis=bn_axis, momentum=batch_norm_decay, epsilon=batch_norm_epsilon, name='bn_conv1')( x) x = layers.Activation('relu')(x) x = layers.MaxPooling2D((3, 3), strides=(2, 2), padding='same')(x) x = conv_block( x, 3, [64, 64, 256], stage=2, block='a', strides=(1, 1), **block_config) x = identity_block(x, 3, [64, 64, 256], stage=2, block='b', **block_config) x = identity_block(x, 3, [64, 64, 256], stage=2, block='c', **block_config) x = conv_block(x, 3, [128, 128, 512], stage=3, block='a', **block_config) x = identity_block(x, 3, [128, 128, 512], stage=3, block='b', **block_config) x = identity_block(x, 3, [128, 128, 512], stage=3, block='c', **block_config) x = identity_block(x, 3, [128, 128, 512], stage=3, block='d', **block_config) x = conv_block(x, 3, [256, 256, 1024], stage=4, block='a', **block_config) x = identity_block(x, 3, [256, 256, 1024], stage=4, block='b', **block_config) x = identity_block(x, 3, [256, 256, 1024], stage=4, block='c', **block_config) x = identity_block(x, 3, [256, 256, 1024], stage=4, block='d', **block_config) x = identity_block(x, 3, [256, 256, 1024], stage=4, block='e', **block_config) x = identity_block(x, 3, [256, 256, 1024], stage=4, block='f', **block_config) x = conv_block(x, 3, [512, 512, 2048], stage=5, block='a', **block_config) x = identity_block(x, 3, [512, 512, 2048], stage=5, block='b', **block_config) x = identity_block(x, 3, [512, 512, 2048], stage=5, block='c', **block_config) x = layers.GlobalAveragePooling2D()(x) x = layers.Dense( num_classes, kernel_initializer=tf.initializers.random_normal(stddev=0.01), kernel_regularizer=_gen_l2_regularizer(use_l2_regularizer), bias_regularizer=_gen_l2_regularizer(use_l2_regularizer), name='fc1000')( x) # A softmax that is followed by the model loss must be done cannot be done # in float16 due to numeric issues. So we pass dtype=float32. x = layers.Activation('softmax', dtype='float32')(x) # Create model. return tf.keras.Model(img_input, x, name='resnet50')
10,945
32.576687
91
py
models
models-master/official/legacy/transformer/transformer_main_test.py
# Copyright 2023 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. """Test Transformer model.""" import os import re import sys import unittest from absl import flags from absl.testing import flagsaver import tensorflow as tf from tensorflow.python.eager import context # pylint: disable=ungrouped-imports from official.legacy.transformer import misc from official.legacy.transformer import transformer_main FLAGS = flags.FLAGS FIXED_TIMESTAMP = 'my_time_stamp' WEIGHT_PATTERN = re.compile(r'weights-epoch-.+\.hdf5') def _generate_file(filepath, lines): with open(filepath, 'w') as f: for l in lines: f.write('{}\n'.format(l)) class TransformerTaskTest(tf.test.TestCase): local_flags = None def setUp(self): # pylint: disable=g-missing-super-call temp_dir = self.get_temp_dir() if TransformerTaskTest.local_flags is None: misc.define_transformer_flags() # Loads flags, array cannot be blank. flags.FLAGS(['foo']) TransformerTaskTest.local_flags = flagsaver.save_flag_values() else: flagsaver.restore_flag_values(TransformerTaskTest.local_flags) FLAGS.model_dir = os.path.join(temp_dir, FIXED_TIMESTAMP) FLAGS.param_set = 'tiny' FLAGS.use_synthetic_data = True FLAGS.steps_between_evals = 1 FLAGS.train_steps = 1 FLAGS.validation_steps = 1 FLAGS.batch_size = 4 FLAGS.max_length = 1 FLAGS.num_gpus = 1 FLAGS.distribution_strategy = 'off' FLAGS.dtype = 'fp32' self.model_dir = FLAGS.model_dir self.temp_dir = temp_dir self.vocab_file = os.path.join(temp_dir, 'vocab') self.vocab_size = misc.get_model_params(FLAGS.param_set, 0)['vocab_size'] self.bleu_source = os.path.join(temp_dir, 'bleu_source') self.bleu_ref = os.path.join(temp_dir, 'bleu_ref') self.orig_policy = ( tf.compat.v2.keras.mixed_precision.global_policy()) def tearDown(self): # pylint: disable=g-missing-super-call tf.compat.v2.keras.mixed_precision.set_global_policy(self.orig_policy) def _assert_exists(self, filepath): self.assertTrue(os.path.exists(filepath)) def test_train_no_dist_strat(self): if context.num_gpus() >= 2: self.skipTest('No need to test 2+ GPUs without a distribution strategy.') t = transformer_main.TransformerTask(FLAGS) t.train() def test_train_save_full_model(self): if context.num_gpus() >= 2: self.skipTest('No need to test 2+ GPUs without a distribution strategy.') FLAGS.save_weights_only = False t = transformer_main.TransformerTask(FLAGS) t.train() def test_train_static_batch(self): if context.num_gpus() >= 2: self.skipTest('No need to test 2+ GPUs without a distribution strategy.') FLAGS.distribution_strategy = 'one_device' if tf.test.is_built_with_cuda(): FLAGS.num_gpus = 1 else: FLAGS.num_gpus = 0 FLAGS.static_batch = True t = transformer_main.TransformerTask(FLAGS) t.train() @unittest.skipUnless(tf.test.is_built_with_cuda(), 'requires GPU') def test_train_1_gpu_with_dist_strat(self): FLAGS.distribution_strategy = 'one_device' t = transformer_main.TransformerTask(FLAGS) t.train() @unittest.skipUnless(tf.test.is_built_with_cuda(), 'requires GPU') def test_train_fp16(self): FLAGS.distribution_strategy = 'one_device' FLAGS.dtype = 'fp16' t = transformer_main.TransformerTask(FLAGS) t.train() @unittest.skipUnless(tf.test.is_built_with_cuda(), 'requires GPU') def test_train_2_gpu(self): if context.num_gpus() < 2: self.skipTest( '{} GPUs are not available for this test. {} GPUs are available' .format(2, context.num_gpus())) FLAGS.distribution_strategy = 'mirrored' FLAGS.num_gpus = 2 FLAGS.param_set = 'base' t = transformer_main.TransformerTask(FLAGS) t.train() @unittest.skipUnless(tf.test.is_built_with_cuda(), 'requires GPU') def test_train_2_gpu_fp16(self): if context.num_gpus() < 2: self.skipTest( '{} GPUs are not available for this test. {} GPUs are available' .format(2, context.num_gpus())) FLAGS.distribution_strategy = 'mirrored' FLAGS.num_gpus = 2 FLAGS.param_set = 'base' FLAGS.dtype = 'fp16' t = transformer_main.TransformerTask(FLAGS) t.train() def _prepare_files_and_flags(self, *extra_flags): # Make log dir. if not os.path.exists(self.temp_dir): os.makedirs(self.temp_dir) # Fake vocab, bleu_source and bleu_ref. tokens = [ "'<pad>'", "'<EOS>'", "'_'", "'a'", "'b'", "'c'", "'d'", "'a_'", "'b_'", "'c_'", "'d_'" ] tokens += ["'{}'".format(i) for i in range(self.vocab_size - len(tokens))] _generate_file(self.vocab_file, tokens) _generate_file(self.bleu_source, ['a b', 'c d']) _generate_file(self.bleu_ref, ['a b', 'd c']) # Update flags. update_flags = [ 'ignored_program_name', '--vocab_file={}'.format(self.vocab_file), '--bleu_source={}'.format(self.bleu_source), '--bleu_ref={}'.format(self.bleu_ref), ] if extra_flags: update_flags.extend(extra_flags) FLAGS(update_flags) def test_predict(self): if context.num_gpus() >= 2: self.skipTest('No need to test 2+ GPUs without a distribution strategy.') self._prepare_files_and_flags() t = transformer_main.TransformerTask(FLAGS) t.predict() @unittest.skipUnless(tf.test.is_built_with_cuda(), 'requires GPU') def test_predict_fp16(self): if context.num_gpus() >= 2: self.skipTest('No need to test 2+ GPUs without a distribution strategy.') self._prepare_files_and_flags('--dtype=fp16') t = transformer_main.TransformerTask(FLAGS) t.predict() def test_eval(self): if context.num_gpus() >= 2: self.skipTest('No need to test 2+ GPUs without a distribution strategy.') if 'test_xla' in sys.argv[0]: self.skipTest('TODO(xla): Make this test faster under XLA.') self._prepare_files_and_flags() t = transformer_main.TransformerTask(FLAGS) t.eval() if __name__ == '__main__': tf.test.main()
6,631
33.185567
80
py
models
models-master/official/legacy/transformer/transformer_forward_test.py
# Copyright 2023 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. """Forward pass test for Transformer model refactoring.""" import numpy as np import tensorflow as tf from official.legacy.transformer import metrics from official.legacy.transformer import model_params from official.legacy.transformer import transformer from official.nlp.modeling import models def _count_params(layer, trainable_only=True): """Returns the count of all model parameters, or just trainable ones.""" if not trainable_only: return layer.count_params() else: return int( np.sum([ tf.keras.backend.count_params(p) for p in layer.trainable_weights ])) def _create_model(params, is_train): """Creates transformer model.""" encdec_kwargs = dict( num_layers=params["num_hidden_layers"], num_attention_heads=params["num_heads"], intermediate_size=params["filter_size"], activation="relu", dropout_rate=params["relu_dropout"], attention_dropout_rate=params["attention_dropout"], use_bias=False, norm_first=True, norm_epsilon=1e-6, intermediate_dropout=params["relu_dropout"]) encoder_layer = models.TransformerEncoder(**encdec_kwargs) decoder_layer = models.TransformerDecoder(**encdec_kwargs) model_kwargs = dict( vocab_size=params["vocab_size"], embedding_width=params["hidden_size"], dropout_rate=params["layer_postprocess_dropout"], padded_decode=params["padded_decode"], decode_max_length=params["decode_max_length"], dtype=params["dtype"], extra_decode_length=params["extra_decode_length"], beam_size=params["beam_size"], alpha=params["alpha"], encoder_layer=encoder_layer, decoder_layer=decoder_layer, name="transformer_v2") if is_train: inputs = tf.keras.layers.Input((None,), dtype="int64", name="inputs") targets = tf.keras.layers.Input((None,), dtype="int64", name="targets") internal_model = models.Seq2SeqTransformer(**model_kwargs) logits = internal_model( dict(inputs=inputs, targets=targets), training=is_train) vocab_size = params["vocab_size"] label_smoothing = params["label_smoothing"] if params["enable_metrics_in_training"]: logits = metrics.MetricLayer(vocab_size)([logits, targets]) logits = tf.keras.layers.Lambda( lambda x: x, name="logits", dtype=tf.float32)( logits) model = tf.keras.Model([inputs, targets], logits) loss = metrics.transformer_loss(logits, targets, label_smoothing, vocab_size) model.add_loss(loss) return model batch_size = params["decode_batch_size"] if params["padded_decode"] else None inputs = tf.keras.layers.Input((None,), batch_size=batch_size, dtype="int64", name="inputs") internal_model = models.Seq2SeqTransformer(**model_kwargs) ret = internal_model(dict(inputs=inputs), training=is_train) outputs, scores = ret["outputs"], ret["scores"] return tf.keras.Model(inputs, [outputs, scores]) class TransformerForwardTest(tf.test.TestCase): def setUp(self): super(TransformerForwardTest, self).setUp() self.params = params = model_params.TINY_PARAMS params["batch_size"] = params["default_batch_size"] = 16 params["hidden_size"] = 12 params["num_hidden_layers"] = 3 params["filter_size"] = 14 params["num_heads"] = 2 params["vocab_size"] = 41 params["extra_decode_length"] = 0 params["beam_size"] = 3 params["dtype"] = tf.float32 params["layer_postprocess_dropout"] = 0.0 params["attention_dropout"] = 0.0 params["relu_dropout"] = 0.0 def test_forward_pass_train(self): # Set input_len different from target_len inputs = np.asarray([[5, 2, 1], [7, 5, 0], [1, 4, 0], [7, 5, 11]]) targets = np.asarray([[4, 3, 4, 0], [13, 19, 17, 8], [20, 14, 1, 2], [5, 7, 3, 0]]) # src_model is the original model before refactored. src_model = transformer.create_model(self.params, True) src_num_weights = _count_params(src_model) src_weights = src_model.get_weights() src_model_output = src_model([inputs, targets], training=True) # dest_model is the refactored model. dest_model = _create_model(self.params, True) dest_num_weights = _count_params(dest_model) self.assertEqual(src_num_weights, dest_num_weights) dest_model.set_weights(src_weights) dest_model_output = dest_model([inputs, targets], training=True) self.assertAllEqual(src_model_output, dest_model_output) def test_forward_pass_not_train(self): inputs = np.asarray([[5, 2, 1], [7, 5, 0], [1, 4, 0], [7, 5, 11]]) # src_model is the original model before refactored. src_model = transformer.create_model(self.params, False) src_num_weights = _count_params(src_model) src_weights = src_model.get_weights() src_model_output = src_model([inputs], training=False) # dest_model is the refactored model. dest_model = _create_model(self.params, False) dest_num_weights = _count_params(dest_model) self.assertEqual(src_num_weights, dest_num_weights) dest_model.set_weights(src_weights) dest_model_output = dest_model([inputs], training=False) self.assertAllEqual(src_model_output[0], dest_model_output[0]) self.assertAllEqual(src_model_output[1], dest_model_output[1]) if __name__ == "__main__": tf.test.main()
6,060
37.605096
79
py
models
models-master/official/legacy/transformer/misc.py
# Copyright 2023 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. """Misc for Transformer.""" # pylint: disable=g-bad-import-order from absl import flags import tensorflow as tf from official.legacy.transformer import model_params from official.utils.flags import core as flags_core from official.utils.misc import keras_utils FLAGS = flags.FLAGS PARAMS_MAP = { 'tiny': model_params.TINY_PARAMS, 'base': model_params.BASE_PARAMS, 'big': model_params.BIG_PARAMS, } def get_model_params(param_set, num_gpus): """Gets predefined model params.""" if num_gpus > 1: if param_set == 'big': return model_params.BIG_MULTI_GPU_PARAMS.copy() elif param_set == 'base': return model_params.BASE_MULTI_GPU_PARAMS.copy() else: raise ValueError('Not valid params: param_set={} num_gpus={}'.format( param_set, num_gpus)) return PARAMS_MAP[param_set].copy() def define_transformer_flags(): """Add flags and flag validators for running transformer_main.""" # Add common flags (data_dir, model_dir, etc.). flags_core.define_base(num_gpu=True, distribution_strategy=True) flags_core.define_performance( num_parallel_calls=True, inter_op=False, intra_op=False, synthetic_data=True, max_train_steps=False, dtype=True, loss_scale=True, all_reduce_alg=True, num_packs=True, tf_gpu_thread_mode=True, datasets_num_private_threads=True, enable_xla=True, fp16_implementation=True) flags_core.define_benchmark() flags_core.define_device(tpu=True) flags.DEFINE_integer( name='train_steps', short_name='ts', default=300000, help=flags_core.help_wrap('The number of steps used to train.')) flags.DEFINE_integer( name='steps_between_evals', short_name='sbe', default=5000, help=flags_core.help_wrap( 'The Number of training steps to run between evaluations. This is ' 'used if --train_steps is defined.')) flags.DEFINE_boolean( name='enable_time_history', default=True, help='Whether to enable TimeHistory callback.') flags.DEFINE_boolean( name='enable_tensorboard', default=False, help='Whether to enable Tensorboard callback.') flags.DEFINE_boolean( name='enable_metrics_in_training', default=False, help='Whether to enable metrics during training.') flags.DEFINE_boolean( name='enable_mlir_bridge', default=False, help='Whether to enable the TF to XLA bridge.') # Set flags from the flags_core module as 'key flags' so they're listed when # the '-h' flag is used. Without this line, the flags defined above are # only shown in the full `--helpful` help text. flags.adopt_module_key_flags(flags_core) # Add transformer-specific flags flags.DEFINE_enum( name='param_set', short_name='mp', default='big', enum_values=PARAMS_MAP.keys(), help=flags_core.help_wrap( 'Parameter set to use when creating and training the model. The ' 'parameters define the input shape (batch size and max length), ' 'model configuration (size of embedding, # of hidden layers, etc.), ' 'and various other settings. The big parameter set increases the ' 'default batch size, embedding/hidden size, and filter size. For a ' 'complete list of parameters, please see model/model_params.py.')) flags.DEFINE_bool( name='static_batch', short_name='sb', default=False, help=flags_core.help_wrap( 'Whether the batches in the dataset should have static shapes. In ' 'general, this setting should be False. Dynamic shapes allow the ' 'inputs to be grouped so that the number of padding tokens is ' 'minimized, and helps model training. In cases where the input shape ' 'must be static (e.g. running on TPU), this setting will be ignored ' 'and static batching will always be used.')) flags.DEFINE_integer( name='max_length', short_name='ml', default=256, help=flags_core.help_wrap( 'Max sentence length for Transformer. Default is 256. Note: Usually ' 'it is more effective to use a smaller max length if static_batch is ' 'enabled, e.g. 64.')) # Flags for training with steps (may be used for debugging) flags.DEFINE_integer( name='validation_steps', short_name='vs', default=64, help=flags_core.help_wrap('The number of steps used in validation.')) # BLEU score computation flags.DEFINE_string( name='bleu_source', short_name='bls', default=None, help=flags_core.help_wrap( 'Path to source file containing text translate when calculating the ' 'official BLEU score. Both --bleu_source and --bleu_ref must be set. ' )) flags.DEFINE_string( name='bleu_ref', short_name='blr', default=None, help=flags_core.help_wrap( 'Path to source file containing text translate when calculating the ' 'official BLEU score. Both --bleu_source and --bleu_ref must be set. ' )) flags.DEFINE_string( name='vocab_file', short_name='vf', default=None, help=flags_core.help_wrap( 'Path to subtoken vocabulary file. If data_download.py was used to ' 'download and encode the training data, look in the data_dir to find ' 'the vocab file.')) flags.DEFINE_string( name='mode', default='train', help=flags_core.help_wrap('mode: train, eval, or predict')) flags.DEFINE_bool( name='use_ctl', default=False, help=flags_core.help_wrap( 'Whether the model runs with custom training loop.')) flags.DEFINE_integer( name='decode_batch_size', default=32, help=flags_core.help_wrap( 'Global batch size used for Transformer autoregressive decoding on ' 'TPU.')) flags.DEFINE_integer( name='decode_max_length', default=97, help=flags_core.help_wrap( 'Max sequence length of the decode/eval data. This is used by ' 'Transformer autoregressive decoding on TPU to have minimum ' 'paddings.')) flags.DEFINE_bool( name='padded_decode', default=False, help=flags_core.help_wrap( 'Whether the autoregressive decoding runs with input data padded to ' 'the decode_max_length. For TPU/XLA-GPU runs, this flag has to be ' 'set due the static shape requirement. Although CPU/GPU could also ' 'use padded_decode, it has not been tested. In addition, this method ' 'will introduce unnecessary overheads which grow quadratically with ' 'the max sequence length.')) flags.DEFINE_bool( name='enable_checkpointing', default=True, help=flags_core.help_wrap( 'Whether to do checkpointing during training. When running under ' 'benchmark harness, we will avoid checkpointing.')) flags.DEFINE_bool( name='save_weights_only', default=True, help=flags_core.help_wrap( 'Only used when above `enable_checkpointing` is True. ' 'If True, then only the model\'s weights will be saved ' '(`model.save_weights(filepath)`), else the full model is saved ' '(`model.save(filepath)`)')) flags_core.set_defaults( data_dir='/tmp/translate_ende', model_dir='/tmp/transformer_model', batch_size=None) # pylint: disable=unused-variable @flags.multi_flags_validator( ['bleu_source', 'bleu_ref'], message='Both or neither --bleu_source and --bleu_ref must be defined.') def _check_bleu_files(flags_dict): return (flags_dict['bleu_source'] is None) == ( flags_dict['bleu_ref'] is None) @flags.multi_flags_validator( ['bleu_source', 'bleu_ref', 'vocab_file'], message='--vocab_file must be defined if --bleu_source and --bleu_ref ' 'are defined.') def _check_bleu_vocab_file(flags_dict): if flags_dict['bleu_source'] and flags_dict['bleu_ref']: return flags_dict['vocab_file'] is not None return True # pylint: enable=unused-variable def get_callbacks(): """Returns common callbacks.""" callbacks = [] if FLAGS.enable_time_history: time_callback = keras_utils.TimeHistory( FLAGS.batch_size, FLAGS.log_steps, logdir=FLAGS.model_dir if FLAGS.enable_tensorboard else None) callbacks.append(time_callback) if FLAGS.enable_tensorboard: tensorboard_callback = tf.keras.callbacks.TensorBoard( log_dir=FLAGS.model_dir) callbacks.append(tensorboard_callback) return callbacks def update_stats(history, stats, callbacks): """Normalizes and updates dictionary of stats. Args: history: Results of the training step. stats: Dict with pre-existing training stats. callbacks: a list of callbacks which might include a time history callback used during keras.fit. """ if history and history.history: train_hist = history.history # Gets final loss from training. stats['loss'] = float(train_hist['loss'][-1]) if not callbacks: return # Look for the time history callback which was used during keras.fit for callback in callbacks: if isinstance(callback, keras_utils.TimeHistory): timestamp_log = callback.timestamp_log stats['step_timestamp_log'] = timestamp_log stats['train_finish_time'] = callback.train_finish_time if len(timestamp_log) > 1: stats['avg_exp_per_second'] = ( callback.batch_size * callback.log_steps * (len(callback.timestamp_log) - 1) / (timestamp_log[-1].timestamp - timestamp_log[0].timestamp))
10,346
34.802768
80
py
models
models-master/official/legacy/transformer/translate.py
# Copyright 2023 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. """Translate text or files using trained transformer model.""" # Import libraries from absl import logging import numpy as np import tensorflow as tf from official.legacy.transformer.utils import tokenizer _EXTRA_DECODE_LENGTH = 100 _BEAM_SIZE = 4 _ALPHA = 0.6 def _get_sorted_inputs(filename): """Read and sort lines from the file sorted by decreasing length. Args: filename: String name of file to read inputs from. Returns: Sorted list of inputs, and dictionary mapping original index->sorted index of each element. """ with tf.io.gfile.GFile(filename) as f: records = f.read().split("\n") inputs = [record.strip() for record in records] if not inputs[-1]: inputs.pop() input_lens = [(i, len(line.split())) for i, line in enumerate(inputs)] sorted_input_lens = sorted(input_lens, key=lambda x: x[1], reverse=True) sorted_inputs = [None] * len(sorted_input_lens) sorted_keys = [0] * len(sorted_input_lens) for i, (index, _) in enumerate(sorted_input_lens): sorted_inputs[i] = inputs[index] sorted_keys[index] = i return sorted_inputs, sorted_keys def _encode_and_add_eos(line, subtokenizer): """Encode line with subtokenizer, and add EOS id to the end.""" return subtokenizer.encode(line) + [tokenizer.EOS_ID] def _trim_and_decode(ids, subtokenizer): """Trim EOS and PAD tokens from ids, and decode to return a string.""" try: index = list(ids).index(tokenizer.EOS_ID) return subtokenizer.decode(ids[:index]) except ValueError: # No EOS found in sequence return subtokenizer.decode(ids) def translate_file(model, params, subtokenizer, input_file, output_file=None, print_all_translations=True, distribution_strategy=None): """Translate lines in file, and save to output file if specified. Args: model: A Keras model, used to generate the translations. params: A dictionary, containing the translation related parameters. subtokenizer: A subtokenizer object, used for encoding and decoding source and translated lines. input_file: A file containing lines to translate. output_file: A file that stores the generated translations. print_all_translations: A bool. If true, all translations are printed to stdout. distribution_strategy: A distribution strategy, used to perform inference directly with tf.function instead of Keras model.predict(). Raises: ValueError: if output file is invalid. """ batch_size = params["decode_batch_size"] # Read and sort inputs by length. Keep dictionary (original index-->new index # in sorted list) to write translations in the original order. sorted_inputs, sorted_keys = _get_sorted_inputs(input_file) total_samples = len(sorted_inputs) num_decode_batches = (total_samples - 1) // batch_size + 1 def input_generator(): """Yield encoded strings from sorted_inputs.""" for i in range(num_decode_batches): lines = [ sorted_inputs[j + i * batch_size] for j in range(batch_size) if j + i * batch_size < total_samples ] lines = [_encode_and_add_eos(l, subtokenizer) for l in lines] if distribution_strategy: for j in range(batch_size - len(lines)): lines.append([tokenizer.EOS_ID]) batch = tf.keras.preprocessing.sequence.pad_sequences( lines, maxlen=params["decode_max_length"], dtype="int32", padding="post") logging.info("Decoding batch %d out of %d.", i, num_decode_batches) yield batch @tf.function def predict_step(inputs): """Decoding step function for TPU runs.""" def _step_fn(inputs): """Per replica step function.""" tag = inputs[0] val_inputs = inputs[1] val_outputs, _ = model([val_inputs], training=False) return tag, val_outputs return distribution_strategy.run(_step_fn, args=(inputs,)) translations = [] if distribution_strategy: num_replicas = distribution_strategy.num_replicas_in_sync local_batch_size = params["decode_batch_size"] // num_replicas for i, text in enumerate(input_generator()): if distribution_strategy: text = np.reshape(text, [num_replicas, local_batch_size, -1]) # Add tag to the input of each replica with the reordering logic after # outputs, to ensure the output order matches the input order. text = tf.constant(text) @tf.function def text_as_per_replica(): replica_context = tf.distribute.get_replica_context() replica_id = replica_context.replica_id_in_sync_group return replica_id, text[replica_id] # pylint: disable=cell-var-from-loop text = distribution_strategy.run(text_as_per_replica) outputs = distribution_strategy.experimental_local_results( predict_step(text)) val_outputs = [output for _, output in outputs] val_outputs = np.reshape(val_outputs, [params["decode_batch_size"], -1]) else: val_outputs, _ = model.predict(text) length = len(val_outputs) for j in range(length): if j + i * batch_size < total_samples: translation = _trim_and_decode(val_outputs[j], subtokenizer) translations.append(translation) if print_all_translations: logging.info("Translating:\n\tInput: %s\n\tOutput: %s", sorted_inputs[j + i * batch_size], translation) # Write translations in the order they appeared in the original file. if output_file is not None: if tf.io.gfile.isdir(output_file): raise ValueError("File output is a directory, will not save outputs to " "file.") logging.info("Writing to file %s", output_file) with tf.io.gfile.GFile(output_file, "w") as f: for i in sorted_keys: f.write("%s\n" % translations[i]) def translate_from_text(model, subtokenizer, txt): encoded_txt = _encode_and_add_eos(txt, subtokenizer) result = model.predict(encoded_txt) outputs = result["outputs"] logging.info("Original: \"%s\"", txt) translate_from_input(outputs, subtokenizer) def translate_from_input(outputs, subtokenizer): translation = _trim_and_decode(outputs, subtokenizer) logging.info("Translation: \"%s\"", translation)
6,951
35.397906
81
py
models
models-master/official/legacy/transformer/embedding_layer.py
# Copyright 2023 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. """Implementation of embedding layer with shared weights.""" import tensorflow as tf class EmbeddingSharedWeights(tf.keras.layers.Layer): """Calculates input embeddings and pre-softmax linear with shared weights.""" def __init__(self, vocab_size, hidden_size): """Specify characteristic parameters of embedding layer. Args: vocab_size: Number of tokens in the embedding. (Typically ~32,000) hidden_size: Dimensionality of the embedding. (Typically 512 or 1024) """ super(EmbeddingSharedWeights, self).__init__() self.vocab_size = vocab_size self.hidden_size = hidden_size def build(self, input_shape): """Build embedding layer.""" with tf.name_scope("embedding_and_softmax"): # Create and initialize weights. The random normal initializer was chosen # arbitrarily, and works well. self.shared_weights = self.add_weight( "weights", shape=[self.vocab_size, self.hidden_size], dtype=tf.float32, initializer=tf.random_normal_initializer( mean=0., stddev=self.hidden_size**-0.5)) super(EmbeddingSharedWeights, self).build(input_shape) def get_config(self): return { "vocab_size": self.vocab_size, "hidden_size": self.hidden_size, } def call(self, inputs, mode="embedding"): """Get token embeddings of inputs. Args: inputs: An int64 tensor with shape [batch_size, length] mode: string, a valid value is one of "embedding" and "linear". Returns: outputs: (1) If mode == "embedding", output embedding tensor, float32 with shape [batch_size, length, embedding_size]; (2) mode == "linear", output linear tensor, float32 with shape [batch_size, length, vocab_size]. Raises: ValueError: if mode is not valid. """ if mode == "embedding": return self._embedding(inputs) elif mode == "linear": return self._linear(inputs) else: raise ValueError("mode {} is not valid.".format(mode)) def _embedding(self, inputs): """Applies embedding based on inputs tensor.""" with tf.name_scope("embedding"): # Create binary mask of size [batch_size, length] embeddings = tf.gather(self.shared_weights, inputs) # mask = tf.cast(tf.not_equal(inputs, 0), embeddings.dtype) # embeddings *= tf.expand_dims(mask, -1) # Scale embedding by the sqrt of the hidden size embeddings *= self.hidden_size**0.5 return embeddings def _linear(self, inputs): """Computes logits by running inputs through a linear layer. Args: inputs: A float32 tensor with shape [batch_size, length, hidden_size] Returns: float32 tensor with shape [batch_size, length, vocab_size]. """ with tf.name_scope("presoftmax_linear"): batch_size = tf.shape(inputs)[0] length = tf.shape(inputs)[1] x = tf.reshape(inputs, [-1, self.hidden_size]) logits = tf.matmul(x, self.shared_weights, transpose_b=True) return tf.reshape(logits, [batch_size, length, self.vocab_size])
3,684
34.776699
80
py
models
models-master/official/legacy/transformer/ffn_layer.py
# Copyright 2023 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. """Implementation of fully connected network.""" import tensorflow as tf class FeedForwardNetwork(tf.keras.layers.Layer): """Fully connected feedforward network.""" def __init__(self, hidden_size, filter_size, relu_dropout): """Initialize FeedForwardNetwork. Args: hidden_size: int, output dim of hidden layer. filter_size: int, filter size for the inner (first) dense layer. relu_dropout: float, dropout rate for training. """ super(FeedForwardNetwork, self).__init__() self.hidden_size = hidden_size self.filter_size = filter_size self.relu_dropout = relu_dropout def build(self, input_shape): self.filter_dense_layer = tf.keras.layers.Dense( self.filter_size, use_bias=True, activation=tf.nn.relu, name="filter_layer") self.output_dense_layer = tf.keras.layers.Dense( self.hidden_size, use_bias=True, name="output_layer") super(FeedForwardNetwork, self).build(input_shape) def get_config(self): return { "hidden_size": self.hidden_size, "filter_size": self.filter_size, "relu_dropout": self.relu_dropout, } def call(self, x, training): """Return outputs of the feedforward network. Args: x: tensor with shape [batch_size, length, hidden_size] training: boolean, whether in training mode or not. Returns: Output of the feedforward network. tensor with shape [batch_size, length, hidden_size] """ # Retrieve dynamically known shapes output = self.filter_dense_layer(x) if training: output = tf.nn.dropout(output, rate=self.relu_dropout) output = self.output_dense_layer(output) return output
2,320
31.236111
74
py
models
models-master/official/legacy/transformer/transformer_layers_test.py
# Copyright 2023 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. """Tests for layers in Transformer.""" import tensorflow as tf from official.legacy.transformer import attention_layer from official.legacy.transformer import embedding_layer from official.legacy.transformer import ffn_layer from official.legacy.transformer import metrics class TransformerLayersTest(tf.test.TestCase): def test_attention_layer(self): hidden_size = 64 num_heads = 4 dropout = 0.5 dim_per_head = hidden_size // num_heads layer = attention_layer.SelfAttention(hidden_size, num_heads, dropout) self.assertDictEqual( layer.get_config(), { "hidden_size": hidden_size, "num_heads": num_heads, "attention_dropout": dropout, }) length = 2 x = tf.ones([1, length, hidden_size]) bias = tf.ones([1]) cache = { "k": tf.zeros([1, 0, num_heads, dim_per_head]), "v": tf.zeros([1, 0, num_heads, dim_per_head]), } y = layer(x, bias, training=True, cache=cache) self.assertEqual(y.shape, ( 1, length, 64, )) self.assertEqual(cache["k"].shape, ( 1, length, num_heads, dim_per_head, )) self.assertEqual(cache["v"].shape, ( 1, length, num_heads, dim_per_head, )) def test_embedding_shared_weights(self): vocab_size = 50 hidden_size = 64 length = 2 layer = embedding_layer.EmbeddingSharedWeights(vocab_size, hidden_size) self.assertDictEqual(layer.get_config(), { "vocab_size": 50, "hidden_size": 64, }) idx = tf.ones([1, length], dtype="int32") y = layer(idx) self.assertEqual(y.shape, ( 1, length, hidden_size, )) x = tf.ones([1, length, hidden_size]) output = layer(x, "linear") self.assertEqual(output.shape, ( 1, length, vocab_size, )) def test_feed_forward_network(self): hidden_size = 64 filter_size = 32 relu_dropout = 0.5 layer = ffn_layer.FeedForwardNetwork(hidden_size, filter_size, relu_dropout) self.assertDictEqual( layer.get_config(), { "hidden_size": hidden_size, "filter_size": filter_size, "relu_dropout": relu_dropout, }) length = 2 x = tf.ones([1, length, hidden_size]) y = layer(x, training=True) self.assertEqual(y.shape, ( 1, length, hidden_size, )) def test_metric_layer(self): vocab_size = 50 logits = tf.keras.layers.Input((None, vocab_size), dtype="float32", name="logits") targets = tf.keras.layers.Input((None,), dtype="int64", name="targets") output_logits = metrics.MetricLayer(vocab_size)([logits, targets]) self.assertEqual(output_logits.shape.as_list(), [ None, None, vocab_size, ]) if __name__ == "__main__": tf.test.main()
3,566
27.309524
80
py
models
models-master/official/legacy/transformer/transformer.py
# Copyright 2023 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. """Defines the Transformer model in TF 2.0. Model paper: https://arxiv.org/pdf/1706.03762.pdf Transformer model code source: https://github.com/tensorflow/tensor2tensor """ import tensorflow as tf from official.legacy.transformer import attention_layer from official.legacy.transformer import embedding_layer from official.legacy.transformer import ffn_layer from official.legacy.transformer import metrics from official.legacy.transformer import model_utils from official.legacy.transformer.utils.tokenizer import EOS_ID from official.nlp.modeling.layers import position_embedding from official.nlp.modeling.ops import beam_search # Disable the not-callable lint error, since it claims many objects are not # callable when they actually are. # pylint: disable=not-callable def create_model(params, is_train): """Creates transformer model.""" with tf.name_scope("model"): if is_train: inputs = tf.keras.layers.Input((None,), dtype="int64", name="inputs") targets = tf.keras.layers.Input((None,), dtype="int64", name="targets") internal_model = Transformer(params, name="transformer_v2") logits = internal_model([inputs, targets], training=is_train) vocab_size = params["vocab_size"] label_smoothing = params["label_smoothing"] if params["enable_metrics_in_training"]: logits = metrics.MetricLayer(vocab_size)([logits, targets]) logits = tf.keras.layers.Lambda( lambda x: x, name="logits", dtype=tf.float32)( logits) model = tf.keras.Model([inputs, targets], logits) loss = metrics.transformer_loss(logits, targets, label_smoothing, vocab_size) model.add_loss(loss) return model else: inputs = tf.keras.layers.Input((None,), dtype="int64", name="inputs") internal_model = Transformer(params, name="transformer_v2") ret = internal_model([inputs], training=is_train) outputs, scores = ret["outputs"], ret["scores"] return tf.keras.Model(inputs, [outputs, scores]) class Transformer(tf.keras.Model): """Transformer model with Keras. Implemented as described in: https://arxiv.org/pdf/1706.03762.pdf The Transformer model consists of an encoder and decoder. The input is an int sequence (or a batch of sequences). The encoder produces a continuous representation, and the decoder uses the encoder output to generate probabilities for the output sequence. """ def __init__(self, params, name=None): """Initialize layers to build Transformer model. Args: params: hyperparameter object defining layer sizes, dropout values, etc. name: name of the model. """ super(Transformer, self).__init__(name=name) self.params = params self.embedding_softmax_layer = embedding_layer.EmbeddingSharedWeights( params["vocab_size"], params["hidden_size"]) self.encoder_stack = EncoderStack(params) self.decoder_stack = DecoderStack(params) self.position_embedding = position_embedding.RelativePositionEmbedding( hidden_size=self.params["hidden_size"]) def get_config(self): return { "params": self.params, } def call(self, inputs, training): """Calculate target logits or inferred target sequences. Args: inputs: input tensor list of size 1 or 2. First item, inputs: int tensor with shape [batch_size, input_length]. Second item (optional), targets: None or int tensor with shape [batch_size, target_length]. training: boolean, whether in training mode or not. Returns: If targets is defined, then return logits for each word in the target sequence. float tensor with shape [batch_size, target_length, vocab_size] If target is none, then generate output sequence one token at a time. returns a dictionary { outputs: int tensor with shape [batch_size, decoded_length] scores: float tensor with shape [batch_size]} Even when float16 is used, the output tensor(s) are always float32. Raises: NotImplementedError: If try to use padded decode method on CPU/GPUs. """ inputs = inputs if isinstance(inputs, list) else [inputs] if len(inputs) == 2: inputs, targets = inputs[0], inputs[1] else: # Decoding path. inputs, targets = inputs[0], None if self.params["padded_decode"]: if not self.params["num_replicas"]: raise NotImplementedError( "Padded decoding on CPU/GPUs is not supported.") decode_batch_size = int(self.params["decode_batch_size"] / self.params["num_replicas"]) inputs.set_shape([decode_batch_size, self.params["decode_max_length"]]) # Variance scaling is used here because it seems to work in many problems. # Other reasonable initializers may also work just as well. with tf.name_scope("Transformer"): # Calculate attention bias for encoder self-attention and decoder # multi-headed attention layers. attention_bias = model_utils.get_padding_bias(inputs) # Run the inputs through the encoder layer to map the symbol # representations to continuous representations. encoder_outputs = self.encode(inputs, attention_bias, training) # Generate output sequence if targets is None, or return logits if target # sequence is known. if targets is None: return self.predict(encoder_outputs, attention_bias, training) else: logits = self.decode(targets, encoder_outputs, attention_bias, training) return logits def encode(self, inputs, attention_bias, training): """Generate continuous representation for inputs. Args: inputs: int tensor with shape [batch_size, input_length]. attention_bias: float tensor with shape [batch_size, 1, 1, input_length]. training: boolean, whether in training mode or not. Returns: float tensor with shape [batch_size, input_length, hidden_size] """ with tf.name_scope("encode"): # Prepare inputs to the layer stack by adding positional encodings and # applying dropout. embedded_inputs = self.embedding_softmax_layer(inputs) embedded_inputs = tf.cast(embedded_inputs, self.params["dtype"]) inputs_padding = model_utils.get_padding(inputs) attention_bias = tf.cast(attention_bias, self.params["dtype"]) with tf.name_scope("add_pos_encoding"): pos_encoding = self.position_embedding(inputs=embedded_inputs) pos_encoding = tf.cast(pos_encoding, self.params["dtype"]) encoder_inputs = embedded_inputs + pos_encoding if training: encoder_inputs = tf.nn.dropout( encoder_inputs, rate=self.params["layer_postprocess_dropout"]) return self.encoder_stack( encoder_inputs, attention_bias, inputs_padding, training=training) def decode(self, targets, encoder_outputs, attention_bias, training): """Generate logits for each value in the target sequence. Args: targets: target values for the output sequence. int tensor with shape [batch_size, target_length] encoder_outputs: continuous representation of input sequence. float tensor with shape [batch_size, input_length, hidden_size] attention_bias: float tensor with shape [batch_size, 1, 1, input_length] training: boolean, whether in training mode or not. Returns: float32 tensor with shape [batch_size, target_length, vocab_size] """ with tf.name_scope("decode"): # Prepare inputs to decoder layers by shifting targets, adding positional # encoding and applying dropout. with tf.name_scope("shift_targets"): # Shift targets to the right, and remove the last element targets = tf.pad(targets, [[0, 0], [1, 0]])[:, :-1] decoder_inputs = self.embedding_softmax_layer(targets) decoder_inputs = tf.cast(decoder_inputs, self.params["dtype"]) attention_bias = tf.cast(attention_bias, self.params["dtype"]) with tf.name_scope("add_pos_encoding"): length = tf.shape(decoder_inputs)[1] pos_encoding = self.position_embedding(decoder_inputs) pos_encoding = tf.cast(pos_encoding, self.params["dtype"]) decoder_inputs += pos_encoding if training: decoder_inputs = tf.nn.dropout( decoder_inputs, rate=self.params["layer_postprocess_dropout"]) # Run values decoder_self_attention_bias = model_utils.get_decoder_self_attention_bias( length, dtype=self.params["dtype"]) outputs = self.decoder_stack( decoder_inputs, encoder_outputs, decoder_self_attention_bias, attention_bias, training=training) logits = self.embedding_softmax_layer(outputs, mode="linear") logits = tf.cast(logits, tf.float32) return logits def _get_symbols_to_logits_fn(self, max_decode_length, training): """Returns a decoding function that calculates logits of the next tokens.""" timing_signal = self.position_embedding( inputs=None, length=max_decode_length + 1) timing_signal = tf.cast(timing_signal, self.params["dtype"]) decoder_self_attention_bias = model_utils.get_decoder_self_attention_bias( max_decode_length, dtype=self.params["dtype"]) def symbols_to_logits_fn(ids, i, cache): """Generate logits for next potential IDs. Args: ids: Current decoded sequences. int tensor with shape [batch_size * beam_size, i + 1]. i: Loop index. cache: dictionary of values storing the encoder output, encoder-decoder attention bias, and previous decoder attention values. Returns: Tuple of (logits with shape [batch_size * beam_size, vocab_size], updated cache values) """ # Set decoder input to the last generated IDs decoder_input = ids[:, -1:] # Preprocess decoder input by getting embeddings and adding timing signal. decoder_input = self.embedding_softmax_layer(decoder_input) decoder_input += timing_signal[i] if self.params["padded_decode"]: bias_shape = decoder_self_attention_bias.shape.as_list() self_attention_bias = tf.slice( decoder_self_attention_bias, [0, 0, i, 0], [bias_shape[0], bias_shape[1], 1, bias_shape[3]]) else: self_attention_bias = decoder_self_attention_bias[:, :, i:i + 1, :i + 1] decoder_outputs = self.decoder_stack( decoder_input, cache.get("encoder_outputs"), self_attention_bias, cache.get("encoder_decoder_attention_bias"), training=training, cache=cache, decode_loop_step=i if self.params["padded_decode"] else None) logits = self.embedding_softmax_layer(decoder_outputs, mode="linear") logits = tf.squeeze(logits, axis=[1]) return logits, cache return symbols_to_logits_fn def predict(self, encoder_outputs, encoder_decoder_attention_bias, training): """Return predicted sequence.""" encoder_outputs = tf.cast(encoder_outputs, self.params["dtype"]) if self.params["padded_decode"]: batch_size = encoder_outputs.shape.as_list()[0] input_length = encoder_outputs.shape.as_list()[1] else: batch_size = tf.shape(encoder_outputs)[0] input_length = tf.shape(encoder_outputs)[1] max_decode_length = input_length + self.params["extra_decode_length"] encoder_decoder_attention_bias = tf.cast(encoder_decoder_attention_bias, self.params["dtype"]) symbols_to_logits_fn = self._get_symbols_to_logits_fn( max_decode_length, training) # Create initial set of IDs that will be passed into symbols_to_logits_fn. initial_ids = tf.zeros([batch_size], dtype=tf.int32) # Create cache storing decoder attention values for each layer. # pylint: disable=g-complex-comprehension init_decode_length = ( max_decode_length if self.params["padded_decode"] else 0) num_heads = self.params["num_heads"] dim_per_head = self.params["hidden_size"] // num_heads cache = { "layer_%d" % layer: { "k": tf.zeros( [batch_size, init_decode_length, num_heads, dim_per_head], dtype=self.params["dtype"]), "v": tf.zeros( [batch_size, init_decode_length, num_heads, dim_per_head], dtype=self.params["dtype"]) } for layer in range(self.params["num_hidden_layers"]) } # pylint: enable=g-complex-comprehension # Add encoder output and attention bias to the cache. cache["encoder_outputs"] = encoder_outputs cache["encoder_decoder_attention_bias"] = encoder_decoder_attention_bias # Use beam search to find the top beam_size sequences and scores. decoded_ids, scores = beam_search.sequence_beam_search( symbols_to_logits_fn=symbols_to_logits_fn, initial_ids=initial_ids, initial_cache=cache, vocab_size=self.params["vocab_size"], beam_size=self.params["beam_size"], alpha=self.params["alpha"], max_decode_length=max_decode_length, eos_id=EOS_ID, padded_decode=self.params["padded_decode"], dtype=self.params["dtype"]) # Get the top sequence for each batch element top_decoded_ids = decoded_ids[:, 0, 1:] top_scores = scores[:, 0] return {"outputs": top_decoded_ids, "scores": top_scores} class PrePostProcessingWrapper(tf.keras.layers.Layer): """Wrapper class that applies layer pre-processing and post-processing.""" def __init__(self, layer, params): super(PrePostProcessingWrapper, self).__init__() self.layer = layer self.params = params self.postprocess_dropout = params["layer_postprocess_dropout"] def build(self, input_shape): # Create normalization layer self.layer_norm = tf.keras.layers.LayerNormalization( epsilon=1e-6, dtype="float32") super(PrePostProcessingWrapper, self).build(input_shape) def get_config(self): return { "params": self.params, } def call(self, x, *args, **kwargs): """Calls wrapped layer with same parameters.""" # Preprocessing: apply layer normalization training = kwargs["training"] y = self.layer_norm(x) # Get layer output y = self.layer(y, *args, **kwargs) # Postprocessing: apply dropout and residual connection if training: y = tf.nn.dropout(y, rate=self.postprocess_dropout) return x + y class EncoderStack(tf.keras.layers.Layer): """Transformer encoder stack. The encoder stack is made up of N identical layers. Each layer is composed of the sublayers: 1. Self-attention layer 2. Feedforward network (which is 2 fully-connected layers) """ def __init__(self, params): super(EncoderStack, self).__init__() self.params = params self.layers = [] def build(self, input_shape): """Builds the encoder stack.""" params = self.params for _ in range(params["num_hidden_layers"]): # Create sublayers for each layer. self_attention_layer = attention_layer.SelfAttention( params["hidden_size"], params["num_heads"], params["attention_dropout"]) feed_forward_network = ffn_layer.FeedForwardNetwork( params["hidden_size"], params["filter_size"], params["relu_dropout"]) self.layers.append([ PrePostProcessingWrapper(self_attention_layer, params), PrePostProcessingWrapper(feed_forward_network, params) ]) # Create final layer normalization layer. self.output_normalization = tf.keras.layers.LayerNormalization( epsilon=1e-6, dtype="float32") super(EncoderStack, self).build(input_shape) def get_config(self): return { "params": self.params, } def call(self, encoder_inputs, attention_bias, inputs_padding, training): """Return the output of the encoder layer stacks. Args: encoder_inputs: tensor with shape [batch_size, input_length, hidden_size] attention_bias: bias for the encoder self-attention layer. [batch_size, 1, 1, input_length] inputs_padding: tensor with shape [batch_size, input_length], inputs with zero paddings. training: boolean, whether in training mode or not. Returns: Output of encoder layer stack. float32 tensor with shape [batch_size, input_length, hidden_size] """ for n, layer in enumerate(self.layers): # Run inputs through the sublayers. self_attention_layer = layer[0] feed_forward_network = layer[1] with tf.name_scope("layer_%d" % n): with tf.name_scope("self_attention"): encoder_inputs = self_attention_layer( encoder_inputs, attention_bias, training=training) with tf.name_scope("ffn"): encoder_inputs = feed_forward_network( encoder_inputs, training=training) return self.output_normalization(encoder_inputs) class DecoderStack(tf.keras.layers.Layer): """Transformer decoder stack. Like the encoder stack, the decoder stack is made up of N identical layers. Each layer is composed of the sublayers: 1. Self-attention layer 2. Multi-headed attention layer combining encoder outputs with results from the previous self-attention layer. 3. Feedforward network (2 fully-connected layers) """ def __init__(self, params): super(DecoderStack, self).__init__() self.params = params self.layers = [] def build(self, input_shape): """Builds the decoder stack.""" params = self.params for _ in range(params["num_hidden_layers"]): self_attention_layer = attention_layer.SelfAttention( params["hidden_size"], params["num_heads"], params["attention_dropout"]) enc_dec_attention_layer = attention_layer.Attention( params["hidden_size"], params["num_heads"], params["attention_dropout"]) feed_forward_network = ffn_layer.FeedForwardNetwork( params["hidden_size"], params["filter_size"], params["relu_dropout"]) self.layers.append([ PrePostProcessingWrapper(self_attention_layer, params), PrePostProcessingWrapper(enc_dec_attention_layer, params), PrePostProcessingWrapper(feed_forward_network, params) ]) self.output_normalization = tf.keras.layers.LayerNormalization( epsilon=1e-6, dtype="float32") super(DecoderStack, self).build(input_shape) def get_config(self): return { "params": self.params, } def call(self, decoder_inputs, encoder_outputs, decoder_self_attention_bias, attention_bias, training, cache=None, decode_loop_step=None): """Return the output of the decoder layer stacks. Args: decoder_inputs: A tensor with shape [batch_size, target_length, hidden_size]. encoder_outputs: A tensor with shape [batch_size, input_length, hidden_size] decoder_self_attention_bias: A tensor with shape [1, 1, target_len, target_length], the bias for decoder self-attention layer. attention_bias: A tensor with shape [batch_size, 1, 1, input_length], the bias for encoder-decoder attention layer. training: A bool, whether in training mode or not. cache: (Used for fast decoding) A nested dictionary storing previous decoder self-attention values. The items are: {layer_n: {"k": A tensor with shape [batch_size, i, key_channels], "v": A tensor with shape [batch_size, i, value_channels]}, ...} decode_loop_step: An integer, the step number of the decoding loop. Used only for autoregressive inference on TPU. Returns: Output of decoder layer stack. float32 tensor with shape [batch_size, target_length, hidden_size] """ for n, layer in enumerate(self.layers): self_attention_layer = layer[0] enc_dec_attention_layer = layer[1] feed_forward_network = layer[2] # Run inputs through the sublayers. layer_name = "layer_%d" % n layer_cache = cache[layer_name] if cache is not None else None with tf.name_scope(layer_name): with tf.name_scope("self_attention"): decoder_inputs = self_attention_layer( decoder_inputs, decoder_self_attention_bias, training=training, cache=layer_cache, decode_loop_step=decode_loop_step) with tf.name_scope("encdec_attention"): decoder_inputs = enc_dec_attention_layer( decoder_inputs, encoder_outputs, attention_bias, training=training) with tf.name_scope("ffn"): decoder_inputs = feed_forward_network( decoder_inputs, training=training) return self.output_normalization(decoder_inputs)
21,751
38.477314
80
py
models
models-master/official/legacy/transformer/metrics.py
# Copyright 2023 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. """Functions for calculating loss, accuracy, and other model metrics. Metrics: - Padded loss, accuracy, and negative log perplexity. Source: https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/utils/metrics.py - BLEU approximation. Source: https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/utils/bleu_hook.py - ROUGE score. Source: https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/utils/rouge.py """ import functools import tensorflow as tf def _pad_tensors_to_same_length(x, y): """Pad x and y so that the results have the same length (second dimension).""" with tf.name_scope("pad_to_same_length"): x_length = tf.shape(x)[1] y_length = tf.shape(y)[1] max_length = tf.maximum(x_length, y_length) x = tf.pad(x, [[0, 0], [0, max_length - x_length], [0, 0]]) y = tf.pad(y, [[0, 0], [0, max_length - y_length]]) return x, y def padded_cross_entropy_loss(logits, labels, smoothing, vocab_size): """Calculate cross entropy loss while ignoring padding. Args: logits: Tensor of size [batch_size, length_logits, vocab_size] labels: Tensor of size [batch_size, length_labels] smoothing: Label smoothing constant, used to determine the on and off values vocab_size: int size of the vocabulary Returns: Returns the cross entropy loss and weight tensors: float32 tensors with shape [batch_size, max(length_logits, length_labels)] """ with tf.name_scope("loss"): logits, labels = _pad_tensors_to_same_length(logits, labels) # Calculate smoothing cross entropy with tf.name_scope("smoothing_cross_entropy"): confidence = 1.0 - smoothing low_confidence = (1.0 - confidence) / tf.cast(vocab_size - 1, tf.float32) soft_targets = tf.one_hot( tf.cast(labels, tf.int32), depth=vocab_size, on_value=confidence, off_value=low_confidence) xentropy = tf.nn.softmax_cross_entropy_with_logits( logits=logits, labels=soft_targets) # Calculate the best (lowest) possible value of cross entropy, and # subtract from the cross entropy loss. normalizing_constant = -( confidence * tf.math.log(confidence) + tf.cast(vocab_size - 1, tf.float32) * low_confidence * tf.math.log(low_confidence + 1e-20)) xentropy -= normalizing_constant weights = tf.cast(tf.not_equal(labels, 0), tf.float32) return xentropy * weights, weights def padded_accuracy(logits, labels): """Percentage of times that predictions matches labels on non-0s.""" with tf.name_scope("padded_accuracy"): logits, labels = _pad_tensors_to_same_length(logits, labels) weights = tf.cast(tf.not_equal(labels, 0), tf.float32) outputs = tf.cast(tf.argmax(logits, axis=-1), tf.int32) padded_labels = tf.cast(labels, tf.int32) return tf.cast(tf.equal(outputs, padded_labels), tf.float32), weights def padded_accuracy_topk(logits, labels, k): """Percentage of times that top-k predictions matches labels on non-0s.""" with tf.name_scope("padded_accuracy_topk"): logits, labels = _pad_tensors_to_same_length(logits, labels) weights = tf.cast(tf.not_equal(labels, 0), tf.float32) effective_k = tf.minimum(k, tf.shape(logits)[-1]) _, outputs = tf.nn.top_k(logits, k=effective_k) outputs = tf.cast(outputs, tf.int32) padded_labels = tf.cast(labels, tf.int32) padded_labels = tf.expand_dims(padded_labels, axis=-1) padded_labels += tf.zeros_like(outputs) # Pad to same shape. same = tf.cast(tf.equal(outputs, padded_labels), tf.float32) same_topk = tf.reduce_sum(same, axis=-1) return same_topk, weights def padded_accuracy_top5(logits, labels): return padded_accuracy_topk(logits, labels, 5) def padded_sequence_accuracy(logits, labels): """Percentage of times that predictions matches labels everywhere (non-0).""" with tf.name_scope("padded_sequence_accuracy"): logits, labels = _pad_tensors_to_same_length(logits, labels) weights = tf.cast(tf.not_equal(labels, 0), tf.float32) outputs = tf.cast(tf.argmax(logits, axis=-1), tf.int32) padded_labels = tf.cast(labels, tf.int32) not_correct = tf.cast(tf.not_equal(outputs, padded_labels), tf.float32) * weights axis = list(range(1, len(outputs.get_shape()))) correct_seq = 1.0 - tf.minimum(1.0, tf.reduce_sum(not_correct, axis=axis)) return correct_seq, tf.constant(1.0) def padded_neg_log_perplexity(logits, labels, vocab_size): """Average log-perplexity excluding padding 0s. No smoothing.""" num, den = padded_cross_entropy_loss(logits, labels, 0, vocab_size) return -num, den class MetricLayer(tf.keras.layers.Layer): """Custom a layer of metrics for Transformer model.""" def __init__(self, vocab_size): super(MetricLayer, self).__init__() self.vocab_size = vocab_size self.metric_mean_fns = [] def build(self, input_shape): """"Builds metric layer.""" neg_log_perplexity = functools.partial( padded_neg_log_perplexity, vocab_size=self.vocab_size) self.metric_mean_fns = [ (tf.keras.metrics.Mean("accuracy"), padded_accuracy), (tf.keras.metrics.Mean("accuracy_top5"), padded_accuracy_top5), (tf.keras.metrics.Mean("accuracy_per_sequence"), padded_sequence_accuracy), (tf.keras.metrics.Mean("neg_log_perplexity"), neg_log_perplexity), ] super(MetricLayer, self).build(input_shape) def get_config(self): return {"vocab_size": self.vocab_size} def call(self, inputs): logits, targets = inputs[0], inputs[1] for mean, fn in self.metric_mean_fns: m = mean(*fn(logits, targets)) self.add_metric(m) return logits def transformer_loss(logits, labels, smoothing, vocab_size): """Calculates total loss containing cross entropy with padding ignored. Args: logits: Tensor of size [batch_size, length_logits, vocab_size] labels: Tensor of size [batch_size, length_labels] smoothing: Label smoothing constant, used to determine the on and off values vocab_size: int size of the vocabulary Returns: A scalar float tensor for loss. """ xentropy, weights = padded_cross_entropy_loss(logits, labels, smoothing, vocab_size) return tf.reduce_sum(xentropy) / tf.reduce_sum(weights)
7,007
37.718232
93
py
models
models-master/official/legacy/transformer/transformer_main.py
# Copyright 2023 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. """Train and evaluate the Transformer model. See README for description of setting the training schedule and evaluating the BLEU score. """ import os import tempfile # Import libraries from absl import app from absl import flags from absl import logging import tensorflow as tf from official.common import distribute_utils from official.legacy.transformer import compute_bleu from official.legacy.transformer import data_pipeline from official.legacy.transformer import metrics from official.legacy.transformer import misc from official.legacy.transformer import optimizer from official.legacy.transformer import transformer from official.legacy.transformer import translate from official.legacy.transformer.utils import tokenizer from official.modeling import performance from official.utils.flags import core as flags_core from official.utils.misc import keras_utils # pylint:disable=logging-format-interpolation INF = int(1e9) BLEU_DIR = "bleu" _SINGLE_SAMPLE = 1 def translate_and_compute_bleu(model, params, subtokenizer, bleu_source, bleu_ref, distribution_strategy=None): """Translate file and report the cased and uncased bleu scores. Args: model: A Keras model, used to generate the translations. params: A dictionary, containing the translation related parameters. subtokenizer: A subtokenizer object, used for encoding and decoding source and translated lines. bleu_source: A file containing source sentences for translation. bleu_ref: A file containing the reference for the translated sentences. distribution_strategy: A platform distribution strategy, used for TPU based translation. Returns: uncased_score: A float, the case insensitive BLEU score. cased_score: A float, the case sensitive BLEU score. """ # Create temporary file to store translation. tmp = tempfile.NamedTemporaryFile(delete=False) tmp_filename = tmp.name translate.translate_file( model, params, subtokenizer, bleu_source, output_file=tmp_filename, print_all_translations=False, distribution_strategy=distribution_strategy) # Compute uncased and cased bleu scores. uncased_score = compute_bleu.bleu_wrapper(bleu_ref, tmp_filename, False) cased_score = compute_bleu.bleu_wrapper(bleu_ref, tmp_filename, True) os.remove(tmp_filename) return uncased_score, cased_score def evaluate_and_log_bleu(model, params, bleu_source, bleu_ref, vocab_file, distribution_strategy=None): """Calculate and record the BLEU score. Args: model: A Keras model, used to generate the translations. params: A dictionary, containing the translation related parameters. bleu_source: A file containing source sentences for translation. bleu_ref: A file containing the reference for the translated sentences. vocab_file: A file containing the vocabulary for translation. distribution_strategy: A platform distribution strategy, used for TPU based translation. Returns: uncased_score: A float, the case insensitive BLEU score. cased_score: A float, the case sensitive BLEU score. """ subtokenizer = tokenizer.Subtokenizer(vocab_file) uncased_score, cased_score = translate_and_compute_bleu( model, params, subtokenizer, bleu_source, bleu_ref, distribution_strategy) logging.info("Bleu score (uncased): %s", uncased_score) logging.info("Bleu score (cased): %s", cased_score) return uncased_score, cased_score class TransformerTask(object): """Main entry of Transformer model.""" def __init__(self, flags_obj): """Init function of TransformerMain. Args: flags_obj: Object containing parsed flag values, i.e., FLAGS. Raises: ValueError: if not using static batch for input data on TPU. """ self.flags_obj = flags_obj self.predict_model = None # Add flag-defined parameters to params object num_gpus = flags_core.get_num_gpus(flags_obj) self.params = params = misc.get_model_params(flags_obj.param_set, num_gpus) params["num_gpus"] = num_gpus params["use_ctl"] = flags_obj.use_ctl params["data_dir"] = flags_obj.data_dir params["model_dir"] = flags_obj.model_dir params["static_batch"] = flags_obj.static_batch params["max_length"] = flags_obj.max_length params["decode_batch_size"] = flags_obj.decode_batch_size params["decode_max_length"] = flags_obj.decode_max_length params["padded_decode"] = flags_obj.padded_decode params["max_io_parallelism"] = ( flags_obj.num_parallel_calls or tf.data.experimental.AUTOTUNE) params["use_synthetic_data"] = flags_obj.use_synthetic_data params["batch_size"] = flags_obj.batch_size or params["default_batch_size"] params["repeat_dataset"] = None params["dtype"] = flags_core.get_tf_dtype(flags_obj) params["enable_tensorboard"] = flags_obj.enable_tensorboard params["enable_metrics_in_training"] = flags_obj.enable_metrics_in_training params["steps_between_evals"] = flags_obj.steps_between_evals params["enable_checkpointing"] = flags_obj.enable_checkpointing params["save_weights_only"] = flags_obj.save_weights_only self.distribution_strategy = distribute_utils.get_distribution_strategy( distribution_strategy=flags_obj.distribution_strategy, num_gpus=num_gpus, all_reduce_alg=flags_obj.all_reduce_alg, num_packs=flags_obj.num_packs, tpu_address=flags_obj.tpu or "") if self.use_tpu: params["num_replicas"] = self.distribution_strategy.num_replicas_in_sync else: logging.info("Running transformer with num_gpus = %d", num_gpus) if self.distribution_strategy: logging.info("For training, using distribution strategy: %s", self.distribution_strategy) else: logging.info("Not using any distribution strategy.") performance.set_mixed_precision_policy(params["dtype"]) @property def use_tpu(self): if self.distribution_strategy: return isinstance(self.distribution_strategy, tf.distribute.TPUStrategy) return False def train(self): """Trains the model.""" params = self.params flags_obj = self.flags_obj # Sets config options. keras_utils.set_session_config(enable_xla=flags_obj.enable_xla) _ensure_dir(flags_obj.model_dir) with distribute_utils.get_strategy_scope(self.distribution_strategy): model = transformer.create_model(params, is_train=True) opt = self._create_optimizer() current_step = 0 checkpoint = tf.train.Checkpoint(model=model, optimizer=opt) latest_checkpoint = tf.train.latest_checkpoint(flags_obj.model_dir) if latest_checkpoint: checkpoint.restore(latest_checkpoint) logging.info("Loaded checkpoint %s", latest_checkpoint) current_step = opt.iterations.numpy() if params["use_ctl"]: train_loss_metric = tf.keras.metrics.Mean( "training_loss", dtype=tf.float32) if params["enable_tensorboard"]: summary_writer = tf.summary.create_file_writer( os.path.join(flags_obj.model_dir, "summary")) else: summary_writer = tf.summary.create_noop_writer() train_metrics = [train_loss_metric] if params["enable_metrics_in_training"]: train_metrics = train_metrics + model.metrics else: model.compile(opt) model.summary() if self.use_tpu: # Different from experimental_distribute_dataset, # distribute_datasets_from_function requires # per-replica/local batch size. params["batch_size"] /= self.distribution_strategy.num_replicas_in_sync train_ds = ( self.distribution_strategy.distribute_datasets_from_function( lambda ctx: data_pipeline.train_input_fn(params, ctx))) else: train_ds = data_pipeline.train_input_fn(params) map_data_fn = data_pipeline.map_data_for_transformer_fn train_ds = train_ds.map( map_data_fn, num_parallel_calls=tf.data.experimental.AUTOTUNE) if params["use_ctl"]: train_ds_iterator = iter(train_ds) callbacks = self._create_callbacks(flags_obj.model_dir, params) # Only TimeHistory callback is supported for CTL if params["use_ctl"]: callbacks = [cb for cb in callbacks if isinstance(cb, keras_utils.TimeHistory)] @tf.function def train_steps(iterator, steps): """Training steps function for TPU runs. Args: iterator: The input iterator of the training dataset. steps: An integer, the number of training steps. Returns: A float, the loss value. """ def _step_fn(inputs): """Per-replica step function.""" inputs, targets = inputs with tf.GradientTape() as tape: logits = model([inputs, targets], training=True) loss = metrics.transformer_loss(logits, targets, params["label_smoothing"], params["vocab_size"]) # Scales the loss, which results in using the average loss across all # of the replicas for backprop. scaled_loss = loss / self.distribution_strategy.num_replicas_in_sync # De-dupes variables due to keras tracking issues. tvars = list({id(v): v for v in model.trainable_variables}.values()) grads = tape.gradient(scaled_loss, tvars) opt.apply_gradients(zip(grads, tvars)) # For reporting, the metric takes the mean of losses. train_loss_metric.update_state(loss) for _ in tf.range(steps): train_loss_metric.reset_states() self.distribution_strategy.run( _step_fn, args=(next(iterator),)) cased_score, uncased_score = None, None cased_score_history, uncased_score_history = [], [] while current_step < flags_obj.train_steps: remaining_steps = flags_obj.train_steps - current_step train_steps_per_eval = ( remaining_steps if remaining_steps < flags_obj.steps_between_evals else flags_obj.steps_between_evals) current_iteration = current_step // flags_obj.steps_between_evals logging.info( "Start train iteration at global step:{}".format(current_step)) history = None if params["use_ctl"]: if not self.use_tpu: raise NotImplementedError( "Custom training loop on GPUs is not implemented.") # Runs training steps. with summary_writer.as_default(): for cb in callbacks: cb.on_epoch_begin(current_iteration) cb.on_batch_begin(0) train_steps( train_ds_iterator, tf.convert_to_tensor(train_steps_per_eval, dtype=tf.int32)) current_step += train_steps_per_eval train_loss = train_loss_metric.result().numpy().astype(float) logging.info("Train Step: %d/%d / loss = %s", current_step, flags_obj.train_steps, train_loss) for cb in callbacks: cb.on_batch_end(train_steps_per_eval - 1) cb.on_epoch_end(current_iteration) if params["enable_tensorboard"]: for metric_obj in train_metrics: tf.summary.scalar(metric_obj.name, metric_obj.result(), current_step) summary_writer.flush() for cb in callbacks: cb.on_train_end() if flags_obj.enable_checkpointing: # avoid check-pointing when running for benchmarking. checkpoint_name = checkpoint.save( os.path.join(flags_obj.model_dir, "ctl_step_{}.ckpt".format(current_step))) logging.info("Saved checkpoint to %s", checkpoint_name) else: if self.use_tpu: raise NotImplementedError( "Keras model.fit on TPUs is not implemented.") history = model.fit( train_ds, initial_epoch=current_iteration, epochs=current_iteration + 1, steps_per_epoch=train_steps_per_eval, callbacks=callbacks, # If TimeHistory is enabled, progress bar would be messy. Increase # the verbose level to get rid of it. verbose=(2 if flags_obj.enable_time_history else 1)) current_step += train_steps_per_eval logging.info("Train history: {}".format(history.history)) logging.info("End train iteration at global step:{}".format(current_step)) if (flags_obj.bleu_source and flags_obj.bleu_ref): uncased_score, cased_score = self.eval() cased_score_history.append([current_iteration + 1, cased_score]) uncased_score_history.append([current_iteration + 1, uncased_score]) stats = ({ "loss": train_loss } if history is None else {}) misc.update_stats(history, stats, callbacks) if uncased_score and cased_score: stats["bleu_uncased"] = uncased_score stats["bleu_cased"] = cased_score stats["bleu_uncased_history"] = uncased_score_history stats["bleu_cased_history"] = cased_score_history return stats def eval(self): """Evaluates the model.""" distribution_strategy = self.distribution_strategy if self.use_tpu else None # We only want to create the model under DS scope for TPU case. # When 'distribution_strategy' is None, a no-op DummyContextManager will # be used. with distribute_utils.get_strategy_scope(distribution_strategy): if not self.predict_model: self.predict_model = transformer.create_model(self.params, False) self._load_weights_if_possible( self.predict_model, tf.train.latest_checkpoint(self.flags_obj.model_dir)) self.predict_model.summary() return evaluate_and_log_bleu( self.predict_model, self.params, self.flags_obj.bleu_source, self.flags_obj.bleu_ref, self.flags_obj.vocab_file, distribution_strategy) def predict(self): """Predicts result from the model.""" params = self.params flags_obj = self.flags_obj with tf.name_scope("model"): model = transformer.create_model(params, is_train=False) self._load_weights_if_possible( model, tf.train.latest_checkpoint(self.flags_obj.model_dir)) model.summary() subtokenizer = tokenizer.Subtokenizer(flags_obj.vocab_file) ds = data_pipeline.eval_input_fn(params) ds = ds.map(lambda x, y: x).take(_SINGLE_SAMPLE) ret = model.predict(ds) val_outputs, _ = ret length = len(val_outputs) for i in range(length): translate.translate_from_input(val_outputs[i], subtokenizer) def _create_callbacks(self, cur_log_dir, params): """Creates a list of callbacks.""" callbacks = misc.get_callbacks() if params["enable_checkpointing"]: ckpt_full_path = os.path.join(cur_log_dir, "cp-{epoch:04d}.ckpt") callbacks.append( tf.keras.callbacks.ModelCheckpoint( ckpt_full_path, save_weights_only=params["save_weights_only"])) return callbacks def _load_weights_if_possible(self, model, init_weight_path=None): """Loads model weights when it is provided.""" if init_weight_path: logging.info("Load weights: {}".format(init_weight_path)) if self.use_tpu: checkpoint = tf.train.Checkpoint( model=model, optimizer=self._create_optimizer()) checkpoint.restore(init_weight_path) else: model.load_weights(init_weight_path) else: logging.info("Weights not loaded from path:{}".format(init_weight_path)) def _create_optimizer(self): """Creates optimizer.""" params = self.params lr_schedule = optimizer.LearningRateSchedule( params["learning_rate"], params["hidden_size"], params["learning_rate_warmup_steps"]) opt = tf.keras.optimizers.Adam( lr_schedule, params["optimizer_adam_beta1"], params["optimizer_adam_beta2"], epsilon=params["optimizer_adam_epsilon"]) opt = performance.configure_optimizer( opt, use_float16=params["dtype"] == tf.float16, loss_scale=flags_core.get_loss_scale( self.flags_obj, default_for_fp16="dynamic")) return opt def _ensure_dir(log_dir): """Makes log dir if not existed.""" if not tf.io.gfile.exists(log_dir): tf.io.gfile.makedirs(log_dir) def main(_): flags_obj = flags.FLAGS if flags_obj.enable_mlir_bridge: tf.config.experimental.enable_mlir_bridge() task = TransformerTask(flags_obj) # Execute flag override logic for better model performance if flags_obj.tf_gpu_thread_mode: keras_utils.set_gpu_thread_mode_and_count( per_gpu_thread_count=flags_obj.per_gpu_thread_count, gpu_thread_mode=flags_obj.tf_gpu_thread_mode, num_gpus=flags_obj.num_gpus, datasets_num_private_threads=flags_obj.datasets_num_private_threads) if flags_obj.mode == "train": task.train() elif flags_obj.mode == "predict": task.predict() elif flags_obj.mode == "eval": task.eval() else: raise ValueError("Invalid mode {}".format(flags_obj.mode)) if __name__ == "__main__": logging.set_verbosity(logging.INFO) misc.define_transformer_flags() app.run(main)
18,183
36.415638
80
py
models
models-master/official/legacy/transformer/attention_layer.py
# Copyright 2023 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. """Implementation of multiheaded attention and self-attention layers.""" import math import tensorflow as tf from official.modeling import tf_utils class Attention(tf.keras.layers.Layer): """Multi-headed attention layer.""" def __init__(self, hidden_size, num_heads, attention_dropout): """Initialize Attention. Args: hidden_size: int, output dim of hidden layer. num_heads: int, number of heads to repeat the same attention structure. attention_dropout: float, dropout rate inside attention for training. """ if hidden_size % num_heads: raise ValueError( "Hidden size ({}) must be divisible by the number of heads ({})." .format(hidden_size, num_heads)) super(Attention, self).__init__() self.hidden_size = hidden_size self.num_heads = num_heads self.attention_dropout = attention_dropout def build(self, input_shape): """Builds the layer.""" # Layers for linearly projecting the queries, keys, and values. size_per_head = self.hidden_size // self.num_heads def _glorot_initializer(fan_in, fan_out): limit = math.sqrt(6.0 / (fan_in + fan_out)) return tf.keras.initializers.RandomUniform(minval=-limit, maxval=limit) attention_initializer = _glorot_initializer(input_shape.as_list()[-1], self.hidden_size) self.query_dense_layer = tf.keras.layers.EinsumDense( "BTE,ENH->BTNH", output_shape=(None, self.num_heads, size_per_head), kernel_initializer=tf_utils.clone_initializer(attention_initializer), bias_axes=None, name="query") self.key_dense_layer = tf.keras.layers.EinsumDense( "BTE,ENH->BTNH", output_shape=(None, self.num_heads, size_per_head), kernel_initializer=tf_utils.clone_initializer(attention_initializer), bias_axes=None, name="key") self.value_dense_layer = tf.keras.layers.EinsumDense( "BTE,ENH->BTNH", output_shape=(None, self.num_heads, size_per_head), kernel_initializer=tf_utils.clone_initializer(attention_initializer), bias_axes=None, name="value") output_initializer = _glorot_initializer(self.hidden_size, self.hidden_size) self.output_dense_layer = tf.keras.layers.EinsumDense( "BTNH,NHE->BTE", output_shape=(None, self.hidden_size), kernel_initializer=output_initializer, bias_axes=None, name="output_transform") super(Attention, self).build(input_shape) def get_config(self): return { "hidden_size": self.hidden_size, "num_heads": self.num_heads, "attention_dropout": self.attention_dropout, } def call(self, query_input, source_input, bias, training, cache=None, decode_loop_step=None): """Apply attention mechanism to query_input and source_input. Args: query_input: A tensor with shape [batch_size, length_query, hidden_size]. source_input: A tensor with shape [batch_size, length_source, hidden_size]. bias: A tensor with shape [batch_size, 1, length_query, length_source], the attention bias that will be added to the result of the dot product. training: A bool, whether in training mode or not. cache: (Used during prediction) A dictionary with tensors containing results of previous attentions. The dictionary must have the items: {"k": tensor with shape [batch_size, i, heads, dim_per_head], "v": tensor with shape [batch_size, i, heads, dim_per_head]} where i is the current decoded length for non-padded decode, or max sequence length for padded decode. decode_loop_step: An integer, step number of the decoding loop. Used only for autoregressive inference on TPU. Returns: Attention layer output with shape [batch_size, length_query, hidden_size] """ # Linearly project the query, key and value using different learned # projections. Splitting heads is automatically done during the linear # projections --> [batch_size, length, num_heads, dim_per_head]. query = self.query_dense_layer(query_input) key = self.key_dense_layer(source_input) value = self.value_dense_layer(source_input) if cache is not None: # Combine cached keys and values with new keys and values. if decode_loop_step is not None: cache_k_shape = cache["k"].shape.as_list() indices = tf.reshape( tf.one_hot(decode_loop_step, cache_k_shape[1], dtype=key.dtype), [1, cache_k_shape[1], 1, 1]) key = cache["k"] + key * indices cache_v_shape = cache["v"].shape.as_list() indices = tf.reshape( tf.one_hot(decode_loop_step, cache_v_shape[1], dtype=value.dtype), [1, cache_v_shape[1], 1, 1]) value = cache["v"] + value * indices else: key = tf.concat([tf.cast(cache["k"], key.dtype), key], axis=1) value = tf.concat([tf.cast(cache["v"], value.dtype), value], axis=1) # Update cache cache["k"] = key cache["v"] = value # Scale query to prevent the dot product between query and key from growing # too large. depth = (self.hidden_size // self.num_heads) query *= depth**-0.5 # Calculate dot product attention logits = tf.einsum("BTNH,BFNH->BNFT", key, query) logits += bias # Note that softmax internally performs math operations using float32 # for numeric stability. When training with float16, we keep the input # and output in float16 for better performance. weights = tf.nn.softmax(logits, name="attention_weights") if training: weights = tf.nn.dropout(weights, rate=self.attention_dropout) attention_output = tf.einsum("BNFT,BTNH->BFNH", weights, value) # Run the outputs through another linear projection layer. Recombining heads # is automatically done --> [batch_size, length, hidden_size] attention_output = self.output_dense_layer(attention_output) return attention_output class SelfAttention(Attention): """Multiheaded self-attention layer.""" def call(self, query_input, bias, training, cache=None, decode_loop_step=None): return super(SelfAttention, self).call(query_input, query_input, bias, training, cache, decode_loop_step)
7,119
38.776536
80
py
models
models-master/official/legacy/transformer/optimizer.py
# Copyright 2023 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. """Optimizer from addons and learning rate scheduler.""" import tensorflow as tf class LearningRateSchedule(tf.keras.optimizers.schedules.LearningRateSchedule): """Learning rate schedule.""" def __init__(self, initial_learning_rate, hidden_size, warmup_steps): """Initialize configuration of the learning rate schedule. Args: initial_learning_rate: A float, the initial learning rate. hidden_size: An integer, the model dimension in the hidden layers. warmup_steps: An integer, the number of steps required for linear warmup. """ super(LearningRateSchedule, self).__init__() self.initial_learning_rate = initial_learning_rate self.hidden_size = hidden_size self.warmup_steps = warmup_steps self.warmup_steps_tensor = tf.cast(warmup_steps, tf.float32) def __call__(self, global_step): """Calculate learning rate with linear warmup and rsqrt decay. Args: global_step: An integer, the current global step used for learning rate calculation. Returns: A float, the learning rate needs to be used for current global step. """ with tf.name_scope('learning_rate_schedule'): global_step = tf.cast(global_step, tf.float32) learning_rate = self.initial_learning_rate learning_rate *= (self.hidden_size**-0.5) # Apply linear warmup learning_rate *= tf.minimum(1.0, global_step / self.warmup_steps_tensor) # Apply rsqrt decay learning_rate /= tf.sqrt( tf.maximum(global_step, self.warmup_steps_tensor)) return learning_rate def get_config(self): """Get the configuration of the learning rate schedule.""" return { 'initial_learning_rate': self.initial_learning_rate, 'hidden_size': self.hidden_size, 'warmup_steps': self.warmup_steps, }
2,434
36.461538
79
py
models
models-master/official/legacy/detection/main.py
# Copyright 2023 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. """Main function to train various object detection models.""" import functools import pprint from absl import app from absl import flags from absl import logging import tensorflow as tf from official.common import distribute_utils from official.legacy.detection.configs import factory as config_factory from official.legacy.detection.dataloader import input_reader from official.legacy.detection.dataloader import mode_keys as ModeKeys from official.legacy.detection.executor import distributed_executor as executor from official.legacy.detection.executor.detection_executor import DetectionDistributedExecutor from official.legacy.detection.modeling import factory as model_factory from official.modeling.hyperparams import params_dict from official.utils import hyperparams_flags from official.utils.flags import core as flags_core from official.utils.misc import keras_utils hyperparams_flags.initialize_common_flags() flags_core.define_log_steps() flags.DEFINE_bool('enable_xla', default=False, help='Enable XLA for GPU') flags.DEFINE_string( 'mode', default='train', help='Mode to run: `train`, `eval` or `eval_once`.') flags.DEFINE_string( 'model', default='retinanet', help='Model to run: `retinanet`, `mask_rcnn` or `shapemask`.') flags.DEFINE_string('training_file_pattern', None, 'Location of the train data.') flags.DEFINE_string('eval_file_pattern', None, 'Location of ther eval data') flags.DEFINE_string( 'checkpoint_path', None, 'The checkpoint path to eval. Only used in eval_once mode.') FLAGS = flags.FLAGS def run_executor(params, mode, checkpoint_path=None, train_input_fn=None, eval_input_fn=None, callbacks=None, prebuilt_strategy=None): """Runs the object detection model on distribution strategy defined by the user.""" if params.architecture.use_bfloat16: tf.compat.v2.keras.mixed_precision.set_global_policy('mixed_bfloat16') model_builder = model_factory.model_generator(params) if prebuilt_strategy is not None: strategy = prebuilt_strategy else: strategy_config = params.strategy_config distribute_utils.configure_cluster(strategy_config.worker_hosts, strategy_config.task_index) strategy = distribute_utils.get_distribution_strategy( distribution_strategy=params.strategy_type, num_gpus=strategy_config.num_gpus, all_reduce_alg=strategy_config.all_reduce_alg, num_packs=strategy_config.num_packs, tpu_address=strategy_config.tpu) num_workers = int(strategy.num_replicas_in_sync + 7) // 8 is_multi_host = (int(num_workers) >= 2) if mode == 'train': def _model_fn(params): return model_builder.build_model(params, mode=ModeKeys.TRAIN) logging.info( 'Train num_replicas_in_sync %d num_workers %d is_multi_host %s', strategy.num_replicas_in_sync, num_workers, is_multi_host) dist_executor = DetectionDistributedExecutor( strategy=strategy, params=params, model_fn=_model_fn, loss_fn=model_builder.build_loss_fn, is_multi_host=is_multi_host, predict_post_process_fn=model_builder.post_processing, trainable_variables_filter=model_builder .make_filter_trainable_variables_fn()) if is_multi_host: train_input_fn = functools.partial( train_input_fn, batch_size=params.train.batch_size // strategy.num_replicas_in_sync) return dist_executor.train( train_input_fn=train_input_fn, model_dir=params.model_dir, iterations_per_loop=params.train.iterations_per_loop, total_steps=params.train.total_steps, init_checkpoint=model_builder.make_restore_checkpoint_fn(), custom_callbacks=callbacks, save_config=True) elif mode == 'eval' or mode == 'eval_once': def _model_fn(params): return model_builder.build_model(params, mode=ModeKeys.PREDICT_WITH_GT) logging.info('Eval num_replicas_in_sync %d num_workers %d is_multi_host %s', strategy.num_replicas_in_sync, num_workers, is_multi_host) if is_multi_host: eval_input_fn = functools.partial( eval_input_fn, batch_size=params.eval.batch_size // strategy.num_replicas_in_sync) dist_executor = DetectionDistributedExecutor( strategy=strategy, params=params, model_fn=_model_fn, loss_fn=model_builder.build_loss_fn, is_multi_host=is_multi_host, predict_post_process_fn=model_builder.post_processing, trainable_variables_filter=model_builder .make_filter_trainable_variables_fn()) if mode == 'eval': results = dist_executor.evaluate_from_model_dir( model_dir=params.model_dir, eval_input_fn=eval_input_fn, eval_metric_fn=model_builder.eval_metrics, eval_timeout=params.eval.eval_timeout, min_eval_interval=params.eval.min_eval_interval, total_steps=params.train.total_steps) else: # Run evaluation once for a single checkpoint. if not checkpoint_path: raise ValueError('checkpoint_path cannot be empty.') if tf.io.gfile.isdir(checkpoint_path): checkpoint_path = tf.train.latest_checkpoint(checkpoint_path) summary_writer = executor.SummaryWriter(params.model_dir, 'eval') results, _ = dist_executor.evaluate_checkpoint( checkpoint_path=checkpoint_path, eval_input_fn=eval_input_fn, eval_metric_fn=model_builder.eval_metrics, summary_writer=summary_writer) for k, v in results.items(): logging.info('Final eval metric %s: %f', k, v) return results else: raise ValueError('Mode not found: %s.' % mode) def run(callbacks=None): """Runs the experiment.""" keras_utils.set_session_config(enable_xla=FLAGS.enable_xla) params = config_factory.config_generator(FLAGS.model) params = params_dict.override_params_dict( params, FLAGS.config_file, is_strict=True) params = params_dict.override_params_dict( params, FLAGS.params_override, is_strict=True) params.override( { 'strategy_type': FLAGS.strategy_type, 'model_dir': FLAGS.model_dir, 'strategy_config': executor.strategy_flags_dict(), }, is_strict=False) # Make sure use_tpu and strategy_type are in sync. params.use_tpu = (params.strategy_type == 'tpu') if not params.use_tpu: params.override({ 'architecture': { 'use_bfloat16': False, }, 'norm_activation': { 'use_sync_bn': False, }, }, is_strict=True) params.validate() params.lock() pp = pprint.PrettyPrinter() params_str = pp.pformat(params.as_dict()) logging.info('Model Parameters: %s', params_str) train_input_fn = None eval_input_fn = None training_file_pattern = FLAGS.training_file_pattern or params.train.train_file_pattern eval_file_pattern = FLAGS.eval_file_pattern or params.eval.eval_file_pattern if not training_file_pattern and not eval_file_pattern: raise ValueError('Must provide at least one of training_file_pattern and ' 'eval_file_pattern.') if training_file_pattern: # Use global batch size for single host. train_input_fn = input_reader.InputFn( file_pattern=training_file_pattern, params=params, mode=input_reader.ModeKeys.TRAIN, batch_size=params.train.batch_size) if eval_file_pattern: eval_input_fn = input_reader.InputFn( file_pattern=eval_file_pattern, params=params, mode=input_reader.ModeKeys.PREDICT_WITH_GT, batch_size=params.eval.batch_size, num_examples=params.eval.eval_samples) if callbacks is None: callbacks = [] if FLAGS.log_steps: callbacks.append( keras_utils.TimeHistory( batch_size=params.train.batch_size, log_steps=FLAGS.log_steps, )) return run_executor( params, FLAGS.mode, checkpoint_path=FLAGS.checkpoint_path, train_input_fn=train_input_fn, eval_input_fn=eval_input_fn, callbacks=callbacks) def main(argv): del argv # Unused. run() if __name__ == '__main__': tf.config.set_soft_device_placement(True) app.run(main)
9,015
33.022642
94
py
models
models-master/official/legacy/detection/evaluation/coco_evaluator.py
# Copyright 2023 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. """The COCO-style evaluator. The following snippet demonstrates the use of interfaces: evaluator = COCOEvaluator(...) for _ in range(num_evals): for _ in range(num_batches_per_eval): predictions, groundtruth = predictor.predict(...) # pop a batch. evaluator.update(predictions, groundtruths) # aggregate internal stats. evaluator.evaluate() # finish one full eval. See also: https://github.com/cocodataset/cocoapi/ """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import atexit import copy import tempfile from absl import logging import numpy as np from pycocotools import cocoeval import six import tensorflow as tf from official.legacy.detection.evaluation import coco_utils from official.legacy.detection.utils import class_utils class OlnCOCOevalWrapper(cocoeval.COCOeval): """COCOeval wrapper class. Rewritten based on cocoapi: (pycocotools/cocoeval.py) This class wraps COCOEVAL API object, which provides the following additional functionalities: 1. summarze 'all', 'seen', and 'novel' split output print-out, e.g., AR at different K proposals, AR and AP resutls for 'seen' and 'novel' class splits. """ def __init__(self, coco_gt, coco_dt, iou_type='box'): super(OlnCOCOevalWrapper, self).__init__( cocoGt=coco_gt, cocoDt=coco_dt, iouType=iou_type) def summarize(self): """Compute and display summary metrics for evaluation results. Delta to the standard cocoapi function: More Averate Recall metrics are produced with different top-K proposals. Note this functin can *only* be applied on the default parameter setting. Raises: Exception: Please run accumulate() first. """ def _summarize(ap=1, iou_thr=None, area_rng='all', max_dets=100): p = self.params i_str = (' {:<18} {} @[ IoU={:<9} | area={:>6s} | maxDets={:>3d} ] = ' '{:0.3f}') title_str = 'Average Precision' if ap == 1 else 'Average Recall' type_str = '(AP)' if ap == 1 else '(AR)' iou_str = '{:0.2f}:{:0.2f}'.format( p.iouThrs[0], p.iouThrs[-1]) if iou_thr is None else '{:0.2f}'.format(iou_thr) aind = [i for i, a_rng in enumerate(p.areaRngLbl) if a_rng == area_rng] mind = [i for i, m_det in enumerate(p.maxDets) if m_det == max_dets] if ap == 1: # dimension of precision: [TxRxKxAxM] s = self.eval['precision'] # IoU if iou_thr is not None: t = np.where(iou_thr == p.iouThrs)[0] s = s[t] s = s[:, :, :, aind, mind] else: # dimension of recall: [TxKxAxM] s = self.eval['recall'] if iou_thr is not None: t = np.where(iou_thr == p.iouThrs)[0] s = s[t] s = s[:, :, aind, mind] if not (s[s > -1]).any(): mean_s = -1 else: mean_s = np.mean(s[s > -1]) print( i_str.format(title_str, type_str, iou_str, area_rng, max_dets, mean_s)) return mean_s def _summarize_dets(): stats = np.zeros((14,)) stats[0] = _summarize(1) stats[1] = _summarize( 1, iou_thr=.5, ) stats[2] = _summarize( 1, iou_thr=.75, ) stats[3] = _summarize( 1, area_rng='small', ) stats[4] = _summarize( 1, area_rng='medium', ) stats[5] = _summarize( 1, area_rng='large', ) stats[6] = _summarize(0, max_dets=self.params.maxDets[0]) # 10 stats[7] = _summarize(0, max_dets=self.params.maxDets[1]) # 20 stats[8] = _summarize(0, max_dets=self.params.maxDets[2]) # 50 stats[9] = _summarize(0, max_dets=self.params.maxDets[3]) # 100 stats[10] = _summarize(0, max_dets=self.params.maxDets[4]) # 200 stats[11] = _summarize(0, area_rng='small', max_dets=10) stats[12] = _summarize(0, area_rng='medium', max_dets=10) stats[13] = _summarize(0, area_rng='large', max_dets=10) return stats if not self.eval: raise Exception('Please run accumulate() first') summarize = _summarize_dets self.stats = summarize() class OlnCOCOevalXclassWrapper(OlnCOCOevalWrapper): """COCOeval wrapper class. Rewritten based on cocoapi: (pycocotools/cocoeval.py) Delta to the standard cocoapi: Detections that hit the 'seen' class objects are ignored in top-K proposals. This class wraps COCOEVAL API object, which provides the following additional functionalities: 1. Include ignore-class split (e.g., 'voc' or 'nonvoc'). 2. Do not count (or ignore) box proposals hitting ignore-class when evaluating Average Recall at top-K proposals. """ def __init__(self, coco_gt, coco_dt, iou_type='box'): super(OlnCOCOevalXclassWrapper, self).__init__( coco_gt=coco_gt, coco_dt=coco_dt, iou_type=iou_type) def evaluateImg(self, img_id, cat_id, a_rng, max_det): p = self.params if p.useCats: gt = self._gts[img_id, cat_id] dt = self._dts[img_id, cat_id] else: gt, dt = [], [] for c_id in p.catIds: gt.extend(self._gts[img_id, c_id]) dt.extend(self._dts[img_id, c_id]) if not gt and not dt: return None for g in gt: if g['ignore'] or (g['area'] < a_rng[0] or g['area'] > a_rng[1]): g['_ignore'] = 1 else: g['_ignore'] = 0 # Class manipulation: ignore the 'ignored_split'. if 'ignored_split' in g and g['ignored_split'] == 1: g['_ignore'] = 1 # sort dt highest score first, sort gt ignore last gtind = np.argsort([g['_ignore'] for g in gt], kind='mergesort') gt = [gt[i] for i in gtind] dtind = np.argsort([-d['score'] for d in dt], kind='mergesort') dt = [dt[i] for i in dtind[0:max_det]] iscrowd = [int(o['iscrowd']) for o in gt] # load computed ious # ious = self.ious[img_id, cat_id][:, gtind] if len( # self.ious[img_id, cat_id]) > 0 else self.ious[img_id, cat_id] if self.ious[img_id, cat_id].any(): ious = self.ious[img_id, cat_id][:, gtind] else: ious = self.ious[img_id, cat_id] tt = len(p.iouThrs) gg = len(gt) dd = len(dt) gtm = np.zeros((tt, gg)) dtm = np.zeros((tt, dd)) gt_ig = np.array([g['_ignore'] for g in gt]) dt_ig = np.zeros((tt, dd)) # indicator of whether the gt object class is of ignored_split or not. gt_ig_split = np.array([g['ignored_split'] for g in gt]) dt_ig_split = np.zeros((dd)) if ious.any(): for tind, t in enumerate(p.iouThrs): for dind, d in enumerate(dt): # information about best match so far (m=-1 -> unmatched) iou = min([t, 1 - 1e-10]) m = -1 for gind, g in enumerate(gt): # if this gt already matched, and not a crowd, continue if gtm[tind, gind] > 0 and not iscrowd[gind]: continue # if dt matched to reg gt, and on ignore gt, stop if m > -1 and gt_ig[m] == 0 and gt_ig[gind] == 1: break # continue to next gt unless better match made if ious[dind, gind] < iou: continue # if match successful and best so far, store appropriately iou = ious[dind, gind] m = gind # if match made store id of match for both dt and gt if m == -1: continue dt_ig[tind, dind] = gt_ig[m] dtm[tind, dind] = gt[m]['id'] gtm[tind, m] = d['id'] # Activate to ignore the seen-class detections. if tind == 0: # Register just only once: tind > 0 is also fine. dt_ig_split[dind] = gt_ig_split[m] # set unmatched detections outside of area range to ignore a = np.array([d['area'] < a_rng[0] or d['area'] > a_rng[1] for d in dt ]).reshape((1, len(dt))) dt_ig = np.logical_or(dt_ig, np.logical_and(dtm == 0, np.repeat(a, tt, 0))) # Activate to ignore the seen-class detections. # Take only eval_split (eg, nonvoc) and ignore seen_split (eg, voc). if dt_ig_split.sum() > 0: dtm = dtm[:, dt_ig_split == 0] dt_ig = dt_ig[:, dt_ig_split == 0] len_dt = min(max_det, len(dt)) dt = [dt[i] for i in range(len_dt) if dt_ig_split[i] == 0] # store results for given image and category return { 'image_id': img_id, 'category_id': cat_id, 'aRng': a_rng, 'maxDet': max_det, 'dtIds': [d['id'] for d in dt], 'gtIds': [g['id'] for g in gt], 'dtMatches': dtm, 'gtMatches': gtm, 'dtScores': [d['score'] for d in dt], 'gtIgnore': gt_ig, 'dtIgnore': dt_ig, } class MetricWrapper(object): """Metric Wrapper of the COCO evaluator.""" # This is only a wrapper for COCO metric and works on for numpy array. So it # doesn't inherit from tf.keras.layers.Layer or tf.keras.metrics.Metric. def __init__(self, evaluator): self._evaluator = evaluator def update_state(self, y_true, y_pred): """Update internal states.""" labels = tf.nest.map_structure(lambda x: x.numpy(), y_true) outputs = tf.nest.map_structure(lambda x: x.numpy(), y_pred) groundtruths = {} predictions = {} for key, val in outputs.items(): if isinstance(val, tuple): val = np.concatenate(val) predictions[key] = val for key, val in labels.items(): if isinstance(val, tuple): val = np.concatenate(val) groundtruths[key] = val self._evaluator.update(predictions, groundtruths) def result(self): return self._evaluator.evaluate() def reset_states(self): return self._evaluator.reset() class COCOEvaluator(object): """COCO evaluation metric class.""" def __init__(self, annotation_file, include_mask, need_rescale_bboxes=True): """Constructs COCO evaluation class. The class provides the interface to metrics_fn in TPUEstimator. The _update_op() takes detections from each image and push them to self.detections. The _evaluate() loads a JSON file in COCO annotation format as the groundtruths and runs COCO evaluation. Args: annotation_file: a JSON file that stores annotations of the eval dataset. If `annotation_file` is None, groundtruth annotations will be loaded from the dataloader. include_mask: a boolean to indicate whether or not to include the mask eval. need_rescale_bboxes: If true bboxes in `predictions` will be rescaled back to absolute values (`image_info` is needed in this case). """ if annotation_file: if annotation_file.startswith('gs://'): _, local_val_json = tempfile.mkstemp(suffix='.json') tf.io.gfile.remove(local_val_json) tf.io.gfile.copy(annotation_file, local_val_json) atexit.register(tf.io.gfile.remove, local_val_json) else: local_val_json = annotation_file self._coco_gt = coco_utils.COCOWrapper( eval_type=('mask' if include_mask else 'box'), annotation_file=local_val_json) self._annotation_file = annotation_file self._include_mask = include_mask self._metric_names = [ 'AP', 'AP50', 'AP75', 'APs', 'APm', 'APl', 'ARmax1', 'ARmax10', 'ARmax100', 'ARs', 'ARm', 'ARl' ] self._required_prediction_fields = [ 'source_id', 'num_detections', 'detection_classes', 'detection_scores', 'detection_boxes' ] self._need_rescale_bboxes = need_rescale_bboxes if self._need_rescale_bboxes: self._required_prediction_fields.append('image_info') self._required_groundtruth_fields = [ 'source_id', 'height', 'width', 'classes', 'boxes' ] if self._include_mask: mask_metric_names = ['mask_' + x for x in self._metric_names] self._metric_names.extend(mask_metric_names) self._required_prediction_fields.extend(['detection_masks']) self._required_groundtruth_fields.extend(['masks']) self.reset() def reset(self): """Resets internal states for a fresh run.""" self._predictions = {} if not self._annotation_file: self._groundtruths = {} def evaluate(self): """Evaluates with detections from all images with COCO API. Returns: coco_metric: float numpy array with shape [24] representing the coco-style evaluation metrics (box and mask). """ if not self._annotation_file: logging.info('Thre is no annotation_file in COCOEvaluator.') gt_dataset = coco_utils.convert_groundtruths_to_coco_dataset( self._groundtruths) coco_gt = coco_utils.COCOWrapper( eval_type=('mask' if self._include_mask else 'box'), gt_dataset=gt_dataset) else: logging.info('Using annotation file: %s', self._annotation_file) coco_gt = self._coco_gt coco_predictions = coco_utils.convert_predictions_to_coco_annotations( self._predictions) coco_dt = coco_gt.loadRes(predictions=coco_predictions) image_ids = [ann['image_id'] for ann in coco_predictions] coco_eval = cocoeval.COCOeval(coco_gt, coco_dt, iouType='bbox') coco_eval.params.imgIds = image_ids coco_eval.evaluate() coco_eval.accumulate() coco_eval.summarize() coco_metrics = coco_eval.stats if self._include_mask: mcoco_eval = cocoeval.COCOeval(coco_gt, coco_dt, iouType='segm') mcoco_eval.params.imgIds = image_ids mcoco_eval.evaluate() mcoco_eval.accumulate() mcoco_eval.summarize() mask_coco_metrics = mcoco_eval.stats if self._include_mask: metrics = np.hstack((coco_metrics, mask_coco_metrics)) else: metrics = coco_metrics # Cleans up the internal variables in order for a fresh eval next time. self.reset() metrics_dict = {} for i, name in enumerate(self._metric_names): metrics_dict[name] = metrics[i].astype(np.float32) return metrics_dict def _process_predictions(self, predictions): image_scale = np.tile(predictions['image_info'][:, 2:3, :], (1, 1, 2)) predictions['detection_boxes'] = ( predictions['detection_boxes'].astype(np.float32)) predictions['detection_boxes'] /= image_scale if 'detection_outer_boxes' in predictions: predictions['detection_outer_boxes'] = ( predictions['detection_outer_boxes'].astype(np.float32)) predictions['detection_outer_boxes'] /= image_scale def update(self, predictions, groundtruths=None): """Update and aggregate detection results and groundtruth data. Args: predictions: a dictionary of numpy arrays including the fields below. See different parsers under `../dataloader` for more details. Required fields: - source_id: a numpy array of int or string of shape [batch_size]. - image_info [if `need_rescale_bboxes` is True]: a numpy array of float of shape [batch_size, 4, 2]. - num_detections: a numpy array of int of shape [batch_size]. - detection_boxes: a numpy array of float of shape [batch_size, K, 4]. - detection_classes: a numpy array of int of shape [batch_size, K]. - detection_scores: a numpy array of float of shape [batch_size, K]. Optional fields: - detection_masks: a numpy array of float of shape [batch_size, K, mask_height, mask_width]. groundtruths: a dictionary of numpy arrays including the fields below. See also different parsers under `../dataloader` for more details. Required fields: - source_id: a numpy array of int or string of shape [batch_size]. - height: a numpy array of int of shape [batch_size]. - width: a numpy array of int of shape [batch_size]. - num_detections: a numpy array of int of shape [batch_size]. - boxes: a numpy array of float of shape [batch_size, K, 4]. - classes: a numpy array of int of shape [batch_size, K]. Optional fields: - is_crowds: a numpy array of int of shape [batch_size, K]. If the field is absent, it is assumed that this instance is not crowd. - areas: a numy array of float of shape [batch_size, K]. If the field is absent, the area is calculated using either boxes or masks depending on which one is available. - masks: a numpy array of float of shape [batch_size, K, mask_height, mask_width], Raises: ValueError: if the required prediction or groundtruth fields are not present in the incoming `predictions` or `groundtruths`. """ for k in self._required_prediction_fields: if k not in predictions: raise ValueError( 'Missing the required key `{}` in predictions!'.format(k)) if self._need_rescale_bboxes: self._process_predictions(predictions) for k, v in six.iteritems(predictions): if k not in self._predictions: self._predictions[k] = [v] else: self._predictions[k].append(v) if not self._annotation_file: assert groundtruths for k in self._required_groundtruth_fields: if k not in groundtruths: raise ValueError( 'Missing the required key `{}` in groundtruths!'.format(k)) for k, v in six.iteritems(groundtruths): if k not in self._groundtruths: self._groundtruths[k] = [v] else: self._groundtruths[k].append(v) class OlnXclassEvaluator(COCOEvaluator): """COCO evaluation metric class.""" def __init__(self, annotation_file, include_mask, need_rescale_bboxes=True, use_category=True, seen_class='all'): """Constructs COCO evaluation class. The class provides the interface to metrics_fn in TPUEstimator. The _update_op() takes detections from each image and push them to self.detections. The _evaluate() loads a JSON file in COCO annotation format as the groundtruths and runs COCO evaluation. Args: annotation_file: a JSON file that stores annotations of the eval dataset. If `annotation_file` is None, groundtruth annotations will be loaded from the dataloader. include_mask: a boolean to indicate whether or not to include the mask eval. need_rescale_bboxes: If true bboxes in `predictions` will be rescaled back to absolute values (`image_info` is needed in this case). use_category: if `False`, treat all object in all classes in one foreground category. seen_class: 'all' or 'voc' or 'nonvoc' """ super(OlnXclassEvaluator, self).__init__( annotation_file=annotation_file, include_mask=include_mask, need_rescale_bboxes=need_rescale_bboxes) self._use_category = use_category self._seen_class = seen_class self._seen_class_ids = class_utils.coco_split_class_ids(seen_class) self._metric_names = [ 'AP', 'AP50', 'AP75', 'APs', 'APm', 'APl', 'ARmax10', 'ARmax20', 'ARmax50', 'ARmax100', 'ARmax200', 'ARmax10s', 'ARmax10m', 'ARmax10l' ] if self._seen_class != 'all': self._metric_names.extend([ 'AP_seen', 'AP50_seen', 'AP75_seen', 'APs_seen', 'APm_seen', 'APl_seen', 'ARmax10_seen', 'ARmax20_seen', 'ARmax50_seen', 'ARmax100_seen', 'ARmax200_seen', 'ARmax10s_seen', 'ARmax10m_seen', 'ARmax10l_seen', 'AP_novel', 'AP50_novel', 'AP75_novel', 'APs_novel', 'APm_novel', 'APl_novel', 'ARmax10_novel', 'ARmax20_novel', 'ARmax50_novel', 'ARmax100_novel', 'ARmax200_novel', 'ARmax10s_novel', 'ARmax10m_novel', 'ARmax10l_novel', ]) if self._include_mask: mask_metric_names = ['mask_' + x for x in self._metric_names] self._metric_names.extend(mask_metric_names) self._required_prediction_fields.extend(['detection_masks']) self._required_groundtruth_fields.extend(['masks']) self.reset() def evaluate(self): """Evaluates with detections from all images with COCO API. Returns: coco_metric: float numpy array with shape [24] representing the coco-style evaluation metrics (box and mask). """ if not self._annotation_file: logging.info('Thre is no annotation_file in COCOEvaluator.') gt_dataset = coco_utils.convert_groundtruths_to_coco_dataset( self._groundtruths) coco_gt = coco_utils.COCOWrapper( eval_type=('mask' if self._include_mask else 'box'), gt_dataset=gt_dataset) else: logging.info('Using annotation file: %s', self._annotation_file) coco_gt = self._coco_gt coco_predictions = coco_utils.convert_predictions_to_coco_annotations( self._predictions) coco_dt = coco_gt.loadRes(predictions=coco_predictions) image_ids = [ann['image_id'] for ann in coco_predictions] # Class manipulation: 'all' split samples -> ignored_split = 0. for idx, ann in enumerate(coco_gt.dataset['annotations']): coco_gt.dataset['annotations'][idx]['ignored_split'] = 0 coco_eval = cocoeval.OlnCOCOevalXclassWrapper( coco_gt, coco_dt, iou_type='bbox') coco_eval.params.maxDets = [10, 20, 50, 100, 200] coco_eval.params.imgIds = image_ids coco_eval.params.useCats = 0 if not self._use_category else 1 coco_eval.evaluate() coco_eval.accumulate() coco_eval.summarize() coco_metrics = coco_eval.stats if self._include_mask: mcoco_eval = cocoeval.OlnCOCOevalXclassWrapper( coco_gt, coco_dt, iou_type='segm') mcoco_eval.params.maxDets = [10, 20, 50, 100, 200] mcoco_eval.params.imgIds = image_ids mcoco_eval.params.useCats = 0 if not self._use_category else 1 mcoco_eval.evaluate() mcoco_eval.accumulate() mcoco_eval.summarize() mask_coco_metrics = mcoco_eval.stats if self._include_mask: metrics = np.hstack((coco_metrics, mask_coco_metrics)) else: metrics = coco_metrics if self._seen_class != 'all': # for seen class eval, samples of novel_class are ignored. coco_gt_seen = copy.deepcopy(coco_gt) for idx, ann in enumerate(coco_gt.dataset['annotations']): if ann['category_id'] in self._seen_class_ids: coco_gt_seen.dataset['annotations'][idx]['ignored_split'] = 0 else: coco_gt_seen.dataset['annotations'][idx]['ignored_split'] = 1 coco_eval_seen = cocoeval.OlnCOCOevalXclassWrapper( coco_gt_seen, coco_dt, iou_type='bbox') coco_eval_seen.params.maxDets = [10, 20, 50, 100, 200] coco_eval_seen.params.imgIds = image_ids coco_eval_seen.params.useCats = 0 if not self._use_category else 1 coco_eval_seen.evaluate() coco_eval_seen.accumulate() coco_eval_seen.summarize() coco_metrics_seen = coco_eval_seen.stats if self._include_mask: mcoco_eval_seen = cocoeval.OlnCOCOevalXclassWrapper( coco_gt_seen, coco_dt, iou_type='segm') mcoco_eval_seen.params.maxDets = [10, 20, 50, 100, 200] mcoco_eval_seen.params.imgIds = image_ids mcoco_eval_seen.params.useCats = 0 if not self._use_category else 1 mcoco_eval_seen.evaluate() mcoco_eval_seen.accumulate() mcoco_eval_seen.summarize() mask_coco_metrics_seen = mcoco_eval_seen.stats # for novel class eval, samples of seen_class are ignored. coco_gt_novel = copy.deepcopy(coco_gt) for idx, ann in enumerate(coco_gt.dataset['annotations']): if ann['category_id'] in self._seen_class_ids: coco_gt_novel.dataset['annotations'][idx]['ignored_split'] = 1 else: coco_gt_novel.dataset['annotations'][idx]['ignored_split'] = 0 coco_eval_novel = cocoeval.OlnCOCOevalXclassWrapper( coco_gt_novel, coco_dt, iou_type='bbox') coco_eval_novel.params.maxDets = [10, 20, 50, 100, 200] coco_eval_novel.params.imgIds = image_ids coco_eval_novel.params.useCats = 0 if not self._use_category else 1 coco_eval_novel.evaluate() coco_eval_novel.accumulate() coco_eval_novel.summarize() coco_metrics_novel = coco_eval_novel.stats if self._include_mask: mcoco_eval_novel = cocoeval.OlnCOCOevalXclassWrapper( coco_gt_novel, coco_dt, iou_type='segm') mcoco_eval_novel.params.maxDets = [10, 20, 50, 100, 200] mcoco_eval_novel.params.imgIds = image_ids mcoco_eval_novel.params.useCats = 0 if not self._use_category else 1 mcoco_eval_novel.evaluate() mcoco_eval_novel.accumulate() mcoco_eval_novel.summarize() mask_coco_metrics_novel = mcoco_eval_novel.stats # Combine all splits. if self._include_mask: metrics = np.hstack(( coco_metrics, coco_metrics_seen, coco_metrics_novel, mask_coco_metrics, mask_coco_metrics_seen, mask_coco_metrics_novel)) else: metrics = np.hstack(( coco_metrics, coco_metrics_seen, coco_metrics_novel)) # Cleans up the internal variables in order for a fresh eval next time. self.reset() metrics_dict = {} for i, name in enumerate(self._metric_names): metrics_dict[name] = metrics[i].astype(np.float32) return metrics_dict class OlnXdataEvaluator(OlnXclassEvaluator): """COCO evaluation metric class.""" def __init__(self, annotation_file, include_mask, need_rescale_bboxes=True, use_category=True, seen_class='all'): """Constructs COCO evaluation class. The class provides the interface to metrics_fn in TPUEstimator. The _update_op() takes detections from each image and push them to self.detections. The _evaluate() loads a JSON file in COCO annotation format as the groundtruths and runs COCO evaluation. Args: annotation_file: a JSON file that stores annotations of the eval dataset. If `annotation_file` is None, groundtruth annotations will be loaded from the dataloader. include_mask: a boolean to indicate whether or not to include the mask eval. need_rescale_bboxes: If true bboxes in `predictions` will be rescaled back to absolute values (`image_info` is needed in this case). use_category: if `False`, treat all object in all classes in one foreground category. seen_class: 'all' or 'voc' or 'nonvoc' """ super(OlnXdataEvaluator, self).__init__( annotation_file=annotation_file, include_mask=include_mask, need_rescale_bboxes=need_rescale_bboxes, use_category=False, seen_class='all') def evaluate(self): """Evaluates with detections from all images with COCO API. Returns: coco_metric: float numpy array with shape [24] representing the coco-style evaluation metrics (box and mask). """ if not self._annotation_file: logging.info('Thre is no annotation_file in COCOEvaluator.') gt_dataset = coco_utils.convert_groundtruths_to_coco_dataset( self._groundtruths) coco_gt = coco_utils.COCOWrapper( eval_type=('mask' if self._include_mask else 'box'), gt_dataset=gt_dataset) else: logging.info('Using annotation file: %s', self._annotation_file) coco_gt = self._coco_gt coco_predictions = coco_utils.convert_predictions_to_coco_annotations( self._predictions) coco_dt = coco_gt.loadRes(predictions=coco_predictions) image_ids = [ann['image_id'] for ann in coco_predictions] # Class manipulation: 'all' split samples -> ignored_split = 0. for idx, _ in enumerate(coco_gt.dataset['annotations']): coco_gt.dataset['annotations'][idx]['ignored_split'] = 0 coco_eval = cocoeval.OlnCOCOevalWrapper(coco_gt, coco_dt, iou_type='bbox') coco_eval.params.maxDets = [10, 20, 50, 100, 200] coco_eval.params.imgIds = image_ids coco_eval.params.useCats = 0 if not self._use_category else 1 coco_eval.evaluate() coco_eval.accumulate() coco_eval.summarize() coco_metrics = coco_eval.stats if self._include_mask: mcoco_eval = cocoeval.OlnCOCOevalWrapper(coco_gt, coco_dt, iou_type='segm') mcoco_eval.params.maxDets = [10, 20, 50, 100, 200] mcoco_eval.params.imgIds = image_ids mcoco_eval.params.useCats = 0 if not self._use_category else 1 mcoco_eval.evaluate() mcoco_eval.accumulate() mcoco_eval.summarize() mask_coco_metrics = mcoco_eval.stats if self._include_mask: metrics = np.hstack((coco_metrics, mask_coco_metrics)) else: metrics = coco_metrics # Cleans up the internal variables in order for a fresh eval next time. self.reset() metrics_dict = {} for i, name in enumerate(self._metric_names): metrics_dict[name] = metrics[i].astype(np.float32) return metrics_dict class ShapeMaskCOCOEvaluator(COCOEvaluator): """COCO evaluation metric class for ShapeMask.""" def __init__(self, mask_eval_class, **kwargs): """Constructs COCO evaluation class. The class provides the interface to metrics_fn in TPUEstimator. The _update_op() takes detections from each image and push them to self.detections. The _evaluate() loads a JSON file in COCO annotation format as the groundtruths and runs COCO evaluation. Args: mask_eval_class: the set of classes for mask evaluation. **kwargs: other keyword arguments passed to the parent class initializer. """ super(ShapeMaskCOCOEvaluator, self).__init__(**kwargs) self._mask_eval_class = mask_eval_class self._eval_categories = class_utils.coco_split_class_ids(mask_eval_class) if mask_eval_class != 'all': self._metric_names = [ x.replace('mask', 'novel_mask') for x in self._metric_names ] def evaluate(self): """Evaluates with detections from all images with COCO API. Returns: coco_metric: float numpy array with shape [24] representing the coco-style evaluation metrics (box and mask). """ if not self._annotation_file: gt_dataset = coco_utils.convert_groundtruths_to_coco_dataset( self._groundtruths) coco_gt = coco_utils.COCOWrapper( eval_type=('mask' if self._include_mask else 'box'), gt_dataset=gt_dataset) else: coco_gt = self._coco_gt coco_predictions = coco_utils.convert_predictions_to_coco_annotations( self._predictions) coco_dt = coco_gt.loadRes(predictions=coco_predictions) image_ids = [ann['image_id'] for ann in coco_predictions] coco_eval = cocoeval.COCOeval(coco_gt, coco_dt, iouType='bbox') coco_eval.params.imgIds = image_ids coco_eval.evaluate() coco_eval.accumulate() coco_eval.summarize() coco_metrics = coco_eval.stats if self._include_mask: mcoco_eval = cocoeval.COCOeval(coco_gt, coco_dt, iouType='segm') mcoco_eval.params.imgIds = image_ids mcoco_eval.evaluate() mcoco_eval.accumulate() mcoco_eval.summarize() if self._mask_eval_class == 'all': metrics = np.hstack((coco_metrics, mcoco_eval.stats)) else: mask_coco_metrics = mcoco_eval.category_stats val_catg_idx = np.isin(mcoco_eval.params.catIds, self._eval_categories) # Gather the valid evaluation of the eval categories. if np.any(val_catg_idx): mean_val_metrics = [] for mid in range(len(self._metric_names) // 2): mean_val_metrics.append( np.nanmean(mask_coco_metrics[mid][val_catg_idx])) mean_val_metrics = np.array(mean_val_metrics) else: mean_val_metrics = np.zeros(len(self._metric_names) // 2) metrics = np.hstack((coco_metrics, mean_val_metrics)) else: metrics = coco_metrics # Cleans up the internal variables in order for a fresh eval next time. self.reset() metrics_dict = {} for i, name in enumerate(self._metric_names): metrics_dict[name] = metrics[i].astype(np.float32) return metrics_dict
32,813
37.695755
80
py
models
models-master/official/legacy/detection/executor/distributed_executor.py
# Copyright 2023 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. """Custom training loop for running TensorFlow 2.0 models.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from typing import Optional, Dict, List, Text, Callable, Union, Iterator, Any from absl import flags from absl import logging import numpy as np import tensorflow as tf # pylint: disable=unused-import,g-import-not-at-top,redefined-outer-name,reimported from official.common import distribute_utils from official.modeling.hyperparams import params_dict from official.utils import hyperparams_flags from official.utils.misc import keras_utils FLAGS = flags.FLAGS strategy_flags_dict = hyperparams_flags.strategy_flags_dict hparam_flags_dict = hyperparams_flags.hparam_flags_dict def _save_checkpoint(checkpoint, model_dir, checkpoint_prefix): """Saves model to model_dir with provided checkpoint prefix.""" checkpoint_path = os.path.join(model_dir, checkpoint_prefix) saved_path = checkpoint.save(checkpoint_path) logging.info('Saving model as TF checkpoint: %s', saved_path) def _steps_to_run(current_step, total_steps, steps_per_loop): """Calculates steps to run on device.""" if steps_per_loop <= 0: raise ValueError('steps_per_loop should be positive integer.') return min(total_steps - current_step, steps_per_loop) def _no_metric(): return None def metrics_as_dict(metric): """Puts input metric(s) into a list. Args: metric: metric(s) to be put into the list. `metric` could be an object, a list, or a dict of tf.keras.metrics.Metric or has the `required_method`. Returns: A dictionary of valid metrics. """ if isinstance(metric, tf.keras.metrics.Metric): metrics = {metric.name: metric} elif isinstance(metric, list): metrics = {m.name: m for m in metric} elif isinstance(metric, dict): metrics = metric elif not metric: return {} else: metrics = {'metric': metric} return metrics def metric_results(metric): """Collects results from the given metric(s).""" metrics = metrics_as_dict(metric) metric_result = { name: m.result().numpy().astype(float) for name, m in metrics.items() } return metric_result def reset_states(metric): """Resets states of the given metric(s).""" metrics = metrics_as_dict(metric) for m in metrics.values(): m.reset_states() class SummaryWriter(object): """Simple SummaryWriter for writing dictionary of metrics. Attributes: writer: The tf.SummaryWriter. """ def __init__(self, model_dir: Text, name: Text): """Inits SummaryWriter with paths. Args: model_dir: the model folder path. name: the summary subfolder name. """ self.writer = tf.summary.create_file_writer(os.path.join(model_dir, name)) def __call__(self, metrics: Union[Dict[Text, float], float], step: int): """Write metrics to summary with the given writer. Args: metrics: a dictionary of metrics values. Prefer dictionary. step: integer. The training step. """ if not isinstance(metrics, dict): # Support scalar metric without name. logging.warning('Warning: summary writer prefer metrics as dictionary.') metrics = {'metric': metrics} with self.writer.as_default(): for k, v in metrics.items(): tf.summary.scalar(k, v, step=step) self.writer.flush() class DistributedExecutor(object): """Interface to train and eval models with tf.distribute.Strategy.""" def __init__(self, strategy, params, model_fn, loss_fn, is_multi_host=False): """Constructor. Args: strategy: an instance of tf.distribute.Strategy. params: Model configuration needed to run distribution strategy. model_fn: Keras model function. Signature: (params: ParamsDict) -> tf.keras.models.Model. loss_fn: loss function. Signature: (y_true: Tensor, y_pred: Tensor) -> Tensor is_multi_host: Set to True when using multi hosts for training, like multi worker GPU or TPU pod (slice). Otherwise, False. """ self._params = params self._model_fn = model_fn self._loss_fn = loss_fn self._strategy = strategy self._checkpoint_name = 'ctl_step_{step}.ckpt' self._is_multi_host = is_multi_host self.train_summary_writer = None self.eval_summary_writer = None self.global_train_step = None @property def checkpoint_name(self): """Returns default checkpoint name.""" return self._checkpoint_name @checkpoint_name.setter def checkpoint_name(self, name): """Sets default summary writer for the current thread.""" self._checkpoint_name = name def loss_fn(self): return self._loss_fn() def model_fn(self, params): return self._model_fn(params) def _save_config(self, model_dir): """Save parameters to config files if model_dir is defined.""" logging.info('Save config to model_dir %s.', model_dir) if model_dir: if not tf.io.gfile.exists(model_dir): tf.io.gfile.makedirs(model_dir) self._params.lock() params_dict.save_params_dict_to_yaml(self._params, model_dir + '/params.yaml') else: logging.warning('model_dir is empty, so skip the save config.') def _get_input_iterator( self, input_fn: Callable[..., tf.data.Dataset], strategy: tf.distribute.Strategy) -> Optional[Iterator[Any]]: """Returns distributed dataset iterator. Args: input_fn: (params: dict) -> tf.data.Dataset. strategy: an instance of tf.distribute.Strategy. Returns: An iterator that yields input tensors. """ if input_fn is None: return None # When training with multiple TPU workers, datasets needs to be cloned # across workers. Since Dataset instance cannot be cloned in eager mode, # we instead pass callable that returns a dataset. if self._is_multi_host: return iter(strategy.distribute_datasets_from_function(input_fn)) else: input_data = input_fn() return iter(strategy.experimental_distribute_dataset(input_data)) def _create_replicated_step(self, strategy, model, loss_fn, optimizer, metric=None): """Creates a single training step. Args: strategy: an instance of tf.distribute.Strategy. model: (Tensor, bool) -> Tensor. model function. loss_fn: (y_true: Tensor, y_pred: Tensor) -> Tensor. optimizer: tf.keras.optimizers.Optimizer. metric: tf.keras.metrics.Metric subclass. Returns: The training step callable. """ metrics = metrics_as_dict(metric) def _replicated_step(inputs): """Replicated training step.""" inputs, labels = inputs with tf.GradientTape() as tape: outputs = model(inputs, training=True) prediction_loss = loss_fn(labels, outputs) loss = tf.reduce_mean(prediction_loss) loss = loss / strategy.num_replicas_in_sync for m in metrics.values(): m.update_state(labels, outputs) grads = tape.gradient(loss, model.trainable_variables) optimizer.apply_gradients(zip(grads, model.trainable_variables)) return loss return _replicated_step def _create_train_step(self, strategy, model, loss_fn, optimizer, metric=None): """Creates a distributed training step. Args: strategy: an instance of tf.distribute.Strategy. model: (Tensor, bool) -> Tensor. model function. loss_fn: (y_true: Tensor, y_pred: Tensor) -> Tensor. optimizer: tf.keras.optimizers.Optimizer. metric: tf.keras.metrics.Metric subclass. Returns: The training step callable. """ replicated_step = self._create_replicated_step(strategy, model, loss_fn, optimizer, metric) @tf.function def train_step(iterator, num_steps): """Performs a distributed training step. Args: iterator: an iterator that yields input tensors. num_steps: the number of steps in the loop. Returns: The loss tensor. """ if not isinstance(num_steps, tf.Tensor): raise ValueError('steps should be an Tensor. Python object may cause ' 'retracing.') per_replica_losses = strategy.run(replicated_step, args=(next(iterator),)) for _ in tf.range(num_steps - 1): per_replica_losses = strategy.run( replicated_step, args=(next(iterator),)) # For reporting, we returns the mean of losses. losses = tf.nest.map_structure( lambda x: strategy.reduce(tf.distribute.ReduceOp.MEAN, x, axis=None), per_replica_losses) return losses return train_step def _create_test_step(self, strategy, model, metric): """Creates a distributed test step.""" metrics = metrics_as_dict(metric) @tf.function def test_step(iterator): """Calculates evaluation metrics on distributed devices.""" if not metric: logging.info('Skip test_step because metric is None (%s)', metric) return None, None def _test_step_fn(inputs): """Replicated accuracy calculation.""" inputs, labels = inputs model_outputs = model(inputs, training=False) for m in metrics.values(): m.update_state(labels, model_outputs) return labels, model_outputs return strategy.run(_test_step_fn, args=(next(iterator),)) return test_step def train( self, train_input_fn: Callable[[params_dict.ParamsDict], tf.data.Dataset], eval_input_fn: Optional[Callable[[params_dict.ParamsDict], tf.data.Dataset]] = None, model_dir: Optional[Text] = None, total_steps: int = 1, iterations_per_loop: int = 1, train_metric_fn: Optional[Callable[[], Any]] = None, eval_metric_fn: Optional[Callable[[], Any]] = None, summary_writer_fn: Callable[[Text, Text], SummaryWriter] = SummaryWriter, init_checkpoint: Optional[Callable[[tf.keras.Model], Any]] = None, custom_callbacks: Optional[List[tf.keras.callbacks.Callback]] = None, continuous_eval: bool = False, save_config: bool = True): """Runs distributed training. Args: train_input_fn: (params: dict) -> tf.data.Dataset training data input function. eval_input_fn: (Optional) same type as train_input_fn. If not None, will trigger evaluating metric on eval data. If None, will not run the eval step. model_dir: the folder path for model checkpoints. total_steps: total training steps. iterations_per_loop: train steps per loop. After each loop, this job will update metrics like loss and save checkpoint. train_metric_fn: metric_fn for evaluation in train_step. eval_metric_fn: metric_fn for evaluation in test_step. summary_writer_fn: function to create summary writer. init_checkpoint: function to load checkpoint. custom_callbacks: A list of Keras Callbacks objects to run during training. More specifically, `on_batch_begin()`, `on_batch_end()`, methods are invoked during training. continuous_eval: If `True`, will continously run evaluation on every available checkpoints. If `False`, will do the evaluation once after the final step. save_config: bool. Whether to save params to model_dir. Returns: The training loss and eval metrics. """ assert train_input_fn is not None if train_metric_fn and not callable(train_metric_fn): raise ValueError('if `train_metric_fn` is specified, ' 'train_metric_fn must be a callable.') if eval_metric_fn and not callable(eval_metric_fn): raise ValueError('if `eval_metric_fn` is specified, ' 'eval_metric_fn must be a callable.') train_metric_fn = train_metric_fn or _no_metric eval_metric_fn = eval_metric_fn or _no_metric if custom_callbacks and iterations_per_loop != 1: logging.warning( 'It is sematically wrong to run callbacks when ' 'iterations_per_loop is not one (%s)', iterations_per_loop) custom_callbacks = custom_callbacks or [] def _run_callbacks_on_batch_begin(batch): """Runs custom callbacks at the start of every step.""" if not custom_callbacks: return for callback in custom_callbacks: if callback: callback.on_batch_begin(batch) def _run_callbacks_on_batch_end(batch): """Runs custom callbacks at the end of every step.""" if not custom_callbacks: return for callback in custom_callbacks: if callback: callback.on_batch_end(batch) if save_config: self._save_config(model_dir) if FLAGS.save_checkpoint_freq: save_freq = FLAGS.save_checkpoint_freq else: save_freq = iterations_per_loop params = self._params strategy = self._strategy # To reduce unnecessary send/receive input pipeline operation, we place # input pipeline ops in worker task. train_iterator = self._get_input_iterator(train_input_fn, strategy) train_loss = None train_metric_result = None eval_metric_result = None tf.keras.backend.set_learning_phase(1) with strategy.scope(): # To correctly place the model weights on accelerators, # model and optimizer should be created in scope. model = self.model_fn(params.as_dict()) if not hasattr(model, 'optimizer'): raise ValueError('User should set optimizer attribute to model ' 'inside `model_fn`.') optimizer = model.optimizer # Training loop starts here. checkpoint = tf.train.Checkpoint(model=model, optimizer=optimizer) latest_checkpoint_file = tf.train.latest_checkpoint(model_dir) initial_step = 0 if latest_checkpoint_file: logging.info( 'Checkpoint file %s found and restoring from ' 'checkpoint', latest_checkpoint_file) checkpoint.restore(latest_checkpoint_file) initial_step = optimizer.iterations.numpy() logging.info('Loading from checkpoint file completed. Init step %d', initial_step) elif init_checkpoint: logging.info('Restoring from init checkpoint function') init_checkpoint(model) logging.info('Loading from init checkpoint file completed') current_step = optimizer.iterations.numpy() checkpoint_name = self.checkpoint_name eval_metric = eval_metric_fn() train_metric = train_metric_fn() train_summary_writer = summary_writer_fn(model_dir, 'eval_train') self.train_summary_writer = train_summary_writer.writer test_summary_writer = summary_writer_fn(model_dir, 'eval_test') self.eval_summary_writer = test_summary_writer.writer # Use training summary writer in TimeHistory if it's in use for cb in custom_callbacks: if isinstance(cb, keras_utils.TimeHistory): cb.summary_writer = self.train_summary_writer # Continue training loop. train_step = self._create_train_step( strategy=strategy, model=model, loss_fn=self.loss_fn(), optimizer=optimizer, metric=train_metric) test_step = None if eval_input_fn and eval_metric: self.global_train_step = model.optimizer.iterations test_step = self._create_test_step(strategy, model, metric=eval_metric) # Step-0 operations if current_step == 0 and not latest_checkpoint_file: _save_checkpoint(checkpoint, model_dir, checkpoint_name.format(step=current_step)) if test_step: eval_iterator = self._get_input_iterator(eval_input_fn, strategy) eval_metric_result = self._run_evaluation(test_step, current_step, eval_metric, eval_iterator) logging.info('Step: %s evalation metric = %s.', current_step, eval_metric_result) test_summary_writer(metrics=eval_metric_result, step=optimizer.iterations) reset_states(eval_metric) logging.info('Training started') last_save_checkpoint_step = current_step while current_step < total_steps: num_steps = _steps_to_run(current_step, total_steps, iterations_per_loop) _run_callbacks_on_batch_begin(current_step) train_loss = train_step(train_iterator, tf.convert_to_tensor(num_steps, dtype=tf.int32)) current_step += num_steps train_loss = tf.nest.map_structure(lambda x: x.numpy().astype(float), train_loss) _run_callbacks_on_batch_end(current_step - 1) if not isinstance(train_loss, dict): train_loss = {'total_loss': train_loss} if np.isnan(train_loss['total_loss']): raise ValueError('total loss is NaN.') if train_metric: train_metric_result = metric_results(train_metric) train_metric_result.update(train_loss) else: train_metric_result = train_loss if callable(optimizer.lr): train_metric_result.update( {'learning_rate': optimizer.lr(current_step).numpy()}) else: train_metric_result.update({'learning_rate': optimizer.lr.numpy()}) logging.info('Train Step: %d/%d / loss = %s / training metric = %s', current_step, total_steps, train_loss, train_metric_result) train_summary_writer( metrics=train_metric_result, step=optimizer.iterations) # Saves model checkpoints and run validation steps at every # iterations_per_loop steps. # To avoid repeated model saving, we do not save after the last # step of training. if save_freq > 0 and current_step < total_steps and ( current_step - last_save_checkpoint_step) >= save_freq: _save_checkpoint(checkpoint, model_dir, checkpoint_name.format(step=current_step)) last_save_checkpoint_step = current_step if continuous_eval and current_step < total_steps and test_step: eval_iterator = self._get_input_iterator(eval_input_fn, strategy) eval_metric_result = self._run_evaluation(test_step, current_step, eval_metric, eval_iterator) logging.info('Step: %s evalation metric = %s.', current_step, eval_metric_result) test_summary_writer( metrics=eval_metric_result, step=optimizer.iterations) # Re-initialize evaluation metric, except the last step. if eval_metric and current_step < total_steps: reset_states(eval_metric) if train_metric and current_step < total_steps: reset_states(train_metric) # Reaches the end of training and saves the last checkpoint. if last_save_checkpoint_step < total_steps: _save_checkpoint(checkpoint, model_dir, checkpoint_name.format(step=current_step)) if test_step: logging.info('Running final evaluation after training is complete.') eval_iterator = self._get_input_iterator(eval_input_fn, strategy) eval_metric_result = self._run_evaluation(test_step, current_step, eval_metric, eval_iterator) logging.info('Final evaluation metric = %s.', eval_metric_result) test_summary_writer(metrics=eval_metric_result, step=optimizer.iterations) self.train_summary_writer.close() self.eval_summary_writer.close() return train_metric_result, eval_metric_result def _run_evaluation(self, test_step, current_training_step, metric, test_iterator): """Runs validation steps and aggregate metrics.""" if not test_iterator or not metric: logging.warning( 'Both test_iterator (%s) and metrics (%s) must not be None.', test_iterator, metric) return None logging.info('Running evaluation after step: %s.', current_training_step) eval_step = 0 while True: try: with tf.experimental.async_scope(): test_step(test_iterator) eval_step += 1 except (StopIteration, tf.errors.OutOfRangeError): tf.experimental.async_clear_error() break metric_result = metric_results(metric) logging.info('Total eval steps: [%d]', eval_step) logging.info('At training step: [%r] Validation metric = %r', current_training_step, metric_result) return metric_result def evaluate_from_model_dir( self, model_dir: Text, eval_input_fn: Callable[[params_dict.ParamsDict], tf.data.Dataset], eval_metric_fn: Callable[[], Any], total_steps: int = -1, eval_timeout: Optional[int] = None, min_eval_interval: int = 180, summary_writer_fn: Callable[[Text, Text], SummaryWriter] = SummaryWriter): """Runs distributed evaluation on model folder. Args: model_dir: the folder for storing model checkpoints. eval_input_fn: (Optional) same type as train_input_fn. If not None, will trigger evaluting metric on eval data. If None, will not run eval step. eval_metric_fn: metric_fn for evaluation in test_step. total_steps: total training steps. If the current step reaches the total_steps, the evaluation loop will stop. eval_timeout: The maximum number of seconds to wait between checkpoints. If left as None, then the process will wait indefinitely. Used by tf.train.checkpoints_iterator. min_eval_interval: The minimum number of seconds between yielding checkpoints. Used by tf.train.checkpoints_iterator. summary_writer_fn: function to create summary writer. Returns: Eval metrics dictionary of the last checkpoint. """ if not model_dir: raise ValueError('model_dir must be set.') def terminate_eval(): tf.logging.info('Terminating eval after %d seconds of no checkpoints' % eval_timeout) return True summary_writer = summary_writer_fn(model_dir, 'eval') self.eval_summary_writer = summary_writer.writer # Read checkpoints from the given model directory # until `eval_timeout` seconds elapses. for checkpoint_path in tf.train.checkpoints_iterator( model_dir, min_interval_secs=min_eval_interval, timeout=eval_timeout, timeout_fn=terminate_eval): eval_metric_result, current_step = self.evaluate_checkpoint( checkpoint_path=checkpoint_path, eval_input_fn=eval_input_fn, eval_metric_fn=eval_metric_fn, summary_writer=summary_writer) if total_steps > 0 and current_step >= total_steps: logging.info('Evaluation finished after training step %d', current_step) break return eval_metric_result def evaluate_checkpoint(self, checkpoint_path: Text, eval_input_fn: Callable[[params_dict.ParamsDict], tf.data.Dataset], eval_metric_fn: Callable[[], Any], summary_writer: Optional[SummaryWriter] = None): """Runs distributed evaluation on the one checkpoint. Args: checkpoint_path: the checkpoint to evaluate. eval_input_fn: (Optional) same type as train_input_fn. If not None, will trigger evaluting metric on eval data. If None, will not run eval step. eval_metric_fn: metric_fn for evaluation in test_step. summary_writer: function to create summary writer. Returns: Eval metrics dictionary of the last checkpoint. """ if not callable(eval_metric_fn): raise ValueError('if `eval_metric_fn` is specified, ' 'eval_metric_fn must be a callable.') old_phase = tf.keras.backend.learning_phase() tf.keras.backend.set_learning_phase(0) params = self._params strategy = self._strategy # To reduce unnecessary send/receive input pipeline operation, we place # input pipeline ops in worker task. with strategy.scope(): # To correctly place the model weights on accelerators, # model and optimizer should be created in scope. model = self.model_fn(params.as_dict()) checkpoint = tf.train.Checkpoint(model=model) eval_metric = eval_metric_fn() assert eval_metric, 'eval_metric does not exist' test_step = self._create_test_step(strategy, model, metric=eval_metric) logging.info('Starting to evaluate.') if not checkpoint_path: raise ValueError('checkpoint path is empty') reader = tf.compat.v1.train.NewCheckpointReader(checkpoint_path) if reader.has_tensor('optimizer/iter/.ATTRIBUTES/VARIABLE_VALUE'): # Legacy keras optimizer iteration. current_step = reader.get_tensor( 'optimizer/iter/.ATTRIBUTES/VARIABLE_VALUE') else: # New keras optimizer iteration. current_step = reader.get_tensor( 'optimizer/_iterations/.ATTRIBUTES/VARIABLE_VALUE') logging.info('Checkpoint file %s found and restoring from ' 'checkpoint', checkpoint_path) status = checkpoint.restore(checkpoint_path) status.expect_partial().assert_existing_objects_matched() self.global_train_step = model.optimizer.iterations eval_iterator = self._get_input_iterator(eval_input_fn, strategy) eval_metric_result = self._run_evaluation(test_step, current_step, eval_metric, eval_iterator) logging.info('Step: %s evalation metric = %s.', current_step, eval_metric_result) summary_writer(metrics=eval_metric_result, step=current_step) reset_states(eval_metric) tf.keras.backend.set_learning_phase(old_phase) return eval_metric_result, current_step def predict(self): return NotImplementedError('Unimplmented function.') class ExecutorBuilder(object): """Builder of DistributedExecutor. Example 1: Builds an executor with supported Strategy. builder = ExecutorBuilder( strategy_type='tpu', strategy_config={'tpu': '/bns/xxx'}) dist_executor = builder.build_executor( params=params, model_fn=my_model_fn, loss_fn=my_loss_fn, metric_fn=my_metric_fn) Example 2: Builds an executor with customized Strategy. builder = ExecutorBuilder() builder.strategy = <some customized Strategy> dist_executor = builder.build_executor( params=params, model_fn=my_model_fn, loss_fn=my_loss_fn, metric_fn=my_metric_fn) Example 3: Builds a customized executor with customized Strategy. class MyDistributedExecutor(DistributedExecutor): # implementation ... builder = ExecutorBuilder() builder.strategy = <some customized Strategy> dist_executor = builder.build_executor( class_ctor=MyDistributedExecutor, params=params, model_fn=my_model_fn, loss_fn=my_loss_fn, metric_fn=my_metric_fn) """ def __init__(self, strategy_type=None, strategy_config=None): _ = distribute_utils.configure_cluster(strategy_config.worker_hosts, strategy_config.task_index) """Constructor. Args: strategy_type: string. One of 'tpu', 'mirrored', 'multi_worker_mirrored'. If None, the user is responsible to set the strategy before calling build_executor(...). strategy_config: necessary config for constructing the proper Strategy. Check strategy_flags_dict() for examples of the structure. """ self._strategy = distribute_utils.get_distribution_strategy( distribution_strategy=strategy_type, num_gpus=strategy_config.num_gpus, all_reduce_alg=strategy_config.all_reduce_alg, num_packs=strategy_config.num_packs, tpu_address=strategy_config.tpu) @property def strategy(self): """Returns default checkpoint name.""" return self._strategy @strategy.setter def strategy(self, new_strategy): """Sets default summary writer for the current thread.""" self._strategy = new_strategy def build_executor(self, class_ctor=DistributedExecutor, params=None, model_fn=None, loss_fn=None, **kwargs): """Creates an executor according to strategy type. See doc string of the DistributedExecutor.__init__ for more information of the input arguments. Args: class_ctor: A constructor of executor (default: DistributedExecutor). params: ParamsDict, all the model parameters and runtime parameters. model_fn: Keras model function. loss_fn: loss function. **kwargs: other arguments to the executor constructor. Returns: An instance of DistributedExecutor or its subclass. """ if self._strategy is None: raise ValueError('`strategy` should not be None. You need to specify ' '`strategy_type` in the builder contructor or directly ' 'set the `strategy` property of the builder.') return class_ctor( strategy=self._strategy, params=params, model_fn=model_fn, loss_fn=loss_fn, **kwargs)
30,360
36.390394
83
py
models
models-master/official/legacy/detection/executor/detection_executor.py
# Copyright 2023 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. """An executor class for running model on TensorFlow 2.0.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl import logging import tensorflow as tf from official.legacy.detection.executor import distributed_executor as executor from official.vision.utils.object_detection import visualization_utils class DetectionDistributedExecutor(executor.DistributedExecutor): """Detection specific customer training loop executor. Subclasses the DistributedExecutor and adds support for numpy based metrics. """ def __init__(self, predict_post_process_fn=None, trainable_variables_filter=None, **kwargs): super(DetectionDistributedExecutor, self).__init__(**kwargs) if predict_post_process_fn: assert callable(predict_post_process_fn) if trainable_variables_filter: assert callable(trainable_variables_filter) self._predict_post_process_fn = predict_post_process_fn self._trainable_variables_filter = trainable_variables_filter self.eval_steps = tf.Variable( 0, trainable=False, dtype=tf.int32, synchronization=tf.VariableSynchronization.ON_READ, aggregation=tf.VariableAggregation.ONLY_FIRST_REPLICA, shape=[]) def _create_replicated_step(self, strategy, model, loss_fn, optimizer, metric=None): trainable_variables = model.trainable_variables if self._trainable_variables_filter: trainable_variables = self._trainable_variables_filter( trainable_variables) logging.info('Filter trainable variables from %d to %d', len(model.trainable_variables), len(trainable_variables)) update_state_fn = lambda labels, outputs: None if isinstance(metric, tf.keras.metrics.Metric): update_state_fn = metric.update_state else: logging.error('Detection: train metric is not an instance of ' 'tf.keras.metrics.Metric.') def _replicated_step(inputs): """Replicated training step.""" inputs, labels = inputs with tf.GradientTape() as tape: outputs = model(inputs, training=True) all_losses = loss_fn(labels, outputs) losses = {} for k, v in all_losses.items(): losses[k] = tf.reduce_mean(v) per_replica_loss = losses['total_loss'] / strategy.num_replicas_in_sync update_state_fn(labels, outputs) grads = tape.gradient(per_replica_loss, trainable_variables) clipped_grads, _ = tf.clip_by_global_norm(grads, clip_norm=1.0) optimizer.apply_gradients(zip(clipped_grads, trainable_variables)) return losses return _replicated_step def _create_test_step(self, strategy, model, metric): """Creates a distributed test step.""" @tf.function def test_step(iterator, eval_steps): """Calculates evaluation metrics on distributed devices.""" def _test_step_fn(inputs, eval_steps): """Replicated accuracy calculation.""" inputs, labels = inputs model_outputs = model(inputs, training=False) if self._predict_post_process_fn: labels, prediction_outputs = self._predict_post_process_fn( labels, model_outputs) num_remaining_visualizations = ( self._params.eval.num_images_to_visualize - eval_steps) # If there are remaining number of visualizations that needs to be # done, add next batch outputs for visualization. # # TODO(hongjunchoi): Once dynamic slicing is supported on TPU, only # write correct slice of outputs to summary file. if num_remaining_visualizations > 0: visualization_utils.visualize_images_with_bounding_boxes( inputs, prediction_outputs['detection_boxes'], self.global_train_step, self.eval_summary_writer) return labels, prediction_outputs labels, outputs = strategy.run( _test_step_fn, args=( next(iterator), eval_steps, )) outputs = tf.nest.map_structure(strategy.experimental_local_results, outputs) labels = tf.nest.map_structure(strategy.experimental_local_results, labels) eval_steps.assign_add(self._params.eval.batch_size) return labels, outputs return test_step def _run_evaluation(self, test_step, current_training_step, metric, test_iterator): """Runs validation steps and aggregate metrics.""" self.eval_steps.assign(0) if not test_iterator or not metric: logging.warning( 'Both test_iterator (%s) and metrics (%s) must not be None.', test_iterator, metric) return None logging.info('Running evaluation after step: %s.', current_training_step) while True: try: labels, outputs = test_step(test_iterator, self.eval_steps) if metric: metric.update_state(labels, outputs) except (StopIteration, tf.errors.OutOfRangeError): break metric_result = metric.result() if isinstance(metric, tf.keras.metrics.Metric): metric_result = tf.nest.map_structure(lambda x: x.numpy().astype(float), metric_result) logging.info('Step: [%d] Validation metric = %s', current_training_step, metric_result) return metric_result
6,259
38.125
79
py
models
models-master/official/legacy/detection/modeling/base_model.py
# Copyright 2023 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. """Base Model definition.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import abc import re import tensorflow as tf from official.legacy.detection.modeling import checkpoint_utils from official.legacy.detection.modeling import learning_rates from official.legacy.detection.modeling import optimizers def _make_filter_trainable_variables_fn(frozen_variable_prefix): """Creates a function for filtering trainable varialbes.""" def _filter_trainable_variables(variables): """Filters trainable varialbes. Args: variables: a list of tf.Variable to be filtered. Returns: filtered_variables: a list of tf.Variable filtered out the frozen ones. """ # frozen_variable_prefix: a regex string specifing the prefix pattern of # the frozen variables' names. filtered_variables = [ v for v in variables if not frozen_variable_prefix or not re.match(frozen_variable_prefix, v.name) ] return filtered_variables return _filter_trainable_variables class Model(object): """Base class for model function.""" __metaclass__ = abc.ABCMeta def __init__(self, params): self._use_bfloat16 = params.architecture.use_bfloat16 if params.architecture.use_bfloat16: tf.compat.v2.keras.mixed_precision.set_global_policy('mixed_bfloat16') # Optimization. self._optimizer_fn = optimizers.OptimizerFactory(params.train.optimizer) self._learning_rate = learning_rates.learning_rate_generator( params.train.total_steps, params.train.learning_rate) self._frozen_variable_prefix = params.train.frozen_variable_prefix self._regularization_var_regex = params.train.regularization_variable_regex self._l2_weight_decay = params.train.l2_weight_decay # Checkpoint restoration. self._checkpoint = params.train.checkpoint.as_dict() # Summary. self._enable_summary = params.enable_summary self._model_dir = params.model_dir @abc.abstractmethod def build_outputs(self, inputs, mode): """Build the graph of the forward path.""" pass @abc.abstractmethod def build_model(self, params, mode): """Build the model object.""" pass @abc.abstractmethod def build_loss_fn(self): """Build the model object.""" pass def post_processing(self, labels, outputs): """Post-processing function.""" return labels, outputs def model_outputs(self, inputs, mode): """Build the model outputs.""" return self.build_outputs(inputs, mode) def build_optimizer(self): """Returns train_op to optimize total loss.""" # Sets up the optimizer. return self._optimizer_fn(self._learning_rate) def make_filter_trainable_variables_fn(self): """Creates a function for filtering trainable varialbes.""" return _make_filter_trainable_variables_fn(self._frozen_variable_prefix) def weight_decay_loss(self, trainable_variables): reg_variables = [ v for v in trainable_variables if self._regularization_var_regex is None or re.match(self._regularization_var_regex, v.name) ] return self._l2_weight_decay * tf.add_n( [tf.nn.l2_loss(v) for v in reg_variables]) def make_restore_checkpoint_fn(self): """Returns scaffold function to restore parameters from v1 checkpoint.""" if 'skip_checkpoint_variables' in self._checkpoint: skip_regex = self._checkpoint['skip_checkpoint_variables'] else: skip_regex = None return checkpoint_utils.make_restore_checkpoint_fn( self._checkpoint['path'], prefix=self._checkpoint['prefix'], skip_regex=skip_regex) def eval_metrics(self): """Returns tuple of metric function and its inputs for evaluation.""" raise NotImplementedError('Unimplemented eval_metrics')
4,439
31.647059
79
py
models
models-master/official/legacy/detection/modeling/losses.py
# Copyright 2023 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. """Losses used for detection models.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl import logging import tensorflow as tf def focal_loss(logits, targets, alpha, gamma, normalizer): """Compute the focal loss between `logits` and the golden `target` values. Focal loss = -(1-pt)^gamma * log(pt) where pt is the probability of being classified to the true class. Args: logits: A float32 tensor of size [batch, height_in, width_in, num_predictions]. targets: A float32 tensor of size [batch, height_in, width_in, num_predictions]. alpha: A float32 scalar multiplying alpha to the loss from positive examples and (1-alpha) to the loss from negative examples. gamma: A float32 scalar modulating loss from hard and easy examples. normalizer: A float32 scalar normalizes the total loss from all examples. Returns: loss: A float32 Tensor of size [batch, height_in, width_in, num_predictions] representing normalized loss on the prediction map. """ with tf.name_scope('focal_loss'): positive_label_mask = tf.math.equal(targets, 1.0) cross_entropy = ( tf.nn.sigmoid_cross_entropy_with_logits(labels=targets, logits=logits)) # Below are comments/derivations for computing modulator. # For brevity, let x = logits, z = targets, r = gamma, and p_t = sigmod(x) # for positive samples and 1 - sigmoid(x) for negative examples. # # The modulator, defined as (1 - P_t)^r, is a critical part in focal loss # computation. For r > 0, it puts more weights on hard examples, and less # weights on easier ones. However if it is directly computed as (1 - P_t)^r, # its back-propagation is not stable when r < 1. The implementation here # resolves the issue. # # For positive samples (labels being 1), # (1 - p_t)^r # = (1 - sigmoid(x))^r # = (1 - (1 / (1 + exp(-x))))^r # = (exp(-x) / (1 + exp(-x)))^r # = exp(log((exp(-x) / (1 + exp(-x)))^r)) # = exp(r * log(exp(-x)) - r * log(1 + exp(-x))) # = exp(- r * x - r * log(1 + exp(-x))) # # For negative samples (labels being 0), # (1 - p_t)^r # = (sigmoid(x))^r # = (1 / (1 + exp(-x)))^r # = exp(log((1 / (1 + exp(-x)))^r)) # = exp(-r * log(1 + exp(-x))) # # Therefore one unified form for positive (z = 1) and negative (z = 0) # samples is: # (1 - p_t)^r = exp(-r * z * x - r * log(1 + exp(-x))). neg_logits = -1.0 * logits modulator = tf.math.exp(gamma * targets * neg_logits - gamma * tf.math.log1p(tf.math.exp(neg_logits))) loss = modulator * cross_entropy weighted_loss = tf.where(positive_label_mask, alpha * loss, (1.0 - alpha) * loss) weighted_loss /= normalizer return weighted_loss class RpnScoreLoss(object): """Region Proposal Network score loss function.""" def __init__(self, params): self._rpn_batch_size_per_im = params.rpn_batch_size_per_im self._binary_crossentropy = tf.keras.losses.BinaryCrossentropy( reduction=tf.keras.losses.Reduction.SUM, from_logits=True) def __call__(self, score_outputs, labels): """Computes total RPN detection loss. Computes total RPN detection loss including box and score from all levels. Args: score_outputs: an OrderDict with keys representing levels and values representing scores in [batch_size, height, width, num_anchors]. labels: the dictionary that returned from dataloader that includes groundturth targets. Returns: rpn_score_loss: a scalar tensor representing total score loss. """ with tf.name_scope('rpn_loss'): levels = sorted(score_outputs.keys()) score_losses = [] for level in levels: score_losses.append( self._rpn_score_loss( score_outputs[level], labels[level], normalizer=tf.cast( tf.shape(score_outputs[level])[0] * self._rpn_batch_size_per_im, dtype=tf.float32))) # Sums per level losses to total loss. return tf.math.add_n(score_losses) def _rpn_score_loss(self, score_outputs, score_targets, normalizer=1.0): """Computes score loss.""" # score_targets has three values: # (1) score_targets[i]=1, the anchor is a positive sample. # (2) score_targets[i]=0, negative. # (3) score_targets[i]=-1, the anchor is don't care (ignore). with tf.name_scope('rpn_score_loss'): mask = tf.math.logical_or(tf.math.equal(score_targets, 1), tf.math.equal(score_targets, 0)) score_targets = tf.math.maximum(score_targets, tf.zeros_like(score_targets)) score_targets = tf.expand_dims(score_targets, axis=-1) score_outputs = tf.expand_dims(score_outputs, axis=-1) score_loss = self._binary_crossentropy( score_targets, score_outputs, sample_weight=mask) score_loss /= normalizer return score_loss class RpnBoxLoss(object): """Region Proposal Network box regression loss function.""" def __init__(self, params): logging.info('RpnBoxLoss huber_loss_delta %s', params.huber_loss_delta) # The delta is typically around the mean value of regression target. # for instances, the regression targets of 512x512 input with 6 anchors on # P2-P6 pyramid is about [0.1, 0.1, 0.2, 0.2]. self._huber_loss = tf.keras.losses.Huber( delta=params.huber_loss_delta, reduction=tf.keras.losses.Reduction.SUM) def __call__(self, box_outputs, labels): """Computes total RPN detection loss. Computes total RPN detection loss including box and score from all levels. Args: box_outputs: an OrderDict with keys representing levels and values representing box regression targets in [batch_size, height, width, num_anchors * 4]. labels: the dictionary that returned from dataloader that includes groundturth targets. Returns: rpn_box_loss: a scalar tensor representing total box regression loss. """ with tf.name_scope('rpn_loss'): levels = sorted(box_outputs.keys()) box_losses = [] for level in levels: box_losses.append(self._rpn_box_loss(box_outputs[level], labels[level])) # Sum per level losses to total loss. return tf.add_n(box_losses) def _rpn_box_loss(self, box_outputs, box_targets, normalizer=1.0): """Computes box regression loss.""" with tf.name_scope('rpn_box_loss'): mask = tf.cast(tf.not_equal(box_targets, 0.0), dtype=tf.float32) box_targets = tf.expand_dims(box_targets, axis=-1) box_outputs = tf.expand_dims(box_outputs, axis=-1) box_loss = self._huber_loss(box_targets, box_outputs, sample_weight=mask) # The loss is normalized by the sum of non-zero weights and additional # normalizer provided by the function caller. Using + 0.01 here to avoid # division by zero. box_loss /= normalizer * (tf.reduce_sum(mask) + 0.01) return box_loss class OlnRpnCenterLoss(object): """Object Localization Network RPN centerness regression loss function.""" def __init__(self): self._l1_loss = tf.keras.losses.MeanAbsoluteError( reduction=tf.keras.losses.Reduction.SUM) def __call__(self, center_outputs, labels): """Computes total RPN centerness regression loss. Computes total RPN centerness score regression loss from all levels. Args: center_outputs: an OrderDict with keys representing levels and values representing anchor centerness regression targets in [batch_size, height, width, num_anchors * 4]. labels: the dictionary that returned from dataloader that includes groundturth targets. Returns: rpn_center_loss: a scalar tensor representing total centerness regression loss. """ with tf.name_scope('rpn_loss'): # Normalizer. levels = sorted(center_outputs.keys()) num_valid = 0 # 0<pos<1, neg=0, ign=-1 for level in levels: num_valid += tf.reduce_sum(tf.cast( tf.greater(labels[level], -1.0), tf.float32)) # in and out of box num_valid += 1e-12 # Centerness loss over multi levels. center_losses = [] for level in levels: center_losses.append( self._rpn_center_l1_loss( center_outputs[level], labels[level], normalizer=num_valid)) # Sum per level losses to total loss. return tf.add_n(center_losses) def _rpn_center_l1_loss(self, center_outputs, center_targets, normalizer=1.0): """Computes centerness regression loss.""" # for instances, the regression targets of 512x512 input with 6 anchors on # P2-P6 pyramid is about [0.1, 0.1, 0.2, 0.2]. with tf.name_scope('rpn_center_loss'): # mask = tf.greater(center_targets, 0.0) # inside box only. mask = tf.greater(center_targets, -1.0) # in and out of box. center_targets = tf.maximum(center_targets, tf.zeros_like(center_targets)) center_outputs = tf.sigmoid(center_outputs) center_targets = tf.expand_dims(center_targets, -1) center_outputs = tf.expand_dims(center_outputs, -1) mask = tf.cast(mask, dtype=tf.float32) center_loss = self._l1_loss(center_targets, center_outputs, sample_weight=mask) center_loss /= normalizer return center_loss class OlnRpnIoULoss(object): """Object Localization Network RPN box-lrtb regression iou loss function.""" def __call__(self, box_outputs, labels, center_targets): """Computes total RPN detection loss. Computes total RPN box regression loss from all levels. Args: box_outputs: an OrderDict with keys representing levels and values representing box regression targets in [batch_size, height, width, num_anchors * 4]. last channel: (left, right, top, bottom). labels: the dictionary that returned from dataloader that includes groundturth targets (left, right, top, bottom). center_targets: valid_target mask. Returns: rpn_iou_loss: a scalar tensor representing total box regression loss. """ with tf.name_scope('rpn_loss'): # Normalizer. levels = sorted(box_outputs.keys()) normalizer = 0. for level in levels: # center_targets pos>0, neg=0, ign=-1. mask_ = tf.cast(tf.logical_and( tf.greater(center_targets[level][..., 0], 0.0), tf.greater(tf.reduce_min(labels[level], -1), 0.0)), tf.float32) normalizer += tf.reduce_sum(mask_) normalizer += 1e-8 # iou_loss over multi levels. iou_losses = [] for level in levels: iou_losses.append( self._rpn_iou_loss( box_outputs[level], labels[level], center_weight=center_targets[level][..., 0], normalizer=normalizer)) # Sum per level losses to total loss. return tf.add_n(iou_losses) def _rpn_iou_loss(self, box_outputs, box_targets, center_weight=None, normalizer=1.0): """Computes box regression loss.""" # for instances, the regression targets of 512x512 input with 6 anchors on # P2-P6 pyramid is about [0.1, 0.1, 0.2, 0.2]. with tf.name_scope('rpn_iou_loss'): mask = tf.logical_and( tf.greater(center_weight, 0.0), tf.greater(tf.reduce_min(box_targets, -1), 0.0)) pred_left = box_outputs[..., 0] pred_right = box_outputs[..., 1] pred_top = box_outputs[..., 2] pred_bottom = box_outputs[..., 3] gt_left = box_targets[..., 0] gt_right = box_targets[..., 1] gt_top = box_targets[..., 2] gt_bottom = box_targets[..., 3] inter_width = (tf.minimum(pred_left, gt_left) + tf.minimum(pred_right, gt_right)) inter_height = (tf.minimum(pred_top, gt_top) + tf.minimum(pred_bottom, gt_bottom)) inter_area = inter_width * inter_height union_area = ((pred_left + pred_right) * (pred_top + pred_bottom) + (gt_left + gt_right) * (gt_top + gt_bottom) - inter_area) iou = inter_area / (union_area + 1e-8) mask_ = tf.cast(mask, tf.float32) iou = tf.clip_by_value(iou, clip_value_min=1e-8, clip_value_max=1.0) neg_log_iou = -tf.math.log(iou) iou_loss = tf.reduce_sum(neg_log_iou * mask_) iou_loss /= normalizer return iou_loss class FastrcnnClassLoss(object): """Fast R-CNN classification loss function.""" def __init__(self): self._categorical_crossentropy = tf.keras.losses.CategoricalCrossentropy( reduction=tf.keras.losses.Reduction.SUM, from_logits=True) def __call__(self, class_outputs, class_targets): """Computes the class loss (Fast-RCNN branch) of Mask-RCNN. This function implements the classification loss of the Fast-RCNN. The classification loss is softmax on all RoIs. Reference: https://github.com/facebookresearch/Detectron/blob/master/detectron/modeling/fast_rcnn_heads.py # pylint: disable=line-too-long Args: class_outputs: a float tensor representing the class prediction for each box with a shape of [batch_size, num_boxes, num_classes]. class_targets: a float tensor representing the class label for each box with a shape of [batch_size, num_boxes]. Returns: a scalar tensor representing total class loss. """ with tf.name_scope('fast_rcnn_loss'): batch_size, num_boxes, num_classes = class_outputs.get_shape().as_list() class_targets = tf.cast(class_targets, dtype=tf.int32) class_targets_one_hot = tf.one_hot(class_targets, num_classes) return self._fast_rcnn_class_loss(class_outputs, class_targets_one_hot, normalizer=batch_size * num_boxes / 2.0) def _fast_rcnn_class_loss(self, class_outputs, class_targets_one_hot, normalizer): """Computes classification loss.""" with tf.name_scope('fast_rcnn_class_loss'): class_loss = self._categorical_crossentropy(class_targets_one_hot, class_outputs) class_loss /= normalizer return class_loss class FastrcnnBoxLoss(object): """Fast R-CNN box regression loss function.""" def __init__(self, params): logging.info('FastrcnnBoxLoss huber_loss_delta %s', params.huber_loss_delta) # The delta is typically around the mean value of regression target. # for instances, the regression targets of 512x512 input with 6 anchors on # P2-P6 pyramid is about [0.1, 0.1, 0.2, 0.2]. self._huber_loss = tf.keras.losses.Huber( delta=params.huber_loss_delta, reduction=tf.keras.losses.Reduction.SUM) def __call__(self, box_outputs, class_targets, box_targets): """Computes the box loss (Fast-RCNN branch) of Mask-RCNN. This function implements the box regression loss of the Fast-RCNN. As the `box_outputs` produces `num_classes` boxes for each RoI, the reference model expands `box_targets` to match the shape of `box_outputs` and selects only the target that the RoI has a maximum overlap. (Reference: https://github.com/facebookresearch/Detectron/blob/master/detectron/roi_data/fast_rcnn.py) # pylint: disable=line-too-long Instead, this function selects the `box_outputs` by the `class_targets` so that it doesn't expand `box_targets`. The box loss is smooth L1-loss on only positive samples of RoIs. Reference: https://github.com/facebookresearch/Detectron/blob/master/detectron/modeling/fast_rcnn_heads.py # pylint: disable=line-too-long Args: box_outputs: a float tensor representing the box prediction for each box with a shape of [batch_size, num_boxes, num_classes * 4]. class_targets: a float tensor representing the class label for each box with a shape of [batch_size, num_boxes]. box_targets: a float tensor representing the box label for each box with a shape of [batch_size, num_boxes, 4]. Returns: box_loss: a scalar tensor representing total box regression loss. """ with tf.name_scope('fast_rcnn_loss'): class_targets = tf.cast(class_targets, dtype=tf.int32) # Selects the box from `box_outputs` based on `class_targets`, with which # the box has the maximum overlap. (batch_size, num_rois, num_class_specific_boxes) = box_outputs.get_shape().as_list() num_classes = num_class_specific_boxes // 4 box_outputs = tf.reshape(box_outputs, [batch_size, num_rois, num_classes, 4]) box_indices = tf.reshape( class_targets + tf.tile( tf.expand_dims( tf.range(batch_size) * num_rois * num_classes, 1), [1, num_rois]) + tf.tile( tf.expand_dims(tf.range(num_rois) * num_classes, 0), [batch_size, 1]), [-1]) box_outputs = tf.matmul( tf.one_hot( box_indices, batch_size * num_rois * num_classes, dtype=box_outputs.dtype), tf.reshape(box_outputs, [-1, 4])) box_outputs = tf.reshape(box_outputs, [batch_size, -1, 4]) return self._fast_rcnn_box_loss(box_outputs, box_targets, class_targets) def _fast_rcnn_box_loss(self, box_outputs, box_targets, class_targets, normalizer=1.0): """Computes box regression loss.""" with tf.name_scope('fast_rcnn_box_loss'): mask = tf.tile(tf.expand_dims(tf.greater(class_targets, 0), axis=2), [1, 1, 4]) mask = tf.cast(mask, dtype=tf.float32) box_targets = tf.expand_dims(box_targets, axis=-1) box_outputs = tf.expand_dims(box_outputs, axis=-1) box_loss = self._huber_loss(box_targets, box_outputs, sample_weight=mask) # The loss is normalized by the number of ones in mask, # additianal normalizer provided by the user and using 0.01 here to avoid # division by 0. box_loss /= normalizer * (tf.reduce_sum(mask) + 0.01) return box_loss class OlnBoxScoreLoss(object): """Object Localization Network Box-Iou scoring function.""" def __init__(self, params): self._ignore_threshold = params.ignore_threshold self._l1_loss = tf.keras.losses.MeanAbsoluteError( reduction=tf.keras.losses.Reduction.SUM) def __call__(self, score_outputs, score_targets): """Computes the class loss (Fast-RCNN branch) of Mask-RCNN. This function implements the classification loss of the Fast-RCNN. The classification loss is softmax on all RoIs. Reference: https://github.com/facebookresearch/Detectron/blob/master/detectron/modeling/fast_rcnn_heads.py # pylint: disable=line-too-long Args: score_outputs: a float tensor representing the class prediction for each box with a shape of [batch_size, num_boxes, num_classes]. score_targets: a float tensor representing the class label for each box with a shape of [batch_size, num_boxes]. Returns: a scalar tensor representing total score loss. """ with tf.name_scope('fast_rcnn_loss'): score_outputs = tf.squeeze(score_outputs, -1) mask = tf.greater(score_targets, self._ignore_threshold) num_valid = tf.reduce_sum(tf.cast(mask, tf.float32)) score_targets = tf.maximum(score_targets, tf.zeros_like(score_targets)) score_outputs = tf.sigmoid(score_outputs) score_targets = tf.expand_dims(score_targets, -1) score_outputs = tf.expand_dims(score_outputs, -1) mask = tf.cast(mask, dtype=tf.float32) score_loss = self._l1_loss(score_targets, score_outputs, sample_weight=mask) score_loss /= (num_valid + 1e-10) return score_loss class MaskrcnnLoss(object): """Mask R-CNN instance segmentation mask loss function.""" def __init__(self): self._binary_crossentropy = tf.keras.losses.BinaryCrossentropy( reduction=tf.keras.losses.Reduction.SUM, from_logits=True) def __call__(self, mask_outputs, mask_targets, select_class_targets): """Computes the mask loss of Mask-RCNN. This function implements the mask loss of Mask-RCNN. As the `mask_outputs` produces `num_classes` masks for each RoI, the reference model expands `mask_targets` to match the shape of `mask_outputs` and selects only the target that the RoI has a maximum overlap. (Reference: https://github.com/facebookresearch/Detectron/blob/master/detectron/roi_data/mask_rcnn.py) # pylint: disable=line-too-long Instead, this implementation selects the `mask_outputs` by the `class_targets` so that it doesn't expand `mask_targets`. Note that the selection logic is done in the post-processing of mask_rcnn_fn in mask_rcnn_architecture.py. Args: mask_outputs: a float tensor representing the prediction for each mask, with a shape of [batch_size, num_masks, mask_height, mask_width]. mask_targets: a float tensor representing the binary mask of ground truth labels for each mask with a shape of [batch_size, num_masks, mask_height, mask_width]. select_class_targets: a tensor with a shape of [batch_size, num_masks], representing the foreground mask targets. Returns: mask_loss: a float tensor representing total mask loss. """ with tf.name_scope('mask_rcnn_loss'): (batch_size, num_masks, mask_height, mask_width) = mask_outputs.get_shape().as_list() weights = tf.tile( tf.reshape(tf.greater(select_class_targets, 0), [batch_size, num_masks, 1, 1]), [1, 1, mask_height, mask_width]) weights = tf.cast(weights, dtype=tf.float32) mask_targets = tf.expand_dims(mask_targets, axis=-1) mask_outputs = tf.expand_dims(mask_outputs, axis=-1) mask_loss = self._binary_crossentropy(mask_targets, mask_outputs, sample_weight=weights) # The loss is normalized by the number of 1's in weights and # + 0.01 is used to avoid division by zero. return mask_loss / (tf.reduce_sum(weights) + 0.01) class RetinanetClassLoss(object): """RetinaNet class loss.""" def __init__(self, params, num_classes): self._num_classes = num_classes self._focal_loss_alpha = params.focal_loss_alpha self._focal_loss_gamma = params.focal_loss_gamma def __call__(self, cls_outputs, labels, num_positives): """Computes total detection loss. Computes total detection loss including box and class loss from all levels. Args: cls_outputs: an OrderDict with keys representing levels and values representing logits in [batch_size, height, width, num_anchors * num_classes]. labels: the dictionary that returned from dataloader that includes class groundturth targets. num_positives: number of positive examples in the minibatch. Returns: an integar tensor representing total class loss. """ # Sums all positives in a batch for normalization and avoids zero # num_positives_sum, which would lead to inf loss during training num_positives_sum = tf.reduce_sum(input_tensor=num_positives) + 1.0 cls_losses = [] for level in cls_outputs.keys(): cls_losses.append(self.class_loss( cls_outputs[level], labels[level], num_positives_sum)) # Sums per level losses to total loss. return tf.add_n(cls_losses) def class_loss(self, cls_outputs, cls_targets, num_positives, ignore_label=-2): """Computes RetinaNet classification loss.""" # Onehot encoding for classification labels. cls_targets_one_hot = tf.one_hot(cls_targets, self._num_classes) bs, height, width, _, _ = cls_targets_one_hot.get_shape().as_list() cls_targets_one_hot = tf.reshape(cls_targets_one_hot, [bs, height, width, -1]) loss = focal_loss(tf.cast(cls_outputs, dtype=tf.float32), tf.cast(cls_targets_one_hot, dtype=tf.float32), self._focal_loss_alpha, self._focal_loss_gamma, num_positives) ignore_loss = tf.where( tf.equal(cls_targets, ignore_label), tf.zeros_like(cls_targets, dtype=tf.float32), tf.ones_like(cls_targets, dtype=tf.float32), ) ignore_loss = tf.expand_dims(ignore_loss, -1) ignore_loss = tf.tile(ignore_loss, [1, 1, 1, 1, self._num_classes]) ignore_loss = tf.reshape(ignore_loss, tf.shape(input=loss)) return tf.reduce_sum(input_tensor=ignore_loss * loss) class RetinanetBoxLoss(object): """RetinaNet box loss.""" def __init__(self, params): self._huber_loss = tf.keras.losses.Huber( delta=params.huber_loss_delta, reduction=tf.keras.losses.Reduction.SUM) def __call__(self, box_outputs, labels, num_positives): """Computes box detection loss. Computes total detection loss including box and class loss from all levels. Args: box_outputs: an OrderDict with keys representing levels and values representing box regression targets in [batch_size, height, width, num_anchors * 4]. labels: the dictionary that returned from dataloader that includes box groundturth targets. num_positives: number of positive examples in the minibatch. Returns: an integer tensor representing total box regression loss. """ # Sums all positives in a batch for normalization and avoids zero # num_positives_sum, which would lead to inf loss during training num_positives_sum = tf.reduce_sum(input_tensor=num_positives) + 1.0 box_losses = [] for level in box_outputs.keys(): box_targets_l = labels[level] box_losses.append( self.box_loss(box_outputs[level], box_targets_l, num_positives_sum)) # Sums per level losses to total loss. return tf.add_n(box_losses) def box_loss(self, box_outputs, box_targets, num_positives): """Computes RetinaNet box regression loss.""" # The delta is typically around the mean value of regression target. # for instances, the regression targets of 512x512 input with 6 anchors on # P3-P7 pyramid is about [0.1, 0.1, 0.2, 0.2]. normalizer = num_positives * 4.0 mask = tf.cast(tf.not_equal(box_targets, 0.0), dtype=tf.float32) box_targets = tf.expand_dims(box_targets, axis=-1) box_outputs = tf.expand_dims(box_outputs, axis=-1) box_loss = self._huber_loss(box_targets, box_outputs, sample_weight=mask) box_loss /= normalizer return box_loss class ShapemaskMseLoss(object): """ShapeMask mask Mean Squared Error loss function wrapper.""" def __call__(self, probs, labels, valid_mask): """Compute instance segmentation loss. Args: probs: A Tensor of shape [batch_size * num_points, height, width, num_classes]. The logits are not necessarily between 0 and 1. labels: A float32/float16 Tensor of shape [batch_size, num_instances, mask_size, mask_size], where mask_size = mask_crop_size * gt_upsample_scale for fine mask, or mask_crop_size for coarse masks and shape priors. valid_mask: a binary mask indicating valid training masks. Returns: loss: an float tensor representing total mask classification loss. """ with tf.name_scope('shapemask_prior_loss'): batch_size, num_instances = valid_mask.get_shape().as_list()[:2] diff = (tf.cast(labels, dtype=tf.float32) - tf.cast(probs, dtype=tf.float32)) diff *= tf.cast( tf.reshape(valid_mask, [batch_size, num_instances, 1, 1]), tf.float32) # Adding 0.001 in the denominator to avoid division by zero. loss = tf.nn.l2_loss(diff) / (tf.reduce_sum(labels) + 0.001) return loss class ShapemaskLoss(object): """ShapeMask mask loss function wrapper.""" def __init__(self): self._binary_crossentropy = tf.keras.losses.BinaryCrossentropy( reduction=tf.keras.losses.Reduction.SUM, from_logits=True) def __call__(self, logits, labels, valid_mask): """ShapeMask mask cross entropy loss function wrapper. Args: logits: A Tensor of shape [batch_size * num_instances, height, width, num_classes]. The logits are not necessarily between 0 and 1. labels: A float16/float32 Tensor of shape [batch_size, num_instances, mask_size, mask_size], where mask_size = mask_crop_size * gt_upsample_scale for fine mask, or mask_crop_size for coarse masks and shape priors. valid_mask: a binary mask of shape [batch_size, num_instances] indicating valid training masks. Returns: loss: an float tensor representing total mask classification loss. """ with tf.name_scope('shapemask_loss'): batch_size, num_instances = valid_mask.get_shape().as_list()[:2] labels = tf.cast(labels, tf.float32) logits = tf.cast(logits, tf.float32) loss = self._binary_crossentropy(labels, logits) loss *= tf.cast(tf.reshape( valid_mask, [batch_size, num_instances, 1, 1]), loss.dtype) # Adding 0.001 in the denominator to avoid division by zero. loss = tf.reduce_sum(loss) / (tf.reduce_sum(labels) + 0.001) return loss
30,203
40.603306
186
py
models
models-master/official/legacy/detection/modeling/optimizers.py
# Copyright 2023 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. """Optimizers.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import functools import tensorflow as tf class OptimizerFactory(object): """Class to generate optimizer function.""" def __init__(self, params): """Creates optimized based on the specified flags.""" if params.type == 'momentum': self._optimizer = functools.partial( tf.keras.optimizers.SGD, momentum=params.momentum, nesterov=params.nesterov) elif params.type == 'adam': self._optimizer = tf.keras.optimizers.Adam elif params.type == 'adadelta': self._optimizer = tf.keras.optimizers.Adadelta elif params.type == 'adagrad': self._optimizer = tf.keras.optimizers.Adagrad elif params.type == 'rmsprop': self._optimizer = functools.partial( tf.keras.optimizers.RMSprop, momentum=params.momentum) else: raise ValueError('Unsupported optimizer type `{}`.'.format(params.type)) def __call__(self, learning_rate): return self._optimizer(learning_rate=learning_rate)
1,716
33.34
78
py
models
models-master/official/legacy/detection/modeling/learning_rates.py
# Copyright 2023 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. """Learning rate schedule.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow as tf from official.modeling.hyperparams import params_dict class StepLearningRateWithLinearWarmup( tf.keras.optimizers.schedules.LearningRateSchedule): """Class to generate learning rate tensor.""" def __init__(self, total_steps, params): """Creates the step learning rate tensor with linear warmup.""" super(StepLearningRateWithLinearWarmup, self).__init__() self._total_steps = total_steps assert isinstance(params, (dict, params_dict.ParamsDict)) if isinstance(params, dict): params = params_dict.ParamsDict(params) self._params = params def __call__(self, global_step): warmup_lr = self._params.warmup_learning_rate warmup_steps = self._params.warmup_steps init_lr = self._params.init_learning_rate lr_levels = self._params.learning_rate_levels lr_steps = self._params.learning_rate_steps linear_warmup = ( warmup_lr + tf.cast(global_step, dtype=tf.float32) / warmup_steps * (init_lr - warmup_lr)) learning_rate = tf.where(global_step < warmup_steps, linear_warmup, init_lr) for next_learning_rate, start_step in zip(lr_levels, lr_steps): learning_rate = tf.where(global_step >= start_step, next_learning_rate, learning_rate) return learning_rate def get_config(self): return {'_params': self._params.as_dict()} class CosineLearningRateWithLinearWarmup( tf.keras.optimizers.schedules.LearningRateSchedule): """Class to generate learning rate tensor.""" def __init__(self, total_steps, params): """Creates the cosine learning rate tensor with linear warmup.""" super(CosineLearningRateWithLinearWarmup, self).__init__() self._total_steps = total_steps assert isinstance(params, (dict, params_dict.ParamsDict)) if isinstance(params, dict): params = params_dict.ParamsDict(params) self._params = params def __call__(self, global_step): global_step = tf.cast(global_step, dtype=tf.float32) warmup_lr = self._params.warmup_learning_rate warmup_steps = self._params.warmup_steps init_lr = self._params.init_learning_rate total_steps = self._total_steps linear_warmup = ( warmup_lr + global_step / warmup_steps * (init_lr - warmup_lr)) cosine_learning_rate = ( init_lr * (tf.cos(np.pi * (global_step - warmup_steps) / (total_steps - warmup_steps)) + 1.0) / 2.0) learning_rate = tf.where(global_step < warmup_steps, linear_warmup, cosine_learning_rate) return learning_rate def get_config(self): return {'_params': self._params.as_dict()} def learning_rate_generator(total_steps, params): """The learning rate function generator.""" if params.type == 'step': return StepLearningRateWithLinearWarmup(total_steps, params) elif params.type == 'cosine': return CosineLearningRateWithLinearWarmup(total_steps, params) else: raise ValueError('Unsupported learning rate type: {}.'.format(params.type))
3,800
37.393939
80
py
models
models-master/official/legacy/detection/modeling/checkpoint_utils.py
# Copyright 2023 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. """Util functions for loading checkpoints. Especially for loading Tensorflow 1.x checkpoint to Tensorflow 2.x (keras) model. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import re from absl import logging import tensorflow as tf def _build_assignment_map(keras_model, prefix='', skip_variables_regex=None, var_to_shape_map=None): """Builds the variable assignment map. Compute an assignment mapping for loading older checkpoints into a Keras model. Variable names are remapped from the original TPUEstimator model to the new Keras name. Args: keras_model: tf.keras.Model object to provide variables to assign. prefix: prefix in the variable name to be remove for alignment with names in the checkpoint. skip_variables_regex: regular expression to math the names of variables that do not need to be assign. var_to_shape_map: variable name to shape mapping from the checkpoint. Returns: The variable assignment map. """ assignment_map = {} checkpoint_names = [] if var_to_shape_map: # pylint: disable=g-long-lambda checkpoint_names = list( filter( lambda x: not x.endswith('Momentum') and not x.endswith( 'global_step'), var_to_shape_map.keys())) # pylint: enable=g-long-lambda logging.info('Number of variables in the checkpoint %d', len(checkpoint_names)) for var in keras_model.variables: var_name = var.name if skip_variables_regex and re.match(skip_variables_regex, var_name): continue # Trim the index of the variable. if ':' in var_name: var_name = var_name[:var_name.rindex(':')] if var_name.startswith(prefix): var_name = var_name[len(prefix):] if not var_to_shape_map: assignment_map[var_name] = var continue # Match name with variables in the checkpoint. # pylint: disable=cell-var-from-loop match_names = list(filter(lambda x: x.endswith(var_name), checkpoint_names)) # pylint: enable=cell-var-from-loop try: if match_names: assert len(match_names) == 1, 'more then on matches for {}: {}'.format( var_name, match_names) checkpoint_names.remove(match_names[0]) assignment_map[match_names[0]] = var else: logging.info('Error not found var name: %s', var_name) except Exception as e: logging.info('Error removing the match_name: %s', match_names) logging.info('Exception: %s', e) raise logging.info('Found matching variable in checkpoint: %d', len(assignment_map)) return assignment_map def _get_checkpoint_map(checkpoint_path): reader = tf.train.load_checkpoint(checkpoint_path) return reader.get_variable_to_shape_map() def make_restore_checkpoint_fn(checkpoint_path, prefix='', skip_regex=None): """Returns scaffold function to restore parameters from v1 checkpoint. Args: checkpoint_path: path of the checkpoint folder or file. Example 1: '/path/to/model_dir/' Example 2: '/path/to/model.ckpt-22500' prefix: prefix in the variable name to be remove for alignment with names in the checkpoint. skip_regex: regular expression to math the names of variables that do not need to be assign. Returns: Callable[tf.kears.Model] -> void. Fn to load v1 checkpoint to keras model. """ def _restore_checkpoint_fn(keras_model): """Loads pretrained model through scaffold function.""" if not checkpoint_path: logging.info('checkpoint_path is empty') return var_prefix = prefix if prefix and not prefix.endswith('/'): var_prefix += '/' var_to_shape_map = _get_checkpoint_map(checkpoint_path) assert var_to_shape_map, 'var_to_shape_map should not be empty' vars_to_load = _build_assignment_map( keras_model, prefix=var_prefix, skip_variables_regex=skip_regex, var_to_shape_map=var_to_shape_map) if not vars_to_load: raise ValueError('Variables to load is empty.') tf.compat.v1.train.init_from_checkpoint(checkpoint_path, vars_to_load) return _restore_checkpoint_fn
4,862
33.006993
80
py
models
models-master/official/legacy/detection/modeling/maskrcnn_model.py
# Copyright 2023 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. """Model defination for the Mask R-CNN Model.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from official.legacy.detection.dataloader import anchor from official.legacy.detection.dataloader import mode_keys from official.legacy.detection.evaluation import factory as eval_factory from official.legacy.detection.modeling import base_model from official.legacy.detection.modeling import losses from official.legacy.detection.modeling.architecture import factory from official.legacy.detection.ops import postprocess_ops from official.legacy.detection.ops import roi_ops from official.legacy.detection.ops import spatial_transform_ops from official.legacy.detection.ops import target_ops from official.legacy.detection.utils import box_utils class MaskrcnnModel(base_model.Model): """Mask R-CNN model function.""" def __init__(self, params): super(MaskrcnnModel, self).__init__(params) # For eval metrics. self._params = params self._keras_model = None self._include_mask = params.architecture.include_mask # Architecture generators. self._backbone_fn = factory.backbone_generator(params) self._fpn_fn = factory.multilevel_features_generator(params) self._rpn_head_fn = factory.rpn_head_generator(params) self._generate_rois_fn = roi_ops.ROIGenerator(params.roi_proposal) self._sample_rois_fn = target_ops.ROISampler(params.roi_sampling) self._sample_masks_fn = target_ops.MaskSampler( params.architecture.mask_target_size, params.mask_sampling.num_mask_samples_per_image) self._frcnn_head_fn = factory.fast_rcnn_head_generator(params) if self._include_mask: self._mrcnn_head_fn = factory.mask_rcnn_head_generator(params) # Loss function. self._rpn_score_loss_fn = losses.RpnScoreLoss(params.rpn_score_loss) self._rpn_box_loss_fn = losses.RpnBoxLoss(params.rpn_box_loss) self._frcnn_class_loss_fn = losses.FastrcnnClassLoss() self._frcnn_box_loss_fn = losses.FastrcnnBoxLoss(params.frcnn_box_loss) if self._include_mask: self._mask_loss_fn = losses.MaskrcnnLoss() self._generate_detections_fn = postprocess_ops.GenericDetectionGenerator( params.postprocess) self._transpose_input = params.train.transpose_input assert not self._transpose_input, 'Transpose input is not supportted.' def build_outputs(self, inputs, mode): is_training = mode == mode_keys.TRAIN model_outputs = {} image = inputs['image'] _, image_height, image_width, _ = image.get_shape().as_list() backbone_features = self._backbone_fn(image, is_training) fpn_features = self._fpn_fn(backbone_features, is_training) rpn_score_outputs, rpn_box_outputs = self._rpn_head_fn( fpn_features, is_training) model_outputs.update({ 'rpn_score_outputs': tf.nest.map_structure(lambda x: tf.cast(x, tf.float32), rpn_score_outputs), 'rpn_box_outputs': tf.nest.map_structure(lambda x: tf.cast(x, tf.float32), rpn_box_outputs), }) input_anchor = anchor.Anchor(self._params.architecture.min_level, self._params.architecture.max_level, self._params.anchor.num_scales, self._params.anchor.aspect_ratios, self._params.anchor.anchor_size, (image_height, image_width)) rpn_rois, _ = self._generate_rois_fn(rpn_box_outputs, rpn_score_outputs, input_anchor.multilevel_boxes, inputs['image_info'][:, 1, :], is_training) if is_training: rpn_rois = tf.stop_gradient(rpn_rois) # Sample proposals. rpn_rois, matched_gt_boxes, matched_gt_classes, matched_gt_indices = ( self._sample_rois_fn(rpn_rois, inputs['gt_boxes'], inputs['gt_classes'])) # Create bounding box training targets. box_targets = box_utils.encode_boxes( matched_gt_boxes, rpn_rois, weights=[10.0, 10.0, 5.0, 5.0]) # If the target is background, the box target is set to all 0s. box_targets = tf.where( tf.tile( tf.expand_dims(tf.equal(matched_gt_classes, 0), axis=-1), [1, 1, 4]), tf.zeros_like(box_targets), box_targets) model_outputs.update({ 'class_targets': matched_gt_classes, 'box_targets': box_targets, }) roi_features = spatial_transform_ops.multilevel_crop_and_resize( fpn_features, rpn_rois, output_size=7) class_outputs, box_outputs = self._frcnn_head_fn(roi_features, is_training) model_outputs.update({ 'class_outputs': tf.nest.map_structure(lambda x: tf.cast(x, tf.float32), class_outputs), 'box_outputs': tf.nest.map_structure(lambda x: tf.cast(x, tf.float32), box_outputs), }) # Add this output to train to make the checkpoint loadable in predict mode. # If we skip it in train mode, the heads will be out-of-order and checkpoint # loading will fail. boxes, scores, classes, valid_detections = self._generate_detections_fn( box_outputs, class_outputs, rpn_rois, inputs['image_info'][:, 1:2, :]) model_outputs.update({ 'num_detections': valid_detections, 'detection_boxes': boxes, 'detection_classes': classes, 'detection_scores': scores, }) if not self._include_mask: return model_outputs if is_training: rpn_rois, classes, mask_targets = self._sample_masks_fn( rpn_rois, matched_gt_boxes, matched_gt_classes, matched_gt_indices, inputs['gt_masks']) mask_targets = tf.stop_gradient(mask_targets) classes = tf.cast(classes, dtype=tf.int32) model_outputs.update({ 'mask_targets': mask_targets, 'sampled_class_targets': classes, }) else: rpn_rois = boxes classes = tf.cast(classes, dtype=tf.int32) mask_roi_features = spatial_transform_ops.multilevel_crop_and_resize( fpn_features, rpn_rois, output_size=14) mask_outputs = self._mrcnn_head_fn(mask_roi_features, classes, is_training) if is_training: model_outputs.update({ 'mask_outputs': tf.nest.map_structure(lambda x: tf.cast(x, tf.float32), mask_outputs), }) else: model_outputs.update({'detection_masks': tf.nn.sigmoid(mask_outputs)}) return model_outputs def build_loss_fn(self): if self._keras_model is None: raise ValueError('build_loss_fn() must be called after build_model().') filter_fn = self.make_filter_trainable_variables_fn() trainable_variables = filter_fn(self._keras_model.trainable_variables) def _total_loss_fn(labels, outputs): rpn_score_loss = self._rpn_score_loss_fn(outputs['rpn_score_outputs'], labels['rpn_score_targets']) rpn_box_loss = self._rpn_box_loss_fn(outputs['rpn_box_outputs'], labels['rpn_box_targets']) frcnn_class_loss = self._frcnn_class_loss_fn(outputs['class_outputs'], outputs['class_targets']) frcnn_box_loss = self._frcnn_box_loss_fn(outputs['box_outputs'], outputs['class_targets'], outputs['box_targets']) if self._include_mask: mask_loss = self._mask_loss_fn(outputs['mask_outputs'], outputs['mask_targets'], outputs['sampled_class_targets']) else: mask_loss = 0.0 model_loss = ( rpn_score_loss + rpn_box_loss + frcnn_class_loss + frcnn_box_loss + mask_loss) l2_regularization_loss = self.weight_decay_loss(trainable_variables) total_loss = model_loss + l2_regularization_loss return { 'total_loss': total_loss, 'loss': total_loss, 'fast_rcnn_class_loss': frcnn_class_loss, 'fast_rcnn_box_loss': frcnn_box_loss, 'mask_loss': mask_loss, 'model_loss': model_loss, 'l2_regularization_loss': l2_regularization_loss, 'rpn_score_loss': rpn_score_loss, 'rpn_box_loss': rpn_box_loss, } return _total_loss_fn def build_input_layers(self, params, mode): is_training = mode == mode_keys.TRAIN input_shape = ( params.maskrcnn_parser.output_size + [params.maskrcnn_parser.num_channels]) if is_training: batch_size = params.train.batch_size input_layer = { 'image': tf.keras.layers.Input( shape=input_shape, batch_size=batch_size, name='image', dtype=tf.bfloat16 if self._use_bfloat16 else tf.float32), 'image_info': tf.keras.layers.Input( shape=[4, 2], batch_size=batch_size, name='image_info', ), 'gt_boxes': tf.keras.layers.Input( shape=[params.maskrcnn_parser.max_num_instances, 4], batch_size=batch_size, name='gt_boxes'), 'gt_classes': tf.keras.layers.Input( shape=[params.maskrcnn_parser.max_num_instances], batch_size=batch_size, name='gt_classes', dtype=tf.int64), } if self._include_mask: input_layer['gt_masks'] = tf.keras.layers.Input( shape=[ params.maskrcnn_parser.max_num_instances, params.maskrcnn_parser.mask_crop_size, params.maskrcnn_parser.mask_crop_size ], batch_size=batch_size, name='gt_masks') else: batch_size = params.eval.batch_size input_layer = { 'image': tf.keras.layers.Input( shape=input_shape, batch_size=batch_size, name='image', dtype=tf.bfloat16 if self._use_bfloat16 else tf.float32), 'image_info': tf.keras.layers.Input( shape=[4, 2], batch_size=batch_size, name='image_info', ), } return input_layer def build_model(self, params, mode): if self._keras_model is None: input_layers = self.build_input_layers(self._params, mode) outputs = self.model_outputs(input_layers, mode) model = tf.keras.models.Model( inputs=input_layers, outputs=outputs, name='maskrcnn') assert model is not None, 'Fail to build tf.keras.Model.' model.optimizer = self.build_optimizer() self._keras_model = model return self._keras_model def post_processing(self, labels, outputs): required_output_fields = ['class_outputs', 'box_outputs'] for field in required_output_fields: if field not in outputs: raise ValueError('"%s" is missing in outputs, requried %s found %s' % (field, required_output_fields, outputs.keys())) predictions = { 'image_info': labels['image_info'], 'num_detections': outputs['num_detections'], 'detection_boxes': outputs['detection_boxes'], 'detection_classes': outputs['detection_classes'], 'detection_scores': outputs['detection_scores'], } if self._include_mask: predictions.update({ 'detection_masks': outputs['detection_masks'], }) if 'groundtruths' in labels: predictions['source_id'] = labels['groundtruths']['source_id'] predictions['gt_source_id'] = labels['groundtruths']['source_id'] predictions['gt_height'] = labels['groundtruths']['height'] predictions['gt_width'] = labels['groundtruths']['width'] predictions['gt_image_info'] = labels['image_info'] predictions['gt_num_detections'] = ( labels['groundtruths']['num_detections']) predictions['gt_boxes'] = labels['groundtruths']['boxes'] predictions['gt_classes'] = labels['groundtruths']['classes'] predictions['gt_areas'] = labels['groundtruths']['areas'] predictions['gt_is_crowds'] = labels['groundtruths']['is_crowds'] return labels, predictions def eval_metrics(self): return eval_factory.evaluator_generator(self._params.eval)
13,458
38.702065
80
py
models
models-master/official/legacy/detection/modeling/olnmask_model.py
# Copyright 2023 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. """Model defination for the Object Localization Network (OLN) Model.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from official.legacy.detection.dataloader import anchor from official.legacy.detection.dataloader import mode_keys from official.legacy.detection.modeling import losses from official.legacy.detection.modeling.architecture import factory from official.legacy.detection.modeling.maskrcnn_model import MaskrcnnModel from official.legacy.detection.ops import postprocess_ops from official.legacy.detection.ops import roi_ops from official.legacy.detection.ops import spatial_transform_ops from official.legacy.detection.ops import target_ops from official.legacy.detection.utils import box_utils class OlnMaskModel(MaskrcnnModel): """OLN-Mask model function.""" def __init__(self, params): super(OlnMaskModel, self).__init__(params) self._params = params # Different heads and layers. self._include_rpn_class = params.architecture.include_rpn_class self._include_mask = params.architecture.include_mask self._include_frcnn_class = params.architecture.include_frcnn_class self._include_frcnn_box = params.architecture.include_frcnn_box self._include_centerness = params.rpn_head.has_centerness self._include_box_score = (params.frcnn_head.has_scoring and params.architecture.include_frcnn_box) self._include_mask_score = (params.mrcnn_head.has_scoring and params.architecture.include_mask) # Architecture generators. self._backbone_fn = factory.backbone_generator(params) self._fpn_fn = factory.multilevel_features_generator(params) self._rpn_head_fn = factory.rpn_head_generator(params) if self._include_centerness: self._rpn_head_fn = factory.oln_rpn_head_generator(params) else: self._rpn_head_fn = factory.rpn_head_generator(params) self._generate_rois_fn = roi_ops.OlnROIGenerator(params.roi_proposal) self._sample_rois_fn = target_ops.ROIScoreSampler(params.roi_sampling) self._sample_masks_fn = target_ops.MaskSampler( params.architecture.mask_target_size, params.mask_sampling.num_mask_samples_per_image) if self._include_box_score: self._frcnn_head_fn = factory.oln_box_score_head_generator(params) else: self._frcnn_head_fn = factory.fast_rcnn_head_generator(params) if self._include_mask: if self._include_mask_score: self._mrcnn_head_fn = factory.oln_mask_score_head_generator(params) else: self._mrcnn_head_fn = factory.mask_rcnn_head_generator(params) # Loss function. self._rpn_score_loss_fn = losses.RpnScoreLoss(params.rpn_score_loss) self._rpn_box_loss_fn = losses.RpnBoxLoss(params.rpn_box_loss) if self._include_centerness: self._rpn_iou_loss_fn = losses.OlnRpnIoULoss() self._rpn_center_loss_fn = losses.OlnRpnCenterLoss() self._frcnn_class_loss_fn = losses.FastrcnnClassLoss() self._frcnn_box_loss_fn = losses.FastrcnnBoxLoss(params.frcnn_box_loss) if self._include_box_score: self._frcnn_box_score_loss_fn = losses.OlnBoxScoreLoss( params.frcnn_box_score_loss) if self._include_mask: self._mask_loss_fn = losses.MaskrcnnLoss() self._generate_detections_fn = postprocess_ops.OlnDetectionGenerator( params.postprocess) self._transpose_input = params.train.transpose_input assert not self._transpose_input, 'Transpose input is not supportted.' def build_outputs(self, inputs, mode): is_training = mode == mode_keys.TRAIN model_outputs = {} image = inputs['image'] _, image_height, image_width, _ = image.get_shape().as_list() backbone_features = self._backbone_fn(image, is_training) fpn_features = self._fpn_fn(backbone_features, is_training) # rpn_centerness. if self._include_centerness: rpn_score_outputs, rpn_box_outputs, rpn_center_outputs = ( self._rpn_head_fn(fpn_features, is_training)) model_outputs.update({ 'rpn_center_outputs': tf.nest.map_structure(lambda x: tf.cast(x, tf.float32), rpn_center_outputs), }) object_scores = rpn_center_outputs else: rpn_score_outputs, rpn_box_outputs = self._rpn_head_fn( fpn_features, is_training) object_scores = None model_outputs.update({ 'rpn_score_outputs': tf.nest.map_structure(lambda x: tf.cast(x, tf.float32), rpn_score_outputs), 'rpn_box_outputs': tf.nest.map_structure(lambda x: tf.cast(x, tf.float32), rpn_box_outputs), }) input_anchor = anchor.Anchor(self._params.architecture.min_level, self._params.architecture.max_level, self._params.anchor.num_scales, self._params.anchor.aspect_ratios, self._params.anchor.anchor_size, (image_height, image_width)) rpn_rois, rpn_roi_scores = self._generate_rois_fn( rpn_box_outputs, rpn_score_outputs, input_anchor.multilevel_boxes, inputs['image_info'][:, 1, :], is_training, is_box_lrtb=self._include_centerness, object_scores=object_scores, ) if (not self._include_frcnn_class and not self._include_frcnn_box and not self._include_mask): # if not is_training: # For direct RPN detection, # use dummy box_outputs = (dy,dx,dh,dw = 0,0,0,0) box_outputs = tf.zeros_like(rpn_rois) box_outputs = tf.concat([box_outputs, box_outputs], -1) boxes, scores, classes, valid_detections = self._generate_detections_fn( box_outputs, rpn_roi_scores, rpn_rois, inputs['image_info'][:, 1:2, :], is_single_fg_score=True, # if no_background, no softmax is applied. keep_nms=True) model_outputs.update({ 'num_detections': valid_detections, 'detection_boxes': boxes, 'detection_classes': classes, 'detection_scores': scores, }) return model_outputs # ---- OLN-Proposal finishes here. ---- if is_training: rpn_rois = tf.stop_gradient(rpn_rois) rpn_roi_scores = tf.stop_gradient(rpn_roi_scores) # Sample proposals. (rpn_rois, rpn_roi_scores, matched_gt_boxes, matched_gt_classes, matched_gt_indices) = ( self._sample_rois_fn(rpn_rois, rpn_roi_scores, inputs['gt_boxes'], inputs['gt_classes'])) # Create bounding box training targets. box_targets = box_utils.encode_boxes( matched_gt_boxes, rpn_rois, weights=[10.0, 10.0, 5.0, 5.0]) # If the target is background, the box target is set to all 0s. box_targets = tf.where( tf.tile( tf.expand_dims(tf.equal(matched_gt_classes, 0), axis=-1), [1, 1, 4]), tf.zeros_like(box_targets), box_targets) model_outputs.update({ 'class_targets': matched_gt_classes, 'box_targets': box_targets, }) # Create Box-IoU targets. { box_ious = box_utils.bbox_overlap( rpn_rois, inputs['gt_boxes']) matched_box_ious = tf.reduce_max(box_ious, 2) model_outputs.update({ 'box_iou_targets': matched_box_ious,}) # } roi_features = spatial_transform_ops.multilevel_crop_and_resize( fpn_features, rpn_rois, output_size=7) if not self._include_box_score: class_outputs, box_outputs = self._frcnn_head_fn( roi_features, is_training) else: class_outputs, box_outputs, score_outputs = self._frcnn_head_fn( roi_features, is_training) model_outputs.update({ 'box_score_outputs': tf.nest.map_structure(lambda x: tf.cast(x, tf.float32), score_outputs),}) model_outputs.update({ 'class_outputs': tf.nest.map_structure(lambda x: tf.cast(x, tf.float32), class_outputs), 'box_outputs': tf.nest.map_structure(lambda x: tf.cast(x, tf.float32), box_outputs), }) # Add this output to train to make the checkpoint loadable in predict mode. # If we skip it in train mode, the heads will be out-of-order and checkpoint # loading will fail. if not self._include_frcnn_box: box_outputs = tf.zeros_like(box_outputs) # dummy zeros. if self._include_box_score: score_outputs = tf.cast(tf.squeeze(score_outputs, -1), rpn_roi_scores.dtype) # box-score = (rpn-centerness * box-iou)^(1/2) # TR: rpn_roi_scores: b,1000, score_outputs: b,512 # TS: rpn_roi_scores: b,1000, score_outputs: b,1000 box_scores = tf.pow( rpn_roi_scores * tf.sigmoid(score_outputs), 1/2.) if not self._include_frcnn_class: boxes, scores, classes, valid_detections = self._generate_detections_fn( box_outputs, box_scores, rpn_rois, inputs['image_info'][:, 1:2, :], is_single_fg_score=True, keep_nms=True,) else: boxes, scores, classes, valid_detections = self._generate_detections_fn( box_outputs, class_outputs, rpn_rois, inputs['image_info'][:, 1:2, :], keep_nms=True,) model_outputs.update({ 'num_detections': valid_detections, 'detection_boxes': boxes, 'detection_classes': classes, 'detection_scores': scores, }) # ---- OLN-Box finishes here. ---- if not self._include_mask: return model_outputs if is_training: rpn_rois, classes, mask_targets = self._sample_masks_fn( rpn_rois, matched_gt_boxes, matched_gt_classes, matched_gt_indices, inputs['gt_masks']) mask_targets = tf.stop_gradient(mask_targets) classes = tf.cast(classes, dtype=tf.int32) model_outputs.update({ 'mask_targets': mask_targets, 'sampled_class_targets': classes, }) else: rpn_rois = boxes classes = tf.cast(classes, dtype=tf.int32) mask_roi_features = spatial_transform_ops.multilevel_crop_and_resize( fpn_features, rpn_rois, output_size=14) mask_outputs = self._mrcnn_head_fn(mask_roi_features, classes, is_training) if is_training: model_outputs.update({ 'mask_outputs': tf.nest.map_structure(lambda x: tf.cast(x, tf.float32), mask_outputs), }) else: model_outputs.update({'detection_masks': tf.nn.sigmoid(mask_outputs)}) return model_outputs def build_loss_fn(self): if self._keras_model is None: raise ValueError('build_loss_fn() must be called after build_model().') filter_fn = self.make_filter_trainable_variables_fn() trainable_variables = filter_fn(self._keras_model.trainable_variables) def _total_loss_fn(labels, outputs): if self._include_rpn_class: rpn_score_loss = self._rpn_score_loss_fn(outputs['rpn_score_outputs'], labels['rpn_score_targets']) else: rpn_score_loss = 0.0 if self._include_centerness: rpn_center_loss = self._rpn_center_loss_fn( outputs['rpn_center_outputs'], labels['rpn_center_targets']) rpn_box_loss = self._rpn_iou_loss_fn( outputs['rpn_box_outputs'], labels['rpn_box_targets'], labels['rpn_center_targets']) else: rpn_center_loss = 0.0 rpn_box_loss = self._rpn_box_loss_fn( outputs['rpn_box_outputs'], labels['rpn_box_targets']) if self._include_frcnn_class: frcnn_class_loss = self._frcnn_class_loss_fn( outputs['class_outputs'], outputs['class_targets']) else: frcnn_class_loss = 0.0 if self._include_frcnn_box: frcnn_box_loss = self._frcnn_box_loss_fn( outputs['box_outputs'], outputs['class_targets'], outputs['box_targets']) else: frcnn_box_loss = 0.0 if self._include_box_score: box_score_loss = self._frcnn_box_score_loss_fn( outputs['box_score_outputs'], outputs['box_iou_targets']) else: box_score_loss = 0.0 if self._include_mask: mask_loss = self._mask_loss_fn(outputs['mask_outputs'], outputs['mask_targets'], outputs['sampled_class_targets']) else: mask_loss = 0.0 model_loss = ( rpn_score_loss + rpn_box_loss + rpn_center_loss + frcnn_class_loss + frcnn_box_loss + box_score_loss + mask_loss) l2_regularization_loss = self.weight_decay_loss(trainable_variables) total_loss = model_loss + l2_regularization_loss return { 'total_loss': total_loss, 'loss': total_loss, 'fast_rcnn_class_loss': frcnn_class_loss, 'fast_rcnn_box_loss': frcnn_box_loss, 'fast_rcnn_box_score_loss': box_score_loss, 'mask_loss': mask_loss, 'model_loss': model_loss, 'l2_regularization_loss': l2_regularization_loss, 'rpn_score_loss': rpn_score_loss, 'rpn_box_loss': rpn_box_loss, 'rpn_center_loss': rpn_center_loss, } return _total_loss_fn def build_input_layers(self, params, mode): is_training = mode == mode_keys.TRAIN input_shape = ( params.olnmask_parser.output_size + [params.olnmask_parser.num_channels]) if is_training: batch_size = params.train.batch_size input_layer = { 'image': tf.keras.layers.Input( shape=input_shape, batch_size=batch_size, name='image', dtype=tf.bfloat16 if self._use_bfloat16 else tf.float32), 'image_info': tf.keras.layers.Input( shape=[4, 2], batch_size=batch_size, name='image_info', ), 'gt_boxes': tf.keras.layers.Input( shape=[params.olnmask_parser.max_num_instances, 4], batch_size=batch_size, name='gt_boxes'), 'gt_classes': tf.keras.layers.Input( shape=[params.olnmask_parser.max_num_instances], batch_size=batch_size, name='gt_classes', dtype=tf.int64), } if self._include_mask: input_layer['gt_masks'] = tf.keras.layers.Input( shape=[ params.olnmask_parser.max_num_instances, params.olnmask_parser.mask_crop_size, params.olnmask_parser.mask_crop_size ], batch_size=batch_size, name='gt_masks') else: batch_size = params.eval.batch_size input_layer = { 'image': tf.keras.layers.Input( shape=input_shape, batch_size=batch_size, name='image', dtype=tf.bfloat16 if self._use_bfloat16 else tf.float32), 'image_info': tf.keras.layers.Input( shape=[4, 2], batch_size=batch_size, name='image_info', ), } return input_layer def build_model(self, params, mode): if self._keras_model is None: input_layers = self.build_input_layers(self._params, mode) outputs = self.model_outputs(input_layers, mode) model = tf.keras.models.Model( inputs=input_layers, outputs=outputs, name='olnmask') assert model is not None, 'Fail to build tf.keras.Model.' model.optimizer = self.build_optimizer() self._keras_model = model return self._keras_model
16,774
37.741339
80
py
models
models-master/official/legacy/detection/modeling/retinanet_model.py
# Copyright 2023 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. """Model defination for the RetinaNet Model.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from official.legacy.detection.dataloader import mode_keys from official.legacy.detection.evaluation import factory as eval_factory from official.legacy.detection.modeling import base_model from official.legacy.detection.modeling import losses from official.legacy.detection.modeling.architecture import factory from official.legacy.detection.ops import postprocess_ops class RetinanetModel(base_model.Model): """RetinaNet model function.""" def __init__(self, params): super(RetinanetModel, self).__init__(params) # For eval metrics. self._params = params # Architecture generators. self._backbone_fn = factory.backbone_generator(params) self._fpn_fn = factory.multilevel_features_generator(params) self._head_fn = factory.retinanet_head_generator(params) # Loss function. self._cls_loss_fn = losses.RetinanetClassLoss( params.retinanet_loss, params.architecture.num_classes) self._box_loss_fn = losses.RetinanetBoxLoss(params.retinanet_loss) self._box_loss_weight = params.retinanet_loss.box_loss_weight self._keras_model = None # Predict function. self._generate_detections_fn = postprocess_ops.MultilevelDetectionGenerator( params.architecture.min_level, params.architecture.max_level, params.postprocess) self._transpose_input = params.train.transpose_input assert not self._transpose_input, 'Transpose input is not supported.' # Input layer. self._input_layer = tf.keras.layers.Input( shape=(None, None, params.retinanet_parser.num_channels), name='', dtype=tf.bfloat16 if self._use_bfloat16 else tf.float32) def build_outputs(self, inputs, mode): # If the input image is transposed (from NHWC to HWCN), we need to revert it # back to the original shape before it's used in the computation. if self._transpose_input: inputs = tf.transpose(inputs, [3, 0, 1, 2]) backbone_features = self._backbone_fn( inputs, is_training=(mode == mode_keys.TRAIN)) fpn_features = self._fpn_fn( backbone_features, is_training=(mode == mode_keys.TRAIN)) cls_outputs, box_outputs = self._head_fn( fpn_features, is_training=(mode == mode_keys.TRAIN)) if self._use_bfloat16: levels = cls_outputs.keys() for level in levels: cls_outputs[level] = tf.cast(cls_outputs[level], tf.float32) box_outputs[level] = tf.cast(box_outputs[level], tf.float32) model_outputs = { 'cls_outputs': cls_outputs, 'box_outputs': box_outputs, } return model_outputs def build_loss_fn(self): if self._keras_model is None: raise ValueError('build_loss_fn() must be called after build_model().') filter_fn = self.make_filter_trainable_variables_fn() trainable_variables = filter_fn(self._keras_model.trainable_variables) def _total_loss_fn(labels, outputs): cls_loss = self._cls_loss_fn(outputs['cls_outputs'], labels['cls_targets'], labels['num_positives']) box_loss = self._box_loss_fn(outputs['box_outputs'], labels['box_targets'], labels['num_positives']) model_loss = cls_loss + self._box_loss_weight * box_loss l2_regularization_loss = self.weight_decay_loss(trainable_variables) total_loss = model_loss + l2_regularization_loss return { 'total_loss': total_loss, 'cls_loss': cls_loss, 'box_loss': box_loss, 'model_loss': model_loss, 'l2_regularization_loss': l2_regularization_loss, } return _total_loss_fn def build_model(self, params, mode=None): if self._keras_model is None: outputs = self.model_outputs(self._input_layer, mode) model = tf.keras.models.Model( inputs=self._input_layer, outputs=outputs, name='retinanet') assert model is not None, 'Fail to build tf.keras.Model.' model.optimizer = self.build_optimizer() self._keras_model = model return self._keras_model def post_processing(self, labels, outputs): # TODO(yeqing): Moves the output related part into build_outputs. required_output_fields = ['cls_outputs', 'box_outputs'] for field in required_output_fields: if field not in outputs: raise ValueError('"%s" is missing in outputs, requried %s found %s' % (field, required_output_fields, outputs.keys())) required_label_fields = ['image_info', 'groundtruths'] for field in required_label_fields: if field not in labels: raise ValueError('"%s" is missing in outputs, requried %s found %s' % (field, required_label_fields, labels.keys())) boxes, scores, classes, valid_detections = self._generate_detections_fn( outputs['box_outputs'], outputs['cls_outputs'], labels['anchor_boxes'], labels['image_info'][:, 1:2, :]) # Discards the old output tensors to save memory. The `cls_outputs` and # `box_outputs` are pretty big and could potentiall lead to memory issue. outputs = { 'source_id': labels['groundtruths']['source_id'], 'image_info': labels['image_info'], 'num_detections': valid_detections, 'detection_boxes': boxes, 'detection_classes': classes, 'detection_scores': scores, } if 'groundtruths' in labels: labels['source_id'] = labels['groundtruths']['source_id'] labels['boxes'] = labels['groundtruths']['boxes'] labels['classes'] = labels['groundtruths']['classes'] labels['areas'] = labels['groundtruths']['areas'] labels['is_crowds'] = labels['groundtruths']['is_crowds'] return labels, outputs def eval_metrics(self): return eval_factory.evaluator_generator(self._params.eval)
6,661
39.13253
80
py
models
models-master/official/legacy/detection/modeling/shapemask_model.py
# Copyright 2023 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. """Model definition for the ShapeMask Model.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from official.legacy.detection.dataloader import anchor from official.legacy.detection.dataloader import mode_keys from official.legacy.detection.evaluation import factory as eval_factory from official.legacy.detection.modeling import base_model from official.legacy.detection.modeling import losses from official.legacy.detection.modeling.architecture import factory from official.legacy.detection.ops import postprocess_ops from official.legacy.detection.utils import box_utils class ShapeMaskModel(base_model.Model): """ShapeMask model function.""" def __init__(self, params): super(ShapeMaskModel, self).__init__(params) self._params = params self._keras_model = None # Architecture generators. self._backbone_fn = factory.backbone_generator(params) self._fpn_fn = factory.multilevel_features_generator(params) self._retinanet_head_fn = factory.retinanet_head_generator(params) self._shape_prior_head_fn = factory.shapeprior_head_generator(params) self._coarse_mask_fn = factory.coarsemask_head_generator(params) self._fine_mask_fn = factory.finemask_head_generator(params) # Loss functions. self._cls_loss_fn = losses.RetinanetClassLoss( params.retinanet_loss, params.architecture.num_classes) self._box_loss_fn = losses.RetinanetBoxLoss(params.retinanet_loss) self._box_loss_weight = params.retinanet_loss.box_loss_weight # Mask loss function. self._shapemask_prior_loss_fn = losses.ShapemaskMseLoss() self._shapemask_loss_fn = losses.ShapemaskLoss() self._shape_prior_loss_weight = ( params.shapemask_loss.shape_prior_loss_weight) self._coarse_mask_loss_weight = ( params.shapemask_loss.coarse_mask_loss_weight) self._fine_mask_loss_weight = (params.shapemask_loss.fine_mask_loss_weight) # Predict function. self._generate_detections_fn = postprocess_ops.MultilevelDetectionGenerator( params.architecture.min_level, params.architecture.max_level, params.postprocess) def build_outputs(self, inputs, mode): is_training = mode == mode_keys.TRAIN images = inputs['image'] if 'anchor_boxes' in inputs: anchor_boxes = inputs['anchor_boxes'] else: anchor_boxes = anchor.Anchor( self._params.architecture.min_level, self._params.architecture.max_level, self._params.anchor.num_scales, self._params.anchor.aspect_ratios, self._params.anchor.anchor_size, images.get_shape().as_list()[1:3]).multilevel_boxes batch_size = tf.shape(images)[0] for level in anchor_boxes: anchor_boxes[level] = tf.tile( tf.expand_dims(anchor_boxes[level], 0), [batch_size, 1, 1, 1]) backbone_features = self._backbone_fn(images, is_training=is_training) fpn_features = self._fpn_fn(backbone_features, is_training=is_training) cls_outputs, box_outputs = self._retinanet_head_fn( fpn_features, is_training=is_training) valid_boxes, valid_scores, valid_classes, valid_detections = ( self._generate_detections_fn(box_outputs, cls_outputs, anchor_boxes, inputs['image_info'][:, 1:2, :])) image_size = images.get_shape().as_list()[1:3] valid_outer_boxes = box_utils.compute_outer_boxes( tf.reshape(valid_boxes, [-1, 4]), image_size, scale=self._params.shapemask_parser.outer_box_scale) valid_outer_boxes = tf.reshape(valid_outer_boxes, tf.shape(valid_boxes)) # Wrapping if else code paths into a layer to make the checkpoint loadable # in prediction mode. class SampledBoxesLayer(tf.keras.layers.Layer): """ShapeMask model function.""" def call(self, inputs, val_boxes, val_classes, val_outer_boxes, training): if training: boxes = inputs['mask_boxes'] outer_boxes = inputs['mask_outer_boxes'] classes = inputs['mask_classes'] else: boxes = val_boxes classes = val_classes outer_boxes = val_outer_boxes return boxes, classes, outer_boxes boxes, classes, outer_boxes = SampledBoxesLayer()( inputs, valid_boxes, valid_classes, valid_outer_boxes, training=is_training) instance_features, prior_masks = self._shape_prior_head_fn( fpn_features, boxes, outer_boxes, classes, is_training) coarse_mask_logits = self._coarse_mask_fn(instance_features, prior_masks, classes, is_training) fine_mask_logits = self._fine_mask_fn(instance_features, coarse_mask_logits, classes, is_training) model_outputs = { 'cls_outputs': cls_outputs, 'box_outputs': box_outputs, 'fine_mask_logits': fine_mask_logits, 'coarse_mask_logits': coarse_mask_logits, 'prior_masks': prior_masks, } if not is_training: model_outputs.update({ 'num_detections': valid_detections, 'detection_boxes': valid_boxes, 'detection_outer_boxes': valid_outer_boxes, 'detection_masks': fine_mask_logits, 'detection_classes': valid_classes, 'detection_scores': valid_scores, }) return model_outputs def build_loss_fn(self): if self._keras_model is None: raise ValueError('build_loss_fn() must be called after build_model().') filter_fn = self.make_filter_trainable_variables_fn() trainable_variables = filter_fn(self._keras_model.trainable_variables) def _total_loss_fn(labels, outputs): cls_loss = self._cls_loss_fn(outputs['cls_outputs'], labels['cls_targets'], labels['num_positives']) box_loss = self._box_loss_fn(outputs['box_outputs'], labels['box_targets'], labels['num_positives']) # Adds Shapemask model losses. shape_prior_loss = self._shapemask_prior_loss_fn(outputs['prior_masks'], labels['mask_targets'], labels['mask_is_valid']) coarse_mask_loss = self._shapemask_loss_fn(outputs['coarse_mask_logits'], labels['mask_targets'], labels['mask_is_valid']) fine_mask_loss = self._shapemask_loss_fn(outputs['fine_mask_logits'], labels['fine_mask_targets'], labels['mask_is_valid']) model_loss = ( cls_loss + self._box_loss_weight * box_loss + shape_prior_loss * self._shape_prior_loss_weight + coarse_mask_loss * self._coarse_mask_loss_weight + fine_mask_loss * self._fine_mask_loss_weight) l2_regularization_loss = self.weight_decay_loss(trainable_variables) total_loss = model_loss + l2_regularization_loss shapemask_losses = { 'total_loss': total_loss, 'loss': total_loss, 'retinanet_cls_loss': cls_loss, 'l2_regularization_loss': l2_regularization_loss, 'retinanet_box_loss': box_loss, 'shapemask_prior_loss': shape_prior_loss, 'shapemask_coarse_mask_loss': coarse_mask_loss, 'shapemask_fine_mask_loss': fine_mask_loss, 'model_loss': model_loss, } return shapemask_losses return _total_loss_fn def build_input_layers(self, params, mode): is_training = mode == mode_keys.TRAIN input_shape = ( params.shapemask_parser.output_size + [params.shapemask_parser.num_channels]) if is_training: batch_size = params.train.batch_size input_layer = { 'image': tf.keras.layers.Input( shape=input_shape, batch_size=batch_size, name='image', dtype=tf.bfloat16 if self._use_bfloat16 else tf.float32), 'image_info': tf.keras.layers.Input( shape=[4, 2], batch_size=batch_size, name='image_info'), 'mask_classes': tf.keras.layers.Input( shape=[params.shapemask_parser.num_sampled_masks], batch_size=batch_size, name='mask_classes', dtype=tf.int64), 'mask_outer_boxes': tf.keras.layers.Input( shape=[params.shapemask_parser.num_sampled_masks, 4], batch_size=batch_size, name='mask_outer_boxes', dtype=tf.float32), 'mask_boxes': tf.keras.layers.Input( shape=[params.shapemask_parser.num_sampled_masks, 4], batch_size=batch_size, name='mask_boxes', dtype=tf.float32), } else: batch_size = params.eval.batch_size input_layer = { 'image': tf.keras.layers.Input( shape=input_shape, batch_size=batch_size, name='image', dtype=tf.bfloat16 if self._use_bfloat16 else tf.float32), 'image_info': tf.keras.layers.Input( shape=[4, 2], batch_size=batch_size, name='image_info'), } return input_layer def build_model(self, params, mode): if self._keras_model is None: input_layers = self.build_input_layers(self._params, mode) outputs = self.model_outputs(input_layers, mode) model = tf.keras.models.Model( inputs=input_layers, outputs=outputs, name='shapemask') assert model is not None, 'Fail to build tf.keras.Model.' model.optimizer = self.build_optimizer() self._keras_model = model return self._keras_model def post_processing(self, labels, outputs): required_output_fields = [ 'num_detections', 'detection_boxes', 'detection_classes', 'detection_masks', 'detection_scores' ] for field in required_output_fields: if field not in outputs: raise ValueError( '"{}" is missing in outputs, requried {} found {}'.format( field, required_output_fields, outputs.keys())) required_label_fields = ['image_info'] for field in required_label_fields: if field not in labels: raise ValueError( '"{}" is missing in labels, requried {} found {}'.format( field, required_label_fields, labels.keys())) predictions = { 'image_info': labels['image_info'], 'num_detections': outputs['num_detections'], 'detection_boxes': outputs['detection_boxes'], 'detection_outer_boxes': outputs['detection_outer_boxes'], 'detection_classes': outputs['detection_classes'], 'detection_scores': outputs['detection_scores'], 'detection_masks': outputs['detection_masks'], } if 'groundtruths' in labels: predictions['source_id'] = labels['groundtruths']['source_id'] labels = labels['groundtruths'] return labels, predictions def eval_metrics(self): return eval_factory.evaluator_generator(self._params.eval)
12,110
38.708197
80
py
models
models-master/official/legacy/detection/modeling/architecture/spinenet.py
# Copyright 2023 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. # ============================================================================== """Implementation of SpineNet model. X. Du, T-Y. Lin, P. Jin, G. Ghiasi, M. Tan, Y. Cui, Q. V. Le, X. Song SpineNet: Learning Scale-Permuted Backbone for Recognition and Localization https://arxiv.org/abs/1912.05027 """ import math from absl import logging import tensorflow as tf from official.legacy.detection.modeling.architecture import nn_blocks from official.modeling import tf_utils layers = tf.keras.layers FILTER_SIZE_MAP = { 1: 32, 2: 64, 3: 128, 4: 256, 5: 256, 6: 256, 7: 256, } # The fixed SpineNet architecture discovered by NAS. # Each element represents a specification of a building block: # (block_level, block_fn, (input_offset0, input_offset1), is_output). SPINENET_BLOCK_SPECS = [ (2, 'bottleneck', (0, 1), False), (4, 'residual', (0, 1), False), (3, 'bottleneck', (2, 3), False), (4, 'bottleneck', (2, 4), False), (6, 'residual', (3, 5), False), (4, 'bottleneck', (3, 5), False), (5, 'residual', (6, 7), False), (7, 'residual', (6, 8), False), (5, 'bottleneck', (8, 9), False), (5, 'bottleneck', (8, 10), False), (4, 'bottleneck', (5, 10), True), (3, 'bottleneck', (4, 10), True), (5, 'bottleneck', (7, 12), True), (7, 'bottleneck', (5, 14), True), (6, 'bottleneck', (12, 14), True), ] SCALING_MAP = { '49S': { 'endpoints_num_filters': 128, 'filter_size_scale': 0.65, 'resample_alpha': 0.5, 'block_repeats': 1, }, '49': { 'endpoints_num_filters': 256, 'filter_size_scale': 1.0, 'resample_alpha': 0.5, 'block_repeats': 1, }, '96': { 'endpoints_num_filters': 256, 'filter_size_scale': 1.0, 'resample_alpha': 0.5, 'block_repeats': 2, }, '143': { 'endpoints_num_filters': 256, 'filter_size_scale': 1.0, 'resample_alpha': 1.0, 'block_repeats': 3, }, '190': { 'endpoints_num_filters': 512, 'filter_size_scale': 1.3, 'resample_alpha': 1.0, 'block_repeats': 4, }, } class BlockSpec(object): """A container class that specifies the block configuration for SpineNet.""" def __init__(self, level, block_fn, input_offsets, is_output): self.level = level self.block_fn = block_fn self.input_offsets = input_offsets self.is_output = is_output def build_block_specs(block_specs=None): """Builds the list of BlockSpec objects for SpineNet.""" if not block_specs: block_specs = SPINENET_BLOCK_SPECS logging.info('Building SpineNet block specs: %s', block_specs) return [BlockSpec(*b) for b in block_specs] class SpineNet(tf.keras.Model): """Class to build SpineNet models.""" def __init__(self, input_specs=tf.keras.layers.InputSpec(shape=[None, 640, 640, 3]), min_level=3, max_level=7, block_specs=None, endpoints_num_filters=256, resample_alpha=0.5, block_repeats=1, filter_size_scale=1.0, kernel_initializer='VarianceScaling', kernel_regularizer=None, bias_regularizer=None, activation='relu', use_sync_bn=False, norm_momentum=0.99, norm_epsilon=0.001, **kwargs): """SpineNet model.""" self._min_level = min_level self._max_level = max_level self._block_specs = ( build_block_specs() if block_specs is None else block_specs ) self._endpoints_num_filters = endpoints_num_filters self._resample_alpha = resample_alpha self._block_repeats = block_repeats self._filter_size_scale = filter_size_scale self._kernel_initializer = kernel_initializer self._kernel_regularizer = kernel_regularizer self._bias_regularizer = bias_regularizer self._use_sync_bn = use_sync_bn self._norm_momentum = norm_momentum self._norm_epsilon = norm_epsilon if activation == 'relu': self._activation = tf.nn.relu elif activation == 'swish': self._activation = tf.nn.swish else: raise ValueError('Activation {} not implemented.'.format(activation)) self._init_block_fn = 'bottleneck' self._num_init_blocks = 2 if use_sync_bn: self._norm = layers.experimental.SyncBatchNormalization else: self._norm = layers.BatchNormalization if tf.keras.backend.image_data_format() == 'channels_last': self._bn_axis = -1 else: self._bn_axis = 1 # Build SpineNet. inputs = tf.keras.Input(shape=input_specs.shape[1:]) net = self._build_stem(inputs=inputs) net = self._build_scale_permuted_network( net=net, input_width=input_specs.shape[1]) net = self._build_endpoints(net=net) super(SpineNet, self).__init__(inputs=inputs, outputs=net) def _block_group(self, inputs, filters, strides, block_fn_cand, block_repeats=1, name='block_group'): """Creates one group of blocks for the SpineNet model.""" block_fn_candidates = { 'bottleneck': nn_blocks.BottleneckBlock, 'residual': nn_blocks.ResidualBlock, } block_fn = block_fn_candidates[block_fn_cand] _, _, _, num_filters = inputs.get_shape().as_list() if block_fn_cand == 'bottleneck': use_projection = not (num_filters == (filters * 4) and strides == 1) else: use_projection = not (num_filters == filters and strides == 1) x = block_fn( filters=filters, strides=strides, use_projection=use_projection, kernel_initializer=self._kernel_initializer, kernel_regularizer=self._kernel_regularizer, bias_regularizer=self._bias_regularizer, activation=self._activation, use_sync_bn=self._use_sync_bn, norm_momentum=self._norm_momentum, norm_epsilon=self._norm_epsilon)( inputs) for _ in range(1, block_repeats): x = block_fn( filters=filters, strides=1, use_projection=False, kernel_initializer=self._kernel_initializer, kernel_regularizer=self._kernel_regularizer, bias_regularizer=self._bias_regularizer, activation=self._activation, use_sync_bn=self._use_sync_bn, norm_momentum=self._norm_momentum, norm_epsilon=self._norm_epsilon)( x) return tf.identity(x, name=name) def _build_stem(self, inputs): """Build SpineNet stem.""" x = layers.Conv2D( filters=64, kernel_size=7, strides=2, use_bias=False, padding='same', kernel_initializer=self._kernel_initializer, kernel_regularizer=self._kernel_regularizer, bias_regularizer=self._bias_regularizer)( inputs) x = self._norm( axis=self._bn_axis, momentum=self._norm_momentum, epsilon=self._norm_epsilon)( x) x = tf_utils.get_activation(self._activation)(x) x = layers.MaxPool2D(pool_size=3, strides=2, padding='same')(x) net = [] # Build the initial level 2 blocks. for i in range(self._num_init_blocks): x = self._block_group( inputs=x, filters=int(FILTER_SIZE_MAP[2] * self._filter_size_scale), strides=1, block_fn_cand=self._init_block_fn, block_repeats=self._block_repeats, name='stem_block_{}'.format(i + 1)) net.append(x) return net def _build_scale_permuted_network(self, net, input_width, weighted_fusion=False): """Build scale-permuted network.""" net_sizes = [int(math.ceil(input_width / 2**2))] * len(net) net_block_fns = [self._init_block_fn] * len(net) num_outgoing_connections = [0] * len(net) endpoints = {} for i, block_spec in enumerate(self._block_specs): # Find out specs for the target block. target_width = int(math.ceil(input_width / 2**block_spec.level)) target_num_filters = int(FILTER_SIZE_MAP[block_spec.level] * self._filter_size_scale) target_block_fn = block_spec.block_fn # Resample then merge input0 and input1. parents = [] input0 = block_spec.input_offsets[0] input1 = block_spec.input_offsets[1] x0 = self._resample_with_alpha( inputs=net[input0], input_width=net_sizes[input0], input_block_fn=net_block_fns[input0], target_width=target_width, target_num_filters=target_num_filters, target_block_fn=target_block_fn, alpha=self._resample_alpha) parents.append(x0) num_outgoing_connections[input0] += 1 x1 = self._resample_with_alpha( inputs=net[input1], input_width=net_sizes[input1], input_block_fn=net_block_fns[input1], target_width=target_width, target_num_filters=target_num_filters, target_block_fn=target_block_fn, alpha=self._resample_alpha) parents.append(x1) num_outgoing_connections[input1] += 1 # Merge 0 outdegree blocks to the output block. if block_spec.is_output: for j, (j_feat, j_connections) in enumerate(zip(net, num_outgoing_connections)): if j_connections == 0 and (j_feat.shape[2] == target_width and j_feat.shape[3] == x0.shape[3]): parents.append(j_feat) num_outgoing_connections[j] += 1 # pylint: disable=g-direct-tensorflow-import if weighted_fusion: dtype = parents[0].dtype parent_weights = [ tf.nn.relu(tf.cast(tf.Variable(1.0, name='block{}_fusion{}'.format( i, j)), dtype=dtype)) for j in range(len(parents))] weights_sum = tf.add_n(parent_weights) parents = [ parents[i] * parent_weights[i] / (weights_sum + 0.0001) for i in range(len(parents)) ] # Fuse all parent nodes then build a new block. x = tf_utils.get_activation(self._activation)(tf.add_n(parents)) x = self._block_group( inputs=x, filters=target_num_filters, strides=1, block_fn_cand=target_block_fn, block_repeats=self._block_repeats, name='scale_permuted_block_{}'.format(i + 1)) net.append(x) net_sizes.append(target_width) net_block_fns.append(target_block_fn) num_outgoing_connections.append(0) # Save output feats. if block_spec.is_output: if block_spec.level in endpoints: raise ValueError('Duplicate feats found for output level {}.'.format( block_spec.level)) if (block_spec.level < self._min_level or block_spec.level > self._max_level): raise ValueError('Output level is out of range [{}, {}]'.format( self._min_level, self._max_level)) endpoints[block_spec.level] = x return endpoints def _build_endpoints(self, net): """Match filter size for endpoints before sharing conv layers.""" endpoints = {} for level in range(self._min_level, self._max_level + 1): x = layers.Conv2D( filters=self._endpoints_num_filters, kernel_size=1, strides=1, use_bias=False, kernel_initializer=self._kernel_initializer, kernel_regularizer=self._kernel_regularizer, bias_regularizer=self._bias_regularizer)( net[level]) x = self._norm( axis=self._bn_axis, momentum=self._norm_momentum, epsilon=self._norm_epsilon)( x) x = tf_utils.get_activation(self._activation)(x) endpoints[level] = x return endpoints def _resample_with_alpha(self, inputs, input_width, input_block_fn, target_width, target_num_filters, target_block_fn, alpha=0.5): """Match resolution and feature dimension.""" _, _, _, input_num_filters = inputs.get_shape().as_list() if input_block_fn == 'bottleneck': input_num_filters /= 4 new_num_filters = int(input_num_filters * alpha) x = layers.Conv2D( filters=new_num_filters, kernel_size=1, strides=1, use_bias=False, kernel_initializer=self._kernel_initializer, kernel_regularizer=self._kernel_regularizer, bias_regularizer=self._bias_regularizer)( inputs) x = self._norm( axis=self._bn_axis, momentum=self._norm_momentum, epsilon=self._norm_epsilon)( x) x = tf_utils.get_activation(self._activation)(x) # Spatial resampling. if input_width > target_width: x = layers.Conv2D( filters=new_num_filters, kernel_size=3, strides=2, padding='SAME', use_bias=False, kernel_initializer=self._kernel_initializer, kernel_regularizer=self._kernel_regularizer, bias_regularizer=self._bias_regularizer)( x) x = self._norm( axis=self._bn_axis, momentum=self._norm_momentum, epsilon=self._norm_epsilon)( x) x = tf_utils.get_activation(self._activation)(x) input_width /= 2 while input_width > target_width: x = layers.MaxPool2D(pool_size=3, strides=2, padding='SAME')(x) input_width /= 2 elif input_width < target_width: scale = target_width // input_width x = layers.UpSampling2D(size=(scale, scale))(x) # Last 1x1 conv to match filter size. if target_block_fn == 'bottleneck': target_num_filters *= 4 x = layers.Conv2D( filters=target_num_filters, kernel_size=1, strides=1, use_bias=False, kernel_initializer=self._kernel_initializer, kernel_regularizer=self._kernel_regularizer, bias_regularizer=self._bias_regularizer)( x) x = self._norm( axis=self._bn_axis, momentum=self._norm_momentum, epsilon=self._norm_epsilon)( x) return x class SpineNetBuilder(object): """SpineNet builder.""" def __init__(self, model_id, input_specs=tf.keras.layers.InputSpec(shape=[None, 640, 640, 3]), min_level=3, max_level=7, block_specs=None, kernel_initializer='VarianceScaling', kernel_regularizer=None, bias_regularizer=None, activation='relu', use_sync_bn=False, norm_momentum=0.99, norm_epsilon=0.001): if model_id not in SCALING_MAP: raise ValueError( 'SpineNet {} is not a valid architecture.'.format(model_id)) scaling_params = SCALING_MAP[model_id] self._input_specs = input_specs self._min_level = min_level self._max_level = max_level self._block_specs = block_specs or build_block_specs() self._endpoints_num_filters = scaling_params['endpoints_num_filters'] self._resample_alpha = scaling_params['resample_alpha'] self._block_repeats = scaling_params['block_repeats'] self._filter_size_scale = scaling_params['filter_size_scale'] self._kernel_initializer = kernel_initializer self._kernel_regularizer = kernel_regularizer self._bias_regularizer = bias_regularizer self._activation = activation self._use_sync_bn = use_sync_bn self._norm_momentum = norm_momentum self._norm_epsilon = norm_epsilon def __call__(self, inputs, is_training=None): model = SpineNet( input_specs=self._input_specs, min_level=self._min_level, max_level=self._max_level, block_specs=self._block_specs, endpoints_num_filters=self._endpoints_num_filters, resample_alpha=self._resample_alpha, block_repeats=self._block_repeats, filter_size_scale=self._filter_size_scale, kernel_initializer=self._kernel_initializer, kernel_regularizer=self._kernel_regularizer, bias_regularizer=self._bias_regularizer, activation=self._activation, use_sync_bn=self._use_sync_bn, norm_momentum=self._norm_momentum, norm_epsilon=self._norm_epsilon) return model(inputs)
17,327
33.312871
80
py
models
models-master/official/legacy/detection/modeling/architecture/resnet.py
# Copyright 2023 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 definitions for the post-activation form of Residual Networks. Residual networks (ResNets) were proposed in: [1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun Deep Residual Learning for Image Recognition. arXiv:1512.03385 """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from official.legacy.detection.modeling.architecture import nn_ops # TODO(b/140112644): Refactor the code with Keras style, i.e. build and call. class Resnet(object): """Class to build ResNet family model.""" def __init__( self, resnet_depth, activation='relu', norm_activation=nn_ops.norm_activation_builder(activation='relu'), data_format='channels_last'): """ResNet initialization function. Args: resnet_depth: `int` depth of ResNet backbone model. activation: the activation function. norm_activation: an operation that includes a normalization layer followed by an optional activation layer. data_format: `str` either "channels_first" for `[batch, channels, height, width]` or "channels_last for `[batch, height, width, channels]`. """ self._resnet_depth = resnet_depth if activation == 'relu': self._activation_op = tf.nn.relu elif activation == 'swish': self._activation_op = tf.nn.swish else: raise ValueError('Unsupported activation `{}`.'.format(activation)) self._norm_activation = norm_activation self._data_format = data_format model_params = { 10: { 'block': self.residual_block, 'layers': [1, 1, 1, 1] }, 18: { 'block': self.residual_block, 'layers': [2, 2, 2, 2] }, 34: { 'block': self.residual_block, 'layers': [3, 4, 6, 3] }, 50: { 'block': self.bottleneck_block, 'layers': [3, 4, 6, 3] }, 101: { 'block': self.bottleneck_block, 'layers': [3, 4, 23, 3] }, 152: { 'block': self.bottleneck_block, 'layers': [3, 8, 36, 3] }, 200: { 'block': self.bottleneck_block, 'layers': [3, 24, 36, 3] } } if resnet_depth not in model_params: valid_resnet_depths = ', '.join( [str(depth) for depth in sorted(model_params.keys())]) raise ValueError( 'The resnet_depth should be in [%s]. Not a valid resnet_depth:' % (valid_resnet_depths), self._resnet_depth) params = model_params[resnet_depth] self._resnet_fn = self.resnet_v1_generator(params['block'], params['layers']) def __call__(self, inputs, is_training=None): """Returns the ResNet model for a given size and number of output classes. Args: inputs: a `Tesnor` with shape [batch_size, height, width, 3] representing a batch of images. is_training: `bool` if True, the model is in training mode. Returns: a `dict` containing `int` keys for continuous feature levels [2, 3, 4, 5]. The values are corresponding feature hierarchy in ResNet with shape [batch_size, height_l, width_l, num_filters]. """ with tf.name_scope('resnet%s' % self._resnet_depth): return self._resnet_fn(inputs, is_training) def fixed_padding(self, inputs, kernel_size): """Pads the input along the spatial dimensions independently of input size. Args: inputs: `Tensor` of size `[batch, channels, height, width]` or `[batch, height, width, channels]` depending on `data_format`. kernel_size: `int` kernel size to be used for `conv2d` or max_pool2d` operations. Should be a positive integer. Returns: A padded `Tensor` of the same `data_format` with size either intact (if `kernel_size == 1`) or padded (if `kernel_size > 1`). """ pad_total = kernel_size - 1 pad_beg = pad_total // 2 pad_end = pad_total - pad_beg if self._data_format == 'channels_first': padded_inputs = tf.pad( tensor=inputs, paddings=[[0, 0], [0, 0], [pad_beg, pad_end], [pad_beg, pad_end]]) else: padded_inputs = tf.pad( tensor=inputs, paddings=[[0, 0], [pad_beg, pad_end], [pad_beg, pad_end], [0, 0]]) return padded_inputs def conv2d_fixed_padding(self, inputs, filters, kernel_size, strides): """Strided 2-D convolution with explicit padding. The padding is consistent and is based only on `kernel_size`, not on the dimensions of `inputs` (as opposed to using `tf.layers.conv2d` alone). Args: inputs: `Tensor` of size `[batch, channels, height_in, width_in]`. filters: `int` number of filters in the convolution. kernel_size: `int` size of the kernel to be used in the convolution. strides: `int` strides of the convolution. Returns: A `Tensor` of shape `[batch, filters, height_out, width_out]`. """ if strides > 1: inputs = self.fixed_padding(inputs, kernel_size) return tf.keras.layers.Conv2D( filters=filters, kernel_size=kernel_size, strides=strides, padding=('SAME' if strides == 1 else 'VALID'), use_bias=False, kernel_initializer=tf.initializers.VarianceScaling(), data_format=self._data_format)( inputs=inputs) def residual_block(self, inputs, filters, strides, use_projection=False, is_training=None): """Standard building block for residual networks with BN after convolutions. Args: inputs: `Tensor` of size `[batch, channels, height, width]`. filters: `int` number of filters for the first two convolutions. Note that the third and final convolution will use 4 times as many filters. strides: `int` block stride. If greater than 1, this block will ultimately downsample the input. use_projection: `bool` for whether this block should use a projection shortcut (versus the default identity shortcut). This is usually `True` for the first block of a block group, which may change the number of filters and the resolution. is_training: `bool` if True, the model is in training mode. Returns: The output `Tensor` of the block. """ shortcut = inputs if use_projection: # Projection shortcut in first layer to match filters and strides shortcut = self.conv2d_fixed_padding( inputs=inputs, filters=filters, kernel_size=1, strides=strides) shortcut = self._norm_activation(use_activation=False)( shortcut, is_training=is_training) inputs = self.conv2d_fixed_padding( inputs=inputs, filters=filters, kernel_size=3, strides=strides) inputs = self._norm_activation()(inputs, is_training=is_training) inputs = self.conv2d_fixed_padding( inputs=inputs, filters=filters, kernel_size=3, strides=1) inputs = self._norm_activation( use_activation=False, init_zero=True)( inputs, is_training=is_training) return self._activation_op(inputs + shortcut) def bottleneck_block(self, inputs, filters, strides, use_projection=False, is_training=None): """Bottleneck block variant for residual networks with BN after convolutions. Args: inputs: `Tensor` of size `[batch, channels, height, width]`. filters: `int` number of filters for the first two convolutions. Note that the third and final convolution will use 4 times as many filters. strides: `int` block stride. If greater than 1, this block will ultimately downsample the input. use_projection: `bool` for whether this block should use a projection shortcut (versus the default identity shortcut). This is usually `True` for the first block of a block group, which may change the number of filters and the resolution. is_training: `bool` if True, the model is in training mode. Returns: The output `Tensor` of the block. """ shortcut = inputs if use_projection: # Projection shortcut only in first block within a group. Bottleneck # blocks end with 4 times the number of filters. filters_out = 4 * filters shortcut = self.conv2d_fixed_padding( inputs=inputs, filters=filters_out, kernel_size=1, strides=strides) shortcut = self._norm_activation(use_activation=False)( shortcut, is_training=is_training) inputs = self.conv2d_fixed_padding( inputs=inputs, filters=filters, kernel_size=1, strides=1) inputs = self._norm_activation()(inputs, is_training=is_training) inputs = self.conv2d_fixed_padding( inputs=inputs, filters=filters, kernel_size=3, strides=strides) inputs = self._norm_activation()(inputs, is_training=is_training) inputs = self.conv2d_fixed_padding( inputs=inputs, filters=4 * filters, kernel_size=1, strides=1) inputs = self._norm_activation( use_activation=False, init_zero=True)( inputs, is_training=is_training) return self._activation_op(inputs + shortcut) def block_group(self, inputs, filters, block_fn, blocks, strides, name, is_training): """Creates one group of blocks for the ResNet model. Args: inputs: `Tensor` of size `[batch, channels, height, width]`. filters: `int` number of filters for the first convolution of the layer. block_fn: `function` for the block to use within the model blocks: `int` number of blocks contained in the layer. strides: `int` stride to use for the first convolution of the layer. If greater than 1, this layer will downsample the input. name: `str`name for the Tensor output of the block layer. is_training: `bool` if True, the model is in training mode. Returns: The output `Tensor` of the block layer. """ # Only the first block per block_group uses projection shortcut and strides. inputs = block_fn( inputs, filters, strides, use_projection=True, is_training=is_training) for _ in range(1, blocks): inputs = block_fn(inputs, filters, 1, is_training=is_training) return tf.identity(inputs, name) def resnet_v1_generator(self, block_fn, layers): """Generator for ResNet v1 models. Args: block_fn: `function` for the block to use within the model. Either `residual_block` or `bottleneck_block`. layers: list of 4 `int`s denoting the number of blocks to include in each of the 4 block groups. Each group consists of blocks that take inputs of the same resolution. Returns: Model `function` that takes in `inputs` and `is_training` and returns the output `Tensor` of the ResNet model. """ def model(inputs, is_training=None): """Creation of the model graph.""" inputs = self.conv2d_fixed_padding( inputs=inputs, filters=64, kernel_size=7, strides=2) inputs = tf.identity(inputs, 'initial_conv') inputs = self._norm_activation()(inputs, is_training=is_training) inputs = tf.keras.layers.MaxPool2D( pool_size=3, strides=2, padding='SAME', data_format=self._data_format)( inputs) inputs = tf.identity(inputs, 'initial_max_pool') c2 = self.block_group( inputs=inputs, filters=64, block_fn=block_fn, blocks=layers[0], strides=1, name='block_group1', is_training=is_training) c3 = self.block_group( inputs=c2, filters=128, block_fn=block_fn, blocks=layers[1], strides=2, name='block_group2', is_training=is_training) c4 = self.block_group( inputs=c3, filters=256, block_fn=block_fn, blocks=layers[2], strides=2, name='block_group3', is_training=is_training) c5 = self.block_group( inputs=c4, filters=512, block_fn=block_fn, blocks=layers[3], strides=2, name='block_group4', is_training=is_training) return {2: c2, 3: c3, 4: c4, 5: c5} return model
13,159
36.280453
81
py
models
models-master/official/legacy/detection/modeling/architecture/nn_ops.py
# Copyright 2023 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. """Neural network operations commonly shared by the architectures.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import functools import tensorflow as tf class NormActivation(tf.keras.layers.Layer): """Combined Normalization and Activation layers.""" def __init__(self, momentum=0.997, epsilon=1e-4, trainable=True, init_zero=False, use_activation=True, activation='relu', fused=True, name=None): """A class to construct layers for a batch normalization followed by a ReLU. Args: momentum: momentum for the moving average. epsilon: small float added to variance to avoid dividing by zero. trainable: `bool`, if True also add variables to the graph collection GraphKeys.TRAINABLE_VARIABLES. If False, freeze batch normalization layer. init_zero: `bool` if True, initializes scale parameter of batch normalization with 0. If False, initialize it with 1. use_activation: `bool`, whether to add the optional activation layer after the batch normalization layer. activation: 'string', the type of the activation layer. Currently support `relu` and `swish`. fused: `bool` fused option in batch normalziation. name: `str` name for the operation. """ super(NormActivation, self).__init__(trainable=trainable) if init_zero: gamma_initializer = tf.keras.initializers.Zeros() else: gamma_initializer = tf.keras.initializers.Ones() self._normalization_op = tf.keras.layers.BatchNormalization( momentum=momentum, epsilon=epsilon, center=True, scale=True, trainable=trainable, fused=fused, gamma_initializer=gamma_initializer, name=name) self._use_activation = use_activation if activation == 'relu': self._activation_op = tf.nn.relu elif activation == 'swish': self._activation_op = tf.nn.swish else: raise ValueError('Unsupported activation `{}`.'.format(activation)) def __call__(self, inputs, is_training=None): """Builds the normalization layer followed by an optional activation layer. Args: inputs: `Tensor` of shape `[batch, channels, ...]`. is_training: `boolean`, if True if model is in training mode. Returns: A normalized `Tensor` with the same `data_format`. """ # We will need to keep training=None by default, so that it can be inherit # from keras.Model.training if is_training and self.trainable: is_training = True inputs = self._normalization_op(inputs, training=is_training) if self._use_activation: inputs = self._activation_op(inputs) return inputs def norm_activation_builder(momentum=0.997, epsilon=1e-4, trainable=True, activation='relu', **kwargs): return functools.partial( NormActivation, momentum=momentum, epsilon=epsilon, trainable=trainable, activation=activation, **kwargs)
3,853
34.036364
80
py
models
models-master/official/legacy/detection/modeling/architecture/heads.py
# Copyright 2023 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. """Classes to build various prediction heads in all supported models.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import functools import numpy as np import tensorflow as tf from official.legacy.detection.modeling.architecture import nn_ops from official.legacy.detection.ops import spatial_transform_ops class RpnHead(tf.keras.layers.Layer): """Region Proposal Network head.""" def __init__( self, min_level, max_level, anchors_per_location, num_convs=2, num_filters=256, use_separable_conv=False, activation='relu', use_batch_norm=True, norm_activation=nn_ops.norm_activation_builder(activation='relu')): """Initialize params to build Region Proposal Network head. Args: min_level: `int` number of minimum feature level. max_level: `int` number of maximum feature level. anchors_per_location: `int` number of number of anchors per pixel location. num_convs: `int` number that represents the number of the intermediate conv layers before the prediction. num_filters: `int` number that represents the number of filters of the intermediate conv layers. use_separable_conv: `bool`, indicating whether the separable conv layers is used. activation: activation function. Support 'relu' and 'swish'. use_batch_norm: 'bool', indicating whether batchnorm layers are added. norm_activation: an operation that includes a normalization layer followed by an optional activation layer. """ super().__init__(autocast=False) self._min_level = min_level self._max_level = max_level self._anchors_per_location = anchors_per_location if activation == 'relu': self._activation_op = tf.nn.relu elif activation == 'swish': self._activation_op = tf.nn.swish else: raise ValueError('Unsupported activation `{}`.'.format(activation)) self._use_batch_norm = use_batch_norm if use_separable_conv: self._conv2d_op = functools.partial( tf.keras.layers.SeparableConv2D, depth_multiplier=1, bias_initializer=tf.zeros_initializer()) else: self._conv2d_op = functools.partial( tf.keras.layers.Conv2D, kernel_initializer=tf.keras.initializers.RandomNormal(stddev=0.01), bias_initializer=tf.zeros_initializer()) self._rpn_conv = self._conv2d_op( num_filters, kernel_size=(3, 3), strides=(1, 1), activation=(None if self._use_batch_norm else self._activation_op), padding='same', name='rpn') self._rpn_class_conv = self._conv2d_op( anchors_per_location, kernel_size=(1, 1), strides=(1, 1), padding='valid', name='rpn-class') self._rpn_box_conv = self._conv2d_op( 4 * anchors_per_location, kernel_size=(1, 1), strides=(1, 1), padding='valid', name='rpn-box') self._norm_activations = {} if self._use_batch_norm: for level in range(self._min_level, self._max_level + 1): self._norm_activations[level] = norm_activation(name='rpn-l%d-bn' % level) def _shared_rpn_heads(self, features, anchors_per_location, level, is_training): """Shared RPN heads.""" features = self._rpn_conv(features) if self._use_batch_norm: # The batch normalization layers are not shared between levels. features = self._norm_activations[level]( features, is_training=is_training) # Proposal classification scores scores = self._rpn_class_conv(features) # Proposal bbox regression deltas bboxes = self._rpn_box_conv(features) return scores, bboxes def call(self, features, is_training=None): scores_outputs = {} box_outputs = {} with tf.name_scope('rpn_head'): for level in range(self._min_level, self._max_level + 1): scores_output, box_output = self._shared_rpn_heads( features[level], self._anchors_per_location, level, is_training) scores_outputs[level] = scores_output box_outputs[level] = box_output return scores_outputs, box_outputs class OlnRpnHead(tf.keras.layers.Layer): """Region Proposal Network for Object Localization Network (OLN).""" def __init__( self, min_level, max_level, anchors_per_location, num_convs=2, num_filters=256, use_separable_conv=False, activation='relu', use_batch_norm=True, norm_activation=nn_ops.norm_activation_builder(activation='relu')): """Initialize params to build Region Proposal Network head. Args: min_level: `int` number of minimum feature level. max_level: `int` number of maximum feature level. anchors_per_location: `int` number of number of anchors per pixel location. num_convs: `int` number that represents the number of the intermediate conv layers before the prediction. num_filters: `int` number that represents the number of filters of the intermediate conv layers. use_separable_conv: `bool`, indicating whether the separable conv layers is used. activation: activation function. Support 'relu' and 'swish'. use_batch_norm: 'bool', indicating whether batchnorm layers are added. norm_activation: an operation that includes a normalization layer followed by an optional activation layer. """ self._min_level = min_level self._max_level = max_level self._anchors_per_location = anchors_per_location if activation == 'relu': self._activation_op = tf.nn.relu elif activation == 'swish': self._activation_op = tf.nn.swish else: raise ValueError('Unsupported activation `{}`.'.format(activation)) self._use_batch_norm = use_batch_norm if use_separable_conv: self._conv2d_op = functools.partial( tf.keras.layers.SeparableConv2D, depth_multiplier=1, bias_initializer=tf.zeros_initializer()) else: self._conv2d_op = functools.partial( tf.keras.layers.Conv2D, kernel_initializer=tf.keras.initializers.RandomNormal(stddev=0.01), bias_initializer=tf.zeros_initializer()) self._rpn_conv = self._conv2d_op( num_filters, kernel_size=(3, 3), strides=(1, 1), activation=(None if self._use_batch_norm else self._activation_op), padding='same', name='rpn') self._rpn_class_conv = self._conv2d_op( anchors_per_location, kernel_size=(1, 1), strides=(1, 1), padding='valid', name='rpn-class') self._rpn_box_conv = self._conv2d_op( 4 * anchors_per_location, kernel_size=(1, 1), strides=(1, 1), padding='valid', name='rpn-box-lrtb') self._rpn_center_conv = self._conv2d_op( anchors_per_location, kernel_size=(1, 1), strides=(1, 1), padding='valid', name='rpn-centerness') self._norm_activations = {} if self._use_batch_norm: for level in range(self._min_level, self._max_level + 1): self._norm_activations[level] = norm_activation(name='rpn-l%d-bn' % level) def _shared_rpn_heads(self, features, anchors_per_location, level, is_training): """Shared RPN heads.""" features = self._rpn_conv(features) if self._use_batch_norm: # The batch normalization layers are not shared between levels. features = self._norm_activations[level]( features, is_training=is_training) # Feature L2 normalization for training stability features = tf.math.l2_normalize( features, axis=-1, name='rpn-norm',) # Proposal classification scores scores = self._rpn_class_conv(features) # Proposal bbox regression deltas bboxes = self._rpn_box_conv(features) # Proposal centerness scores centers = self._rpn_center_conv(features) return scores, bboxes, centers def __call__(self, features, is_training=None): scores_outputs = {} box_outputs = {} center_outputs = {} with tf.name_scope('rpn_head'): for level in range(self._min_level, self._max_level + 1): scores_output, box_output, center_output = self._shared_rpn_heads( features[level], self._anchors_per_location, level, is_training) scores_outputs[level] = scores_output box_outputs[level] = box_output center_outputs[level] = center_output return scores_outputs, box_outputs, center_outputs class FastrcnnHead(tf.keras.layers.Layer): """Fast R-CNN box head.""" def __init__( self, num_classes, num_convs=0, num_filters=256, use_separable_conv=False, num_fcs=2, fc_dims=1024, activation='relu', use_batch_norm=True, norm_activation=nn_ops.norm_activation_builder(activation='relu')): """Initialize params to build Fast R-CNN box head. Args: num_classes: a integer for the number of classes. num_convs: `int` number that represents the number of the intermediate conv layers before the FC layers. num_filters: `int` number that represents the number of filters of the intermediate conv layers. use_separable_conv: `bool`, indicating whether the separable conv layers is used. num_fcs: `int` number that represents the number of FC layers before the predictions. fc_dims: `int` number that represents the number of dimension of the FC layers. activation: activation function. Support 'relu' and 'swish'. use_batch_norm: 'bool', indicating whether batchnorm layers are added. norm_activation: an operation that includes a normalization layer followed by an optional activation layer. """ super(FastrcnnHead, self).__init__(autocast=False) self._num_classes = num_classes self._num_convs = num_convs self._num_filters = num_filters if use_separable_conv: self._conv2d_op = functools.partial( tf.keras.layers.SeparableConv2D, depth_multiplier=1, bias_initializer=tf.zeros_initializer()) else: self._conv2d_op = functools.partial( tf.keras.layers.Conv2D, kernel_initializer=tf.keras.initializers.VarianceScaling( scale=2, mode='fan_out', distribution='untruncated_normal'), bias_initializer=tf.zeros_initializer()) self._num_fcs = num_fcs self._fc_dims = fc_dims if activation == 'relu': self._activation_op = tf.nn.relu elif activation == 'swish': self._activation_op = tf.nn.swish else: raise ValueError('Unsupported activation `{}`.'.format(activation)) self._use_batch_norm = use_batch_norm self._norm_activation = norm_activation self._conv_ops = [] self._conv_bn_ops = [] for i in range(self._num_convs): self._conv_ops.append( self._conv2d_op( self._num_filters, kernel_size=(3, 3), strides=(1, 1), padding='same', dilation_rate=(1, 1), activation=(None if self._use_batch_norm else self._activation_op), name='conv_{}'.format(i))) if self._use_batch_norm: self._conv_bn_ops.append(self._norm_activation()) self._fc_ops = [] self._fc_bn_ops = [] for i in range(self._num_fcs): self._fc_ops.append( tf.keras.layers.Dense( units=self._fc_dims, activation=(None if self._use_batch_norm else self._activation_op), name='fc{}'.format(i))) if self._use_batch_norm: self._fc_bn_ops.append(self._norm_activation(fused=False)) self._class_predict = tf.keras.layers.Dense( self._num_classes, kernel_initializer=tf.keras.initializers.RandomNormal(stddev=0.01), bias_initializer=tf.zeros_initializer(), name='class-predict') self._box_predict = tf.keras.layers.Dense( self._num_classes * 4, kernel_initializer=tf.keras.initializers.RandomNormal(stddev=0.001), bias_initializer=tf.zeros_initializer(), name='box-predict') def call(self, roi_features, is_training=None): """Box and class branches for the Mask-RCNN model. Args: roi_features: A ROI feature tensor of shape [batch_size, num_rois, height_l, width_l, num_filters]. is_training: `boolean`, if True if model is in training mode. Returns: class_outputs: a tensor with a shape of [batch_size, num_rois, num_classes], representing the class predictions. box_outputs: a tensor with a shape of [batch_size, num_rois, num_classes * 4], representing the box predictions. """ with tf.name_scope( 'fast_rcnn_head'): # reshape inputs beofre FC. _, num_rois, height, width, filters = roi_features.get_shape().as_list() net = tf.reshape(roi_features, [-1, height, width, filters]) for i in range(self._num_convs): net = self._conv_ops[i](net) if self._use_batch_norm: net = self._conv_bn_ops[i](net, is_training=is_training) filters = self._num_filters if self._num_convs > 0 else filters net = tf.reshape(net, [-1, num_rois, height * width * filters]) for i in range(self._num_fcs): net = self._fc_ops[i](net) if self._use_batch_norm: net = self._fc_bn_ops[i](net, is_training=is_training) class_outputs = self._class_predict(net) box_outputs = self._box_predict(net) return class_outputs, box_outputs class OlnBoxScoreHead(tf.keras.layers.Layer): """Box head of Object Localization Network (OLN).""" def __init__( self, num_classes, num_convs=0, num_filters=256, use_separable_conv=False, num_fcs=2, fc_dims=1024, activation='relu', use_batch_norm=True, norm_activation=nn_ops.norm_activation_builder(activation='relu')): """Initialize params to build OLN box head. Args: num_classes: a integer for the number of classes. num_convs: `int` number that represents the number of the intermediate conv layers before the FC layers. num_filters: `int` number that represents the number of filters of the intermediate conv layers. use_separable_conv: `bool`, indicating whether the separable conv layers is used. num_fcs: `int` number that represents the number of FC layers before the predictions. fc_dims: `int` number that represents the number of dimension of the FC layers. activation: activation function. Support 'relu' and 'swish'. use_batch_norm: 'bool', indicating whether batchnorm layers are added. norm_activation: an operation that includes a normalization layer followed by an optional activation layer. """ self._num_classes = num_classes self._num_convs = num_convs self._num_filters = num_filters if use_separable_conv: self._conv2d_op = functools.partial( tf.keras.layers.SeparableConv2D, depth_multiplier=1, bias_initializer=tf.zeros_initializer()) else: self._conv2d_op = functools.partial( tf.keras.layers.Conv2D, kernel_initializer=tf.keras.initializers.VarianceScaling( scale=2, mode='fan_out', distribution='untruncated_normal'), bias_initializer=tf.zeros_initializer()) self._num_fcs = num_fcs self._fc_dims = fc_dims if activation == 'relu': self._activation_op = tf.nn.relu elif activation == 'swish': self._activation_op = tf.nn.swish else: raise ValueError('Unsupported activation `{}`.'.format(activation)) self._use_batch_norm = use_batch_norm self._norm_activation = norm_activation self._conv_ops = [] self._conv_bn_ops = [] for i in range(self._num_convs): self._conv_ops.append( self._conv2d_op( self._num_filters, kernel_size=(3, 3), strides=(1, 1), padding='same', dilation_rate=(1, 1), activation=(None if self._use_batch_norm else self._activation_op), name='conv_{}'.format(i))) if self._use_batch_norm: self._conv_bn_ops.append(self._norm_activation()) self._fc_ops = [] self._fc_bn_ops = [] for i in range(self._num_fcs): self._fc_ops.append( tf.keras.layers.Dense( units=self._fc_dims, activation=(None if self._use_batch_norm else self._activation_op), name='fc{}'.format(i))) if self._use_batch_norm: self._fc_bn_ops.append(self._norm_activation(fused=False)) self._class_predict = tf.keras.layers.Dense( self._num_classes, kernel_initializer=tf.keras.initializers.RandomNormal(stddev=0.01), bias_initializer=tf.zeros_initializer(), name='class-predict') self._box_predict = tf.keras.layers.Dense( self._num_classes * 4, kernel_initializer=tf.keras.initializers.RandomNormal(stddev=0.001), bias_initializer=tf.zeros_initializer(), name='box-predict') self._score_predict = tf.keras.layers.Dense( 1, kernel_initializer=tf.keras.initializers.RandomNormal(stddev=0.01), bias_initializer=tf.zeros_initializer(), name='score-predict') def __call__(self, roi_features, is_training=None): """Box and class branches for the Mask-RCNN model. Args: roi_features: A ROI feature tensor of shape [batch_size, num_rois, height_l, width_l, num_filters]. is_training: `boolean`, if True if model is in training mode. Returns: class_outputs: a tensor with a shape of [batch_size, num_rois, num_classes], representing the class predictions. box_outputs: a tensor with a shape of [batch_size, num_rois, num_classes * 4], representing the box predictions. """ with tf.name_scope('fast_rcnn_head'): # reshape inputs beofre FC. _, num_rois, height, width, filters = roi_features.get_shape().as_list() net = tf.reshape(roi_features, [-1, height, width, filters]) for i in range(self._num_convs): net = self._conv_ops[i](net) if self._use_batch_norm: net = self._conv_bn_ops[i](net, is_training=is_training) filters = self._num_filters if self._num_convs > 0 else filters net = tf.reshape(net, [-1, num_rois, height * width * filters]) for i in range(self._num_fcs): net = self._fc_ops[i](net) if self._use_batch_norm: net = self._fc_bn_ops[i](net, is_training=is_training) class_outputs = self._class_predict(net) box_outputs = self._box_predict(net) score_outputs = self._score_predict(net) return class_outputs, box_outputs, score_outputs class MaskrcnnHead(tf.keras.layers.Layer): """Mask R-CNN head.""" def __init__( self, num_classes, mask_target_size, num_convs=4, num_filters=256, use_separable_conv=False, activation='relu', use_batch_norm=True, norm_activation=nn_ops.norm_activation_builder(activation='relu')): """Initialize params to build Fast R-CNN head. Args: num_classes: a integer for the number of classes. mask_target_size: a integer that is the resolution of masks. num_convs: `int` number that represents the number of the intermediate conv layers before the prediction. num_filters: `int` number that represents the number of filters of the intermediate conv layers. use_separable_conv: `bool`, indicating whether the separable conv layers is used. activation: activation function. Support 'relu' and 'swish'. use_batch_norm: 'bool', indicating whether batchnorm layers are added. norm_activation: an operation that includes a normalization layer followed by an optional activation layer. """ super(MaskrcnnHead, self).__init__(autocast=False) self._num_classes = num_classes self._mask_target_size = mask_target_size self._num_convs = num_convs self._num_filters = num_filters if use_separable_conv: self._conv2d_op = functools.partial( tf.keras.layers.SeparableConv2D, depth_multiplier=1, bias_initializer=tf.zeros_initializer()) else: self._conv2d_op = functools.partial( tf.keras.layers.Conv2D, kernel_initializer=tf.keras.initializers.VarianceScaling( scale=2, mode='fan_out', distribution='untruncated_normal'), bias_initializer=tf.zeros_initializer()) if activation == 'relu': self._activation_op = tf.nn.relu elif activation == 'swish': self._activation_op = tf.nn.swish else: raise ValueError('Unsupported activation `{}`.'.format(activation)) self._use_batch_norm = use_batch_norm self._norm_activation = norm_activation self._conv2d_ops = [] for i in range(self._num_convs): self._conv2d_ops.append( self._conv2d_op( self._num_filters, kernel_size=(3, 3), strides=(1, 1), padding='same', dilation_rate=(1, 1), activation=(None if self._use_batch_norm else self._activation_op), name='mask-conv-l%d' % i)) self._mask_conv_transpose = tf.keras.layers.Conv2DTranspose( self._num_filters, kernel_size=(2, 2), strides=(2, 2), padding='valid', activation=(None if self._use_batch_norm else self._activation_op), kernel_initializer=tf.keras.initializers.VarianceScaling( scale=2, mode='fan_out', distribution='untruncated_normal'), bias_initializer=tf.zeros_initializer(), name='conv5-mask') with tf.name_scope('mask_head'): self._mask_conv2d_op = self._conv2d_op( self._num_classes, kernel_size=(1, 1), strides=(1, 1), padding='valid', name='mask_fcn_logits') def call(self, roi_features, class_indices, is_training=None): """Mask branch for the Mask-RCNN model. Args: roi_features: A ROI feature tensor of shape [batch_size, num_rois, height_l, width_l, num_filters]. class_indices: a Tensor of shape [batch_size, num_rois], indicating which class the ROI is. is_training: `boolean`, if True if model is in training mode. Returns: mask_outputs: a tensor with a shape of [batch_size, num_masks, mask_height, mask_width, num_classes], representing the mask predictions. fg_gather_indices: a tensor with a shape of [batch_size, num_masks, 2], representing the fg mask targets. Raises: ValueError: If boxes is not a rank-3 tensor or the last dimension of boxes is not 4. """ with tf.name_scope('mask_head'): _, num_rois, height, width, filters = roi_features.get_shape().as_list() net = tf.reshape(roi_features, [-1, height, width, filters]) for i in range(self._num_convs): net = self._conv2d_ops[i](net) if self._use_batch_norm: net = self._norm_activation()(net, is_training=is_training) net = self._mask_conv_transpose(net) if self._use_batch_norm: net = self._norm_activation()(net, is_training=is_training) mask_outputs = self._mask_conv2d_op(net) mask_outputs = tf.reshape(mask_outputs, [ -1, num_rois, self._mask_target_size, self._mask_target_size, self._num_classes ]) with tf.name_scope('masks_post_processing'): mask_outputs = tf.gather( mask_outputs, tf.cast(class_indices, tf.int32), axis=-1, batch_dims=2, ) return mask_outputs class RetinanetHead(object): """RetinaNet head.""" def __init__( self, min_level, max_level, num_classes, anchors_per_location, num_convs=4, num_filters=256, use_separable_conv=False, norm_activation=nn_ops.norm_activation_builder(activation='relu')): """Initialize params to build RetinaNet head. Args: min_level: `int` number of minimum feature level. max_level: `int` number of maximum feature level. num_classes: `int` number of classification categories. anchors_per_location: `int` number of anchors per pixel location. num_convs: `int` number of stacked convolution before the last prediction layer. num_filters: `int` number of filters used in the head architecture. use_separable_conv: `bool` to indicate whether to use separable convoluation. norm_activation: an operation that includes a normalization layer followed by an optional activation layer. """ self._min_level = min_level self._max_level = max_level self._num_classes = num_classes self._anchors_per_location = anchors_per_location self._num_convs = num_convs self._num_filters = num_filters self._use_separable_conv = use_separable_conv with tf.name_scope('class_net') as scope_name: self._class_name_scope = tf.name_scope(scope_name) with tf.name_scope('box_net') as scope_name: self._box_name_scope = tf.name_scope(scope_name) self._build_class_net_layers(norm_activation) self._build_box_net_layers(norm_activation) def _class_net_batch_norm_name(self, i, level): return 'class-%d-%d' % (i, level) def _box_net_batch_norm_name(self, i, level): return 'box-%d-%d' % (i, level) def _build_class_net_layers(self, norm_activation): """Build re-usable layers for class prediction network.""" if self._use_separable_conv: self._class_predict = tf.keras.layers.SeparableConv2D( self._num_classes * self._anchors_per_location, kernel_size=(3, 3), bias_initializer=tf.constant_initializer(-np.log((1 - 0.01) / 0.01)), padding='same', name='class-predict') else: self._class_predict = tf.keras.layers.Conv2D( self._num_classes * self._anchors_per_location, kernel_size=(3, 3), bias_initializer=tf.constant_initializer(-np.log((1 - 0.01) / 0.01)), kernel_initializer=tf.keras.initializers.RandomNormal(stddev=1e-5), padding='same', name='class-predict') self._class_conv = [] self._class_norm_activation = {} for i in range(self._num_convs): if self._use_separable_conv: self._class_conv.append( tf.keras.layers.SeparableConv2D( self._num_filters, kernel_size=(3, 3), bias_initializer=tf.zeros_initializer(), activation=None, padding='same', name='class-' + str(i))) else: self._class_conv.append( tf.keras.layers.Conv2D( self._num_filters, kernel_size=(3, 3), bias_initializer=tf.zeros_initializer(), kernel_initializer=tf.keras.initializers.RandomNormal( stddev=0.01), activation=None, padding='same', name='class-' + str(i))) for level in range(self._min_level, self._max_level + 1): name = self._class_net_batch_norm_name(i, level) self._class_norm_activation[name] = norm_activation(name=name) def _build_box_net_layers(self, norm_activation): """Build re-usable layers for box prediction network.""" if self._use_separable_conv: self._box_predict = tf.keras.layers.SeparableConv2D( 4 * self._anchors_per_location, kernel_size=(3, 3), bias_initializer=tf.zeros_initializer(), padding='same', name='box-predict') else: self._box_predict = tf.keras.layers.Conv2D( 4 * self._anchors_per_location, kernel_size=(3, 3), bias_initializer=tf.zeros_initializer(), kernel_initializer=tf.keras.initializers.RandomNormal(stddev=1e-5), padding='same', name='box-predict') self._box_conv = [] self._box_norm_activation = {} for i in range(self._num_convs): if self._use_separable_conv: self._box_conv.append( tf.keras.layers.SeparableConv2D( self._num_filters, kernel_size=(3, 3), activation=None, bias_initializer=tf.zeros_initializer(), padding='same', name='box-' + str(i))) else: self._box_conv.append( tf.keras.layers.Conv2D( self._num_filters, kernel_size=(3, 3), activation=None, bias_initializer=tf.zeros_initializer(), kernel_initializer=tf.keras.initializers.RandomNormal( stddev=0.01), padding='same', name='box-' + str(i))) for level in range(self._min_level, self._max_level + 1): name = self._box_net_batch_norm_name(i, level) self._box_norm_activation[name] = norm_activation(name=name) def __call__(self, fpn_features, is_training=None): """Returns outputs of RetinaNet head.""" class_outputs = {} box_outputs = {} with tf.name_scope('retinanet_head'): for level in range(self._min_level, self._max_level + 1): features = fpn_features[level] class_outputs[level] = self.class_net( features, level, is_training=is_training) box_outputs[level] = self.box_net( features, level, is_training=is_training) return class_outputs, box_outputs def class_net(self, features, level, is_training): """Class prediction network for RetinaNet.""" with self._class_name_scope: for i in range(self._num_convs): features = self._class_conv[i](features) # The convolution layers in the class net are shared among all levels, # but each level has its batch normlization to capture the statistical # difference among different levels. name = self._class_net_batch_norm_name(i, level) features = self._class_norm_activation[name]( features, is_training=is_training) classes = self._class_predict(features) return classes def box_net(self, features, level, is_training=None): """Box regression network for RetinaNet.""" with self._box_name_scope: for i in range(self._num_convs): features = self._box_conv[i](features) # The convolution layers in the box net are shared among all levels, but # each level has its batch normlization to capture the statistical # difference among different levels. name = self._box_net_batch_norm_name(i, level) features = self._box_norm_activation[name]( features, is_training=is_training) boxes = self._box_predict(features) return boxes # TODO(yeqing): Refactor this class when it is ready for var_scope reuse. class ShapemaskPriorHead(object): """ShapeMask Prior head.""" def __init__(self, num_classes, num_downsample_channels, mask_crop_size, use_category_for_mask, shape_prior_path): """Initialize params to build RetinaNet head. Args: num_classes: Number of output classes. num_downsample_channels: number of channels in mask branch. mask_crop_size: feature crop size. use_category_for_mask: use class information in mask branch. shape_prior_path: the path to load shape priors. """ self._mask_num_classes = num_classes if use_category_for_mask else 1 self._num_downsample_channels = num_downsample_channels self._mask_crop_size = mask_crop_size self._shape_prior_path = shape_prior_path self._use_category_for_mask = use_category_for_mask self._shape_prior_fc = tf.keras.layers.Dense( self._num_downsample_channels, name='shape-prior-fc') def __call__(self, fpn_features, boxes, outer_boxes, classes, is_training): """Generate the detection priors from the box detections and FPN features. This corresponds to the Fig. 4 of the ShapeMask paper at https://arxiv.org/pdf/1904.03239.pdf Args: fpn_features: a dictionary of FPN features. boxes: a float tensor of shape [batch_size, num_instances, 4] representing the tight gt boxes from dataloader/detection. outer_boxes: a float tensor of shape [batch_size, num_instances, 4] representing the loose gt boxes from dataloader/detection. classes: a int Tensor of shape [batch_size, num_instances] of instance classes. is_training: training mode or not. Returns: instance_features: a float Tensor of shape [batch_size * num_instances, mask_crop_size, mask_crop_size, num_downsample_channels]. This is the instance feature crop. detection_priors: A float Tensor of shape [batch_size * num_instances, mask_size, mask_size, 1]. """ with tf.name_scope('prior_mask'): batch_size, num_instances, _ = boxes.get_shape().as_list() outer_boxes = tf.cast(outer_boxes, tf.float32) boxes = tf.cast(boxes, tf.float32) instance_features = spatial_transform_ops.multilevel_crop_and_resize( fpn_features, outer_boxes, output_size=self._mask_crop_size) instance_features = self._shape_prior_fc(instance_features) shape_priors = self._get_priors() # Get uniform priors for each outer box. uniform_priors = tf.ones([ batch_size, num_instances, self._mask_crop_size, self._mask_crop_size ]) uniform_priors = spatial_transform_ops.crop_mask_in_target_box( uniform_priors, boxes, outer_boxes, self._mask_crop_size) # Classify shape priors using uniform priors + instance features. prior_distribution = self._classify_shape_priors( tf.cast(instance_features, tf.float32), uniform_priors, classes) instance_priors = tf.gather(shape_priors, classes) instance_priors *= tf.expand_dims( tf.expand_dims(tf.cast(prior_distribution, tf.float32), axis=-1), axis=-1) instance_priors = tf.reduce_sum(instance_priors, axis=2) detection_priors = spatial_transform_ops.crop_mask_in_target_box( instance_priors, boxes, outer_boxes, self._mask_crop_size) return instance_features, detection_priors def _get_priors(self): """Load shape priors from file.""" # loads class specific or agnostic shape priors if self._shape_prior_path: # Priors are loaded into shape [mask_num_classes, num_clusters, 32, 32]. priors = np.load(tf.io.gfile.GFile(self._shape_prior_path, 'rb')) priors = tf.convert_to_tensor(priors, dtype=tf.float32) self._num_clusters = priors.get_shape().as_list()[1] else: # If prior path does not exist, do not use priors, i.e., pirors equal to # uniform empty 32x32 patch. self._num_clusters = 1 priors = tf.zeros([ self._mask_num_classes, self._num_clusters, self._mask_crop_size, self._mask_crop_size ]) return priors def _classify_shape_priors(self, features, uniform_priors, classes): """Classify the uniform prior by predicting the shape modes. Classify the object crop features into K modes of the clusters for each category. Args: features: A float Tensor of shape [batch_size, num_instances, mask_size, mask_size, num_channels]. uniform_priors: A float Tensor of shape [batch_size, num_instances, mask_size, mask_size] representing the uniform detection priors. classes: A int Tensor of shape [batch_size, num_instances] of detection class ids. Returns: prior_distribution: A float Tensor of shape [batch_size, num_instances, num_clusters] representing the classifier output probability over all possible shapes. """ batch_size, num_instances, _, _, _ = features.get_shape().as_list() features *= tf.expand_dims(uniform_priors, axis=-1) # Reduce spatial dimension of features. The features have shape # [batch_size, num_instances, num_channels]. features = tf.reduce_mean(features, axis=(2, 3)) logits = tf.keras.layers.Dense( self._mask_num_classes * self._num_clusters, kernel_initializer=tf.random_normal_initializer(stddev=0.01), name='classify-shape-prior-fc')(features) logits = tf.reshape( logits, [batch_size, num_instances, self._mask_num_classes, self._num_clusters]) if self._use_category_for_mask: logits = tf.gather(logits, tf.expand_dims(classes, axis=-1), batch_dims=2) logits = tf.squeeze(logits, axis=2) else: logits = logits[:, :, 0, :] distribution = tf.nn.softmax(logits, name='shape_prior_weights') return distribution class ShapemaskCoarsemaskHead(object): """ShapemaskCoarsemaskHead head.""" def __init__(self, num_classes, num_downsample_channels, mask_crop_size, use_category_for_mask, num_convs, norm_activation=nn_ops.norm_activation_builder()): """Initialize params to build ShapeMask coarse and fine prediction head. Args: num_classes: `int` number of mask classification categories. num_downsample_channels: `int` number of filters at mask head. mask_crop_size: feature crop size. use_category_for_mask: use class information in mask branch. num_convs: `int` number of stacked convolution before the last prediction layer. norm_activation: an operation that includes a normalization layer followed by an optional activation layer. """ self._mask_num_classes = num_classes if use_category_for_mask else 1 self._use_category_for_mask = use_category_for_mask self._num_downsample_channels = num_downsample_channels self._mask_crop_size = mask_crop_size self._num_convs = num_convs self._norm_activation = norm_activation self._coarse_mask_fc = tf.keras.layers.Dense( self._num_downsample_channels, name='coarse-mask-fc') self._class_conv = [] self._class_norm_activation = [] for i in range(self._num_convs): self._class_conv.append( tf.keras.layers.Conv2D( self._num_downsample_channels, kernel_size=(3, 3), bias_initializer=tf.zeros_initializer(), kernel_initializer=tf.keras.initializers.RandomNormal( stddev=0.01), padding='same', name='coarse-mask-class-%d' % i)) self._class_norm_activation.append( norm_activation(name='coarse-mask-class-%d-bn' % i)) self._class_predict = tf.keras.layers.Conv2D( self._mask_num_classes, kernel_size=(1, 1), # Focal loss bias initialization to have foreground 0.01 probability. bias_initializer=tf.constant_initializer(-np.log((1 - 0.01) / 0.01)), kernel_initializer=tf.keras.initializers.RandomNormal(stddev=0.01), padding='same', name='coarse-mask-class-predict') def __call__(self, features, detection_priors, classes, is_training): """Generate instance masks from FPN features and detection priors. This corresponds to the Fig. 5-6 of the ShapeMask paper at https://arxiv.org/pdf/1904.03239.pdf Args: features: a float Tensor of shape [batch_size, num_instances, mask_crop_size, mask_crop_size, num_downsample_channels]. This is the instance feature crop. detection_priors: a float Tensor of shape [batch_size, num_instances, mask_crop_size, mask_crop_size, 1]. This is the detection prior for the instance. classes: a int Tensor of shape [batch_size, num_instances] of instance classes. is_training: a bool indicating whether in training mode. Returns: mask_outputs: instance mask prediction as a float Tensor of shape [batch_size, num_instances, mask_size, mask_size]. """ with tf.name_scope('coarse_mask'): # Transform detection priors to have the same dimension as features. detection_priors = tf.expand_dims(detection_priors, axis=-1) detection_priors = self._coarse_mask_fc(detection_priors) features += detection_priors mask_logits = self.decoder_net(features, is_training) # Gather the logits with right input class. if self._use_category_for_mask: mask_logits = tf.transpose(mask_logits, [0, 1, 4, 2, 3]) mask_logits = tf.gather( mask_logits, tf.expand_dims(classes, -1), batch_dims=2) mask_logits = tf.squeeze(mask_logits, axis=2) else: mask_logits = mask_logits[..., 0] return mask_logits def decoder_net(self, features, is_training=False): """Coarse mask decoder network architecture. Args: features: A tensor of size [batch, height_in, width_in, channels_in]. is_training: Whether batch_norm layers are in training mode. Returns: images: A feature tensor of size [batch, output_size, output_size, num_channels] """ (batch_size, num_instances, height, width, num_channels) = features.get_shape().as_list() features = tf.reshape( features, [batch_size * num_instances, height, width, num_channels]) for i in range(self._num_convs): features = self._class_conv[i](features) features = self._class_norm_activation[i]( features, is_training=is_training) mask_logits = self._class_predict(features) mask_logits = tf.reshape( mask_logits, [batch_size, num_instances, height, width, self._mask_num_classes]) return mask_logits class ShapemaskFinemaskHead(object): """ShapemaskFinemaskHead head.""" def __init__(self, num_classes, num_downsample_channels, mask_crop_size, use_category_for_mask, num_convs, upsample_factor, norm_activation=nn_ops.norm_activation_builder()): """Initialize params to build ShapeMask coarse and fine prediction head. Args: num_classes: `int` number of mask classification categories. num_downsample_channels: `int` number of filters at mask head. mask_crop_size: feature crop size. use_category_for_mask: use class information in mask branch. num_convs: `int` number of stacked convolution before the last prediction layer. upsample_factor: `int` number of fine mask upsampling factor. norm_activation: an operation that includes a batch normalization layer followed by a relu layer(optional). """ self._use_category_for_mask = use_category_for_mask self._mask_num_classes = num_classes if use_category_for_mask else 1 self._num_downsample_channels = num_downsample_channels self._mask_crop_size = mask_crop_size self._num_convs = num_convs self.up_sample_factor = upsample_factor self._fine_mask_fc = tf.keras.layers.Dense( self._num_downsample_channels, name='fine-mask-fc') self._upsample_conv = tf.keras.layers.Conv2DTranspose( self._num_downsample_channels, (self.up_sample_factor, self.up_sample_factor), (self.up_sample_factor, self.up_sample_factor), name='fine-mask-conv2d-tran') self._fine_class_conv = [] self._fine_class_bn = [] for i in range(self._num_convs): self._fine_class_conv.append( tf.keras.layers.Conv2D( self._num_downsample_channels, kernel_size=(3, 3), bias_initializer=tf.zeros_initializer(), kernel_initializer=tf.keras.initializers.RandomNormal( stddev=0.01), activation=None, padding='same', name='fine-mask-class-%d' % i)) self._fine_class_bn.append( norm_activation(name='fine-mask-class-%d-bn' % i)) self._class_predict_conv = tf.keras.layers.Conv2D( self._mask_num_classes, kernel_size=(1, 1), # Focal loss bias initialization to have foreground 0.01 probability. bias_initializer=tf.constant_initializer(-np.log((1 - 0.01) / 0.01)), kernel_initializer=tf.keras.initializers.RandomNormal(stddev=0.01), padding='same', name='fine-mask-class-predict') def __call__(self, features, mask_logits, classes, is_training): """Generate instance masks from FPN features and detection priors. This corresponds to the Fig. 5-6 of the ShapeMask paper at https://arxiv.org/pdf/1904.03239.pdf Args: features: a float Tensor of shape [batch_size, num_instances, mask_crop_size, mask_crop_size, num_downsample_channels]. This is the instance feature crop. mask_logits: a float Tensor of shape [batch_size, num_instances, mask_crop_size, mask_crop_size] indicating predicted mask logits. classes: a int Tensor of shape [batch_size, num_instances] of instance classes. is_training: a bool indicating whether in training mode. Returns: mask_outputs: instance mask prediction as a float Tensor of shape [batch_size, num_instances, mask_size, mask_size]. """ # Extract the foreground mean features # with tf.variable_scope('fine_mask', reuse=tf.AUTO_REUSE): with tf.name_scope('fine_mask'): mask_probs = tf.nn.sigmoid(mask_logits) # Compute instance embedding for hard average. binary_mask = tf.cast(tf.greater(mask_probs, 0.5), features.dtype) instance_embedding = tf.reduce_sum( features * tf.expand_dims(binary_mask, axis=-1), axis=(2, 3)) instance_embedding /= tf.expand_dims( tf.reduce_sum(binary_mask, axis=(2, 3)) + 1e-20, axis=-1) # Take the difference between crop features and mean instance features. features -= tf.expand_dims( tf.expand_dims(instance_embedding, axis=2), axis=2) features += self._fine_mask_fc(tf.expand_dims(mask_probs, axis=-1)) # Decoder to generate upsampled segmentation mask. mask_logits = self.decoder_net(features, is_training) if self._use_category_for_mask: mask_logits = tf.transpose(mask_logits, [0, 1, 4, 2, 3]) mask_logits = tf.gather( mask_logits, tf.expand_dims(classes, -1), batch_dims=2) mask_logits = tf.squeeze(mask_logits, axis=2) else: mask_logits = mask_logits[..., 0] return mask_logits def decoder_net(self, features, is_training=False): """Fine mask decoder network architecture. Args: features: A tensor of size [batch, height_in, width_in, channels_in]. is_training: Whether batch_norm layers are in training mode. Returns: images: A feature tensor of size [batch, output_size, output_size, num_channels], where output size is self._gt_upsample_scale times that of input. """ (batch_size, num_instances, height, width, num_channels) = features.get_shape().as_list() features = tf.reshape( features, [batch_size * num_instances, height, width, num_channels]) for i in range(self._num_convs): features = self._fine_class_conv[i](features) features = self._fine_class_bn[i](features, is_training=is_training) if self.up_sample_factor > 1: features = self._upsample_conv(features) # Predict per-class instance masks. mask_logits = self._class_predict_conv(features) mask_logits = tf.reshape(mask_logits, [ batch_size, num_instances, height * self.up_sample_factor, width * self.up_sample_factor, self._mask_num_classes ]) return mask_logits
48,977
37.44427
80
py
models
models-master/official/legacy/detection/modeling/architecture/fpn.py
# Copyright 2023 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. """Feature Pyramid Networks. Feature Pyramid Networks were proposed in: [1] Tsung-Yi Lin, Piotr Dollar, Ross Girshick, Kaiming He, Bharath Hariharan, , and Serge Belongie Feature Pyramid Networks for Object Detection. CVPR 2017. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import functools import tensorflow as tf from official.legacy.detection.modeling.architecture import nn_ops from official.legacy.detection.ops import spatial_transform_ops class Fpn(object): """Feature pyramid networks.""" def __init__(self, min_level=3, max_level=7, fpn_feat_dims=256, use_separable_conv=False, activation='relu', use_batch_norm=True, norm_activation=nn_ops.norm_activation_builder( activation='relu')): """FPN initialization function. Args: min_level: `int` minimum level in FPN output feature maps. max_level: `int` maximum level in FPN output feature maps. fpn_feat_dims: `int` number of filters in FPN layers. use_separable_conv: `bool`, if True use separable convolution for convolution in FPN layers. activation: the activation function. use_batch_norm: 'bool', indicating whether batchnorm layers are added. norm_activation: an operation that includes a normalization layer followed by an optional activation layer. """ self._min_level = min_level self._max_level = max_level self._fpn_feat_dims = fpn_feat_dims if use_separable_conv: self._conv2d_op = functools.partial( tf.keras.layers.SeparableConv2D, depth_multiplier=1) else: self._conv2d_op = tf.keras.layers.Conv2D if activation == 'relu': self._activation_op = tf.nn.relu elif activation == 'swish': self._activation_op = tf.nn.swish else: raise ValueError('Unsupported activation `{}`.'.format(activation)) self._use_batch_norm = use_batch_norm self._norm_activation = norm_activation self._norm_activations = {} self._lateral_conv2d_op = {} self._post_hoc_conv2d_op = {} self._coarse_conv2d_op = {} for level in range(self._min_level, self._max_level + 1): if self._use_batch_norm: self._norm_activations[level] = norm_activation( use_activation=False, name='p%d-bn' % level) self._lateral_conv2d_op[level] = self._conv2d_op( filters=self._fpn_feat_dims, kernel_size=(1, 1), padding='same', name='l%d' % level) self._post_hoc_conv2d_op[level] = self._conv2d_op( filters=self._fpn_feat_dims, strides=(1, 1), kernel_size=(3, 3), padding='same', name='post_hoc_d%d' % level) self._coarse_conv2d_op[level] = self._conv2d_op( filters=self._fpn_feat_dims, strides=(2, 2), kernel_size=(3, 3), padding='same', name='p%d' % level) def __call__(self, multilevel_features, is_training=None): """Returns the FPN features for a given multilevel features. Args: multilevel_features: a `dict` containing `int` keys for continuous feature levels, e.g., [2, 3, 4, 5]. The values are corresponding features with shape [batch_size, height_l, width_l, num_filters]. is_training: `bool` if True, the model is in training mode. Returns: a `dict` containing `int` keys for continuous feature levels [min_level, min_level + 1, ..., max_level]. The values are corresponding FPN features with shape [batch_size, height_l, width_l, fpn_feat_dims]. """ input_levels = list(multilevel_features.keys()) if min(input_levels) > self._min_level: raise ValueError( 'The minimum backbone level %d should be '%(min(input_levels)) + 'less or equal to FPN minimum level %d.:'%(self._min_level)) backbone_max_level = min(max(input_levels), self._max_level) with tf.name_scope('fpn'): # Adds lateral connections. feats_lateral = {} for level in range(self._min_level, backbone_max_level + 1): feats_lateral[level] = self._lateral_conv2d_op[level]( multilevel_features[level]) # Adds top-down path. feats = {backbone_max_level: feats_lateral[backbone_max_level]} for level in range(backbone_max_level - 1, self._min_level - 1, -1): feats[level] = spatial_transform_ops.nearest_upsampling( feats[level + 1], 2) + feats_lateral[level] # Adds post-hoc 3x3 convolution kernel. for level in range(self._min_level, backbone_max_level + 1): feats[level] = self._post_hoc_conv2d_op[level](feats[level]) # Adds coarser FPN levels introduced for RetinaNet. for level in range(backbone_max_level + 1, self._max_level + 1): feats_in = feats[level - 1] if level > backbone_max_level + 1: feats_in = self._activation_op(feats_in) feats[level] = self._coarse_conv2d_op[level](feats_in) if self._use_batch_norm: # Adds batch_norm layer. for level in range(self._min_level, self._max_level + 1): feats[level] = self._norm_activations[level]( feats[level], is_training=is_training) return feats
5,976
38.322368
80
py
models
models-master/official/legacy/detection/modeling/architecture/nn_blocks.py
# Copyright 2023 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 common building blocks for neural networks.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from official.modeling import tf_utils class ResidualBlock(tf.keras.layers.Layer): """A residual block.""" def __init__(self, filters, strides, use_projection=False, kernel_initializer='VarianceScaling', kernel_regularizer=None, bias_regularizer=None, activation='relu', use_sync_bn=False, norm_momentum=0.99, norm_epsilon=0.001, **kwargs): """A residual block with BN after convolutions. Args: filters: `int` number of filters for the first two convolutions. Note that the third and final convolution will use 4 times as many filters. strides: `int` block stride. If greater than 1, this block will ultimately downsample the input. use_projection: `bool` for whether this block should use a projection shortcut (versus the default identity shortcut). This is usually `True` for the first block of a block group, which may change the number of filters and the resolution. kernel_initializer: kernel_initializer for convolutional layers. kernel_regularizer: tf.keras.regularizers.Regularizer object for Conv2D. Default to None. bias_regularizer: tf.keras.regularizers.Regularizer object for Conv2d. Default to None. activation: `str` name of the activation function. use_sync_bn: if True, use synchronized batch normalization. norm_momentum: `float` normalization omentum for the moving average. norm_epsilon: `float` small float added to variance to avoid dividing by zero. **kwargs: keyword arguments to be passed. """ super(ResidualBlock, self).__init__(**kwargs) self._filters = filters self._strides = strides self._use_projection = use_projection self._use_sync_bn = use_sync_bn self._activation = activation self._kernel_initializer = kernel_initializer self._norm_momentum = norm_momentum self._norm_epsilon = norm_epsilon self._kernel_regularizer = kernel_regularizer self._bias_regularizer = bias_regularizer if use_sync_bn: self._norm = tf.keras.layers.experimental.SyncBatchNormalization else: self._norm = tf.keras.layers.BatchNormalization if tf.keras.backend.image_data_format() == 'channels_last': self._bn_axis = -1 else: self._bn_axis = 1 self._activation_fn = tf_utils.get_activation(activation) def build(self, input_shape): if self._use_projection: self._shortcut = tf.keras.layers.Conv2D( filters=self._filters, kernel_size=1, strides=self._strides, use_bias=False, kernel_initializer=self._kernel_initializer, kernel_regularizer=self._kernel_regularizer, bias_regularizer=self._bias_regularizer) self._norm0 = self._norm( axis=self._bn_axis, momentum=self._norm_momentum, epsilon=self._norm_epsilon) self._conv1 = tf.keras.layers.Conv2D( filters=self._filters, kernel_size=3, strides=self._strides, padding='same', use_bias=False, kernel_initializer=self._kernel_initializer, kernel_regularizer=self._kernel_regularizer, bias_regularizer=self._bias_regularizer) self._norm1 = self._norm( axis=self._bn_axis, momentum=self._norm_momentum, epsilon=self._norm_epsilon) self._conv2 = tf.keras.layers.Conv2D( filters=self._filters, kernel_size=3, strides=1, padding='same', use_bias=False, kernel_initializer=self._kernel_initializer, kernel_regularizer=self._kernel_regularizer, bias_regularizer=self._bias_regularizer) self._norm2 = self._norm( axis=self._bn_axis, momentum=self._norm_momentum, epsilon=self._norm_epsilon) super(ResidualBlock, self).build(input_shape) def get_config(self): config = { 'filters': self._filters, 'strides': self._strides, 'use_projection': self._use_projection, 'kernel_initializer': self._kernel_initializer, 'kernel_regularizer': self._kernel_regularizer, 'bias_regularizer': self._bias_regularizer, 'activation': self._activation, 'use_sync_bn': self._use_sync_bn, 'norm_momentum': self._norm_momentum, 'norm_epsilon': self._norm_epsilon } base_config = super(ResidualBlock, self).get_config() return dict(list(base_config.items()) + list(config.items())) def call(self, inputs): shortcut = inputs if self._use_projection: shortcut = self._shortcut(shortcut) shortcut = self._norm0(shortcut) x = self._conv1(inputs) x = self._norm1(x) x = self._activation_fn(x) x = self._conv2(x) x = self._norm2(x) return self._activation_fn(x + shortcut) class BottleneckBlock(tf.keras.layers.Layer): """A standard bottleneck block.""" def __init__(self, filters, strides, use_projection=False, kernel_initializer='VarianceScaling', kernel_regularizer=None, bias_regularizer=None, activation='relu', use_sync_bn=False, norm_momentum=0.99, norm_epsilon=0.001, **kwargs): """A standard bottleneck block with BN after convolutions. Args: filters: `int` number of filters for the first two convolutions. Note that the third and final convolution will use 4 times as many filters. strides: `int` block stride. If greater than 1, this block will ultimately downsample the input. use_projection: `bool` for whether this block should use a projection shortcut (versus the default identity shortcut). This is usually `True` for the first block of a block group, which may change the number of filters and the resolution. kernel_initializer: kernel_initializer for convolutional layers. kernel_regularizer: tf.keras.regularizers.Regularizer object for Conv2D. Default to None. bias_regularizer: tf.keras.regularizers.Regularizer object for Conv2d. Default to None. activation: `str` name of the activation function. use_sync_bn: if True, use synchronized batch normalization. norm_momentum: `float` normalization omentum for the moving average. norm_epsilon: `float` small float added to variance to avoid dividing by zero. **kwargs: keyword arguments to be passed. """ super(BottleneckBlock, self).__init__(**kwargs) self._filters = filters self._strides = strides self._use_projection = use_projection self._use_sync_bn = use_sync_bn self._activation = activation self._kernel_initializer = kernel_initializer self._norm_momentum = norm_momentum self._norm_epsilon = norm_epsilon self._kernel_regularizer = kernel_regularizer self._bias_regularizer = bias_regularizer if use_sync_bn: self._norm = tf.keras.layers.experimental.SyncBatchNormalization else: self._norm = tf.keras.layers.BatchNormalization if tf.keras.backend.image_data_format() == 'channels_last': self._bn_axis = -1 else: self._bn_axis = 1 self._activation_fn = tf_utils.get_activation(activation) def build(self, input_shape): if self._use_projection: self._shortcut = tf.keras.layers.Conv2D( filters=self._filters * 4, kernel_size=1, strides=self._strides, use_bias=False, kernel_initializer=self._kernel_initializer, kernel_regularizer=self._kernel_regularizer, bias_regularizer=self._bias_regularizer) self._norm0 = self._norm( axis=self._bn_axis, momentum=self._norm_momentum, epsilon=self._norm_epsilon) self._conv1 = tf.keras.layers.Conv2D( filters=self._filters, kernel_size=1, strides=1, use_bias=False, kernel_initializer=self._kernel_initializer, kernel_regularizer=self._kernel_regularizer, bias_regularizer=self._bias_regularizer) self._norm1 = self._norm( axis=self._bn_axis, momentum=self._norm_momentum, epsilon=self._norm_epsilon) self._conv2 = tf.keras.layers.Conv2D( filters=self._filters, kernel_size=3, strides=self._strides, padding='same', use_bias=False, kernel_initializer=self._kernel_initializer, kernel_regularizer=self._kernel_regularizer, bias_regularizer=self._bias_regularizer) self._norm2 = self._norm( axis=self._bn_axis, momentum=self._norm_momentum, epsilon=self._norm_epsilon) self._conv3 = tf.keras.layers.Conv2D( filters=self._filters * 4, kernel_size=1, strides=1, use_bias=False, kernel_initializer=self._kernel_initializer, kernel_regularizer=self._kernel_regularizer, bias_regularizer=self._bias_regularizer) self._norm3 = self._norm( axis=self._bn_axis, momentum=self._norm_momentum, epsilon=self._norm_epsilon) super(BottleneckBlock, self).build(input_shape) def get_config(self): config = { 'filters': self._filters, 'strides': self._strides, 'use_projection': self._use_projection, 'kernel_initializer': self._kernel_initializer, 'kernel_regularizer': self._kernel_regularizer, 'bias_regularizer': self._bias_regularizer, 'activation': self._activation, 'use_sync_bn': self._use_sync_bn, 'norm_momentum': self._norm_momentum, 'norm_epsilon': self._norm_epsilon } base_config = super(BottleneckBlock, self).get_config() return dict(list(base_config.items()) + list(config.items())) def call(self, inputs): shortcut = inputs if self._use_projection: shortcut = self._shortcut(shortcut) shortcut = self._norm0(shortcut) x = self._conv1(inputs) x = self._norm1(x) x = self._activation_fn(x) x = self._conv2(x) x = self._norm2(x) x = self._activation_fn(x) x = self._conv3(x) x = self._norm3(x) return self._activation_fn(x + shortcut)
11,219
34.394322
80
py
models
models-master/official/legacy/detection/ops/roi_ops.py
# Copyright 2023 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. """ROI-related ops.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from official.legacy.detection.ops import nms from official.legacy.detection.utils import box_utils def multilevel_propose_rois(rpn_boxes, rpn_scores, anchor_boxes, image_shape, rpn_pre_nms_top_k=2000, rpn_post_nms_top_k=1000, rpn_nms_threshold=0.7, rpn_score_threshold=0.0, rpn_min_size_threshold=0.0, decode_boxes=True, clip_boxes=True, use_batched_nms=False, apply_sigmoid_to_score=True): """Proposes RoIs given a group of candidates from different FPN levels. The following describes the steps: 1. For each individual level: a. Apply sigmoid transform if specified. b. Decode boxes if specified. c. Clip boxes if specified. d. Filter small boxes and those fall outside image if specified. e. Apply pre-NMS filtering including pre-NMS top k and score thresholding. f. Apply NMS. 2. Aggregate post-NMS boxes from each level. 3. Apply an overall top k to generate the final selected RoIs. Args: rpn_boxes: a dict with keys representing FPN levels and values representing box tenors of shape [batch_size, feature_h, feature_w, num_anchors * 4]. rpn_scores: a dict with keys representing FPN levels and values representing logit tensors of shape [batch_size, feature_h, feature_w, num_anchors]. anchor_boxes: a dict with keys representing FPN levels and values representing anchor box tensors of shape [batch_size, feature_h, feature_w, num_anchors * 4]. image_shape: a tensor of shape [batch_size, 2] where the last dimension are [height, width] of the scaled image. rpn_pre_nms_top_k: an integer of top scoring RPN proposals *per level* to keep before applying NMS. Default: 2000. rpn_post_nms_top_k: an integer of top scoring RPN proposals *in total* to keep after applying NMS. Default: 1000. rpn_nms_threshold: a float between 0 and 1 representing the IoU threshold used for NMS. If 0.0, no NMS is applied. Default: 0.7. rpn_score_threshold: a float between 0 and 1 representing the minimal box score to keep before applying NMS. This is often used as a pre-filtering step for better performance. If 0, no filtering is applied. Default: 0. rpn_min_size_threshold: a float representing the minimal box size in each side (w.r.t. the scaled image) to keep before applying NMS. This is often used as a pre-filtering step for better performance. If 0, no filtering is applied. Default: 0. decode_boxes: a boolean indicating whether `rpn_boxes` needs to be decoded using `anchor_boxes`. If False, use `rpn_boxes` directly and ignore `anchor_boxes`. Default: True. clip_boxes: a boolean indicating whether boxes are first clipped to the scaled image size before appliying NMS. If False, no clipping is applied and `image_shape` is ignored. Default: True. use_batched_nms: a boolean indicating whether NMS is applied in batch using `tf.image.combined_non_max_suppression`. Currently only available in CPU/GPU. Default: False. apply_sigmoid_to_score: a boolean indicating whether apply sigmoid to `rpn_scores` before applying NMS. Default: True. Returns: selected_rois: a tensor of shape [batch_size, rpn_post_nms_top_k, 4], representing the box coordinates of the selected proposals w.r.t. the scaled image. selected_roi_scores: a tensor of shape [batch_size, rpn_post_nms_top_k, 1], representing the scores of the selected proposals. """ with tf.name_scope('multilevel_propose_rois'): rois = [] roi_scores = [] image_shape = tf.expand_dims(image_shape, axis=1) for level in sorted(rpn_scores.keys()): with tf.name_scope('level_%d' % level): _, feature_h, feature_w, num_anchors_per_location = ( rpn_scores[level].get_shape().as_list()) num_boxes = feature_h * feature_w * num_anchors_per_location this_level_scores = tf.reshape(rpn_scores[level], [-1, num_boxes]) this_level_boxes = tf.reshape(rpn_boxes[level], [-1, num_boxes, 4]) this_level_anchors = tf.cast( tf.reshape(anchor_boxes[level], [-1, num_boxes, 4]), dtype=this_level_scores.dtype) if apply_sigmoid_to_score: this_level_scores = tf.sigmoid(this_level_scores) if decode_boxes: this_level_boxes = box_utils.decode_boxes(this_level_boxes, this_level_anchors) if clip_boxes: this_level_boxes = box_utils.clip_boxes(this_level_boxes, image_shape) if rpn_min_size_threshold > 0.0: this_level_boxes, this_level_scores = box_utils.filter_boxes( this_level_boxes, this_level_scores, image_shape, rpn_min_size_threshold) this_level_pre_nms_top_k = min(num_boxes, rpn_pre_nms_top_k) this_level_post_nms_top_k = min(num_boxes, rpn_post_nms_top_k) if rpn_nms_threshold > 0.0: if use_batched_nms: this_level_rois, this_level_roi_scores, _, _ = ( tf.image.combined_non_max_suppression( tf.expand_dims(this_level_boxes, axis=2), tf.expand_dims(this_level_scores, axis=-1), max_output_size_per_class=this_level_pre_nms_top_k, max_total_size=this_level_post_nms_top_k, iou_threshold=rpn_nms_threshold, score_threshold=rpn_score_threshold, pad_per_class=False, clip_boxes=False)) else: if rpn_score_threshold > 0.0: this_level_boxes, this_level_scores = ( box_utils.filter_boxes_by_scores(this_level_boxes, this_level_scores, rpn_score_threshold)) this_level_boxes, this_level_scores = box_utils.top_k_boxes( this_level_boxes, this_level_scores, k=this_level_pre_nms_top_k) this_level_roi_scores, this_level_rois = ( nms.sorted_non_max_suppression_padded( this_level_scores, this_level_boxes, max_output_size=this_level_post_nms_top_k, iou_threshold=rpn_nms_threshold)) else: this_level_rois, this_level_roi_scores = box_utils.top_k_boxes( this_level_rois, this_level_scores, k=this_level_post_nms_top_k) rois.append(this_level_rois) roi_scores.append(this_level_roi_scores) all_rois = tf.concat(rois, axis=1) all_roi_scores = tf.concat(roi_scores, axis=1) with tf.name_scope('top_k_rois'): _, num_valid_rois = all_roi_scores.get_shape().as_list() overall_top_k = min(num_valid_rois, rpn_post_nms_top_k) selected_rois, selected_roi_scores = box_utils.top_k_boxes( all_rois, all_roi_scores, k=overall_top_k) return selected_rois, selected_roi_scores class ROIGenerator(tf.keras.layers.Layer): """Proposes RoIs for the second stage processing.""" def __init__(self, params): self._rpn_pre_nms_top_k = params.rpn_pre_nms_top_k self._rpn_post_nms_top_k = params.rpn_post_nms_top_k self._rpn_nms_threshold = params.rpn_nms_threshold self._rpn_score_threshold = params.rpn_score_threshold self._rpn_min_size_threshold = params.rpn_min_size_threshold self._test_rpn_pre_nms_top_k = params.test_rpn_pre_nms_top_k self._test_rpn_post_nms_top_k = params.test_rpn_post_nms_top_k self._test_rpn_nms_threshold = params.test_rpn_nms_threshold self._test_rpn_score_threshold = params.test_rpn_score_threshold self._test_rpn_min_size_threshold = params.test_rpn_min_size_threshold self._use_batched_nms = params.use_batched_nms super(ROIGenerator, self).__init__(autocast=False) def call(self, boxes, scores, anchor_boxes, image_shape, is_training): """Generates RoI proposals. Args: boxes: a dict with keys representing FPN levels and values representing box tenors of shape [batch_size, feature_h, feature_w, num_anchors * 4]. scores: a dict with keys representing FPN levels and values representing logit tensors of shape [batch_size, feature_h, feature_w, num_anchors]. anchor_boxes: a dict with keys representing FPN levels and values representing anchor box tensors of shape [batch_size, feature_h, feature_w, num_anchors * 4]. image_shape: a tensor of shape [batch_size, 2] where the last dimension are [height, width] of the scaled image. is_training: a bool indicating whether it is in training or inference mode. Returns: proposed_rois: a tensor of shape [batch_size, rpn_post_nms_top_k, 4], representing the box coordinates of the proposed RoIs w.r.t. the scaled image. proposed_roi_scores: a tensor of shape [batch_size, rpn_post_nms_top_k, 1], representing the scores of the proposed RoIs. """ proposed_rois, proposed_roi_scores = multilevel_propose_rois( boxes, scores, anchor_boxes, image_shape, rpn_pre_nms_top_k=(self._rpn_pre_nms_top_k if is_training else self._test_rpn_pre_nms_top_k), rpn_post_nms_top_k=(self._rpn_post_nms_top_k if is_training else self._test_rpn_post_nms_top_k), rpn_nms_threshold=(self._rpn_nms_threshold if is_training else self._test_rpn_nms_threshold), rpn_score_threshold=(self._rpn_score_threshold if is_training else self._test_rpn_score_threshold), rpn_min_size_threshold=(self._rpn_min_size_threshold if is_training else self._test_rpn_min_size_threshold), decode_boxes=True, clip_boxes=True, use_batched_nms=self._use_batched_nms, apply_sigmoid_to_score=True) return proposed_rois, proposed_roi_scores class OlnROIGenerator(ROIGenerator): """Proposes RoIs for the second stage processing.""" def __call__(self, boxes, scores, anchor_boxes, image_shape, is_training, is_box_lrtb=False, object_scores=None): """Generates RoI proposals. Args: boxes: a dict with keys representing FPN levels and values representing box tenors of shape [batch_size, feature_h, feature_w, num_anchors * 4]. scores: a dict with keys representing FPN levels and values representing logit tensors of shape [batch_size, feature_h, feature_w, num_anchors]. anchor_boxes: a dict with keys representing FPN levels and values representing anchor box tensors of shape [batch_size, feature_h, feature_w, num_anchors * 4]. image_shape: a tensor of shape [batch_size, 2] where the last dimension are [height, width] of the scaled image. is_training: a bool indicating whether it is in training or inference mode. is_box_lrtb: a bool indicating whether boxes are in lrtb (=left,right,top, bottom) format. object_scores: another objectness score (e.g., centerness). In OLN, we use object_scores=centerness as a replacement of the scores at each level. A dict with keys representing FPN levels and values representing logit tensors of shape [batch_size, feature_h, feature_w, num_anchors]. Returns: proposed_rois: a tensor of shape [batch_size, rpn_post_nms_top_k, 4], representing the box coordinates of the proposed RoIs w.r.t. the scaled image. proposed_roi_scores: a tensor of shape [batch_size, rpn_post_nms_top_k, 1], representing the scores of the proposed RoIs. """ proposed_rois, proposed_roi_scores = self.oln_multilevel_propose_rois( boxes, scores, anchor_boxes, image_shape, rpn_pre_nms_top_k=(self._rpn_pre_nms_top_k if is_training else self._test_rpn_pre_nms_top_k), rpn_post_nms_top_k=(self._rpn_post_nms_top_k if is_training else self._test_rpn_post_nms_top_k), rpn_nms_threshold=(self._rpn_nms_threshold if is_training else self._test_rpn_nms_threshold), rpn_score_threshold=(self._rpn_score_threshold if is_training else self._test_rpn_score_threshold), rpn_min_size_threshold=(self._rpn_min_size_threshold if is_training else self._test_rpn_min_size_threshold), decode_boxes=True, clip_boxes=True, use_batched_nms=self._use_batched_nms, apply_sigmoid_to_score=True, is_box_lrtb=is_box_lrtb, rpn_object_scores=object_scores,) return proposed_rois, proposed_roi_scores def oln_multilevel_propose_rois(self, rpn_boxes, rpn_scores, anchor_boxes, image_shape, rpn_pre_nms_top_k=2000, rpn_post_nms_top_k=1000, rpn_nms_threshold=0.7, rpn_score_threshold=0.0, rpn_min_size_threshold=0.0, decode_boxes=True, clip_boxes=True, use_batched_nms=False, apply_sigmoid_to_score=True, is_box_lrtb=False, rpn_object_scores=None,): """Proposes RoIs given a group of candidates from different FPN levels. The following describes the steps: 1. For each individual level: a. Adjust scores for each level if specified by rpn_object_scores. b. Apply sigmoid transform if specified. c. Decode boxes (either of xyhw or left-right-top-bottom format) if specified. d. Clip boxes if specified. e. Filter small boxes and those fall outside image if specified. f. Apply pre-NMS filtering including pre-NMS top k and score thresholding. g. Apply NMS. 2. Aggregate post-NMS boxes from each level. 3. Apply an overall top k to generate the final selected RoIs. Args: rpn_boxes: a dict with keys representing FPN levels and values representing box tenors of shape [batch_size, feature_h, feature_w, num_anchors * 4]. rpn_scores: a dict with keys representing FPN levels and values representing logit tensors of shape [batch_size, feature_h, feature_w, num_anchors]. anchor_boxes: a dict with keys representing FPN levels and values representing anchor box tensors of shape [batch_size, feature_h, feature_w, num_anchors * 4]. image_shape: a tensor of shape [batch_size, 2] where the last dimension are [height, width] of the scaled image. rpn_pre_nms_top_k: an integer of top scoring RPN proposals *per level* to keep before applying NMS. Default: 2000. rpn_post_nms_top_k: an integer of top scoring RPN proposals *in total* to keep after applying NMS. Default: 1000. rpn_nms_threshold: a float between 0 and 1 representing the IoU threshold used for NMS. If 0.0, no NMS is applied. Default: 0.7. rpn_score_threshold: a float between 0 and 1 representing the minimal box score to keep before applying NMS. This is often used as a pre-filtering step for better performance. If 0, no filtering is applied. Default: 0. rpn_min_size_threshold: a float representing the minimal box size in each side (w.r.t. the scaled image) to keep before applying NMS. This is often used as a pre-filtering step for better performance. If 0, no filtering is applied. Default: 0. decode_boxes: a boolean indicating whether `rpn_boxes` needs to be decoded using `anchor_boxes`. If False, use `rpn_boxes` directly and ignore `anchor_boxes`. Default: True. clip_boxes: a boolean indicating whether boxes are first clipped to the scaled image size before appliying NMS. If False, no clipping is applied and `image_shape` is ignored. Default: True. use_batched_nms: a boolean indicating whether NMS is applied in batch using `tf.image.combined_non_max_suppression`. Currently only available in CPU/GPU. Default: False. apply_sigmoid_to_score: a boolean indicating whether apply sigmoid to `rpn_scores` before applying NMS. Default: True. is_box_lrtb: a bool indicating whether boxes are in lrtb (=left,right,top, bottom) format. rpn_object_scores: a predicted objectness score (e.g., centerness). In OLN, we use object_scores=centerness as a replacement of the scores at each level. A dict with keys representing FPN levels and values representing logit tensors of shape [batch_size, feature_h, feature_w, num_anchors]. Returns: selected_rois: a tensor of shape [batch_size, rpn_post_nms_top_k, 4], representing the box coordinates of the selected proposals w.r.t. the scaled image. selected_roi_scores: a tensor of shape [batch_size, rpn_post_nms_top_k, 1],representing the scores of the selected proposals. """ with tf.name_scope('multilevel_propose_rois'): rois = [] roi_scores = [] image_shape = tf.expand_dims(image_shape, axis=1) for level in sorted(rpn_scores.keys()): with tf.name_scope('level_%d' % level): _, feature_h, feature_w, num_anchors_per_location = ( rpn_scores[level].get_shape().as_list()) num_boxes = feature_h * feature_w * num_anchors_per_location this_level_scores = tf.reshape(rpn_scores[level], [-1, num_boxes]) this_level_boxes = tf.reshape(rpn_boxes[level], [-1, num_boxes, 4]) this_level_anchors = tf.cast( tf.reshape(anchor_boxes[level], [-1, num_boxes, 4]), dtype=this_level_scores.dtype) if rpn_object_scores: this_level_object_scores = rpn_object_scores[level] this_level_object_scores = tf.reshape(this_level_object_scores, [-1, num_boxes]) this_level_object_scores = tf.cast(this_level_object_scores, this_level_scores.dtype) this_level_scores = this_level_object_scores if apply_sigmoid_to_score: this_level_scores = tf.sigmoid(this_level_scores) if decode_boxes: if is_box_lrtb: # Box in left-right-top-bottom format. this_level_boxes = box_utils.decode_boxes_lrtb( this_level_boxes, this_level_anchors) else: # Box in standard x-y-h-w format. this_level_boxes = box_utils.decode_boxes( this_level_boxes, this_level_anchors) if clip_boxes: this_level_boxes = box_utils.clip_boxes( this_level_boxes, image_shape) if rpn_min_size_threshold > 0.0: this_level_boxes, this_level_scores = box_utils.filter_boxes( this_level_boxes, this_level_scores, image_shape, rpn_min_size_threshold) this_level_pre_nms_top_k = min(num_boxes, rpn_pre_nms_top_k) this_level_post_nms_top_k = min(num_boxes, rpn_post_nms_top_k) if rpn_nms_threshold > 0.0: if use_batched_nms: this_level_rois, this_level_roi_scores, _, _ = ( tf.image.combined_non_max_suppression( tf.expand_dims(this_level_boxes, axis=2), tf.expand_dims(this_level_scores, axis=-1), max_output_size_per_class=this_level_pre_nms_top_k, max_total_size=this_level_post_nms_top_k, iou_threshold=rpn_nms_threshold, score_threshold=rpn_score_threshold, pad_per_class=False, clip_boxes=False)) else: if rpn_score_threshold > 0.0: this_level_boxes, this_level_scores = ( box_utils.filter_boxes_by_scores(this_level_boxes, this_level_scores, rpn_score_threshold)) this_level_boxes, this_level_scores = box_utils.top_k_boxes( this_level_boxes, this_level_scores, k=this_level_pre_nms_top_k) this_level_roi_scores, this_level_rois = ( nms.sorted_non_max_suppression_padded( this_level_scores, this_level_boxes, max_output_size=this_level_post_nms_top_k, iou_threshold=rpn_nms_threshold)) else: this_level_rois, this_level_roi_scores = box_utils.top_k_boxes( this_level_rois, this_level_scores, k=this_level_post_nms_top_k) rois.append(this_level_rois) roi_scores.append(this_level_roi_scores) all_rois = tf.concat(rois, axis=1) all_roi_scores = tf.concat(roi_scores, axis=1) with tf.name_scope('top_k_rois'): _, num_valid_rois = all_roi_scores.get_shape().as_list() overall_top_k = min(num_valid_rois, rpn_post_nms_top_k) selected_rois, selected_roi_scores = box_utils.top_k_boxes( all_rois, all_roi_scores, k=overall_top_k) return selected_rois, selected_roi_scores
22,986
48.012793
80
py
models
models-master/official/legacy/detection/ops/postprocess_ops.py
# Copyright 2023 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. """Post-processing model outputs to generate detection.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import functools import tensorflow as tf from official.legacy.detection.ops import nms from official.legacy.detection.utils import box_utils def generate_detections_factory(params): """Factory to select function to generate detection.""" if params.use_batched_nms: func = functools.partial( _generate_detections_batched, max_total_size=params.max_total_size, nms_iou_threshold=params.nms_iou_threshold, score_threshold=params.score_threshold) else: func = functools.partial( _generate_detections, max_total_size=params.max_total_size, nms_iou_threshold=params.nms_iou_threshold, score_threshold=params.score_threshold, pre_nms_num_boxes=params.pre_nms_num_boxes) return func def _select_top_k_scores(scores_in, pre_nms_num_detections): """Select top_k scores and indices for each class. Args: scores_in: a Tensor with shape [batch_size, N, num_classes], which stacks class logit outputs on all feature levels. The N is the number of total anchors on all levels. The num_classes is the number of classes predicted by the model. pre_nms_num_detections: Number of candidates before NMS. Returns: scores and indices: Tensors with shape [batch_size, pre_nms_num_detections, num_classes]. """ batch_size, num_anchors, num_class = scores_in.get_shape().as_list() scores_trans = tf.transpose(scores_in, perm=[0, 2, 1]) scores_trans = tf.reshape(scores_trans, [-1, num_anchors]) top_k_scores, top_k_indices = tf.nn.top_k( scores_trans, k=pre_nms_num_detections, sorted=True) top_k_scores = tf.reshape(top_k_scores, [batch_size, num_class, pre_nms_num_detections]) top_k_indices = tf.reshape(top_k_indices, [batch_size, num_class, pre_nms_num_detections]) return tf.transpose(top_k_scores, [0, 2, 1]), tf.transpose(top_k_indices, [0, 2, 1]) def _generate_detections(boxes, scores, max_total_size=100, nms_iou_threshold=0.3, score_threshold=0.05, pre_nms_num_boxes=5000): """Generate the final detections given the model outputs. This uses classes unrolling with while loop based NMS, could be parralled at batch dimension. Args: boxes: a tensor with shape [batch_size, N, num_classes, 4] or [batch_size, N, 1, 4], which box predictions on all feature levels. The N is the number of total anchors on all levels. scores: a tensor with shape [batch_size, N, num_classes], which stacks class probability on all feature levels. The N is the number of total anchors on all levels. The num_classes is the number of classes predicted by the model. Note that the class_outputs here is the raw score. max_total_size: a scalar representing maximum number of boxes retained over all classes. nms_iou_threshold: a float representing the threshold for deciding whether boxes overlap too much with respect to IOU. score_threshold: a float representing the threshold for deciding when to remove boxes based on score. pre_nms_num_boxes: an int number of top candidate detections per class before NMS. Returns: nms_boxes: `float` Tensor of shape [batch_size, max_total_size, 4] representing top detected boxes in [y1, x1, y2, x2]. nms_scores: `float` Tensor of shape [batch_size, max_total_size] representing sorted confidence scores for detected boxes. The values are between [0, 1]. nms_classes: `int` Tensor of shape [batch_size, max_total_size] representing classes for detected boxes. valid_detections: `int` Tensor of shape [batch_size] only the top `valid_detections` boxes are valid detections. """ with tf.name_scope('generate_detections'): nmsed_boxes = [] nmsed_classes = [] nmsed_scores = [] valid_detections = [] batch_size, _, num_classes_for_box, _ = boxes.get_shape().as_list() _, total_anchors, num_classes = scores.get_shape().as_list() # Selects top pre_nms_num scores and indices before NMS. scores, indices = _select_top_k_scores( scores, min(total_anchors, pre_nms_num_boxes)) for i in range(num_classes): boxes_i = boxes[:, :, min(num_classes_for_box - 1, i), :] scores_i = scores[:, :, i] # Obtains pre_nms_num_boxes before running NMS. boxes_i = tf.gather(boxes_i, indices[:, :, i], batch_dims=1, axis=1) # Filter out scores. boxes_i, scores_i = box_utils.filter_boxes_by_scores( boxes_i, scores_i, min_score_threshold=score_threshold) (nmsed_scores_i, nmsed_boxes_i) = nms.sorted_non_max_suppression_padded( tf.cast(scores_i, tf.float32), tf.cast(boxes_i, tf.float32), max_total_size, iou_threshold=nms_iou_threshold) nmsed_classes_i = tf.fill([batch_size, max_total_size], i) nmsed_boxes.append(nmsed_boxes_i) nmsed_scores.append(nmsed_scores_i) nmsed_classes.append(nmsed_classes_i) nmsed_boxes = tf.concat(nmsed_boxes, axis=1) nmsed_scores = tf.concat(nmsed_scores, axis=1) nmsed_classes = tf.concat(nmsed_classes, axis=1) nmsed_scores, indices = tf.nn.top_k( nmsed_scores, k=max_total_size, sorted=True) nmsed_boxes = tf.gather(nmsed_boxes, indices, batch_dims=1, axis=1) nmsed_classes = tf.gather(nmsed_classes, indices, batch_dims=1) valid_detections = tf.reduce_sum( input_tensor=tf.cast(tf.greater(nmsed_scores, -1), tf.int32), axis=1) return nmsed_boxes, nmsed_scores, nmsed_classes, valid_detections def _generate_detections_per_image(boxes, scores, max_total_size=100, nms_iou_threshold=0.3, score_threshold=0.05, pre_nms_num_boxes=5000): """Generate the final detections per image given the model outputs. Args: boxes: a tensor with shape [N, num_classes, 4] or [N, 1, 4], which box predictions on all feature levels. The N is the number of total anchors on all levels. scores: a tensor with shape [N, num_classes], which stacks class probability on all feature levels. The N is the number of total anchors on all levels. The num_classes is the number of classes predicted by the model. Note that the class_outputs here is the raw score. max_total_size: a scalar representing maximum number of boxes retained over all classes. nms_iou_threshold: a float representing the threshold for deciding whether boxes overlap too much with respect to IOU. score_threshold: a float representing the threshold for deciding when to remove boxes based on score. pre_nms_num_boxes: an int number of top candidate detections per class before NMS. Returns: nms_boxes: `float` Tensor of shape [max_total_size, 4] representing top detected boxes in [y1, x1, y2, x2]. nms_scores: `float` Tensor of shape [max_total_size] representing sorted confidence scores for detected boxes. The values are between [0, 1]. nms_classes: `int` Tensor of shape [max_total_size] representing classes for detected boxes. valid_detections: `int` Tensor of shape [1] only the top `valid_detections` boxes are valid detections. """ nmsed_boxes = [] nmsed_scores = [] nmsed_classes = [] num_classes_for_box = boxes.get_shape().as_list()[1] num_classes = scores.get_shape().as_list()[1] for i in range(num_classes): boxes_i = boxes[:, min(num_classes_for_box - 1, i)] scores_i = scores[:, i] # Obtains pre_nms_num_boxes before running NMS. scores_i, indices = tf.nn.top_k( scores_i, k=tf.minimum(tf.shape(input=scores_i)[-1], pre_nms_num_boxes)) boxes_i = tf.gather(boxes_i, indices) (nmsed_indices_i, nmsed_num_valid_i) = tf.image.non_max_suppression_padded( tf.cast(boxes_i, tf.float32), tf.cast(scores_i, tf.float32), max_total_size, iou_threshold=nms_iou_threshold, score_threshold=score_threshold, pad_to_max_output_size=True, name='nms_detections_' + str(i)) nmsed_boxes_i = tf.gather(boxes_i, nmsed_indices_i) nmsed_scores_i = tf.gather(scores_i, nmsed_indices_i) # Sets scores of invalid boxes to -1. nmsed_scores_i = tf.where( tf.less(tf.range(max_total_size), [nmsed_num_valid_i]), nmsed_scores_i, -tf.ones_like(nmsed_scores_i)) nmsed_classes_i = tf.fill([max_total_size], i) nmsed_boxes.append(nmsed_boxes_i) nmsed_scores.append(nmsed_scores_i) nmsed_classes.append(nmsed_classes_i) # Concats results from all classes and sort them. nmsed_boxes = tf.concat(nmsed_boxes, axis=0) nmsed_scores = tf.concat(nmsed_scores, axis=0) nmsed_classes = tf.concat(nmsed_classes, axis=0) nmsed_scores, indices = tf.nn.top_k( nmsed_scores, k=max_total_size, sorted=True) nmsed_boxes = tf.gather(nmsed_boxes, indices) nmsed_classes = tf.gather(nmsed_classes, indices) valid_detections = tf.reduce_sum( input_tensor=tf.cast(tf.greater(nmsed_scores, -1), tf.int32)) return nmsed_boxes, nmsed_scores, nmsed_classes, valid_detections def _generate_detections_batched(boxes, scores, max_total_size, nms_iou_threshold, score_threshold): """Generates detected boxes with scores and classes for one-stage detector. The function takes output of multi-level ConvNets and anchor boxes and generates detected boxes. Note that this used batched nms, which is not supported on TPU currently. Args: boxes: a tensor with shape [batch_size, N, num_classes, 4] or [batch_size, N, 1, 4], which box predictions on all feature levels. The N is the number of total anchors on all levels. scores: a tensor with shape [batch_size, N, num_classes], which stacks class probability on all feature levels. The N is the number of total anchors on all levels. The num_classes is the number of classes predicted by the model. Note that the class_outputs here is the raw score. max_total_size: a scalar representing maximum number of boxes retained over all classes. nms_iou_threshold: a float representing the threshold for deciding whether boxes overlap too much with respect to IOU. score_threshold: a float representing the threshold for deciding when to remove boxes based on score. Returns: nms_boxes: `float` Tensor of shape [batch_size, max_total_size, 4] representing top detected boxes in [y1, x1, y2, x2]. nms_scores: `float` Tensor of shape [batch_size, max_total_size] representing sorted confidence scores for detected boxes. The values are between [0, 1]. nms_classes: `int` Tensor of shape [batch_size, max_total_size] representing classes for detected boxes. valid_detections: `int` Tensor of shape [batch_size] only the top `valid_detections` boxes are valid detections. """ with tf.name_scope('generate_detections'): # TODO(tsungyi): Removes normalization/denomalization once the # tf.image.combined_non_max_suppression is coordinate system agnostic. # Normalizes maximum box cooridinates to 1. normalizer = tf.reduce_max(boxes) boxes /= normalizer (nmsed_boxes, nmsed_scores, nmsed_classes, valid_detections) = tf.image.combined_non_max_suppression( boxes, scores, max_output_size_per_class=max_total_size, max_total_size=max_total_size, iou_threshold=nms_iou_threshold, score_threshold=score_threshold, pad_per_class=False, ) # De-normalizes box cooridinates. nmsed_boxes *= normalizer nmsed_classes = tf.cast(nmsed_classes, tf.int32) return nmsed_boxes, nmsed_scores, nmsed_classes, valid_detections class MultilevelDetectionGenerator(tf.keras.layers.Layer): """Generates detected boxes with scores and classes for one-stage detector.""" def __init__(self, min_level, max_level, params): self._min_level = min_level self._max_level = max_level self._generate_detections = generate_detections_factory(params) super(MultilevelDetectionGenerator, self).__init__(autocast=False) def call(self, box_outputs, class_outputs, anchor_boxes, image_shape): # Collects outputs from all levels into a list. boxes = [] scores = [] for i in range(self._min_level, self._max_level + 1): box_outputs_i_shape = tf.shape(box_outputs[i]) batch_size = box_outputs_i_shape[0] num_anchors_per_locations = box_outputs_i_shape[-1] // 4 num_classes = tf.shape(class_outputs[i])[-1] // num_anchors_per_locations # Applies score transformation and remove the implicit background class. scores_i = tf.sigmoid( tf.reshape(class_outputs[i], [batch_size, -1, num_classes])) scores_i = tf.slice(scores_i, [0, 0, 1], [-1, -1, -1]) # Box decoding. # The anchor boxes are shared for all data in a batch. # One stage detector only supports class agnostic box regression. anchor_boxes_i = tf.reshape(anchor_boxes[i], [batch_size, -1, 4]) box_outputs_i = tf.reshape(box_outputs[i], [batch_size, -1, 4]) boxes_i = box_utils.decode_boxes(box_outputs_i, anchor_boxes_i) # Box clipping. boxes_i = box_utils.clip_boxes(boxes_i, image_shape) boxes.append(boxes_i) scores.append(scores_i) boxes = tf.concat(boxes, axis=1) scores = tf.concat(scores, axis=1) nmsed_boxes, nmsed_scores, nmsed_classes, valid_detections = ( self._generate_detections(tf.expand_dims(boxes, axis=2), scores)) # Adds 1 to offset the background class which has index 0. nmsed_classes += 1 return nmsed_boxes, nmsed_scores, nmsed_classes, valid_detections class GenericDetectionGenerator(tf.keras.layers.Layer): """Generates the final detected boxes with scores and classes.""" def __init__(self, params): super(GenericDetectionGenerator, self).__init__(autocast=False) self._generate_detections = generate_detections_factory(params) def call(self, box_outputs, class_outputs, anchor_boxes, image_shape): """Generate final detections. Args: box_outputs: a tensor of shape of [batch_size, K, num_classes * 4] representing the class-specific box coordinates relative to anchors. class_outputs: a tensor of shape of [batch_size, K, num_classes] representing the class logits before applying score activiation. anchor_boxes: a tensor of shape of [batch_size, K, 4] representing the corresponding anchor boxes w.r.t `box_outputs`. image_shape: a tensor of shape of [batch_size, 2] storing the image height and width w.r.t. the scaled image, i.e. the same image space as `box_outputs` and `anchor_boxes`. Returns: nms_boxes: `float` Tensor of shape [batch_size, max_total_size, 4] representing top detected boxes in [y1, x1, y2, x2]. nms_scores: `float` Tensor of shape [batch_size, max_total_size] representing sorted confidence scores for detected boxes. The values are between [0, 1]. nms_classes: `int` Tensor of shape [batch_size, max_total_size] representing classes for detected boxes. valid_detections: `int` Tensor of shape [batch_size] only the top `valid_detections` boxes are valid detections. """ class_outputs = tf.nn.softmax(class_outputs, axis=-1) # Removes the background class. class_outputs_shape = tf.shape(class_outputs) batch_size = class_outputs_shape[0] num_locations = class_outputs_shape[1] num_classes = class_outputs_shape[-1] num_detections = num_locations * (num_classes - 1) class_outputs = tf.slice(class_outputs, [0, 0, 1], [-1, -1, -1]) box_outputs = tf.reshape( box_outputs, tf.stack([batch_size, num_locations, num_classes, 4], axis=-1)) box_outputs = tf.slice(box_outputs, [0, 0, 1, 0], [-1, -1, -1, -1]) anchor_boxes = tf.tile( tf.expand_dims(anchor_boxes, axis=2), [1, 1, num_classes - 1, 1]) box_outputs = tf.reshape(box_outputs, tf.stack([batch_size, num_detections, 4], axis=-1)) anchor_boxes = tf.reshape( anchor_boxes, tf.stack([batch_size, num_detections, 4], axis=-1)) # Box decoding. decoded_boxes = box_utils.decode_boxes( box_outputs, anchor_boxes, weights=[10.0, 10.0, 5.0, 5.0]) # Box clipping decoded_boxes = box_utils.clip_boxes(decoded_boxes, image_shape) decoded_boxes = tf.reshape( decoded_boxes, tf.stack([batch_size, num_locations, num_classes - 1, 4], axis=-1)) nmsed_boxes, nmsed_scores, nmsed_classes, valid_detections = ( self._generate_detections(decoded_boxes, class_outputs)) # Adds 1 to offset the background class which has index 0. nmsed_classes += 1 return nmsed_boxes, nmsed_scores, nmsed_classes, valid_detections class OlnDetectionGenerator(GenericDetectionGenerator): """Generates the final detected boxes with scores and classes.""" def __call__(self, box_outputs, class_outputs, anchor_boxes, image_shape, is_single_fg_score=False, keep_nms=True): """Generate final detections for Object Localization Network (OLN). Args: box_outputs: a tensor of shape of [batch_size, K, num_classes * 4] representing the class-specific box coordinates relative to anchors. class_outputs: a tensor of shape of [batch_size, K, num_classes] representing the class logits before applying score activiation. anchor_boxes: a tensor of shape of [batch_size, K, 4] representing the corresponding anchor boxes w.r.t `box_outputs`. image_shape: a tensor of shape of [batch_size, 2] storing the image height and width w.r.t. the scaled image, i.e. the same image space as `box_outputs` and `anchor_boxes`. is_single_fg_score: a Bool indicator of whether class_outputs includes the background scores concatenated or not. By default, class_outputs is a concatenation of both scores for the foreground and background. That is, scores_without_bg=False. keep_nms: a Bool indicator of whether to perform NMS or not. Returns: nms_boxes: `float` Tensor of shape [batch_size, max_total_size, 4] representing top detected boxes in [y1, x1, y2, x2]. nms_scores: `float` Tensor of shape [batch_size, max_total_size] representing sorted confidence scores for detected boxes. The values are between [0, 1]. nms_classes: `int` Tensor of shape [batch_size, max_total_size] representing classes for detected boxes. valid_detections: `int` Tensor of shape [batch_size] only the top `valid_detections` boxes are valid detections. """ if is_single_fg_score: # Concatenates dummy background scores. dummy_bg_scores = tf.zeros_like(class_outputs) class_outputs = tf.stack([dummy_bg_scores, class_outputs], -1) else: class_outputs = tf.nn.softmax(class_outputs, axis=-1) # Removes the background class. class_outputs_shape = tf.shape(class_outputs) batch_size = class_outputs_shape[0] num_locations = class_outputs_shape[1] num_classes = class_outputs_shape[-1] num_detections = num_locations * (num_classes - 1) class_outputs = tf.slice(class_outputs, [0, 0, 1], [-1, -1, -1]) box_outputs = tf.reshape( box_outputs, tf.stack([batch_size, num_locations, num_classes, 4], axis=-1)) box_outputs = tf.slice(box_outputs, [0, 0, 1, 0], [-1, -1, -1, -1]) anchor_boxes = tf.tile( tf.expand_dims(anchor_boxes, axis=2), [1, 1, num_classes - 1, 1]) box_outputs = tf.reshape(box_outputs, tf.stack([batch_size, num_detections, 4], axis=-1)) anchor_boxes = tf.reshape( anchor_boxes, tf.stack([batch_size, num_detections, 4], axis=-1)) # Box decoding. For RPN outputs, box_outputs are all zeros. decoded_boxes = box_utils.decode_boxes( box_outputs, anchor_boxes, weights=[10.0, 10.0, 5.0, 5.0]) # Box clipping decoded_boxes = box_utils.clip_boxes(decoded_boxes, image_shape) decoded_boxes = tf.reshape( decoded_boxes, tf.stack([batch_size, num_locations, num_classes - 1, 4], axis=-1)) if keep_nms: nmsed_boxes, nmsed_scores, nmsed_classes, valid_detections = ( self._generate_detections(decoded_boxes, class_outputs)) # Adds 1 to offset the background class which has index 0. nmsed_classes += 1 else: nmsed_boxes = decoded_boxes[:, :, 0, :] nmsed_scores = class_outputs[:, :, 0] nmsed_classes = tf.cast(tf.ones_like(nmsed_scores), tf.int32) valid_detections = tf.cast( tf.reduce_sum(tf.ones_like(nmsed_scores), axis=-1), tf.int32) return nmsed_boxes, nmsed_scores, nmsed_classes, valid_detections
21,942
43.062249
80
py
models
models-master/official/legacy/detection/ops/target_ops.py
# Copyright 2023 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. """Target and sampling related ops.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from official.legacy.detection.ops import spatial_transform_ops from official.legacy.detection.utils import box_utils from official.vision.utils.object_detection import balanced_positive_negative_sampler def box_matching(boxes, gt_boxes, gt_classes): """Match boxes to groundtruth boxes. Given the proposal boxes and the groundtruth boxes and classes, perform the groundtruth matching by taking the argmax of the IoU between boxes and groundtruth boxes. Args: boxes: a tensor of shape of [batch_size, N, 4] representing the box coordiantes to be matched to groundtruth boxes. gt_boxes: a tensor of shape of [batch_size, MAX_INSTANCES, 4] representing the groundtruth box coordinates. It is padded with -1s to indicate the invalid boxes. gt_classes: [batch_size, MAX_INSTANCES] representing the groundtruth box classes. It is padded with -1s to indicate the invalid classes. Returns: matched_gt_boxes: a tensor of shape of [batch_size, N, 4], representing the matched groundtruth box coordinates for each input box. If the box does not overlap with any groundtruth boxes, the matched boxes of it will be set to all 0s. matched_gt_classes: a tensor of shape of [batch_size, N], representing the matched groundtruth classes for each input box. If the box does not overlap with any groundtruth boxes, the matched box classes of it will be set to 0, which corresponds to the background class. matched_gt_indices: a tensor of shape of [batch_size, N], representing the indices of the matched groundtruth boxes in the original gt_boxes tensor. If the box does not overlap with any groundtruth boxes, the index of the matched groundtruth will be set to -1. matched_iou: a tensor of shape of [batch_size, N], representing the IoU between the box and its matched groundtruth box. The matched IoU is the maximum IoU of the box and all the groundtruth boxes. iou: a tensor of shape of [batch_size, N, K], representing the IoU matrix between boxes and the groundtruth boxes. The IoU between a box and the invalid groundtruth boxes whose coordinates are [-1, -1, -1, -1] is -1. """ # Compute IoU between boxes and gt_boxes. # iou <- [batch_size, N, K] iou = box_utils.bbox_overlap(boxes, gt_boxes) # max_iou <- [batch_size, N] # 0.0 -> no match to gt, or -1.0 match to no gt matched_iou = tf.reduce_max(iou, axis=-1) # background_box_mask <- bool, [batch_size, N] background_box_mask = tf.less_equal(matched_iou, 0.0) argmax_iou_indices = tf.argmax(iou, axis=-1, output_type=tf.int32) argmax_iou_indices_shape = tf.shape(argmax_iou_indices) batch_indices = ( tf.expand_dims(tf.range(argmax_iou_indices_shape[0]), axis=-1) * tf.ones([1, argmax_iou_indices_shape[-1]], dtype=tf.int32)) gather_nd_indices = tf.stack([batch_indices, argmax_iou_indices], axis=-1) matched_gt_boxes = tf.gather_nd(gt_boxes, gather_nd_indices) matched_gt_boxes = tf.where( tf.tile(tf.expand_dims(background_box_mask, axis=-1), [1, 1, 4]), tf.zeros_like(matched_gt_boxes, dtype=matched_gt_boxes.dtype), matched_gt_boxes) matched_gt_classes = tf.gather_nd(gt_classes, gather_nd_indices) matched_gt_classes = tf.where(background_box_mask, tf.zeros_like(matched_gt_classes), matched_gt_classes) matched_gt_indices = tf.where(background_box_mask, -tf.ones_like(argmax_iou_indices), argmax_iou_indices) return (matched_gt_boxes, matched_gt_classes, matched_gt_indices, matched_iou, iou) def assign_and_sample_proposals(proposed_boxes, gt_boxes, gt_classes, num_samples_per_image=512, mix_gt_boxes=True, fg_fraction=0.25, fg_iou_thresh=0.5, bg_iou_thresh_hi=0.5, bg_iou_thresh_lo=0.0): """Assigns the proposals with groundtruth classes and performs subsmpling. Given `proposed_boxes`, `gt_boxes`, and `gt_classes`, the function uses the following algorithm to generate the final `num_samples_per_image` RoIs. 1. Calculates the IoU between each proposal box and each gt_boxes. 2. Assigns each proposed box with a groundtruth class and box by choosing the largest IoU overlap. 3. Samples `num_samples_per_image` boxes from all proposed boxes, and returns box_targets, class_targets, and RoIs. Args: proposed_boxes: a tensor of shape of [batch_size, N, 4]. N is the number of proposals before groundtruth assignment. The last dimension is the box coordinates w.r.t. the scaled images in [ymin, xmin, ymax, xmax] format. gt_boxes: a tensor of shape of [batch_size, MAX_NUM_INSTANCES, 4]. The coordinates of gt_boxes are in the pixel coordinates of the scaled image. This tensor might have padding of values -1 indicating the invalid box coordinates. gt_classes: a tensor with a shape of [batch_size, MAX_NUM_INSTANCES]. This tensor might have paddings with values of -1 indicating the invalid classes. num_samples_per_image: a integer represents RoI minibatch size per image. mix_gt_boxes: a bool indicating whether to mix the groundtruth boxes before sampling proposals. fg_fraction: a float represents the target fraction of RoI minibatch that is labeled foreground (i.e., class > 0). fg_iou_thresh: a float represents the IoU overlap threshold for an RoI to be considered foreground (if >= fg_iou_thresh). bg_iou_thresh_hi: a float represents the IoU overlap threshold for an RoI to be considered background (class = 0 if overlap in [LO, HI)). bg_iou_thresh_lo: a float represents the IoU overlap threshold for an RoI to be considered background (class = 0 if overlap in [LO, HI)). Returns: sampled_rois: a tensor of shape of [batch_size, K, 4], representing the coordinates of the sampled RoIs, where K is the number of the sampled RoIs, i.e. K = num_samples_per_image. sampled_gt_boxes: a tensor of shape of [batch_size, K, 4], storing the box coordinates of the matched groundtruth boxes of the samples RoIs. sampled_gt_classes: a tensor of shape of [batch_size, K], storing the classes of the matched groundtruth boxes of the sampled RoIs. sampled_gt_indices: a tensor of shape of [batch_size, K], storing the indices of the sampled groudntruth boxes in the original `gt_boxes` tensor, i.e. gt_boxes[sampled_gt_indices[:, i]] = sampled_gt_boxes[:, i]. """ with tf.name_scope('sample_proposals'): if mix_gt_boxes: boxes = tf.concat([proposed_boxes, gt_boxes], axis=1) else: boxes = proposed_boxes (matched_gt_boxes, matched_gt_classes, matched_gt_indices, matched_iou, _) = box_matching(boxes, gt_boxes, gt_classes) positive_match = tf.greater(matched_iou, fg_iou_thresh) negative_match = tf.logical_and( tf.greater_equal(matched_iou, bg_iou_thresh_lo), tf.less(matched_iou, bg_iou_thresh_hi)) ignored_match = tf.less(matched_iou, 0.0) # re-assign negatively matched boxes to the background class. matched_gt_classes = tf.where(negative_match, tf.zeros_like(matched_gt_classes), matched_gt_classes) matched_gt_indices = tf.where(negative_match, tf.zeros_like(matched_gt_indices), matched_gt_indices) sample_candidates = tf.logical_and( tf.logical_or(positive_match, negative_match), tf.logical_not(ignored_match)) sampler = ( balanced_positive_negative_sampler.BalancedPositiveNegativeSampler( positive_fraction=fg_fraction, is_static=True)) batch_size, _ = sample_candidates.get_shape().as_list() sampled_indicators = [] for i in range(batch_size): sampled_indicator = sampler.subsample(sample_candidates[i], num_samples_per_image, positive_match[i]) sampled_indicators.append(sampled_indicator) sampled_indicators = tf.stack(sampled_indicators) _, sampled_indices = tf.nn.top_k( tf.cast(sampled_indicators, dtype=tf.int32), k=num_samples_per_image, sorted=True) sampled_indices_shape = tf.shape(sampled_indices) batch_indices = ( tf.expand_dims(tf.range(sampled_indices_shape[0]), axis=-1) * tf.ones([1, sampled_indices_shape[-1]], dtype=tf.int32)) gather_nd_indices = tf.stack([batch_indices, sampled_indices], axis=-1) sampled_rois = tf.gather_nd(boxes, gather_nd_indices) sampled_gt_boxes = tf.gather_nd(matched_gt_boxes, gather_nd_indices) sampled_gt_classes = tf.gather_nd(matched_gt_classes, gather_nd_indices) sampled_gt_indices = tf.gather_nd(matched_gt_indices, gather_nd_indices) return (sampled_rois, sampled_gt_boxes, sampled_gt_classes, sampled_gt_indices) def sample_and_crop_foreground_masks(candidate_rois, candidate_gt_boxes, candidate_gt_classes, candidate_gt_indices, gt_masks, num_mask_samples_per_image=128, mask_target_size=28): """Samples and creates cropped foreground masks for training. Args: candidate_rois: a tensor of shape of [batch_size, N, 4], where N is the number of candidate RoIs to be considered for mask sampling. It includes both positive and negative RoIs. The `num_mask_samples_per_image` positive RoIs will be sampled to create mask training targets. candidate_gt_boxes: a tensor of shape of [batch_size, N, 4], storing the corresponding groundtruth boxes to the `candidate_rois`. candidate_gt_classes: a tensor of shape of [batch_size, N], storing the corresponding groundtruth classes to the `candidate_rois`. 0 in the tensor corresponds to the background class, i.e. negative RoIs. candidate_gt_indices: a tensor of shape [batch_size, N], storing the corresponding groundtruth instance indices to the `candidate_gt_boxes`, i.e. gt_boxes[candidate_gt_indices[:, i]] = candidate_gt_boxes[:, i] and gt_boxes which is of shape [batch_size, MAX_INSTANCES, 4], M >= N, is the superset of candidate_gt_boxes. gt_masks: a tensor of [batch_size, MAX_INSTANCES, mask_height, mask_width] containing all the groundtruth masks which sample masks are drawn from. num_mask_samples_per_image: an integer which specifies the number of masks to sample. mask_target_size: an integer which specifies the final cropped mask size after sampling. The output masks are resized w.r.t the sampled RoIs. Returns: foreground_rois: a tensor of shape of [batch_size, K, 4] storing the RoI that corresponds to the sampled foreground masks, where K = num_mask_samples_per_image. foreground_classes: a tensor of shape of [batch_size, K] storing the classes corresponding to the sampled foreground masks. cropoped_foreground_masks: a tensor of shape of [batch_size, K, mask_target_size, mask_target_size] storing the cropped foreground masks used for training. """ with tf.name_scope('sample_and_crop_foreground_masks'): _, fg_instance_indices = tf.nn.top_k( tf.cast(tf.greater(candidate_gt_classes, 0), dtype=tf.int32), k=num_mask_samples_per_image) fg_instance_indices_shape = tf.shape(fg_instance_indices) batch_indices = ( tf.expand_dims(tf.range(fg_instance_indices_shape[0]), axis=-1) * tf.ones([1, fg_instance_indices_shape[-1]], dtype=tf.int32)) gather_nd_instance_indices = tf.stack([batch_indices, fg_instance_indices], axis=-1) foreground_rois = tf.gather_nd(candidate_rois, gather_nd_instance_indices) foreground_boxes = tf.gather_nd(candidate_gt_boxes, gather_nd_instance_indices) foreground_classes = tf.gather_nd(candidate_gt_classes, gather_nd_instance_indices) foreground_gt_indices = tf.gather_nd(candidate_gt_indices, gather_nd_instance_indices) foreground_gt_indices_shape = tf.shape(foreground_gt_indices) batch_indices = ( tf.expand_dims(tf.range(foreground_gt_indices_shape[0]), axis=-1) * tf.ones([1, foreground_gt_indices_shape[-1]], dtype=tf.int32)) gather_nd_gt_indices = tf.stack([batch_indices, foreground_gt_indices], axis=-1) foreground_masks = tf.gather_nd(gt_masks, gather_nd_gt_indices) cropped_foreground_masks = spatial_transform_ops.crop_mask_in_target_box( foreground_masks, foreground_boxes, foreground_rois, mask_target_size, sample_offset=0.5) return foreground_rois, foreground_classes, cropped_foreground_masks class ROISampler(tf.keras.layers.Layer): """Samples RoIs and creates training targets.""" def __init__(self, params): self._num_samples_per_image = params.num_samples_per_image self._fg_fraction = params.fg_fraction self._fg_iou_thresh = params.fg_iou_thresh self._bg_iou_thresh_hi = params.bg_iou_thresh_hi self._bg_iou_thresh_lo = params.bg_iou_thresh_lo self._mix_gt_boxes = params.mix_gt_boxes super(ROISampler, self).__init__(autocast=False) def call(self, rois, gt_boxes, gt_classes): """Sample and assign RoIs for training. Args: rois: a tensor of shape of [batch_size, N, 4]. N is the number of proposals before groundtruth assignment. The last dimension is the box coordinates w.r.t. the scaled images in [ymin, xmin, ymax, xmax] format. gt_boxes: a tensor of shape of [batch_size, MAX_NUM_INSTANCES, 4]. The coordinates of gt_boxes are in the pixel coordinates of the scaled image. This tensor might have padding of values -1 indicating the invalid box coordinates. gt_classes: a tensor with a shape of [batch_size, MAX_NUM_INSTANCES]. This tensor might have paddings with values of -1 indicating the invalid classes. Returns: sampled_rois: a tensor of shape of [batch_size, K, 4], representing the coordinates of the sampled RoIs, where K is the number of the sampled RoIs, i.e. K = num_samples_per_image. sampled_gt_boxes: a tensor of shape of [batch_size, K, 4], storing the box coordinates of the matched groundtruth boxes of the samples RoIs. sampled_gt_classes: a tensor of shape of [batch_size, K], storing the classes of the matched groundtruth boxes of the sampled RoIs. """ sampled_rois, sampled_gt_boxes, sampled_gt_classes, sampled_gt_indices = ( assign_and_sample_proposals( rois, gt_boxes, gt_classes, num_samples_per_image=self._num_samples_per_image, mix_gt_boxes=self._mix_gt_boxes, fg_fraction=self._fg_fraction, fg_iou_thresh=self._fg_iou_thresh, bg_iou_thresh_hi=self._bg_iou_thresh_hi, bg_iou_thresh_lo=self._bg_iou_thresh_lo)) return (sampled_rois, sampled_gt_boxes, sampled_gt_classes, sampled_gt_indices) class ROIScoreSampler(ROISampler): """Samples RoIs, RoI-scores and creates training targets.""" def __call__(self, rois, roi_scores, gt_boxes, gt_classes): """Sample and assign RoIs for training. Args: rois: a tensor of shape of [batch_size, N, 4]. N is the number of proposals before groundtruth assignment. The last dimension is the box coordinates w.r.t. the scaled images in [ymin, xmin, ymax, xmax] format. roi_scores: gt_boxes: a tensor of shape of [batch_size, MAX_NUM_INSTANCES, 4]. The coordinates of gt_boxes are in the pixel coordinates of the scaled image. This tensor might have padding of values -1 indicating the invalid box coordinates. gt_classes: a tensor with a shape of [batch_size, MAX_NUM_INSTANCES]. This tensor might have paddings with values of -1 indicating the invalid classes. Returns: sampled_rois: a tensor of shape of [batch_size, K, 4], representing the coordinates of the sampled RoIs, where K is the number of the sampled RoIs, i.e. K = num_samples_per_image. sampled_roi_scores: sampled_gt_boxes: a tensor of shape of [batch_size, K, 4], storing the box coordinates of the matched groundtruth boxes of the samples RoIs. sampled_gt_classes: a tensor of shape of [batch_size, K], storing the classes of the matched groundtruth boxes of the sampled RoIs. """ (sampled_rois, sampled_roi_scores, sampled_gt_boxes, sampled_gt_classes, sampled_gt_indices) = ( self.assign_and_sample_proposals_and_scores( rois, roi_scores, gt_boxes, gt_classes, num_samples_per_image=self._num_samples_per_image, mix_gt_boxes=self._mix_gt_boxes, fg_fraction=self._fg_fraction, fg_iou_thresh=self._fg_iou_thresh, bg_iou_thresh_hi=self._bg_iou_thresh_hi, bg_iou_thresh_lo=self._bg_iou_thresh_lo)) return (sampled_rois, sampled_roi_scores, sampled_gt_boxes, sampled_gt_classes, sampled_gt_indices) def assign_and_sample_proposals_and_scores(self, proposed_boxes, proposed_scores, gt_boxes, gt_classes, num_samples_per_image=512, mix_gt_boxes=True, fg_fraction=0.25, fg_iou_thresh=0.5, bg_iou_thresh_hi=0.5, bg_iou_thresh_lo=0.0): """Assigns the proposals with groundtruth classes and performs subsmpling. Given `proposed_boxes`, `gt_boxes`, and `gt_classes`, the function uses the following algorithm to generate the final `num_samples_per_image` RoIs. 1. Calculates the IoU between each proposal box and each gt_boxes. 2. Assigns each proposed box with a groundtruth class and box by choosing the largest IoU overlap. 3. Samples `num_samples_per_image` boxes from all proposed boxes, and returns box_targets, class_targets, and RoIs. Args: proposed_boxes: a tensor of shape of [batch_size, N, 4]. N is the number of proposals before groundtruth assignment. The last dimension is the box coordinates w.r.t. the scaled images in [ymin, xmin, ymax, xmax] format. proposed_scores: a tensor of shape of [batch_size, N]. N is the number of proposals before groundtruth assignment. It is the rpn scores for all proposed boxes which can be either their classification or centerness scores. gt_boxes: a tensor of shape of [batch_size, MAX_NUM_INSTANCES, 4]. The coordinates of gt_boxes are in the pixel coordinates of the scaled image. This tensor might have padding of values -1 indicating the invalid box coordinates. gt_classes: a tensor with a shape of [batch_size, MAX_NUM_INSTANCES]. This tensor might have paddings with values of -1 indicating the invalid classes. num_samples_per_image: a integer represents RoI minibatch size per image. mix_gt_boxes: a bool indicating whether to mix the groundtruth boxes before sampling proposals. fg_fraction: a float represents the target fraction of RoI minibatch that is labeled foreground (i.e., class > 0). fg_iou_thresh: a float represents the IoU overlap threshold for an RoI to be considered foreground (if >= fg_iou_thresh). bg_iou_thresh_hi: a float represents the IoU overlap threshold for an RoI to be considered background (class = 0 if overlap in [LO, HI)). bg_iou_thresh_lo: a float represents the IoU overlap threshold for an RoI to be considered background (class = 0 if overlap in [LO, HI)). Returns: sampled_rois: a tensor of shape of [batch_size, K, 4], representing the coordinates of the sampled RoIs, where K is the number of the sampled RoIs, i.e. K = num_samples_per_image. sampled_scores: a tensor of shape of [batch_size, K], representing the confidence score of the sampled RoIs, where K is the number of the sampled RoIs, i.e. K = num_samples_per_image. sampled_gt_boxes: a tensor of shape of [batch_size, K, 4], storing the box coordinates of the matched groundtruth boxes of the samples RoIs. sampled_gt_classes: a tensor of shape of [batch_size, K], storing the classes of the matched groundtruth boxes of the sampled RoIs. sampled_gt_indices: a tensor of shape of [batch_size, K], storing the indices of the sampled groudntruth boxes in the original `gt_boxes` tensor, i.e. gt_boxes[sampled_gt_indices[:, i]] = sampled_gt_boxes[:, i]. """ with tf.name_scope('sample_proposals_and_scores'): if mix_gt_boxes: boxes = tf.concat([proposed_boxes, gt_boxes], axis=1) gt_scores = tf.ones_like(gt_boxes[:, :, 0]) scores = tf.concat([proposed_scores, gt_scores], axis=1) else: boxes = proposed_boxes scores = proposed_scores (matched_gt_boxes, matched_gt_classes, matched_gt_indices, matched_iou, _) = box_matching(boxes, gt_boxes, gt_classes) positive_match = tf.greater(matched_iou, fg_iou_thresh) negative_match = tf.logical_and( tf.greater_equal(matched_iou, bg_iou_thresh_lo), tf.less(matched_iou, bg_iou_thresh_hi)) ignored_match = tf.less(matched_iou, 0.0) # re-assign negatively matched boxes to the background class. matched_gt_classes = tf.where(negative_match, tf.zeros_like(matched_gt_classes), matched_gt_classes) matched_gt_indices = tf.where(negative_match, tf.zeros_like(matched_gt_indices), matched_gt_indices) sample_candidates = tf.logical_and( tf.logical_or(positive_match, negative_match), tf.logical_not(ignored_match)) sampler = ( balanced_positive_negative_sampler.BalancedPositiveNegativeSampler( positive_fraction=fg_fraction, is_static=True)) batch_size, _ = sample_candidates.get_shape().as_list() sampled_indicators = [] for i in range(batch_size): sampled_indicator = sampler.subsample(sample_candidates[i], num_samples_per_image, positive_match[i]) sampled_indicators.append(sampled_indicator) sampled_indicators = tf.stack(sampled_indicators) _, sampled_indices = tf.nn.top_k( tf.cast(sampled_indicators, dtype=tf.int32), k=num_samples_per_image, sorted=True) sampled_indices_shape = tf.shape(sampled_indices) batch_indices = ( tf.expand_dims(tf.range(sampled_indices_shape[0]), axis=-1) * tf.ones([1, sampled_indices_shape[-1]], dtype=tf.int32)) gather_nd_indices = tf.stack([batch_indices, sampled_indices], axis=-1) sampled_rois = tf.gather_nd(boxes, gather_nd_indices) sampled_roi_scores = tf.gather_nd(scores, gather_nd_indices) sampled_gt_boxes = tf.gather_nd(matched_gt_boxes, gather_nd_indices) sampled_gt_classes = tf.gather_nd(matched_gt_classes, gather_nd_indices) sampled_gt_indices = tf.gather_nd(matched_gt_indices, gather_nd_indices) return (sampled_rois, sampled_roi_scores, sampled_gt_boxes, sampled_gt_classes, sampled_gt_indices) class MaskSampler(tf.keras.layers.Layer): """Samples and creates mask training targets.""" def __init__(self, mask_target_size, num_mask_samples_per_image): self._mask_target_size = mask_target_size self._num_mask_samples_per_image = num_mask_samples_per_image super(MaskSampler, self).__init__(autocast=False) def call(self, candidate_rois, candidate_gt_boxes, candidate_gt_classes, candidate_gt_indices, gt_masks): """Sample and create mask targets for training. Args: candidate_rois: a tensor of shape of [batch_size, N, 4], where N is the number of candidate RoIs to be considered for mask sampling. It includes both positive and negative RoIs. The `num_mask_samples_per_image` positive RoIs will be sampled to create mask training targets. candidate_gt_boxes: a tensor of shape of [batch_size, N, 4], storing the corresponding groundtruth boxes to the `candidate_rois`. candidate_gt_classes: a tensor of shape of [batch_size, N], storing the corresponding groundtruth classes to the `candidate_rois`. 0 in the tensor corresponds to the background class, i.e. negative RoIs. candidate_gt_indices: a tensor of shape [batch_size, N], storing the corresponding groundtruth instance indices to the `candidate_gt_boxes`, i.e. gt_boxes[candidate_gt_indices[:, i]] = candidate_gt_boxes[:, i], where gt_boxes which is of shape [batch_size, MAX_INSTANCES, 4], M >= N, is the superset of candidate_gt_boxes. gt_masks: a tensor of [batch_size, MAX_INSTANCES, mask_height, mask_width] containing all the groundtruth masks which sample masks are drawn from. after sampling. The output masks are resized w.r.t the sampled RoIs. Returns: foreground_rois: a tensor of shape of [batch_size, K, 4] storing the RoI that corresponds to the sampled foreground masks, where K = num_mask_samples_per_image. foreground_classes: a tensor of shape of [batch_size, K] storing the classes corresponding to the sampled foreground masks. cropoped_foreground_masks: a tensor of shape of [batch_size, K, mask_target_size, mask_target_size] storing the cropped foreground masks used for training. """ foreground_rois, foreground_classes, cropped_foreground_masks = ( sample_and_crop_foreground_masks(candidate_rois, candidate_gt_boxes, candidate_gt_classes, candidate_gt_indices, gt_masks, self._num_mask_samples_per_image, self._mask_target_size)) return foreground_rois, foreground_classes, cropped_foreground_masks
28,304
48.484266
85
py
models
models-master/research/adversarial_text/layers.py
# Copyright 2017 Google Inc. 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. # ============================================================================== """Layers for VatxtModel.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # Dependency imports from six.moves import xrange import tensorflow as tf K = tf.keras def cl_logits_subgraph(layer_sizes, input_size, num_classes, keep_prob=1.): """Construct multiple ReLU layers with dropout and a linear layer.""" subgraph = K.models.Sequential(name='cl_logits') for i, layer_size in enumerate(layer_sizes): if i == 0: subgraph.add( K.layers.Dense(layer_size, activation='relu', input_dim=input_size)) else: subgraph.add(K.layers.Dense(layer_size, activation='relu')) if keep_prob < 1.: subgraph.add(K.layers.Dropout(1. - keep_prob)) subgraph.add(K.layers.Dense(1 if num_classes == 2 else num_classes)) return subgraph class Embedding(K.layers.Layer): """Embedding layer with frequency-based normalization and dropout.""" def __init__(self, vocab_size, embedding_dim, normalize=False, vocab_freqs=None, keep_prob=1., **kwargs): self.vocab_size = vocab_size self.embedding_dim = embedding_dim self.normalized = normalize self.keep_prob = keep_prob if normalize: assert vocab_freqs is not None self.vocab_freqs = tf.constant( vocab_freqs, dtype=tf.float32, shape=(vocab_size, 1)) super(Embedding, self).__init__(**kwargs) def build(self, input_shape): with tf.device('/cpu:0'): self.var = self.add_weight( shape=(self.vocab_size, self.embedding_dim), initializer=tf.random_uniform_initializer(-1., 1.), name='embedding', dtype=tf.float32) if self.normalized: self.var = self._normalize(self.var) super(Embedding, self).build(input_shape) def call(self, x): embedded = tf.nn.embedding_lookup(self.var, x) if self.keep_prob < 1.: shape = embedded.get_shape().as_list() # Use same dropout masks at each timestep with specifying noise_shape. # This slightly improves performance. # Please see https://arxiv.org/abs/1512.05287 for the theoretical # explanation. embedded = tf.nn.dropout( embedded, self.keep_prob, noise_shape=(shape[0], 1, shape[2])) return embedded def _normalize(self, emb): weights = self.vocab_freqs / tf.reduce_sum(self.vocab_freqs) mean = tf.reduce_sum(weights * emb, 0, keep_dims=True) var = tf.reduce_sum(weights * tf.pow(emb - mean, 2.), 0, keep_dims=True) stddev = tf.sqrt(1e-6 + var) return (emb - mean) / stddev class LSTM(object): """LSTM layer using dynamic_rnn. Exposes variables in `trainable_weights` property. """ def __init__(self, cell_size, num_layers=1, keep_prob=1., name='LSTM'): self.cell_size = cell_size self.num_layers = num_layers self.keep_prob = keep_prob self.reuse = None self.trainable_weights = None self.name = name def __call__(self, x, initial_state, seq_length): with tf.variable_scope(self.name, reuse=self.reuse) as vs: cell = tf.contrib.rnn.MultiRNNCell([ tf.contrib.rnn.BasicLSTMCell( self.cell_size, forget_bias=0.0, reuse=tf.get_variable_scope().reuse) for _ in xrange(self.num_layers) ]) # shape(x) = (batch_size, num_timesteps, embedding_dim) lstm_out, next_state = tf.nn.dynamic_rnn( cell, x, initial_state=initial_state, sequence_length=seq_length) # shape(lstm_out) = (batch_size, timesteps, cell_size) if self.keep_prob < 1.: lstm_out = tf.nn.dropout(lstm_out, self.keep_prob) if self.reuse is None: self.trainable_weights = vs.global_variables() self.reuse = True return lstm_out, next_state class SoftmaxLoss(K.layers.Layer): """Softmax xentropy loss with candidate sampling.""" def __init__(self, vocab_size, num_candidate_samples=-1, vocab_freqs=None, **kwargs): self.vocab_size = vocab_size self.num_candidate_samples = num_candidate_samples self.vocab_freqs = vocab_freqs super(SoftmaxLoss, self).__init__(**kwargs) self.multiclass_dense_layer = K.layers.Dense(self.vocab_size) def build(self, input_shape): input_shape = input_shape[0].as_list() with tf.device('/cpu:0'): self.lin_w = self.add_weight( shape=(input_shape[-1], self.vocab_size), name='lm_lin_w', initializer=K.initializers.glorot_uniform()) self.lin_b = self.add_weight( shape=(self.vocab_size,), name='lm_lin_b', initializer=K.initializers.glorot_uniform()) self.multiclass_dense_layer.build(input_shape) super(SoftmaxLoss, self).build(input_shape) def call(self, inputs): x, labels, weights = inputs if self.num_candidate_samples > -1: assert self.vocab_freqs is not None labels_reshaped = tf.reshape(labels, [-1]) labels_reshaped = tf.expand_dims(labels_reshaped, -1) sampled = tf.nn.fixed_unigram_candidate_sampler( true_classes=labels_reshaped, num_true=1, num_sampled=self.num_candidate_samples, unique=True, range_max=self.vocab_size, unigrams=self.vocab_freqs) inputs_reshaped = tf.reshape(x, [-1, int(x.get_shape()[2])]) lm_loss = tf.nn.sampled_softmax_loss( weights=tf.transpose(self.lin_w), biases=self.lin_b, labels=labels_reshaped, inputs=inputs_reshaped, num_sampled=self.num_candidate_samples, num_classes=self.vocab_size, sampled_values=sampled) lm_loss = tf.reshape( lm_loss, [int(x.get_shape()[0]), int(x.get_shape()[1])]) else: logits = self.multiclass_dense_layer(x) lm_loss = tf.nn.sparse_softmax_cross_entropy_with_logits( logits=logits, labels=labels) lm_loss = tf.identity( tf.reduce_sum(lm_loss * weights) / _num_labels(weights), name='lm_xentropy_loss') return lm_loss def classification_loss(logits, labels, weights): """Computes cross entropy loss between logits and labels. Args: logits: 2-D [timesteps*batch_size, m] float tensor, where m=1 if num_classes=2, otherwise m=num_classes. labels: 1-D [timesteps*batch_size] integer tensor. weights: 1-D [timesteps*batch_size] float tensor. Returns: Loss scalar of type float. """ inner_dim = logits.get_shape().as_list()[-1] with tf.name_scope('classifier_loss'): # Logistic loss if inner_dim == 1: loss = tf.nn.sigmoid_cross_entropy_with_logits( logits=tf.squeeze(logits, -1), labels=tf.cast(labels, tf.float32)) # Softmax loss else: loss = tf.nn.sparse_softmax_cross_entropy_with_logits( logits=logits, labels=labels) num_lab = _num_labels(weights) tf.summary.scalar('num_labels', num_lab) return tf.identity( tf.reduce_sum(weights * loss) / num_lab, name='classification_xentropy') def accuracy(logits, targets, weights): """Computes prediction accuracy. Args: logits: 2-D classifier logits [timesteps*batch_size, num_classes] targets: 1-D [timesteps*batch_size] integer tensor. weights: 1-D [timesteps*batch_size] float tensor. Returns: Accuracy: float scalar. """ with tf.name_scope('accuracy'): eq = tf.cast(tf.equal(predictions(logits), targets), tf.float32) return tf.identity( tf.reduce_sum(weights * eq) / _num_labels(weights), name='accuracy') def predictions(logits): """Class prediction from logits.""" inner_dim = logits.get_shape().as_list()[-1] with tf.name_scope('predictions'): # For binary classification if inner_dim == 1: pred = tf.cast(tf.greater(tf.squeeze(logits, -1), 0.), tf.int64) # For multi-class classification else: pred = tf.argmax(logits, 2) return pred def _num_labels(weights): """Number of 1's in weights. Returns 1. if 0.""" num_labels = tf.reduce_sum(weights) num_labels = tf.where(tf.equal(num_labels, 0.), 1., num_labels) return num_labels def optimize(loss, global_step, max_grad_norm, lr, lr_decay, sync_replicas=False, replicas_to_aggregate=1, task_id=0): """Builds optimization graph. * Creates an optimizer, and optionally wraps with SyncReplicasOptimizer * Computes, clips, and applies gradients * Maintains moving averages for all trainable variables * Summarizes variables and gradients Args: loss: scalar loss to minimize. global_step: integer scalar Variable. max_grad_norm: float scalar. Grads will be clipped to this value. lr: float scalar, learning rate. lr_decay: float scalar, learning rate decay rate. sync_replicas: bool, whether to use SyncReplicasOptimizer. replicas_to_aggregate: int, number of replicas to aggregate when using SyncReplicasOptimizer. task_id: int, id of the current task; used to ensure proper initialization of SyncReplicasOptimizer. Returns: train_op """ with tf.name_scope('optimization'): # Compute gradients. tvars = tf.trainable_variables() grads = tf.gradients( loss, tvars, aggregation_method=tf.AggregationMethod.EXPERIMENTAL_ACCUMULATE_N) # Clip non-embedding grads non_embedding_grads_and_vars = [(g, v) for (g, v) in zip(grads, tvars) if 'embedding' not in v.op.name] embedding_grads_and_vars = [(g, v) for (g, v) in zip(grads, tvars) if 'embedding' in v.op.name] ne_grads, ne_vars = zip(*non_embedding_grads_and_vars) ne_grads, _ = tf.clip_by_global_norm(ne_grads, max_grad_norm) non_embedding_grads_and_vars = zip(ne_grads, ne_vars) grads_and_vars = embedding_grads_and_vars + list(non_embedding_grads_and_vars) # Summarize _summarize_vars_and_grads(grads_and_vars) # Decaying learning rate lr = tf.train.exponential_decay( lr, global_step, 1, lr_decay, staircase=True) tf.summary.scalar('learning_rate', lr) opt = tf.train.AdamOptimizer(lr) # Track the moving averages of all trainable variables. variable_averages = tf.train.ExponentialMovingAverage(0.999, global_step) # Apply gradients if sync_replicas: opt = tf.train.SyncReplicasOptimizer( opt, replicas_to_aggregate, variable_averages=variable_averages, variables_to_average=tvars, total_num_replicas=replicas_to_aggregate) apply_gradient_op = opt.apply_gradients( grads_and_vars, global_step=global_step) with tf.control_dependencies([apply_gradient_op]): train_op = tf.no_op(name='train_op') # Initialization ops tf.add_to_collection(tf.GraphKeys.QUEUE_RUNNERS, opt.get_chief_queue_runner()) if task_id == 0: # Chief task local_init_op = opt.chief_init_op tf.add_to_collection('chief_init_op', opt.get_init_tokens_op()) else: local_init_op = opt.local_step_init_op tf.add_to_collection('local_init_op', local_init_op) tf.add_to_collection('ready_for_local_init_op', opt.ready_for_local_init_op) else: # Non-sync optimizer apply_gradient_op = opt.apply_gradients(grads_and_vars, global_step) with tf.control_dependencies([apply_gradient_op]): train_op = variable_averages.apply(tvars) return train_op def _summarize_vars_and_grads(grads_and_vars): tf.logging.info('Trainable variables:') tf.logging.info('-' * 60) for grad, var in grads_and_vars: tf.logging.info(var) def tag(name, v=var): return v.op.name + '_' + name # Variable summary mean = tf.reduce_mean(var) tf.summary.scalar(tag('mean'), mean) with tf.name_scope(tag('stddev')): stddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean))) tf.summary.scalar(tag('stddev'), stddev) tf.summary.scalar(tag('max'), tf.reduce_max(var)) tf.summary.scalar(tag('min'), tf.reduce_min(var)) tf.summary.histogram(tag('histogram'), var) # Gradient summary if grad is not None: if isinstance(grad, tf.IndexedSlices): grad_values = grad.values else: grad_values = grad tf.summary.histogram(tag('gradient'), grad_values) tf.summary.scalar(tag('gradient_norm'), tf.global_norm([grad_values])) else: tf.logging.info('Var %s has no gradient', var.op.name)
13,373
32.603015
82
py
models
models-master/research/audioset/yamnet/yamnet.py
# Copyright 2019 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. # ============================================================================== """Core model definition of YAMNet.""" import csv import numpy as np import tensorflow as tf from tensorflow.keras import Model, layers import features as features_lib def _batch_norm(name, params): def _bn_layer(layer_input): return layers.BatchNormalization( name=name, center=params.batchnorm_center, scale=params.batchnorm_scale, epsilon=params.batchnorm_epsilon)(layer_input) return _bn_layer def _conv(name, kernel, stride, filters, params): def _conv_layer(layer_input): output = layers.Conv2D(name='{}/conv'.format(name), filters=filters, kernel_size=kernel, strides=stride, padding=params.conv_padding, use_bias=False, activation=None)(layer_input) output = _batch_norm('{}/conv/bn'.format(name), params)(output) output = layers.ReLU(name='{}/relu'.format(name))(output) return output return _conv_layer def _separable_conv(name, kernel, stride, filters, params): def _separable_conv_layer(layer_input): output = layers.DepthwiseConv2D(name='{}/depthwise_conv'.format(name), kernel_size=kernel, strides=stride, depth_multiplier=1, padding=params.conv_padding, use_bias=False, activation=None)(layer_input) output = _batch_norm('{}/depthwise_conv/bn'.format(name), params)(output) output = layers.ReLU(name='{}/depthwise_conv/relu'.format(name))(output) output = layers.Conv2D(name='{}/pointwise_conv'.format(name), filters=filters, kernel_size=(1, 1), strides=1, padding=params.conv_padding, use_bias=False, activation=None)(output) output = _batch_norm('{}/pointwise_conv/bn'.format(name), params)(output) output = layers.ReLU(name='{}/pointwise_conv/relu'.format(name))(output) return output return _separable_conv_layer _YAMNET_LAYER_DEFS = [ # (layer_function, kernel, stride, num_filters) (_conv, [3, 3], 2, 32), (_separable_conv, [3, 3], 1, 64), (_separable_conv, [3, 3], 2, 128), (_separable_conv, [3, 3], 1, 128), (_separable_conv, [3, 3], 2, 256), (_separable_conv, [3, 3], 1, 256), (_separable_conv, [3, 3], 2, 512), (_separable_conv, [3, 3], 1, 512), (_separable_conv, [3, 3], 1, 512), (_separable_conv, [3, 3], 1, 512), (_separable_conv, [3, 3], 1, 512), (_separable_conv, [3, 3], 1, 512), (_separable_conv, [3, 3], 2, 1024), (_separable_conv, [3, 3], 1, 1024) ] def yamnet(features, params): """Define the core YAMNet mode in Keras.""" net = layers.Reshape( (params.patch_frames, params.patch_bands, 1), input_shape=(params.patch_frames, params.patch_bands))(features) for (i, (layer_fun, kernel, stride, filters)) in enumerate(_YAMNET_LAYER_DEFS): net = layer_fun('layer{}'.format(i + 1), kernel, stride, filters, params)(net) embeddings = layers.GlobalAveragePooling2D()(net) logits = layers.Dense(units=params.num_classes, use_bias=True)(embeddings) predictions = layers.Activation(activation=params.classifier_activation)(logits) return predictions, embeddings def yamnet_frames_model(params): """Defines the YAMNet waveform-to-class-scores model. Args: params: An instance of Params containing hyperparameters. Returns: A model accepting (num_samples,) waveform input and emitting: - predictions: (num_patches, num_classes) matrix of class scores per time frame - embeddings: (num_patches, embedding size) matrix of embeddings per time frame - log_mel_spectrogram: (num_spectrogram_frames, num_mel_bins) spectrogram feature matrix """ waveform = layers.Input(batch_shape=(None,), dtype=tf.float32) waveform_padded = features_lib.pad_waveform(waveform, params) log_mel_spectrogram, features = features_lib.waveform_to_log_mel_spectrogram_patches( waveform_padded, params) predictions, embeddings = yamnet(features, params) frames_model = Model( name='yamnet_frames', inputs=waveform, outputs=[predictions, embeddings, log_mel_spectrogram]) return frames_model def class_names(class_map_csv): """Read the class name definition file and return a list of strings.""" if tf.is_tensor(class_map_csv): class_map_csv = class_map_csv.numpy() with open(class_map_csv) as csv_file: reader = csv.reader(csv_file) next(reader) # Skip header return np.array([display_name for (_, _, display_name) in reader])
5,549
38.928058
92
py
models
models-master/research/object_detection/model_lib_v2.py
# Copyright 2019 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. # ============================================================================== r"""Constructs model, inputs, and training environment.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import copy import os import pprint import time import numpy as np import tensorflow.compat.v1 as tf from object_detection import eval_util from object_detection import inputs from object_detection import model_lib from object_detection.builders import optimizer_builder from object_detection.core import standard_fields as fields from object_detection.protos import train_pb2 from object_detection.utils import config_util from object_detection.utils import label_map_util from object_detection.utils import ops from object_detection.utils import variables_helper from object_detection.utils import visualization_utils as vutils MODEL_BUILD_UTIL_MAP = model_lib.MODEL_BUILD_UTIL_MAP NUM_STEPS_PER_ITERATION = 100 LOG_EVERY = 100 RESTORE_MAP_ERROR_TEMPLATE = ( 'Since we are restoring a v2 style checkpoint' ' restore_map was expected to return a (str -> Model) mapping,' ' but we received a ({} -> {}) mapping instead.' ) def _compute_losses_and_predictions_dicts( model, features, labels, training_step=None, add_regularization_loss=True): """Computes the losses dict and predictions dict for a model on inputs. Args: model: a DetectionModel (based on Keras). features: Dictionary of feature tensors from the input dataset. Should be in the format output by `inputs.train_input` and `inputs.eval_input`. features[fields.InputDataFields.image] is a [batch_size, H, W, C] float32 tensor with preprocessed images. features[HASH_KEY] is a [batch_size] int32 tensor representing unique identifiers for the images. features[fields.InputDataFields.true_image_shape] is a [batch_size, 3] int32 tensor representing the true image shapes, as preprocessed images could be padded. features[fields.InputDataFields.original_image] (optional) is a [batch_size, H, W, C] float32 tensor with original images. labels: A dictionary of groundtruth tensors post-unstacking. The original labels are of the form returned by `inputs.train_input` and `inputs.eval_input`. The shapes may have been modified by unstacking with `model_lib.unstack_batch`. However, the dictionary includes the following fields. labels[fields.InputDataFields.num_groundtruth_boxes] is a int32 tensor indicating the number of valid groundtruth boxes per image. labels[fields.InputDataFields.groundtruth_boxes] is a float32 tensor containing the corners of the groundtruth boxes. labels[fields.InputDataFields.groundtruth_classes] is a float32 one-hot tensor of classes. labels[fields.InputDataFields.groundtruth_weights] is a float32 tensor containing groundtruth weights for the boxes. -- Optional -- labels[fields.InputDataFields.groundtruth_instance_masks] is a float32 tensor containing only binary values, which represent instance masks for objects. labels[fields.InputDataFields.groundtruth_instance_mask_weights] is a float32 tensor containing weights for the instance masks. labels[fields.InputDataFields.groundtruth_keypoints] is a float32 tensor containing keypoints for each box. labels[fields.InputDataFields.groundtruth_dp_num_points] is an int32 tensor with the number of sampled DensePose points per object. labels[fields.InputDataFields.groundtruth_dp_part_ids] is an int32 tensor with the DensePose part ids (0-indexed) per object. labels[fields.InputDataFields.groundtruth_dp_surface_coords] is a float32 tensor with the DensePose surface coordinates. labels[fields.InputDataFields.groundtruth_group_of] is a tf.bool tensor containing group_of annotations. labels[fields.InputDataFields.groundtruth_labeled_classes] is a float32 k-hot tensor of classes. labels[fields.InputDataFields.groundtruth_track_ids] is a int32 tensor of track IDs. labels[fields.InputDataFields.groundtruth_keypoint_depths] is a float32 tensor containing keypoint depths information. labels[fields.InputDataFields.groundtruth_keypoint_depth_weights] is a float32 tensor containing the weights of the keypoint depth feature. training_step: int, the current training step. add_regularization_loss: Whether or not to include the model's regularization loss in the losses dictionary. Returns: A tuple containing the losses dictionary (with the total loss under the key 'Loss/total_loss'), and the predictions dictionary produced by `model.predict`. """ model_lib.provide_groundtruth(model, labels, training_step=training_step) preprocessed_images = features[fields.InputDataFields.image] prediction_dict = model.predict( preprocessed_images, features[fields.InputDataFields.true_image_shape], **model.get_side_inputs(features)) prediction_dict = ops.bfloat16_to_float32_nested(prediction_dict) losses_dict = model.loss( prediction_dict, features[fields.InputDataFields.true_image_shape]) losses = [loss_tensor for loss_tensor in losses_dict.values()] if add_regularization_loss: # TODO(kaftan): As we figure out mixed precision & bfloat 16, we may ## need to convert these regularization losses from bfloat16 to float32 ## as well. regularization_losses = model.regularization_losses() if regularization_losses: regularization_losses = ops.bfloat16_to_float32_nested( regularization_losses) regularization_loss = tf.add_n( regularization_losses, name='regularization_loss') losses.append(regularization_loss) losses_dict['Loss/regularization_loss'] = regularization_loss total_loss = tf.add_n(losses, name='total_loss') losses_dict['Loss/total_loss'] = total_loss return losses_dict, prediction_dict def _ensure_model_is_built(model, input_dataset, unpad_groundtruth_tensors): """Ensures that model variables are all built, by running on a dummy input. Args: model: A DetectionModel to be built. input_dataset: The tf.data Dataset the model is being trained on. Needed to get the shapes for the dummy loss computation. unpad_groundtruth_tensors: A parameter passed to unstack_batch. """ features, labels = iter(input_dataset).next() @tf.function def _dummy_computation_fn(features, labels): model._is_training = False # pylint: disable=protected-access tf.keras.backend.set_learning_phase(False) labels = model_lib.unstack_batch( labels, unpad_groundtruth_tensors=unpad_groundtruth_tensors) return _compute_losses_and_predictions_dicts(model, features, labels, training_step=0) strategy = tf.compat.v2.distribute.get_strategy() if hasattr(tf.distribute.Strategy, 'run'): strategy.run( _dummy_computation_fn, args=( features, labels, )) else: strategy.experimental_run_v2( _dummy_computation_fn, args=( features, labels, )) def normalize_dict(values_dict, num_replicas): num_replicas = tf.constant(num_replicas, dtype=tf.float32) return {key: tf.math.divide(loss, num_replicas) for key, loss in values_dict.items()} def reduce_dict(strategy, reduction_dict, reduction_op): # TODO(anjalisridhar): explore if it is safe to remove the # num_replicas # scaling of the loss and switch this to a ReduceOp.Mean return { name: strategy.reduce(reduction_op, loss, axis=None) for name, loss in reduction_dict.items() } # TODO(kaftan): Explore removing learning_rate from this method & returning ## The full losses dict instead of just total_loss, then doing all summaries ## saving in a utility method called by the outer training loop. # TODO(kaftan): Explore adding gradient summaries def eager_train_step(detection_model, features, labels, unpad_groundtruth_tensors, optimizer, training_step, add_regularization_loss=True, clip_gradients_value=None, num_replicas=1.0): """Process a single training batch. This method computes the loss for the model on a single training batch, while tracking the gradients with a gradient tape. It then updates the model variables with the optimizer, clipping the gradients if clip_gradients_value is present. This method can run eagerly or inside a tf.function. Args: detection_model: A DetectionModel (based on Keras) to train. features: Dictionary of feature tensors from the input dataset. Should be in the format output by `inputs.train_input. features[fields.InputDataFields.image] is a [batch_size, H, W, C] float32 tensor with preprocessed images. features[HASH_KEY] is a [batch_size] int32 tensor representing unique identifiers for the images. features[fields.InputDataFields.true_image_shape] is a [batch_size, 3] int32 tensor representing the true image shapes, as preprocessed images could be padded. features[fields.InputDataFields.original_image] (optional, not used during training) is a [batch_size, H, W, C] float32 tensor with original images. labels: A dictionary of groundtruth tensors. This method unstacks these labels using model_lib.unstack_batch. The stacked labels are of the form returned by `inputs.train_input` and `inputs.eval_input`. labels[fields.InputDataFields.num_groundtruth_boxes] is a [batch_size] int32 tensor indicating the number of valid groundtruth boxes per image. labels[fields.InputDataFields.groundtruth_boxes] is a [batch_size, num_boxes, 4] float32 tensor containing the corners of the groundtruth boxes. labels[fields.InputDataFields.groundtruth_classes] is a [batch_size, num_boxes, num_classes] float32 one-hot tensor of classes. num_classes includes the background class. labels[fields.InputDataFields.groundtruth_weights] is a [batch_size, num_boxes] float32 tensor containing groundtruth weights for the boxes. -- Optional -- labels[fields.InputDataFields.groundtruth_instance_masks] is a [batch_size, num_boxes, H, W] float32 tensor containing only binary values, which represent instance masks for objects. labels[fields.InputDataFields.groundtruth_instance_mask_weights] is a [batch_size, num_boxes] float32 tensor containing weights for the instance masks. labels[fields.InputDataFields.groundtruth_keypoints] is a [batch_size, num_boxes, num_keypoints, 2] float32 tensor containing keypoints for each box. labels[fields.InputDataFields.groundtruth_dp_num_points] is a [batch_size, num_boxes] int32 tensor with the number of DensePose sampled points per instance. labels[fields.InputDataFields.groundtruth_dp_part_ids] is a [batch_size, num_boxes, max_sampled_points] int32 tensor with the part ids (0-indexed) for each instance. labels[fields.InputDataFields.groundtruth_dp_surface_coords] is a [batch_size, num_boxes, max_sampled_points, 4] float32 tensor with the surface coordinates for each point. Each surface coordinate is of the form (y, x, v, u) where (y, x) are normalized image locations and (v, u) are part-relative normalized surface coordinates. labels[fields.InputDataFields.groundtruth_labeled_classes] is a float32 k-hot tensor of classes. labels[fields.InputDataFields.groundtruth_track_ids] is a int32 tensor of track IDs. labels[fields.InputDataFields.groundtruth_keypoint_depths] is a float32 tensor containing keypoint depths information. labels[fields.InputDataFields.groundtruth_keypoint_depth_weights] is a float32 tensor containing the weights of the keypoint depth feature. unpad_groundtruth_tensors: A parameter passed to unstack_batch. optimizer: The training optimizer that will update the variables. training_step: int, the training step number. add_regularization_loss: Whether or not to include the model's regularization loss in the losses dictionary. clip_gradients_value: If this is present, clip the gradients global norm at this value using `tf.clip_by_global_norm`. num_replicas: The number of replicas in the current distribution strategy. This is used to scale the total loss so that training in a distribution strategy works correctly. Returns: The total loss observed at this training step """ # """Execute a single training step in the TF v2 style loop.""" is_training = True detection_model._is_training = is_training # pylint: disable=protected-access tf.keras.backend.set_learning_phase(is_training) labels = model_lib.unstack_batch( labels, unpad_groundtruth_tensors=unpad_groundtruth_tensors) with tf.GradientTape() as tape: losses_dict, _ = _compute_losses_and_predictions_dicts( detection_model, features, labels, training_step=training_step, add_regularization_loss=add_regularization_loss) losses_dict = normalize_dict(losses_dict, num_replicas) trainable_variables = detection_model.trainable_variables total_loss = losses_dict['Loss/total_loss'] gradients = tape.gradient(total_loss, trainable_variables) if clip_gradients_value: gradients, _ = tf.clip_by_global_norm(gradients, clip_gradients_value) optimizer.apply_gradients(zip(gradients, trainable_variables)) return losses_dict def validate_tf_v2_checkpoint_restore_map(checkpoint_restore_map): """Ensure that given dict is a valid TF v2 style restore map. Args: checkpoint_restore_map: A nested dict mapping strings to tf.keras.Model objects. Raises: ValueError: If they keys in checkpoint_restore_map are not strings or if the values are not keras Model objects. """ for key, value in checkpoint_restore_map.items(): if not (isinstance(key, str) and (isinstance(value, tf.Module) or isinstance(value, tf.train.Checkpoint))): if isinstance(key, str) and isinstance(value, dict): validate_tf_v2_checkpoint_restore_map(value) else: raise TypeError( RESTORE_MAP_ERROR_TEMPLATE.format(key.__class__.__name__, value.__class__.__name__)) def is_object_based_checkpoint(checkpoint_path): """Returns true if `checkpoint_path` points to an object-based checkpoint.""" var_names = [var[0] for var in tf.train.list_variables(checkpoint_path)] return '_CHECKPOINTABLE_OBJECT_GRAPH' in var_names def load_fine_tune_checkpoint(model, checkpoint_path, checkpoint_type, checkpoint_version, run_model_on_dummy_input, input_dataset, unpad_groundtruth_tensors): """Load a fine tuning classification or detection checkpoint. To make sure the model variables are all built, this method first executes the model by computing a dummy loss. (Models might not have built their variables before their first execution) It then loads an object-based classification or detection checkpoint. This method updates the model in-place and does not return a value. Args: model: A DetectionModel (based on Keras) to load a fine-tuning checkpoint for. checkpoint_path: Directory with checkpoints file or path to checkpoint. checkpoint_type: Whether to restore from a full detection checkpoint (with compatible variable names) or to restore from a classification checkpoint for initialization prior to training. Valid values: `detection`, `classification`. checkpoint_version: train_pb2.CheckpointVersion.V1 or V2 enum indicating whether to load checkpoints in V1 style or V2 style. In this binary we only support V2 style (object-based) checkpoints. run_model_on_dummy_input: Whether to run the model on a dummy input in order to ensure that all model variables have been built successfully before loading the fine_tune_checkpoint. input_dataset: The tf.data Dataset the model is being trained on. Needed to get the shapes for the dummy loss computation. unpad_groundtruth_tensors: A parameter passed to unstack_batch. Raises: IOError: if `checkpoint_path` does not point at a valid object-based checkpoint ValueError: if `checkpoint_version` is not train_pb2.CheckpointVersion.V2 """ if not is_object_based_checkpoint(checkpoint_path): raise IOError('Checkpoint is expected to be an object-based checkpoint.') if checkpoint_version == train_pb2.CheckpointVersion.V1: raise ValueError('Checkpoint version should be V2') if run_model_on_dummy_input: _ensure_model_is_built(model, input_dataset, unpad_groundtruth_tensors) restore_from_objects_dict = model.restore_from_objects( fine_tune_checkpoint_type=checkpoint_type) validate_tf_v2_checkpoint_restore_map(restore_from_objects_dict) ckpt = tf.train.Checkpoint(**restore_from_objects_dict) ckpt.restore( checkpoint_path).expect_partial().assert_existing_objects_matched() def get_filepath(strategy, filepath): """Get appropriate filepath for worker. Args: strategy: A tf.distribute.Strategy object. filepath: A path to where the Checkpoint object is stored. Returns: A temporary filepath for non-chief workers to use or the original filepath for the chief. """ if strategy.extended.should_checkpoint: return filepath else: # TODO(vighneshb) Replace with the public API when TF exposes it. task_id = strategy.extended._task_id # pylint:disable=protected-access return os.path.join(filepath, 'temp_worker_{:03d}'.format(task_id)) def clean_temporary_directories(strategy, filepath): """Temporary directory clean up for MultiWorker Mirrored Strategy. This is needed for all non-chief workers. Args: strategy: A tf.distribute.Strategy object. filepath: The filepath for the temporary directory. """ if not strategy.extended.should_checkpoint: if tf.io.gfile.exists(filepath) and tf.io.gfile.isdir(filepath): tf.io.gfile.rmtree(filepath) def train_loop( pipeline_config_path, model_dir, config_override=None, train_steps=None, use_tpu=False, save_final_config=False, checkpoint_every_n=1000, checkpoint_max_to_keep=7, record_summaries=True, performance_summary_exporter=None, num_steps_per_iteration=NUM_STEPS_PER_ITERATION, **kwargs): """Trains a model using eager + functions. This method: 1. Processes the pipeline configs 2. (Optionally) saves the as-run config 3. Builds the model & optimizer 4. Gets the training input data 5. Loads a fine-tuning detection or classification checkpoint if requested 6. Loops over the train data, executing distributed training steps inside tf.functions. 7. Checkpoints the model every `checkpoint_every_n` training steps. 8. Logs the training metrics as TensorBoard summaries. Args: pipeline_config_path: A path to a pipeline config file. model_dir: The directory to save checkpoints and summaries to. config_override: A pipeline_pb2.TrainEvalPipelineConfig text proto to override the config from `pipeline_config_path`. train_steps: Number of training steps. If None, the number of training steps is set from the `TrainConfig` proto. use_tpu: Boolean, whether training and evaluation should run on TPU. save_final_config: Whether to save final config (obtained after applying overrides) to `model_dir`. checkpoint_every_n: Checkpoint every n training steps. checkpoint_max_to_keep: int, the number of most recent checkpoints to keep in the model directory. record_summaries: Boolean, whether or not to record summaries defined by the model or the training pipeline. This does not impact the summaries of the loss values which are always recorded. Examples of summaries that are controlled by this flag include: - Image summaries of training images. - Intermediate tensors which maybe logged by meta architectures. performance_summary_exporter: function for exporting performance metrics. num_steps_per_iteration: int, The number of training steps to perform in each iteration. **kwargs: Additional keyword arguments for configuration override. """ ## Parse the configs get_configs_from_pipeline_file = MODEL_BUILD_UTIL_MAP[ 'get_configs_from_pipeline_file'] merge_external_params_with_configs = MODEL_BUILD_UTIL_MAP[ 'merge_external_params_with_configs'] create_pipeline_proto_from_configs = MODEL_BUILD_UTIL_MAP[ 'create_pipeline_proto_from_configs'] steps_per_sec_list = [] configs = get_configs_from_pipeline_file( pipeline_config_path, config_override=config_override) kwargs.update({ 'train_steps': train_steps, 'use_bfloat16': configs['train_config'].use_bfloat16 and use_tpu }) configs = merge_external_params_with_configs( configs, None, kwargs_dict=kwargs) model_config = configs['model'] train_config = configs['train_config'] train_input_config = configs['train_input_config'] unpad_groundtruth_tensors = train_config.unpad_groundtruth_tensors add_regularization_loss = train_config.add_regularization_loss clip_gradients_value = None if train_config.gradient_clipping_by_norm > 0: clip_gradients_value = train_config.gradient_clipping_by_norm # update train_steps from config but only when non-zero value is provided if train_steps is None and train_config.num_steps != 0: train_steps = train_config.num_steps if kwargs['use_bfloat16']: tf.compat.v2.keras.mixed_precision.set_global_policy('mixed_bfloat16') if train_config.load_all_detection_checkpoint_vars: raise ValueError('train_pb2.load_all_detection_checkpoint_vars ' 'unsupported in TF2') config_util.update_fine_tune_checkpoint_type(train_config) fine_tune_checkpoint_type = train_config.fine_tune_checkpoint_type fine_tune_checkpoint_version = train_config.fine_tune_checkpoint_version # Write the as-run pipeline config to disk. if save_final_config: tf.logging.info('Saving pipeline config file to directory %s', model_dir) pipeline_config_final = create_pipeline_proto_from_configs(configs) config_util.save_pipeline_config(pipeline_config_final, model_dir) # Build the model, optimizer, and training input strategy = tf.compat.v2.distribute.get_strategy() with strategy.scope(): detection_model = MODEL_BUILD_UTIL_MAP['detection_model_fn_base']( model_config=model_config, is_training=True, add_summaries=record_summaries) def train_dataset_fn(input_context): """Callable to create train input.""" # Create the inputs. train_input = inputs.train_input( train_config=train_config, train_input_config=train_input_config, model_config=model_config, model=detection_model, input_context=input_context) train_input = train_input.repeat() return train_input train_input = strategy.experimental_distribute_datasets_from_function( train_dataset_fn) global_step = tf.Variable( 0, trainable=False, dtype=tf.compat.v2.dtypes.int64, name='global_step', aggregation=tf.compat.v2.VariableAggregation.ONLY_FIRST_REPLICA) optimizer, (learning_rate,) = optimizer_builder.build( train_config.optimizer, global_step=global_step) # We run the detection_model on dummy inputs in order to ensure that the # model and all its variables have been properly constructed. Specifically, # this is currently necessary prior to (potentially) creating shadow copies # of the model variables for the EMA optimizer. if train_config.optimizer.use_moving_average: _ensure_model_is_built(detection_model, train_input, unpad_groundtruth_tensors) optimizer.shadow_copy(detection_model) if callable(learning_rate): learning_rate_fn = learning_rate else: learning_rate_fn = lambda: learning_rate ## Train the model # Get the appropriate filepath (temporary or not) based on whether the worker # is the chief. summary_writer_filepath = get_filepath(strategy, os.path.join(model_dir, 'train')) summary_writer = tf.compat.v2.summary.create_file_writer( summary_writer_filepath) with summary_writer.as_default(): with strategy.scope(): with tf.compat.v2.summary.record_if( lambda: global_step % num_steps_per_iteration == 0): # Load a fine-tuning checkpoint. if train_config.fine_tune_checkpoint: variables_helper.ensure_checkpoint_supported( train_config.fine_tune_checkpoint, fine_tune_checkpoint_type, model_dir) load_fine_tune_checkpoint( detection_model, train_config.fine_tune_checkpoint, fine_tune_checkpoint_type, fine_tune_checkpoint_version, train_config.run_fine_tune_checkpoint_dummy_computation, train_input, unpad_groundtruth_tensors) ckpt = tf.compat.v2.train.Checkpoint( step=global_step, model=detection_model, optimizer=optimizer) manager_dir = get_filepath(strategy, model_dir) if not strategy.extended.should_checkpoint: checkpoint_max_to_keep = 1 manager = tf.compat.v2.train.CheckpointManager( ckpt, manager_dir, max_to_keep=checkpoint_max_to_keep) # We use the following instead of manager.latest_checkpoint because # manager_dir does not point to the model directory when we are running # in a worker. latest_checkpoint = tf.train.latest_checkpoint(model_dir) ckpt.restore(latest_checkpoint) def train_step_fn(features, labels): """Single train step.""" if record_summaries: tf.compat.v2.summary.image( name='train_input_images', step=global_step, data=features[fields.InputDataFields.image], max_outputs=3) losses_dict = eager_train_step( detection_model, features, labels, unpad_groundtruth_tensors, optimizer, training_step=global_step, add_regularization_loss=add_regularization_loss, clip_gradients_value=clip_gradients_value, num_replicas=strategy.num_replicas_in_sync) global_step.assign_add(1) return losses_dict def _sample_and_train(strategy, train_step_fn, data_iterator): features, labels = data_iterator.next() if hasattr(tf.distribute.Strategy, 'run'): per_replica_losses_dict = strategy.run( train_step_fn, args=(features, labels)) else: per_replica_losses_dict = ( strategy.experimental_run_v2( train_step_fn, args=(features, labels))) return reduce_dict( strategy, per_replica_losses_dict, tf.distribute.ReduceOp.SUM) @tf.function def _dist_train_step(data_iterator): """A distributed train step.""" if num_steps_per_iteration > 1: for _ in tf.range(num_steps_per_iteration - 1): # Following suggestion on yaqs/5402607292645376 with tf.name_scope(''): _sample_and_train(strategy, train_step_fn, data_iterator) return _sample_and_train(strategy, train_step_fn, data_iterator) train_input_iter = iter(train_input) if int(global_step.value()) == 0: manager.save() checkpointed_step = int(global_step.value()) logged_step = global_step.value() last_step_time = time.time() for _ in range(global_step.value(), train_steps, num_steps_per_iteration): losses_dict = _dist_train_step(train_input_iter) time_taken = time.time() - last_step_time last_step_time = time.time() steps_per_sec = num_steps_per_iteration * 1.0 / time_taken tf.compat.v2.summary.scalar( 'steps_per_sec', steps_per_sec, step=global_step) steps_per_sec_list.append(steps_per_sec) logged_dict = losses_dict.copy() logged_dict['learning_rate'] = learning_rate_fn() for key, val in logged_dict.items(): tf.compat.v2.summary.scalar(key, val, step=global_step) if global_step.value() - logged_step >= LOG_EVERY: logged_dict_np = {name: value.numpy() for name, value in logged_dict.items()} tf.logging.info( 'Step {} per-step time {:.3f}s'.format( global_step.value(), time_taken / num_steps_per_iteration)) tf.logging.info(pprint.pformat(logged_dict_np, width=40)) logged_step = global_step.value() if ((int(global_step.value()) - checkpointed_step) >= checkpoint_every_n): manager.save() checkpointed_step = int(global_step.value()) # Remove the checkpoint directories of the non-chief workers that # MultiWorkerMirroredStrategy forces us to save during sync distributed # training. clean_temporary_directories(strategy, manager_dir) clean_temporary_directories(strategy, summary_writer_filepath) # TODO(pkanwar): add accuracy metrics. if performance_summary_exporter is not None: metrics = { 'steps_per_sec': np.mean(steps_per_sec_list), 'steps_per_sec_p50': np.median(steps_per_sec_list), 'steps_per_sec_max': max(steps_per_sec_list), 'last_batch_loss': float(losses_dict['Loss/total_loss']) } mixed_precision = 'bf16' if kwargs['use_bfloat16'] else 'fp32' performance_summary_exporter(metrics, mixed_precision) def prepare_eval_dict(detections, groundtruth, features): """Prepares eval dictionary containing detections and groundtruth. Takes in `detections` from the model, `groundtruth` and `features` returned from the eval tf.data.dataset and creates a dictionary of tensors suitable for detection eval modules. Args: detections: A dictionary of tensors returned by `model.postprocess`. groundtruth: `inputs.eval_input` returns an eval dataset of (features, labels) tuple. `groundtruth` must be set to `labels`. Please note that: * fields.InputDataFields.groundtruth_classes must be 0-indexed and in its 1-hot representation. * fields.InputDataFields.groundtruth_verified_neg_classes must be 0-indexed and in its multi-hot repesentation. * fields.InputDataFields.groundtruth_not_exhaustive_classes must be 0-indexed and in its multi-hot repesentation. * fields.InputDataFields.groundtruth_labeled_classes must be 0-indexed and in its multi-hot repesentation. features: `inputs.eval_input` returns an eval dataset of (features, labels) tuple. This argument must be set to a dictionary containing the following keys and their corresponding values from `features` -- * fields.InputDataFields.image * fields.InputDataFields.original_image * fields.InputDataFields.original_image_spatial_shape * fields.InputDataFields.true_image_shape * inputs.HASH_KEY Returns: eval_dict: A dictionary of tensors to pass to eval module. class_agnostic: Whether to evaluate detection in class agnostic mode. """ groundtruth_boxes = groundtruth[fields.InputDataFields.groundtruth_boxes] groundtruth_boxes_shape = tf.shape(groundtruth_boxes) # For class-agnostic models, groundtruth one-hot encodings collapse to all # ones. class_agnostic = ( fields.DetectionResultFields.detection_classes not in detections) if class_agnostic: groundtruth_classes_one_hot = tf.ones( [groundtruth_boxes_shape[0], groundtruth_boxes_shape[1], 1]) else: groundtruth_classes_one_hot = groundtruth[ fields.InputDataFields.groundtruth_classes] label_id_offset = 1 # Applying label id offset (b/63711816) groundtruth_classes = ( tf.argmax(groundtruth_classes_one_hot, axis=2) + label_id_offset) groundtruth[fields.InputDataFields.groundtruth_classes] = groundtruth_classes label_id_offset_paddings = tf.constant([[0, 0], [1, 0]]) if fields.InputDataFields.groundtruth_verified_neg_classes in groundtruth: groundtruth[ fields.InputDataFields.groundtruth_verified_neg_classes] = tf.pad( groundtruth[ fields.InputDataFields.groundtruth_verified_neg_classes], label_id_offset_paddings) if fields.InputDataFields.groundtruth_not_exhaustive_classes in groundtruth: groundtruth[ fields.InputDataFields.groundtruth_not_exhaustive_classes] = tf.pad( groundtruth[ fields.InputDataFields.groundtruth_not_exhaustive_classes], label_id_offset_paddings) if fields.InputDataFields.groundtruth_labeled_classes in groundtruth: groundtruth[fields.InputDataFields.groundtruth_labeled_classes] = tf.pad( groundtruth[fields.InputDataFields.groundtruth_labeled_classes], label_id_offset_paddings) use_original_images = fields.InputDataFields.original_image in features if use_original_images: eval_images = features[fields.InputDataFields.original_image] true_image_shapes = features[fields.InputDataFields.true_image_shape][:, :3] original_image_spatial_shapes = features[ fields.InputDataFields.original_image_spatial_shape] else: eval_images = features[fields.InputDataFields.image] true_image_shapes = None original_image_spatial_shapes = None eval_dict = eval_util.result_dict_for_batched_example( eval_images, features[inputs.HASH_KEY], detections, groundtruth, class_agnostic=class_agnostic, scale_to_absolute=True, original_image_spatial_shapes=original_image_spatial_shapes, true_image_shapes=true_image_shapes) return eval_dict, class_agnostic def concat_replica_results(tensor_dict): new_tensor_dict = {} for key, values in tensor_dict.items(): new_tensor_dict[key] = tf.concat(values, axis=0) return new_tensor_dict def eager_eval_loop( detection_model, configs, eval_dataset, use_tpu=False, postprocess_on_cpu=False, global_step=None, ): """Evaluate the model eagerly on the evaluation dataset. This method will compute the evaluation metrics specified in the configs on the entire evaluation dataset, then return the metrics. It will also log the metrics to TensorBoard. Args: detection_model: A DetectionModel (based on Keras) to evaluate. configs: Object detection configs that specify the evaluators that should be used, as well as whether regularization loss should be included and if bfloat16 should be used on TPUs. eval_dataset: Dataset containing evaluation data. use_tpu: Whether a TPU is being used to execute the model for evaluation. postprocess_on_cpu: Whether model postprocessing should happen on the CPU when using a TPU to execute the model. global_step: A variable containing the training step this model was trained to. Used for logging purposes. Returns: A dict of evaluation metrics representing the results of this evaluation. """ del postprocess_on_cpu train_config = configs['train_config'] eval_input_config = configs['eval_input_config'] eval_config = configs['eval_config'] add_regularization_loss = train_config.add_regularization_loss is_training = False detection_model._is_training = is_training # pylint: disable=protected-access tf.keras.backend.set_learning_phase(is_training) evaluator_options = eval_util.evaluator_options_from_eval_config( eval_config) batch_size = eval_config.batch_size class_agnostic_category_index = ( label_map_util.create_class_agnostic_category_index()) class_agnostic_evaluators = eval_util.get_evaluators( eval_config, list(class_agnostic_category_index.values()), evaluator_options) class_aware_evaluators = None if eval_input_config.label_map_path: class_aware_category_index = ( label_map_util.create_category_index_from_labelmap( eval_input_config.label_map_path)) class_aware_evaluators = eval_util.get_evaluators( eval_config, list(class_aware_category_index.values()), evaluator_options) evaluators = None loss_metrics = {} @tf.function def compute_eval_dict(features, labels): """Compute the evaluation result on an image.""" # For evaling on train data, it is necessary to check whether groundtruth # must be unpadded. boxes_shape = ( labels[fields.InputDataFields.groundtruth_boxes].get_shape().as_list()) unpad_groundtruth_tensors = (boxes_shape[1] is not None and not use_tpu and batch_size == 1) groundtruth_dict = labels labels = model_lib.unstack_batch( labels, unpad_groundtruth_tensors=unpad_groundtruth_tensors) losses_dict, prediction_dict = _compute_losses_and_predictions_dicts( detection_model, features, labels, training_step=None, add_regularization_loss=add_regularization_loss) prediction_dict = detection_model.postprocess( prediction_dict, features[fields.InputDataFields.true_image_shape]) eval_features = { fields.InputDataFields.image: features[fields.InputDataFields.image], fields.InputDataFields.original_image: features[fields.InputDataFields.original_image], fields.InputDataFields.original_image_spatial_shape: features[fields.InputDataFields.original_image_spatial_shape], fields.InputDataFields.true_image_shape: features[fields.InputDataFields.true_image_shape], inputs.HASH_KEY: features[inputs.HASH_KEY], } return losses_dict, prediction_dict, groundtruth_dict, eval_features agnostic_categories = label_map_util.create_class_agnostic_category_index() per_class_categories = label_map_util.create_category_index_from_labelmap( eval_input_config.label_map_path) keypoint_edges = [ (kp.start, kp.end) for kp in eval_config.keypoint_edge] strategy = tf.compat.v2.distribute.get_strategy() for i, (features, labels) in enumerate(eval_dataset): try: (losses_dict, prediction_dict, groundtruth_dict, eval_features) = strategy.run( compute_eval_dict, args=(features, labels)) except Exception as exc: # pylint:disable=broad-except tf.logging.info('Encountered %s exception.', exc) tf.logging.info('A replica probably exhausted all examples. Skipping ' 'pending examples on other replicas.') break (local_prediction_dict, local_groundtruth_dict, local_eval_features) = tf.nest.map_structure( strategy.experimental_local_results, [prediction_dict, groundtruth_dict, eval_features]) local_prediction_dict = concat_replica_results(local_prediction_dict) local_groundtruth_dict = concat_replica_results(local_groundtruth_dict) local_eval_features = concat_replica_results(local_eval_features) eval_dict, class_agnostic = prepare_eval_dict(local_prediction_dict, local_groundtruth_dict, local_eval_features) for loss_key, loss_tensor in iter(losses_dict.items()): losses_dict[loss_key] = strategy.reduce(tf.distribute.ReduceOp.MEAN, loss_tensor, None) if class_agnostic: category_index = agnostic_categories else: category_index = per_class_categories if i % 100 == 0: tf.logging.info('Finished eval step %d', i) use_original_images = fields.InputDataFields.original_image in features if (use_original_images and i < eval_config.num_visualizations): sbys_image_list = vutils.draw_side_by_side_evaluation_image( eval_dict, category_index=category_index, max_boxes_to_draw=eval_config.max_num_boxes_to_visualize, min_score_thresh=eval_config.min_score_threshold, use_normalized_coordinates=False, keypoint_edges=keypoint_edges or None) for j, sbys_image in enumerate(sbys_image_list): tf.compat.v2.summary.image( name='eval_side_by_side_{}_{}'.format(i, j), step=global_step, data=sbys_image, max_outputs=eval_config.num_visualizations) if eval_util.has_densepose(eval_dict): dp_image_list = vutils.draw_densepose_visualizations( eval_dict) for j, dp_image in enumerate(dp_image_list): tf.compat.v2.summary.image( name='densepose_detections_{}_{}'.format(i, j), step=global_step, data=dp_image, max_outputs=eval_config.num_visualizations) if evaluators is None: if class_agnostic: evaluators = class_agnostic_evaluators else: evaluators = class_aware_evaluators for evaluator in evaluators: evaluator.add_eval_dict(eval_dict) for loss_key, loss_tensor in iter(losses_dict.items()): if loss_key not in loss_metrics: loss_metrics[loss_key] = [] loss_metrics[loss_key].append(loss_tensor) eval_metrics = {} for evaluator in evaluators: eval_metrics.update(evaluator.evaluate()) for loss_key in loss_metrics: eval_metrics[loss_key] = tf.reduce_mean(loss_metrics[loss_key]) eval_metrics = {str(k): v for k, v in eval_metrics.items()} tf.logging.info('Eval metrics at step %d', global_step.numpy()) for k in eval_metrics: tf.compat.v2.summary.scalar(k, eval_metrics[k], step=global_step) tf.logging.info('\t+ %s: %f', k, eval_metrics[k]) return eval_metrics def eval_continuously( pipeline_config_path, config_override=None, train_steps=None, sample_1_of_n_eval_examples=1, sample_1_of_n_eval_on_train_examples=1, use_tpu=False, override_eval_num_epochs=True, postprocess_on_cpu=False, model_dir=None, checkpoint_dir=None, wait_interval=180, timeout=3600, eval_index=0, save_final_config=False, **kwargs): """Run continuous evaluation of a detection model eagerly. This method builds the model, and continously restores it from the most recent training checkpoint in the checkpoint directory & evaluates it on the evaluation data. Args: pipeline_config_path: A path to a pipeline config file. config_override: A pipeline_pb2.TrainEvalPipelineConfig text proto to override the config from `pipeline_config_path`. train_steps: Number of training steps. If None, the number of training steps is set from the `TrainConfig` proto. sample_1_of_n_eval_examples: Integer representing how often an eval example should be sampled. If 1, will sample all examples. sample_1_of_n_eval_on_train_examples: Similar to `sample_1_of_n_eval_examples`, except controls the sampling of training data for evaluation. use_tpu: Boolean, whether training and evaluation should run on TPU. override_eval_num_epochs: Whether to overwrite the number of epochs to 1 for eval_input. postprocess_on_cpu: When use_tpu and postprocess_on_cpu are true, postprocess is scheduled on the host cpu. model_dir: Directory to output resulting evaluation summaries to. checkpoint_dir: Directory that contains the training checkpoints. wait_interval: The mimmum number of seconds to wait before checking for a new checkpoint. timeout: The maximum number of seconds to wait for a checkpoint. Execution will terminate if no new checkpoints are found after these many seconds. eval_index: int, If given, only evaluate the dataset at the given index. By default, evaluates dataset at 0'th index. save_final_config: Whether to save the pipeline config file to the model directory. **kwargs: Additional keyword arguments for configuration override. """ get_configs_from_pipeline_file = MODEL_BUILD_UTIL_MAP[ 'get_configs_from_pipeline_file'] create_pipeline_proto_from_configs = MODEL_BUILD_UTIL_MAP[ 'create_pipeline_proto_from_configs'] merge_external_params_with_configs = MODEL_BUILD_UTIL_MAP[ 'merge_external_params_with_configs'] configs = get_configs_from_pipeline_file( pipeline_config_path, config_override=config_override) kwargs.update({ 'sample_1_of_n_eval_examples': sample_1_of_n_eval_examples, 'use_bfloat16': configs['train_config'].use_bfloat16 and use_tpu }) if train_steps is not None: kwargs['train_steps'] = train_steps if override_eval_num_epochs: kwargs.update({'eval_num_epochs': 1}) tf.logging.warning( 'Forced number of epochs for all eval validations to be 1.') configs = merge_external_params_with_configs( configs, None, kwargs_dict=kwargs) if model_dir and save_final_config: tf.logging.info('Saving pipeline config file to directory %s', model_dir) pipeline_config_final = create_pipeline_proto_from_configs(configs) config_util.save_pipeline_config(pipeline_config_final, model_dir) model_config = configs['model'] train_input_config = configs['train_input_config'] eval_config = configs['eval_config'] eval_input_configs = configs['eval_input_configs'] eval_on_train_input_config = copy.deepcopy(train_input_config) eval_on_train_input_config.sample_1_of_n_examples = ( sample_1_of_n_eval_on_train_examples) if override_eval_num_epochs and eval_on_train_input_config.num_epochs != 1: tf.logging.warning( ('Expected number of evaluation epochs is 1, but ' 'instead encountered `eval_on_train_input_config' '.num_epochs` = %d. Overwriting `num_epochs` to 1.'), eval_on_train_input_config.num_epochs) eval_on_train_input_config.num_epochs = 1 if kwargs['use_bfloat16']: tf.compat.v2.keras.mixed_precision.set_global_policy('mixed_bfloat16') eval_input_config = eval_input_configs[eval_index] strategy = tf.compat.v2.distribute.get_strategy() with strategy.scope(): detection_model = MODEL_BUILD_UTIL_MAP['detection_model_fn_base']( model_config=model_config, is_training=True) eval_input = strategy.experimental_distribute_dataset( inputs.eval_input( eval_config=eval_config, eval_input_config=eval_input_config, model_config=model_config, model=detection_model)) global_step = tf.compat.v2.Variable( 0, trainable=False, dtype=tf.compat.v2.dtypes.int64) optimizer, _ = optimizer_builder.build( configs['train_config'].optimizer, global_step=global_step) for latest_checkpoint in tf.train.checkpoints_iterator( checkpoint_dir, timeout=timeout, min_interval_secs=wait_interval): ckpt = tf.compat.v2.train.Checkpoint( step=global_step, model=detection_model, optimizer=optimizer) # We run the detection_model on dummy inputs in order to ensure that the # model and all its variables have been properly constructed. Specifically, # this is currently necessary prior to (potentially) creating shadow copies # of the model variables for the EMA optimizer. if eval_config.use_moving_averages: unpad_groundtruth_tensors = (eval_config.batch_size == 1 and not use_tpu) _ensure_model_is_built(detection_model, eval_input, unpad_groundtruth_tensors) optimizer.shadow_copy(detection_model) ckpt.restore(latest_checkpoint).expect_partial() if eval_config.use_moving_averages: optimizer.swap_weights() summary_writer = tf.compat.v2.summary.create_file_writer( os.path.join(model_dir, 'eval', eval_input_config.name)) with summary_writer.as_default(): eager_eval_loop( detection_model, configs, eval_input, use_tpu=use_tpu, postprocess_on_cpu=postprocess_on_cpu, global_step=global_step, ) if global_step.numpy() == configs['train_config'].num_steps: tf.logging.info('Exiting evaluation at step %d', global_step.numpy()) return
49,989
41.726496
80
py
models
models-master/research/object_detection/model_lib_tf2_test.py
# Copyright 2017 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. # ============================================================================== """Tests for object detection model library.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import json import os import tempfile import unittest import numpy as np import six import tensorflow.compat.v1 as tf import tensorflow.compat.v2 as tf2 from object_detection import exporter_lib_v2 from object_detection import inputs from object_detection import model_lib_v2 from object_detection.core import model from object_detection.protos import train_pb2 from object_detection.utils import config_util from object_detection.utils import tf_version if six.PY2: import mock # pylint: disable=g-importing-member,g-import-not-at-top else: from unittest import mock # pylint: disable=g-importing-member,g-import-not-at-top # Model for test. Current options are: # 'ssd_mobilenet_v2_pets_keras' MODEL_NAME_FOR_TEST = 'ssd_mobilenet_v2_pets_keras' def _get_data_path(): """Returns an absolute path to TFRecord file.""" return os.path.join(tf.resource_loader.get_data_files_path(), 'test_data', 'pets_examples.record') def get_pipeline_config_path(model_name): """Returns path to the local pipeline config file.""" return os.path.join(tf.resource_loader.get_data_files_path(), 'samples', 'configs', model_name + '.config') def _get_labelmap_path(): """Returns an absolute path to label map file.""" return os.path.join(tf.resource_loader.get_data_files_path(), 'data', 'pet_label_map.pbtxt') def _get_config_kwarg_overrides(): """Returns overrides to the configs that insert the correct local paths.""" data_path = _get_data_path() label_map_path = _get_labelmap_path() return { 'train_input_path': data_path, 'eval_input_path': data_path, 'label_map_path': label_map_path, 'train_input_reader': {'batch_size': 1} } @unittest.skipIf(tf_version.is_tf1(), 'Skipping TF2.X only test.') class ModelLibTest(tf.test.TestCase): @classmethod def setUpClass(cls): # pylint:disable=g-missing-super-call tf.keras.backend.clear_session() def test_train_loop_then_eval_loop(self): """Tests that Estimator and input function are constructed correctly.""" model_dir = tf.test.get_temp_dir() pipeline_config_path = get_pipeline_config_path(MODEL_NAME_FOR_TEST) new_pipeline_config_path = os.path.join(model_dir, 'new_pipeline.config') config_util.clear_fine_tune_checkpoint(pipeline_config_path, new_pipeline_config_path) config_kwarg_overrides = _get_config_kwarg_overrides() train_steps = 2 strategy = tf2.distribute.MirroredStrategy(['/cpu:0', '/cpu:1']) with strategy.scope(): model_lib_v2.train_loop( new_pipeline_config_path, model_dir=model_dir, train_steps=train_steps, checkpoint_every_n=1, num_steps_per_iteration=1, **config_kwarg_overrides) model_lib_v2.eval_continuously( new_pipeline_config_path, model_dir=model_dir, checkpoint_dir=model_dir, train_steps=train_steps, wait_interval=1, timeout=10, **config_kwarg_overrides) class SimpleModel(model.DetectionModel): """A model with a single weight vector.""" def __init__(self, num_classes=1): super(SimpleModel, self).__init__(num_classes) self.weight = tf.keras.backend.variable(np.ones(10), name='weight') def postprocess(self, prediction_dict, true_image_shapes): return {} def updates(self): return [] def restore_map(self, *args, **kwargs): pass def restore_from_objects(self, fine_tune_checkpoint_type): return {'model': self} def preprocess(self, _): return tf.zeros((1, 128, 128, 3)), tf.constant([[128, 128, 3]]) def provide_groundtruth(self, *args, **kwargs): pass def predict(self, pred_inputs, true_image_shapes): return {'prediction': tf.abs(tf.reduce_sum(self.weight) * tf.reduce_sum(pred_inputs))} def loss(self, prediction_dict, _): return {'loss': tf.reduce_sum(prediction_dict['prediction'])} def regularization_losses(self): return [] def fake_model_builder(*_, **__): return SimpleModel() FAKE_BUILDER_MAP = {'detection_model_fn_base': fake_model_builder} @unittest.skipIf(tf_version.is_tf1(), 'Skipping TF2.X only test.') class ModelCheckpointTest(tf.test.TestCase): """Test for model checkpoint related functionality.""" def test_checkpoint_max_to_keep(self): """Test that only the most recent checkpoints are kept.""" strategy = tf2.distribute.OneDeviceStrategy(device='/cpu:0') with mock.patch.dict( model_lib_v2.MODEL_BUILD_UTIL_MAP, FAKE_BUILDER_MAP): model_dir = tempfile.mkdtemp(dir=self.get_temp_dir()) pipeline_config_path = get_pipeline_config_path(MODEL_NAME_FOR_TEST) new_pipeline_config_path = os.path.join(model_dir, 'new_pipeline.config') config_util.clear_fine_tune_checkpoint(pipeline_config_path, new_pipeline_config_path) config_kwarg_overrides = _get_config_kwarg_overrides() with strategy.scope(): model_lib_v2.train_loop( new_pipeline_config_path, model_dir=model_dir, train_steps=5, checkpoint_every_n=2, checkpoint_max_to_keep=3, num_steps_per_iteration=1, **config_kwarg_overrides ) ckpt_files = tf.io.gfile.glob(os.path.join(model_dir, 'ckpt-*.index')) self.assertEqual(len(ckpt_files), 3, '{} not of length 3.'.format(ckpt_files)) class IncompatibleModel(SimpleModel): def restore_from_objects(self, *args, **kwargs): return {'weight': self.weight} @unittest.skipIf(tf_version.is_tf1(), 'Skipping TF2.X only test.') class CheckpointV2Test(tf.test.TestCase): def setUp(self): super(CheckpointV2Test, self).setUp() self._model = SimpleModel() tf.keras.backend.set_value(self._model.weight, np.ones(10) * 42) ckpt = tf.train.Checkpoint(model=self._model) self._test_dir = tf.test.get_temp_dir() self._ckpt_path = ckpt.save(os.path.join(self._test_dir, 'ckpt')) tf.keras.backend.set_value(self._model.weight, np.ones(10)) pipeline_config_path = get_pipeline_config_path(MODEL_NAME_FOR_TEST) configs = config_util.get_configs_from_pipeline_file(pipeline_config_path) configs = config_util.merge_external_params_with_configs( configs, kwargs_dict=_get_config_kwarg_overrides()) self._train_input_fn = inputs.create_train_input_fn( configs['train_config'], configs['train_input_config'], configs['model']) def test_restore_v2(self): """Test that restoring a v2 style checkpoint works.""" model_lib_v2.load_fine_tune_checkpoint( self._model, self._ckpt_path, checkpoint_type='', checkpoint_version=train_pb2.CheckpointVersion.V2, run_model_on_dummy_input=True, input_dataset=self._train_input_fn(), unpad_groundtruth_tensors=True) np.testing.assert_allclose(self._model.weight.numpy(), 42) def test_restore_map_incompatible_error(self): """Test that restoring an incompatible restore map causes an error.""" with self.assertRaisesRegex(TypeError, r'.*received a \(str -> ResourceVariable\).*'): model_lib_v2.load_fine_tune_checkpoint( IncompatibleModel(), self._ckpt_path, checkpoint_type='', checkpoint_version=train_pb2.CheckpointVersion.V2, run_model_on_dummy_input=True, input_dataset=self._train_input_fn(), unpad_groundtruth_tensors=True) @unittest.skipIf(tf_version.is_tf1(), 'Skipping TF2.X only test.') class MetricsExportTest(tf.test.TestCase): @classmethod def setUpClass(cls): # pylint:disable=g-missing-super-call tf.keras.backend.clear_session() def test_export_metrics_json_serializable(self): """Tests that Estimator and input function are constructed correctly.""" strategy = tf2.distribute.OneDeviceStrategy(device='/cpu:0') def export(data, _): json.dumps(data) with mock.patch.dict( exporter_lib_v2.INPUT_BUILDER_UTIL_MAP, FAKE_BUILDER_MAP): with strategy.scope(): model_dir = tf.test.get_temp_dir() new_pipeline_config_path = os.path.join(model_dir, 'new_pipeline.config') pipeline_config_path = get_pipeline_config_path(MODEL_NAME_FOR_TEST) config_util.clear_fine_tune_checkpoint(pipeline_config_path, new_pipeline_config_path) train_steps = 2 with strategy.scope(): model_lib_v2.train_loop( new_pipeline_config_path, model_dir=model_dir, train_steps=train_steps, checkpoint_every_n=100, performance_summary_exporter=export, num_steps_per_iteration=1, **_get_config_kwarg_overrides()) def setUpModule(): # Setup virtual CPUs. cpus = tf.config.list_physical_devices('CPU') tf.config.set_logical_device_configuration( cpus[-1], [tf.config.LogicalDeviceConfiguration()] * 2 ) if __name__ == '__main__': tf.test.main()
9,990
34.05614
85
py