partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
train
get_policy
Get a policy network. Args: observations: observations hparams: parameters action_space: action space Returns: Tuple (action logits, value).
tensor2tensor/models/research/rl.py
def get_policy(observations, hparams, action_space): """Get a policy network. Args: observations: observations hparams: parameters action_space: action space Returns: Tuple (action logits, value). """ if not isinstance(action_space, gym.spaces.Discrete): raise ValueError("Expecting discrete action space.") obs_shape = common_layers.shape_list(observations) (frame_height, frame_width) = obs_shape[2:4] # TODO(afrozm): We have these dummy problems mainly for hparams, so cleanup # when possible and do this properly. if hparams.policy_problem_name == "dummy_policy_problem_ttt": tf.logging.info("Using DummyPolicyProblemTTT for the policy.") policy_problem = tic_tac_toe_env.DummyPolicyProblemTTT() else: tf.logging.info("Using DummyPolicyProblem for the policy.") policy_problem = DummyPolicyProblem(action_space, frame_height, frame_width) trainer_lib.add_problem_hparams(hparams, policy_problem) hparams.force_full_predict = True model = registry.model(hparams.policy_network)( hparams, tf.estimator.ModeKeys.TRAIN ) try: num_target_frames = hparams.video_num_target_frames except AttributeError: num_target_frames = 1 features = { "inputs": observations, "input_action": tf.zeros(obs_shape[:2] + [1], dtype=tf.int32), "input_reward": tf.zeros(obs_shape[:2] + [1], dtype=tf.int32), "targets": tf.zeros(obs_shape[:1] + [num_target_frames] + obs_shape[2:]), "target_action": tf.zeros( obs_shape[:1] + [num_target_frames, 1], dtype=tf.int32), "target_reward": tf.zeros( obs_shape[:1] + [num_target_frames, 1], dtype=tf.int32), "target_policy": tf.zeros( obs_shape[:1] + [num_target_frames] + [action_space.n]), "target_value": tf.zeros( obs_shape[:1] + [num_target_frames]) } with tf.variable_scope(tf.get_variable_scope(), reuse=tf.AUTO_REUSE): t2t_model.create_dummy_vars() (targets, _) = model(features) return (targets["target_policy"][:, 0, :], targets["target_value"][:, 0])
def get_policy(observations, hparams, action_space): """Get a policy network. Args: observations: observations hparams: parameters action_space: action space Returns: Tuple (action logits, value). """ if not isinstance(action_space, gym.spaces.Discrete): raise ValueError("Expecting discrete action space.") obs_shape = common_layers.shape_list(observations) (frame_height, frame_width) = obs_shape[2:4] # TODO(afrozm): We have these dummy problems mainly for hparams, so cleanup # when possible and do this properly. if hparams.policy_problem_name == "dummy_policy_problem_ttt": tf.logging.info("Using DummyPolicyProblemTTT for the policy.") policy_problem = tic_tac_toe_env.DummyPolicyProblemTTT() else: tf.logging.info("Using DummyPolicyProblem for the policy.") policy_problem = DummyPolicyProblem(action_space, frame_height, frame_width) trainer_lib.add_problem_hparams(hparams, policy_problem) hparams.force_full_predict = True model = registry.model(hparams.policy_network)( hparams, tf.estimator.ModeKeys.TRAIN ) try: num_target_frames = hparams.video_num_target_frames except AttributeError: num_target_frames = 1 features = { "inputs": observations, "input_action": tf.zeros(obs_shape[:2] + [1], dtype=tf.int32), "input_reward": tf.zeros(obs_shape[:2] + [1], dtype=tf.int32), "targets": tf.zeros(obs_shape[:1] + [num_target_frames] + obs_shape[2:]), "target_action": tf.zeros( obs_shape[:1] + [num_target_frames, 1], dtype=tf.int32), "target_reward": tf.zeros( obs_shape[:1] + [num_target_frames, 1], dtype=tf.int32), "target_policy": tf.zeros( obs_shape[:1] + [num_target_frames] + [action_space.n]), "target_value": tf.zeros( obs_shape[:1] + [num_target_frames]) } with tf.variable_scope(tf.get_variable_scope(), reuse=tf.AUTO_REUSE): t2t_model.create_dummy_vars() (targets, _) = model(features) return (targets["target_policy"][:, 0, :], targets["target_value"][:, 0])
[ "Get", "a", "policy", "network", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/rl.py#L280-L332
[ "def", "get_policy", "(", "observations", ",", "hparams", ",", "action_space", ")", ":", "if", "not", "isinstance", "(", "action_space", ",", "gym", ".", "spaces", ".", "Discrete", ")", ":", "raise", "ValueError", "(", "\"Expecting discrete action space.\"", ")"...
272500b6efe353aeb638d2745ed56e519462ca31
train
rlmf_tictactoe
Base set of hparams for model-free PPO.
tensor2tensor/models/research/rl.py
def rlmf_tictactoe(): """Base set of hparams for model-free PPO.""" hparams = rlmf_original() hparams.game = "tictactoe" hparams.rl_env_name = "T2TEnv-TicTacToeEnv-v0" # Since we don't have any no-op actions, otherwise we have to have an # attribute called `get_action_meanings`. hparams.eval_max_num_noops = 0 hparams.max_num_noops = 0 hparams.rl_should_derive_observation_space = False hparams.policy_network = "feed_forward_categorical_policy" hparams.base_algo_params = "ppo_ttt_params" # Number of last observations to feed to the agent hparams.frame_stack_size = 1 return hparams
def rlmf_tictactoe(): """Base set of hparams for model-free PPO.""" hparams = rlmf_original() hparams.game = "tictactoe" hparams.rl_env_name = "T2TEnv-TicTacToeEnv-v0" # Since we don't have any no-op actions, otherwise we have to have an # attribute called `get_action_meanings`. hparams.eval_max_num_noops = 0 hparams.max_num_noops = 0 hparams.rl_should_derive_observation_space = False hparams.policy_network = "feed_forward_categorical_policy" hparams.base_algo_params = "ppo_ttt_params" # Number of last observations to feed to the agent hparams.frame_stack_size = 1 return hparams
[ "Base", "set", "of", "hparams", "for", "model", "-", "free", "PPO", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/rl.py#L427-L443
[ "def", "rlmf_tictactoe", "(", ")", ":", "hparams", "=", "rlmf_original", "(", ")", "hparams", ".", "game", "=", "\"tictactoe\"", "hparams", ".", "rl_env_name", "=", "\"T2TEnv-TicTacToeEnv-v0\"", "# Since we don't have any no-op actions, otherwise we have to have an", "# att...
272500b6efe353aeb638d2745ed56e519462ca31
train
rlmf_tiny
Tiny set of hparams for model-free PPO.
tensor2tensor/models/research/rl.py
def rlmf_tiny(): """Tiny set of hparams for model-free PPO.""" hparams = rlmf_original() hparams = hparams.override_from_dict(rlmf_tiny_overrides()) hparams.batch_size = 2 hparams.base_algo_params = "ppo_original_tiny" hparams.add_hparam("ppo_epochs_num", 3) hparams.add_hparam("ppo_epoch_length", 2) return hparams
def rlmf_tiny(): """Tiny set of hparams for model-free PPO.""" hparams = rlmf_original() hparams = hparams.override_from_dict(rlmf_tiny_overrides()) hparams.batch_size = 2 hparams.base_algo_params = "ppo_original_tiny" hparams.add_hparam("ppo_epochs_num", 3) hparams.add_hparam("ppo_epoch_length", 2) return hparams
[ "Tiny", "set", "of", "hparams", "for", "model", "-", "free", "PPO", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/rl.py#L456-L464
[ "def", "rlmf_tiny", "(", ")", ":", "hparams", "=", "rlmf_original", "(", ")", "hparams", "=", "hparams", ".", "override_from_dict", "(", "rlmf_tiny_overrides", "(", ")", ")", "hparams", ".", "batch_size", "=", "2", "hparams", ".", "base_algo_params", "=", "\...
272500b6efe353aeb638d2745ed56e519462ca31
train
rlmf_dqn_tiny
Tiny DQN params.
tensor2tensor/models/research/rl.py
def rlmf_dqn_tiny(): """Tiny DQN params.""" hparams = rlmf_original() hparams = hparams.override_from_dict(rlmf_tiny_overrides()) hparams.batch_size = 1 hparams.base_algo = "dqn" hparams.base_algo_params = "dqn_original_params" hparams.add_hparam("dqn_num_frames", 128) hparams.add_hparam("dqn_save_every_steps", 128) hparams.add_hparam("dqn_replay_buffer_replay_capacity", 100) hparams.add_hparam("dqn_agent_min_replay_history", 10) return hparams
def rlmf_dqn_tiny(): """Tiny DQN params.""" hparams = rlmf_original() hparams = hparams.override_from_dict(rlmf_tiny_overrides()) hparams.batch_size = 1 hparams.base_algo = "dqn" hparams.base_algo_params = "dqn_original_params" hparams.add_hparam("dqn_num_frames", 128) hparams.add_hparam("dqn_save_every_steps", 128) hparams.add_hparam("dqn_replay_buffer_replay_capacity", 100) hparams.add_hparam("dqn_agent_min_replay_history", 10) return hparams
[ "Tiny", "DQN", "params", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/rl.py#L468-L479
[ "def", "rlmf_dqn_tiny", "(", ")", ":", "hparams", "=", "rlmf_original", "(", ")", "hparams", "=", "hparams", ".", "override_from_dict", "(", "rlmf_tiny_overrides", "(", ")", ")", "hparams", ".", "batch_size", "=", "1", "hparams", ".", "base_algo", "=", "\"dq...
272500b6efe353aeb638d2745ed56e519462ca31
train
rlmf_eval
Eval set of hparams for model-free PPO.
tensor2tensor/models/research/rl.py
def rlmf_eval(): """Eval set of hparams for model-free PPO.""" hparams = rlmf_original() hparams.batch_size = 8 hparams.eval_sampling_temps = [0.0, 0.5, 1.0] hparams.eval_rl_env_max_episode_steps = -1 hparams.add_hparam("ppo_epoch_length", 128) hparams.add_hparam("ppo_optimization_batch_size", 32) hparams.add_hparam("ppo_epochs_num", 10000) hparams.add_hparam("ppo_eval_every_epochs", 500) hparams.add_hparam("attempt", 0) hparams.add_hparam("moe_loss_coef", 0) return hparams
def rlmf_eval(): """Eval set of hparams for model-free PPO.""" hparams = rlmf_original() hparams.batch_size = 8 hparams.eval_sampling_temps = [0.0, 0.5, 1.0] hparams.eval_rl_env_max_episode_steps = -1 hparams.add_hparam("ppo_epoch_length", 128) hparams.add_hparam("ppo_optimization_batch_size", 32) hparams.add_hparam("ppo_epochs_num", 10000) hparams.add_hparam("ppo_eval_every_epochs", 500) hparams.add_hparam("attempt", 0) hparams.add_hparam("moe_loss_coef", 0) return hparams
[ "Eval", "set", "of", "hparams", "for", "model", "-", "free", "PPO", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/rl.py#L483-L495
[ "def", "rlmf_eval", "(", ")", ":", "hparams", "=", "rlmf_original", "(", ")", "hparams", ".", "batch_size", "=", "8", "hparams", ".", "eval_sampling_temps", "=", "[", "0.0", ",", "0.5", ",", "1.0", "]", "hparams", ".", "eval_rl_env_max_episode_steps", "=", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
feed_forward_gaussian_fun
Feed-forward Gaussian.
tensor2tensor/models/research/rl.py
def feed_forward_gaussian_fun(action_space, config, observations): """Feed-forward Gaussian.""" if not isinstance(action_space, gym.spaces.box.Box): raise ValueError("Expecting continuous action space.") mean_weights_initializer = tf.initializers.variance_scaling( scale=config.init_mean_factor) logstd_initializer = tf.random_normal_initializer(config.init_logstd, 1e-10) flat_observations = tf.reshape(observations, [ tf.shape(observations)[0], tf.shape(observations)[1], functools.reduce(operator.mul, observations.shape.as_list()[2:], 1)]) with tf.variable_scope("network_parameters"): with tf.variable_scope("policy"): x = flat_observations for size in config.policy_layers: x = tf.layers.dense(x, size, activation=tf.nn.relu) mean = tf.layers.dense( x, action_space.shape[0], activation=tf.tanh, kernel_initializer=mean_weights_initializer) logstd = tf.get_variable( "logstd", mean.shape[2:], tf.float32, logstd_initializer) logstd = tf.tile( logstd[None, None], [tf.shape(mean)[0], tf.shape(mean)[1]] + [1] * (mean.shape.ndims - 2)) with tf.variable_scope("value"): x = flat_observations for size in config.value_layers: x = tf.layers.dense(x, size, activation=tf.nn.relu) value = tf.layers.dense(x, 1)[..., 0] mean = tf.check_numerics(mean, "mean") logstd = tf.check_numerics(logstd, "logstd") value = tf.check_numerics(value, "value") policy = tfp.distributions.MultivariateNormalDiag(mean, tf.exp(logstd)) return NetworkOutput(policy, value, lambda a: tf.clip_by_value(a, -2., 2))
def feed_forward_gaussian_fun(action_space, config, observations): """Feed-forward Gaussian.""" if not isinstance(action_space, gym.spaces.box.Box): raise ValueError("Expecting continuous action space.") mean_weights_initializer = tf.initializers.variance_scaling( scale=config.init_mean_factor) logstd_initializer = tf.random_normal_initializer(config.init_logstd, 1e-10) flat_observations = tf.reshape(observations, [ tf.shape(observations)[0], tf.shape(observations)[1], functools.reduce(operator.mul, observations.shape.as_list()[2:], 1)]) with tf.variable_scope("network_parameters"): with tf.variable_scope("policy"): x = flat_observations for size in config.policy_layers: x = tf.layers.dense(x, size, activation=tf.nn.relu) mean = tf.layers.dense( x, action_space.shape[0], activation=tf.tanh, kernel_initializer=mean_weights_initializer) logstd = tf.get_variable( "logstd", mean.shape[2:], tf.float32, logstd_initializer) logstd = tf.tile( logstd[None, None], [tf.shape(mean)[0], tf.shape(mean)[1]] + [1] * (mean.shape.ndims - 2)) with tf.variable_scope("value"): x = flat_observations for size in config.value_layers: x = tf.layers.dense(x, size, activation=tf.nn.relu) value = tf.layers.dense(x, 1)[..., 0] mean = tf.check_numerics(mean, "mean") logstd = tf.check_numerics(logstd, "logstd") value = tf.check_numerics(value, "value") policy = tfp.distributions.MultivariateNormalDiag(mean, tf.exp(logstd)) return NetworkOutput(policy, value, lambda a: tf.clip_by_value(a, -2., 2))
[ "Feed", "-", "forward", "Gaussian", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/rl.py#L559-L596
[ "def", "feed_forward_gaussian_fun", "(", "action_space", ",", "config", ",", "observations", ")", ":", "if", "not", "isinstance", "(", "action_space", ",", "gym", ".", "spaces", ".", "box", ".", "Box", ")", ":", "raise", "ValueError", "(", "\"Expecting continu...
272500b6efe353aeb638d2745ed56e519462ca31
train
YellowFinOptimizer._curvature_range
Curvature range. Returns: h_max_t, h_min_t ops
tensor2tensor/utils/yellowfin.py
def _curvature_range(self): """Curvature range. Returns: h_max_t, h_min_t ops """ self._curv_win = tf.get_variable("curv_win", dtype=tf.float32, trainable=False, shape=[self.curvature_window_width,], initializer=tf.zeros_initializer) # We use log smoothing for curvature range self._curv_win = tf.scatter_update(self._curv_win, self._step % self.curvature_window_width, tf.log(self._grad_norm_squared)) # Note here the iterations start from iteration 0 valid_window = tf.slice(self._curv_win, tf.constant([0,]), tf.expand_dims( tf.minimum( tf.constant(self.curvature_window_width), self._step + 1), dim=0)) self._h_min_t = tf.reduce_min(valid_window) self._h_max_t = tf.reduce_max(valid_window) curv_range_ops = [] with tf.control_dependencies([self._h_min_t, self._h_max_t]): avg_op = self._moving_averager.apply([self._h_min_t, self._h_max_t]) with tf.control_dependencies([avg_op]): self._h_min = tf.exp( tf.identity(self._moving_averager.average(self._h_min_t))) self._h_max = tf.exp( tf.identity(self._moving_averager.average(self._h_max_t))) if self._sparsity_debias: self._h_min *= self._sparsity_avg self._h_max *= self._sparsity_avg curv_range_ops.append(avg_op) return curv_range_ops
def _curvature_range(self): """Curvature range. Returns: h_max_t, h_min_t ops """ self._curv_win = tf.get_variable("curv_win", dtype=tf.float32, trainable=False, shape=[self.curvature_window_width,], initializer=tf.zeros_initializer) # We use log smoothing for curvature range self._curv_win = tf.scatter_update(self._curv_win, self._step % self.curvature_window_width, tf.log(self._grad_norm_squared)) # Note here the iterations start from iteration 0 valid_window = tf.slice(self._curv_win, tf.constant([0,]), tf.expand_dims( tf.minimum( tf.constant(self.curvature_window_width), self._step + 1), dim=0)) self._h_min_t = tf.reduce_min(valid_window) self._h_max_t = tf.reduce_max(valid_window) curv_range_ops = [] with tf.control_dependencies([self._h_min_t, self._h_max_t]): avg_op = self._moving_averager.apply([self._h_min_t, self._h_max_t]) with tf.control_dependencies([avg_op]): self._h_min = tf.exp( tf.identity(self._moving_averager.average(self._h_min_t))) self._h_max = tf.exp( tf.identity(self._moving_averager.average(self._h_max_t))) if self._sparsity_debias: self._h_min *= self._sparsity_avg self._h_max *= self._sparsity_avg curv_range_ops.append(avg_op) return curv_range_ops
[ "Curvature", "range", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/yellowfin.py#L193-L230
[ "def", "_curvature_range", "(", "self", ")", ":", "self", ".", "_curv_win", "=", "tf", ".", "get_variable", "(", "\"curv_win\"", ",", "dtype", "=", "tf", ".", "float32", ",", "trainable", "=", "False", ",", "shape", "=", "[", "self", ".", "curvature_wind...
272500b6efe353aeb638d2745ed56e519462ca31
train
YellowFinOptimizer._grad_variance
Estimate of gradient Variance. Returns: C_t ops.
tensor2tensor/utils/yellowfin.py
def _grad_variance(self): """Estimate of gradient Variance. Returns: C_t ops. """ grad_var_ops = [] tensor_to_avg = [] for t, g in zip(self._vars, self._grad): if isinstance(g, tf.IndexedSlices): tensor_to_avg.append( tf.reshape(tf.unsorted_segment_sum(g.values, g.indices, g.dense_shape[0]), shape=t.get_shape())) else: tensor_to_avg.append(g) avg_op = self._moving_averager.apply(tensor_to_avg) grad_var_ops.append(avg_op) with tf.control_dependencies([avg_op]): self._grad_avg = [self._moving_averager.average(val) for val in tensor_to_avg] self._grad_avg_squared = [tf.square(val) for val in self._grad_avg] # Compute Variance self._grad_var = tf.maximum( tf.constant(1e-6, dtype=self._grad_norm_squared_avg.dtype), self._grad_norm_squared_avg - tf.add_n([tf.reduce_sum(val) for val in self._grad_avg_squared])) if self._sparsity_debias: self._grad_var *= self._sparsity_avg return grad_var_ops
def _grad_variance(self): """Estimate of gradient Variance. Returns: C_t ops. """ grad_var_ops = [] tensor_to_avg = [] for t, g in zip(self._vars, self._grad): if isinstance(g, tf.IndexedSlices): tensor_to_avg.append( tf.reshape(tf.unsorted_segment_sum(g.values, g.indices, g.dense_shape[0]), shape=t.get_shape())) else: tensor_to_avg.append(g) avg_op = self._moving_averager.apply(tensor_to_avg) grad_var_ops.append(avg_op) with tf.control_dependencies([avg_op]): self._grad_avg = [self._moving_averager.average(val) for val in tensor_to_avg] self._grad_avg_squared = [tf.square(val) for val in self._grad_avg] # Compute Variance self._grad_var = tf.maximum( tf.constant(1e-6, dtype=self._grad_norm_squared_avg.dtype), self._grad_norm_squared_avg - tf.add_n([tf.reduce_sum(val) for val in self._grad_avg_squared])) if self._sparsity_debias: self._grad_var *= self._sparsity_avg return grad_var_ops
[ "Estimate", "of", "gradient", "Variance", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/yellowfin.py#L232-L263
[ "def", "_grad_variance", "(", "self", ")", ":", "grad_var_ops", "=", "[", "]", "tensor_to_avg", "=", "[", "]", "for", "t", ",", "g", "in", "zip", "(", "self", ".", "_vars", ",", "self", ".", "_grad", ")", ":", "if", "isinstance", "(", "g", ",", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
YellowFinOptimizer._dist_to_opt
Distance to optimum. Returns: D_t ops
tensor2tensor/utils/yellowfin.py
def _dist_to_opt(self): """Distance to optimum. Returns: D_t ops """ dist_to_opt_ops = [] # Running average of the norm of gradient self._grad_norm = tf.sqrt(self._grad_norm_squared) avg_op = self._moving_averager.apply([self._grad_norm,]) dist_to_opt_ops.append(avg_op) with tf.control_dependencies([avg_op]): self._grad_norm_avg = self._moving_averager.average(self._grad_norm) # Single iteration distance estimation, note here # self._grad_norm_avg is per variable self._d_t = self._grad_norm_avg / self._grad_norm_squared_avg # Running average of distance avg_op = self._moving_averager.apply([self._d_t]) dist_to_opt_ops.append(avg_op) with tf.control_dependencies([avg_op]): self._dist_to_opt_avg = tf.identity( self._moving_averager.average(self._d_t)) if self._sparsity_debias: self._dist_to_opt_avg /= tf.sqrt(self._sparsity_avg) return dist_to_opt_ops
def _dist_to_opt(self): """Distance to optimum. Returns: D_t ops """ dist_to_opt_ops = [] # Running average of the norm of gradient self._grad_norm = tf.sqrt(self._grad_norm_squared) avg_op = self._moving_averager.apply([self._grad_norm,]) dist_to_opt_ops.append(avg_op) with tf.control_dependencies([avg_op]): self._grad_norm_avg = self._moving_averager.average(self._grad_norm) # Single iteration distance estimation, note here # self._grad_norm_avg is per variable self._d_t = self._grad_norm_avg / self._grad_norm_squared_avg # Running average of distance avg_op = self._moving_averager.apply([self._d_t]) dist_to_opt_ops.append(avg_op) with tf.control_dependencies([avg_op]): self._dist_to_opt_avg = tf.identity( self._moving_averager.average(self._d_t)) if self._sparsity_debias: self._dist_to_opt_avg /= tf.sqrt(self._sparsity_avg) return dist_to_opt_ops
[ "Distance", "to", "optimum", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/yellowfin.py#L265-L289
[ "def", "_dist_to_opt", "(", "self", ")", ":", "dist_to_opt_ops", "=", "[", "]", "# Running average of the norm of gradient", "self", ".", "_grad_norm", "=", "tf", ".", "sqrt", "(", "self", ".", "_grad_norm_squared", ")", "avg_op", "=", "self", ".", "_moving_aver...
272500b6efe353aeb638d2745ed56e519462ca31
train
YellowFinOptimizer._grad_sparsity
Gradient sparsity.
tensor2tensor/utils/yellowfin.py
def _grad_sparsity(self): """Gradient sparsity.""" # If the sparse minibatch gradient has 10 percent of its entries # non-zero, its sparsity is 0.1. # The norm of dense gradient averaged from full dataset # are roughly estimated norm of minibatch # sparse gradient norm * sqrt(sparsity) # An extension maybe only correct the sparse blob. non_zero_cnt = tf.add_n([tf.count_nonzero(g) for g in self._grad]) all_entry_cnt = tf.add_n([tf.size(g) for g in self._grad]) self._sparsity = tf.cast(non_zero_cnt, self._grad[0].dtype) self._sparsity /= tf.cast(all_entry_cnt, self._grad[0].dtype) avg_op = self._moving_averager.apply([self._sparsity,]) with tf.control_dependencies([avg_op]): self._sparsity_avg = self._moving_averager.average(self._sparsity) return avg_op
def _grad_sparsity(self): """Gradient sparsity.""" # If the sparse minibatch gradient has 10 percent of its entries # non-zero, its sparsity is 0.1. # The norm of dense gradient averaged from full dataset # are roughly estimated norm of minibatch # sparse gradient norm * sqrt(sparsity) # An extension maybe only correct the sparse blob. non_zero_cnt = tf.add_n([tf.count_nonzero(g) for g in self._grad]) all_entry_cnt = tf.add_n([tf.size(g) for g in self._grad]) self._sparsity = tf.cast(non_zero_cnt, self._grad[0].dtype) self._sparsity /= tf.cast(all_entry_cnt, self._grad[0].dtype) avg_op = self._moving_averager.apply([self._sparsity,]) with tf.control_dependencies([avg_op]): self._sparsity_avg = self._moving_averager.average(self._sparsity) return avg_op
[ "Gradient", "sparsity", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/yellowfin.py#L291-L306
[ "def", "_grad_sparsity", "(", "self", ")", ":", "# If the sparse minibatch gradient has 10 percent of its entries", "# non-zero, its sparsity is 0.1.", "# The norm of dense gradient averaged from full dataset", "# are roughly estimated norm of minibatch", "# sparse gradient norm * sqrt(sparsity)...
272500b6efe353aeb638d2745ed56e519462ca31
train
YellowFinOptimizer._prepare_variables
Prepare Variables for YellowFin. Returns: Grad**2, Norm, Norm**2, Mean(Norm**2) ops
tensor2tensor/utils/yellowfin.py
def _prepare_variables(self): """Prepare Variables for YellowFin. Returns: Grad**2, Norm, Norm**2, Mean(Norm**2) ops """ self._moving_averager = tf.train.ExponentialMovingAverage( decay=self._beta, zero_debias=self._zero_debias) # assert self._grad is not None and len(self._grad) > 0 # List for the returned Operations prepare_variables_op = [] # Get per var g**2 and norm**2 self._grad_squared = [] self._grad_norm_squared = [] # Gradient squared for v, g in zip(self._vars, self._grad): if g is None: continue with tf.colocate_with(v): self._grad_squared.append(tf.square(g)) # Norm squared. self._grad_norm_squared = [tf.reduce_sum(g_sq) for g_sq in self._grad_squared] if self._sparsity_debias: avg_op_sparsity = self._grad_sparsity() prepare_variables_op.append(avg_op_sparsity) # The following running average on squared norm of gradient # is shared by grad_var and dist_to_opt avg_op = self._moving_averager.apply(self._grad_norm_squared) with tf.control_dependencies([avg_op]): self._grad_norm_squared_avg = [self._moving_averager.average(val) for val in self._grad_norm_squared] self._grad_norm_squared = tf.add_n(self._grad_norm_squared) self._grad_norm_squared_avg = tf.add_n(self._grad_norm_squared_avg) prepare_variables_op.append(avg_op) return tf.group(*prepare_variables_op)
def _prepare_variables(self): """Prepare Variables for YellowFin. Returns: Grad**2, Norm, Norm**2, Mean(Norm**2) ops """ self._moving_averager = tf.train.ExponentialMovingAverage( decay=self._beta, zero_debias=self._zero_debias) # assert self._grad is not None and len(self._grad) > 0 # List for the returned Operations prepare_variables_op = [] # Get per var g**2 and norm**2 self._grad_squared = [] self._grad_norm_squared = [] # Gradient squared for v, g in zip(self._vars, self._grad): if g is None: continue with tf.colocate_with(v): self._grad_squared.append(tf.square(g)) # Norm squared. self._grad_norm_squared = [tf.reduce_sum(g_sq) for g_sq in self._grad_squared] if self._sparsity_debias: avg_op_sparsity = self._grad_sparsity() prepare_variables_op.append(avg_op_sparsity) # The following running average on squared norm of gradient # is shared by grad_var and dist_to_opt avg_op = self._moving_averager.apply(self._grad_norm_squared) with tf.control_dependencies([avg_op]): self._grad_norm_squared_avg = [self._moving_averager.average(val) for val in self._grad_norm_squared] self._grad_norm_squared = tf.add_n(self._grad_norm_squared) self._grad_norm_squared_avg = tf.add_n(self._grad_norm_squared_avg) prepare_variables_op.append(avg_op) return tf.group(*prepare_variables_op)
[ "Prepare", "Variables", "for", "YellowFin", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/yellowfin.py#L308-L349
[ "def", "_prepare_variables", "(", "self", ")", ":", "self", ".", "_moving_averager", "=", "tf", ".", "train", ".", "ExponentialMovingAverage", "(", "decay", "=", "self", ".", "_beta", ",", "zero_debias", "=", "self", ".", "_zero_debias", ")", "# assert self._g...
272500b6efe353aeb638d2745ed56e519462ca31
train
YellowFinOptimizer._get_cubic_root
Get the cubic root.
tensor2tensor/utils/yellowfin.py
def _get_cubic_root(self): """Get the cubic root.""" # We have the equation x^2 D^2 + (1-x)^4 * C / h_min^2 # where x = sqrt(mu). # We substitute x, which is sqrt(mu), with x = y + 1. # It gives y^3 + py = q # where p = (D^2 h_min^2)/(2*C) and q = -p. # We use the Vieta's substitution to compute the root. # There is only one real solution y (which is in [0, 1] ). # http://mathworld.wolfram.com/VietasSubstitution.html assert_array = [ tf.Assert( tf.logical_not(tf.is_nan(self._dist_to_opt_avg)), [self._dist_to_opt_avg,]), tf.Assert( tf.logical_not(tf.is_nan(self._h_min)), [self._h_min,]), tf.Assert( tf.logical_not(tf.is_nan(self._grad_var)), [self._grad_var,]), tf.Assert( tf.logical_not(tf.is_inf(self._dist_to_opt_avg)), [self._dist_to_opt_avg,]), tf.Assert( tf.logical_not(tf.is_inf(self._h_min)), [self._h_min,]), tf.Assert( tf.logical_not(tf.is_inf(self._grad_var)), [self._grad_var,]) ] with tf.control_dependencies(assert_array): p = self._dist_to_opt_avg**2 * self._h_min**2 / 2 / self._grad_var w3 = (-tf.sqrt(p**2 + 4.0 / 27.0 * p**3) - p) / 2.0 w = tf.sign(w3) * tf.pow(tf.abs(w3), 1.0/3.0) y = w - p / 3.0 / w x = y + 1 return x
def _get_cubic_root(self): """Get the cubic root.""" # We have the equation x^2 D^2 + (1-x)^4 * C / h_min^2 # where x = sqrt(mu). # We substitute x, which is sqrt(mu), with x = y + 1. # It gives y^3 + py = q # where p = (D^2 h_min^2)/(2*C) and q = -p. # We use the Vieta's substitution to compute the root. # There is only one real solution y (which is in [0, 1] ). # http://mathworld.wolfram.com/VietasSubstitution.html assert_array = [ tf.Assert( tf.logical_not(tf.is_nan(self._dist_to_opt_avg)), [self._dist_to_opt_avg,]), tf.Assert( tf.logical_not(tf.is_nan(self._h_min)), [self._h_min,]), tf.Assert( tf.logical_not(tf.is_nan(self._grad_var)), [self._grad_var,]), tf.Assert( tf.logical_not(tf.is_inf(self._dist_to_opt_avg)), [self._dist_to_opt_avg,]), tf.Assert( tf.logical_not(tf.is_inf(self._h_min)), [self._h_min,]), tf.Assert( tf.logical_not(tf.is_inf(self._grad_var)), [self._grad_var,]) ] with tf.control_dependencies(assert_array): p = self._dist_to_opt_avg**2 * self._h_min**2 / 2 / self._grad_var w3 = (-tf.sqrt(p**2 + 4.0 / 27.0 * p**3) - p) / 2.0 w = tf.sign(w3) * tf.pow(tf.abs(w3), 1.0/3.0) y = w - p / 3.0 / w x = y + 1 return x
[ "Get", "the", "cubic", "root", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/yellowfin.py#L351-L387
[ "def", "_get_cubic_root", "(", "self", ")", ":", "# We have the equation x^2 D^2 + (1-x)^4 * C / h_min^2", "# where x = sqrt(mu).", "# We substitute x, which is sqrt(mu), with x = y + 1.", "# It gives y^3 + py = q", "# where p = (D^2 h_min^2)/(2*C) and q = -p.", "# We use the Vieta's substitut...
272500b6efe353aeb638d2745ed56e519462ca31
train
YellowFinOptimizer._get_lr_tensor
Get lr minimizing the surrogate. Returns: The lr_t.
tensor2tensor/utils/yellowfin.py
def _get_lr_tensor(self): """Get lr minimizing the surrogate. Returns: The lr_t. """ lr = tf.squared_difference(1.0, tf.sqrt(self._mu)) / self._h_min return lr
def _get_lr_tensor(self): """Get lr minimizing the surrogate. Returns: The lr_t. """ lr = tf.squared_difference(1.0, tf.sqrt(self._mu)) / self._h_min return lr
[ "Get", "lr", "minimizing", "the", "surrogate", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/yellowfin.py#L389-L396
[ "def", "_get_lr_tensor", "(", "self", ")", ":", "lr", "=", "tf", ".", "squared_difference", "(", "1.0", ",", "tf", ".", "sqrt", "(", "self", ".", "_mu", ")", ")", "/", "self", ".", "_h_min", "return", "lr" ]
272500b6efe353aeb638d2745ed56e519462ca31
train
YellowFinOptimizer._get_mu_tensor
Get the min mu which minimize the surrogate. Returns: The mu_t.
tensor2tensor/utils/yellowfin.py
def _get_mu_tensor(self): """Get the min mu which minimize the surrogate. Returns: The mu_t. """ root = self._get_cubic_root() dr = self._h_max / self._h_min mu = tf.maximum( root**2, ((tf.sqrt(dr) - 1) / (tf.sqrt(dr) + 1))**2) return mu
def _get_mu_tensor(self): """Get the min mu which minimize the surrogate. Returns: The mu_t. """ root = self._get_cubic_root() dr = self._h_max / self._h_min mu = tf.maximum( root**2, ((tf.sqrt(dr) - 1) / (tf.sqrt(dr) + 1))**2) return mu
[ "Get", "the", "min", "mu", "which", "minimize", "the", "surrogate", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/yellowfin.py#L398-L408
[ "def", "_get_mu_tensor", "(", "self", ")", ":", "root", "=", "self", ".", "_get_cubic_root", "(", ")", "dr", "=", "self", ".", "_h_max", "/", "self", ".", "_h_min", "mu", "=", "tf", ".", "maximum", "(", "root", "**", "2", ",", "(", "(", "tf", "."...
272500b6efe353aeb638d2745ed56e519462ca31
train
YellowFinOptimizer._yellowfin
YellowFin auto-tuning optimizer based on momentum SGD. Returns: YF ops (Curvature range, Grad_variance, Dist_to_opt, Single-Step, Auto-Tuning)
tensor2tensor/utils/yellowfin.py
def _yellowfin(self): """YellowFin auto-tuning optimizer based on momentum SGD. Returns: YF ops (Curvature range, Grad_variance, Dist_to_opt, Single-Step, Auto-Tuning) """ # List for the returned Operations. yellowfin_ops = [] # Curvature range ops. curv_range_ops = self._curvature_range() yellowfin_ops += curv_range_ops # Estimate of gradient Variance ops. grad_var_ops = self._grad_variance() yellowfin_ops += grad_var_ops # Distance to optimum ops. dist_to_opt_ops = self._dist_to_opt() yellowfin_ops += dist_to_opt_ops # Single-Step: minimizes the surrogate for the expected # squared distance from the optimum of a local quadratic # approximation after a single step while keeping all directions in the # robust region. self._mu = tf.identity(tf.cond(self._do_tune, self._get_mu_tensor, lambda: self._mu_var)) with tf.control_dependencies([self._mu]): self._lr = tf.identity(tf.cond(self._do_tune, self._get_lr_tensor, lambda: self._lr_var)) # Tune learning rate and momentum. with tf.control_dependencies([self._mu, self._lr]): self._mu = self._beta * self._mu_var + (1 - self._beta) * self._mu self._lr = self._beta * self._lr_var + (1 - self._beta) * self._lr yellowfin_ops.append(tf.assign(self._mu_var, self._mu)) yellowfin_ops.append(tf.assign(self._lr_var, self._lr)) yellowfin_ops = tf.group(*yellowfin_ops) return yellowfin_ops
def _yellowfin(self): """YellowFin auto-tuning optimizer based on momentum SGD. Returns: YF ops (Curvature range, Grad_variance, Dist_to_opt, Single-Step, Auto-Tuning) """ # List for the returned Operations. yellowfin_ops = [] # Curvature range ops. curv_range_ops = self._curvature_range() yellowfin_ops += curv_range_ops # Estimate of gradient Variance ops. grad_var_ops = self._grad_variance() yellowfin_ops += grad_var_ops # Distance to optimum ops. dist_to_opt_ops = self._dist_to_opt() yellowfin_ops += dist_to_opt_ops # Single-Step: minimizes the surrogate for the expected # squared distance from the optimum of a local quadratic # approximation after a single step while keeping all directions in the # robust region. self._mu = tf.identity(tf.cond(self._do_tune, self._get_mu_tensor, lambda: self._mu_var)) with tf.control_dependencies([self._mu]): self._lr = tf.identity(tf.cond(self._do_tune, self._get_lr_tensor, lambda: self._lr_var)) # Tune learning rate and momentum. with tf.control_dependencies([self._mu, self._lr]): self._mu = self._beta * self._mu_var + (1 - self._beta) * self._mu self._lr = self._beta * self._lr_var + (1 - self._beta) * self._lr yellowfin_ops.append(tf.assign(self._mu_var, self._mu)) yellowfin_ops.append(tf.assign(self._lr_var, self._lr)) yellowfin_ops = tf.group(*yellowfin_ops) return yellowfin_ops
[ "YellowFin", "auto", "-", "tuning", "optimizer", "based", "on", "momentum", "SGD", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/yellowfin.py#L410-L454
[ "def", "_yellowfin", "(", "self", ")", ":", "# List for the returned Operations.", "yellowfin_ops", "=", "[", "]", "# Curvature range ops.", "curv_range_ops", "=", "self", ".", "_curvature_range", "(", ")", "yellowfin_ops", "+=", "curv_range_ops", "# Estimate of gradient ...
272500b6efe353aeb638d2745ed56e519462ca31
train
YellowFinOptimizer.apply_gradients
Applying gradients and tune hyperparams with YellowFin. Args: grads_and_vars: List of (gradient, variable) pairs as returned by compute_gradients(). global_step: Optional Variable to increment by one after the variables have been updated. name: Optional name for the returned operation. Default to the name passed to the Optimizer constructor. Returns: (A group of operations) Variable Update with Momentum ops, YellowFin ops(Curvature, Variance, Distance) ops, SingleStep and lr_mu tuning ops, Step increment ops.
tensor2tensor/utils/yellowfin.py
def apply_gradients(self, grads_and_vars, global_step=None, name=None): """Applying gradients and tune hyperparams with YellowFin. Args: grads_and_vars: List of (gradient, variable) pairs as returned by compute_gradients(). global_step: Optional Variable to increment by one after the variables have been updated. name: Optional name for the returned operation. Default to the name passed to the Optimizer constructor. Returns: (A group of operations) Variable Update with Momentum ops, YellowFin ops(Curvature, Variance, Distance) ops, SingleStep and lr_mu tuning ops, Step increment ops. """ self._grad, self._vars = zip(*[(g, t) for g, t in grads_and_vars if g is not None]) # Var update with Momentum. with tf.variable_scope("apply_updates"): # Gradient Clipping? if self._clip_thresh_var is not None: self._grad, _ = tf.clip_by_global_norm( self._grad, self._clip_thresh_var) apply_grad_op = self._momentum_optimizer.apply_gradients( zip(self._grad, self._vars), global_step=global_step, name=name) else: apply_grad_op = self._momentum_optimizer.apply_gradients( zip(self._grad, self._vars), global_step=global_step, name=name) # Begin lr and mu tuning. with tf.variable_scope("prepare_yellowFin_variables"): # the dependencies ideally only need to be after clip is done, # i.e. depends on self._grads. However, the control_dependencies # does not support indexed slice for sparse gradients. # The alternative dependencies here might be slightly slower due # to less parallelization. with tf.control_dependencies([apply_grad_op,]): prepare_variables_op = self._prepare_variables() with tf.variable_scope("yellowfin"): with tf.control_dependencies([prepare_variables_op]): yellowfin_op = self._yellowfin() # Update YellowFin step variable. with tf.control_dependencies([yellowfin_op]): self._increment_step_op = tf.assign_add(self._step, 1).op return tf.group(apply_grad_op, prepare_variables_op, yellowfin_op, self._increment_step_op)
def apply_gradients(self, grads_and_vars, global_step=None, name=None): """Applying gradients and tune hyperparams with YellowFin. Args: grads_and_vars: List of (gradient, variable) pairs as returned by compute_gradients(). global_step: Optional Variable to increment by one after the variables have been updated. name: Optional name for the returned operation. Default to the name passed to the Optimizer constructor. Returns: (A group of operations) Variable Update with Momentum ops, YellowFin ops(Curvature, Variance, Distance) ops, SingleStep and lr_mu tuning ops, Step increment ops. """ self._grad, self._vars = zip(*[(g, t) for g, t in grads_and_vars if g is not None]) # Var update with Momentum. with tf.variable_scope("apply_updates"): # Gradient Clipping? if self._clip_thresh_var is not None: self._grad, _ = tf.clip_by_global_norm( self._grad, self._clip_thresh_var) apply_grad_op = self._momentum_optimizer.apply_gradients( zip(self._grad, self._vars), global_step=global_step, name=name) else: apply_grad_op = self._momentum_optimizer.apply_gradients( zip(self._grad, self._vars), global_step=global_step, name=name) # Begin lr and mu tuning. with tf.variable_scope("prepare_yellowFin_variables"): # the dependencies ideally only need to be after clip is done, # i.e. depends on self._grads. However, the control_dependencies # does not support indexed slice for sparse gradients. # The alternative dependencies here might be slightly slower due # to less parallelization. with tf.control_dependencies([apply_grad_op,]): prepare_variables_op = self._prepare_variables() with tf.variable_scope("yellowfin"): with tf.control_dependencies([prepare_variables_op]): yellowfin_op = self._yellowfin() # Update YellowFin step variable. with tf.control_dependencies([yellowfin_op]): self._increment_step_op = tf.assign_add(self._step, 1).op return tf.group(apply_grad_op, prepare_variables_op, yellowfin_op, self._increment_step_op)
[ "Applying", "gradients", "and", "tune", "hyperparams", "with", "YellowFin", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/yellowfin.py#L460-L519
[ "def", "apply_gradients", "(", "self", ",", "grads_and_vars", ",", "global_step", "=", "None", ",", "name", "=", "None", ")", ":", "self", ".", "_grad", ",", "self", ".", "_vars", "=", "zip", "(", "*", "[", "(", "g", ",", "t", ")", "for", "g", ",...
272500b6efe353aeb638d2745ed56e519462ca31
train
YellowFinOptimizer.compute_gradients
Compute gradients through momentum optimizer. Args: loss: A Tensor containing the value to minimize. var_list: Optional list or tuple of tf.Variable to update to minimize loss. Defaults to the list of variables collected in the graph under the key GraphKey.TRAINABLE_VARIABLES. global_step: Optional Variable to increment by one after the variables have been updated. gate_gradients: How to gate the computation of gradients. Can be GATE_NONE, GATE_OP, or GATE_GRAPH. aggregation_method: Specifies the method used to combine gradient terms. Valid values are defined in the class AggregationMethod. colocate_gradients_with_ops: If True, try collocating gradients with the corresponding op. name: Optional name for the returned operation. Default to the name passed to the Optimizer constructor. grad_loss: Optional. A Tensor holding the gradient computed for loss. Returns: A list of (gradient, variable) pairs. Variable is always present, but gradient can be None.
tensor2tensor/utils/yellowfin.py
def compute_gradients(self, loss, var_list, global_step=None, gate_gradients=GATE_OP, aggregation_method=None, colocate_gradients_with_ops=False, name=None, grad_loss=None): """Compute gradients through momentum optimizer. Args: loss: A Tensor containing the value to minimize. var_list: Optional list or tuple of tf.Variable to update to minimize loss. Defaults to the list of variables collected in the graph under the key GraphKey.TRAINABLE_VARIABLES. global_step: Optional Variable to increment by one after the variables have been updated. gate_gradients: How to gate the computation of gradients. Can be GATE_NONE, GATE_OP, or GATE_GRAPH. aggregation_method: Specifies the method used to combine gradient terms. Valid values are defined in the class AggregationMethod. colocate_gradients_with_ops: If True, try collocating gradients with the corresponding op. name: Optional name for the returned operation. Default to the name passed to the Optimizer constructor. grad_loss: Optional. A Tensor holding the gradient computed for loss. Returns: A list of (gradient, variable) pairs. Variable is always present, but gradient can be None. """ del global_step, name # Unused for now. return self._momentum_optimizer.compute_gradients( loss, var_list=var_list, gate_gradients=gate_gradients, aggregation_method=aggregation_method, colocate_gradients_with_ops=colocate_gradients_with_ops, grad_loss=grad_loss)
def compute_gradients(self, loss, var_list, global_step=None, gate_gradients=GATE_OP, aggregation_method=None, colocate_gradients_with_ops=False, name=None, grad_loss=None): """Compute gradients through momentum optimizer. Args: loss: A Tensor containing the value to minimize. var_list: Optional list or tuple of tf.Variable to update to minimize loss. Defaults to the list of variables collected in the graph under the key GraphKey.TRAINABLE_VARIABLES. global_step: Optional Variable to increment by one after the variables have been updated. gate_gradients: How to gate the computation of gradients. Can be GATE_NONE, GATE_OP, or GATE_GRAPH. aggregation_method: Specifies the method used to combine gradient terms. Valid values are defined in the class AggregationMethod. colocate_gradients_with_ops: If True, try collocating gradients with the corresponding op. name: Optional name for the returned operation. Default to the name passed to the Optimizer constructor. grad_loss: Optional. A Tensor holding the gradient computed for loss. Returns: A list of (gradient, variable) pairs. Variable is always present, but gradient can be None. """ del global_step, name # Unused for now. return self._momentum_optimizer.compute_gradients( loss, var_list=var_list, gate_gradients=gate_gradients, aggregation_method=aggregation_method, colocate_gradients_with_ops=colocate_gradients_with_ops, grad_loss=grad_loss)
[ "Compute", "gradients", "through", "momentum", "optimizer", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/yellowfin.py#L521-L560
[ "def", "compute_gradients", "(", "self", ",", "loss", ",", "var_list", ",", "global_step", "=", "None", ",", "gate_gradients", "=", "GATE_OP", ",", "aggregation_method", "=", "None", ",", "colocate_gradients_with_ops", "=", "False", ",", "name", "=", "None", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
YellowFinOptimizer.minimize
Adapted from TensorFlow Optimizer base class member function. Add operations to minimize `loss` by updating `var_list`. This method simply combines calls `compute_gradients()` and `apply_gradients()`. If you want to process the gradient before applying them call `tf.gradients()` and `self.apply_gradients()` explicitly instead of using this function. Args: loss: A Tensor containing the value to minimize. global_step: Optional Variable to increment by one after the variables have been updated. var_list: Optional list or tuple of Variable objects to update to minimize loss. Defaults to the list of variables collected in the graph under the key GraphKeys.TRAINABLE_VARIABLES. gate_gradients: How to gate the computation of gradients. Can be GATE_NONE, GATE_OP, or GATE_GRAPH. aggregation_method: Specifies the method used to combine gradient terms. Valid values are defined in the class AggregationMethod. colocate_gradients_with_ops: If True, try collocating gradients with the corresponding op. name: Optional name for the returned operation. grad_loss: Optional. A Tensor holding the gradient computed for loss. Returns: An Operation that updates the variables in var_list. If global_step was not None, that operation also increments global_step. Raises: ValueError: if no gradients are provided for any variable.
tensor2tensor/utils/yellowfin.py
def minimize(self, loss, global_step=None, var_list=None, gate_gradients=GATE_OP, aggregation_method=None, colocate_gradients_with_ops=False, name=None, grad_loss=None): """Adapted from TensorFlow Optimizer base class member function. Add operations to minimize `loss` by updating `var_list`. This method simply combines calls `compute_gradients()` and `apply_gradients()`. If you want to process the gradient before applying them call `tf.gradients()` and `self.apply_gradients()` explicitly instead of using this function. Args: loss: A Tensor containing the value to minimize. global_step: Optional Variable to increment by one after the variables have been updated. var_list: Optional list or tuple of Variable objects to update to minimize loss. Defaults to the list of variables collected in the graph under the key GraphKeys.TRAINABLE_VARIABLES. gate_gradients: How to gate the computation of gradients. Can be GATE_NONE, GATE_OP, or GATE_GRAPH. aggregation_method: Specifies the method used to combine gradient terms. Valid values are defined in the class AggregationMethod. colocate_gradients_with_ops: If True, try collocating gradients with the corresponding op. name: Optional name for the returned operation. grad_loss: Optional. A Tensor holding the gradient computed for loss. Returns: An Operation that updates the variables in var_list. If global_step was not None, that operation also increments global_step. Raises: ValueError: if no gradients are provided for any variable. """ grads_and_vars = self._momentum_optimizer.compute_gradients( loss, var_list=var_list, gate_gradients=gate_gradients, aggregation_method=aggregation_method, colocate_gradients_with_ops=colocate_gradients_with_ops, grad_loss=grad_loss) vars_with_grad = [v for g, v in grads_and_vars if g is not None] if not vars_with_grad: raise ValueError( "No gradients provided for any variable, check your graph for ops" " that do not support gradients, between variables %s and loss %s." % ([str(v) for _, v in grads_and_vars], loss)) for g, v in grads_and_vars: print("g ", g) print("v ", v) return self.apply_gradients(grads_and_vars, global_step=global_step, name=name)
def minimize(self, loss, global_step=None, var_list=None, gate_gradients=GATE_OP, aggregation_method=None, colocate_gradients_with_ops=False, name=None, grad_loss=None): """Adapted from TensorFlow Optimizer base class member function. Add operations to minimize `loss` by updating `var_list`. This method simply combines calls `compute_gradients()` and `apply_gradients()`. If you want to process the gradient before applying them call `tf.gradients()` and `self.apply_gradients()` explicitly instead of using this function. Args: loss: A Tensor containing the value to minimize. global_step: Optional Variable to increment by one after the variables have been updated. var_list: Optional list or tuple of Variable objects to update to minimize loss. Defaults to the list of variables collected in the graph under the key GraphKeys.TRAINABLE_VARIABLES. gate_gradients: How to gate the computation of gradients. Can be GATE_NONE, GATE_OP, or GATE_GRAPH. aggregation_method: Specifies the method used to combine gradient terms. Valid values are defined in the class AggregationMethod. colocate_gradients_with_ops: If True, try collocating gradients with the corresponding op. name: Optional name for the returned operation. grad_loss: Optional. A Tensor holding the gradient computed for loss. Returns: An Operation that updates the variables in var_list. If global_step was not None, that operation also increments global_step. Raises: ValueError: if no gradients are provided for any variable. """ grads_and_vars = self._momentum_optimizer.compute_gradients( loss, var_list=var_list, gate_gradients=gate_gradients, aggregation_method=aggregation_method, colocate_gradients_with_ops=colocate_gradients_with_ops, grad_loss=grad_loss) vars_with_grad = [v for g, v in grads_and_vars if g is not None] if not vars_with_grad: raise ValueError( "No gradients provided for any variable, check your graph for ops" " that do not support gradients, between variables %s and loss %s." % ([str(v) for _, v in grads_and_vars], loss)) for g, v in grads_and_vars: print("g ", g) print("v ", v) return self.apply_gradients(grads_and_vars, global_step=global_step, name=name)
[ "Adapted", "from", "TensorFlow", "Optimizer", "base", "class", "member", "function", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/yellowfin.py#L562-L622
[ "def", "minimize", "(", "self", ",", "loss", ",", "global_step", "=", "None", ",", "var_list", "=", "None", ",", "gate_gradients", "=", "GATE_OP", ",", "aggregation_method", "=", "None", ",", "colocate_gradients_with_ops", "=", "False", ",", "name", "=", "No...
272500b6efe353aeb638d2745ed56e519462ca31
train
residual_dilated_conv
A stack of convolution blocks with residual connections.
tensor2tensor/models/bytenet.py
def residual_dilated_conv(x, repeat, padding, name, hparams): """A stack of convolution blocks with residual connections.""" with tf.variable_scope(name): k = (hparams.kernel_height, hparams.kernel_width) dilations_and_kernels = [((2**i, 1), k) for i in range(hparams.num_hidden_layers)] for i in range(repeat): with tf.variable_scope("repeat_%d" % i): y = common_layers.conv_block( common_layers.layer_norm(x, hparams.hidden_size, name="lnorm"), hparams.hidden_size, dilations_and_kernels, padding=padding, name="residual_conv") y = tf.nn.dropout(y, 1.0 - hparams.dropout) x += y return x
def residual_dilated_conv(x, repeat, padding, name, hparams): """A stack of convolution blocks with residual connections.""" with tf.variable_scope(name): k = (hparams.kernel_height, hparams.kernel_width) dilations_and_kernels = [((2**i, 1), k) for i in range(hparams.num_hidden_layers)] for i in range(repeat): with tf.variable_scope("repeat_%d" % i): y = common_layers.conv_block( common_layers.layer_norm(x, hparams.hidden_size, name="lnorm"), hparams.hidden_size, dilations_and_kernels, padding=padding, name="residual_conv") y = tf.nn.dropout(y, 1.0 - hparams.dropout) x += y return x
[ "A", "stack", "of", "convolution", "blocks", "with", "residual", "connections", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/bytenet.py#L31-L47
[ "def", "residual_dilated_conv", "(", "x", ",", "repeat", ",", "padding", ",", "name", ",", "hparams", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ")", ":", "k", "=", "(", "hparams", ".", "kernel_height", ",", "hparams", ".", "kernel_width...
272500b6efe353aeb638d2745ed56e519462ca31
train
bytenet_internal
ByteNet, main step used for training.
tensor2tensor/models/bytenet.py
def bytenet_internal(inputs, targets, hparams): """ByteNet, main step used for training.""" with tf.variable_scope("bytenet"): # Flatten inputs and extend length by 50%. inputs = tf.expand_dims(common_layers.flatten4d3d(inputs), axis=2) extend_length = tf.to_int32(0.5 * tf.to_float(tf.shape(inputs)[1])) inputs_shape = inputs.shape.as_list() inputs = tf.pad(inputs, [[0, 0], [0, extend_length], [0, 0], [0, 0]]) inputs_shape[1] = None inputs.set_shape(inputs_shape) # Don't lose the other shapes when padding. # Pad inputs and targets to be the same length, divisible by 50. inputs, targets = common_layers.pad_to_same_length( inputs, targets, final_length_divisible_by=50) final_encoder = residual_dilated_conv(inputs, hparams.num_block_repeat, "SAME", "encoder", hparams) shifted_targets = common_layers.shift_right(targets) kernel = (hparams.kernel_height, hparams.kernel_width) decoder_start = common_layers.conv_block( tf.concat([final_encoder, shifted_targets], axis=3), hparams.hidden_size, [((1, 1), kernel)], padding="LEFT") return residual_dilated_conv(decoder_start, hparams.num_block_repeat, "LEFT", "decoder", hparams)
def bytenet_internal(inputs, targets, hparams): """ByteNet, main step used for training.""" with tf.variable_scope("bytenet"): # Flatten inputs and extend length by 50%. inputs = tf.expand_dims(common_layers.flatten4d3d(inputs), axis=2) extend_length = tf.to_int32(0.5 * tf.to_float(tf.shape(inputs)[1])) inputs_shape = inputs.shape.as_list() inputs = tf.pad(inputs, [[0, 0], [0, extend_length], [0, 0], [0, 0]]) inputs_shape[1] = None inputs.set_shape(inputs_shape) # Don't lose the other shapes when padding. # Pad inputs and targets to be the same length, divisible by 50. inputs, targets = common_layers.pad_to_same_length( inputs, targets, final_length_divisible_by=50) final_encoder = residual_dilated_conv(inputs, hparams.num_block_repeat, "SAME", "encoder", hparams) shifted_targets = common_layers.shift_right(targets) kernel = (hparams.kernel_height, hparams.kernel_width) decoder_start = common_layers.conv_block( tf.concat([final_encoder, shifted_targets], axis=3), hparams.hidden_size, [((1, 1), kernel)], padding="LEFT") return residual_dilated_conv(decoder_start, hparams.num_block_repeat, "LEFT", "decoder", hparams)
[ "ByteNet", "main", "step", "used", "for", "training", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/bytenet.py#L50-L74
[ "def", "bytenet_internal", "(", "inputs", ",", "targets", ",", "hparams", ")", ":", "with", "tf", ".", "variable_scope", "(", "\"bytenet\"", ")", ":", "# Flatten inputs and extend length by 50%.", "inputs", "=", "tf", ".", "expand_dims", "(", "common_layers", ".",...
272500b6efe353aeb638d2745ed56e519462ca31
train
bytenet_base
Set of hyperparameters.
tensor2tensor/models/bytenet.py
def bytenet_base(): """Set of hyperparameters.""" hparams = common_hparams.basic_params1() hparams.batch_size = 2048 hparams.hidden_size = 768 hparams.dropout = 0.2 hparams.symbol_dropout = 0.2 hparams.label_smoothing = 0.1 hparams.clip_grad_norm = 2.0 hparams.num_hidden_layers = 4 hparams.kernel_height = 3 hparams.kernel_width = 1 hparams.learning_rate_decay_scheme = "exp" hparams.learning_rate = 0.05 hparams.learning_rate_warmup_steps = 3000 hparams.initializer_gain = 1.0 hparams.weight_decay = 3.0 hparams.num_sampled_classes = 0 hparams.sampling_method = "argmax" hparams.optimizer_adam_epsilon = 1e-6 hparams.optimizer_adam_beta1 = 0.85 hparams.optimizer_adam_beta2 = 0.997 hparams.add_hparam("num_block_repeat", 4) return hparams
def bytenet_base(): """Set of hyperparameters.""" hparams = common_hparams.basic_params1() hparams.batch_size = 2048 hparams.hidden_size = 768 hparams.dropout = 0.2 hparams.symbol_dropout = 0.2 hparams.label_smoothing = 0.1 hparams.clip_grad_norm = 2.0 hparams.num_hidden_layers = 4 hparams.kernel_height = 3 hparams.kernel_width = 1 hparams.learning_rate_decay_scheme = "exp" hparams.learning_rate = 0.05 hparams.learning_rate_warmup_steps = 3000 hparams.initializer_gain = 1.0 hparams.weight_decay = 3.0 hparams.num_sampled_classes = 0 hparams.sampling_method = "argmax" hparams.optimizer_adam_epsilon = 1e-6 hparams.optimizer_adam_beta1 = 0.85 hparams.optimizer_adam_beta2 = 0.997 hparams.add_hparam("num_block_repeat", 4) return hparams
[ "Set", "of", "hyperparameters", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/bytenet.py#L86-L109
[ "def", "bytenet_base", "(", ")", ":", "hparams", "=", "common_hparams", ".", "basic_params1", "(", ")", "hparams", ".", "batch_size", "=", "2048", "hparams", ".", "hidden_size", "=", "768", "hparams", ".", "dropout", "=", "0.2", "hparams", ".", "symbol_dropo...
272500b6efe353aeb638d2745ed56e519462ca31
train
_download_and_parse_dataset
Downloads and prepairs the dataset to be parsed by the data_generator.
tensor2tensor/data_generators/snli.py
def _download_and_parse_dataset(tmp_dir, train): """Downloads and prepairs the dataset to be parsed by the data_generator.""" file_path = generator_utils.maybe_download(tmp_dir, _SNLI_ZIP, _SNLI_URL) zip_ref = zipfile.ZipFile(file_path, 'r') zip_ref.extractall(tmp_dir) zip_ref.close() file_name = 'train' if train else 'dev' dataset_file_path = os.path.join(tmp_dir, _SNLI_DATA_PATH % file_name) _parse_dataset(dataset_file_path, tmp_dir, train)
def _download_and_parse_dataset(tmp_dir, train): """Downloads and prepairs the dataset to be parsed by the data_generator.""" file_path = generator_utils.maybe_download(tmp_dir, _SNLI_ZIP, _SNLI_URL) zip_ref = zipfile.ZipFile(file_path, 'r') zip_ref.extractall(tmp_dir) zip_ref.close() file_name = 'train' if train else 'dev' dataset_file_path = os.path.join(tmp_dir, _SNLI_DATA_PATH % file_name) _parse_dataset(dataset_file_path, tmp_dir, train)
[ "Downloads", "and", "prepairs", "the", "dataset", "to", "be", "parsed", "by", "the", "data_generator", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/snli.py#L51-L60
[ "def", "_download_and_parse_dataset", "(", "tmp_dir", ",", "train", ")", ":", "file_path", "=", "generator_utils", ".", "maybe_download", "(", "tmp_dir", ",", "_SNLI_ZIP", ",", "_SNLI_URL", ")", "zip_ref", "=", "zipfile", ".", "ZipFile", "(", "file_path", ",", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
_get_tokens_and_tags
Parse str to tokens and pos tags.
tensor2tensor/data_generators/snli.py
def _get_tokens_and_tags(parse_str): """Parse str to tokens and pos tags.""" tokens = [] parse_split = parse_str.split(' ') for p in parse_split: assert p.startswith('(') or p.endswith(')') if p.endswith(')'): token = p.replace(')', '') tokens.append(token) return tokens
def _get_tokens_and_tags(parse_str): """Parse str to tokens and pos tags.""" tokens = [] parse_split = parse_str.split(' ') for p in parse_split: assert p.startswith('(') or p.endswith(')') if p.endswith(')'): token = p.replace(')', '') tokens.append(token) return tokens
[ "Parse", "str", "to", "tokens", "and", "pos", "tags", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/snli.py#L63-L73
[ "def", "_get_tokens_and_tags", "(", "parse_str", ")", ":", "tokens", "=", "[", "]", "parse_split", "=", "parse_str", ".", "split", "(", "' '", ")", "for", "p", "in", "parse_split", ":", "assert", "p", ".", "startswith", "(", "'('", ")", "or", "p", ".",...
272500b6efe353aeb638d2745ed56e519462ca31
train
_parse_dataset
Convert the dataset in to a simpler format. This function creates two files. One for being processed to produce a vocab and another to generate the data. Args: file_path: string, path to the file to parse. tmp_dir: string, path to the directory to output the files. train: bool, indicating if we are parsing the training set.
tensor2tensor/data_generators/snli.py
def _parse_dataset(file_path, tmp_dir, train): """Convert the dataset in to a simpler format. This function creates two files. One for being processed to produce a vocab and another to generate the data. Args: file_path: string, path to the file to parse. tmp_dir: string, path to the directory to output the files. train: bool, indicating if we are parsing the training set. """ input_path = file_path file_name = 'train' if train else 'dev' gen_output_path = os.path.join(tmp_dir, file_name + '.txt') example_output_path = os.path.join(tmp_dir, _EXAMPLES_FILE) print('input path: ' + input_path) print('gen_output_path: ' + gen_output_path) print('example_output_path: ' + example_output_path) input_file = tf.gfile.Open(input_path, mode='r') examples = [] for counter, line in enumerate(input_file): if counter == 0: # Ignore first line since its a header. continue # Get the token and embedding vector. line_split = line.split('\t') parse1 = line_split[_PARSE1_INDEX] parse2 = line_split[_PARSE2_INDEX] consensus_label = line_split[_LABEL_INDEX] tokens1 = _get_tokens_and_tags(parse1) tokens2 = _get_tokens_and_tags(parse2) tokens1_str = ' '.join(tokens1) tokens2_str = ' '.join(tokens2) if consensus_label != '-': examples.append([tokens1_str, tokens2_str, consensus_label]) input_file.close() # Output tab delimited file of lines of examples (sentence1, sentence2, label) with tf.gfile.GFile(gen_output_path, 'w') as f: for tokens1_str, tokens2_str, consensus_label in examples: f.write('%s\t%s\t%s\n' % (tokens1_str, tokens2_str, consensus_label)) if train: # Output file containing all the sentences for generating the vocab from. with tf.gfile.GFile(example_output_path, 'w') as f: for tokens1_str, tokens2_str, consensus_label in examples: f.write('%s %s\n' % (tokens1_str, tokens2_str))
def _parse_dataset(file_path, tmp_dir, train): """Convert the dataset in to a simpler format. This function creates two files. One for being processed to produce a vocab and another to generate the data. Args: file_path: string, path to the file to parse. tmp_dir: string, path to the directory to output the files. train: bool, indicating if we are parsing the training set. """ input_path = file_path file_name = 'train' if train else 'dev' gen_output_path = os.path.join(tmp_dir, file_name + '.txt') example_output_path = os.path.join(tmp_dir, _EXAMPLES_FILE) print('input path: ' + input_path) print('gen_output_path: ' + gen_output_path) print('example_output_path: ' + example_output_path) input_file = tf.gfile.Open(input_path, mode='r') examples = [] for counter, line in enumerate(input_file): if counter == 0: # Ignore first line since its a header. continue # Get the token and embedding vector. line_split = line.split('\t') parse1 = line_split[_PARSE1_INDEX] parse2 = line_split[_PARSE2_INDEX] consensus_label = line_split[_LABEL_INDEX] tokens1 = _get_tokens_and_tags(parse1) tokens2 = _get_tokens_and_tags(parse2) tokens1_str = ' '.join(tokens1) tokens2_str = ' '.join(tokens2) if consensus_label != '-': examples.append([tokens1_str, tokens2_str, consensus_label]) input_file.close() # Output tab delimited file of lines of examples (sentence1, sentence2, label) with tf.gfile.GFile(gen_output_path, 'w') as f: for tokens1_str, tokens2_str, consensus_label in examples: f.write('%s\t%s\t%s\n' % (tokens1_str, tokens2_str, consensus_label)) if train: # Output file containing all the sentences for generating the vocab from. with tf.gfile.GFile(example_output_path, 'w') as f: for tokens1_str, tokens2_str, consensus_label in examples: f.write('%s %s\n' % (tokens1_str, tokens2_str))
[ "Convert", "the", "dataset", "in", "to", "a", "simpler", "format", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/snli.py#L76-L128
[ "def", "_parse_dataset", "(", "file_path", ",", "tmp_dir", ",", "train", ")", ":", "input_path", "=", "file_path", "file_name", "=", "'train'", "if", "train", "else", "'dev'", "gen_output_path", "=", "os", ".", "path", ".", "join", "(", "tmp_dir", ",", "fi...
272500b6efe353aeb638d2745ed56e519462ca31
train
_get_or_generate_vocab
Read or create vocabulary.
tensor2tensor/data_generators/snli.py
def _get_or_generate_vocab(tmp_dir, vocab_filename, vocab_size): """Read or create vocabulary.""" vocab_filepath = os.path.join(tmp_dir, vocab_filename) print('Vocab file written to: ' + vocab_filepath) if tf.gfile.Exists(vocab_filepath): gs = text_encoder.SubwordTextEncoder(vocab_filepath) return gs example_file = os.path.join(tmp_dir, _EXAMPLES_FILE) gs = text_encoder.SubwordTextEncoder() token_counts = tokenizer.corpus_token_counts( example_file, corpus_max_lines=1000000) gs = gs.build_to_target_size( vocab_size, token_counts, min_val=1, max_val=1e3) gs.store_to_file(vocab_filepath) return gs
def _get_or_generate_vocab(tmp_dir, vocab_filename, vocab_size): """Read or create vocabulary.""" vocab_filepath = os.path.join(tmp_dir, vocab_filename) print('Vocab file written to: ' + vocab_filepath) if tf.gfile.Exists(vocab_filepath): gs = text_encoder.SubwordTextEncoder(vocab_filepath) return gs example_file = os.path.join(tmp_dir, _EXAMPLES_FILE) gs = text_encoder.SubwordTextEncoder() token_counts = tokenizer.corpus_token_counts( example_file, corpus_max_lines=1000000) gs = gs.build_to_target_size( vocab_size, token_counts, min_val=1, max_val=1e3) gs.store_to_file(vocab_filepath) return gs
[ "Read", "or", "create", "vocabulary", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/snli.py#L131-L146
[ "def", "_get_or_generate_vocab", "(", "tmp_dir", ",", "vocab_filename", ",", "vocab_size", ")", ":", "vocab_filepath", "=", "os", ".", "path", ".", "join", "(", "tmp_dir", ",", "vocab_filename", ")", "print", "(", "'Vocab file written to: '", "+", "vocab_filepath"...
272500b6efe353aeb638d2745ed56e519462ca31
train
snli_token_generator
Generate example dicts.
tensor2tensor/data_generators/snli.py
def snli_token_generator(tmp_dir, train, vocab_size): """Generate example dicts.""" _download_and_parse_dataset(tmp_dir, train) symbolizer_vocab = _get_or_generate_vocab( tmp_dir, 'vocab.subword_text_encoder', vocab_size) file_name = 'train' if train else 'dev' data_file = os.path.join(tmp_dir, file_name + '.txt') with tf.gfile.GFile(data_file, mode='r') as f: for line in f: sent1, sent2, label = line.strip().split('\t') sent1_enc = symbolizer_vocab.encode(sent1) sent2_enc = symbolizer_vocab.encode(sent2) inputs = sent1_enc + [_SEP] + sent2_enc + [_EOS] yield { 'inputs': inputs, 'targets': [_LABEL_TO_ID[label]], }
def snli_token_generator(tmp_dir, train, vocab_size): """Generate example dicts.""" _download_and_parse_dataset(tmp_dir, train) symbolizer_vocab = _get_or_generate_vocab( tmp_dir, 'vocab.subword_text_encoder', vocab_size) file_name = 'train' if train else 'dev' data_file = os.path.join(tmp_dir, file_name + '.txt') with tf.gfile.GFile(data_file, mode='r') as f: for line in f: sent1, sent2, label = line.strip().split('\t') sent1_enc = symbolizer_vocab.encode(sent1) sent2_enc = symbolizer_vocab.encode(sent2) inputs = sent1_enc + [_SEP] + sent2_enc + [_EOS] yield { 'inputs': inputs, 'targets': [_LABEL_TO_ID[label]], }
[ "Generate", "example", "dicts", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/snli.py#L149-L168
[ "def", "snli_token_generator", "(", "tmp_dir", ",", "train", ",", "vocab_size", ")", ":", "_download_and_parse_dataset", "(", "tmp_dir", ",", "train", ")", "symbolizer_vocab", "=", "_get_or_generate_vocab", "(", "tmp_dir", ",", "'vocab.subword_text_encoder'", ",", "vo...
272500b6efe353aeb638d2745ed56e519462ca31
train
shard
Split items into num_shards groups.
tensor2tensor/data_generators/wikisum/get_references_web_single_group.py
def shard(items, num_shards): """Split items into num_shards groups.""" sharded = [] num_per_shard = len(items) // num_shards start = 0 for _ in range(num_shards): sharded.append(items[start:start + num_per_shard]) start += num_per_shard remainder = len(items) % num_shards start = len(items) - remainder for i in range(remainder): sharded[i].append(items[start + i]) assert sum([len(fs) for fs in sharded]) == len(items) return sharded
def shard(items, num_shards): """Split items into num_shards groups.""" sharded = [] num_per_shard = len(items) // num_shards start = 0 for _ in range(num_shards): sharded.append(items[start:start + num_per_shard]) start += num_per_shard remainder = len(items) % num_shards start = len(items) - remainder for i in range(remainder): sharded[i].append(items[start + i]) assert sum([len(fs) for fs in sharded]) == len(items) return sharded
[ "Split", "items", "into", "num_shards", "groups", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wikisum/get_references_web_single_group.py#L87-L102
[ "def", "shard", "(", "items", ",", "num_shards", ")", ":", "sharded", "=", "[", "]", "num_per_shard", "=", "len", "(", "items", ")", "//", "num_shards", "start", "=", "0", "for", "_", "in", "range", "(", "num_shards", ")", ":", "sharded", ".", "appen...
272500b6efe353aeb638d2745ed56e519462ca31
train
RandomNormalInitializer
An initializer function for random normal coefficients.
tensor2tensor/trax/layers/core.py
def RandomNormalInitializer(stddev=1e-2): """An initializer function for random normal coefficients.""" def init(shape, rng): return (stddev * backend.random.normal(rng, shape)).astype('float32') return init
def RandomNormalInitializer(stddev=1e-2): """An initializer function for random normal coefficients.""" def init(shape, rng): return (stddev * backend.random.normal(rng, shape)).astype('float32') return init
[ "An", "initializer", "function", "for", "random", "normal", "coefficients", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/core.py#L42-L46
[ "def", "RandomNormalInitializer", "(", "stddev", "=", "1e-2", ")", ":", "def", "init", "(", "shape", ",", "rng", ")", ":", "return", "(", "stddev", "*", "backend", ".", "random", ".", "normal", "(", "rng", ",", "shape", ")", ")", ".", "astype", "(", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
GlorotNormalInitializer
An initializer function for random Glorot-scaled coefficients.
tensor2tensor/trax/layers/core.py
def GlorotNormalInitializer(out_dim=0, in_dim=1, scale=onp.sqrt(2)): """An initializer function for random Glorot-scaled coefficients.""" def init(shape, rng): fan_in, fan_out = shape[in_dim], shape[out_dim] size = onp.prod(onp.delete(shape, [in_dim, out_dim])) std = scale / np.sqrt((fan_in + fan_out) / 2. * size) return (std * backend.random.normal(rng, shape)).astype('float32') return init
def GlorotNormalInitializer(out_dim=0, in_dim=1, scale=onp.sqrt(2)): """An initializer function for random Glorot-scaled coefficients.""" def init(shape, rng): fan_in, fan_out = shape[in_dim], shape[out_dim] size = onp.prod(onp.delete(shape, [in_dim, out_dim])) std = scale / np.sqrt((fan_in + fan_out) / 2. * size) return (std * backend.random.normal(rng, shape)).astype('float32') return init
[ "An", "initializer", "function", "for", "random", "Glorot", "-", "scaled", "coefficients", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/core.py#L49-L56
[ "def", "GlorotNormalInitializer", "(", "out_dim", "=", "0", ",", "in_dim", "=", "1", ",", "scale", "=", "onp", ".", "sqrt", "(", "2", ")", ")", ":", "def", "init", "(", "shape", ",", "rng", ")", ":", "fan_in", ",", "fan_out", "=", "shape", "[", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
GlorotUniformInitializer
An initializer function for random uniform Glorot-scaled coefficients.
tensor2tensor/trax/layers/core.py
def GlorotUniformInitializer(out_dim=0, in_dim=1): """An initializer function for random uniform Glorot-scaled coefficients.""" def init(shape, rng): fan_in, fan_out = shape[in_dim], shape[out_dim] std = np.sqrt(2.0 / (fan_in + fan_out)) a = np.sqrt(3.0) * std return backend.random.uniform(rng, shape, minval=-a, maxval=a) return init
def GlorotUniformInitializer(out_dim=0, in_dim=1): """An initializer function for random uniform Glorot-scaled coefficients.""" def init(shape, rng): fan_in, fan_out = shape[in_dim], shape[out_dim] std = np.sqrt(2.0 / (fan_in + fan_out)) a = np.sqrt(3.0) * std return backend.random.uniform(rng, shape, minval=-a, maxval=a) return init
[ "An", "initializer", "function", "for", "random", "uniform", "Glorot", "-", "scaled", "coefficients", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/core.py#L59-L66
[ "def", "GlorotUniformInitializer", "(", "out_dim", "=", "0", ",", "in_dim", "=", "1", ")", ":", "def", "init", "(", "shape", ",", "rng", ")", ":", "fan_in", ",", "fan_out", "=", "shape", "[", "in_dim", "]", ",", "shape", "[", "out_dim", "]", "std", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
one_hot
Make a n+1 dim one-hot array from n dim int-categorical array.
tensor2tensor/trax/layers/core.py
def one_hot(x, size, dtype=np.float32): """Make a n+1 dim one-hot array from n dim int-categorical array.""" return np.array(x[..., np.newaxis] == np.arange(size), dtype)
def one_hot(x, size, dtype=np.float32): """Make a n+1 dim one-hot array from n dim int-categorical array.""" return np.array(x[..., np.newaxis] == np.arange(size), dtype)
[ "Make", "a", "n", "+", "1", "dim", "one", "-", "hot", "array", "from", "n", "dim", "int", "-", "categorical", "array", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/core.py#L69-L71
[ "def", "one_hot", "(", "x", ",", "size", ",", "dtype", "=", "np", ".", "float32", ")", ":", "return", "np", ".", "array", "(", "x", "[", "...", ",", "np", ".", "newaxis", "]", "==", "np", ".", "arange", "(", "size", ")", ",", "dtype", ")" ]
272500b6efe353aeb638d2745ed56e519462ca31
train
LogSoftmax
Apply log softmax to x: log-normalize along the given axis.
tensor2tensor/trax/layers/core.py
def LogSoftmax(x, params, axis=-1, **kwargs): """Apply log softmax to x: log-normalize along the given axis.""" del params, kwargs return x - backend.logsumexp(x, axis, keepdims=True)
def LogSoftmax(x, params, axis=-1, **kwargs): """Apply log softmax to x: log-normalize along the given axis.""" del params, kwargs return x - backend.logsumexp(x, axis, keepdims=True)
[ "Apply", "log", "softmax", "to", "x", ":", "log", "-", "normalize", "along", "the", "given", "axis", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/core.py#L116-L119
[ "def", "LogSoftmax", "(", "x", ",", "params", ",", "axis", "=", "-", "1", ",", "*", "*", "kwargs", ")", ":", "del", "params", ",", "kwargs", "return", "x", "-", "backend", ".", "logsumexp", "(", "x", ",", "axis", ",", "keepdims", "=", "True", ")"...
272500b6efe353aeb638d2745ed56e519462ca31
train
Softmax
Apply softmax to x: exponentiate and normalize along the given axis.
tensor2tensor/trax/layers/core.py
def Softmax(x, params, axis=-1, **kwargs): """Apply softmax to x: exponentiate and normalize along the given axis.""" del params, kwargs return np.exp(x - backend.logsumexp(x, axis, keepdims=True))
def Softmax(x, params, axis=-1, **kwargs): """Apply softmax to x: exponentiate and normalize along the given axis.""" del params, kwargs return np.exp(x - backend.logsumexp(x, axis, keepdims=True))
[ "Apply", "softmax", "to", "x", ":", "exponentiate", "and", "normalize", "along", "the", "given", "axis", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/core.py#L123-L126
[ "def", "Softmax", "(", "x", ",", "params", ",", "axis", "=", "-", "1", ",", "*", "*", "kwargs", ")", ":", "del", "params", ",", "kwargs", "return", "np", ".", "exp", "(", "x", "-", "backend", ".", "logsumexp", "(", "x", ",", "axis", ",", "keepd...
272500b6efe353aeb638d2745ed56e519462ca31
train
padtype_to_pads
Convert padding string to list of pairs of pad values.
tensor2tensor/trax/layers/core.py
def padtype_to_pads(in_shape, window_shape, window_strides, padding): """Convert padding string to list of pairs of pad values.""" padding = padding.upper() if padding == 'SAME': out_shape = onp.ceil( onp.true_divide(in_shape, window_strides)).astype(int) pad_sizes = [max((out_size - 1) * stride + window_shape - in_size, 0) for out_size, stride, window_shape, in_size in zip(out_shape, window_strides, window_shape, in_shape)] return [(pad_size // 2, pad_size - pad_size // 2) for pad_size in pad_sizes] elif padding == 'VALID': return [(0, 0)] * len(in_shape) else: msg = 'Unknown padding type: {}.' raise TypeError(msg.format(padding))
def padtype_to_pads(in_shape, window_shape, window_strides, padding): """Convert padding string to list of pairs of pad values.""" padding = padding.upper() if padding == 'SAME': out_shape = onp.ceil( onp.true_divide(in_shape, window_strides)).astype(int) pad_sizes = [max((out_size - 1) * stride + window_shape - in_size, 0) for out_size, stride, window_shape, in_size in zip(out_shape, window_strides, window_shape, in_shape)] return [(pad_size // 2, pad_size - pad_size // 2) for pad_size in pad_sizes] elif padding == 'VALID': return [(0, 0)] * len(in_shape) else: msg = 'Unknown padding type: {}.' raise TypeError(msg.format(padding))
[ "Convert", "padding", "string", "to", "list", "of", "pairs", "of", "pad", "values", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/core.py#L181-L196
[ "def", "padtype_to_pads", "(", "in_shape", ",", "window_shape", ",", "window_strides", ",", "padding", ")", ":", "padding", "=", "padding", ".", "upper", "(", ")", "if", "padding", "==", "'SAME'", ":", "out_shape", "=", "onp", ".", "ceil", "(", "onp", "....
272500b6efe353aeb638d2745ed56e519462ca31
train
_flatten_output_shape
Output shape of a flatten layer.
tensor2tensor/trax/layers/core.py
def _flatten_output_shape(input_shape, num_axis_to_keep=1): """Output shape of a flatten layer.""" if num_axis_to_keep >= len(input_shape): raise ValueError( "num_axis_to_keep[%d] should be less than input's rank[%d]" % (num_axis_to_keep, len(input_shape))) return tuple(input_shape[:num_axis_to_keep]) + ( reduce(op.mul, input_shape[num_axis_to_keep:], 1),)
def _flatten_output_shape(input_shape, num_axis_to_keep=1): """Output shape of a flatten layer.""" if num_axis_to_keep >= len(input_shape): raise ValueError( "num_axis_to_keep[%d] should be less than input's rank[%d]" % (num_axis_to_keep, len(input_shape))) return tuple(input_shape[:num_axis_to_keep]) + ( reduce(op.mul, input_shape[num_axis_to_keep:], 1),)
[ "Output", "shape", "of", "a", "flatten", "layer", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/core.py#L304-L311
[ "def", "_flatten_output_shape", "(", "input_shape", ",", "num_axis_to_keep", "=", "1", ")", ":", "if", "num_axis_to_keep", ">=", "len", "(", "input_shape", ")", ":", "raise", "ValueError", "(", "\"num_axis_to_keep[%d] should be less than input's rank[%d]\"", "%", "(", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
_batch_norm_new_params
Helper to initialize batch norm params.
tensor2tensor/trax/layers/core.py
def _batch_norm_new_params(input_shape, rng, axis=(0, 1, 2), center=True, scale=True, **kwargs): """Helper to initialize batch norm params.""" del rng, kwargs axis = (axis,) if np.isscalar(axis) else axis shape = tuple(d for i, d in enumerate(input_shape) if i not in axis) beta = np.zeros(shape, dtype='float32') if center else () gamma = np.ones(shape, dtype='float32') if scale else () return (beta, gamma)
def _batch_norm_new_params(input_shape, rng, axis=(0, 1, 2), center=True, scale=True, **kwargs): """Helper to initialize batch norm params.""" del rng, kwargs axis = (axis,) if np.isscalar(axis) else axis shape = tuple(d for i, d in enumerate(input_shape) if i not in axis) beta = np.zeros(shape, dtype='float32') if center else () gamma = np.ones(shape, dtype='float32') if scale else () return (beta, gamma)
[ "Helper", "to", "initialize", "batch", "norm", "params", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/core.py#L321-L329
[ "def", "_batch_norm_new_params", "(", "input_shape", ",", "rng", ",", "axis", "=", "(", "0", ",", "1", ",", "2", ")", ",", "center", "=", "True", ",", "scale", "=", "True", ",", "*", "*", "kwargs", ")", ":", "del", "rng", ",", "kwargs", "axis", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
BatchNorm
Layer construction function for a batch normalization layer.
tensor2tensor/trax/layers/core.py
def BatchNorm(x, params, axis=(0, 1, 2), epsilon=1e-5, center=True, scale=True, **unused_kwargs): """Layer construction function for a batch normalization layer.""" mean = np.mean(x, axis, keepdims=True) # Fast but less numerically-stable variance calculation than np.var. m1 = np.mean(x**2, axis, keepdims=True) var = m1 - mean**2 z = (x - mean) / np.sqrt(var + epsilon) # Expand the parameters to have the right axes. beta, gamma = params # TODO(phawkins): np.expand_dims should accept an axis tuple. # (https://github.com/numpy/numpy/issues/12290) ed = tuple(None if i in axis else slice(None) for i in range(np.ndim(x))) beta = beta[ed] gamma = gamma[ed] # Return the z rescaled by the parameters if requested. if center and scale: return gamma * z + beta if center: return z + beta if scale: return gamma * z return z
def BatchNorm(x, params, axis=(0, 1, 2), epsilon=1e-5, center=True, scale=True, **unused_kwargs): """Layer construction function for a batch normalization layer.""" mean = np.mean(x, axis, keepdims=True) # Fast but less numerically-stable variance calculation than np.var. m1 = np.mean(x**2, axis, keepdims=True) var = m1 - mean**2 z = (x - mean) / np.sqrt(var + epsilon) # Expand the parameters to have the right axes. beta, gamma = params # TODO(phawkins): np.expand_dims should accept an axis tuple. # (https://github.com/numpy/numpy/issues/12290) ed = tuple(None if i in axis else slice(None) for i in range(np.ndim(x))) beta = beta[ed] gamma = gamma[ed] # Return the z rescaled by the parameters if requested. if center and scale: return gamma * z + beta if center: return z + beta if scale: return gamma * z return z
[ "Layer", "construction", "function", "for", "a", "batch", "normalization", "layer", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/core.py#L333-L357
[ "def", "BatchNorm", "(", "x", ",", "params", ",", "axis", "=", "(", "0", ",", "1", ",", "2", ")", ",", "epsilon", "=", "1e-5", ",", "center", "=", "True", ",", "scale", "=", "True", ",", "*", "*", "unused_kwargs", ")", ":", "mean", "=", "np", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
_pooling_output_shape
Helper: compute the output shape for the pooling layer.
tensor2tensor/trax/layers/core.py
def _pooling_output_shape(input_shape, pool_size=(2, 2), strides=None, padding='VALID'): """Helper: compute the output shape for the pooling layer.""" dims = (1,) + pool_size + (1,) # NHWC spatial_strides = strides or (1,) * len(pool_size) strides = (1,) + spatial_strides + (1,) pads = padtype_to_pads(input_shape, dims, strides, padding) operand_padded = onp.add(input_shape, onp.add(*zip(*pads))) t = onp.floor_divide(onp.subtract(operand_padded, dims), strides) + 1 return tuple(t)
def _pooling_output_shape(input_shape, pool_size=(2, 2), strides=None, padding='VALID'): """Helper: compute the output shape for the pooling layer.""" dims = (1,) + pool_size + (1,) # NHWC spatial_strides = strides or (1,) * len(pool_size) strides = (1,) + spatial_strides + (1,) pads = padtype_to_pads(input_shape, dims, strides, padding) operand_padded = onp.add(input_shape, onp.add(*zip(*pads))) t = onp.floor_divide(onp.subtract(operand_padded, dims), strides) + 1 return tuple(t)
[ "Helper", ":", "compute", "the", "output", "shape", "for", "the", "pooling", "layer", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/core.py#L361-L370
[ "def", "_pooling_output_shape", "(", "input_shape", ",", "pool_size", "=", "(", "2", ",", "2", ")", ",", "strides", "=", "None", ",", "padding", "=", "'VALID'", ")", ":", "dims", "=", "(", "1", ",", ")", "+", "pool_size", "+", "(", "1", ",", ")", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
_pooling_general
Helper: general pooling computation used in pooling layers later.
tensor2tensor/trax/layers/core.py
def _pooling_general(inputs, reducer, init_val, rescaler=None, pool_size=(2, 2), strides=None, padding='VALID'): """Helper: general pooling computation used in pooling layers later.""" spatial_strides = strides or (1,) * len(pool_size) rescale = rescaler(pool_size, spatial_strides, padding) if rescaler else None dims = (1,) + pool_size + (1,) # NHWC strides = (1,) + spatial_strides + (1,) out = lax.reduce_window(inputs, init_val, reducer, dims, strides, padding) return rescale(out, inputs) if rescale else out
def _pooling_general(inputs, reducer, init_val, rescaler=None, pool_size=(2, 2), strides=None, padding='VALID'): """Helper: general pooling computation used in pooling layers later.""" spatial_strides = strides or (1,) * len(pool_size) rescale = rescaler(pool_size, spatial_strides, padding) if rescaler else None dims = (1,) + pool_size + (1,) # NHWC strides = (1,) + spatial_strides + (1,) out = lax.reduce_window(inputs, init_val, reducer, dims, strides, padding) return rescale(out, inputs) if rescale else out
[ "Helper", ":", "general", "pooling", "computation", "used", "in", "pooling", "layers", "later", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/core.py#L373-L381
[ "def", "_pooling_general", "(", "inputs", ",", "reducer", ",", "init_val", ",", "rescaler", "=", "None", ",", "pool_size", "=", "(", "2", ",", "2", ")", ",", "strides", "=", "None", ",", "padding", "=", "'VALID'", ")", ":", "spatial_strides", "=", "str...
272500b6efe353aeb638d2745ed56e519462ca31
train
Dropout
Layer construction function for a dropout layer with given rate.
tensor2tensor/trax/layers/core.py
def Dropout(x, params, rate=0.0, mode='train', rng=None, **kwargs): """Layer construction function for a dropout layer with given rate.""" del params, kwargs if rng is None: msg = ('Dropout layer requires apply_fun to be called with a rng keyword ' 'argument. That is, instead of `Dropout(params, inputs)`, call ' 'it like `Dropout(params, inputs, rng=key)`.') raise ValueError(msg) if rate >= 1.0: raise ValueError('Dropout rate (%f) must be lower than 1.' % rate) if mode == 'train' and rate > 0.0: keep = backend.random.bernoulli(rng, 1.0 - rate, x.shape) return np.where(keep, x / (1.0 - rate), 0) else: return x
def Dropout(x, params, rate=0.0, mode='train', rng=None, **kwargs): """Layer construction function for a dropout layer with given rate.""" del params, kwargs if rng is None: msg = ('Dropout layer requires apply_fun to be called with a rng keyword ' 'argument. That is, instead of `Dropout(params, inputs)`, call ' 'it like `Dropout(params, inputs, rng=key)`.') raise ValueError(msg) if rate >= 1.0: raise ValueError('Dropout rate (%f) must be lower than 1.' % rate) if mode == 'train' and rate > 0.0: keep = backend.random.bernoulli(rng, 1.0 - rate, x.shape) return np.where(keep, x / (1.0 - rate), 0) else: return x
[ "Layer", "construction", "function", "for", "a", "dropout", "layer", "with", "given", "rate", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/core.py#L415-L429
[ "def", "Dropout", "(", "x", ",", "params", ",", "rate", "=", "0.0", ",", "mode", "=", "'train'", ",", "rng", "=", "None", ",", "*", "*", "kwargs", ")", ":", "del", "params", ",", "kwargs", "if", "rng", "is", "None", ":", "msg", "=", "(", "'Drop...
272500b6efe353aeb638d2745ed56e519462ca31
train
Conv._kernel_shape
Helper to calculate the kernel shape.
tensor2tensor/trax/layers/core.py
def _kernel_shape(self, input_shape): """Helper to calculate the kernel shape.""" kernel_size_iter = iter(self._kernel_size) return [self._filters if c == 'O' else input_shape[self._lhs_spec.index('C')] if c == 'I' else next(kernel_size_iter) for c in self._rhs_spec]
def _kernel_shape(self, input_shape): """Helper to calculate the kernel shape.""" kernel_size_iter = iter(self._kernel_size) return [self._filters if c == 'O' else input_shape[self._lhs_spec.index('C')] if c == 'I' else next(kernel_size_iter) for c in self._rhs_spec]
[ "Helper", "to", "calculate", "the", "kernel", "shape", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/core.py#L226-L231
[ "def", "_kernel_shape", "(", "self", ",", "input_shape", ")", ":", "kernel_size_iter", "=", "iter", "(", "self", ".", "_kernel_size", ")", "return", "[", "self", ".", "_filters", "if", "c", "==", "'O'", "else", "input_shape", "[", "self", ".", "_lhs_spec",...
272500b6efe353aeb638d2745ed56e519462ca31
train
Conv._conv_shape_tuple
Compute the shape of a conv given input shapes in canonical order.
tensor2tensor/trax/layers/core.py
def _conv_shape_tuple(self, lhs_shape, rhs_shape, strides, pads): """Compute the shape of a conv given input shapes in canonical order.""" if isinstance(pads, str): pads = padtype_to_pads(lhs_shape[2:], rhs_shape[2:], strides, pads) if len(pads) != len(lhs_shape) - 2: msg = 'Wrong number of explicit pads for conv: expected {}, got {}.' raise TypeError(msg.format(len(lhs_shape) - 2, len(pads))) lhs_padded = onp.add(lhs_shape[2:], onp.add(*zip(*pads))) out_space = onp.floor_divide( onp.subtract(lhs_padded, rhs_shape[2:]), strides) + 1 out_space = onp.maximum(0, out_space) out_shape = (lhs_shape[0], rhs_shape[0]) + tuple(out_space) return tuple(out_shape)
def _conv_shape_tuple(self, lhs_shape, rhs_shape, strides, pads): """Compute the shape of a conv given input shapes in canonical order.""" if isinstance(pads, str): pads = padtype_to_pads(lhs_shape[2:], rhs_shape[2:], strides, pads) if len(pads) != len(lhs_shape) - 2: msg = 'Wrong number of explicit pads for conv: expected {}, got {}.' raise TypeError(msg.format(len(lhs_shape) - 2, len(pads))) lhs_padded = onp.add(lhs_shape[2:], onp.add(*zip(*pads))) out_space = onp.floor_divide( onp.subtract(lhs_padded, rhs_shape[2:]), strides) + 1 out_space = onp.maximum(0, out_space) out_shape = (lhs_shape[0], rhs_shape[0]) + tuple(out_space) return tuple(out_shape)
[ "Compute", "the", "shape", "of", "a", "conv", "given", "input", "shapes", "in", "canonical", "order", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/core.py#L233-L245
[ "def", "_conv_shape_tuple", "(", "self", ",", "lhs_shape", ",", "rhs_shape", ",", "strides", ",", "pads", ")", ":", "if", "isinstance", "(", "pads", ",", "str", ")", ":", "pads", "=", "padtype_to_pads", "(", "lhs_shape", "[", "2", ":", "]", ",", "rhs_s...
272500b6efe353aeb638d2745ed56e519462ca31
train
Conv._conv_general_permutations
Utility for convolution dimension permutations relative to Conv HLO.
tensor2tensor/trax/layers/core.py
def _conv_general_permutations(self, dimension_numbers): """Utility for convolution dimension permutations relative to Conv HLO.""" lhs_spec, rhs_spec, out_spec = dimension_numbers lhs_char, rhs_char, out_char = ('N', 'C'), ('O', 'I'), ('N', 'C') charpairs = (lhs_char, rhs_char, out_char) for i, (a, b) in enumerate(charpairs): if not (dimension_numbers[i].count(a) == 1 and dimension_numbers[i].count(b) == 1): msg = ('convolution dimension_numbers[{}] must contain the characters ' '"{}" and "{}" exatly once, got {}.') raise TypeError(msg.format(i, a, b, dimension_numbers[i])) if len(dimension_numbers[i]) != len(set(dimension_numbers[i])): msg = ('convolution dimension_numbers[{}] cannot have duplicate ' 'characters, got {}.') raise TypeError(msg.format(i, dimension_numbers[i])) if not (set(lhs_spec) - set(lhs_char) == set(rhs_spec) - set(rhs_char) == set(out_spec) - set(out_char)): msg = ('convolution dimension_numbers elements must each have the same ' 'set of spatial characters, got {}.') raise TypeError(msg.format(dimension_numbers)) def getperm(spec, charpair): spatial = (i for i, c in enumerate(spec) if c not in charpair) if spec is not rhs_spec: spatial = sorted(spatial, key=lambda i: rhs_spec.index(spec[i])) return (spec.index(charpair[0]), spec.index(charpair[1])) + tuple(spatial) lhs_perm, rhs_perm, out_perm = map(getperm, dimension_numbers, charpairs) return lhs_perm, rhs_perm, out_perm
def _conv_general_permutations(self, dimension_numbers): """Utility for convolution dimension permutations relative to Conv HLO.""" lhs_spec, rhs_spec, out_spec = dimension_numbers lhs_char, rhs_char, out_char = ('N', 'C'), ('O', 'I'), ('N', 'C') charpairs = (lhs_char, rhs_char, out_char) for i, (a, b) in enumerate(charpairs): if not (dimension_numbers[i].count(a) == 1 and dimension_numbers[i].count(b) == 1): msg = ('convolution dimension_numbers[{}] must contain the characters ' '"{}" and "{}" exatly once, got {}.') raise TypeError(msg.format(i, a, b, dimension_numbers[i])) if len(dimension_numbers[i]) != len(set(dimension_numbers[i])): msg = ('convolution dimension_numbers[{}] cannot have duplicate ' 'characters, got {}.') raise TypeError(msg.format(i, dimension_numbers[i])) if not (set(lhs_spec) - set(lhs_char) == set(rhs_spec) - set(rhs_char) == set(out_spec) - set(out_char)): msg = ('convolution dimension_numbers elements must each have the same ' 'set of spatial characters, got {}.') raise TypeError(msg.format(dimension_numbers)) def getperm(spec, charpair): spatial = (i for i, c in enumerate(spec) if c not in charpair) if spec is not rhs_spec: spatial = sorted(spatial, key=lambda i: rhs_spec.index(spec[i])) return (spec.index(charpair[0]), spec.index(charpair[1])) + tuple(spatial) lhs_perm, rhs_perm, out_perm = map(getperm, dimension_numbers, charpairs) return lhs_perm, rhs_perm, out_perm
[ "Utility", "for", "convolution", "dimension", "permutations", "relative", "to", "Conv", "HLO", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/core.py#L247-L275
[ "def", "_conv_general_permutations", "(", "self", ",", "dimension_numbers", ")", ":", "lhs_spec", ",", "rhs_spec", ",", "out_spec", "=", "dimension_numbers", "lhs_char", ",", "rhs_char", ",", "out_char", "=", "(", "'N'", ",", "'C'", ")", ",", "(", "'O'", ","...
272500b6efe353aeb638d2745ed56e519462ca31
train
Conv._conv_general_shape_tuple
Generalized computation of conv shape.
tensor2tensor/trax/layers/core.py
def _conv_general_shape_tuple(self, lhs_shape, rhs_shape, window_strides, padding, dimension_numbers): """Generalized computation of conv shape.""" lhs_perm, rhs_perm, out_perm = self._conv_general_permutations( dimension_numbers) lhs_trans = onp.take(lhs_shape, lhs_perm) rhs_trans = onp.take(rhs_shape, rhs_perm) out_trans = self._conv_shape_tuple( lhs_trans, rhs_trans, window_strides, padding) return tuple(onp.take(out_trans, onp.argsort(out_perm)))
def _conv_general_shape_tuple(self, lhs_shape, rhs_shape, window_strides, padding, dimension_numbers): """Generalized computation of conv shape.""" lhs_perm, rhs_perm, out_perm = self._conv_general_permutations( dimension_numbers) lhs_trans = onp.take(lhs_shape, lhs_perm) rhs_trans = onp.take(rhs_shape, rhs_perm) out_trans = self._conv_shape_tuple( lhs_trans, rhs_trans, window_strides, padding) return tuple(onp.take(out_trans, onp.argsort(out_perm)))
[ "Generalized", "computation", "of", "conv", "shape", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/core.py#L277-L286
[ "def", "_conv_general_shape_tuple", "(", "self", ",", "lhs_shape", ",", "rhs_shape", ",", "window_strides", ",", "padding", ",", "dimension_numbers", ")", ":", "lhs_perm", ",", "rhs_perm", ",", "out_perm", "=", "self", ".", "_conv_general_permutations", "(", "dime...
272500b6efe353aeb638d2745ed56e519462ca31
train
get_create_agent
Factory for dopamine agent initialization. Args: agent_kwargs: dict of BatchDQNAgent parameters Returns: Function(sess, environment, summary_writer) -> BatchDQNAgent instance.
tensor2tensor/rl/dopamine_connector.py
def get_create_agent(agent_kwargs): """Factory for dopamine agent initialization. Args: agent_kwargs: dict of BatchDQNAgent parameters Returns: Function(sess, environment, summary_writer) -> BatchDQNAgent instance. """ def create_agent(sess, environment, summary_writer=None): """Creates a DQN agent. Simplified version of `dopamine.discrete_domains.train.create_agent` Args: sess: a session environment: an environment summary_writer: a summary writer. Returns: a DQN agent. """ return BatchDQNAgent( env_batch_size=environment.batch_size, sess=sess, num_actions=environment.action_space.n, summary_writer=summary_writer, tf_device="/gpu:*", **agent_kwargs) return create_agent
def get_create_agent(agent_kwargs): """Factory for dopamine agent initialization. Args: agent_kwargs: dict of BatchDQNAgent parameters Returns: Function(sess, environment, summary_writer) -> BatchDQNAgent instance. """ def create_agent(sess, environment, summary_writer=None): """Creates a DQN agent. Simplified version of `dopamine.discrete_domains.train.create_agent` Args: sess: a session environment: an environment summary_writer: a summary writer. Returns: a DQN agent. """ return BatchDQNAgent( env_batch_size=environment.batch_size, sess=sess, num_actions=environment.action_space.n, summary_writer=summary_writer, tf_device="/gpu:*", **agent_kwargs) return create_agent
[ "Factory", "for", "dopamine", "agent", "initialization", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/dopamine_connector.py#L274-L305
[ "def", "get_create_agent", "(", "agent_kwargs", ")", ":", "def", "create_agent", "(", "sess", ",", "environment", ",", "summary_writer", "=", "None", ")", ":", "\"\"\"Creates a DQN agent.\n\n Simplified version of `dopamine.discrete_domains.train.create_agent`\n\n Args:\n ...
272500b6efe353aeb638d2745ed56e519462ca31
train
get_create_batch_env_fun
Factory for dopamine environment initialization function. Args: batch_env_fn: function(in_graph: bool) -> batch environment. time_limit: time steps limit for environment. Returns: function (with optional, unused parameters) initializing environment.
tensor2tensor/rl/dopamine_connector.py
def get_create_batch_env_fun(batch_env_fn, time_limit): """Factory for dopamine environment initialization function. Args: batch_env_fn: function(in_graph: bool) -> batch environment. time_limit: time steps limit for environment. Returns: function (with optional, unused parameters) initializing environment. """ def create_env_fun(game_name=None, sticky_actions=None): del game_name, sticky_actions batch_env = batch_env_fn(in_graph=False) batch_env = ResizeBatchObservation(batch_env) # pylint: disable=redefined-variable-type batch_env = DopamineBatchEnv(batch_env, max_episode_steps=time_limit) return batch_env return create_env_fun
def get_create_batch_env_fun(batch_env_fn, time_limit): """Factory for dopamine environment initialization function. Args: batch_env_fn: function(in_graph: bool) -> batch environment. time_limit: time steps limit for environment. Returns: function (with optional, unused parameters) initializing environment. """ def create_env_fun(game_name=None, sticky_actions=None): del game_name, sticky_actions batch_env = batch_env_fn(in_graph=False) batch_env = ResizeBatchObservation(batch_env) # pylint: disable=redefined-variable-type batch_env = DopamineBatchEnv(batch_env, max_episode_steps=time_limit) return batch_env return create_env_fun
[ "Factory", "for", "dopamine", "environment", "initialization", "function", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/dopamine_connector.py#L450-L468
[ "def", "get_create_batch_env_fun", "(", "batch_env_fn", ",", "time_limit", ")", ":", "def", "create_env_fun", "(", "game_name", "=", "None", ",", "sticky_actions", "=", "None", ")", ":", "del", "game_name", ",", "sticky_actions", "batch_env", "=", "batch_env_fn", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
_parse_hparams
Split hparams, based on key prefixes. Args: hparams: hyperparameters Returns: Tuple of hparams for respectably: agent, optimizer, runner, replay_buffer.
tensor2tensor/rl/dopamine_connector.py
def _parse_hparams(hparams): """Split hparams, based on key prefixes. Args: hparams: hyperparameters Returns: Tuple of hparams for respectably: agent, optimizer, runner, replay_buffer. """ prefixes = ["agent_", "optimizer_", "runner_", "replay_buffer_"] ret = [] for prefix in prefixes: ret_dict = {} for key in hparams.values(): if prefix in key: par_name = key[len(prefix):] ret_dict[par_name] = hparams.get(key) ret.append(ret_dict) return ret
def _parse_hparams(hparams): """Split hparams, based on key prefixes. Args: hparams: hyperparameters Returns: Tuple of hparams for respectably: agent, optimizer, runner, replay_buffer. """ prefixes = ["agent_", "optimizer_", "runner_", "replay_buffer_"] ret = [] for prefix in prefixes: ret_dict = {} for key in hparams.values(): if prefix in key: par_name = key[len(prefix):] ret_dict[par_name] = hparams.get(key) ret.append(ret_dict) return ret
[ "Split", "hparams", "based", "on", "key", "prefixes", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/dopamine_connector.py#L471-L491
[ "def", "_parse_hparams", "(", "hparams", ")", ":", "prefixes", "=", "[", "\"agent_\"", ",", "\"optimizer_\"", ",", "\"runner_\"", ",", "\"replay_buffer_\"", "]", "ret", "=", "[", "]", "for", "prefix", "in", "prefixes", ":", "ret_dict", "=", "{", "}", "for"...
272500b6efe353aeb638d2745ed56e519462ca31
train
_DQNAgent._build_replay_buffer
Build WrappedReplayBuffer with custom OutOfGraphReplayBuffer.
tensor2tensor/rl/dopamine_connector.py
def _build_replay_buffer(self, use_staging): """Build WrappedReplayBuffer with custom OutOfGraphReplayBuffer.""" replay_buffer_kwargs = dict( observation_shape=dqn_agent.NATURE_DQN_OBSERVATION_SHAPE, stack_size=dqn_agent.NATURE_DQN_STACK_SIZE, replay_capacity=self._replay_capacity, batch_size=self._buffer_batch_size, update_horizon=self.update_horizon, gamma=self.gamma, extra_storage_types=None, observation_dtype=np.uint8, ) replay_memory = _OutOfGraphReplayBuffer( artificial_done=not self._generates_trainable_dones, **replay_buffer_kwargs) return circular_replay_buffer.WrappedReplayBuffer( wrapped_memory=replay_memory, use_staging=use_staging, **replay_buffer_kwargs)
def _build_replay_buffer(self, use_staging): """Build WrappedReplayBuffer with custom OutOfGraphReplayBuffer.""" replay_buffer_kwargs = dict( observation_shape=dqn_agent.NATURE_DQN_OBSERVATION_SHAPE, stack_size=dqn_agent.NATURE_DQN_STACK_SIZE, replay_capacity=self._replay_capacity, batch_size=self._buffer_batch_size, update_horizon=self.update_horizon, gamma=self.gamma, extra_storage_types=None, observation_dtype=np.uint8, ) replay_memory = _OutOfGraphReplayBuffer( artificial_done=not self._generates_trainable_dones, **replay_buffer_kwargs) return circular_replay_buffer.WrappedReplayBuffer( wrapped_memory=replay_memory, use_staging=use_staging, **replay_buffer_kwargs)
[ "Build", "WrappedReplayBuffer", "with", "custom", "OutOfGraphReplayBuffer", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/dopamine_connector.py#L60-L79
[ "def", "_build_replay_buffer", "(", "self", ",", "use_staging", ")", ":", "replay_buffer_kwargs", "=", "dict", "(", "observation_shape", "=", "dqn_agent", ".", "NATURE_DQN_OBSERVATION_SHAPE", ",", "stack_size", "=", "dqn_agent", ".", "NATURE_DQN_STACK_SIZE", ",", "rep...
272500b6efe353aeb638d2745ed56e519462ca31
train
_OutOfGraphReplayBuffer.add
Append artificial_done to *args and run parent method.
tensor2tensor/rl/dopamine_connector.py
def add(self, observation, action, reward, terminal, *args): """Append artificial_done to *args and run parent method.""" # If this will be a problem for maintenance, we could probably override # DQNAgent.add() method instead. artificial_done = self._artificial_done and terminal args = list(args) args.append(artificial_done) return super(_OutOfGraphReplayBuffer, self).add(observation, action, reward, terminal, *args)
def add(self, observation, action, reward, terminal, *args): """Append artificial_done to *args and run parent method.""" # If this will be a problem for maintenance, we could probably override # DQNAgent.add() method instead. artificial_done = self._artificial_done and terminal args = list(args) args.append(artificial_done) return super(_OutOfGraphReplayBuffer, self).add(observation, action, reward, terminal, *args)
[ "Append", "artificial_done", "to", "*", "args", "and", "run", "parent", "method", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/dopamine_connector.py#L257-L265
[ "def", "add", "(", "self", ",", "observation", ",", "action", ",", "reward", ",", "terminal", ",", "*", "args", ")", ":", "# If this will be a problem for maintenance, we could probably override", "# DQNAgent.add() method instead.", "artificial_done", "=", "self", ".", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
DopamineBatchEnv.step
Step.
tensor2tensor/rl/dopamine_connector.py
def step(self, actions): """Step.""" self._elapsed_steps += 1 obs, rewards, dones = \ [np.array(r) for r in self.batch_env.step(actions)] if self._elapsed_steps > self._max_episode_steps: done = True if self._elapsed_steps > self._max_episode_steps + 1: rewards.fill(0) else: done = dones[0] assert np.all(done == dones), ("Current modifications of Dopamine " "require same number of steps for each " "environment in batch") del dones self.game_over = done return obs, rewards, done, {}
def step(self, actions): """Step.""" self._elapsed_steps += 1 obs, rewards, dones = \ [np.array(r) for r in self.batch_env.step(actions)] if self._elapsed_steps > self._max_episode_steps: done = True if self._elapsed_steps > self._max_episode_steps + 1: rewards.fill(0) else: done = dones[0] assert np.all(done == dones), ("Current modifications of Dopamine " "require same number of steps for each " "environment in batch") del dones self.game_over = done return obs, rewards, done, {}
[ "Step", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/dopamine_connector.py#L371-L388
[ "def", "step", "(", "self", ",", "actions", ")", ":", "self", ".", "_elapsed_steps", "+=", "1", "obs", ",", "rewards", ",", "dones", "=", "[", "np", ".", "array", "(", "r", ")", "for", "r", "in", "self", ".", "batch_env", ".", "step", "(", "actio...
272500b6efe353aeb638d2745ed56e519462ca31
train
text_cnn_base
Set of hyperparameters.
tensor2tensor/models/text_cnn.py
def text_cnn_base(): """Set of hyperparameters.""" hparams = common_hparams.basic_params1() hparams.batch_size = 4096 hparams.max_length = 256 hparams.clip_grad_norm = 0. # i.e. no gradient clipping hparams.optimizer_adam_epsilon = 1e-9 hparams.learning_rate_schedule = "legacy" hparams.learning_rate_decay_scheme = "noam" hparams.learning_rate = 0.1 hparams.learning_rate_warmup_steps = 4000 hparams.initializer_gain = 1.0 hparams.num_hidden_layers = 6 hparams.initializer = "uniform_unit_scaling" hparams.weight_decay = 0.0 hparams.optimizer_adam_beta1 = 0.9 hparams.optimizer_adam_beta2 = 0.98 hparams.num_sampled_classes = 0 hparams.label_smoothing = 0.1 hparams.shared_embedding_and_softmax_weights = True hparams.symbol_modality_num_shards = 16 # Add new ones like this. hparams.add_hparam("filter_sizes", [2, 3, 4, 5]) hparams.add_hparam("num_filters", 128) hparams.add_hparam("output_dropout", 0.4) return hparams
def text_cnn_base(): """Set of hyperparameters.""" hparams = common_hparams.basic_params1() hparams.batch_size = 4096 hparams.max_length = 256 hparams.clip_grad_norm = 0. # i.e. no gradient clipping hparams.optimizer_adam_epsilon = 1e-9 hparams.learning_rate_schedule = "legacy" hparams.learning_rate_decay_scheme = "noam" hparams.learning_rate = 0.1 hparams.learning_rate_warmup_steps = 4000 hparams.initializer_gain = 1.0 hparams.num_hidden_layers = 6 hparams.initializer = "uniform_unit_scaling" hparams.weight_decay = 0.0 hparams.optimizer_adam_beta1 = 0.9 hparams.optimizer_adam_beta2 = 0.98 hparams.num_sampled_classes = 0 hparams.label_smoothing = 0.1 hparams.shared_embedding_and_softmax_weights = True hparams.symbol_modality_num_shards = 16 # Add new ones like this. hparams.add_hparam("filter_sizes", [2, 3, 4, 5]) hparams.add_hparam("num_filters", 128) hparams.add_hparam("output_dropout", 0.4) return hparams
[ "Set", "of", "hyperparameters", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/text_cnn.py#L86-L112
[ "def", "text_cnn_base", "(", ")", ":", "hparams", "=", "common_hparams", ".", "basic_params1", "(", ")", "hparams", ".", "batch_size", "=", "4096", "hparams", ".", "max_length", "=", "256", "hparams", ".", "clip_grad_norm", "=", "0.", "# i.e. no gradient clippin...
272500b6efe353aeb638d2745ed56e519462ca31
train
next_frame_glow_hparams
Hparams for next_frame_glow.
tensor2tensor/models/video/next_frame_glow.py
def next_frame_glow_hparams(): """Hparams for next_frame_glow.""" hparams = glow.glow_hparams() # Possible modes are conditional and unconditional hparams.add_hparam("gen_mode", "conditional") hparams.add_hparam("learn_top_scale", False) hparams.add_hparam("condition_all_levels", True) # For each video, substitutes "num_input_frames + num_output_frames" with a # randomly sampled patch of length "num_train_frames" during training. # -1 indicates that the entire video is used for training. hparams.add_hparam("num_train_frames", -1) # The following are hparams that model the latent transitions. # Encoder that maps the latents to a Gaussian distribution. # This function is used to model the prior over z_{t}. Can be, # Pointwise -> point-wise multiplication of z_{t-1}. # conv_net -> one-layer convolution over z_{t-1} .. z_{t - num_cond_latents} # conv3d_net or conv_lstm hparams.add_hparam("latent_dist_encoder", "conv_net") # Number of latents used in the encoder above. hparams.add_hparam("num_cond_latents", 1) hparams.add_hparam("latent_architecture", "glow_resnet") hparams.add_hparam("latent_apply_dilations", False) hparams.add_hparam("latent_dilation_rates", [1, 3]) # Use latent skip connections hparams.add_hparam("model_input", False) hparams.add_hparam("cond_first_frame", False) hparams.add_hparam("latent_skip", True) hparams.add_hparam("latent_encoder_depth", 2) hparams.add_hparam("latent_encoder_width", 512) hparams.add_hparam("latent_dropout", 0.0) hparams.add_hparam("latent_pre_output_channels", 512) hparams.add_hparam("latent_activation", "relu") hparams.add_hparam("latent_noise", 0.0) # Pretrains the glow encoder for "pretrain_steps" number of steps. # By default, don't pretrain and learn end-to-end hparams.add_hparam("pretrain_steps", -1) hparams.bottom = { "inputs": modalities.video_raw_bottom, "targets": modalities.video_raw_targets_bottom, } hparams.loss = { "targets": modalities.video_l1_raw_loss, } hparams.top = { "targets": modalities.video_raw_top, } hparams.init_batch_size = 256 hparams.batch_size = 32 # Possible options: are prev_frame, single_conv and normal hparams.top_prior = "single_conv" return hparams
def next_frame_glow_hparams(): """Hparams for next_frame_glow.""" hparams = glow.glow_hparams() # Possible modes are conditional and unconditional hparams.add_hparam("gen_mode", "conditional") hparams.add_hparam("learn_top_scale", False) hparams.add_hparam("condition_all_levels", True) # For each video, substitutes "num_input_frames + num_output_frames" with a # randomly sampled patch of length "num_train_frames" during training. # -1 indicates that the entire video is used for training. hparams.add_hparam("num_train_frames", -1) # The following are hparams that model the latent transitions. # Encoder that maps the latents to a Gaussian distribution. # This function is used to model the prior over z_{t}. Can be, # Pointwise -> point-wise multiplication of z_{t-1}. # conv_net -> one-layer convolution over z_{t-1} .. z_{t - num_cond_latents} # conv3d_net or conv_lstm hparams.add_hparam("latent_dist_encoder", "conv_net") # Number of latents used in the encoder above. hparams.add_hparam("num_cond_latents", 1) hparams.add_hparam("latent_architecture", "glow_resnet") hparams.add_hparam("latent_apply_dilations", False) hparams.add_hparam("latent_dilation_rates", [1, 3]) # Use latent skip connections hparams.add_hparam("model_input", False) hparams.add_hparam("cond_first_frame", False) hparams.add_hparam("latent_skip", True) hparams.add_hparam("latent_encoder_depth", 2) hparams.add_hparam("latent_encoder_width", 512) hparams.add_hparam("latent_dropout", 0.0) hparams.add_hparam("latent_pre_output_channels", 512) hparams.add_hparam("latent_activation", "relu") hparams.add_hparam("latent_noise", 0.0) # Pretrains the glow encoder for "pretrain_steps" number of steps. # By default, don't pretrain and learn end-to-end hparams.add_hparam("pretrain_steps", -1) hparams.bottom = { "inputs": modalities.video_raw_bottom, "targets": modalities.video_raw_targets_bottom, } hparams.loss = { "targets": modalities.video_l1_raw_loss, } hparams.top = { "targets": modalities.video_raw_top, } hparams.init_batch_size = 256 hparams.batch_size = 32 # Possible options: are prev_frame, single_conv and normal hparams.top_prior = "single_conv" return hparams
[ "Hparams", "for", "next_frame_glow", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/next_frame_glow.py#L37-L87
[ "def", "next_frame_glow_hparams", "(", ")", ":", "hparams", "=", "glow", ".", "glow_hparams", "(", ")", "# Possible modes are conditional and unconditional", "hparams", ".", "add_hparam", "(", "\"gen_mode\"", ",", "\"conditional\"", ")", "hparams", ".", "add_hparam", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
next_frame_glow_bair_quant
Hparams to reproduce bits-per-pixel results on BAIR action-free dataset.
tensor2tensor/models/video/next_frame_glow.py
def next_frame_glow_bair_quant(): """Hparams to reproduce bits-per-pixel results on BAIR action-free dataset.""" hparams = next_frame_glow_hparams() hparams.video_num_input_frames = 3 hparams.video_num_target_frames = 10 hparams.num_train_frames = 4 hparams.num_cond_latents = 3 hparams.depth = 24 hparams.latent_dist_encoder = "conv3d_net" hparams.latent_encoder_width = 256 hparams.latent_architecture = "glow_resnet" hparams.latent_encoder_depth = 5 hparams.latent_apply_dilations = True hparams.latent_activation = "gatu" hparams.activation = "gatu" hparams.learning_rate_constant = 3e-4 hparams.learning_rate_schedule = "constant*linear_warmup" hparams.learning_rate_warmup_steps = 10000 hparams.init_batch_size = 128 hparams.batch_size = 5 return hparams
def next_frame_glow_bair_quant(): """Hparams to reproduce bits-per-pixel results on BAIR action-free dataset.""" hparams = next_frame_glow_hparams() hparams.video_num_input_frames = 3 hparams.video_num_target_frames = 10 hparams.num_train_frames = 4 hparams.num_cond_latents = 3 hparams.depth = 24 hparams.latent_dist_encoder = "conv3d_net" hparams.latent_encoder_width = 256 hparams.latent_architecture = "glow_resnet" hparams.latent_encoder_depth = 5 hparams.latent_apply_dilations = True hparams.latent_activation = "gatu" hparams.activation = "gatu" hparams.learning_rate_constant = 3e-4 hparams.learning_rate_schedule = "constant*linear_warmup" hparams.learning_rate_warmup_steps = 10000 hparams.init_batch_size = 128 hparams.batch_size = 5 return hparams
[ "Hparams", "to", "reproduce", "bits", "-", "per", "-", "pixel", "results", "on", "BAIR", "action", "-", "free", "dataset", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/next_frame_glow.py#L91-L111
[ "def", "next_frame_glow_bair_quant", "(", ")", ":", "hparams", "=", "next_frame_glow_hparams", "(", ")", "hparams", ".", "video_num_input_frames", "=", "3", "hparams", ".", "video_num_target_frames", "=", "10", "hparams", ".", "num_train_frames", "=", "4", "hparams"...
272500b6efe353aeb638d2745ed56e519462ca31
train
next_frame_glow_bair_qual
Hparams for qualitative video generation results.
tensor2tensor/models/video/next_frame_glow.py
def next_frame_glow_bair_qual(): """Hparams for qualitative video generation results.""" hparams = next_frame_glow_bair_quant() hparams.coupling = "additive" hparams.temperature = 0.5 hparams.coupling_width = 392 return hparams
def next_frame_glow_bair_qual(): """Hparams for qualitative video generation results.""" hparams = next_frame_glow_bair_quant() hparams.coupling = "additive" hparams.temperature = 0.5 hparams.coupling_width = 392 return hparams
[ "Hparams", "for", "qualitative", "video", "generation", "results", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/next_frame_glow.py#L115-L121
[ "def", "next_frame_glow_bair_qual", "(", ")", ":", "hparams", "=", "next_frame_glow_bair_quant", "(", ")", "hparams", ".", "coupling", "=", "\"additive\"", "hparams", ".", "temperature", "=", "0.5", "hparams", ".", "coupling_width", "=", "392", "return", "hparams"...
272500b6efe353aeb638d2745ed56e519462ca31
train
next_frame_glow_shapes
Hparams for qualitative and quantitative results on shapes dataset.
tensor2tensor/models/video/next_frame_glow.py
def next_frame_glow_shapes(): """Hparams for qualitative and quantitative results on shapes dataset.""" hparams = next_frame_glow_bair_quant() hparams.video_num_input_frames = 1 hparams.video_num_target_frames = 2 hparams.num_train_frames = 2 hparams.num_cond_latents = 1 hparams.coupling = "additive" hparams.coupling_width = 512 hparams.latent_encoder_depth = 10 hparams.latent_skip = False hparams.learning_rate_constant = 1e-4 hparams.batch_size = 10 return hparams
def next_frame_glow_shapes(): """Hparams for qualitative and quantitative results on shapes dataset.""" hparams = next_frame_glow_bair_quant() hparams.video_num_input_frames = 1 hparams.video_num_target_frames = 2 hparams.num_train_frames = 2 hparams.num_cond_latents = 1 hparams.coupling = "additive" hparams.coupling_width = 512 hparams.latent_encoder_depth = 10 hparams.latent_skip = False hparams.learning_rate_constant = 1e-4 hparams.batch_size = 10 return hparams
[ "Hparams", "for", "qualitative", "and", "quantitative", "results", "on", "shapes", "dataset", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/next_frame_glow.py#L125-L138
[ "def", "next_frame_glow_shapes", "(", ")", ":", "hparams", "=", "next_frame_glow_bair_quant", "(", ")", "hparams", ".", "video_num_input_frames", "=", "1", "hparams", ".", "video_num_target_frames", "=", "2", "hparams", ".", "num_train_frames", "=", "2", "hparams", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
get_cond_latents
Get z^{cond}_{t} given z^{1..t-1}. Args: all_latents: list of list of tensors, outer-size equals no.of time_steps-1 inner-size equals hparams.n_levels. hparams: See next_frame_glow_hparams. Returns: cond_latents: conditional latents at time-step t.
tensor2tensor/models/video/next_frame_glow.py
def get_cond_latents(all_latents=None, hparams=None): """Get z^{cond}_{t} given z^{1..t-1}. Args: all_latents: list of list of tensors, outer-size equals no.of time_steps-1 inner-size equals hparams.n_levels. hparams: See next_frame_glow_hparams. Returns: cond_latents: conditional latents at time-step t. """ cond_latents = None if hparams.gen_mode == "conditional": if hparams.latent_dist_encoder in ["conv_net", "conv3d_net"]: num_cond_latents = (hparams.num_cond_latents + int(hparams.cond_first_frame)) if len(all_latents) >= num_cond_latents: cond_latents = all_latents[-hparams.num_cond_latents:] if hparams.cond_first_frame: cond_latents = [all_latents[0]] + cond_latents elif hparams.latent_dist_encoder in ["pointwise", "conv_lstm"]: if all_latents: cond_latents = all_latents[-1] if hparams.gen_mode == "conditional": global_step = tf.train.get_or_create_global_step() condition = tf.greater(global_step, hparams.pretrain_steps) else: condition = tf.constant(False, dtype=tf.bool) return condition, cond_latents
def get_cond_latents(all_latents=None, hparams=None): """Get z^{cond}_{t} given z^{1..t-1}. Args: all_latents: list of list of tensors, outer-size equals no.of time_steps-1 inner-size equals hparams.n_levels. hparams: See next_frame_glow_hparams. Returns: cond_latents: conditional latents at time-step t. """ cond_latents = None if hparams.gen_mode == "conditional": if hparams.latent_dist_encoder in ["conv_net", "conv3d_net"]: num_cond_latents = (hparams.num_cond_latents + int(hparams.cond_first_frame)) if len(all_latents) >= num_cond_latents: cond_latents = all_latents[-hparams.num_cond_latents:] if hparams.cond_first_frame: cond_latents = [all_latents[0]] + cond_latents elif hparams.latent_dist_encoder in ["pointwise", "conv_lstm"]: if all_latents: cond_latents = all_latents[-1] if hparams.gen_mode == "conditional": global_step = tf.train.get_or_create_global_step() condition = tf.greater(global_step, hparams.pretrain_steps) else: condition = tf.constant(False, dtype=tf.bool) return condition, cond_latents
[ "Get", "z^", "{", "cond", "}", "_", "{", "t", "}", "given", "z^", "{", "1", "..", "t", "-", "1", "}", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/next_frame_glow.py#L150-L179
[ "def", "get_cond_latents", "(", "all_latents", "=", "None", ",", "hparams", "=", "None", ")", ":", "cond_latents", "=", "None", "if", "hparams", ".", "gen_mode", "==", "\"conditional\"", ":", "if", "hparams", ".", "latent_dist_encoder", "in", "[", "\"conv_net\...
272500b6efe353aeb638d2745ed56e519462ca31
train
basic_fc_small
Small fully connected model.
tensor2tensor/models/basic.py
def basic_fc_small(): """Small fully connected model.""" hparams = common_hparams.basic_params1() hparams.learning_rate = 0.1 hparams.batch_size = 128 hparams.hidden_size = 256 hparams.num_hidden_layers = 2 hparams.initializer = "uniform_unit_scaling" hparams.initializer_gain = 1.0 hparams.weight_decay = 0.0 hparams.dropout = 0.0 return hparams
def basic_fc_small(): """Small fully connected model.""" hparams = common_hparams.basic_params1() hparams.learning_rate = 0.1 hparams.batch_size = 128 hparams.hidden_size = 256 hparams.num_hidden_layers = 2 hparams.initializer = "uniform_unit_scaling" hparams.initializer_gain = 1.0 hparams.weight_decay = 0.0 hparams.dropout = 0.0 return hparams
[ "Small", "fully", "connected", "model", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/basic.py#L47-L58
[ "def", "basic_fc_small", "(", ")", ":", "hparams", "=", "common_hparams", ".", "basic_params1", "(", ")", "hparams", ".", "learning_rate", "=", "0.1", "hparams", ".", "batch_size", "=", "128", "hparams", ".", "hidden_size", "=", "256", "hparams", ".", "num_h...
272500b6efe353aeb638d2745ed56e519462ca31
train
_layer_stack
A stack of layers. Args: mp: a Parallelism object inputs: a list of Tensors self_attention_bias: list of bias Tensor for self-attention (see common_attention.attention_bias()) layers: a string hparams: hyperparameters for model encoder_output: optional list of tensors encoder_decoder_attention_bias: optional list of tensors Returns: y: a list of Tensors
tensor2tensor/models/research/transformer_symshard.py
def _layer_stack(mp, inputs, self_attention_bias, layers, hparams, encoder_output=None, encoder_decoder_attention_bias=None): """A stack of layers. Args: mp: a Parallelism object inputs: a list of Tensors self_attention_bias: list of bias Tensor for self-attention (see common_attention.attention_bias()) layers: a string hparams: hyperparameters for model encoder_output: optional list of tensors encoder_decoder_attention_bias: optional list of tensors Returns: y: a list of Tensors """ layers = layers.strip(",").split(",") # scaled_dot_product_attention_with_projections uses a 3d attention bias # (no heads), where multihead_attention uses 4d attention bias. self_attention_bias_3d = mp(tf.squeeze, self_attention_bias, 1) if encoder_decoder_attention_bias is not None: encoder_decoder_attention_bias_3d = mp( tf.squeeze, encoder_decoder_attention_bias, 1) relu_dropout_broadcast_dims = ( common_layers.comma_separated_string_to_integer_list( getattr(hparams, "relu_dropout_broadcast_dims", ""))) mix_size = int(hparams.mix_fraction * hparams.hidden_size) accumulator = inputs x = inputs for layer_num, layer_type in enumerate(layers): with tf.variable_scope("%s_%d" % (layer_type, layer_num)): tf.logging.info("%s_%d" % (layer_type, layer_num)) if layer_type == "a": # accumulate accumulator = mp(tf.add, x, accumulator) x = accumulator elif layer_type == "n": # normalize x = mp(common_layers.apply_norm, x, hparams.norm_type, hparams.hidden_size, hparams.norm_epsilon) elif layer_type == "d": # dropout x = mp(tf.nn.dropout, x, 1.0 - hparams.layer_prepostprocess_dropout) elif layer_type == "m": if mix_size > 0: # mix across shards def _split(t): return tuple(tf.split( t, [mix_size, hparams.hidden_size - mix_size], 2)) to_mix, to_keep = mp(_split, x) mixed = expert_utils.all_reduce_ring(to_mix, mp) mixed = mp(tf.multiply, mixed, mp.n ** -0.5) x = mp(lambda a, b: tf.concat([a, b], 2), mixed, to_keep) elif layer_type == "att": # single-head attention q = mp(tf.layers.dense, x, hparams.hidden_size, use_bias=False, name="q_transform") x = mp( common_attention.scaled_dot_product_attention_simple, q, x, x, self_attention_bias_3d) x = mp(tf.layers.dense, x, hparams.hidden_size, use_bias=False, name="o_transform") elif layer_type == "enc-att": # single-head attention over encoder q = mp(tf.layers.dense, x, hparams.hidden_size, use_bias=False, name="q_transform") assert encoder_output is not None x = mp( common_attention.scaled_dot_product_attention_simple, q, encoder_output, encoder_output, encoder_decoder_attention_bias_3d) x = mp(tf.layers.dense, x, hparams.hidden_size, use_bias=False, name="o_transform") elif layer_type == "multihead-att": # multi-head attention x = mp( common_attention.multihead_attention, x, None, self_attention_bias, # bias hparams.multihead_attention_key_channels or hparams.hidden_size, hparams.multihead_attention_value_channels or hparams.hidden_size, hparams.hidden_size, hparams.multihead_attention_num_heads, hparams.attention_dropout) elif layer_type == "enc-multihead-att": # multi-head attention x = mp( common_attention.multihead_attention, x, encoder_output, encoder_decoder_attention_bias, # bias hparams.multihead_attention_key_channels or hparams.hidden_size, hparams.multihead_attention_value_channels or hparams.hidden_size, hparams.hidden_size, hparams.multihead_attention_num_heads, hparams.attention_dropout) elif layer_type == "ffn": x = mp( common_layers.dense_relu_dense, x, hparams.filter_size, hparams.hidden_size, dropout=hparams.relu_dropout, dropout_broadcast_dims=[relu_dropout_broadcast_dims] * mp.n) else: assert False, "unknown sublayer %s" % layer_type return x
def _layer_stack(mp, inputs, self_attention_bias, layers, hparams, encoder_output=None, encoder_decoder_attention_bias=None): """A stack of layers. Args: mp: a Parallelism object inputs: a list of Tensors self_attention_bias: list of bias Tensor for self-attention (see common_attention.attention_bias()) layers: a string hparams: hyperparameters for model encoder_output: optional list of tensors encoder_decoder_attention_bias: optional list of tensors Returns: y: a list of Tensors """ layers = layers.strip(",").split(",") # scaled_dot_product_attention_with_projections uses a 3d attention bias # (no heads), where multihead_attention uses 4d attention bias. self_attention_bias_3d = mp(tf.squeeze, self_attention_bias, 1) if encoder_decoder_attention_bias is not None: encoder_decoder_attention_bias_3d = mp( tf.squeeze, encoder_decoder_attention_bias, 1) relu_dropout_broadcast_dims = ( common_layers.comma_separated_string_to_integer_list( getattr(hparams, "relu_dropout_broadcast_dims", ""))) mix_size = int(hparams.mix_fraction * hparams.hidden_size) accumulator = inputs x = inputs for layer_num, layer_type in enumerate(layers): with tf.variable_scope("%s_%d" % (layer_type, layer_num)): tf.logging.info("%s_%d" % (layer_type, layer_num)) if layer_type == "a": # accumulate accumulator = mp(tf.add, x, accumulator) x = accumulator elif layer_type == "n": # normalize x = mp(common_layers.apply_norm, x, hparams.norm_type, hparams.hidden_size, hparams.norm_epsilon) elif layer_type == "d": # dropout x = mp(tf.nn.dropout, x, 1.0 - hparams.layer_prepostprocess_dropout) elif layer_type == "m": if mix_size > 0: # mix across shards def _split(t): return tuple(tf.split( t, [mix_size, hparams.hidden_size - mix_size], 2)) to_mix, to_keep = mp(_split, x) mixed = expert_utils.all_reduce_ring(to_mix, mp) mixed = mp(tf.multiply, mixed, mp.n ** -0.5) x = mp(lambda a, b: tf.concat([a, b], 2), mixed, to_keep) elif layer_type == "att": # single-head attention q = mp(tf.layers.dense, x, hparams.hidden_size, use_bias=False, name="q_transform") x = mp( common_attention.scaled_dot_product_attention_simple, q, x, x, self_attention_bias_3d) x = mp(tf.layers.dense, x, hparams.hidden_size, use_bias=False, name="o_transform") elif layer_type == "enc-att": # single-head attention over encoder q = mp(tf.layers.dense, x, hparams.hidden_size, use_bias=False, name="q_transform") assert encoder_output is not None x = mp( common_attention.scaled_dot_product_attention_simple, q, encoder_output, encoder_output, encoder_decoder_attention_bias_3d) x = mp(tf.layers.dense, x, hparams.hidden_size, use_bias=False, name="o_transform") elif layer_type == "multihead-att": # multi-head attention x = mp( common_attention.multihead_attention, x, None, self_attention_bias, # bias hparams.multihead_attention_key_channels or hparams.hidden_size, hparams.multihead_attention_value_channels or hparams.hidden_size, hparams.hidden_size, hparams.multihead_attention_num_heads, hparams.attention_dropout) elif layer_type == "enc-multihead-att": # multi-head attention x = mp( common_attention.multihead_attention, x, encoder_output, encoder_decoder_attention_bias, # bias hparams.multihead_attention_key_channels or hparams.hidden_size, hparams.multihead_attention_value_channels or hparams.hidden_size, hparams.hidden_size, hparams.multihead_attention_num_heads, hparams.attention_dropout) elif layer_type == "ffn": x = mp( common_layers.dense_relu_dense, x, hparams.filter_size, hparams.hidden_size, dropout=hparams.relu_dropout, dropout_broadcast_dims=[relu_dropout_broadcast_dims] * mp.n) else: assert False, "unknown sublayer %s" % layer_type return x
[ "A", "stack", "of", "layers", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_symshard.py#L227-L339
[ "def", "_layer_stack", "(", "mp", ",", "inputs", ",", "self_attention_bias", ",", "layers", ",", "hparams", ",", "encoder_output", "=", "None", ",", "encoder_decoder_attention_bias", "=", "None", ")", ":", "layers", "=", "layers", ".", "strip", "(", "\",\"", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
transformer_symshard_base
Set of hyperparameters.
tensor2tensor/models/research/transformer_symshard.py
def transformer_symshard_base(): """Set of hyperparameters.""" hparams = common_hparams.basic_params1() hparams.hidden_size = 256 hparams.batch_size = 2048 hparams.max_length = 0 # All hyperparameters ending in "dropout" are automatically set to 0.0 # when not in training mode. hparams.layer_prepostprocess_dropout = 0.2 hparams.add_hparam("attention_dropout", 0.1) hparams.add_hparam("relu_dropout", 0.0) hparams.add_hparam("relu_dropout_broadcast_dims", "1") hparams.layer_prepostprocess_dropout = 0.1 hparams.layer_prepostprocess_dropout_broadcast_dims = "1" # length hparams.label_smoothing = 0.1 hparams.clip_grad_norm = 0. # i.e. no gradient clipping hparams.optimizer = "Adafactor" hparams.learning_rate_schedule = "rsqrt_decay" hparams.learning_rate_warmup_steps = 10000 hparams.initializer_gain = 1.0 hparams.initializer = "uniform_unit_scaling" hparams.weight_decay = 0.0 # TODO(noam): use this to control sharing. We now share always hparams.shared_embedding_and_softmax_weights = True # we only want one data shard. hparams.no_data_parallelism = True # bypass the symbol modality so that we can use model parallelism. hparams.bottom = { "inputs": modalities.identity_bottom, "targets": modalities.identity_bottom, } hparams.top = { "targets": modalities.identity_top, } hparams.add_hparam("filter_size", 1280) hparams.add_hparam("mix_fraction", 0.5) # attention-related flags hparams.add_hparam("multihead_attention_num_heads", 4) hparams.add_hparam("multihead_attention_key_channels", 0) hparams.add_hparam("multihead_attention_value_channels", 0) hparams.add_hparam("pos", "timing") # timing, none hparams.add_hparam( "encoder_layers", ("n,att,m,d,a," "n,ffn,m,d,a,") * 6 + "n,d") hparams.add_hparam( "decoder_layers", ("n,att,m,d,a," "n,enc-att,m,d,a," "n,ffn,m,d,a,") * 6 + "n,d") # Number of model shards - each one has separate parameters. # Changing this number invalidates checkpoints. hparams.add_hparam("num_model_shards", 8) return hparams
def transformer_symshard_base(): """Set of hyperparameters.""" hparams = common_hparams.basic_params1() hparams.hidden_size = 256 hparams.batch_size = 2048 hparams.max_length = 0 # All hyperparameters ending in "dropout" are automatically set to 0.0 # when not in training mode. hparams.layer_prepostprocess_dropout = 0.2 hparams.add_hparam("attention_dropout", 0.1) hparams.add_hparam("relu_dropout", 0.0) hparams.add_hparam("relu_dropout_broadcast_dims", "1") hparams.layer_prepostprocess_dropout = 0.1 hparams.layer_prepostprocess_dropout_broadcast_dims = "1" # length hparams.label_smoothing = 0.1 hparams.clip_grad_norm = 0. # i.e. no gradient clipping hparams.optimizer = "Adafactor" hparams.learning_rate_schedule = "rsqrt_decay" hparams.learning_rate_warmup_steps = 10000 hparams.initializer_gain = 1.0 hparams.initializer = "uniform_unit_scaling" hparams.weight_decay = 0.0 # TODO(noam): use this to control sharing. We now share always hparams.shared_embedding_and_softmax_weights = True # we only want one data shard. hparams.no_data_parallelism = True # bypass the symbol modality so that we can use model parallelism. hparams.bottom = { "inputs": modalities.identity_bottom, "targets": modalities.identity_bottom, } hparams.top = { "targets": modalities.identity_top, } hparams.add_hparam("filter_size", 1280) hparams.add_hparam("mix_fraction", 0.5) # attention-related flags hparams.add_hparam("multihead_attention_num_heads", 4) hparams.add_hparam("multihead_attention_key_channels", 0) hparams.add_hparam("multihead_attention_value_channels", 0) hparams.add_hparam("pos", "timing") # timing, none hparams.add_hparam( "encoder_layers", ("n,att,m,d,a," "n,ffn,m,d,a,") * 6 + "n,d") hparams.add_hparam( "decoder_layers", ("n,att,m,d,a," "n,enc-att,m,d,a," "n,ffn,m,d,a,") * 6 + "n,d") # Number of model shards - each one has separate parameters. # Changing this number invalidates checkpoints. hparams.add_hparam("num_model_shards", 8) return hparams
[ "Set", "of", "hyperparameters", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_symshard.py#L343-L392
[ "def", "transformer_symshard_base", "(", ")", ":", "hparams", "=", "common_hparams", ".", "basic_params1", "(", ")", "hparams", ".", "hidden_size", "=", "256", "hparams", ".", "batch_size", "=", "2048", "hparams", ".", "max_length", "=", "0", "# All hyperparamet...
272500b6efe353aeb638d2745ed56e519462ca31
train
imagenet_pixelrnn_generator
Image generator for Imagenet 64x64 downsampled images. It assumes that the data has been downloaded from http://image-net.org/small/*_32x32.tar or http://image-net.org/small/*_64x64.tar into tmp_dir. Args: tmp_dir: path to temporary storage directory. training: a Boolean; if true, we use the train set, otherwise the test set. size: image size (assumes height and width are same) Yields: A dictionary representing the images with the following fields: * image/encoded: the string encoding the image as JPEG, * image/format: the string "jpeg" representing image format, * image/height: an integer representing the height, * image/width: an integer representing the width. Every field is actually a list of the corresponding type.
tensor2tensor/data_generators/imagenet.py
def imagenet_pixelrnn_generator(tmp_dir, training, size=_IMAGENET_SMALL_IMAGE_SIZE): """Image generator for Imagenet 64x64 downsampled images. It assumes that the data has been downloaded from http://image-net.org/small/*_32x32.tar or http://image-net.org/small/*_64x64.tar into tmp_dir. Args: tmp_dir: path to temporary storage directory. training: a Boolean; if true, we use the train set, otherwise the test set. size: image size (assumes height and width are same) Yields: A dictionary representing the images with the following fields: * image/encoded: the string encoding the image as JPEG, * image/format: the string "jpeg" representing image format, * image/height: an integer representing the height, * image/width: an integer representing the width. Every field is actually a list of the corresponding type. """ if size == _IMAGENET_SMALL_IMAGE_SIZE: train_prefix = _IMAGENET_SMALL_TRAIN_PREFIX eval_prefix = _IMAGENET_SMALL_EVAL_PREFIX else: train_prefix = _IMAGENET_MEDIUM_TRAIN_PREFIX eval_prefix = _IMAGENET_MEDIUM_EVAL_PREFIX prefix = train_prefix if training else eval_prefix images_filepath = os.path.join(tmp_dir, prefix) image_files = tf.gfile.Glob(images_filepath + "/*") height = size width = size const_label = 0 for filename in image_files: with tf.gfile.Open(filename, "r") as f: encoded_image = f.read() yield { "image/encoded": [encoded_image], "image/format": ["png"], "image/class/label": [const_label], "image/height": [height], "image/width": [width] }
def imagenet_pixelrnn_generator(tmp_dir, training, size=_IMAGENET_SMALL_IMAGE_SIZE): """Image generator for Imagenet 64x64 downsampled images. It assumes that the data has been downloaded from http://image-net.org/small/*_32x32.tar or http://image-net.org/small/*_64x64.tar into tmp_dir. Args: tmp_dir: path to temporary storage directory. training: a Boolean; if true, we use the train set, otherwise the test set. size: image size (assumes height and width are same) Yields: A dictionary representing the images with the following fields: * image/encoded: the string encoding the image as JPEG, * image/format: the string "jpeg" representing image format, * image/height: an integer representing the height, * image/width: an integer representing the width. Every field is actually a list of the corresponding type. """ if size == _IMAGENET_SMALL_IMAGE_SIZE: train_prefix = _IMAGENET_SMALL_TRAIN_PREFIX eval_prefix = _IMAGENET_SMALL_EVAL_PREFIX else: train_prefix = _IMAGENET_MEDIUM_TRAIN_PREFIX eval_prefix = _IMAGENET_MEDIUM_EVAL_PREFIX prefix = train_prefix if training else eval_prefix images_filepath = os.path.join(tmp_dir, prefix) image_files = tf.gfile.Glob(images_filepath + "/*") height = size width = size const_label = 0 for filename in image_files: with tf.gfile.Open(filename, "r") as f: encoded_image = f.read() yield { "image/encoded": [encoded_image], "image/format": ["png"], "image/class/label": [const_label], "image/height": [height], "image/width": [width] }
[ "Image", "generator", "for", "Imagenet", "64x64", "downsampled", "images", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/imagenet.py#L56-L98
[ "def", "imagenet_pixelrnn_generator", "(", "tmp_dir", ",", "training", ",", "size", "=", "_IMAGENET_SMALL_IMAGE_SIZE", ")", ":", "if", "size", "==", "_IMAGENET_SMALL_IMAGE_SIZE", ":", "train_prefix", "=", "_IMAGENET_SMALL_TRAIN_PREFIX", "eval_prefix", "=", "_IMAGENET_SMAL...
272500b6efe353aeb638d2745ed56e519462ca31
train
imagenet_preprocess_example
Preprocessing used for Imagenet and similar problems.
tensor2tensor/data_generators/imagenet.py
def imagenet_preprocess_example(example, mode, resize_size=None, normalize=True): """Preprocessing used for Imagenet and similar problems.""" resize_size = resize_size or [299, 299] assert resize_size[0] == resize_size[1] image = example["inputs"] if mode == tf.estimator.ModeKeys.TRAIN: image = preprocess_for_train(image, image_size=resize_size[0], normalize=normalize) else: image = preprocess_for_eval(image, image_size=resize_size[0], normalize=normalize) example["inputs"] = image return example
def imagenet_preprocess_example(example, mode, resize_size=None, normalize=True): """Preprocessing used for Imagenet and similar problems.""" resize_size = resize_size or [299, 299] assert resize_size[0] == resize_size[1] image = example["inputs"] if mode == tf.estimator.ModeKeys.TRAIN: image = preprocess_for_train(image, image_size=resize_size[0], normalize=normalize) else: image = preprocess_for_eval(image, image_size=resize_size[0], normalize=normalize) example["inputs"] = image return example
[ "Preprocessing", "used", "for", "Imagenet", "and", "similar", "problems", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/imagenet.py#L101-L116
[ "def", "imagenet_preprocess_example", "(", "example", ",", "mode", ",", "resize_size", "=", "None", ",", "normalize", "=", "True", ")", ":", "resize_size", "=", "resize_size", "or", "[", "299", ",", "299", "]", "assert", "resize_size", "[", "0", "]", "==",...
272500b6efe353aeb638d2745ed56e519462ca31
train
_crop
Crops the given image using the provided offsets and sizes. Note that the method doesn't assume we know the input image size but it does assume we know the input image rank. Args: image: `Tensor` image of shape [height, width, channels]. offset_height: `Tensor` indicating the height offset. offset_width: `Tensor` indicating the width offset. crop_height: the height of the cropped image. crop_width: the width of the cropped image. Returns: the cropped (and resized) image. Raises: InvalidArgumentError: if the rank is not 3 or if the image dimensions are less than the crop size.
tensor2tensor/data_generators/imagenet.py
def _crop(image, offset_height, offset_width, crop_height, crop_width): """Crops the given image using the provided offsets and sizes. Note that the method doesn't assume we know the input image size but it does assume we know the input image rank. Args: image: `Tensor` image of shape [height, width, channels]. offset_height: `Tensor` indicating the height offset. offset_width: `Tensor` indicating the width offset. crop_height: the height of the cropped image. crop_width: the width of the cropped image. Returns: the cropped (and resized) image. Raises: InvalidArgumentError: if the rank is not 3 or if the image dimensions are less than the crop size. """ original_shape = tf.shape(image) rank_assertion = tf.Assert( tf.equal(tf.rank(image), 3), ["Rank of image must be equal to 3."]) with tf.control_dependencies([rank_assertion]): cropped_shape = tf.stack([crop_height, crop_width, original_shape[2]]) size_assertion = tf.Assert( tf.logical_and( tf.greater_equal(original_shape[0], crop_height), tf.greater_equal(original_shape[1], crop_width)), ["Crop size greater than the image size."]) offsets = tf.to_int32(tf.stack([offset_height, offset_width, 0])) # Use tf.slice instead of crop_to_bounding box as it accepts tensors to # define the crop size. with tf.control_dependencies([size_assertion]): image = tf.slice(image, offsets, cropped_shape) return tf.reshape(image, cropped_shape)
def _crop(image, offset_height, offset_width, crop_height, crop_width): """Crops the given image using the provided offsets and sizes. Note that the method doesn't assume we know the input image size but it does assume we know the input image rank. Args: image: `Tensor` image of shape [height, width, channels]. offset_height: `Tensor` indicating the height offset. offset_width: `Tensor` indicating the width offset. crop_height: the height of the cropped image. crop_width: the width of the cropped image. Returns: the cropped (and resized) image. Raises: InvalidArgumentError: if the rank is not 3 or if the image dimensions are less than the crop size. """ original_shape = tf.shape(image) rank_assertion = tf.Assert( tf.equal(tf.rank(image), 3), ["Rank of image must be equal to 3."]) with tf.control_dependencies([rank_assertion]): cropped_shape = tf.stack([crop_height, crop_width, original_shape[2]]) size_assertion = tf.Assert( tf.logical_and( tf.greater_equal(original_shape[0], crop_height), tf.greater_equal(original_shape[1], crop_width)), ["Crop size greater than the image size."]) offsets = tf.to_int32(tf.stack([offset_height, offset_width, 0])) # Use tf.slice instead of crop_to_bounding box as it accepts tensors to # define the crop size. with tf.control_dependencies([size_assertion]): image = tf.slice(image, offsets, cropped_shape) return tf.reshape(image, cropped_shape)
[ "Crops", "the", "given", "image", "using", "the", "provided", "offsets", "and", "sizes", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/imagenet.py#L427-L466
[ "def", "_crop", "(", "image", ",", "offset_height", ",", "offset_width", ",", "crop_height", ",", "crop_width", ")", ":", "original_shape", "=", "tf", ".", "shape", "(", "image", ")", "rank_assertion", "=", "tf", ".", "Assert", "(", "tf", ".", "equal", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
distorted_bounding_box_crop
Generates cropped_image using a one of the bboxes randomly distorted. See `tf.image.sample_distorted_bounding_box` for more documentation. Args: image: `Tensor` of image (it will be converted to floats in [0, 1]). bbox: `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]`. If num_boxes is 0 then use the whole image. min_object_covered: An optional `float`. Defaults to `0.1`. The cropped area of the image must contain at least this fraction of any bounding box supplied. aspect_ratio_range: An optional list of `float`s. The cropped area of the image must have an aspect ratio = width / height within this range. area_range: An optional list of `float`s. The cropped area of the image must contain a fraction of the supplied image within in this range. max_attempts: An optional `int`. Number of attempts at generating a cropped region of the image of the specified constraints. After `max_attempts` failures, return the entire image. scope: Optional `str` for name scope. Returns: (cropped image `Tensor`, distorted bbox `Tensor`).
tensor2tensor/data_generators/imagenet.py
def distorted_bounding_box_crop(image, bbox, min_object_covered=0.1, aspect_ratio_range=(0.75, 1.33), area_range=(0.05, 1.0), max_attempts=100, scope=None): """Generates cropped_image using a one of the bboxes randomly distorted. See `tf.image.sample_distorted_bounding_box` for more documentation. Args: image: `Tensor` of image (it will be converted to floats in [0, 1]). bbox: `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]`. If num_boxes is 0 then use the whole image. min_object_covered: An optional `float`. Defaults to `0.1`. The cropped area of the image must contain at least this fraction of any bounding box supplied. aspect_ratio_range: An optional list of `float`s. The cropped area of the image must have an aspect ratio = width / height within this range. area_range: An optional list of `float`s. The cropped area of the image must contain a fraction of the supplied image within in this range. max_attempts: An optional `int`. Number of attempts at generating a cropped region of the image of the specified constraints. After `max_attempts` failures, return the entire image. scope: Optional `str` for name scope. Returns: (cropped image `Tensor`, distorted bbox `Tensor`). """ with tf.name_scope(scope, default_name="distorted_bounding_box_crop", values=[image, bbox]): # Each bounding box has shape [1, num_boxes, box coords] and # the coordinates are ordered [ymin, xmin, ymax, xmax]. # 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.shape(image), bounding_boxes=bbox, min_object_covered=min_object_covered, aspect_ratio_range=aspect_ratio_range, area_range=area_range, max_attempts=max_attempts, use_image_if_no_bounding_boxes=True) bbox_begin, bbox_size, distort_bbox = sample_distorted_bounding_box # Crop the image to the specified bounding box. cropped_image = tf.slice(image, bbox_begin, bbox_size) return cropped_image, distort_bbox
def distorted_bounding_box_crop(image, bbox, min_object_covered=0.1, aspect_ratio_range=(0.75, 1.33), area_range=(0.05, 1.0), max_attempts=100, scope=None): """Generates cropped_image using a one of the bboxes randomly distorted. See `tf.image.sample_distorted_bounding_box` for more documentation. Args: image: `Tensor` of image (it will be converted to floats in [0, 1]). bbox: `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]`. If num_boxes is 0 then use the whole image. min_object_covered: An optional `float`. Defaults to `0.1`. The cropped area of the image must contain at least this fraction of any bounding box supplied. aspect_ratio_range: An optional list of `float`s. The cropped area of the image must have an aspect ratio = width / height within this range. area_range: An optional list of `float`s. The cropped area of the image must contain a fraction of the supplied image within in this range. max_attempts: An optional `int`. Number of attempts at generating a cropped region of the image of the specified constraints. After `max_attempts` failures, return the entire image. scope: Optional `str` for name scope. Returns: (cropped image `Tensor`, distorted bbox `Tensor`). """ with tf.name_scope(scope, default_name="distorted_bounding_box_crop", values=[image, bbox]): # Each bounding box has shape [1, num_boxes, box coords] and # the coordinates are ordered [ymin, xmin, ymax, xmax]. # 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.shape(image), bounding_boxes=bbox, min_object_covered=min_object_covered, aspect_ratio_range=aspect_ratio_range, area_range=area_range, max_attempts=max_attempts, use_image_if_no_bounding_boxes=True) bbox_begin, bbox_size, distort_bbox = sample_distorted_bounding_box # Crop the image to the specified bounding box. cropped_image = tf.slice(image, bbox_begin, bbox_size) return cropped_image, distort_bbox
[ "Generates", "cropped_image", "using", "a", "one", "of", "the", "bboxes", "randomly", "distorted", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/imagenet.py#L469-L524
[ "def", "distorted_bounding_box_crop", "(", "image", ",", "bbox", ",", "min_object_covered", "=", "0.1", ",", "aspect_ratio_range", "=", "(", "0.75", ",", "1.33", ")", ",", "area_range", "=", "(", "0.05", ",", "1.0", ")", ",", "max_attempts", "=", "100", ",...
272500b6efe353aeb638d2745ed56e519462ca31
train
_random_crop
Make a random crop of (`size` x `size`).
tensor2tensor/data_generators/imagenet.py
def _random_crop(image, size): """Make a random crop of (`size` x `size`).""" bbox = tf.constant([0.0, 0.0, 1.0, 1.0], dtype=tf.float32, shape=[1, 1, 4]) random_image, bbox = distorted_bounding_box_crop( image, bbox, min_object_covered=0.1, aspect_ratio_range=(3. / 4, 4. / 3.), area_range=(0.08, 1.0), max_attempts=1, scope=None) bad = _at_least_x_are_true(tf.shape(image), tf.shape(random_image), 3) image = tf.cond( bad, lambda: _center_crop(_do_scale(image, size), size), lambda: tf.image.resize_bicubic([random_image], [size, size])[0]) return image
def _random_crop(image, size): """Make a random crop of (`size` x `size`).""" bbox = tf.constant([0.0, 0.0, 1.0, 1.0], dtype=tf.float32, shape=[1, 1, 4]) random_image, bbox = distorted_bounding_box_crop( image, bbox, min_object_covered=0.1, aspect_ratio_range=(3. / 4, 4. / 3.), area_range=(0.08, 1.0), max_attempts=1, scope=None) bad = _at_least_x_are_true(tf.shape(image), tf.shape(random_image), 3) image = tf.cond( bad, lambda: _center_crop(_do_scale(image, size), size), lambda: tf.image.resize_bicubic([random_image], [size, size])[0]) return image
[ "Make", "a", "random", "crop", "of", "(", "size", "x", "size", ")", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/imagenet.py#L527-L543
[ "def", "_random_crop", "(", "image", ",", "size", ")", ":", "bbox", "=", "tf", ".", "constant", "(", "[", "0.0", ",", "0.0", ",", "1.0", ",", "1.0", "]", ",", "dtype", "=", "tf", ".", "float32", ",", "shape", "=", "[", "1", ",", "1", ",", "4"...
272500b6efe353aeb638d2745ed56e519462ca31
train
_at_least_x_are_true
At least `x` of `a` and `b` `Tensors` are true.
tensor2tensor/data_generators/imagenet.py
def _at_least_x_are_true(a, b, x): """At least `x` of `a` and `b` `Tensors` are true.""" match = tf.equal(a, b) match = tf.cast(match, tf.int32) return tf.greater_equal(tf.reduce_sum(match), x)
def _at_least_x_are_true(a, b, x): """At least `x` of `a` and `b` `Tensors` are true.""" match = tf.equal(a, b) match = tf.cast(match, tf.int32) return tf.greater_equal(tf.reduce_sum(match), x)
[ "At", "least", "x", "of", "a", "and", "b", "Tensors", "are", "true", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/imagenet.py#L552-L556
[ "def", "_at_least_x_are_true", "(", "a", ",", "b", ",", "x", ")", ":", "match", "=", "tf", ".", "equal", "(", "a", ",", "b", ")", "match", "=", "tf", ".", "cast", "(", "match", ",", "tf", ".", "int32", ")", "return", "tf", ".", "greater_equal", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
_do_scale
Rescale the image by scaling the smaller spatial dimension to `size`.
tensor2tensor/data_generators/imagenet.py
def _do_scale(image, size): """Rescale the image by scaling the smaller spatial dimension to `size`.""" shape = tf.cast(tf.shape(image), tf.float32) w_greater = tf.greater(shape[0], shape[1]) shape = tf.cond(w_greater, lambda: tf.cast([shape[0] / shape[1] * size, size], tf.int32), lambda: tf.cast([size, shape[1] / shape[0] * size], tf.int32)) return tf.image.resize_bicubic([image], shape)[0]
def _do_scale(image, size): """Rescale the image by scaling the smaller spatial dimension to `size`.""" shape = tf.cast(tf.shape(image), tf.float32) w_greater = tf.greater(shape[0], shape[1]) shape = tf.cond(w_greater, lambda: tf.cast([shape[0] / shape[1] * size, size], tf.int32), lambda: tf.cast([size, shape[1] / shape[0] * size], tf.int32)) return tf.image.resize_bicubic([image], shape)[0]
[ "Rescale", "the", "image", "by", "scaling", "the", "smaller", "spatial", "dimension", "to", "size", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/imagenet.py#L559-L567
[ "def", "_do_scale", "(", "image", ",", "size", ")", ":", "shape", "=", "tf", ".", "cast", "(", "tf", ".", "shape", "(", "image", ")", ",", "tf", ".", "float32", ")", "w_greater", "=", "tf", ".", "greater", "(", "shape", "[", "0", "]", ",", "sha...
272500b6efe353aeb638d2745ed56e519462ca31
train
_center_crop
Crops to center of image with specified `size`.
tensor2tensor/data_generators/imagenet.py
def _center_crop(image, size): """Crops to center of image with specified `size`.""" image_height = tf.shape(image)[0] image_width = tf.shape(image)[1] offset_height = ((image_height - size) + 1) / 2 offset_width = ((image_width - size) + 1) / 2 image = _crop(image, offset_height, offset_width, size, size) return image
def _center_crop(image, size): """Crops to center of image with specified `size`.""" image_height = tf.shape(image)[0] image_width = tf.shape(image)[1] offset_height = ((image_height - size) + 1) / 2 offset_width = ((image_width - size) + 1) / 2 image = _crop(image, offset_height, offset_width, size, size) return image
[ "Crops", "to", "center", "of", "image", "with", "specified", "size", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/imagenet.py#L570-L578
[ "def", "_center_crop", "(", "image", ",", "size", ")", ":", "image_height", "=", "tf", ".", "shape", "(", "image", ")", "[", "0", "]", "image_width", "=", "tf", ".", "shape", "(", "image", ")", "[", "1", "]", "offset_height", "=", "(", "(", "image_...
272500b6efe353aeb638d2745ed56e519462ca31
train
_normalize
Normalize the image to zero mean and unit variance.
tensor2tensor/data_generators/imagenet.py
def _normalize(image): """Normalize the image to zero mean and unit variance.""" offset = tf.constant(MEAN_RGB, shape=[1, 1, 3]) image -= offset scale = tf.constant(STDDEV_RGB, shape=[1, 1, 3]) image /= scale return image
def _normalize(image): """Normalize the image to zero mean and unit variance.""" offset = tf.constant(MEAN_RGB, shape=[1, 1, 3]) image -= offset scale = tf.constant(STDDEV_RGB, shape=[1, 1, 3]) image /= scale return image
[ "Normalize", "the", "image", "to", "zero", "mean", "and", "unit", "variance", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/imagenet.py#L581-L588
[ "def", "_normalize", "(", "image", ")", ":", "offset", "=", "tf", ".", "constant", "(", "MEAN_RGB", ",", "shape", "=", "[", "1", ",", "1", ",", "3", "]", ")", "image", "-=", "offset", "scale", "=", "tf", ".", "constant", "(", "STDDEV_RGB", ",", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
preprocess_for_train
Preprocesses the given image for evaluation. Args: image: `Tensor` representing an image of arbitrary size. image_size: int, how large the output image should be. normalize: bool, if True the image is normalized. Returns: A preprocessed image `Tensor`.
tensor2tensor/data_generators/imagenet.py
def preprocess_for_train(image, image_size=224, normalize=True): """Preprocesses the given image for evaluation. Args: image: `Tensor` representing an image of arbitrary size. image_size: int, how large the output image should be. normalize: bool, if True the image is normalized. Returns: A preprocessed image `Tensor`. """ if normalize: image = tf.to_float(image) / 255.0 image = _random_crop(image, image_size) if normalize: image = _normalize(image) image = _flip(image) image = tf.reshape(image, [image_size, image_size, 3]) return image
def preprocess_for_train(image, image_size=224, normalize=True): """Preprocesses the given image for evaluation. Args: image: `Tensor` representing an image of arbitrary size. image_size: int, how large the output image should be. normalize: bool, if True the image is normalized. Returns: A preprocessed image `Tensor`. """ if normalize: image = tf.to_float(image) / 255.0 image = _random_crop(image, image_size) if normalize: image = _normalize(image) image = _flip(image) image = tf.reshape(image, [image_size, image_size, 3]) return image
[ "Preprocesses", "the", "given", "image", "for", "evaluation", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/imagenet.py#L591-L607
[ "def", "preprocess_for_train", "(", "image", ",", "image_size", "=", "224", ",", "normalize", "=", "True", ")", ":", "if", "normalize", ":", "image", "=", "tf", ".", "to_float", "(", "image", ")", "/", "255.0", "image", "=", "_random_crop", "(", "image",...
272500b6efe353aeb638d2745ed56e519462ca31
train
preprocess_for_eval
Preprocesses the given image for evaluation. Args: image: `Tensor` representing an image of arbitrary size. image_size: int, how large the output image should be. normalize: bool, if True the image is normalized. Returns: A preprocessed image `Tensor`.
tensor2tensor/data_generators/imagenet.py
def preprocess_for_eval(image, image_size=224, normalize=True): """Preprocesses the given image for evaluation. Args: image: `Tensor` representing an image of arbitrary size. image_size: int, how large the output image should be. normalize: bool, if True the image is normalized. Returns: A preprocessed image `Tensor`. """ if normalize: image = tf.to_float(image) / 255.0 image = _do_scale(image, image_size + 32) if normalize: image = _normalize(image) image = _center_crop(image, image_size) image = tf.reshape(image, [image_size, image_size, 3]) return image
def preprocess_for_eval(image, image_size=224, normalize=True): """Preprocesses the given image for evaluation. Args: image: `Tensor` representing an image of arbitrary size. image_size: int, how large the output image should be. normalize: bool, if True the image is normalized. Returns: A preprocessed image `Tensor`. """ if normalize: image = tf.to_float(image) / 255.0 image = _do_scale(image, image_size + 32) if normalize: image = _normalize(image) image = _center_crop(image, image_size) image = tf.reshape(image, [image_size, image_size, 3]) return image
[ "Preprocesses", "the", "given", "image", "for", "evaluation", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/imagenet.py#L610-L626
[ "def", "preprocess_for_eval", "(", "image", ",", "image_size", "=", "224", ",", "normalize", "=", "True", ")", ":", "if", "normalize", ":", "image", "=", "tf", ".", "to_float", "(", "image", ")", "/", "255.0", "image", "=", "_do_scale", "(", "image", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
MultifactorSchedule
Factor-based learning rate schedule. Interprets factors in the factors string which can consist of: * constant: interpreted as the constant value, * linear_warmup: interpreted as linear warmup until warmup_steps, * rsqrt_decay: divide by square root of max(step, warmup_steps) * decay_every: Every k steps decay the learning rate by decay_factor. Args: history: the history of training and evaluation (History object). factors: a string with factors separated by "*" that defines the schedule. constant: float, the starting constant for the learning rate schedule. warmup_steps: how many steps to warm up for in the warmup schedule. decay_factor: The amount to decay the learning rate by. steps_per_decay: How often to decay the learning rate. Returns: a function learning_rate(step): float -> float, the step-dependent lr.
tensor2tensor/trax/learning_rate.py
def MultifactorSchedule(history=None, factors="constant * linear_warmup * rsqrt_decay", constant=0.1, warmup_steps=100, decay_factor=0.5, steps_per_decay=20000): """Factor-based learning rate schedule. Interprets factors in the factors string which can consist of: * constant: interpreted as the constant value, * linear_warmup: interpreted as linear warmup until warmup_steps, * rsqrt_decay: divide by square root of max(step, warmup_steps) * decay_every: Every k steps decay the learning rate by decay_factor. Args: history: the history of training and evaluation (History object). factors: a string with factors separated by "*" that defines the schedule. constant: float, the starting constant for the learning rate schedule. warmup_steps: how many steps to warm up for in the warmup schedule. decay_factor: The amount to decay the learning rate by. steps_per_decay: How often to decay the learning rate. Returns: a function learning_rate(step): float -> float, the step-dependent lr. """ del history cache_args = (factors, constant, warmup_steps) if cache_args in _memoized_multifactor_schedules: return _memoized_multifactor_schedules[cache_args] factors = [n.strip() for n in factors.split("*")] def learning_rate(step): # pylint: disable=invalid-name """Step to learning rate function.""" ret = 1.0 for name in factors: if name == "constant": ret *= constant elif name == "linear_warmup": ret *= np.minimum(1.0, step / warmup_steps) elif name == "rsqrt_decay": ret /= np.sqrt(np.maximum(step, warmup_steps)) elif name == "decay_every": ret *= (decay_factor ** (step//steps_per_decay)) else: raise ValueError("Unknown factor %s." % name) return ret _memoized_multifactor_schedules[cache_args] = learning_rate return learning_rate
def MultifactorSchedule(history=None, factors="constant * linear_warmup * rsqrt_decay", constant=0.1, warmup_steps=100, decay_factor=0.5, steps_per_decay=20000): """Factor-based learning rate schedule. Interprets factors in the factors string which can consist of: * constant: interpreted as the constant value, * linear_warmup: interpreted as linear warmup until warmup_steps, * rsqrt_decay: divide by square root of max(step, warmup_steps) * decay_every: Every k steps decay the learning rate by decay_factor. Args: history: the history of training and evaluation (History object). factors: a string with factors separated by "*" that defines the schedule. constant: float, the starting constant for the learning rate schedule. warmup_steps: how many steps to warm up for in the warmup schedule. decay_factor: The amount to decay the learning rate by. steps_per_decay: How often to decay the learning rate. Returns: a function learning_rate(step): float -> float, the step-dependent lr. """ del history cache_args = (factors, constant, warmup_steps) if cache_args in _memoized_multifactor_schedules: return _memoized_multifactor_schedules[cache_args] factors = [n.strip() for n in factors.split("*")] def learning_rate(step): # pylint: disable=invalid-name """Step to learning rate function.""" ret = 1.0 for name in factors: if name == "constant": ret *= constant elif name == "linear_warmup": ret *= np.minimum(1.0, step / warmup_steps) elif name == "rsqrt_decay": ret /= np.sqrt(np.maximum(step, warmup_steps)) elif name == "decay_every": ret *= (decay_factor ** (step//steps_per_decay)) else: raise ValueError("Unknown factor %s." % name) return ret _memoized_multifactor_schedules[cache_args] = learning_rate return learning_rate
[ "Factor", "-", "based", "learning", "rate", "schedule", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/learning_rate.py#L42-L92
[ "def", "MultifactorSchedule", "(", "history", "=", "None", ",", "factors", "=", "\"constant * linear_warmup * rsqrt_decay\"", ",", "constant", "=", "0.1", ",", "warmup_steps", "=", "100", ",", "decay_factor", "=", "0.5", ",", "steps_per_decay", "=", "20000", ")", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
EvalAdjustingSchedule
Learning rate that decreases when eval metric stalls. If the chosen metric does not improve by improvement_margin for as many as steps_to_decrease steps, then the constant gets decreased by decrease rate. Finally, the MultifactorSchedule gets called with the adjusted constant. Args: history: trax.history.History, the history of training and evaluation. constant: float, the starting constant for the learning rate schedule. steps_to_decrease: int, after how many steps without improvement should we decrease the constant. improvement_margin: how much we need to improve to consider the metric improved. decrease_rate: by what fraction to decrease (i.e. lr /= decrease_rate). history_mode: str, which mode of the history to use. metric: which evaluation metric to use for adjustments. Returns: a function learning_rate(step): float -> float, the step-dependent lr.
tensor2tensor/trax/learning_rate.py
def EvalAdjustingSchedule(history, constant=0.1, steps_to_decrease=20, improvement_margin=0.001, decrease_rate=1.5, history_mode="eval", metric="metrics/accuracy"): """Learning rate that decreases when eval metric stalls. If the chosen metric does not improve by improvement_margin for as many as steps_to_decrease steps, then the constant gets decreased by decrease rate. Finally, the MultifactorSchedule gets called with the adjusted constant. Args: history: trax.history.History, the history of training and evaluation. constant: float, the starting constant for the learning rate schedule. steps_to_decrease: int, after how many steps without improvement should we decrease the constant. improvement_margin: how much we need to improve to consider the metric improved. decrease_rate: by what fraction to decrease (i.e. lr /= decrease_rate). history_mode: str, which mode of the history to use. metric: which evaluation metric to use for adjustments. Returns: a function learning_rate(step): float -> float, the step-dependent lr. """ metrics = history.get(history_mode, metric) adjusted = constant if len(metrics) < 2: return MultifactorSchedule(history, constant=adjusted) steps_without_improvement = 0 cur = metrics.pop()[1] # The most-recent value of the metric. while len(metrics) > 1: # The one-before value of metrics as .pop() removes one element each time. prev = metrics.pop()[1] if cur < prev * (1 + improvement_margin): steps_without_improvement += 1 else: cur = prev steps_without_improvement = 0 if steps_without_improvement >= steps_to_decrease: adjusted /= decrease_rate cur = prev steps_without_improvement = 0 return MultifactorSchedule(history, constant=adjusted)
def EvalAdjustingSchedule(history, constant=0.1, steps_to_decrease=20, improvement_margin=0.001, decrease_rate=1.5, history_mode="eval", metric="metrics/accuracy"): """Learning rate that decreases when eval metric stalls. If the chosen metric does not improve by improvement_margin for as many as steps_to_decrease steps, then the constant gets decreased by decrease rate. Finally, the MultifactorSchedule gets called with the adjusted constant. Args: history: trax.history.History, the history of training and evaluation. constant: float, the starting constant for the learning rate schedule. steps_to_decrease: int, after how many steps without improvement should we decrease the constant. improvement_margin: how much we need to improve to consider the metric improved. decrease_rate: by what fraction to decrease (i.e. lr /= decrease_rate). history_mode: str, which mode of the history to use. metric: which evaluation metric to use for adjustments. Returns: a function learning_rate(step): float -> float, the step-dependent lr. """ metrics = history.get(history_mode, metric) adjusted = constant if len(metrics) < 2: return MultifactorSchedule(history, constant=adjusted) steps_without_improvement = 0 cur = metrics.pop()[1] # The most-recent value of the metric. while len(metrics) > 1: # The one-before value of metrics as .pop() removes one element each time. prev = metrics.pop()[1] if cur < prev * (1 + improvement_margin): steps_without_improvement += 1 else: cur = prev steps_without_improvement = 0 if steps_without_improvement >= steps_to_decrease: adjusted /= decrease_rate cur = prev steps_without_improvement = 0 return MultifactorSchedule(history, constant=adjusted)
[ "Learning", "rate", "that", "decreases", "when", "eval", "metric", "stalls", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/learning_rate.py#L96-L143
[ "def", "EvalAdjustingSchedule", "(", "history", ",", "constant", "=", "0.1", ",", "steps_to_decrease", "=", "20", ",", "improvement_margin", "=", "0.001", ",", "decrease_rate", "=", "1.5", ",", "history_mode", "=", "\"eval\"", ",", "metric", "=", "\"metrics/accu...
272500b6efe353aeb638d2745ed56e519462ca31
train
project_hidden
Project encoder hidden state under num_blocks using projection tensors. Args: x: Encoder hidden state of shape [batch_size, latent_dim, hidden_size]. projection_tensors: Projection tensors used to project the hidden state. hidden_size: Dimension of the latent space. num_blocks: Number of blocks in DVQ. Returns: x_projected: Projected states of shape [batch_size, latent_dim, num_blocks, hidden_size / num_blocks].
tensor2tensor/layers/discretization.py
def project_hidden(x, projection_tensors, hidden_size, num_blocks): """Project encoder hidden state under num_blocks using projection tensors. Args: x: Encoder hidden state of shape [batch_size, latent_dim, hidden_size]. projection_tensors: Projection tensors used to project the hidden state. hidden_size: Dimension of the latent space. num_blocks: Number of blocks in DVQ. Returns: x_projected: Projected states of shape [batch_size, latent_dim, num_blocks, hidden_size / num_blocks]. """ batch_size, latent_dim, _ = common_layers.shape_list(x) x = tf.reshape(x, shape=[1, -1, hidden_size]) x_tiled = tf.reshape( tf.tile(x, multiples=[num_blocks, 1, 1]), shape=[num_blocks, -1, hidden_size]) x_projected = tf.matmul(x_tiled, projection_tensors) x_projected = tf.transpose(x_projected, perm=[1, 0, 2]) x_4d = tf.reshape(x_projected, [batch_size, latent_dim, num_blocks, -1]) return x_4d
def project_hidden(x, projection_tensors, hidden_size, num_blocks): """Project encoder hidden state under num_blocks using projection tensors. Args: x: Encoder hidden state of shape [batch_size, latent_dim, hidden_size]. projection_tensors: Projection tensors used to project the hidden state. hidden_size: Dimension of the latent space. num_blocks: Number of blocks in DVQ. Returns: x_projected: Projected states of shape [batch_size, latent_dim, num_blocks, hidden_size / num_blocks]. """ batch_size, latent_dim, _ = common_layers.shape_list(x) x = tf.reshape(x, shape=[1, -1, hidden_size]) x_tiled = tf.reshape( tf.tile(x, multiples=[num_blocks, 1, 1]), shape=[num_blocks, -1, hidden_size]) x_projected = tf.matmul(x_tiled, projection_tensors) x_projected = tf.transpose(x_projected, perm=[1, 0, 2]) x_4d = tf.reshape(x_projected, [batch_size, latent_dim, num_blocks, -1]) return x_4d
[ "Project", "encoder", "hidden", "state", "under", "num_blocks", "using", "projection", "tensors", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/discretization.py#L33-L54
[ "def", "project_hidden", "(", "x", ",", "projection_tensors", ",", "hidden_size", ",", "num_blocks", ")", ":", "batch_size", ",", "latent_dim", ",", "_", "=", "common_layers", ".", "shape_list", "(", "x", ")", "x", "=", "tf", ".", "reshape", "(", "x", ",...
272500b6efe353aeb638d2745ed56e519462ca31
train
slice_hidden
Slice encoder hidden state under num_blocks. Args: x: Encoder hidden state of shape [batch_size, latent_dim, hidden_size]. hidden_size: Dimension of the latent space. num_blocks: Number of blocks in DVQ. Returns: Sliced states of shape [batch_size, latent_dim, num_blocks, block_dim].
tensor2tensor/layers/discretization.py
def slice_hidden(x, hidden_size, num_blocks): """Slice encoder hidden state under num_blocks. Args: x: Encoder hidden state of shape [batch_size, latent_dim, hidden_size]. hidden_size: Dimension of the latent space. num_blocks: Number of blocks in DVQ. Returns: Sliced states of shape [batch_size, latent_dim, num_blocks, block_dim]. """ batch_size, latent_dim, _ = common_layers.shape_list(x) block_dim = hidden_size // num_blocks x_sliced = tf.reshape(x, shape=[batch_size, latent_dim, num_blocks, block_dim]) return x_sliced
def slice_hidden(x, hidden_size, num_blocks): """Slice encoder hidden state under num_blocks. Args: x: Encoder hidden state of shape [batch_size, latent_dim, hidden_size]. hidden_size: Dimension of the latent space. num_blocks: Number of blocks in DVQ. Returns: Sliced states of shape [batch_size, latent_dim, num_blocks, block_dim]. """ batch_size, latent_dim, _ = common_layers.shape_list(x) block_dim = hidden_size // num_blocks x_sliced = tf.reshape(x, shape=[batch_size, latent_dim, num_blocks, block_dim]) return x_sliced
[ "Slice", "encoder", "hidden", "state", "under", "num_blocks", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/discretization.py#L57-L72
[ "def", "slice_hidden", "(", "x", ",", "hidden_size", ",", "num_blocks", ")", ":", "batch_size", ",", "latent_dim", ",", "_", "=", "common_layers", ".", "shape_list", "(", "x", ")", "block_dim", "=", "hidden_size", "//", "num_blocks", "x_sliced", "=", "tf", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
nearest_neighbor
Find the nearest element in means to elements in x. Args: x: Continuous encodings of shape [batch_size, latent_dim, num_blocks, block_dim]. means: Embedding table of shape [num_blocks, block_v_size, block_dim]. block_v_size: Number of table entries per block. random_top_k: Noisy top-k if this is bigger than 1. soft_em: If True then use soft EM rather than hard EM. num_samples: Number of samples to take in soft EM. sum_over_latents: Whether to sum over non-batch dimensions when calculating negative entropy loss. Used only when doing soft EM. summary: If True then record summary histogram of entropies. Returns: Tensor with nearest element in mean encoded in one-hot notation and distances.
tensor2tensor/layers/discretization.py
def nearest_neighbor(x, means, block_v_size, random_top_k=1, soft_em=False, num_samples=1, sum_over_latents=False, summary=True): """Find the nearest element in means to elements in x. Args: x: Continuous encodings of shape [batch_size, latent_dim, num_blocks, block_dim]. means: Embedding table of shape [num_blocks, block_v_size, block_dim]. block_v_size: Number of table entries per block. random_top_k: Noisy top-k if this is bigger than 1. soft_em: If True then use soft EM rather than hard EM. num_samples: Number of samples to take in soft EM. sum_over_latents: Whether to sum over non-batch dimensions when calculating negative entropy loss. Used only when doing soft EM. summary: If True then record summary histogram of entropies. Returns: Tensor with nearest element in mean encoded in one-hot notation and distances. """ batch_size, latent_dim, num_blocks, block_dim = common_layers.shape_list(x) x = tf.reshape(x, [batch_size * latent_dim, num_blocks, block_dim]) x_norm_sq = tf.reduce_sum(tf.square(x), axis=-1, keep_dims=True) means_norm_sq = tf.reduce_sum(tf.square(means), axis=-1, keep_dims=True) scalar_prod = tf.matmul( tf.transpose(x, perm=[1, 0, 2]), tf.transpose(means, perm=[0, 2, 1])) scalar_prod = tf.transpose(scalar_prod, perm=[1, 0, 2]) dist = x_norm_sq + tf.transpose( means_norm_sq, perm=[2, 0, 1]) - 2 * scalar_prod # computing cluster probabilities if soft_em: num_blocks = common_layers.shape_list(dist)[1] nearest_idx = tf.stack( [ tf.multinomial(-dist[:, i, :], num_samples=num_samples) for i in range(num_blocks) ], axis=1) nearest_hot = tf.one_hot(nearest_idx, depth=block_v_size) neg_q_entropy = tf.reduce_sum( nearest_hot * tf.expand_dims(tf.nn.log_softmax(-dist), 2), axis=2) if sum_over_latents: neg_q_entropy = tf.reduce_sum(neg_q_entropy, [1, 2]) neg_q_entropy = tf.reduce_mean(neg_q_entropy, axis=0) nearest_hot = tf.reduce_mean(nearest_hot, axis=-2) if summary: tf.summary.histogram("neg_q_entropy", tf.reshape(neg_q_entropy, [-1])) else: neg_q_entropy = 0. if random_top_k > 1: _, top_k_idx = tf.nn.top_k(-dist, k=random_top_k) nearest_idx = tf.gather( top_k_idx, tf.random_uniform( [1], minval=0, maxval=random_top_k - 1, dtype=tf.int32), axis=-1) else: nearest_idx = tf.argmax(-dist, axis=-1) nearest_hot = tf.one_hot(nearest_idx, block_v_size) return nearest_hot, neg_q_entropy
def nearest_neighbor(x, means, block_v_size, random_top_k=1, soft_em=False, num_samples=1, sum_over_latents=False, summary=True): """Find the nearest element in means to elements in x. Args: x: Continuous encodings of shape [batch_size, latent_dim, num_blocks, block_dim]. means: Embedding table of shape [num_blocks, block_v_size, block_dim]. block_v_size: Number of table entries per block. random_top_k: Noisy top-k if this is bigger than 1. soft_em: If True then use soft EM rather than hard EM. num_samples: Number of samples to take in soft EM. sum_over_latents: Whether to sum over non-batch dimensions when calculating negative entropy loss. Used only when doing soft EM. summary: If True then record summary histogram of entropies. Returns: Tensor with nearest element in mean encoded in one-hot notation and distances. """ batch_size, latent_dim, num_blocks, block_dim = common_layers.shape_list(x) x = tf.reshape(x, [batch_size * latent_dim, num_blocks, block_dim]) x_norm_sq = tf.reduce_sum(tf.square(x), axis=-1, keep_dims=True) means_norm_sq = tf.reduce_sum(tf.square(means), axis=-1, keep_dims=True) scalar_prod = tf.matmul( tf.transpose(x, perm=[1, 0, 2]), tf.transpose(means, perm=[0, 2, 1])) scalar_prod = tf.transpose(scalar_prod, perm=[1, 0, 2]) dist = x_norm_sq + tf.transpose( means_norm_sq, perm=[2, 0, 1]) - 2 * scalar_prod # computing cluster probabilities if soft_em: num_blocks = common_layers.shape_list(dist)[1] nearest_idx = tf.stack( [ tf.multinomial(-dist[:, i, :], num_samples=num_samples) for i in range(num_blocks) ], axis=1) nearest_hot = tf.one_hot(nearest_idx, depth=block_v_size) neg_q_entropy = tf.reduce_sum( nearest_hot * tf.expand_dims(tf.nn.log_softmax(-dist), 2), axis=2) if sum_over_latents: neg_q_entropy = tf.reduce_sum(neg_q_entropy, [1, 2]) neg_q_entropy = tf.reduce_mean(neg_q_entropy, axis=0) nearest_hot = tf.reduce_mean(nearest_hot, axis=-2) if summary: tf.summary.histogram("neg_q_entropy", tf.reshape(neg_q_entropy, [-1])) else: neg_q_entropy = 0. if random_top_k > 1: _, top_k_idx = tf.nn.top_k(-dist, k=random_top_k) nearest_idx = tf.gather( top_k_idx, tf.random_uniform( [1], minval=0, maxval=random_top_k - 1, dtype=tf.int32), axis=-1) else: nearest_idx = tf.argmax(-dist, axis=-1) nearest_hot = tf.one_hot(nearest_idx, block_v_size) return nearest_hot, neg_q_entropy
[ "Find", "the", "nearest", "element", "in", "means", "to", "elements", "in", "x", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/discretization.py#L75-L141
[ "def", "nearest_neighbor", "(", "x", ",", "means", ",", "block_v_size", ",", "random_top_k", "=", "1", ",", "soft_em", "=", "False", ",", "num_samples", "=", "1", ",", "sum_over_latents", "=", "False", ",", "summary", "=", "True", ")", ":", "batch_size", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
embedding_lookup
Compute nearest neighbors and loss for training the embeddings via DVQ. Args: x: Continuous encodings of shape [batch_size, latent_dim, num_blocks, block_dim]. means: Embedding table of shape [num_blocks, block_v_size, block_dim]. num_blocks: Number of blocks in DVQ. block_v_size: Number of table entries per block. bottleneck_kind: Discrete bottleneck type. random_top_k: Noisy top-k if this is bigger than 1. soft_em: If True then use soft EM rather than hard EM. num_samples: Number of samples to use for soft EM. do_hard_gumbel_softmax: Whether to use hard or soft Gumbel-Softmax samples for gumbel-softmax-dvq bottleneck. temperature_warmup_steps: Number of steps it takes to decay temperature to 0. Used only if bottleneck_kind is gumbel-softmax-dvq. num_flows: Number of inverse autoregressive flows for gumbel-softmax-dvq bottleneck. approximate_gs_entropy: Whether to approximate the Gumbel-Softmax density as a categorical distribution when calculating the sample entropy. Used only if bottleneck_kind is gumbel-softmax-dvq. sum_over_latents: Whether to sum over non-batch dimensions when calculating negative entropy loss. Used only if soft EM or when bottleneck_kind is gumbel-softmax-dvq. Returns: x_means_hot: The nearest neighbor in one hot form, with shape [batch_size * latent_dim, num_blocks, block_v_size]. x_means: The nearest neighbor itself, with shape [batch_size * latent_dim, num_blocks, block_dim]. q_loss: Scalar Tensor representing codebook loss. e_loss: Scalar Tensor representing commitment loss. neg_q_entropy: Scalar Tensor representing negative entropy of variational approximation (0 if it is deterministic).
tensor2tensor/layers/discretization.py
def embedding_lookup(x, means, num_blocks, block_v_size, bottleneck_kind="dvq", random_top_k=1, soft_em=False, num_samples=1, do_hard_gumbel_softmax=False, temperature_warmup_steps=150000, num_flows=0, approximate_gs_entropy=False, sum_over_latents=False): """Compute nearest neighbors and loss for training the embeddings via DVQ. Args: x: Continuous encodings of shape [batch_size, latent_dim, num_blocks, block_dim]. means: Embedding table of shape [num_blocks, block_v_size, block_dim]. num_blocks: Number of blocks in DVQ. block_v_size: Number of table entries per block. bottleneck_kind: Discrete bottleneck type. random_top_k: Noisy top-k if this is bigger than 1. soft_em: If True then use soft EM rather than hard EM. num_samples: Number of samples to use for soft EM. do_hard_gumbel_softmax: Whether to use hard or soft Gumbel-Softmax samples for gumbel-softmax-dvq bottleneck. temperature_warmup_steps: Number of steps it takes to decay temperature to 0. Used only if bottleneck_kind is gumbel-softmax-dvq. num_flows: Number of inverse autoregressive flows for gumbel-softmax-dvq bottleneck. approximate_gs_entropy: Whether to approximate the Gumbel-Softmax density as a categorical distribution when calculating the sample entropy. Used only if bottleneck_kind is gumbel-softmax-dvq. sum_over_latents: Whether to sum over non-batch dimensions when calculating negative entropy loss. Used only if soft EM or when bottleneck_kind is gumbel-softmax-dvq. Returns: x_means_hot: The nearest neighbor in one hot form, with shape [batch_size * latent_dim, num_blocks, block_v_size]. x_means: The nearest neighbor itself, with shape [batch_size * latent_dim, num_blocks, block_dim]. q_loss: Scalar Tensor representing codebook loss. e_loss: Scalar Tensor representing commitment loss. neg_q_entropy: Scalar Tensor representing negative entropy of variational approximation (0 if it is deterministic). """ if bottleneck_kind == "gumbel-softmax-dvq": x_means_hot, neg_q_entropy = gumbel_softmax_nearest_neighbor_dvq( x, means, block_v_size, hard=do_hard_gumbel_softmax, num_samples=num_samples, temperature_warmup_steps=temperature_warmup_steps, num_flows=num_flows, approximate_gs_entropy=approximate_gs_entropy, sum_over_latents=sum_over_latents) else: x_means_hot, neg_q_entropy = nearest_neighbor( x, means, block_v_size, random_top_k, soft_em=soft_em, num_samples=num_samples, sum_over_latents=sum_over_latents) x_means_hot_flat = tf.reshape(x_means_hot, [-1, num_blocks, block_v_size]) x_means = tf.matmul(tf.transpose(x_means_hot_flat, perm=[1, 0, 2]), means) x_means = tf.transpose(x_means, [1, 0, 2]) batch_size, latent_dim, num_blocks, block_dim = common_layers.shape_list(x) x = tf.reshape(x, [batch_size * latent_dim, num_blocks, block_dim]) # Currently, we use the mean scaling for the commitment loss, as opposed to # summing across all non-batch dimensions. q_loss = tf.reduce_mean(tf.squared_difference(tf.stop_gradient(x), x_means)) e_loss = tf.reduce_mean(tf.squared_difference(x, tf.stop_gradient(x_means))) return x_means_hot, x_means, q_loss, e_loss, neg_q_entropy
def embedding_lookup(x, means, num_blocks, block_v_size, bottleneck_kind="dvq", random_top_k=1, soft_em=False, num_samples=1, do_hard_gumbel_softmax=False, temperature_warmup_steps=150000, num_flows=0, approximate_gs_entropy=False, sum_over_latents=False): """Compute nearest neighbors and loss for training the embeddings via DVQ. Args: x: Continuous encodings of shape [batch_size, latent_dim, num_blocks, block_dim]. means: Embedding table of shape [num_blocks, block_v_size, block_dim]. num_blocks: Number of blocks in DVQ. block_v_size: Number of table entries per block. bottleneck_kind: Discrete bottleneck type. random_top_k: Noisy top-k if this is bigger than 1. soft_em: If True then use soft EM rather than hard EM. num_samples: Number of samples to use for soft EM. do_hard_gumbel_softmax: Whether to use hard or soft Gumbel-Softmax samples for gumbel-softmax-dvq bottleneck. temperature_warmup_steps: Number of steps it takes to decay temperature to 0. Used only if bottleneck_kind is gumbel-softmax-dvq. num_flows: Number of inverse autoregressive flows for gumbel-softmax-dvq bottleneck. approximate_gs_entropy: Whether to approximate the Gumbel-Softmax density as a categorical distribution when calculating the sample entropy. Used only if bottleneck_kind is gumbel-softmax-dvq. sum_over_latents: Whether to sum over non-batch dimensions when calculating negative entropy loss. Used only if soft EM or when bottleneck_kind is gumbel-softmax-dvq. Returns: x_means_hot: The nearest neighbor in one hot form, with shape [batch_size * latent_dim, num_blocks, block_v_size]. x_means: The nearest neighbor itself, with shape [batch_size * latent_dim, num_blocks, block_dim]. q_loss: Scalar Tensor representing codebook loss. e_loss: Scalar Tensor representing commitment loss. neg_q_entropy: Scalar Tensor representing negative entropy of variational approximation (0 if it is deterministic). """ if bottleneck_kind == "gumbel-softmax-dvq": x_means_hot, neg_q_entropy = gumbel_softmax_nearest_neighbor_dvq( x, means, block_v_size, hard=do_hard_gumbel_softmax, num_samples=num_samples, temperature_warmup_steps=temperature_warmup_steps, num_flows=num_flows, approximate_gs_entropy=approximate_gs_entropy, sum_over_latents=sum_over_latents) else: x_means_hot, neg_q_entropy = nearest_neighbor( x, means, block_v_size, random_top_k, soft_em=soft_em, num_samples=num_samples, sum_over_latents=sum_over_latents) x_means_hot_flat = tf.reshape(x_means_hot, [-1, num_blocks, block_v_size]) x_means = tf.matmul(tf.transpose(x_means_hot_flat, perm=[1, 0, 2]), means) x_means = tf.transpose(x_means, [1, 0, 2]) batch_size, latent_dim, num_blocks, block_dim = common_layers.shape_list(x) x = tf.reshape(x, [batch_size * latent_dim, num_blocks, block_dim]) # Currently, we use the mean scaling for the commitment loss, as opposed to # summing across all non-batch dimensions. q_loss = tf.reduce_mean(tf.squared_difference(tf.stop_gradient(x), x_means)) e_loss = tf.reduce_mean(tf.squared_difference(x, tf.stop_gradient(x_means))) return x_means_hot, x_means, q_loss, e_loss, neg_q_entropy
[ "Compute", "nearest", "neighbors", "and", "loss", "for", "training", "the", "embeddings", "via", "DVQ", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/discretization.py#L144-L222
[ "def", "embedding_lookup", "(", "x", ",", "means", ",", "num_blocks", ",", "block_v_size", ",", "bottleneck_kind", "=", "\"dvq\"", ",", "random_top_k", "=", "1", ",", "soft_em", "=", "False", ",", "num_samples", "=", "1", ",", "do_hard_gumbel_softmax", "=", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
bit_to_int
Turn x_bit representing numbers bitwise (lower-endian) to int tensor. Args: x_bit: Tensor containing numbers in a particular base to be converted to int. num_bits: Number of bits in the representation. base: Base of the representation. Returns: Integer representation of this number.
tensor2tensor/layers/discretization.py
def bit_to_int(x_bit, num_bits, base=2): """Turn x_bit representing numbers bitwise (lower-endian) to int tensor. Args: x_bit: Tensor containing numbers in a particular base to be converted to int. num_bits: Number of bits in the representation. base: Base of the representation. Returns: Integer representation of this number. """ x_l = tf.stop_gradient(tf.to_int32(tf.reshape(x_bit, [-1, num_bits]))) x_labels = [ x_l[:, i] * tf.to_int32(base)**tf.to_int32(i) for i in range(num_bits)] res = sum(x_labels) return tf.to_int32(tf.reshape(res, common_layers.shape_list(x_bit)[:-1]))
def bit_to_int(x_bit, num_bits, base=2): """Turn x_bit representing numbers bitwise (lower-endian) to int tensor. Args: x_bit: Tensor containing numbers in a particular base to be converted to int. num_bits: Number of bits in the representation. base: Base of the representation. Returns: Integer representation of this number. """ x_l = tf.stop_gradient(tf.to_int32(tf.reshape(x_bit, [-1, num_bits]))) x_labels = [ x_l[:, i] * tf.to_int32(base)**tf.to_int32(i) for i in range(num_bits)] res = sum(x_labels) return tf.to_int32(tf.reshape(res, common_layers.shape_list(x_bit)[:-1]))
[ "Turn", "x_bit", "representing", "numbers", "bitwise", "(", "lower", "-", "endian", ")", "to", "int", "tensor", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/discretization.py#L225-L241
[ "def", "bit_to_int", "(", "x_bit", ",", "num_bits", ",", "base", "=", "2", ")", ":", "x_l", "=", "tf", ".", "stop_gradient", "(", "tf", ".", "to_int32", "(", "tf", ".", "reshape", "(", "x_bit", ",", "[", "-", "1", ",", "num_bits", "]", ")", ")", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
int_to_bit_embed
Turn x_int into a bitwise (lower-endian) tensor and embed densly.
tensor2tensor/layers/discretization.py
def int_to_bit_embed(x_int, num_bits, embedding_size, base=2): """Turn x_int into a bitwise (lower-endian) tensor and embed densly.""" shape = common_layers.shape_list(x_int) inputs = int_to_bit(x_int, num_bits, base=base) inputs = tf.reshape(inputs, shape[:-1] + [shape[-1] * 8]) inputs = 2.0 * tf.to_float(inputs) - 1.0 # Move from 0/1 to -1/1. return tf.layers.dense(inputs, embedding_size, name="int_to_bit_embed")
def int_to_bit_embed(x_int, num_bits, embedding_size, base=2): """Turn x_int into a bitwise (lower-endian) tensor and embed densly.""" shape = common_layers.shape_list(x_int) inputs = int_to_bit(x_int, num_bits, base=base) inputs = tf.reshape(inputs, shape[:-1] + [shape[-1] * 8]) inputs = 2.0 * tf.to_float(inputs) - 1.0 # Move from 0/1 to -1/1. return tf.layers.dense(inputs, embedding_size, name="int_to_bit_embed")
[ "Turn", "x_int", "into", "a", "bitwise", "(", "lower", "-", "endian", ")", "tensor", "and", "embed", "densly", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/discretization.py#L263-L269
[ "def", "int_to_bit_embed", "(", "x_int", ",", "num_bits", ",", "embedding_size", ",", "base", "=", "2", ")", ":", "shape", "=", "common_layers", ".", "shape_list", "(", "x_int", ")", "inputs", "=", "int_to_bit", "(", "x_int", ",", "num_bits", ",", "base", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
embed
Embedding function that takes discrete latent and returns embedding. Args: x: Input to the discretization bottleneck. hidden_size: Dimension of the latent state. z_size: Number of bits, where discrete codes range from 1 to 2**z_size. filter_size: Dimension to project embedding by. Used only if bottleneck_kind is semhash. bottleneck_kind: Kind of discretization bottleneck to use; one of dvq, semhash, gumbel-softmax (Default: dvq). soft_em: If True then it uses a multi-sample version of EM (Default: False). num_blocks: Number of blocks in DVQ (Default: 2). num_residuals: Number of residuals (Default: 1). block_v_size: Number of embedding entries per block (Default: None). means: The embedding table for dvq (Default: None). name: Name for the bottleneck scope. Returns: Continuous embedding to be passed on to the decoder. Raises: ValueError: For unknown or missing arguments.
tensor2tensor/layers/discretization.py
def embed(x, hidden_size, z_size, filter_size, bottleneck_kind="dvq", soft_em=False, num_blocks=2, num_residuals=1, block_v_size=None, means=None, name=None): """Embedding function that takes discrete latent and returns embedding. Args: x: Input to the discretization bottleneck. hidden_size: Dimension of the latent state. z_size: Number of bits, where discrete codes range from 1 to 2**z_size. filter_size: Dimension to project embedding by. Used only if bottleneck_kind is semhash. bottleneck_kind: Kind of discretization bottleneck to use; one of dvq, semhash, gumbel-softmax (Default: dvq). soft_em: If True then it uses a multi-sample version of EM (Default: False). num_blocks: Number of blocks in DVQ (Default: 2). num_residuals: Number of residuals (Default: 1). block_v_size: Number of embedding entries per block (Default: None). means: The embedding table for dvq (Default: None). name: Name for the bottleneck scope. Returns: Continuous embedding to be passed on to the decoder. Raises: ValueError: For unknown or missing arguments. """ with tf.variable_scope(name, default_name="embed", reuse=tf.AUTO_REUSE): if bottleneck_kind == "semhash": c = int_to_bit(x, z_size) h1a = tf.layers.dense(c, filter_size, name="vch1a") h1b = tf.layers.dense(1.0 - c, filter_size, name="vch1b") h1 = h1a + h1b elif bottleneck_kind == "gumbel-softmax": hot = tf.one_hot(x, 2**z_size) h1 = tf.layers.dense(hot, hidden_size, name="dae_dense") elif bottleneck_kind in ["dvq", "gumbel-softmax-dvq"]: if block_v_size is None: raise ValueError("Bottleneck kind is dvq but block_v_size is None.") if soft_em: assert num_residuals == 1 x_hot_flat = tf.reshape(x, shape=[-1, num_blocks, block_v_size]) h1 = tf.matmul(tf.transpose(x_hot_flat, perm=[1, 0, 2]), means[0]) h1 = tf.transpose(h1, perm=[1, 0, 2]) new_shape = common_layers.shape_list(x) new_shape[-1] = hidden_size h1 = tf.reshape(h1, shape=new_shape) else: shape_x = common_layers.shape_list(x) x_flat = tf.reshape(x, [-1, 1]) c = int_to_bit(x_flat, num_bits=z_size, base=2) shape = common_layers.shape_list(c) new_shape = shape new_shape[-1] = num_residuals new_shape.append(num_blocks) new_shape.append(int(z_size / (num_residuals * num_blocks))) c = tf.to_int32(tf.reshape(c, shape=new_shape)) h1_shape = shape_x h1_shape.append(hidden_size) h1 = tf.zeros(dtype=tf.float32, shape=h1_shape) for i in range(num_residuals): c_residual = bit_to_int( c[:, :, i, :, :], num_bits=int(z_size / (num_residuals * num_blocks)), base=2) c_hot = tf.one_hot(c_residual, depth=block_v_size, axis=-1) c_hot_flat = tf.reshape(c_hot, shape=[-1, num_blocks, block_v_size]) h1_residual = tf.matmul( tf.transpose(c_hot_flat, perm=[1, 0, 2]), means[i]) h1_residual = tf.transpose(h1_residual, perm=[1, 0, 2]) h1_residual = tf.reshape(h1_residual, shape=h1_shape) h1 += h1_residual elif bottleneck_kind == "rounding": h1 = x else: raise ValueError("Unknown bottleneck kind.") return h1
def embed(x, hidden_size, z_size, filter_size, bottleneck_kind="dvq", soft_em=False, num_blocks=2, num_residuals=1, block_v_size=None, means=None, name=None): """Embedding function that takes discrete latent and returns embedding. Args: x: Input to the discretization bottleneck. hidden_size: Dimension of the latent state. z_size: Number of bits, where discrete codes range from 1 to 2**z_size. filter_size: Dimension to project embedding by. Used only if bottleneck_kind is semhash. bottleneck_kind: Kind of discretization bottleneck to use; one of dvq, semhash, gumbel-softmax (Default: dvq). soft_em: If True then it uses a multi-sample version of EM (Default: False). num_blocks: Number of blocks in DVQ (Default: 2). num_residuals: Number of residuals (Default: 1). block_v_size: Number of embedding entries per block (Default: None). means: The embedding table for dvq (Default: None). name: Name for the bottleneck scope. Returns: Continuous embedding to be passed on to the decoder. Raises: ValueError: For unknown or missing arguments. """ with tf.variable_scope(name, default_name="embed", reuse=tf.AUTO_REUSE): if bottleneck_kind == "semhash": c = int_to_bit(x, z_size) h1a = tf.layers.dense(c, filter_size, name="vch1a") h1b = tf.layers.dense(1.0 - c, filter_size, name="vch1b") h1 = h1a + h1b elif bottleneck_kind == "gumbel-softmax": hot = tf.one_hot(x, 2**z_size) h1 = tf.layers.dense(hot, hidden_size, name="dae_dense") elif bottleneck_kind in ["dvq", "gumbel-softmax-dvq"]: if block_v_size is None: raise ValueError("Bottleneck kind is dvq but block_v_size is None.") if soft_em: assert num_residuals == 1 x_hot_flat = tf.reshape(x, shape=[-1, num_blocks, block_v_size]) h1 = tf.matmul(tf.transpose(x_hot_flat, perm=[1, 0, 2]), means[0]) h1 = tf.transpose(h1, perm=[1, 0, 2]) new_shape = common_layers.shape_list(x) new_shape[-1] = hidden_size h1 = tf.reshape(h1, shape=new_shape) else: shape_x = common_layers.shape_list(x) x_flat = tf.reshape(x, [-1, 1]) c = int_to_bit(x_flat, num_bits=z_size, base=2) shape = common_layers.shape_list(c) new_shape = shape new_shape[-1] = num_residuals new_shape.append(num_blocks) new_shape.append(int(z_size / (num_residuals * num_blocks))) c = tf.to_int32(tf.reshape(c, shape=new_shape)) h1_shape = shape_x h1_shape.append(hidden_size) h1 = tf.zeros(dtype=tf.float32, shape=h1_shape) for i in range(num_residuals): c_residual = bit_to_int( c[:, :, i, :, :], num_bits=int(z_size / (num_residuals * num_blocks)), base=2) c_hot = tf.one_hot(c_residual, depth=block_v_size, axis=-1) c_hot_flat = tf.reshape(c_hot, shape=[-1, num_blocks, block_v_size]) h1_residual = tf.matmul( tf.transpose(c_hot_flat, perm=[1, 0, 2]), means[i]) h1_residual = tf.transpose(h1_residual, perm=[1, 0, 2]) h1_residual = tf.reshape(h1_residual, shape=h1_shape) h1 += h1_residual elif bottleneck_kind == "rounding": h1 = x else: raise ValueError("Unknown bottleneck kind.") return h1
[ "Embedding", "function", "that", "takes", "discrete", "latent", "and", "returns", "embedding", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/discretization.py#L272-L357
[ "def", "embed", "(", "x", ",", "hidden_size", ",", "z_size", ",", "filter_size", ",", "bottleneck_kind", "=", "\"dvq\"", ",", "soft_em", "=", "False", ",", "num_blocks", "=", "2", ",", "num_residuals", "=", "1", ",", "block_v_size", "=", "None", ",", "me...
272500b6efe353aeb638d2745ed56e519462ca31
train
vae
Simple variational autoencoder without discretization. Args: x: Input to the discretization bottleneck. z_size: Number of bits, where discrete codes range from 1 to 2**z_size. name: Name for the bottleneck scope. Returns: Embedding function, latent, loss, mu and log_simga.
tensor2tensor/layers/discretization.py
def vae(x, z_size, name=None): """Simple variational autoencoder without discretization. Args: x: Input to the discretization bottleneck. z_size: Number of bits, where discrete codes range from 1 to 2**z_size. name: Name for the bottleneck scope. Returns: Embedding function, latent, loss, mu and log_simga. """ with tf.variable_scope(name, default_name="vae"): mu = tf.layers.dense(x, z_size, name="mu") log_sigma = tf.layers.dense(x, z_size, name="log_sigma") shape = common_layers.shape_list(x) epsilon = tf.random_normal([shape[0], shape[1], 1, z_size]) z = mu + tf.exp(log_sigma / 2) * epsilon kl = 0.5 * tf.reduce_mean( tf.expm1(log_sigma) + tf.square(mu) - log_sigma, axis=-1) free_bits = z_size // 4 kl_loss = tf.reduce_mean(tf.maximum(kl - free_bits, 0.0)) return z, kl_loss, mu, log_sigma
def vae(x, z_size, name=None): """Simple variational autoencoder without discretization. Args: x: Input to the discretization bottleneck. z_size: Number of bits, where discrete codes range from 1 to 2**z_size. name: Name for the bottleneck scope. Returns: Embedding function, latent, loss, mu and log_simga. """ with tf.variable_scope(name, default_name="vae"): mu = tf.layers.dense(x, z_size, name="mu") log_sigma = tf.layers.dense(x, z_size, name="log_sigma") shape = common_layers.shape_list(x) epsilon = tf.random_normal([shape[0], shape[1], 1, z_size]) z = mu + tf.exp(log_sigma / 2) * epsilon kl = 0.5 * tf.reduce_mean( tf.expm1(log_sigma) + tf.square(mu) - log_sigma, axis=-1) free_bits = z_size // 4 kl_loss = tf.reduce_mean(tf.maximum(kl - free_bits, 0.0)) return z, kl_loss, mu, log_sigma
[ "Simple", "variational", "autoencoder", "without", "discretization", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/discretization.py#L360-L381
[ "def", "vae", "(", "x", ",", "z_size", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ",", "default_name", "=", "\"vae\"", ")", ":", "mu", "=", "tf", ".", "layers", ".", "dense", "(", "x", ",", "z_size", ","...
272500b6efe353aeb638d2745ed56e519462ca31
train
gumbel_sample
Sample from the Gumbel distribution, protect from overflows. Args: shape: Shape of Gumbel samples. Returns: Noise drawn from Gumbel distribution.
tensor2tensor/layers/discretization.py
def gumbel_sample(shape): """Sample from the Gumbel distribution, protect from overflows. Args: shape: Shape of Gumbel samples. Returns: Noise drawn from Gumbel distribution. """ uniform_samples = tf.random_uniform(shape, minval=0.00001, maxval=0.99998) return -tf.log(-tf.log(uniform_samples))
def gumbel_sample(shape): """Sample from the Gumbel distribution, protect from overflows. Args: shape: Shape of Gumbel samples. Returns: Noise drawn from Gumbel distribution. """ uniform_samples = tf.random_uniform(shape, minval=0.00001, maxval=0.99998) return -tf.log(-tf.log(uniform_samples))
[ "Sample", "from", "the", "Gumbel", "distribution", "protect", "from", "overflows", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/discretization.py#L402-L412
[ "def", "gumbel_sample", "(", "shape", ")", ":", "uniform_samples", "=", "tf", ".", "random_uniform", "(", "shape", ",", "minval", "=", "0.00001", ",", "maxval", "=", "0.99998", ")", "return", "-", "tf", ".", "log", "(", "-", "tf", ".", "log", "(", "u...
272500b6efe353aeb638d2745ed56e519462ca31
train
gumbel_softmax
Gumbel softmax discretization bottleneck. Args: x: Input to the discretization bottleneck. z_size: Number of bits, where discrete codes range from 1 to 2**z_size. mode: tf.estimator.ModeKeys. softmax_k: If > 0 then do top-k softmax. temperature_warmup_steps: Number of steps it takes to decay temperature to 0. summary: Whether to write summaries. name: Name for the bottleneck scope. Returns: Embedding function, discrete code, and loss.
tensor2tensor/layers/discretization.py
def gumbel_softmax(x, z_size, mode, softmax_k=0, temperature_warmup_steps=150000, summary=True, name=None): """Gumbel softmax discretization bottleneck. Args: x: Input to the discretization bottleneck. z_size: Number of bits, where discrete codes range from 1 to 2**z_size. mode: tf.estimator.ModeKeys. softmax_k: If > 0 then do top-k softmax. temperature_warmup_steps: Number of steps it takes to decay temperature to 0. summary: Whether to write summaries. name: Name for the bottleneck scope. Returns: Embedding function, discrete code, and loss. """ with tf.variable_scope(name, default_name="gumbel_softmax"): m = tf.layers.dense(x, 2**z_size, name="mask") if softmax_k > 0: m, kl = top_k_softmax(m, softmax_k) return m, m, 1.0 - tf.reduce_mean(kl) logsm = tf.nn.log_softmax(m) # Gumbel-softmax sample. gumbel_samples = gumbel_sample(common_layers.shape_list(m)) steps = temperature_warmup_steps gumbel_samples *= common_layers.inverse_exp_decay(steps // 5) * 0.5 temperature = 1.2 - common_layers.inverse_lin_decay(steps) # 10% of the time keep reasonably high temperature to keep learning. temperature = tf.cond( tf.less(tf.random_uniform([]), 0.9), lambda: temperature, lambda: tf.random_uniform([], minval=0.5, maxval=1.0)) s = tf.nn.softmax((logsm + gumbel_samples) / temperature) m = tf.nn.softmax(m) kl = -tf.reduce_max(logsm, axis=-1) if summary: tf.summary.histogram("max-log", tf.reshape(kl, [-1])) # Calculate the argmax and construct hot vectors. maxvec = tf.reshape(tf.argmax(m, axis=-1), [-1]) maxvhot = tf.stop_gradient(tf.one_hot(maxvec, 2**z_size)) # Add losses that prevent too few being used. distrib = tf.reshape(logsm, [-1, 2**z_size]) * maxvhot d_mean = tf.reduce_mean(distrib, axis=[0], keep_dims=True) d_variance = tf.reduce_mean( tf.squared_difference(distrib, d_mean), axis=[0]) d_dev = -tf.reduce_mean(d_variance) ret = s if mode != tf.estimator.ModeKeys.TRAIN: ret = tf.reshape(maxvhot, common_layers.shape_list(s)) # Just hot @eval. return m, ret, d_dev * 5.0 + tf.reduce_mean(kl) * 0.002
def gumbel_softmax(x, z_size, mode, softmax_k=0, temperature_warmup_steps=150000, summary=True, name=None): """Gumbel softmax discretization bottleneck. Args: x: Input to the discretization bottleneck. z_size: Number of bits, where discrete codes range from 1 to 2**z_size. mode: tf.estimator.ModeKeys. softmax_k: If > 0 then do top-k softmax. temperature_warmup_steps: Number of steps it takes to decay temperature to 0. summary: Whether to write summaries. name: Name for the bottleneck scope. Returns: Embedding function, discrete code, and loss. """ with tf.variable_scope(name, default_name="gumbel_softmax"): m = tf.layers.dense(x, 2**z_size, name="mask") if softmax_k > 0: m, kl = top_k_softmax(m, softmax_k) return m, m, 1.0 - tf.reduce_mean(kl) logsm = tf.nn.log_softmax(m) # Gumbel-softmax sample. gumbel_samples = gumbel_sample(common_layers.shape_list(m)) steps = temperature_warmup_steps gumbel_samples *= common_layers.inverse_exp_decay(steps // 5) * 0.5 temperature = 1.2 - common_layers.inverse_lin_decay(steps) # 10% of the time keep reasonably high temperature to keep learning. temperature = tf.cond( tf.less(tf.random_uniform([]), 0.9), lambda: temperature, lambda: tf.random_uniform([], minval=0.5, maxval=1.0)) s = tf.nn.softmax((logsm + gumbel_samples) / temperature) m = tf.nn.softmax(m) kl = -tf.reduce_max(logsm, axis=-1) if summary: tf.summary.histogram("max-log", tf.reshape(kl, [-1])) # Calculate the argmax and construct hot vectors. maxvec = tf.reshape(tf.argmax(m, axis=-1), [-1]) maxvhot = tf.stop_gradient(tf.one_hot(maxvec, 2**z_size)) # Add losses that prevent too few being used. distrib = tf.reshape(logsm, [-1, 2**z_size]) * maxvhot d_mean = tf.reduce_mean(distrib, axis=[0], keep_dims=True) d_variance = tf.reduce_mean( tf.squared_difference(distrib, d_mean), axis=[0]) d_dev = -tf.reduce_mean(d_variance) ret = s if mode != tf.estimator.ModeKeys.TRAIN: ret = tf.reshape(maxvhot, common_layers.shape_list(s)) # Just hot @eval. return m, ret, d_dev * 5.0 + tf.reduce_mean(kl) * 0.002
[ "Gumbel", "softmax", "discretization", "bottleneck", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/discretization.py#L415-L475
[ "def", "gumbel_softmax", "(", "x", ",", "z_size", ",", "mode", ",", "softmax_k", "=", "0", ",", "temperature_warmup_steps", "=", "150000", ",", "summary", "=", "True", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
discrete_bottleneck
Discretization bottleneck. Args: inputs: Input to the bottleneck, a Tensor of shape [..., channels]. hidden_size: Dimension of the dense output. z_size: Number of bits, where discrete codes range from 1 to 2**z_size. filter_size: Filter size in the embedding function. mode: tf.estimator.ModeKeys. bottleneck_kind: Kind of discretization bottleneck. One of dense, dvq (decomposed vector quantization), gumbel-softmax, gumbel-softmax-dvq, semhash, or vae. num_blocks: Number of blocks. Used only if bottleneck_kind is DVQ. num_residuals: Number of residual units used to compute nearest neighbors. Used only if bottleneck_kind is DVQ. reshape_method: Method to reshape. Used only if bottleneck_kind is DVQ. projection_tensors: If the reshape method is project, then these are the tensors used to project. beta: Scale factor for codebook loss and EMA. Used only if bottleneck_kind is DVQ. ema: Whether to update embeddings using exponential moving averages. Used only if bottleneck_kind is DVQ. means: The embedding table. Used only if ema is True. ema_count: Table of counts for each embedding corresponding to how many examples in a batch it was the closest to. Used only if ema is True. ema_means: Exponentially averaged version of the embeddings. Used only if ema is True. epsilon: Small value to avoid dividing by zero in EMA update. Used only if ema is True. decay: Decay factor for the exponential moving average. Used only if ema is True. random_top_k: Noisy top-k. Used only if bottleneck_kind is DVQ. soft_em: Whether to use soft EM or hard EM. Used only if bottleneck_kind is DVQ. num_samples: Number of samples for soft EM. Used only if soft_em is True. softmax_k: If > 0 then do top-k softmax. Used only if bottleneck_kind is gumbel-softmax. temperature_warmup_steps: Number of steps it takes to decay temperature to 0. Used only if bottleneck_kind is gumbel-softmax or gumbel-softmax-dvq. do_hard_gumbel_softmax: Whether to use hard or soft Gumbel-Softmax samples. Used only if bottleneck_kind is gumbel-softmax-dvq. num_flows: Number of inverse autoregresive flows. Used only if bottleneck_kind is gumbel-softmax-dvq. approximate_gs_entropy: Whether to approximate the Gumbel-Softmax density as a categorical distribution when calculating the sample entropy. Used only if bottleneck_kind is gumbel-softmax-dvq. sum_over_latents: Whether to sum over all non-batch dimensions before taking mean of entropy loss term. Used only if bottleneck kind is DVQ or gumbel-softmax-dvq. discrete_mix: Factor for mixing discrete and non-discrete input. Used only if bottleneck_kind is semhash. noise_dev: Noise stddev. Used only if bottleneck_kind is semhash. startup_steps: Number of steps after which latent predictor is trained. Used only if bottleneck_kind is semhash. summary: Whether to write summaries. name: Name for the bottleneck scope. cond: A tf.bool condition on whether to update the codebook. Returns: outputs_dense: Tensor of shape [..., output_dim]. The output dimension is hidden_size if bottleneck_kind is gumbel-softmax, DVQ; filter_size if bottleneck_kind is dense, semhash, vae. If bottleneck_kind is DVQ, outputs_dense represents the codebook (means) indexed by outputs_discrete. outputs_discrete: Tensor of shape [...]. Discrete codes, each an index in [0, 2**z_size). It uses the hot representation if soft_em is True. extra_loss: Scalar Tensor. Sum of codebook and commitment losses if bottleneck_kind is DVQ; else zero. embed_fn: Function embed with arguments partially filled in. neg_q_entropy: Scalar Tensor representing negative entropy of variational approximation (0 if it is deterministic). Raises: ValueError: If projection_tensors is None for reshape_method project, or ema_count or ema_means is None if ema is True, or unknown args.
tensor2tensor/layers/discretization.py
def discrete_bottleneck(inputs, hidden_size, z_size, filter_size, mode=None, bottleneck_kind="dvq", num_blocks=2, num_residuals=1, reshape_method="slice", projection_tensors=None, beta=0.25, ema=True, means=None, ema_count=None, ema_means=None, epsilon=1e-5, decay=0.999, random_top_k=1, soft_em=False, num_samples=1, softmax_k=0, temperature_warmup_steps=150000, do_hard_gumbel_softmax=False, num_flows=0, approximate_gs_entropy=False, sum_over_latents=False, discrete_mix=0.5, noise_dev=1., startup_steps=50000, summary=True, name=None, cond=True): """Discretization bottleneck. Args: inputs: Input to the bottleneck, a Tensor of shape [..., channels]. hidden_size: Dimension of the dense output. z_size: Number of bits, where discrete codes range from 1 to 2**z_size. filter_size: Filter size in the embedding function. mode: tf.estimator.ModeKeys. bottleneck_kind: Kind of discretization bottleneck. One of dense, dvq (decomposed vector quantization), gumbel-softmax, gumbel-softmax-dvq, semhash, or vae. num_blocks: Number of blocks. Used only if bottleneck_kind is DVQ. num_residuals: Number of residual units used to compute nearest neighbors. Used only if bottleneck_kind is DVQ. reshape_method: Method to reshape. Used only if bottleneck_kind is DVQ. projection_tensors: If the reshape method is project, then these are the tensors used to project. beta: Scale factor for codebook loss and EMA. Used only if bottleneck_kind is DVQ. ema: Whether to update embeddings using exponential moving averages. Used only if bottleneck_kind is DVQ. means: The embedding table. Used only if ema is True. ema_count: Table of counts for each embedding corresponding to how many examples in a batch it was the closest to. Used only if ema is True. ema_means: Exponentially averaged version of the embeddings. Used only if ema is True. epsilon: Small value to avoid dividing by zero in EMA update. Used only if ema is True. decay: Decay factor for the exponential moving average. Used only if ema is True. random_top_k: Noisy top-k. Used only if bottleneck_kind is DVQ. soft_em: Whether to use soft EM or hard EM. Used only if bottleneck_kind is DVQ. num_samples: Number of samples for soft EM. Used only if soft_em is True. softmax_k: If > 0 then do top-k softmax. Used only if bottleneck_kind is gumbel-softmax. temperature_warmup_steps: Number of steps it takes to decay temperature to 0. Used only if bottleneck_kind is gumbel-softmax or gumbel-softmax-dvq. do_hard_gumbel_softmax: Whether to use hard or soft Gumbel-Softmax samples. Used only if bottleneck_kind is gumbel-softmax-dvq. num_flows: Number of inverse autoregresive flows. Used only if bottleneck_kind is gumbel-softmax-dvq. approximate_gs_entropy: Whether to approximate the Gumbel-Softmax density as a categorical distribution when calculating the sample entropy. Used only if bottleneck_kind is gumbel-softmax-dvq. sum_over_latents: Whether to sum over all non-batch dimensions before taking mean of entropy loss term. Used only if bottleneck kind is DVQ or gumbel-softmax-dvq. discrete_mix: Factor for mixing discrete and non-discrete input. Used only if bottleneck_kind is semhash. noise_dev: Noise stddev. Used only if bottleneck_kind is semhash. startup_steps: Number of steps after which latent predictor is trained. Used only if bottleneck_kind is semhash. summary: Whether to write summaries. name: Name for the bottleneck scope. cond: A tf.bool condition on whether to update the codebook. Returns: outputs_dense: Tensor of shape [..., output_dim]. The output dimension is hidden_size if bottleneck_kind is gumbel-softmax, DVQ; filter_size if bottleneck_kind is dense, semhash, vae. If bottleneck_kind is DVQ, outputs_dense represents the codebook (means) indexed by outputs_discrete. outputs_discrete: Tensor of shape [...]. Discrete codes, each an index in [0, 2**z_size). It uses the hot representation if soft_em is True. extra_loss: Scalar Tensor. Sum of codebook and commitment losses if bottleneck_kind is DVQ; else zero. embed_fn: Function embed with arguments partially filled in. neg_q_entropy: Scalar Tensor representing negative entropy of variational approximation (0 if it is deterministic). Raises: ValueError: If projection_tensors is None for reshape_method project, or ema_count or ema_means is None if ema is True, or unknown args. """ if bottleneck_kind in ["dvq", "gumbel-softmax-dvq"]: assert means is not None if hidden_size % num_blocks != 0: raise ValueError("num_blocks does not divide hidden size") if z_size % num_residuals != 0: raise ValueError("num_residuals does not divide embedding table size") z_size_per_residual = int(z_size / num_residuals) if z_size_per_residual % num_blocks != 0: raise ValueError("num_blocks does not divide embedding table size") block_v_size = 2**int(z_size_per_residual / num_blocks) if ema: if ema_count is None: raise ValueError("ema_count is None but ema is True") if ema_means is None: raise ValueError("ema_means is None but ema is True") else: block_v_size = None with tf.variable_scope( name, default_name="discrete_bottleneck", reuse=tf.AUTO_REUSE): embed_fn = partial( embed, hidden_size=hidden_size, z_size=z_size, filter_size=filter_size, bottleneck_kind=bottleneck_kind, soft_em=soft_em, num_blocks=num_blocks, num_residuals=num_residuals, block_v_size=block_v_size, means=means, name=name) if bottleneck_kind == "dense": # Note discrete output is continuous here. outputs_discrete = tf.layers.dense(inputs, z_size, name="vcc") outputs_dense = tf.layers.dense( outputs_discrete, filter_size, name="vch1") extra_loss = tf.constant(0.0) neg_q_entropy = tf.constant(0.0) elif bottleneck_kind in ["dvq", "gumbel-softmax-dvq"]: inputs_3d = inputs if len(inputs.shape) == 4: inputs_3d = tf.squeeze(inputs, axis=2) if reshape_method == "slice": x_reshaped = slice_hidden( inputs_3d, hidden_size=hidden_size, num_blocks=num_blocks) elif reshape_method == "project": if projection_tensors is None: raise ValueError( "Projection tensors is None for reshape_method project") x_reshaped = project_hidden( inputs_3d, projection_tensors=projection_tensors, hidden_size=hidden_size, num_blocks=num_blocks) else: raise ValueError("Unknown reshape_method") x_res = tf.reshape(x_reshaped, [-1] + common_layers.shape_list(x_reshaped)[2:]) x_means_hot = [] x_means = 0 extra_loss = 0 for i in range(num_residuals): x_means_hot_res, x_means_res, q_loss_res, e_loss_res, neg_q_entropy = ( embedding_lookup( x_reshaped, means=means[i], num_blocks=num_blocks, block_v_size=block_v_size, bottleneck_kind=bottleneck_kind, random_top_k=random_top_k, soft_em=soft_em, num_samples=num_samples, temperature_warmup_steps=temperature_warmup_steps, do_hard_gumbel_softmax=do_hard_gumbel_softmax, num_flows=num_flows, approximate_gs_entropy=approximate_gs_entropy, sum_over_latents=sum_over_latents)) # Update the EMA variables. if ema: tf.logging.info("Using EMA with beta = {}".format(beta)) updated_ema_count_res = moving_averages.assign_moving_average( ema_count[i], tf.where(cond, tf.reduce_sum( tf.reshape(x_means_hot_res, shape=[-1, num_blocks, block_v_size]), axis=0), ema_count[i]), decay, zero_debias=False) dw = tf.matmul( tf.transpose(x_means_hot_res, perm=[1, 2, 0]), tf.transpose(x_res, perm=[1, 0, 2])) updated_ema_means_res = moving_averages.assign_moving_average( ema_means[i], tf.where(cond, dw, ema_means[i]), decay, zero_debias=False) n = tf.reduce_sum(updated_ema_count_res, axis=-1, keep_dims=True) updated_ema_count_res = ( (updated_ema_count_res + epsilon) / (n + 2**z_size * epsilon) * n) # pylint: disable=g-no-augmented-assignment updated_ema_means_res = updated_ema_means_res / tf.expand_dims( updated_ema_count_res, axis=-1) # pylint: enable=g-no-augmented-assignment with tf.control_dependencies([e_loss_res]): update_means_res = tf.assign(means[i], tf.where(cond, updated_ema_means_res, means[i])) with tf.control_dependencies([update_means_res]): extra_loss += beta * e_loss_res else: extra_loss += q_loss_res + beta * e_loss_res # Update the residuals. x_res -= x_means_res x_means += x_means_res x_means_hot.append(x_means_hot_res) # Get the discrete latent representation. x_means_hot = tf.stack(x_means_hot, axis=1) x_means_idx = tf.argmax(x_means_hot, axis=-1) # Get the binary representation. x_means_bits = int_to_bit( x_means_idx, num_bits=int(z_size / (num_residuals * num_blocks)), base=2) shape = common_layers.shape_list(x_means_bits) new_shape = shape[:-2] new_shape[-1] = z_size x_means_bits = tf.reshape(x_means_bits, shape=new_shape) outputs_discrete = bit_to_int( tf.to_int32(x_means_bits), num_bits=z_size, base=2) # Adjust shape of discrete outputs. inputs_shape = common_layers.shape_list(inputs) outputs_discrete = tf.reshape(outputs_discrete, inputs_shape[:-1]) # If we're using soft EM then set discretes to the hot representation. if soft_em: outputs_discrete = x_means_hot outputs_discrete = tf.reshape(outputs_discrete, inputs_shape[:-1] + [block_v_size]) # Reshape assuming hidden_size == inputs_shape[:-1]. x_means = tf.reshape(x_means, inputs_shape) outputs_dense = inputs + tf.stop_gradient(x_means - inputs) elif bottleneck_kind == "gumbel-softmax": _, outputs_hot, extra_loss = gumbel_softmax( inputs, z_size=z_size, mode=mode, softmax_k=softmax_k, temperature_warmup_steps=temperature_warmup_steps, summary=summary, name=name) outputs_discrete = tf.argmax(outputs_hot, axis=-1) outputs_dense = tf.layers.dense( outputs_hot, hidden_size, name="dae_dense") neg_q_entropy = tf.constant(0.0) elif bottleneck_kind == "semhash": outputs_discrete = tf.layers.dense(inputs, z_size, name="vcc") y_clean = common_layers.saturating_sigmoid(outputs_discrete) if summary: tf.summary.histogram("y_clean", tf.reshape(y_clean, [-1])) if noise_dev > 0 and mode == tf.estimator.ModeKeys.TRAIN: noise = tf.truncated_normal( common_layers.shape_list(outputs_discrete), mean=0.0, stddev=noise_dev) y = common_layers.saturating_sigmoid(outputs_discrete + noise) else: y = y_clean d = tf.to_float(tf.less(0.5, y)) y_discrete = tf.stop_gradient(d) + y - tf.stop_gradient(y) pd = common_layers.inverse_exp_decay(startup_steps * 2) pd *= discrete_mix pd = pd if mode == tf.estimator.ModeKeys.TRAIN else 1.0 c = tf.where( tf.less(tf.random_uniform([common_layers.shape_list(y)[0]]), pd), y_discrete, y) outputs_dense_a = tf.layers.dense(c, filter_size, name="vch1a") outputs_dense_b = tf.layers.dense(1.0 - c, filter_size, name="vch1b") outputs_dense = outputs_dense_a + outputs_dense_b dx = tf.to_int32(tf.stop_gradient(d)) outputs_discrete = bit_to_int(dx, z_size) extra_loss = tf.constant(0.0) neg_q_entropy = tf.constant(0.0) elif bottleneck_kind == "vae": outputs_discrete, extra_loss, _, _ = vae(inputs, z_size, name="vae") outputs_dense = tf.layers.dense( outputs_discrete, filter_size, name="vch1") neg_q_entropy = tf.constant(0.0) else: raise ValueError("Unknown discretization method.") return outputs_dense, outputs_discrete, extra_loss, embed_fn, neg_q_entropy
def discrete_bottleneck(inputs, hidden_size, z_size, filter_size, mode=None, bottleneck_kind="dvq", num_blocks=2, num_residuals=1, reshape_method="slice", projection_tensors=None, beta=0.25, ema=True, means=None, ema_count=None, ema_means=None, epsilon=1e-5, decay=0.999, random_top_k=1, soft_em=False, num_samples=1, softmax_k=0, temperature_warmup_steps=150000, do_hard_gumbel_softmax=False, num_flows=0, approximate_gs_entropy=False, sum_over_latents=False, discrete_mix=0.5, noise_dev=1., startup_steps=50000, summary=True, name=None, cond=True): """Discretization bottleneck. Args: inputs: Input to the bottleneck, a Tensor of shape [..., channels]. hidden_size: Dimension of the dense output. z_size: Number of bits, where discrete codes range from 1 to 2**z_size. filter_size: Filter size in the embedding function. mode: tf.estimator.ModeKeys. bottleneck_kind: Kind of discretization bottleneck. One of dense, dvq (decomposed vector quantization), gumbel-softmax, gumbel-softmax-dvq, semhash, or vae. num_blocks: Number of blocks. Used only if bottleneck_kind is DVQ. num_residuals: Number of residual units used to compute nearest neighbors. Used only if bottleneck_kind is DVQ. reshape_method: Method to reshape. Used only if bottleneck_kind is DVQ. projection_tensors: If the reshape method is project, then these are the tensors used to project. beta: Scale factor for codebook loss and EMA. Used only if bottleneck_kind is DVQ. ema: Whether to update embeddings using exponential moving averages. Used only if bottleneck_kind is DVQ. means: The embedding table. Used only if ema is True. ema_count: Table of counts for each embedding corresponding to how many examples in a batch it was the closest to. Used only if ema is True. ema_means: Exponentially averaged version of the embeddings. Used only if ema is True. epsilon: Small value to avoid dividing by zero in EMA update. Used only if ema is True. decay: Decay factor for the exponential moving average. Used only if ema is True. random_top_k: Noisy top-k. Used only if bottleneck_kind is DVQ. soft_em: Whether to use soft EM or hard EM. Used only if bottleneck_kind is DVQ. num_samples: Number of samples for soft EM. Used only if soft_em is True. softmax_k: If > 0 then do top-k softmax. Used only if bottleneck_kind is gumbel-softmax. temperature_warmup_steps: Number of steps it takes to decay temperature to 0. Used only if bottleneck_kind is gumbel-softmax or gumbel-softmax-dvq. do_hard_gumbel_softmax: Whether to use hard or soft Gumbel-Softmax samples. Used only if bottleneck_kind is gumbel-softmax-dvq. num_flows: Number of inverse autoregresive flows. Used only if bottleneck_kind is gumbel-softmax-dvq. approximate_gs_entropy: Whether to approximate the Gumbel-Softmax density as a categorical distribution when calculating the sample entropy. Used only if bottleneck_kind is gumbel-softmax-dvq. sum_over_latents: Whether to sum over all non-batch dimensions before taking mean of entropy loss term. Used only if bottleneck kind is DVQ or gumbel-softmax-dvq. discrete_mix: Factor for mixing discrete and non-discrete input. Used only if bottleneck_kind is semhash. noise_dev: Noise stddev. Used only if bottleneck_kind is semhash. startup_steps: Number of steps after which latent predictor is trained. Used only if bottleneck_kind is semhash. summary: Whether to write summaries. name: Name for the bottleneck scope. cond: A tf.bool condition on whether to update the codebook. Returns: outputs_dense: Tensor of shape [..., output_dim]. The output dimension is hidden_size if bottleneck_kind is gumbel-softmax, DVQ; filter_size if bottleneck_kind is dense, semhash, vae. If bottleneck_kind is DVQ, outputs_dense represents the codebook (means) indexed by outputs_discrete. outputs_discrete: Tensor of shape [...]. Discrete codes, each an index in [0, 2**z_size). It uses the hot representation if soft_em is True. extra_loss: Scalar Tensor. Sum of codebook and commitment losses if bottleneck_kind is DVQ; else zero. embed_fn: Function embed with arguments partially filled in. neg_q_entropy: Scalar Tensor representing negative entropy of variational approximation (0 if it is deterministic). Raises: ValueError: If projection_tensors is None for reshape_method project, or ema_count or ema_means is None if ema is True, or unknown args. """ if bottleneck_kind in ["dvq", "gumbel-softmax-dvq"]: assert means is not None if hidden_size % num_blocks != 0: raise ValueError("num_blocks does not divide hidden size") if z_size % num_residuals != 0: raise ValueError("num_residuals does not divide embedding table size") z_size_per_residual = int(z_size / num_residuals) if z_size_per_residual % num_blocks != 0: raise ValueError("num_blocks does not divide embedding table size") block_v_size = 2**int(z_size_per_residual / num_blocks) if ema: if ema_count is None: raise ValueError("ema_count is None but ema is True") if ema_means is None: raise ValueError("ema_means is None but ema is True") else: block_v_size = None with tf.variable_scope( name, default_name="discrete_bottleneck", reuse=tf.AUTO_REUSE): embed_fn = partial( embed, hidden_size=hidden_size, z_size=z_size, filter_size=filter_size, bottleneck_kind=bottleneck_kind, soft_em=soft_em, num_blocks=num_blocks, num_residuals=num_residuals, block_v_size=block_v_size, means=means, name=name) if bottleneck_kind == "dense": # Note discrete output is continuous here. outputs_discrete = tf.layers.dense(inputs, z_size, name="vcc") outputs_dense = tf.layers.dense( outputs_discrete, filter_size, name="vch1") extra_loss = tf.constant(0.0) neg_q_entropy = tf.constant(0.0) elif bottleneck_kind in ["dvq", "gumbel-softmax-dvq"]: inputs_3d = inputs if len(inputs.shape) == 4: inputs_3d = tf.squeeze(inputs, axis=2) if reshape_method == "slice": x_reshaped = slice_hidden( inputs_3d, hidden_size=hidden_size, num_blocks=num_blocks) elif reshape_method == "project": if projection_tensors is None: raise ValueError( "Projection tensors is None for reshape_method project") x_reshaped = project_hidden( inputs_3d, projection_tensors=projection_tensors, hidden_size=hidden_size, num_blocks=num_blocks) else: raise ValueError("Unknown reshape_method") x_res = tf.reshape(x_reshaped, [-1] + common_layers.shape_list(x_reshaped)[2:]) x_means_hot = [] x_means = 0 extra_loss = 0 for i in range(num_residuals): x_means_hot_res, x_means_res, q_loss_res, e_loss_res, neg_q_entropy = ( embedding_lookup( x_reshaped, means=means[i], num_blocks=num_blocks, block_v_size=block_v_size, bottleneck_kind=bottleneck_kind, random_top_k=random_top_k, soft_em=soft_em, num_samples=num_samples, temperature_warmup_steps=temperature_warmup_steps, do_hard_gumbel_softmax=do_hard_gumbel_softmax, num_flows=num_flows, approximate_gs_entropy=approximate_gs_entropy, sum_over_latents=sum_over_latents)) # Update the EMA variables. if ema: tf.logging.info("Using EMA with beta = {}".format(beta)) updated_ema_count_res = moving_averages.assign_moving_average( ema_count[i], tf.where(cond, tf.reduce_sum( tf.reshape(x_means_hot_res, shape=[-1, num_blocks, block_v_size]), axis=0), ema_count[i]), decay, zero_debias=False) dw = tf.matmul( tf.transpose(x_means_hot_res, perm=[1, 2, 0]), tf.transpose(x_res, perm=[1, 0, 2])) updated_ema_means_res = moving_averages.assign_moving_average( ema_means[i], tf.where(cond, dw, ema_means[i]), decay, zero_debias=False) n = tf.reduce_sum(updated_ema_count_res, axis=-1, keep_dims=True) updated_ema_count_res = ( (updated_ema_count_res + epsilon) / (n + 2**z_size * epsilon) * n) # pylint: disable=g-no-augmented-assignment updated_ema_means_res = updated_ema_means_res / tf.expand_dims( updated_ema_count_res, axis=-1) # pylint: enable=g-no-augmented-assignment with tf.control_dependencies([e_loss_res]): update_means_res = tf.assign(means[i], tf.where(cond, updated_ema_means_res, means[i])) with tf.control_dependencies([update_means_res]): extra_loss += beta * e_loss_res else: extra_loss += q_loss_res + beta * e_loss_res # Update the residuals. x_res -= x_means_res x_means += x_means_res x_means_hot.append(x_means_hot_res) # Get the discrete latent representation. x_means_hot = tf.stack(x_means_hot, axis=1) x_means_idx = tf.argmax(x_means_hot, axis=-1) # Get the binary representation. x_means_bits = int_to_bit( x_means_idx, num_bits=int(z_size / (num_residuals * num_blocks)), base=2) shape = common_layers.shape_list(x_means_bits) new_shape = shape[:-2] new_shape[-1] = z_size x_means_bits = tf.reshape(x_means_bits, shape=new_shape) outputs_discrete = bit_to_int( tf.to_int32(x_means_bits), num_bits=z_size, base=2) # Adjust shape of discrete outputs. inputs_shape = common_layers.shape_list(inputs) outputs_discrete = tf.reshape(outputs_discrete, inputs_shape[:-1]) # If we're using soft EM then set discretes to the hot representation. if soft_em: outputs_discrete = x_means_hot outputs_discrete = tf.reshape(outputs_discrete, inputs_shape[:-1] + [block_v_size]) # Reshape assuming hidden_size == inputs_shape[:-1]. x_means = tf.reshape(x_means, inputs_shape) outputs_dense = inputs + tf.stop_gradient(x_means - inputs) elif bottleneck_kind == "gumbel-softmax": _, outputs_hot, extra_loss = gumbel_softmax( inputs, z_size=z_size, mode=mode, softmax_k=softmax_k, temperature_warmup_steps=temperature_warmup_steps, summary=summary, name=name) outputs_discrete = tf.argmax(outputs_hot, axis=-1) outputs_dense = tf.layers.dense( outputs_hot, hidden_size, name="dae_dense") neg_q_entropy = tf.constant(0.0) elif bottleneck_kind == "semhash": outputs_discrete = tf.layers.dense(inputs, z_size, name="vcc") y_clean = common_layers.saturating_sigmoid(outputs_discrete) if summary: tf.summary.histogram("y_clean", tf.reshape(y_clean, [-1])) if noise_dev > 0 and mode == tf.estimator.ModeKeys.TRAIN: noise = tf.truncated_normal( common_layers.shape_list(outputs_discrete), mean=0.0, stddev=noise_dev) y = common_layers.saturating_sigmoid(outputs_discrete + noise) else: y = y_clean d = tf.to_float(tf.less(0.5, y)) y_discrete = tf.stop_gradient(d) + y - tf.stop_gradient(y) pd = common_layers.inverse_exp_decay(startup_steps * 2) pd *= discrete_mix pd = pd if mode == tf.estimator.ModeKeys.TRAIN else 1.0 c = tf.where( tf.less(tf.random_uniform([common_layers.shape_list(y)[0]]), pd), y_discrete, y) outputs_dense_a = tf.layers.dense(c, filter_size, name="vch1a") outputs_dense_b = tf.layers.dense(1.0 - c, filter_size, name="vch1b") outputs_dense = outputs_dense_a + outputs_dense_b dx = tf.to_int32(tf.stop_gradient(d)) outputs_discrete = bit_to_int(dx, z_size) extra_loss = tf.constant(0.0) neg_q_entropy = tf.constant(0.0) elif bottleneck_kind == "vae": outputs_discrete, extra_loss, _, _ = vae(inputs, z_size, name="vae") outputs_dense = tf.layers.dense( outputs_discrete, filter_size, name="vch1") neg_q_entropy = tf.constant(0.0) else: raise ValueError("Unknown discretization method.") return outputs_dense, outputs_discrete, extra_loss, embed_fn, neg_q_entropy
[ "Discretization", "bottleneck", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/discretization.py#L478-L788
[ "def", "discrete_bottleneck", "(", "inputs", ",", "hidden_size", ",", "z_size", ",", "filter_size", ",", "mode", "=", "None", ",", "bottleneck_kind", "=", "\"dvq\"", ",", "num_blocks", "=", "2", ",", "num_residuals", "=", "1", ",", "reshape_method", "=", "\"...
272500b6efe353aeb638d2745ed56e519462ca31
train
predict_bits_with_lstm
Predict a sequence of bits (a latent) with LSTM, both training and infer. Given a tensor on which the predictions are based (prediction_source), we use a single-layer LSTM with state of size state_size to predict total_num_bits, which we predict in groups of size bits_at_once. During training, we use target_bits as input to the LSTM (teacher forcing) and return the target_bits together with the prediction loss. During inference, we sample with the given temperature and return the predicted sequence and loss 0. Args: prediction_source: a Tensor of shape [batch_size, ...] used to create the initial state and the first input to the LSTM. state_size: python integer, the size of the LSTM state. total_num_bits: python integer, how many bits in total to predict. target_bits: a tensor of shape [batch_size, total_num_bits] used during training as the target to predict; each element should be -1 or 1. extra_inputs: a Tensor [batch_size, total_num_bits // bits_at_once, d] of additional inputs, passed as additional LSTM inputs. bits_at_once: pytho integer, how many bits to predict at once. temperature: python float, temperature used for sampling during inference. dropout: float, the amount of dropout to aply during training (0.1 default). Returns: a pair (bits, loss) with the predicted bit sequence, which is a Tensor of shape [batch_size, total_num_bits] with elements either -1 or 1, and a loss used to train the predictions against the provided target_bits.
tensor2tensor/layers/discretization.py
def predict_bits_with_lstm(prediction_source, state_size, total_num_bits, target_bits=None, extra_inputs=None, bits_at_once=8, temperature=1.0, dropout=0.1): """Predict a sequence of bits (a latent) with LSTM, both training and infer. Given a tensor on which the predictions are based (prediction_source), we use a single-layer LSTM with state of size state_size to predict total_num_bits, which we predict in groups of size bits_at_once. During training, we use target_bits as input to the LSTM (teacher forcing) and return the target_bits together with the prediction loss. During inference, we sample with the given temperature and return the predicted sequence and loss 0. Args: prediction_source: a Tensor of shape [batch_size, ...] used to create the initial state and the first input to the LSTM. state_size: python integer, the size of the LSTM state. total_num_bits: python integer, how many bits in total to predict. target_bits: a tensor of shape [batch_size, total_num_bits] used during training as the target to predict; each element should be -1 or 1. extra_inputs: a Tensor [batch_size, total_num_bits // bits_at_once, d] of additional inputs, passed as additional LSTM inputs. bits_at_once: pytho integer, how many bits to predict at once. temperature: python float, temperature used for sampling during inference. dropout: float, the amount of dropout to aply during training (0.1 default). Returns: a pair (bits, loss) with the predicted bit sequence, which is a Tensor of shape [batch_size, total_num_bits] with elements either -1 or 1, and a loss used to train the predictions against the provided target_bits. """ with tf.variable_scope("predict_bits_with_lstm"): # Layers and cell state creation. lstm_cell = tf.nn.rnn_cell.LSTMCell(state_size) discrete_predict = tf.layers.Dense(2**bits_at_once, name="discrete_predict") discrete_embed = tf.layers.Dense(state_size, name="discrete_embed") batch_size = common_layers.shape_list(prediction_source)[0] layer_pred = tf.layers.flatten(prediction_source) first_lstm_input = tf.layers.dense(layer_pred, state_size, name="istate") c_state = tf.layers.dense(layer_pred, state_size, name="cstate") m_state = tf.layers.dense(layer_pred, state_size, name="mstate") state = (c_state, m_state) # Prediction mode if no targets are given. if target_bits is None: outputs = [] lstm_input = first_lstm_input for i in range(total_num_bits // bits_at_once): if extra_inputs is not None: lstm_input = tf.concat([lstm_input, extra_inputs[:, i, :]], axis=1) output, state = lstm_cell(lstm_input, state) discrete_logits = discrete_predict(output) discrete_samples = common_layers.sample_with_temperature( discrete_logits, temperature) outputs.append(tf.expand_dims(discrete_samples, axis=1)) lstm_input = discrete_embed(tf.one_hot(discrete_samples, 256)) outputs = tf.concat(outputs, axis=1) outputs = int_to_bit(outputs, bits_at_once) outputs = tf.reshape(outputs, [batch_size, total_num_bits]) return 2 * outputs - 1, 0.0 # Training mode, calculating loss. assert total_num_bits % bits_at_once == 0 target_bits = tf.reshape(tf.maximum(tf.stop_gradient(target_bits), 0), [ batch_size, total_num_bits // bits_at_once, bits_at_once]) target_ints = bit_to_int(target_bits, bits_at_once) tf.summary.histogram("target_integers", tf.reshape(target_ints, [-1])) target_hot = tf.one_hot(target_ints, 2**bits_at_once, axis=-1) target_embedded = discrete_embed(target_hot) target_embedded = tf.nn.dropout(target_embedded, 1.0 - dropout) teacher_input = tf.concat( [tf.expand_dims(first_lstm_input, axis=1), target_embedded], axis=1) outputs = [] for i in range(total_num_bits // bits_at_once): lstm_input = teacher_input[:, i, :] if extra_inputs is not None: lstm_input = tf.concat([lstm_input, extra_inputs[:, i, :]], axis=1) output, state = lstm_cell(lstm_input, state) outputs.append(tf.expand_dims(output, axis=1)) outputs = tf.concat(outputs, axis=1) outputs = tf.nn.dropout(outputs, 1.0 - dropout) d_int_pred = discrete_predict(outputs) pred_loss = tf.losses.sparse_softmax_cross_entropy( logits=d_int_pred, labels=target_ints) pred_loss = tf.reduce_mean(pred_loss) return d_int_pred, pred_loss
def predict_bits_with_lstm(prediction_source, state_size, total_num_bits, target_bits=None, extra_inputs=None, bits_at_once=8, temperature=1.0, dropout=0.1): """Predict a sequence of bits (a latent) with LSTM, both training and infer. Given a tensor on which the predictions are based (prediction_source), we use a single-layer LSTM with state of size state_size to predict total_num_bits, which we predict in groups of size bits_at_once. During training, we use target_bits as input to the LSTM (teacher forcing) and return the target_bits together with the prediction loss. During inference, we sample with the given temperature and return the predicted sequence and loss 0. Args: prediction_source: a Tensor of shape [batch_size, ...] used to create the initial state and the first input to the LSTM. state_size: python integer, the size of the LSTM state. total_num_bits: python integer, how many bits in total to predict. target_bits: a tensor of shape [batch_size, total_num_bits] used during training as the target to predict; each element should be -1 or 1. extra_inputs: a Tensor [batch_size, total_num_bits // bits_at_once, d] of additional inputs, passed as additional LSTM inputs. bits_at_once: pytho integer, how many bits to predict at once. temperature: python float, temperature used for sampling during inference. dropout: float, the amount of dropout to aply during training (0.1 default). Returns: a pair (bits, loss) with the predicted bit sequence, which is a Tensor of shape [batch_size, total_num_bits] with elements either -1 or 1, and a loss used to train the predictions against the provided target_bits. """ with tf.variable_scope("predict_bits_with_lstm"): # Layers and cell state creation. lstm_cell = tf.nn.rnn_cell.LSTMCell(state_size) discrete_predict = tf.layers.Dense(2**bits_at_once, name="discrete_predict") discrete_embed = tf.layers.Dense(state_size, name="discrete_embed") batch_size = common_layers.shape_list(prediction_source)[0] layer_pred = tf.layers.flatten(prediction_source) first_lstm_input = tf.layers.dense(layer_pred, state_size, name="istate") c_state = tf.layers.dense(layer_pred, state_size, name="cstate") m_state = tf.layers.dense(layer_pred, state_size, name="mstate") state = (c_state, m_state) # Prediction mode if no targets are given. if target_bits is None: outputs = [] lstm_input = first_lstm_input for i in range(total_num_bits // bits_at_once): if extra_inputs is not None: lstm_input = tf.concat([lstm_input, extra_inputs[:, i, :]], axis=1) output, state = lstm_cell(lstm_input, state) discrete_logits = discrete_predict(output) discrete_samples = common_layers.sample_with_temperature( discrete_logits, temperature) outputs.append(tf.expand_dims(discrete_samples, axis=1)) lstm_input = discrete_embed(tf.one_hot(discrete_samples, 256)) outputs = tf.concat(outputs, axis=1) outputs = int_to_bit(outputs, bits_at_once) outputs = tf.reshape(outputs, [batch_size, total_num_bits]) return 2 * outputs - 1, 0.0 # Training mode, calculating loss. assert total_num_bits % bits_at_once == 0 target_bits = tf.reshape(tf.maximum(tf.stop_gradient(target_bits), 0), [ batch_size, total_num_bits // bits_at_once, bits_at_once]) target_ints = bit_to_int(target_bits, bits_at_once) tf.summary.histogram("target_integers", tf.reshape(target_ints, [-1])) target_hot = tf.one_hot(target_ints, 2**bits_at_once, axis=-1) target_embedded = discrete_embed(target_hot) target_embedded = tf.nn.dropout(target_embedded, 1.0 - dropout) teacher_input = tf.concat( [tf.expand_dims(first_lstm_input, axis=1), target_embedded], axis=1) outputs = [] for i in range(total_num_bits // bits_at_once): lstm_input = teacher_input[:, i, :] if extra_inputs is not None: lstm_input = tf.concat([lstm_input, extra_inputs[:, i, :]], axis=1) output, state = lstm_cell(lstm_input, state) outputs.append(tf.expand_dims(output, axis=1)) outputs = tf.concat(outputs, axis=1) outputs = tf.nn.dropout(outputs, 1.0 - dropout) d_int_pred = discrete_predict(outputs) pred_loss = tf.losses.sparse_softmax_cross_entropy( logits=d_int_pred, labels=target_ints) pred_loss = tf.reduce_mean(pred_loss) return d_int_pred, pred_loss
[ "Predict", "a", "sequence", "of", "bits", "(", "a", "latent", ")", "with", "LSTM", "both", "training", "and", "infer", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/discretization.py#L791-L876
[ "def", "predict_bits_with_lstm", "(", "prediction_source", ",", "state_size", ",", "total_num_bits", ",", "target_bits", "=", "None", ",", "extra_inputs", "=", "None", ",", "bits_at_once", "=", "8", ",", "temperature", "=", "1.0", ",", "dropout", "=", "0.1", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
get_vq_codebook
Get lookup table for VQ bottleneck.
tensor2tensor/layers/discretization.py
def get_vq_codebook(codebook_size, hidden_size): """Get lookup table for VQ bottleneck.""" with tf.variable_scope("vq", reuse=tf.AUTO_REUSE): means = tf.get_variable( name="means", shape=[codebook_size, hidden_size], initializer=tf.uniform_unit_scaling_initializer()) ema_count = tf.get_variable( name="ema_count", shape=[codebook_size], initializer=tf.constant_initializer(0), trainable=False) with tf.colocate_with(means): ema_means = tf.get_variable( name="ema_means", initializer=means.initialized_value(), trainable=False) return means, ema_means, ema_count
def get_vq_codebook(codebook_size, hidden_size): """Get lookup table for VQ bottleneck.""" with tf.variable_scope("vq", reuse=tf.AUTO_REUSE): means = tf.get_variable( name="means", shape=[codebook_size, hidden_size], initializer=tf.uniform_unit_scaling_initializer()) ema_count = tf.get_variable( name="ema_count", shape=[codebook_size], initializer=tf.constant_initializer(0), trainable=False) with tf.colocate_with(means): ema_means = tf.get_variable( name="ema_means", initializer=means.initialized_value(), trainable=False) return means, ema_means, ema_count
[ "Get", "lookup", "table", "for", "VQ", "bottleneck", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/discretization.py#L885-L905
[ "def", "get_vq_codebook", "(", "codebook_size", ",", "hidden_size", ")", ":", "with", "tf", ".", "variable_scope", "(", "\"vq\"", ",", "reuse", "=", "tf", ".", "AUTO_REUSE", ")", ":", "means", "=", "tf", ".", "get_variable", "(", "name", "=", "\"means\"", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
vq_nearest_neighbor
Find the nearest element in means to elements in x.
tensor2tensor/layers/discretization.py
def vq_nearest_neighbor(x, means, soft_em=False, num_samples=10, temperature=None): """Find the nearest element in means to elements in x.""" bottleneck_size = common_layers.shape_list(means)[0] x_norm_sq = tf.reduce_sum(tf.square(x), axis=-1, keepdims=True) means_norm_sq = tf.reduce_sum(tf.square(means), axis=-1, keepdims=True) scalar_prod = tf.matmul(x, means, transpose_b=True) dist = x_norm_sq + tf.transpose(means_norm_sq) - 2 * scalar_prod if soft_em: x_means_idx = tf.multinomial(-dist, num_samples=num_samples) x_means_hot = tf.one_hot( x_means_idx, depth=common_layers.shape_list(means)[0]) x_means_hot = tf.reduce_mean(x_means_hot, axis=1) else: if temperature is None: x_means_idx = tf.argmax(-dist, axis=-1) else: x_means_idx = tf.multinomial(- dist / temperature, 1) x_means_idx = tf.squeeze(x_means_idx, axis=-1) if (common_layers.should_generate_summaries() and not common_layers.is_xla_compiled()): tf.summary.histogram("means_idx", tf.reshape(x_means_idx, [-1])) x_means_hot = tf.one_hot(x_means_idx, bottleneck_size) x_means_hot_flat = tf.reshape(x_means_hot, [-1, bottleneck_size]) x_means = tf.matmul(x_means_hot_flat, means) e_loss = tf.reduce_mean(tf.squared_difference(x, tf.stop_gradient(x_means))) return x_means_hot, e_loss, dist
def vq_nearest_neighbor(x, means, soft_em=False, num_samples=10, temperature=None): """Find the nearest element in means to elements in x.""" bottleneck_size = common_layers.shape_list(means)[0] x_norm_sq = tf.reduce_sum(tf.square(x), axis=-1, keepdims=True) means_norm_sq = tf.reduce_sum(tf.square(means), axis=-1, keepdims=True) scalar_prod = tf.matmul(x, means, transpose_b=True) dist = x_norm_sq + tf.transpose(means_norm_sq) - 2 * scalar_prod if soft_em: x_means_idx = tf.multinomial(-dist, num_samples=num_samples) x_means_hot = tf.one_hot( x_means_idx, depth=common_layers.shape_list(means)[0]) x_means_hot = tf.reduce_mean(x_means_hot, axis=1) else: if temperature is None: x_means_idx = tf.argmax(-dist, axis=-1) else: x_means_idx = tf.multinomial(- dist / temperature, 1) x_means_idx = tf.squeeze(x_means_idx, axis=-1) if (common_layers.should_generate_summaries() and not common_layers.is_xla_compiled()): tf.summary.histogram("means_idx", tf.reshape(x_means_idx, [-1])) x_means_hot = tf.one_hot(x_means_idx, bottleneck_size) x_means_hot_flat = tf.reshape(x_means_hot, [-1, bottleneck_size]) x_means = tf.matmul(x_means_hot_flat, means) e_loss = tf.reduce_mean(tf.squared_difference(x, tf.stop_gradient(x_means))) return x_means_hot, e_loss, dist
[ "Find", "the", "nearest", "element", "in", "means", "to", "elements", "in", "x", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/discretization.py#L908-L934
[ "def", "vq_nearest_neighbor", "(", "x", ",", "means", ",", "soft_em", "=", "False", ",", "num_samples", "=", "10", ",", "temperature", "=", "None", ")", ":", "bottleneck_size", "=", "common_layers", ".", "shape_list", "(", "means", ")", "[", "0", "]", "x...
272500b6efe353aeb638d2745ed56e519462ca31
train
vq_discrete_bottleneck
Simple vector quantized discrete bottleneck.
tensor2tensor/layers/discretization.py
def vq_discrete_bottleneck(x, bottleneck_bits, beta=0.25, decay=0.999, epsilon=1e-5, soft_em=False, num_samples=10): """Simple vector quantized discrete bottleneck.""" bottleneck_size = 2**bottleneck_bits x_means_hot, e_loss, _ = vq_body( x, bottleneck_size, beta=beta, decay=decay, epsilon=epsilon, soft_em=soft_em, num_samples=num_samples) return x_means_hot, e_loss
def vq_discrete_bottleneck(x, bottleneck_bits, beta=0.25, decay=0.999, epsilon=1e-5, soft_em=False, num_samples=10): """Simple vector quantized discrete bottleneck.""" bottleneck_size = 2**bottleneck_bits x_means_hot, e_loss, _ = vq_body( x, bottleneck_size, beta=beta, decay=decay, epsilon=epsilon, soft_em=soft_em, num_samples=num_samples) return x_means_hot, e_loss
[ "Simple", "vector", "quantized", "discrete", "bottleneck", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/discretization.py#L937-L954
[ "def", "vq_discrete_bottleneck", "(", "x", ",", "bottleneck_bits", ",", "beta", "=", "0.25", ",", "decay", "=", "0.999", ",", "epsilon", "=", "1e-5", ",", "soft_em", "=", "False", ",", "num_samples", "=", "10", ")", ":", "bottleneck_size", "=", "2", "**"...
272500b6efe353aeb638d2745ed56e519462ca31
train
vq_body
Discretize each x into one of codebook_size codes.
tensor2tensor/layers/discretization.py
def vq_body(x, codebook_size, beta=0.25, decay=0.999, epsilon=1e-5, soft_em=False, num_samples=10, temperature=None, do_update=True): """Discretize each x into one of codebook_size codes.""" x_shape = common_layers.shape_list(x) hidden_size = x_shape[-1] means, ema_means, ema_count = get_vq_codebook(codebook_size, hidden_size) x = tf.reshape(x, [-1, hidden_size]) x_means_hot, e_loss, distances = vq_nearest_neighbor( x, means, soft_em=soft_em, num_samples=num_samples, temperature=temperature) def loss_with_update(): """Update the ema variables and return loss triggering the update.""" updated_ema_count = moving_averages.assign_moving_average( ema_count, tf.reduce_sum(tf.reshape(x_means_hot, shape=[-1, codebook_size]), axis=0), decay, zero_debias=False) dw = tf.matmul(x_means_hot, x, transpose_a=True) updated_ema_means = tf.identity( moving_averages.assign_moving_average( ema_means, dw, decay, zero_debias=False)) n = tf.reduce_sum(updated_ema_count, axis=-1, keepdims=True) updated_ema_count = ( (updated_ema_count + epsilon) / (n + codebook_size * epsilon) * n) updated_ema_means /= tf.expand_dims(updated_ema_count, axis=-1) with tf.control_dependencies([e_loss]): update_means = means.assign(updated_ema_means) with tf.control_dependencies([update_means]): return beta * e_loss # Loss, also do update if requested. if do_update: loss = loss_with_update() else: loss = tf.cond(do_update, loss_with_update, lambda: beta * e_loss) d = tf.reshape(x_means_hot, x_shape[:-1] + [codebook_size]) return d, loss, distances
def vq_body(x, codebook_size, beta=0.25, decay=0.999, epsilon=1e-5, soft_em=False, num_samples=10, temperature=None, do_update=True): """Discretize each x into one of codebook_size codes.""" x_shape = common_layers.shape_list(x) hidden_size = x_shape[-1] means, ema_means, ema_count = get_vq_codebook(codebook_size, hidden_size) x = tf.reshape(x, [-1, hidden_size]) x_means_hot, e_loss, distances = vq_nearest_neighbor( x, means, soft_em=soft_em, num_samples=num_samples, temperature=temperature) def loss_with_update(): """Update the ema variables and return loss triggering the update.""" updated_ema_count = moving_averages.assign_moving_average( ema_count, tf.reduce_sum(tf.reshape(x_means_hot, shape=[-1, codebook_size]), axis=0), decay, zero_debias=False) dw = tf.matmul(x_means_hot, x, transpose_a=True) updated_ema_means = tf.identity( moving_averages.assign_moving_average( ema_means, dw, decay, zero_debias=False)) n = tf.reduce_sum(updated_ema_count, axis=-1, keepdims=True) updated_ema_count = ( (updated_ema_count + epsilon) / (n + codebook_size * epsilon) * n) updated_ema_means /= tf.expand_dims(updated_ema_count, axis=-1) with tf.control_dependencies([e_loss]): update_means = means.assign(updated_ema_means) with tf.control_dependencies([update_means]): return beta * e_loss # Loss, also do update if requested. if do_update: loss = loss_with_update() else: loss = tf.cond(do_update, loss_with_update, lambda: beta * e_loss) d = tf.reshape(x_means_hot, x_shape[:-1] + [codebook_size]) return d, loss, distances
[ "Discretize", "each", "x", "into", "one", "of", "codebook_size", "codes", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/discretization.py#L957-L1004
[ "def", "vq_body", "(", "x", ",", "codebook_size", ",", "beta", "=", "0.25", ",", "decay", "=", "0.999", ",", "epsilon", "=", "1e-5", ",", "soft_em", "=", "False", ",", "num_samples", "=", "10", ",", "temperature", "=", "None", ",", "do_update", "=", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
vq_loss
Compute the loss of large vocab tensors using a VQAE codebook. Args: x: Tensor of inputs to be quantized to nearest code targets: Tensor of target indices to target codes codebook_size: Size of quantization codebook beta: scalar float for moving averages decay: scalar float for moving averages epsilon: scalar float for moving averages soft_em: boolean, whether to apply a soft sampling procedure num_samples: if soft_em, number of samples to take temperature: temperature if we want to sample nearest neighbors or None do_update: whether to update the means; True by default, can be a Tensor Returns: discrete_x: one-hot Tensor indicating which codebook element is closest to x x_means: Tensor, on the forward pass: closest codebook element to x, on the backwards pass: soft convex-combination of codebook elements by proximity to x target_means: the codebook elements corresponding to the targets code_loss: loss driving x closer to its nearest codebook element targets_loss: cross-entropy loss driving x closer to code corresponding to target
tensor2tensor/layers/discretization.py
def vq_loss(x, targets, codebook_size, beta=0.25, decay=0.999, epsilon=1e-5, soft_em=False, num_samples=10, temperature=None, do_update=True): """Compute the loss of large vocab tensors using a VQAE codebook. Args: x: Tensor of inputs to be quantized to nearest code targets: Tensor of target indices to target codes codebook_size: Size of quantization codebook beta: scalar float for moving averages decay: scalar float for moving averages epsilon: scalar float for moving averages soft_em: boolean, whether to apply a soft sampling procedure num_samples: if soft_em, number of samples to take temperature: temperature if we want to sample nearest neighbors or None do_update: whether to update the means; True by default, can be a Tensor Returns: discrete_x: one-hot Tensor indicating which codebook element is closest to x x_means: Tensor, on the forward pass: closest codebook element to x, on the backwards pass: soft convex-combination of codebook elements by proximity to x target_means: the codebook elements corresponding to the targets code_loss: loss driving x closer to its nearest codebook element targets_loss: cross-entropy loss driving x closer to code corresponding to target """ x_shape = common_layers.shape_list(x) target_shape = common_layers.shape_list(targets) hidden_size = x_shape[-1] means, _, _ = get_vq_codebook(codebook_size, hidden_size) x = tf.reshape(x, [-1, hidden_size]) targets = tf.reshape(targets, [-1]) one_hot_targets = tf.one_hot(targets, codebook_size) target_means = tf.matmul(one_hot_targets, means) discrete_x, code_loss, distances = vq_body( x, codebook_size, beta=beta, decay=decay, epsilon=epsilon, soft_em=soft_em, num_samples=num_samples, temperature=temperature, do_update=do_update) logits = -distances targets_loss = tf.losses.sparse_softmax_cross_entropy( logits=logits, labels=targets) targets_loss = tf.reduce_mean(targets_loss) x_means = tf.matmul(discrete_x, means) x_means = x + tf.stop_gradient(x_means - x) discrete_x = tf.reshape(discrete_x, x_shape[:-1] + [codebook_size]) target_means = tf.reshape(target_means, target_shape + [hidden_size]) return discrete_x, x_means, target_means, code_loss, targets_loss
def vq_loss(x, targets, codebook_size, beta=0.25, decay=0.999, epsilon=1e-5, soft_em=False, num_samples=10, temperature=None, do_update=True): """Compute the loss of large vocab tensors using a VQAE codebook. Args: x: Tensor of inputs to be quantized to nearest code targets: Tensor of target indices to target codes codebook_size: Size of quantization codebook beta: scalar float for moving averages decay: scalar float for moving averages epsilon: scalar float for moving averages soft_em: boolean, whether to apply a soft sampling procedure num_samples: if soft_em, number of samples to take temperature: temperature if we want to sample nearest neighbors or None do_update: whether to update the means; True by default, can be a Tensor Returns: discrete_x: one-hot Tensor indicating which codebook element is closest to x x_means: Tensor, on the forward pass: closest codebook element to x, on the backwards pass: soft convex-combination of codebook elements by proximity to x target_means: the codebook elements corresponding to the targets code_loss: loss driving x closer to its nearest codebook element targets_loss: cross-entropy loss driving x closer to code corresponding to target """ x_shape = common_layers.shape_list(x) target_shape = common_layers.shape_list(targets) hidden_size = x_shape[-1] means, _, _ = get_vq_codebook(codebook_size, hidden_size) x = tf.reshape(x, [-1, hidden_size]) targets = tf.reshape(targets, [-1]) one_hot_targets = tf.one_hot(targets, codebook_size) target_means = tf.matmul(one_hot_targets, means) discrete_x, code_loss, distances = vq_body( x, codebook_size, beta=beta, decay=decay, epsilon=epsilon, soft_em=soft_em, num_samples=num_samples, temperature=temperature, do_update=do_update) logits = -distances targets_loss = tf.losses.sparse_softmax_cross_entropy( logits=logits, labels=targets) targets_loss = tf.reduce_mean(targets_loss) x_means = tf.matmul(discrete_x, means) x_means = x + tf.stop_gradient(x_means - x) discrete_x = tf.reshape(discrete_x, x_shape[:-1] + [codebook_size]) target_means = tf.reshape(target_means, target_shape + [hidden_size]) return discrete_x, x_means, target_means, code_loss, targets_loss
[ "Compute", "the", "loss", "of", "large", "vocab", "tensors", "using", "a", "VQAE", "codebook", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/discretization.py#L1007-L1071
[ "def", "vq_loss", "(", "x", ",", "targets", ",", "codebook_size", ",", "beta", "=", "0.25", ",", "decay", "=", "0.999", ",", "epsilon", "=", "1e-5", ",", "soft_em", "=", "False", ",", "num_samples", "=", "10", ",", "temperature", "=", "None", ",", "d...
272500b6efe353aeb638d2745ed56e519462ca31
train
vq_discrete_unbottleneck
Simple undiscretization from vector quantized representation.
tensor2tensor/layers/discretization.py
def vq_discrete_unbottleneck(x, hidden_size): """Simple undiscretization from vector quantized representation.""" x_shape = common_layers.shape_list(x) x = tf.to_float(x) bottleneck_size = common_layers.shape_list(x)[-1] means, _, _ = get_vq_codebook(bottleneck_size, hidden_size) result = tf.matmul(tf.reshape(x, [-1, x_shape[-1]]), means) return tf.reshape(result, x_shape[:-1] + [hidden_size])
def vq_discrete_unbottleneck(x, hidden_size): """Simple undiscretization from vector quantized representation.""" x_shape = common_layers.shape_list(x) x = tf.to_float(x) bottleneck_size = common_layers.shape_list(x)[-1] means, _, _ = get_vq_codebook(bottleneck_size, hidden_size) result = tf.matmul(tf.reshape(x, [-1, x_shape[-1]]), means) return tf.reshape(result, x_shape[:-1] + [hidden_size])
[ "Simple", "undiscretization", "from", "vector", "quantized", "representation", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/discretization.py#L1074-L1081
[ "def", "vq_discrete_unbottleneck", "(", "x", ",", "hidden_size", ")", ":", "x_shape", "=", "common_layers", ".", "shape_list", "(", "x", ")", "x", "=", "tf", ".", "to_float", "(", "x", ")", "bottleneck_size", "=", "common_layers", ".", "shape_list", "(", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
gumbel_softmax_nearest_neighbor_dvq
Sample from Gumbel-Softmax and compute neighbors and losses. Args: x: A `float`-like `Tensor` of shape [batch_size, latent_dim, num_blocks, block_dim] containing the latent vectors to be compared to the codebook. means: Embedding table of shape [num_blocks, block_v_size, block_dim]. block_v_size: Number of discrete codes per block. hard: Determines whether we take hard or soft Gumbel-Softmax samples (Default: False). temperature_init: Initial temperature used for Gumbel-Softmax samples, after it which it decays to 0 (Default: 1.2). num_samples: Number of samples drawn for each latent (Default: 1). temperature_warmup_steps: Number of steps it takes to decay temperature to 0 (Default: 150000). summary: When `True`, we save histogram summaries of the KL term (Default: True). num_flows: Number of inverse autoregressive flows with Gumbel-Softmax samples. approximate_gs_entropy: When `True`, we approximate Gumbel-Softmax density as categorical when calculating sample entropy (Default: False). sum_over_latents: Whether to sum over non-batch dimensions when calculating negative entropy loss. Returns: x_means_assignments: A `float`-like `Tensor` containing the codebook assignments, averaged over samples, with shape [batch_size * latent_dim, num_blocks, block_v_size]. neg_q_entropy: The negative entropy of the variational distribution, averaged over samples.
tensor2tensor/layers/discretization.py
def gumbel_softmax_nearest_neighbor_dvq(x, means, block_v_size, hard=False, temperature_init=1.2, num_samples=1, temperature_warmup_steps=150000, summary=True, num_flows=0, approximate_gs_entropy=False, sum_over_latents=False): """Sample from Gumbel-Softmax and compute neighbors and losses. Args: x: A `float`-like `Tensor` of shape [batch_size, latent_dim, num_blocks, block_dim] containing the latent vectors to be compared to the codebook. means: Embedding table of shape [num_blocks, block_v_size, block_dim]. block_v_size: Number of discrete codes per block. hard: Determines whether we take hard or soft Gumbel-Softmax samples (Default: False). temperature_init: Initial temperature used for Gumbel-Softmax samples, after it which it decays to 0 (Default: 1.2). num_samples: Number of samples drawn for each latent (Default: 1). temperature_warmup_steps: Number of steps it takes to decay temperature to 0 (Default: 150000). summary: When `True`, we save histogram summaries of the KL term (Default: True). num_flows: Number of inverse autoregressive flows with Gumbel-Softmax samples. approximate_gs_entropy: When `True`, we approximate Gumbel-Softmax density as categorical when calculating sample entropy (Default: False). sum_over_latents: Whether to sum over non-batch dimensions when calculating negative entropy loss. Returns: x_means_assignments: A `float`-like `Tensor` containing the codebook assignments, averaged over samples, with shape [batch_size * latent_dim, num_blocks, block_v_size]. neg_q_entropy: The negative entropy of the variational distribution, averaged over samples. """ batch_size, latent_dim, num_blocks, block_dim = common_layers.shape_list(x) # Combine latent_dim and batch_size for computing distances. x = tf.reshape(x, [-1, num_blocks, block_dim]) # Compute distances using (x - means)**2 = x**2 + means**2 - 2*x*means. x_norm_sq = tf.reduce_sum(tf.square(x), axis=-1, keepdims=True) means_norm_sq = tf.reduce_sum(tf.square(means), axis=-1, keepdims=True) means_norm_sq = tf.transpose(means_norm_sq, perm=[2, 0, 1]) scalar_prod = tf.matmul( tf.transpose(x, perm=[1, 0, 2]), tf.transpose(means, perm=[0, 2, 1])) scalar_prod = tf.transpose(scalar_prod, perm=[1, 0, 2]) dist = x_norm_sq + means_norm_sq - 2 * scalar_prod # IAF requires latents to have their own dimension, so reshape dist from # [batch_size * latent_dim, num_blocks, block_v_size] to # [batch_size * num_blocks, latent_dim, block_v_size]. dist = tf.reshape(dist, [batch_size, latent_dim, num_blocks, -1]) dist = tf.reshape( tf.transpose(dist, perm=[0, 2, 1, 3]), [-1, latent_dim, block_v_size]) log_class_probs = tf.nn.log_softmax(-dist) sample_shape = [num_samples] + common_layers.shape_list(dist) gumbel_samples = gumbel_sample(sample_shape) # Temperature decays linearly. temperature = temperature_init - common_layers.inverse_lin_decay( temperature_warmup_steps) # 10% of the time keep reasonably high temperature to keep learning. temperature = tf.cond( tf.less(tf.random_uniform([]), 0.9), lambda: temperature, lambda: tf.random_uniform([], minval=0.5, maxval=1.0)) gumbel_softmax_samples = tf.nn.softmax( (tf.expand_dims(log_class_probs, 0) + gumbel_samples) / temperature) q_samples = tf.clip_by_value(gumbel_softmax_samples, 1e-6, 1 - 1e-6) if approximate_gs_entropy: q_dist = tfp.distributions.Multinomial(total_count=1.0, logits=-dist) else: q_dist = tfp.distributions.RelaxedOneHotCategorical( temperature, logits=-dist) # Take mean over samples to approximate entropy. neg_q_entropy = tf.reduce_mean(q_dist.log_prob(q_samples), 0) if summary: tf.summary.histogram("neg_q_entropy", tf.reshape(neg_q_entropy, [-1])) if sum_over_latents: neg_q_entropy = tf.reshape(neg_q_entropy, [batch_size, num_blocks, latent_dim]) neg_q_entropy = tf.reduce_sum(neg_q_entropy, [1, 2]) neg_q_entropy = tf.reduce_mean(neg_q_entropy) if num_flows > 0: hparams = iaf_hparams(hidden_size=512, filter_size=4096) q_samples = tf.reshape(q_samples, [-1, latent_dim, block_v_size]) for flow in range(num_flows): shifted_samples = tf.pad(q_samples, [[0, 0], [1, 0], [0, 0]])[:, :-1, :] # Project samples from [batch_size, latent_size, block_v_size] to # [batch_size, latent_size, hidden_size]. shifted_samples = common_layers.dense(shifted_samples, hparams.hidden_size) # TODO(vafa): Include masking as a flag. mask = True if mask: attention_type = cia.AttentionType.LOCAL_1D else: attention_type = cia.AttentionType.GLOBAL ffn_output = cia.transformer_decoder_layers( inputs=shifted_samples, encoder_output=None, num_layers=6, hparams=hparams, attention_type=attention_type, name="transformer_" + str(flow)) # Project samples back to [batch_size, latent_size, block_v_size]. ffn_output = common_layers.dense(ffn_output, block_v_size) log_pi = tf.nn.log_softmax(ffn_output) # Flow 1: Adding log_pi to q_samples and dividing by the temperature. # Note that we drop the last dimension of q_samples for centered-softmax, # which we can do without recalculating probabilities because the last # dimension of log_pi and q_samples are deterministic given the others. # Flow 2: Centered-softmax. chained_bijectors = tfp.bijectors.Chain([ tfp.bijectors.SoftmaxCentered(), tfp.bijectors.Affine( shift=log_pi[:, :, :-1], scale_identity_multiplier=1. / temperature) ]) q_samples = chained_bijectors.forward(q_samples[:, :, :-1]) log_det = chained_bijectors.inverse_log_det_jacobian( q_samples, event_ndims=1) log_det = tf.reshape(log_det, [num_samples, batch_size, num_blocks, latent_dim]) if sum_over_latents: log_det = tf.reduce_sum(log_det, axis=[2, 3]) neg_q_entropy += tf.reduce_mean(log_det) q_samples = tf.reshape( q_samples, [num_samples, batch_size * num_blocks, latent_dim, block_v_size]) if hard: x_means_idx = tf.argmax(q_samples, -1) # Take average of one-hot vectors over samples. x_means_hot = tf.reduce_mean(tf.one_hot(x_means_idx, block_v_size), 0) x_means_assignments = ( tf.reduce_mean(q_samples, 0) + tf.stop_gradient(x_means_hot - tf.reduce_mean(q_samples, 0))) else: x_means_assignments = tf.reduce_mean(gumbel_softmax_samples, 0) # Reshape assignments to [batch_size * latent_dim, num_blocks, # block_v_size]. We have to transpose between reshapes to make sure the # dimensions have the correct interpretation. x_means_assignments = tf.reshape( x_means_assignments, [batch_size, num_blocks, latent_dim, block_v_size]) x_means_assignments = tf.transpose(x_means_assignments, [0, 2, 1, 3]) x_means_assignments = tf.reshape( x_means_assignments, [batch_size * latent_dim, num_blocks, block_v_size]) return x_means_assignments, neg_q_entropy
def gumbel_softmax_nearest_neighbor_dvq(x, means, block_v_size, hard=False, temperature_init=1.2, num_samples=1, temperature_warmup_steps=150000, summary=True, num_flows=0, approximate_gs_entropy=False, sum_over_latents=False): """Sample from Gumbel-Softmax and compute neighbors and losses. Args: x: A `float`-like `Tensor` of shape [batch_size, latent_dim, num_blocks, block_dim] containing the latent vectors to be compared to the codebook. means: Embedding table of shape [num_blocks, block_v_size, block_dim]. block_v_size: Number of discrete codes per block. hard: Determines whether we take hard or soft Gumbel-Softmax samples (Default: False). temperature_init: Initial temperature used for Gumbel-Softmax samples, after it which it decays to 0 (Default: 1.2). num_samples: Number of samples drawn for each latent (Default: 1). temperature_warmup_steps: Number of steps it takes to decay temperature to 0 (Default: 150000). summary: When `True`, we save histogram summaries of the KL term (Default: True). num_flows: Number of inverse autoregressive flows with Gumbel-Softmax samples. approximate_gs_entropy: When `True`, we approximate Gumbel-Softmax density as categorical when calculating sample entropy (Default: False). sum_over_latents: Whether to sum over non-batch dimensions when calculating negative entropy loss. Returns: x_means_assignments: A `float`-like `Tensor` containing the codebook assignments, averaged over samples, with shape [batch_size * latent_dim, num_blocks, block_v_size]. neg_q_entropy: The negative entropy of the variational distribution, averaged over samples. """ batch_size, latent_dim, num_blocks, block_dim = common_layers.shape_list(x) # Combine latent_dim and batch_size for computing distances. x = tf.reshape(x, [-1, num_blocks, block_dim]) # Compute distances using (x - means)**2 = x**2 + means**2 - 2*x*means. x_norm_sq = tf.reduce_sum(tf.square(x), axis=-1, keepdims=True) means_norm_sq = tf.reduce_sum(tf.square(means), axis=-1, keepdims=True) means_norm_sq = tf.transpose(means_norm_sq, perm=[2, 0, 1]) scalar_prod = tf.matmul( tf.transpose(x, perm=[1, 0, 2]), tf.transpose(means, perm=[0, 2, 1])) scalar_prod = tf.transpose(scalar_prod, perm=[1, 0, 2]) dist = x_norm_sq + means_norm_sq - 2 * scalar_prod # IAF requires latents to have their own dimension, so reshape dist from # [batch_size * latent_dim, num_blocks, block_v_size] to # [batch_size * num_blocks, latent_dim, block_v_size]. dist = tf.reshape(dist, [batch_size, latent_dim, num_blocks, -1]) dist = tf.reshape( tf.transpose(dist, perm=[0, 2, 1, 3]), [-1, latent_dim, block_v_size]) log_class_probs = tf.nn.log_softmax(-dist) sample_shape = [num_samples] + common_layers.shape_list(dist) gumbel_samples = gumbel_sample(sample_shape) # Temperature decays linearly. temperature = temperature_init - common_layers.inverse_lin_decay( temperature_warmup_steps) # 10% of the time keep reasonably high temperature to keep learning. temperature = tf.cond( tf.less(tf.random_uniform([]), 0.9), lambda: temperature, lambda: tf.random_uniform([], minval=0.5, maxval=1.0)) gumbel_softmax_samples = tf.nn.softmax( (tf.expand_dims(log_class_probs, 0) + gumbel_samples) / temperature) q_samples = tf.clip_by_value(gumbel_softmax_samples, 1e-6, 1 - 1e-6) if approximate_gs_entropy: q_dist = tfp.distributions.Multinomial(total_count=1.0, logits=-dist) else: q_dist = tfp.distributions.RelaxedOneHotCategorical( temperature, logits=-dist) # Take mean over samples to approximate entropy. neg_q_entropy = tf.reduce_mean(q_dist.log_prob(q_samples), 0) if summary: tf.summary.histogram("neg_q_entropy", tf.reshape(neg_q_entropy, [-1])) if sum_over_latents: neg_q_entropy = tf.reshape(neg_q_entropy, [batch_size, num_blocks, latent_dim]) neg_q_entropy = tf.reduce_sum(neg_q_entropy, [1, 2]) neg_q_entropy = tf.reduce_mean(neg_q_entropy) if num_flows > 0: hparams = iaf_hparams(hidden_size=512, filter_size=4096) q_samples = tf.reshape(q_samples, [-1, latent_dim, block_v_size]) for flow in range(num_flows): shifted_samples = tf.pad(q_samples, [[0, 0], [1, 0], [0, 0]])[:, :-1, :] # Project samples from [batch_size, latent_size, block_v_size] to # [batch_size, latent_size, hidden_size]. shifted_samples = common_layers.dense(shifted_samples, hparams.hidden_size) # TODO(vafa): Include masking as a flag. mask = True if mask: attention_type = cia.AttentionType.LOCAL_1D else: attention_type = cia.AttentionType.GLOBAL ffn_output = cia.transformer_decoder_layers( inputs=shifted_samples, encoder_output=None, num_layers=6, hparams=hparams, attention_type=attention_type, name="transformer_" + str(flow)) # Project samples back to [batch_size, latent_size, block_v_size]. ffn_output = common_layers.dense(ffn_output, block_v_size) log_pi = tf.nn.log_softmax(ffn_output) # Flow 1: Adding log_pi to q_samples and dividing by the temperature. # Note that we drop the last dimension of q_samples for centered-softmax, # which we can do without recalculating probabilities because the last # dimension of log_pi and q_samples are deterministic given the others. # Flow 2: Centered-softmax. chained_bijectors = tfp.bijectors.Chain([ tfp.bijectors.SoftmaxCentered(), tfp.bijectors.Affine( shift=log_pi[:, :, :-1], scale_identity_multiplier=1. / temperature) ]) q_samples = chained_bijectors.forward(q_samples[:, :, :-1]) log_det = chained_bijectors.inverse_log_det_jacobian( q_samples, event_ndims=1) log_det = tf.reshape(log_det, [num_samples, batch_size, num_blocks, latent_dim]) if sum_over_latents: log_det = tf.reduce_sum(log_det, axis=[2, 3]) neg_q_entropy += tf.reduce_mean(log_det) q_samples = tf.reshape( q_samples, [num_samples, batch_size * num_blocks, latent_dim, block_v_size]) if hard: x_means_idx = tf.argmax(q_samples, -1) # Take average of one-hot vectors over samples. x_means_hot = tf.reduce_mean(tf.one_hot(x_means_idx, block_v_size), 0) x_means_assignments = ( tf.reduce_mean(q_samples, 0) + tf.stop_gradient(x_means_hot - tf.reduce_mean(q_samples, 0))) else: x_means_assignments = tf.reduce_mean(gumbel_softmax_samples, 0) # Reshape assignments to [batch_size * latent_dim, num_blocks, # block_v_size]. We have to transpose between reshapes to make sure the # dimensions have the correct interpretation. x_means_assignments = tf.reshape( x_means_assignments, [batch_size, num_blocks, latent_dim, block_v_size]) x_means_assignments = tf.transpose(x_means_assignments, [0, 2, 1, 3]) x_means_assignments = tf.reshape( x_means_assignments, [batch_size * latent_dim, num_blocks, block_v_size]) return x_means_assignments, neg_q_entropy
[ "Sample", "from", "Gumbel", "-", "Softmax", "and", "compute", "neighbors", "and", "losses", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/discretization.py#L1084-L1251
[ "def", "gumbel_softmax_nearest_neighbor_dvq", "(", "x", ",", "means", ",", "block_v_size", ",", "hard", "=", "False", ",", "temperature_init", "=", "1.2", ",", "num_samples", "=", "1", ",", "temperature_warmup_steps", "=", "150000", ",", "summary", "=", "True", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
gumbel_softmax_discrete_bottleneck
VQ-VAE using Gumbel-Softmax. Different from `gumbel_softmax()` function as this function calculates the KL by using the discrete entropy instead of taking the argmax, and it also uses an exponential moving average to update the codebook while the `gumbel_softmax()` function includes no codebook update. Args: x: A `float`-like `Tensor` containing the latent vectors to be compared to the codebook, whose squared difference is used as the Gumbel-Softmax logits. bottleneck_bits: An `int` that sets the size of the bottleneck in `log_2`. beta: Beta factor for commitment loss (Default: 0.25). decay: Decay factor for exponential moving average (Default: 0.999). epsilon: Small value to avoid dividing by zero in EMA update (Default: 1e-5). temperature_warmup_steps: Number of steps it takes to decay temperature to 0 (Default: 150000). hard: When `True`, we use hard Gumbel-Softmax samples and force discrete latents by taking the argmax. When `False`, we use soft samples, which we treat as codebook weights (Default: False). summary: When `True`, we save histogram summaries of the KL term (Default: True). Returns: x_means_assignments: A `float`-like `Tensor` containing the codebook assignments. When `hard == True`, this is one-hot, containing the arg-max of the Gumbel-Softmax samples (and we use the straightthrough gradient). Otherwise, it contains the Gumbel-Softmax samples exactly, which are values from the `(K-1)`-simplex where `K` is the bottleneck size. loss: The loss, which is the sum of the KL between the Gumbel-Softmax and the uniform prior and the commitment loss multiplied by the beta factor. We approximate the KL by using the entropy of a categorical distribution instead of the Gumbel Softmax.
tensor2tensor/layers/discretization.py
def gumbel_softmax_discrete_bottleneck(x, bottleneck_bits, beta=0.25, decay=0.999, epsilon=1e-5, temperature_warmup_steps=150000, hard=False, summary=True): """VQ-VAE using Gumbel-Softmax. Different from `gumbel_softmax()` function as this function calculates the KL by using the discrete entropy instead of taking the argmax, and it also uses an exponential moving average to update the codebook while the `gumbel_softmax()` function includes no codebook update. Args: x: A `float`-like `Tensor` containing the latent vectors to be compared to the codebook, whose squared difference is used as the Gumbel-Softmax logits. bottleneck_bits: An `int` that sets the size of the bottleneck in `log_2`. beta: Beta factor for commitment loss (Default: 0.25). decay: Decay factor for exponential moving average (Default: 0.999). epsilon: Small value to avoid dividing by zero in EMA update (Default: 1e-5). temperature_warmup_steps: Number of steps it takes to decay temperature to 0 (Default: 150000). hard: When `True`, we use hard Gumbel-Softmax samples and force discrete latents by taking the argmax. When `False`, we use soft samples, which we treat as codebook weights (Default: False). summary: When `True`, we save histogram summaries of the KL term (Default: True). Returns: x_means_assignments: A `float`-like `Tensor` containing the codebook assignments. When `hard == True`, this is one-hot, containing the arg-max of the Gumbel-Softmax samples (and we use the straightthrough gradient). Otherwise, it contains the Gumbel-Softmax samples exactly, which are values from the `(K-1)`-simplex where `K` is the bottleneck size. loss: The loss, which is the sum of the KL between the Gumbel-Softmax and the uniform prior and the commitment loss multiplied by the beta factor. We approximate the KL by using the entropy of a categorical distribution instead of the Gumbel Softmax. """ bottleneck_size = 2**bottleneck_bits x_shape = common_layers.shape_list(x) hidden_size = x_shape[-1] means, ema_means, ema_count = get_vq_codebook(bottleneck_size, hidden_size) x = tf.reshape(x, [-1, hidden_size]) bottleneck_size = common_layers.shape_list(means)[0] x_norm_sq = tf.reduce_sum(tf.square(x), axis=-1, keepdims=True) means_norm_sq = tf.reduce_sum(tf.square(means), axis=-1, keepdims=True) scalar_prod = tf.matmul(x, means, transpose_b=True) dist = x_norm_sq + tf.transpose(means_norm_sq) - 2 * scalar_prod class_probs = tf.nn.softmax(dist) log_class_probs = tf.nn.log_softmax(dist) gumbel_samples = gumbel_sample(common_layers.shape_list(dist)) steps = temperature_warmup_steps gumbel_samples *= common_layers.inverse_exp_decay(steps // 5) * 0.5 temperature = 1.2 - common_layers.inverse_lin_decay(steps) # 10% of the time keep reasonably high temperature to keep learning. temperature = tf.cond( tf.less(tf.random_uniform([]), 0.9), lambda: temperature, lambda: tf.random_uniform([], minval=0.5, maxval=1.0)) gumbel_softmax_samples = tf.nn.softmax( (log_class_probs + gumbel_samples) / temperature) # Calculate KL between q and a uniform prior. kl = tf.reduce_sum( class_probs * (log_class_probs - tf.log(1.0 / bottleneck_size)), -1) if summary: tf.summary.histogram("KL", tf.reshape(kl, [-1])) # Straight-through gradient estimation when we're using hard assignments. if hard: x_means_idx = tf.reshape(tf.argmax(gumbel_softmax_samples, axis=-1), [-1]) x_means_hot = tf.one_hot(x_means_idx, bottleneck_size) x_means_assignments = gumbel_softmax_samples + tf.stop_gradient( x_means_hot - gumbel_softmax_samples) else: x_means_assignments = gumbel_softmax_samples x_means_assignments_flat = tf.reshape(x_means_assignments, [-1, bottleneck_size]) x_means = tf.matmul(x_means_assignments_flat, means) commitment_loss = tf.reduce_mean( tf.squared_difference(x, tf.stop_gradient(x_means))) # Update the ema variables. updated_ema_count = moving_averages.assign_moving_average( ema_count, tf.reduce_sum( tf.reshape(x_means_assignments, shape=[-1, bottleneck_size]), axis=0), decay, zero_debias=False) dw = tf.matmul(x_means_assignments, x, transpose_a=True) updated_ema_means = tf.identity( moving_averages.assign_moving_average( ema_means, dw, decay, zero_debias=False)) n = tf.reduce_sum(updated_ema_count, axis=-1, keepdims=True) updated_ema_count = ( (updated_ema_count + epsilon) / (n + bottleneck_size * epsilon) * n) updated_ema_means /= tf.expand_dims(updated_ema_count, axis=-1) with tf.control_dependencies([commitment_loss]): update_means = means.assign(updated_ema_means) with tf.control_dependencies([update_means]): loss = beta * commitment_loss # Add KL loss. loss += tf.reduce_mean(kl) x_means_assignments = tf.reshape(x_means_assignments, x_shape[:-1] + [bottleneck_size]) return x_means_assignments, loss
def gumbel_softmax_discrete_bottleneck(x, bottleneck_bits, beta=0.25, decay=0.999, epsilon=1e-5, temperature_warmup_steps=150000, hard=False, summary=True): """VQ-VAE using Gumbel-Softmax. Different from `gumbel_softmax()` function as this function calculates the KL by using the discrete entropy instead of taking the argmax, and it also uses an exponential moving average to update the codebook while the `gumbel_softmax()` function includes no codebook update. Args: x: A `float`-like `Tensor` containing the latent vectors to be compared to the codebook, whose squared difference is used as the Gumbel-Softmax logits. bottleneck_bits: An `int` that sets the size of the bottleneck in `log_2`. beta: Beta factor for commitment loss (Default: 0.25). decay: Decay factor for exponential moving average (Default: 0.999). epsilon: Small value to avoid dividing by zero in EMA update (Default: 1e-5). temperature_warmup_steps: Number of steps it takes to decay temperature to 0 (Default: 150000). hard: When `True`, we use hard Gumbel-Softmax samples and force discrete latents by taking the argmax. When `False`, we use soft samples, which we treat as codebook weights (Default: False). summary: When `True`, we save histogram summaries of the KL term (Default: True). Returns: x_means_assignments: A `float`-like `Tensor` containing the codebook assignments. When `hard == True`, this is one-hot, containing the arg-max of the Gumbel-Softmax samples (and we use the straightthrough gradient). Otherwise, it contains the Gumbel-Softmax samples exactly, which are values from the `(K-1)`-simplex where `K` is the bottleneck size. loss: The loss, which is the sum of the KL between the Gumbel-Softmax and the uniform prior and the commitment loss multiplied by the beta factor. We approximate the KL by using the entropy of a categorical distribution instead of the Gumbel Softmax. """ bottleneck_size = 2**bottleneck_bits x_shape = common_layers.shape_list(x) hidden_size = x_shape[-1] means, ema_means, ema_count = get_vq_codebook(bottleneck_size, hidden_size) x = tf.reshape(x, [-1, hidden_size]) bottleneck_size = common_layers.shape_list(means)[0] x_norm_sq = tf.reduce_sum(tf.square(x), axis=-1, keepdims=True) means_norm_sq = tf.reduce_sum(tf.square(means), axis=-1, keepdims=True) scalar_prod = tf.matmul(x, means, transpose_b=True) dist = x_norm_sq + tf.transpose(means_norm_sq) - 2 * scalar_prod class_probs = tf.nn.softmax(dist) log_class_probs = tf.nn.log_softmax(dist) gumbel_samples = gumbel_sample(common_layers.shape_list(dist)) steps = temperature_warmup_steps gumbel_samples *= common_layers.inverse_exp_decay(steps // 5) * 0.5 temperature = 1.2 - common_layers.inverse_lin_decay(steps) # 10% of the time keep reasonably high temperature to keep learning. temperature = tf.cond( tf.less(tf.random_uniform([]), 0.9), lambda: temperature, lambda: tf.random_uniform([], minval=0.5, maxval=1.0)) gumbel_softmax_samples = tf.nn.softmax( (log_class_probs + gumbel_samples) / temperature) # Calculate KL between q and a uniform prior. kl = tf.reduce_sum( class_probs * (log_class_probs - tf.log(1.0 / bottleneck_size)), -1) if summary: tf.summary.histogram("KL", tf.reshape(kl, [-1])) # Straight-through gradient estimation when we're using hard assignments. if hard: x_means_idx = tf.reshape(tf.argmax(gumbel_softmax_samples, axis=-1), [-1]) x_means_hot = tf.one_hot(x_means_idx, bottleneck_size) x_means_assignments = gumbel_softmax_samples + tf.stop_gradient( x_means_hot - gumbel_softmax_samples) else: x_means_assignments = gumbel_softmax_samples x_means_assignments_flat = tf.reshape(x_means_assignments, [-1, bottleneck_size]) x_means = tf.matmul(x_means_assignments_flat, means) commitment_loss = tf.reduce_mean( tf.squared_difference(x, tf.stop_gradient(x_means))) # Update the ema variables. updated_ema_count = moving_averages.assign_moving_average( ema_count, tf.reduce_sum( tf.reshape(x_means_assignments, shape=[-1, bottleneck_size]), axis=0), decay, zero_debias=False) dw = tf.matmul(x_means_assignments, x, transpose_a=True) updated_ema_means = tf.identity( moving_averages.assign_moving_average( ema_means, dw, decay, zero_debias=False)) n = tf.reduce_sum(updated_ema_count, axis=-1, keepdims=True) updated_ema_count = ( (updated_ema_count + epsilon) / (n + bottleneck_size * epsilon) * n) updated_ema_means /= tf.expand_dims(updated_ema_count, axis=-1) with tf.control_dependencies([commitment_loss]): update_means = means.assign(updated_ema_means) with tf.control_dependencies([update_means]): loss = beta * commitment_loss # Add KL loss. loss += tf.reduce_mean(kl) x_means_assignments = tf.reshape(x_means_assignments, x_shape[:-1] + [bottleneck_size]) return x_means_assignments, loss
[ "VQ", "-", "VAE", "using", "Gumbel", "-", "Softmax", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/discretization.py#L1254-L1371
[ "def", "gumbel_softmax_discrete_bottleneck", "(", "x", ",", "bottleneck_bits", ",", "beta", "=", "0.25", ",", "decay", "=", "0.999", ",", "epsilon", "=", "1e-5", ",", "temperature_warmup_steps", "=", "150000", ",", "hard", "=", "False", ",", "summary", "=", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
tanh_discrete_bottleneck
Simple discretization through tanh, flip bottleneck_noise many bits.
tensor2tensor/layers/discretization.py
def tanh_discrete_bottleneck(x, bottleneck_bits, bottleneck_noise, discretize_warmup_steps, mode): """Simple discretization through tanh, flip bottleneck_noise many bits.""" x = tf.layers.dense(x, bottleneck_bits, name="tanh_discrete_bottleneck") d0 = tf.stop_gradient(2.0 * tf.to_float(tf.less(0.0, x))) - 1.0 if mode == tf.estimator.ModeKeys.TRAIN: x += tf.truncated_normal( common_layers.shape_list(x), mean=0.0, stddev=0.2) x = tf.tanh(x) d = x + tf.stop_gradient(2.0 * tf.to_float(tf.less(0.0, x)) - 1.0 - x) if mode == tf.estimator.ModeKeys.TRAIN: noise = tf.random_uniform(common_layers.shape_list(x)) noise = 2.0 * tf.to_float(tf.less(bottleneck_noise, noise)) - 1.0 d *= noise d = common_layers.mix(d, x, discretize_warmup_steps, mode == tf.estimator.ModeKeys.TRAIN) return d, d0
def tanh_discrete_bottleneck(x, bottleneck_bits, bottleneck_noise, discretize_warmup_steps, mode): """Simple discretization through tanh, flip bottleneck_noise many bits.""" x = tf.layers.dense(x, bottleneck_bits, name="tanh_discrete_bottleneck") d0 = tf.stop_gradient(2.0 * tf.to_float(tf.less(0.0, x))) - 1.0 if mode == tf.estimator.ModeKeys.TRAIN: x += tf.truncated_normal( common_layers.shape_list(x), mean=0.0, stddev=0.2) x = tf.tanh(x) d = x + tf.stop_gradient(2.0 * tf.to_float(tf.less(0.0, x)) - 1.0 - x) if mode == tf.estimator.ModeKeys.TRAIN: noise = tf.random_uniform(common_layers.shape_list(x)) noise = 2.0 * tf.to_float(tf.less(bottleneck_noise, noise)) - 1.0 d *= noise d = common_layers.mix(d, x, discretize_warmup_steps, mode == tf.estimator.ModeKeys.TRAIN) return d, d0
[ "Simple", "discretization", "through", "tanh", "flip", "bottleneck_noise", "many", "bits", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/discretization.py#L1374-L1390
[ "def", "tanh_discrete_bottleneck", "(", "x", ",", "bottleneck_bits", ",", "bottleneck_noise", ",", "discretize_warmup_steps", ",", "mode", ")", ":", "x", "=", "tf", ".", "layers", ".", "dense", "(", "x", ",", "bottleneck_bits", ",", "name", "=", "\"tanh_discre...
272500b6efe353aeb638d2745ed56e519462ca31
train
tanh_discrete_unbottleneck
Simple un-discretization from tanh.
tensor2tensor/layers/discretization.py
def tanh_discrete_unbottleneck(x, hidden_size): """Simple un-discretization from tanh.""" x = tf.layers.dense(x, hidden_size, name="tanh_discrete_unbottleneck") return x
def tanh_discrete_unbottleneck(x, hidden_size): """Simple un-discretization from tanh.""" x = tf.layers.dense(x, hidden_size, name="tanh_discrete_unbottleneck") return x
[ "Simple", "un", "-", "discretization", "from", "tanh", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/discretization.py#L1393-L1396
[ "def", "tanh_discrete_unbottleneck", "(", "x", ",", "hidden_size", ")", ":", "x", "=", "tf", ".", "layers", ".", "dense", "(", "x", ",", "hidden_size", ",", "name", "=", "\"tanh_discrete_unbottleneck\"", ")", "return", "x" ]
272500b6efe353aeb638d2745ed56e519462ca31
train
isemhash_bottleneck
Improved semantic hashing bottleneck.
tensor2tensor/layers/discretization.py
def isemhash_bottleneck(x, bottleneck_bits, bottleneck_noise, discretize_warmup_steps, mode, isemhash_noise_dev=0.5, isemhash_mix_prob=0.5): """Improved semantic hashing bottleneck.""" with tf.variable_scope("isemhash_bottleneck"): x = tf.layers.dense(x, bottleneck_bits, name="dense") y = common_layers.saturating_sigmoid(x) if isemhash_noise_dev > 0 and mode == tf.estimator.ModeKeys.TRAIN: noise = tf.truncated_normal( common_layers.shape_list(x), mean=0.0, stddev=isemhash_noise_dev) y = common_layers.saturating_sigmoid(x + noise) d = tf.to_float(tf.less(0.5, y)) + y - tf.stop_gradient(y) d = 2.0 * d - 1.0 # Move from [0, 1] to [-1, 1]. if mode == tf.estimator.ModeKeys.TRAIN: # Flip some bits. noise = tf.random_uniform(common_layers.shape_list(x)) noise = 2.0 * tf.to_float(tf.less(bottleneck_noise, noise)) - 1.0 d *= noise d = common_layers.mix( d, 2.0 * y - 1.0, discretize_warmup_steps, mode == tf.estimator.ModeKeys.TRAIN, max_prob=isemhash_mix_prob) return d, 0.0
def isemhash_bottleneck(x, bottleneck_bits, bottleneck_noise, discretize_warmup_steps, mode, isemhash_noise_dev=0.5, isemhash_mix_prob=0.5): """Improved semantic hashing bottleneck.""" with tf.variable_scope("isemhash_bottleneck"): x = tf.layers.dense(x, bottleneck_bits, name="dense") y = common_layers.saturating_sigmoid(x) if isemhash_noise_dev > 0 and mode == tf.estimator.ModeKeys.TRAIN: noise = tf.truncated_normal( common_layers.shape_list(x), mean=0.0, stddev=isemhash_noise_dev) y = common_layers.saturating_sigmoid(x + noise) d = tf.to_float(tf.less(0.5, y)) + y - tf.stop_gradient(y) d = 2.0 * d - 1.0 # Move from [0, 1] to [-1, 1]. if mode == tf.estimator.ModeKeys.TRAIN: # Flip some bits. noise = tf.random_uniform(common_layers.shape_list(x)) noise = 2.0 * tf.to_float(tf.less(bottleneck_noise, noise)) - 1.0 d *= noise d = common_layers.mix( d, 2.0 * y - 1.0, discretize_warmup_steps, mode == tf.estimator.ModeKeys.TRAIN, max_prob=isemhash_mix_prob) return d, 0.0
[ "Improved", "semantic", "hashing", "bottleneck", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/discretization.py#L1399-L1426
[ "def", "isemhash_bottleneck", "(", "x", ",", "bottleneck_bits", ",", "bottleneck_noise", ",", "discretize_warmup_steps", ",", "mode", ",", "isemhash_noise_dev", "=", "0.5", ",", "isemhash_mix_prob", "=", "0.5", ")", ":", "with", "tf", ".", "variable_scope", "(", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
isemhash_unbottleneck
Improved semantic hashing un-bottleneck.
tensor2tensor/layers/discretization.py
def isemhash_unbottleneck(x, hidden_size, isemhash_filter_size_multiplier=1.0): """Improved semantic hashing un-bottleneck.""" filter_size = int(hidden_size * isemhash_filter_size_multiplier) x = 0.5 * (x - 1.0) # Move from [-1, 1] to [0, 1]. with tf.variable_scope("isemhash_unbottleneck"): h1a = tf.layers.dense(x, filter_size, name="hidden1a") h1b = tf.layers.dense(1.0 - x, filter_size, name="hidden1b") h2 = tf.layers.dense(tf.nn.relu(h1a + h1b), filter_size, name="hidden2") return tf.layers.dense(tf.nn.relu(h2), hidden_size, name="final")
def isemhash_unbottleneck(x, hidden_size, isemhash_filter_size_multiplier=1.0): """Improved semantic hashing un-bottleneck.""" filter_size = int(hidden_size * isemhash_filter_size_multiplier) x = 0.5 * (x - 1.0) # Move from [-1, 1] to [0, 1]. with tf.variable_scope("isemhash_unbottleneck"): h1a = tf.layers.dense(x, filter_size, name="hidden1a") h1b = tf.layers.dense(1.0 - x, filter_size, name="hidden1b") h2 = tf.layers.dense(tf.nn.relu(h1a + h1b), filter_size, name="hidden2") return tf.layers.dense(tf.nn.relu(h2), hidden_size, name="final")
[ "Improved", "semantic", "hashing", "un", "-", "bottleneck", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/discretization.py#L1429-L1437
[ "def", "isemhash_unbottleneck", "(", "x", ",", "hidden_size", ",", "isemhash_filter_size_multiplier", "=", "1.0", ")", ":", "filter_size", "=", "int", "(", "hidden_size", "*", "isemhash_filter_size_multiplier", ")", "x", "=", "0.5", "*", "(", "x", "-", "1.0", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
parametrized_bottleneck
Meta-function calling all the above bottlenecks with hparams.
tensor2tensor/layers/discretization.py
def parametrized_bottleneck(x, hparams): """Meta-function calling all the above bottlenecks with hparams.""" if hparams.bottleneck_kind == "tanh_discrete": d, _ = tanh_discrete_bottleneck( x, hparams.bottleneck_bits, hparams.bottleneck_noise * 0.5, hparams.discretize_warmup_steps, hparams.mode) return d, 0.0 if hparams.bottleneck_kind == "isemhash": return isemhash_bottleneck( x, hparams.bottleneck_bits, hparams.bottleneck_noise * 0.5, hparams.discretize_warmup_steps, hparams.mode, hparams.isemhash_noise_dev, hparams.isemhash_mix_prob) if hparams.bottleneck_kind == "vq": return vq_discrete_bottleneck(x, hparams.bottleneck_bits, hparams.vq_beta, hparams.vq_decay, hparams.vq_epsilon) if hparams.bottleneck_kind == "em": return vq_discrete_bottleneck( x, hparams.bottleneck_bits, hparams.vq_beta, hparams.vq_decay, hparams.vq_epsilon, soft_em=True, num_samples=hparams.vq_num_samples) if hparams.bottleneck_kind == "gumbel_softmax": return gumbel_softmax_discrete_bottleneck( x, hparams.bottleneck_bits, hparams.vq_beta, hparams.vq_decay, hparams.vq_epsilon, hparams.temperature_warmup_steps, hard=False, summary=True) raise ValueError( "Unsupported hparams.bottleneck_kind %s" % hparams.bottleneck_kind)
def parametrized_bottleneck(x, hparams): """Meta-function calling all the above bottlenecks with hparams.""" if hparams.bottleneck_kind == "tanh_discrete": d, _ = tanh_discrete_bottleneck( x, hparams.bottleneck_bits, hparams.bottleneck_noise * 0.5, hparams.discretize_warmup_steps, hparams.mode) return d, 0.0 if hparams.bottleneck_kind == "isemhash": return isemhash_bottleneck( x, hparams.bottleneck_bits, hparams.bottleneck_noise * 0.5, hparams.discretize_warmup_steps, hparams.mode, hparams.isemhash_noise_dev, hparams.isemhash_mix_prob) if hparams.bottleneck_kind == "vq": return vq_discrete_bottleneck(x, hparams.bottleneck_bits, hparams.vq_beta, hparams.vq_decay, hparams.vq_epsilon) if hparams.bottleneck_kind == "em": return vq_discrete_bottleneck( x, hparams.bottleneck_bits, hparams.vq_beta, hparams.vq_decay, hparams.vq_epsilon, soft_em=True, num_samples=hparams.vq_num_samples) if hparams.bottleneck_kind == "gumbel_softmax": return gumbel_softmax_discrete_bottleneck( x, hparams.bottleneck_bits, hparams.vq_beta, hparams.vq_decay, hparams.vq_epsilon, hparams.temperature_warmup_steps, hard=False, summary=True) raise ValueError( "Unsupported hparams.bottleneck_kind %s" % hparams.bottleneck_kind)
[ "Meta", "-", "function", "calling", "all", "the", "above", "bottlenecks", "with", "hparams", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/discretization.py#L1440-L1476
[ "def", "parametrized_bottleneck", "(", "x", ",", "hparams", ")", ":", "if", "hparams", ".", "bottleneck_kind", "==", "\"tanh_discrete\"", ":", "d", ",", "_", "=", "tanh_discrete_bottleneck", "(", "x", ",", "hparams", ".", "bottleneck_bits", ",", "hparams", "."...
272500b6efe353aeb638d2745ed56e519462ca31
train
parametrized_unbottleneck
Meta-function calling all the above un-bottlenecks with hparams.
tensor2tensor/layers/discretization.py
def parametrized_unbottleneck(x, hidden_size, hparams): """Meta-function calling all the above un-bottlenecks with hparams.""" if hparams.bottleneck_kind == "tanh_discrete": return tanh_discrete_unbottleneck(x, hidden_size) if hparams.bottleneck_kind == "isemhash": return isemhash_unbottleneck(x, hidden_size, hparams.isemhash_filter_size_multiplier) if hparams.bottleneck_kind in ["vq", "em", "gumbel_softmax"]: return vq_discrete_unbottleneck(x, hidden_size) raise ValueError( "Unsupported hparams.bottleneck_kind %s" % hparams.bottleneck_kind)
def parametrized_unbottleneck(x, hidden_size, hparams): """Meta-function calling all the above un-bottlenecks with hparams.""" if hparams.bottleneck_kind == "tanh_discrete": return tanh_discrete_unbottleneck(x, hidden_size) if hparams.bottleneck_kind == "isemhash": return isemhash_unbottleneck(x, hidden_size, hparams.isemhash_filter_size_multiplier) if hparams.bottleneck_kind in ["vq", "em", "gumbel_softmax"]: return vq_discrete_unbottleneck(x, hidden_size) raise ValueError( "Unsupported hparams.bottleneck_kind %s" % hparams.bottleneck_kind)
[ "Meta", "-", "function", "calling", "all", "the", "above", "un", "-", "bottlenecks", "with", "hparams", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/discretization.py#L1479-L1489
[ "def", "parametrized_unbottleneck", "(", "x", ",", "hidden_size", ",", "hparams", ")", ":", "if", "hparams", ".", "bottleneck_kind", "==", "\"tanh_discrete\"", ":", "return", "tanh_discrete_unbottleneck", "(", "x", ",", "hidden_size", ")", "if", "hparams", ".", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
iaf_hparams
Create hyperpameters for inverse autoregressive flows. Args: hidden_size: Width of attention layers and neural network output layer. filter_size: Hidden layer width for neural network. Returns: hparams: Hyperpameters with basic presets for inverse autoregressive flows.
tensor2tensor/layers/discretization.py
def iaf_hparams(hidden_size=512, filter_size=4096): """Create hyperpameters for inverse autoregressive flows. Args: hidden_size: Width of attention layers and neural network output layer. filter_size: Hidden layer width for neural network. Returns: hparams: Hyperpameters with basic presets for inverse autoregressive flows. """ hparams = common_hparams.basic_params1() # Attention hyperparameters. hparams.hidden_size = hidden_size hparams.add_hparam("attention_key_channels", None) hparams.add_hparam("attention_value_channels", None) hparams.add_hparam("num_heads", 4) hparams.add_hparam("attention_dropout", 0.1) hparams.add_hparam("shared_rel", False) hparams.add_hparam("block_width", 1) hparams.add_hparam("block_length", 1) hparams.add_hparam("q_filter_width", 1) hparams.add_hparam("kv_filter_width", 1) # Preprocessing and postprocesing hyperparameters. hparams.layer_preprocess_sequence = "n" hparams.layer_prepostprocess_dropout = 0.1 hparams.norm_type = "layer" hparams.norm_epsilon = 1e-06 hparams.layer_prepostprocess_dropout_broadcast_dims = "" hparams.layer_postprocess_sequence = "da" # Feedforward neural network hyperparameters. hparams.add_hparam("filter_size", filter_size) hparams.add_hparam("ffn_layer", "conv_hidden_relu") hparams.add_hparam("relu_dropout", 0.1) return hparams
def iaf_hparams(hidden_size=512, filter_size=4096): """Create hyperpameters for inverse autoregressive flows. Args: hidden_size: Width of attention layers and neural network output layer. filter_size: Hidden layer width for neural network. Returns: hparams: Hyperpameters with basic presets for inverse autoregressive flows. """ hparams = common_hparams.basic_params1() # Attention hyperparameters. hparams.hidden_size = hidden_size hparams.add_hparam("attention_key_channels", None) hparams.add_hparam("attention_value_channels", None) hparams.add_hparam("num_heads", 4) hparams.add_hparam("attention_dropout", 0.1) hparams.add_hparam("shared_rel", False) hparams.add_hparam("block_width", 1) hparams.add_hparam("block_length", 1) hparams.add_hparam("q_filter_width", 1) hparams.add_hparam("kv_filter_width", 1) # Preprocessing and postprocesing hyperparameters. hparams.layer_preprocess_sequence = "n" hparams.layer_prepostprocess_dropout = 0.1 hparams.norm_type = "layer" hparams.norm_epsilon = 1e-06 hparams.layer_prepostprocess_dropout_broadcast_dims = "" hparams.layer_postprocess_sequence = "da" # Feedforward neural network hyperparameters. hparams.add_hparam("filter_size", filter_size) hparams.add_hparam("ffn_layer", "conv_hidden_relu") hparams.add_hparam("relu_dropout", 0.1) return hparams
[ "Create", "hyperpameters", "for", "inverse", "autoregressive", "flows", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/discretization.py#L1492-L1528
[ "def", "iaf_hparams", "(", "hidden_size", "=", "512", ",", "filter_size", "=", "4096", ")", ":", "hparams", "=", "common_hparams", ".", "basic_params1", "(", ")", "# Attention hyperparameters.", "hparams", ".", "hidden_size", "=", "hidden_size", "hparams", ".", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
_original_vocab
Returns a set containing the original vocabulary. This is important for comparing with published results. Args: tmp_dir: directory containing dataset. Returns: a set of strings
tensor2tensor/data_generators/lm1b.py
def _original_vocab(tmp_dir): """Returns a set containing the original vocabulary. This is important for comparing with published results. Args: tmp_dir: directory containing dataset. Returns: a set of strings """ vocab_url = ("http://download.tensorflow.org/models/LM_LSTM_CNN/" "vocab-2016-09-10.txt") vocab_filename = os.path.basename(vocab_url + ".en") vocab_filepath = os.path.join(tmp_dir, vocab_filename) if not os.path.exists(vocab_filepath): generator_utils.maybe_download(tmp_dir, vocab_filename, vocab_url) return set([ text_encoder.native_to_unicode(l.strip()) for l in tf.gfile.Open(vocab_filepath) ])
def _original_vocab(tmp_dir): """Returns a set containing the original vocabulary. This is important for comparing with published results. Args: tmp_dir: directory containing dataset. Returns: a set of strings """ vocab_url = ("http://download.tensorflow.org/models/LM_LSTM_CNN/" "vocab-2016-09-10.txt") vocab_filename = os.path.basename(vocab_url + ".en") vocab_filepath = os.path.join(tmp_dir, vocab_filename) if not os.path.exists(vocab_filepath): generator_utils.maybe_download(tmp_dir, vocab_filename, vocab_url) return set([ text_encoder.native_to_unicode(l.strip()) for l in tf.gfile.Open(vocab_filepath) ])
[ "Returns", "a", "set", "containing", "the", "original", "vocabulary", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/lm1b.py#L35-L55
[ "def", "_original_vocab", "(", "tmp_dir", ")", ":", "vocab_url", "=", "(", "\"http://download.tensorflow.org/models/LM_LSTM_CNN/\"", "\"vocab-2016-09-10.txt\"", ")", "vocab_filename", "=", "os", ".", "path", ".", "basename", "(", "vocab_url", "+", "\".en\"", ")", "voc...
272500b6efe353aeb638d2745ed56e519462ca31