python_code
stringlengths
0
1.02M
repo_name
stringlengths
9
48
file_path
stringlengths
5
114
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================= """Tests for EAOptimizer.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import portpicker from tensorflow.contrib.opt.python.training import agn_optimizer from tensorflow.python.framework import constant_op from tensorflow.python.framework import ops from tensorflow.python.ops import init_ops from tensorflow.python.ops import partitioned_variables from tensorflow.python.ops import variable_scope from tensorflow.python.ops import variables from tensorflow.python.platform import test from tensorflow.python.training import adam from tensorflow.python.training import device_setter from tensorflow.python.training import server_lib from tensorflow.python.training import training from tensorflow.python.training import training_util def create_local_cluster(num_workers, num_ps, protocol="grpc"): """Create local GRPC servers and return them.""" worker_ports = [portpicker.pick_unused_port() for _ in range(num_workers)] ps_ports = [portpicker.pick_unused_port() for _ in range(num_ps)] cluster_dict = { "worker": ["localhost:%s" % port for port in worker_ports], "ps": ["localhost:%s" % port for port in ps_ports] } cs = server_lib.ClusterSpec(cluster_dict) workers = [ server_lib.Server( cs, job_name="worker", protocol=protocol, task_index=ix, start=True) for ix in range(num_workers) ] ps_servers = [ server_lib.Server( cs, job_name="ps", protocol=protocol, task_index=ix, start=True) for ix in range(num_ps) ] return cluster_dict, workers, ps_servers # Creates the workers and return their sessions, graphs, train_ops. # Cheif worker will update at last def _get_workers(num_workers, period, workers, num_ps=1): sessions = [] graphs = [] train_ops = [] for worker_id in range(num_workers): graph = ops.Graph() is_chief = (worker_id == 0) with graph.as_default(): worker_device = "/job:worker/task:%d/cpu:0" % (worker_id) ps_device = device_setter.replica_device_setter( worker_device=worker_device, ps_device="/job:ps/task:0/cpu:0", ps_tasks=1) agn_getter = agn_optimizer.AGNCustomGetter(worker_device=worker_device) with variable_scope.variable_scope( "", custom_getter=agn_getter), ops.device(ps_device): global_step = training_util.get_or_create_global_step() var_0 = variable_scope.get_variable(initializer=0.0, name="v0") var_1 = variable_scope.get_variable(initializer=0.5, name="v1") if num_ps > 1: with variable_scope.variable_scope( "", partitioner=partitioned_variables.fixed_size_partitioner( num_ps, axis=0), custom_getter=agn_getter), ops.device(ps_device): partition_var = variable_scope.get_variable( "partition_var", shape=[2, 4], initializer=init_ops.zeros_initializer) part_0 = list(partition_var)[0] part_1 = list(partition_var)[1] with ops.device("/job:worker/task:" + str(worker_id)): grads_0 = constant_op.constant(-1.0) grads_1 = constant_op.constant(-1.0) grads_part_0 = constant_op.constant([[-1., -1., -1., -1.]]) grads_part_1 = constant_op.constant([[-1., -1., -1., -1.]]) optimizer = \ adam.AdamOptimizer(learning_rate=0.1, beta1=0.0, beta2=0.0) opt = agn_optimizer.AGNOptimizer( optimizer, num_worker=num_workers, communication_period=period, custom_getter=agn_getter) if num_ps == 1: train_op = [ opt.apply_gradients(([grads_0, var_0], [grads_1, var_1]), global_step) ] else: train_op = [ opt.apply_gradients( ([grads_0, var_0], [grads_1, var_1], [grads_part_0, part_0], [grads_part_1, part_1]), global_step) ] hook = opt.make_session_run_hook(is_chief, worker_id) # Creates MonitoredSession sess = training.MonitoredTrainingSession( workers[worker_id].target, hooks=[hook]) sessions.append(sess) graphs.append(graph) train_ops.append(train_op) return sessions, graphs, train_ops class AGNOptimizerTest(test.TestCase): def _run(self, train_op, sess): sess.run(train_op) def test1Workers2Period(self): num_workers = 1 communication_period = 4 num_ps = 1 _, workers, _ = create_local_cluster(num_workers=num_workers, num_ps=num_ps) sessions, graphs, train_ops = _get_workers(num_workers, communication_period, workers) var_0 = graphs[0].get_tensor_by_name("v0:0") var_1 = graphs[0].get_tensor_by_name("v1:0") global_step = training_util.get_global_step(graphs[0]) var_0_g = graphs[0].get_tensor_by_name( agn_optimizer.GLOBAL_VARIABLE_NAME + "/v0:0") var_1_g = graphs[0].get_tensor_by_name( agn_optimizer.GLOBAL_VARIABLE_NAME + "/v1:0") # verify adam/beta variables not in global collection with graphs[0].as_default(): for ele in variables.global_variables(): self.assertTrue(ele.op.name.find("beta") < 0) if ele.op.name.find("global_center_variable") < 0: self.assertTrue(ele.op.name.find("Adam") < 0) # Verify the initialized value. self.assertAllEqual(0.0, sessions[0].run(var_0)) self.assertAllEqual(0.5, sessions[0].run(var_1)) self.assertAllEqual(0.0, sessions[0].run(var_0_g)) self.assertAllEqual(0.5, sessions[0].run(var_1_g)) self.assertAllEqual(0, sessions[0].run(global_step)) # step 0 sessions[0].run(train_ops[0]) self.assertNear(0.1, sessions[0].run(var_0), 1e-6) self.assertNear(0.6, sessions[0].run(var_1), 1e-6) self.assertAllEqual(0.0, sessions[0].run(var_0_g)) self.assertAllEqual(0.5, sessions[0].run(var_1_g)) self.assertAllEqual(0, sessions[0].run(global_step)) # 2 & 3 sessions[0].run(train_ops[0]) sessions[0].run(train_ops[0]) self.assertNear(0.3, sessions[0].run(var_0), 1e-6) self.assertNear(0.8, sessions[0].run(var_1), 1e-6) # 4 sessions[0].run(train_ops[0]) # pull self.assertAllEqual(sessions[0].run(var_0), sessions[0].run(var_0_g)) self.assertAllEqual(sessions[0].run(var_1), sessions[0].run(var_1_g)) self.assertNear(0.1, sessions[0].run(var_0), 1e-6) self.assertNear(0.6, sessions[0].run(var_1), 1e-6) sessions[0].run(train_ops[0]) sessions[0].run(train_ops[0]) sessions[0].run(train_ops[0]) sessions[0].run(train_ops[0]) self.assertAllEqual(sessions[0].run(var_0), sessions[0].run(var_0_g)) self.assertAllEqual(sessions[0].run(var_1), sessions[0].run(var_1_g)) self.assertNear(0.2, sessions[0].run(var_0), 1e-6) self.assertNear(0.7, sessions[0].run(var_1), 1e-6) def test2Worker1Period(self): num_workers = 2 communication_period = 1 num_ps = 2 _, workers, _ = create_local_cluster(num_workers=num_workers, num_ps=num_ps) sessions, graphs, train_ops = _get_workers( num_workers, communication_period, workers, num_ps=2) var_0 = graphs[0].get_tensor_by_name("v0:0") var_1 = graphs[0].get_tensor_by_name("v1:0") var_0_1 = graphs[1].get_tensor_by_name("v0:0") var_1_1 = graphs[1].get_tensor_by_name("v1:0") var_0_g = graphs[0].get_tensor_by_name( agn_optimizer.GLOBAL_VARIABLE_NAME + "/v0:0") var_1_g = graphs[0].get_tensor_by_name( agn_optimizer.GLOBAL_VARIABLE_NAME + "/v1:0") part_0_g = graphs[0].get_tensor_by_name( agn_optimizer.GLOBAL_VARIABLE_NAME + "/partition_var/part_0:0") part_1_g = graphs[0].get_tensor_by_name( agn_optimizer.GLOBAL_VARIABLE_NAME + "/partition_var/part_1:0") # Verify the initialized value. self.assertAllEqual(0.0, sessions[0].run(var_0)) self.assertAllEqual(0.5, sessions[0].run(var_1)) self.assertAllEqual(0.0, sessions[1].run(var_0_1)) self.assertAllEqual(0.5, sessions[1].run(var_1_1)) self.assertAllEqual(0.0, sessions[0].run(var_0_g)) self.assertAllEqual(0.5, sessions[0].run(var_1_g)) # verify each step sessions[0].run(train_ops[0]) self.assertNear(0.1, sessions[0].run(var_0_g), 1e-6) self.assertNDArrayNear([0.1, 0.1, 0.1, 0.1], sessions[0].run(part_0_g), 1e-6) self.assertNDArrayNear([0.1, 0.1, 0.1, 0.1], sessions[0].run(part_1_g), 1e-6) sessions[1].run(train_ops[1]) self.assertNear(0.2, sessions[0].run(var_0_g), 1e-6) self.assertNDArrayNear([0.2, 0.2, 0.2, 0.2], sessions[0].run(part_0_g), 1e-6) self.assertNDArrayNear([0.2, 0.2, 0.2, 0.2], sessions[0].run(part_1_g), 1e-6) sessions[0].run(train_ops[0]) sessions[1].run(train_ops[1]) sessions[0].run(train_ops[0]) sessions[1].run(train_ops[1]) self.assertNear(0.6, sessions[0].run(var_0_g), 1e-6) self.assertNDArrayNear([0.6, 0.6, 0.6, 0.6], sessions[0].run(part_0_g), 1e-6) self.assertNDArrayNear([0.6, 0.6, 0.6, 0.6], sessions[0].run(part_1_g), 1e-6) def testAGNCustomGetter(self): cluster_spec = server_lib.ClusterSpec({ "ps": ["ps0:2222", "ps1:2222"], "worker": ["worker0:2222", "worker1:2222", "worker2:2222"] }) agn_getter = agn_optimizer.AGNCustomGetter( worker_device="/job:worker/task:0") with ops.device( device_setter.replica_device_setter(cluster=cluster_spec, worker_device="/job:worker/task:0", ps_device="/job:ps")), \ variable_scope.variable_scope("", custom_getter=agn_getter): v = variable_scope.get_variable(initializer=[1, 2], name="v") w = variable_scope.get_variable(initializer=[2, 1], name="w") v_g, w_g = agn_getter._global_map[v], agn_getter._global_map[w] self.assertDeviceEqual("/job:worker/task:0", v.device) self.assertDeviceEqual("job:ps/task:0", v_g.device) self.assertDeviceEqual("/job:worker/task:0", w.device) self.assertDeviceEqual("job:ps/task:1", w_g.device) if __name__ == "__main__": test.main()
tensorflow-master
tensorflow/contrib/opt/python/training/agn_optimizer_test.py
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """The Shampoo Optimizer. Variant of Adagrad using one preconditioner matrix per variable dimension. For details, see https://arxiv.org/abs/1802.09568 """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.contrib.opt.python.training import matrix_functions from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import linalg_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import state_ops from tensorflow.python.platform import tf_logging from tensorflow.python.training import optimizer def GetParam(var, timestep): if callable(var): return var(timestep) else: return var class ShampooOptimizer(optimizer.Optimizer): """The Shampoo Optimizer Variant of Adagrad using one preconditioner matrix per variable dimension. For details, see https://arxiv.org/abs/1802.09568 gbar is time-weighted accumulated gradient: gbar[t] = gbar_decay[t] * gbar[t-1] + gbar_weight[t] * g[t] mat_gbar is time-weighted accumulated gradient square: mat_gbar_j[t] = mat_gbar_decay[t] * mat_gbar_j[t-1] + mat_gbar_weight[t] * gg_j[t] where if g[t] = g_abcd then gg_a[t] = g_abcd g_a'bcd (Einstein notation) Update rule: w[t+1] = w[t] - learning_rate[t] * Prod_j mat_gbar_j[t]^(-alpha/n) gbar[t] Again, mat_gbar_j[t]^(-alpha) gbar[t] is a tensor contraction along the j'th dimension of gbar[t] with the first dimension of mat_gbar_j[t]^(-alpha/n), where alpha is a hyperparameter, and n = rank of the variable. Prod_j represents doing this contraction for all j in 0..n-1. Typically learning_rate is constant, but could be time dependent by passing a lambda function that depends on step. """ def __init__(self, global_step=0, max_matrix_size=768, gbar_decay=0.0, gbar_weight=1.0, mat_gbar_decay=1.0, mat_gbar_weight=1.0, learning_rate=1.0, svd_interval=1, precond_update_interval=1, epsilon=1e-4, alpha=0.5, use_iterative_root=False, use_locking=False, name="Shampoo"): """Default values of the various hyper-parameters. gbar_decay, gbar_weight etc. can be a float or a time varying parameter. For time-varying parameters use e.g. "lambda T: T / (T + 1.0)" where the expression in the lambda is a tensorflow expression Args: global_step: tensorflow variable indicating the step. max_matrix_size: We do not perform SVD for matrices larger than this. gbar_decay: gbar_weight: Used to update gbar: gbar[t] = gbar_decay[t] * gbar[t-1] + gbar_weight[t] * g[t] mat_gbar_decay: mat_gbar_weight: Used to update mat_gbar: mat_gbar_j[t] = mat_gbar_decay[t] * mat_gbar_j[t-1] + mat_gbar_weight[t] * gg_j[t] learning_rate: Similar to SGD svd_interval: We should do SVD after this many steps. Default = 1, i.e. every step. Usually 20 leads to no loss of accuracy, and 50 or 100 is also OK. May also want more often early, and less often later - set in caller as for example: "svd_interval = lambda(T): tf.cond( T < 2000, lambda: 20.0, lambda: 1000.0)" precond_update_interval: We should update the preconditioners after this many steps. Default = 1. Usually less than svd_interval. epsilon: epsilon * I_n is added to each mat_gbar_j for stability for non-diagonal version of shampoo. alpha: total power of the preconditioners. use_iterative_root: should the optimizer use SVD (faster) or the iterative root method (for TPU) for finding the roots of PSD matrices. use_locking: name: name of optimizer. """ super(ShampooOptimizer, self).__init__(use_locking, name) self._global_step = math_ops.cast(global_step, dtypes.float32) self._max_matrix_size = max_matrix_size self._gbar_decay = gbar_decay self._gbar_weight = gbar_weight self._mat_gbar_decay = mat_gbar_decay self._mat_gbar_weight = mat_gbar_weight self._learning_rate = learning_rate self._svd_interval = svd_interval self._precond_update_interval = precond_update_interval self._epsilon = epsilon self._alpha = alpha self._use_iterative_root = use_iterative_root self._name = name def _create_slots(self, var_list): for v in var_list: with ops.colocate_with(v): _ = self._zeros_slot(v, "gbar", self._name) shape = np.array(v.get_shape()) for i, d in enumerate(shape): d_tensor = ops.convert_to_tensor(d) if d <= self._max_matrix_size: mat_g_init = array_ops.zeros_like(linalg_ops.eye(d_tensor)) if self._svd_interval > 1: _ = self._get_or_make_slot(v, linalg_ops.eye(d_tensor), "H_" + str(i), self._name) else: mat_g_init = array_ops.zeros([d_tensor]) _ = self._get_or_make_slot(v, mat_g_init, "Gbar_" + str(i), self._name) def _resource_apply_dense(self, grad, var): return self._apply_dense(grad, var) def _apply_dense(self, grad, var): return self._apply_gradient(grad, var) def _resource_apply_sparse(self, grad_values, var, grad_indices): return self._apply_sparse_shared(grad_values, grad_indices, var) def _apply_sparse(self, grad, var): return self._apply_sparse_shared(grad.values, grad.indices, var) def _apply_sparse_shared(self, grad_values, grad_indices, var): if var.get_shape()[0] <= self._max_matrix_size or self._gbar_decay != 0.0: # The dimension is small enough, we can make the variable dense and # do a dense update dense_grad = array_ops.scatter_nd( array_ops.expand_dims(grad_indices, axis=1), grad_values, array_ops.shape(var, out_type=grad_indices.dtype)) return self._apply_gradient(dense_grad, var) return self._apply_gradient(grad_values, var, grad_indices) def _weighted_average(self, var, weight, weight_t, rest): """Computes exponential weighted average: var = weight_t * var + rest. Important to ensure that var does not occur in rest, otherwise we can get race conditions in a distributed setting. Args: var: variable to be updated weight: parameter to be checked. If it is a constant, we can optimize. weight_t: current value of parameter, used for weighting rest: the remaining tensor to be added Returns: updated variable. """ if weight == 0.0: return rest # no need to update var, we will never use it. if weight == 1.0: # common case return state_ops.assign_add(var, rest) # The op below can cause race conditions in a distributed setting, # since computing weight_t * var + rest can take some time, during # which var may be set by another worker. To prevent this, it should # be implemented as a C++ op. return var.assign_add((weight_t - 1) * var + rest) def _update_mat_g(self, mat_g, grad, axes, mat_gbar_decay, mat_gbar_weight, i): """Updates the cumulative outer products of the gradients. Args: mat_g: the matrix to be updated grad: the gradient of the variable axes: a list of k-1 integers 0 to k-1, except i mat_gbar_decay: constant for weighted average: mat_g = mat_g * decay + grad * weight mat_gbar_weight: constant for weighted average i: index of dimension to be updated. Returns: updated mat_g = mat_g * mat_gbar_decay + grad_outer * mat_gbar_weight In Einstein notation if i = 0: grad_outer_aa'= g_abcd g_a'bcd thus grad_outer is a matrix d_i x d_i, where d_i is the size of the i'th dimension of g. Alternate view: If mat_i(grad) is the flattening of grad to a d_i x (d_1d_2...d_{i-1}d_{i+1}...d_k) matrix, then grad_outer = mat_i(grad) mat_i(grad).transpose """ grad_outer = math_ops.tensordot(grad, grad, axes=(axes, axes), name="grad_outer_" + str(i)) return self._weighted_average(mat_g, self._mat_gbar_decay, mat_gbar_decay, mat_gbar_weight * grad_outer) def _compute_power_svd(self, var, mat_g, mat_g_size, alpha, mat_h_slot_name): """Computes mat_h = mat_g^alpha using svd. mat_g is a symmetric PSD matrix. Args: var: the variable we are updating. mat_g: the symmetric PSD matrix whose power it to be computed mat_g_size: size of mat_g alpha: a real number mat_h_slot_name: name of slot to store the power, if needed. Returns: mat_h = mat_g^alpha Stores mat_h in the appropriate slot, if it exists. Note that mat_g is PSD. So we could use linalg_ops.self_adjoint_eig. """ if mat_g_size == 1: mat_h = math_ops.pow(mat_g + self._epsilon, alpha) else: damping = self._epsilon * linalg_ops.eye( math_ops.cast(mat_g_size, dtypes.int32)) diag_d, mat_u, mat_v = linalg_ops.svd(mat_g + damping, full_matrices=True) mat_h = math_ops.matmul( mat_v * math_ops.pow(math_ops.maximum(diag_d, self._epsilon), alpha), array_ops.transpose(mat_u)) if mat_h_slot_name is not None: return state_ops.assign(self.get_slot(var, mat_h_slot_name), mat_h) return mat_h def _compute_power_iter(self, var, mat_g, mat_g_size, alpha, mat_h_slot_name, iter_count=100, epsilon=1e-6): """Computes mat_g^alpha, where alpha = -1/p, p a positive integer.""" mat_g_sqrt = matrix_functions.matrix_square_root(mat_g, mat_g_size, iter_count, self._epsilon) mat_h = matrix_functions.matrix_inverse_pth_root( mat_g_sqrt, mat_g_size, 2 * alpha, iter_count, epsilon, ridge_epsilon=0.0) if mat_h_slot_name is not None: return state_ops.assign(self.get_slot(var, mat_h_slot_name), mat_h) return mat_h def _compute_power(self, var, mat_g, mat_g_size, alpha, mat_h_slot_name=None): """Just a switch between the iterative power vs svd.""" with ops.name_scope("matrix_iterative_power"): if self._use_iterative_root: return self._compute_power_iter(var, mat_g, mat_g_size, alpha, mat_h_slot_name) else: return self._compute_power_svd(var, mat_g, mat_g_size, alpha, mat_h_slot_name) def _apply_gradient(self, grad, var, indices=None): """The main function to update a variable. Args: grad: A Tensor containing gradient to apply. var: A Tensor containing the variable to update. indices: An array of integers, for sparse update. Returns: Updated variable var = var - learning_rate * preconditioner * grad If the gradient is dense, var and grad have the same shape. If the update is sparse, then the first dimension of the gradient and var may differ, others are all the same. In this case the indices array provides the set of indices of the variable which are to be updated with each row of the gradient. """ global_step = self._global_step + 1 # Update accumulated weighted average of gradients gbar = self.get_slot(var, "gbar") gbar_decay_t = GetParam(self._gbar_decay, global_step) gbar_weight_t = GetParam(self._gbar_weight, global_step) if indices is not None: # Note - the sparse update is not easily implemented, since the # algorithm needs all indices of gbar to be updated # if mat_gbar_decay != 1 or mat_gbar_decay != 0. # One way to make mat_gbar_decay = 1 is by rescaling. # If we want the update: # G_{t+1} = a_{t+1} G_t + b_{t+1} w_t # define: # r_{t+1} = a_{t+1} * r_t # h_t = G_t / r_t # Then: # h_{t+1} = h_t + (b_{t+1} / r_{t+1}) * w_t # So we get the mat_gbar_decay = 1 as desired. # We can implement this in a future version as needed. # However we still need gbar_decay = 0, otherwise all indices # of the variable will need to be updated. if self._gbar_decay != 0.0: tf_logging.warning("Not applying momentum for variable: %s" % var.name) gbar_updated = grad else: gbar_updated = self._weighted_average(gbar, self._gbar_decay, gbar_decay_t, gbar_weight_t * grad) # Update the preconditioners and compute the preconditioned gradient shape = var.get_shape() mat_g_list = [] for i in range(len(shape)): mat_g_list.append(self.get_slot(var, "Gbar_" + str(i))) mat_gbar_decay_t = GetParam(self._mat_gbar_decay, global_step) mat_gbar_weight_t = GetParam(self._mat_gbar_weight, global_step) preconditioned_grad = gbar_updated v_rank = len(mat_g_list) neg_alpha = - GetParam(self._alpha, global_step) / v_rank svd_interval = GetParam(self._svd_interval, global_step) precond_update_interval = GetParam(self._precond_update_interval, global_step) for i, mat_g in enumerate(mat_g_list): # axes is the list of indices to reduce - everything but the current i. axes = list(range(i)) + list(range(i+1, v_rank)) if shape[i] <= self._max_matrix_size: # If the tensor size is sufficiently small perform full Shampoo update # Note if precond_update_interval > 1 and mat_gbar_decay_t != 1, this # is not strictly correct. However we will use it for now, and # fix if needed. (G_1 = aG + bg ==> G_n = a^n G + (1+a+..+a^{n-1})bg) # pylint: disable=g-long-lambda,cell-var-from-loop mat_g_updated = control_flow_ops.cond( math_ops.mod(global_step, precond_update_interval) < 1, lambda: self._update_mat_g( mat_g, grad, axes, mat_gbar_decay_t, mat_gbar_weight_t * precond_update_interval, i), lambda: mat_g) mat_g_updated = mat_g_updated / float(shape[i].value) if self._svd_interval == 1: mat_h = self._compute_power(var, mat_g_updated, shape[i], neg_alpha) else: mat_h = control_flow_ops.cond( math_ops.mod(global_step, svd_interval) < 1, lambda: self._compute_power(var, mat_g_updated, shape[i], neg_alpha, "H_" + str(i)), lambda: self.get_slot(var, "H_" + str(i))) # mat_h is a square matrix of size d_i x d_i # preconditioned_grad is a d_i x ... x d_n x d_0 x ... d_{i-1} tensor # After contraction with a d_i x d_i tensor # it becomes a d_{i+1} x ... x d_n x d_0 x ... d_i tensor # (the first dimension is contracted out, and the second dimension of # mat_h is appended). After going through all the indices, it becomes # a d_0 x ... x d_n tensor again. preconditioned_grad = math_ops.tensordot(preconditioned_grad, mat_h, axes=([0], [0]), name="precond_" + str(i)) else: # Tensor size is too large -- perform diagonal Shampoo update # Only normalize non-vector cases. if axes: normalizer = 1.0 if indices is not None else float(shape[i].value) grad_outer = math_ops.reduce_sum(grad * grad, axis=axes) / normalizer else: grad_outer = grad * grad if i == 0 and indices is not None: assert self._mat_gbar_decay == 1.0 mat_g_updated = state_ops.scatter_add(mat_g, indices, mat_gbar_weight_t * grad_outer) mat_g_updated_slice = array_ops.gather(mat_g_updated, indices) mat_h = array_ops.where( math_ops.greater(mat_g_updated_slice, 0), math_ops.pow(mat_g_updated_slice, neg_alpha), array_ops.zeros_like(mat_g_updated_slice)) else: mat_g_updated = self._weighted_average(mat_g, self._mat_gbar_decay, mat_gbar_decay_t, mat_gbar_weight_t * grad_outer) mat_h = array_ops.where( math_ops.greater(mat_g_updated, 0), math_ops.pow(mat_g_updated, neg_alpha), array_ops.zeros_like(mat_g_updated)) # Need to do the transpose to ensure that the tensor becomes # a d_{i+1} x ... x d_n x d_0 x ... d_i tensor as described above. preconditioned_grad = array_ops.transpose( preconditioned_grad, perm=list(range(1, v_rank)) + [0]) * mat_h # Update the variable based on the Shampoo update learning_rate_t = GetParam(self._learning_rate, global_step) if indices is not None: var_updated = state_ops.scatter_add( var, indices, -learning_rate_t * preconditioned_grad) else: var_updated = state_ops.assign_sub(var, learning_rate_t * preconditioned_grad) return var_updated
tensorflow-master
tensorflow/contrib/opt/python/training/shampoo.py
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Nadam for TensorFlow.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import state_ops from tensorflow.python.training import adam from tensorflow.python.training import training_ops class NadamOptimizer(adam.AdamOptimizer): """Optimizer that implements the Nadam algorithm. See [Dozat, T., 2015](http://cs229.stanford.edu/proj2015/054_report.pdf). """ def _apply_dense(self, grad, var): m = self.get_slot(var, "m") v = self.get_slot(var, "v") beta1_power, beta2_power = self._get_beta_accumulators() return training_ops.apply_adam( var, m, v, math_ops.cast(beta1_power, var.dtype.base_dtype), math_ops.cast(beta2_power, var.dtype.base_dtype), math_ops.cast(self._lr_t, var.dtype.base_dtype), math_ops.cast(self._beta1_t, var.dtype.base_dtype), math_ops.cast(self._beta2_t, var.dtype.base_dtype), math_ops.cast(self._epsilon_t, var.dtype.base_dtype), grad, use_locking=self._use_locking, use_nesterov=True).op def _resource_apply_dense(self, grad, var): m = self.get_slot(var, "m") v = self.get_slot(var, "v") beta1_power, beta2_power = self._get_beta_accumulators() return training_ops.resource_apply_adam( var.handle, m.handle, v.handle, math_ops.cast(beta1_power, grad.dtype.base_dtype), math_ops.cast(beta2_power, grad.dtype.base_dtype), math_ops.cast(self._lr_t, grad.dtype.base_dtype), math_ops.cast(self._beta1_t, grad.dtype.base_dtype), math_ops.cast(self._beta2_t, grad.dtype.base_dtype), math_ops.cast(self._epsilon_t, grad.dtype.base_dtype), grad, use_locking=self._use_locking, use_nesterov=True) def _apply_sparse_shared(self, grad, var, indices, scatter_add): beta1_power, beta2_power = self._get_beta_accumulators() beta1_power = math_ops.cast(beta1_power, var.dtype.base_dtype) beta2_power = math_ops.cast(beta2_power, var.dtype.base_dtype) lr_t = math_ops.cast(self._lr_t, var.dtype.base_dtype) beta1_t = math_ops.cast(self._beta1_t, var.dtype.base_dtype) beta2_t = math_ops.cast(self._beta2_t, var.dtype.base_dtype) epsilon_t = math_ops.cast(self._epsilon_t, var.dtype.base_dtype) lr = (lr_t * math_ops.sqrt(1 - beta2_power) / (1 - beta1_power)) # m_t = beta1 * m + (1 - beta1) * g_t m = self.get_slot(var, "m") m_scaled_g_values = grad * (1 - beta1_t) m_t = state_ops.assign(m, m * beta1_t, use_locking=self._use_locking) with ops.control_dependencies([m_t]): m_t = scatter_add(m, indices, m_scaled_g_values) # m_bar = (1 - beta1) * g_t + beta1 * m_t m_bar = m_scaled_g_values + beta1_t * array_ops.gather(m_t, indices) # v_t = beta2 * v + (1 - beta2) * (g_t * g_t) v = self.get_slot(var, "v") v_scaled_g_values = (grad * grad) * (1 - beta2_t) v_t = state_ops.assign(v, v * beta2_t, use_locking=self._use_locking) with ops.control_dependencies([v_t]): v_t = scatter_add(v, indices, v_scaled_g_values) v_t_slice = array_ops.gather(v_t, indices) v_sqrt = math_ops.sqrt(v_t_slice) var_update = scatter_add(var, indices, -lr * m_bar / (v_sqrt + epsilon_t)) return control_flow_ops.group(*[var_update, m_bar, v_t])
tensorflow-master
tensorflow/contrib/opt/python/training/nadam_optimizer.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Moving average optimizer.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import six from tensorflow.python.framework import ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import variables from tensorflow.python.training import moving_averages from tensorflow.python.training import optimizer from tensorflow.python.training import saver from tensorflow.python.training.saving import saveable_object_util class MovingAverageOptimizer(optimizer.Optimizer): """Optimizer that computes a moving average of the variables. Empirically it has been found that using the moving average of the trained parameters of a deep network is better than using its trained parameters directly. This optimizer allows you to compute this moving average and swap the variables at save time so that any code outside of the training loop will use by default the averaged values instead of the original ones. Example of usage: ```python // Encapsulate your favorite optimizer (here the momentum one) // inside the MovingAverageOptimizer. opt = tf.compat.v1.train.MomentumOptimizer(learning_rate, FLAGS.momentum) opt = tf.contrib.opt.MovingAverageOptimizer(opt) // Then create your model and all its variables. model = build_model() // Add the training op that optimizes using opt. // This needs to be called before swapping_saver(). opt.minimize(cost, var_list) // Then create your saver like this: saver = opt.swapping_saver() // Pass it to your training loop. slim.learning.train( model, ... saver=saver) ``` Note that for evaluation, the normal saver should be used instead of swapping_saver(). """ def __init__(self, opt, average_decay=0.9999, num_updates=None, sequential_update=True): """Construct a new MovingAverageOptimizer. Args: opt: A tf.Optimizer that will be used to compute and apply gradients. average_decay: Float. Decay to use to maintain the moving averages of trained variables. See tf.train.ExponentialMovingAverage for details. num_updates: Optional count of number of updates applied to variables. See tf.train.ExponentialMovingAverage for details. sequential_update: Bool. If False, will compute the moving average at the same time as the model is updated, potentially doing benign data races. If True, will update the moving average after gradient updates. """ self._optimizer = opt self._ema = moving_averages.ExponentialMovingAverage( average_decay, num_updates=num_updates) self._swapped_variable_name_map = None self._sequential_update = sequential_update def compute_gradients(self, *args, **kwargs): return self._optimizer.compute_gradients(*args, **kwargs) def apply_gradients(self, grads_and_vars, global_step=None, name=None): train_op = self._optimizer.apply_gradients( grads_and_vars, global_step=global_step, name=name) var_list = [x[1] for x in grads_and_vars if x[0] is not None] self._swapped_variable_name_map = {} if self._sequential_update: with ops.control_dependencies([train_op]): ma_op = self._ema.apply(var_list) else: ma_op = self._ema.apply(var_list) for v in var_list: v_avg = self._ema.average(v) self._swapped_variable_name_map[v.op.name] = v_avg.op.name self._swapped_variable_name_map[v_avg.op.name] = v.op.name return control_flow_ops.group(train_op, ma_op, name='train_with_avg') def _find_swapped_variable(self, v_name_to_tensor, v_name, tensor): """Returns name of swapped variable for given tensor. Args: v_name_to_tensor: Mapping from variable names to tensors. v_name: name of the variable for which swapped variable should be returned tensor: Tensor which correspond to variable for which swapped variable should be returned. Returns: Tensor which correspond to swapped variable. Raises: ValueError: If swapped variable could not be found in v_name_to_tensor. """ swapped_v_name = self._swapped_variable_name_map.get(v_name, None) if swapped_v_name is None: return tensor else: if swapped_v_name in v_name_to_tensor: return v_name_to_tensor[swapped_v_name] else: raise ValueError( ('Variable to swap %s is not part of variables to save. ' 'This breaks MovingAverageOptimizer.') % swapped_v_name) def swapping_saver(self, var_list=None, name='swapping_saver', **kwargs): """Create a saver swapping moving averages and variables. You should use this saver during training. It will save the moving averages of the trained parameters under the original parameter names. For evaluations or inference you should use a regular saver and it will automatically use the moving averages for the trained variable. You must call this function after all variables have been created and after you have called Optimizer.minimize(). Args: var_list: List of variables to save, as per `Saver()`. If set to None, will save all the variables that have been created before this call. name: The name of the saver. **kwargs: Keyword arguments of `Saver()`. Returns: A `tf.compat.v1.train.Saver` object. Raises: RuntimeError: If apply_gradients or minimize has not been called before. ValueError: If var_list is provided and contains some variables but not their moving average counterpart. """ if self._swapped_variable_name_map is None: raise RuntimeError('Must call apply_gradients or minimize before ' 'creating the swapping_saver') if var_list is None: var_list = variables.global_variables() if not isinstance(var_list, dict): var_list = saveable_object_util.op_list_to_dict(var_list) v_name_to_tensor = {} for k, tensor_or_list in six.iteritems(var_list): # For each partitioned variable OpListToDict returns list of constituent # parts instead of single tensor. if (isinstance(tensor_or_list, list) or isinstance(tensor_or_list, variables.PartitionedVariable)): for tensor in tensor_or_list: v_name = tensor.op.name v_name_to_tensor[v_name] = tensor else: v_name_to_tensor[k] = tensor_or_list # Now swap variables and moving averages swapped_var_list = {} for k, tensor_or_list in six.iteritems(var_list): if isinstance(tensor_or_list, list): tensor_list_to_save = [] for tensor in tensor_or_list: v_name = tensor.op.name swapped_variable = self._find_swapped_variable(v_name_to_tensor, v_name, tensor) tensor_list_to_save.append(swapped_variable) swapped_var_list[k] = tensor_list_to_save else: swapped_var_list[k] = self._find_swapped_variable( v_name_to_tensor, k, tensor_or_list) # Build the swapping saver. return saver.Saver(swapped_var_list, name=name, **kwargs)
tensorflow-master
tensorflow/contrib/opt/python/training/moving_average_optimizer.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for MultitaskOptimizerWrapper.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import six from tensorflow.contrib.opt.python.training import multitask_optimizer_wrapper from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.ops import variables from tensorflow.python.platform import test from tensorflow.python.training import momentum class MultitaskOptimizerWrapperTest(test.TestCase): """Tests for the multitask optimizer wrapper. """ def testWrapper(self): with self.cached_session(): var0 = variables.Variable([1.0, 2.0], dtype=dtypes.float32) var1 = variables.Variable([3.0, 4.0], dtype=dtypes.float32) grads0 = constant_op.constant([0.1, 0.1], dtype=dtypes.float32) grads1 = constant_op.constant([0.01, 0.01], dtype=dtypes.float32) grads_allzero = constant_op.constant([0.0, 0.0], dtype=dtypes.float32) mom_opt_impl = momentum.MomentumOptimizer(learning_rate=2.0, momentum=0.9) mom_opt = multitask_optimizer_wrapper.MultitaskOptimizerWrapper( mom_opt_impl) mom_update = mom_opt.apply_gradients(zip([grads0, grads1], [var0, var1])) mom_update_partial = mom_opt.apply_gradients( zip([grads_allzero, grads1], [var0, var1])) mom_update_no_action = mom_opt.apply_gradients( zip([grads_allzero, grads_allzero], [var0, var1])) self.evaluate(variables.global_variables_initializer()) # Fetch params to validate initial values self.assertAllClose([1.0, 2.0], self.evaluate(var0)) self.assertAllClose([3.0, 4.0], self.evaluate(var1)) self.assertEqual(["momentum"], mom_opt.get_slot_names()) slot0 = mom_opt.get_slot(var0, "momentum") self.assertEquals(slot0.get_shape(), var0.get_shape()) slot1 = mom_opt.get_slot(var1, "momentum") self.assertEquals(slot1.get_shape(), var1.get_shape()) # Step 1: normal momentum update. self.evaluate(mom_update) # Check that the momentum accumulators have been updated. self.assertAllCloseAccordingToType( np.array([0.1, 0.1]), self.evaluate(slot0)) self.assertAllCloseAccordingToType( np.array([0.01, 0.01]), self.evaluate(slot1)) # Check that the parameters have been updated. self.assertAllCloseAccordingToType( np.array([1.0 - (0.1 * 2.0), 2.0 - (0.1 * 2.0)]), self.evaluate(var0)) self.assertAllCloseAccordingToType( np.array([3.0 - (0.01 * 2.0), 4.0 - (0.01 * 2.0)]), self.evaluate(var1)) # Step 2: momentum update that changes only slot1 but not slot0. self.evaluate(mom_update_partial) # Check that only the relevant momentum accumulator has been updated. self.assertAllCloseAccordingToType( np.array([0.1, 0.1]), self.evaluate(slot0)) self.assertAllCloseAccordingToType( np.array([(0.9 * 0.01 + 0.01), (0.9 * 0.01 + 0.01)]), self.evaluate(slot1)) # Step 3: momentum update that does not change anything. self.evaluate(mom_update_no_action) # Check that the momentum accumulators have *NOT* been updated. self.assertAllCloseAccordingToType( np.array([0.1, 0.1]), self.evaluate(slot0)) self.assertAllCloseAccordingToType( np.array([(0.9 * 0.01 + 0.01), (0.9 * 0.01 + 0.01)]), self.evaluate(slot1)) def testGradientClipping(self): with self.cached_session(): var0 = variables.Variable([1.0, 2.0], dtype=dtypes.float32) var1 = variables.Variable([3.0, 4.0], dtype=dtypes.float32) var2 = variables.Variable([3.0, 4.0], dtype=dtypes.float32) var3 = variables.Variable([3.0, 4.0], dtype=dtypes.float32) grads0 = constant_op.constant([10.0, 15.0], dtype=dtypes.float32) grads1 = constant_op.constant([0.0, 5.0], dtype=dtypes.float32) grads2 = constant_op.constant([0.0, 0.0], dtype=dtypes.float32) grads3 = None varlist = [var0, var1, var2, var3] gradients = [grads0, grads1, grads2, grads3] clipped_gradvars, global_norm = ( multitask_optimizer_wrapper.clip_gradients_by_global_norm( six.moves.zip(gradients, varlist), clip_norm=1.0)) clipped_grads = list(six.moves.zip(*clipped_gradvars))[0] reference_global_norm = np.sqrt(np.sum(np.square([10.0, 15.0, 0.0, 5.0]))) self.assertAllCloseAccordingToType( self.evaluate(global_norm), reference_global_norm) self.assertAllCloseAccordingToType( self.evaluate(clipped_grads[2]), np.array([0., 0.])) self.assertEqual(clipped_grads[3], None) if __name__ == "__main__": test.main()
tensorflow-master
tensorflow/contrib/opt/python/training/multitask_optimizer_wrapper_test.py
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for AdamGS.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.contrib.opt.python.training import adam_gs_optimizer from tensorflow.python.client import session from tensorflow.python.eager import context from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.framework import test_util from tensorflow.python.ops import array_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import resource_variable_ops from tensorflow.python.ops import variables from tensorflow.python.platform import test def adam_update_numpy(param, g_t, t, m, v, alpha=0.001, beta1=0.9, beta2=0.999, epsilon=1e-8): alpha_t = alpha * np.sqrt(1 - beta2**t) / (1 - beta1**t) m_t = beta1 * m + (1 - beta1) * g_t v_t = beta2 * v + (1 - beta2) * g_t * g_t param_t = param - alpha_t * m_t / (np.sqrt(v_t) + epsilon) return param_t, m_t, v_t class AdamGSOptimizerTest(test.TestCase): def doTestSparse(self, use_resource=False): for dtype in [dtypes.half, dtypes.float32, dtypes.float64]: with self.cached_session(): # Initialize variables for numpy implementation. m0, v0, m1, v1 = 0.0, 0.0, 0.0, 0.0 var0_np = np.array([1.0, 2.0], dtype=dtype.as_numpy_dtype) grads0_np = np.array([0.1, 0.1], dtype=dtype.as_numpy_dtype) var1_np = np.array([3.0, 4.0], dtype=dtype.as_numpy_dtype) grads1_np = np.array([0.01, 0.01], dtype=dtype.as_numpy_dtype) if use_resource: global_step = resource_variable_ops.ResourceVariable( array_ops.zeros([], dtypes.int64)) var0 = resource_variable_ops.ResourceVariable(var0_np) var1 = resource_variable_ops.ResourceVariable(var1_np) else: global_step = variables.Variable(array_ops.zeros([], dtypes.int64)) var0 = variables.Variable(var0_np) var1 = variables.Variable(var1_np) grads0_np_indices = np.array([0, 1], dtype=np.int32) grads0 = ops.IndexedSlices( constant_op.constant(grads0_np), constant_op.constant(grads0_np_indices), constant_op.constant([2])) grads1_np_indices = np.array([0, 1], dtype=np.int32) grads1 = ops.IndexedSlices( constant_op.constant(grads1_np), constant_op.constant(grads1_np_indices), constant_op.constant([2])) opt = adam_gs_optimizer.AdamGSOptimizer(global_step=global_step) update = opt.apply_gradients(zip([grads0, grads1], [var0, var1]), global_step=global_step) variables.global_variables_initializer().run() # Fetch params to validate initial values self.assertAllClose([1.0, 2.0], self.evaluate(var0)) self.assertAllClose([3.0, 4.0], self.evaluate(var1)) beta1_power, beta2_power = opt._get_beta_accumulators() # Run 3 steps of Adam for t in range(1, 4): self.assertAllCloseAccordingToType(0.9**t, self.evaluate(beta1_power)) self.assertAllCloseAccordingToType(0.999**t, self.evaluate(beta2_power)) update.run() var0_np, m0, v0 = adam_update_numpy(var0_np, grads0_np, t, m0, v0) var1_np, m1, v1 = adam_update_numpy(var1_np, grads1_np, t, m1, v1) # Validate updated params self.assertAllCloseAccordingToType(var0_np, self.evaluate(var0)) self.assertAllCloseAccordingToType(var1_np, self.evaluate(var1)) def testSparse(self): self.doTestSparse(use_resource=False) def testResourceSparse(self): self.doTestSparse(use_resource=True) def testSparseDevicePlacement(self): for index_dtype in [dtypes.int32, dtypes.int64]: with self.cached_session(force_gpu=test.is_gpu_available()): # If a GPU is available, tests that all optimizer ops can be placed on # it (i.e. they have GPU kernels). var = variables.Variable([[1.0], [2.0]]) indices = constant_op.constant([0, 1], dtype=index_dtype) gathered_sum = math_ops.reduce_sum(array_ops.gather(var, indices)) optimizer = adam_gs_optimizer.AdamGSOptimizer(3.0) minimize_op = optimizer.minimize(gathered_sum) variables.global_variables_initializer().run() minimize_op.run() def testSparseRepeatedIndices(self): for dtype in [dtypes.half, dtypes.float32, dtypes.float64]: with self.cached_session(): repeated_index_global_step = variables.Variable( array_ops.zeros([], dtypes.int64)) aggregated_global_step = variables.Variable( array_ops.zeros([], dtypes.int64)) repeated_index_update_var = variables.Variable( [[1.0], [2.0]], dtype=dtype) aggregated_update_var = variables.Variable( [[1.0], [2.0]], dtype=dtype) grad_repeated_index = ops.IndexedSlices( constant_op.constant( [0.1, 0.1], shape=[2, 1], dtype=dtype), constant_op.constant([1, 1]), constant_op.constant([2, 1])) grad_aggregated = ops.IndexedSlices( constant_op.constant( [0.2], shape=[1, 1], dtype=dtype), constant_op.constant([1]), constant_op.constant([2, 1])) repeated_update = adam_gs_optimizer.AdamGSOptimizer( global_step=repeated_index_global_step).apply_gradients( [(grad_repeated_index, repeated_index_update_var)], global_step=repeated_index_global_step) aggregated_update = adam_gs_optimizer.AdamGSOptimizer( global_step=aggregated_global_step).apply_gradients( [(grad_aggregated, aggregated_update_var)], global_step=aggregated_global_step) variables.global_variables_initializer().run() self.assertAllClose(aggregated_update_var.eval(), self.evaluate(repeated_index_update_var)) for _ in range(3): repeated_update.run() aggregated_update.run() self.assertAllClose(aggregated_update_var.eval(), self.evaluate(repeated_index_update_var)) def doTestBasic(self, use_resource=False, use_callable_params=False): for i, dtype in enumerate([dtypes.half, dtypes.float32, dtypes.float64]): with self.session(graph=ops.Graph()): # Initialize variables for numpy implementation. m0, v0, m1, v1 = 0.0, 0.0, 0.0, 0.0 var0_np = np.array([1.0, 2.0], dtype=dtype.as_numpy_dtype) grads0_np = np.array([0.1, 0.1], dtype=dtype.as_numpy_dtype) var1_np = np.array([3.0, 4.0], dtype=dtype.as_numpy_dtype) grads1_np = np.array([0.01, 0.01], dtype=dtype.as_numpy_dtype) if use_resource: global_step = resource_variable_ops.ResourceVariable( array_ops.zeros([], dtypes.int64), name="global_step_%d" % i) var0 = resource_variable_ops.ResourceVariable( var0_np, name="var0_%d" % i) var1 = resource_variable_ops.ResourceVariable( var1_np, name="var1_%d" % i) else: global_step = variables.Variable(array_ops.zeros([], dtypes.int64)) var0 = variables.Variable(var0_np) var1 = variables.Variable(var1_np) grads0 = constant_op.constant(grads0_np) grads1 = constant_op.constant(grads1_np) learning_rate = lambda: 0.001 beta1 = lambda: 0.9 beta2 = lambda: 0.999 epsilon = lambda: 1e-8 if not use_callable_params: learning_rate = learning_rate() beta1 = beta1() beta2 = beta2() epsilon = epsilon() opt = adam_gs_optimizer.AdamGSOptimizer(global_step=global_step, learning_rate=learning_rate) update = opt.apply_gradients(zip([grads0, grads1], [var0, var1]), global_step=global_step) opt_variables = opt.variables() beta1_power, beta2_power = opt._get_beta_accumulators() self.assertTrue(beta1_power is not None) self.assertTrue(beta2_power is not None) self.assertNotIn(beta1_power, opt_variables) self.assertNotIn(beta2_power, opt_variables) if not context.executing_eagerly(): with ops.Graph().as_default(): # Shouldn't return non-slot variables from other graphs. self.assertEqual(0, len(opt.variables())) self.evaluate(variables.global_variables_initializer()) # Fetch params to validate initial values self.assertAllClose([1.0, 2.0], self.evaluate(var0)) self.assertAllClose([3.0, 4.0], self.evaluate(var1)) # Run 3 steps of Adam for t in range(1, 4): if not context.executing_eagerly(): self.evaluate(update) self.assertAllCloseAccordingToType( 0.9**(t + 1), self.evaluate(beta1_power)) self.assertAllCloseAccordingToType( 0.999**(t + 1), self.evaluate(beta2_power)) else: if t > 1: opt.apply_gradients(zip([grads0, grads1], [var0, var1]), global_step=global_step) beta1_power, beta2_power = opt._get_beta_accumulators() self.assertAllCloseAccordingToType( 0.9**t, self.evaluate(beta1_power)) self.assertAllCloseAccordingToType( 0.999**t, self.evaluate(beta2_power)) var0_np, m0, v0 = adam_update_numpy(var0_np, grads0_np, t, m0, v0) var1_np, m1, v1 = adam_update_numpy(var1_np, grads1_np, t, m1, v1) # Validate updated params self.assertAllCloseAccordingToType(var0_np, self.evaluate(var0)) self.assertAllCloseAccordingToType(var1_np, self.evaluate(var1)) if use_resource: self.assertEqual("var0_%d/Adam:0" % (i,), opt.get_slot(var=var0, name="m").name) def testBasic(self): with self.cached_session(): self.doTestBasic(use_resource=False) @test_util.run_in_graph_and_eager_modes(reset_test=True) def testResourceBasic(self): self.doTestBasic(use_resource=True) def testBasicCallableParams(self): with context.eager_mode(): self.doTestBasic(use_resource=True, use_callable_params=True) def testTensorLearningRate(self): for dtype in [dtypes.half, dtypes.float32, dtypes.float64]: with self.cached_session(): global_step = variables.Variable(array_ops.zeros([], dtypes.int64)) # Initialize variables for numpy implementation. m0, v0, m1, v1 = 0.0, 0.0, 0.0, 0.0 var0_np = np.array([1.0, 2.0], dtype=dtype.as_numpy_dtype) grads0_np = np.array([0.1, 0.1], dtype=dtype.as_numpy_dtype) var1_np = np.array([3.0, 4.0], dtype=dtype.as_numpy_dtype) grads1_np = np.array([0.01, 0.01], dtype=dtype.as_numpy_dtype) var0 = variables.Variable(var0_np) var1 = variables.Variable(var1_np) grads0 = constant_op.constant(grads0_np) grads1 = constant_op.constant(grads1_np) opt = adam_gs_optimizer.AdamGSOptimizer( global_step=global_step, learning_rate=constant_op.constant(0.001)) update = opt.apply_gradients(zip([grads0, grads1], [var0, var1]), global_step=global_step) variables.global_variables_initializer().run() # Fetch params to validate initial values self.assertAllClose([1.0, 2.0], self.evaluate(var0)) self.assertAllClose([3.0, 4.0], self.evaluate(var1)) beta1_power, beta2_power = opt._get_beta_accumulators() # Run 3 steps of Adam for t in range(1, 4): self.assertAllCloseAccordingToType(0.9**t, self.evaluate(beta1_power)) self.assertAllCloseAccordingToType(0.999**t, self.evaluate(beta2_power)) update.run() var0_np, m0, v0 = adam_update_numpy(var0_np, grads0_np, t, m0, v0) var1_np, m1, v1 = adam_update_numpy(var1_np, grads1_np, t, m1, v1) # Validate updated params self.assertAllCloseAccordingToType(var0_np, self.evaluate(var0)) self.assertAllCloseAccordingToType(var1_np, self.evaluate(var1)) def testSharing(self): for dtype in [dtypes.half, dtypes.float32, dtypes.float64]: with self.cached_session(): global_step = variables.Variable(array_ops.zeros([], dtypes.int64)) # Initialize variables for numpy implementation. m0, v0, m1, v1 = 0.0, 0.0, 0.0, 0.0 var0_np = np.array([1.0, 2.0], dtype=dtype.as_numpy_dtype) grads0_np = np.array([0.1, 0.1], dtype=dtype.as_numpy_dtype) var1_np = np.array([3.0, 4.0], dtype=dtype.as_numpy_dtype) grads1_np = np.array([0.01, 0.01], dtype=dtype.as_numpy_dtype) var0 = variables.Variable(var0_np) var1 = variables.Variable(var1_np) grads0 = constant_op.constant(grads0_np) grads1 = constant_op.constant(grads1_np) opt = adam_gs_optimizer.AdamGSOptimizer(global_step=global_step) update1 = opt.apply_gradients(zip([grads0, grads1], [var0, var1]), global_step=global_step) update2 = opt.apply_gradients(zip([grads0, grads1], [var0, var1]), global_step=global_step) variables.global_variables_initializer().run() beta1_power, beta2_power = opt._get_beta_accumulators() # Fetch params to validate initial values self.assertAllClose([1.0, 2.0], self.evaluate(var0)) self.assertAllClose([3.0, 4.0], self.evaluate(var1)) # Run 3 steps of intertwined Adam1 and Adam2. for t in range(1, 4): self.assertAllCloseAccordingToType(0.9**t, self.evaluate(beta1_power)) self.assertAllCloseAccordingToType(0.999**t, self.evaluate(beta2_power)) if t % 2 == 0: update1.run() else: update2.run() var0_np, m0, v0 = adam_update_numpy(var0_np, grads0_np, t, m0, v0) var1_np, m1, v1 = adam_update_numpy(var1_np, grads1_np, t, m1, v1) # Validate updated params self.assertAllCloseAccordingToType(var0_np, self.evaluate(var0)) self.assertAllCloseAccordingToType(var1_np, self.evaluate(var1)) def testTwoSessions(self): optimizer = adam_gs_optimizer.AdamGSOptimizer() with context.eager_mode(): var0 = variables.Variable(np.array([1.0, 2.0]), name="v0") grads0 = constant_op.constant(np.array([0.1, 0.1])) optimizer.apply_gradients([(grads0, var0)]) g = ops.Graph() with g.as_default(): with session.Session(): var0 = variables.Variable(np.array([1.0, 2.0]), name="v0") grads0 = constant_op.constant(np.array([0.1, 0.1])) optimizer.apply_gradients([(grads0, var0)]) gg = ops.Graph() with gg.as_default(): with session.Session(): var0 = variables.Variable(np.array([1.0, 2.0]), name="v0") grads0 = constant_op.constant(np.array([0.1, 0.1])) # If the optimizer saves any state not keyed by graph the following line # fails. optimizer.apply_gradients([(grads0, var0)]) def testSlotsUniqueEager(self): with context.eager_mode(): v1 = resource_variable_ops.ResourceVariable(1.) v2 = resource_variable_ops.ResourceVariable(1.) opt = adam_gs_optimizer.AdamGSOptimizer(1.) opt.minimize(lambda: v1 + v2) # There should be two unique slot variables for v1 and v2 respectively. self.assertEqual(4, len(set(opt.variables()))) if __name__ == "__main__": test.main()
tensorflow-master
tensorflow/contrib/opt/python/training/adam_gs_optimizer_test.py
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Functional tests for Matrix functions.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.contrib.opt.python.training import matrix_functions from tensorflow.python.platform import test TOLERANCE = 1e-3 def np_power(mat_g, alpha): """Computes mat_g^alpha for a square symmetric matrix mat_g.""" mat_u, diag_d, mat_v = np.linalg.svd(mat_g) diag_d = np.power(diag_d, alpha) return np.dot(np.dot(mat_u, np.diag(diag_d)), mat_v) class MatrixFunctionTests(test.TestCase): def testMatrixSquareRootFunction(self): """Tests for matrix square roots.""" size = 20 mat_a = np.random.rand(size, size) mat = np.dot(mat_a, mat_a.T) expected_mat = np_power(mat, 0.5) mat_root = matrix_functions.matrix_square_root(mat, size) self.assertAllCloseAccordingToType( expected_mat, mat_root, atol=TOLERANCE, rtol=TOLERANCE) def testMatrixInversePthRootFunction(self): """Tests for matrix inverse pth roots.""" size = 20 mat_a = np.random.rand(size, size) mat = np.dot(mat_a, mat_a.T) expected_mat = np_power(mat, -0.125) mat_root = matrix_functions.matrix_inverse_pth_root(mat, size, -0.125) self.assertAllCloseAccordingToType( expected_mat, mat_root, atol=TOLERANCE, rtol=TOLERANCE) if __name__ == '__main__': test.main()
tensorflow-master
tensorflow/contrib/opt/python/training/matrix_functions_test.py
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Functional tests for Regreg_adagrad_optimizer.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.contrib.opt.python.training import reg_adagrad_optimizer from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.ops import embedding_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import resource_variable_ops from tensorflow.python.ops import variable_scope from tensorflow.python.ops import variables from tensorflow.python.platform import test class RegAdagradOptimizerTest(test.TestCase): def doTestBasic(self, use_locking=False, use_resource=False): for dtype in [dtypes.half, dtypes.float32, dtypes.float64]: with self.cached_session(): if use_resource: var0 = resource_variable_ops.ResourceVariable([1.0, 2.0], dtype=dtype) var1 = resource_variable_ops.ResourceVariable([3.0, 4.0], dtype=dtype) else: var0 = variables.Variable([1.0, 2.0], dtype=dtype) var1 = variables.Variable([3.0, 4.0], dtype=dtype) grads0 = constant_op.constant([0.1, 0.1], dtype=dtype) grads1 = constant_op.constant([0.01, 0.01], dtype=dtype) ada_opt = reg_adagrad_optimizer.RegAdagradOptimizer( 3.0, initial_accumulator_value=0.1, use_locking=use_locking) ada_update = ada_opt.apply_gradients( zip([grads0, grads1], [var0, var1])) variables.global_variables_initializer().run() # Fetch params to validate initial values self.assertAllClose([1.0, 2.0], var0.eval()) self.assertAllClose([3.0, 4.0], var1.eval()) # Run 3 steps of adagrad for _ in range(3): ada_update.run() # Validate updated params self.assertAllCloseAccordingToType( np.array([-1.6026098728179932, -0.6026098728179932]), var0.eval()) self.assertAllCloseAccordingToType( np.array([2.715679168701172, 3.715679168701172]), var1.eval()) def testBasic(self): self.doTestBasic(use_locking=False) def testBasicResource(self): self.doTestBasic(use_locking=False, use_resource=True) def testBasicLocked(self): self.doTestBasic(use_locking=True) def testMinimizeSparseResourceVariable(self): for dtype in [dtypes.half, dtypes.float32, dtypes.float64]: with self.cached_session(): var0 = resource_variable_ops.ResourceVariable( [[1.0, 2.0], [3.0, 4.0]], dtype=dtype) x = constant_op.constant([[4.0], [5.0]], dtype=dtype) pred = math_ops.matmul(embedding_ops.embedding_lookup([var0], [0]), x) loss = pred * pred sgd_op = reg_adagrad_optimizer.RegAdagradOptimizer(1.0).minimize(loss) variables.global_variables_initializer().run() # Fetch params to validate initial values self.assertAllCloseAccordingToType([[1.0, 2.0], [3.0, 4.0]], var0.eval()) # Run 1 step of sgd sgd_op.run() # Validate updated params self.assertAllCloseAccordingToType( [[0, 1], [3, 4]], var0.eval(), atol=0.01) def testTensorLearningRate(self): for dtype in [dtypes.half, dtypes.float32, dtypes.float64]: with self.cached_session(): var0 = variables.Variable([1.0, 2.0], dtype=dtype) var1 = variables.Variable([3.0, 4.0], dtype=dtype) grads0 = constant_op.constant([0.1, 0.1], dtype=dtype) grads1 = constant_op.constant([0.01, 0.01], dtype=dtype) ada_opt = reg_adagrad_optimizer.RegAdagradOptimizer( constant_op.constant(3.0), initial_accumulator_value=0.1) ada_update = ada_opt.apply_gradients( zip([grads0, grads1], [var0, var1])) variables.global_variables_initializer().run() # Fetch params to validate initial values self.assertAllClose([1.0, 2.0], var0.eval()) self.assertAllClose([3.0, 4.0], var1.eval()) # Run 3 steps of adagrad for _ in range(3): ada_update.run() # Validate updated params self.assertAllCloseAccordingToType( np.array([-1.6026098728179932, -0.6026098728179932]), var0.eval()) self.assertAllCloseAccordingToType( np.array([2.715679168701172, 3.715679168701172]), var1.eval()) def testSparseBasic(self): for dtype in [dtypes.half, dtypes.float32, dtypes.float64]: with self.cached_session(): var0 = variables.Variable([[1.0], [2.0]], dtype=dtype) var1 = variables.Variable([[3.0], [4.0]], dtype=dtype) grads0 = ops.IndexedSlices( constant_op.constant([0.1], shape=[1, 1], dtype=dtype), constant_op.constant([0]), constant_op.constant([2, 1])) grads1 = ops.IndexedSlices( constant_op.constant([0.01], shape=[1, 1], dtype=dtype), constant_op.constant([1]), constant_op.constant([2, 1])) ada_opt = reg_adagrad_optimizer.RegAdagradOptimizer( 3.0, initial_accumulator_value=0.1) ada_update = ada_opt.apply_gradients( zip([grads0, grads1], [var0, var1])) variables.global_variables_initializer().run() # Fetch params to validate initial values self.assertAllClose([[1.0], [2.0]], var0.eval()) self.assertAllClose([[3.0], [4.0]], var1.eval()) # Run 3 step of sgd for _ in range(3): ada_update.run() # Validate updated params self.assertAllCloseAccordingToType( np.array([[-1.6026098728179932], [2.0]]), var0.eval()) self.assertAllCloseAccordingToType( np.array([[3.0], [3.715679168701172]]), var1.eval()) def testSparseRepeatedIndices(self): for dtype in [dtypes.half, dtypes.float32, dtypes.float64]: with self.cached_session(): repeated_index_update_var = variables.Variable( [[1.0], [2.0]], dtype=dtype) aggregated_update_var = variables.Variable([[1.0], [2.0]], dtype=dtype) grad_repeated_index = ops.IndexedSlices( constant_op.constant([0.1, 0.1], shape=[2, 1], dtype=dtype), constant_op.constant([1, 1]), constant_op.constant([2, 1])) grad_aggregated = ops.IndexedSlices( constant_op.constant([0.2], shape=[1, 1], dtype=dtype), constant_op.constant([1]), constant_op.constant([2, 1])) repeated_update = reg_adagrad_optimizer.RegAdagradOptimizer( 3.0).apply_gradients([(grad_repeated_index, repeated_index_update_var)]) aggregated_update = reg_adagrad_optimizer.RegAdagradOptimizer( 3.0).apply_gradients([(grad_aggregated, aggregated_update_var)]) variables.global_variables_initializer().run() self.assertAllClose(aggregated_update_var.eval(), repeated_index_update_var.eval()) for _ in range(3): repeated_update.run() aggregated_update.run() self.assertAllClose(aggregated_update_var.eval(), repeated_index_update_var.eval()) def testSparseRepeatedIndicesResourceVariable(self): for dtype in [dtypes.half, dtypes.float32, dtypes.float64]: with self.cached_session(): var_repeated = resource_variable_ops.ResourceVariable( [1.0, 2.0], dtype=dtype) loss_repeated = math_ops.reduce_sum( embedding_ops.embedding_lookup(var_repeated, [0, 0])) var_aggregated = resource_variable_ops.ResourceVariable( [1.0, 2.0], dtype=dtype) loss_aggregated = 2 * math_ops.reduce_sum( embedding_ops.embedding_lookup(var_aggregated, [0])) update_op_repeated = reg_adagrad_optimizer.RegAdagradOptimizer( 2.0).minimize(loss_repeated) update_op_aggregated = reg_adagrad_optimizer.RegAdagradOptimizer( 2.0).minimize(loss_aggregated) variables.global_variables_initializer().run() self.assertAllCloseAccordingToType(var_repeated.eval(), var_aggregated.eval()) for _ in range(3): update_op_repeated.run() update_op_aggregated.run() self.assertAllCloseAccordingToType(var_repeated.eval(), var_aggregated.eval()) def testSparseStability(self): for dtype in [dtypes.half, dtypes.float32, dtypes.float64]: with self.cached_session(): shape = [1, 6] var0 = variables.Variable( [[ 0.00872496, -0.106952, 0.110467, 0.226505, -0.0147257, -0.0105945 ]], dtype=dtype) grads0 = ops.IndexedSlices( constant_op.constant( [[ -5.91278e-05, 5.31673e-05, -2.5779e-06, 4.29153e-05, -8.4877e-05, -9.48906e-05 ]], shape=shape, dtype=dtype), constant_op.constant([0]), constant_op.constant(shape)) ada_opt = reg_adagrad_optimizer.RegAdagradOptimizer( 1.0, initial_accumulator_value=0.1) ada_update = ada_opt.apply_gradients(zip([grads0], [var0])) self.assertEqual(["accumulator"], ada_opt.get_slot_names()) slot0 = ada_opt.get_slot(var0, "accumulator") init = variables.global_variables_initializer() for _ in range(100): init.run() ada_update.run() self.assertAllCloseAccordingToType( np.array([[0.1, 0.1, 0.1, 0.1, 0.1, 0.1]]), slot0.eval()) self.assertAllCloseAccordingToType( np.array([[ 0.00891194, -0.10712013, 0.11047515, 0.22636929, -0.0144573, -0.01029443 ]]), var0.eval()) def testSharing(self): for dtype in [dtypes.half, dtypes.float32, dtypes.float64]: with self.cached_session(): var0 = variables.Variable([1.0, 2.0], dtype=dtype) var1 = variables.Variable([3.0, 4.0], dtype=dtype) grads0 = constant_op.constant([0.1, 0.1], dtype=dtype) grads1 = constant_op.constant([0.01, 0.01], dtype=dtype) ada_opt = reg_adagrad_optimizer.RegAdagradOptimizer(3.0) # Apply the optimizer twice. Both applications will use # the same accums. ada_update1 = ada_opt.apply_gradients( zip([grads0, grads1], [var0, var1])) ada_update2 = ada_opt.apply_gradients( zip([grads0, grads1], [var0, var1])) self.assertEqual(["accumulator"], ada_opt.get_slot_names()) slot0 = ada_opt.get_slot(var0, "accumulator") self.assertEquals(slot0.get_shape(), var0.get_shape()) slot1 = ada_opt.get_slot(var1, "accumulator") self.assertEquals(slot1.get_shape(), var1.get_shape()) variables.global_variables_initializer().run() # Fetch params to validate initial values. self.assertAllClose([1.0, 2.0], var0.eval()) self.assertAllClose([3.0, 4.0], var1.eval()) # Mix the first and the second adagrad for 3 steps. ada_update1.run() ada_update2.run() ada_update1.run() # Validate updated params (the same as with only 1 RegAdagrad). self.assertAllCloseAccordingToType( np.array([-1.6026098728179932, -0.6026098728179932]), var0.eval()) self.assertAllCloseAccordingToType( np.array([2.715679168701172, 3.715679168701172]), var1.eval()) def testDynamicShapeVariable_Ok(self): with self.cached_session(): v = variable_scope.get_variable( "v", initializer=constant_op.constant(1.), validate_shape=False) self.assertFalse(v.shape.is_fully_defined()) # Creating optimizer should cause no exception. reg_adagrad_optimizer.RegAdagradOptimizer( 3.0, initial_accumulator_value=0.1) def testSkipUpdatingSlots(self): iav = 0.130005 # A value that works with float16 for dtype in [dtypes.half, dtypes.float32, dtypes.float64]: with self.cached_session(): var0 = variables.Variable([1.0, 2.0], dtype=dtype) var1 = variables.Variable([3.0, 4.0], dtype=dtype) grads0 = constant_op.constant([0.1, 0.1], dtype=dtype) grads1 = constant_op.constant([0.01, 0.01], dtype=dtype) ada_opt = reg_adagrad_optimizer.RegAdagradOptimizer( 3.0, initial_accumulator_value=iav) # Apply the optimizer twice. Both applications will use # the same accums. with ada_opt.avoid_updating_slots(): ada_update = ada_opt.apply_gradients( zip([grads0, grads1], [var0, var1])) self.assertEqual(["accumulator"], ada_opt.get_slot_names()) slot0 = ada_opt.get_slot(var0, "accumulator") self.assertEquals(slot0.get_shape(), var0.get_shape()) slot1 = ada_opt.get_slot(var1, "accumulator") self.assertEquals(slot1.get_shape(), var1.get_shape()) variables.global_variables_initializer().run() # Fetch params to validate initial values. self.assertAllClose([1.0, 2.0], var0.eval()) self.assertAllClose([3.0, 4.0], var1.eval()) # Mix the first and the second adagrad for 3 steps. for _ in range(3): ada_update.run() # Validate that ada_opt's slots are not updated. self.assertAllCloseAccordingToType(np.array([iav, iav]), slot0.eval()) self.assertAllCloseAccordingToType(np.array([iav, iav]), slot1.eval()) def testSparseSkipUpdatingSlots(self): iav = 0.130005 # A value that works with float16 for dtype in [dtypes.half, dtypes.float32, dtypes.float64]: with self.cached_session(): var0 = variables.Variable([[1.0], [2.0]], dtype=dtype) var1 = variables.Variable([[3.0], [4.0]], dtype=dtype) grads0 = ops.IndexedSlices( constant_op.constant([0.1], shape=[1, 1], dtype=dtype), constant_op.constant([0]), constant_op.constant([2, 1])) grads1 = ops.IndexedSlices( constant_op.constant([0.01], shape=[1, 1], dtype=dtype), constant_op.constant([1]), constant_op.constant([2, 1])) ada_opt = reg_adagrad_optimizer.RegAdagradOptimizer( 3.0, initial_accumulator_value=iav) with ada_opt.avoid_updating_slots(): ada_update = ada_opt.apply_gradients( zip([grads0, grads1], [var0, var1])) slot0 = ada_opt.get_slot(var0, "accumulator") self.assertEquals(slot0.get_shape(), var0.get_shape()) slot1 = ada_opt.get_slot(var1, "accumulator") self.assertEquals(slot1.get_shape(), var1.get_shape()) variables.global_variables_initializer().run() # Fetch params to validate initial values self.assertAllClose([[1.0], [2.0]], var0.eval()) self.assertAllClose([[3.0], [4.0]], var1.eval()) # Run 3 step of sgd for _ in range(3): ada_update.run() # Validate that ada_opt's slots are not updated. self.assertAllCloseAccordingToType( np.array([[iav], [iav]]), slot0.eval()) self.assertAllCloseAccordingToType( np.array([[iav], [iav]]), slot1.eval()) if __name__ == "__main__": test.main()
tensorflow-master
tensorflow/contrib/opt/python/training/reg_adagrad_optimizer_test.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for AddSign.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.contrib.opt.python.training import addsign from tensorflow.contrib.opt.python.training import sign_decay from tensorflow.python.eager import context from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.ops import resource_variable_ops from tensorflow.python.ops import variables from tensorflow.python.platform import test def py_linear_decay_fn(decay_steps): def linear_decay(step): step = min(step, decay_steps) return float(decay_steps - step) / decay_steps return linear_decay def addsign_update_numpy(params, g_t, m, lr, alpha=1.0, beta=0.9, py_sign_decay_fn=None, t=None): m_t = beta * m + (1 - beta) * g_t if py_sign_decay_fn is None: sign_decayed = 1.0 else: sign_decayed = py_sign_decay_fn(t-1) multiplier = alpha + sign_decayed * np.sign(g_t) * np.sign(m_t) params_t = params - lr * multiplier * g_t return params_t, m_t class AddSignTest(test.TestCase): def _testDense(self, use_resource=False, learning_rate=0.1, sign_decay_fn=None, py_sign_decay_fn=None, alpha=1.0, beta=0.9): for dtype in [dtypes.half, dtypes.float32, dtypes.float64]: with self.cached_session(use_gpu=True): # Initialize variables for numpy implementation. m0, m1 = 0.0, 0.0 var0_np = np.array([1.0, 2.0], dtype=dtype.as_numpy_dtype) grads0_np = np.array([0.1, 0.1], dtype=dtype.as_numpy_dtype) var1_np = np.array([3.0, 4.0], dtype=dtype.as_numpy_dtype) grads1_np = np.array([0.01, 0.01], dtype=dtype.as_numpy_dtype) if use_resource: var0 = resource_variable_ops.ResourceVariable(var0_np) var1 = resource_variable_ops.ResourceVariable(var1_np) global_step = resource_variable_ops.ResourceVariable( 0, trainable=False) else: var0 = variables.VariableV1(var0_np) var1 = variables.VariableV1(var1_np) global_step = variables.VariableV1( 0, trainable=False) grads0 = constant_op.constant(grads0_np) grads1 = constant_op.constant(grads1_np) opt = addsign.AddSignOptimizer( learning_rate=learning_rate, alpha=alpha, beta=beta, sign_decay_fn=sign_decay_fn, ) update = opt.apply_gradients(zip([grads0, grads1], [var0, var1]), global_step=global_step) neg_update = opt.apply_gradients(zip([-grads0, -grads1], [var0, var1]), global_step=global_step) if not context.executing_eagerly(): self.evaluate(variables.global_variables_initializer()) # Fetch params to validate initial values self.assertAllClose([1.0, 2.0], self.evaluate(var0)) self.assertAllClose([3.0, 4.0], self.evaluate(var1)) # Run 7 steps of AddSign # first 4 steps with positive gradient # last 3 steps with negative gradient (sign(gm) should be -1) for t in range(1, 8): if t < 5: if not context.executing_eagerly(): self.evaluate(update) elif t > 1: opt.apply_gradients(zip([grads0, grads1], [var0, var1]), global_step=global_step) else: if not context.executing_eagerly(): self.evaluate(neg_update) elif t > 1: opt.apply_gradients(zip([-grads0, -grads1], [var0, var1]), global_step=global_step) var0_np, m0 = addsign_update_numpy( var0_np, grads0_np if t < 5 else -grads0_np, m0, learning_rate, alpha=alpha, beta=beta, py_sign_decay_fn=py_sign_decay_fn, t=t, ) var1_np, m1 = addsign_update_numpy( var1_np, grads1_np if t < 5 else -grads1_np, m1, learning_rate, alpha=alpha, beta=beta, py_sign_decay_fn=py_sign_decay_fn, t=t, ) # Validate updated params self.assertAllCloseAccordingToType(var0_np, self.evaluate(var0)) self.assertAllCloseAccordingToType(var1_np, self.evaluate(var1)) def testDense(self): decay_steps = 10 sign_decay_fn = sign_decay.get_linear_decay_fn(decay_steps) py_sign_decay_fn = py_linear_decay_fn(decay_steps) self._testDense(use_resource=False) self._testDense(use_resource=False, learning_rate=0.01, alpha=0.1, beta=0.8) self._testDense(use_resource=False, sign_decay_fn=sign_decay_fn, py_sign_decay_fn=py_sign_decay_fn) self._testDense(use_resource=True) self._testDense(use_resource=True, learning_rate=0.01, alpha=0.1, beta=0.8) self._testDense(use_resource=True, sign_decay_fn=sign_decay_fn, py_sign_decay_fn=py_sign_decay_fn) def _testSparse(self, use_resource=False, learning_rate=0.1, sign_decay_fn=None, py_sign_decay_fn=None, alpha=1.0, beta=0.9): for dtype in [dtypes.half, dtypes.float32, dtypes.float64]: with self.cached_session(use_gpu=True): # Initialize variables for numpy implementation. m0, m1 = 0.0, 0.0 var0_np = np.array([1.0, 2.0], dtype=dtype.as_numpy_dtype) grads0_np = np.array([0.1, 0.1], dtype=dtype.as_numpy_dtype) var1_np = np.array([3.0, 4.0], dtype=dtype.as_numpy_dtype) grads1_np = np.array([0.01, 0.01], dtype=dtype.as_numpy_dtype) if use_resource: var0 = resource_variable_ops.ResourceVariable(var0_np) var1 = resource_variable_ops.ResourceVariable(var1_np) global_step = resource_variable_ops.ResourceVariable( 0, trainable=False) else: var0 = variables.VariableV1(var0_np) var1 = variables.VariableV1(var1_np) global_step = variables.VariableV1( 0, trainable=False) grads0_np_indices = np.array([0, 1], dtype=np.int32) grads0 = ops.IndexedSlices( constant_op.constant(grads0_np), constant_op.constant(grads0_np_indices), constant_op.constant([2])) grads1_np_indices = np.array([0, 1], dtype=np.int32) grads1 = ops.IndexedSlices( constant_op.constant(grads1_np), constant_op.constant(grads1_np_indices), constant_op.constant([2])) opt = addsign.AddSignOptimizer( learning_rate=learning_rate, alpha=alpha, beta=beta, sign_decay_fn=sign_decay_fn, ) update = opt.apply_gradients(zip([grads0, grads1], [var0, var1]), global_step=global_step) neg_update = opt.apply_gradients(zip([-grads0, -grads1], [var0, var1]), global_step=global_step) variables.global_variables_initializer().run() # Fetch params to validate initial values self.assertAllClose([1.0, 2.0], var0.eval()) self.assertAllClose([3.0, 4.0], var1.eval()) # Run 7 steps of AddSign # first 4 steps with positive gradient # last 3 steps with negative gradient (sign(gm) should be -1) for t in range(1, 8): if t < 5: update.run() else: neg_update.run() var0_np, m0 = addsign_update_numpy( var0_np, grads0_np if t < 5 else -grads0_np, m0, learning_rate, alpha=alpha, beta=beta, py_sign_decay_fn=py_sign_decay_fn, t=t, ) var1_np, m1 = addsign_update_numpy( var1_np, grads1_np if t < 5 else -grads1_np, m1, learning_rate, alpha=alpha, beta=beta, py_sign_decay_fn=py_sign_decay_fn, t=t, ) # Validate updated params self.assertAllCloseAccordingToType(var0_np, var0.eval()) self.assertAllCloseAccordingToType(var1_np, var1.eval()) def testSparse(self): decay_steps = 10 sign_decay_fn = sign_decay.get_linear_decay_fn(decay_steps) py_sign_decay_fn = py_linear_decay_fn(decay_steps) self._testSparse(use_resource=False) self._testSparse(use_resource=False, learning_rate=0.01, alpha=0.1, beta=0.8) self._testSparse(use_resource=False, sign_decay_fn=sign_decay_fn, py_sign_decay_fn=py_sign_decay_fn) if __name__ == '__main__': test.main()
tensorflow-master
tensorflow/contrib/opt/python/training/addsign_test.py
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """GGT for Tensorflow.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import numpy as np from tensorflow.contrib.optimizer_v2 import optimizer_v2 from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_shape from tensorflow.python.ops import array_ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import linalg_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import state_ops class GGTOptimizer(optimizer_v2.OptimizerV2): """Optimizer that implements the GGT algorithm. GGT has an advantage over sgd and adam on large models with poor conditioning, for example language models and CNNs, see [[ABCHSZZ 2018]](https://arxiv.org/pdf/1806.02958.pdf). """ def __init__(self, learning_rate=0.001, beta1=0.9, use_locking=False, name="GGT", window=10, eps=1e-4, svd_eps=1e-6, sigma_eps=1e-2): """Construct a new GGT optimizer. Initialization: ``` t <- 0 (Initialize timestep) grad_buffer <- 0 (Initialize buffer for keeping past gradients) flat_grad <- 0 (Initialize flattened gradient that contains gradients of all variables) m_0 <- 0 (Initialize 1st moment vector) ``` Suppose all variables and their gradients are concatenated into vectors `flat_vars` and `flat_grad`. The update rule for `flat_vars` uses an optimization described at the beginning of section 2 of the paper: ``` t <- t + 1 m_t <- beta1 * m_{t-1} + (1 - beta1) * flat_grad grad_buffer[(t-1) % window, :] <- m_t M <- grad_buffer^T / sqrt(min(t, window)) U, sigma, _ <- SVD(M^TM + I * svd_eps) sigma_sqrt_inv <- (sqrt(sigma) + sigma_eps)^(-3) sigma_sqrt_min <- min(sqrt(sigma)) if sigma_sqrt_min > eps: new_step <- M U diag(sigma_sqrt_inv) U^T M^T m_t + (m_t - M U diag(1/sigma) U^T M^T m_t) / sigma_sqrt_min else: new_step <- M U diag(sigma_sqrt_inv) U^T M^T m_t flat_vars <- flat_vars - learning_rate * new_step ``` GGT provides the power of full-matrix adaptive regularization at a cost not much larger than SGD. As a result it is suited for large models where the gradient covariance matrix has a poor condition number that slows down first order methods. GGT uses the preconditioner from full-matrix AdaGrad, with gradient history attenuated exponentially as in Adam, and truncated to a window parameter. It has provable guarantees even for non-convex optimization that is never significantly worse than SGD and in some cases better. Args: learning_rate: A float hyperparameter. The learning rate. beta1: A float hyperparameter. The exponential decay rate for the 1st moment estimates. use_locking: If True use locks for update operations. name: Optional name for the operations created when applying gradients. Defaults to "GGT". window: An integer hyperparameter. The number of first moments to keep in computing the adaptive preconditioner. eps: A float hyperparameter. Used to truncate small eigenvalues of the gradient covariance matrix. svd_eps: A float hyperparameter. Used to stabilize SVD. sigma_eps: A float hyperparameter. Used to regularize matrix inversion. """ super(GGTOptimizer, self).__init__(use_locking, name) self._set_hyper("lr", learning_rate) self._set_hyper("beta1", beta1) self._set_hyper("window", window) self._set_hyper("eps", eps) self._set_hyper("svd_eps", svd_eps) self._set_hyper("sigma_eps", sigma_eps) self.index_dict = {} self.shape_dict = {} def _create_vars(self, var_list, state): # Construct ordered dictionary for variable dimensions, sorted by name. shape_dict = {} for v in var_list: shape_dict[v.name] = tensor_shape.dimension_value(np.prod(v.get_shape())) self.shape_dict = collections.OrderedDict( sorted(shape_dict.items(), key=lambda t: t[0])) # Assign each variable its location in flat_grad. The locations are based on # the order of sorted names. idx = 0 for v_name, v_dim in self.shape_dict.items(): self.index_dict[v_name] = idx idx += v_dim state.create_non_slot( initial_value=math_ops.cast(0., dtype=var_list[0].dtype.base_dtype), name="global_step") # Buffer for keeping past gradients. window = state.get_hyper("window") grad_buffer_init = array_ops.zeros( [window, idx], dtype=var_list[0].dtype.base_dtype) state.create_non_slot(initial_value=grad_buffer_init, name="grad_buffer") state.create_non_slot( initial_value=array_ops.zeros( (idx,), dtype=var_list[0].dtype.base_dtype), name="moment1") # Flattened gradient that contains gradients for all variables in the model. state.create_non_slot( initial_value=array_ops.zeros( (idx,), dtype=var_list[0].dtype.base_dtype), name="flat_grad") def _get_global_step(self, state=None): if state is None: state = self._get_per_graph_state() return state.get_non_slot("global_step") def _get_moment1(self, state=None): if state is None: state = self._get_per_graph_state() return state.get_non_slot("moment1") def _get_grad_buffer(self, state=None): if state is None: state = self._get_per_graph_state() return state.get_non_slot("grad_buffer") def _get_flat_grad(self, state=None): if state is None: state = self._get_per_graph_state() return state.get_non_slot("flat_grad") def _apply_sparse(self, grad, var): raise NotImplementedError("Sparse gradient updates are not supported.") def _prepare(self, state): self._variables = [] def _apply_dense(self, grad, var, state): self._variables.append(var) dim = self.shape_dict[var.name] start_index = self.index_dict[var.name] end_index = start_index + dim # Update flat_gradient at the index associated with the variable. flat_grad = self._get_flat_grad(state) new_flat_grad = array_ops.reshape(grad, [-1]) flat_grad_updated = state_ops.scatter_update( flat_grad, math_ops.range(start_index, end_index), new_flat_grad) return flat_grad_updated def _resource_apply_dense(self, grad, var, state): self._variables.append(var) dim = self.shape_dict[var.name] start_index = self.index_dict[var.name] end_index = start_index + dim # Update flat_gradient at the index associated with the variable. flat_grad = self._get_flat_grad(state) new_flat_grad = array_ops.reshape(grad, [-1]) flat_grad_updated = state_ops.scatter_update( flat_grad, math_ops.range(start_index, end_index), new_flat_grad) return flat_grad_updated def _finish(self, state): var_dtype = self._variables[0].dtype.base_dtype # Update global step. global_step = self._get_global_step(state) update_global_step = state_ops.assign_add(global_step, 1.) # Update the first moment estimate. beta1 = state.get_hyper("beta1", dtype=var_dtype) moment1 = self._get_moment1(state) flat_grad = self._get_flat_grad(state) # moment1_t := beta1 * moment1_{t-1} + (1 - beta1) * flat_grad_t update_moment1 = moment1.assign(beta1 * moment1 + (1. - beta1) * flat_grad) # Update the gradient buffer. window = state.get_hyper("window") grad_buffer = self._get_grad_buffer(state) next_grad_index = math_ops.floormod( math_ops.cast(update_global_step - 1., dtypes.int32), window) # grad_buffer[(t-1) % window] := moment1_t update_grad_buffer = state_ops.scatter_update(grad_buffer, next_grad_index, update_moment1) # Compute the update step. eps = state.get_hyper("eps", dtype=var_dtype) svd_eps = state.get_hyper("svd_eps", dtype=var_dtype) sigma_eps = state.get_hyper("sigma_eps", dtype=var_dtype) lr = state.get_hyper("lr", dtype=var_dtype) denom = math_ops.sqrt( math_ops.minimum( ops.convert_to_tensor(update_global_step), ops.convert_to_tensor(math_ops.cast(window, dtype=var_dtype)))) moment1_2d = array_ops.expand_dims(update_moment1, -1) # m = grad_buffer^T / sqrt(min(t, window)) # m has shape [model dimension, window], where model dimension is the sum # of the dimensions of the flattened variables. m = array_ops.transpose(math_ops.divide(update_grad_buffer, denom)) # sigma, u, _ = SVD(m^Tm + I * svd_eps) mm = math_ops.matmul(m, m, transpose_a=True) damping = math_ops.cast(linalg_ops.eye(window), dtype=var_dtype) * svd_eps sigma, u, _ = linalg_ops.svd(mm + damping) sigma_sqrt = math_ops.sqrt(sigma) sigma_sqrt_min = math_ops.reduce_min(sigma_sqrt) # sigma_sqrt_inv = 1 / (\sqrt{sigma} + sigma_eps) ^ 3 # We add sigma_eps to alleviate numerical instability. # Note that (m^Tm)^(-3/2) = u diag(sigma_sqrt_inv) u^T. sigma_sqrt_inv = math_ops.divide( math_ops.cast(1.0, dtype=var_dtype), math_ops.pow(sigma_sqrt + sigma_eps, 3)) # In full matrix AdaGrad, the update step computes (mm^T)^(-1/2)g, where the # inversion of a model dimension by model dimension matrix is needed. To # speed up this computation we calculate the following instead: # m(m^Tm)^(-3/2)m^T moment1 = m u diag(sigma_sqrt_inv) u^T m^T moment1. new_step = array_ops.expand_dims( array_ops.zeros(flat_grad.get_shape(), dtype=var_dtype), -1) head = math_ops.matmul( m, math_ops.matmul( u, math_ops.matmul( array_ops.diag(sigma_sqrt_inv), math_ops.matmul( u, math_ops.matmul(m, moment1_2d, transpose_a=True), transpose_a=True)))) # When inverting (mm^t)^(1/2), we also add epsilon * I regularization for # degenerate cases. We expand ((mm^t)^(1/2) + epsilon * I)^(-1) using # Woodbury's identity. # For full derivation please see paper at # https://arxiv.org/pdf/1806.02958.pdf tail = moment1_2d - math_ops.matmul( m, math_ops.matmul( u, math_ops.matmul( array_ops.diag( math_ops.divide(math_ops.cast(1.0, dtype=var_dtype), sigma)), math_ops.matmul( u, math_ops.matmul(m, moment1_2d, transpose_a=True), transpose_a=True)))) scaled_tail = math_ops.divide(tail, sigma_sqrt_min) update_new_step = control_flow_ops.cond( sigma_sqrt_min > eps, lambda: math_ops.add(head, scaled_tail), lambda: math_ops.add(new_step, head)) # Update each variable. update_step = [] for var in self._variables: dim = self.shape_dict[var.name] start_index = self.index_dict[var.name] end_index = start_index + dim var_update_correct_shape = array_ops.reshape( update_new_step[start_index:end_index], var.get_shape()) var_updated = state_ops.assign_sub(var, lr * var_update_correct_shape) update_step.append(var_updated) return control_flow_ops.group(update_step)
tensorflow-master
tensorflow/contrib/opt/python/training/ggt.py
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Adam rewrite to use global step for computing beta1 & beta2 accumulation.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import resource_variable_ops from tensorflow.python.ops import state_ops from tensorflow.python.training import optimizer from tensorflow.python.training import training_ops from tensorflow.python.util.tf_export import tf_export @tf_export("train.AdamOptimizer") class AdamGSOptimizer(optimizer.Optimizer): """Optimizer that implements the Adam algorithm. See [Kingma et al., 2014](http://arxiv.org/abs/1412.6980) ([pdf](http://arxiv.org/pdf/1412.6980.pdf)). """ def __init__(self, global_step=0, learning_rate=0.001, beta1=0.9, beta2=0.999, epsilon=1e-8, use_locking=False, name="Adam"): r"""Construct a new Adam optimizer. Branched from tf.train.AdamOptimizer. The only difference is to pass global step for computing beta1 and beta2 accumulators, instead of having optimizer keep its own independent beta1 and beta2 accumulators as non-slot variables. Initialization: $$m_0 := 0 \text{(Initialize initial 1st moment vector)}$$ $$v_0 := 0 \text{(Initialize initial 2nd moment vector)}$$ $$t := 0 \text{(Initialize timestep)}$$ The update rule for `variable` with gradient `g` uses an optimization described at the end of section2 of the paper: $$t := t + 1$$ $$lr_t := \text{learning\_rate} * \sqrt{1 - beta_2^t} / (1 - beta_1^t)$$ $$m_t := beta_1 * m_{t-1} + (1 - beta_1) * g$$ $$v_t := beta_2 * v_{t-1} + (1 - beta_2) * g * g$$ $$variable := variable - lr_t * m_t / (\sqrt{v_t} + \epsilon)$$ The default value of 1e-8 for epsilon might not be a good default in general. For example, when training an Inception network on ImageNet a current good choice is 1.0 or 0.1. Note that since AdamOptimizer uses the formulation just before Section 2.1 of the Kingma and Ba paper rather than the formulation in Algorithm 1, the "epsilon" referred to here is "epsilon hat" in the paper. The sparse implementation of this algorithm (used when the gradient is an IndexedSlices object, typically because of `tf.gather` or an embedding lookup in the forward pass) does apply momentum to variable slices even if they were not used in the forward pass (meaning they have a gradient equal to zero). Momentum decay (beta1) is also applied to the entire momentum accumulator. This means that the sparse behavior is equivalent to the dense behavior (in contrast to some momentum implementations which ignore momentum unless a variable slice was actually used). Args: global_step: tensorflow variable indicating the step. learning_rate: A Tensor or a floating point value. The learning rate. beta1: A float value or a constant float tensor. The exponential decay rate for the 1st moment estimates. beta2: A float value or a constant float tensor. The exponential decay rate for the 2nd moment estimates. epsilon: A small constant for numerical stability. This epsilon is "epsilon hat" in the Kingma and Ba paper (in the formula just before Section 2.1), not the epsilon in Algorithm 1 of the paper. use_locking: If True use locks for update operations. name: Optional name for the operations created when applying gradients. Defaults to "Adam". @compatibility(eager) When eager execution is enabled, `learning_rate`, `beta1`, `beta2`, and `epsilon` can each be a callable that takes no arguments and returns the actual value to use. This can be useful for changing these values across different invocations of optimizer functions. @end_compatibility """ super(AdamGSOptimizer, self).__init__(use_locking, name) self._lr = learning_rate self._beta1 = beta1 self._beta2 = beta2 self._epsilon = epsilon self._global_step = global_step self._global_step_on_worker = None # Tensor versions of the constructor arguments, created in _prepare(). self._lr_t = None self._beta1_t = None self._beta2_t = None self._epsilon_t = None def _get_beta_accumulators(self): return (math_ops.pow(self._beta1_t, self._global_step_on_worker), math_ops.pow(self._beta2_t, self._global_step_on_worker)) def _create_slots(self, var_list): # Create slots for the first and second moments. for v in var_list: self._zeros_slot(v, "m", self._name) self._zeros_slot(v, "v", self._name) def _prepare(self): lr = self._call_if_callable(self._lr) beta1 = self._call_if_callable(self._beta1) beta2 = self._call_if_callable(self._beta2) epsilon = self._call_if_callable(self._epsilon) self._lr_t = ops.convert_to_tensor(lr, name="learning_rate") self._beta1_t = ops.convert_to_tensor(beta1, name="beta1") self._beta2_t = ops.convert_to_tensor(beta2, name="beta2") self._epsilon_t = ops.convert_to_tensor(epsilon, name="epsilon") # Performance optimization so that worker creates a copy of the global step # to avoid overloading the parameter server holding the global step. self._global_step_on_worker = math_ops.cast( array_ops.identity(self._global_step) + 1, dtypes.float32) def _apply_dense(self, grad, var): m = self.get_slot(var, "m") v = self.get_slot(var, "v") beta1_power, beta2_power = self._get_beta_accumulators() return training_ops.apply_adam( var, m, v, math_ops.cast(beta1_power, var.dtype.base_dtype), math_ops.cast(beta2_power, var.dtype.base_dtype), math_ops.cast(self._lr_t, var.dtype.base_dtype), math_ops.cast(self._beta1_t, var.dtype.base_dtype), math_ops.cast(self._beta2_t, var.dtype.base_dtype), math_ops.cast(self._epsilon_t, var.dtype.base_dtype), grad, use_locking=self._use_locking).op def _resource_apply_dense(self, grad, var): m = self.get_slot(var, "m") v = self.get_slot(var, "v") beta1_power, beta2_power = self._get_beta_accumulators() return training_ops.resource_apply_adam( var.handle, m.handle, v.handle, math_ops.cast(beta1_power, grad.dtype.base_dtype), math_ops.cast(beta2_power, grad.dtype.base_dtype), math_ops.cast(self._lr_t, grad.dtype.base_dtype), math_ops.cast(self._beta1_t, grad.dtype.base_dtype), math_ops.cast(self._beta2_t, grad.dtype.base_dtype), math_ops.cast(self._epsilon_t, grad.dtype.base_dtype), grad, use_locking=self._use_locking) def _apply_sparse_shared(self, grad, var, indices, scatter_add): beta1_power, beta2_power = self._get_beta_accumulators() beta1_power = math_ops.cast(beta1_power, var.dtype.base_dtype) beta2_power = math_ops.cast(beta2_power, var.dtype.base_dtype) lr_t = math_ops.cast(self._lr_t, var.dtype.base_dtype) beta1_t = math_ops.cast(self._beta1_t, var.dtype.base_dtype) beta2_t = math_ops.cast(self._beta2_t, var.dtype.base_dtype) epsilon_t = math_ops.cast(self._epsilon_t, var.dtype.base_dtype) lr = (lr_t * math_ops.sqrt(1 - beta2_power) / (1 - beta1_power)) # m_t = beta1 * m + (1 - beta1) * g_t m = self.get_slot(var, "m") m_scaled_g_values = grad * (1 - beta1_t) m_t = state_ops.assign(m, m * beta1_t, use_locking=self._use_locking) with ops.control_dependencies([m_t]): m_t = scatter_add(m, indices, m_scaled_g_values) # v_t = beta2 * v + (1 - beta2) * (g_t * g_t) v = self.get_slot(var, "v") v_scaled_g_values = (grad * grad) * (1 - beta2_t) v_t = state_ops.assign(v, v * beta2_t, use_locking=self._use_locking) with ops.control_dependencies([v_t]): v_t = scatter_add(v, indices, v_scaled_g_values) v_sqrt = math_ops.sqrt(v_t) var_update = state_ops.assign_sub( var, lr * m_t / (v_sqrt + epsilon_t), use_locking=self._use_locking) return control_flow_ops.group(*[var_update, m_t, v_t]) def _apply_sparse(self, grad, var): return self._apply_sparse_shared( grad.values, var, grad.indices, lambda x, i, v: state_ops.scatter_add( # pylint: disable=g-long-lambda x, i, v, use_locking=self._use_locking)) def _resource_scatter_add(self, x, i, v): with ops.control_dependencies( [resource_variable_ops.resource_scatter_add(x.handle, i, v)]): return x.value() def _resource_apply_sparse(self, grad, var, indices): return self._apply_sparse_shared(grad, var, indices, self._resource_scatter_add)
tensorflow-master
tensorflow/contrib/opt/python/training/adam_gs_optimizer.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Implementation of PowerSign.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import math from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import state_ops from tensorflow.python.training import optimizer from tensorflow.python.training import training_ops class PowerSignOptimizer(optimizer.Optimizer): """Optimizer that implements the PowerSign update. See [Bello et al., ICML2017], [Neural Optimizer Search with RL](https://arxiv.org/abs/1709.07417). """ def __init__(self, learning_rate=0.1, base=math.e, beta=0.9, sign_decay_fn=None, use_locking=False, name='PowerSignOptimizer'): """Constructs a new PowerSignOptimizer object. Initialization: ``` m_0 <- 0 (Initialize initial 1st moment vector) t <- 0 (Initialize timestep) ``` Update: ``` t <- t + 1 m_t <- beta1 * m_{t-1} + (1 - beta1) * g sign_decay <- sign_decay_fn(t) update <- base ** (sign_decay * sign(g) * sign(m)) * g variable <- variable - lr_t * update ``` Example usage for PowerSign-cd (PowerSign with cosine sign decay) ``` decay_steps = 1000 linear_decay_fn = sign_decays.get_cosine_decay_fn(decay_steps) opt = PowerSignOptimizer(learning_rate=0.1, sign_decay_fn=linear_decay_fn) ``` Args: learning_rate: learning_rate used when taking a step. base: base used in optimizer. beta: decay used for computing the moving average m. sign_decay_fn: decay function applied to the sign(g) sign(m) quantity. Takes global_step as an argument. See sign_decay.py for some examples. use_locking: If True, use locks for update operations. name: Optional name for the operations created iwhen applying gradients. Defaults to "PowerSignOptimizer". """ super(PowerSignOptimizer, self).__init__(use_locking, name) self._lr = learning_rate self._beta = beta self._logbase = math.log(base) self._sign_decay_fn = sign_decay_fn # Tensor versions of the constructor arguments, created in _prepare(). self._lr_t = None self._beta_t = None self._logbase_t = None def apply_gradients(self, grads_and_vars, global_step=None, name=None): if self._sign_decay_fn is not None: self._sign_decay_t = ops.convert_to_tensor( self._sign_decay_fn(global_step), name='sign_decay') return super(PowerSignOptimizer, self).apply_gradients( grads_and_vars, global_step=global_step, name=name) def _create_slots(self, var_list): # Create slots for the first moment. for v in var_list: self._zeros_slot(v, 'm', self._name) def _prepare(self): self._lr_t = ops.convert_to_tensor(self._lr, name='learning_rate') self._beta_t = ops.convert_to_tensor(self._beta, name='beta') self._logbase_t = ops.convert_to_tensor(self._logbase, name='logbase') if self._sign_decay_fn is None: self._sign_decay_t = ops.convert_to_tensor(1.0, name='sign_decay') def _apply_dense(self, grad, var): m = self.get_slot(var, 'm') return training_ops.apply_power_sign( var, m, math_ops.cast(self._lr_t, var.dtype.base_dtype), math_ops.cast(self._logbase_t, var.dtype.base_dtype), math_ops.cast(self._sign_decay_t, var.dtype.base_dtype), math_ops.cast(self._beta_t, var.dtype.base_dtype), grad, use_locking=self._use_locking).op def _resource_apply_dense(self, grad, var): m = self.get_slot(var, 'm') return training_ops.resource_apply_power_sign( var.handle, m.handle, math_ops.cast(self._lr_t, var.dtype.base_dtype), math_ops.cast(self._logbase_t, var.dtype.base_dtype), math_ops.cast(self._sign_decay_t, var.dtype.base_dtype), math_ops.cast(self._beta_t, var.dtype.base_dtype), grad, use_locking=self._use_locking) def _apply_sparse(self, grad, var): lr_t = math_ops.cast(self._lr_t, var.dtype.base_dtype) beta_t = math_ops.cast(self._beta_t, var.dtype.base_dtype) logbase_t = math_ops.cast(self._logbase_t, var.dtype.base_dtype) e_t = math_ops.cast(math.e, var.dtype.base_dtype) m = self.get_slot(var, 'm') m_t = state_ops.assign( m, (m * beta_t) + (grad * (1 - beta_t)), use_locking=self._use_locking) sign_g = ops.IndexedSlices( math_ops.sign(grad.values), grad.indices, dense_shape=grad.dense_shape) sign_gm = ops.IndexedSlices( array_ops.gather(math_ops.sign(m_t), sign_g.indices) * sign_g.values, sign_g.indices, dense_shape=sign_g.dense_shape) sign_decayed = math_ops.cast( self._sign_decay_t, var.dtype.base_dtype) multiplier_values = math_ops.pow( e_t, logbase_t * sign_decayed * sign_gm.values) multiplier = ops.IndexedSlices( multiplier_values, sign_gm.indices, dense_shape=sign_gm.dense_shape) final_update = ops.IndexedSlices( lr_t * multiplier.values * grad.values, multiplier.indices, dense_shape=multiplier.dense_shape) var_update = state_ops.scatter_sub( var, final_update.indices, final_update.values, use_locking=self._use_locking) return control_flow_ops.group(* [var_update, m_t])
tensorflow-master
tensorflow/contrib/opt/python/training/powersign.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Delegating optimizer to clip norm for specified variables.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import contextlib from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import clip_ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.platform import tf_logging as logging from tensorflow.python.training import optimizer __all__ = ["VariableClippingOptimizer"] class VariableClippingOptimizer(optimizer.Optimizer): """Wrapper optimizer that clips the norm of specified variables after update. This optimizer delegates all aspects of gradient calculation and application to an underlying optimizer. After applying gradients, this optimizer then clips the variable to have a maximum L2 norm along specified dimensions. NB: this is quite different from clipping the norm of the gradients. Multiple instances of `VariableClippingOptimizer` may be chained to specify different max norms for different subsets of variables. This is more efficient at serving-time than using normalization during embedding lookup, at the expense of more expensive training and fewer guarantees about the norms. @@__init__ """ def __init__(self, opt, vars_to_clip_dims, max_norm, use_locking=False, colocate_clip_ops_with_vars=False, name="VariableClipping"): """Construct a new clip-norm optimizer. Args: opt: The actual optimizer that will be used to compute and apply the gradients. Must be one of the Optimizer classes. vars_to_clip_dims: A dict with keys as Variables and values as lists of dimensions along which to compute the L2-norm. See `tf.clip_by_norm` for more details. max_norm: The L2-norm to clip to, for all variables specified. use_locking: If `True` use locks for clip update operations. colocate_clip_ops_with_vars: If `True`, try colocating the clip norm ops with the corresponding variable. name: Optional name prefix for the operations created when applying gradients. Defaults to "VariableClipping". """ super(VariableClippingOptimizer, self).__init__(use_locking, name) self._opt = opt # Defensive copy of input dict self._vars_to_clip_dims = { var: clip_dims[:] for var, clip_dims in vars_to_clip_dims.items()} self._max_norm = max_norm self._colocate_clip_ops_with_vars = colocate_clip_ops_with_vars def compute_gradients(self, *args, **kwargs): return self._opt.compute_gradients(*args, **kwargs) def get_slot(self, *args, **kwargs): return self._opt.get_slot(*args, **kwargs) def get_slot_names(self, *args, **kwargs): return self._opt.get_slot_names(*args, **kwargs) def apply_gradients(self, grads_and_vars, global_step=None, name=None): with ops.name_scope(name, self._name) as name: update_op = self._opt.apply_gradients( grads_and_vars, global_step=global_step) clip_update_ops = [] with ops.control_dependencies([update_op]): for grad, var in grads_and_vars: if grad is None or var not in self._vars_to_clip_dims: continue with ops.name_scope("clip_" + var.op.name): if isinstance(grad, ops.Tensor): clip_update_ops.append(self._clip_dense(var)) else: clip_update_ops.append(self._clip_sparse(grad, var)) # In case no var was clipped, still need to run the update_op. return control_flow_ops.group(*([update_op] + clip_update_ops), name=name) def _clip_dense(self, var): with self._maybe_colocate_with(var): updated_var_value = var.read_value() normalized_var = clip_ops.clip_by_norm( updated_var_value, self._max_norm, self._vars_to_clip_dims[var]) delta = updated_var_value - normalized_var with ops.colocate_with(var): return var.assign_sub(delta, use_locking=self._use_locking) def _clip_sparse(self, grad, var): assert isinstance(grad, ops.IndexedSlices) clip_dims = self._vars_to_clip_dims[var] if 0 in clip_dims: logging.warning("Clipping norm across dims %s for %s is inefficient " "when including sparse dimension 0.", clip_dims, var.op.name) return self._clip_dense(var) with ops.colocate_with(var): var_subset = array_ops.gather(var, grad.indices) with self._maybe_colocate_with(var): normalized_var_subset = clip_ops.clip_by_norm( var_subset, self._max_norm, clip_dims) delta = ops.IndexedSlices( var_subset - normalized_var_subset, grad.indices, grad.dense_shape) with ops.colocate_with(var): return var.scatter_sub(delta, use_locking=self._use_locking) @contextlib.contextmanager def _maybe_colocate_with(self, var): """Context to colocate with `var` if `colocate_clip_ops_with_vars`.""" if self._colocate_clip_ops_with_vars: with ops.colocate_with(var): yield else: yield
tensorflow-master
tensorflow/contrib/opt/python/training/variable_clipping_optimizer.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Exposes the Python wrapper for StatSummarizer utility class. The wrapper implementation is in tensorflow/python/util/stat_summarizer.i for technical reasons, but it should be accessed via tf.contrib.stat_summarizer. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function # pylint: disable=unused-import,wildcard-import, line-too-long from tensorflow.python.pywrap_tensorflow import DeleteStatSummarizer from tensorflow.python.pywrap_tensorflow import NewStatSummarizer from tensorflow.python.pywrap_tensorflow import StatSummarizer from tensorflow.python.util.all_util import remove_undocumented _allowed_symbols = ['DeleteStatSummarizer', 'NewStatSummarizer', 'StatSummarizer'] remove_undocumented(__name__, _allowed_symbols)
tensorflow-master
tensorflow/contrib/stat_summarizer/__init__.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for StatSummarizer Python wrapper.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.core.protobuf import config_pb2 from tensorflow.python import pywrap_tensorflow from tensorflow.python.framework import constant_op from tensorflow.python.framework import ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import variables from tensorflow.python.platform import test class StatSummarizerTest(test.TestCase): def testStatSummarizer(self): with ops.Graph().as_default() as graph: matrix1 = constant_op.constant([[3., 3.]], name=r"m1") matrix2 = constant_op.constant([[2.], [2.]], name=r"m2") product = math_ops.matmul(matrix1, matrix2, name=r"product") graph_def = graph.as_graph_def() ss = pywrap_tensorflow.NewStatSummarizer(graph_def.SerializeToString()) with self.cached_session() as sess: sess.run(variables.global_variables_initializer()) for _ in range(20): run_metadata = config_pb2.RunMetadata() run_options = config_pb2.RunOptions( trace_level=config_pb2.RunOptions.FULL_TRACE) sess.run(product, options=run_options, run_metadata=run_metadata) ss.ProcessStepStatsStr(run_metadata.step_stats.SerializeToString()) output_string = ss.GetOutputString() print(output_string) # Test it recorded running the expected number of times. self.assertRegexpMatches(output_string, r"count=20") # Test that a header line got printed. self.assertRegexpMatches(output_string, r"====== .* ======") # Test that the nodes we added were analyzed. # The line for the op should contain both the op type (MatMul) # and the name of the node (product) self.assertRegexpMatches(output_string, r"MatMul.*product") self.assertRegexpMatches(output_string, r"Const.*m1") self.assertRegexpMatches(output_string, r"Const.*m2") # Test that a CDF summed to 100% self.assertRegexpMatches(output_string, r"100\.") pywrap_tensorflow.DeleteStatSummarizer(ss) if __name__ == "__main__": test.main()
tensorflow-master
tensorflow/contrib/stat_summarizer/python/stat_summarizer_test.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Linear-chain CRF layer. @@crf_binary_score @@crf_decode @@crf_log_likelihood @@crf_log_norm @@crf_multitag_sequence_score @@crf_sequence_score @@crf_unary_score @@CrfDecodeBackwardRnnCell @@CrfDecodeForwardRnnCell @@CrfForwardRnnCell @@viterbi_decode """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.contrib.crf.python.ops.crf import crf_binary_score from tensorflow.contrib.crf.python.ops.crf import crf_decode from tensorflow.contrib.crf.python.ops.crf import crf_log_likelihood from tensorflow.contrib.crf.python.ops.crf import crf_log_norm from tensorflow.contrib.crf.python.ops.crf import crf_multitag_sequence_score from tensorflow.contrib.crf.python.ops.crf import crf_sequence_score from tensorflow.contrib.crf.python.ops.crf import crf_unary_score from tensorflow.contrib.crf.python.ops.crf import CrfDecodeBackwardRnnCell from tensorflow.contrib.crf.python.ops.crf import CrfDecodeForwardRnnCell from tensorflow.contrib.crf.python.ops.crf import CrfForwardRnnCell from tensorflow.contrib.crf.python.ops.crf import viterbi_decode from tensorflow.python.util.all_util import remove_undocumented remove_undocumented(__name__)
tensorflow-master
tensorflow/contrib/crf/__init__.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Linear-chain CRF.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function
tensorflow-master
tensorflow/contrib/crf/python/__init__.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for CRF.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import itertools import numpy as np from tensorflow.contrib.crf.python.ops import crf from tensorflow.python.framework import constant_op from tensorflow.python.ops import array_ops from tensorflow.python.ops import math_ops from tensorflow.python.platform import test class CrfTest(test.TestCase): def calculateSequenceScore(self, inputs, transition_params, tag_indices, sequence_lengths): expected_unary_score = sum( inputs[i][tag_indices[i]] for i in range(sequence_lengths)) expected_binary_score = sum( transition_params[tag_indices[i], tag_indices[i + 1]] for i in range(sequence_lengths - 1)) return expected_unary_score + expected_binary_score def testCrfSequenceScore(self): transition_params = np.array( [[-3, 5, -2], [3, 4, 1], [1, 2, 1]], dtype=np.float32) # Test both the length-1 and regular cases. sequence_lengths_list = [ np.array(3, dtype=np.int32), np.array(1, dtype=np.int32) ] inputs_list = [ np.array([[4, 5, -3], [3, -1, 3], [-1, 2, 1], [0, 0, 0]], dtype=np.float32), np.array([[4, 5, -3]], dtype=np.float32), ] tag_indices_list = [ np.array([1, 2, 1, 0], dtype=np.int32), np.array([1], dtype=np.int32) ] for sequence_lengths, inputs, tag_indices in zip(sequence_lengths_list, inputs_list, tag_indices_list): with self.cached_session() as sess: sequence_score = crf.crf_sequence_score( inputs=array_ops.expand_dims(inputs, 0), tag_indices=array_ops.expand_dims(tag_indices, 0), sequence_lengths=array_ops.expand_dims(sequence_lengths, 0), transition_params=constant_op.constant(transition_params)) sequence_score = array_ops.squeeze(sequence_score, [0]) tf_sequence_score = sess.run(sequence_score) expected_sequence_score = self.calculateSequenceScore( inputs, transition_params, tag_indices, sequence_lengths) self.assertAllClose(tf_sequence_score, expected_sequence_score) def testCrfMultiTagSequenceScore(self): transition_params = np.array( [[-3, 5, -2], [3, 4, 1], [1, 2, 1]], dtype=np.float32) # Test both the length-1 and regular cases. sequence_lengths_list = [ np.array(3, dtype=np.int32), np.array(1, dtype=np.int32) ] inputs_list = [ np.array([[4, 5, -3], [3, -1, 3], [-1, 2, 1], [0, 0, 0]], dtype=np.float32), np.array([[4, 5, -3]], dtype=np.float32), ] tag_bitmap_list = [ np.array( [[True, True, False], [True, False, True], [False, True, True], [True, False, True]], dtype=np.bool), np.array([[True, True, False]], dtype=np.bool) ] for sequence_lengths, inputs, tag_bitmap in zip( sequence_lengths_list, inputs_list, tag_bitmap_list): with self.cached_session() as sess: sequence_score = crf.crf_multitag_sequence_score( inputs=array_ops.expand_dims(inputs, 0), tag_bitmap=array_ops.expand_dims(tag_bitmap, 0), sequence_lengths=array_ops.expand_dims(sequence_lengths, 0), transition_params=constant_op.constant(transition_params)) sequence_score = array_ops.squeeze(sequence_score, [0]) tf_sum_sequence_score = sess.run(sequence_score) all_indices_list = [ single_index_bitmap.nonzero()[0] for single_index_bitmap in tag_bitmap[:sequence_lengths] ] expected_sequence_scores = [ self.calculateSequenceScore(inputs, transition_params, indices, sequence_lengths) for indices in itertools.product(*all_indices_list) ] expected_log_sum_exp_sequence_scores = np.logaddexp.reduce( expected_sequence_scores) self.assertAllClose(tf_sum_sequence_score, expected_log_sum_exp_sequence_scores) def testCrfUnaryScore(self): inputs = np.array( [[4, 5, -3], [3, -1, 3], [-1, 2, 1], [0, 0, 0]], dtype=np.float32) for dtype in (np.int32, np.int64): tag_indices = np.array([1, 2, 1, 0], dtype=dtype) sequence_lengths = np.array(3, dtype=np.int32) with self.cached_session() as sess: unary_score = crf.crf_unary_score( tag_indices=array_ops.expand_dims(tag_indices, 0), sequence_lengths=array_ops.expand_dims(sequence_lengths, 0), inputs=array_ops.expand_dims(inputs, 0)) unary_score = array_ops.squeeze(unary_score, [0]) tf_unary_score = sess.run(unary_score) expected_unary_score = sum(inputs[i][tag_indices[i]] for i in range(sequence_lengths)) self.assertAllClose(tf_unary_score, expected_unary_score) def testCrfBinaryScore(self): tag_indices = np.array([1, 2, 1, 0], dtype=np.int32) transition_params = np.array( [[-3, 5, -2], [3, 4, 1], [1, 2, 1]], dtype=np.float32) sequence_lengths = np.array(3, dtype=np.int32) with self.cached_session() as sess: binary_score = crf.crf_binary_score( tag_indices=array_ops.expand_dims(tag_indices, 0), sequence_lengths=array_ops.expand_dims(sequence_lengths, 0), transition_params=constant_op.constant(transition_params)) binary_score = array_ops.squeeze(binary_score, [0]) tf_binary_score = sess.run(binary_score) expected_binary_score = sum( transition_params[tag_indices[i], tag_indices[i + 1]] for i in range(sequence_lengths - 1)) self.assertAllClose(tf_binary_score, expected_binary_score) def testCrfLogNorm(self): transition_params = np.array( [[-3, 5, -2], [3, 4, 1], [1, 2, 1]], dtype=np.float32) # Test both the length-1 and regular cases. sequence_lengths_list = [ np.array(3, dtype=np.int32), np.array(1, dtype=np.int64) ] inputs_list = [ np.array([[4, 5, -3], [3, -1, 3], [-1, 2, 1], [0, 0, 0]], dtype=np.float32), np.array([[3, -1, 3]], dtype=np.float32), ] tag_indices_list = [ np.array([1, 2, 1, 0], dtype=np.int32), np.array([2], dtype=np.int32) ] for sequence_lengths, inputs, tag_indices in zip(sequence_lengths_list, inputs_list, tag_indices_list): num_words = inputs.shape[0] num_tags = inputs.shape[1] with self.cached_session() as sess: all_sequence_scores = [] # Compare the dynamic program with brute force computation. for tag_indices in itertools.product( range(num_tags), repeat=sequence_lengths): tag_indices = list(tag_indices) tag_indices.extend([0] * (num_words - sequence_lengths)) all_sequence_scores.append( crf.crf_sequence_score( inputs=array_ops.expand_dims(inputs, 0), tag_indices=array_ops.expand_dims(tag_indices, 0), sequence_lengths=array_ops.expand_dims(sequence_lengths, 0), transition_params=constant_op.constant(transition_params))) brute_force_log_norm = math_ops.reduce_logsumexp(all_sequence_scores) log_norm = crf.crf_log_norm( inputs=array_ops.expand_dims(inputs, 0), sequence_lengths=array_ops.expand_dims(sequence_lengths, 0), transition_params=constant_op.constant(transition_params)) log_norm = array_ops.squeeze(log_norm, [0]) tf_brute_force_log_norm, tf_log_norm = sess.run( [brute_force_log_norm, log_norm]) self.assertAllClose(tf_log_norm, tf_brute_force_log_norm) def testCrfLogNormZeroSeqLength(self): """ Test `crf_log_norm` when `sequence_lengths` contains one or more zeros. """ with self.cached_session() as sess: inputs = constant_op.constant(np.ones([2, 10, 5], dtype=np.float32)) transition_params = constant_op.constant(np.ones([5, 5], dtype=np.float32)) sequence_lengths = constant_op.constant(np.zeros([2], dtype=np.int32)) expected_log_norm = np.zeros([2], dtype=np.float32) log_norm = crf.crf_log_norm(inputs, sequence_lengths, transition_params) tf_log_norm = sess.run(log_norm) self.assertAllClose(tf_log_norm, expected_log_norm) def testCrfLogLikelihood(self): inputs = np.array( [[4, 5, -3], [3, -1, 3], [-1, 2, 1], [0, 0, 0]], dtype=np.float32) transition_params = np.array( [[-3, 5, -2], [3, 4, 1], [1, 2, 1]], dtype=np.float32) sequence_lengths = np.array(3, dtype=np.int32) num_words = inputs.shape[0] num_tags = inputs.shape[1] with self.cached_session() as sess: all_sequence_log_likelihoods = [] # Make sure all probabilities sum to 1. for tag_indices in itertools.product( range(num_tags), repeat=sequence_lengths): tag_indices = list(tag_indices) tag_indices.extend([0] * (num_words - sequence_lengths)) sequence_log_likelihood, _ = crf.crf_log_likelihood( inputs=array_ops.expand_dims(inputs, 0), tag_indices=array_ops.expand_dims(tag_indices, 0), sequence_lengths=array_ops.expand_dims(sequence_lengths, 0), transition_params=constant_op.constant(transition_params)) all_sequence_log_likelihoods.append(sequence_log_likelihood) total_log_likelihood = math_ops.reduce_logsumexp( all_sequence_log_likelihoods) tf_total_log_likelihood = sess.run(total_log_likelihood) self.assertAllClose(tf_total_log_likelihood, 0.0) def testViterbiDecode(self): inputs = np.array( [[4, 5, -3], [3, -1, 3], [-1, 2, 1], [0, 0, 0]], dtype=np.float32) transition_params = np.array( [[-3, 5, -2], [3, 4, 1], [1, 2, 1]], dtype=np.float32) sequence_lengths = np.array(3, dtype=np.int32) num_words = inputs.shape[0] num_tags = inputs.shape[1] with self.cached_session() as sess: all_sequence_scores = [] all_sequences = [] # Compare the dynamic program with brute force computation. for tag_indices in itertools.product( range(num_tags), repeat=sequence_lengths): tag_indices = list(tag_indices) tag_indices.extend([0] * (num_words - sequence_lengths)) all_sequences.append(tag_indices) sequence_score = crf.crf_sequence_score( inputs=array_ops.expand_dims(inputs, 0), tag_indices=array_ops.expand_dims(tag_indices, 0), sequence_lengths=array_ops.expand_dims(sequence_lengths, 0), transition_params=constant_op.constant(transition_params)) sequence_score = array_ops.squeeze(sequence_score, [0]) all_sequence_scores.append(sequence_score) tf_all_sequence_scores = sess.run(all_sequence_scores) expected_max_sequence_index = np.argmax(tf_all_sequence_scores) expected_max_sequence = all_sequences[expected_max_sequence_index] expected_max_score = tf_all_sequence_scores[expected_max_sequence_index] actual_max_sequence, actual_max_score = crf.viterbi_decode( inputs[:sequence_lengths], transition_params) self.assertAllClose(actual_max_score, expected_max_score) self.assertEqual(actual_max_sequence, expected_max_sequence[:sequence_lengths]) def testCrfDecode(self): transition_params = np.array( [[-3, 5, -2], [3, 4, 1], [1, 2, 1]], dtype=np.float32) # Test both the length-1 and regular cases. sequence_lengths_list = [ np.array(3, dtype=np.int32), np.array(1, dtype=np.int64) ] inputs_list = [ np.array([[4, 5, -3], [3, -1, 3], [-1, 2, 1], [0, 0, 0]], dtype=np.float32), np.array([[-1, 2, 1]], dtype=np.float32), ] tag_indices_list = [ np.array([1, 2, 1, 0], dtype=np.int32), np.array([2], dtype=np.int32) ] for sequence_lengths, inputs, tag_indices in zip(sequence_lengths_list, inputs_list, tag_indices_list): num_words = inputs.shape[0] num_tags = inputs.shape[1] with self.cached_session() as sess: all_sequence_scores = [] all_sequences = [] # Compare the dynamic program with brute force computation. for tag_indices in itertools.product( range(num_tags), repeat=sequence_lengths): tag_indices = list(tag_indices) tag_indices.extend([0] * (num_words - sequence_lengths)) all_sequences.append(tag_indices) sequence_score = crf.crf_sequence_score( inputs=array_ops.expand_dims(inputs, 0), tag_indices=array_ops.expand_dims(tag_indices, 0), sequence_lengths=array_ops.expand_dims(sequence_lengths, 0), transition_params=constant_op.constant(transition_params)) sequence_score = array_ops.squeeze(sequence_score, [0]) all_sequence_scores.append(sequence_score) tf_all_sequence_scores = sess.run(all_sequence_scores) expected_max_sequence_index = np.argmax(tf_all_sequence_scores) expected_max_sequence = all_sequences[expected_max_sequence_index] expected_max_score = tf_all_sequence_scores[expected_max_sequence_index] actual_max_sequence, actual_max_score = crf.crf_decode( array_ops.expand_dims(inputs, 0), constant_op.constant(transition_params), array_ops.expand_dims(sequence_lengths, 0)) actual_max_sequence = array_ops.squeeze(actual_max_sequence, [0]) actual_max_score = array_ops.squeeze(actual_max_score, [0]) tf_actual_max_sequence, tf_actual_max_score = sess.run( [actual_max_sequence, actual_max_score]) self.assertAllClose(tf_actual_max_score, expected_max_score) self.assertEqual(list(tf_actual_max_sequence[:sequence_lengths]), expected_max_sequence[:sequence_lengths]) def testCrfDecodeZeroSeqLength(self): """ Test that crf_decode works when sequence_length contains one or more zeros. """ with self.cached_session() as sess: inputs = constant_op.constant(np.ones([2, 10, 5], dtype=np.float32)) transition_params = constant_op.constant(np.ones([5, 5], dtype=np.float32)) sequence_lengths = constant_op.constant(np.zeros([2], dtype=np.int32)) tags, scores = crf.crf_decode(inputs, transition_params, sequence_lengths) tf_tags, tf_scores = sess.run([tags, scores]) self.assertEqual(len(tf_tags.shape), 2) self.assertEqual(len(tf_scores.shape), 1) if __name__ == "__main__": test.main()
tensorflow-master
tensorflow/contrib/crf/python/kernel_tests/crf_test.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Module for constructing a linear-chain CRF. The following snippet is an example of a CRF layer on top of a batched sequence of unary scores (logits for every word). This example also decodes the most likely sequence at test time. There are two ways to do decoding. One is using crf_decode to do decoding in Tensorflow , and the other one is using viterbi_decode in Numpy. log_likelihood, transition_params = tf.contrib.crf.crf_log_likelihood( unary_scores, gold_tags, sequence_lengths) loss = tf.reduce_mean(-log_likelihood) train_op = tf.compat.v1.train.GradientDescentOptimizer(0.01).minimize(loss) # Decoding in Tensorflow. viterbi_sequence, viterbi_score = tf.contrib.crf.crf_decode( unary_scores, transition_params, sequence_lengths) tf_viterbi_sequence, tf_viterbi_score, _ = session.run( [viterbi_sequence, viterbi_score, train_op]) # Decoding in Numpy. tf_unary_scores, tf_sequence_lengths, tf_transition_params, _ = session.run( [unary_scores, sequence_lengths, transition_params, train_op]) for tf_unary_scores_, tf_sequence_length_ in zip(tf_unary_scores, tf_sequence_lengths): # Remove padding. tf_unary_scores_ = tf_unary_scores_[:tf_sequence_length_] # Compute the highest score and its tag sequence. tf_viterbi_sequence, tf_viterbi_score = tf.contrib.crf.viterbi_decode( tf_unary_scores_, tf_transition_params) """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import tensor_shape from tensorflow.python.layers import utils from tensorflow.python.ops import array_ops from tensorflow.python.ops import gen_array_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import rnn from tensorflow.python.ops import rnn_cell from tensorflow.python.ops import variable_scope as vs __all__ = [ "crf_sequence_score", "crf_log_norm", "crf_log_likelihood", "crf_unary_score", "crf_binary_score", "CrfForwardRnnCell", "viterbi_decode", "crf_decode", "CrfDecodeForwardRnnCell", "CrfDecodeBackwardRnnCell", "crf_multitag_sequence_score" ] def crf_sequence_score(inputs, tag_indices, sequence_lengths, transition_params): """Computes the unnormalized score for a tag sequence. Args: inputs: A [batch_size, max_seq_len, num_tags] tensor of unary potentials to use as input to the CRF layer. tag_indices: A [batch_size, max_seq_len] matrix of tag indices for which we compute the unnormalized score. sequence_lengths: A [batch_size] vector of true sequence lengths. transition_params: A [num_tags, num_tags] transition matrix. Returns: sequence_scores: A [batch_size] vector of unnormalized sequence scores. """ # If max_seq_len is 1, we skip the score calculation and simply gather the # unary potentials of the single tag. def _single_seq_fn(): batch_size = array_ops.shape(inputs, out_type=tag_indices.dtype)[0] example_inds = array_ops.reshape( math_ops.range(batch_size, dtype=tag_indices.dtype), [-1, 1]) sequence_scores = array_ops.gather_nd( array_ops.squeeze(inputs, [1]), array_ops.concat([example_inds, tag_indices], axis=1)) sequence_scores = array_ops.where(math_ops.less_equal(sequence_lengths, 0), array_ops.zeros_like(sequence_scores), sequence_scores) return sequence_scores def _multi_seq_fn(): # Compute the scores of the given tag sequence. unary_scores = crf_unary_score(tag_indices, sequence_lengths, inputs) binary_scores = crf_binary_score(tag_indices, sequence_lengths, transition_params) sequence_scores = unary_scores + binary_scores return sequence_scores return utils.smart_cond( pred=math_ops.equal( tensor_shape.dimension_value( inputs.shape[1]) or array_ops.shape(inputs)[1], 1), true_fn=_single_seq_fn, false_fn=_multi_seq_fn) def crf_multitag_sequence_score(inputs, tag_bitmap, sequence_lengths, transition_params): """Computes the unnormalized score of all tag sequences matching tag_bitmap. tag_bitmap enables more than one tag to be considered correct at each time step. This is useful when an observed output at a given time step is consistent with more than one tag, and thus the log likelihood of that observation must take into account all possible consistent tags. Using one-hot vectors in tag_bitmap gives results identical to crf_sequence_score. Args: inputs: A [batch_size, max_seq_len, num_tags] tensor of unary potentials to use as input to the CRF layer. tag_bitmap: A [batch_size, max_seq_len, num_tags] boolean tensor representing all active tags at each index for which to calculate the unnormalized score. sequence_lengths: A [batch_size] vector of true sequence lengths. transition_params: A [num_tags, num_tags] transition matrix. Returns: sequence_scores: A [batch_size] vector of unnormalized sequence scores. """ # If max_seq_len is 1, we skip the score calculation and simply gather the # unary potentials of all active tags. def _single_seq_fn(): filtered_inputs = array_ops.where( tag_bitmap, inputs, array_ops.fill(array_ops.shape(inputs), float("-inf"))) return math_ops.reduce_logsumexp( filtered_inputs, axis=[1, 2], keepdims=False) def _multi_seq_fn(): # Compute the logsumexp of all scores of sequences matching the given tags. filtered_inputs = array_ops.where( tag_bitmap, inputs, array_ops.fill(array_ops.shape(inputs), float("-inf"))) return crf_log_norm( inputs=filtered_inputs, sequence_lengths=sequence_lengths, transition_params=transition_params) return utils.smart_cond( pred=math_ops.equal( tensor_shape.dimension_value( inputs.shape[1]) or array_ops.shape(inputs)[1], 1), true_fn=_single_seq_fn, false_fn=_multi_seq_fn) def crf_log_norm(inputs, sequence_lengths, transition_params): """Computes the normalization for a CRF. Args: inputs: A [batch_size, max_seq_len, num_tags] tensor of unary potentials to use as input to the CRF layer. sequence_lengths: A [batch_size] vector of true sequence lengths. transition_params: A [num_tags, num_tags] transition matrix. Returns: log_norm: A [batch_size] vector of normalizers for a CRF. """ # Split up the first and rest of the inputs in preparation for the forward # algorithm. first_input = array_ops.slice(inputs, [0, 0, 0], [-1, 1, -1]) first_input = array_ops.squeeze(first_input, [1]) # If max_seq_len is 1, we skip the algorithm and simply reduce_logsumexp over # the "initial state" (the unary potentials). def _single_seq_fn(): log_norm = math_ops.reduce_logsumexp(first_input, [1]) # Mask `log_norm` of the sequences with length <= zero. log_norm = array_ops.where(math_ops.less_equal(sequence_lengths, 0), array_ops.zeros_like(log_norm), log_norm) return log_norm def _multi_seq_fn(): """Forward computation of alpha values.""" rest_of_input = array_ops.slice(inputs, [0, 1, 0], [-1, -1, -1]) # Compute the alpha values in the forward algorithm in order to get the # partition function. forward_cell = CrfForwardRnnCell(transition_params) # Sequence length is not allowed to be less than zero. sequence_lengths_less_one = math_ops.maximum( constant_op.constant(0, dtype=sequence_lengths.dtype), sequence_lengths - 1) _, alphas = rnn.dynamic_rnn( cell=forward_cell, inputs=rest_of_input, sequence_length=sequence_lengths_less_one, initial_state=first_input, dtype=dtypes.float32) log_norm = math_ops.reduce_logsumexp(alphas, [1]) # Mask `log_norm` of the sequences with length <= zero. log_norm = array_ops.where(math_ops.less_equal(sequence_lengths, 0), array_ops.zeros_like(log_norm), log_norm) return log_norm return utils.smart_cond( pred=math_ops.equal( tensor_shape.dimension_value( inputs.shape[1]) or array_ops.shape(inputs)[1], 1), true_fn=_single_seq_fn, false_fn=_multi_seq_fn) def crf_log_likelihood(inputs, tag_indices, sequence_lengths, transition_params=None): """Computes the log-likelihood of tag sequences in a CRF. Args: inputs: A [batch_size, max_seq_len, num_tags] tensor of unary potentials to use as input to the CRF layer. tag_indices: A [batch_size, max_seq_len] matrix of tag indices for which we compute the log-likelihood. sequence_lengths: A [batch_size] vector of true sequence lengths. transition_params: A [num_tags, num_tags] transition matrix, if available. Returns: log_likelihood: A [batch_size] `Tensor` containing the log-likelihood of each example, given the sequence of tag indices. transition_params: A [num_tags, num_tags] transition matrix. This is either provided by the caller or created in this function. """ # Get shape information. num_tags = tensor_shape.dimension_value(inputs.shape[2]) # Get the transition matrix if not provided. if transition_params is None: transition_params = vs.get_variable("transitions", [num_tags, num_tags]) sequence_scores = crf_sequence_score(inputs, tag_indices, sequence_lengths, transition_params) log_norm = crf_log_norm(inputs, sequence_lengths, transition_params) # Normalize the scores to get the log-likelihood per example. log_likelihood = sequence_scores - log_norm return log_likelihood, transition_params def crf_unary_score(tag_indices, sequence_lengths, inputs): """Computes the unary scores of tag sequences. Args: tag_indices: A [batch_size, max_seq_len] matrix of tag indices. sequence_lengths: A [batch_size] vector of true sequence lengths. inputs: A [batch_size, max_seq_len, num_tags] tensor of unary potentials. Returns: unary_scores: A [batch_size] vector of unary scores. """ batch_size = array_ops.shape(inputs)[0] max_seq_len = array_ops.shape(inputs)[1] num_tags = array_ops.shape(inputs)[2] flattened_inputs = array_ops.reshape(inputs, [-1]) offsets = array_ops.expand_dims( math_ops.range(batch_size) * max_seq_len * num_tags, 1) offsets += array_ops.expand_dims(math_ops.range(max_seq_len) * num_tags, 0) # Use int32 or int64 based on tag_indices' dtype. if tag_indices.dtype == dtypes.int64: offsets = math_ops.cast(offsets, dtypes.int64) flattened_tag_indices = array_ops.reshape(offsets + tag_indices, [-1]) unary_scores = array_ops.reshape( array_ops.gather(flattened_inputs, flattened_tag_indices), [batch_size, max_seq_len]) masks = array_ops.sequence_mask(sequence_lengths, maxlen=array_ops.shape(tag_indices)[1], dtype=dtypes.float32) unary_scores = math_ops.reduce_sum(unary_scores * masks, 1) return unary_scores def crf_binary_score(tag_indices, sequence_lengths, transition_params): """Computes the binary scores of tag sequences. Args: tag_indices: A [batch_size, max_seq_len] matrix of tag indices. sequence_lengths: A [batch_size] vector of true sequence lengths. transition_params: A [num_tags, num_tags] matrix of binary potentials. Returns: binary_scores: A [batch_size] vector of binary scores. """ # Get shape information. num_tags = transition_params.get_shape()[0] num_transitions = array_ops.shape(tag_indices)[1] - 1 # Truncate by one on each side of the sequence to get the start and end # indices of each transition. start_tag_indices = array_ops.slice(tag_indices, [0, 0], [-1, num_transitions]) end_tag_indices = array_ops.slice(tag_indices, [0, 1], [-1, num_transitions]) # Encode the indices in a flattened representation. flattened_transition_indices = start_tag_indices * num_tags + end_tag_indices flattened_transition_params = array_ops.reshape(transition_params, [-1]) # Get the binary scores based on the flattened representation. binary_scores = array_ops.gather(flattened_transition_params, flattened_transition_indices) masks = array_ops.sequence_mask(sequence_lengths, maxlen=array_ops.shape(tag_indices)[1], dtype=dtypes.float32) truncated_masks = array_ops.slice(masks, [0, 1], [-1, -1]) binary_scores = math_ops.reduce_sum(binary_scores * truncated_masks, 1) return binary_scores class CrfForwardRnnCell(rnn_cell.RNNCell): """Computes the alpha values in a linear-chain CRF. See http://www.cs.columbia.edu/~mcollins/fb.pdf for reference. """ def __init__(self, transition_params): """Initialize the CrfForwardRnnCell. Args: transition_params: A [num_tags, num_tags] matrix of binary potentials. This matrix is expanded into a [1, num_tags, num_tags] in preparation for the broadcast summation occurring within the cell. """ self._transition_params = array_ops.expand_dims(transition_params, 0) self._num_tags = tensor_shape.dimension_value(transition_params.shape[0]) @property def state_size(self): return self._num_tags @property def output_size(self): return self._num_tags def __call__(self, inputs, state, scope=None): """Build the CrfForwardRnnCell. Args: inputs: A [batch_size, num_tags] matrix of unary potentials. state: A [batch_size, num_tags] matrix containing the previous alpha values. scope: Unused variable scope of this cell. Returns: new_alphas, new_alphas: A pair of [batch_size, num_tags] matrices values containing the new alpha values. """ state = array_ops.expand_dims(state, 2) # This addition op broadcasts self._transitions_params along the zeroth # dimension and state along the second dimension. This performs the # multiplication of previous alpha values and the current binary potentials # in log space. transition_scores = state + self._transition_params new_alphas = inputs + math_ops.reduce_logsumexp(transition_scores, [1]) # Both the state and the output of this RNN cell contain the alphas values. # The output value is currently unused and simply satisfies the RNN API. # This could be useful in the future if we need to compute marginal # probabilities, which would require the accumulated alpha values at every # time step. return new_alphas, new_alphas def viterbi_decode(score, transition_params): """Decode the highest scoring sequence of tags outside of TensorFlow. This should only be used at test time. Args: score: A [seq_len, num_tags] matrix of unary potentials. transition_params: A [num_tags, num_tags] matrix of binary potentials. Returns: viterbi: A [seq_len] list of integers containing the highest scoring tag indices. viterbi_score: A float containing the score for the Viterbi sequence. """ trellis = np.zeros_like(score) backpointers = np.zeros_like(score, dtype=np.int32) trellis[0] = score[0] for t in range(1, score.shape[0]): v = np.expand_dims(trellis[t - 1], 1) + transition_params trellis[t] = score[t] + np.max(v, 0) backpointers[t] = np.argmax(v, 0) viterbi = [np.argmax(trellis[-1])] for bp in reversed(backpointers[1:]): viterbi.append(bp[viterbi[-1]]) viterbi.reverse() viterbi_score = np.max(trellis[-1]) return viterbi, viterbi_score class CrfDecodeForwardRnnCell(rnn_cell.RNNCell): """Computes the forward decoding in a linear-chain CRF. """ def __init__(self, transition_params): """Initialize the CrfDecodeForwardRnnCell. Args: transition_params: A [num_tags, num_tags] matrix of binary potentials. This matrix is expanded into a [1, num_tags, num_tags] in preparation for the broadcast summation occurring within the cell. """ self._transition_params = array_ops.expand_dims(transition_params, 0) self._num_tags = tensor_shape.dimension_value(transition_params.shape[0]) @property def state_size(self): return self._num_tags @property def output_size(self): return self._num_tags def __call__(self, inputs, state, scope=None): """Build the CrfDecodeForwardRnnCell. Args: inputs: A [batch_size, num_tags] matrix of unary potentials. state: A [batch_size, num_tags] matrix containing the previous step's score values. scope: Unused variable scope of this cell. Returns: backpointers: A [batch_size, num_tags] matrix of backpointers. new_state: A [batch_size, num_tags] matrix of new score values. """ # For simplicity, in shape comments, denote: # 'batch_size' by 'B', 'max_seq_len' by 'T' , 'num_tags' by 'O' (output). state = array_ops.expand_dims(state, 2) # [B, O, 1] # This addition op broadcasts self._transitions_params along the zeroth # dimension and state along the second dimension. # [B, O, 1] + [1, O, O] -> [B, O, O] transition_scores = state + self._transition_params # [B, O, O] new_state = inputs + math_ops.reduce_max(transition_scores, [1]) # [B, O] backpointers = math_ops.argmax(transition_scores, 1) backpointers = math_ops.cast(backpointers, dtype=dtypes.int32) # [B, O] return backpointers, new_state class CrfDecodeBackwardRnnCell(rnn_cell.RNNCell): """Computes backward decoding in a linear-chain CRF. """ def __init__(self, num_tags): """Initialize the CrfDecodeBackwardRnnCell. Args: num_tags: An integer. The number of tags. """ self._num_tags = num_tags @property def state_size(self): return 1 @property def output_size(self): return 1 def __call__(self, inputs, state, scope=None): """Build the CrfDecodeBackwardRnnCell. Args: inputs: A [batch_size, num_tags] matrix of backpointer of next step (in time order). state: A [batch_size, 1] matrix of tag index of next step. scope: Unused variable scope of this cell. Returns: new_tags, new_tags: A pair of [batch_size, num_tags] tensors containing the new tag indices. """ state = array_ops.squeeze(state, axis=[1]) # [B] batch_size = array_ops.shape(inputs)[0] b_indices = math_ops.range(batch_size) # [B] indices = array_ops.stack([b_indices, state], axis=1) # [B, 2] new_tags = array_ops.expand_dims( gen_array_ops.gather_nd(inputs, indices), # [B] axis=-1) # [B, 1] return new_tags, new_tags def crf_decode(potentials, transition_params, sequence_length): """Decode the highest scoring sequence of tags in TensorFlow. This is a function for tensor. Args: potentials: A [batch_size, max_seq_len, num_tags] tensor of unary potentials. transition_params: A [num_tags, num_tags] matrix of binary potentials. sequence_length: A [batch_size] vector of true sequence lengths. Returns: decode_tags: A [batch_size, max_seq_len] matrix, with dtype `tf.int32`. Contains the highest scoring tag indices. best_score: A [batch_size] vector, containing the score of `decode_tags`. """ # If max_seq_len is 1, we skip the algorithm and simply return the argmax tag # and the max activation. def _single_seq_fn(): squeezed_potentials = array_ops.squeeze(potentials, [1]) decode_tags = array_ops.expand_dims( math_ops.argmax(squeezed_potentials, axis=1), 1) best_score = math_ops.reduce_max(squeezed_potentials, axis=1) return math_ops.cast(decode_tags, dtype=dtypes.int32), best_score def _multi_seq_fn(): """Decoding of highest scoring sequence.""" # For simplicity, in shape comments, denote: # 'batch_size' by 'B', 'max_seq_len' by 'T' , 'num_tags' by 'O' (output). num_tags = tensor_shape.dimension_value(potentials.shape[2]) # Computes forward decoding. Get last score and backpointers. crf_fwd_cell = CrfDecodeForwardRnnCell(transition_params) initial_state = array_ops.slice(potentials, [0, 0, 0], [-1, 1, -1]) initial_state = array_ops.squeeze(initial_state, axis=[1]) # [B, O] inputs = array_ops.slice(potentials, [0, 1, 0], [-1, -1, -1]) # [B, T-1, O] # Sequence length is not allowed to be less than zero. sequence_length_less_one = math_ops.maximum( constant_op.constant(0, dtype=sequence_length.dtype), sequence_length - 1) backpointers, last_score = rnn.dynamic_rnn( # [B, T - 1, O], [B, O] crf_fwd_cell, inputs=inputs, sequence_length=sequence_length_less_one, initial_state=initial_state, time_major=False, dtype=dtypes.int32) backpointers = gen_array_ops.reverse_sequence( # [B, T - 1, O] backpointers, sequence_length_less_one, seq_dim=1) # Computes backward decoding. Extract tag indices from backpointers. crf_bwd_cell = CrfDecodeBackwardRnnCell(num_tags) initial_state = math_ops.cast(math_ops.argmax(last_score, axis=1), # [B] dtype=dtypes.int32) initial_state = array_ops.expand_dims(initial_state, axis=-1) # [B, 1] decode_tags, _ = rnn.dynamic_rnn( # [B, T - 1, 1] crf_bwd_cell, inputs=backpointers, sequence_length=sequence_length_less_one, initial_state=initial_state, time_major=False, dtype=dtypes.int32) decode_tags = array_ops.squeeze(decode_tags, axis=[2]) # [B, T - 1] decode_tags = array_ops.concat([initial_state, decode_tags], # [B, T] axis=1) decode_tags = gen_array_ops.reverse_sequence( # [B, T] decode_tags, sequence_length, seq_dim=1) best_score = math_ops.reduce_max(last_score, axis=1) # [B] return decode_tags, best_score return utils.smart_cond( pred=math_ops.equal(tensor_shape.dimension_value(potentials.shape[1]) or array_ops.shape(potentials)[1], 1), true_fn=_single_seq_fn, false_fn=_multi_seq_fn)
tensorflow-master
tensorflow/contrib/crf/python/ops/crf.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Ops for building a linear-chain CRF layer.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function
tensorflow-master
tensorflow/contrib/crf/python/ops/__init__.py
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """A library for performing constrained optimization in TensorFlow.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # pylint: disable=wildcard-import from tensorflow.contrib.constrained_optimization.python.candidates import * from tensorflow.contrib.constrained_optimization.python.constrained_minimization_problem import * from tensorflow.contrib.constrained_optimization.python.constrained_optimizer import * from tensorflow.contrib.constrained_optimization.python.external_regret_optimizer import * from tensorflow.contrib.constrained_optimization.python.swap_regret_optimizer import * # pylint: enable=wildcard-import from tensorflow.python.util.all_util import remove_undocumented _allowed_symbols = [ "AdditiveExternalRegretOptimizer", "AdditiveSwapRegretOptimizer", "ConstrainedMinimizationProblem", "ConstrainedOptimizer", "find_best_candidate_distribution", "find_best_candidate_index", "MultiplicativeSwapRegretOptimizer", ] remove_undocumented(__name__, _allowed_symbols)
tensorflow-master
tensorflow/contrib/constrained_optimization/__init__.py
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Defines `AdditiveExternalRegretOptimizer`. This optimizer minimizes a `ConstrainedMinimizationProblem` by introducing Lagrange multipliers, and using `tf.compat.v1.train.Optimizer`s to jointly optimize over the model parameters and Lagrange multipliers. For the purposes of constrained optimization, at least in theory, external-regret minimization suffices if the `ConstrainedMinimizationProblem` we're optimizing doesn't have any `proxy_constraints`, while swap-regret minimization should be used if `proxy_constraints` are present. For more specifics, please refer to: > Cotter, Jiang and Sridharan. "Two-Player Games for Efficient Non-Convex > Constrained Optimization". > [https://arxiv.org/abs/1804.06500](https://arxiv.org/abs/1804.06500) The formulation used by the AdditiveExternalRegretOptimizer--which is simply the usual Lagrangian formulation--can be found in Definition 1, and is discussed in Section 3. This optimizer is most similar to Algorithm 3 in Appendix C.3, with the two differences being that it uses proxy constraints (if they're provided) in the update of the model parameters, and uses `tf.compat.v1.train.Optimizer`s, instead of SGD, for the "inner" updates. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import abc import six from tensorflow.contrib.constrained_optimization.python import constrained_optimizer from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import standard_ops from tensorflow.python.ops import state_ops from tensorflow.python.training import optimizer as train_optimizer def _project_multipliers_wrt_euclidean_norm(multipliers, radius): """Projects its argument onto the feasible region. The feasible region is the set of all vectors with nonnegative elements that sum to at most `radius`. Args: multipliers: 1d tensor, the Lagrange multipliers to project. radius: float, the radius of the feasible region. Returns: The 1d tensor that results from projecting `multipliers` onto the feasible region w.r.t. the Euclidean norm. Raises: ValueError: if the `multipliers` tensor is not floating-point, does not have a fully-known shape, or is not one-dimensional. """ if not multipliers.dtype.is_floating: raise ValueError("multipliers must have a floating-point dtype") multipliers_shape = multipliers.get_shape() if multipliers_shape.ndims is None: raise ValueError("multipliers must have known shape") if multipliers_shape.ndims != 1: raise ValueError( "multipliers must be one dimensional (instead is %d-dimensional)" % multipliers_shape.ndims) dimension = multipliers_shape.dims[0].value if dimension is None: raise ValueError("multipliers must have fully-known shape") def while_loop_condition(iteration, multipliers, inactive, old_inactive): """Returns false if the while loop should terminate.""" del multipliers # Needed by the body, but not the condition. not_done = (iteration < dimension) not_converged = standard_ops.reduce_any( standard_ops.not_equal(inactive, old_inactive)) return standard_ops.logical_and(not_done, not_converged) def while_loop_body(iteration, multipliers, inactive, old_inactive): """Performs one iteration of the projection.""" del old_inactive # Needed by the condition, but not the body. iteration += 1 scale = standard_ops.minimum( 0.0, (radius - standard_ops.reduce_sum(multipliers)) / standard_ops.maximum(1.0, standard_ops.reduce_sum(inactive))) multipliers = multipliers + (scale * inactive) new_inactive = standard_ops.cast(multipliers > 0, multipliers.dtype) multipliers = multipliers * new_inactive return (iteration, multipliers, new_inactive, inactive) iteration = standard_ops.constant(0) inactive = standard_ops.ones_like(multipliers, dtype=multipliers.dtype) # We actually want a do-while loop, so we explicitly call while_loop_body() # once before tf.while_loop(). iteration, multipliers, inactive, old_inactive = while_loop_body( iteration, multipliers, inactive, inactive) iteration, multipliers, inactive, old_inactive = control_flow_ops.while_loop( while_loop_condition, while_loop_body, loop_vars=(iteration, multipliers, inactive, old_inactive), name="euclidean_projection") return multipliers @six.add_metaclass(abc.ABCMeta) class _ExternalRegretOptimizer(constrained_optimizer.ConstrainedOptimizer): """Base class representing an `_ExternalRegretOptimizer`. This class contains most of the logic for performing constrained optimization, minimizing external regret for the constraints player. What it *doesn't* do is keep track of the internal state (the Lagrange multipliers). Instead, the state is accessed via the _initial_state(), _lagrange_multipliers(), _constraint_grad_and_var() and _projection_op() methods. The reason for this is that we want to make it easy to implement different representations of the internal state. For more specifics, please refer to: > Cotter, Jiang and Sridharan. "Two-Player Games for Efficient Non-Convex > Constrained Optimization". > [https://arxiv.org/abs/1804.06500](https://arxiv.org/abs/1804.06500) The formulation used by `_ExternalRegretOptimizer`s--which is simply the usual Lagrangian formulation--can be found in Definition 1, and is discussed in Section 3. Such optimizers are most similar to Algorithm 3 in Appendix C.3. """ def __init__(self, optimizer, constraint_optimizer=None): """Constructs a new `_ExternalRegretOptimizer`. The difference between `optimizer` and `constraint_optimizer` (if the latter is provided) is that the former is used for learning the model parameters, while the latter us used for the Lagrange multipliers. If no `constraint_optimizer` is provided, then `optimizer` is used for both. Args: optimizer: tf.compat.v1.train.Optimizer, used to optimize the objective and proxy_constraints portion of the ConstrainedMinimizationProblem. If constraint_optimizer is not provided, this will also be used to optimize the Lagrange multipliers. constraint_optimizer: optional tf.compat.v1.train.Optimizer, used to optimize the Lagrange multipliers. Returns: A new `_ExternalRegretOptimizer`. """ super(_ExternalRegretOptimizer, self).__init__(optimizer=optimizer) self._constraint_optimizer = constraint_optimizer @property def constraint_optimizer(self): """Returns the `tf.compat.v1.train.Optimizer` used for the Lagrange multipliers.""" return self._constraint_optimizer @abc.abstractmethod def _initial_state(self, num_constraints): pass @abc.abstractmethod def _lagrange_multipliers(self, state): pass @abc.abstractmethod def _constraint_grad_and_var(self, state, gradient): pass @abc.abstractmethod def _projection_op(self, state, name=None): pass def _minimize_constrained(self, minimization_problem, global_step=None, var_list=None, gate_gradients=train_optimizer.Optimizer.GATE_OP, aggregation_method=None, colocate_gradients_with_ops=False, name=None, grad_loss=None): """Returns an `Operation` for minimizing the constrained problem. The `optimizer` constructor parameter will be used to update the model parameters, while the Lagrange multipliers will be updated using `constrained_optimizer` (if provided) or `optimizer` (if not). Args: minimization_problem: ConstrainedMinimizationProblem, the problem to optimize. global_step: as in `tf.compat.v1.train.Optimizer`'s `minimize` method. var_list: as in `tf.compat.v1.train.Optimizer`'s `minimize` method. gate_gradients: as in `tf.compat.v1.train.Optimizer`'s `minimize` method. aggregation_method: as in `tf.compat.v1.train.Optimizer`'s `minimize` method. colocate_gradients_with_ops: as in `tf.compat.v1.train.Optimizer`'s `minimize` method. name: as in `tf.compat.v1.train.Optimizer`'s `minimize` method. grad_loss: as in `tf.compat.v1.train.Optimizer`'s `minimize` method. Raises: ValueError: If the minimization_problem tensors have different dtypes. Returns: `Operation`, the train_op. """ objective = minimization_problem.objective constraints = minimization_problem.constraints proxy_constraints = minimization_problem.proxy_constraints if proxy_constraints is None: proxy_constraints = constraints # Make sure that the objective, constraints and proxy constraints all have # the same dtype. if (objective.dtype.base_dtype != constraints.dtype.base_dtype or objective.dtype.base_dtype != proxy_constraints.dtype.base_dtype): raise ValueError("objective, constraints and proxy_constraints must " "have the same dtype") # Flatten both constraints tensors to 1d. num_constraints = minimization_problem.num_constraints constraints = standard_ops.reshape(constraints, shape=(num_constraints,)) proxy_constraints = standard_ops.reshape( proxy_constraints, shape=(num_constraints,)) # We use a lambda to initialize the state so that, if this function call is # inside the scope of a tf.control_dependencies() block, the dependencies # will not be applied to the initializer. state = standard_ops.Variable( lambda: self._initial_state(num_constraints), trainable=False, name="external_regret_optimizer_state") multipliers = self._lagrange_multipliers(state) loss = ( objective + standard_ops.tensordot( standard_ops.cast(multipliers, proxy_constraints.dtype), proxy_constraints, 1)) multipliers_gradient = standard_ops.cast(constraints, multipliers.dtype) update_ops = [] if self.constraint_optimizer is None: # If we don't have a separate constraint_optimizer, then we use # self._optimizer for both the update of the model parameters, and that of # the internal state. grads_and_vars = self.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) grads_and_vars.append( self._constraint_grad_and_var(state, multipliers_gradient)) update_ops.append( self.optimizer.apply_gradients(grads_and_vars, name="update")) else: # If we have a separate constraint_optimizer, then we use self._optimizer # for the update of the model parameters, and self._constraint_optimizer # for that of the internal state. grads_and_vars = self.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) multiplier_grads_and_vars = [ self._constraint_grad_and_var(state, multipliers_gradient) ] gradients = [ gradient for gradient, _ in grads_and_vars + multiplier_grads_and_vars if gradient is not None ] with ops.control_dependencies(gradients): update_ops.append( self.optimizer.apply_gradients(grads_and_vars, name="update")) update_ops.append( self.constraint_optimizer.apply_gradients( multiplier_grads_and_vars, name="optimizer_state_update")) with ops.control_dependencies(update_ops): if global_step is None: # If we don't have a global step, just project, and we're done. return self._projection_op(state, name=name) else: # If we have a global step, then we need to increment it in addition to # projecting. projection_op = self._projection_op(state, name="project") with ops.colocate_with(global_step): global_step_op = state_ops.assign_add( global_step, 1, name="global_step_increment") return control_flow_ops.group(projection_op, global_step_op, name=name) class AdditiveExternalRegretOptimizer(_ExternalRegretOptimizer): """A `ConstrainedOptimizer` based on external-regret minimization. This `ConstrainedOptimizer` uses the given `tf.compat.v1.train.Optimizer`s to jointly minimize over the model parameters, and maximize over Lagrange multipliers, with the latter maximization using additive updates and an algorithm that minimizes external regret. For more specifics, please refer to: > Cotter, Jiang and Sridharan. "Two-Player Games for Efficient Non-Convex > Constrained Optimization". > [https://arxiv.org/abs/1804.06500](https://arxiv.org/abs/1804.06500) The formulation used by this optimizer--which is simply the usual Lagrangian formulation--can be found in Definition 1, and is discussed in Section 3. It is most similar to Algorithm 3 in Appendix C.3, with the two differences being that it uses proxy constraints (if they're provided) in the update of the model parameters, and uses `tf.compat.v1.train.Optimizer`s, instead of SGD, for the "inner" updates. """ def __init__(self, optimizer, constraint_optimizer=None, maximum_multiplier_radius=None): """Constructs a new `AdditiveExternalRegretOptimizer`. Args: optimizer: tf.compat.v1.train.Optimizer, used to optimize the objective and proxy_constraints portion of ConstrainedMinimizationProblem. If constraint_optimizer is not provided, this will also be used to optimize the Lagrange multipliers. constraint_optimizer: optional tf.compat.v1.train.Optimizer, used to optimize the Lagrange multipliers. maximum_multiplier_radius: float, an optional upper bound to impose on the sum of the Lagrange multipliers. Returns: A new `AdditiveExternalRegretOptimizer`. Raises: ValueError: If the maximum_multiplier_radius parameter is nonpositive. """ super(AdditiveExternalRegretOptimizer, self).__init__( optimizer=optimizer, constraint_optimizer=constraint_optimizer) if maximum_multiplier_radius and (maximum_multiplier_radius <= 0.0): raise ValueError("maximum_multiplier_radius must be strictly positive") self._maximum_multiplier_radius = maximum_multiplier_radius def _initial_state(self, num_constraints): # For an AdditiveExternalRegretOptimizer, the internal state is simply a # tensor of Lagrange multipliers with shape (m,), where m is the number of # constraints. # # FUTURE WORK: make the dtype a parameter. return standard_ops.zeros((num_constraints,), dtype=dtypes.float32) def _lagrange_multipliers(self, state): return state def _constraint_grad_and_var(self, state, gradient): # TODO(acotter): v1.colocate_with(), if colocate_gradients_with_ops is True? return (-gradient, state) def _projection_op(self, state, name=None): with ops.colocate_with(state): if self._maximum_multiplier_radius: projected_multipliers = _project_multipliers_wrt_euclidean_norm( state, self._maximum_multiplier_radius) else: projected_multipliers = standard_ops.maximum(state, 0.0) return state_ops.assign(state, projected_multipliers, name=name)
tensorflow-master
tensorflow/contrib/constrained_optimization/python/external_regret_optimizer.py
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for constrained_optimization.python.swap_regret_optimizer.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.contrib.constrained_optimization.python import swap_regret_optimizer from tensorflow.contrib.constrained_optimization.python import test_util from tensorflow.python.ops import standard_ops from tensorflow.python.platform import test from tensorflow.python.training import gradient_descent class AdditiveSwapRegretOptimizerWrapper( swap_regret_optimizer.AdditiveSwapRegretOptimizer): """Testing wrapper class around AdditiveSwapRegretOptimizer. This class is identical to AdditiveSwapRegretOptimizer, except that it caches the internal optimization state when _stochastic_matrix() is called, so that we can test that the stochastic matrices take on their expected values. """ def __init__(self, optimizer, constraint_optimizer=None): """Same as AdditiveSwapRegretOptimizer.__init__().""" super(AdditiveSwapRegretOptimizerWrapper, self).__init__( optimizer=optimizer, constraint_optimizer=constraint_optimizer) self._cached_stochastic_matrix = None @property def stochastic_matrix(self): """Returns the cached stochastic matrix.""" return self._cached_stochastic_matrix def _stochastic_matrix(self, state): """Caches the internal state for testing.""" self._cached_stochastic_matrix = super(AdditiveSwapRegretOptimizerWrapper, self)._stochastic_matrix(state) return self._cached_stochastic_matrix class MultiplicativeSwapRegretOptimizerWrapper( swap_regret_optimizer.MultiplicativeSwapRegretOptimizer): """Testing wrapper class around MultiplicativeSwapRegretOptimizer. This class is identical to MultiplicativeSwapRegretOptimizer, except that it caches the internal optimization state when _stochastic_matrix() is called, so that we can test that the stochastic matrices take on their expected values. """ def __init__(self, optimizer, constraint_optimizer=None, minimum_multiplier_radius=None, initial_multiplier_radius=None): """Same as MultiplicativeSwapRegretOptimizer.__init__().""" super(MultiplicativeSwapRegretOptimizerWrapper, self).__init__( optimizer=optimizer, constraint_optimizer=constraint_optimizer, minimum_multiplier_radius=1e-3, initial_multiplier_radius=initial_multiplier_radius) self._cached_stochastic_matrix = None @property def stochastic_matrix(self): """Returns the cached stochastic matrix.""" return self._cached_stochastic_matrix def _stochastic_matrix(self, state): """Caches the internal state for testing.""" self._cached_stochastic_matrix = super( MultiplicativeSwapRegretOptimizerWrapper, self)._stochastic_matrix(state) return self._cached_stochastic_matrix class SwapRegretOptimizerTest(test.TestCase): def test_maximum_eigenvector_power_method(self): """Tests power method routine on some known left-stochastic matrices.""" matrix1 = np.matrix([[0.6, 0.1, 0.1], [0.0, 0.6, 0.9], [0.4, 0.3, 0.0]]) matrix2 = np.matrix([[0.4, 0.4, 0.2], [0.2, 0.1, 0.5], [0.4, 0.5, 0.3]]) with self.cached_session() as session: eigenvector1 = session.run( swap_regret_optimizer._maximal_eigenvector_power_method( standard_ops.constant(matrix1))) eigenvector2 = session.run( swap_regret_optimizer._maximal_eigenvector_power_method( standard_ops.constant(matrix2))) # Check that eigenvector1 and eigenvector2 are eigenvectors of matrix1 and # matrix2 (respectively) with associated eigenvalue 1. matrix_eigenvector1 = np.tensordot(matrix1, eigenvector1, axes=1) matrix_eigenvector2 = np.tensordot(matrix2, eigenvector2, axes=1) self.assertAllClose(eigenvector1, matrix_eigenvector1, rtol=0, atol=1e-6) self.assertAllClose(eigenvector2, matrix_eigenvector2, rtol=0, atol=1e-6) def test_project_stochastic_matrix_wrt_euclidean_norm(self): """Tests Euclidean projection routine on some known values.""" matrix = standard_ops.constant([[-0.1, -0.1, 0.4], [-0.8, 0.4, 1.2], [-0.3, 0.1, 0.2]]) expected_projected_matrix = np.array([[0.6, 0.1, 0.1], [0.0, 0.6, 0.9], [0.4, 0.3, 0.0]]) with self.cached_session() as session: projected_matrix = session.run( swap_regret_optimizer._project_stochastic_matrix_wrt_euclidean_norm( matrix)) self.assertAllClose( expected_projected_matrix, projected_matrix, rtol=0, atol=1e-6) def test_project_log_stochastic_matrix_wrt_kl_divergence(self): """Tests KL-divergence projection routine on some known values.""" matrix = standard_ops.constant([[0.2, 0.8, 0.6], [0.1, 0.2, 1.5], [0.2, 1.0, 0.9]]) expected_projected_matrix = np.array([[0.4, 0.4, 0.2], [0.2, 0.1, 0.5], [0.4, 0.5, 0.3]]) with self.cached_session() as session: projected_matrix = session.run( standard_ops.exp( swap_regret_optimizer. _project_log_stochastic_matrix_wrt_kl_divergence( standard_ops.log(matrix)))) self.assertAllClose( expected_projected_matrix, projected_matrix, rtol=0, atol=1e-6) def test_additive_swap_regret_optimizer(self): """Tests that the stochastic matrices update as expected.""" minimization_problem = test_util.ConstantMinimizationProblem( np.array([0.6, -0.1, 0.4])) optimizer = AdditiveSwapRegretOptimizerWrapper( gradient_descent.GradientDescentOptimizer(1.0)) train_op = optimizer.minimize_constrained(minimization_problem) # Calculated using a numpy+python implementation of the algorithm. expected_matrices = [ np.array([[1.0, 1.0, 1.0, 1.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]]), np.array([[0.66666667, 1.0, 1.0, 1.0], [0.26666667, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.06666667, 0.0, 0.0, 0.0]]), np.array([[0.41666667, 0.93333333, 1.0, 0.98333333], [0.46666667, 0.05333333, 0.0, 0.01333333], [0.0, 0.0, 0.0, 0.0], [0.11666667, 0.01333333, 0.0, 0.00333333]]), ] matrices = [] with self.cached_session() as session: session.run(standard_ops.global_variables_initializer()) while len(matrices) < len(expected_matrices): matrices.append(session.run(optimizer.stochastic_matrix)) session.run(train_op) for expected, actual in zip(expected_matrices, matrices): self.assertAllClose(expected, actual, rtol=0, atol=1e-6) def test_multiplicative_swap_regret_optimizer(self): """Tests that the stochastic matrices update as expected.""" minimization_problem = test_util.ConstantMinimizationProblem( np.array([0.6, -0.1, 0.4])) optimizer = MultiplicativeSwapRegretOptimizerWrapper( gradient_descent.GradientDescentOptimizer(1.0), initial_multiplier_radius=0.8) train_op = optimizer.minimize_constrained(minimization_problem) # Calculated using a numpy+python implementation of the algorithm. expected_matrices = [ np.array([[0.4, 0.4, 0.4, 0.4], [0.2, 0.2, 0.2, 0.2], [0.2, 0.2, 0.2, 0.2], [0.2, 0.2, 0.2, 0.2]]), np.array([[0.36999014, 0.38528351, 0.38528351, 0.38528351], [ 0.23517483, 0.21720297, 0.21720297, 0.21720297 ], [0.17774131, 0.18882719, 0.18882719, 0.18882719], [0.21709373, 0.20868632, 0.20868632, 0.20868632]]), np.array([[0.33972109, 0.36811863, 0.37118462, 0.36906575], [ 0.27114826, 0.23738228, 0.23376693, 0.23626491 ], [0.15712313, 0.17641793, 0.17858959, 0.17708679], [0.23200752, 0.21808115, 0.21645886, 0.21758255]]), ] matrices = [] with self.cached_session() as session: session.run(standard_ops.global_variables_initializer()) while len(matrices) < len(expected_matrices): matrices.append(session.run(optimizer.stochastic_matrix)) session.run(train_op) for expected, actual in zip(expected_matrices, matrices): self.assertAllClose(expected, actual, rtol=0, atol=1e-6) if __name__ == '__main__': test.main()
tensorflow-master
tensorflow/contrib/constrained_optimization/python/swap_regret_optimizer_test.py
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Defines base class for `ConstrainedOptimizer`s.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import abc import six from tensorflow.python.framework import ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import standard_ops from tensorflow.python.training import optimizer as train_optimizer @six.add_metaclass(abc.ABCMeta) class ConstrainedOptimizer(object): """Base class representing a constrained optimizer. A ConstrainedOptimizer wraps a tf.compat.v1.train.Optimizer (or more than one), and applies it to a ConstrainedMinimizationProblem. Unlike a tf.compat.v1.train.Optimizer, which takes a tensor to minimize as a parameter to its minimize() method, a constrained optimizer instead takes a ConstrainedMinimizationProblem. """ def __init__(self, optimizer): """Constructs a new `ConstrainedOptimizer`. Args: optimizer: tf.compat.v1.train.Optimizer, used to optimize the ConstraintedMinimizationProblem. Returns: A new `ConstrainedOptimizer`. """ self._optimizer = optimizer @property def optimizer(self): """Returns the `tf.compat.v1.train.Optimizer` used for optimization.""" return self._optimizer @abc.abstractmethod def _minimize_constrained(self, minimization_problem, global_step=None, var_list=None, gate_gradients=train_optimizer.Optimizer.GATE_OP, aggregation_method=None, colocate_gradients_with_ops=False, name=None, grad_loss=None): """Version of `minimize_constrained` to be overridden by subclasses. Implementations of this method should ignore the `pre_train_ops` property of the `minimization_problem`. The public `minimize_constrained` method will take care of executing these before the returned train_op. Args: minimization_problem: ConstrainedMinimizationProblem, the problem to optimize. global_step: as in `tf.compat.v1.train.Optimizer`'s `minimize` method. var_list: as in `tf.compat.v1.train.Optimizer`'s `minimize` method. gate_gradients: as in `tf.compat.v1.train.Optimizer`'s `minimize` method. aggregation_method: as in `tf.compat.v1.train.Optimizer`'s `minimize` method. colocate_gradients_with_ops: as in `tf.compat.v1.train.Optimizer`'s `minimize` method. name: as in `tf.compat.v1.train.Optimizer`'s `minimize` method. grad_loss: as in `tf.compat.v1.train.Optimizer`'s `minimize` method. Returns: `Operation`, the train_op. """ pass def minimize_constrained(self, minimization_problem, global_step=None, var_list=None, gate_gradients=train_optimizer.Optimizer.GATE_OP, aggregation_method=None, colocate_gradients_with_ops=False, name=None, grad_loss=None): """Returns an `Operation` for minimizing the constrained problem. Unlike `minimize_unconstrained`, this function attempts to find a solution that minimizes the `objective` portion of the minimization problem while satisfying the `constraints` portion. Args: minimization_problem: ConstrainedMinimizationProblem, the problem to optimize. global_step: as in `tf.compat.v1.train.Optimizer`'s `minimize` method. var_list: as in `tf.compat.v1.train.Optimizer`'s `minimize` method. gate_gradients: as in `tf.compat.v1.train.Optimizer`'s `minimize` method. aggregation_method: as in `tf.compat.v1.train.Optimizer`'s `minimize` method. colocate_gradients_with_ops: as in `tf.compat.v1.train.Optimizer`'s `minimize` method. name: as in `tf.compat.v1.train.Optimizer`'s `minimize` method. grad_loss: as in `tf.compat.v1.train.Optimizer`'s `minimize` method. Returns: `Operation`, the train_op. """ def train_op_callback(): return self._minimize_constrained( minimization_problem, global_step=global_step, var_list=var_list, gate_gradients=gate_gradients, aggregation_method=aggregation_method, colocate_gradients_with_ops=colocate_gradients_with_ops, name=name, grad_loss=grad_loss) # If we have pre_train_ops, use tf.control_dependencies() to ensure that # they execute before the train_op. pre_train_ops = minimization_problem.pre_train_ops if pre_train_ops: with ops.control_dependencies(pre_train_ops): train_op = train_op_callback() else: train_op = train_op_callback() return train_op def minimize_unconstrained(self, minimization_problem, global_step=None, var_list=None, gate_gradients=train_optimizer.Optimizer.GATE_OP, aggregation_method=None, colocate_gradients_with_ops=False, name=None, grad_loss=None): """Returns an `Operation` for minimizing the unconstrained problem. Unlike `minimize_constrained`, this function ignores the `constraints` (and `proxy_constraints`) portion of the minimization problem entirely, and only minimizes `objective`. Args: minimization_problem: ConstrainedMinimizationProblem, the problem to optimize. global_step: as in `tf.compat.v1.train.Optimizer`'s `minimize` method. var_list: as in `tf.compat.v1.train.Optimizer`'s `minimize` method. gate_gradients: as in `tf.compat.v1.train.Optimizer`'s `minimize` method. aggregation_method: as in `tf.compat.v1.train.Optimizer`'s `minimize` method. colocate_gradients_with_ops: as in `tf.compat.v1.train.Optimizer`'s `minimize` method. name: as in `tf.compat.v1.train.Optimizer`'s `minimize` method. grad_loss: as in `tf.compat.v1.train.Optimizer`'s `minimize` method. Returns: `Operation`, the train_op. """ def train_op_callback(): return self.optimizer.minimize( minimization_problem.objective, global_step=global_step, var_list=var_list, gate_gradients=gate_gradients, aggregation_method=aggregation_method, colocate_gradients_with_ops=colocate_gradients_with_ops, name=name, grad_loss=grad_loss) # If we have pre_train_ops, use tf.control_dependencies() to ensure that # they execute before the train_op. pre_train_ops = minimization_problem.pre_train_ops if pre_train_ops: with ops.control_dependencies(pre_train_ops): train_op = train_op_callback() else: train_op = train_op_callback() return train_op def minimize(self, minimization_problem, unconstrained_steps=None, global_step=None, var_list=None, gate_gradients=train_optimizer.Optimizer.GATE_OP, aggregation_method=None, colocate_gradients_with_ops=False, name=None, grad_loss=None): """Returns an `Operation` for minimizing the constrained problem. This method combines the functionality of `minimize_unconstrained` and `minimize_constrained`. If global_step < unconstrained_steps, it will perform an unconstrained update, and if global_step >= unconstrained_steps, it will perform a constrained update. The reason for this functionality is that it may be best to initialize the constrained optimizer with an approximate optimum of the unconstrained problem. Args: minimization_problem: ConstrainedMinimizationProblem, the problem to optimize. unconstrained_steps: int, number of steps for which we should perform unconstrained updates, before transitioning to constrained updates. global_step: as in `tf.compat.v1.train.Optimizer`'s `minimize` method. var_list: as in `tf.compat.v1.train.Optimizer`'s `minimize` method. gate_gradients: as in `tf.compat.v1.train.Optimizer`'s `minimize` method. aggregation_method: as in `tf.compat.v1.train.Optimizer`'s `minimize` method. colocate_gradients_with_ops: as in `tf.compat.v1.train.Optimizer`'s `minimize` method. name: as in `tf.compat.v1.train.Optimizer`'s `minimize` method. grad_loss: as in `tf.compat.v1.train.Optimizer`'s `minimize` method. Returns: `Operation`, the train_op. Raises: ValueError: If unconstrained_steps is provided, but global_step is not. """ def unconstrained_fn(): """Returns an `Operation` for minimizing the unconstrained problem.""" return self.minimize_unconstrained( minimization_problem=minimization_problem, global_step=global_step, var_list=var_list, gate_gradients=gate_gradients, aggregation_method=aggregation_method, colocate_gradients_with_ops=colocate_gradients_with_ops, name=name, grad_loss=grad_loss) def constrained_fn(): """Returns an `Operation` for minimizing the constrained problem.""" return self.minimize_constrained( minimization_problem=minimization_problem, global_step=global_step, var_list=var_list, gate_gradients=gate_gradients, aggregation_method=aggregation_method, colocate_gradients_with_ops=colocate_gradients_with_ops, name=name, grad_loss=grad_loss) if unconstrained_steps is not None: if global_step is None: raise ValueError( "global_step cannot be None if unconstrained_steps is provided") unconstrained_steps_tensor = ops.convert_to_tensor(unconstrained_steps) dtype = unconstrained_steps_tensor.dtype return control_flow_ops.cond( standard_ops.cast(global_step, dtype) < unconstrained_steps_tensor, true_fn=unconstrained_fn, false_fn=constrained_fn) else: return constrained_fn()
tensorflow-master
tensorflow/contrib/constrained_optimization/python/constrained_optimizer.py
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Contains helpers used by tests.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.contrib.constrained_optimization.python import constrained_minimization_problem from tensorflow.python.framework import dtypes from tensorflow.python.ops import standard_ops class ConstantMinimizationProblem( constrained_minimization_problem.ConstrainedMinimizationProblem): """A `ConstrainedMinimizationProblem` with constant constraint violations. This minimization problem is intended for use in performing simple tests of the Lagrange multiplier (or equivalent) update in the optimizers. There is a one-element "dummy" model parameter, but it should be ignored. """ def __init__(self, constraints): """Constructs a new `ConstantMinimizationProblem'. Args: constraints: 1d numpy array, the constant constraint violations. Returns: A new `ConstantMinimizationProblem'. """ # We make an fake 1-parameter linear objective so that we don't get a "no # variables to optimize" error. self._objective = standard_ops.Variable(0.0, dtype=dtypes.float32) self._constraints = standard_ops.constant(constraints, dtype=dtypes.float32) @property def objective(self): """Returns the objective function.""" return self._objective @property def constraints(self): """Returns the constant constraint violations.""" return self._constraints
tensorflow-master
tensorflow/contrib/constrained_optimization/python/test_util.py
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Defines abstract class for `ConstrainedMinimizationProblem`s. A ConstrainedMinimizationProblem consists of an objective function to minimize, and a set of constraint functions that are constrained to be nonpositive. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import abc import six @six.add_metaclass(abc.ABCMeta) class ConstrainedMinimizationProblem(object): """Abstract class representing a `ConstrainedMinimizationProblem`. A ConstrainedMinimizationProblem consists of an objective function to minimize, and a set of constraint functions that are constrained to be nonpositive. In addition to the constraint functions, there may (optionally) be proxy constraint functions: a ConstrainedOptimizer will attempt to penalize these proxy constraint functions so as to satisfy the (non-proxy) constraints. Proxy constraints could be used if the constraints functions are difficult or impossible to optimize (e.g. if they're piecewise constant), in which case the proxy constraints should be some approximation of the original constraints that is well-enough behaved to permit successful optimization. """ @abc.abstractproperty def objective(self): """Returns the objective function. Returns: A 0d tensor that should be minimized. """ pass @property def num_constraints(self): """Returns the number of constraints. Returns: An int containing the number of constraints. Raises: ValueError: If the constraints (or proxy_constraints, if present) do not have fully-known shapes, OR if proxy_constraints are present, and the shapes of constraints and proxy_constraints are fully-known, but they're different. """ constraints_shape = self.constraints.get_shape() if self.proxy_constraints is None: proxy_constraints_shape = constraints_shape else: proxy_constraints_shape = self.proxy_constraints.get_shape() if (constraints_shape.ndims is None or proxy_constraints_shape.ndims is None or any(ii is None for ii in constraints_shape.as_list()) or any(ii is None for ii in proxy_constraints_shape.as_list())): raise ValueError( "constraints and proxy_constraints must have fully-known shapes") if constraints_shape != proxy_constraints_shape: raise ValueError( "constraints and proxy_constraints must have the same shape") size = 1 for ii in constraints_shape.as_list(): size *= ii return int(size) @abc.abstractproperty def constraints(self): """Returns the vector of constraint functions. Letting g_i be the ith element of the constraints vector, the ith constraint will be g_i <= 0. Returns: A tensor of constraint functions. """ pass # This is a property, instead of an abstract property, since it doesn't need # to be overridden: if proxy_constraints returns None, then there are no # proxy constraints. @property def proxy_constraints(self): """Returns the optional vector of proxy constraint functions. The difference between `constraints` and `proxy_constraints` is that, when proxy constraints are present, the `constraints` are merely EVALUATED during optimization, whereas the `proxy_constraints` are DIFFERENTIATED. If there are no proxy constraints, then the `constraints` are both evaluated and differentiated. For example, if we want to impose constraints on step functions, then we could use these functions for `constraints`. However, because a step function has zero gradient almost everywhere, we can't differentiate these functions, so we would take `proxy_constraints` to be some differentiable approximation of `constraints`. Returns: A tensor of proxy constraint functions. """ return None # This is a property, instead of an abstract property, since it doesn't need # to be overridden: if pre_train_ops returns None, then there are no ops to # run before train_op. @property def pre_train_ops(self): """Returns a list of `Operation`s to run before the train_op. When a `ConstrainedOptimizer` creates a train_op (in `minimize` `minimize_unconstrained`, or `minimize_constrained`), it will include these ops before the main training step. Returns: A list of `Operation`s. """ return None
tensorflow-master
tensorflow/contrib/constrained_optimization/python/constrained_minimization_problem.py
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for constrained_optimization.python.external_regret_optimizer.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.contrib.constrained_optimization.python import external_regret_optimizer from tensorflow.contrib.constrained_optimization.python import test_util from tensorflow.python.ops import standard_ops from tensorflow.python.platform import test from tensorflow.python.training import gradient_descent class AdditiveExternalRegretOptimizerWrapper( external_regret_optimizer.AdditiveExternalRegretOptimizer): """Testing wrapper class around AdditiveExternalRegretOptimizer. This class is identical to AdditiveExternalRegretOptimizer, except that it caches the internal optimization state when _lagrange_multipliers() is called, so that we can test that the Lagrange multipliers take on their expected values. """ def __init__(self, optimizer, constraint_optimizer=None, maximum_multiplier_radius=None): """Same as AdditiveExternalRegretOptimizer.__init__.""" super(AdditiveExternalRegretOptimizerWrapper, self).__init__( optimizer=optimizer, constraint_optimizer=constraint_optimizer, maximum_multiplier_radius=maximum_multiplier_radius) self._cached_lagrange_multipliers = None @property def lagrange_multipliers(self): """Returns the cached Lagrange multipliers.""" return self._cached_lagrange_multipliers def _lagrange_multipliers(self, state): """Caches the internal state for testing.""" self._cached_lagrange_multipliers = super( AdditiveExternalRegretOptimizerWrapper, self)._lagrange_multipliers(state) return self._cached_lagrange_multipliers class ExternalRegretOptimizerTest(test.TestCase): def test_project_multipliers_wrt_euclidean_norm(self): """Tests Euclidean projection routine on some known values.""" multipliers1 = standard_ops.constant([-0.1, -0.6, -0.3]) expected_projected_multipliers1 = np.array([0.0, 0.0, 0.0]) multipliers2 = standard_ops.constant([-0.1, 0.6, 0.3]) expected_projected_multipliers2 = np.array([0.0, 0.6, 0.3]) multipliers3 = standard_ops.constant([0.4, 0.7, -0.2, 0.5, 0.1]) expected_projected_multipliers3 = np.array([0.2, 0.5, 0.0, 0.3, 0.0]) with self.cached_session() as session: projected_multipliers1 = session.run( external_regret_optimizer._project_multipliers_wrt_euclidean_norm( multipliers1, 1.0)) projected_multipliers2 = session.run( external_regret_optimizer._project_multipliers_wrt_euclidean_norm( multipliers2, 1.0)) projected_multipliers3 = session.run( external_regret_optimizer._project_multipliers_wrt_euclidean_norm( multipliers3, 1.0)) self.assertAllClose( expected_projected_multipliers1, projected_multipliers1, rtol=0, atol=1e-6) self.assertAllClose( expected_projected_multipliers2, projected_multipliers2, rtol=0, atol=1e-6) self.assertAllClose( expected_projected_multipliers3, projected_multipliers3, rtol=0, atol=1e-6) def test_additive_external_regret_optimizer(self): """Tests that the Lagrange multipliers update as expected.""" minimization_problem = test_util.ConstantMinimizationProblem( np.array([0.6, -0.1, 0.4])) optimizer = AdditiveExternalRegretOptimizerWrapper( gradient_descent.GradientDescentOptimizer(1.0), maximum_multiplier_radius=1.0) train_op = optimizer.minimize_constrained(minimization_problem) expected_multipliers = [ np.array([0.0, 0.0, 0.0]), np.array([0.6, 0.0, 0.4]), np.array([0.7, 0.0, 0.3]), np.array([0.8, 0.0, 0.2]), np.array([0.9, 0.0, 0.1]), np.array([1.0, 0.0, 0.0]), np.array([1.0, 0.0, 0.0]), ] multipliers = [] with self.cached_session() as session: session.run(standard_ops.global_variables_initializer()) while len(multipliers) < len(expected_multipliers): multipliers.append(session.run(optimizer.lagrange_multipliers)) session.run(train_op) for expected, actual in zip(expected_multipliers, multipliers): self.assertAllClose(expected, actual, rtol=0, atol=1e-6) if __name__ == "__main__": test.main()
tensorflow-master
tensorflow/contrib/constrained_optimization/python/external_regret_optimizer_test.py
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Code for optimizing over a set of candidate solutions. The functions in this file deal with the constrained problem: > minimize f(w) > s.t. g_i(w) <= 0 for all i in {0,1,...,m-1} Here, f(w) is the "objective function", and g_i(w) is the ith (of m) "constraint function". Given the values of the objective and constraint functions for a set of n "candidate solutions" {w_0,w_1,...,w_{n-1}} (for a total of n objective function values, and n*m constraint function values), the `find_best_candidate_distribution` function finds the best DISTRIBUTION over these candidates, while `find_best_candidate_index' heuristically finds the single best candidate. Both of these functions have dependencies on `scipy`, so if you want to call them, then you must make sure that `scipy` is available. The imports are performed inside the functions themselves, so if they're not actually called, then `scipy` is not needed. For more specifics, please refer to: > Cotter, Jiang and Sridharan. "Two-Player Games for Efficient Non-Convex > Constrained Optimization". > [https://arxiv.org/abs/1804.06500](https://arxiv.org/abs/1804.06500) The `find_best_candidate_distribution` function implements the approach described in Lemma 3, while `find_best_candidate_index` implements the heuristic used for hyperparameter search in the experiments of Section 5.2. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from six.moves import xrange # pylint: disable=redefined-builtin def _find_best_candidate_distribution_helper(objective_vector, constraints_matrix, maximum_violation=0.0): """Finds a distribution minimizing an objective subject to constraints. This function deals with the constrained problem: > minimize f(w) > s.t. g_i(w) <= 0 for all i in {0,1,...,m-1} Here, f(w) is the "objective function", and g_i(w) is the ith (of m) "constraint function". Given a set of n "candidate solutions" {w_0,w_1,...,w_{n-1}}, this function finds a distribution over these n candidates that, in expectation, minimizes the objective while violating the constraints by no more than `maximum_violation`. If no such distribution exists, it returns an error (using Go-style error reporting). The `objective_vector` parameter should be a numpy array with shape (n,), for which objective_vector[i] = f(w_i). Likewise, `constraints_matrix` should be a numpy array with shape (m,n), for which constraints_matrix[i,j] = g_i(w_j). This function will return a distribution for which at most m+1 probabilities, and often fewer, are nonzero. Args: objective_vector: numpy array of shape (n,), where n is the number of "candidate solutions". Contains the objective function values. constraints_matrix: numpy array of shape (m,n), where m is the number of constraints and n is the number of "candidate solutions". Contains the constraint violation magnitudes. maximum_violation: nonnegative float, the maximum amount by which any constraint may be violated, in expectation. Returns: A pair (`result`, `message`), exactly one of which is None. If `message` is None, then the `result` contains the optimal distribution as a numpy array of shape (n,). If `result` is None, then `message` contains an error message. Raises: ValueError: If `objective_vector` and `constraints_matrix` have inconsistent shapes, or if `maximum_violation` is negative. ImportError: If we're unable to import `scipy.optimize`. """ if maximum_violation < 0.0: raise ValueError("maximum_violation must be nonnegative") mm, nn = np.shape(constraints_matrix) if (nn,) != np.shape(objective_vector): raise ValueError( "objective_vector must have shape (n,), and constraints_matrix (m, n)," " where n is the number of candidates, and m is the number of " "constraints") # We import scipy inline, instead of at the top of the file, so that a scipy # dependency is only introduced if either find_best_candidate_distribution() # or find_best_candidate_index() are actually called. import scipy.optimize # pylint: disable=g-import-not-at-top # Feasibility (within maximum_violation) constraints. a_ub = constraints_matrix b_ub = np.full((mm, 1), maximum_violation) # Sum-to-one constraint. a_eq = np.ones((1, nn)) b_eq = np.ones((1, 1)) # Nonnegativity constraints. bounds = (0, None) result = scipy.optimize.linprog( objective_vector, A_ub=a_ub, b_ub=b_ub, A_eq=a_eq, b_eq=b_eq, bounds=bounds) # Go-style error reporting. We don't raise on error, since # find_best_candidate_distribution() needs to handle the failure case, and we # shouldn't use exceptions as flow-control. if not result.success: return (None, result.message) else: return (result.x, None) def find_best_candidate_distribution(objective_vector, constraints_matrix, epsilon=0.0): """Finds a distribution minimizing an objective subject to constraints. This function deals with the constrained problem: > minimize f(w) > s.t. g_i(w) <= 0 for all i in {0,1,...,m-1} Here, f(w) is the "objective function", and g_i(w) is the ith (of m) "constraint function". Given a set of n "candidate solutions" {w_0,w_1,...,w_{n-1}}, this function finds a distribution over these n candidates that, in expectation, minimizes the objective while violating the constraints by the smallest possible amount (with the amount being found via bisection search). The `objective_vector` parameter should be a numpy array with shape (n,), for which objective_vector[i] = f(w_i). Likewise, `constraints_matrix` should be a numpy array with shape (m,n), for which constraints_matrix[i,j] = g_i(w_j). This function will return a distribution for which at most m+1 probabilities, and often fewer, are nonzero. For more specifics, please refer to: > Cotter, Jiang and Sridharan. "Two-Player Games for Efficient Non-Convex > Constrained Optimization". > [https://arxiv.org/abs/1804.06500](https://arxiv.org/abs/1804.06500) This function implements the approach described in Lemma 3. Args: objective_vector: numpy array of shape (n,), where n is the number of "candidate solutions". Contains the objective function values. constraints_matrix: numpy array of shape (m,n), where m is the number of constraints and n is the number of "candidate solutions". Contains the constraint violation magnitudes. epsilon: nonnegative float, the threshold at which to terminate the binary search while searching for the minimal expected constraint violation magnitude. Returns: The optimal distribution, as a numpy array of shape (n,). Raises: ValueError: If `objective_vector` and `constraints_matrix` have inconsistent shapes, or if `epsilon` is negative. ImportError: If we're unable to import `scipy.optimize`. """ if epsilon < 0.0: raise ValueError("epsilon must be nonnegative") # If there is a feasible solution (i.e. with maximum_violation=0), then that's # what we'll return. pp, _ = _find_best_candidate_distribution_helper(objective_vector, constraints_matrix) if pp is not None: return pp # The bound is the minimum over all candidates, of the maximum per-candidate # constraint violation. lower = 0.0 upper = np.min(np.amax(constraints_matrix, axis=0)) best_pp, _ = _find_best_candidate_distribution_helper( objective_vector, constraints_matrix, maximum_violation=upper) assert best_pp is not None # Throughout this loop, a maximum_violation of "lower" is not achievable, # but a maximum_violation of "upper" is achievable. while True: middle = 0.5 * (lower + upper) if (middle - lower <= epsilon) or (upper - middle <= epsilon): break else: pp, _ = _find_best_candidate_distribution_helper( objective_vector, constraints_matrix, maximum_violation=middle) if pp is None: lower = middle else: best_pp = pp upper = middle return best_pp def find_best_candidate_index(objective_vector, constraints_matrix, rank_objectives=False): """Heuristically finds the best candidate solution to a constrained problem. This function deals with the constrained problem: > minimize f(w) > s.t. g_i(w) <= 0 for all i in {0,1,...,m-1} Here, f(w) is the "objective function", and g_i(w) is the ith (of m) "constraint function". Given a set of n "candidate solutions" {w_0,w_1,...,w_{n-1}}, this function finds the "best" solution according to the following heuristic: 1. Across all models, the ith constraint violations (i.e. max{0, g_i(0)}) are ranked, as are the objectives (if rank_objectives=True). 2. Each model is then associated its MAXIMUM rank across all m constraints (and the objective, if rank_objectives=True). 3. The model with the minimal maximum rank is then identified. Ties are broken using the objective function value. 4. The index of this "best" model is returned. The `objective_vector` parameter should be a numpy array with shape (n,), for which objective_vector[i] = f(w_i). Likewise, `constraints_matrix` should be a numpy array with shape (m,n), for which constraints_matrix[i,j] = g_i(w_j). For more specifics, please refer to: > Cotter, Jiang and Sridharan. "Two-Player Games for Efficient Non-Convex > Constrained Optimization". > [https://arxiv.org/abs/1804.06500](https://arxiv.org/abs/1804.06500) This function implements the heuristic used for hyperparameter search in the experiments of Section 5.2. Args: objective_vector: numpy array of shape (n,), where n is the number of "candidate solutions". Contains the objective function values. constraints_matrix: numpy array of shape (m,n), where m is the number of constraints and n is the number of "candidate solutions". Contains the constraint violation magnitudes. rank_objectives: bool, whether the objective function values should be included in the initial ranking step. If True, both the objective and constraints will be ranked. If False, only the constraints will be ranked. In either case, the objective function values will be used for tiebreaking. Returns: The index (in {0,1,...,n-1}) of the "best" model according to the above heuristic. Raises: ValueError: If `objective_vector` and `constraints_matrix` have inconsistent shapes. ImportError: If we're unable to import `scipy.stats`. """ mm, nn = np.shape(constraints_matrix) if (nn,) != np.shape(objective_vector): raise ValueError( "objective_vector must have shape (n,), and constraints_matrix (m, n)," " where n is the number of candidates, and m is the number of " "constraints") # We import scipy inline, instead of at the top of the file, so that a scipy # dependency is only introduced if either find_best_candidate_distribution() # or find_best_candidate_index() are actually called. import scipy.stats # pylint: disable=g-import-not-at-top if rank_objectives: maximum_ranks = scipy.stats.rankdata(objective_vector, method="min") else: maximum_ranks = np.zeros(nn, dtype=np.int64) for ii in xrange(mm): # Take the maximum of the constraint functions with zero, since we want to # rank the magnitude of constraint *violations*. If the constraint is # satisfied, then we don't care how much it's satisfied by (as a result, we # we expect all models satisfying a constraint to be tied at rank 1). ranks = scipy.stats.rankdata( np.maximum(0.0, constraints_matrix[ii, :]), method="min") maximum_ranks = np.maximum(maximum_ranks, ranks) best_index = None best_rank = float("Inf") best_objective = float("Inf") for ii in xrange(nn): if maximum_ranks[ii] < best_rank: best_index = ii best_rank = maximum_ranks[ii] best_objective = objective_vector[ii] elif (maximum_ranks[ii] == best_rank) and (objective_vector[ii] <= best_objective): best_index = ii best_objective = objective_vector[ii] return best_index
tensorflow-master
tensorflow/contrib/constrained_optimization/python/candidates.py
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Defines `{Additive,Multiplicative}SwapRegretOptimizer`s. These optimizers minimize a `ConstrainedMinimizationProblem` by using a swap-regret minimizing algorithm (either SGD or multiplicative weights) to learn what weights should be associated with the objective function and constraints. These algorithms do *not* use Lagrange multipliers, but the idea is similar. The main differences between the formulation used here, and the standard Lagrangian formulation, are that (i) the objective function is weighted, in addition to the constraints, and (ii) we learn a matrix of weights, instead of a vector. For the purposes of constrained optimization, at least in theory, external-regret minimization suffices if the `ConstrainedMinimizationProblem` we're optimizing doesn't have any `proxy_constraints`, while swap-regret minimization should be used if `proxy_constraints` are present. For more specifics, please refer to: > Cotter, Jiang and Sridharan. "Two-Player Games for Efficient Non-Convex > Constrained Optimization". > [https://arxiv.org/abs/1804.06500](https://arxiv.org/abs/1804.06500) The formulation used by both of the SwapRegretOptimizers can be found in Definition 2, and is discussed in Section 4. The `MultiplicativeSwapRegretOptimizer` is most similar to Algorithm 2 in Section 4, with the difference being that it uses `tf.compat.v1.train.Optimizer`s, instead of SGD, for the "inner" updates. The `AdditiveSwapRegretOptimizer` differs further in that it performs additive (instead of multiplicative) updates of the stochastic matrix. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import abc import math import six from tensorflow.contrib.constrained_optimization.python import constrained_optimizer from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import standard_ops from tensorflow.python.ops import state_ops from tensorflow.python.training import optimizer as train_optimizer def _maximal_eigenvector_power_method(matrix, epsilon=1e-6, maximum_iterations=100): """Returns the maximal right-eigenvector of `matrix` using the power method. Args: matrix: 2D Tensor, the matrix of which we will find the maximal right-eigenvector. epsilon: nonnegative float, if two iterations of the power method differ (in L2 norm) by no more than epsilon, we will terminate. maximum_iterations: nonnegative int, if we perform this many iterations, we will terminate. Result: The maximal right-eigenvector of `matrix`. Raises: ValueError: If the `matrix` tensor is not floating-point, or if the `epsilon` or `maximum_iterations` parameters violate their bounds. """ if not matrix.dtype.is_floating: raise ValueError("multipliers must have a floating-point dtype") if epsilon <= 0.0: raise ValueError("epsilon must be strictly positive") if maximum_iterations <= 0: raise ValueError("maximum_iterations must be strictly positive") def while_loop_condition(iteration, eigenvector, old_eigenvector): """Returns false if the while loop should terminate.""" not_done = (iteration < maximum_iterations) not_converged = (standard_ops.norm(eigenvector - old_eigenvector) > epsilon) return standard_ops.logical_and(not_done, not_converged) def while_loop_body(iteration, eigenvector, old_eigenvector): """Performs one iteration of the power method.""" del old_eigenvector # Needed by the condition, but not the body. iteration += 1 # We need to use tf.matmul() and tf.expand_dims(), instead of # tf.tensordot(), since the former will infer the shape of the result, while # the latter will not (tf.while_loop() needs the shapes). new_eigenvector = standard_ops.matmul( matrix, standard_ops.expand_dims(eigenvector, 1))[:, 0] new_eigenvector /= standard_ops.norm(new_eigenvector) return (iteration, new_eigenvector, eigenvector) iteration = standard_ops.constant(0) eigenvector = standard_ops.ones_like(matrix[:, 0]) eigenvector /= standard_ops.norm(eigenvector) # We actually want a do-while loop, so we explicitly call while_loop_body() # once before tf.while_loop(). iteration, eigenvector, old_eigenvector = while_loop_body( iteration, eigenvector, eigenvector) iteration, eigenvector, old_eigenvector = control_flow_ops.while_loop( while_loop_condition, while_loop_body, loop_vars=(iteration, eigenvector, old_eigenvector), name="power_method") return eigenvector def _project_stochastic_matrix_wrt_euclidean_norm(matrix): """Projects its argument onto the set of left-stochastic matrices. This algorithm is O(n^3) at worst, where `matrix` is n*n. It can be done in O(n^2 * log(n)) time by sorting each column (and maybe better with a different algorithm), but the algorithm implemented here is easier to implement in TensorFlow. Args: matrix: 2d square tensor, the matrix to project. Returns: The 2d square tensor that results from projecting `matrix` onto the set of left-stochastic matrices w.r.t. the Euclidean norm applied column-wise (i.e. the Frobenius norm). Raises: ValueError: if the `matrix` tensor is not floating-point, does not have a fully-known shape, or is not two-dimensional and square. """ if not matrix.dtype.is_floating: raise ValueError("multipliers must have a floating-point dtype") matrix_shape = matrix.get_shape() if matrix_shape.ndims is None: raise ValueError("matrix must have known shape") if matrix_shape.ndims != 2: raise ValueError( "matrix must be two dimensional (instead is %d-dimensional)" % matrix_shape.ndims) if matrix_shape[0] != matrix_shape[1]: raise ValueError("matrix must be square (instead has shape (%d,%d))" % (matrix_shape[0], matrix_shape[1])) dimension = matrix_shape.dims[0].value if dimension is None: raise ValueError("matrix must have fully-known shape") def while_loop_condition(iteration, matrix, inactive, old_inactive): """Returns false if the while loop should terminate.""" del matrix # Needed by the body, but not the condition. not_done = (iteration < dimension) not_converged = standard_ops.reduce_any( standard_ops.not_equal(inactive, old_inactive)) return standard_ops.logical_and(not_done, not_converged) def while_loop_body(iteration, matrix, inactive, old_inactive): """Performs one iteration of the projection.""" del old_inactive # Needed by the condition, but not the body. iteration += 1 scale = (1.0 - standard_ops.reduce_sum( matrix, axis=0, keepdims=True)) / standard_ops.maximum( 1.0, standard_ops.reduce_sum(inactive, axis=0, keepdims=True)) matrix = matrix + (scale * inactive) new_inactive = standard_ops.cast(matrix > 0, matrix.dtype) matrix = matrix * new_inactive return (iteration, matrix, new_inactive, inactive) iteration = standard_ops.constant(0) inactive = standard_ops.ones_like(matrix, dtype=matrix.dtype) # We actually want a do-while loop, so we explicitly call while_loop_body() # once before tf.while_loop(). iteration, matrix, inactive, old_inactive = while_loop_body( iteration, matrix, inactive, inactive) iteration, matrix, inactive, old_inactive = control_flow_ops.while_loop( while_loop_condition, while_loop_body, loop_vars=(iteration, matrix, inactive, old_inactive), name="euclidean_projection") return matrix def _project_log_stochastic_matrix_wrt_kl_divergence(log_matrix): """Projects its argument onto the set of log-left-stochastic matrices. Args: log_matrix: 2d square tensor, the element-wise logarithm of the matrix to project. Returns: The 2d square tensor that results from projecting exp(`matrix`) onto the set of left-stochastic matrices w.r.t. the KL-divergence applied column-wise. """ # For numerical reasons, make sure that the largest matrix element is zero # before exponentiating. log_matrix = log_matrix - standard_ops.reduce_max( log_matrix, axis=0, keepdims=True) log_matrix = log_matrix - standard_ops.log( standard_ops.reduce_sum( standard_ops.exp(log_matrix), axis=0, keepdims=True)) return log_matrix @six.add_metaclass(abc.ABCMeta) class _SwapRegretOptimizer(constrained_optimizer.ConstrainedOptimizer): """Base class representing a `_SwapRegretOptimizer`. This class contains most of the logic for performing constrained optimization, minimizing swap regret for the constraints player. What it *doesn't* do is keep track of the internal state (the stochastic matrix). Instead, the state is accessed via the _initial_state(), _stochastic_matrix(), _constraint_grad_and_var() and _projection_op() methods. The reason for this is that we want to make it easy to implement different representations of the internal state. For example, for additive updates, it's most natural to store the stochastic matrix directly, whereas for multiplicative updates, it's most natural to store its element-wise logarithm. For more specifics, please refer to: > Cotter, Jiang and Sridharan. "Two-Player Games for Efficient Non-Convex > Constrained Optimization". > [https://arxiv.org/abs/1804.06500](https://arxiv.org/abs/1804.06500) The formulation used by `_SwapRegretOptimizer`s can be found in Definition 2, and is discussed in Section 4. Such optimizers are most similar to Algorithm 2 in Section 4. Most notably, the internal state is a left-stochastic matrix of shape (m+1,m+1), where m is the number of constraints. """ def __init__(self, optimizer, constraint_optimizer=None): """Constructs a new `_SwapRegretOptimizer`. The difference between `optimizer` and `constraint_optimizer` (if the latter is provided) is that the former is used for learning the model parameters, while the latter us used for the update to the constraint/objective weight matrix (the analogue of Lagrange multipliers). If no `constraint_optimizer` is provided, then `optimizer` is used for both. Args: optimizer: tf.compat.v1.train.Optimizer, used to optimize the objective and proxy_constraints portion of ConstrainedMinimizationProblem. If constraint_optimizer is not provided, this will also be used to optimize the Lagrange multiplier analogues. constraint_optimizer: optional tf.compat.v1.train.Optimizer, used to optimize the Lagrange multiplier analogues. Returns: A new `_SwapRegretOptimizer`. """ super(_SwapRegretOptimizer, self).__init__(optimizer=optimizer) self._constraint_optimizer = constraint_optimizer @property def constraint_optimizer(self): """Returns the `tf.compat.v1.train.Optimizer` used for the matrix.""" return self._constraint_optimizer @abc.abstractmethod def _initial_state(self, num_constraints): pass @abc.abstractmethod def _stochastic_matrix(self, state): pass def _distribution(self, state): distribution = _maximal_eigenvector_power_method( self._stochastic_matrix(state)) distribution = standard_ops.abs(distribution) distribution /= standard_ops.reduce_sum(distribution) return distribution @abc.abstractmethod def _constraint_grad_and_var(self, state, gradient): pass @abc.abstractmethod def _projection_op(self, state, name=None): pass def _minimize_constrained(self, minimization_problem, global_step=None, var_list=None, gate_gradients=train_optimizer.Optimizer.GATE_OP, aggregation_method=None, colocate_gradients_with_ops=False, name=None, grad_loss=None): """Returns an `Operation` for minimizing the constrained problem. The `optimizer` constructor parameter will be used to update the model parameters, while the constraint/objective weight matrix (the analogue of Lagrange multipliers) will be updated using `constrained_optimizer` (if provided) or `optimizer` (if not). Whether the matrix updates are additive or multiplicative depends on the derived class. Args: minimization_problem: ConstrainedMinimizationProblem, the problem to optimize. global_step: as in `tf.compat.v1.train.Optimizer`'s `minimize` method. var_list: as in `tf.compat.v1.train.Optimizer`'s `minimize` method. gate_gradients: as in `tf.compat.v1.train.Optimizer`'s `minimize` method. aggregation_method: as in `tf.compat.v1.train.Optimizer`'s `minimize` method. colocate_gradients_with_ops: as in `tf.compat.v1.train.Optimizer`'s `minimize` method. name: as in `tf.compat.v1.train.Optimizer`'s `minimize` method. grad_loss: as in `tf.compat.v1.train.Optimizer`'s `minimize` method. Raises: ValueError: If the minimization_problem tensors have different dtypes. Returns: `Operation`, the train_op. """ objective = minimization_problem.objective constraints = minimization_problem.constraints proxy_constraints = minimization_problem.proxy_constraints if proxy_constraints is None: proxy_constraints = constraints # Make sure that the objective, constraints and proxy constraints all have # the same dtype. if (objective.dtype.base_dtype != constraints.dtype.base_dtype or objective.dtype.base_dtype != proxy_constraints.dtype.base_dtype): raise ValueError("objective, constraints and proxy_constraints must " "have the same dtype") # Flatten both constraints tensors to 1d. num_constraints = minimization_problem.num_constraints constraints = standard_ops.reshape(constraints, shape=(num_constraints,)) proxy_constraints = standard_ops.reshape( proxy_constraints, shape=(num_constraints,)) # We use a lambda to initialize the state so that, if this function call is # inside the scope of a tf.control_dependencies() block, the dependencies # will not be applied to the initializer. state = standard_ops.Variable( lambda: self._initial_state(num_constraints), trainable=False, name="swap_regret_optimizer_state") zero_and_constraints = standard_ops.concat((standard_ops.zeros( (1,), dtype=constraints.dtype), constraints), axis=0) objective_and_proxy_constraints = standard_ops.concat( (standard_ops.expand_dims(objective, 0), proxy_constraints), axis=0) distribution = self._distribution(state) loss = standard_ops.tensordot( standard_ops.cast(distribution, objective_and_proxy_constraints.dtype), objective_and_proxy_constraints, 1) matrix_gradient = standard_ops.matmul( standard_ops.expand_dims( standard_ops.cast(zero_and_constraints, distribution.dtype), 1), standard_ops.expand_dims(distribution, 0)) update_ops = [] if self.constraint_optimizer is None: # If we don't have a separate constraint_optimizer, then we use # self._optimizer for both the update of the model parameters, and that of # the internal state. grads_and_vars = self.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) grads_and_vars.append( self._constraint_grad_and_var(state, matrix_gradient)) update_ops.append( self.optimizer.apply_gradients(grads_and_vars, name="update")) else: # If we have a separate constraint_optimizer, then we use self._optimizer # for the update of the model parameters, and self._constraint_optimizer # for that of the internal state. grads_and_vars = self.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) matrix_grads_and_vars = [ self._constraint_grad_and_var(state, matrix_gradient) ] gradients = [ gradient for gradient, _ in grads_and_vars + matrix_grads_and_vars if gradient is not None ] with ops.control_dependencies(gradients): update_ops.append( self.optimizer.apply_gradients(grads_and_vars, name="update")) update_ops.append( self.constraint_optimizer.apply_gradients( matrix_grads_and_vars, name="optimizer_state_update")) with ops.control_dependencies(update_ops): if global_step is None: # If we don't have a global step, just project, and we're done. return self._projection_op(state, name=name) else: # If we have a global step, then we need to increment it in addition to # projecting. projection_op = self._projection_op(state, name="project") with ops.colocate_with(global_step): global_step_op = state_ops.assign_add( global_step, 1, name="global_step_increment") return control_flow_ops.group(projection_op, global_step_op, name=name) class AdditiveSwapRegretOptimizer(_SwapRegretOptimizer): """A `ConstrainedOptimizer` based on swap-regret minimization. This `ConstrainedOptimizer` uses the given `tf.compat.v1.train.Optimizer`s to jointly minimize over the model parameters, and maximize over constraint/objective weight matrix (the analogue of Lagrange multipliers), with the latter maximization using additive updates and an algorithm that minimizes swap regret. For more specifics, please refer to: > Cotter, Jiang and Sridharan. "Two-Player Games for Efficient Non-Convex > Constrained Optimization". > [https://arxiv.org/abs/1804.06500](https://arxiv.org/abs/1804.06500) The formulation used by this optimizer can be found in Definition 2, and is discussed in Section 4. It is most similar to Algorithm 2 in Section 4, with the differences being that it uses `tf.compat.v1.train.Optimizer`s, instead of SGD, for the "inner" updates, and performs additive (instead of multiplicative) updates of the stochastic matrix. """ def __init__(self, optimizer, constraint_optimizer=None): """Constructs a new `AdditiveSwapRegretOptimizer`. Args: optimizer: tf.compat.v1.train.Optimizer, used to optimize the objective and proxy_constraints portion of ConstrainedMinimizationProblem. If constraint_optimizer is not provided, this will also be used to optimize the Lagrange multiplier analogues. constraint_optimizer: optional tf.compat.v1.train.Optimizer, used to optimize the Lagrange multiplier analogues. Returns: A new `AdditiveSwapRegretOptimizer`. """ # TODO(acotter): add a parameter determining the initial values of the # matrix elements (like initial_multiplier_radius in # MultiplicativeSwapRegretOptimizer). super(AdditiveSwapRegretOptimizer, self).__init__( optimizer=optimizer, constraint_optimizer=constraint_optimizer) def _initial_state(self, num_constraints): # For an AdditiveSwapRegretOptimizer, the internal state is a tensor of # shape (m+1,m+1), where m is the number of constraints, representing a # left-stochastic matrix. dimension = num_constraints + 1 # Initialize by putting all weight on the objective, and none on the # constraints. return standard_ops.concat((standard_ops.ones( (1, dimension)), standard_ops.zeros((dimension - 1, dimension))), axis=0) def _stochastic_matrix(self, state): return state def _constraint_grad_and_var(self, state, gradient): # TODO(acotter): tf.compat.v1.colocate_with(), # if colocate_gradients_with_ops is True? return (-gradient, state) def _projection_op(self, state, name=None): with ops.colocate_with(state): return state_ops.assign( state, _project_stochastic_matrix_wrt_euclidean_norm(state), name=name) class MultiplicativeSwapRegretOptimizer(_SwapRegretOptimizer): """A `ConstrainedOptimizer` based on swap-regret minimization. This `ConstrainedOptimizer` uses the given `tf.compat.v1.train.Optimizer`s to jointly minimize over the model parameters, and maximize over constraint/objective weight matrix (the analogue of Lagrange multipliers), with the latter maximization using multiplicative updates and an algorithm that minimizes swap regret. For more specifics, please refer to: > Cotter, Jiang and Sridharan. "Two-Player Games for Efficient Non-Convex > Constrained Optimization". > [https://arxiv.org/abs/1804.06500](https://arxiv.org/abs/1804.06500) The formulation used by this optimizer can be found in Definition 2, and is discussed in Section 4. It is most similar to Algorithm 2 in Section 4, with the difference being that it uses `tf.compat.v1.train.Optimizer`s, instead of SGD, for the "inner" updates. """ def __init__(self, optimizer, constraint_optimizer=None, minimum_multiplier_radius=1e-3, initial_multiplier_radius=None): """Constructs a new `MultiplicativeSwapRegretOptimizer`. Args: optimizer: tf.compat.v1.train.Optimizer, used to optimize the objective and proxy_constraints portion of ConstrainedMinimizationProblem. If constraint_optimizer is not provided, this will also be used to optimize the Lagrange multiplier analogues. constraint_optimizer: optional tf.compat.v1.train.Optimizer, used to optimize the Lagrange multiplier analogues. minimum_multiplier_radius: float, each element of the matrix will be lower bounded by `minimum_multiplier_radius` divided by one plus the number of constraints. initial_multiplier_radius: float, the initial value of each element of the matrix associated with a constraint (i.e. excluding those elements associated with the objective) will be `initial_multiplier_radius` divided by one plus the number of constraints. Defaults to the value of `minimum_multiplier_radius`. Returns: A new `MultiplicativeSwapRegretOptimizer`. Raises: ValueError: If the two radius parameters are inconsistent. """ super(MultiplicativeSwapRegretOptimizer, self).__init__( optimizer=optimizer, constraint_optimizer=constraint_optimizer) if (minimum_multiplier_radius <= 0.0) or (minimum_multiplier_radius >= 1.0): raise ValueError("minimum_multiplier_radius must be in the range (0,1)") if initial_multiplier_radius is None: initial_multiplier_radius = minimum_multiplier_radius elif (initial_multiplier_radius < minimum_multiplier_radius) or (minimum_multiplier_radius > 1.0): raise ValueError("initial_multiplier_radius must be in the range " "[minimum_multiplier_radius,1]") self._minimum_multiplier_radius = minimum_multiplier_radius self._initial_multiplier_radius = initial_multiplier_radius def _initial_state(self, num_constraints): # For a MultiplicativeSwapRegretOptimizer, the internal state is a tensor of # shape (m+1,m+1), where m is the number of constraints, representing the # element-wise logarithm of a left-stochastic matrix. dimension = num_constraints + 1 # Initialize by putting as much weight as possible on the objective, and as # little as possible on the constraints. log_initial_one = math.log(1.0 - (self._initial_multiplier_radius * (dimension - 1) / (dimension))) log_initial_zero = math.log(self._initial_multiplier_radius / dimension) # FUTURE WORK: make the dtype a parameter. return standard_ops.concat((standard_ops.constant( log_initial_one, dtype=dtypes.float32, shape=(1, dimension)), standard_ops.constant( log_initial_zero, dtype=dtypes.float32, shape=(dimension - 1, dimension))), axis=0) def _stochastic_matrix(self, state): return standard_ops.exp(state) def _constraint_grad_and_var(self, state, gradient): # TODO(acotter): tf.compat.v1.colocate_with(), # if colocate_gradients_with_ops is True? return (-gradient, state) def _projection_op(self, state, name=None): with ops.colocate_with(state): # Gets the dimension of the state (num_constraints + 1)--all of these # assertions are of things that should be impossible, since the state # passed into this method will have the same shape as that returned by # _initial_state(). state_shape = state.get_shape() assert state_shape is not None assert state_shape.ndims == 2 assert state_shape[0] == state_shape[1] dimension = state_shape.dims[0].value assert dimension is not None minimum_log_multiplier = standard_ops.log( self._minimum_multiplier_radius / standard_ops.to_float(dimension)) return state_ops.assign( state, standard_ops.maximum( _project_log_stochastic_matrix_wrt_kl_divergence(state), minimum_log_multiplier), name=name)
tensorflow-master
tensorflow/contrib/constrained_optimization/python/swap_regret_optimizer.py
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for constrained_optimization.python.candidates.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.contrib.constrained_optimization.python import candidates from tensorflow.python.platform import test class CandidatesTest(test.TestCase): def test_inconsistent_shapes_for_best_distribution(self): """An error is raised when parameters have inconsistent shapes.""" objective_vector = np.array([1, 2, 3]) constraints_matrix = np.array([[1, 2, 3, 4], [5, 6, 7, 8]]) with self.assertRaises(ValueError): _ = candidates.find_best_candidate_distribution(objective_vector, constraints_matrix) def test_inconsistent_shapes_for_best_index(self): """An error is raised when parameters have inconsistent shapes.""" objective_vector = np.array([1, 2, 3]) constraints_matrix = np.array([[1, 2, 3, 4], [5, 6, 7, 8]]) with self.assertRaises(ValueError): _ = candidates.find_best_candidate_index(objective_vector, constraints_matrix) def test_best_distribution(self): """Distribution should match known solution.""" objective_vector = np.array( [0.03053309, -0.06667082, 0.88355145, 0.46529806]) constraints_matrix = np.array( [[-0.60164551, 0.36676229, 0.7856454, -0.8441711], [0.00371592, -0.16392108, -0.59778071, -0.56908492]]) distribution = candidates.find_best_candidate_distribution( objective_vector, constraints_matrix) # Verify that the solution is a probability distribution. self.assertTrue(np.all(distribution >= -1e-6)) self.assertAlmostEqual(np.sum(distribution), 1.0) # Verify that the solution satisfies the constraints. maximum_constraint_violation = np.amax( np.dot(constraints_matrix, distribution)) self.assertLessEqual(maximum_constraint_violation, 1e-6) # Verify that the solution matches that which we expect. expected_distribution = np.array([0.37872711, 0.62127289, 0, 0]) self.assertAllClose(expected_distribution, distribution, rtol=0, atol=1e-6) def test_best_index_rank_objectives_true(self): """Index should match known solution.""" # Objective ranks = [2, 1, 4, 3]. objective_vector = np.array( [0.03053309, -0.06667082, 0.88355145, 0.46529806]) # Constraint ranks = [[1, 3, 4, 1], [4, 1, 1, 1]]. constraints_matrix = np.array( [[-0.60164551, 0.36676229, 0.7856454, -0.8441711], [0.00371592, -0.16392108, -0.59778071, -0.56908492]]) # Maximum ranks = [4, 3, 4, 3]. index = candidates.find_best_candidate_index( objective_vector, constraints_matrix, rank_objectives=True) self.assertEqual(1, index) def test_best_index_rank_objectives_false(self): """Index should match known solution.""" # Objective ranks = [2, 1, 4, 3]. objective_vector = np.array( [0.03053309, -0.06667082, 0.88355145, 0.46529806]) # Constraint ranks = [[1, 3, 4, 1], [4, 1, 1, 1]]. constraints_matrix = np.array( [[-0.60164551, 0.36676229, 0.7856454, -0.8441711], [0.00371592, -0.16392108, -0.59778071, -0.56908492]]) # Maximum ranks = [4, 3, 4, 1]. index = candidates.find_best_candidate_index( objective_vector, constraints_matrix, rank_objectives=False) self.assertEqual(3, index) if __name__ == "__main__": test.main()
tensorflow-master
tensorflow/contrib/constrained_optimization/python/candidates_test.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Ops for fused Cudnn RNN models. @@CudnnCompatibleGRUCell @@CudnnCompatibleLSTMCell @@CudnnGRU @@CudnnLSTM @@CudnnRNNRelu @@CudnnRNNTanh @@CudnnLSTMSaveable @@CudnnGRUSaveable @@CudnnRNNReluSaveable @@CudnnRNNTanhSaveable @@CudnnParamsFormatConverterLSTM @@CudnnParamsFormatConverterGRU @@CudnnParamsFormatConverterTanh @@CudnnParamsFormatConverterRelu """ from __future__ import absolute_import from __future__ import division from __future__ import print_function # pylint: disable=unused-import,wildcard-import from tensorflow.contrib.cudnn_rnn.python.layers import * # pylint: enable=unused-import,wildcard-import from tensorflow.python.util.all_util import remove_undocumented _allowed_symbols = [ "CudnnCompatibleGRUCell", "CudnnCompatibleLSTMCell", "CudnnGRU", "CudnnLSTM", "CudnnRNNRelu", "CudnnRNNTanh", "CudnnLSTMSaveable", "CudnnGRUSaveable", "CudnnRNNReluSaveable", "CudnnRNNTanhSaveable", "CudnnParamsFormatConverterLSTM", "CudnnParamsFormatConverterGRU", "CudnnParamsFormatConverterTanh", "CudnnParamsFormatConverterRelu", ] remove_undocumented(__name__, _allowed_symbols)
tensorflow-master
tensorflow/contrib/cudnn_rnn/__init__.py
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """layers module with higher level CudnnRNN primitives.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import sys # pylint: disable=unused-import,wildcard-import from tensorflow.contrib.cudnn_rnn.python.layers.cudnn_rnn import * # pylint: enable=unused-import,wildcard-import from tensorflow.contrib.cudnn_rnn.python.ops.cudnn_rnn_ops import CudnnCompatibleGRUCell from tensorflow.contrib.cudnn_rnn.python.ops.cudnn_rnn_ops import CudnnCompatibleLSTMCell from tensorflow.contrib.cudnn_rnn.python.ops.cudnn_rnn_ops import CudnnGRUSaveable from tensorflow.contrib.cudnn_rnn.python.ops.cudnn_rnn_ops import CudnnLSTMSaveable from tensorflow.contrib.cudnn_rnn.python.ops.cudnn_rnn_ops import CudnnParamsFormatConverterGRU from tensorflow.contrib.cudnn_rnn.python.ops.cudnn_rnn_ops import CudnnParamsFormatConverterLSTM from tensorflow.contrib.cudnn_rnn.python.ops.cudnn_rnn_ops import CudnnParamsFormatConverterRelu from tensorflow.contrib.cudnn_rnn.python.ops.cudnn_rnn_ops import CudnnParamsFormatConverterTanh from tensorflow.contrib.cudnn_rnn.python.ops.cudnn_rnn_ops import CudnnRNNReluSaveable from tensorflow.contrib.cudnn_rnn.python.ops.cudnn_rnn_ops import CudnnRNNTanhSaveable
tensorflow-master
tensorflow/contrib/cudnn_rnn/python/layers/__init__.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Cudnn RNN operators.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.contrib.cudnn_rnn.python.ops import cudnn_rnn_ops from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_shape from tensorflow.python.keras.engine import input_spec from tensorflow.python.layers import base as base_layer from tensorflow.python.ops import array_ops from tensorflow.python.ops import init_ops from tensorflow.python.ops import variable_scope as vs from tensorflow.python.platform import tf_logging as logging CUDNN_RNN_UNIDIRECTION = cudnn_rnn_ops.CUDNN_RNN_UNIDIRECTION CUDNN_RNN_BIDIRECTION = cudnn_rnn_ops.CUDNN_RNN_BIDIRECTION CUDNN_LSTM = cudnn_rnn_ops.CUDNN_LSTM CUDNN_GRU = cudnn_rnn_ops.CUDNN_GRU CUDNN_RNN_RELU = cudnn_rnn_ops.CUDNN_RNN_RELU CUDNN_RNN_TANH = cudnn_rnn_ops.CUDNN_RNN_TANH # Half for cell input, half for hidden states. CUDNN_LSTM_PARAMS_PER_LAYER = cudnn_rnn_ops.CUDNN_LSTM_PARAMS_PER_LAYER CUDNN_GRU_PARAMS_PER_LAYER = cudnn_rnn_ops.CUDNN_GRU_PARAMS_PER_LAYER CUDNN_RNN_TANH_PARAMS_PER_LAYER = cudnn_rnn_ops.CUDNN_RNN_TANH_PARAMS_PER_LAYER CUDNN_RNN_RELU_PARAMS_PER_LAYER = cudnn_rnn_ops.CUDNN_RNN_RELU_PARAMS_PER_LAYER CUDNN_INPUT_LINEAR_MODE = cudnn_rnn_ops.CUDNN_INPUT_LINEAR_MODE CUDNN_INPUT_SKIP_MODE = cudnn_rnn_ops.CUDNN_INPUT_SKIP_MODE CUDNN_INPUT_AUTO_MODE = cudnn_rnn_ops.CUDNN_INPUT_AUTO_MODE __all__ = ["CudnnLSTM", "CudnnGRU", "CudnnRNNTanh", "CudnnRNNRelu"] class _CudnnRNN(base_layer.Layer): # pylint:disable=line-too-long """Abstract class for RNN layers with Cudnn implementation. Cudnn RNNs have two major differences from other platform-independent RNNs tf provides: * Cudnn LSTM and GRU are mathematically different from their tf counterparts. (e.g. `tf.contrib.rnn.LSTMBlockCell` and `tf.compat.v1.nn.rnn_cell.GRUCell`. * Cudnn-trained checkpoints are not directly compatible with tf RNNs: * They use a single opaque parameter buffer for the entire (possibly) multi-layer multi-directional RNN; Whereas tf RNN weights are per-cell and layer. * The size and layout of the parameter buffers may change between CUDA/CuDNN/GPU generations. Because of that, the opaque parameter variable does not have a static shape and is not partitionable. Instead of using partitioning to alleviate the PS's traffic load, try building a multi-tower model and do gradient aggregation locally within the host before updating the PS. See https://www.tensorflow.org/performance/performance_models#parameter_server_variables for a detailed performance guide. Consequently, if one plans to use Cudnn trained models on both GPU and CPU for inference and training, one needs to: * Create a CudnnOpaqueParamsSaveable subclass object to save RNN params in canonical format. (This is done for you automatically during layer building process.) * When not using a Cudnn RNN class, use CudnnCompatibleRNN classes to load the checkpoints. These classes are platform-independent and perform the same computation as Cudnn for training and inference. Similarly, CudnnCompatibleRNN-trained checkpoints can be loaded by CudnnRNN classes seamlessly. Below is a typical workflow(using LSTM as an example): for detailed performance guide. # Use Cudnn-trained checkpoints with CudnnCompatibleRNNs ```python with tf.Graph().as_default(): lstm = CudnnLSTM(num_layers, num_units, direction, ...) outputs, output_states = lstm(inputs, initial_states, training=True) # If user plans to delay calling the cell with inputs, one can do # lstm.build(input_shape) saver = Saver() # training subgraph ... # Once in a while save the model. saver.save(save_path) # Inference subgraph for unidirectional RNN on, e.g., CPU or mobile. with tf.Graph().as_default(): single_cell = lambda: tf.contrib.cudnn_rnn.CudnnCompatibleLSTMCell(num_units) # NOTE: Even if there's only one layer, the cell needs to be wrapped in # MultiRNNCell. cell = tf.compat.v1.nn.rnn_cell.MultiRNNCell( [single_cell() for _ in range(num_layers)]) # Leave the scope arg unset. outputs, final_state = tf.compat.v1.nn.dynamic_rnn(cell, inputs, initial_state, ...) saver = Saver() # Create session sess = ... # Restores saver.restore(sess, save_path) # Inference subgraph for bidirectional RNN with tf.Graph().as_default(): single_cell = lambda: tf.contrib.cudnn_rnn.CudnnCompatibleLSTMCell(num_units) cells_fw = [single_cell() for _ in range(num_layers)] cells_bw = [single_cell() for _ in range(num_layers)] # Leave the scope arg unset. (outputs, output_state_fw, output_state_bw) = tf.contrib.rnn.stack_bidirectional_dynamic_rnn( cells_fw, cells_bw, inputs, ...) saver = Saver() # Create session sess = ... # Restores saver.restore(sess, save_path) ``` """ # pylint:enable=line-too-long # TODO(allenl): Document object-based saving and checkpoint compatibility once # it's implemented for more cuDNN Layers. # The following are constants defined by subclasses. # Type of RNN cell. _rnn_mode = None # Number of cell weights(or biases) per layer. _num_params_per_layer = None # Custom SaveableObject class for the CudnnRNN class. _saveable_cls = None def __init__(self, num_layers, num_units, input_mode=CUDNN_INPUT_LINEAR_MODE, direction=CUDNN_RNN_UNIDIRECTION, dropout=0., seed=None, dtype=dtypes.float32, kernel_initializer=None, bias_initializer=None, name=None): """Creates a CudnnRNN model from model spec. Args: num_layers: the number of layers for the RNN model. num_units: the number of units within the RNN model. input_mode: indicate whether there is a linear projection between the input and the actual computation before the first layer. It can be 'linear_input', 'skip_input' or 'auto_select'. 'linear_input' (default) always applies a linear projection of input onto RNN hidden state. (standard RNN behavior). 'skip_input' is only allowed when input_size == num_units; 'auto_select' implies 'skip_input' when input_size == num_units; otherwise, it implies 'linear_input'. direction: the direction model that the model operates. Can be either 'unidirectional' or 'bidirectional' dropout: dropout rate, a number between [0, 1]. Dropout is applied between each layer (no dropout is applied for a model with a single layer). When set to 0, dropout is disabled. seed: the op seed used for initializing dropout. See `tf.compat.v1.set_random_seed` for behavior. dtype: tf.float16, tf.float32 or tf.float64 kernel_initializer: starting value to initialize the weight. bias_initializer: starting value to initialize the bias (default is all zeros). name: VariableScope for the created subgraph; defaults to class name. This only serves the default scope if later no scope is specified when invoking __call__(). Raises: ValueError: if direction is invalid. Or dtype is not supported. """ super(_CudnnRNN, self).__init__(dtype=dtype, name=name) cudnn_rnn_ops.check_direction(direction) cudnn_rnn_ops.check_input_mode(input_mode) if dtype not in [dtypes.float16, dtypes.float32, dtypes.float64]: raise ValueError("Only support float16, float32, float64, provided %s" % dtype) # Layer self.dtype is type name, the original DType object is kept here. self._plain_dtype = dtype self._num_layers = num_layers self._num_units = num_units self._input_mode = input_mode self._direction = direction self._dropout = dropout self._seed = seed self._kernel_initializer = kernel_initializer self._bias_initializer = bias_initializer # Init input_size to None, which will be set after build(). self._input_size = None self._saveable = None @property def num_layers(self): return self._num_layers @property def num_units(self): return self._num_units @property def input_mode(self): """Input mode of first layer. Indicates whether there is a linear projection between the input and the actual computation before the first layer. It can be * 'linear_input': (default) always applies a linear projection of input onto RNN hidden state. (standard RNN behavior) * 'skip_input': 'skip_input' is only allowed when input_size == num_units. * 'auto_select'. implies 'skip_input' when input_size == num_units; otherwise, it implies 'linear_input'. Returns: 'linear_input', 'skip_input' or 'auto_select'. """ return self._input_mode @property def input_size(self): if not self._input_size: raise ValueError( "\'input_size\' is unknown since layer has not been built.") return self._input_size @property def rnn_mode(self): """Type of RNN cell used. Returns: `lstm`, `gru`, `rnn_relu` or `rnn_tanh`. """ return self._rnn_mode @property def direction(self): """Returns `unidirectional` or `bidirectional`.""" return self._direction @property def num_dirs(self): return 1 if self._direction == CUDNN_RNN_UNIDIRECTION else 2 @property def saveable(self): return self._saveable @property def canonical_weight_shapes(self): """Shapes of Cudnn canonical weight tensors.""" if not self._input_size: raise RuntimeError( "%s.canonical_weight_shapes invoked before input shape is known" % type(self).__name__) shapes = [] for i in range(self._num_layers): shapes.extend(self._canonical_weight_shape(i)) return shapes @property def canonical_bias_shapes(self): """Shapes of Cudnn canonical bias tensors.""" return self._canonical_bias_shape(0) * self._num_layers def _update_trainable_weights(self, getter, *args, **kwargs): """Custom getter for layer variables.""" # Add variables to layer's `(non_)trainable_weights` list(s). variable = getter(*args, **kwargs) trainable = kwargs.get("trainable", True) if trainable and variable not in self._trainable_weights: self._trainable_weights.append(variable) elif not trainable and variable not in self._non_trainable_weights: self._non_trainable_weights.append(variable) return variable def build(self, input_shape): """Create variables of the Cudnn RNN. It can be called manually before `__call__()` or automatically through `__call__()`. In the former case, subsequent `__call__()`s will skip creating variables. Args: input_shape: network input tensor shape, a python list or a TensorShape object with 3 dimensions. Raises: ValueError: if input_shape has wrong dimension or unknown 3rd dimension. """ if self.built: return input_shape = tensor_shape.TensorShape(input_shape) if input_shape.ndims != 3: raise ValueError("Expecting input_shape with 3 dims, got %d" % input_shape.ndims) if input_shape[-1].value is None: raise ValueError("The last dimension of the inputs to `CudnnRNN` " "should be defined. Found `None`.") self._input_size = input_shape[-1].value self.input_spec = input_spec.InputSpec(ndim=3, axes={-1: self._input_size}) self._set_scope(None) # Not using base class `add_variable()` since the it calls # `tf.compat.v1.get_variable()` with a callable initializer whereas here # with a tensor. The difference is mandated to support forward-compatibility # with Cudnn. with vs.variable_scope( self._scope, reuse=self.built, custom_getter=self._update_trainable_weights): if self._kernel_initializer is None: self._kernel_initializer = init_ops.glorot_uniform_initializer( seed=self._seed, dtype=self._plain_dtype) if self._bias_initializer is None: self._bias_initializer = init_ops.constant_initializer( 0.0, dtype=self._plain_dtype) weights = [ self._kernel_initializer(sp, dtype=self._plain_dtype) for sp in self.canonical_weight_shapes ] biases = [ self._bias_initializer(sp, dtype=self._plain_dtype) for sp in self.canonical_bias_shapes ] opaque_params_t = self._canonical_to_opaque(weights, biases) if vs.get_variable_scope().partitioner is not None: logging.warn( "Partitioner is not supported for Cudnn RNN layer variables, using " "it will create forward-compatibility issues with future " "CUDA/CuDNN generations.") # Initialize opaque params with a tensor with unknown shape, thus couldn't # use self.add_variable(name, shape, initializer, ...) self.kernel = vs.get_variable( "opaque_kernel", dtype=self._plain_dtype, initializer=opaque_params_t, validate_shape=False) # Create saveable in the outer scope of the cudnn subgraph, such that # alternative subgraph with platform-independent rnn cells can load the # checkpoints directly. if not (self.built or vs.get_variable_scope().reuse is True): self._create_saveable() self.built = True def _gather_saveables_for_checkpoint(self): raise NotImplementedError( "This cell does not yet support object-based saving. File a feature " "request if this limitation bothers you.") def call(self, inputs, initial_state=None, sequence_lengths=None, time_major=True, training=True): """Runs the forward step for the RNN model. Args: inputs: `3-D` tensor. If `time_major` is True (default), the Tensor shape is [time_len, batch_size, input_size]. If `time_major` is False, the shape is [batch_size, time_len, input_size]. initial_state: a tuple of tensor(s) of shape `[num_layers * num_dirs, batch_size, num_units]` if `time_major` is True (default) or `[batch_size, num_layers * num_dirs, num_units]` if `time_major` is False. If not provided, use zero initial states. The tuple size is 2 for LSTM and 1 for other RNNs. sequence_lengths: an int32 array representing the variable sequence lengths in a batch. The size of the array has to equal the batch_size. If not provided, the same sequence length will be assumed. time_major: The shape format of the `inputs` and `outputs` Tensors. If true, these Tensors must be shaped ['max_time', 'batch_size', 'depth']. If false, these Tensors must be shaped ['batch_size', 'max_time', 'depth']. By default this function accepts input and emits output in time-major form. This param is only effective when 'sequence_lengths' is used. training: whether this operation will be used in training or inference. Returns: output: a tensor of shape `[time_len, batch_size, num_dirs * num_units]` if `time_major` is True (default) or `[batch_size, time_len, num_dirs * num_units]` if `time_major` is False. It is a `concat([fwd_output, bak_output], axis=2)`. output_states: a tuple of tensor(s) of the same shape and structure as `initial_state`. Raises: TypeError: initial_state is not a tuple. """ if initial_state is not None and not isinstance(initial_state, tuple): raise TypeError("Invalid initial_state type: %s, expecting tuple." % initial_state) dtype = self.dtype inputs = ops.convert_to_tensor(inputs, dtype=dtype) batch_size = array_ops.shape(inputs)[1] if initial_state is None: initial_state = self._zero_state(batch_size) if self._rnn_mode == CUDNN_LSTM: h, c = initial_state # pylint:disable=unbalanced-tuple-unpacking,unpacking-non-sequence else: h, = initial_state # pylint:disable=unbalanced-tuple-unpacking,unpacking-non-sequence h = ops.convert_to_tensor(h, dtype=dtype) if self._rnn_mode == CUDNN_LSTM: c = ops.convert_to_tensor(c, dtype=dtype) else: # For model that doesn't take input_c, replace with a dummy tensor. c = array_ops.constant([], dtype=dtype) outputs, (output_h, output_c) = self._forward(inputs, h, c, self.kernel, sequence_lengths, time_major, training) if self._rnn_mode == CUDNN_LSTM: return outputs, (output_h, output_c) else: return outputs, (output_h,) def state_shape(self, batch_size): raise NotImplementedError def _zero_state(self, batch_size): res = [] for sp in self.state_shape(batch_size): res.append(array_ops.zeros(sp, dtype=self.dtype)) return tuple(res) def _canonical_weight_shape(self, layer): """Shapes of Cudnn canonical weight tensors for given layer.""" if layer < 0 or layer >= self._num_layers: raise ValueError("\'layer\' is not valid, got %s, expecting [%d, %d]" % (layer, 0, self._num_layers - 1)) if not self._input_size: raise RuntimeError( "%s._canonical_weight_shape invoked before input shape is known" % type(self).__name__) input_size = self._input_size num_units = self._num_units num_gates = self._num_params_per_layer // 2 is_bidi = self._direction == CUDNN_RNN_BIDIRECTION if layer == 0: wts_applied_on_inputs = [(num_units, input_size)] * num_gates else: if is_bidi: wts_applied_on_inputs = [(num_units, 2 * num_units)] * num_gates else: wts_applied_on_inputs = [(num_units, num_units)] * num_gates wts_applied_on_hidden_states = [(num_units, num_units)] * num_gates tf_wts = wts_applied_on_inputs + wts_applied_on_hidden_states return tf_wts if not is_bidi else tf_wts * 2 def _canonical_bias_shape(self, unused_layer): """Shapes of Cudnn canonical bias tensors for given layer.""" num_dirs = 1 if self._direction == CUDNN_RNN_UNIDIRECTION else 2 return [[self._num_units]] * num_dirs * self._num_params_per_layer def _canonical_to_opaque(self, cu_weights, cu_biases): if not self._input_size: raise RuntimeError( "%s._canonical_to_opaque invoked before input shape is known" % type(self).__name__) with ops.device("/gpu:0"): return cudnn_rnn_ops.cudnn_rnn_canonical_to_opaque_params( rnn_mode=self._rnn_mode, num_layers=self._num_layers, num_units=self._num_units, input_size=self._input_size, weights=cu_weights, biases=cu_biases, input_mode=self._input_mode, seed=self._seed, dropout=self._dropout, direction=self._direction) def _forward(self, inputs, h, c, opaque_params, sequence_lengths, time_major, training): output, output_h, output_c = cudnn_rnn_ops._cudnn_rnn( # pylint:disable=protected-access inputs, h, c, opaque_params, training, self._rnn_mode, sequence_lengths=sequence_lengths, time_major=time_major, input_mode=self._input_mode, direction=self._direction, dropout=self._dropout, seed=self._seed) return output, (output_h, output_c) def _create_saveable(self): """Create custom saveable for the Cudnn layer. Called during layer building process to make sharing checkpoints between Cudnn and Cudnn-compatible RNNs easy. Returns: a `CudnnOpaqueParamsSaveable` object. Raises: RuntimeError: if any custom saveable is already created for this layer. """ if self._saveable is not None: raise RuntimeError("Cudnn saveable already created.") self._saveable = self._saveable_cls( # pylint:disable=not-callable opaque_params=self.trainable_variables[0], num_layers=self.num_layers, num_units=self.num_units, input_size=self.input_size, input_mode=self.input_mode, direction=self.direction, scope=vs.get_variable_scope(), name="%s_saveable" % self.trainable_variables[0].name.split(":")[0]) self._saveable._add_trackable_dependencies( # pylint: disable=protected-access trackable=self, dtype=self._plain_dtype) ops.add_to_collection(ops.GraphKeys.SAVEABLE_OBJECTS, self._saveable) class CudnnLSTM(_CudnnRNN): """Cudnn implementation of LSTM layer.""" _rnn_mode = CUDNN_LSTM _num_params_per_layer = CUDNN_LSTM_PARAMS_PER_LAYER _saveable_cls = cudnn_rnn_ops.CudnnLSTMSaveable def state_shape(self, batch_size): """Shape of Cudnn LSTM states. Shape is a 2-element tuple. Each is [num_layers * num_dirs, batch_size, num_units] Args: batch_size: an int Returns: a tuple of python arrays. """ return ([self.num_layers * self.num_dirs, batch_size, self.num_units], [self.num_layers * self.num_dirs, batch_size, self.num_units]) @property def _gather_saveables_for_checkpoint(self): if self._direction == CUDNN_RNN_UNIDIRECTION: # Skip one inheritance level to avoid NotImplementedError. return super(_CudnnRNN, self)._gather_saveables_for_checkpoint else: raise NotImplementedError( "Object-based saving does not currently support bidirectional LSTM " "cells. File a feature request if this limitation bothers you.") class _CudnnRNNNoInputC(_CudnnRNN): """Abstract simple CudnnRNN layer without input_c.""" def state_shape(self, batch_size): """Shape of the state of Cudnn RNN cells w/o. input_c. Shape is a 1-element tuple, [num_layers * num_dirs, batch_size, num_units] Args: batch_size: an int Returns: a tuple of python arrays. """ return [self.num_layers * self.num_dirs, batch_size, self.num_units], class CudnnGRU(_CudnnRNNNoInputC): """Cudnn implementation of the GRU layer.""" _rnn_mode = CUDNN_GRU _num_params_per_layer = CUDNN_GRU_PARAMS_PER_LAYER _saveable_cls = cudnn_rnn_ops.CudnnGRUSaveable class CudnnRNNTanh(_CudnnRNNNoInputC): """Cudnn implementation of the RNN-tanh layer.""" _rnn_mode = CUDNN_RNN_TANH _num_params_per_layer = CUDNN_RNN_TANH_PARAMS_PER_LAYER _saveable_cls = cudnn_rnn_ops.CudnnRNNTanhSaveable class CudnnRNNRelu(_CudnnRNNNoInputC): """Cudnn implementation of the RNN-relu layer.""" _rnn_mode = CUDNN_RNN_RELU _num_params_per_layer = CUDNN_RNN_RELU_PARAMS_PER_LAYER _saveable_cls = cudnn_rnn_ops.CudnnRNNReluSaveable
tensorflow-master
tensorflow/contrib/cudnn_rnn/python/layers/cudnn_rnn.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Benchmarks for Cudnn RNN models.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import time from six.moves import xrange # pylint: disable=redefined-builtin from tensorflow.contrib import rnn as contrib_rnn from tensorflow.contrib.cudnn_rnn.python.ops import cudnn_rnn_ops from tensorflow.contrib.rnn.python.ops import lstm_ops from tensorflow.python.client import session from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import gradients_impl from tensorflow.python.ops import rnn from tensorflow.python.ops import variables from tensorflow.python.platform import test class CudnnRNNBenchmark(test.Benchmark): """Benchmarks Cudnn LSTM and other related models. """ def _GetTestConfig(self): return { "large": { "num_layers": 4, "num_units": 1024, "seq_length": 50, "batch_size": 64, }, "medium": { "num_layers": 4, "num_units": 512, "seq_length": 50, "batch_size": 64, }, "small": { "num_layers": 4, "num_units": 128, "seq_length": 50, "batch_size": 64, }, } def _GetConfigDesc(self, config): num_layers = config["num_layers"] num_units = config["num_units"] batch_size = config["batch_size"] seq_length = config["seq_length"] return "y%d_u%d_b%d_q%d" % (num_layers, num_units, batch_size, seq_length) def _BenchmarkOp(self, op, desc): burn_in_steps = 10 benchmark_steps = 20 with session.Session() as sess: sess.run(variables.global_variables_initializer()) for i in xrange(burn_in_steps + benchmark_steps): if i == burn_in_steps: start_time = time.time() sess.run(op) total_time = time.time() - start_time step_time = total_time / benchmark_steps print("%s takes %.4f sec/step" % (desc, step_time)) self.report_benchmark( name=desc, iters=benchmark_steps, wall_time=total_time) def benchmarkCudnnLSTMTraining(self): test_configs = self._GetTestConfig() for config_name, config in test_configs.items(): config = test_configs[config_name] num_layers = config["num_layers"] num_units = config["num_units"] batch_size = config["batch_size"] seq_length = config["seq_length"] with ops.Graph().as_default(), ops.device("/device:GPU:0"): model = cudnn_rnn_ops.CudnnLSTM(num_layers, num_units, num_units) params_size_t = model.params_size() input_data = variables.Variable( array_ops.ones([seq_length, batch_size, num_units])) input_h = variables.Variable( array_ops.ones([num_layers, batch_size, num_units])) input_c = variables.Variable( array_ops.ones([num_layers, batch_size, num_units])) params = variables.Variable( array_ops.ones([params_size_t]), validate_shape=False) output, output_h, output_c = model( is_training=True, input_data=input_data, input_h=input_h, input_c=input_c, params=params) all_grads = gradients_impl.gradients( [output, output_h, output_c], [params, input_data, input_h, input_c]) training_op = control_flow_ops.group(*all_grads) self._BenchmarkOp(training_op, "cudnn_lstm %s %s" % (config_name, self._GetConfigDesc(config))) def benchmarkTfRNNLSTMTraining(self): test_configs = self._GetTestConfig() for config_name, config in test_configs.items(): num_layers = config["num_layers"] num_units = config["num_units"] batch_size = config["batch_size"] seq_length = config["seq_length"] with ops.Graph().as_default(), ops.device("/device:GPU:0"): inputs = array_ops.zeros([batch_size, seq_length, num_units], dtypes.float32) multi_cell = contrib_rnn.MultiRNNCell( [contrib_rnn.BasicLSTMCell(num_units) for _ in range(num_layers)]) outputs, final_state = rnn.dynamic_rnn( multi_cell, inputs, dtype=dtypes.float32) trainable_variables = ops.get_collection( ops.GraphKeys.TRAINABLE_VARIABLES) gradients = gradients_impl.gradients([outputs, final_state], trainable_variables) training_op = control_flow_ops.group(*gradients) self._BenchmarkOp(training_op, "tf_rnn_lstm %s %s" % (config_name, self._GetConfigDesc(config))) def benchmarkTfRNNLSTMBlockCellTraining(self): test_configs = self._GetTestConfig() for config_name, config in test_configs.items(): num_layers = config["num_layers"] num_units = config["num_units"] batch_size = config["batch_size"] seq_length = config["seq_length"] with ops.Graph().as_default(), ops.device("/device:GPU:0"): inputs = array_ops.zeros([batch_size, seq_length, num_units], dtypes.float32) multi_cell = contrib_rnn.MultiRNNCell( [lstm_ops.LSTMBlockCell(num_units) for _ in range(num_layers)]) outputs, final_state = rnn.dynamic_rnn( multi_cell, inputs, dtype=dtypes.float32) trainable_variables = ops.get_collection( ops.GraphKeys.TRAINABLE_VARIABLES) gradients = gradients_impl.gradients([outputs, final_state], trainable_variables) training_op = control_flow_ops.group(*gradients) self._BenchmarkOp(training_op, "tf_rnn_lstm_block_cell %s %s" % (config_name, self._GetConfigDesc(config))) if __name__ == "__main__": test.main()
tensorflow-master
tensorflow/contrib/cudnn_rnn/python/kernel_tests/cudnn_rnn_ops_benchmark.py
# -*- coding: utf-8 -*- # Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for Cudnn RNN models.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import itertools import os from absl.testing import parameterized import numpy as np from tensorflow.contrib.cudnn_rnn.python.ops import cudnn_rnn_ops from tensorflow.core.protobuf import saver_pb2 from tensorflow.python.compat import compat from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.framework import random_seed from tensorflow.python.framework import test_util from tensorflow.python.ops import array_ops from tensorflow.python.ops import gradients_impl from tensorflow.python.ops import init_ops from tensorflow.python.ops import random_ops from tensorflow.python.ops import rnn from tensorflow.python.ops import rnn_cell_impl from tensorflow.python.ops import state_ops from tensorflow.python.ops import variable_scope from tensorflow.python.ops import variables from tensorflow.python.platform import googletest from tensorflow.python.platform import tf_logging as logging from tensorflow.python.training import saver as saver_lib CUDNN_RNN_UNIDIRECTION = cudnn_rnn_ops.CUDNN_RNN_UNIDIRECTION CUDNN_RNN_BIDIRECTION = cudnn_rnn_ops.CUDNN_RNN_BIDIRECTION CUDNN_LSTM = cudnn_rnn_ops.CUDNN_LSTM CUDNN_GRU = cudnn_rnn_ops.CUDNN_GRU CUDNN_RNN_RELU = cudnn_rnn_ops.CUDNN_RNN_RELU CUDNN_RNN_TANH = cudnn_rnn_ops.CUDNN_RNN_TANH CUDNN_LSTM_PARAMS_PER_LAYER = cudnn_rnn_ops.CUDNN_LSTM_PARAMS_PER_LAYER CUDNN_GRU_PARAMS_PER_LAYER = cudnn_rnn_ops.CUDNN_GRU_PARAMS_PER_LAYER CUDNN_RNN_TANH_PARAMS_PER_LAYER = cudnn_rnn_ops.CUDNN_RNN_TANH_PARAMS_PER_LAYER CUDNN_RNN_RELU_PARAMS_PER_LAYER = cudnn_rnn_ops.CUDNN_RNN_RELU_PARAMS_PER_LAYER def RunLSTM(sess, num_units, input_size, batch_size, time, num_layers=1, variable_seq_lengths=False, time_major=True, dynamic_shape_input=False, is_training=True, dropout=0., num_dirs=True, dtype=dtypes.float32, num_proj=None): # TODO(jamesqin): add multi-layer tests. # TODO(jamesqin): add multi-dir tests assert num_layers == 1 assert num_dirs == 1 if is_training and not np.isclose(dropout, 0): raise ValueError("dropout can not be 0. when test training.") # set graph level random seed and numpy random seed. random_seed.set_random_seed(0) np.random.seed(0) shape = ([time, batch_size, input_size] if time_major else [batch_size, time, input_size]) inputs_np = np.random.rand(*shape).astype(dtype.as_numpy_dtype) inputs_static = variable_scope.get_variable( "inputs", initializer=inputs_np, dtype=dtype) inputs_dynamic = array_ops.placeholder( dtype, shape=[None, None, None], name="inputs") inputs = inputs_dynamic if dynamic_shape_input else inputs_static unified_num_units = num_proj if num_proj else num_units unified_num_proj = num_proj if num_proj else None initial_h_op = variable_scope.get_variable( "initial_h_op", initializer=np.random.rand(batch_size, unified_num_units).astype( dtype.as_numpy_dtype), dtype=dtype) initial_c_op = variable_scope.get_variable( "initial_c_op", initializer=np.random.rand(batch_size, num_units).astype(dtype.as_numpy_dtype), dtype=dtype) if variable_seq_lengths: lengths_v = np.random.randint(low=1, high=time + 1, size=batch_size) lengths_v[0] = time # make sure the max sequence has 'time' elems lengths = ops.convert_to_tensor(lengths_v.astype(np.int32)) else: lengths = None initializer = init_ops.random_uniform_initializer( -0.01, 0.01, dtype=dtype, seed=19980904) with variable_scope.variable_scope("test", initializer=initializer): w = variable_scope.get_variable( "rnn/lstm_cell/kernel", shape=[input_size + unified_num_units, num_units * 4], dtype=dtype) b = variable_scope.get_variable( "rnn/lstm_cell/bias", shape=[num_units * 4], dtype=dtype) if num_proj: pw = variable_scope.get_variable( "rnn/lstm_cell/projection/kernel", shape=[num_units, num_proj], dtype=dtype) # canonical lstm. must set forget_bias to 0. to align with cudnn lstm. cell = rnn_cell_impl.LSTMCell( num_units, forget_bias=0., reuse=True, num_proj=unified_num_proj) outputs_op, state_tuple_op = rnn.dynamic_rnn( cell, inputs_static, sequence_length=lengths, initial_state=rnn_cell_impl.LSTMStateTuple( h=initial_h_op, c=initial_c_op), dtype=dtype, time_major=time_major, scope=None) # Convert to cudnn opaque param. format_converter = cudnn_rnn_ops.CudnnParamsFormatConverterLSTM( num_layers, num_units, input_size, num_proj=unified_num_proj) if num_proj: opaque_params = format_converter.tf_canonical_to_opaque([w, b], [ pw, ]) else: opaque_params = format_converter.tf_canonical_to_opaque([w, b]) cu_initial_h_op = array_ops.expand_dims( initial_h_op, axis=(0 if time_major else 1)) cu_initial_c_op = array_ops.expand_dims( initial_c_op, axis=(0 if time_major else 1)) cu_outputs_op, cu_h_op, cu_c_op = cudnn_rnn_ops._cudnn_rnn( inputs, cu_initial_h_op, cu_initial_c_op, opaque_params, sequence_lengths=lengths, time_major=time_major, dropout=dropout, is_training=is_training, rnn_mode=cudnn_rnn_ops.CUDNN_LSTM, num_proj=unified_num_proj) # Remove the trivial 1st dimension. cu_state_tuple_op = rnn_cell_impl.LSTMStateTuple( c=array_ops.squeeze(cu_c_op, axis=0 if time_major else 1), h=array_ops.squeeze(cu_h_op, axis=0 if time_major else 1)) if is_training: if num_proj: (inp_grad_op, hgrad_op, cgrad_op, wgrad_op, bgrad_op, pwgrad_op) = gradients_impl.gradients( outputs_op, [inputs_static, initial_h_op, initial_c_op, w, b, pw]) else: (inp_grad_op, hgrad_op, cgrad_op, wgrad_op, bgrad_op) = gradients_impl.gradients( outputs_op, [inputs_static, initial_h_op, initial_c_op, w, b]) (cu_inp_grad_op, cu_hgrad_op, cu_cgrad_op, opaque_grad_op) = gradients_impl.gradients( cu_outputs_op, [inputs, cu_initial_h_op, cu_initial_c_op, opaque_params]) # Remove the trivial 1st dimension cu_hgrad_op = array_ops.squeeze(cu_hgrad_op, axis=0 if time_major else 1) # Remove the trivial 1st dimension cu_cgrad_op = array_ops.squeeze(cu_cgrad_op, axis=0 if time_major else 1) if num_proj: cu_wgrad_op, cu_bgrad_op, cu_pwgrad_op = \ format_converter.opaque_to_tf_canonical(opaque_grad_op) else: cu_wgrad_op, cu_bgrad_op = format_converter.opaque_to_tf_canonical( opaque_grad_op) cu_wgrad_op = cu_wgrad_op[0] cu_bgrad_op = cu_bgrad_op[0] if num_proj: cu_pwgrad_op = cu_pwgrad_op[0] # cudnn lstm has 2 biases each gate. When converting to tf canonical format, # the two biases are summed into one. Thus here bias gradient should be # halved when comparing with tf lstm. cu_bgrad_op *= 0.5 init_op = variables.global_variables_initializer() sess.run(init_op) if is_training: if num_proj: (outputs, state_tuple, inp_grad, state_grad, wgrad, bgrad, pwgrad) = sess.run([ outputs_op, state_tuple_op, inp_grad_op, (hgrad_op, cgrad_op), wgrad_op, bgrad_op, pwgrad_op ]) (cu_outputs, cu_state_tuple, cu_inp_grad, cu_state_grad, cu_wgrad, cu_bgrad, cu_pwgrad) = sess.run( [ cu_outputs_op, cu_state_tuple_op, cu_inp_grad_op, (cu_hgrad_op, cu_cgrad_op), cu_wgrad_op, cu_bgrad_op, cu_pwgrad_op ], feed_dict={inputs: inputs_np} if dynamic_shape_input else None) else: outputs, state_tuple, inp_grad, state_grad, wgrad, bgrad = sess.run([ outputs_op, state_tuple_op, inp_grad_op, (hgrad_op, cgrad_op), wgrad_op, bgrad_op ]) (cu_outputs, cu_state_tuple, cu_inp_grad, cu_state_grad, cu_wgrad, cu_bgrad) = sess.run( [ cu_outputs_op, cu_state_tuple_op, cu_inp_grad_op, (cu_hgrad_op, cu_cgrad_op), cu_wgrad_op, cu_bgrad_op ], feed_dict={inputs: inputs_np} if dynamic_shape_input else None) logging.vlog(1, "outputs: %s" % outputs) logging.vlog(1, "cu_outputs: %s" % cu_outputs) logging.vlog(1, "state_tuple: %s" % str(state_tuple)) logging.vlog(1, "cu_state_tuple: %s" % str(cu_state_tuple)) logging.vlog(1, "inp_grad: %s" % inp_grad) logging.vlog(1, "cu_inp_grad: %s" % cu_inp_grad) logging.vlog(1, "state_grad: %s" % str(state_grad)) logging.vlog(1, "cu_state_grad: %s" % str(cu_state_grad)) logging.vlog(1, "wgrad: %s" % str(wgrad)) logging.vlog(1, "bgrad: %s" % str(bgrad)) if num_proj: logging.vlog(1, "pwgrad: %s" % str(bgrad)) logging.vlog(1, "cu_wgrad: %s" % str(cu_wgrad)) logging.vlog(1, "cu_bgrad: %s" % str(cu_bgrad)) if num_proj: logging.vlog(1, "cu_pwgrad: %s" % str(cu_bgrad)) if num_proj: return (outputs, cu_outputs, state_tuple, cu_state_tuple, inp_grad, cu_inp_grad, state_grad, cu_state_grad, wgrad, bgrad, pwgrad, cu_wgrad, cu_bgrad, cu_pwgrad) else: return (outputs, cu_outputs, state_tuple, cu_state_tuple, inp_grad, cu_inp_grad, state_grad, cu_state_grad, wgrad, bgrad, cu_wgrad, cu_bgrad) else: outputs, state_tuple = sess.run([outputs_op, state_tuple_op]) cu_outputs, cu_state_tuple = sess.run([cu_outputs_op, cu_state_tuple_op], feed_dict=({ inputs: inputs_np } if dynamic_shape_input else None)) logging.vlog(1, "outputs: %s" % outputs) logging.vlog(1, "cu_outputs: %s" % cu_outputs) logging.vlog(1, "state_tuple: %s" % str(state_tuple)) logging.vlog(1, "cu_state_tuple: %s" % str(cu_state_tuple)) return outputs, cu_outputs, state_tuple, cu_state_tuple # Basic set of RNN configs to test. They can be further extended in relevant # test (e.g. adding num_dirs). NAMED_RNN_TESTCASES = ({ "testcase_name": "xsmall", "num_units": 1, "input_size": 1, "batch_size": 1, "time": 1, "num_layers": 1, }, { "testcase_name": "small", "num_units": 4, "input_size": 4, "batch_size": 4, "time": 4, "num_layers": 1, }, { "testcase_name": "medium", "num_units": 128, "input_size": 64, "batch_size": 8, "time": 16, "num_layers": 1, }, { "testcase_name": "large", "num_units": 128, "input_size": 128, "batch_size": 16, "time": 32, "num_layers": 1, }) def ExpandNamedTestCases(inputs, *remove_keys, **extra_configs): """Expands testcase with new config dimensions. Example: inputs = ( {'testcase_name': 'test1', 'gender': 'male'} {'testcase_name': 'test2', 'gender': 'female'} ) remove_keys: empty extra_configs = { 'age': [40, 80] 'height': [5, 6] } Returns: ( {'testcase_name': 'test1_age_40_height_5','gender': 'male', 'age': 40,'height': 5} {'testcase_name': 'test1_age_40_height_6', 'gender': 'male', 'age': 40, 'height': 6} {'testcase_name': 'test1_age_80_height_5', 'gender': 'male', 'age': 80, 'height': 5} {'testcase_name': 'test1_age_80_height_6', 'gender': 'male', 'age': 80, 'height': 6} {'testcase_name': 'test2_age_40_height_5', 'gender': 'female', 'age': 40, 'height': 5} {'testcase_name': 'test2_age_40_height_6', 'gender': 'female', 'age': 40, 'height': 6} {'testcase_name': 'test2_age_80_height_5', 'gender': 'female', 'age': 80, 'height': 5} {'testcase_name': 'test2_age_80_height_6', 'gender': 'female', 'age': 80, 'height': 6} ) Args: inputs: A list of dictionary, each being a testcase. *remove_keys: A list of keys into testcase which are not needed in new testcases. **extra_configs: A dict of new test dimension and applicable values in that dimension. Returns: A list of dictionary with expanded test cases. """ res = [] ordered_extra_configs = collections.OrderedDict(extra_configs) keys = ordered_extra_configs.keys() # A list of list of configs. # The outer loop is iterating keys, the innner is values of one key. combined_kv = [[(k, v) for v in ordered_extra_configs[k]] for k in keys] logging.info("combined_kv: %s", combined_kv) for inp in inputs: # Each inp is a dict for config in itertools.product(*combined_kv): new_inp = dict(inp) # config is a list in the form of [(k_i, v_j), (k_p, v_q), ...] suffix = ["%s_%s" % (p[0], str(p[1])) for p in config] suffix = "_".join(suffix) new_inp["testcase_name"] += "_" + suffix for k, v in config: new_inp[k] = v # Remove not used keys from the new test case. if remove_keys: if not isinstance(remove_keys, (list, tuple)): remove_keys = [remove_keys] for k in remove_keys: new_inp.pop(k, None) logging.info("new_inp: %s", new_inp) res.append(new_inp) # Dedup, necessary if `remove_keys` is set. return [dict(t) for t in {tuple(d.items()) for d in res}] class CudnnLSTMTest(test_util.TensorFlowTestCase, parameterized.TestCase): def _test_training_helper(self, num_units, input_size, batch_size, time, num_layers, dtype, variable_seq_lengths, time_major, dynamic_shape_input=False, rtol=3e-6, atol=3e-6, num_proj=None): with self.session(use_gpu=True) as sess: if num_proj is not None and num_proj != 0: (outputs, cu_outputs, state_tuple, cu_state_tuple, inp_grad, cu_inp_grad, state_grad, cu_state_grad, wgrad, bgrad, pwgrad, cu_wgrad, cu_bgrad, cu_pwgrad) = RunLSTM( sess, num_units, input_size, batch_size, time, num_layers, variable_seq_lengths=variable_seq_lengths, dynamic_shape_input=dynamic_shape_input, num_proj=num_proj) else: (outputs, cu_outputs, state_tuple, cu_state_tuple, inp_grad, cu_inp_grad, state_grad, cu_state_grad, wgrad, bgrad, cu_wgrad, cu_bgrad) = RunLSTM( sess, num_units, input_size, batch_size, time, num_layers, variable_seq_lengths=variable_seq_lengths, dynamic_shape_input=dynamic_shape_input, num_proj=num_proj) self.assertAllClose(outputs, cu_outputs, rtol=rtol, atol=atol) for s, cu_s in zip(state_tuple, cu_state_tuple): self.assertAllClose(s, cu_s, rtol=rtol, atol=atol) for sg, cu_sg in zip(state_grad, cu_state_grad): self.assertAllClose(sg, cu_sg, rtol=rtol, atol=atol) self.assertAllClose(inp_grad, cu_inp_grad, rtol=rtol, atol=atol) self.assertAllClose(bgrad, cu_bgrad, rtol=rtol, atol=atol) self.assertAllClose(wgrad, cu_wgrad, rtol=rtol, atol=atol) if num_proj is not None and num_proj != 0: self.assertAllClose(pwgrad, cu_pwgrad, rtol=rtol, atol=atol) @parameterized.named_parameters( ExpandNamedTestCases( NAMED_RNN_TESTCASES, **{ "variable_seq_lengths": [True, False], "time_major": [True, False], "dynamic_shape_input": [True, False], "use_proj": [True, False], })) @test_util.run_gpu_only def test_training(self, num_units, input_size, batch_size, time, num_layers, variable_seq_lengths, time_major, dynamic_shape_input, use_proj): with compat.forward_compatibility_horizon(2019, 6, 27): num_proj = num_units // 2 if use_proj and num_proj == 0: self.skipTest("num_proj cannot be 0") self._test_training_helper( num_units, input_size, batch_size, time, num_layers, dtypes.float32, variable_seq_lengths=variable_seq_lengths, time_major=time_major, dynamic_shape_input=dynamic_shape_input, num_proj=num_proj if use_proj else None) @parameterized.named_parameters( ExpandNamedTestCases( NAMED_RNN_TESTCASES, **{ "variable_seq_lengths": [True, False], "time_major": [True, False], "dynamic_shape_input": [True, False], "use_proj": [True, False], })) @test_util.run_gpu_only def test_training_fp16(self, num_units, input_size, batch_size, time, num_layers, variable_seq_lengths, time_major, dynamic_shape_input, use_proj): with compat.forward_compatibility_horizon(2019, 6, 27): num_proj = num_units // 2 if use_proj and num_proj == 0: self.skipTest("num_proj cannot be 0") self._test_training_helper( num_units, input_size, batch_size, time, num_layers, dtypes.float16, rtol=5e-3, atol=5e-4, variable_seq_lengths=variable_seq_lengths, time_major=time_major, dynamic_shape_input=dynamic_shape_input, num_proj=num_proj if use_proj else None) @parameterized.named_parameters( ExpandNamedTestCases( NAMED_RNN_TESTCASES, **{ "variable_seq_lengths": [True, False], "time_major": [True, False], "dynamic_shape_input": [True, False], "use_proj": [True, False], })) @test_util.run_gpu_only def test_inference(self, num_units, input_size, batch_size, time, num_layers, variable_seq_lengths, time_major, dynamic_shape_input, use_proj): with compat.forward_compatibility_horizon(2019, 6, 27): num_proj = num_units // 2 if use_proj and num_proj == 0: self.skipTest("num_proj cannot be 0") with self.session(use_gpu=True) as sess: (outputs, cu_outputs, state_tuple, cu_state_tuple) = RunLSTM( sess, num_units, input_size, batch_size, time, num_layers, is_training=False, variable_seq_lengths=variable_seq_lengths, time_major=time_major, dynamic_shape_input=dynamic_shape_input, num_proj=num_proj if use_proj else None) self.assertAllClose(outputs, cu_outputs) # h self.assertAllClose(state_tuple.h, cu_state_tuple.h) # c self.assertAllClose(state_tuple.c, cu_state_tuple.c) @parameterized.named_parameters( ExpandNamedTestCases( NAMED_RNN_TESTCASES, **{ "variable_seq_lengths": [True, False], "time_major": [True, False], "dynamic_shape_input": [True, False], "use_proj": [True, False], })) @test_util.run_gpu_only def test_inference_fp16(self, num_units, input_size, batch_size, time, num_layers, variable_seq_lengths, time_major, dynamic_shape_input, use_proj): with compat.forward_compatibility_horizon(2019, 6, 27): num_proj = num_units // 2 if use_proj and num_proj == 0: self.skipTest("num_proj cannot be 0") with self.session(use_gpu=True) as sess: (outputs, cu_outputs, state_tuple, cu_state_tuple) = RunLSTM( sess, num_units, input_size, batch_size, time, num_layers, is_training=False, dtype=dtypes.float16, variable_seq_lengths=variable_seq_lengths, time_major=time_major, dynamic_shape_input=dynamic_shape_input, num_proj=num_proj if use_proj else None) rtol, atol = 5e-3, 5e-4 self.assertAllClose(outputs, cu_outputs, rtol=rtol, atol=atol) # h self.assertAllClose( state_tuple.h, cu_state_tuple.h, rtol=rtol, atol=atol) # c self.assertAllClose( state_tuple.c, cu_state_tuple.c, rtol=rtol, atol=atol) @parameterized.named_parameters( ExpandNamedTestCases( NAMED_RNN_TESTCASES, **{ "variable_seq_lengths": [True, False], "time_major": [True, False], "dynamic_shape_input": [True, False], "use_proj": [True, False], })) @test_util.run_gpu_only def test_inference_with_dropout(self, num_units, input_size, batch_size, time, num_layers, variable_seq_lengths, time_major, dynamic_shape_input, use_proj): """Validates that dropout does not affect Cudnn Rnn inference.""" with compat.forward_compatibility_horizon(2019, 6, 27): num_proj = num_units // 2 if use_proj and num_proj == 0: self.skipTest("num_proj cannot be 0") # Hand-picked dropouts are used below (0. and 1.) with ops.Graph().as_default() as g: with self.session(use_gpu=True, graph=g) as sess: # 1st time w/o dropout. (_, cu_outputs, _, cu_state_tuple) = RunLSTM( sess, num_units, input_size, batch_size, time, num_layers, is_training=False, dropout=0., variable_seq_lengths=variable_seq_lengths, time_major=time_major, dynamic_shape_input=dynamic_shape_input, num_proj=num_proj if use_proj else None) with ops.Graph().as_default() as g: with self.session(use_gpu=True, graph=g) as sess: (_, cu_outputs2, _, cu_state_tuple2) = RunLSTM( sess, num_units, input_size, batch_size, time, num_layers, is_training=False, dropout=1., variable_seq_lengths=variable_seq_lengths, time_major=time_major, dynamic_shape_input=dynamic_shape_input, num_proj=num_proj if use_proj else None) self.assertAllClose(cu_outputs, cu_outputs2) # h self.assertAllClose(cu_state_tuple.h, cu_state_tuple2.h) # c self.assertAllClose(cu_state_tuple.c, cu_state_tuple2.c) def RunGRU(sess, num_units, input_size, batch_size, time, num_layers=1, is_training=True, variable_seq_lengths=False, time_major=True, dynamic_shape_input=False, dropout=0., num_dirs=True, dtype=dtypes.float32): # TODO(jamesqin): add multi-layer tests. # TODO(jamesqin): add multi-dir tests assert num_layers == 1 assert num_dirs == 1 if is_training and not np.isclose(dropout, 0): raise ValueError("dropout can not be 0. when test training.") # set graph level random seed and numpy random seed. random_seed.set_random_seed(0) np.random.seed(0) shape = ([time, batch_size, input_size] if time_major else [batch_size, time, input_size]) inputs_np = np.random.rand(*shape).astype(dtype.as_numpy_dtype) inputs_static = variable_scope.get_variable( "inputs", initializer=inputs_np, dtype=dtype) inputs_dynamic = array_ops.placeholder( dtype, shape=[None, None, None], name="inputs") inputs = inputs_dynamic if dynamic_shape_input else inputs_static initial_h_op = variable_scope.get_variable( "initial_h_op", initializer=np.random.rand(batch_size, num_units).astype(dtype.as_numpy_dtype), dtype=dtype) if variable_seq_lengths: lengths_v = np.random.randint(low=1, high=time + 1, size=batch_size) lengths_v[0] = time # make sure the max sequence has 'time' elems lengths = ops.convert_to_tensor(lengths_v.astype(np.int32)) else: lengths = None initializer = init_ops.random_uniform_initializer( -0.01, 0.01, dtype=dtype, seed=19980904) with variable_scope.variable_scope("test", initializer=initializer): gate_kernel = variable_scope.get_variable( "rnn/cudnn_compatible_gru_cell/gates/kernel", shape=[input_size + num_units, num_units * 2], dtype=dtype) gate_bias = variable_scope.get_variable( "rnn/cudnn_compatible_gru_cell/gates/bias", shape=[num_units * 2], dtype=dtype) candidate_inp_kernel = variable_scope.get_variable( "rnn/cudnn_compatible_gru_cell/candidate/input_projection/kernel", shape=[input_size, num_units], dtype=dtype) candidate_inp_bias = variable_scope.get_variable( "rnn/cudnn_compatible_gru_cell/candidate/input_projection/bias", shape=[num_units], dtype=dtype) candidate_hid_kernel = variable_scope.get_variable( "rnn/cudnn_compatible_gru_cell/candidate/hidden_projection/kernel", shape=[num_units, num_units], dtype=dtype) candidate_hid_bias = variable_scope.get_variable( "rnn/cudnn_compatible_gru_cell/candidate/hidden_projection/bias", shape=[num_units], dtype=dtype) cell = cudnn_rnn_ops.CudnnCompatibleGRUCell(num_units, reuse=True) outputs_op, h_op = rnn.dynamic_rnn( cell, inputs_static, sequence_length=lengths, initial_state=initial_h_op, dtype=dtype, time_major=time_major, scope=None) ws = [gate_kernel, candidate_inp_kernel, candidate_hid_kernel] bs = [gate_bias, candidate_inp_bias, candidate_hid_bias] # Convert to cudnn opaque param. format_converter = cudnn_rnn_ops.CudnnParamsFormatConverterGRU( num_layers, num_units, input_size) opaque_params = format_converter.tf_canonical_to_opaque(ws + bs) cu_initial_h_op = array_ops.expand_dims( initial_h_op, axis=(0 if time_major else 1)) cu_outputs_op, cu_h_op, _ = cudnn_rnn_ops._cudnn_rnn( inputs, cu_initial_h_op, array_ops.zeros_like(cu_initial_h_op), # not used opaque_params, sequence_lengths=lengths, time_major=time_major, dropout=dropout, is_training=is_training, rnn_mode=cudnn_rnn_ops.CUDNN_GRU) if is_training: (inp_grad_op, hgrad_op, gk_grad_op, cik_grad_op, chk_grad_op, gb_grad_op, cib_grad_op, chb_grad_op) = gradients_impl.gradients( outputs_op, [inputs_static, initial_h_op] + ws + bs) (cu_inp_grad_op, cu_hgrad_op, opaque_grad_op) = gradients_impl.gradients( cu_outputs_op, [inputs, cu_initial_h_op, opaque_params]) # Remove the trivial 1st dimension cu_hgrad_op = array_ops.squeeze(cu_hgrad_op, axis=0 if time_major else 1) cu_wgrad_op, cu_bgrad_op = format_converter.opaque_to_tf_canonical( opaque_grad_op) (cu_gk_grad_op, cu_cik_grad_op, cu_chk_grad_op) = cu_wgrad_op (cu_gb_grad_op, cu_cib_grad_op, cu_chb_grad_op) = cu_bgrad_op # cudnn gru has 2 biases for reset and update gates. When converting to tf # canonical format, the two biases are summed into one. Thus here relevant # bias gradient should be halved before comparing with tf gru. cu_gb_grad_op *= 0.5 init_op = variables.global_variables_initializer() sess.run(init_op) if is_training: outputs, h, inp_grad, hgrad, wgrad, bgrad = sess.run([ outputs_op, h_op, inp_grad_op, hgrad_op, (gk_grad_op, cik_grad_op, chk_grad_op), (gb_grad_op, cib_grad_op, chb_grad_op) ]) (cu_outputs, cu_h, cu_inp_grad, cu_hgrad, cu_wgrad, cu_bgrad) = sess.run( [ cu_outputs_op, cu_h_op, cu_inp_grad_op, cu_hgrad_op, (cu_gk_grad_op, cu_cik_grad_op, cu_chk_grad_op), (cu_gb_grad_op, cu_cib_grad_op, cu_chb_grad_op) ], feed_dict={inputs: inputs_np} if dynamic_shape_input else None) # Remove the trivial 1st dimension cu_h = np.squeeze(cu_h, axis=0 if time_major else 1) logging.vlog(1, "outputs: %s" % outputs) logging.vlog(1, "cu_outputs: %s" % cu_outputs) logging.vlog(1, "h: %s" % h) logging.vlog(1, "cu_h: %s" % h) logging.vlog(1, "inp_grad: %s" % inp_grad) logging.vlog(1, "cu_inp_grad: %s" % cu_inp_grad) logging.vlog(1, "hgrad: %s" % hgrad) logging.vlog(1, "cu_hgrad: %s" % cu_hgrad) logging.vlog(1, "wgrad: %s" % str(wgrad)) logging.vlog(1, "bgrad: %s" % str(bgrad)) logging.vlog(1, "cu_wgrad: %s" % str(cu_wgrad)) logging.vlog(1, "cu_bgrad: %s" % str(cu_bgrad)) return (outputs, cu_outputs, h, cu_h, inp_grad, cu_inp_grad, hgrad, cu_hgrad, wgrad, bgrad, cu_wgrad, cu_bgrad) else: outputs, h = sess.run([outputs_op, h_op]) cu_outputs, cu_h = sess.run([cu_outputs_op, cu_h_op], feed_dict=({ inputs: inputs_np } if dynamic_shape_input else None)) # Remove the trivial 1st dimension. cu_h = np.squeeze(cu_h, axis=0 if time_major else 1) logging.vlog(1, "outputs: %s" % outputs) logging.vlog(1, "cu_outputs: %s" % cu_outputs) logging.vlog(1, "h: %s" % h) logging.vlog(1, "cu_h: %s" % h) return outputs, cu_outputs, h, cu_h class CudnnGRUTest(test_util.TensorFlowTestCase, parameterized.TestCase): def _test_training_helper(self, num_units, input_size, batch_size, time, num_layers, dtype, variable_seq_lengths, time_major, dynamic_shape_input=False, rtol=3e-6, atol=3e-6): with self.session(use_gpu=True) as sess: (outputs, cu_outputs, h, cu_h, inp_grad, cu_inp_grad, hgrad, cu_hgrad, wgrad, bgrad, cu_wgrad, cu_bgrad) = RunGRU( sess, num_units, input_size, batch_size, time, num_layers, variable_seq_lengths=variable_seq_lengths, time_major=time_major, dynamic_shape_input=dynamic_shape_input) self.assertAllClose(outputs, cu_outputs, rtol=rtol, atol=atol) self.assertAllClose(h, cu_h, rtol=rtol, atol=atol) self.assertAllClose(hgrad, cu_hgrad, rtol=rtol, atol=atol) self.assertAllClose(inp_grad, cu_inp_grad, rtol=rtol, atol=atol) for bg, cu_bg in zip(bgrad, cu_bgrad): self.assertAllClose(bg, cu_bg, rtol=rtol, atol=atol) for wg, cu_wg in zip(wgrad, cu_wgrad): self.assertAllClose(wg, cu_wg, rtol=rtol, atol=atol) @parameterized.named_parameters( ExpandNamedTestCases( NAMED_RNN_TESTCASES, **{ "variable_seq_lengths": [True, False], "time_major": [True, False], "dynamic_shape_input": [True, False], })) @test_util.run_gpu_only def test_training(self, num_units, input_size, batch_size, time, num_layers, variable_seq_lengths, time_major, dynamic_shape_input): self._test_training_helper( num_units, input_size, batch_size, time, num_layers, dtypes.float32, variable_seq_lengths=variable_seq_lengths, time_major=time_major, dynamic_shape_input=dynamic_shape_input) @parameterized.named_parameters( ExpandNamedTestCases( NAMED_RNN_TESTCASES, **{ "variable_seq_lengths": [True, False], "time_major": [True, False], "dynamic_shape_input": [True, False], })) @test_util.run_gpu_only def test_training_fp16(self, num_units, input_size, batch_size, time, num_layers, variable_seq_lengths, time_major, dynamic_shape_input): self._test_training_helper( num_units, input_size, batch_size, time, num_layers, dtypes.float16, rtol=5e-3, atol=5e-4, variable_seq_lengths=variable_seq_lengths, time_major=time_major, dynamic_shape_input=dynamic_shape_input) @parameterized.named_parameters( ExpandNamedTestCases( NAMED_RNN_TESTCASES, **{ "variable_seq_lengths": [True, False], "time_major": [True, False], "dynamic_shape_input": [True, False], })) @test_util.run_gpu_only def test_inference(self, num_units, input_size, batch_size, time, num_layers, variable_seq_lengths, time_major, dynamic_shape_input): with self.session(use_gpu=True) as sess: (outputs, cu_outputs, h, cu_h) = RunGRU( sess, num_units, input_size, batch_size, time, num_layers, is_training=False, variable_seq_lengths=variable_seq_lengths, time_major=time_major, dynamic_shape_input=dynamic_shape_input) self.assertAllClose(outputs, cu_outputs) self.assertAllClose(h, cu_h) @parameterized.named_parameters( ExpandNamedTestCases( NAMED_RNN_TESTCASES, **{ "variable_seq_lengths": [True, False], "time_major": [True, False], "dynamic_shape_input": [True, False], })) @test_util.run_gpu_only def test_inference_fp16(self, num_units, input_size, batch_size, time, num_layers, variable_seq_lengths, time_major, dynamic_shape_input): with self.session(use_gpu=True) as sess: (outputs, cu_outputs, h, cu_h) = RunGRU( sess, num_units, input_size, batch_size, time, num_layers, is_training=False, dtype=dtypes.float16, variable_seq_lengths=variable_seq_lengths, time_major=time_major, dynamic_shape_input=dynamic_shape_input) rtol, atol = 5e-3, 5e-4 self.assertAllClose(outputs, cu_outputs, rtol=rtol, atol=atol) self.assertAllClose(h, cu_h, rtol=rtol, atol=atol) @parameterized.named_parameters( ExpandNamedTestCases( NAMED_RNN_TESTCASES, **{ "variable_seq_lengths": [True, False], "time_major": [True, False], "dynamic_shape_input": [True, False], })) @test_util.run_gpu_only def test_inference_with_dropout(self, num_units, input_size, batch_size, time, num_layers, variable_seq_lengths, time_major, dynamic_shape_input): """Validates that dropout does not affect Cudnn Rnn inference.""" # Hand-picked dropouts are used below (0. and 1.) with ops.Graph().as_default() as g: with self.session(use_gpu=True, graph=g) as sess: # 1st time w/o dropout. (_, cu_outputs, _, cu_h) = RunGRU( sess, num_units, input_size, batch_size, time, num_layers, is_training=False, dropout=0., variable_seq_lengths=variable_seq_lengths, time_major=time_major, dynamic_shape_input=dynamic_shape_input) with ops.Graph().as_default() as g: with self.session(use_gpu=True, graph=g) as sess: (_, cu_outputs2, _, cu_h2) = RunGRU( sess, num_units, input_size, batch_size, time, num_layers, is_training=False, dropout=1., variable_seq_lengths=variable_seq_lengths, time_major=time_major, dynamic_shape_input=dynamic_shape_input) self.assertAllClose(cu_outputs, cu_outputs2) self.assertAllClose(cu_h[0], cu_h2[0]) class CudnnParamsFormatConverterTest(test_util.TensorFlowTestCase, parameterized.TestCase): """Class for testing various format converters.""" def _test_lstm_helper(self, num_units, input_size, num_layers, direction, num_proj=None): with self.session(use_gpu=True) as sess: random_seed.set_random_seed(0) np.random.seed(0) num_dirs = 1 if direction == cudnn_rnn_ops.CUDNN_RNN_UNIDIRECTION else 2 format_converter = cudnn_rnn_ops.CudnnParamsFormatConverterLSTM( num_layers, num_units, input_size, direction=direction, num_proj=num_proj if num_proj else None) ws, bs, pws = [], [], [] for _ in range(num_layers * num_dirs): w = constant_op.constant( np.random.rand(input_size + (num_proj if num_proj else num_units), 4 * num_units), dtype=dtypes.float32) b = constant_op.constant( np.random.rand(4 * num_units), dtype=dtypes.float32) ws.append(w) bs.append(b) if num_proj: pw = constant_op.constant( np.random.rand(num_units, num_proj), dtype=dtypes.float32) pws.append(pw) if num_proj: opaque_params = format_converter.tf_canonical_to_opaque(ws + bs, pws) else: opaque_params = format_converter.tf_canonical_to_opaque(ws + bs) opaque_params_size = cudnn_rnn_ops.cudnn_rnn_opaque_params_size( cudnn_rnn_ops.CUDNN_LSTM, num_layers, num_units, input_size, direction=direction, num_proj=num_proj if num_proj else None) if num_proj: ws_r, bs_r, pws_r = format_converter.opaque_to_tf_canonical( opaque_params) ws, ws_r, pws, bs, bs_r, pws_r = sess.run( [ws, ws_r, pws, bs, bs_r, pws_r]) else: ws_r, bs_r = format_converter.opaque_to_tf_canonical(opaque_params) ws, ws_r, bs, bs_r = sess.run([ws, ws_r, bs, bs_r]) # Test tf_canonical_to_opaque() followed by opaque_to_tf_canonical() # returns the original input. for w, w_r in zip(ws, ws_r): self.assertAllClose(w, w_r) if num_proj: for pw, pw_r in zip(pws, pws_r): self.assertAllClose(pw, pw_r) for b, b_r in zip(bs, bs_r): self.assertAllClose(b, b_r) # Test opaque_params size lower bound opaque_params_size_v = sess.run(opaque_params_size) min_params_size = sum(x.size for x in ws) + np.sum(x.size for x in bs) logging.info("min_parm_size: %d vs actual_opaque_param_size: %d", min_params_size, opaque_params_size_v) self.assertLessEqual(min_params_size, opaque_params_size_v) @parameterized.named_parameters((c["testcase_name"], c["num_units"], c["input_size"], c["num_layers"]) for c in NAMED_RNN_TESTCASES) @test_util.run_gpu_only def test_lstm(self, num_units, input_size, num_layers): self._test_lstm_helper(num_units, input_size, num_layers, cudnn_rnn_ops.CUDNN_RNN_UNIDIRECTION) @parameterized.named_parameters( (c["testcase_name"], c["num_units"], c["input_size"], c["num_layers"]) for c in NAMED_RNN_TESTCASES) @test_util.run_gpu_only def test_lstmp(self, num_units, input_size, num_layers): with compat.forward_compatibility_horizon(2019, 6, 27): num_proj = num_units // 2 if num_proj == 0: self.skipTest("num_proj cannot be 0") self._test_lstm_helper( num_units, input_size, num_layers, cudnn_rnn_ops.CUDNN_RNN_UNIDIRECTION, num_proj=num_proj) @parameterized.named_parameters((c["testcase_name"], c["num_units"], c["input_size"], c["num_layers"]) for c in NAMED_RNN_TESTCASES) @test_util.run_gpu_only def test_lstm_bidi(self, num_units, input_size, num_layers): self._test_lstm_helper(num_units, input_size, num_layers, cudnn_rnn_ops.CUDNN_RNN_BIDIRECTION) @parameterized.named_parameters( (c["testcase_name"], c["num_units"], c["input_size"], c["num_layers"]) for c in NAMED_RNN_TESTCASES) @test_util.run_gpu_only def test_lstmp_bidi(self, num_units, input_size, num_layers): with compat.forward_compatibility_horizon(2019, 6, 27): num_proj = num_units // 2 if num_proj == 0: self.skipTest("num_proj cannot be 0") self._test_lstm_helper( num_units, input_size, num_layers, cudnn_rnn_ops.CUDNN_RNN_BIDIRECTION, num_proj=num_proj) def _test_gru_helper(self, num_units, input_size, num_layers, direction): with self.session(use_gpu=True) as sess: random_seed.set_random_seed(0) np.random.seed(0) num_dirs = 1 if direction == cudnn_rnn_ops.CUDNN_RNN_UNIDIRECTION else 2 format_converter = cudnn_rnn_ops.CudnnParamsFormatConverterGRU( num_layers, num_units, input_size, direction=direction) ws, bs = [], [] for _ in range(num_layers * num_dirs): gate_kernel = constant_op.constant( np.random.rand(input_size + num_units, num_units * 2), dtype=dtypes.float32) gate_bias = constant_op.constant( np.random.rand(num_units * 2), dtype=dtypes.float32) candidate_inp_kernel = constant_op.constant( np.random.rand(input_size, num_units), dtype=dtypes.float32) candidate_inp_bias = constant_op.constant( np.random.rand(num_units), dtype=dtypes.float32) candidate_hid_kernel = constant_op.constant( np.random.rand(num_units, num_units), dtype=dtypes.float32) candidate_hid_bias = constant_op.constant( np.random.rand(num_units), dtype=dtypes.float32) ws.extend([gate_kernel, candidate_inp_kernel, candidate_hid_kernel]) bs.extend([gate_bias, candidate_inp_bias, candidate_hid_bias]) opaque_params = format_converter.tf_canonical_to_opaque(ws + bs) opaque_params_size = cudnn_rnn_ops.cudnn_rnn_opaque_params_size( cudnn_rnn_ops.CUDNN_GRU, num_layers, num_units, input_size, direction=direction) ws_r, bs_r = format_converter.opaque_to_tf_canonical(opaque_params) # Test tf_canonical_to_opaque() followed by opaque_to_tf_canonical() # returns the original input. ws, ws_r, bs, bs_r = sess.run([ws, ws_r, bs, bs_r]) for w, w_r in zip(ws, ws_r): self.assertAllClose(w, w_r) for b, b_r in zip(bs, bs_r): self.assertAllClose(b, b_r) # Test opaque_params size lower bound opaque_params_size_v = sess.run(opaque_params_size) min_params_size = sum(x.size for x in ws) + sum(x.size for x in bs) logging.info("min_parm_size: %d vs actual_opaque_param_size: %d", min_params_size, opaque_params_size_v) self.assertLessEqual(min_params_size, opaque_params_size_v) @parameterized.named_parameters((c["testcase_name"], c["num_units"], c["input_size"], c["num_layers"]) for c in NAMED_RNN_TESTCASES) @test_util.run_gpu_only def test_gru(self, num_units, input_size, num_layers): self._test_gru_helper(num_units, input_size, num_layers, cudnn_rnn_ops.CUDNN_RNN_UNIDIRECTION) @parameterized.named_parameters((c["testcase_name"], c["num_units"], c["input_size"], c["num_layers"]) for c in NAMED_RNN_TESTCASES) @test_util.run_gpu_only def test_gru_bidi(self, num_units, input_size, num_layers): self._test_gru_helper(num_units, input_size, num_layers, cudnn_rnn_ops.CUDNN_RNN_BIDIRECTION) class CudnnRnnSaveRestoreTest(test_util.TensorFlowTestCase, parameterized.TestCase): """Class for testing various Cudnn Rnn SaveableObjects.""" def _create_opaque_param(self, rnn_mode, num_units, input_size, num_layers, direction, name=None): param_size_t = cudnn_rnn_ops.cudnn_rnn_opaque_params_size( rnn_mode, num_layers, num_units, input_size, direction=direction) init_val = random_ops.random_uniform([param_size_t]) return variable_scope.get_variable( name or "opaque_param", initializer=init_val, validate_shape=False) def _create_saveable(self, opaque_param, rnn_mode, num_units, input_size, num_layers, direction): if rnn_mode == CUDNN_LSTM: fn = cudnn_rnn_ops.CudnnLSTMSaveable elif rnn_mode == CUDNN_GRU: fn = cudnn_rnn_ops.CudnnGRUSaveable elif rnn_mode == CUDNN_RNN_TANH: fn = cudnn_rnn_ops.CudnnRNNTanhSaveable elif rnn_mode == CUDNN_RNN_RELU: fn = cudnn_rnn_ops.CudnnRNNReluSaveable saveable = fn( opaque_param, num_layers, num_units, input_size, direction=direction) return saveable def _compare_weights(self, lhs, rhs): self.assertLen(rhs, len(lhs)) for lw, rw in zip(lhs, rhs): self.assertAllEqual(lw, rw) def _compare_biases(self, lhs, rhs): self.assertLen(rhs, len(lhs)) for lf, rt in zip(lhs, rhs): self.assertAllEqual(lf, rt) @parameterized.named_parameters( ExpandNamedTestCases( NAMED_RNN_TESTCASES, "time", "batch_size", **{ "rnn_mode": [ CUDNN_LSTM, CUDNN_GRU, CUDNN_RNN_RELU, CUDNN_RNN_TANH ], "direction": [CUDNN_RNN_UNIDIRECTION, CUDNN_RNN_BIDIRECTION] })) @test_util.run_gpu_only def test_save_restore_variable(self, rnn_mode, num_units, input_size, num_layers, direction): # Verify the restored opaque param, once converted to tf_canonical format, # is the same as the tf canonicals of the pre-restored param. with self.session(use_gpu=True) as sess: opaque_param = self._create_opaque_param(rnn_mode, num_units, input_size, num_layers, direction) saveable = self._create_saveable(opaque_param, rnn_mode, num_units, input_size, num_layers, direction) ops.add_to_collection(ops.GraphKeys.SAVEABLE_OBJECTS, saveable) weights_op, biases_op = saveable.format_converter.opaque_to_tf_canonical( saveable._variables) save_path = os.path.join(self.get_temp_dir(), "save_restore_var_test") saver = saver_lib.Saver(write_version=saver_pb2.SaverDef.V2) init_op = variables.global_variables_initializer() reset_op = state_ops.assign(opaque_param, array_ops.zeros_like(opaque_param)) sess.run(init_op) self.assertEqual(save_path, saver.save(sess, save_path)) # Get the tf canonical vals before reset-restore weights, biases = sess.run([weights_op, biases_op]) # Reset the opaque param value sess.run(reset_op) # Assert reset happened. weights_z, biases_z = sess.run([weights_op, biases_op]) for w in weights_z: self.assertAllClose(w, np.zeros_like(w)) for b in biases_z: self.assertAllClose(b, np.zeros_like(b)) # Restore opaque param value from checkpoint. saver.restore(sess, save_path) weights_r, biases_r = sess.run([weights_op, biases_op]) self._compare_weights(weights, weights_r) self._compare_biases(biases, biases_r) @parameterized.named_parameters( ExpandNamedTestCases( NAMED_RNN_TESTCASES, "time", "batch_size", **{ "rnn_mode": [ CUDNN_LSTM, CUDNN_GRU, CUDNN_RNN_RELU, CUDNN_RNN_TANH ], "direction": [CUDNN_RNN_UNIDIRECTION, CUDNN_RNN_BIDIRECTION] })) @test_util.run_gpu_only def test_save_restore_multi_variables(self, rnn_mode, num_units, input_size, num_layers, direction): # Verify the restored opaque param, once converted to tf_canonical format, # is the same as the tf canonicals of the pre-restored param. with self.session(use_gpu=True) as sess: opaque_params = [] saveables = [] num_opaque_params = 2 for i in range(num_opaque_params): opaque_params.append( self._create_opaque_param( rnn_mode, num_units, input_size, num_layers, direction, name="opaque_param_%d" % i)) saveable = self._create_saveable(opaque_params[i], rnn_mode, num_units, input_size, num_layers, direction) ops.add_to_collection(ops.GraphKeys.SAVEABLE_OBJECTS, saveable) saveables.append(saveable) weights_ops, biases_ops = [], [] for i in range(num_opaque_params): weights_op, biases_op = ( saveables[i].format_converter.opaque_to_tf_canonical( saveables[i]._variables)) weights_ops.append(weights_op) biases_ops.append(biases_op) save_path = os.path.join(self.get_temp_dir(), "save_restore_var_test") saver = saver_lib.Saver(write_version=saver_pb2.SaverDef.V2) init_op = variables.global_variables_initializer() reset_ops = [] for i in range(num_opaque_params): reset_ops.append( state_ops.assign(opaque_params[i], array_ops.zeros_like(opaque_params[i]))) sess.run(init_op) self.assertEqual(save_path, saver.save(sess, save_path)) # Get the tf canonical vals before reset-restore for i in range(num_opaque_params): weights, biases = sess.run([weights_ops[i], biases_ops[i]]) # Reset the opaque param value sess.run(reset_ops[i]) # Assert reset happened. weights_z, biases_z = sess.run([weights_ops[i], biases_ops[i]]) for w in weights_z: self.assertAllClose(w, np.zeros_like(w)) for b in biases_z: self.assertAllClose(b, np.zeros_like(b)) # Restore opaque param value from checkpoint. saver.restore(sess, save_path) weights_r, biases_r = sess.run([weights_ops[i], biases_ops[i]]) self._compare_weights(weights, weights_r) self._compare_biases(biases, biases_r) if __name__ == "__main__": googletest.main()
tensorflow-master
tensorflow/contrib/cudnn_rnn/python/kernel_tests/cudnn_rnn_ops_test.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for Cudnn RNN models.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import collections import functools import itertools import os import sys import unittest import numpy as np from tensorflow.contrib.cudnn_rnn.python.layers import cudnn_rnn from tensorflow.contrib.cudnn_rnn.python.ops import cudnn_rnn_ops from tensorflow.contrib.rnn.python.ops import rnn as contrib_rnn_lib from tensorflow.python.eager import backprop from tensorflow.python.eager import context from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.framework import random_seed from tensorflow.python.framework import test_util from tensorflow.python.ops import array_ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import gen_nn_ops from tensorflow.python.ops import gradients_impl as gradients from tensorflow.python.ops import init_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import random_ops from tensorflow.python.ops import rnn as rnn_lib from tensorflow.python.ops import rnn_cell_impl from tensorflow.python.ops import state_ops from tensorflow.python.ops import variable_scope as vs from tensorflow.python.ops import variables from tensorflow.python.ops.losses import losses from tensorflow.python.platform import googletest from tensorflow.python.platform import test from tensorflow.python.platform import tf_logging as logging from tensorflow.python.training import adagrad from tensorflow.python.training import adam from tensorflow.python.training import gradient_descent from tensorflow.python.training import momentum from tensorflow.python.training import rmsprop from tensorflow.python.training import saver as saver_lib from tensorflow.python.training.tracking import util as trackable_utils CUDNN_LSTM = cudnn_rnn_ops.CUDNN_LSTM CUDNN_GRU = cudnn_rnn_ops.CUDNN_GRU CUDNN_RNN_RELU = cudnn_rnn_ops.CUDNN_RNN_RELU CUDNN_RNN_TANH = cudnn_rnn_ops.CUDNN_RNN_TANH CUDNN_RNN_UNIDIRECTION = cudnn_rnn_ops.CUDNN_RNN_UNIDIRECTION CUDNN_RNN_BIDIRECTION = cudnn_rnn_ops.CUDNN_RNN_BIDIRECTION CUDNN_LSTM_PARAMS_PER_LAYER = cudnn_rnn_ops.CUDNN_LSTM_PARAMS_PER_LAYER CUDNN_GRU_PARAMS_PER_LAYER = cudnn_rnn_ops.CUDNN_GRU_PARAMS_PER_LAYER CUDNN_RNN_TANH_PARAMS_PER_LAYER = cudnn_rnn_ops.CUDNN_RNN_TANH_PARAMS_PER_LAYER CUDNN_RNN_RELU_PARAMS_PER_LAYER = cudnn_rnn_ops.CUDNN_RNN_RELU_PARAMS_PER_LAYER class CudnnTestModel(object): """Model with convenient APIs for easier building and running test graph. The graph built is used by all tests below to avoid repeatedly building similar test graphs. """ def __init__(self, rnn_mode, num_layers, num_units, input_size, direction=CUDNN_RNN_UNIDIRECTION, dropout=0., dtype=dtypes.float32, training=False, seed=None, kernel_initializer=None, bias_initializer=None): if dtype not in (dtypes.float16, dtypes.float32, dtypes.float64): raise ValueError("Invalid dtype: %s" % dtype) self._dtype = dtype self._inputs = array_ops.placeholder( dtype=dtype, shape=[None, None, input_size], name="inputs") h = array_ops.placeholder( dtype=dtype, shape=[None, None, num_units], name="h") c = array_ops.placeholder( dtype=dtype, shape=[None, None, num_units], name="c") if rnn_mode == CUDNN_LSTM: model_fn = cudnn_rnn.CudnnLSTM self._initial_state = (h, c) elif rnn_mode == CUDNN_GRU: model_fn = cudnn_rnn.CudnnGRU self._initial_state = (h,) elif rnn_mode == CUDNN_RNN_TANH: model_fn = cudnn_rnn.CudnnRNNTanh self._initial_state = (h,) elif rnn_mode == CUDNN_RNN_RELU: model_fn = cudnn_rnn.CudnnRNNRelu self._initial_state = (h,) else: raise ValueError("Invalid rnn_mode: %s" % rnn_mode) self._rnn = model_fn( num_layers, num_units, direction=direction, dropout=dropout, dtype=dtype, seed=seed, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer) self._rnn.build([None, None, input_size]) self._outputs, self._output_state = self._rnn( self._inputs, initial_state=self._initial_state, training=training) def _AddUp(self, outputs, output_state): total = math_ops.reduce_sum(outputs) for s in output_state: total += math_ops.reduce_sum(s) return total @property def inputs(self): return self._inputs @property def initial_state(self): return self._initial_state @property def outputs(self): return self._outputs @property def output_state(self): return self._output_state @property def rnn(self): return self._rnn @property def total_sum(self): return self._AddUp(self.outputs, self.output_state) def SynthesizeInput(self, seq_length, batch_size, seed=1234): """Synthesizes input and initial state values for testing.""" np.random.seed(seed) num_layers = self._rnn.num_layers dir_count = self._rnn.num_dirs num_units = self._rnn.num_units input_size = self._rnn.input_size np_dtype = np.float32 if self._dtype == dtypes.float32 else np.float64 inputs = np.random.randn(seq_length, batch_size, input_size).astype(np_dtype) input_h = np.random.randn(num_layers * dir_count, batch_size, num_units).astype(np_dtype) if self._rnn.rnn_mode == CUDNN_LSTM: input_c = np.random.randn(num_layers * dir_count, batch_size, num_units).astype(np_dtype) initial_state = (input_h, input_c) else: initial_state = (input_h,) return inputs, initial_state def ZeroState(self, batch_size): num_layers = self._rnn.num_layers dir_count = self._rnn.num_dirs num_units = self._rnn.num_units np_dtype = np.float32 if self._dtype == dtypes.float32 else np.float64 input_h = np.zeros((num_layers * dir_count, batch_size, num_units)).astype(np_dtype) if self._rnn.rnn_mode == CUDNN_LSTM: input_c = np.zeros((num_layers * dir_count, batch_size, num_units)).astype(np_dtype) initial_state = (input_h, input_c) else: initial_state = (input_h,) return initial_state def FProp(self, inputs_t, initial_state_t, training): """Builds additional subgraph with given inputs and state. Args: inputs_t: a tensor. initial_state_t: a tensor. training: boolean, true if training mode. Returns: A tensor of the forward pass output of the model. """ outputs, output_state = self._rnn( inputs_t, initial_state=initial_state_t, training=training) return self._AddUp(outputs, output_state) def Feed(self, sess, inputs, initial_state=None, return_sum=True): """Runs graph with given inputs and initial state.""" batch_size = inputs.shape[1] if initial_state is None: initial_state = self.ZeroState(batch_size) if return_sum: return sess.run( self.total_sum, feed_dict={self.inputs: inputs, self.initial_state: initial_state}) else: return sess.run( [self.outputs, self.output_state], feed_dict={self.inputs: inputs, self.initial_state: initial_state}) def _CreateCudnnCompatibleCanonicalRNN(rnn, inputs, is_bidi=False, scope=None): mode = rnn.rnn_mode num_units = rnn.num_units num_layers = rnn.num_layers # To reuse cuDNN-trained models, must use cudnn compatible rnn cells. if mode == CUDNN_LSTM: single_cell = lambda: cudnn_rnn_ops.CudnnCompatibleLSTMCell(num_units) elif mode == CUDNN_GRU: single_cell = lambda: cudnn_rnn_ops.CudnnCompatibleGRUCell(num_units) elif mode == CUDNN_RNN_TANH: single_cell = (lambda: rnn_cell_impl.BasicRNNCell(num_units, math_ops.tanh)) elif mode == CUDNN_RNN_RELU: single_cell = ( lambda: rnn_cell_impl.BasicRNNCell(num_units, gen_nn_ops.relu)) else: raise ValueError("%s is not supported!" % mode) if not is_bidi: cell = rnn_cell_impl.MultiRNNCell( [single_cell() for _ in range(num_layers)]) return rnn_lib.dynamic_rnn( cell, inputs, dtype=dtypes.float32, time_major=True, scope=scope) else: cells_fw = [single_cell() for _ in range(num_layers)] cells_bw = [single_cell() for _ in range(num_layers)] (outputs, output_state_fw, output_state_bw) = contrib_rnn_lib.stack_bidirectional_dynamic_rnn( cells_fw, cells_bw, inputs, dtype=dtypes.float32, time_major=True, scope=scope) return outputs, (output_state_fw, output_state_bw) class CudnnRNNTestBasic(test_util.TensorFlowTestCase): @unittest.skipUnless(test.is_built_with_cuda(), "Test only applicable when running on GPUs") def testLayerBasic(self): num_layers = 4 num_units = 2 batch_size = 8 direction = CUDNN_RNN_UNIDIRECTION dir_count = 1 with vs.variable_scope("main"): kernel_initializer = init_ops.constant_initializer(0.) bias_initializer = init_ops.constant_initializer(0.) inputs = random_ops.random_uniform([ num_layers * dir_count, batch_size, num_units], dtype=dtypes.float32) lstm = cudnn_rnn.CudnnLSTM(num_layers, num_units, direction=direction, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, name="awesome_lstm") # Build the layer outputs1, _ = lstm(inputs) # Reuse the layer outputs2, _ = lstm(inputs) total_sum1 = math_ops.reduce_sum(outputs1) total_sum2 = math_ops.reduce_sum(outputs2) with vs.variable_scope("main", reuse=True): lstm = cudnn_rnn.CudnnLSTM(num_layers, num_units, direction=direction, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, name="awesome_lstm") # Reuse the layer outputs3, _ = lstm(inputs) total_sum3 = math_ops.reduce_sum(outputs3) self.assertEqual(1, len(variables.trainable_variables())) self.assertEqual(1, len(ops.get_collection(ops.GraphKeys.SAVEABLE_OBJECTS))) self.assertEqual("main/awesome_lstm/opaque_kernel", variables.trainable_variables()[0].op.name) with self.test_session(use_gpu=True) as sess: sess.run(variables.global_variables_initializer()) (total_sum1_v, total_sum2_v, total_sum3_v) = sess.run( [total_sum1, total_sum2, total_sum3]) self.assertEqual(0, total_sum1_v) self.assertEqual(0, total_sum2_v) self.assertEqual(0, total_sum3_v) @unittest.skipUnless(test.is_built_with_cuda(), "Test only applicable when running on GPUs") def testOptimizersSupport(self): for opt in ("adagrad", "adam", "rmsprop", "momentum", "sgd"): self._TestOptimizerSupportHelper(opt) def _GetOptimizer(self, opt): if opt == "adagrad": return adagrad.AdagradOptimizer(learning_rate=1e-2) elif opt == "adam": return adam.AdamOptimizer(learning_rate=1e-2) elif opt == "rmsprop": return rmsprop.RMSPropOptimizer(learning_rate=1e-2) elif opt == "momentum": return momentum.MomentumOptimizer(learning_rate=1e-2, momentum=0.9) elif opt == "sgd": return gradient_descent.GradientDescentOptimizer(learning_rate=1e-2) else: raise ValueError("Unsupported optimizer: %s" % opt) def _TestOptimizerSupportHelper(self, opt): num_layers = 4 num_units = 2 batch_size = 8 direction = CUDNN_RNN_UNIDIRECTION dir_count = 1 with ops.Graph().as_default() as g: kernel_initializer = init_ops.constant_initializer(0.) bias_initializer = init_ops.constant_initializer(0.) inputs = random_ops.random_uniform([ num_layers * dir_count, batch_size, num_units], dtype=dtypes.float32) lstm = cudnn_rnn.CudnnLSTM(num_layers, num_units, direction=direction, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, name="awesome_lstm") outputs, _ = lstm(inputs) loss = math_ops.reduce_sum(outputs) optimizer = self._GetOptimizer(opt) train_op = optimizer.minimize(loss) with self.test_session(use_gpu=True, graph=g) as sess: sess.run(variables.global_variables_initializer()) sess.run(train_op) @unittest.skipUnless(test.is_built_with_cuda(), "Test only applicable when running on GPUs") def testSaveableGraphDeviceAssignment(self): num_layers = 4 num_units = 2 batch_size = 8 direction = CUDNN_RNN_UNIDIRECTION dir_count = 1 def DeviceFn(op): if op.type in ("Variable", "VariableV2"): return "/cpu:0" else: return "/gpu:0" with ops.Graph().as_default() as g: with ops.device(DeviceFn): with vs.variable_scope("main"): kernel_initializer = init_ops.constant_initializer(3.14) bias_initializer = init_ops.constant_initializer(1.59) inputs = random_ops.random_uniform( [num_layers * dir_count, batch_size, num_units], dtype=dtypes.float32) lstm = cudnn_rnn.CudnnLSTM(num_layers, num_units, direction=direction, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, name="awesome_lstm") outputs = lstm(inputs) # saver is created in the scope of DeviceFn. saver = saver_lib.Saver() with self.test_session(use_gpu=True, graph=g) as sess: save_path = os.path.join(self.get_temp_dir(), "test-saveable-device-assignment") sess.run(variables.global_variables_initializer()) saver.save(sess, save_path) saver.restore(sess, save_path) sess.run(outputs) @unittest.skipUnless(test.is_built_with_cuda(), "Test only applicable when running on GPUs") def testDifferentShapesEager(self): # Checks that kernel caching does not cause sharing of temporary storage # across different input shapes when executing eagerly. with context.eager_mode(): with ops.device("gpu:0"): first_output, _ = cudnn_rnn.CudnnGRU(1, 100)( array_ops.zeros([28, 100, 28])) second_output, _ = cudnn_rnn.CudnnGRU(1, 100)( array_ops.zeros([28, 100, 100])) self.assertAllEqual([28, 100, 100], first_output.shape) self.assertAllEqual([28, 100, 100], second_output.shape) def _LossFunc(): first_output, _ = cudnn_rnn.CudnnGRU(1, 100)( array_ops.zeros([28, 100, 28])) second_output, _ = cudnn_rnn.CudnnGRU(1, 100)( array_ops.zeros([28, 100, 100])) return (math_ops.reduce_sum(first_output) + math_ops.reduce_sum(second_output)) backprop.implicit_grad(_LossFunc)() @unittest.skipUnless(test.is_built_with_cuda(), "Test only applicable when running on GPUs") def testDifferentShapesGraph(self): # Tests that a single kernel instance presented with multiple input shapes # does not crash with graph execution. with ops.device("gpu:0"): layer = cudnn_rnn.CudnnGRU(1, 100) layer(array_ops.zeros([28, 100, 100])) def _Cond(index, accumulation): del accumulation # unused return math_ops.less(index, 4) def _Body(index, accumulation): layer_input = accumulation[:, :, 10 * (1 + index % 2):] output, _ = layer(layer_input) return index + 1, accumulation + output original_input = array_ops.zeros([28, 100, 100]) _, accumulation = control_flow_ops.while_loop(_Cond, _Body, [0, original_input]) grad, = gradients.gradients( math_ops.reduce_sum(accumulation), (original_input,)) init_op = variables.global_variables_initializer() with self.cached_session() as sess: sess.run(init_op) accumulation_eval, grad_eval = sess.run((accumulation, grad)) self.assertAllEqual([28, 100, 100], accumulation_eval.shape) self.assertAllEqual([28, 100, 100], grad_eval.shape) # TODO(jamesqin): Transform to parameterized test after it is included in the # TF open source codebase. class CudnnRNNTestSaveRestore(test_util.TensorFlowTestCase): def _CompareWeights(self, lhs, rhs): self.assertEqual(len(lhs), len(rhs)) for lw, rw in zip(lhs, rhs): self.assertAllEqual(lw, rw) def _CompareBiases(self, lhs, rhs, rnn_mode, num_layers, direction): self.assertEqual(len(lhs), len(rhs)) if rnn_mode == CUDNN_LSTM: num_params_per_layer = CUDNN_LSTM_PARAMS_PER_LAYER elif rnn_mode == CUDNN_GRU: num_params_per_layer = CUDNN_GRU_PARAMS_PER_LAYER elif rnn_mode == CUDNN_RNN_TANH: num_params_per_layer = CUDNN_RNN_TANH_PARAMS_PER_LAYER else: num_params_per_layer = CUDNN_RNN_RELU_PARAMS_PER_LAYER num_dirs = 1 if direction == CUDNN_RNN_UNIDIRECTION else 2 num_params_per_layer *= num_dirs self.assertEqual(num_params_per_layer * num_layers, len(lhs)) for i in range(num_layers): layer_lhs = lhs[i * num_params_per_layer: (i+1) * num_params_per_layer] layer_rhs = rhs[i * num_params_per_layer: (i+1) * num_params_per_layer] if direction == CUDNN_RNN_UNIDIRECTION: self._CompareSingleLayerBiases(layer_lhs, layer_rhs) else: size = len(layer_lhs) fw_lhs, bw_lhs = layer_lhs[:size//2], layer_lhs[size//2:] fw_rhs, bw_rhs = layer_rhs[:size//2], layer_rhs[size//2:] self._CompareSingleLayerBiases(fw_lhs, fw_rhs) self._CompareSingleLayerBiases(bw_lhs, bw_rhs) def _CompareSingleLayerBiases(self, lhs, rhs): self.assertEqual(len(lhs), len(rhs)) lf_lhs, rt_lhs = lhs[:len(lhs)//2], lhs[len(lhs)//2:] lf_rhs, rt_rhs = rhs[:len(rhs)//2], rhs[len(rhs)//2:] self.assertEqual(len(lf_lhs), len(rt_lhs)) self.assertEqual(len(lf_rhs), len(rt_rhs)) sum_lhs, sum_rhs = [], [] for lf, rt in zip(lf_lhs, rt_lhs): sum_lhs.append(lf + rt) for lf, rt in zip(lf_rhs, rt_rhs): sum_rhs.append(lf + rt) self.assertEqual(len(sum_lhs), len(sum_rhs)) for lf, rt in zip(sum_lhs, sum_rhs): self.assertAllEqual(lf, rt) def _TestSaveRestoreVariable(self, rnn_mode, direction, dtype): input_size = 3 num_layers = 2 num_units = 7 with ops.Graph().as_default() as g: random_seed.set_random_seed(1234) model = CudnnTestModel( rnn_mode, num_layers, num_units, input_size, direction=direction, dtype=dtype) rnn = model.rnn save_path = os.path.join(self.get_temp_dir(), "save-restore-variable-test") saver = saver_lib.Saver() weights, biases = ( model.rnn.saveable.format_converter._opaque_to_cu_canonical( model.rnn.saveable._variables)) opaque_params = rnn.trainable_variables[0] # CudnnTestModel() creates CudnnOpaqueParamsSaveable that helps saver save # Cudnn vars in canonical format. reset_op = state_ops.assign( opaque_params, array_ops.zeros(array_ops.shape(opaque_params), dtype=dtype)) # Passing graph explicitly, otherwise an old sess would be reused. with self.test_session(use_gpu=True, graph=g) as sess: sess.run(variables.global_variables_initializer()) val = saver.save(sess, save_path) self.assertEqual(save_path, val) weights_v, biases_v = sess.run([weights, biases]) # Reset opaque param sess.run(reset_op) saver.restore(sess, save_path) weights_v_restored, biases_v_restored = sess.run([weights, biases]) self._CompareWeights(weights_v, weights_v_restored) self._CompareBiases(biases_v, biases_v_restored, rnn_mode, num_layers, direction) def _TestSaveRestoreTwoVariables(self, rnn_mode, direction, dtype): input_size = 3 num_layers = 2 num_units = 7 with ops.Graph().as_default() as g: random_seed.set_random_seed(1234) with vs.variable_scope("m1"): model1 = CudnnTestModel( rnn_mode, num_layers, num_units, input_size, direction=direction, dtype=dtype) with vs.variable_scope("m2"): model2 = CudnnTestModel( rnn_mode, num_layers, num_units, input_size, direction=direction, dtype=dtype) opaque_params = (model1.rnn.trainable_variables[0], model2.rnn.trainable_variables[0]) saveable1 = model1.rnn.saveable weights1, biases1 = saveable1.format_converter._opaque_to_cu_canonical( saveable1._variables) saveable2 = model1.rnn.saveable weights2, biases2 = saveable2.format_converter._opaque_to_cu_canonical( saveable2._variables) reset_params = [ state_ops.assign(params, array_ops.zeros_like(params, dtype=dtype)) for params in opaque_params ] reset_op = control_flow_ops.group(*reset_params) save_path = os.path.join(self.get_temp_dir(), "save-restore-variable-test2") saver = saver_lib.Saver() # Passing graph explicitly, otherwise an old sess would be reused. with self.test_session(use_gpu=True, graph=g) as sess: sess.run(variables.global_variables_initializer()) val = saver.save(sess, save_path) self.assertEqual(save_path, val) weights1_v, biases1_v = sess.run([weights1, biases1]) weights2_v, biases2_v = sess.run([weights2, biases2]) sess.run(reset_op) saver.restore(sess, save_path) weights1_v_restored, biases1_v_restored = sess.run([weights1, biases1]) weights2_v_restored, biases2_v_restored = sess.run([weights2, biases2]) self._CompareWeights(weights1_v, weights1_v_restored) self._CompareWeights(weights2_v, weights2_v_restored) self._CompareBiases(biases1_v, biases1_v_restored, rnn_mode, num_layers, direction) self._CompareBiases(biases2_v, biases2_v_restored, rnn_mode, num_layers, direction) def _TestSaveRestoreOutput(self, rnn_mode, direction, dtype): with ops.Graph().as_default() as g: num_layers = 2 num_units = 7 input_size = 7 seq_length = 8 batch_size = 4 model = CudnnTestModel( rnn_mode, num_layers, num_units, input_size, direction=direction, dtype=dtype, training=False) rnn = model.rnn save_path = os.path.join(self.get_temp_dir(), "save-restore-output-test") saver = saver_lib.Saver() # Only one opaque var in a cudnn layer. assert len(rnn.trainable_variables) == 1 reset_params = state_ops.assign( rnn.trainable_variables[0], array_ops.zeros( array_ops.shape(rnn.trainable_variables[0]), dtype=dtype)) # Passing graph explicitly, otherwise an old sess would be reused. with self.test_session(use_gpu=True, graph=g) as sess: sess.run(variables.global_variables_initializer()) inputs, initial_state = model.SynthesizeInput(seq_length, batch_size) total_sum_v = model.Feed(sess, inputs, initial_state) val = saver.save(sess, save_path) self.assertEqual(save_path, val) sess.run(reset_params) saver.restore(sess, save_path) total_sum_v_restored = model.Feed(sess, inputs, initial_state) self.assertAllClose(total_sum_v, total_sum_v_restored, atol=1e-5) def _TestSaveRestoreHelper(self, rnn_mode): directions = [CUDNN_RNN_UNIDIRECTION, CUDNN_RNN_BIDIRECTION] dtype_list = [dtypes.float16, dtypes.float32, dtypes.float64] for direction, dtype in itertools.product(directions, dtype_list): self._TestSaveRestoreVariable(rnn_mode, direction, dtype) self._TestSaveRestoreTwoVariables(rnn_mode, direction, dtype) self._TestSaveRestoreOutput(rnn_mode, direction, dtype) @unittest.skipUnless(test.is_built_with_cuda(), "Test only applicable when running on GPUs") def testSaveRestoreRepeatedlyCreateCustomSaveable(self): input_size = 3 num_layers = 2 num_units = 7 with ops.Graph().as_default(): random_seed.set_random_seed(1234) model = CudnnTestModel( CUDNN_LSTM, num_layers, num_units, input_size, direction=CUDNN_RNN_UNIDIRECTION, dtype=dtypes.float32) with self.assertRaisesRegexp(RuntimeError, "Cudnn saveable already created"): model.rnn._create_saveable() @unittest.skipUnless(test.is_built_with_cuda(), "Test only applicable when running on GPUs") def testSaveRestoreLSTM(self): self._TestSaveRestoreHelper(CUDNN_LSTM) @unittest.skipUnless(test.is_built_with_cuda(), "Test only applicable when running on GPUs") def testSaveRestoreGRU(self): self._TestSaveRestoreHelper(CUDNN_GRU) @unittest.skipUnless(test.is_built_with_cuda(), "Test only applicable when running on GPUs") def testSaveRestoreRNNTanh(self): self._TestSaveRestoreHelper(CUDNN_RNN_TANH) @unittest.skipUnless(test.is_built_with_cuda(), "Test only applicable when running on GPUs") def testSaveRestoreRNNRelu(self): self._TestSaveRestoreHelper(CUDNN_RNN_RELU) class CudnnRNNTestSaveRestoreTrackable(test_util.TensorFlowTestCase): def _VerifyCheckpoint( self, checkpoint_path, compatible_cell_fn, cudnn_cell_fn, num_layers, input_size, expected_variable_values, num_applications=3): checkpoint_directory = self.get_temp_dir() checkpoint_prefix = os.path.join(checkpoint_directory, "ckpt") with ops.device("gpu:0"): cudnn_layer = cudnn_cell_fn() cudnn_checkpoint = trackable_utils.Checkpoint(cell=cudnn_layer) status = cudnn_checkpoint.restore(checkpoint_path) inputs = 3. * array_ops.ones([num_applications, num_layers, input_size], dtype=dtypes.float32) cudnn_output, _ = cudnn_layer(inputs) status.run_restore_ops() second_save_path = cudnn_checkpoint.save(checkpoint_prefix) restore_layer = compatible_cell_fn() restore_layer_checkpoint = trackable_utils.Checkpoint( cell=restore_layer) status = restore_layer_checkpoint.restore(second_save_path) current_state = restore_layer.zero_state(1, dtypes.float32) for _ in range(num_applications): restore_layer_output, current_state = restore_layer( inputs=3. * array_ops.ones([1, input_size]), state=current_state) status.run_restore_ops() self.assertTrue(restore_layer.variables) for variable, expected_value in zip( restore_layer.variables, expected_variable_values): self.assertAllClose(expected_value, self.evaluate(variable)) self.assertAllClose(self.evaluate(restore_layer_output), self.evaluate(cudnn_output)[-1, -1:, ...]) def _TrackableSingleCellUnidirectionalTestTemplate( self, single_cell_fn, cudnn_cell_fn): # Single-layer cuDNN cells with object-based checkpointing should be # checkpoint compatible with either single CudnnCompatible cells or # MultiRnnCells with one cell. input_size = 3 save_cell_layer = single_cell_fn() save_cell_layer( inputs=array_ops.ones([1, input_size]), state=save_cell_layer.zero_state(1, dtypes.float32)) self.assertTrue(save_cell_layer.variables) expected_values = [] np.random.seed(10) for variable in save_cell_layer.variables: value = np.random.normal(size=variable.shape) expected_values.append(value) self.evaluate(variable.assign(value)) save_checkpoint = trackable_utils.Checkpoint(cell=save_cell_layer) checkpoint_directory = self.get_temp_dir() checkpoint_prefix = os.path.join(checkpoint_directory, "ckpt") first_save_path = save_checkpoint.save(checkpoint_prefix) self._VerifyCheckpoint( checkpoint_path=first_save_path, compatible_cell_fn= lambda: rnn_cell_impl.MultiRNNCell([single_cell_fn()]), cudnn_cell_fn=cudnn_cell_fn, num_layers=1, expected_variable_values=expected_values, input_size=input_size) @unittest.skipUnless(test.is_built_with_cuda(), "Test only applicable when running on GPUs") @test_util.run_in_graph_and_eager_modes def testLSTMTrackableSingleLayer(self): num_units = 2 direction = CUDNN_RNN_UNIDIRECTION self._TrackableSingleCellUnidirectionalTestTemplate( single_cell_fn=functools.partial( cudnn_rnn_ops.CudnnCompatibleLSTMCell, num_units=num_units), cudnn_cell_fn=functools.partial( cudnn_rnn.CudnnLSTM, num_layers=1, num_units=num_units, direction=direction, name="awesome_lstm")) @unittest.skipUnless(test.is_built_with_cuda(), "Test only applicable when running on GPUs") @test_util.run_in_graph_and_eager_modes def testGRUTrackableSingleLayer(self): num_units = 2 direction = CUDNN_RNN_UNIDIRECTION with self.assertRaises(NotImplementedError): # TODO(allenl): Implement object-based saving for GRUs and other cells. self._TrackableSingleCellUnidirectionalTestTemplate( single_cell_fn=functools.partial( cudnn_rnn_ops.CudnnCompatibleGRUCell, num_units=num_units), cudnn_cell_fn=functools.partial( cudnn_rnn.CudnnGRU, num_layers=1, num_units=num_units, direction=direction, name="awesome_gru")) def _TrackableMultiLayerTestTemplate( self, single_cell_fn, cudnn_cell_fn, num_layers): def _MultiCellFn(): return rnn_cell_impl.MultiRNNCell( [single_cell_fn() for _ in range(num_layers)]) input_size = 3 save_graph = ops.Graph() with save_graph.as_default(), self.session(graph=save_graph): save_layer = _MultiCellFn() save_layer(inputs=array_ops.ones([1, input_size]), state=save_layer.zero_state(1, dtypes.float32)) self.assertTrue(save_layer.variables) expected_values = [] np.random.seed(10) for variable in save_layer.variables: value = np.random.normal(size=variable.shape) expected_values.append(value) self.evaluate(variable.assign(value)) save_checkpoint = trackable_utils.Checkpoint(cell=save_layer) checkpoint_directory = self.get_temp_dir() checkpoint_prefix = os.path.join(checkpoint_directory, "ckpt") first_save_path = save_checkpoint.save(checkpoint_prefix) self._VerifyCheckpoint( checkpoint_path=first_save_path, compatible_cell_fn=_MultiCellFn, cudnn_cell_fn=cudnn_cell_fn, num_layers=num_layers, expected_variable_values=expected_values, input_size=input_size) @unittest.skipUnless(test.is_built_with_cuda(), "Test only applicable when running on GPUs") @test_util.run_in_graph_and_eager_modes def testCudnnCompatibleLSTMCheckpointablMultiLayer(self): num_units = 2 num_layers = 3 direction = CUDNN_RNN_UNIDIRECTION self._TrackableMultiLayerTestTemplate( single_cell_fn=functools.partial( cudnn_rnn_ops.CudnnCompatibleLSTMCell, num_units=num_units), cudnn_cell_fn=functools.partial( cudnn_rnn.CudnnLSTM, num_layers=num_layers, num_units=num_units, direction=direction, name="awesome_lstm"), num_layers=num_layers) # TODO(jamesqin): Transform to parameterized test after it is included in the # TF open source codebase. class CudnnRNNTestCompatibleRNNCells(test_util.TensorFlowTestCase): @unittest.skipUnless(test.is_built_with_cuda(), "Test only applicable when running on GPUs") def testCudnnCompatibleLSTM(self): self._TestCudnnCompatibleRnnCellsHelper(CUDNN_LSTM) @unittest.skipUnless(test.is_built_with_cuda(), "Test only applicable when running on GPUs") def testCudnnCompatibleGRU(self): self._TestCudnnCompatibleRnnCellsHelper(CUDNN_GRU) @unittest.skipUnless(test.is_built_with_cuda(), "Test only applicable when running on GPUs") def testCudnnCompatibleRNNTanh(self): self._TestCudnnCompatibleRnnCellsHelper(CUDNN_RNN_TANH) @unittest.skipUnless(test.is_built_with_cuda(), "Test only applicable when running on GPUs") def testCudnnCompatibleRNNRelu(self): self._TestCudnnCompatibleRnnCellsHelper(CUDNN_RNN_RELU) def _TestCudnnCompatibleRnnCellsHelper(self, rnn_mode): configs = [ { "num_layers": 1, "seq_length": 3, "num_units": 4, "input_size": 5, "batch_size": 6, }, { "num_layers": 2, "seq_length": 8, "num_units": 4, "input_size": 8, "batch_size": 16, }, { "num_layers": 2, "seq_length": 3, "num_units": 4, "input_size": 5, "batch_size": 6, }, { "num_layers": 1, "seq_length": 2, "num_units": 2, "input_size": 4, "batch_size": 1, }, ] directions = [CUDNN_RNN_UNIDIRECTION, CUDNN_RNN_BIDIRECTION] for cfg, direction in zip(configs, directions): self._TestCudnnCompatibleRnnCells(cfg["num_layers"], cfg["seq_length"], cfg["num_units"], cfg["input_size"], cfg["batch_size"], rnn_mode, direction) def _TestCudnnCompatibleRnnCells(self, num_layers, seq_length, num_units, input_size, batch_size, rnn_mode, direction): dtype = dtypes.float32 # Train graph with ops.Graph().as_default() as g: model = CudnnTestModel( rnn_mode, num_layers, num_units, input_size, direction=direction, dtype=dtype, training=True) target_output = array_ops.placeholder(dtype=dtype) loss_op = losses.log_loss( labels=target_output, predictions=model.total_sum) optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=1e-2) train_op = optimizer.minimize(loss_op) saver = saver_lib.Saver() # Train Cudnn model seed = 0 with self.test_session(use_gpu=True, graph=g) as sess: sess.run(variables.global_variables_initializer()) # Train 128 steps num_steps = 128 for _ in range(num_steps): inputs, _ = model.SynthesizeInput(seq_length, batch_size, seed) targets = np.random.rand() sess.run( train_op, feed_dict={ model.inputs: inputs, model.initial_state: model.ZeroState(batch_size), target_output: targets }) seed += 1 save_path = os.path.join(self.get_temp_dir(), ("cudnn-rnn-%s-test" % rnn_mode)) save_v = saver.save(sess, save_path) self.assertEqual(save_path, save_v) # Cudnn inference graph with ops.Graph().as_default() as g: model = CudnnTestModel( rnn_mode, num_layers, num_units, input_size, direction=direction, dtype=dtype, training=False) rnn = model.rnn saver = saver_lib.Saver() inference_input = np.random.rand(seq_length, batch_size, input_size).astype(np.float32) with self.test_session(use_gpu=True, graph=g) as sess: sess.run(variables.global_variables_initializer()) saver.restore(sess, save_path) # Cudnn inference cudnn_outputs_v, cudnn_output_states_v = model.Feed( sess, inference_input, return_sum=False) # Canonical RNN inference graph with ops.Graph().as_default() as g: cell_inputs = array_ops.placeholder( dtype, shape=[seq_length, batch_size, input_size]) if direction == CUDNN_RNN_UNIDIRECTION: # outputs is one tensor, states are num_layer tuples, each 2 tensors (outputs, states) = _CreateCudnnCompatibleCanonicalRNN(rnn, cell_inputs) if rnn_mode == CUDNN_LSTM: output_h = array_ops.stack([s.h for s in states]) output_c = array_ops.stack([s.c for s in states]) else: output_state = array_ops.stack([s for s in states]) else: # outputs is one tensor. # states is a tuple of 2 tuples: # each sub tuple is num_layer tuples, each with 2 tensors. (outputs, states) = _CreateCudnnCompatibleCanonicalRNN( rnn, cell_inputs, is_bidi=True) output_state_fw, output_state_bw = states if rnn_mode == CUDNN_LSTM: output_h, output_c = [], [] for s_fw, s_bw in zip(output_state_fw, output_state_bw): output_h.append(array_ops.stack([s_fw.h, s_bw.h])) output_c.append(array_ops.stack([s_fw.c, s_bw.c])) output_h = array_ops.concat(output_h, axis=0) output_c = array_ops.concat(output_c, axis=0) else: output_state = [] for s_fw, s_bw in zip(output_state_fw, output_state_bw): output_state.append(array_ops.stack([s_fw, s_bw])) output_state = array_ops.concat(output_state, axis=0) saver = saver_lib.Saver() with self.test_session(use_gpu=True, graph=g) as sess: saver.restore(sess, save_path) # BlockCell inference if rnn_mode == CUDNN_LSTM: outputs_v, output_h_v, output_c_v = sess.run( [outputs, output_h, output_c], feed_dict={cell_inputs: inference_input}) self.assertAllClose(cudnn_outputs_v, outputs_v) cudnn_output_h_v, cudnn_output_c_v = cudnn_output_states_v self.assertAllClose(cudnn_output_h_v, output_h_v) self.assertAllClose(cudnn_output_c_v, output_c_v) else: outputs_v, output_state_v = sess.run( [outputs, output_state], feed_dict={cell_inputs: inference_input}) self.assertAllClose(cudnn_outputs_v, outputs_v, atol=1e-4, rtol=2e-4) (cudnn_output_h_v,) = cudnn_output_states_v self.assertAllClose(cudnn_output_h_v, output_state_v, atol=2e-5, rtol=2e-5) class CudnnRNNTestParamsSize(test_util.TensorFlowTestCase): def _TestOpaqueParamsSize(self, rnn_mode, num_layers, num_units, input_size, dtype, direction): logging.info("Testing one lstm param size with config: %s", locals()) model = CudnnTestModel( rnn_mode, num_layers, num_units, input_size, dtype=dtype, direction=direction) rnn = model.rnn # Min param size estimate = sum(weights.size) + sum(biases.size) min_params_size = ( sum(map(np.prod, rnn.canonical_weight_shapes)) + sum(sp[0] for sp in rnn.canonical_bias_shapes)) opaque_params = rnn.trainable_variables[0] with self.test_session(use_gpu=True, graph=ops.get_default_graph()): variables.global_variables_initializer().run() opaque_params_size_v = opaque_params.eval().size self.assertLessEqual(min_params_size, opaque_params_size_v) @unittest.skipUnless(test.is_built_with_cuda(), "Test only applicable when running on GPUs") def testOpaqueParamsSize(self): test_configs = [ [4, 200, 200], [4, 200, 300], [4, 200, 100], [1, 100, 200], [2, 200, 100], [3, 200, 400], ] directions = [CUDNN_RNN_UNIDIRECTION, CUDNN_RNN_BIDIRECTION] dtype_list = [dtypes.float16, dtypes.float32, dtypes.float64] rnns = [CUDNN_LSTM, CUDNN_GRU, CUDNN_RNN_RELU, CUDNN_RNN_TANH] for (rnn, config, dtype, direction) in itertools.product( rnns, test_configs, dtype_list, directions): num_layers, num_units, input_size = config with ops.Graph().as_default(): self._TestOpaqueParamsSize(rnn, num_layers, num_units, input_size, dtype, direction) class CudnnRNNTestTraining(test_util.TensorFlowTestCase): def setUp(self): super(CudnnRNNTestTraining, self).setUp() self._reset_rnd_gen_state = os.environ.get("TF_CUDNN_RESET_RND_GEN_STATE", str(False)) self._rnn_use_v2 = os.environ.get("TF_CUDNN_RNN_USE_V2", "0") def tearDown(self): super(CudnnRNNTestTraining, self).tearDown() os.environ["TF_CUDNN_RESET_RND_GEN_STATE"] = self._reset_rnd_gen_state os.environ["TF_CUDNN_RNN_USE_V2"] = self._rnn_use_v2 def _ComputeNumericGrad(self, sess, y, x, delta=1e-4, step=1): """Compute the numeric gradient of y wrt to x. Args: sess: The TF session constructed with a graph containing x and y. y: A scalar TF Tensor in the graph constructed in sess. x: A TF Tensor in the graph constructed in sess. delta: Gradient checker's small perturbation of x[i]. step: Only compute numerical gradients for a subset of x values. I.e. dy/dx[i] is computed if i % step == 0. Returns: A Tensor of the same shape and dtype as x. If x[i] is not chosen to compute the numerical gradient dy/x[i], the corresponding value is set to 0. """ x_data = sess.run(x) x_size = x_data.size x_shape = x_data.shape numeric_grad = np.zeros(x_size, dtype=x_data.dtype) for i in range(0, x_size, step): x_pos = x_data.copy() if x_size == 1: x_pos += delta else: x_pos.flat[i] += delta y_pos_feed_dict = dict([(x.name, x_pos)]) y_pos = sess.run(y, feed_dict=y_pos_feed_dict) x_neg = x_data.copy() if x_size == 1: x_neg -= delta else: x_neg.flat[i] -= delta y_neg_feed_dict = dict([(x.name, x_neg)]) y_neg = sess.run(y, feed_dict=y_neg_feed_dict) numeric_grad[i] = (y_pos - y_neg) / (2 * delta) return numeric_grad.reshape(x_shape) def _GetShape(self, sess, inputs): if not isinstance(inputs, collections.Iterable): return sess.run(array_ops.shape(inputs)) else: return sess.run([array_ops.shape(x) for x in inputs]) def _GradientCheckFp16(self, sess, y, xs, num_samples, tolerance=1e-6, delta=1e-4): """Gradient check for Fp16. Fp16 numerical gradients end up being zeros. Use a new way to check gradients: Given multi-variant function: y = f(x1, x2, ... xn) delta_y = f(x1 + delta_x1, x2+delta_x2, ..., xn+delta_xn) - f(x1, x2, ..., xn) = f'(x1) * delta_x1 + f'(x2) * delta_x2 + .. + f'(xn) * delta_xn where: delta_xi are very small disturbance. f'(xi) is the gradient of y w.r.t xi. The gradient check verifies the expected delta_y calculated by the above equation is close to the actual delta_y. Args: sess: tf.compat.v1.Session object. y: output tensor. xs: a tensor or a list of input tensors. num_samples: number of test samples to run. tolerance: error tolerance. delta: the order of magnititued of input disturbance to apply to calculate the output change w.r.t inputs. """ sym_grads = self._ComputeSymGrads(sess, y, xs) xs_shapes = self._GetShape(sess, xs) x_vals = [sess.run(x) for x in xs] for _ in range(num_samples): delta_xs = [delta * np.random.rand(*shape.tolist()) for shape in xs_shapes] feed_dict = {} for x, x_val, delta_x in zip(xs, x_vals, delta_xs): feed_dict[x] = x_val + delta_x actual_delta_y = (float(sess.run(y, feed_dict=feed_dict)) - float(sess.run(y))) expected_delta_y = 0. for sym_grad, delta_x in zip(sym_grads, delta_xs): expected_delta_y += np.dot( sym_grad.astype(np.float32).flatten(), delta_x.astype(np.float32).flatten()) self.assertAllClose(expected_delta_y, actual_delta_y, atol=tolerance, rtol=tolerance) def _GradientCheck(self, sess, y, xs, tolerance=1e-6, delta=1e-4): sym_grads = self._ComputeSymGrads(sess, y, xs) num_grads = [self._ComputeNumericGrad(sess, y, x, delta) for x in xs] self.assertEqual(len(sym_grads), len(num_grads)) for x, sym, num in zip(xs, sym_grads, num_grads): logging.info("Comparing gradients for input: %s", x.name) self.assertFalse(np.any(np.isnan(sym))) self.assertFalse(np.any(np.isnan(num))) self.assertAllClose(sym, num, atol=tolerance, rtol=tolerance) def _ComputeSymGrads(self, sess, y, xs): sym_grads_t = gradients.gradients(y, xs) return sess.run(sym_grads_t) def _TestOneSimpleTraining(self, rnn_mode, num_layers, num_units, input_size, batch_size, seq_length, dir_count, dropout, dtype, use_v2, delta, tolerance): # Gradient checking runs two forward ops with almost the same input. Need to # make sure the drop patterns across the two runs are the same. logging.info("Training test with config: %s", locals()) os.environ["TF_CUDNN_RESET_RND_GEN_STATE"] = str(True) np.random.seed(1234) random_seed.set_random_seed(5678) has_input_c = (rnn_mode == CUDNN_LSTM) direction = (CUDNN_RNN_UNIDIRECTION if dir_count == 1 else CUDNN_RNN_BIDIRECTION) if use_v2: os.environ["TF_CUDNN_RNN_USE_V2"] = "1" else: os.environ["TF_CUDNN_RNN_USE_V2"] = "0" model = CudnnTestModel( rnn_mode, num_layers, num_units, input_size, direction=direction, dropout=dropout, dtype=dtype, training=True, bias_initializer=init_ops.random_normal_initializer( mean=1., dtype=dtype)) rnn = model.rnn params = rnn.trainable_variables[0] inputs = variables.Variable( random_ops.random_uniform([seq_length, batch_size, input_size], dtype=dtype), dtype=dtype).read_value() input_h = variables.Variable( random_ops.random_uniform( [num_layers * dir_count, batch_size, num_units], dtype=dtype), dtype=dtype).read_value() if has_input_c: input_c = variables.Variable( random_ops.random_uniform( [num_layers * dir_count, batch_size, num_units], dtype=dtype), dtype=dtype).read_value() initial_state = (input_h, input_c) else: initial_state = (input_h,) total_sum = model.FProp(inputs, initial_state, training=True) with self.test_session(use_gpu=True, graph=ops.get_default_graph()) as sess: sess.run(variables.global_variables_initializer()) all_inputs = [inputs, params] for s in initial_state: all_inputs.append(s) if dtype == dtypes.float16: self._GradientCheckFp16( sess, total_sum, all_inputs, num_samples=FLAGS.grad_check_num_samples, tolerance=tolerance, delta=delta) else: for _ in range(FLAGS.grad_check_num_samples): # Each time choose a different set of inputs. sess.run(variables.global_variables_initializer()) self._GradientCheck( sess, total_sum, all_inputs, tolerance=tolerance, delta=delta) def _TestSimpleTrainingHelper(self, rnn_mode, test_configs): dropouts = [0, 0.5, 1.] v2_options = [False, True] for config, dropout, use_v2 in itertools.product(test_configs, dropouts, v2_options): dtype = config.get("dtype", dtypes.float32) delta = config.get("delta", 1e-4) tolerance = config.get("tolerance", 1e-6) dir_count = config.get("dir_count", 1) shape = config["shape"] if dtype == dtypes.float64: # TODO(jamesqin): b/117848763 use_v2 = False with ops.Graph().as_default(): self._TestOneSimpleTraining( rnn_mode, shape["num_layers"], shape["num_units"], shape["input_size"], shape["batch_size"], shape["seq_length"], dir_count, dropout, dtype, use_v2, delta, tolerance) @unittest.skipUnless(test.is_built_with_cuda(), "Test only applicable when running on GPUs") def testSimpleTrainingLSTMFp64(self): test_configs = [ { "dtype": dtypes.float64, "tolerance": 5e-6, "shape": { "num_layers": 2, "num_units": 3, "input_size": 4, "batch_size": 3, "seq_length": 4, }, }, ] self._TestSimpleTrainingHelper(CUDNN_LSTM, test_configs) @unittest.skipUnless(test.is_built_with_cuda(), "Test only applicable when running on GPUs") def testSimpleTrainingLSTMFp32(self): test_configs = [ { "dtype": dtypes.float32, "delta": 1e-4, "tolerance": 9e-2, "shape": { "num_layers": 2, "num_units": 3, "input_size": 4, "batch_size": 3, "seq_length": 4, }, }, ] self._TestSimpleTrainingHelper(CUDNN_LSTM, test_configs) @unittest.skipUnless(test.is_built_with_cuda(), "Test only applicable when running on GPUs") def testSimpleTrainingLSTMFp16(self): test_configs = [ { "dtype": dtypes.float16, "delta": 1e-3, "tolerance": 9e-2, "shape": { "num_layers": 2, "num_units": 3, "input_size": 4, "batch_size": 3, "seq_length": 4, }, }, { "dtype": dtypes.float16, "delta": 1e-2, "tolerance": 9e-2, "shape": { "num_layers": 2, "num_units": 6, "input_size": 8, "batch_size": 6, "seq_length": 4, }, }, ] self._TestSimpleTrainingHelper(CUDNN_LSTM, test_configs) @unittest.skipUnless(test.is_built_with_cuda(), "Test only applicable when running on GPUs") def testSimpleTrainingGRUFp64(self): test_configs = [ { "dtype": dtypes.float64, "tolerance": 5e-6, "shape": { "num_layers": 2, "num_units": 3, "input_size": 4, "batch_size": 3, "seq_length": 4, } }, ] self._TestSimpleTrainingHelper(CUDNN_GRU, test_configs) @unittest.skipUnless(test.is_built_with_cuda(), "Test only applicable when running on GPUs") def testSimpleTrainingGRUFp32(self): test_configs = [ { "dtype": dtypes.float32, "delta": 1e-3, "tolerance": 4e-3, "shape": { "num_layers": 2, "num_units": 3, "input_size": 4, "batch_size": 3, "seq_length": 4, }, }, ] self._TestSimpleTrainingHelper(CUDNN_GRU, test_configs) @unittest.skipUnless(test.is_built_with_cuda(), "Test only applicable when running on GPUs") def testSimpleTrainingGRUFp16(self): test_configs = [ { "dtype": dtypes.float16, "delta": 2e-3, "tolerance": 6e-2, "shape": { "num_layers": 2, "num_units": 3, "input_size": 4, "batch_size": 3, "seq_length": 4, }, }, ] self._TestSimpleTrainingHelper(CUDNN_GRU, test_configs) @unittest.skipUnless(test.is_built_with_cuda(), "Test only applicable when running on GPUs") def testSimpleTrainingRNNTanhFp64(self): test_configs = [ { "dtype": dtypes.float64, "tolerance": 5e-6, "shape": { "num_layers": 2, "num_units": 3, "input_size": 4, "batch_size": 3, "seq_length": 4, }, }, ] self._TestSimpleTrainingHelper(CUDNN_RNN_TANH, test_configs) @unittest.skipUnless(test.is_built_with_cuda(), "Test only applicable when running on GPUs") def testSimpleTrainingRNNTanhFp32(self): test_configs = [ { "dtype": dtypes.float32, "delta": 1e-3, "tolerance": 5e-3, "shape": { "num_layers": 2, "num_units": 3, "input_size": 4, "batch_size": 3, "seq_length": 4, }, }, ] self._TestSimpleTrainingHelper(CUDNN_RNN_TANH, test_configs) @unittest.skipUnless(test.is_built_with_cuda(), "Test only applicable when running on GPUs") def testSimpleTrainingRNNTanhFp16(self): test_configs = [ { "dtype": dtypes.float16, "delta": 1e-3, "tolerance": 5e-2, "shape": { "num_layers": 2, "num_units": 3, "input_size": 4, "batch_size": 3, "seq_length": 4, }, }, ] self._TestSimpleTrainingHelper(CUDNN_RNN_TANH, test_configs) @unittest.skipUnless(test.is_built_with_cuda(), "Test only applicable when running on GPUs") def testSimpleTrainingRNNReluFp64(self): test_configs = [ { "dtype": dtypes.float64, "tolerance": 5e-6, "shape": { "num_layers": 2, "num_units": 3, "input_size": 4, "batch_size": 3, "seq_length": 4, }, }, ] self._TestSimpleTrainingHelper(CUDNN_RNN_RELU, test_configs) @unittest.skipUnless(test.is_built_with_cuda(), "Test only applicable when running on GPUs") def testSimpleTrainingRNNReluFp32(self): test_configs = [ { "dtype": dtypes.float32, "delta": 1e-4, "tolerance": 3e-1, "shape": { "num_layers": 2, "num_units": 3, "input_size": 4, "batch_size": 3, "seq_length": 4, }, }, ] self._TestSimpleTrainingHelper(CUDNN_RNN_RELU, test_configs) @unittest.skipUnless(test.is_built_with_cuda(), "Test only applicable when running on GPUs") def testSimpleTrainingRNNReluFp16(self): test_configs = [ { "dtype": dtypes.float16, "delta": 1e-3, "tolerance": 7e-2, "shape": { "num_layers": 2, "num_units": 3, "input_size": 4, "batch_size": 3, "seq_length": 4, }, }, ] self._TestSimpleTrainingHelper(CUDNN_RNN_RELU, test_configs) if __name__ == "__main__": argv0 = sys.argv[0] parser = argparse.ArgumentParser() parser.add_argument( "--grad_check_num_samples", type=int, default=1, help="Number of samples to run for gradient check.") FLAGS, unparsed = parser.parse_known_args() sys.argv = [argv0] + unparsed googletest.main()
tensorflow-master
tensorflow/contrib/cudnn_rnn/python/kernel_tests/cudnn_rnn_test.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Cudnn RNN operators.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from tensorflow.contrib.checkpoint.python import split_dependency from tensorflow.contrib.rnn.python.ops import lstm_ops from tensorflow.python.compat import compat from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.framework import random_seed from tensorflow.python.keras.engine import base_layer from tensorflow.python.ops import array_ops from tensorflow.python.ops import gen_cudnn_rnn_ops from tensorflow.python.ops import init_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import nn_ops from tensorflow.python.ops import rnn_cell_impl from tensorflow.python.ops import state_ops from tensorflow.python.ops import variable_scope as vs from tensorflow.python.training import saver from tensorflow.python.training.tracking import tracking as trackable_lib CUDNN_RNN_UNIDIRECTION = "unidirectional" CUDNN_RNN_BIDIRECTION = "bidirectional" CUDNN_LSTM = "lstm" CUDNN_GRU = "gru" CUDNN_RNN_RELU = "rnn_relu" CUDNN_RNN_TANH = "rnn_tanh" # Half for cell input, half for hidden states. CUDNN_LSTM_PARAMS_PER_LAYER = 8 CUDNN_GRU_PARAMS_PER_LAYER = 6 CUDNN_RNN_TANH_PARAMS_PER_LAYER = 2 CUDNN_RNN_RELU_PARAMS_PER_LAYER = 2 CUDNN_INPUT_LINEAR_MODE = "linear_input" CUDNN_INPUT_SKIP_MODE = "skip_input" CUDNN_INPUT_AUTO_MODE = "auto_select" # pylint:disable=protected-access _BIAS_VARIABLE_NAME = rnn_cell_impl._BIAS_VARIABLE_NAME _WEIGHTS_VARIABLE_NAME = rnn_cell_impl._WEIGHTS_VARIABLE_NAME # pylint:enable=protected-access class CudnnCompatibleLSTMCell(lstm_ops.LSTMBlockCell): """Cudnn Compatible LSTMCell. A simple wrapper around `tf.contrib.rnn.LSTMBlockCell` to use along with `tf.contrib.cudnn_rnn.CudnnLSTM`. The latter's params can be used by this cell seamlessly. """ def __init__(self, num_units, reuse=None): super(CudnnCompatibleLSTMCell, self).__init__( num_units, forget_bias=0, cell_clip=None, use_peephole=False, reuse=reuse, name="cudnn_compatible_lstm_cell") self._names.update({"scope": "cudnn_compatible_lstm_cell"}) class CudnnCompatibleGRUCell(rnn_cell_impl.GRUCell): r"""Cudnn Compatible GRUCell. A GRU impl akin to `tf.compat.v1.nn.rnn_cell.GRUCell` to use along with `tf.contrib.cudnn_rnn.CudnnGRU`. The latter's params can be used by it seamlessly. It differs from platform-independent GRUs in how the new memory gate is calculated. Nvidia picks this variant based on GRU author's[1] suggestion and the fact it has no accuracy impact[2]. [1] https://arxiv.org/abs/1406.1078 [2] http://svail.github.io/diff_graphs/ Cudnn compatible GRU (from Cudnn library user guide): ```python # reset gate $$r_t = \sigma(x_t * W_r + h_t-1 * R_h + b_{Wr} + b_{Rr})$$ # update gate $$u_t = \sigma(x_t * W_u + h_t-1 * R_u + b_{Wu} + b_{Ru})$$ # new memory gate $$h'_t = tanh(x_t * W_h + r_t .* (h_t-1 * R_h + b_{Rh}) + b_{Wh})$$ $$h_t = (1 - u_t) .* h'_t + u_t .* h_t-1$$ ``` Other GRU (see `tf.compat.v1.nn.rnn_cell.GRUCell` and `tf.contrib.rnn.GRUBlockCell`): ```python # new memory gate \\(h'_t = tanh(x_t * W_h + (r_t .* h_t-1) * R_h + b_{Wh})\\) ``` which is not equivalent to Cudnn GRU: in addition to the extra bias term b_Rh, ```python \\(r .* (h * R) != (r .* h) * R\\) ``` """ def __init__(self, num_units, reuse=None, kernel_initializer=None): super(CudnnCompatibleGRUCell, self).__init__( num_units, activation=None, reuse=reuse, kernel_initializer=kernel_initializer) def build(self, inputs_shape): if inputs_shape[1].value is None: raise ValueError("Expected inputs.shape[-1] to be known, saw shape: %s" % inputs_shape) input_depth = inputs_shape[1].value self._gate_kernel = self.add_variable( "gates/%s" % _WEIGHTS_VARIABLE_NAME, shape=[input_depth + self._num_units, 2 * self._num_units], initializer=self._kernel_initializer) self._gate_bias = self.add_variable( "gates/%s" % _BIAS_VARIABLE_NAME, shape=[2 * self._num_units], initializer=(self._bias_initializer if self._bias_initializer is not None else init_ops.constant_initializer(1.0, dtype=self.dtype))) self._candidate_input_kernel = self.add_variable( "candidate/input_projection/%s" % _WEIGHTS_VARIABLE_NAME, shape=[input_depth, self._num_units], initializer=self._kernel_initializer) self._candidate_hidden_kernel = self.add_variable( "candidate/hidden_projection/%s" % _WEIGHTS_VARIABLE_NAME, shape=[self._num_units, self._num_units], initializer=self._kernel_initializer) self._candidate_input_bias = self.add_variable( "candidate/input_projection/%s" % _BIAS_VARIABLE_NAME, shape=[self._num_units], initializer=(self._bias_initializer if self._bias_initializer is not None else init_ops.zeros_initializer(dtype=self.dtype))) self._candidate_hidden_bias = self.add_variable( "candidate/hidden_projection/%s" % _BIAS_VARIABLE_NAME, shape=[self._num_units], initializer=(self._bias_initializer if self._bias_initializer is not None else init_ops.zeros_initializer(dtype=self.dtype))) def call(self, inputs, state): """Gated recurrent unit (GRU) with nunits cells.""" gate_inputs = math_ops.matmul( array_ops.concat([inputs, state], 1), self._gate_kernel) gate_inputs = nn_ops.bias_add(gate_inputs, self._gate_bias) value = math_ops.sigmoid(gate_inputs) r, u = array_ops.split(value=value, num_or_size_splits=2, axis=1) candidate = nn_ops.bias_add( math_ops.matmul(inputs, self._candidate_input_kernel), self._candidate_input_bias) candidate += r * nn_ops.bias_add( math_ops.matmul(state, self._candidate_hidden_kernel), self._candidate_hidden_bias) candidate = self._activation(candidate) new_h = (1 - u) * candidate + u * state return new_h, new_h class CudnnParamsFormatConverter(object): """Abstract class that converts between params of Cudnn Rnn and TF Rnn.""" def __init__(self, num_layers, num_units, input_size, num_proj=None, input_mode=CUDNN_INPUT_LINEAR_MODE, direction=CUDNN_RNN_UNIDIRECTION): """Constructor. Args: num_layers: the number of layers for the RNN model. num_units: the number of units within the RNN model. input_size: the size of the input, it could be different from the num_units. num_proj: The output dimensionality for the projection matrices. If None or 0, no projection is performed. input_mode: indicate whether there is a linear projection between the input and the actual computation before the first layer. It could be one of 'linear_input', 'skip_input' or 'auto_select'. * 'linear_input' (default) always applies a linear projection of input onto RNN hidden state. (standard RNN behavior). * 'skip_input' is only allowed when input_size == num_units; * 'auto_select' implies 'skip_input' when input_size == num_units; otherwise, it implies 'linear_input'. direction: the direction model that the model operates. Could be either 'unidirectional' or 'bidirectional' """ self._num_layers = num_layers self._input_size = input_size self._num_units = num_units self._input_mode = input_mode self._num_proj = num_proj self._direction = direction self._num_dirs = 1 if self._direction == CUDNN_RNN_UNIDIRECTION else 2 self._num_params = ( self._num_params_per_layer * self._num_layers * self._num_dirs) def tf_canonical_to_opaque(self, tf_canonicals, weights_proj=None): r"""Converts tf canonical weights to cudnn opaque param.""" cu_weights, cu_biases = self._tf_canonical_to_cu_canonical( tf_canonicals, weights_proj) cu_weights = [array_ops.reshape(w, [-1]) for w in cu_weights] opaque_params = self._cu_canonical_to_opaque(cu_weights, cu_biases) return opaque_params def opaque_to_tf_canonical(self, opaque_param): r"""Converts cudnn opaque param to tf canonical weights.""" cu_weights, cu_biases = self._opaque_to_cu_canonical(opaque_param) if self._num_proj: weights, biases, weights_proj = self._cu_canonical_to_tf_canonical( cu_weights, cu_biases) return weights, biases, weights_proj else: weights, biases = self._cu_canonical_to_tf_canonical( cu_weights, cu_biases) return weights, biases def _opaque_to_cu_canonical(self, opaque_param): """Converts opaque params to Cudnn canonical format. Args: opaque_param: An opaque tensor storing cudnn rnn params (weights and biases). Returns: 2 list for weights and biases respectively. """ with ops.device("/gpu:0"): if compat.forward_compatible(2019, 6, 26) and self._num_proj: num_params_weights = ( self._num_params + 1 * self._num_layers * self._num_dirs) num_params_biases = self._num_params weights, biases = gen_cudnn_rnn_ops.cudnn_rnn_params_to_canonical_v2( num_layers=self._num_layers, num_units=self._num_units, input_size=self._input_size, params=opaque_param, rnn_mode=self._rnn_mode, input_mode=self._input_mode, direction=self._direction, num_params_weights=num_params_weights, num_params_biases=num_params_biases, num_proj=self._num_proj) else: weights, biases = gen_cudnn_rnn_ops.cudnn_rnn_params_to_canonical( num_layers=self._num_layers, num_units=self._num_units, input_size=self._input_size, params=opaque_param, num_params=self._num_params, rnn_mode=self._rnn_mode, input_mode=self._input_mode, direction=self._direction) return (weights, biases) def _cu_canonical_to_opaque(self, cu_weights, cu_biases): """Converts from Cudnn canonical format to opaque params. Args: cu_weights: a list of tensors, Cudnn canonical weights. cu_biases: a list of tensors, Cudnn canonical biases. Returns: a single opaque tensor. """ with ops.device("/gpu:0"): if compat.forward_compatible(2019, 6, 26) and self._num_proj: return gen_cudnn_rnn_ops.cudnn_rnn_canonical_to_params_v2( num_layers=self._num_layers, num_units=self._num_units, input_size=self._input_size, weights=cu_weights, biases=cu_biases, rnn_mode=self._rnn_mode, input_mode=self._input_mode, num_proj=self._num_proj, direction=self._direction) else: return gen_cudnn_rnn_ops.cudnn_rnn_canonical_to_params( num_layers=self._num_layers, num_units=self._num_units, input_size=self._input_size, weights=cu_weights, biases=cu_biases, rnn_mode=self._rnn_mode, input_mode=self._input_mode, direction=self._direction) def _cu_canonical_to_tf_canonical(self, cu_weights, cu_biases): r"""Transform from Cudnn canonical to tf canonical. The elements of argument lists are laid out in the following format: ------------------------------------------------------------ | weights | biases | ------------------------------------------------------------ \ \ \ \ ------------------------------- | layer1 |layer2 |... | ------------------------------- \ \ --------------- |fwd |bak | --------------- Args: cu_weights: a list of tensors of Cudnn canonical weights. cu_biases: a list of tensors of Cudnn canonical biases. Returns: 1 tuple, tf canonical weights and biases. """ tf_weights, tf_biases = [], [] tf_weights_proj = [] layer_weights_num = self._num_params_per_layer * self._num_dirs layer_biases_num = layer_weights_num layer_weights_num += (1 * self._num_dirs) if self._num_proj else 0 for i in range(self._num_layers): layer_weights = cu_weights[i * layer_weights_num:(i + 1) * layer_weights_num] layer_biases = cu_biases[i * layer_biases_num:(i + 1) * layer_biases_num] if self._direction == CUDNN_RNN_UNIDIRECTION: self._cu_canonical_to_tf_canonical_single_layer(layer_weights, layer_biases, tf_weights, tf_biases, tf_weights_proj) else: fw_weights = layer_weights[:len(layer_weights) // 2] bw_weights = layer_weights[len(layer_weights) // 2:] fw_biases = layer_biases[:len(layer_biases) // 2] bw_biases = layer_biases[len(layer_biases) // 2:] self._cu_canonical_to_tf_canonical_single_layer( fw_weights, fw_biases, tf_weights, tf_biases, tf_weights_proj, ) self._cu_canonical_to_tf_canonical_single_layer( bw_weights, bw_biases, tf_weights, tf_biases, tf_weights_proj, ) if self._num_proj: return (tf_weights, tf_biases, tf_weights_proj) else: return (tf_weights, tf_biases) def _cu_canonical_to_tf_canonical_single_layer(self, cu_weights, cu_biases, tf_weights, tf_biases, tf_weigths_proj=None): r"""Transform single layer Cudnn canonicals to tf canonicals. The elements of cu_weights, cu_biases are laid out in the following format: ------------------------------------------------------------------------- | gate0 param on inputs | gate0 param on hidden state | gate1 ..........| ------------------------------------------------------------------------- Args: cu_weights: a list of tensors, single layer weights. cu_biases: a list of tensors, single layer biases. tf_weights: a list where transformed weights are stored. tf_biases: a list where transformed biases are stored. """ raise NotImplementedError("Abstract method") def _tf_canonical_to_cu_canonical(self, tf_canonicals, weights_proj): r"""Transform from tf canonical to Cudnn canonical. This is the reverse routine of _TransformCanonical(). Args: tf_canonicals: a list of tensors of tf canonical params. The elements are laid out in the following format: ------------------------------------------------------------ | weights | biases | ------------------------------------------------------------ \ \ \ \ ------------------------------- | layer1 |layer2 |... | ------------------------------- \ \ --------------- |fwd |bak | --------------- weights_proj: (optional) weights matrices for projection Returns: 2 lists: the recovered cudnn canonical weights and biases. """ weights = tf_canonicals[:len(tf_canonicals) // 2] biases = tf_canonicals[len(tf_canonicals) // 2:] cu_weights, cu_biases = [], [] layer_weights_num = len(weights) // self._num_layers layer_biases_num = len(biases) // self._num_layers for i in range(self._num_layers): layer_weights = weights[i * layer_weights_num:(i + 1) * layer_weights_num] layer_biases = biases[i * layer_biases_num:(i + 1) * layer_biases_num] if self._direction == CUDNN_RNN_UNIDIRECTION: cu_weights.extend(self._tf_to_cudnn_weights(i, *layer_weights)) if weights_proj is not None: pw = array_ops.transpose(weights_proj[i]) cu_weights.append(pw) cu_biases.extend(self._tf_to_cudnn_biases(*layer_biases)) else: fw_weights, bw_weights = layer_weights[:len(layer_weights) // 2], layer_weights[ len(layer_weights) // 2:] fw_biases, bw_biases = layer_biases[:len(layer_biases) // 2], layer_biases[len(layer_biases ) // 2:] cu_weights.extend(self._tf_to_cudnn_weights(i, *fw_weights)) if weights_proj is not None: pw0 = array_ops.transpose(weights_proj[2 * i + 0]) cu_weights.append(pw0) cu_biases.extend(self._tf_to_cudnn_biases(*fw_biases)) cu_weights.extend(self._tf_to_cudnn_weights(i, *bw_weights)) if weights_proj is not None: pw1 = array_ops.transpose(weights_proj[2 * i + 1]) cu_weights.append(pw1) cu_biases.extend(self._tf_to_cudnn_biases(*bw_biases)) return cu_weights, cu_biases def _cudnn_to_tf_weights(self, *cu_weights): r"""Stitches cudnn canonical weights to generate tf canonical weights.""" raise NotImplementedError("Abstract method") def _tf_to_cudnn_weights(self, layer, *tf_weights): r"""Reverses the operations in StitchWeights().""" raise NotImplementedError("Abstract method") def _cudnn_to_tf_biases(self, *biases): r"""Stitches cudnn canonical biases to generate tf canonical biases.""" raise NotImplementedError("Abstract method") def _tf_to_cudnn_biases(self, *tf_biases): r"""Reverses the operations in StitchBiases().""" raise NotImplementedError("Abstract method") class CudnnParamsFormatConverterLSTM(CudnnParamsFormatConverter): """Helper class that converts between params of Cudnn and TF LSTM.""" _rnn_mode = CUDNN_LSTM _num_params_per_layer = CUDNN_LSTM_PARAMS_PER_LAYER def _cudnn_to_tf_gate_params(self, *cu_gate_order): i_g, f_g, c_g, o_g = cu_gate_order return [i_g, c_g, f_g, o_g] def _tf_to_cudnn_gate_params(self, *tf_gate_order): i_g, c_g, f_g, o_g = tf_gate_order return [i_g, f_g, c_g, o_g] def _cudnn_to_tf_weights(self, *cu_weights): r"""Stitching cudnn canonical weights to generate tf canonical weights.""" if self._num_proj: w_i, w_f, w_c, w_o, r_i, r_f, r_c, r_o, pw = cu_weights else: w_i, w_f, w_c, w_o, r_i, r_f, r_c, r_o = cu_weights # pylint: disable=invalid-name W_i = array_ops.concat([w_i, r_i], axis=1) W_f = array_ops.concat([w_f, r_f], axis=1) W_c = array_ops.concat([w_c, r_c], axis=1) W_o = array_ops.concat([w_o, r_o], axis=1) # pylint: enable=invalid-name # Cudnn LSTM weights are in ifco order, other tf LSTMs are in icfo order. reordered = self._cudnn_to_tf_gate_params(*[W_i, W_f, W_c, W_o]) if self._num_proj: return (array_ops.transpose(array_ops.concat(reordered, axis=0)), array_ops.transpose(pw)) else: return (array_ops.transpose(array_ops.concat(reordered, axis=0)),) def _tf_to_cudnn_weights(self, layer, *tf_weights): r"""Reverse the operations in StitchWeights().""" input_size = self._input_size num_units = self._num_units if layer == 0: input_weight_width = input_size else: input_weight_width = self._num_proj if self._num_proj else num_units if self._direction == CUDNN_RNN_BIDIRECTION: input_weight_width *= 2 (tf_weight,) = tf_weights w = array_ops.transpose(tf_weight) # pylint: disable=invalid-name W_i, W_f, W_c, W_o = self._tf_to_cudnn_gate_params( *array_ops.split(w, 4, axis=0)) hidden_state_width = self._num_proj if self._num_proj else num_units w_i, r_i = array_ops.split( W_i, [input_weight_width, hidden_state_width], axis=1) w_c, r_c = array_ops.split( W_c, [input_weight_width, hidden_state_width], axis=1) w_f, r_f = array_ops.split( W_f, [input_weight_width, hidden_state_width], axis=1) w_o, r_o = array_ops.split( W_o, [input_weight_width, hidden_state_width], axis=1) return w_i, w_f, w_c, w_o, r_i, r_f, r_c, r_o # pylint: enable=invalid-name def _cudnn_to_tf_biases(self, *cu_biases): r"""Stitching cudnn canonical biases to generate tf canonical biases.""" b_wi, b_wf, b_wc, b_wo, b_ri, b_rf, b_rc, b_ro = cu_biases # Save only the sum instead of individual biases. When recovering, return # two biases each with half the value. Since RNN does not regularize by # weight decay, it has no side effect in training or inference. # pylint: disable=invalid-name B_i = b_wi + b_ri B_f = b_wf + b_rf B_c = b_wc + b_rc B_o = b_wo + b_ro # pylint: enable=invalid-name reordered = self._cudnn_to_tf_gate_params(*[B_i, B_f, B_c, B_o]) return (array_ops.concat(reordered, axis=0),) def _tf_to_cudnn_biases(self, *tf_biases): r"""Reverse the operations in StitchBiases().""" (tf_bias,) = tf_biases # pylint: disable=invalid-name B_i, B_f, B_c, B_o = self._tf_to_cudnn_gate_params( *array_ops.split(tf_bias, 4, axis=0)) # pylint: enable=invalid-name # pylint: disable=unbalanced-tuple-unpacking b_wi, b_ri = (B_i * 0.5,) * 2 b_wf, b_rf = (B_f * 0.5,) * 2 b_wc, b_rc = (B_c * 0.5,) * 2 b_wo, b_ro = (B_o * 0.5,) * 2 # pylint: enable=unbalanced-tuple-unpacking # Return ifco order for Cudnn LSTM. return b_wi, b_wf, b_wc, b_wo, b_ri, b_rf, b_rc, b_ro def _cu_canonical_to_tf_canonical_single_layer(self, cu_weights, cu_biases, tf_weights, tf_biases, tf_weights_proj=None): if self._num_proj: (w, pw) = self._cudnn_to_tf_weights(*cu_weights) tf_weights.append(w) tf_weights_proj.append(pw) else: (w,) = self._cudnn_to_tf_weights(*cu_weights) tf_weights.append(w) (b,) = self._cudnn_to_tf_biases(*cu_biases) tf_biases.append(b) class CudnnParamsFormatConverterGRU(CudnnParamsFormatConverter): """Helper class that converts between params of Cudnn and TF GRU.""" _rnn_mode = CUDNN_GRU _num_params_per_layer = CUDNN_GRU_PARAMS_PER_LAYER _rnn_cell_name = base_layer.to_snake_case(CudnnCompatibleGRUCell.__name__) def _cudnn_to_tf_weights(self, *cu_weights): r"""Stitching cudnn canonical weights to generate tf canonical weights.""" w_i, w_r, w_h, r_i, r_r, r_h = cu_weights # pylint: disable=invalid-name W_i = array_ops.concat([w_i, r_i], axis=1) W_r = array_ops.concat([w_r, r_r], axis=1) # pylint: enable=invalid-name return (array_ops.transpose(array_ops.concat([W_i, W_r], axis=0)), array_ops.transpose(w_h), array_ops.transpose(r_h)) def _tf_to_cudnn_weights(self, layer, *tf_weights): r"""Reverse the operations in StitchWeights().""" input_size = self._input_size num_units = self._num_units if layer == 0: input_weight_width = input_size else: input_weight_width = num_units if self._direction == CUDNN_RNN_BIDIRECTION: input_weight_width *= 2 # pylint: disable=invalid-name W_ir, w_h, r_h = tf_weights W_ir = array_ops.transpose(W_ir) w_h = array_ops.transpose(w_h) r_h = array_ops.transpose(r_h) W_i, W_r = array_ops.split(W_ir, 2, axis=0) w_i, r_i = array_ops.split(W_i, [input_weight_width, num_units], axis=1) w_r, r_r = array_ops.split(W_r, [input_weight_width, num_units], axis=1) # pylint: enable=invalid-name return w_i, w_r, w_h, r_i, r_r, r_h def _cudnn_to_tf_biases(self, *biases): r"""Stitching cudnn canonical biases to generate tf canonical biases.""" b_wi, b_wr, b_wh, b_ri, b_rr, b_rh = biases return ( # Save only the sum instead of individual biases. When recovering, # return two biases each with half the value. Since RNN does not # regularize by weight decay, it has no side effect in training or # inference. array_ops.concat([b_wi, b_wr], axis=0) + array_ops.concat([b_ri, b_rr], axis=0), b_wh, b_rh) def _tf_to_cudnn_biases(self, *tf_biases): r"""Reverse the operations in StitchBiases().""" # b_ir is the summed bias of reset and update gate. b_ir, b_wh, b_rh = tf_biases bi, br = b_ir * 0.5, b_ir * 0.5 b_wi, b_wr = array_ops.split(bi, 2, axis=0) b_ri, b_rr = array_ops.split(br, 2, axis=0) return b_wi, b_wr, b_wh, b_ri, b_rr, b_rh def _cu_canonical_to_tf_canonical_single_layer(self, cu_weights, cu_biases, tf_weights, tf_biases, tf_weights_proj=None): # pylint: disable=invalid-name W_ir, w_h, r_h = self._cudnn_to_tf_weights(*cu_weights) b_ir, b_wh, b_rh = self._cudnn_to_tf_biases(*cu_biases) # pylint: enable=invalid-name tf_weights.extend([W_ir, w_h, r_h]) tf_biases.extend([b_ir, b_wh, b_rh]) class CudnnParamsFormatConverterBasic(CudnnParamsFormatConverterLSTM): """Helper class that converts between params of Cudnn and TF Relu/Tanh RNN.""" def _cudnn_to_tf_weights(self, *cu_weights): r"""Stitching cudnn canonical weights to generate tf canonical weights.""" w_i, w_h = cu_weights W = array_ops.concat([w_i, w_h], axis=1) # pylint: disable=invalid-name return (array_ops.transpose(W),) def _tf_to_cudnn_weights(self, layer, *tf_weights): r"""Reverse the operations in StitchWeights().""" input_size = self._input_size num_units = self._num_units if layer == 0: input_weight_width = input_size else: input_weight_width = num_units if self._direction == CUDNN_RNN_BIDIRECTION: input_weight_width *= 2 (tf_weight,) = tf_weights # pylint: disable=invalid-name W = array_ops.transpose(tf_weight) w_i, w_h = array_ops.split(W, [input_weight_width, num_units], axis=1) return w_i, w_h # pylint: enable=invalid-name def _cudnn_to_tf_biases(self, *cu_biases): r"""Stitching cudnn canonical biases to generate tf canonical biases.""" # Save only the sum instead of individual biases. When recovering, return # two biases each with half the value. Since RNN does not regularize by # weight decay, it has no side effect in training or inference. b_wi, b_wh = cu_biases return (b_wi + b_wh,) def _tf_to_cudnn_biases(self, *tf_biases): r"""Reverse the operations in StitchBiases().""" (tf_bias,) = tf_biases b_i = tf_bias * 0.5 b_h = tf_bias * 0.5 return b_i, b_h class CudnnParamsFormatConverterTanh(CudnnParamsFormatConverterBasic): """Helper class that converts between params of Cudnn and TF Tanh RNN.""" _rnn_mode = CUDNN_RNN_TANH _num_params_per_layer = CUDNN_RNN_TANH_PARAMS_PER_LAYER class CudnnParamsFormatConverterRelu(CudnnParamsFormatConverterBasic): """Helper class that converts between params of Cudnn and TF Relu RNN.""" _rnn_mode = CUDNN_RNN_RELU _num_params_per_layer = CUDNN_RNN_RELU_PARAMS_PER_LAYER # TODO(yaozhang): make sure we only save the canonical version of params and # don't save the platform-specific version to avoid potential race # conditions where params is updated by both versions when being restored. # Currently, checkpointing will function properly, despite that we save both # versions, because Saver restores customized savables after Variables. # However, it is good to not rely on this restoring order of Saver and to # avoid unnecessary storage. Add a test to check only the canonical version is # saved. class CudnnOpaqueParamsSaveable(saver.BaseSaverBuilder.SaveableObject): """Abstract SaveableObject implementation handling Cudnn opaque params.""" def __init__(self, opaque_params, num_layers, num_units, input_size, input_mode=CUDNN_INPUT_LINEAR_MODE, direction=CUDNN_RNN_UNIDIRECTION, scope=None, name="cudnn_rnn_saveable"): """Creates a CudnnOpaqueParamsSaveable object. CudnnOpaqueParamsSaveable is saveable/restorable in a checkpoint file and is used to save/restore the weights and biases parameters in a canonical format which is directly consumable by platform-independent tf RNN cells. Parameters are saved as tensors layer by layer with weight tensors followed by bias tensors, and forward direction followed by backward direction (if applicable). When restoring, a user could name param_variables as desired, and restore weight and bias tensors to these variables. For CudnnRNNRelu or CudnnRNNTanh, there are 2 tensors per weight and per bias for each layer: tensor 0 is applied to the input from the previous layer and tensor 1 to the recurrent input. For CudnnLSTM, there are 8 tensors per weight and per bias for each layer: tensor 0-3 are applied to the input from the previous layer and tensor 4-7 to the recurrent input. Tensor 0 and 4 are for the input gate; tensor 1 and 5 the forget gate; tensor 2 and 6 the new memory gate; tensor 3 and 7 the output gate. For CudnnGRU, there are 6 tensors per weight and per bias for each layer: tensor 0-2 are applied to the input from the previous layer and tensor 3-5 to the recurrent input. Tensor 0 and 3 are for the reset gate; tensor 1 and 4 the update gate; tensor 2 and 5 the new memory gate. Args: opaque_params: a variable, Cudnn RNN opaque params. num_layers: the number of layers for the RNN model. num_units: the number of units within the RNN model. input_size: the size of the input, it could be different from the num_units. input_mode: indicate whether there is a linear projection between the input and the actual computation before the first layer. It could be 'linear_input', 'skip_input' or 'auto_select'. 'linear_input' (default) always applies a linear projection of input onto RNN hidden state. (standard RNN behavior). 'skip_input' is only allowed when input_size == num_units; 'auto_select' implies 'skip_input' when input_size == num_units; otherwise, it implies 'linear_input'. direction: the direction model that the model operates. Could be either 'unidirectional' or 'bidirectional' scope: string of VariableScope, the scope of equivalent subgraph consisting only platform-independent tf RNN cells. name: the name of the CudnnOpaqueParamsSaveable object. """ # Define in subclasses. self._num_layers = num_layers self._input_size = input_size self._num_units = num_units self._input_mode = input_mode self._direction = direction if scope is not None: scope_name = scope.name if isinstance(scope, vs.VariableScope) else scope self._scope = scope_name or None else: self._scope = None self._variables = opaque_params self._num_dirs = 1 if self._direction == CUDNN_RNN_UNIDIRECTION else 2 # Defined in subclasses. self._format_converter = None tf_weights, tf_biases = ( self.format_converter.opaque_to_tf_canonical(self._variables)) tf_weight_names, tf_bias_names = self._tf_canonical_names() # We currently don't use slice_spec. It might be useful in a distributed # setting where each parameter server node stores a slice of variable, # instead of having the master pull all slices and then save them. slice_spec = "" params = tf_weights + tf_biases self._weight_names = tf_weight_names self._bias_names = tf_bias_names self._param_names = tf_weight_names + tf_bias_names prefixed_param_names = tf_weight_names + tf_bias_names if self._scope: prefixed_param_names = [ "%s/%s" % (self._scope, pn) for pn in prefixed_param_names ] specs = [ saver.BaseSaverBuilder.SaveSpec(param, slice_spec, param_name) for param, param_name in zip(params, prefixed_param_names) ] super(CudnnOpaqueParamsSaveable, self).__init__(array_ops.identity(self._variables), specs, name) @property def format_converter(self): if self._format_converter is None: self._format_converter = self._format_converter_cls( self._num_layers, self._num_units, self._input_size, input_mode=self._input_mode, direction=self._direction) return self._format_converter def restore(self, restored_tensors, restored_shapes): opaque_params = self.format_converter.tf_canonical_to_opaque( restored_tensors) return state_ops.assign( self._variables, opaque_params, validate_shape=False) def _trackable_save(self, save_buffer): weights, biases = self.format_converter.opaque_to_tf_canonical( self._variables) for name, tensor in zip(self._param_names, weights + biases): save_buffer[name] = array_ops.identity(tensor) def _trackable_restore(self, restore_buffer): tensors = [ array_ops.identity(restore_buffer[name]) for name in self._param_names ] return self.restore( restored_tensors=tensors, restored_shapes=None # Unused ) def _add_trackable_dependencies(self, trackable, dtype): """Add canonical weight dependencies to `trackable`. When saving or restoring, converts to or from the opaque buffer format. Weights are saved and loaded in the configuration expected by cuDNN-compatible cells. Args: trackable: An object inheriting from `Trackable` to add dependencies too (typically the cuDNN `Layer`). dtype: The dtype for the canonical parameter Tensors. """ split_dependencies = split_dependency.split_dependency( component_names=self._param_names, component_dtypes=(dtype,) * len(self._param_names), fill_save_buffer_fn=self._trackable_save, consume_restore_buffer_fn=self._trackable_restore, device=self._variables[0].device) self._trackable_track_params(trackable, split_dependencies) def _trackable_track_params(self, trackable, params): """Tracks parameters in a canonical configuration.""" return # NotImplementedError raised by the Layer. def _tf_canonical_names(self): tf_weights_names, tf_biases_names = [], [] for i in range(self._num_layers): if self._direction == CUDNN_RNN_UNIDIRECTION: prefix = self._tf_canonical_name_prefix(i) self._tf_canonical_names_single_layer(prefix, tf_weights_names, tf_biases_names) else: fwd_prefix = self._tf_canonical_name_prefix(i, is_fwd=True) bak_prefix = self._tf_canonical_name_prefix(i, is_fwd=False) self._tf_canonical_names_single_layer(fwd_prefix, tf_weights_names, tf_biases_names) self._tf_canonical_names_single_layer(bak_prefix, tf_weights_names, tf_biases_names) return tf_weights_names, tf_biases_names def _tf_canonical_name_prefix(self, layer, is_fwd=True): if self._direction == CUDNN_RNN_UNIDIRECTION: return "rnn/multi_rnn_cell/cell_%d/%s" % (layer, self._rnn_cell_name) else: if is_fwd: return ("stack_bidirectional_rnn/cell_%d/bidirectional_rnn/fw/%s" % (layer, self._rnn_cell_name)) else: return ("stack_bidirectional_rnn/cell_%d/bidirectional_rnn/bw/%s" % (layer, self._rnn_cell_name)) def _tf_canonical_names_single_layer(self, prefix, tf_weights_names, tf_biases_names): raise NotImplementedError("Abstract method") class CudnnLSTMSaveable(CudnnOpaqueParamsSaveable): """SaveableObject implementation handling Cudnn LSTM opaque params.""" _format_converter_cls = CudnnParamsFormatConverterLSTM _rnn_cell_name = base_layer.to_snake_case(CudnnCompatibleLSTMCell.__name__) def _tf_canonical_names_single_layer(self, prefix, tf_weights_names, tf_bias_names): tf_weights_names.append(prefix + "/kernel") tf_bias_names.append(prefix + "/bias") def _trackable_track_params(self, trackable, params): """Track parameters for compatibility with CudnnCompatibleLSTMCell.""" biases = [] weights = [] for name in self._weight_names: weights.append(params[name]) for name in self._bias_names: biases.append(params[name]) assert len(params) == len(weights) + len(biases) if len(weights) == 1 and len(biases) == 1: # For single-layer cells, allow substituting a cell with no MultiRNNCell # wrapping. kernel, = weights # pylint: disable=unbalanced-tuple-unpacking bias, = biases # pylint: disable=unbalanced-tuple-unpacking trackable._track_trackable(kernel, name="kernel") # pylint: disable=protected-access trackable._track_trackable(bias, name="bias") # pylint: disable=protected-access assert len(biases) == len(weights) for cell_index, (bias, kernel) in enumerate(zip(biases, weights)): cell = trackable_lib.AutoTrackable() trackable._track_trackable(cell, name="cell-%d" % cell_index) # pylint: disable=protected-access cell.bias = bias cell.kernel = kernel class CudnnGRUSaveable(CudnnOpaqueParamsSaveable): """SaveableObject implementation handling Cudnn GRU opaque params.""" _format_converter_cls = CudnnParamsFormatConverterGRU _rnn_cell_name = base_layer.to_snake_case(CudnnCompatibleGRUCell.__name__) def _tf_canonical_names_single_layer(self, prefix, tf_weights_names, tf_bias_names): tf_weights_names.append(prefix + "/gates/kernel") tf_weights_names.append(prefix + "/candidate/input_projection/kernel") tf_weights_names.append(prefix + "/candidate/hidden_projection/kernel") tf_bias_names.append(prefix + "/gates/bias") tf_bias_names.append(prefix + "/candidate/input_projection/bias") tf_bias_names.append(prefix + "/candidate/hidden_projection/bias") class CudnnRNNTanhSaveable(CudnnLSTMSaveable): _format_converter_cls = CudnnParamsFormatConverterTanh _rnn_cell_name = base_layer.to_snake_case(rnn_cell_impl.BasicRNNCell.__name__) class CudnnRNNReluSaveable(CudnnLSTMSaveable): _format_converter_cls = CudnnParamsFormatConverterRelu _rnn_cell_name = base_layer.to_snake_case(rnn_cell_impl.BasicRNNCell.__name__) _cudnn_rnn_common_doc_string = """ Cudnn RNN has an opaque parameter buffer that can be used for inference and training. But it is possible that the layout of the parameter buffers changes between generations. So it is highly recommended to use CudnnOpaqueParamsSaveable to save and restore weights and biases in a canonical format. This is a typical use case: * The user creates a CudnnRNN model. * The user query that parameter buffer size. * The user creates a variable of that size that serves as the parameter buffers. * The user either initialize the parameter buffer, or load the canonical weights into the parameter buffer. * The user calls the model with the parameter buffer for inference, or training. * If training, the user creates a Saver object. * If training, the user creates a CudnnOpaqueParamsSaveable object from the parameter buffer for it to be later saved in the canonical format. When creating a CudnnOpaqueParamsSaveable object, a name could be provided, which is useful in distinguishing the names of multiple CudnnOpaqueParamsSaveable objects (e.g. for an encoder-decoder model). * Once a while, the user saves the parameter buffer into model checkpoints with Saver.save(). * When restoring, the user creates a CudnnOpaqueParamsSaveable object and uses Saver.restore() to restore the parameter buffer from the canonical format to a user-defined format, as well as to restore other savable objects in the checkpoint file. """ def _check_rnn_mode(rnn_mode): if rnn_mode not in (CUDNN_LSTM, CUDNN_GRU, CUDNN_RNN_TANH, CUDNN_RNN_RELU): raise ValueError( "Invalid rnn_mode: %s, expect one of (%s, %s, %s, %s)" % (rnn_mode, CUDNN_LSTM, CUDNN_GRU, CUDNN_RNN_TANH, CUDNN_RNN_RELU)) def _get_seed(seed): seed, seed2 = random_seed.get_seed(seed) if seed is None and seed2 is None: seed, seed2 = 0, 0 return seed, seed2 def check_direction(direction): """Check validity of direction.""" if direction not in (CUDNN_RNN_UNIDIRECTION, CUDNN_RNN_BIDIRECTION): raise ValueError("Invalid direction: %s, expecting %s or %s" % (direction, CUDNN_RNN_UNIDIRECTION, CUDNN_RNN_BIDIRECTION)) def check_input_mode(input_mode): if input_mode not in (CUDNN_INPUT_LINEAR_MODE, CUDNN_INPUT_SKIP_MODE, CUDNN_INPUT_AUTO_MODE): raise ValueError("Invalid input_mode: %s, expect one of (%s, %s, %s)" % (input_mode, CUDNN_INPUT_LINEAR_MODE, CUDNN_INPUT_SKIP_MODE, CUDNN_INPUT_AUTO_MODE)) def _get_num_params(rnn_mode, num_layers, direction): """Return num params for given Cudnn config.""" if rnn_mode == CUDNN_LSTM: num_params_per_layer = CUDNN_LSTM_PARAMS_PER_LAYER elif rnn_mode == CUDNN_GRU: num_params_per_layer = CUDNN_GRU_PARAMS_PER_LAYER elif rnn_mode == CUDNN_RNN_RELU: num_params_per_layer = CUDNN_RNN_RELU_PARAMS_PER_LAYER elif rnn_mode == CUDNN_RNN_TANH: num_params_per_layer = CUDNN_RNN_TANH_PARAMS_PER_LAYER else: raise ValueError("Invalid \'rnn_mode\': %s" % rnn_mode) num_params = num_layers * num_params_per_layer if direction != CUDNN_RNN_UNIDIRECTION: num_params *= 2 return num_params def _cudnn_rnn(inputs, input_h, input_c, params, is_training, rnn_mode, sequence_lengths=None, time_major=True, input_mode=CUDNN_INPUT_LINEAR_MODE, direction=CUDNN_RNN_UNIDIRECTION, dropout=0., seed=0, num_proj=None, name=None): """Cudnn RNN. Args: inputs: the input sequence to the RNN model. If `time_major` is True (default), the Tensor shape is [max_time, batch_size, input_size]. If `time_major` is False, the shape is [batch_size, max_time, input_size]. input_h: the initial hidden state for h. If `time_major` is True (default), the Tensor shape is [num_layers, batch_size, num_units]. If `time_major` is False, the shape is [batch_size, num_layers, num_units]. input_c: the initial hidden state for c. This is only relevant for LSTM. A Tensor of the same shape as input_h. params: the parameter buffer created for this model. is_training: whether this operation will be used in training or inference rnn_mode: one of ('lstm', 'gru', 'rnn_relu', 'rnn_tanh'). sequence_lengths: an int32 array representing the variable sequence lengths in a batch. The size of the array has to equal the batch_size. Default to None, in which case sequences in the batch are assumed to have the same length, which is inferred from inputs. time_major: The shape format of the `inputs` and `outputs` Tensors. If true, these Tensors must be shaped ['max_time', 'batch_size', 'depth']. If false, these Tensors must be shaped ['batch_size', 'max_time', 'depth']. By default this function accepts input and emits output in time-major form. This param is only effective when 'sequence_lengths' is used. input_mode: indicate whether there is a linear projection between the input and the actual computation before the first layer. It could be 'linear_input', 'skip_input' or 'auto_select'. 'linear_input' (default) always applies a linear projection of input onto RNN hidden state. (standard RNN behavior). 'skip_input' is only allowed when input_size == num_units; 'auto_select' implies 'skip_input' when input_size == num_units; otherwise, it implies 'linear_input'. direction: the direction model that the model operates. Could be either 'unidirectional' or 'bidirectional' dropout: whether to enable dropout. With it is 0, dropout is disabled. seed: the op seed used for initializing dropout. See `tf.compat.v1.set_random_seed` for behavior. num_proj: The output dimensionality for the projection matrices. If None or 0, no projection is performed. name: name of the operation. Returns: outputs, output_h, output_c """ _check_rnn_mode(rnn_mode) check_direction(direction) check_input_mode(input_mode) seed, seed2 = random_seed.get_seed(seed) # TODO(jamesqin): switch default value to "1" on May 25th 2018, and get rid # of V1 ops. use_cudnn_v2 = os.environ.get("TF_CUDNN_RNN_USE_V2", "0") args = { "input": inputs, "input_h": input_h, "input_c": input_c, "params": params, "is_training": is_training, "rnn_mode": rnn_mode, "input_mode": input_mode, "direction": direction, "dropout": dropout, "seed": seed, "seed2": seed2, "name": name } if sequence_lengths is not None: args["sequence_lengths"] = sequence_lengths args["time_major"] = time_major args["num_proj"] = 0 if num_proj is None else num_proj outputs, output_h, output_c, _, _ = gen_cudnn_rnn_ops.cudnn_rnnv3(**args) elif time_major is False or num_proj: batch_id, time_id = (1, 0) if time_major else (0, 1) batch_size = array_ops.shape(inputs)[batch_id] max_time = array_ops.shape(inputs)[time_id] sequence_lengths = array_ops.fill([batch_size], max_time) args["sequence_lengths"] = sequence_lengths args["time_major"] = time_major args["num_proj"] = 0 if num_proj is None else num_proj outputs, output_h, output_c, _, _ = gen_cudnn_rnn_ops.cudnn_rnnv3(**args) elif use_cudnn_v2 != "1": outputs, output_h, output_c, _ = gen_cudnn_rnn_ops.cudnn_rnn(**args) else: outputs, output_h, output_c, _, _ = gen_cudnn_rnn_ops.cudnn_rnnv2(**args) return (outputs, output_h, output_c) def cudnn_lstm(inputs, input_h, input_c, params, is_training, sequence_lengths=None, time_major=True, input_mode=CUDNN_INPUT_LINEAR_MODE, direction=CUDNN_RNN_UNIDIRECTION, dropout=0., seed=0, num_proj=None, name=None): """Cudnn LSTM. Args: inputs: the input sequence to the RNN model. If `time_major` is True (default), the Tensor shape is [max_time, batch_size, input_size]. If `time_major` is False, the shape is [batch_size, max_time, input_size]. input_h: the initial hidden state for h. If `time_major` is True (default), the Tensor shape is [num_layers, batch_size, num_units]. If `time_major` is False, the shape is [batch_size, num_layers, num_units]. input_c: the initial hidden state for c. This is only relevant for LSTM. A Tensor of the same shape as input_h. params: the parameter buffer created for this model. is_training: whether this operation will be used in training or inference sequence_lengths: an int32 array representing the variable sequence lengths in a batch. The size of the array has to equal the batch_size. Default to None, in which case sequences in the batch are assumed to have the same length, which is inferred from inputs. time_major: The shape format of the `inputs` and `outputs` Tensors. If true, these Tensors must be shaped ['max_time', 'batch_size', 'depth']. If false, these Tensors must be shaped ['batch_size', 'max_time', 'depth']. By default this function accepts input and emits output in time-major form. This param is only effective when 'sequence_lengths' is used. input_mode: indicate whether there is a linear projection between the input and the actual computation before the first layer. It could be 'linear_input', 'skip_input' or 'auto_select'. 'linear_input' (default) always applies a linear projection of input onto RNN hidden state. (standard RNN behavior). 'skip_input' is only allowed when input_size == num_units; 'auto_select' implies 'skip_input' when input_size == num_units; otherwise, it implies 'linear_input'. direction: the direction model that the model operates. Could be either 'unidirectional' or 'bidirectional' dropout: whether to enable dropout. With it is 0, dropout is disabled. seed: the op seed used for initializing dropout. See `tf.compat.v1.set_random_seed` for behavior. num_proj: The output dimensionality for the projection matrices. If None or 0, no projection is performed. name: name of the operation. Returns: outputs, output_h, output_c """ return _cudnn_rnn(inputs, input_h, input_c, params, is_training, CUDNN_LSTM, sequence_lengths, time_major, input_mode, direction, dropout, seed, num_proj, name) def _cudnn_rnn_no_input_c(inputs, input_h, params, is_training, rnn_mode, sequence_lengths=None, time_major=True, input_mode=CUDNN_INPUT_LINEAR_MODE, direction=CUDNN_RNN_UNIDIRECTION, dropout=0., seed=0, name=None): """Cudnn RNN w/o input_c. Args: inputs: the input sequence to the RNN model. If `time_major` is True (default), the Tensor shape is [max_time, batch_size, input_size]. If `time_major` is False, the shape is [batch_size, max_time, input_size]. input_h: the initial hidden state for h. If `time_major` is True (default), the Tensor shape is [num_layers, batch_size, num_units]. If `time_major` is False, the shape is [batch_size, num_layers, num_units]. params: the parameter buffer created for this model. is_training: whether this operation will be used in training or inference rnn_mode: one of ('lstm', 'gru', 'rnn_relu', 'rnn_tanh'). sequence_lengths: an int32 array representing the variable sequence lengths in a batch. The size of the array has to equal the batch_size. Default to None, in which case sequences in the batch are assumed to have the same length, which is inferred from inputs. time_major: The shape format of the `inputs` and `outputs` Tensors. If true, these Tensors must be shaped ['max_time', 'batch_size', 'depth']. If false, these Tensors must be shaped ['batch_size', 'max_time', 'depth']. By default this function accepts input and emits output in time-major form. This param is only effective when 'sequence_lengths' is used. input_mode: indicate whether there is a linear projection between the input and the actual computation before the first layer. It could be 'linear_input', 'skip_input' or 'auto_select'. 'linear_input' (default) always applies a linear projection of input onto RNN hidden state. (standard RNN behavior). 'skip_input' is only allowed when input_size == num_units; 'auto_select' implies 'skip_input' when input_size == num_units; otherwise, it implies 'linear_input'. direction: the direction model that the model operates. Could be either 'unidirectional' or 'bidirectional' dropout: whether to enable dropout. With it is 0, dropout is disabled. seed: the op seed used for initializing dropout. See `tf.compat.v1.set_random_seed` for behavior. name: name of the operation. Returns: outputs, output_h """ input_c = array_ops.constant([], dtype=input_h.dtype) outputs, output_h, _ = _cudnn_rnn(inputs, input_h, input_c, params, is_training, rnn_mode, sequence_lengths, time_major, input_mode, direction, dropout, seed, None, name) return outputs, output_h def cudnn_gru(inputs, input_h, params, is_training, sequence_lengths=None, time_major=True, input_mode=CUDNN_INPUT_LINEAR_MODE, direction=CUDNN_RNN_UNIDIRECTION, dropout=0., seed=0, name=None): """Cudnn GRU. Args: inputs: the input sequence to the RNN model. If `time_major` is True (default), the Tensor shape is [max_time, batch_size, input_size]. If `time_major` is False, the shape is [batch_size, max_time, input_size]. input_h: the initial hidden state for h. If `time_major` is True (default), the Tensor shape is [num_layers, batch_size, num_units]. If `time_major` is False, the shape is [batch_size, num_layers, num_units]. params: the parameter buffer created for this model. is_training: whether this operation will be used in training or inference input_mode: indicate whether there is a linear projection between the input and the actual computation before the first layer. It could be 'linear_input', 'skip_input' or 'auto_select'. 'linear_input' (default) always applies a linear projection of input onto RNN hidden state. (standard RNN behavior). 'skip_input' is only allowed when input_size == num_units; 'auto_select' implies 'skip_input' when input_size == num_units; otherwise, it implies 'linear_input'. sequence_lengths: an int32 array representing the variable sequence lengths in a batch. The size of the array has to equal the batch_size. Default to None, in which case sequences in the batch are assumed to have the same length, which is inferred from inputs. time_major: The shape format of the `inputs` and `outputs` Tensors. If true, these Tensors must be shaped ['max_time', 'batch_size', 'depth']. If false, these Tensors must be shaped ['batch_size', 'max_time', 'depth']. By default this function accepts input and emits output in time-major form. This param is only effective when 'sequence_lengths' is used. direction: the direction model that the model operates. Could be either 'unidirectional' or 'bidirectional' dropout: whether to enable dropout. With it is 0, dropout is disabled. seed: the op seed used for initializing dropout. See `tf.compat.v1.set_random_seed` for behavior. name: name of the operation. Returns: outputs, output_h """ return _cudnn_rnn_no_input_c(inputs, input_h, params, is_training, CUDNN_GRU, sequence_lengths, time_major, input_mode, direction, dropout, seed, name) def cudnn_rnn_relu(inputs, input_h, params, is_training, input_mode=CUDNN_INPUT_LINEAR_MODE, direction=CUDNN_RNN_UNIDIRECTION, dropout=0., seed=0, sequence_lengths=None, time_major=True, name=None): """Cudnn RNN Relu. Args: inputs: the input sequence to the RNN model. If `time_major` is True (default), the Tensor shape is [max_time, batch_size, input_size]. If `time_major` is False, the shape is [batch_size, max_time, input_size]. input_h: the initial hidden state for h. If `time_major` is True (default), the Tensor shape is [num_layers, batch_size, num_units]. If `time_major` is False, the shape is [batch_size, num_layers, num_units]. params: the parameter buffer created for this model. is_training: whether this operation will be used in training or inference input_mode: indicate whether there is a linear projection between the input and the actual computation before the first layer. It could be 'linear_input', 'skip_input' or 'auto_select'. 'linear_input' (default) always applies a linear projection of input onto RNN hidden state. (standard RNN behavior). 'skip_input' is only allowed when input_size == num_units; 'auto_select' implies 'skip_input' when input_size == num_units; otherwise, it implies 'linear_input'. direction: the direction model that the model operates. Could be either 'unidirectional' or 'bidirectional' dropout: whether to enable dropout. With it is 0, dropout is disabled. seed: the op seed used for initializing dropout. See `tf.compat.v1.set_random_seed` for behavior. sequence_lengths: an int32 array representing the variable sequence lengths in a batch. The size of the array has to equal the batch_size. If not provided, the same sequence length will be assumed. time_major: The shape format of the `inputs` and `outputs` Tensors. If true, these Tensors must be shaped ['max_time', 'batch_size', 'depth']. If false, these Tensors must be shaped ['batch_size', 'max_time', 'depth']. By default this function accepts input and emits output in time-major form. This param is only effective when 'sequence_lengths' is used. name: name of the operation. Returns: outputs, output_h """ return _cudnn_rnn_no_input_c(inputs, input_h, params, is_training, CUDNN_RNN_RELU, sequence_lengths, time_major, input_mode, direction, dropout, seed, name) def cudnn_rnn_tanh(inputs, input_h, params, is_training, sequence_lengths=None, time_major=True, input_mode=CUDNN_INPUT_LINEAR_MODE, direction=CUDNN_RNN_UNIDIRECTION, dropout=0., seed=0, name=None): """Cudnn RNN Tanh. Args: inputs: the input sequence to the RNN model. If `time_major` is True (default), the Tensor shape is [max_time, batch_size, input_size]. If `time_major` is False, the shape is [batch_size, max_time, input_size]. input_h: the initial hidden state for h. If `time_major` is True (default), the Tensor shape is [num_layers, batch_size, num_units]. If `time_major` is False, the shape is [batch_size, num_layers, num_units]. params: the parameter buffer created for this model. is_training: whether this operation will be used in training or inference input_mode: indicate whether there is a linear projection between the input and the actual computation before the first layer. It could be 'linear_input', 'skip_input' or 'auto_select'. 'linear_input' (default) always applies a linear projection of input onto RNN hidden state. (standard RNN behavior). 'skip_input' is only allowed when input_size == num_units; 'auto_select' implies 'skip_input' when input_size == num_units; otherwise, it implies 'linear_input'. sequence_lengths: an int32 array representing the variable sequence lengths in a batch. The size of the array has to equal the batch_size. Default to None, in which case sequences in the batch are assumed to have the same length, which is inferred from inputs. time_major: The shape format of the `inputs` and `outputs` Tensors. If true, these Tensors must be shaped ['max_time', 'batch_size', 'depth']. If false, these Tensors must be shaped ['batch_size', 'max_time', 'depth']. By default this function accepts input and emits output in time-major form. This param is only effective when 'sequence_lengths' is used. direction: the direction model that the model operates. Could be either 'unidirectional' or 'bidirectional' dropout: whether to enable dropout. With it is 0, dropout is disabled. seed: the op seed used for initializing dropout. See `tf.compat.v1.set_random_seed` for behavior. name: name of the operation. Returns: outputs, output_h """ return _cudnn_rnn_no_input_c(inputs, input_h, params, is_training, CUDNN_RNN_TANH, sequence_lengths, time_major, input_mode, direction, dropout, seed, name) def cudnn_rnn_opaque_params_to_canonical(rnn_mode, num_layers, num_units, input_size, params, input_mode=CUDNN_INPUT_LINEAR_MODE, direction=CUDNN_RNN_UNIDIRECTION, dropout=0, seed=0, num_proj=None, name=None): """Convert cudnn opaque params to canonical. Args: rnn_mode: a string specifies the mode, under which this RNN model runs. Could be either 'lstm', 'gru', 'rnn_tanh' or 'rnn_relu'. num_layers: the number of layers for the RNN model. num_units: the number of units within the RNN model. input_size: the size of the input, it could be different from the num_units. params: opaque cudnn params var. input_mode: indicate whether there is a linear projection between the input and the actual computation before the first layer. It could be 'linear_input', 'skip_input' or 'auto_select'. 'linear_input' (default) always applies a linear projection of input onto RNN hidden state. (standard RNN behavior). 'skip_input' is only allowed when input_size == num_units; 'auto_select' implies 'skip_input' when input_size == num_units; otherwise, it implies 'linear_input'. direction: the direction model that the model operates. Could be either 'unidirectional' or 'bidirectional' dropout: whether to enable dropout. With it is 0, dropout is disabled. seed: the op seed used for initializing dropout. See `tf.compat.v1.set_random_seed` for behavior. num_proj: The output dimensionality for the projection matrices. If None or 0, no projection is performed. name: name of the operation. Returns: weights list and bias list Raises: ValueError: if rnn_mode or direction is invalid. """ _check_rnn_mode(rnn_mode) check_direction(direction) check_input_mode(input_mode) num_params = _get_num_params(rnn_mode, num_layers, direction) seed, seed2 = random_seed.get_seed(seed) num_dirs = 1 if direction == CUDNN_RNN_UNIDIRECTION else 2 if num_proj is not None and num_proj != 0: num_params_weights = (num_params + 1 * num_layers * num_dirs) num_params_biases = num_params weights, biases = gen_cudnn_rnn_ops.cudnn_rnn_params_to_canonical_v2( rnn_mode=rnn_mode, num_layers=num_layers, num_units=num_units, input_size=input_size, params=params, input_mode=input_mode, direction=direction, dropout=dropout, seed=seed, seed2=seed2, num_params_weights=num_params_weights, num_params_biases=num_params_biases, num_proj=num_proj, name=name) else: weights, biases = gen_cudnn_rnn_ops.cudnn_rnn_params_to_canonical( rnn_mode=rnn_mode, num_layers=num_layers, num_units=num_units, input_size=input_size, params=params, input_mode=input_mode, direction=direction, dropout=dropout, seed=seed, seed2=seed2, num_params=num_params, name=name) return weights, biases def cudnn_rnn_canonical_to_opaque_params(rnn_mode, num_layers, num_units, input_size, weights, biases, input_mode=CUDNN_INPUT_LINEAR_MODE, direction=CUDNN_RNN_UNIDIRECTION, dropout=0, seed=0, num_proj=None, name=None): """Converts params from the canonical format to a specific format of cuDNN. Args: rnn_mode: a string specifies the mode, under which this RNN model runs. Could be either 'lstm', 'gru', 'rnn_tanh' or 'rnn_relu'. num_layers: the number of layers for the RNN model. num_units: the number of units within the RNN model. input_size: the size of the input, it could be different from the num_units. weights: a Tensor for weight parameters. biases: a Tensor for bias parameters. input_mode: indicate whether there is a linear projection between the input and the actual computation before the first layer. It could be 'linear_input', 'skip_input' or 'auto_select'. 'linear_input' (default) always applies a linear projection of input onto RNN hidden state. (standard RNN behavior). 'skip_input' is only allowed when input_size == num_units; 'auto_select' implies 'skip_input' when input_size == num_units; otherwise, it implies 'linear_input'. direction: the direction model that the model operates. Could be either 'unidirectional' or 'bidirectional' dropout: whether to enable dropout. With it is 0, dropout is disabled. seed: the op seed used for initializing dropout. See `tf.compat.v1.set_random_seed` for behavior. num_proj: The output dimensionality for the projection matrices. If None or 0, no projection is performed. name: name of the operation. Returns: an opaque Cudnn param. Raises: ValueError: if rnn_mode or direction is invalid. """ _check_rnn_mode(rnn_mode) check_direction(direction) check_input_mode(input_mode) seed, seed2 = random_seed.get_seed(seed) if num_proj is not None and num_proj != 0: return gen_cudnn_rnn_ops.cudnn_rnn_canonical_to_params_v2( rnn_mode=rnn_mode, num_layers=num_layers, num_units=num_units, input_size=input_size, weights=weights, biases=biases, input_mode=input_mode, direction=direction, dropout=dropout, seed=seed, seed2=seed2, num_proj=num_proj, name=name) else: return gen_cudnn_rnn_ops.cudnn_rnn_canonical_to_params( rnn_mode=rnn_mode, num_layers=num_layers, num_units=num_units, input_size=input_size, weights=weights, biases=biases, input_mode=input_mode, direction=direction, dropout=dropout, seed=seed, seed2=seed2, name=name) def cudnn_rnn_opaque_params_size(rnn_mode, num_layers, num_units, input_size, input_mode=CUDNN_INPUT_LINEAR_MODE, direction=CUDNN_RNN_UNIDIRECTION, dtype=dtypes.float32, dropout=0, seed=0, num_proj=None, name=None): """Returns opaque params size for specific Cudnn config. Args: rnn_mode: a string specifies the mode, under which this RNN model runs. Could be either 'lstm', 'gru', 'rnn_tanh' or 'rnn_relu'. num_layers: the number of layers for the RNN model. num_units: the number of units within the RNN model. input_size: the size of the input, it could be different from the num_units. input_mode: indicate whether there is a linear projection between the input and the actual computation before the first layer. It could be 'linear_input', 'skip_input' or 'auto_select'. 'linear_input' (default) always applies a linear projection of input onto RNN hidden state. (standard RNN behavior). 'skip_input' is only allowed when input_size == num_units; 'auto_select' implies 'skip_input' when input_size == num_units; otherwise, it implies 'linear_input'. direction: the direction model that the model operates. Could be either 'unidirectional' or 'bidirectional' dtype: one of tf.float32 or tf.float64. dropout: whether to enable dropout. With it is 0, dropout is disabled. seed: the op seed used for initializing dropout. See `tf.compat.v1.set_random_seed` for behavior. num_proj: The output dimensionality for the projection matrices. If None or 0, no projection is performed. name: name of the operation. Returns: a int, size of Cudnn opaque params. Raises: ValueError: if rnn_mode or direction is invalid. """ _check_rnn_mode(rnn_mode) check_direction(direction) check_input_mode(input_mode) seed, seed2 = random_seed.get_seed(seed) return gen_cudnn_rnn_ops.cudnn_rnn_params_size( rnn_mode=rnn_mode, num_layers=num_layers, num_units=num_units, input_size=input_size, num_proj=num_proj, T=dtype, S=dtypes.int32, dropout=dropout, seed=seed, seed2=seed2, input_mode=input_mode, direction=direction, name=name)[0] class _CudnnRNN(object): """Creates an RNN model using the underlying Cudnn implementation. Note that self._NUM_PARAMS_PER_LAYER is the number of parameter sets of weight and bias per layer. It needs to be defined in subclasses. """ __doc__ += _cudnn_rnn_common_doc_string # TODO(jamesqin): support float16 CuDNN RNN def __init__(self, rnn_mode, num_layers, num_units, input_size, input_mode=CUDNN_INPUT_LINEAR_MODE, direction=CUDNN_RNN_UNIDIRECTION, dtype=dtypes.float32, dropout=0., seed=0, num_proj=None): """Creates a CudnnRNN model from model spec. Args: rnn_mode: a string specifies the mode, under which this RNN model runs. Could be either 'lstm', 'gru', 'rnn_tanh' or 'rnn_relu'. num_layers: the number of layers for the RNN model. num_units: the number of units within the RNN model. input_size: the size of the input, it could be different from the num_units. input_mode: indicate whether there is a linear projection between the input and the actual computation before the first layer. It could be 'linear_input', 'skip_input' or 'auto_select'. 'linear_input' (default) always applies a linear projection of input onto RNN hidden state. (standard RNN behavior). 'skip_input' is only allowed when input_size == num_units; 'auto_select' implies 'skip_input' when input_size == num_units; otherwise, it implies 'linear_input'. direction: the direction model that the model operates. Could be either 'unidirectional' or 'bidirectional' dtype: dtype of params, tf.float32 or tf.float64. dropout: whether to enable dropout. With it is 0, dropout is disabled. seed: the op seed used for initializing dropout. See `tf.compat.v1.set_random_seed` for behavior. num_proj: The output dimensionality for the projection matrices. If None or 0, no projection is performed. Raises: ValueError: if direction is invalid. """ self._num_layers = num_layers self._num_units = num_units self._input_size = input_size self._rnn_mode = rnn_mode self._input_mode = input_mode self._direction = direction self._dtype = dtype self._dropout = dropout self._seed = seed self._num_proj = num_proj @property def input_mode(self): return self._input_mode @property def input_size(self): return self._input_size @property def num_units(self): return self._num_units @property def num_layers(self): return self._num_layers @property def rnn_mode(self): return self._rnn_mode @property def direction(self): return self._direction @property def num_proj(self): return self._num_proj def params_size(self): """Calculates the size of the opaque parameter buffer needed for this model. Returns: The calculated parameter buffer size. """ return cudnn_rnn_opaque_params_size( rnn_mode=self._rnn_mode, num_layers=self._num_layers, num_units=self._num_units, input_size=self._input_size, num_proj=self._num_proj, dtype=self._dtype, dropout=self._dropout, seed=self._seed, input_mode=self._input_mode, direction=self._direction) def __call__(self, input_data, input_h, input_c, params, is_training=True, sequence_lengths=None, time_major=True): """Runs the forward step for the RNN model. Args: input_data: the input sequence to the RNN model. If `time_major` is True (default), the Tensor shape is [max_time, batch_size, input_size]. If `time_major` is False, the shape is [batch_size, max_time, input_size]. input_h: the initial hidden state for h. If `time_major` is True (default), the Tensor shape is [num_layers, batch_size, num_units]. If `time_major` is False, the shape is [batch_size, num_layers, num_units]. input_c: the initial hidden state for c. This is only relevant for LSTM. A Tensor of the same shape as input_h. params: the parameter buffer created for this model. is_training: whether this operation will be used in training or inference. sequence_lengths: an int32 array representing the variable sequence lengths in a batch. The size of the array has to equal the batch_size. Default to None, in which case sequences in the batch are assumed to have the same length, which is inferred from inputs. time_major: The shape format of the `inputs` and `outputs` Tensors. If true, these Tensors must be shaped ['max_time', 'batch_size', 'depth']. If false, these Tensors must be shaped ['batch_size', 'max_time', 'depth']. By default this function accepts input and emits output in time-major form. This param is only effective when 'sequence_lengths' is used. Returns: output: the output sequence. output_h: the final state for h. output_c: the final state for c. This is only relevant for LSTM. """ return _cudnn_rnn( input_data, input_h, input_c, params, is_training, self._rnn_mode, sequence_lengths=sequence_lengths, time_major=time_major, input_mode=self._input_mode, direction=self._direction, dropout=self._dropout, seed=self._seed, num_proj=self._num_proj) def params_to_canonical(self, params): """Converts params from a specific format of cuDNN to the canonical format. Args: params: a Variable for weight and bias parameters. Returns: A function for the specific-to-canonical conversion. """ return cudnn_rnn_opaque_params_to_canonical( rnn_mode=self._rnn_mode, num_layers=self._num_layers, num_units=self._num_units, input_size=self._input_size, params=params, input_mode=self._input_mode, direction=self._direction, dropout=self._dropout, seed=self._seed, num_proj=self._num_proj) def canonical_to_params(self, weights, biases): """Converts params from the canonical format to a specific format of cuDNN. Args: weights: a Tensor for weight parameters. biases: a Tensor for bias parameters. Returns: A function for the canonical-to-params-to-specific conversion.. """ return cudnn_rnn_canonical_to_opaque_params( rnn_mode=self._rnn_mode, num_layers=self._num_layers, num_units=self._num_units, input_size=self._input_size, weights=weights, biases=biases, input_mode=self._input_mode, direction=self._direction, dropout=self._dropout, seed=self._seed, num_proj=self._num_proj) class CudnnLSTM(_CudnnRNN): """Cudnn implementation of the LSTM model.""" __doc__ += _cudnn_rnn_common_doc_string # 4 sets of weight and bias parameters for the recurrent input, and 4 for the # previous layer input. _NUM_PARAMS_PER_LAYER = CUDNN_LSTM_PARAMS_PER_LAYER def __init__(self, num_layers, num_units, input_size, input_mode=CUDNN_INPUT_LINEAR_MODE, direction=CUDNN_RNN_UNIDIRECTION, dtype=dtypes.float32, dropout=0., seed=0, num_proj=None): """Creates a Cudnn LSTM model from model spec. Args: num_layers: the number of layers for the RNN model. num_units: the number of units within the RNN model. input_size: the size of the input, it could be different from the num_units. input_mode: indicate whether there is a linear projection between the input and The actual computation before the first layer. It could be 'skip_input', 'linear_input' or 'auto_select'. 'skip_input' is only allowed when input_size == num_units; 'auto_select' implies 'skip_input' when input_size == num_units; otherwise, it implies 'linear_input'. direction: the direction model that the model operates. Could be either 'unidirectional' or 'bidirectional' dtype: dtype of params, tf.float32 or tf.float64. dropout: whether to enable dropout. With it is 0, dropout is disabled. seed: the seed used for initializing dropout. num_proj: The output dimensionality for the projection matrices. If None or 0, no projection is performed. """ super(CudnnLSTM, self).__init__( CUDNN_LSTM, num_layers, num_units, input_size, input_mode=input_mode, direction=direction, dtype=dtype, dropout=dropout, seed=seed, num_proj=num_proj) def __call__(self, input_data, input_h, input_c, params, sequence_lengths=None, time_major=True, is_training=True): """Runs the forward step for the Cudnn LSTM model. Args: input_data: the input sequence to the RNN model. If `time_major` is True (default), the Tensor shape is [max_time, batch_size, input_size]. If `time_major` is False, the shape is [batch_size, max_time, input_size]. input_h: the initial hidden state for h. If `time_major` is True (default), the Tensor shape is [num_layers, batch_size, num_units]. If `time_major` is False, the shape is [batch_size, num_layers, num_units]. input_c: the initial hidden state for c. A Tensor of the same shape as input_h. params: the parameter buffer created for this model. sequence_lengths: an int32 array representing the variable sequence lengths in a batch. The size of the array has to equal the batch_size. Default to None, in which case sequences in the batch are assumed to have the same length, which is inferred from inputs. time_major: The shape format of the `inputs` and `outputs` Tensors. If true, these Tensors must be shaped ['max_time', 'batch_size', 'depth']. If false, these Tensors must be shaped ['batch_size', 'max_time', 'depth']. By default this function accepts input and emits output in time-major form. This param is only effective when 'sequence_lengths' is used. is_training: whether this operation will be used in training or inference. Returns: output: the output sequence. output_h: the final state for h. output_c: the final state for c. """ output, output_h, output_c = super(CudnnLSTM, self).__call__( input_data, input_h, input_c, params, sequence_lengths=sequence_lengths, time_major=time_major, is_training=is_training) return (output, output_h, output_c) class _CudnnRNNNoInputC(_CudnnRNN): """Simple CudnnRNN models without input_c.""" __doc__ += _cudnn_rnn_common_doc_string def __init__(self, num_layers, num_units, input_size, input_mode=CUDNN_INPUT_LINEAR_MODE, direction=CUDNN_RNN_UNIDIRECTION, dtype=dtypes.float32, dropout=0., seed=0): """Creates a Cudnn RNN model from model without hidden-state C. Args: num_layers: the number of layers for the RNN model. num_units: the number of units within the RNN model. input_size: the size of the input, it could be different from the num_units. input_mode: indicate whether there is a linear projection between the input and The actual computation before the first layer. It could be 'skip_input', 'linear_input' or 'auto_select'. 'skip_input' is only allowed when input_size == num_units; 'auto_select' implies 'skip_input' when input_size == num_units; otherwise, it implies 'linear_input'. direction: the direction model that the model operates. Could be either 'unidirectional' or 'bidirectional' dtype: dtype of params, tf.float32 or tf.float64. dropout: whether to enable dropout. With it is 0, dropout is disabled. seed: the seed used for initializing dropout. Raises: ValueError: if direction is not 'unidirectional' or 'bidirectional'. """ if direction not in (CUDNN_RNN_UNIDIRECTION, CUDNN_RNN_BIDIRECTION): raise ValueError("Invalid direction: %s" % direction) super(_CudnnRNNNoInputC, self).__init__( self._rnn_mode, num_layers, num_units, input_size, input_mode=input_mode, direction=direction, dtype=dtype, dropout=dropout, seed=seed) def __call__(self, input_data, input_h, params, sequence_lengths=None, time_major=True, is_training=True): """Runs the forward step for the Cudnn LSTM model. Args: input_data: the input sequence to the RNN model. If `time_major` is True (default), the Tensor shape is [max_time, batch_size, input_size]. If `time_major` is False, the shape is [batch_size, max_time, input_size]. input_h: the initial hidden state for h. If `time_major` is True (default), the Tensor shape is [num_layers, batch_size, num_units]. If `time_major` is False, the shape is [batch_size, num_layers, num_units]. params: the parameter buffer created for this model. sequence_lengths: an int32 array representing the variable sequence lengths in a batch. The size of the array has to equal the batch_size. Default to None, in which case sequences in the batch are assumed to have the same length, which is inferred from inputs. time_major: The shape format of the `inputs` and `outputs` Tensors. If true, these Tensors must be shaped ['max_time', 'batch_size', 'depth']. If false, these Tensors must be shaped ['batch_size', 'max_time', 'depth']. By default this function accepts input and emits output in time-major form. This param is only effective when 'sequence_lengths' is used. is_training: whether this operation will be used in training or inference. Returns: output: the output sequence. output_h: the final state for h. """ return _cudnn_rnn_no_input_c( input_data, input_h, params, is_training, self._rnn_mode, sequence_lengths=sequence_lengths, time_major=time_major, input_mode=self._input_mode, direction=self._direction, dropout=self._dropout, seed=self._seed) class CudnnGRU(_CudnnRNNNoInputC): """Cudnn implementation of the GRU model.""" __doc__ += _cudnn_rnn_common_doc_string _rnn_mode = CUDNN_GRU # 3 sets of weight and bias parameters for the recurrent input, and 3 for the # previous layer input. _NUM_PARAMS_PER_LAYER = CUDNN_GRU_PARAMS_PER_LAYER class CudnnRNNTanh(_CudnnRNNNoInputC): """Cudnn implementation of the RNN-tanh model.""" __doc__ += _cudnn_rnn_common_doc_string _rnn_mode = CUDNN_RNN_TANH # 1 set of weight and bias parameters for the recurrent input, and 1 for the # previous layer input. _NUM_PARAMS_PER_LAYER = CUDNN_RNN_TANH_PARAMS_PER_LAYER class CudnnRNNRelu(_CudnnRNNNoInputC): """Cudnn implementation of the RNN-relu model.""" __doc__ += _cudnn_rnn_common_doc_string _rnn_mode = CUDNN_RNN_RELU # 1 set of weight and bias parameters for the recurrent input, and 1 for the # previous layer input. _NUM_PARAMS_PER_LAYER = CUDNN_RNN_RELU_PARAMS_PER_LAYER
tensorflow-master
tensorflow/contrib/cudnn_rnn/python/ops/cudnn_rnn_ops.py
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Logging tensorflow::tfprof::OpLogProto. OpLogProto is used to add extra model information for offline analysis. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.profiler.tfprof_logger import write_op_log as _write_op_log from tensorflow.python.util.deprecation import deprecated @deprecated("2018-01-01", "Use `tf.profiler.write_op_log. go/tfprof`") def write_op_log(graph, log_dir, op_log=None, run_meta=None, add_trace=True): _write_op_log(graph, log_dir, op_log, run_meta, add_trace)
tensorflow-master
tensorflow/contrib/tfprof/tfprof_logger.py
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """tfprof is a tool that profile various aspect of TensorFlow model. @@model_analyzer @@tfprof_logger @@ProfileContext """ from __future__ import absolute_import from __future__ import division from __future__ import print_function # pylint: disable=unused-import from tensorflow.contrib.tfprof import model_analyzer from tensorflow.contrib.tfprof import tfprof_logger from tensorflow.contrib.tfprof.model_analyzer import ProfileContext from tensorflow.python.util.all_util import remove_undocumented _allowed_symbols = ['model_analyzer', 'tfprof_logger', 'ProfileContext'] remove_undocumented(__name__, _allowed_symbols)
tensorflow-master
tensorflow/contrib/tfprof/__init__.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Model Analyzer. Analyze model, including shape, params, time, memory, structure, etc. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function # Import the names here for existing users. # pylint: disable=unused-import from tensorflow.python.profiler import tfprof_logger from tensorflow.python.profiler.model_analyzer import advise as _advise from tensorflow.python.profiler.model_analyzer import ALL_ADVICE from tensorflow.python.profiler.model_analyzer import profile as _profile from tensorflow.python.profiler.model_analyzer import Profiler from tensorflow.python.profiler.profile_context import ProfileContext from tensorflow.python.util.deprecation import deprecated _DEFAULT_PROFILE_OPTIONS = 0 _DEFAULT_ADVISE_OPTIONS = 0 # pylint: disable=bad-whitespace # pylint: disable=bad-continuation # options examples for profiling API. # # Show the parameter statistics of trainable variables. TRAINABLE_VARS_PARAMS_STAT_OPTIONS = { 'max_depth': 10000, 'min_bytes': 0, 'min_micros': 0, 'min_params': 0, 'min_float_ops': 0, 'order_by': 'name', 'account_type_regexes': [tfprof_logger.TRAINABLE_VARIABLES], 'start_name_regexes': ['.*'], 'trim_name_regexes': [], 'show_name_regexes': ['.*'], 'hide_name_regexes': [], 'account_displayed_op_only': True, 'select': ['params'], 'output': 'stdout', 'dump_to_file': '' # Deprecated, use 'output': 'file:outfile=<name>' } # Show the number float operations. FLOAT_OPS_OPTIONS = { 'max_depth': 10000, 'min_bytes': 0, 'min_micros': 0, 'min_params': 0, 'min_float_ops': 1, 'order_by': 'float_ops', 'account_type_regexes': ['.*'], 'start_name_regexes': ['.*'], 'trim_name_regexes': [], 'show_name_regexes': ['.*'], 'hide_name_regexes': [], 'account_displayed_op_only': True, 'select': ['float_ops'], 'output': 'stdout', 'dump_to_file': '' # Deprecated, use 'output': 'file:outfile=<name>' } # Show the timing stats and memory demands. PRINT_ALL_TIMING_MEMORY = { 'max_depth': 10000, 'min_bytes': 1, # Only >=1 'min_micros': 1, # Only >=1 'min_params': 0, 'min_float_ops': 0, 'order_by': 'name', 'account_type_regexes': ['.*'], 'start_name_regexes': ['.*'], 'trim_name_regexes': [], 'show_name_regexes': ['.*'], 'hide_name_regexes': [], 'account_displayed_op_only': True, 'select': ['micros', 'bytes'], 'output': 'stdout', 'dump_to_file': '' # Deprecated, use 'output': 'file:outfile=<name>' } # pylint: enable=bad-whitespace # pylint: enable=bad-continuation @deprecated('2018-01-01', 'Use `tf.profiler.advise(graph, run_meta, options)`. See README.md') def advise(graph, run_meta=None, tfprof_options=_DEFAULT_ADVISE_OPTIONS): return _advise(graph, run_meta, tfprof_options) @deprecated('2018-01-01', 'Use `tf.profiler.profile(graph, run_meta, op_log, cmd, options)`. ' 'Build `options` with `tf.profiler.ProfileOptionBuilder`. ' 'See README.md for details') def print_model_analysis(graph, run_meta=None, op_log=None, tfprof_cmd='scope', tfprof_options=_DEFAULT_PROFILE_OPTIONS): return _profile(graph, run_meta, op_log, tfprof_cmd, tfprof_options)
tensorflow-master
tensorflow/contrib/tfprof/model_analyzer.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Text-processing ops. @@skip_gram_sample @@skip_gram_sample_with_text_vocab """ from __future__ import absolute_import from __future__ import division from __future__ import print_function # pylint: disable=unused-import,wildcard-import from tensorflow.contrib.text.python.ops import * # pylint: enable=unused-import,wildcard-import from tensorflow.python.util.all_util import remove_undocumented remove_undocumented(__name__)
tensorflow-master
tensorflow/contrib/text/__init__.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Skip-gram sampling ops from https://arxiv.org/abs/1301.3781.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import csv from tensorflow.contrib import lookup from tensorflow.contrib.text.python.ops import gen_skip_gram_ops from tensorflow.contrib.util import loader from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.framework import random_seed from tensorflow.python.ops import array_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import random_ops from tensorflow.python.platform import gfile from tensorflow.python.platform import resource_loader from tensorflow.python.training import input as input_ops _checkpoint_ops_so = loader.load_op_library( resource_loader.get_path_to_datafile("_skip_gram_ops.so")) ops.NotDifferentiable("SkipGramGenerateCandidates") def skip_gram_sample(input_tensor, min_skips=1, max_skips=5, start=0, limit=-1, emit_self_as_target=False, vocab_freq_table=None, vocab_min_count=None, vocab_subsampling=None, corpus_size=None, batch_size=None, batch_capacity=None, seed=None, name=None): """Generates skip-gram token and label paired Tensors from the input tensor. Generates skip-gram `("token", "label")` pairs using each element in the rank-1 `input_tensor` as a token. The window size used for each token will be randomly selected from the range specified by `[min_skips, max_skips]`, inclusive. See https://arxiv.org/abs/1301.3781 for more details about skip-gram. For example, given `input_tensor = ["the", "quick", "brown", "fox", "jumps"]`, `min_skips = 1`, `max_skips = 2`, `emit_self_as_target = False`, the output `(tokens, labels)` pairs for the token "quick" will be randomly selected from either `(tokens=["quick", "quick"], labels=["the", "brown"])` for 1 skip, or `(tokens=["quick", "quick", "quick"], labels=["the", "brown", "fox"])` for 2 skips. If `emit_self_as_target = True`, each token will also be emitted as a label for itself. From the previous example, the output will be either `(tokens=["quick", "quick", "quick"], labels=["the", "quick", "brown"])` for 1 skip, or `(tokens=["quick", "quick", "quick", "quick"], labels=["the", "quick", "brown", "fox"])` for 2 skips. The same process is repeated for each element of `input_tensor` and concatenated together into the two output rank-1 `Tensors` (one for all the tokens, another for all the labels). If `vocab_freq_table` is specified, tokens in `input_tensor` that are not present in the vocabulary are discarded. Tokens whose frequency counts are below `vocab_min_count` are also discarded. Tokens whose frequency proportions in the corpus exceed `vocab_subsampling` may be randomly down-sampled. See Eq. 5 in http://arxiv.org/abs/1310.4546 for more details about subsampling. Due to the random window sizes used for each token, the lengths of the outputs are non-deterministic, unless `batch_size` is specified to batch the outputs to always return `Tensors` of length `batch_size`. Args: input_tensor: A rank-1 `Tensor` from which to generate skip-gram candidates. min_skips: `int` or scalar `Tensor` specifying the minimum window size to randomly use for each token. Must be >= 0 and <= `max_skips`. If `min_skips` and `max_skips` are both 0, the only label outputted will be the token itself when `emit_self_as_target = True` - or no output otherwise. max_skips: `int` or scalar `Tensor` specifying the maximum window size to randomly use for each token. Must be >= 0. start: `int` or scalar `Tensor` specifying the position in `input_tensor` from which to start generating skip-gram candidates. limit: `int` or scalar `Tensor` specifying the maximum number of elements in `input_tensor` to use in generating skip-gram candidates. -1 means to use the rest of the `Tensor` after `start`. emit_self_as_target: `bool` or scalar `Tensor` specifying whether to emit each token as a label for itself. vocab_freq_table: (Optional) A lookup table (subclass of `lookup.InitializableLookupTableBase`) that maps tokens to their raw frequency counts. If specified, any token in `input_tensor` that is not found in `vocab_freq_table` will be filtered out before generating skip-gram candidates. While this will typically map to integer raw frequency counts, it could also map to float frequency proportions. `vocab_min_count` and `corpus_size` should be in the same units as this. vocab_min_count: (Optional) `int`, `float`, or scalar `Tensor` specifying minimum frequency threshold (from `vocab_freq_table`) for a token to be kept in `input_tensor`. If this is specified, `vocab_freq_table` must also be specified - and they should both be in the same units. vocab_subsampling: (Optional) `float` specifying frequency proportion threshold for tokens from `input_tensor`. Tokens that occur more frequently (based on the ratio of the token's `vocab_freq_table` value to the `corpus_size`) will be randomly down-sampled. Reasonable starting values may be around 1e-3 or 1e-5. If this is specified, both `vocab_freq_table` and `corpus_size` must also be specified. See Eq. 5 in http://arxiv.org/abs/1310.4546 for more details. corpus_size: (Optional) `int`, `float`, or scalar `Tensor` specifying the total number of tokens in the corpus (e.g., sum of all the frequency counts of `vocab_freq_table`). Used with `vocab_subsampling` for down-sampling frequently occurring tokens. If this is specified, `vocab_freq_table` and `vocab_subsampling` must also be specified. batch_size: (Optional) `int` specifying batch size of returned `Tensors`. batch_capacity: (Optional) `int` specifying batch capacity for the queue used for batching returned `Tensors`. Only has an effect if `batch_size` > 0. Defaults to 100 * `batch_size` if not specified. seed: (Optional) `int` used to create a random seed for window size and subsampling. See `set_random_seed` docs for behavior. name: (Optional) A `string` name or a name scope for the operations. Returns: A `tuple` containing (token, label) `Tensors`. Each output `Tensor` is of rank-1 and has the same type as `input_tensor`. The `Tensors` will be of length `batch_size`; if `batch_size` is not specified, they will be of random length, though they will be in sync with each other as long as they are evaluated together. Raises: ValueError: If `vocab_freq_table` is not provided, but `vocab_min_count`, `vocab_subsampling`, or `corpus_size` is specified. If `vocab_subsampling` and `corpus_size` are not both present or both absent. """ if vocab_freq_table is None and (vocab_min_count is not None or vocab_subsampling is not None or corpus_size is not None): raise ValueError( "vocab_freq_table is not provided, but vocab_min_count={}, " "vocab_subsampling={}, or corpus_size={} is not None. These settings " "are useless without a vocab_freq_table.".format( vocab_min_count, vocab_subsampling, corpus_size)) if (vocab_subsampling is None) != (corpus_size is None): raise ValueError( "vocab_subsampling is {} while corpus_size is {} - both must be " "provided in order for subsampling to work.".format( vocab_subsampling, corpus_size)) with ops.name_scope( name, "skip_gram_sample", values=[input_tensor, min_skips, max_skips, start, limit]): input_tensor = _filter_input( input_tensor=input_tensor, vocab_freq_table=vocab_freq_table, vocab_min_count=vocab_min_count, vocab_subsampling=vocab_subsampling, corpus_size=corpus_size, seed=seed) seed1, seed2 = random_seed.get_seed(seed) tokens, labels = gen_skip_gram_ops.skip_gram_generate_candidates( input_tensor=input_tensor, min_skips=min_skips, max_skips=max_skips, start=start, limit=limit, emit_self_as_target=emit_self_as_target, # Note that seed here should be seed1! This is due to # GuardedPhiloxRandom's hard-coded attributes of "seed" and "seed2". seed=seed1, seed2=seed2) # TODO(weiho): If the need arises, add support for sparse input_tensor that # figures out sentence boundaries, then calls # skip_gram_generate_candidates() on each sentence. # Batches the (tokens, labels) outputs so that they will be of deterministic # batch_size, to facilitate feeding them into the rest of the network. if batch_size is not None and batch_size > 0: batch_capacity = (batch_capacity if (batch_capacity is not None and batch_capacity > 0) else 100 * batch_size) return input_ops.batch( [tokens, labels], batch_size, capacity=batch_capacity, enqueue_many=True) return tokens, labels def skip_gram_sample_with_text_vocab(input_tensor, vocab_freq_file, vocab_token_index=0, vocab_token_dtype=dtypes.string, vocab_freq_index=1, vocab_freq_dtype=dtypes.float64, vocab_delimiter=",", vocab_min_count=0, vocab_subsampling=None, corpus_size=None, min_skips=1, max_skips=5, start=0, limit=-1, emit_self_as_target=False, batch_size=None, batch_capacity=None, seed=None, name=None): """Skip-gram sampling with a text vocabulary file. Wrapper around `skip_gram_sample()` for use with a text vocabulary file. The vocabulary file is expected to be a plain-text file, with lines of `vocab_delimiter`-separated columns. The `vocab_token_index` column should contain the vocabulary term, while the `vocab_freq_index` column should contain the number of times that term occurs in the corpus. For example, with a text vocabulary file of: ``` bonjour,fr,42 hello,en,777 hola,es,99 ``` You should set `vocab_delimiter=","`, `vocab_token_index=0`, and `vocab_freq_index=2`. See `skip_gram_sample()` documentation for more details about the skip-gram sampling process. Args: input_tensor: A rank-1 `Tensor` from which to generate skip-gram candidates. vocab_freq_file: `string` specifying full file path to the text vocab file. vocab_token_index: `int` specifying which column in the text vocab file contains the tokens. vocab_token_dtype: `DType` specifying the format of the tokens in the text vocab file. vocab_freq_index: `int` specifying which column in the text vocab file contains the frequency counts of the tokens. vocab_freq_dtype: `DType` specifying the format of the frequency counts in the text vocab file. vocab_delimiter: `string` specifying the delimiter used in the text vocab file. vocab_min_count: `int`, `float`, or scalar `Tensor` specifying minimum frequency threshold (from `vocab_freq_file`) for a token to be kept in `input_tensor`. This should correspond with `vocab_freq_dtype`. vocab_subsampling: (Optional) `float` specifying frequency proportion threshold for tokens from `input_tensor`. Tokens that occur more frequently will be randomly down-sampled. Reasonable starting values may be around 1e-3 or 1e-5. See Eq. 5 in http://arxiv.org/abs/1310.4546 for more details. corpus_size: (Optional) `int`, `float`, or scalar `Tensor` specifying the total number of tokens in the corpus (e.g., sum of all the frequency counts of `vocab_freq_file`). Used with `vocab_subsampling` for down-sampling frequently occurring tokens. If this is specified, `vocab_freq_file` and `vocab_subsampling` must also be specified. If `corpus_size` is needed but not supplied, then it will be calculated from `vocab_freq_file`. You might want to supply your own value if you have already eliminated infrequent tokens from your vocabulary files (where frequency < vocab_min_count) to save memory in the internal token lookup table. Otherwise, the unused tokens' variables will waste memory. The user-supplied `corpus_size` value must be greater than or equal to the sum of all the frequency counts of `vocab_freq_file`. min_skips: `int` or scalar `Tensor` specifying the minimum window size to randomly use for each token. Must be >= 0 and <= `max_skips`. If `min_skips` and `max_skips` are both 0, the only label outputted will be the token itself. max_skips: `int` or scalar `Tensor` specifying the maximum window size to randomly use for each token. Must be >= 0. start: `int` or scalar `Tensor` specifying the position in `input_tensor` from which to start generating skip-gram candidates. limit: `int` or scalar `Tensor` specifying the maximum number of elements in `input_tensor` to use in generating skip-gram candidates. -1 means to use the rest of the `Tensor` after `start`. emit_self_as_target: `bool` or scalar `Tensor` specifying whether to emit each token as a label for itself. batch_size: (Optional) `int` specifying batch size of returned `Tensors`. batch_capacity: (Optional) `int` specifying batch capacity for the queue used for batching returned `Tensors`. Only has an effect if `batch_size` > 0. Defaults to 100 * `batch_size` if not specified. seed: (Optional) `int` used to create a random seed for window size and subsampling. See [`set_random_seed`](../../g3doc/python/constant_op.md#set_random_seed) for behavior. name: (Optional) A `string` name or a name scope for the operations. Returns: A `tuple` containing (token, label) `Tensors`. Each output `Tensor` is of rank-1 and has the same type as `input_tensor`. The `Tensors` will be of length `batch_size`; if `batch_size` is not specified, they will be of random length, though they will be in sync with each other as long as they are evaluated together. Raises: ValueError: If `vocab_token_index` or `vocab_freq_index` is less than 0 or exceeds the number of columns in `vocab_freq_file`. If `vocab_token_index` and `vocab_freq_index` are both set to the same column. If any token in `vocab_freq_file` has a negative frequency. """ if vocab_token_index < 0 or vocab_freq_index < 0: raise ValueError( "vocab_token_index={} and vocab_freq_index={} must both be >= 0.". format(vocab_token_index, vocab_freq_index)) if vocab_token_index == vocab_freq_index: raise ValueError( "vocab_token_index and vocab_freq_index should be different, but are " "both {}.".format(vocab_token_index)) # Iterates through the vocab file and calculates the number of vocab terms as # well as the total corpus size (by summing the frequency counts of all the # vocab terms). calculated_corpus_size = 0.0 vocab_size = 0 with gfile.GFile(vocab_freq_file, mode="r") as f: reader = csv.reader(f, delimiter=vocab_delimiter) for row in reader: if vocab_token_index >= len(row) or vocab_freq_index >= len(row): raise ValueError( "Row in vocab file only has {} columns, so vocab_token_index={} or " "vocab_freq_index={} is out of bounds. Row content: {}".format( len(row), vocab_token_index, vocab_freq_index, row)) vocab_size += 1 freq = vocab_freq_dtype.as_numpy_dtype(row[vocab_freq_index]) if freq < 0: raise ValueError( "Row in vocab file has negative frequency of {}. Row content: {}". format(freq, row)) # Note: tokens whose frequencies are below vocab_min_count will still # contribute to the total corpus size used for vocab subsampling. calculated_corpus_size += freq if not corpus_size: corpus_size = calculated_corpus_size elif calculated_corpus_size - corpus_size > 1e-6: raise ValueError( "`corpus_size`={} must be greater than or equal to the sum of all the " "frequency counts ({}) of `vocab_freq_file` ({}).".format( corpus_size, calculated_corpus_size, vocab_freq_file)) vocab_freq_table = lookup.HashTable( lookup.TextFileInitializer( filename=vocab_freq_file, key_dtype=vocab_token_dtype, key_index=vocab_token_index, value_dtype=vocab_freq_dtype, value_index=vocab_freq_index, vocab_size=vocab_size, delimiter=vocab_delimiter), # For vocab terms not in vocab file, use a default value of -1. default_value=-1) return skip_gram_sample( input_tensor, min_skips=min_skips, max_skips=max_skips, start=start, limit=limit, emit_self_as_target=emit_self_as_target, vocab_freq_table=vocab_freq_table, vocab_min_count=vocab_min_count, vocab_subsampling=vocab_subsampling, # corpus_size is not used unless vocab_subsampling is specified. corpus_size=None if vocab_subsampling is None else corpus_size, batch_size=batch_size, batch_capacity=batch_capacity, seed=seed, name=name) def _filter_input(input_tensor, vocab_freq_table, vocab_min_count, vocab_subsampling, corpus_size, seed): """Filters input tensor based on vocab freq, threshold, and subsampling.""" if vocab_freq_table is None: return input_tensor if not isinstance(vocab_freq_table, lookup.InitializableLookupTableBase): raise ValueError( "vocab_freq_table must be a subclass of " "InitializableLookupTableBase (such as HashTable) instead of type " "{}.".format(type(vocab_freq_table))) with ops.name_scope( "filter_vocab", values=[vocab_freq_table, input_tensor, vocab_min_count]): freq = vocab_freq_table.lookup(input_tensor) # Filters out elements in input_tensor that are not found in # vocab_freq_table (table returns a default value of -1 specified above when # an element is not found). mask = math_ops.not_equal(freq, vocab_freq_table.default_value) # Filters out elements whose vocab frequencies are less than the threshold. if vocab_min_count is not None: cast_threshold = math_ops.cast(vocab_min_count, freq.dtype) mask = math_ops.logical_and(mask, math_ops.greater_equal(freq, cast_threshold)) input_tensor = array_ops.boolean_mask(input_tensor, mask) freq = array_ops.boolean_mask(freq, mask) if not vocab_subsampling: return input_tensor if vocab_subsampling < 0 or vocab_subsampling > 1: raise ValueError( "Invalid vocab_subsampling={} - it should be within range [0, 1].". format(vocab_subsampling)) # Subsamples the input tokens based on vocabulary frequency and # vocab_subsampling threshold (ie randomly discard commonly appearing # tokens). with ops.name_scope( "subsample_vocab", values=[input_tensor, freq, vocab_subsampling]): corpus_size = math_ops.cast(corpus_size, dtypes.float64) freq = math_ops.cast(freq, dtypes.float64) vocab_subsampling = math_ops.cast(vocab_subsampling, dtypes.float64) # From tensorflow_models/tutorials/embedding/word2vec_kernels.cc, which is # suppose to correlate with Eq. 5 in http://arxiv.org/abs/1310.4546. keep_prob = ((math_ops.sqrt(freq / (vocab_subsampling * corpus_size)) + 1.0) * (vocab_subsampling * corpus_size / freq)) random_prob = random_ops.random_uniform( array_ops.shape(freq), minval=0, maxval=1, dtype=dtypes.float64, seed=seed) mask = math_ops.less_equal(random_prob, keep_prob) return array_ops.boolean_mask(input_tensor, mask)
tensorflow-master
tensorflow/contrib/text/python/ops/skip_gram_ops.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Various contrib ops related to text-processing.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.contrib.text.python.ops.skip_gram_ops import skip_gram_sample from tensorflow.contrib.text.python.ops.skip_gram_ops import skip_gram_sample_with_text_vocab
tensorflow-master
tensorflow/contrib/text/python/ops/__init__.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Skip-gram sampling ops tests.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import csv import os from tensorflow.contrib import lookup from tensorflow.contrib import text from tensorflow.contrib.text.python.ops import skip_gram_ops from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import errors from tensorflow.python.framework import random_seed from tensorflow.python.ops import lookup_ops from tensorflow.python.ops import math_ops from tensorflow.python.platform import test from tensorflow.python.training import coordinator from tensorflow.python.training import queue_runner_impl class SkipGramOpsTest(test.TestCase): def _split_tokens_labels(self, output): tokens = [x[0] for x in output] labels = [x[1] for x in output] return tokens, labels def test_skip_gram_sample_skips_2(self): """Tests skip-gram with min_skips = max_skips = 2.""" input_tensor = constant_op.constant( [b"the", b"quick", b"brown", b"fox", b"jumps"]) tokens, labels = text.skip_gram_sample( input_tensor, min_skips=2, max_skips=2) expected_tokens, expected_labels = self._split_tokens_labels([ (b"the", b"quick"), (b"the", b"brown"), (b"quick", b"the"), (b"quick", b"brown"), (b"quick", b"fox"), (b"brown", b"the"), (b"brown", b"quick"), (b"brown", b"fox"), (b"brown", b"jumps"), (b"fox", b"quick"), (b"fox", b"brown"), (b"fox", b"jumps"), (b"jumps", b"brown"), (b"jumps", b"fox"), ]) with self.cached_session(): self.assertAllEqual(expected_tokens, tokens.eval()) self.assertAllEqual(expected_labels, labels.eval()) def test_skip_gram_sample_emit_self(self): """Tests skip-gram with emit_self_as_target = True.""" input_tensor = constant_op.constant( [b"the", b"quick", b"brown", b"fox", b"jumps"]) tokens, labels = text.skip_gram_sample( input_tensor, min_skips=2, max_skips=2, emit_self_as_target=True) expected_tokens, expected_labels = self._split_tokens_labels([ (b"the", b"the"), (b"the", b"quick"), (b"the", b"brown"), (b"quick", b"the"), (b"quick", b"quick"), (b"quick", b"brown"), (b"quick", b"fox"), (b"brown", b"the"), (b"brown", b"quick"), (b"brown", b"brown"), (b"brown", b"fox"), (b"brown", b"jumps"), (b"fox", b"quick"), (b"fox", b"brown"), (b"fox", b"fox"), (b"fox", b"jumps"), (b"jumps", b"brown"), (b"jumps", b"fox"), (b"jumps", b"jumps"), ]) with self.cached_session(): self.assertAllEqual(expected_tokens, tokens.eval()) self.assertAllEqual(expected_labels, labels.eval()) def test_skip_gram_sample_skips_0(self): """Tests skip-gram with min_skips = max_skips = 0.""" input_tensor = constant_op.constant([b"the", b"quick", b"brown"]) # If emit_self_as_target is False (default), output will be empty. tokens, labels = text.skip_gram_sample( input_tensor, min_skips=0, max_skips=0, emit_self_as_target=False) with self.cached_session(): self.assertEqual(0, tokens.eval().size) self.assertEqual(0, labels.eval().size) # If emit_self_as_target is True, each token will be its own label. tokens, labels = text.skip_gram_sample( input_tensor, min_skips=0, max_skips=0, emit_self_as_target=True) expected_tokens, expected_labels = self._split_tokens_labels([ (b"the", b"the"), (b"quick", b"quick"), (b"brown", b"brown"), ]) with self.cached_session(): self.assertAllEqual(expected_tokens, tokens.eval()) self.assertAllEqual(expected_labels, labels.eval()) def test_skip_gram_sample_skips_exceed_length(self): """Tests skip-gram when min/max_skips exceed length of input.""" input_tensor = constant_op.constant([b"the", b"quick", b"brown"]) tokens, labels = text.skip_gram_sample( input_tensor, min_skips=100, max_skips=100) expected_tokens, expected_labels = self._split_tokens_labels([ (b"the", b"quick"), (b"the", b"brown"), (b"quick", b"the"), (b"quick", b"brown"), (b"brown", b"the"), (b"brown", b"quick"), ]) with self.cached_session(): self.assertAllEqual(expected_tokens, tokens.eval()) self.assertAllEqual(expected_labels, labels.eval()) def test_skip_gram_sample_start_limit(self): """Tests skip-gram over a limited portion of the input.""" input_tensor = constant_op.constant( [b"foo", b"the", b"quick", b"brown", b"bar"]) tokens, labels = text.skip_gram_sample( input_tensor, min_skips=1, max_skips=1, start=1, limit=3) expected_tokens, expected_labels = self._split_tokens_labels([ (b"the", b"quick"), (b"quick", b"the"), (b"quick", b"brown"), (b"brown", b"quick"), ]) with self.cached_session(): self.assertAllEqual(expected_tokens, tokens.eval()) self.assertAllEqual(expected_labels, labels.eval()) def test_skip_gram_sample_limit_exceeds(self): """Tests skip-gram when limit exceeds the length of the input.""" input_tensor = constant_op.constant([b"foo", b"the", b"quick", b"brown"]) tokens, labels = text.skip_gram_sample( input_tensor, min_skips=1, max_skips=1, start=1, limit=100) expected_tokens, expected_labels = self._split_tokens_labels([ (b"the", b"quick"), (b"quick", b"the"), (b"quick", b"brown"), (b"brown", b"quick"), ]) with self.cached_session(): self.assertAllEqual(expected_tokens, tokens.eval()) self.assertAllEqual(expected_labels, labels.eval()) def test_skip_gram_sample_random_skips(self): """Tests skip-gram with min_skips != max_skips, with random output.""" # The number of outputs is non-deterministic in this case, so set random # seed to help ensure the outputs remain constant for this test case. random_seed.set_random_seed(42) input_tensor = constant_op.constant( [b"the", b"quick", b"brown", b"fox", b"jumps", b"over"]) tokens, labels = text.skip_gram_sample( input_tensor, min_skips=1, max_skips=2, seed=9) expected_tokens, expected_labels = self._split_tokens_labels([ (b"the", b"quick"), (b"the", b"brown"), (b"quick", b"the"), (b"quick", b"brown"), (b"quick", b"fox"), (b"brown", b"the"), (b"brown", b"quick"), (b"brown", b"fox"), (b"brown", b"jumps"), (b"fox", b"brown"), (b"fox", b"jumps"), (b"jumps", b"fox"), (b"jumps", b"over"), (b"over", b"fox"), (b"over", b"jumps"), ]) with self.cached_session() as sess: tokens_eval, labels_eval = sess.run([tokens, labels]) self.assertAllEqual(expected_tokens, tokens_eval) self.assertAllEqual(expected_labels, labels_eval) def test_skip_gram_sample_random_skips_default_seed(self): """Tests outputs are still random when no op-level seed is specified.""" # This is needed since tests set a graph-level seed by default. We want to # explicitly avoid setting both graph-level seed and op-level seed, to # simulate behavior under non-test settings when the user doesn't provide a # seed to us. This results in random_seed.get_seed() returning None for both # seeds, forcing the C++ kernel to execute its default seed logic. random_seed.set_random_seed(None) # Uses an input tensor with 10 words, with possible skip ranges in [1, # 5]. Thus, the probability that two random samplings would result in the # same outputs is 1/5^10 ~ 1e-7 (aka the probability of this test being # flaky). input_tensor = constant_op.constant([str(x) for x in range(10)]) # Do not provide an op-level seed here! tokens_1, labels_1 = text.skip_gram_sample( input_tensor, min_skips=1, max_skips=5) tokens_2, labels_2 = text.skip_gram_sample( input_tensor, min_skips=1, max_skips=5) with self.cached_session() as sess: tokens_1_eval, labels_1_eval, tokens_2_eval, labels_2_eval = sess.run( [tokens_1, labels_1, tokens_2, labels_2]) if len(tokens_1_eval) == len(tokens_2_eval): self.assertNotEqual(tokens_1_eval.tolist(), tokens_2_eval.tolist()) if len(labels_1_eval) == len(labels_2_eval): self.assertNotEqual(labels_1_eval.tolist(), labels_2_eval.tolist()) def test_skip_gram_sample_batch(self): """Tests skip-gram with batching.""" input_tensor = constant_op.constant([b"the", b"quick", b"brown", b"fox"]) tokens, labels = text.skip_gram_sample( input_tensor, min_skips=1, max_skips=1, batch_size=3) expected_tokens, expected_labels = self._split_tokens_labels([ (b"the", b"quick"), (b"quick", b"the"), (b"quick", b"brown"), (b"brown", b"quick"), (b"brown", b"fox"), (b"fox", b"brown"), ]) with self.cached_session() as sess: coord = coordinator.Coordinator() threads = queue_runner_impl.start_queue_runners(sess=sess, coord=coord) tokens_eval, labels_eval = sess.run([tokens, labels]) self.assertAllEqual(expected_tokens[:3], tokens_eval) self.assertAllEqual(expected_labels[:3], labels_eval) tokens_eval, labels_eval = sess.run([tokens, labels]) self.assertAllEqual(expected_tokens[3:6], tokens_eval) self.assertAllEqual(expected_labels[3:6], labels_eval) coord.request_stop() coord.join(threads) def test_skip_gram_sample_non_string_input(self): """Tests skip-gram with non-string input.""" input_tensor = constant_op.constant([1, 2, 3], dtype=dtypes.int16) tokens, labels = text.skip_gram_sample( input_tensor, min_skips=1, max_skips=1) expected_tokens, expected_labels = self._split_tokens_labels([ (1, 2), (2, 1), (2, 3), (3, 2), ]) with self.cached_session(): self.assertAllEqual(expected_tokens, tokens.eval()) self.assertAllEqual(expected_labels, labels.eval()) def test_skip_gram_sample_errors(self): """Tests various errors raised by skip_gram_sample().""" input_tensor = constant_op.constant([b"the", b"quick", b"brown"]) invalid_skips = ( # min_skips and max_skips must be >= 0. (-1, 2), (1, -2), # min_skips must be <= max_skips. (2, 1)) for min_skips, max_skips in invalid_skips: tokens, labels = text.skip_gram_sample( input_tensor, min_skips=min_skips, max_skips=max_skips) with self.cached_session() as sess, self.assertRaises( errors.InvalidArgumentError): sess.run([tokens, labels]) # input_tensor must be of rank 1. with self.assertRaises(ValueError): invalid_tensor = constant_op.constant([[b"the"], [b"quick"], [b"brown"]]) text.skip_gram_sample(invalid_tensor) # vocab_freq_table must be provided if vocab_min_count, vocab_subsampling, # or corpus_size is specified. dummy_input = constant_op.constant([""]) with self.assertRaises(ValueError): text.skip_gram_sample( dummy_input, vocab_freq_table=None, vocab_min_count=1) with self.assertRaises(ValueError): text.skip_gram_sample( dummy_input, vocab_freq_table=None, vocab_subsampling=1e-5) with self.assertRaises(ValueError): text.skip_gram_sample(dummy_input, vocab_freq_table=None, corpus_size=100) with self.assertRaises(ValueError): text.skip_gram_sample( dummy_input, vocab_freq_table=None, vocab_subsampling=1e-5, corpus_size=100) # vocab_subsampling and corpus_size must both be present or absent. dummy_table = lookup.HashTable( lookup.KeyValueTensorInitializer([b"foo"], [10]), -1) with self.assertRaises(ValueError): text.skip_gram_sample( dummy_input, vocab_freq_table=dummy_table, vocab_subsampling=None, corpus_size=100) with self.assertRaises(ValueError): text.skip_gram_sample( dummy_input, vocab_freq_table=dummy_table, vocab_subsampling=1e-5, corpus_size=None) def test_filter_input_filter_vocab(self): """Tests input filtering based on vocab frequency table and thresholds.""" input_tensor = constant_op.constant( [b"the", b"answer", b"to", b"life", b"and", b"universe"]) keys = constant_op.constant([b"and", b"life", b"the", b"to", b"universe"]) values = constant_op.constant([0, 1, 2, 3, 4], dtypes.int64) vocab_freq_table = lookup.HashTable( lookup.KeyValueTensorInitializer(keys, values), -1) with self.cached_session(): vocab_freq_table.initializer.run() # No vocab_freq_table specified - output should be the same as input. no_table_output = skip_gram_ops._filter_input( input_tensor=input_tensor, vocab_freq_table=None, vocab_min_count=None, vocab_subsampling=None, corpus_size=None, seed=None) self.assertAllEqual(input_tensor.eval(), no_table_output.eval()) # vocab_freq_table specified, but no vocab_min_count - output should have # filtered out tokens not in the table (b"answer"). table_output = skip_gram_ops._filter_input( input_tensor=input_tensor, vocab_freq_table=vocab_freq_table, vocab_min_count=None, vocab_subsampling=None, corpus_size=None, seed=None) self.assertAllEqual([b"the", b"to", b"life", b"and", b"universe"], table_output.eval()) # vocab_freq_table and vocab_min_count specified - output should have # filtered out tokens whose frequencies are below the threshold # (b"and": 0, b"life": 1). threshold_output = skip_gram_ops._filter_input( input_tensor=input_tensor, vocab_freq_table=vocab_freq_table, vocab_min_count=2, vocab_subsampling=None, corpus_size=None, seed=None) self.assertAllEqual([b"the", b"to", b"universe"], threshold_output.eval()) def test_filter_input_subsample_vocab(self): """Tests input filtering based on vocab subsampling.""" # The outputs are non-deterministic, so set random seed to help ensure that # the outputs remain constant for testing. random_seed.set_random_seed(42) input_tensor = constant_op.constant([ # keep_prob = (sqrt(30/(0.05*100)) + 1) * (0.05*100/30) = 0.57. b"the", b"answer", # Not in vocab. (Always discarded) b"to", # keep_prob = 0.75. b"life", # keep_prob > 1. (Always kept) b"and", # keep_prob = 0.48. b"universe" # Below vocab threshold of 3. (Always discarded) ]) keys = constant_op.constant([b"and", b"life", b"the", b"to", b"universe"]) values = constant_op.constant([40, 8, 30, 20, 2], dtypes.int64) vocab_freq_table = lookup.HashTable( lookup.KeyValueTensorInitializer(keys, values), -1) with self.cached_session(): vocab_freq_table.initializer.run() output = skip_gram_ops._filter_input( input_tensor=input_tensor, vocab_freq_table=vocab_freq_table, vocab_min_count=3, vocab_subsampling=0.05, corpus_size=math_ops.reduce_sum(values), seed=9) self.assertAllEqual([b"the", b"to", b"life", b"and"], output.eval()) def _make_text_vocab_freq_file(self): filepath = os.path.join(test.get_temp_dir(), "vocab_freq.txt") with open(filepath, "w") as f: writer = csv.writer(f) writer.writerows([ ["and", 40], ["life", 8], ["the", 30], ["to", 20], ["universe", 2], ]) return filepath def _make_text_vocab_float_file(self): filepath = os.path.join(test.get_temp_dir(), "vocab_freq_float.txt") with open(filepath, "w") as f: writer = csv.writer(f) writer.writerows([ ["and", 0.4], ["life", 0.08], ["the", 0.3], ["to", 0.2], ["universe", 0.02], ]) return filepath def test_skip_gram_sample_with_text_vocab_filter_vocab(self): """Tests skip-gram sampling with text vocab and freq threshold filtering.""" input_tensor = constant_op.constant([ b"the", b"answer", # Will be filtered before candidate generation. b"to", b"life", b"and", b"universe" # Will be filtered before candidate generation. ]) # b"answer" is not in vocab file, and b"universe"'s frequency is below # threshold of 3. vocab_freq_file = self._make_text_vocab_freq_file() tokens, labels = text.skip_gram_sample_with_text_vocab( input_tensor=input_tensor, vocab_freq_file=vocab_freq_file, vocab_token_index=0, vocab_freq_index=1, vocab_min_count=3, min_skips=1, max_skips=1) expected_tokens, expected_labels = self._split_tokens_labels([ (b"the", b"to"), (b"to", b"the"), (b"to", b"life"), (b"life", b"to"), (b"life", b"and"), (b"and", b"life"), ]) with self.cached_session(): lookup_ops.tables_initializer().run() self.assertAllEqual(expected_tokens, tokens.eval()) self.assertAllEqual(expected_labels, labels.eval()) def _text_vocab_subsample_vocab_helper(self, vocab_freq_file, vocab_min_count, vocab_freq_dtype, corpus_size=None): # The outputs are non-deterministic, so set random seed to help ensure that # the outputs remain constant for testing. random_seed.set_random_seed(42) input_tensor = constant_op.constant([ # keep_prob = (sqrt(30/(0.05*100)) + 1) * (0.05*100/30) = 0.57. b"the", b"answer", # Not in vocab. (Always discarded) b"to", # keep_prob = 0.75. b"life", # keep_prob > 1. (Always kept) b"and", # keep_prob = 0.48. b"universe" # Below vocab threshold of 3. (Always discarded) ]) # keep_prob calculated from vocab file with relative frequencies of: # and: 40 # life: 8 # the: 30 # to: 20 # universe: 2 tokens, labels = text.skip_gram_sample_with_text_vocab( input_tensor=input_tensor, vocab_freq_file=vocab_freq_file, vocab_token_index=0, vocab_freq_index=1, vocab_freq_dtype=vocab_freq_dtype, vocab_min_count=vocab_min_count, vocab_subsampling=0.05, corpus_size=corpus_size, min_skips=1, max_skips=1, seed=123) expected_tokens, expected_labels = self._split_tokens_labels([ (b"the", b"to"), (b"to", b"the"), (b"to", b"life"), (b"life", b"to"), ]) with self.cached_session() as sess: lookup_ops.tables_initializer().run() tokens_eval, labels_eval = sess.run([tokens, labels]) self.assertAllEqual(expected_tokens, tokens_eval) self.assertAllEqual(expected_labels, labels_eval) def test_skip_gram_sample_with_text_vocab_subsample_vocab(self): """Tests skip-gram sampling with text vocab and vocab subsampling.""" # Vocab file frequencies # and: 40 # life: 8 # the: 30 # to: 20 # universe: 2 # # corpus_size for the above vocab is 40+8+30+20+2 = 100. text_vocab_freq_file = self._make_text_vocab_freq_file() self._text_vocab_subsample_vocab_helper( vocab_freq_file=text_vocab_freq_file, vocab_min_count=3, vocab_freq_dtype=dtypes.int64) self._text_vocab_subsample_vocab_helper( vocab_freq_file=text_vocab_freq_file, vocab_min_count=3, vocab_freq_dtype=dtypes.int64, corpus_size=100) # The user-supplied corpus_size should not be less than the sum of all # the frequency counts of vocab_freq_file, which is 100. with self.assertRaises(ValueError): self._text_vocab_subsample_vocab_helper( vocab_freq_file=text_vocab_freq_file, vocab_min_count=3, vocab_freq_dtype=dtypes.int64, corpus_size=99) def test_skip_gram_sample_with_text_vocab_subsample_vocab_float(self): """Tests skip-gram sampling with text vocab and subsampling with floats.""" # Vocab file frequencies # and: 0.4 # life: 0.08 # the: 0.3 # to: 0.2 # universe: 0.02 # # corpus_size for the above vocab is 0.4+0.08+0.3+0.2+0.02 = 1. text_vocab_float_file = self._make_text_vocab_float_file() self._text_vocab_subsample_vocab_helper( vocab_freq_file=text_vocab_float_file, vocab_min_count=0.03, vocab_freq_dtype=dtypes.float32) self._text_vocab_subsample_vocab_helper( vocab_freq_file=text_vocab_float_file, vocab_min_count=0.03, vocab_freq_dtype=dtypes.float32, corpus_size=1.0) # The user-supplied corpus_size should not be less than the sum of all # the frequency counts of vocab_freq_file, which is 1. with self.assertRaises(ValueError): self._text_vocab_subsample_vocab_helper( vocab_freq_file=text_vocab_float_file, vocab_min_count=0.03, vocab_freq_dtype=dtypes.float32, corpus_size=0.99) def test_skip_gram_sample_with_text_vocab_errors(self): """Tests various errors raised by skip_gram_sample_with_text_vocab().""" dummy_input = constant_op.constant([""]) vocab_freq_file = self._make_text_vocab_freq_file() invalid_indices = ( # vocab_token_index can't be negative. (-1, 0), # vocab_freq_index can't be negative. (0, -1), # vocab_token_index can't be equal to vocab_freq_index. (0, 0), (1, 1), # vocab_freq_file only has two columns. (0, 2), (2, 0)) for vocab_token_index, vocab_freq_index in invalid_indices: with self.assertRaises(ValueError): text.skip_gram_sample_with_text_vocab( input_tensor=dummy_input, vocab_freq_file=vocab_freq_file, vocab_token_index=vocab_token_index, vocab_freq_index=vocab_freq_index) if __name__ == "__main__": test.main()
tensorflow-master
tensorflow/contrib/text/python/ops/skip_gram_ops_test.py
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Utility functions for the graph_editor. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import re from six import iteritems from tensorflow.python.framework import ops as tf_ops from tensorflow.python.ops import array_ops as tf_array_ops __all__ = [ "make_list_of_op", "get_tensors", "make_list_of_t", "get_generating_ops", "get_consuming_ops", "ControlOutputs", "placeholder_name", "make_placeholder_from_tensor", "make_placeholder_from_dtype_and_shape", ] # The graph editor sometimes need to create placeholders, they are named # "geph_*". "geph" stands for Graph-Editor PlaceHolder. _DEFAULT_PLACEHOLDER_PREFIX = "geph" def concatenate_unique(la, lb): """Add all the elements of `lb` to `la` if they are not there already. The elements added to `la` maintain ordering with respect to `lb`. Args: la: List of Python objects. lb: List of Python objects. Returns: `la`: The list `la` with missing elements from `lb`. """ la_set = set(la) for l in lb: if l not in la_set: la.append(l) la_set.add(l) return la # TODO(fkp): very generic code, it should be moved in a more generic place. class ListView(object): """Immutable list wrapper. This class is strongly inspired by the one in tf.Operation. """ def __init__(self, list_): if not isinstance(list_, list): raise TypeError("Expected a list, got: {}.".format(type(list_))) self._list = list_ def __iter__(self): return iter(self._list) def __len__(self): return len(self._list) def __bool__(self): return bool(self._list) # Python 3 wants __bool__, Python 2.7 wants __nonzero__ __nonzero__ = __bool__ def __getitem__(self, i): return self._list[i] def __add__(self, other): if not isinstance(other, list): other = list(other) return list(self) + other # TODO(fkp): very generic code, it should be moved in a more generic place. def is_iterable(obj): """Return true if the object is iterable.""" if isinstance(obj, tf_ops.Tensor): return False try: _ = iter(obj) except Exception: # pylint: disable=broad-except return False return True def flatten_tree(tree, leaves=None): """Flatten a tree into a list. Args: tree: iterable or not. If iterable, its elements (child) can also be iterable or not. leaves: list to which the tree leaves are appended (None by default). Returns: A list of all the leaves in the tree. """ if leaves is None: leaves = [] if isinstance(tree, dict): for _, child in iteritems(tree): flatten_tree(child, leaves) elif is_iterable(tree): for child in tree: flatten_tree(child, leaves) else: leaves.append(tree) return leaves def transform_tree(tree, fn, iterable_type=tuple): """Transform all the nodes of a tree. Args: tree: iterable or not. If iterable, its elements (child) can also be iterable or not. fn: function to apply to each leaves. iterable_type: type use to construct the resulting tree for unknown iterable, typically `list` or `tuple`. Returns: A tree whose leaves has been transformed by `fn`. The hierarchy of the output tree mimics the one of the input tree. """ if is_iterable(tree): if isinstance(tree, dict): res = tree.__new__(type(tree)) res.__init__( (k, transform_tree(child, fn)) for k, child in iteritems(tree)) return res elif isinstance(tree, tuple): # NamedTuple? if hasattr(tree, "_asdict"): res = tree.__new__(type(tree), **transform_tree(tree._asdict(), fn)) else: res = tree.__new__(type(tree), (transform_tree(child, fn) for child in tree)) return res elif isinstance(tree, collections.Sequence): res = tree.__new__(type(tree)) res.__init__(transform_tree(child, fn) for child in tree) return res else: return iterable_type(transform_tree(child, fn) for child in tree) else: return fn(tree) def check_graphs(*args): """Check that all the element in args belong to the same graph. Args: *args: a list of object with a obj.graph property. Raises: ValueError: if all the elements do not belong to the same graph. """ graph = None for i, sgv in enumerate(args): if graph is None and sgv.graph is not None: graph = sgv.graph elif sgv.graph is not None and sgv.graph is not graph: raise ValueError("Argument[{}]: Wrong graph!".format(i)) def get_unique_graph(tops, check_types=None, none_if_empty=False): """Return the unique graph used by the all the elements in tops. Args: tops: list of elements to check (usually a list of tf.Operation and/or tf.Tensor). Or a tf.Graph. check_types: check that the element in tops are of given type(s). If None, the types (tf.Operation, tf.Tensor) are used. none_if_empty: don't raise an error if tops is an empty list, just return None. Returns: The unique graph used by all the tops. Raises: TypeError: if tops is not a iterable of tf.Operation. ValueError: if the graph is not unique. """ if isinstance(tops, tf_ops.Graph): return tops if not is_iterable(tops): raise TypeError("{} is not iterable".format(type(tops))) if check_types is None: check_types = (tf_ops.Operation, tf_ops.Tensor) elif not is_iterable(check_types): check_types = (check_types,) g = None for op in tops: if not isinstance(op, check_types): raise TypeError("Expected a type in ({}), got: {}".format(", ".join([str( t) for t in check_types]), type(op))) if g is None: g = op.graph elif g is not op.graph: raise ValueError("Operation {} does not belong to given graph".format(op)) if g is None and not none_if_empty: raise ValueError("Can't find the unique graph of an empty list") return g def make_list_of_op(ops, check_graph=True, allow_graph=True, ignore_ts=False): """Convert ops to a list of `tf.Operation`. Args: ops: can be an iterable of `tf.Operation`, a `tf.Graph` or a single operation. check_graph: if `True` check if all the operations belong to the same graph. allow_graph: if `False` a `tf.Graph` cannot be converted. ignore_ts: if True, silently ignore `tf.Tensor`. Returns: A newly created list of `tf.Operation`. Raises: TypeError: if ops cannot be converted to a list of `tf.Operation` or, if `check_graph` is `True`, if all the ops do not belong to the same graph. """ if isinstance(ops, tf_ops.Graph): if allow_graph: return ops.get_operations() else: raise TypeError("allow_graph is False: cannot convert a tf.Graph.") else: if not is_iterable(ops): ops = [ops] if not ops: return [] if check_graph: check_types = None if ignore_ts else tf_ops.Operation get_unique_graph(ops, check_types=check_types) return [op for op in ops if isinstance(op, tf_ops.Operation)] # TODO(fkp): move this function in tf.Graph? def get_tensors(graph): """get all the tensors which are input or output of an op in the graph. Args: graph: a `tf.Graph`. Returns: A list of `tf.Tensor`. Raises: TypeError: if graph is not a `tf.Graph`. """ if not isinstance(graph, tf_ops.Graph): raise TypeError("Expected a graph, got: {}".format(type(graph))) ts = [] for op in graph.get_operations(): ts += op.outputs return ts def make_list_of_t(ts, check_graph=True, allow_graph=True, ignore_ops=False): """Convert ts to a list of `tf.Tensor`. Args: ts: can be an iterable of `tf.Tensor`, a `tf.Graph` or a single tensor. check_graph: if `True` check if all the tensors belong to the same graph. allow_graph: if `False` a `tf.Graph` cannot be converted. ignore_ops: if `True`, silently ignore `tf.Operation`. Returns: A newly created list of `tf.Tensor`. Raises: TypeError: if `ts` cannot be converted to a list of `tf.Tensor` or, if `check_graph` is `True`, if all the ops do not belong to the same graph. """ if isinstance(ts, tf_ops.Graph): if allow_graph: return get_tensors(ts) else: raise TypeError("allow_graph is False: cannot convert a tf.Graph.") else: if not is_iterable(ts): ts = [ts] if not ts: return [] if check_graph: check_types = None if ignore_ops else tf_ops.Tensor get_unique_graph(ts, check_types=check_types) return [t for t in ts if isinstance(t, tf_ops.Tensor)] def get_generating_ops(ts): """Return all the generating ops of the tensors in `ts`. Args: ts: a list of `tf.Tensor` Returns: A list of all the generating `tf.Operation` of the tensors in `ts`. Raises: TypeError: if `ts` cannot be converted to a list of `tf.Tensor`. """ ts = make_list_of_t(ts, allow_graph=False) return [t.op for t in ts] def get_consuming_ops(ts): """Return all the consuming ops of the tensors in ts. Args: ts: a list of `tf.Tensor` Returns: A list of all the consuming `tf.Operation` of the tensors in `ts`. Raises: TypeError: if ts cannot be converted to a list of `tf.Tensor`. """ ts = make_list_of_t(ts, allow_graph=False) ops = [] for t in ts: for op in t.consumers(): if op not in ops: ops.append(op) return ops class ControlOutputs(object): """The control outputs topology.""" def __init__(self, graph): """Create a dictionary of control-output dependencies. Args: graph: a `tf.Graph`. Returns: A dictionary where a key is a `tf.Operation` instance and the corresponding value is a list of all the ops which have the key as one of their control-input dependencies. Raises: TypeError: graph is not a `tf.Graph`. """ if not isinstance(graph, tf_ops.Graph): raise TypeError("Expected a tf.Graph, got: {}".format(type(graph))) self._control_outputs = {} self._graph = graph self._version = None self._build() def update(self): """Update the control outputs if the graph has changed.""" if self._version != self._graph.version: self._build() return self def _build(self): """Build the control outputs dictionary.""" self._control_outputs.clear() ops = self._graph.get_operations() for op in ops: for control_input in op.control_inputs: if control_input not in self._control_outputs: self._control_outputs[control_input] = [] if op not in self._control_outputs[control_input]: self._control_outputs[control_input].append(op) self._version = self._graph.version def get_all(self): return self._control_outputs def get(self, op): """return the control outputs of op.""" if op in self._control_outputs: return self._control_outputs[op] else: return () @property def graph(self): return self._graph def scope_finalize(scope): if scope and scope[-1] != "/": scope += "/" return scope def scope_dirname(scope): slash = scope.rfind("/") if slash == -1: return "" return scope[:slash + 1] def scope_basename(scope): slash = scope.rfind("/") if slash == -1: return scope return scope[slash + 1:] def placeholder_name(t=None, scope=None, prefix=_DEFAULT_PLACEHOLDER_PREFIX): """Create placeholder name for the graph editor. Args: t: optional tensor on which the placeholder operation's name will be based on scope: absolute scope with which to prefix the placeholder's name. None means that the scope of t is preserved. "" means the root scope. prefix: placeholder name prefix. Returns: A new placeholder name prefixed by "geph". Note that "geph" stands for Graph Editor PlaceHolder. This convention allows to quickly identify the placeholder generated by the Graph Editor. Raises: TypeError: if t is not None or a tf.Tensor. """ if scope is not None: scope = scope_finalize(scope) if t is not None: if not isinstance(t, tf_ops.Tensor): raise TypeError("Expected a tf.Tenfor, got: {}".format(type(t))) op_dirname = scope_dirname(t.op.name) op_basename = scope_basename(t.op.name) if scope is None: scope = op_dirname if op_basename.startswith("{}__".format(prefix)): ph_name = op_basename else: ph_name = "{}__{}_{}".format(prefix, op_basename, t.value_index) return scope + ph_name else: if scope is None: scope = "" return "{}{}".format(scope, prefix) def make_placeholder_from_tensor(t, scope=None, prefix=_DEFAULT_PLACEHOLDER_PREFIX): """Create a `tf.compat.v1.placeholder` for the Graph Editor. Note that the correct graph scope must be set by the calling function. Args: t: a `tf.Tensor` whose name will be used to create the placeholder (see function placeholder_name). scope: absolute scope within which to create the placeholder. None means that the scope of `t` is preserved. `""` means the root scope. prefix: placeholder name prefix. Returns: A newly created `tf.compat.v1.placeholder`. Raises: TypeError: if `t` is not `None` or a `tf.Tensor`. """ return tf_array_ops.placeholder( dtype=t.dtype, shape=t.get_shape(), name=placeholder_name(t, scope=scope, prefix=prefix)) def make_placeholder_from_dtype_and_shape(dtype, shape=None, scope=None, prefix=_DEFAULT_PLACEHOLDER_PREFIX): """Create a tf.compat.v1.placeholder for the Graph Editor. Note that the correct graph scope must be set by the calling function. The placeholder is named using the function placeholder_name (with no tensor argument). Args: dtype: the tensor type. shape: the tensor shape (optional). scope: absolute scope within which to create the placeholder. None means that the scope of t is preserved. "" means the root scope. prefix: placeholder name prefix. Returns: A newly created tf.placeholder. """ return tf_array_ops.placeholder( dtype=dtype, shape=shape, name=placeholder_name(scope=scope, prefix=prefix)) _INTERNAL_VARIABLE_RE = re.compile(r"^__\w+__$") def get_predefined_collection_names(): """Return all the predefined collection names.""" return [getattr(tf_ops.GraphKeys, key) for key in dir(tf_ops.GraphKeys) if not _INTERNAL_VARIABLE_RE.match(key)] def find_corresponding_elem(target, dst_graph, dst_scope="", src_scope=""): """Find corresponding op/tensor in a different graph. Args: target: A `tf.Tensor` or a `tf.Operation` belonging to the original graph. dst_graph: The graph in which the corresponding graph element must be found. dst_scope: A scope which is prepended to the name to look for. src_scope: A scope which is removed from the original of `target` name. Returns: The corresponding tf.Tensor` or a `tf.Operation`. Raises: ValueError: if `src_name` does not start with `src_scope`. TypeError: if `target` is not a `tf.Tensor` or a `tf.Operation` KeyError: If the corresponding graph element cannot be found. """ src_name = target.name if src_scope: src_scope = scope_finalize(src_scope) if not src_name.startswidth(src_scope): raise ValueError("{} does not start with {}".format(src_name, src_scope)) src_name = src_name[len(src_scope):] dst_name = src_name if dst_scope: dst_scope = scope_finalize(dst_scope) dst_name = dst_scope + dst_name if isinstance(target, tf_ops.Tensor): return dst_graph.get_tensor_by_name(dst_name) if isinstance(target, tf_ops.Operation): return dst_graph.get_operation_by_name(dst_name) raise TypeError("Expected tf.Tensor or tf.Operation, got: {}", type(target)) def find_corresponding(targets, dst_graph, dst_scope="", src_scope=""): """Find corresponding ops/tensors in a different graph. `targets` is a Python tree, that is, a nested structure of iterable (list, tupple, dictionary) whose leaves are instances of `tf.Tensor` or `tf.Operation` Args: targets: A Python tree containing `tf.Tensor` or `tf.Operation` belonging to the original graph. dst_graph: The graph in which the corresponding graph element must be found. dst_scope: A scope which is prepended to the name to look for. src_scope: A scope which is removed from the original of `top` name. Returns: A Python tree containin the corresponding tf.Tensor` or a `tf.Operation`. Raises: ValueError: if `src_name` does not start with `src_scope`. TypeError: if `top` is not a `tf.Tensor` or a `tf.Operation` KeyError: If the corresponding graph element cannot be found. """ def func(top): return find_corresponding_elem(top, dst_graph, dst_scope, src_scope) return transform_tree(targets, func)
tensorflow-master
tensorflow/contrib/graph_editor/util.py
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """TensorFlow Graph Editor. See the [Graph Editor](https://tensorflow.org/api_guides/python/contrib.graph_editor) guide. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function # pylint: disable=wildcard-import from tensorflow.contrib.graph_editor.edit import * from tensorflow.contrib.graph_editor.reroute import * from tensorflow.contrib.graph_editor.select import * from tensorflow.contrib.graph_editor.subgraph import * from tensorflow.contrib.graph_editor.transform import * from tensorflow.contrib.graph_editor.util import * # pylint: enable=wildcard-import # some useful aliases # pylint: disable=g-bad-import-order from tensorflow.contrib.graph_editor import subgraph as _subgraph from tensorflow.contrib.graph_editor import util as _util # pylint: enable=g-bad-import-order ph = _util.make_placeholder_from_dtype_and_shape sgv = _subgraph.make_view sgv_scope = _subgraph.make_view_from_scope del absolute_import del division del print_function
tensorflow-master
tensorflow/contrib/graph_editor/__init__.py
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Various function for graph editing.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.contrib.graph_editor import reroute from tensorflow.contrib.graph_editor import select from tensorflow.contrib.graph_editor import subgraph from tensorflow.contrib.graph_editor import util from tensorflow.python.ops import array_ops as tf_array_ops __all__ = [ "detach_control_inputs", "detach_control_outputs", "detach_inputs", "detach_outputs", "detach", "connect", "bypass", ] def detach_control_inputs(sgv): """Detach all the external control inputs of the subgraph sgv. Args: sgv: the subgraph view to be detached. This argument is converted to a subgraph using the same rules as the function subgraph.make_view. """ sgv = subgraph.make_view(sgv) for op in sgv.ops: cops = [cop for cop in op.control_inputs if cop not in sgv.ops] reroute.remove_control_inputs(op, cops) def detach_control_outputs(sgv, control_outputs): """Detach all the external control outputs of the subgraph sgv. Args: sgv: the subgraph view to be detached. This argument is converted to a subgraph using the same rules as the function subgraph.make_view. control_outputs: a util.ControlOutputs instance. """ if not isinstance(control_outputs, util.ControlOutputs): raise TypeError("Expected a util.ControlOutputs, got: {}", type(control_outputs)) control_outputs.update() sgv = subgraph.make_view(sgv) for op in sgv.ops: for cop in control_outputs.get(op): if cop not in sgv.ops: reroute.remove_control_inputs(cop, op) def detach_inputs(sgv, control_inputs=False): """Detach the inputs of a subgraph view. Args: sgv: the subgraph view to be detached. This argument is converted to a subgraph using the same rules as the function subgraph.make_view. Note that sgv is modified in place. control_inputs: if True control_inputs are also detached. Returns: A tuple `(sgv, input_placeholders)` where `sgv` is a new subgraph view of the detached subgraph; `input_placeholders` is a list of the created input placeholders. Raises: StandardError: if sgv cannot be converted to a SubGraphView using the same rules than the function subgraph.make_view. """ sgv = subgraph.make_view(sgv) with sgv.graph.as_default(): input_placeholders = [ tf_array_ops.placeholder( dtype=input_t.dtype, name=util.placeholder_name(input_t)) for input_t in sgv.inputs ] reroute.swap_inputs(sgv, input_placeholders) if control_inputs: detach_control_inputs(sgv) return sgv, input_placeholders def detach_outputs(sgv, control_outputs=None): """Detach the output of a subgraph view. Args: sgv: the subgraph view to be detached. This argument is converted to a subgraph using the same rules as the function subgraph.make_view. Note that sgv is modified in place. control_outputs: a util.ControlOutputs instance or None. If not None the control outputs are also detached. Returns: A tuple `(sgv, output_placeholders)` where `sgv` is a new subgraph view of the detached subgraph; `output_placeholders` is a list of the created output placeholders. Raises: StandardError: if sgv cannot be converted to a SubGraphView using the same rules than the function subgraph.make_view. """ sgv = subgraph.make_view(sgv) # only select outputs with consumers sgv_ = sgv.remap_outputs([output_id for output_id, output_t in enumerate(sgv.outputs) if output_t.consumers()]) # create consumer subgraph and remap consumers_sgv = subgraph.SubGraphView(sgv_.consumers()) consumers_sgv = consumers_sgv.remap_inputs( [input_id for input_id, input_t in enumerate(consumers_sgv.inputs) if input_t in sgv_.outputs]) with sgv_.graph.as_default(): output_placeholders = [ util.make_placeholder_from_tensor(input_t) for input_t in consumers_sgv.inputs ] reroute.swap_outputs(sgv_, output_placeholders) if control_outputs is not None: detach_control_outputs(sgv_, control_outputs) return sgv_, output_placeholders def detach(sgv, control_inputs=False, control_outputs=None, control_ios=None): """Detach both the inputs and the outputs of a subgraph view. Args: sgv: the subgraph view to be detached. This argument is converted to a subgraph using the same rules as the function subgraph.make_view. Note that sgv is modified in place. control_inputs: A boolean indicating whether control inputs are enabled. control_outputs: An instance of util.ControlOutputs or None. If not None, control outputs are enabled. control_ios: An instance of util.ControlOutputs or None. If not None, both control inputs and control outputs are enabled. This is equivalent to set control_inputs to True and control_outputs to the util.ControlOutputs instance. Returns: A tuple `(sgv, detached_inputs, detached_outputs)` where: `sgv` is a new subgraph view of the detached subgraph; `detach_inputs` is a list of the created input placeholders; `detach_outputs` is a list of the created output placeholders. Raises: StandardError: if sgv cannot be converted to a SubGraphView using the same rules than the function subgraph.make_view. """ control_inputs, control_outputs = select.check_cios(control_inputs, control_outputs, control_ios) _, detached_inputs = detach_inputs(sgv, control_inputs) _, detached_outputs = detach_outputs(sgv, control_outputs) return sgv, detached_inputs, detached_outputs def connect(sgv0, sgv1, disconnect_first=False): """Connect the outputs of sgv0 to the inputs of sgv1. Args: sgv0: the first subgraph to have its outputs swapped. This argument is converted to a subgraph using the same rules as the function subgraph.make_view. Note that sgv0 is modified in place. sgv1: the second subgraph to have its outputs swapped. This argument is converted to a subgraph using the same rules as the function subgraph.make_view. Note that sgv1 is modified in place. disconnect_first: if True the current outputs of sgv0 are disconnected. Returns: A tuple `(sgv0, sgv1)` of the now connected subgraphs. Raises: StandardError: if sgv0 or sgv1 cannot be converted to a SubGraphView using the same rules than the function subgraph.make_view. """ sgv0 = subgraph.make_view(sgv0) sgv1 = subgraph.make_view(sgv1) util.check_graphs(sgv0, sgv1) if disconnect_first: detach_outputs(sgv0) sgv0_outputs = subgraph.SubGraphView(passthrough_ts=sgv0.outputs) reroute.reroute_inputs(sgv0_outputs, sgv1) return sgv0, sgv1 def bypass(sgv): """Bypass the given subgraph by connecting its inputs to its outputs. Args: sgv: the subgraph view to be bypassed. This argument is converted to a subgraph using the same rules than the function subgraph.make_view. Note that sgv is modified in place. Returns: A tuple `(sgv, detached_inputs)` where: `sgv` is a new subgraph view of the bypassed subgraph; `detached_inputs` is a list of the created input placeholders. Raises: StandardError: if sgv cannot be converted to a SubGraphView using the same rules than the function subgraph.make_view. """ # TODO(fkp): allows to plug sgv.inputs to individual sgv.outputs consumers sgv = subgraph.make_view(sgv) sgv_inputs = list(sgv.inputs) sgv, detached_inputs = detach_inputs(sgv) reroute.reroute_ts(sgv_inputs, sgv.outputs) return sgv, detached_inputs
tensorflow-master
tensorflow/contrib/graph_editor/edit.py
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Class to transform an subgraph into another. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from copy import deepcopy from functools import partial from six import iteritems from six import string_types from six import StringIO from tensorflow.contrib.graph_editor import reroute from tensorflow.contrib.graph_editor import select from tensorflow.contrib.graph_editor import subgraph from tensorflow.contrib.graph_editor import util from tensorflow.python.framework import ops as tf_ops from tensorflow.python.platform import tf_logging as logging __all__ = [ "replace_t_with_placeholder_handler", "keep_t_if_possible_handler", "assign_renamed_collections_handler", "transform_op_if_inside_handler", "copy_op_handler", "Transformer", "TransformerInfo", "copy", "copy_with_input_replacements", "graph_replace", ] def replace_t_with_placeholder_handler(info, t): """Transform a tensor into a placeholder tensor. This handler is typically used to transform a subgraph input tensor into a placeholder. Args: info: Transform._TmpInfo instance. t: tensor whose input must be transformed into a place holder. Returns: The tensor generated by the newly created place holder. """ with info.graph_.as_default(): t_ = util.make_placeholder_from_tensor(t, scope=info.scope_) return t_ def keep_t_if_possible_handler(info, t): """Transform a tensor into itself (identity) if possible. This handler transform a tensor into itself if the source and destination graph are the same. Otherwise it will create a placeholder. This handler is typically used to transform a hidden input tensors. Args: info: Transform._TmpInfo instance. t: tensor whose input must be transformed into a place holder. Returns: The tensor generated by the newly created place holder. """ if info.graph is info.graph_: return t else: return replace_t_with_placeholder_handler(info, t) def assign_renamed_collections_handler(info, elem, elem_): """Add the transformed elem to the (renamed) collections of elem. A collection is renamed only if is not a known key, as described in `tf.compat.v1.GraphKeys`. Args: info: Transform._TmpInfo instance. elem: the original element (`tf.Tensor` or `tf.Operation`) elem_: the transformed element """ known_collection_names = util.get_predefined_collection_names() for name, collection in iteritems(info.collections): if elem not in collection: continue if name in known_collection_names: transformed_name = name else: transformed_name = info.new_name(name) info.graph_.add_to_collection(transformed_name, elem_) def transform_op_if_inside_handler(info, op, keep_if_possible=True): """Transform an optional op only if it is inside the subgraph. This handler is typically use to handle original op: it is fine to keep them if they are inside the subgraph, otherwise they are just ignored. Args: info: Transform._TmpInfo instance. op: the optional op to transform (or ignore). keep_if_possible: re-attach to the original op if possible, that is, if the source graph and the destination graph are the same. Returns: The transformed op or None. """ if op in info.sgv.ops: return info.transformed_ops[op] else: if keep_if_possible and info.graph is info.graph_: return op else: return None def copy_op_handler(info, op, new_inputs, copy_shape=False, nodedef_fn=None): """Copy a `tf.Operation`. Args: info: Transform._TmpInfo instance. op: the `tf.Operation` to be copied. new_inputs: The new inputs for this op. copy_shape: also copy the shape of the tensor nodedef_fn: If provided, a function that will be run on the NodeDef and should return a mutated NodeDef before a new Operation is created. This is useful as certain features cannot be set on the Operation and must be modified in NodeDef. Returns: A `(op, op_outputs)` tuple containing the transformed op and its outputs. """ # The `new_inputs` was added to this function. For compatibility reason, # let's raise an error if `new_inputs` is a boolean. if isinstance(new_inputs, bool): raise TypeError("the `new_inputs` argument must be an iterable.") # pylint: disable=protected-access # Clone the node def: node_def_ = deepcopy(op.node_def) # Transform name: name_ = info.new_name(op.name) name_ = info.graph_.unique_name(name_) node_def_.name = name_ # Mutate NodeDef if requested: if nodedef_fn is not None: node_def_ = nodedef_fn(node_def_) # Copy the other inputs needed for initialization output_types_ = op._output_types[:] input_types_ = op._input_types[:] # Make a copy of the op_def too. # Its unique to every _type_ of Operation. op_def_ = deepcopy(op.op_def) # Initialize a new Operation instance op_ = tf_ops.Operation(node_def_, info.graph_, new_inputs, output_types_, [], input_types_, None, op_def_) # copy the shape over if copy_shape: for t, t_ in zip(op.outputs, op_.outputs): t_.set_shape(t.get_shape()) # Original op cannot be finalised here yet. Because some ops require this # attribute to exist, we will create a dummy original_op first and then # later finalise it with the actual original_op when all the ops have # been copied. # TODO(fkp): Stop worrying about _original_op and remove this code? if op._original_op: op_._original_op = op._original_op return op_, op_.outputs class TransformerInfo(object): """"Contains information about the result of a transform operation.""" def __init__(self, info): """Constructor. Args: info: an instance of Transformer._TmpInfo containing various internal information about the transform operation. """ self._graph = info.graph self._scope = info.scope self._graph_ = info.graph_ self._scope_ = info.scope_ self._transformed_ops = info.transformed_ops self._transformed_ts = info.transformed_ts def _get_transformed_map(self, top): """Return the correct container depending on the type of `top`.""" if isinstance(top, tf_ops.Operation): return self._transformed_ops elif isinstance(top, tf_ops.Tensor): return self._transformed_ts else: raise TypeError( "Expected a tf.Tensor or a tf.Operation, got a {}".format( type(top))) def _transformed_elem(self, original_top, missing_fn=None): """Return the transformed op/tensor corresponding to the original one. Args: original_top: the original tensor/operation. missing_fn: function handling the case where the counterpart cannot be found. By default, None is returned. Returns: the transformed tensor/operation (or None if no match is found). """ transformed_map = self._get_transformed_map(original_top) if isinstance(original_top, string_types): for original, transformed in iteritems(transformed_map): if original.name == original_top: return transformed return None if missing_fn is None else missing_fn(original_top) else: if original_top not in transformed_map: return None if missing_fn is None else missing_fn(original_top) return transformed_map[original_top] def _original_elem(self, transformed_top, missing_fn=None): """Return the original op/tensor corresponding to the transformed one. Args: transformed_top: the transformed tensor/operation. missing_fn: function handling the case where the counterpart cannot be found. By default, None is returned. Returns: the original tensor/operation (or None if no match is found). """ transformed_map = self._get_transformed_map(transformed_top) if isinstance(transformed_top, string_types): finder = lambda transformed: transformed.name == transformed_top else: finder = lambda transformed: transformed == transformed_top for original, transformed in iteritems(transformed_map): if finder(transformed): return original return None if missing_fn is None else missing_fn(transformed_top) def transformed(self, original, missing_fn=None): """Return the transformed op/tensor corresponding to the original one. Note that the output of this function mimics the hierarchy of its input argument `original`. Given an iterable, it returns a list. Given an operation or a tensor, it will return an operation or a tensor. Args: original: the original tensor/operation. missing_fn: function handling the case where the counterpart cannot be found. By default, None is returned. Returns: the transformed tensor/operation (or None if no match is found). """ transformed_elem = partial(self._transformed_elem, missing_fn=missing_fn) return util.transform_tree(original, transformed_elem) def original(self, transformed, missing_fn=None): """Return the original op/tensor corresponding to the transformed one. Note that the output of this function mimics the hierarchy of its input argument `transformed`. Given an iterable, it returns a list. Given an operation or a tensor, it will return an operation or a tensor. Args: transformed: the transformed tensor/operation. missing_fn: function handling the case where the counterpart cannot be found. By default, None is returned. Returns: the original tensor/operation (or None if no match is found). """ original_elem = partial(self._original_elem, missing_fn=missing_fn) return util.transform_tree(transformed, original_elem) def __str__(self): res = StringIO() print("Transform result info:", file=res) if self._graph == self._graph_: in_place_str = "" if self._scope_ else " IN-PLACE" print(" Within graph[{}]{}".format( id(self._graph), in_place_str), file=res) else: print(" graph[{}] => graph[{}]".format( id(self._graph), id(self._graph_)), file=res) if self._scope: print(" Relative to source scope: {}".format(self._scope), file=res) if self._scope_: print(" Scope destination: {}".format(self._scope_), file=res) print("Operations mapping:", file=res) for op, op_ in iteritems(self._transformed_ops): print(" {} => {}".format(op.name, op_.name), file=res) return res.getvalue() class _TmpInfo(object): """Transformer temporary data. An instance of this class holds all the information relevant to a call to a transformer instance (that is, a call to __call__). An instance is created for the life-time of the __call__ function and is passed as argument to the handlers. """ def __init__(self, sgv, dst_graph, dst_scope, src_scope): self.sgv = sgv self.sgv_inputs_set = frozenset(sgv.inputs) self.ops = frozenset(sgv.ops) self.control_outputs = util.ControlOutputs(sgv.graph) self.graph = sgv.graph self.scope = src_scope self.graph_ = dst_graph self.scope_ = dst_scope self.transformed_ops = {} self.transformed_ts = {} self.collections = dict((key, self.graph.get_collection(key)) for key in self.graph.get_all_collection_keys()) self.cyclic_ops = [] self.transform_original_op_handler = transform_op_if_inside_handler # The graph is transformed op by op, in the same order the original ops # were created. However, this is sometimes not possible due to cycles # (i.e. while loops). So when the transformer creates a new op whose # inputs do not exist yet, temporary placeholders are created and stored # in this `tmp_cyclic_ts` container. During a second pass, # those temporary tensors are replaced by the proper transformed tensors # (see the function `_finalize_cycles`). self.tmp_cyclic_ts = [] def new_name(self, name): """Compute a destination name from a source name. Args: name: the name to be "transformed". Returns: The transformed name. Raises: ValueError: if the source scope is used (that is, not an empty string) and the source name does not belong to the source scope. """ scope = self.scope if not name.startswith(scope): raise ValueError("{} does not belong to source scope: {}.".format( name, scope)) rel_name = name[len(scope):] name_ = self.scope_ + rel_name return name_ class Transformer(object): """Transform a subgraph into another one. By default, the constructor create a transform which copy a subgraph and replaces inputs with placeholders. This behavior can be modified by changing the handlers. """ def __init__(self): """Transformer constructor. The following members can be modified: transform_op_handler: handle the transformation of a `tf.Operation`. This handler defaults to a simple copy. assign_collections_handler: handle the assignment of collections. This handler defaults to assigning new collections created under the given name-scope. transform_external_input_handler: handle the transform of the inputs to the given subgraph. This handler defaults to creating placeholders instead of the ops just before the input tensors of the subgraph. transform_external_hidden_input_handler: handle the transform of the hidden inputs of the subgraph, that is, the inputs which are not listed in sgv.inputs. This handler defaults to a transform which keep the same input if the source and destination graphs are the same, otherwise use placeholders. transform_original_op_handler: handle the transform of original_op. This handler defaults to transforming original_op only if they are in the subgraph, otherwise they are ignored. """ # handlers self.transform_op_handler = copy_op_handler self.transform_control_input_handler = transform_op_if_inside_handler self.assign_collections_handler = assign_renamed_collections_handler self.transform_external_input_handler = replace_t_with_placeholder_handler self.transform_external_hidden_input_handler = keep_t_if_possible_handler self.transform_original_op_handler = transform_op_if_inside_handler def __call__(self, sgv, dst_graph, dst_scope, src_scope="", reuse_dst_scope=False): """Execute the transformation. Args: sgv: the source subgraph-view. dst_graph: the destination graph. dst_scope: the destination scope. src_scope: the source scope, which specify the path from which the relative path of the transformed nodes are computed. For instance, if src_scope is a/ and dst_scoped is b/, then the node a/x/y will have a relative path of x/y and will be transformed into b/x/y. reuse_dst_scope: if True the dst_scope is re-used if it already exists. Otherwise, the scope is given a unique name based on the one given by appending an underscore followed by a digit (default). Returns: A tuple `(sgv, info)` where: `sgv` is the transformed subgraph view; `info` is an instance of TransformerInfo containing information about the transform, including mapping between original and transformed tensors and operations. Raises: ValueError: if the arguments are invalid. """ sgv = subgraph.make_view(sgv) if not isinstance(dst_graph, tf_ops.Graph): raise TypeError("Expected a tf.Graph, got: {}".format(type(dst_graph))) src_scope = util.scope_finalize(src_scope) dst_scope = util.scope_finalize(dst_scope) # Potentially create new scope if reuse_dst_scope is False if dst_scope and not reuse_dst_scope: dst_scope = util.scope_finalize(dst_graph.unique_name(dst_scope[:-1])) # Create temporary info used during this transform call info = _TmpInfo(sgv, dst_graph, dst_scope, src_scope) self._copy_ops(info) self._finalize_cycles(info) self._connect_control_inputs(info) # Compute information about the transformation res_info = TransformerInfo(info) sgv_ = self._transform_sgv(info, sgv) return sgv_, res_info def _copy_ops(self, info): """Copy ops without connecting them.""" sorted_ops = sorted(info.sgv.ops, key=lambda op: op._id) # pylint: disable=protected-access for op in sorted_ops: new_inputs = [self._transformed_t(info, t, op) for t in op.inputs] op_, op_outputs_ = self.transform_op_handler(info, op, new_inputs) if op is op_: raise ValueError("In-place transformation not allowed.") # Process op. info.transformed_ops[op] = op_ self.assign_collections_handler(info, op, op_) # Process output tensors. for op_output, op_output_ in zip(op.outputs, op_outputs_): info.transformed_ts[op_output] = op_output_ self.assign_collections_handler(info, op_output, op_output_) def _finalize_cycles(self, info): """Reconnects the cyclic tensors.""" for t, tmp_t_, consumer_op in info.tmp_cyclic_ts: if t not in info.transformed_ts: raise ValueError("The tensor {} should be transformed by now.".format( t.name)) if consumer_op not in info.transformed_ops: raise ValueError("The op {} should be transformed by now.".format( consumer_op.name)) t_ = info.transformed_ts[t] consumer_op_ = info.transformed_ops[consumer_op] t_index_ = list(consumer_op_.inputs).index(tmp_t_) consumer_op_._update_input(t_index_, t_) # pylint: disable=protected-access def _connect_control_inputs(self, info): """Connect the previously copied ops.""" for op in info.sgv.ops: logging.debug("Connecting control inputs of op: %s", op.name) op_ = info.transformed_ops[op] # Finalize original op. # TODO(fkp): Stop worrying about _original_op and remove this code? # pylint: disable=protected-access if op._original_op: original_op = self.transform_original_op_handler(info, op._original_op) if original_op is None: logging.debug("Could not find original op for: %s", op_.name) else: op_._original_op = original_op # pylint: enable=protected-access # Finalize control inputs: control_inputs_ = [self.transform_control_input_handler(info, ci) for ci in op.control_inputs] control_inputs_ = [ci for ci in control_inputs_ if ci is not None] reroute.add_control_inputs(op_, control_inputs_) def _transform_sgv(self, info, sgv): """Transform a subgraph view. For convenience, a transform operation returns a subgraph view of the transformed graph. Args: info: Temporary information for this transorfm call. sgv: the subgraph to be transformed. Returns: The transformed subgraph. """ ops_ = [op_ for _, op_ in iteritems(info.transformed_ops)] sgv_ = subgraph.SubGraphView(ops_) sgv_inputs_ = sgv_.inputs sgv_outputs_ = sgv_.outputs # re-order inputs input_map_ = [] for input_t in sgv.inputs: if input_t not in info.transformed_ts: continue input_t_ = info.transformed_ts[input_t] if input_t_ not in sgv_inputs_: continue input_t_index_ = sgv_.input_index(input_t_) input_map_.append(input_t_index_) # re-order outputs output_map_ = [] for output_t in sgv.outputs: if output_t not in info.transformed_ts: continue output_t_ = info.transformed_ts[output_t] if output_t_ not in sgv_outputs_: continue output_t_index_ = sgv_.output_index(output_t_) output_map_.append(output_t_index_) return sgv_.remap(input_map_, output_map_) def _transformed_t(self, info, t, consumer_op): """Return tre transformed tensor of `t`.""" if t in info.transformed_ts: # If op is in the subgraph, just return its transformed counterpart. return info.transformed_ts[t] if t in info.sgv_inputs_set: # `t` is an input of the subgraph. return self.transform_external_input_handler(info, t) elif t.op in info.ops: # `t` is an internal tensor but is not transformed yet because it # belongs to a graph cycle. logging.debug("Cyclic tensor: t.name = %s", t.name) # Try to find an existing tensor we can use for now, # otherwise create one. We'll rewire this later. if consumer_op.type == "Merge": first_input = consumer_op.inputs[0] tmp_t_ = self._transformed_t(info, first_input, consumer_op) elif t.op.type == "Enter": enter_input = t.op.inputs[0] tmp_t_ = self._transformed_t(info, enter_input, consumer_op) else: with info.graph_.as_default(): tmp_t_ = util.make_placeholder_from_tensor(t, scope=info.scope_, prefix="geph_tmp") logging.debug("Created temporary placeholder: %s.", tmp_t_.name) # Register as temporary and return. info.tmp_cyclic_ts.append((t, tmp_t_, consumer_op)) return tmp_t_ else: # `t` is a hidden input of the subgraph. return self.transform_external_hidden_input_handler(info, t) def copy(sgv, dst_graph=None, dst_scope="", src_scope="", reuse_dst_scope=False): """Copy a subgraph. Args: sgv: the source subgraph-view. This argument is converted to a subgraph using the same rules than the function subgraph.make_view. dst_graph: the destination graph. dst_scope: the destination scope. src_scope: the source scope. reuse_dst_scope: if True the dst_scope is re-used if it already exists. Otherwise, the scope is given a unique name based on the one given by appending an underscore followed by a digit (default). Returns: A tuple `(sgv, info)` where: `sgv` is the transformed subgraph view; `info` is an instance of TransformerInfo containing information about the transform, including mapping between original and transformed tensors and operations. Raises: TypeError: if `dst_graph` is not a `tf.Graph`. StandardError: if sgv cannot be converted to a SubGraphView using the same rules than the function subgraph.make_view. """ sgv = subgraph.make_view(sgv) if dst_graph is None: dst_graph = sgv.graph if not isinstance(dst_graph, tf_ops.Graph): raise TypeError("Expected a tf.Graph, got: {}".format(type(dst_graph))) copier = Transformer() return copier( sgv, dst_graph, dst_scope, src_scope, reuse_dst_scope=reuse_dst_scope) def copy_with_input_replacements(sgv, replacement_ts, dst_graph=None, dst_scope="", src_scope="", reuse_dst_scope=False): """Copy a subgraph, replacing some of its inputs. Note a replacement only happens if the tensor to be replaced is an input of the given subgraph. The inputs of a subgraph can be queried using sgv.inputs. Args: sgv: the source subgraph-view. This argument is converted to a subgraph using the same rules as the function subgraph.make_view. replacement_ts: dictionary mapping from original tensors to the replaced one. dst_graph: the destination graph. dst_scope: the destination scope. src_scope: the source scope. reuse_dst_scope: if True the dst_scope is re-used if it already exists. Otherwise, the scope is given a unique name based on the one given by appending an underscore followed by a digit (default). Returns: A tuple `(sgv, info)` where: `sgv` is the transformed subgraph view; `info` is an instance of TransformerInfo containing information about the transform, including mapping between original and transformed tensors and operations. Raises: TypeError: if dst_graph is not a tf.Graph. StandardError: if sgv cannot be converted to a SubGraphView using the same rules as the function subgraph.make_view. """ sgv = subgraph.make_view(sgv) if dst_graph is None: dst_graph = sgv.graph if not isinstance(dst_graph, tf_ops.Graph): raise TypeError("Expected a tf.Graph, got: {}".format(type(dst_graph))) copier = Transformer() # Replace tensor if possible. def replace_t_with_replacement_handler(info, t): if t in replacement_ts: return replacement_ts[t] else: return keep_t_if_possible_handler(info, t) copier.transform_external_input_handler = replace_t_with_replacement_handler return copier( sgv, dst_graph, dst_scope, src_scope, reuse_dst_scope=reuse_dst_scope) def _add_control_flow_ops(ops, control_ios): """Complete `ops` so that the transformed graph is valid. Partially copying a graph can lead to a malformed graph. For instance, copying half of a while construct is likely to result in an invalid graph. This function attempts to add missing ops so that the transformation result in a valid graph. Args: ops: list of ops (modifed in-place). control_ios: object created by a call to `util.ControlOutputs`. """ # Find while contexts. control_flow_contexts = set() for op in ops: cfc = op._control_flow_context # pylint: disable=protected-access if cfc: control_flow_contexts.add(cfc) # Find new ops. new_ops = [] for cfc in control_flow_contexts: if cfc.IsWhileContext(): new_ops += select.get_walks_intersection_ops( [enter_t.op for enter_t in cfc.loop_enters], [exit_t.op for exit_t in cfc.loop_exits], control_ios=control_ios) # Add new ops. new_ops_set = set(new_ops) ops_set = frozenset(ops) for op in new_ops_set: if op not in ops_set: ops.append(op) def graph_replace(target_ts, replacement_ts, dst_scope="", src_scope="", reuse_dst_scope=False): """Create a new graph which compute the targets from the replaced Tensors. Args: target_ts: a single tf.Tensor or an iterable of tf.Tensor. replacement_ts: dictionary mapping from original tensors to replaced tensors dst_scope: the destination scope. src_scope: the source scope. reuse_dst_scope: if True the dst_scope is re-used if it already exists. Otherwise, the scope is given a unique name based on the one given by appending an underscore followed by a digit (default). Returns: A single tf.Tensor or a list of target tf.Tensor, depending on the type of the input argument `target_ts`. The returned tensors are recomputed using the tensors from replacement_ts. Raises: ValueError: if the targets are not connected to replacement_ts. """ # Identify operations in the graph that will change. # Start forward walk at Tensors that will be replaced, and # backward walk at the target output Tensors. flatten_target_ts = util.flatten_tree(target_ts) # Construct the forward control dependencies edges so that # the get_walks_intersection_ops can also traverse the # control dependencies. graph = util.get_unique_graph(flatten_target_ts, check_types=(tf_ops.Tensor)) control_ios = util.ControlOutputs(graph) ops = select.get_walks_intersection_ops( list(replacement_ts), flatten_target_ts, control_ios=control_ios) if not ops: raise ValueError("Targets and replacements are not connected!") # Complete ops to avoid malformed control flow. # TODO(fkp): Consider moving this function deeper (in the transformer?). _add_control_flow_ops(ops, control_ios) # Create a copy of the relevant subgraph unused_sgv_, info = copy_with_input_replacements( ops, replacement_ts, None, dst_scope, src_scope, reuse_dst_scope) # Return the transformed targets but keep the original if the transformed # counterpart cannot be found missing_fn = lambda original_t: original_t return info.transformed(target_ts, missing_fn)
tensorflow-master
tensorflow/contrib/graph_editor/transform.py
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Various function for graph rerouting.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.contrib.graph_editor import subgraph as _subgraph from tensorflow.contrib.graph_editor import util as _util from tensorflow.python.framework import ops as _tf_ops from tensorflow.python.util.all_util import remove_undocumented _allowed_symbols = [ "swap_ts", "reroute_ts", "swap_inputs", "reroute_inputs", "swap_outputs", "reroute_outputs", "swap_ios", "reroute_ios", "remove_control_inputs", "add_control_inputs", ] def _check_ts_compatibility(ts0, ts1): """Make sure the shape and dtype of the two tensor's lists are compatible. Args: ts0: an object convertible to a list of `tf.Tensor`. ts1: an object convertible to a list of `tf.Tensor`. Raises: ValueError: if any pair of tensors (same index in ts0 and ts1) have a dtype or a shape which is not compatible. """ ts0 = _util.make_list_of_t(ts0) ts1 = _util.make_list_of_t(ts1) if len(ts0) != len(ts1): raise ValueError("ts0 and ts1 have different sizes: {} != {}".format( len(ts0), len(ts1))) for t0, t1 in zip(ts0, ts1): # check dtype dtype0, dtype1 = t0.dtype, t1.dtype if not dtype0.is_compatible_with(dtype1): raise ValueError("Dtypes {} and {} are not compatible.".format(dtype0, dtype1)) # check shape shape0, shape1 = t0.get_shape(), t1.get_shape() if not shape0.is_compatible_with(shape1): raise ValueError("Shapes {} and {} are not compatible.".format(shape0, shape1)) class _RerouteMode(object): """Enums for reroute's mode. swap: the end of tensors a and b are swapped. a2b: the end of the tensor a are also rerouted to the end of the tensor b (the end of b is left dangling). b2a: the end of the tensor b are also rerouted to the end of the tensor a (the end of a is left dangling). """ swap, a2b, b2a = range(3) @classmethod def check(cls, mode): """Check swap mode. Args: mode: an integer representing one of the modes. Returns: A tuple `(a2b, b2a)` boolean indicating what rerouting needs doing. Raises: ValueError: if mode is outside the enum range. """ if mode == cls.swap: return True, True elif mode == cls.b2a: return False, True elif mode == cls.a2b: return True, False else: raise ValueError("Unknown _RerouteMode: {}".format(mode)) def _reroute_t(t0, t1, consumers1, can_modify=None, cannot_modify=None): """Reroute the end of the tensors (t0,t1). Warning: this function is directly manipulating the internals of the `tf.Graph`. Args: t0: a tf.Tensor. t1: a tf.Tensor. consumers1: The consumers of t1 which needs to be rerouted. can_modify: iterable of operations which can be modified. Any operation outside within_ops will be left untouched by this function. cannot_modify: iterable of operations which cannot be modified. Any operation within cannot_modify will be left untouched by this function. Returns: The number of individual modifications made by the function. """ nb_update_inputs = 0 if can_modify is not None: consumers1 &= can_modify if cannot_modify is not None: consumers1 -= cannot_modify consumers1_indices = {} for consumer1 in consumers1: consumers1_indices[consumer1] = [i for i, t in enumerate(consumer1.inputs) if t is t1] for consumer1 in consumers1: for i in consumers1_indices[consumer1]: consumer1._update_input(i, t0) # pylint: disable=protected-access nb_update_inputs += 1 return nb_update_inputs def _reroute_ts(ts0, ts1, mode, can_modify=None, cannot_modify=None): """Reroute the end of the tensors in each pair (t0,t1) in ts0 x ts1. This function is the back-bone of the Graph-Editor. It is essentially a thin wrapper on top of the tf.Operation._update_input. Given a pair of tensor t0, t1 in ts0 x ts1, this function re-route the end of t0 and t1 in three possible ways: 1) The reroute mode is "a<->b" or "b<->a": the tensors' end are swapped. After this operation, the previous consumers of t0 are now consumers of t1 and vice-versa. 2) The reroute mode is "a->b": the tensors' end of t0 are re-routed to the tensors's end of t1 (which are left dangling). After this operation, the previous consumers of t0 are still consuming t0 but the previous consumers of t1 are not also consuming t0. The tensor t1 has no consumer. 3) The reroute mode is "b->a": this mode is the symmetric of the "a->b" mode. Note that this function is re-routing the end of two tensors, not the start. Re-routing the start of two tensors is not supported by this library. The reason for that is the following: TensorFlow, by design, creates a strong bond between an op and its output tensor. This Graph editor follows this design and treats an operation A and its generating tensors {t_i} as an entity which cannot be broken. In other words, an op cannot be detached from any of its output tensors, ever. But it is possible to detach an op from its input tensors, which is what this function concerns itself with. Warning: this function is directly manipulating the internals of the tf.Graph. Args: ts0: an object convertible to a list of `tf.Tensor`. ts1: an object convertible to a list of `tf.Tensor`. mode: what to do with those tensors: "a->b" or "b<->a" for swaping and "a->b" or "b->a" for one direction re-routing. can_modify: iterable of operations which can be modified. Any operation outside within_ops will be left untouched by this function. cannot_modify: iterable of operations which cannot be modified. Any operation within cannot_modify will be left untouched by this function. Returns: The number of individual modifications made by the function. Raises: TypeError: if `ts0` or `ts1` cannot be converted to a list of `tf.Tensor`. TypeError: if `can_modify` or `cannot_modify` is not `None` and cannot be converted to a list of `tf.Operation`. """ a2b, b2a = _RerouteMode.check(mode) ts0 = _util.make_list_of_t(ts0) ts1 = _util.make_list_of_t(ts1) _check_ts_compatibility(ts0, ts1) if cannot_modify is not None: cannot_modify = frozenset(_util.make_list_of_op(cannot_modify)) if can_modify is not None: can_modify = frozenset(_util.make_list_of_op(can_modify)) nb_update_inputs = 0 precomputed_consumers = [] # precompute consumers to avoid issue with repeated tensors: for t0, t1 in zip(ts0, ts1): consumers0 = set(t0.consumers()) consumers1 = set(t1.consumers()) precomputed_consumers.append((consumers0, consumers1)) for t0, t1, consumers in zip(ts0, ts1, precomputed_consumers): if t0 is t1: continue # Silently ignore identical tensors. consumers0, consumers1 = consumers if a2b: nb_update_inputs += _reroute_t(t0, t1, consumers1, can_modify, cannot_modify) if b2a: nb_update_inputs += _reroute_t(t1, t0, consumers0, can_modify, cannot_modify) return nb_update_inputs def swap_ts(ts0, ts1, can_modify=None, cannot_modify=None): """For each tensor's pair, swap the end of (t0,t1). B0 B1 B0 B1 | | => X A0 A1 A0 A1 Args: ts0: an object convertible to a list of `tf.Tensor`. ts1: an object convertible to a list of `tf.Tensor`. can_modify: iterable of operations which can be modified. Any operation outside within_ops will be left untouched by this function. cannot_modify: iterable of operations which cannot be modified. Any operation within cannot_modify will be left untouched by this function. Returns: The number of individual modifications made by the function. Raises: TypeError: if ts0 or ts1 cannot be converted to a list of tf.Tensor. TypeError: if can_modify or cannot_modify is not None and cannot be converted to a list of tf.Operation. """ return _reroute_ts(ts0, ts1, _RerouteMode.swap, can_modify, cannot_modify) def reroute_ts(ts0, ts1, can_modify=None, cannot_modify=None): """For each tensor's pair, replace the end of t1 by the end of t0. B0 B1 B0 B1 | | => |/ A0 A1 A0 A1 The end of the tensors in ts1 are left dangling. Args: ts0: an object convertible to a list of `tf.Tensor`. ts1: an object convertible to a list of `tf.Tensor`. can_modify: iterable of operations which can be modified. Any operation outside within_ops will be left untouched by this function. cannot_modify: iterable of operations which cannot be modified. Any operation within cannot_modify will be left untouched by this function. Returns: The number of individual modifications made by the function. Raises: TypeError: if ts0 or ts1 cannot be converted to a list of tf.Tensor. TypeError: if can_modify or cannot_modify is not None and cannot be converted to a list of tf.Operation. """ return _reroute_ts(ts0, ts1, _RerouteMode.a2b, can_modify, cannot_modify) def _reroute_sgv_remap(sgv0, sgv1, mode): """Remap in place the inputs of two subgraph views to mimic the reroute. This function is meant to used by reroute_inputs only. Args: sgv0: the first subgraph to have its inputs remapped. sgv1: the second subgraph to have its inputs remapped. mode: reroute mode, see _reroute_ts(...). Raises: TypeError: if svg0 or svg1 are not SubGraphView. ValueError: if sgv0 and sgv1 do not belong to the same graph. """ a2b, b2a = _RerouteMode.check(mode) if not isinstance(sgv0, _subgraph.SubGraphView): raise TypeError("Expected a SubGraphView, got {}".format(type(sgv0))) if not isinstance(sgv1, _subgraph.SubGraphView): raise TypeError("Expected a SubGraphView, got {}".format(type(sgv1))) _util.check_graphs(sgv0, sgv1) sgv0_ = sgv0.copy() sgv1_ = sgv1.copy() # pylint: disable=protected-access if a2b and b2a: (sgv0_._input_ts, sgv1_._input_ts) = (sgv1_._input_ts, sgv0_._input_ts) (sgv0_._passthrough_ts, sgv1_._passthrough_ts) = (sgv1_._passthrough_ts, sgv0_._passthrough_ts) elif a2b: sgv1_._input_ts = sgv0_._input_ts[:] sgv1_._passthrough_ts = sgv0_._passthrough_ts[:] elif b2a: sgv0_._input_ts = sgv1_._input_ts[:] sgv0_._passthrough_ts = sgv1_._passthrough_ts[:] # pylint: enable=protected-access # Update the passthrough outputs as well. def update_passthrough_outputs(a, b): # pylint: disable=protected-access for i, t in enumerate(b._output_ts): if t in a._passthrough_ts: ii = a._input_ts.index(t) b._output_ts[i] = b._input_ts[ii] # pylint: enable=protected-access if a2b: update_passthrough_outputs(sgv0_, sgv1_) if b2a: update_passthrough_outputs(sgv1_, sgv0_) # in-place # pylint: disable=protected-access sgv0._assign_from(sgv0_) sgv1._assign_from(sgv1_) # pylint: enable=protected-access def _reroute_sgv_inputs(sgv0, sgv1, mode): """Re-route all the inputs of two subgraphs. Args: sgv0: the first subgraph to have its inputs swapped. This argument is converted to a subgraph using the same rules than the function subgraph.make_view. sgv1: the second subgraph to have its inputs swapped. This argument is converted to a subgraph using the same rules than the function subgraph.make_view. mode: reroute mode, see _reroute_ts(...). Returns: A tuple `(sgv0, sgv1)` of subgraph views with their inputs swapped. Note that the function argument sgv0 and sgv1 are also modified in place. Raises: StandardError: if sgv0 or sgv1 cannot be converted to a SubGraphView using the same rules than the function subgraph.make_view. """ sgv0 = _subgraph.make_view(sgv0) sgv1 = _subgraph.make_view(sgv1) _util.check_graphs(sgv0, sgv1) can_modify = sgv0.ops + sgv1.ops # also allow consumers of passthrough to be modified: can_modify += _util.get_consuming_ops(sgv0.passthroughs) can_modify += _util.get_consuming_ops(sgv1.passthroughs) _reroute_ts(sgv0.inputs, sgv1.inputs, mode, can_modify=can_modify) _reroute_sgv_remap(sgv0, sgv1, mode) return sgv0, sgv1 def _reroute_sgv_outputs(sgv0, sgv1, mode): """Re-route all the outputs of two operations. Args: sgv0: the first subgraph to have its outputs swapped. This argument is converted to a subgraph using the same rules than the function subgraph.make_view. sgv1: the second subgraph to have its outputs swapped. This argument is converted to a subgraph using the same rules than the function subgraph.make_view. mode: reroute mode, see _reroute_ts(...). Returns: A tuple `(sgv0, sgv1)` of subgraph views with their outputs swapped. Note that the function argument sgv0 and sgv1 are also modified in place. Raises: StandardError: if sgv0 or sgv1 cannot be converted to a SubGraphView using the same rules than the function subgraph.make_view. """ sgv0 = _subgraph.make_view(sgv0) sgv1 = _subgraph.make_view(sgv1) _util.check_graphs(sgv0, sgv1) cannot_modify = sgv0.ops + sgv1.ops _reroute_ts(sgv0.outputs, sgv1.outputs, mode, cannot_modify=cannot_modify) return sgv0, sgv1 def _reroute_sgv(sgv0, sgv1, mode): """Re-route both the inputs and the outputs of the two subgraph views. This involves swapping all the inputs/outputs of the two subgraph views. Args: sgv0: the first subgraph to be swapped. This argument is converted to a subgraph using the same rules than the function subgraph.make_view. sgv1: the second subgraph to be swapped. This argument is converted to a subgraph using the same rules than the function subgraph.make_view. mode: reroute mode, see _reroute_ts(...). Returns: A tuple `(sgv0, sgv1)` of subgraph views with their outputs and inputs swapped. Note that the function argument sgv0 and sgv1 are also modified in place. Raises: StandardError: if sgv0 or sgv1 cannot be converted to a SubGraphView using the same rules than the function subgraph.make_view. """ _reroute_sgv_outputs(sgv0, sgv1, mode) _reroute_sgv_inputs(sgv0, sgv1, mode) return sgv0, sgv1 def swap_inputs(sgv0, sgv1): """Swap all the inputs of sgv0 and sgv1 (see reroute_inputs).""" return _reroute_sgv_inputs(sgv0, sgv1, _RerouteMode.swap) def reroute_inputs(sgv0, sgv1): """Re-route all the inputs of two subgraphs. Args: sgv0: the first subgraph to have its inputs swapped. This argument is converted to a subgraph using the same rules than the function subgraph.make_view. sgv1: the second subgraph to have its inputs swapped. This argument is converted to a subgraph using the same rules than the function subgraph.make_view. Returns: A tuple `(sgv0, sgv1)` of subgraph views with their inputs swapped. Note that the function argument sgv0 and sgv1 are also modified in place. Raises: StandardError: if sgv0 or sgv1 cannot be converted to a SubGraphView using the same rules than the function subgraph.make_view. """ return _reroute_sgv_inputs(sgv0, sgv1, _RerouteMode.a2b) def swap_outputs(sgv0, sgv1): """Swap all the outputs of sgv0 and sgv1 (see reroute_outputs).""" return _reroute_sgv_outputs(sgv0, sgv1, _RerouteMode.swap) def reroute_outputs(sgv0, sgv1): """Re-route all the outputs of two operations. Args: sgv0: the first subgraph to have its outputs swapped. This argument is converted to a subgraph using the same rules than the function subgraph.make_view. sgv1: the second subgraph to have its outputs swapped. This argument is converted to a subgraph using the same rules than the function subgraph.make_view. Returns: A tuple `(sgv0, sgv1)` of subgraph views with their outputs swapped. Note that the function argument sgv0 and sgv1 are also modified in place. Raises: StandardError: if sgv0 or sgv1 cannot be converted to a SubGraphView using the same rules than the function subgraph.make_view. """ return _reroute_sgv_outputs(sgv0, sgv1, _RerouteMode.a2b) def swap_ios(sgv0, sgv1): """Swap the inputs and outputs of sgv1 to sgv0 (see _reroute_sgv).""" return _reroute_sgv(sgv0, sgv1, _RerouteMode.swap) def reroute_ios(sgv0, sgv1): """Re-route the inputs and outputs of sgv0 to sgv1 (see _reroute_sgv).""" return _reroute_sgv(sgv0, sgv1, _RerouteMode.a2b) def remove_control_inputs(op, cops): """Remove the control inputs cops from co. Warning: this function is directly manipulating the internals of the `tf.Graph`. Args: op: a `tf.Operation` from which to remove the control inputs. cops: an object convertible to a list of `tf.Operation`. Raises: TypeError: if op is not a `tf.Operation`. ValueError: if any cop in cops is not a control input of op. """ if not isinstance(op, _tf_ops.Operation): raise TypeError("Expected a tf.Operation, got: {}", type(op)) cops = _util.make_list_of_op(cops, allow_graph=False) for cop in cops: if cop not in op.control_inputs: raise ValueError("{} is not a control_input of {}".format(op.name, cop.name)) control_inputs = [cop for cop in op.control_inputs if cop not in cops] # pylint: disable=protected-access op._remove_all_control_inputs() op._add_control_inputs(control_inputs) # pylint: enable=protected-access def add_control_inputs(op, cops): """Add the control inputs cops to op. Warning: this function is directly manipulating the internals of the tf.Graph. Args: op: a tf.Operation to which the control inputs are added. cops: an object convertible to a list of `tf.Operation`. Raises: TypeError: if op is not a tf.Operation ValueError: if any cop in cops is already a control input of op. """ if not isinstance(op, _tf_ops.Operation): raise TypeError("Expected a tf.Operation, got: {}", type(op)) cops = _util.make_list_of_op(cops, allow_graph=False) for cop in cops: if cop in op.control_inputs: raise ValueError("{} is already a control_input of {}".format(cop.name, op.name)) op._add_control_inputs(cops) # pylint: disable=protected-access remove_undocumented(__name__, _allowed_symbols)
tensorflow-master
tensorflow/contrib/graph_editor/reroute.py
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Various ways of selecting operations and tensors in a graph.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import re from six import iteritems from six import string_types from tensorflow.contrib.graph_editor import util from tensorflow.python.framework import ops as tf_ops __all__ = [ "can_be_regex", "make_regex", "filter_ts", "filter_ts_from_regex", "filter_ops", "filter_ops_from_regex", "get_name_scope_ops", "check_cios", "get_ops_ios", "compute_boundary_ts", "get_within_boundary_ops", "get_forward_walk_ops", "get_backward_walk_ops", "get_walks_intersection_ops", "get_walks_union_ops", "select_ops", "select_ts", "select_ops_and_ts", ] _RE_TYPE = type(re.compile("")) def can_be_regex(obj): """Return True if obj can be turned into a regular expression.""" return isinstance(obj, string_types + (_RE_TYPE,)) def make_regex(obj): """Return a compiled regular expression. Args: obj: a string or a regular expression. Returns: A compiled regular expression. Raises: ValueError: if obj could not be converted to a regular expression. """ if not can_be_regex(obj): raise ValueError("Expected a string or a regex, got: {}".format(type(obj))) if isinstance(obj, string_types): return re.compile(obj) else: return obj def _get_input_ts(ops): """Compute the list of unique input tensors of all the op in ops. Args: ops: an object convertible to a list of `tf.Operation`. Returns: The list of unique input tensors of all the op in ops. Raises: TypeError: if ops cannot be converted to a list of `tf.Operation`. """ ops = util.make_list_of_op(ops) ts = [] ts_set = set() for op in ops: for t in op.inputs: if t not in ts_set: ts.append(t) ts_set.add(t) return ts def _get_output_ts(ops): """Compute the list of unique output tensors of all the op in ops. Args: ops: an object convertible to a list of tf.Operation. Returns: The list of unique output tensors of all the op in ops. Raises: TypeError: if ops cannot be converted to a list of tf.Operation. """ ops = util.make_list_of_op(ops) ts = [] for op in ops: ts += op.outputs return ts def filter_ts(ops, positive_filter): """Get all the tensors which are input or output of an op in ops. Args: ops: an object convertible to a list of `tf.Operation`. positive_filter: a function deciding whether to keep a tensor or not. If `True`, all the tensors are returned. Returns: A list of `tf.Tensor`. Raises: TypeError: if ops cannot be converted to a list of `tf.Operation`. """ ops = util.make_list_of_op(ops) ts = _get_input_ts(ops) util.concatenate_unique(ts, _get_output_ts(ops)) if positive_filter is not True: ts = [t for t in ts if positive_filter(t)] return ts def filter_ts_from_regex(ops, regex): r"""Get all the tensors linked to ops that match the given regex. Args: ops: an object convertible to a list of tf.Operation. regex: a regular expression matching the tensors' name. For example, "^foo(/.*)?:\d+$" will match all the tensors in the "foo" scope. Returns: A list of tf.Tensor. Raises: TypeError: if ops cannot be converted to a list of tf.Operation. """ ops = util.make_list_of_op(ops) regex_obj = make_regex(regex) return filter_ts(ops, positive_filter=lambda op: regex_obj.search(op.name)) def filter_ops(ops, positive_filter): """Get the ops passing the given filter. Args: ops: an object convertible to a list of tf.Operation. positive_filter: a function deciding where to keep an operation or not. If True, all the operations are returned. Returns: A list of selected tf.Operation. Raises: TypeError: if ops cannot be converted to a list of tf.Operation. """ ops = util.make_list_of_op(ops) if positive_filter is not True: # pylint: disable=g-explicit-bool-comparison ops = [op for op in ops if positive_filter(op)] return ops def filter_ops_from_regex(ops, regex): """Get all the operations that match the given regex. Args: ops: an object convertible to a list of `tf.Operation`. regex: a regular expression matching the operation's name. For example, `"^foo(/.*)?$"` will match all the operations in the "foo" scope. Returns: A list of `tf.Operation`. Raises: TypeError: if ops cannot be converted to a list of `tf.Operation`. """ ops = util.make_list_of_op(ops) regex_obj = make_regex(regex) return filter_ops(ops, lambda op: regex_obj.search(op.name)) def get_name_scope_ops(ops, scope): """Get all the operations under the given scope path. Args: ops: an object convertible to a list of tf.Operation. scope: a scope path. Returns: A list of tf.Operation. Raises: TypeError: if ops cannot be converted to a list of tf.Operation. """ if scope and scope[-1] == "/": scope = scope[:-1] return filter_ops_from_regex(ops, "^{}(/.*)?$".format(scope)) def check_cios(control_inputs=False, control_outputs=None, control_ios=None): """Do various check on control_inputs and control_outputs. Args: control_inputs: A boolean indicating whether control inputs are enabled. control_outputs: An instance of util.ControlOutputs or None. If not None, control outputs are enabled. control_ios: An instance of util.ControlOutputs or None. If not None, both control inputs and control outputs are enabled. This is equivalent to set control_inputs to True and control_outputs to the util.ControlOutputs instance. Returns: A tuple `(control_inputs, control_outputs)` where: `control_inputs` is a boolean indicating whether to use control inputs. `control_outputs` is an instance of util.ControlOutputs or None Raises: ValueError: if control_inputs is an instance of util.ControlOutputs but control_outputs is not None TypeError: if control_outputs is not None and is not a util.ControlOutputs. """ if control_ios is not None: if not isinstance(control_ios, util.ControlOutputs): raise TypeError("Expected a util.ControlOutputs, got: {}".format( type(control_ios))) if control_outputs is not None: raise ValueError("control_outputs should be None when using control_ios.") control_inputs = True control_outputs = control_ios elif control_outputs is not None: if not isinstance(control_outputs, util.ControlOutputs): raise TypeError("Expected a util.ControlOutputs, got: {}".format( type(control_outputs))) if control_outputs is not None: control_outputs.update() return control_inputs, control_outputs def get_ops_ios(ops, control_inputs=False, control_outputs=None, control_ios=None): """Return all the `tf.Operation` which are connected to an op in ops. Args: ops: an object convertible to a list of `tf.Operation`. control_inputs: A boolean indicating whether control inputs are enabled. control_outputs: An instance of `util.ControlOutputs` or `None`. If not `None`, control outputs are enabled. control_ios: An instance of `util.ControlOutputs` or `None`. If not `None`, both control inputs and control outputs are enabled. This is equivalent to set `control_inputs` to `True` and `control_outputs` to the `util.ControlOutputs` instance. Returns: All the `tf.Operation` surrounding the given ops. Raises: TypeError: if `ops` cannot be converted to a list of `tf.Operation`. """ control_inputs, control_outputs = check_cios(control_inputs, control_outputs, control_ios) ops = util.make_list_of_op(ops) res = [] for op in ops: util.concatenate_unique(res, [t.op for t in op.inputs]) for t in op.outputs: util.concatenate_unique(res, t.consumers()) if control_outputs is not None: util.concatenate_unique(res, control_outputs.get(op)) if control_inputs: util.concatenate_unique(res, op.control_inputs) return res def compute_boundary_ts(ops): """Compute the tensors at the boundary of a set of ops. This function looks at all the tensors connected to the given ops (in/out) and classify them into three categories: 1) input tensors: tensors whose generating operation is not in ops. 2) output tensors: tensors whose consumer operations are not in ops 3) inside tensors: tensors which are neither input nor output tensors. Note that a tensor can be both an inside tensor and an output tensor if it is consumed by operations both outside and inside of `ops`. Args: ops: an object convertible to a list of tf.Operation. Returns: A tuple `(outside_input_ts, outside_output_ts, inside_ts)` where: `outside_input_ts` is a Python list of input tensors; `outside_output_ts` is a python list of output tensors; `inside_ts` is a python list of inside tensors. Since a tensor can be both an inside tensor and an output tensor, `outside_output_ts` and `inside_ts` might intersect. Raises: TypeError: if ops cannot be converted to a list of tf.Operation. """ ops = util.make_list_of_op(ops) input_ts = _get_input_ts(ops) output_ts = _get_output_ts(ops) output_ts_set = frozenset(output_ts) ops_set = frozenset(ops) # Compute inside tensors. inside_ts = [] only_inside_ts = [] for t in input_ts: # Skip if the input tensor is not also an output tensor. if t not in output_ts_set: continue # Mark as "inside". inside_ts.append(t) # Mark as "only inside" if the tensor is not both inside and output. consumers = frozenset(t.consumers()) if consumers - ops_set: continue only_inside_ts.append(t) inside_ts_set = frozenset(inside_ts) only_inside_ts_set = frozenset(only_inside_ts) outside_output_ts = [t for t in output_ts if t not in only_inside_ts_set] outside_input_ts = [t for t in input_ts if t not in inside_ts_set] return outside_input_ts, outside_output_ts, inside_ts def get_within_boundary_ops(ops, seed_ops, boundary_ops=(), inclusive=True, control_inputs=False, control_outputs=None, control_ios=None): """Return all the `tf.Operation` within the given boundary. Args: ops: an object convertible to a list of `tf.Operation`. those ops define the set in which to perform the operation (if a `tf.Graph` is given, it will be converted to the list of all its operations). seed_ops: the operations from which to start expanding. boundary_ops: the ops forming the boundary. inclusive: if `True`, the result will also include the boundary ops. control_inputs: A boolean indicating whether control inputs are enabled. control_outputs: An instance of `util.ControlOutputs` or `None`. If not `None`, control outputs are enabled. control_ios: An instance of `util.ControlOutputs` or `None`. If not `None`, both control inputs and control outputs are enabled. This is equivalent to set control_inputs to True and control_outputs to the `util.ControlOutputs` instance. Returns: All the `tf.Operation` surrounding the given ops. Raises: TypeError: if `ops` or `seed_ops` cannot be converted to a list of `tf.Operation`. ValueError: if the boundary is intersecting with the seeds. """ control_inputs, control_outputs = check_cios(control_inputs, control_outputs, control_ios) ops = util.make_list_of_op(ops) seed_ops = util.make_list_of_op(seed_ops, allow_graph=False) boundary_ops = set(util.make_list_of_op(boundary_ops)) res = set(seed_ops) if boundary_ops & res: raise ValueError("Boundary is intersecting with the seeds.") wave = set(seed_ops) while wave: new_wave = set() ops_io = get_ops_ios(wave, control_inputs, control_outputs) for op in ops_io: if op in res: continue if op in boundary_ops: if inclusive: res.add(op) else: new_wave.add(op) res.update(new_wave) wave = new_wave return [op for op in ops if op in res] def get_forward_walk_ops(seed_ops, inclusive=True, within_ops=None, within_ops_fn=None, stop_at_ts=(), control_outputs=None): """Do a forward graph walk and return all the visited ops. Args: seed_ops: an iterable of operations from which the forward graph walk starts. If a list of tensors is given instead, the seed_ops are set to be the consumers of those tensors. inclusive: if True the given seed_ops are also part of the resulting set. within_ops: an iterable of `tf.Operation` within which the search is restricted. If `within_ops` is `None`, the search is performed within the whole graph. within_ops_fn: if provided, a function on ops that should return True iff the op is within the graph traversal. This can be used along within_ops, in which case an op is within if it is also in within_ops. stop_at_ts: an iterable of tensors at which the graph walk stops. control_outputs: a `util.ControlOutputs` instance or None. If not `None`, it will be used while walking the graph forward. Returns: A Python set of all the `tf.Operation` ahead of `seed_ops`. Raises: TypeError: if `seed_ops` or `within_ops` cannot be converted to a list of `tf.Operation`. """ _, control_outputs = check_cios(False, control_outputs) if not util.is_iterable(seed_ops): seed_ops = [seed_ops] if not seed_ops: return [] if isinstance(seed_ops[0], tf_ops.Tensor): ts = util.make_list_of_t(seed_ops, allow_graph=False) seed_ops = util.get_consuming_ops(ts) else: seed_ops = util.make_list_of_op(seed_ops, allow_graph=False) seed_ops = frozenset(seed_ops) stop_at_ts = frozenset(util.make_list_of_t(stop_at_ts)) if within_ops: within_ops = util.make_list_of_op(within_ops, allow_graph=False) within_ops = frozenset(within_ops) seed_ops &= within_ops def is_within(op): return (within_ops is None or op in within_ops) and ( within_ops_fn is None or within_ops_fn(op)) result = list(seed_ops) wave = set(seed_ops) while wave: new_wave = set() for op in wave: for new_t in op.outputs: if new_t in stop_at_ts: continue for new_op in new_t.consumers(): if new_op not in result and is_within(new_op): new_wave.add(new_op) if control_outputs is not None: for new_op in control_outputs.get(op): if new_op not in result and is_within(new_op): new_wave.add(new_op) util.concatenate_unique(result, new_wave) wave = new_wave if not inclusive: result = [op for op in result if op not in seed_ops] return result def get_backward_walk_ops(seed_ops, inclusive=True, within_ops=None, within_ops_fn=None, stop_at_ts=(), control_inputs=False): """Do a backward graph walk and return all the visited ops. Args: seed_ops: an iterable of operations from which the backward graph walk starts. If a list of tensors is given instead, the seed_ops are set to be the generators of those tensors. inclusive: if True the given seed_ops are also part of the resulting set. within_ops: an iterable of `tf.Operation` within which the search is restricted. If `within_ops` is `None`, the search is performed within the whole graph. within_ops_fn: if provided, a function on ops that should return True iff the op is within the graph traversal. This can be used along within_ops, in which case an op is within if it is also in within_ops. stop_at_ts: an iterable of tensors at which the graph walk stops. control_inputs: if True, control inputs will be used while moving backward. Returns: A Python set of all the `tf.Operation` behind `seed_ops`. Raises: TypeError: if `seed_ops` or `within_ops` cannot be converted to a list of `tf.Operation`. """ if not util.is_iterable(seed_ops): seed_ops = [seed_ops] if not seed_ops: return [] if isinstance(seed_ops[0], tf_ops.Tensor): ts = util.make_list_of_t(seed_ops, allow_graph=False) seed_ops = util.get_generating_ops(ts) else: seed_ops = util.make_list_of_op(seed_ops, allow_graph=False) stop_at_ts = frozenset(util.make_list_of_t(stop_at_ts)) seed_ops = frozenset(util.make_list_of_op(seed_ops)) if within_ops: within_ops = util.make_list_of_op(within_ops, allow_graph=False) within_ops = frozenset(within_ops) seed_ops &= within_ops def is_within(op): return (within_ops is None or op in within_ops) and ( within_ops_fn is None or within_ops_fn(op)) result = list(seed_ops) wave = set(seed_ops) while wave: new_wave = set() for op in wave: for new_t in op.inputs: if new_t in stop_at_ts: continue if new_t.op not in result and is_within(new_t.op): new_wave.add(new_t.op) if control_inputs: for new_op in op.control_inputs: if new_op not in result and is_within(new_op): new_wave.add(new_op) util.concatenate_unique(result, new_wave) wave = new_wave if not inclusive: result = [op for op in result if op not in seed_ops] return result def get_walks_intersection_ops(forward_seed_ops, backward_seed_ops, forward_inclusive=True, backward_inclusive=True, within_ops=None, within_ops_fn=None, control_inputs=False, control_outputs=None, control_ios=None): """Return the intersection of a forward and a backward walk. Args: forward_seed_ops: an iterable of operations from which the forward graph walk starts. If a list of tensors is given instead, the seed_ops are set to be the consumers of those tensors. backward_seed_ops: an iterable of operations from which the backward graph walk starts. If a list of tensors is given instead, the seed_ops are set to be the generators of those tensors. forward_inclusive: if True the given forward_seed_ops are also part of the resulting set. backward_inclusive: if True the given backward_seed_ops are also part of the resulting set. within_ops: an iterable of tf.Operation within which the search is restricted. If within_ops is None, the search is performed within the whole graph. within_ops_fn: if provided, a function on ops that should return True iff the op is within the graph traversal. This can be used along within_ops, in which case an op is within if it is also in within_ops. control_inputs: A boolean indicating whether control inputs are enabled. control_outputs: An instance of util.ControlOutputs or None. If not None, control outputs are enabled. control_ios: An instance of util.ControlOutputs or None. If not None, both control inputs and control outputs are enabled. This is equivalent to set control_inputs to True and control_outputs to the util.ControlOutputs instance. Returns: A Python set of all the tf.Operation in the intersection of a forward and a backward walk. Raises: TypeError: if `forward_seed_ops` or `backward_seed_ops` or `within_ops` cannot be converted to a list of `tf.Operation`. """ control_inputs, control_outputs = check_cios(control_inputs, control_outputs, control_ios) forward_ops = get_forward_walk_ops( forward_seed_ops, inclusive=forward_inclusive, within_ops=within_ops, within_ops_fn=within_ops_fn, control_outputs=control_outputs) backward_ops = get_backward_walk_ops( backward_seed_ops, inclusive=backward_inclusive, within_ops=within_ops, within_ops_fn=within_ops_fn, control_inputs=control_inputs) return [op for op in forward_ops if op in backward_ops] def get_walks_union_ops(forward_seed_ops, backward_seed_ops, forward_inclusive=True, backward_inclusive=True, within_ops=None, within_ops_fn=None, control_inputs=False, control_outputs=None, control_ios=None): """Return the union of a forward and a backward walk. Args: forward_seed_ops: an iterable of operations from which the forward graph walk starts. If a list of tensors is given instead, the seed_ops are set to be the consumers of those tensors. backward_seed_ops: an iterable of operations from which the backward graph walk starts. If a list of tensors is given instead, the seed_ops are set to be the generators of those tensors. forward_inclusive: if True the given forward_seed_ops are also part of the resulting set. backward_inclusive: if True the given backward_seed_ops are also part of the resulting set. within_ops: restrict the search within those operations. If within_ops is None, the search is done within the whole graph. within_ops_fn: if provided, a function on ops that should return True iff the op is within the graph traversal. This can be used along within_ops, in which case an op is within if it is also in within_ops. control_inputs: A boolean indicating whether control inputs are enabled. control_outputs: An instance of util.ControlOutputs or None. If not None, control outputs are enabled. control_ios: An instance of util.ControlOutputs or None. If not None, both control inputs and control outputs are enabled. This is equivalent to set control_inputs to True and control_outputs to the util.ControlOutputs instance. Returns: A Python set of all the tf.Operation in the union of a forward and a backward walk. Raises: TypeError: if forward_seed_ops or backward_seed_ops or within_ops cannot be converted to a list of tf.Operation. """ control_inputs, control_outputs = check_cios(control_inputs, control_outputs, control_ios) forward_ops = get_forward_walk_ops( forward_seed_ops, inclusive=forward_inclusive, within_ops=within_ops, within_ops_fn=within_ops_fn, control_outputs=control_outputs) backward_ops = get_backward_walk_ops( backward_seed_ops, inclusive=backward_inclusive, within_ops=within_ops, within_ops_fn=within_ops_fn, control_inputs=control_inputs) return util.concatenate_unique(forward_ops, backward_ops) def select_ops(*args, **kwargs): """Helper to select operations. Args: *args: list of 1) regular expressions (compiled or not) or 2) (array of) `tf.Operation`. `tf.Tensor` instances are silently ignored. **kwargs: 'graph': `tf.Graph` in which to perform the regex query.This is required when using regex. 'positive_filter': an elem if selected only if `positive_filter(elem)` is `True`. This is optional. 'restrict_ops_regex': a regular expression is ignored if it doesn't start with the substring "(?#ops)". Returns: A list of `tf.Operation`. Raises: TypeError: if the optional keyword argument graph is not a `tf.Graph` or if an argument in args is not an (array of) `tf.Operation` or an (array of) `tf.Tensor` (silently ignored) or a string or a regular expression. ValueError: if one of the keyword arguments is unexpected or if a regular expression is used without passing a graph as a keyword argument. """ # get keywords arguments graph = None positive_filter = None restrict_ops_regex = False for k, v in iteritems(kwargs): if k == "graph": graph = v if graph is not None and not isinstance(graph, tf_ops.Graph): raise TypeError("Expected a tf.Graph, got: {}".format(type(graph))) elif k == "positive_filter": positive_filter = v elif k == "restrict_ops_regex": restrict_ops_regex = v elif k == "restrict_ts_regex": pass else: raise ValueError("Wrong keywords argument: {}.".format(k)) ops = [] for arg in args: if can_be_regex(arg): if graph is None: raise ValueError("Use the keyword argument 'graph' to use regex.") regex = make_regex(arg) if regex.pattern.startswith("(?#ts)"): continue if restrict_ops_regex and not regex.pattern.startswith("(?#ops)"): continue ops_ = filter_ops_from_regex(graph, regex) for op_ in ops_: if op_ not in ops: if positive_filter is None or positive_filter(op_): ops.append(op_) else: ops_aux = util.make_list_of_op(arg, ignore_ts=True) if positive_filter is not None: ops_aux = [op for op in ops_aux if positive_filter(op)] ops_aux = [op for op in ops_aux if op not in ops] ops += ops_aux return ops def select_ts(*args, **kwargs): """Helper to select tensors. Args: *args: list of 1) regular expressions (compiled or not) or 2) (array of) `tf.Tensor`. `tf.Operation` instances are silently ignored. **kwargs: 'graph': `tf.Graph` in which to perform the regex query.This is required when using regex. 'positive_filter': an elem if selected only if `positive_filter(elem)` is `True`. This is optional. 'restrict_ts_regex': a regular expression is ignored if it doesn't start with the substring "(?#ts)". Returns: A list of `tf.Tensor`. Raises: TypeError: if the optional keyword argument graph is not a `tf.Graph` or if an argument in args is not an (array of) `tf.Tensor` or an (array of) `tf.Operation` (silently ignored) or a string or a regular expression. ValueError: if one of the keyword arguments is unexpected or if a regular expression is used without passing a graph as a keyword argument. """ # get keywords arguments graph = None positive_filter = None restrict_ts_regex = False for k, v in iteritems(kwargs): if k == "graph": graph = v if graph is not None and not isinstance(graph, tf_ops.Graph): raise TypeError("Expected a tf.Graph, got {}".format(type(graph))) elif k == "positive_filter": positive_filter = v elif k == "restrict_ts_regex": restrict_ts_regex = v elif k == "restrict_ops_regex": pass else: raise ValueError("Wrong keywords argument: {}.".format(k)) ts = [] for arg in args: if can_be_regex(arg): if graph is None: raise ValueError("Use the keyword argument 'graph' to use regex.") regex = make_regex(arg) if regex.pattern.startswith("(?#ops)"): continue if restrict_ts_regex and not regex.pattern.startswith("(?#ts)"): continue ts_ = filter_ts_from_regex(graph, regex) for t_ in ts_: if t_ not in ts: if positive_filter is None or positive_filter(t_): ts.append(t_) else: ts_aux = util.make_list_of_t(arg, ignore_ops=True) if positive_filter is not None: ts_aux = [t for t in ts_aux if positive_filter(t)] ts_aux = [t for t in ts_aux if t not in ts] ts += ts_aux return ts def select_ops_and_ts(*args, **kwargs): """Helper to select operations and tensors. Args: *args: list of 1) regular expressions (compiled or not) or 2) (array of) `tf.Operation` 3) (array of) tf.Tensor. Regular expressions matching tensors must start with the comment `"(?#ts)"`, for instance: `"(?#ts)^foo/.*"`. **kwargs: 'graph': `tf.Graph` in which to perform the regex query.This is required when using regex. 'positive_filter': an elem if selected only if `positive_filter(elem)` is `True`. This is optional. Returns: A tuple `(ops, ts)` where: `ops` is a list of `tf.Operation`, and `ts` is a list of `tf.Tensor` Raises: TypeError: if the optional keyword argument graph is not a `tf.Graph` or if an argument in args is not an (array of) `tf.Tensor` or an (array of) `tf.Operation` or a string or a regular expression. ValueError: if one of the keyword arguments is unexpected or if a regular expression is used without passing a graph as a keyword argument. """ ops = select_ops(*args, restrict_ops_regex=False, **kwargs) ts = select_ts(*args, restrict_ts_regex=True, **kwargs) return ops, ts
tensorflow-master
tensorflow/contrib/graph_editor/select.py
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """SubGraphView: a subgraph view on an existing tf.Graph. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import copy import six from six import iteritems from six import StringIO from tensorflow.contrib.graph_editor import select from tensorflow.contrib.graph_editor import util from tensorflow.python.framework import ops as tf_ops __all__ = [ "SubGraphView", "make_view", "make_view_from_scope", ] def _finalize_index(index_or_t, ts): """Returns index as is or return index of tensor in `ts`.""" if isinstance(index_or_t, six.integer_types): return index_or_t else: return ts.index(index_or_t) def _finalize_indices(list_of_index_or_t, ts): """Returns index in `indices` as is or replace with tensor's index.""" return [_finalize_index(index_or_t, ts) for index_or_t in list_of_index_or_t] def _check_within_range(mapping, n, repetition): """Check is the mapping is valid. Args: mapping: an iterable of integer. n: define the input domain as [0, n-1]. Note that the mapping can be under-complete, that is, it can only contain a subset of the integers on [0, n-1]. repetition: if True repetition are allowed (the function is surjective) otherwise repetition are not allowed (the function is injective). Raises: ValueError: if the mapping is out of range ot if repetition is False and the mapping has some repetition. """ for i in mapping: if not 0 <= i < n: raise ValueError("Out of [0, {}[ range: {}".format(n, i)) if not repetition and len(set(mapping)) != len(mapping): raise ValueError("Found repetition in mapping: {}".format(mapping)) class SubGraphView(object): """A subgraph view on an existing `tf.Graph`. An instance of this class is a subgraph view on an existing `tf.Graph`. "subgraph" means that it can represent part of the whole `tf.Graph`. "view" means that it only provides a passive observation and do not to act on the `tf.Graph`. Note that in this documentation, the term "subgraph" is often used as substitute to "subgraph view". A subgraph contains: * a list of input tensors, accessible via the `inputs` property. * a list of output tensors, accessible via the `outputs` property. * and the operations in between, accessible via the "ops" property. An subgraph can be seen as a function F(i0, i1, ...) -> o0, o1, ... It is a function which takes as input some input tensors and returns as output some output tensors. The computation that the function performs is encoded in the operations of the subgraph. The tensors (input or output) can be of two kinds: - connected: a connected tensor connects to at least one operation contained in the subgraph. One example is a subgraph representing a single operation and its inputs and outputs: all the input and output tensors of the op are "connected". - passthrough: a passthrough tensor does not connect to any operation contained in the subgraph. One example is a subgraph representing a single tensor: this tensor is passthrough. By default a passthrough tensor is present both in the input and output tensors of the subgraph. It can however be remapped to only appear as an input (or output) only. The input and output tensors can be remapped. For instance, some input tensor can be omitted. For instance, a subgraph representing an operation with two inputs can be remapped to only take one input. Note that this does not change at all the underlying `tf.Graph` (remember, it is a view). It means that the other input is being ignored, or is being treated as "given". The analogy with functions can be extended like this: F(x,y) is the original function. Remapping the inputs from [x, y] to just [x] means that the subgraph now represent the function F_y(x) (y is "given"). The output tensors can also be remapped. For instance, some output tensor can be omitted. Other output tensor can be duplicated as well. As mentioned before, this does not change at all the underlying `tf.Graph`. The analogy with functions can be extended like this: F(...)->x,y is the original function. Remapping the outputs from [x, y] to just [y,y] means that the subgraph now represent the function M(F(...)) where M is the function M(a,b)->b,b. It is useful to describe three other kind of tensors: * internal: an internal tensor is a tensor connecting operations contained in the subgraph. One example in the subgraph representing the two operations A and B connected sequentially: -> A -> B ->. The middle arrow is an internal tensor. * actual input: an input tensor of the subgraph, regardless of whether it is listed in "inputs" or not (masked-out). * actual output: an output tensor of the subgraph, regardless of whether it is listed in "outputs" or not (masked-out). * hidden input: an actual input which has been masked-out using an input remapping. In other word, a hidden input is a non-internal tensor not listed as a input tensor and one of whose consumers belongs to the subgraph. * hidden output: a actual output which has been masked-out using an output remapping. In other word, a hidden output is a non-internal tensor not listed as an output and one of whose generating operations belongs to the subgraph. Here are some useful guarantees about an instance of a SubGraphView: * the input (or output) tensors are not internal. * the input (or output) tensors are either "connected" or "passthrough". * the passthrough tensors are not connected to any of the operation of the subgraph. Note that there is no guarantee that an operation in a subgraph contributes at all to its inputs or outputs. For instance, remapping both the inputs and outputs to empty lists will produce a subgraph which still contains all the original operations. However, the remove_unused_ops function can be used to make a new subgraph view whose operations are connected to at least one of the input or output tensors. An instance of this class is meant to be a lightweight object which is not modified in-place by the user. Rather, the user can create new modified instances of a given subgraph. In that sense, the class SubGraphView is meant to be used like an immutable python object. A common problem when using views is that they can get out-of-sync with the data they observe (in this case, a `tf.Graph`). This is up to the user to ensure that this doesn't happen. To keep on the safe side, it is recommended that the life time of subgraph views are kept very short. One way to achieve this is to use subgraphs within a "with make_sgv(...) as sgv:" Python context. To alleviate the out-of-sync problem, some functions are granted the right to modified subgraph in place. This is typically the case of graph manipulation functions which, given some subgraphs as arguments, can modify the underlying `tf.Graph`. Since this modification is likely to render the subgraph view invalid, those functions can modify the argument in place to reflect the change. For instance, calling the function swap_inputs(svg0, svg1) will modify svg0 and svg1 in place to reflect the fact that their inputs have now being swapped. """ def __init__(self, inside_ops=(), passthrough_ts=()): """Create a subgraph containing the given ops and the "passthrough" tensors. Args: inside_ops: an object convertible to a list of `tf.Operation`. This list defines all the operations in the subgraph. passthrough_ts: an object convertible to a list of `tf.Tensor`. This list define all the "passthrough" tensors. A passthrough tensor is a tensor which goes directly from the input of the subgraph to it output, without any intermediate operations. All the non passthrough tensors are silently ignored. Raises: TypeError: if inside_ops cannot be converted to a list of `tf.Operation` or if `passthrough_ts` cannot be converted to a list of `tf.Tensor`. """ inside_ops = util.make_list_of_op(inside_ops) passthrough_ts = util.make_list_of_t(passthrough_ts) ops_and_ts = inside_ops + passthrough_ts if ops_and_ts: self._graph = util.get_unique_graph(ops_and_ts) self._ops = inside_ops # Compute inside and outside tensor inputs, outputs, insides = select.compute_boundary_ts(inside_ops) # Compute passthrough tensors, silently ignoring the non-passthrough ones. all_tensors = frozenset(inputs + outputs + list(insides)) self._passthrough_ts = [t for t in passthrough_ts if t not in all_tensors] # Set inputs and outputs. self._input_ts = inputs + self._passthrough_ts self._output_ts = outputs + self._passthrough_ts else: self._graph = None self._passthrough_ts = [] self._input_ts = [] self._output_ts = [] self._ops = [] def __copy__(self): """Create a copy of this subgraph. Note that this class is a "view", copying it only create another view and does not copy the underlying part of the `tf.Graph`. Returns: A new identical instance of the original subgraph view. """ cls = self.__class__ result = cls.__new__(cls) for k, v in iteritems(self.__dict__): if k == "_graph": setattr(result, k, v) else: setattr(result, k, list(v)) # copy the list return result def _assign_from(self, other): """Assign other to itself. Args: other: another subgraph-view. Returns: A new instance identical to the original one. Raises: TypeError: if other is not an SubGraphView. """ if not isinstance(other, SubGraphView): raise TypeError("Expected SubGraphView, got: {}".format(type(other))) # pylint: disable=protected-access self._graph = other._graph self._ops = list(other._ops) self._passthrough_ts = list(other._passthrough_ts) self._input_ts = list(other._input_ts) self._output_ts = list(other._output_ts) # pylint: enable=protected-access def copy(self): """Return a copy of itself. Note that this class is a "view", copying it only create another view and does not copy the underlying part of the tf.Graph. Returns: A new instance identical to the original one. """ return copy.copy(self) def _remap_default(self, remove_input_map=True, remove_output_map=True): """Remap in the place the inputs and/or outputs to the default mapping. Args: remove_input_map: if True the input map is reset to the default one. remove_output_map: if True the output map is reset to the default one. """ if not remove_input_map and not remove_output_map: return # Compute inside and outside tensor inputs, outputs, _ = select.compute_boundary_ts(self._ops) if remove_input_map: self._input_ts = list(inputs) + self._passthrough_ts if remove_output_map: self._output_ts = list(outputs) + self._passthrough_ts def remap_default(self, remove_input_map=True, remove_output_map=True): """Remap the inputs and/or outputs to the default mapping. Args: remove_input_map: if True the input map is reset to the default one. remove_output_map: if True the output map is reset to the default one. Returns: A new modified instance of the original subgraph view with its input and/or output mapping reset to the default one. """ res = self.copy() res._remap_default(remove_input_map, remove_output_map) # pylint: disable=protected-access return res def _remap_inputs(self, new_input_indices): """Remap the inputs of the subgraph in-place.""" new_input_indices = _finalize_indices(new_input_indices, self._input_ts) _check_within_range( new_input_indices, len(self._input_ts), repetition=False) self._input_ts = [self._input_ts[i] for i in new_input_indices] def _remap_outputs(self, new_output_indices): """Remap the outputs of the subgraph in-place.""" new_output_indices = _finalize_indices(new_output_indices, self._output_ts) _check_within_range( new_output_indices, len(self._output_ts), repetition=True) self._output_ts = [self._output_ts[i] for i in new_output_indices] def _remap_outputs_make_unique(self): """Remap the outputs in place so that all the tensors appears only once.""" output_ts = list(self._output_ts) self._output_ts = [] util.concatenate_unique(self._output_ts, output_ts) def _remap_outputs_to_consumers(self): """Remap the outputs in place to match the number of consumers.""" self._remap_outputs_make_unique() output_ts = list(self._output_ts) self._output_ts = [] for t in output_ts: self._output_ts += [t] * len(t.consumers()) def remap_outputs_make_unique(self): """Remap the outputs so that all the tensors appears only once.""" res = copy.copy(self) res._remap_outputs_make_unique() # pylint: disable=protected-access return res def remap_outputs_to_consumers(self): """Remap the outputs to match the number of consumers.""" res = copy.copy(self) res._remap_outputs_to_consumers() # pylint: disable=protected-access return res def _remove_unused_ops(self, control_inputs=True): """Remove unused ops in place. Args: control_inputs: if True, control inputs are used to detect used ops. Returns: A new subgraph view which only contains used operations. """ ops = select.get_walks_union_ops( self.connected_inputs, self.connected_outputs, within_ops=self._ops, control_inputs=control_inputs) self._ops = [op for op in self._ops if op in ops] def remove_unused_ops(self, control_inputs=True): """Remove unused ops. Args: control_inputs: if True, control inputs are used to detect used ops. Returns: A new subgraph view which only contains used operations. """ res = copy.copy(self) res._remove_unused_ops(control_inputs) # pylint: disable=protected-access return res def remap_inputs(self, new_input_indices): """Remap the inputs of the subgraph. If the inputs of the original subgraph are [t0, t1, t2], remapping to [2,0] will create a new instance whose inputs is [t2, t0]. Note that this is only modifying the view: the underlying `tf.Graph` is not affected. Args: new_input_indices: an iterable of integers or tf.Tensors representing a mapping between the old inputs and the new ones. Integers must be positive and smaller than the number of old inputs. tf.Tensors must belong to the old list of inputs. This mapping can be under-complete and must be without repetitions. Returns: A new modified instance of the original subgraph view with remapped inputs. """ res = self.copy() res._remap_inputs(new_input_indices) # pylint: disable=protected-access return res def remap_outputs(self, new_output_indices): """Remap the output of the subgraph. If the output of the original subgraph are [t0, t1, t2], remapping to [1,1,0] will create a new instance whose outputs is [t1, t1, t0]. Note that this is only modifying the view: the underlying tf.Graph is not affected. Args: new_output_indices: an iterable of integers or tf.Tensors representing a mapping between the old outputs and the new ones. Integers must be positive and smaller than the number of old outputs. tf.Tensors must belong to the old list of outputs. This mapping can be under-complete and can have repetitions. Returns: A new modified instance of the original subgraph view with remapped outputs. """ res = copy.copy(self) res._remap_outputs(new_output_indices) # pylint: disable=protected-access return res def remap(self, new_input_indices=None, new_output_indices=None): """Remap the inputs and outputs of the subgraph. Note that this is only modifying the view: the underlying tf.Graph is not affected. Args: new_input_indices: an iterable of integers or tf.Tensors representing a mapping between the old inputs and the new ones. Integers must be positive and smaller than the number of old inputs. tf.Tensors must belong to the old list of inputs. This mapping can be under-complete and must be without repetitions. new_output_indices: an iterable of integers or tf.Tensors representing a mapping between the old outputs and the new ones. Integers must be positive and smaller than the number of old outputs. tf.Tensors must belong to the old list of outputs. This mapping can be under-complete and can have repetitions. Returns: A new modified instance of the original subgraph view with remapped inputs and outputs. """ res = copy.copy(self) if new_input_indices is not None: res._remap_inputs(new_input_indices) # pylint: disable=protected-access if new_output_indices is not None: res._remap_outputs(new_output_indices) # pylint: disable=protected-access return res def find_op_by_name(self, op_name): """Return the op named op_name. Args: op_name: the name to search for Returns: The op named op_name. Raises: ValueError: if the op_name could not be found. AssertionError: if the name was found multiple time. """ res = [op for op in self._ops if op.name == op_name] if not res: raise ValueError("{} not in subgraph.".format(op_name)) if len(res) > 1: raise AssertionError("More than 1 op named: {}!".format(op_name)) return res[0] def __str__(self): if not self: return "SubGraphView: empty" def op_name(op): return op.name def tensor_name(t): if t in self._passthrough_ts: return "{} *".format(t.name) else: return t.name def print_list(name, iterable, get_name): if iterable: print("** {}[{}]:".format(name, len(iterable)), file=res) print("\n".join([" {}".format(get_name(elem)) for elem in iterable]), file=res) else: print("** {}: empty".format(name), file=res) res = StringIO() print("SubGraphView (graphid={}):".format(id(self.graph)), file=res) print_list("ops", self._ops, op_name) print_list("inputs", self._input_ts, tensor_name) print_list("outputs", self._output_ts, tensor_name) return res.getvalue() @property def graph(self): """The underlying `tf.Graph`.""" return self._graph @property def ops(self): """The operations in this subgraph view.""" return self._ops @property def inputs(self): """The input tensors of this subgraph view.""" return util.ListView(self._input_ts) @property def connected_inputs(self): """The connected input tensors of this subgraph view.""" return [t for t in self._input_ts if t not in self._passthrough_ts] @property def outputs(self): """The output tensors of this subgraph view.""" return util.ListView(self._output_ts) @property def connected_outputs(self): """The connected output tensors of this subgraph view.""" return [t for t in self._output_ts if t not in self._passthrough_ts] @property def passthroughs(self): """The passthrough tensors, going straight from input to output.""" return util.ListView(self._passthrough_ts) def __bool__(self): """Allows for implicit boolean conversion.""" return self._graph is not None # Python 3 wants __bool__, Python 2.7 wants __nonzero__ __nonzero__ = __bool__ def op(self, op_id): """Get an op by its index.""" return self._ops[op_id] def is_passthrough(self, t): """Check whether a tensor is passthrough.""" return t in self._passthrough_ts def __enter__(self): """Allow Python context to minimize the life time of a subgraph view. A subgraph view is meant to be a lightweight and transient object. A short lifetime will alleviate the "out-of-sync" issue mentioned earlier. For that reason, a SubGraphView instance can be used within a Python context. For example: from tensorflow.contrib import graph_editor as ge with ge.make_sgv(...) as sgv: print(sgv) Returns: Itself. """ return self def __exit__(self, exc_type, exc_value, traceback): pass def input_index(self, t): """Find the input index corresponding to the given input tensor t. Args: t: the input tensor of this subgraph view. Returns: The index in the self.inputs list. Raises: Error: if t in not an input tensor. """ try: subgraph_id = self._input_ts.index(t) except: raise ValueError("Can't find {} in inputs of subgraph {}.".format( t.name, self.name)) return subgraph_id def output_index(self, t): """Find the output index corresponding to given output tensor t. Args: t: the output tensor of this subgraph view. Returns: The index in the self.outputs list. Raises: Error: if t in not an output tensor. """ try: subgraph_id = self._output_ts.index(t) except: raise ValueError("Can't find {} in outputs of subgraph {}.".format( t.name, self.name)) return subgraph_id def consumers(self): """Return a Python set of all the consumers of this subgraph view. A consumer of a subgraph view is a tf.Operation which is a consumer of one of the output tensors and is not in the subgraph. Returns: A list of `tf.Operation` which are the consumers of this subgraph view. """ ops_set = frozenset(self._ops) res = [] for output in self._output_ts: consumers = [op for op in output.consumers() if op not in ops_set] util.concatenate_unique(res, consumers) return res def _check_graph(sgv, graph): """Check if sgv belongs to the given graph. Args: sgv: a SubGraphView. graph: a graph or None. Returns: The SubGraphView sgv. Raises: TypeError: if sgv is not a SubGraphView or if graph is not None and not a tf.Graph. ValueError: if the graph of sgv and the given graph are not None and different. """ if not isinstance(sgv, SubGraphView): raise TypeError("Expected a SubGraphView, got: {}".format(type(graph))) if graph is None or not sgv.graph: return sgv if not isinstance(graph, tf_ops.Graph): raise TypeError("Expected a tf.Graph, got: {}".format(type(graph))) if sgv.graph is not graph: raise ValueError("Graph mismatch.") return sgv def make_view(*args, **kwargs): """Create a SubGraphView from selected operations and passthrough tensors. Args: *args: list of 1) regular expressions (compiled or not) or 2) (array of) `tf.Operation` 3) (array of) `tf.Tensor`. Those objects will be converted into a list of operations and a list of candidate for passthrough tensors. **kwargs: keyword graph is used 1) to check that the ops and ts are from the correct graph 2) for regular expression query Returns: A subgraph view. Raises: TypeError: if the optional keyword argument graph is not a `tf.Graph` or if an argument in args is not an (array of) `tf.Tensor` or an (array of) `tf.Operation` or a string or a regular expression. ValueError: if one of the keyword arguments is unexpected. """ # get keywords arguments graph = kwargs["graph"] if "graph" in kwargs else None # already a view? if len(args) == 1 and isinstance(args[0], SubGraphView): return _check_graph(args[0], graph) ops, ts = select.select_ops_and_ts(*args, **kwargs) sgv = SubGraphView(ops, ts) return _check_graph(sgv, graph) def make_view_from_scope(scope, graph): """Make a subgraph from a name scope. Args: scope: the name of the scope. graph: the `tf.Graph`. Returns: A subgraph view representing the given scope. """ ops = select.get_name_scope_ops(graph, scope) return SubGraphView(ops)
tensorflow-master
tensorflow/contrib/graph_editor/subgraph.py
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for tensorflow.contrib.graph_editor.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import functools import numpy as np from tensorflow.contrib import graph_editor as ge from tensorflow.contrib.graph_editor.tests import match from tensorflow.core.framework import attr_value_pb2 from tensorflow.python.client import session from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import gradients_impl from tensorflow.python.ops import math_ops from tensorflow.python.ops import variables from tensorflow.python.platform import test # Precision tolerance for floating-point value tests. ERROR_TOLERANCE = 1e-3 class TransformTest(test.TestCase): def setUp(self): self.graph = ops.Graph() with self.graph.as_default(): c0 = constant_op.constant(1.0, shape=[10], name="Const") c0.op._set_attr("_foo", attr_value_pb2.AttrValue(s=b"foo")) c1 = constant_op.constant(1.0, shape=[10], name="Const") c2 = constant_op.constant(1.0, shape=[10], name="Const") i = constant_op.constant(1.0, shape=[10], name="Input") self.o = math_ops.add(c2, math_ops.add(c1, math_ops.add(c0, i))) def test_copy(self): graph = ops.Graph() _, info = ge.copy(self.graph, graph) self.assertEqual( set(op.name for op in self.graph.get_operations()), set(op.name for op in graph.get_operations())) src_ops = self.graph.get_operations() dst_ops = graph.get_operations() for op in src_ops: op_ = info.transformed(op) self.assertTrue(op_ in dst_ops) self.assertEqual(op.name, op_.name) self.assertEqual(info.original(op_), op) src_ts = ge.util.get_tensors(self.graph) dst_ts = ge.util.get_tensors(graph) for t in src_ts: t_ = info.transformed(t) self.assertTrue(t_ in dst_ts) self.assertEqual(t.name, t_.name) self.assertEqual(info.original(t_), t) def test_copy_assert(self): ops.reset_default_graph() a = constant_op.constant(1) b = constant_op.constant(1) eq = math_ops.equal(a, b) assert_op = control_flow_ops.Assert(eq, [a, b]) with ops.control_dependencies([assert_op]): _ = math_ops.add(a, b) sgv = ge.make_view([assert_op, eq.op, a.op, b.op]) copier = ge.Transformer() _, info = copier(sgv, sgv.graph, "", "") new_assert_op = info.transformed(assert_op) self.assertIsNotNone(new_assert_op) def test_transform(self): transformer = ge.Transformer() def my_transform_op_handler(info, op, new_inputs): add_noise = op.name.startswith("Add") op_, op_outputs_ = ge.transform.copy_op_handler(info, op, new_inputs) if not add_noise: return op_, op_outputs_ # add some noise to op with info.graph_.as_default(): t_ = math_ops.add( constant_op.constant(1.0, shape=[10], name="Noise"), op_.outputs[0], name="AddNoise") # return the "noisy" op return op_, [t_] transformer.transform_op_handler = my_transform_op_handler graph = ops.Graph() transformer(self.graph, graph, "", "") matcher0 = match.OpMatcher("AddNoise").input_ops( "Noise", match.OpMatcher("Add").input_ops("Const", "Input")) matcher1 = match.OpMatcher("AddNoise_1").input_ops( "Noise_1", match.OpMatcher("Add_1").input_ops("Const_1", matcher0)) matcher2 = match.OpMatcher("AddNoise_2").input_ops( "Noise_2", match.OpMatcher("Add_2").input_ops("Const_2", matcher1)) top = ge.select_ops("^AddNoise_2$", graph=graph)[0] self.assertTrue(matcher2(top)) def test_transform_nodedef_fn(self): transformer = ge.Transformer() def nodedef_fn(node_def): if "_foo" in node_def.attr: del node_def.attr["_foo"] node_def.attr["_bar"].s = b"bar" return node_def my_copy_op_handler = functools.partial( ge.transform.copy_op_handler, nodedef_fn=nodedef_fn) transformer.transform_op_handler = my_copy_op_handler graph = ops.Graph() transformer(self.graph, graph, "", "") c0_before = self.graph.get_operation_by_name("Const") c0_after = graph.get_operation_by_name("Const") self.assertEquals(c0_before.get_attr("_foo"), b"foo") with self.assertRaises(ValueError): c0_after.get_attr("_foo") all_ops = graph.get_operations() for op in all_ops: self.assertEquals(op.get_attr("_bar"), b"bar") def test_copy_with_input_replacements(self): with self.graph.as_default(): ten = constant_op.constant(10.0, shape=[10], name="Input") sgv, _ = ge.copy_with_input_replacements(self.o.op, {self.o.op.inputs[1]: ten}) with session.Session() as sess: val = sess.run(sgv.outputs[0]) self.assertNear( np.linalg.norm(val - np.array([11])), 0.0, ERROR_TOLERANCE) def test_graph_replace(self): ops.reset_default_graph() a = constant_op.constant(1.0, name="a") b = variables.Variable(1.0, name="b") eps = constant_op.constant(0.001, name="eps") c = array_ops.identity(a + b + eps, name="c") a_new = constant_op.constant(2.0, name="a_new") c_new = ge.graph_replace(c, {a: a_new}) with session.Session() as sess: sess.run(variables.global_variables_initializer()) c_val, c_new_val = sess.run([c, c_new]) self.assertNear(c_val, 2.001, ERROR_TOLERANCE) self.assertNear(c_new_val, 3.001, ERROR_TOLERANCE) def test_graph_replace_dict(self): ops.reset_default_graph() a = constant_op.constant(1.0, name="a") b = variables.Variable(1.0, name="b") eps = constant_op.constant(0.001, name="eps") c = array_ops.identity(a + b + eps, name="c") a_new = constant_op.constant(2.0, name="a_new") c_new = ge.graph_replace({"c": c}, {a: a_new}) self.assertTrue(isinstance(c_new, dict)) with session.Session() as sess: sess.run(variables.global_variables_initializer()) c_val, c_new_val = sess.run([c, c_new]) self.assertTrue(isinstance(c_new_val, dict)) self.assertNear(c_val, 2.001, ERROR_TOLERANCE) self.assertNear(c_new_val["c"], 3.001, ERROR_TOLERANCE) def test_graph_replace_ordered_dict(self): ops.reset_default_graph() a = constant_op.constant(1.0, name="a") b = variables.Variable(1.0, name="b") eps = constant_op.constant(0.001, name="eps") c = array_ops.identity(a + b + eps, name="c") a_new = constant_op.constant(2.0, name="a_new") c_new = ge.graph_replace(collections.OrderedDict({"c": c}), {a: a_new}) self.assertTrue(isinstance(c_new, collections.OrderedDict)) def test_graph_replace_named_tuple(self): ops.reset_default_graph() a = constant_op.constant(1.0, name="a") b = variables.Variable(1.0, name="b") eps = constant_op.constant(0.001, name="eps") c = array_ops.identity(a + b + eps, name="c") a_new = constant_op.constant(2.0, name="a_new") one_tensor = collections.namedtuple("OneTensor", ["t"]) c_new = ge.graph_replace(one_tensor(c), {a: a_new}) self.assertTrue(isinstance(c_new, one_tensor)) def test_graph_replace_missing(self): ops.reset_default_graph() a = constant_op.constant(1.0, name="a") b = constant_op.constant(2.0, name="b") c = a + 2 * b d = constant_op.constant(2.0, name="d") res = ge.graph_replace([b, c], {a: d}) self.assertEqual(res[0].name, "b:0") self.assertEqual(res[1].name, "add_1:0") def test_graph_replace_gradients(self): ops.reset_default_graph() w = variables.VariableV1(0.0, name="w") y = math_ops.multiply(math_ops.multiply(w, w, name="mul1"), w, name="mul2") g = gradients_impl.gradients(y, w, name="grad")[0] # Extract the operations. replacement_ts = {w.value(): g} original_mul1_grad = (ops.get_default_graph(). get_operation_by_name("grad/mul1_grad/Mul_1")) # Should not raise exception. res = ge.graph_replace(g, replacement_ts, dst_scope="res") # Extract the operations after graph_replace. result_mul1_grad = (ops.get_default_graph(). get_operation_by_name("res/grad/mul1_grad/Mul_1")) # Make sure _original_ops are as expected. self.assertEqual(original_mul1_grad._original_op.name, u"mul1") self.assertEqual(result_mul1_grad._original_op.name, u"res/mul1") self.assertNotEqual(res.name, g.name) with session.Session() as sess: sess.run(variables.global_variables_initializer()) g_val, res_val = sess.run([g, res]) self.assertNear(g_val, 0.0, ERROR_TOLERANCE) self.assertNear(res_val, 0.0, ERROR_TOLERANCE) def test_graph_while_loop(self): graph = ops.Graph() with graph.as_default(): max_index = array_ops.placeholder(dtype=dtypes.int32, shape=tuple()) index_start = constant_op.constant(1) sum_start = constant_op.constant(0) _, result = control_flow_ops.while_loop( cond=lambda i, unused_s: i <= max_index, body=lambda i, s: (i + 1, s + i), loop_vars=[index_start, sum_start]) copied_graph = ops.Graph() _, copy_info = ge.copy( graph, dst_graph=copied_graph, dst_scope="imported") copied_result = copy_info.transformed(result) copied_max_index = copy_info.transformed(max_index) with copied_graph.as_default(): with session.Session() as sess: n = 10 sum_val = sess.run(copied_result, feed_dict={copied_max_index: n}) self.assertEqual(sum_val, 55) def test_graph_cond(self): graph = ops.Graph() with graph.as_default(): choice = array_ops.placeholder(shape=(), dtype=dtypes.bool) result = control_flow_ops.cond( choice, lambda: constant_op.constant(1), lambda: constant_op.constant(2)) copied_graph = ops.Graph() _, copy_info = ge.copy( graph, dst_graph=copied_graph, dst_scope="imported") copied_result = copy_info.transformed(result) copied_choice = copy_info.transformed(choice) with copied_graph.as_default(): with session.Session() as sess: res = sess.run(copied_result, feed_dict={copied_choice: True}) self.assertEqual(res, 1) res = sess.run(copied_result, feed_dict={copied_choice: False}) self.assertEqual(res, 2) if __name__ == "__main__": test.main()
tensorflow-master
tensorflow/contrib/graph_editor/tests/transform_test.py
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for tensorflow.contrib.graph_editor.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import re from tensorflow.contrib import graph_editor as ge from tensorflow.python.framework import constant_op from tensorflow.python.framework import ops as ops_lib from tensorflow.python.ops import math_ops from tensorflow.python.platform import test class SelectTest(test.TestCase): def setUp(self): self.graph = ops_lib.Graph() with self.graph.as_default(): self.a = constant_op.constant([1., 1.], shape=[2], name="a") with ops_lib.name_scope("foo"): self.b = constant_op.constant([2., 2.], shape=[2], name="b") self.c = math_ops.add(self.a, self.b, name="c") self.d = constant_op.constant([3., 3.], shape=[2], name="d") with ops_lib.name_scope("bar"): self.e = math_ops.add(self.c, self.d, name="e") self.f = math_ops.add(self.c, self.d, name="f") self.g = math_ops.add(self.c, self.a, name="g") with ops_lib.control_dependencies([self.c.op]): self.h = math_ops.add(self.f, self.g, name="h") def test_regex(self): """Test for ge.can_be_regex and ge.make_regex.""" self.assertTrue(ge.can_be_regex("foo")) self.assertTrue(ge.can_be_regex(re.compile("foo"))) regex = re.compile("foo") self.assertIs(ge.make_regex(regex), regex) def test_get_input_output_ts(self): """Test for ge._get_input_ts abd ge._get_output_ts.""" self.assertEqual(len(ge.select._get_input_ts(self.graph)), 6) self.assertEqual(len(ge.select._get_output_ts(self.graph)), 8) def test_get_filter(self): """Test for various filtering operations on ts ops.""" # TODO(fkp): parameterise self.assertEqual(len(ge.filter_ops(self.graph, True)), 8) self.assertEqual( len(ge.filter_ops(self.graph, lambda op: op.node_def.op == "Const")), 3) self.assertEqual( len(ge.filter_ops(self.graph, lambda op: op.node_def.op == "Add")), 5) self.assertEqual( len(ge.filter_ops_from_regex(self.graph, r"^.*\b[abc]$")), 3) self.assertEqual(len(ge.filter_ts(self.graph, True)), 8) self.assertEqual( len(ge.filter_ts_from_regex(self.graph, r"^.*/[fgh]:\d$")), 3) self.assertEqual(len(ge.get_name_scope_ops(self.graph, "foo/")), 7) self.assertEqual(len(ge.get_name_scope_ops(self.graph, "foo/bar")), 4) def test_get_ops_ios(self): """Test for ge.get_ops_ios.""" control_outputs = ge.util.ControlOutputs(self.graph) self.assertEqual( len(ge.get_ops_ios(self.h.op, control_ios=control_outputs)), 3) self.assertEqual(len(ge.get_ops_ios(self.h.op)), 2) self.assertEqual( len(ge.get_ops_ios(self.c.op, control_ios=control_outputs)), 6) self.assertEqual(len(ge.get_ops_ios(self.c.op)), 5) def test_compute_boundary_ts_0(self): """Test for ge.compute_boundary_ts.""" input_ts, output_ts, inside_ts = ge.compute_boundary_ts(self.g.op) self.assertEqual(list(input_ts), [self.c, self.a]) self.assertEqual(list(output_ts), [self.g]) self.assertEqual(list(inside_ts), []) def test_compute_boundary_ts_1(self): """Test for ge.compute_boundary_ts.""" input_ts, output_ts, inside_ts = ge.compute_boundary_ts( [self.g.op, self.h.op]) self.assertEqual(list(input_ts), [self.c, self.a, self.f]) self.assertEqual(list(output_ts), [self.h]) self.assertEqual(list(inside_ts), [self.g]) def test_compute_boundary_ts_2(self): """Test for ge.compute_boundary_ts.""" graph = ops_lib.Graph() with graph.as_default(): a = constant_op.constant(1, name="a") b = constant_op.constant(1, name="b") c = math_ops.add(a, b, name="c") _ = a + c input_ts, output_ts, inside_ts = ge.compute_boundary_ts([a.op, c.op]) self.assertEqual(list(input_ts), [b]) self.assertEqual(list(output_ts), [a, c]) self.assertEqual(list(inside_ts), [a]) def test_get_within_boundary_ops_0(self): """Test for test_get_within_boundary_ops.""" control_outputs = ge.util.ControlOutputs(self.graph) ops = ge.get_within_boundary_ops( ops=self.graph, seed_ops=self.f.op, boundary_ops=[self.c.op, self.h.op], inclusive=False, control_ios=control_outputs) self.assertEqual(len(ops), 3) def test_get_within_boundary_ops_1(self): """Test for ge.test_get_within_boundary_ops.""" ops = ge.get_within_boundary_ops( ops=self.graph, seed_ops=self.h.op, boundary_ops=[self.f.op, self.g.op]) self.assertEqual(len(ops), 3) def test_get_walks_intersection(self): """Test for ge.get_walks_intersection_ops.""" ops = ge.get_walks_intersection_ops([self.c.op], [self.g.op]) self.assertEqual(len(ops), 2) ops = ge.get_walks_intersection_ops([self.a.op], [self.f.op]) self.assertEqual(len(ops), 3) self.assertTrue(self.a.op in ops) self.assertTrue(self.c.op in ops) self.assertTrue(self.f.op in ops) within_ops = [self.a.op, self.f.op] ops = ge.get_walks_intersection_ops( [self.a.op], [self.f.op], within_ops=within_ops) self.assertEqual(len(ops), 0) within_ops_fn = lambda op: op in [self.a.op, self.f.op] ops = ge.get_walks_intersection_ops( [self.a.op], [self.f.op], within_ops_fn=within_ops_fn) self.assertEqual(len(ops), 0) def test_get_walks_union(self): """Test for ge.get_walks_union_ops.""" ops = ge.get_walks_union_ops([self.f.op], [self.g.op]) self.assertEqual(len(ops), 6) ops = ge.get_walks_union_ops([self.a.op], [self.f.op]) self.assertEqual(len(ops), 8) within_ops = [self.a.op, self.c.op, self.d.op, self.f.op] ops = ge.get_walks_union_ops([self.a.op], [self.f.op], within_ops=within_ops) self.assertEqual(len(ops), 4) self.assertTrue(self.b.op not in ops) within_ops_fn = lambda op: op in [self.a.op, self.c.op, self.f.op] ops = ge.get_walks_union_ops([self.a.op], [self.f.op], within_ops_fn=within_ops_fn) self.assertEqual(len(ops), 3) self.assertTrue(self.b.op not in ops) self.assertTrue(self.d.op not in ops) def test_select_ops(self): parameters = ( (("^foo/",), 7), (("^foo/bar/",), 4), (("^foo/bar/", "a"), 5), ) for param, length in parameters: ops = ge.select_ops(*param, graph=self.graph) self.assertEqual(len(ops), length) def test_select_ts(self): parameters = ( (".*:0", 8), (r".*/bar/\w+:0", 4), ) for regex, length in parameters: ts = ge.select_ts(regex, graph=self.graph) self.assertEqual(len(ts), length) def test_select_ops_and_ts(self): parameters = ( (("^foo/.*",), 7, 0), (("^foo/.*", "(?#ts)^foo/bar/.*"), 7, 4), ) for param, l0, l1 in parameters: ops, ts = ge.select_ops_and_ts(*param, graph=self.graph) self.assertEqual(len(ops), l0) self.assertEqual(len(ts), l1) def test_forward_walk_ops(self): seed_ops = [self.a.op, self.d.op] # Include all ops except for self.g.op within_ops = [ x.op for x in [self.a, self.b, self.c, self.d, self.e, self.f, self.h] ] # For the fn, exclude self.e.op. within_ops_fn = lambda op: op not in (self.e.op,) stop_at_ts = (self.f,) with self.graph.as_default(): # No b.op since it's an independent source node. # No g.op from within_ops. # No e.op from within_ops_fn. # No h.op from stop_at_ts and within_ops. ops = ge.select.get_forward_walk_ops( seed_ops, inclusive=True, within_ops=within_ops, within_ops_fn=within_ops_fn, stop_at_ts=stop_at_ts) self.assertEqual( set(ops), set([self.a.op, self.c.op, self.d.op, self.f.op])) # Also no a.op and d.op when inclusive=False ops = ge.select.get_forward_walk_ops( seed_ops, inclusive=False, within_ops=within_ops, within_ops_fn=within_ops_fn, stop_at_ts=stop_at_ts) self.assertEqual(set(ops), set([self.c.op, self.f.op])) # Not using within_ops_fn adds e.op. ops = ge.select.get_forward_walk_ops( seed_ops, inclusive=False, within_ops=within_ops, stop_at_ts=stop_at_ts) self.assertEqual(set(ops), set([self.c.op, self.e.op, self.f.op])) # Not using stop_at_ts adds back h.op. ops = ge.select.get_forward_walk_ops( seed_ops, inclusive=False, within_ops=within_ops) self.assertEqual( set(ops), set([self.c.op, self.e.op, self.f.op, self.h.op])) # Starting just form a (the tensor, not op) omits a, b, d. ops = ge.select.get_forward_walk_ops([self.a], inclusive=True) self.assertEqual( set(ops), set([self.c.op, self.e.op, self.f.op, self.g.op, self.h.op])) def test_backward_walk_ops(self): seed_ops = [self.h.op] # Include all ops except for self.g.op within_ops = [ x.op for x in [self.a, self.b, self.c, self.d, self.e, self.f, self.h] ] # For the fn, exclude self.c.op. within_ops_fn = lambda op: op not in (self.c.op,) stop_at_ts = (self.f,) with self.graph.as_default(): # Backward walk only includes h since we stop at f and g is not within. ops = ge.select.get_backward_walk_ops( seed_ops, inclusive=True, within_ops=within_ops, within_ops_fn=within_ops_fn, stop_at_ts=stop_at_ts) self.assertEqual(set(ops), set([self.h.op])) # If we do inclusive=False, the result is empty. ops = ge.select.get_backward_walk_ops( seed_ops, inclusive=False, within_ops=within_ops, within_ops_fn=within_ops_fn, stop_at_ts=stop_at_ts) self.assertEqual(set(ops), set()) # Removing stop_at_fs adds f.op, d.op. ops = ge.select.get_backward_walk_ops( seed_ops, inclusive=True, within_ops=within_ops, within_ops_fn=within_ops_fn) self.assertEqual(set(ops), set([self.d.op, self.f.op, self.h.op])) # Not using within_ops_fn adds back ops for a, b, c. ops = ge.select.get_backward_walk_ops( seed_ops, inclusive=True, within_ops=within_ops) self.assertEqual( set(ops), set([ self.a.op, self.b.op, self.c.op, self.d.op, self.f.op, self.h.op ])) # Vanially backward search via self.h.op includes everything excpet e.op. ops = ge.select.get_backward_walk_ops(seed_ops, inclusive=True) self.assertEqual( set(ops), set([ self.a.op, self.b.op, self.c.op, self.d.op, self.f.op, self.g.op, self.h.op ])) if __name__ == "__main__": test.main()
tensorflow-master
tensorflow/contrib/graph_editor/tests/select_test.py
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for tensorflow.contrib.graph_editor.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.contrib import graph_editor as ge from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.ops import math_ops from tensorflow.python.platform import test class UtilTest(test.TestCase): def test_list_view(self): """Test for ge.util.ListView.""" l = [0, 1, 2] lv = ge.util.ListView(l) # Should not be the same id. self.assertIsNot(l, lv) # Should behave the same way than the original list. self.assertTrue(len(lv) == 3 and lv[0] == 0 and lv[1] == 1 and lv[2] == 2) # Should be read only. with self.assertRaises(TypeError): lv[0] = 0 def test_is_iterable(self): """Test for ge.util.is_iterable.""" self.assertTrue(ge.util.is_iterable([0, 1, 2])) self.assertFalse(ge.util.is_iterable(3)) def test_unique_graph(self): """Test for ge.util.check_graphs and ge.util.get_unique_graph.""" g0 = ops.Graph() with g0.as_default(): a0 = constant_op.constant(1) b0 = constant_op.constant(2) g1 = ops.Graph() with g1.as_default(): a1 = constant_op.constant(1) b1 = constant_op.constant(2) # Same graph, should be fine. self.assertIsNone(ge.util.check_graphs(a0, b0)) # Two different graphs, should assert. with self.assertRaises(ValueError): ge.util.check_graphs(a0, b0, a1, b1) # a0 and b0 belongs to the same graph, should be fine. self.assertEqual(ge.util.get_unique_graph([a0, b0]), g0) # Different graph, should raise an error. with self.assertRaises(ValueError): ge.util.get_unique_graph([a0, b0, a1, b1]) def test_make_list_of_op(self): """Test for ge.util.make_list_of_op.""" g0 = ops.Graph() with g0.as_default(): a0 = constant_op.constant(1) b0 = constant_op.constant(2) # Should extract the ops from the graph. self.assertEqual(len(ge.util.make_list_of_op(g0)), 2) # Should extract the ops from the tuple. self.assertEqual(len(ge.util.make_list_of_op((a0.op, b0.op))), 2) def test_make_list_of_t(self): """Test for ge.util.make_list_of_t.""" g0 = ops.Graph() with g0.as_default(): a0 = constant_op.constant(1) b0 = constant_op.constant(2) c0 = math_ops.add(a0, b0) # pylint: disable=unused-variable # Should extract the tensors from tre graph. self.assertEqual(len(ge.util.make_list_of_t(g0)), 3) # Should extract the tensors from the tuple self.assertEqual(len(ge.util.make_list_of_t((a0, b0))), 2) # Should extract the tensors and ignore the ops. self.assertEqual( len(ge.util.make_list_of_t( (a0, a0.op, b0), ignore_ops=True)), 2) def test_get_generating_consuming(self): """Test for ge.util.get_generating_ops and ge.util.get_generating_ops.""" g0 = ops.Graph() with g0.as_default(): a0 = constant_op.constant(1) b0 = constant_op.constant(2) c0 = math_ops.add(a0, b0) self.assertEqual(len(ge.util.get_generating_ops([a0, b0])), 2) self.assertEqual(len(ge.util.get_consuming_ops([a0, b0])), 1) self.assertEqual(len(ge.util.get_generating_ops([c0])), 1) self.assertEqual(ge.util.get_consuming_ops([c0]), []) def test_control_outputs(self): """Test for the ge.util.ControlOutputs class.""" g0 = ops.Graph() with g0.as_default(): a0 = constant_op.constant(1) b0 = constant_op.constant(2) x0 = constant_op.constant(3) with ops.control_dependencies([x0.op]): c0 = math_ops.add(a0, b0) # pylint: disable=unused-variable control_outputs = ge.util.ControlOutputs(g0).get_all() self.assertEqual(len(control_outputs), 1) self.assertEqual(len(control_outputs[x0.op]), 1) self.assertIs(list(control_outputs[x0.op])[0], c0.op) def test_scope(self): """Test simple path scope functionalities.""" self.assertEqual(ge.util.scope_finalize("foo/bar"), "foo/bar/") self.assertEqual(ge.util.scope_dirname("foo/bar/op"), "foo/bar/") self.assertEqual(ge.util.scope_basename("foo/bar/op"), "op") def test_placeholder(self): """Test placeholder functionalities.""" g0 = ops.Graph() with g0.as_default(): a0 = constant_op.constant(1, name="foo") # Test placeholder name. self.assertEqual(ge.util.placeholder_name(a0), "geph__foo_0") self.assertEqual(ge.util.placeholder_name(None), "geph") self.assertEqual( ge.util.placeholder_name( a0, scope="foo/"), "foo/geph__foo_0") self.assertEqual( ge.util.placeholder_name( a0, scope="foo"), "foo/geph__foo_0") self.assertEqual(ge.util.placeholder_name(None, scope="foo/"), "foo/geph") self.assertEqual(ge.util.placeholder_name(None, scope="foo"), "foo/geph") # Test placeholder creation. g0 = ops.Graph() with g0.as_default(): a0 = constant_op.constant(1, dtype=dtypes.float32, name="a0") c0 = math_ops.add( ge.util.make_placeholder_from_tensor(a0), ge.util.make_placeholder_from_dtype_and_shape(dtype=dtypes.float32)) self.assertEqual(c0.op.inputs[0].op.name, "geph__a0_0") self.assertEqual(c0.op.inputs[1].op.name, "geph") if __name__ == "__main__": test.main()
tensorflow-master
tensorflow/contrib/graph_editor/tests/util_test.py
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for tensorflow.contrib.graph_editor.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.contrib import graph_editor as ge from tensorflow.python.framework import constant_op from tensorflow.python.framework import ops from tensorflow.python.ops import math_ops from tensorflow.python.platform import test class SubgraphTest(test.TestCase): def setUp(self): self.graph = ops.Graph() with self.graph.as_default(): self.a = constant_op.constant([1., 1.], shape=[2], name="a") with ops.name_scope("foo"): self.b = constant_op.constant([2., 2.], shape=[2], name="b") self.c = math_ops.add(self.a, self.b, name="c") self.d = constant_op.constant([3., 3.], shape=[2], name="d") with ops.name_scope("bar"): self.e = math_ops.add(self.c, self.d, name="e") self.f = math_ops.add(self.c, self.d, name="f") self.g = math_ops.add(self.c, self.a, name="g") with ops.control_dependencies([self.c.op]): self.h = math_ops.add(self.f, self.g, name="h") def test_subgraph(self): sgv = ge.sgv(self.graph) self.assertEqual(list(sgv.outputs), [self.e, self.h]) self.assertEqual(list(sgv.inputs), []) self.assertEqual(len(sgv.ops), 8) sgv = ge.sgv(self.f.op, self.g.op) self.assertEqual(list(sgv.outputs), [self.f, self.g]) self.assertEqual(list(sgv.inputs), [self.c, self.d, self.a]) sgv = ge.sgv_scope("foo/bar", graph=self.graph) self.assertEqual( list(sgv.ops), [self.e.op, self.f.op, self.g.op, self.h.op]) def test_subgraph_remap(self): sgv = ge.sgv(self.c.op) self.assertEqual(list(sgv.outputs), [self.c]) self.assertEqual(list(sgv.inputs), [self.a, self.b]) sgv = ge.sgv(self.c.op).remap([self.a], [0, self.c]) self.assertEqual(list(sgv.outputs), [self.c, self.c]) self.assertEqual(list(sgv.inputs), [self.a]) sgv = sgv.remap_outputs_to_consumers() self.assertEqual(list(sgv.outputs), [self.c, self.c, self.c]) sgv = sgv.remap_outputs_make_unique() self.assertEqual(list(sgv.outputs), [self.c]) sgv = sgv.remap(new_input_indices=[], new_output_indices=[]) self.assertEqual(len(sgv.inputs), 0) self.assertEqual(len(sgv.outputs), 0) sgv = sgv.remap_default() self.assertEqual(list(sgv.outputs), [self.c]) self.assertEqual(list(sgv.inputs), [self.a, self.b]) def test_remove_unused_ops(self): sgv = ge.sgv(self.graph) self.assertEqual(list(sgv.outputs), [self.e, self.h]) self.assertEqual(len(sgv.ops), 8) sgv = sgv.remap_outputs(new_output_indices=[1]).remove_unused_ops() self.assertEqual(list(sgv.outputs), [self.h]) self.assertEqual(len(sgv.ops), 7) if __name__ == "__main__": test.main()
tensorflow-master
tensorflow/contrib/graph_editor/tests/subgraph_test.py
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for tensorflow.contrib.graph_editor.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.contrib.graph_editor.tests import match from tensorflow.python.framework import constant_op from tensorflow.python.framework import ops from tensorflow.python.ops import math_ops from tensorflow.python.platform import test class MatchTest(test.TestCase): def setUp(self): self.graph = ops.Graph() with self.graph.as_default(): self.a = constant_op.constant([1., 1.], shape=[2], name="a") with ops.name_scope("foo"): self.b = constant_op.constant([2., 2.], shape=[2], name="b") self.c = math_ops.add(self.a, self.b, name="c") self.d = constant_op.constant([3., 3.], shape=[2], name="d") with ops.name_scope("bar"): self.e = math_ops.add(self.c, self.d, name="e") self.f = math_ops.add(self.c, self.d, name="f") self.g = math_ops.add(self.c, self.a, name="g") with ops.control_dependencies([self.c.op]): self.h = math_ops.add(self.f, self.g, name="h") def test_simple_match(self): self.assertTrue(match.OpMatcher("^.*/f$")(self.f.op)) self.assertTrue( match.OpMatcher("^.*/f$").input_ops("^.*/c$", "^.*/d$")(self.f.op)) self.assertTrue( match.OpMatcher("^.*/f$").input_ops(True, "^.*/d$")(self.f.op)) self.assertTrue( match.OpMatcher("^.*/f$").input_ops( match.op_type("Add"), match.op_type("Const"))(self.f.op)) self.assertTrue( match.OpMatcher("^.*/f$").input_ops("^.*/c$", "^.*/d$") .output_ops(match.OpMatcher("^.*/h$") .control_input_ops("^.*/c$"))(self.f.op)) self.assertTrue( match.OpMatcher("^.*/f$").input_ops("^.*/c$", "^.*/d$").output_ops( match.OpMatcher("^.*/h$").control_input_ops("^.*/c$") .output_ops([]))(self.f.op)) if __name__ == "__main__": test.main()
tensorflow-master
tensorflow/contrib/graph_editor/tests/match_test.py
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for tensorflow.contrib.graph_editor.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.contrib import graph_editor as ge from tensorflow.contrib.graph_editor.tests import match from tensorflow.python.framework import constant_op from tensorflow.python.framework import ops from tensorflow.python.ops import math_ops from tensorflow.python.platform import test class EditTest(test.TestCase): """edit module test. Generally the tests are in two steps: - modify an existing graph. - then make sure it has the expected topology using the graph matcher. """ def setUp(self): self.graph = ops.Graph() with self.graph.as_default(): self.a = constant_op.constant([1., 1.], shape=[2], name="a") with ops.name_scope("foo"): self.b = constant_op.constant([2., 2.], shape=[2], name="b") self.c = math_ops.add(self.a, self.b, name="c") self.d = constant_op.constant([3., 3.], shape=[2], name="d") with ops.name_scope("bar"): self.e = math_ops.add(self.c, self.d, name="e") self.f = math_ops.add(self.c, self.d, name="f") self.g = math_ops.add(self.c, self.a, name="g") with ops.control_dependencies([self.c.op]): self.h = math_ops.add(self.f, self.g, name="h") def test_detach(self): """Test for ge.detach.""" sgv = ge.sgv(self.c.op, self.a.op) control_outputs = ge.ControlOutputs(self.graph) ge.detach(sgv, control_ios=control_outputs) # make sure the detached graph is as expected. self.assertTrue( match.OpMatcher("^foo/c$").input_ops("a", "geph__b_0")(self.c.op)) def test_connect(self): """Test for ge.connect.""" with self.graph.as_default(): x = constant_op.constant([1., 1.], shape=[2], name="x") y = constant_op.constant([2., 2.], shape=[2], name="y") z = math_ops.add(x, y, name="z") sgv = ge.sgv(x.op, y.op, z.op) ge.connect(sgv, ge.sgv(self.e.op).remap_inputs([0])) self.assertTrue( match.OpMatcher("^foo/bar/e$").input_ops("^z$", "foo/d$")(self.e.op)) def test_bypass(self): """Test for ge.bypass.""" ge.bypass(ge.sgv(self.f.op).remap_inputs([0])) self.assertTrue( match.OpMatcher("^foo/bar/h$").input_ops("^foo/c$", "foo/bar/g$")( self.h.op)) if __name__ == "__main__": test.main()
tensorflow-master
tensorflow/contrib/graph_editor/tests/edit_test.py
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for tensorflow.contrib.graph_editor.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.contrib import graph_editor as ge from tensorflow.contrib.graph_editor.tests import match from tensorflow.python.framework import constant_op from tensorflow.python.framework import ops from tensorflow.python.ops import math_ops from tensorflow.python.platform import test class RerouteTest(test.TestCase): def setUp(self): self.graph = ops.Graph() with self.graph.as_default(): self.a0 = constant_op.constant(1.0, shape=[2], name="a0") self.b0 = constant_op.constant(2.0, shape=[2], name="b0") self.c0 = math_ops.add(self.a0, self.b0, name="c0") self.a1 = constant_op.constant(3.0, shape=[2], name="a1") self.b1 = constant_op.constant(4.0, shape=[2], name="b1") self.c1 = math_ops.add(self.a1, self.b1, name="c1") self.a2 = constant_op.constant(3.0, shape=[3], name="a2") self.b2 = constant_op.constant(4.0, shape=[3], name="b2") self.c2 = math_ops.add(self.a2, self.b2, name="c2") def test_swap(self): ge.swap_ts([self.a0, self.b0], [self.a1, self.b1]) self.assertTrue(match.OpMatcher("c0").input_ops("a1", "b1")(self.c0.op)) self.assertTrue(match.OpMatcher("c1").input_ops("a0", "b0")(self.c1.op)) def test_multiswap(self): with self.graph.as_default(): a3 = constant_op.constant(3.0, shape=[2], name="a3") ge.swap_ios(ge.sgv(a3.op).remap_outputs([0, 0]), ge.sgv(self.a0.op, self.a1.op)) self.assertTrue(match.OpMatcher("c0").input_ops("a3", "b0")(self.c0.op)) self.assertTrue(match.OpMatcher("c1").input_ops("a3", "b1")(self.c1.op)) def test_reroute(self): ge.reroute_ts([self.a0, self.b0], [self.a1, self.b1]) self.assertTrue(match.OpMatcher("c0").input_ops("a0", "b0")(self.c0.op)) self.assertTrue(match.OpMatcher("c1").input_ops("a0", "b0")(self.c1.op)) ge.reroute_ts([self.a1, self.b1], [self.a0, self.b0]) self.assertTrue(match.OpMatcher("c0").input_ops("a1", "b1")(self.c0.op)) self.assertTrue(match.OpMatcher("c1").input_ops("a1", "b1")(self.c1.op)) def test_compatibility(self): with self.assertRaises(ValueError): ge.reroute_ts([self.a0, self.b0], [self.a2, self.b2]) def test_reroute_can_modify(self): graph = ops.Graph() # create a special graph where "a" is an ambiguous tensor. That is # it is both an input and an output of the ops in sgv0. with graph.as_default(): a = constant_op.constant(1.0, shape=[2], name="a") b = constant_op.constant(2.0, shape=[2], name="b") c = math_ops.add(a, b, name="c") d = math_ops.add(a, c, name="d") e = constant_op.constant(1.0, shape=[2], name="e") f = constant_op.constant(2.0, shape=[2], name="f") g = math_ops.add(e, f, name="g") sgv0 = ge.sgv(a.op, b.op, c.op) sgv1 = ge.sgv(e.op, f.op) ge.swap_outputs(sgv0, sgv1) self.assertTrue( match.OpMatcher("g").input_ops( "a", match.OpMatcher("c").input_ops("a", "b"))(g.op)) self.assertTrue(match.OpMatcher("d").input_ops("e", "f")(d.op)) if __name__ == "__main__": test.main()
tensorflow-master
tensorflow/contrib/graph_editor/tests/reroute_test.py
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Simple graph matching functions.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from six import string_types from tensorflow.contrib.graph_editor import select from tensorflow.python.framework import ops as tf_ops __all__ = [ "op_type", "OpMatcher", ] def _make_graph_match(graph_match): """Convert to a OpMatcher instance.""" if graph_match is None: return None if not isinstance(graph_match, OpMatcher): graph_match = OpMatcher(graph_match) return graph_match def op_type(op_types, op=None): """Check if an op is of the given type. Args: op_types: tuple of strings containing the types to check against. For instance: ("Add", "Const") op: the operation to check (or None). Returns: if op is not None, return True if the op is of the correct type. if op is None, return a lambda function which does the type checking. """ if isinstance(op_types, string_types): op_types = (op_types) if op is None: return lambda op: op.node_def.op in op_types else: return op.node_def.op in op_types class OpMatcher(object): """Graph match class.""" def __init__(self, positive_filter): """Graph match constructor.""" self.positive_filters = [] self.input_op_matches = None self.control_input_op_matches = None self.output_op_matches = None positive_filter = self._finalize_positive_filter(positive_filter) self.positive_filters.append(positive_filter) def _finalize_positive_filter(self, elem): """Convert to a filter function.""" if select.can_be_regex(elem): regex_ = select.make_regex(elem) return lambda op, regex=regex_: regex.search(op.name) is not None elif isinstance(elem, tf_ops.Operation): return lambda op, match_op=elem: op is match_op elif callable(elem): return elem elif elem is True: return lambda op: True else: raise ValueError("Cannot finalize the positive filter: {}".format(elem)) def __call__(self, op): """Evaluate if the op matches or not.""" if not isinstance(op, tf_ops.Operation): raise TypeError("Expect tf.Operation, got: {}".format(type(op))) for positive_filter in self.positive_filters: if not positive_filter(op): return False if self.input_op_matches is not None: if len(op.inputs) != len(self.input_op_matches): return False for input_t, input_op_match in zip(op.inputs, self.input_op_matches): if input_op_match is None: continue if not input_op_match(input_t.op): return False if self.control_input_op_matches is not None: if len(op.control_inputs) != len(self.control_input_op_matches): return False for cinput_op, cinput_op_match in zip(op.control_inputs, self.control_input_op_matches): if cinput_op_match is None: continue if not cinput_op_match(cinput_op): return False if self.output_op_matches is not None: if len(op.outputs) != len(self.output_op_matches): return False for output_t, output_op_matches in zip(op.outputs, self.output_op_matches): if output_op_matches is None: continue if len(output_t.consumers()) != len(output_op_matches): return False for consumer_op, consumer_op_match in zip(output_t.consumers(), output_op_matches): if consumer_op_match is None: continue if not consumer_op_match(consumer_op): return False return True def input_ops(self, *args): """Add input matches.""" if self.input_op_matches is not None: raise ValueError("input_op_matches is already set.") self.input_op_matches = [] for input_match in args: self.input_op_matches.append(_make_graph_match(input_match)) return self def control_input_ops(self, *args): """Add input matches.""" if self.control_input_op_matches is not None: raise ValueError("control_input_op_matches is already set.") self.control_input_op_matches = [] for input_match in args: self.control_input_op_matches.append(_make_graph_match(input_match)) return self def output_ops(self, *args): """Add output matches.""" if self.output_op_matches is not None: raise ValueError("output_op_matches is already set.") self.output_op_matches = [] for consumer_op_matches in args: if consumer_op_matches is None: self.output_op_matches.append(None) if not isinstance(consumer_op_matches, list): consumer_op_matches = [consumer_op_matches] consumer_op_matches = [_make_graph_match(consumer_op_match) for consumer_op_match in consumer_op_matches] self.output_op_matches.append(consumer_op_matches) return self
tensorflow-master
tensorflow/contrib/graph_editor/tests/match.py
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Simple GraphEditor example. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow as tf from tensorflow.contrib import graph_editor as ge FLAGS = tf.flags.FLAGS def main(_): # create a graph g = tf.Graph() with g.as_default(): a = tf.constant(1.0, shape=[2, 3], name="a") b = tf.constant(2.0, shape=[2, 3], name="b") c = tf.add( tf.placeholder(dtype=np.float32), tf.placeholder(dtype=np.float32), name="c") # modify the graph ge.swap_inputs(c.op, [a, b]) # print the graph def print(g.as_graph_def()) # and print the value of c with tf.Session(graph=g) as sess: res = sess.run(c) print(res) if __name__ == "__main__": tf.app.run()
tensorflow-master
tensorflow/contrib/graph_editor/examples/edit_graph_example.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================= """Ops related to Tensor Processing Units. @@cross_replica_sum @@infeed_dequeue @@infeed_dequeue_tuple @@infeed_enqueue @@infeed_enqueue_tuple @@outfeed_dequeue @@outfeed_dequeue_tuple @@outfeed_enqueue @@outfeed_enqueue_tuple @@initialize_system @@shutdown_system @@device_assignment @@core @@replicate @@shard @@batch_parallel @@rewrite @@outside_compilation @@CrossShardOptimizer @@InfeedQueue @@DeviceAssignment @@Topology @@while_loop @@repeat @@TPUEstimator @@TPUEstimatorSpec @@export_estimator_savedmodel @@RunConfig @@InputPipelineConfig @@TPUConfig @@bfloat16_scope @@TPUDistributionStrategy @@keras_to_tpu_model @@AsyncCheckpointSaverHook @@TPUInMemoryEvalHook """ from __future__ import absolute_import from __future__ import division from __future__ import print_function # pylint: disable=wildcard-import,unused-import from tensorflow.contrib.tpu.python import profiler from tensorflow.contrib.tpu.python.ops.tpu_ops import * from tensorflow.contrib.tpu.python.tpu.async_checkpoint import * from tensorflow.contrib.tpu.python.tpu.bfloat16 import * from tensorflow.contrib.tpu.python.tpu.device_assignment import * from tensorflow.contrib.tpu.python.tpu.keras_support import tpu_model as keras_to_tpu_model from tensorflow.contrib.tpu.python.tpu.keras_support import TPUDistributionStrategy from tensorflow.contrib.tpu.python.tpu.topology import * from tensorflow.contrib.tpu.python.tpu.tpu import * from tensorflow.contrib.tpu.python.tpu.tpu_config import * from tensorflow.contrib.tpu.python.tpu.tpu_estimator import * from tensorflow.contrib.tpu.python.tpu.tpu_feed import InfeedQueue from tensorflow.contrib.tpu.python.tpu.tpu_optimizer import * from tensorflow.contrib.tpu.python.tpu.training_loop import * # pylint: enable=wildcard-import,unused-import from tensorflow.python.util.all_util import remove_undocumented _allowed_symbols = ['profiler'] remove_undocumented(__name__, _allowed_symbols)
tensorflow-master
tensorflow/contrib/tpu/__init__.py
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Stub file to maintain backwards compatibility.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # pylint: disable=wildcard-import,unused-import from tensorflow.python.tpu.ops.tpu_ops import * # pylint: enable=wildcard-import,unused-import
tensorflow-master
tensorflow/contrib/tpu/python/ops/tpu_ops.py
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Stub file to maintain backwards compatibility.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # pylint: disable=wildcard-import,unused-import from tensorflow.python.tpu.ops.tpu_ordinal_selector_op import * # pylint: enable=wildcard-import,unused-import
tensorflow-master
tensorflow/contrib/tpu/python/ops/tpu_ordinal_selector_op.py
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Stub file to maintain backwards compatibility.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # pylint: disable=wildcard-import,unused-import from tensorflow.python.tpu.profiler import * # pylint: enable=wildcard-import,unused-import
tensorflow-master
tensorflow/contrib/tpu/python/profiler/__init__.py
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Stub file to maintain backwards compatibility.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # pylint: disable=wildcard-import,unused-import,redefined-builtin from tensorflow.python.tpu.device_assignment import * # pylint: enable=wildcard-import,unused-import,redefined-builtin
tensorflow-master
tensorflow/contrib/tpu/python/tpu/device_assignment.py
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Stub file to maintain backwards compatibility.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # pylint: disable=wildcard-import,unused-import from tensorflow.python.tpu.tpu_embedding import * # pylint: enable=wildcard-import,unused-import
tensorflow-master
tensorflow/contrib/tpu/python/tpu/tpu_embedding.py
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Stub file to maintain backwards compatibility.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # pylint: disable=wildcard-import,unused-import from tensorflow.python.tpu.tensor_tracer import * # pylint: enable=wildcard-import,unused-import
tensorflow-master
tensorflow/contrib/tpu/python/tpu/tensor_tracer.py
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Stub file to maintain backwards compatibility.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # pylint: disable=wildcard-import,unused-import from tensorflow_estimator.python.estimator.tpu.util import * # pylint: enable=wildcard-import,unused-import
tensorflow-master
tensorflow/contrib/tpu/python/tpu/util.py
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Stub file to maintain backwards compatibility.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # pylint: disable=wildcard-import,unused-import from tensorflow.python.tpu.feature_column import * # used by tests from tensorflow.python.tpu.feature_column import _is_running_on_cpu from tensorflow.python.tpu.feature_column import _record_variable_scope_and_name from tensorflow.python.tpu.feature_column import _TPU_FC_TO_SCOPE from tensorflow.python.tpu.feature_column import _TPUBaseEmbeddingColumn from tensorflow.python.tpu.feature_column import _TPUEmbeddingColumn from tensorflow.python.tpu.feature_column import _TPUSharedEmbeddingColumn # pylint: enable=wildcard-import,unused-import
tensorflow-master
tensorflow/contrib/tpu/python/tpu/feature_column.py
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Stub file to maintain backwards compatibility.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # pylint: disable=wildcard-import,unused-import from tensorflow.python.tpu.datasets import * # pylint: enable=wildcard-import,unused-import
tensorflow-master
tensorflow/contrib/tpu/python/tpu/datasets.py
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Stub file to maintain backwards compatibility.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # pylint: disable=wildcard-import,unused-import from tensorflow.python.tpu import * # pylint: enable=wildcard-import,unused-import
tensorflow-master
tensorflow/contrib/tpu/python/tpu/__init__.py
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Distributed variable implementation for TPUs. N.B. This is an experimental feature that should only be used for Keras support. It is unsupported and will be removed in favor of Distribution Strategy soon. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import contextlib import numpy as np from tensorflow.python.client import session as session_lib from tensorflow.python.framework import dtypes as dtypes_module from tensorflow.python.framework import ops from tensorflow.python.keras import backend from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import gen_resource_variable_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import resource_variable_ops from tensorflow.python.ops import variable_scope @contextlib.contextmanager def _handle_graph(handle): with handle.graph.as_default(): yield def _enclosing_tpu_context(): # pylint: disable=protected-access context = ops.get_default_graph()._get_control_flow_context() # pylint: enable=protected-access while context is not None and not isinstance( context, control_flow_ops.XLAControlFlowContext): context = context.outer_context return context class ReplicatedVariable(object): """A replicated variable for use on TPUs. When accessed inside a tpu.replicate() context, this variable acts as if it is a single variable whose handle is a replicated input to the computation. Outside a tpu.replicate() context currently this object has pretty murky semantics, especially with respect to things such as * initialization * colocation. """ def __init__(self, name, variables): self._name = name self._primary_var = variables[0] self._common_name = self._primary_var.name.split(":")[0] self._vars = variables self._cached_value = None self._dtype = variables[0].dtype @property def handle(self): tpu_context = _enclosing_tpu_context() if tpu_context is None: return self._primary_var.handle return tpu_context.get_replicated_var_handle(self._name, self._vars) @contextlib.contextmanager def _assign_dependencies(self): """Makes assignments depend on the cached value, if any. This prevents undefined behavior with reads not ordered wrt writes. Yields: None. """ if self._cached_value is not None: with ops.control_dependencies([self._cached_value]): yield else: yield @property def initializer(self): return control_flow_ops.group([v.initializer for v in self._vars]) @property def graph(self): return self._primary_var.graph @property def _shared_name(self): return self._common_name @property def _unique_id(self): return self._primary_var._unique_id # pylint: disable=protected-access @property def name(self): return self._name @property def dtype(self): return self._primary_var.dtype @property def shape(self): return self._primary_var.shape def get_shape(self): return self._primary_var.get_shape() def to_proto(self, export_scope=None): return self._primary_var.to_proto(export_scope=export_scope) @property def constraint(self): return None @property def op(self): return self.get().op @property def is_tensor_like(self): return True def _read_variable_op(self): if _enclosing_tpu_context() is None: return self._primary_var.read_value() v = gen_resource_variable_ops.read_variable_op(self.handle, self._dtype) return v def read_value(self): return self._read_variable_op() def is_initialized(self, name=None): return self._vars[0].is_initialized(name=name) def __getitem__(self, *args): return self.read_value().__getitem__(*args) def assign(self, value, use_locking=None, name=None, read_value=False): """Assign `value` to all replicas. Outside of the tpu.rewrite context, assign explicitly to all replicas. Inside of the tpu.rewrite context, assigns to the local replica. Arguments: value: Tensor to assign use_locking: ignored name: ignored read_value: return the value from the assignment Returns: Assignment operation, or new value of the variable if `read_value` is True """ del use_locking if _enclosing_tpu_context() is None: assign_ops = [] with self._assign_dependencies(): for var in self._vars: assign_ops.append(var.assign(value, use_locking=None, name=name)) if read_value: with ops.control_dependencies(assign_ops): return self.read_value() else: return control_flow_ops.group(assign_ops) with _handle_graph(self.handle), self._assign_dependencies(): value_tensor = ops.convert_to_tensor(value, dtype=self.dtype) assign_op = gen_resource_variable_ops.assign_variable_op( self.handle, value_tensor, name=name) if read_value: return self._read_variable_op() return assign_op def assign_add(self, delta, use_locking=None, name=None, read_value=True): del use_locking with _handle_graph(self.handle), self._assign_dependencies(): assign_add_op = gen_resource_variable_ops.assign_add_variable_op( self.handle, ops.convert_to_tensor(delta, dtype=self.dtype), name=name) if read_value: return self._read_variable_op() return assign_add_op def assign_sub(self, delta, use_locking=None, name=None, read_value=True): del use_locking with _handle_graph(self.handle), self._assign_dependencies(): assign_sub_op = gen_resource_variable_ops.assign_sub_variable_op( self.handle, ops.convert_to_tensor(delta, dtype=self.dtype), name=name) if read_value: return self._read_variable_op() return assign_sub_op def get(self): return self._primary_var @property def _in_graph_mode(self): return self._primary_var._in_graph_mode # pylint: disable=protected-access def _should_act_as_resource_variable(self): """Pass resource_variable_ops.is_resource_variable check.""" pass def _dense_var_to_tensor(self, dtype=None, name=None, as_ref=False): """Converts a variable to a tensor.""" # pylint: disable=protected-access if _enclosing_tpu_context() is None: return self._primary_var._dense_var_to_tensor(dtype, name, as_ref) # pylint: enable=protected-access if dtype is not None and dtype != self.dtype: return math_ops.cast(self._read_variable_op(), dtype) if as_ref: return self.handle else: return self.read_value() # Register a conversion function which reads the value of the variable, # allowing instances of the class to be used as tensors. def _tensor_conversion(var, dtype=None, name=None, as_ref=False): return var._dense_var_to_tensor(dtype=dtype, name=name, as_ref=as_ref) # pylint: disable=protected-access def replicated_fetch_function(var): # pylint: disable=protected-access return ([var._dense_var_to_tensor()], lambda v: v[0]) # pylint: enable=protected-access ops.register_tensor_conversion_function(ReplicatedVariable, _tensor_conversion) ops.register_dense_tensor_like_type(ReplicatedVariable) session_lib.register_session_run_conversion_functions( ReplicatedVariable, replicated_fetch_function) def replicated_scope(num_replicas): """Variable scope for constructing replicated variables.""" def _replicated_variable_getter(getter, name, *args, **kwargs): """Getter that constructs replicated variables.""" collections = kwargs.pop("collections", None) if collections is None: collections = [ops.GraphKeys.GLOBAL_VARIABLES] kwargs["collections"] = [] variables = [] index = {} for i in range(num_replicas): replica_name = "{}/{}".format(name, i) with ops.device("device:TPU:{}".format(i)): v = getter(*args, name=replica_name, **kwargs) variables.append(v) index[i] = v result = ReplicatedVariable(name, variables) g = ops.get_default_graph() # If "trainable" is True, next_creator() will add the member variables # to the TRAINABLE_VARIABLES collection, so we manually remove # them and replace with the MirroredVariable. We can't set # "trainable" to False for next_creator() since that causes functions # like implicit_gradients to skip those variables. if kwargs.get("trainable", True): collections.append(ops.GraphKeys.TRAINABLE_VARIABLES) l = g.get_collection_ref(ops.GraphKeys.TRAINABLE_VARIABLES) for v in index.values(): if v in l: l.remove(v) g.add_to_collections(collections, result) return result return variable_scope.variable_scope( "", custom_getter=_replicated_variable_getter) @contextlib.contextmanager def replicated_variable_for_optimizer(num_replicas): """Context manager for optimizer weights. Overrides K.variable.""" if num_replicas == 1: yield return try: old_v = backend.variable def opt_variable(value, dtype=None, name=None, constraint=None): """Instantiates a variable and returns it.""" if dtype is None: dtype = backend.floatx() variables = [] for i in range(num_replicas): # Keras holds the variables in optimizer class instance , so the name # does not matter here. ResourceVariable constructor will find a unique # name (including name=None) for each replica. with ops.device("device:TPU:{}".format(i)): v = resource_variable_ops.ResourceVariable( value, dtype=dtypes_module.as_dtype(dtype), name=name, constraint=constraint) variables.append(v) name = "replicate_{}_{}".format("variable" if name is None else name, ops.uid()) v = ReplicatedVariable(name, variables) # pylint: disable=protected-access if isinstance(value, np.ndarray): v._keras_shape = value.shape elif hasattr(value, "shape"): v._keras_shape = backend.int_shape(value) v._uses_learning_phase = False backend.track_variable(v) return v backend.variable = opt_variable yield finally: backend.variable = old_v
tensorflow-master
tensorflow/contrib/tpu/python/tpu/keras_tpu_variables.py
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """*Experimental* support for running Keras models on the TPU. To use, wrap your model with the `keras_support.tpu_model` function. Example usage: ``` image = tf.keras.layers.Input(shape=(28, 28, 3), name='image') c1 = tf.keras.layers.Conv2D(filters=16, kernel_size=(3, 3))( image) flattened = tf.keras.layers.Flatten()(c1) logits = tf.keras.layers.Dense(10, activation='softmax')(flattened) model = tf.keras.Model(inputs=[image], outputs=[logits]) resolver = tf.contrib.cluster_resolver.TPUClusterResolver(tpu=tpu_name) strategy = keras_support.TPUDistributionStrategy(resolver) model = keras_support.tpu_model(model, strategy=strategy) # Only TF optimizers are currently supported. model.compile(optimizer=tf.compat.v1.train.AdamOptimizer(), ...) # `images` and `labels` should be Numpy arrays. Support for tensor input # (e.g. datasets) is planned. model.fit(images, labels) ``` """ # pylint: disable=protected-access from __future__ import absolute_import from __future__ import division from __future__ import print_function import abc import collections import contextlib import re import sys import time import numpy as np import six from tensorflow.contrib.cluster_resolver.python.training import tpu_cluster_resolver as tpu_cluster_resolver_lib from tensorflow.contrib.tpu.python.ops import tpu_ops from tensorflow.contrib.tpu.python.tpu import keras_tpu_variables from tensorflow.contrib.tpu.python.tpu import tpu from tensorflow.contrib.tpu.python.tpu import tpu_function from tensorflow.contrib.tpu.python.tpu import tpu_optimizer from tensorflow.contrib.tpu.python.tpu import tpu_system_metadata as tpu_system_metadata_lib from tensorflow.core.protobuf import config_pb2 from tensorflow.core.protobuf.tpu import compilation_result_pb2 as tpu_compilation_result from tensorflow.python import tf2 from tensorflow.python.client import session as tf_session from tensorflow.python.data.ops import dataset_ops from tensorflow.python.data.ops import iterator_ops from tensorflow.python.eager import context from tensorflow.python.estimator import model_fn as model_fn_lib from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import errors from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_shape from tensorflow.python.framework import tensor_spec from tensorflow.python.keras import backend as K from tensorflow.python.keras import callbacks as cbks from tensorflow.python.keras import metrics as metrics_module from tensorflow.python.keras import models from tensorflow.python.keras import optimizers as keras_optimizers from tensorflow.python.keras.engine import base_layer from tensorflow.python.keras.engine import base_layer_utils from tensorflow.python.keras.engine import training_arrays from tensorflow.python.keras.engine import training_utils from tensorflow.python.keras.layers import embeddings from tensorflow.python.keras.utils.generic_utils import make_batches from tensorflow.python.keras.utils.generic_utils import slice_arrays from tensorflow.python.ops import array_ops from tensorflow.python.ops import gen_linalg_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import random_ops from tensorflow.python.ops import variable_scope from tensorflow.python.ops import variables from tensorflow.python.platform import tf_logging as logging from tensorflow.python.util.deprecation import deprecated # TODO(b/114775106): temporary shim to optionally initialize the TPU # This increases the odds our session is initialized, but shouldn't be needed. _TEST_REWRITE_OP = None def _maybe_initialize_tpu(session): """Initialize the TPU if it has not already been initialized.""" global _TEST_REWRITE_OP try: # Try to use cached version to avoid another ground of graph optimization. test_rewrite_op = _TEST_REWRITE_OP if (test_rewrite_op is None or test_rewrite_op[0].graph != ops.get_default_graph()): def test_op(): return constant_op.constant(1) + constant_op.constant(1) test_rewrite_op = tpu.rewrite(test_op) _TEST_REWRITE_OP = test_rewrite_op session.run(test_rewrite_op) except errors.FailedPreconditionError as _: session.run(tpu.initialize_system()) @contextlib.contextmanager def _tpu_session_context(): """Initialize the TPU and cleans cache entries for bad sessions.""" try: _maybe_initialize_tpu(K.get_session()) yield except (errors.FailedPreconditionError, errors.AbortedError) as e: K.clear_session() raise Exception(""" An error occurred connecting or initializing your TPU. The session has been reset. re-run keras_to_tpu_model to create a new session. """ + str(e)) def setup_tpu_session(cluster_resolver): """Construct or return a `tf.Session` connected to the given cluster.""" master = cluster_resolver.master() # Use the existing session if we're already connected to this TPU # N.B K.get_session() is a non-trivial operation, and may fail if the remote # session has been reset. try: default_session = K.get_session() if (default_session._target == master and getattr(default_session, '_tpu_initialized', None)): return except errors.AbortedError as _: # We lost the remote session and need to re-initialize. logging.warning('Lost remote session: creating a new session.') cluster_spec = cluster_resolver.cluster_spec() config = config_pb2.ConfigProto(isolate_session_state=True) if cluster_spec: config.cluster_def.CopyFrom(cluster_spec.as_cluster_def()) tpu_session = tf_session.Session(target=master, config=config) tpu_session.run(tpu.initialize_system()) tpu_session._tpu_initialized = True # N.B. We have to call `K.set_session()` AND set our session as the # TF default. `K.get_session()` surprisingly does not return the value # supplied by K.set_session otherwise. K.set_session(tpu_session) try: from scipy.sparse import issparse # pylint: disable=g-import-not-at-top except ImportError: issparse = None def get_tpu_system_metadata(tpu_cluster_resolver): """Retrieves TPU system metadata given a TPUClusterResolver.""" master = tpu_cluster_resolver.master() # pylint: disable=protected-access cluster_spec = tpu_cluster_resolver.cluster_spec() cluster_def = cluster_spec.as_cluster_def() if cluster_spec else None tpu_system_metadata = ( tpu_system_metadata_lib._query_tpu_system_metadata( master, cluster_def=cluster_def, query_topology=False)) return tpu_system_metadata class TPUDistributionStrategy(object): """The strategy to run Keras model on TPU.""" def __init__(self, tpu_cluster_resolver=None, using_single_core=False): """Construct a TPUDistributionStrategy. Args: tpu_cluster_resolver: Any instance of `TPUClusterResolver`. If None, will create one with '' as master address. using_single_core: Bool. This is the debugging option, which might be removed in future once the model replication functionality is mature enough. If `False` (default behavior), the system automatically finds the best configuration, in terms of number of TPU cores, for the model replication, typically using all available TPU cores. If overwrites as `True`, force the model replication using single core, i.e., no replication. Raises: Exception: No TPU Found on the given worker. """ if tf2.enabled(): raise RuntimeError( 'Keras support is now deprecated in support of TPU Strategy. ' 'Please follow the distribution strategy guide on tensorflow.org ' 'to migrate to the 2.0 supported version.') else: logging.warning( 'Keras support is now deprecated in support of TPU Strategy. ' 'Please follow the distribution strategy guide on tensorflow.org ' 'to migrate to the 2.0 supported version.') if tpu_cluster_resolver is None: tpu_cluster_resolver = tpu_cluster_resolver_lib.TPUClusterResolver('') metadata = get_tpu_system_metadata(tpu_cluster_resolver) self._tpu_metadata = metadata self._tpu_cluster_resolver = tpu_cluster_resolver self._num_cores = 1 if using_single_core else metadata.num_cores # Walk device list to identify TPU worker for enqueue/dequeue operations. worker_re = re.compile('/job:([^/]+)') for device in metadata.devices: if 'TPU:0' in device.name: self._worker_name = worker_re.search(device.name).group(1) return raise Exception('No TPU found on given worker.') def _make_assignment_for_model(self, cpu_model): """Makes a `TPUAssignment` for the passed in `cpu_model`.""" num_cores = self._num_cores if num_cores > 1 and cpu_model.stateful: logging.warning( 'Model replication does not currently support stateful models. ' 'Degrading to a single core.') num_cores = 1 return TPUAssignment(worker_name=self._worker_name, num_cores=num_cores) class TPUAssignment(object): """This is object holding TPU resources assignment for the concrete model. `TPUDistributionStrategy` is responsible to create the instance of `TPUAssignment`, so, it can dynamically adjust the `num_cores` to use based on model and input batch sizes. """ def __init__(self, worker_name, num_cores): self._worker_name = worker_name self._num_cores = num_cores @property def worker_name(self): return self._worker_name @property def num_towers(self): # TODO(xiejw): Support automatically assign num_cores based on inputs. return self._num_cores class TPUEmbedding(embeddings.Embedding): """TPU compatible embedding layer. The default Keras layer is not TPU compatible. This layer is a drop-in replacement: it has the same behavior and will work on CPU and GPU devices. """ def build(self, input_shape): if input_shape[0] is None: raise ValueError( 'TPUEmbeddings must have a fixed input_length or input shape.') return super(TPUEmbedding, self).build(input_shape) def call(self, inputs): if K.dtype(inputs) != 'int32': inputs = math_ops.cast(inputs, 'int32') inputs = array_ops.one_hot(inputs, self.input_dim) return math_ops.tensordot(inputs, self.embeddings, 1) def _cross_replica_concat(tensor, core_id, num_cores, name): """Concatenate `tensor` across cores. Args: tensor: The tensor to be concatenated. Must be [int32 and float32]. core_id: Tensor indicating the current TPU core. num_cores: Python int. The total number of TPU cores in the system. name: The string name to print for debugging. Returns: The same concatenated Tensor on each core. """ input_dtype = tensor.dtype if input_dtype not in [dtypes.bfloat16, dtypes.float32, dtypes.int32]: raise TypeError('For model replication, only (bfloat16, float32 and int32) ' 'is supported for model outputs and targets. Got {} for ' '{}.'.format(input_dtype, name)) batch_size = tensor.shape[0] mask = math_ops.cast( math_ops.equal(np.arange(num_cores, dtype=np.int32), core_id), dtypes.float32) mask = array_ops.reshape(mask, [num_cores] + [1] * tensor.shape.ndims) result = mask * math_ops.cast(tensor, dtypes.float32) local_tensor_with_holes = array_ops.reshape(result, [-1] + result.shape.as_list()[2:]) concat_tensor = tpu_ops.cross_replica_sum(local_tensor_with_holes) concat_tensor.set_shape((num_cores * batch_size,) + tuple(tensor.shape[1:])) if concat_tensor != input_dtype: concat_tensor = math_ops.cast(concat_tensor, input_dtype) return concat_tensor class KerasCrossShardOptimizer(keras_optimizers.Optimizer): """An optimizer that averages gradients across TPU shards.""" def __init__(self, opt, name='KerasCrossShardOptimizer'): """Construct a new cross-shard optimizer. Args: opt: An existing `Optimizer` to encapsulate. name: Optional name prefix for the operations created when applying gradients. Defaults to "KerasCrossShardOptimizer". Raises: ValueError: If reduction is not a valid cross-shard reduction. """ super(KerasCrossShardOptimizer, self).__init__() self._name = name self._opt = opt logging.info('KerasCrossShard: %s %s', self._opt, self._opt.weights) def get_updates(self, loss, params): self._opt.get_gradients = self.get_gradients return self._opt.get_updates(loss, params) def get_gradients(self, loss, params): num_shards = tpu_function.get_tpu_context().number_of_shards grads = super(KerasCrossShardOptimizer, self).get_gradients(loss, params) return [tpu_ops.cross_replica_sum(grad) / num_shards for grad in grads] def get_weights(self): return self._opt.get_weights() def get_config(self): return self._opt.get_config() # Defer remaining operations to the underlying optimizer def __getattr__(self, key): return getattr(self._opt, key) class TPUModelOp( collections.namedtuple('TPUModelOp', [ 'compile_op', 'execute_op', 'infeed_tensors', 'infeed_op', 'outfeed_op' ])): pass def _valid_name(tensor_name): """Return a valid tensor name (strips '/', ':', etc).""" return re.sub('[^a-zA-Z0-9_-]+', '', tensor_name) def _replicated_optimizer(opt): """Wrap the optimizer `opt` with CrossShardOptimizer if applicable.""" # Always wrap `opt` with CrossShardOptimizer, even if we are running on a # single core. This ensures Keras properly tracks and initializes optimizer # variables. if isinstance(opt, keras_optimizers.TFOptimizer): return tpu_optimizer.CrossShardOptimizer(opt.optimizer) else: return KerasCrossShardOptimizer(opt) def _clone_optimizer(optimizer, config=None, worker_name=None): """Returns a cloned optimizer with the provided optimizer.config or config.""" if not isinstance(optimizer, keras_optimizers.Optimizer): # In the first call to tpu_model(model), Keras may not have wrapped the TF # optimizer in the TFOptimizer helper, e.g., the given model isn't compiled # or optimizer isn't set, and later generated tpu_model compiles with a TF # optimizer. return optimizer if isinstance(optimizer, keras_optimizers.TFOptimizer): return keras_optimizers.TFOptimizer(optimizer.optimizer) if config is None: config = optimizer.get_config() logging.info('Cloning %s %s', optimizer.__class__.__name__, config) with ops.device( '%s/device:CPU:0' % ('/job:%s' % worker_name if worker_name else '')): # Explicitly put optimizer parameter variables on TPU worker. return optimizer.__class__.from_config(config) class TPURewriteContext(object): """Prepare the environment for a Keras model during `tpu.rewrite`. This overrides the default placeholder behaviour to instead refer to a preset input mapping. Placeholders are unsupported in TPU compiled code, and must be replaced with explicit inputs or values from the infeed queue. Instead of explicitly threading inputs all the way through the Keras codebase, we override the behavior of the placeholder while compiling and inject the Tensors from the infeed in place of the placeholder. Similarly, as we compile a new sub-graph for each unique shape and execution mode, we need to override the behavior of an embedded `name_scope` call in the base Keras layer code. This allows us to re-use the same weights across many compiles and share a single session/graph. """ def __init__(self, input_map): self._input_map = input_map self._default_placeholder = None self._default_name_scope = None def __enter__(self): def _placeholder(dtype, shape=None, name=None): # pylint: disable=unused-argument logging.info('Remapping placeholder for %s', name) if name in self._input_map: return self._input_map[name] else: logging.info('Default: %s', name) return self._default_placeholder(dtype, shape, name) def _name_scope(name, default_name=None, values=None): caller_frame = sys._getframe().f_back caller_obj = caller_frame.f_locals.get('self') if (caller_obj is not None and isinstance(caller_obj, base_layer.Layer) and name is not None): return variable_scope.variable_scope( name, default_name, values, reuse=variable_scope.AUTO_REUSE) return self._default_name_scope(name, default_name, values) self._default_placeholder = array_ops.placeholder self._default_name_scope = ops.name_scope self._default_make_variable = base_layer_utils.make_variable self._default_random_normal = random_ops.random_normal self._default_qr = gen_linalg_ops.qr array_ops.placeholder = _placeholder # Replace random_ops.random_normal with a dummy function because # `random_normal` isn't yet implemented on the TPU. Because these # initialized values are overwritten by the CPU values, this is okay. def random_normal(shape, mean=0.0, stddev=1.0, dtype=dtypes.float32, seed=None, name=None): del mean del stddev del seed return array_ops.zeros(shape, dtype=dtype, name=name) random_ops.random_normal = random_normal # Replace gen_linalg_ops.qr because QR decomposition is not yet implemented. # TODO(saeta): Remove qr override once we confirm the qr implementation is # ok. # pylint: disable=redefined-builtin def qr(input, full_matrices=False, name=None): """Dummy implementation of qr decomposition.""" del full_matrices # TODO(saeta): Properly handle the full matrix case. input_shape = input.shape if len(input_shape) < 2: raise ValueError('Invalid shape passed to qr: %s' % input_shape) p = min(input_shape[-1], input_shape[-2]) if len(input_shape) == 2: q = array_ops.zeros((p, p), name=name) r = array_ops.zeros(input_shape, name=name) return (r, q) elif len(input_shape) == 3: n = input_shape[0] q = array_ops.zeros((n, p, p), name=name) r = array_ops.zeros(input_shape, name=name) return (r, q) else: raise ValueError('Invalid shape passed to qr: %s' % input_shape) gen_linalg_ops.qr = qr ops.name_scope = _name_scope base_layer_utils.make_variable = variable_scope.get_variable logging.info('Overriding default placeholder.') return def __exit__(self, exc_type, exc_val, exc_tb): array_ops.placeholder = self._default_placeholder ops.name_scope = self._default_name_scope base_layer_utils.make_variable = self._default_make_variable random_ops.random_normal = self._default_random_normal gen_linalg_ops.qr = self._default_qr class SizedInfeed( collections.namedtuple('SizedInfeed', ['sharded_infeed_tensors', 'infeed_ops'])): """Represents an instantiation of the infeed ops for a concrete input shape. sharded_infeed_tensors: A data structure of Tensors used to represent the placeholder tensors that must be fed when using feed_dicts. infeed_ops: the set of ops that will be run to drive infeed for a single step. """ pass class TPUInfeedInstance(object): """TPUInfeedInstance represents the logic to manage feeding in a single step. See the comments on the `TPUInfeedManager` for a description for how infeed is managed. """ @abc.abstractmethod def make_input_specs(self, input_tensors): """Constructs the infeed_specs for the given Infeed instance. Args: input_tensors: The inputs to the model. Returns: A list of """ pass def make_feed_dict(self, tpu_model_op): """Constructs a feed_dict for this instance, given the tpu_model_op. Args: tpu_model_op: A `TPUModelOp` representing the TPU Model for this instance's input spec. Returns: A dictionary to use as the feed_dict of a `session.run` call. """ pass @six.add_metaclass(abc.ABCMeta) class TPUInfeedManager(object): """TPUInfeedManager manages the data infeeding of data to a TPU computation. Because there are multiple data sources (e.g. in-memory NumPy arrays, `tf.data.Dataset`s), we abstract the different logic behind a single interface: the `TPUInfeedManager`. (1) A `TPUFunction` is called with a set of inputs. Based on the inputs, `TPUFunction` retrieves the corresponding `TPUInfeedManager` (or constructs a new one if required). (2) The `TPUFunction` calls `make_infeed_instance` on the `TPUInfeedManager` which returns a `TPUInfeedInstance`. (3) The `TPUFunction` checks in the shape cache for a pre-compiled instance of the model based on the returned `input_specs` from `TPUInfeedInstance`. (4) [Optional.] If the model has not already been instantiated for the given input spec, the `TPUFunction` compiles the model for the input spec (using the `TPUInfeedManager`). (5) The `TPUInfeedInstance` constructs the session.run's feed_dict given the compiled model instance corresponding to its shape. """ @abc.abstractmethod def make_infeed_instance(self, inputs): """Given a single step's input, construct a `TPUInfeedInstance`. Args: inputs: The inputs to a given step. Returns: A subclass of `TPUInfeedInstance`. """ pass @abc.abstractmethod def build_infeed_from_input_specs(self, input_specs, execution_mode): """For a given input specification (size, type), construct the infeed ops. This is called only once for a given input specification and builds the graph ops. It does not have a pointer to the actual infeed data. Args: input_specs: TODO(saeta): Document me! execution_mode: TODO(saeta): Document me! Returns: A `SizedInfeed` instance. """ pass class TPUNumpyInfeedManager(TPUInfeedManager): """TPU Infeed manager for Numpy inputs.""" class NumpyInfeedInstance(TPUInfeedInstance): """Infeed instance for Numpy inputs.""" def __init__(self, sharded_inputs): self._sharded_inputs = sharded_inputs def make_input_specs(self, input_tensors): # Compute an input specification (used to generate infeed enqueue and # dequeue operations). We use the shape from our input array and the # dtype from our model. A user may pass in a float64 for a float32 # input: for model compatibility we still must generate a float32 infeed. input_specs = [] # We use the shape and dtype from the first shard to compute the input # metadata (`input_specs`); all replicas have the same type and shape. for tensor, ary in zip(input_tensors, self._sharded_inputs[0]): input_specs.append( tensor_spec.TensorSpec(ary.shape, tensor.dtype, _valid_name(tensor.name))) return input_specs def make_feed_dict(self, tpu_model_op): infeed_dict = {} for infeed_tensors, inputs in zip(tpu_model_op.infeed_tensors, self._sharded_inputs): for tensor, value in zip(infeed_tensors, inputs): infeed_dict[tensor] = value return infeed_dict def __init__(self, tpu_assignment): self._tpu_assignment = tpu_assignment def _split_tensors(self, inputs): """Split input data across shards. Each input is sliced along the batch axis. Args: inputs: List of Numpy arrays to run on the TPU. Returns: List of lists containing the input to feed to each TPU shard. """ if self._tpu_assignment.num_towers == 1: return [inputs] batch_size = inputs[0].shape[0] assert batch_size % self._tpu_assignment.num_towers == 0, ( 'batch_size must be divisible by the number of TPU cores in use (%s ' 'vs %s)' % (batch_size, self._tpu_assignment.num_towers)) shard_size = batch_size // self._tpu_assignment.num_towers input_list = [] for index in range(self._tpu_assignment.num_towers): shard_inputs = [ x[index * shard_size:(index + 1) * shard_size] for x in inputs ] input_list.append(shard_inputs) return input_list def make_infeed_instance(self, inputs): sharded_inputs = self._split_tensors(inputs) return self.NumpyInfeedInstance(sharded_inputs) def build_infeed_from_input_specs(self, input_specs, execution_mode): infeed_op = [] shard_infeed_tensors = [] for shard_id in range(self._tpu_assignment.num_towers): with ops.device( '/job:%s/device:CPU:0' % self._tpu_assignment.worker_name): infeed_tensors = [] with ops.device('/device:TPU:%d' % shard_id): for spec in input_specs: # Construct placeholders for each of the inputs. infeed_tensors.append( array_ops.placeholder( dtype=spec.dtype, shape=spec.shape, name='infeed-enqueue-%s-%d' % (spec.name, shard_id))) shard_infeed_tensors.append(infeed_tensors) infeed_op.append( tpu_ops.infeed_enqueue_tuple( infeed_tensors, [spec.shape for spec in input_specs], name='infeed-enqueue-%s-%d' % (execution_mode, shard_id), device_ordinal=shard_id)) return SizedInfeed( infeed_ops=infeed_op, sharded_infeed_tensors=shard_infeed_tensors) class TPUDatasetInfeedManager(TPUInfeedManager): """Manages infeed for a `tf.data.Dataset` into a TPU computation. """ class DatasetInfeedInstance(TPUInfeedInstance): """An instance of the TPU infeed.""" def __init__(self, input_specs): self._input_specs = input_specs def make_input_specs(self, input_tensors): # TODO(saeta): Do error checking here! return self._input_specs def make_feed_dict(self, tpu_model_op): # TODO(saeta): Verify tpu_model_op is as expected! return {} # pylint: disable=redefined-outer-name def __init__(self, dataset, tpu_assignment, mode): """Constructs a TPUDatasetInfeedManager. Args: dataset: A `tf.data.Dataset` to infeed. tpu_assignment: The `TPUAssignment` used to configure the Keras TPU model. mode: ModeKeys enum. """ self._verify_dataset_shape(dataset) self._dataset = dataset self._tpu_assignment = tpu_assignment dataset_output_shapes = dataset_ops.get_legacy_output_shapes(dataset) dummy_x_shape = dataset_output_shapes[0].as_list() dummy_x_shape[0] *= tpu_assignment.num_towers dummy_y_shape = dataset_output_shapes[1].as_list() dummy_y_shape[0] *= tpu_assignment.num_towers self._iterator = dataset_ops.make_initializable_iterator(dataset) K.get_session().run(self._iterator.initializer) self._get_next_ops = [] ctrl_deps = [] for i in range(tpu_assignment.num_towers): with ops.control_dependencies(ctrl_deps): # Ensure deterministic # TODO(saeta): Ensure correct placement! get_next_op = self._iterator.get_next() self._get_next_ops.append(get_next_op) ctrl_deps.extend(get_next_op) # Use dummy numpy inputs for the rest of Keras' shape checking. We # intercept them when building the model. dataset_output_types = dataset_ops.get_legacy_output_types(dataset) self._dummy_x = np.zeros( dummy_x_shape, dtype=dataset_output_types[0].as_numpy_dtype) self._dummy_y = np.zeros( dummy_y_shape, dtype=dataset_output_types[1].as_numpy_dtype) input_specs = [] iterator_output_shapes = dataset_ops.get_legacy_output_shapes( self._iterator) iterator_output_types = dataset_ops.get_legacy_output_types(self._iterator) if isinstance(iterator_output_shapes, tuple): assert isinstance(iterator_output_types, tuple) assert len(iterator_output_shapes) == len(iterator_output_types) for i in range(len(iterator_output_shapes)): spec = tensor_spec.TensorSpec(iterator_output_shapes[i], iterator_output_types[i]) input_specs.append(spec) elif isinstance(iterator_output_shapes, tensor_shape.TensorShape): spec = tensor_spec.TensorSpec(iterator_output_shapes, iterator_output_types) input_specs.append(spec) # Pre-process the inputs and get_next_ops before caching. input_specs, self._get_next_ops = ( _inject_tpu_inputs_for_dataset( tpu_assignment, mode, input_specs, self._get_next_ops)) self._infeed_instance = self.DatasetInfeedInstance(input_specs) def _verify_dataset_shape(self, dataset): """Verifies a dataset is of an appropriate shape for TPUs.""" dataset_output_shapes = dataset_ops.get_legacy_output_shapes(dataset) dataset_output_classes = dataset_ops.get_legacy_output_classes(dataset) if not isinstance(dataset, dataset_ops.DatasetV2): raise ValueError('The function passed as the `x` parameter did not ' 'return a `tf.data.Dataset`.') if not isinstance(dataset_output_classes, tuple): raise ValueError('The dataset must return a tuple of tf.Tensors, ' 'instead it returns: %s' % dataset_output_classes) if len(dataset_output_classes) != 2: raise ValueError('The dataset must return a 2-element tuple, got ' '%s output classes instead.' % (dataset_output_classes,)) for i, cls in enumerate(dataset_output_classes): if cls != ops.Tensor: raise ValueError('The dataset returned a non-Tensor type (%s) at ' 'index %d.' % (cls, i)) for i, shape in enumerate(dataset_output_shapes): if not shape: raise ValueError('The dataset returns a scalar tensor in ' 'tuple index %d. Did you forget to batch? ' '(Output shapes: %s).' % (i, dataset_output_shapes)) for j, dim in enumerate(shape): if dim.value is None: if j == 0: hint = (' Hint: did you use `ds.batch(BATCH_SIZE, ' 'drop_remainder=True)`?') else: hint = '' raise ValueError( 'The Keras-TPU integration for `tf.data` ' 'currently requires static shapes. The provided ' 'dataset only has a partially defined shape. ' '(Dimension %d of output tensor %d is not statically known ' 'for output shapes: %s.%s)' % (j, i, dataset_output_shapes, hint)) @property def dummy_x(self): return self._dummy_x @property def dummy_y(self): return self._dummy_y def make_infeed_instance(self, inputs): # TODO(saeta): Verify inputs is as expected. return self._infeed_instance def build_infeed_from_input_specs(self, input_specs, execution_mode): shard_infeed_tensors = self._get_next_ops assert len(shard_infeed_tensors) == self._tpu_assignment.num_towers infeed_ops = [] for shard_id in range(self._tpu_assignment.num_towers): with ops.device( '/job:%s/device:CPU:0' % self._tpu_assignment.worker_name): infeed_ops.append( tpu_ops.infeed_enqueue_tuple( shard_infeed_tensors[shard_id], [spec.shape for spec in input_specs], name='infeed-enqueue-%s-%d' % (execution_mode, shard_id), device_ordinal=shard_id)) return SizedInfeed( infeed_ops=infeed_ops, sharded_infeed_tensors=shard_infeed_tensors) def _inject_tpu_inputs_for_dataset(tpu_assignment, mode, input_specs, get_next_ops): """Append core information to the set of dataset inputs.""" # This is used during compilation to identify the current TPU core and enable # concatenation operations across cores. if mode not in [model_fn_lib.ModeKeys.TRAIN, model_fn_lib.ModeKeys.EVAL]: return input_specs, get_next_ops # Dataset inputs operate on per core basis. per_core_batch_size = input_specs[0].shape.as_list()[0] # Insert, at head, the tensor for core_id. assert len(get_next_ops) == tpu_assignment.num_towers for i in range(tpu_assignment.num_towers): core_id_constant = constant_op.constant( np.array([i] * per_core_batch_size).astype('int32'), dtype=dtypes.int32, name='cord_id_constant') get_next_ops[i] = [core_id_constant] + list(get_next_ops[i]) # Insert the input spec at head also. input_specs = [tensor_spec.TensorSpec([per_core_batch_size], dtypes.int32) ] + input_specs return input_specs, get_next_ops def _inject_tpu_inputs_for_infeed(tpu_assignment, mode, core_id_place_holder, input_tensors, inputs): """Append core information to the set of inputs.""" # This is used during compilation to identify the current TPU core and enable # concatenation operations across cores. if mode not in [model_fn_lib.ModeKeys.TRAIN, model_fn_lib.ModeKeys.EVAL]: return input_tensors, inputs # Puts a place holder in input spec. input_tensors = [core_id_place_holder] + input_tensors # Now fill the core id. For `num_cores` = 2, `batch_size` = 8, we fill the # core id inputs as [0, 0, 0, 0, 1, 1, 1, 1], so each core sees its core id # (duplicated). num_cores = tpu_assignment.num_towers per_core_batch_size = inputs[0].shape[0] // num_cores core_ids = np.arange(num_cores).repeat(per_core_batch_size) inputs = [core_ids] + inputs return input_tensors, inputs def _read_tpu_coreid_from_infeed(mode, infeed_tensors): """Popping out the core ids from infeed.""" if mode not in [model_fn_lib.ModeKeys.TRAIN, model_fn_lib.ModeKeys.EVAL]: return None, infeed_tensors if len(infeed_tensors) <= 1: raise RuntimeError( 'The infeed tensors on TPU core has only {} tensors. ' 'This is not expected. Please report a bug.\nTensors: {}'.format( len(infeed_tensors), infeed_tensors)) core_id = infeed_tensors[0][0] # Pop out the scalar version. rest = infeed_tensors[1:] return core_id, rest class TPUFunction(object): """K.function compatible interface for invoking a TPU compiled function. Recompilation is triggered on-demand for each set of new inputs shapes: the results are cached for future execution. We expect most computations will be dominated by a standard batch-size, followed by a straggler batch for the end of training or evaluation. All `inputs` and `outputs` will be loaded via the infeed and outfeed queues instead of being injected as `feed_dict` items or fetches. """ def __init__(self, model, execution_mode, tpu_assignment): self.model = model self.execution_mode = execution_mode self._tpu_assignment = tpu_assignment self._compilation_cache = {} self._cloned_model = None self._cloned_optimizer = None # Create a placeholder for the TPU core ID. Cache the placeholder to avoid # modifying the graph for every batch. self._core_id_place_holder = array_ops.placeholder( dtype=dtypes.int32, shape=[1], name='core_id') def _specialize_model(self, input_specs, infeed_manager): """Specialize `self.model` (a Keras model) for the given input shapes.""" # Re-create our input and output layers inside our subgraph. They will be # attached to the true computation when we clone our model in `tpu_fn`. K.set_learning_phase(self.execution_mode == model_fn_lib.ModeKeys.TRAIN) # functools.partial and callable objects are not supported by tpu.rewrite def _model_fn(): """Compute fit/eval/predict for the TPU.""" is_training = self.execution_mode == model_fn_lib.ModeKeys.TRAIN is_test = self.execution_mode == model_fn_lib.ModeKeys.EVAL is_predict = self.execution_mode == model_fn_lib.ModeKeys.PREDICT # During train/eval, we infeed our features as well as labels. if is_training or is_test: infeed_layers = self.model._input_layers + self.model._output_layers else: infeed_layers = self.model._input_layers # Generate our infeed operation to read features & labels. infeed_tensors = tpu_ops.infeed_dequeue_tuple( dtypes=[spec.dtype for spec in input_specs], shapes=[spec.shape for spec in input_specs], name='infeed-%s' % self.execution_mode) core_id, infeed_tensors = ( _read_tpu_coreid_from_infeed( mode=self.execution_mode, infeed_tensors=infeed_tensors)) assert len(infeed_tensors) == len(infeed_layers), ( 'Infeed inputs did not match model: %s vs %s' % (infeed_layers, infeed_tensors)) tpu_targets = [] tpu_input_map = {} # Sort infeed outputs into inputs and labels for calling our Keras model. for tensor, layer in zip(infeed_tensors, infeed_layers): if layer in self.model._input_layers: tpu_input_map[layer.name] = tensor if layer in self.model._output_layers: tpu_targets.append(tensor) # Clone our CPU model, running within the TPU device context. # # We use the id of the original model as a key to avoid weight collisions # (if a user re-runs the same model multiple times, in e.g. Colab). with TPURewriteContext(tpu_input_map): with variable_scope.variable_scope('tpu_%s' % id(self.model)): with keras_tpu_variables.replicated_scope( self._tpu_assignment.num_towers): if not self._cloned_optimizer: self._cloned_optimizer = _clone_optimizer( self.model.cpu_optimizer, worker_name=self._tpu_assignment.worker_name) self._cloned_model = models.clone_model(self.model) # When running on more than one core, concatenate outputs at the end # of processing. In backprop stage, the gradients will be # calculated according to the local inputs as gradient of # cross-replica-concat being zero for any outputs other than those # from mlocal core so the loss calculation is identical. num_towers = self.model._tpu_assignment.num_towers if num_towers > 1 and (is_training or is_test): new_outputs = [ _cross_replica_concat( o, core_id, num_towers, name='model output ({})'.format(o.name)) for o in self._cloned_model.outputs ] # Recast all low precision outputs back to float32 since we only # casted the inputs to bfloat16 and not targets. This is done so # that we can preserve precision when calculating the loss value. if new_outputs and new_outputs[0].dtype == dtypes.bfloat16: new_outputs = [ math_ops.cast(o, dtypes.float32) for o in new_outputs] self._cloned_model.outputs = new_outputs tpu_targets = [ _cross_replica_concat( tensor, core_id, num_towers, name='model target ({})'.format(tensor.name)) for tensor in tpu_targets ] if is_training or is_test: with variable_scope.variable_scope( 'metrics', reuse=variable_scope.AUTO_REUSE): self._cloned_model.compile( optimizer=_replicated_optimizer(self._cloned_optimizer), loss=self.model.loss, loss_weights=self.model.loss_weights, metrics=metrics_module.clone_metrics( self.model._compile_metrics), weighted_metrics=metrics_module.clone_metrics( self.model._compile_weighted_metrics), target_tensors=tpu_targets, ) # Compute our outfeed depending on the execution mode if is_training: if not isinstance(self._cloned_optimizer, keras_optimizers.TFOptimizer): # For Keras optimizer, we try to place the variable weights on the TPU # device. Keras creates optimizer variables (e.g. momentum values for # the Momentum optimizer) when _make_train_function is invoked. with keras_tpu_variables.replicated_variable_for_optimizer( self._tpu_assignment.num_towers): self._cloned_model._make_train_function() else: self._cloned_model._make_train_function() self._outfeed_spec = [ tensor_spec.TensorSpec(tensor.shape, tensor.dtype, tensor.name) for tensor in self._cloned_model.train_function.outputs ] return [ self._cloned_model.train_function.updates_op, tpu_ops.outfeed_enqueue_tuple( self._cloned_model.train_function.outputs, name='outfeed-enqueue-train') ] elif is_test: self._cloned_model._make_test_function() self._outfeed_spec = [ tensor_spec.TensorSpec(tensor.shape, tensor.dtype, tensor.name) for tensor in self._cloned_model.test_function.outputs ] return [ tpu_ops.outfeed_enqueue_tuple( self._cloned_model.test_function.outputs, name='outfeed-enqueue-test') ] elif is_predict: self._cloned_model._make_predict_function() self._outfeed_spec = [ tensor_spec.TensorSpec(tensor.shape, tensor.dtype, tensor.name) for tensor in self._cloned_model.predict_function.outputs ] return [ tpu_ops.outfeed_enqueue_tuple( self._cloned_model.predict_function.outputs, name='outfeed-enqueue-predict', ) ] else: assert False, 'Unexpected execution mode: %s' % self.execution_mode # Capture outfeed metadata computed during the rewrite. self._outfeed_spec = None # Generate out TPU operations using `tpu.split_compile_and_replicate`. # `compile_op` can be used to test the TPU model compiles before execution. # `execute op` replicates `_model_fn` `num_replicas` times, with each shard # running on a different logical core. compile_op, execute_op = tpu.split_compile_and_replicate( _model_fn, inputs=[[] for _ in range(self._tpu_assignment.num_towers)]) # Generate CPU side operations to enqueue features/labels and dequeue # outputs from the model call. sized_infeed = infeed_manager.build_infeed_from_input_specs( input_specs, self.execution_mode) # Build output ops. outfeed_op = [] for shard_id in range(self._tpu_assignment.num_towers): with ops.device( '/job:%s/device:CPU:0' % self._tpu_assignment.worker_name): outfeed_op.extend( tpu_ops.outfeed_dequeue_tuple( dtypes=[spec.dtype for spec in self._outfeed_spec], shapes=[spec.shape for spec in self._outfeed_spec], name='outfeed-dequeue-%s-%d' % (self.execution_mode, shard_id), device_ordinal=shard_id)) return TPUModelOp( compile_op, execute_op, infeed_tensors=sized_infeed.sharded_infeed_tensors, infeed_op=sized_infeed.infeed_ops, outfeed_op=outfeed_op) def _test_model_compiles(self, tpu_model_ops): """Verifies that the given TPUModelOp can be compiled via XLA.""" logging.info('Started compiling') start_time = time.time() result = K.get_session().run(tpu_model_ops.compile_op) proto = tpu_compilation_result.CompilationResultProto() proto.ParseFromString(result) if proto.status_error_message: raise RuntimeError('Compilation failed: {}'.format( proto.status_error_message)) end_time = time.time() logging.info('Finished compiling. Time elapsed: %s secs', end_time - start_time) def _lookup_infeed_manager(self, inputs): """Return an existing manager, or construct a new InfeedManager for inputs. _lookup_infeed_manager will return an existing InfeedManager if one has been previously assigned for this model and input. If not, it will construct a new TPUNumpyInfeedManager. Args: inputs: A NumPy input to the model. Returns: A `TPUInfeedManager` object to manage infeeds for this input. """ if inputs is None: return None for x, mgr in self.model._numpy_to_infeed_manager_list: if inputs[0] is x: return mgr return TPUNumpyInfeedManager(self.model._tpu_assignment) def _tpu_model_ops_for_input_specs(self, input_specs, infeed_manager): """Looks up the corresponding `TPUModelOp` for a given `input_specs`. It instantiates a new copy of the model for each unique input shape. Args: input_specs: The specification of the inputs to train on. infeed_manager: The infeed manager responsible for feeding in data. Returns: A `TPUModelOp` instance that can be used to execute a step of the model. """ if input_specs is None or infeed_manager is None: # Note: this condition is possible during the prologue or epilogue of the # pipelined loop. return None # XLA requires every operation in the graph has a fixed shape. To # handle varying batch sizes we recompile a new sub-graph for each # unique input shape. shape_key = tuple([tuple(spec.shape.as_list()) for spec in input_specs]) if shape_key not in self._compilation_cache: logging.info( 'New input shapes; (re-)compiling: mode=%s ' '(# of cores %d), %s', self.execution_mode, self._tpu_assignment.num_towers, input_specs) new_tpu_model_ops = self._specialize_model(input_specs, infeed_manager) self._compilation_cache[shape_key] = new_tpu_model_ops self._test_model_compiles(new_tpu_model_ops) return self._compilation_cache[shape_key] def _construct_input_tensors_and_inputs(self, inputs): """Returns input tensors and numpy array inputs corresponding to `inputs`. Args: inputs: NumPy inputs. Returns: A tuple of `input_tensors`, and `inputs`. """ if inputs is None: # Note: this condition is possible during the prologue or epilogue of the # pipelined loop. return None, None if isinstance(inputs[-1], int): # Remove the learning_phase flag at the end. We currently hard code the # learning_phase in TPUFunction. inputs = inputs[:-1] if (self.execution_mode == model_fn_lib.ModeKeys.TRAIN or self.execution_mode == model_fn_lib.ModeKeys.EVAL): # Strip sample weight from inputs. input_tensors = self.model._feed_inputs + self.model._feed_targets else: input_tensors = self.model._feed_inputs inputs = inputs[:len(input_tensors)] input_tensors, inputs = ( _inject_tpu_inputs_for_infeed( self._tpu_assignment, self.execution_mode, self._core_id_place_holder, input_tensors, inputs)) return input_tensors, inputs def _process_outputs(self, outfeed_outputs): """Processes the outputs of a model function execution. Args: outfeed_outputs: The sharded outputs of the TPU computation. Returns: The aggregated outputs of the TPU computation to be used in the rest of the model execution. """ # TODO(xiejw): Decide how to reduce outputs, or discard all but first. if self.execution_mode == model_fn_lib.ModeKeys.PREDICT: outputs = [[] for _ in range(len(self._outfeed_spec))] outputs_per_replica = len(self._outfeed_spec) for i in range(self._tpu_assignment.num_towers): output_group = outfeed_outputs[i * outputs_per_replica:(i + 1) * outputs_per_replica] for j in range(outputs_per_replica): outputs[j].append(output_group[j]) return [np.concatenate(group) for group in outputs] else: return outfeed_outputs[:len(outfeed_outputs) // self._tpu_assignment.num_towers] def __call__(self, inputs): """__call__ executes the function on the computational hardware. It handles executing infeed, and preprocessing in addition to executing the model on the TPU hardware. Note: `__call__` has a sibling method `pipeline_run` which performs the same operations, but with software pipelining. Args: inputs: The inputs to use to train. Returns: The output of the computation for the given mode it is executed in. Raises: RuntimeError: If there is an inappropriate use of the function. """ assert isinstance(inputs, list) infeed_manager = self._lookup_infeed_manager(inputs) input_tensors, inputs = self._construct_input_tensors_and_inputs(inputs) infeed_instance = infeed_manager.make_infeed_instance(inputs) del inputs # To avoid accident usage. input_specs = infeed_instance.make_input_specs(input_tensors) tpu_model_ops = self._tpu_model_ops_for_input_specs(input_specs, infeed_manager) infeed_dict = infeed_instance.make_feed_dict(tpu_model_ops) # Initialize our TPU weights on the first compile. self.model._initialize_weights(self._cloned_model) _, _, outfeed_outputs = K.get_session().run([ tpu_model_ops.infeed_op, tpu_model_ops.execute_op, tpu_model_ops.outfeed_op ], infeed_dict) return self._process_outputs(outfeed_outputs) def pipeline_run(self, cur_step_inputs, next_step_inputs): """pipeline_run executes the function on the computational hardware. pipeline_run performs the same computation as __call__, however it runs the infeed in a software pipelined fashion compared to the on-device execution. Note: it is the responsibility of the caller to call `pipeline_run` in the following sequence: - Once with `cur_step_inputs=None` and `next_step_inputs=list(...)` - `n` times with `cur_step_inputs` and `next_step_inputs` as `list`s - Once with `cur_step_inputs=list(...)` and `next_step_inputs=None` Additionally, it is the responsibility of the caller to pass `next_step_inputs` as `cur_step_inputs` on the next invocation of `pipeline_run`. Args: cur_step_inputs: The current step's inputs. next_step_inputs: The next step's inputs. Returns: The output of the computation for the given mode it is executed in. Raises: RuntimeError: If there is an inappropriate use of the function. """ # Software pipelined case. next_step_infeed_manager = self._lookup_infeed_manager(next_step_inputs) cur_step_infeed_manager = self._lookup_infeed_manager(cur_step_inputs) if (next_step_infeed_manager is not None and cur_step_infeed_manager is not None): assert type(next_step_infeed_manager) is type(cur_step_infeed_manager) next_input_tensors, next_step_inputs = ( self._construct_input_tensors_and_inputs(next_step_inputs)) cur_input_tensors, cur_step_inputs = ( self._construct_input_tensors_and_inputs(cur_step_inputs)) cur_infeed_instance = None if cur_step_infeed_manager: cur_infeed_instance = cur_step_infeed_manager.make_infeed_instance( cur_step_inputs) next_infeed_instance = None if next_step_infeed_manager: next_infeed_instance = next_step_infeed_manager.make_infeed_instance( next_step_inputs) del cur_step_inputs # Avoid accidental re-use. del next_step_inputs # Avoid accidental re-use. cur_tpu_model_ops = None next_tpu_model_ops = None infeed_dict = None if cur_infeed_instance and cur_input_tensors and cur_step_infeed_manager: cur_input_specs = cur_infeed_instance.make_input_specs(cur_input_tensors) cur_tpu_model_ops = self._tpu_model_ops_for_input_specs( cur_input_specs, cur_step_infeed_manager) if (next_infeed_instance and next_input_tensors and next_step_infeed_manager): next_input_specs = next_infeed_instance.make_input_specs( next_input_tensors) next_tpu_model_ops = self._tpu_model_ops_for_input_specs( next_input_specs, next_step_infeed_manager) infeed_dict = next_infeed_instance.make_feed_dict(next_tpu_model_ops) # Initialize our TPU weights on the first compile. self.model._initialize_weights(self._cloned_model) if next_tpu_model_ops and cur_tpu_model_ops: _, _, outfeed_outputs = K.get_session().run([ next_tpu_model_ops.infeed_op, cur_tpu_model_ops.execute_op, cur_tpu_model_ops.outfeed_op ], infeed_dict) return self._process_outputs(outfeed_outputs) if cur_tpu_model_ops: _, outfeed_outputs = K.get_session().run( [cur_tpu_model_ops.execute_op, cur_tpu_model_ops.outfeed_op]) return self._process_outputs(outfeed_outputs) if next_tpu_model_ops: K.get_session().run(next_tpu_model_ops.infeed_op, infeed_dict) return None raise RuntimeError('Internal error: both current & next tpu_model_ops ' 'were None') class KerasTPUModel(models.Model): """TPU compatible Keras model wrapper.""" def __init__(self, cpu_model, strategy): super(models.Model, self).__init__( # pylint: disable=bad-super-call inputs=cpu_model.inputs, outputs=cpu_model.outputs, name=cpu_model.name, ) if tf2.enabled(): raise RuntimeError( 'Keras support is now deprecated in support of TPU Strategy. ' 'Please follow the distribution strategy guide on tensorflow.org ' 'to migrate to the 2.0 supported version.') else: logging.warning( 'Keras support is now deprecated in support of TPU Strategy. ' 'Please follow the distribution strategy guide on tensorflow.org ' 'to migrate to the 2.0 supported version.') # Create a mapping from numpy arrays to infeed managers. # Note: uses a list of tuples instead of a map because numpy arrays are # not hashable. self._numpy_to_infeed_manager_list = [] # Add distribution specific arguments since we don't call the Model init. self._distribution_strategy = None self._compile_distribution = None self.predict_function = None self.test_function = None self.train_function = None self._stateful_metric_functions = [] cluster_resolver = strategy._tpu_cluster_resolver self._tpu_name_or_address = cluster_resolver.get_master() self._cpu_model = cpu_model self._tpu_assignment = strategy._make_assignment_for_model(cpu_model) self._tpu_model = None self._tpu_weights_initialized = False # If the input CPU model has already been compiled, compile our TPU model # immediately. if self._cpu_model.optimizer: self.compile( self._cpu_model.optimizer, self._cpu_model.loss, self._cpu_model._compile_metrics, self._cpu_model.loss_weights, self._cpu_model.sample_weight_mode, self._cpu_model._compile_weighted_metrics, self._cpu_model.target_tensors, ) # This flag must be disabled upon model mutation, such as changing the model # layers or recompiling the model to use a different optimizer. New function # definitions are generated whenever this flag is disabled, ensuring that # internal graph functions are always using the current model structure. # # Requires declaration here because this constructor skips the # Model constructor. self._built_graph_functions = False def get_config(self): return { 'cpu_model': self._cpu_model, 'tpu_name_or_address': self._tpu_name_or_address, 'tpu_assignment': self._tpu_assignment, } def compile(self, optimizer, loss=None, metrics=None, loss_weights=None, sample_weight_mode=None, weighted_metrics=None, target_tensors=None, **kwargs): if sample_weight_mode: raise ValueError('sample_weight_mode not supported for TPU execution.') if weighted_metrics: raise ValueError('weighted_metrics not supported for TPU execution.') if target_tensors: raise ValueError('target_tensors is not supported for TPU execution.') self._cpu_model.compile( _clone_optimizer(optimizer), loss, metrics_module.clone_metrics(metrics), loss_weights, sample_weight_mode, metrics_module.clone_metrics(weighted_metrics), target_tensors, **kwargs) super(KerasTPUModel, self).compile(optimizer, loss, metrics, loss_weights, sample_weight_mode, weighted_metrics, target_tensors, **kwargs) def fit(self, x=None, y=None, batch_size=None, epochs=1, verbose=1, callbacks=None, validation_split=0., validation_data=None, shuffle=True, class_weight=None, sample_weight=None, initial_epoch=0, steps_per_epoch=None, validation_steps=None, **kwargs): if context.executing_eagerly(): raise EnvironmentError('KerasTPUModel currently does not support eager ' 'mode.') with _tpu_session_context(): assert not self._numpy_to_infeed_manager_list # Ensure empty. infeed_managers = [] # Managers to clean up at the end of the fit call. if isinstance(x, dataset_ops.DatasetV2): # TODO(b/111413240): Support taking a tf.data.Dataset directly. raise ValueError( 'Taking a Dataset directly is not yet supported. Please ' 'wrap your dataset construction code in a function and ' 'pass that to fit instead. For examples, see: ' 'https://github.com/tensorflow/tpu/tree/master/models/experimental' '/keras') if callable(x): with ops.device( '/job:%s/device:CPU:0' % self._tpu_assignment.worker_name): dataset = x() if steps_per_epoch is None: raise ValueError('When using tf.data as input to a model, you ' 'should specify the steps_per_epoch argument.') if y is not None: raise ValueError('When using tf.data as input to a model, y must ' 'be None') infeed_manager = TPUDatasetInfeedManager( dataset, self._tpu_assignment, model_fn_lib.ModeKeys.TRAIN) # Use dummy numpy inputs for the rest of Keras' shape checking. We # intercept them when building the model. x = infeed_manager.dummy_x y = infeed_manager.dummy_y infeed_managers.append((x, infeed_manager)) if isinstance(validation_data, dataset_ops.DatasetV2): # TODO(b/111413240): Support taking a tf.data.Dataset directly. raise ValueError( 'Taking a Dataset directly is not yet supported. Please ' 'wrap your dataset construction code in a function and ' 'pass that to fit instead. For examples, see: ' 'https://github.com/tensorflow/tpu/tree/master/models/experimental' '/keras') if callable(validation_data): dataset = validation_data() if validation_steps is None: raise ValueError('When using tf.data as validation for a model, you ' 'should specify the validation_steps argument.') infeed_manager = TPUDatasetInfeedManager(dataset, self._tpu_assignment, model_fn_lib.ModeKeys.EVAL) # Use dummy numpy inputs for the rest of Keras' shape checking. We # intercept them when building the model. val_x = infeed_manager.dummy_x val_y = infeed_manager.dummy_y infeed_managers.append((val_x, infeed_manager)) validation_data = (val_x, val_y) self._numpy_to_infeed_manager_list = infeed_managers try: pipeline = kwargs.get('_pipeline', True) if '_pipeline' in kwargs: kwargs.pop('_pipeline') if not pipeline: logging.info('Running non-pipelined training loop (`_pipeline=%s`).', pipeline) return super(KerasTPUModel, self).fit( x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, **kwargs) return self._pipeline_fit(x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, **kwargs) finally: self._numpy_to_infeed_manager_list = [] def evaluate(self, x=None, y=None, batch_size=None, verbose=1, sample_weight=None, steps=None): original_numpy_to_infeed_manager_list = [] if self._numpy_to_infeed_manager_list: # evaluate call may be executed as callbacks during the training. In this # case, _numpy_to_infeed_manager_list is not empty, so save it for # recovery at the end of evaluate call. original_numpy_to_infeed_manager_list = self._numpy_to_infeed_manager_list self._numpy_to_infeed_manager_list = [] with _tpu_session_context(): # Managers to clean up at the end of the evaluate call. infeed_managers = [] if isinstance(x, dataset_ops.DatasetV2): # TODO(b/111413240): Support taking a tf.data.Dataset directly. raise ValueError( 'Taking a Dataset directly is not yet supported. Please ' 'wrap your dataset construction code in a function and ' 'pass that to fit instead. For examples, see: ' 'https://github.com/tensorflow/tpu/tree/master/models/experimental' '/keras') if callable(x): dataset = x() if steps is None: raise ValueError('When using tf.data as input to a model, you ' 'should specify the steps argument.') if y is not None: raise ValueError('When using tf.data as input to a model, y must be ' 'None') infeed_manager = TPUDatasetInfeedManager(dataset, self._tpu_assignment, model_fn_lib.ModeKeys.EVAL) # Use dummy numpy inputs for the rest of Keras' shape checking. We # intercept them when building the model. x = infeed_manager.dummy_x y = infeed_manager.dummy_y infeed_managers.append((x, infeed_manager)) self._numpy_to_infeed_manager_list = infeed_managers try: return super(KerasTPUModel, self).evaluate(x, y, batch_size, verbose, sample_weight, steps) finally: self._numpy_to_infeed_manager_list = ( original_numpy_to_infeed_manager_list) def _pipeline_fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, **kwargs): # Similar to super.fit(...), but modified to support software pipelining. # Backwards compatibility if batch_size is None and steps_per_epoch is None: batch_size = 32 # Legacy support if 'nb_epoch' in kwargs: logging.warning('The `nb_epoch` argument in `fit` has been renamed ' '`epochs`.') epochs = kwargs.pop('nb_epoch') if kwargs: raise TypeError('Unrecognized keyword arguments: ' + str(kwargs)) # Validate and standardize user data x, y, sample_weights = self._standardize_user_data( x, y, sample_weight=sample_weight, class_weight=class_weight, batch_size=batch_size, check_steps=True, steps_name='steps_per_epoch', steps=steps_per_epoch, validation_split=validation_split) # Prepare validation data x, y, val_x, val_y, val_sample_weights = self._prepare_validation_data( validation_data, validation_split, validation_steps, x, y, sample_weights, batch_size) return self._pipeline_fit_loop( x, y, sample_weights=sample_weights, batch_size=batch_size, epochs=epochs, verbose=verbose, callbacks=callbacks, val_inputs=val_x, val_targets=val_y, val_sample_weights=val_sample_weights, shuffle=shuffle, initial_epoch=initial_epoch, steps_per_epoch=steps_per_epoch, validation_steps=validation_steps) def _pipeline_fit_loop(self, inputs, targets, sample_weights, batch_size, epochs, verbose, callbacks, val_inputs, val_targets, val_sample_weights, shuffle, initial_epoch, steps_per_epoch, validation_steps): self._make_train_function() sample_weights = sample_weights or [] val_sample_weights = val_sample_weights or [] if not isinstance(K.learning_phase(), int): ins = inputs + targets + sample_weights + [1] else: ins = inputs + targets + sample_weights do_validation = False if val_inputs: do_validation = True if (steps_per_epoch is None and verbose and inputs and hasattr(inputs[0], 'shape') and hasattr(val_inputs[0], 'shape')): print('Train on %d samples, validate on %d samples' % (inputs[0].shape[0], val_inputs[0].shape[0])) if validation_steps: do_validation = True if steps_per_epoch is None: raise ValueError('Can only use `validation_steps` when doing step-wise ' 'training, i.e. `steps_per_epoch` must be set.') num_training_samples = training_utils.check_num_samples( ins, batch_size, steps_per_epoch, 'steps_per_epoch') count_mode = 'steps' if steps_per_epoch else 'samples' callbacks = cbks.configure_callbacks( callbacks, self, do_validation=do_validation, batch_size=batch_size, epochs=epochs, steps_per_epoch=steps_per_epoch, samples=num_training_samples, verbose=verbose, count_mode=count_mode) if num_training_samples is not None: index_array = np.arange(num_training_samples) # To prevent a slowdown, we find beforehand the arrays that need conversion. feed = self._feed_inputs + self._feed_targets + self._feed_sample_weights indices_for_conversion_to_dense = [] for i in range(len(feed)): if issparse is not None and issparse(ins[i]) and not K.is_sparse(feed[i]): indices_for_conversion_to_dense.append(i) callbacks.on_train_begin() for epoch in range(initial_epoch, epochs): # Reset stateful metrics for m in self.metrics: m.reset_states() # Update callbacks callbacks.on_epoch_begin(epoch) epoch_logs = {} if steps_per_epoch is not None: # Step-wise fit loop. self._pipeline_fit_loop_step_wise( ins=ins, callbacks=callbacks, steps_per_epoch=steps_per_epoch, epochs=epochs, do_validation=do_validation, val_inputs=val_inputs, val_targets=val_targets, val_sample_weights=val_sample_weights, validation_steps=validation_steps, epoch_logs=epoch_logs) else: # Sample-wise fit loop. self._pipeline_fit_loop_sample_wise( ins=ins, callbacks=callbacks, index_array=index_array, shuffle=shuffle, batch_size=batch_size, num_training_samples=num_training_samples, indices_for_conversion_to_dense=indices_for_conversion_to_dense, do_validation=do_validation, val_inputs=val_inputs, val_targets=val_targets, val_sample_weights=val_sample_weights, validation_steps=validation_steps, epoch_logs=epoch_logs) callbacks.on_epoch_end(epoch, epoch_logs) if callbacks.model.stop_training: break callbacks.on_train_end() return self.history def _pipeline_fit_loop_sample_wise(self, ins, callbacks, index_array, shuffle, batch_size, num_training_samples, indices_for_conversion_to_dense, do_validation, val_inputs, val_targets, val_sample_weights, validation_steps, epoch_logs): f = self.train_function if shuffle == 'batch': index_array = training_utils.batch_shuffle(index_array, batch_size) elif shuffle: np.random.shuffle(index_array) batches = make_batches(num_training_samples, batch_size) ins_last_batch = None last_batch_logs = None batch_index = 0 for batch_index, (batch_start, batch_end) in enumerate(batches): batch_ids = index_array[batch_start:batch_end] try: if isinstance(ins[-1], int): # Do not slice the training phase flag. ins_batch = slice_arrays(ins[:-1], batch_ids) + [ins[-1]] else: ins_batch = slice_arrays(ins, batch_ids) except TypeError: raise TypeError('TypeError while preparing batch. If using HDF5 ' 'input data, pass shuffle="batch".') # Pipeline batch logs next_batch_logs = {} next_batch_logs['batch'] = batch_index next_batch_logs['size'] = len(batch_ids) if batch_index > 0: # Callbacks operate one step behind in software pipeline. callbacks.on_batch_begin(batch_index - 1, last_batch_logs) for i in indices_for_conversion_to_dense: ins_batch[i] = ins_batch[i].toarray() outs = f.pipeline_run( cur_step_inputs=ins_last_batch, next_step_inputs=ins_batch) ins_last_batch = ins_batch if batch_index == 0: assert outs is None else: if not isinstance(outs, list): outs = [outs] for l, o in zip(self.metrics_names, outs): last_batch_logs[l] = o # pylint: disable=unsupported-assignment-operation callbacks.on_batch_end(batch_index - 1, last_batch_logs) if callbacks.model.stop_training: return last_batch_logs = next_batch_logs # Final batch callbacks.on_batch_begin(batch_index, last_batch_logs) outs = f.pipeline_run(cur_step_inputs=ins_last_batch, next_step_inputs=None) if not isinstance(outs, list): outs = [outs] for l, o in zip(self.metrics_names, outs): last_batch_logs[l] = o callbacks.on_batch_end(batch_index, last_batch_logs) if callbacks.model.stop_training: return if do_validation: val_outs = training_arrays.test_loop( self, val_inputs, val_targets, sample_weights=val_sample_weights, batch_size=batch_size, steps=validation_steps, verbose=0) if not isinstance(val_outs, list): val_outs = [val_outs] # Same labels assumed. for l, o in zip(self.metrics_names, val_outs): epoch_logs['val_' + l] = o def _pipeline_fit_loop_step_wise(self, ins, callbacks, steps_per_epoch, epochs, do_validation, val_inputs, val_targets, val_sample_weights, validation_steps, epoch_logs): f = self.train_function # Loop prologue try: outs = f.pipeline_run(cur_step_inputs=None, next_step_inputs=ins) assert outs is None # Function shouldn't return anything! except errors.OutOfRangeError: logging.warning('Your dataset iterator ran out of data on the first step ' 'of the epoch, preventing further training. Check to ' 'make sure your paths are correct and you have ' 'permissions to read the files. Skipping validation') for step_index in range(steps_per_epoch): batch_logs = {'batch': step_index, 'size': 1} callbacks.on_batch_begin(step_index, batch_logs) try: if step_index < steps_per_epoch - 1: next_step_inputs = ins else: next_step_inputs = None outs = f.pipeline_run( cur_step_inputs=ins, next_step_inputs=next_step_inputs) except errors.OutOfRangeError: logging.warning('Your dataset iterator ran out of data; ' 'interrupting training. Make sure that your ' 'dataset can generate at least `steps_per_batch * ' 'epochs` batches (in this case, %d batches). You ' 'may need to use the repeat() function when ' 'building your dataset.' % steps_per_epoch * epochs) break if not isinstance(outs, list): outs = [outs] for l, o in zip(self.metrics_names, outs): batch_logs[l] = o callbacks.on_batch_end(step_index, batch_logs) if callbacks.model.stop_training: break if do_validation: val_outs = training_arrays.test_loop( self, val_inputs, val_targets, sample_weights=val_sample_weights, steps=validation_steps, verbose=0) if not isinstance(val_outs, list): val_outs = [val_outs] # Same labels assumed. for l, o in zip(self.metrics_names, val_outs): epoch_logs['val_' + l] = o def _prepare_validation_data(self, validation_data, validation_split, validation_steps, x, y, sample_weights, batch_size): """Prepares the validation dataset. Args: validation_data: The validation data (if provided) validation_split: The validation split (if provided) validation_steps: The validation steps (if provided) x: The main training data x (if provided) y: The main training data y (if provided) sample_weights: The sample weights (if provided) batch_size: The training batch size (if provided) Returns: A 5-tuple of (x, y, val_x, val_y, val_sample_weights). Raises: ValueError: If the provided arguments are not compatible with `KerasTPUModel`. """ # Note: this is similar to a section of $tf/python/keras/engine/training.py # It differns in that tf.data objects are not allowed to be passed directly. # Additionally, it handles validating shapes & types appropriately for use # in TPUs. if validation_data: if (isinstance(validation_data, iterator_ops.Iterator) or isinstance(validation_data, iterator_ops.IteratorV2) or isinstance(validation_data, dataset_ops.DatasetV2)): raise ValueError('KerasTPUModel cannot handle a Dataset or Iterator ' 'for validation_data. Please instead pass a function ' 'that returns a `tf.data.Dataset`.') if len(validation_data) == 2: val_x, val_y = validation_data # pylint: disable=unpacking-non-sequence val_sample_weight = None elif len(validation_data) == 3: val_x, val_y, val_sample_weight = validation_data # pylint: disable=unpacking-non-sequence else: raise ValueError('When passing a `validation_data` argument, it must ' 'contain either 2 items (x_val, y_val), or 3 items ' '(x_val, y_val, val_sample_weights). However we ' 'received `validation_data=%s`' % validation_data) val_x, val_y, val_sample_weights = self._standardize_user_data( val_x, val_y, sample_weight=val_sample_weight, batch_size=batch_size, steps=validation_steps) elif validation_split and 0. < validation_split < 1.: if training_utils.has_symbolic_tensors(x): raise ValueError('If your data is in the form of symbolic tensors, you ' 'cannot use `validation_split`.') if hasattr(x[0], 'shape'): split_at = int(x[0].shape[0] * (1. - validation_split)) else: split_at = int(len(x[0]) * (1. - validation_split)) x, val_x = (slice_arrays(x, 0, split_at), slice_arrays(x, split_at)) y, val_y = (slice_arrays(y, 0, split_at), slice_arrays(y, split_at)) sample_weights, val_sample_weights = ( slice_arrays(sample_weights, 0, split_at), slice_arrays(sample_weights, split_at) ) elif validation_steps: val_x = [] val_y = [] val_sample_weights = [] else: val_x = None val_y = None val_sample_weights = None return x, y, val_x, val_y, val_sample_weights def predict(self, x, batch_size=None, verbose=0, steps=None, max_queue_size=10, workers=1, use_multiprocessing=False): with _tpu_session_context(): return super(KerasTPUModel, self).predict( x, batch_size=batch_size, verbose=verbose, steps=steps, max_queue_size=max_queue_size, workers=workers, use_multiprocessing=use_multiprocessing) @property def optimizer(self): if self._tpu_model: return self._tpu_model.optimizer return self._cpu_model.optimizer @optimizer.setter def optimizer(self, optimizer): self._optimizer = optimizer @property def metrics(self): if self._tpu_model: return self._tpu_model.metrics return self._stateful_metric_functions @metrics.setter def metrics(self, metrics): self._stateful_metric_functions = metrics def _make_train_function(self): if not self.train_function: self.train_function = TPUFunction( self, model_fn_lib.ModeKeys.TRAIN, tpu_assignment=self._tpu_assignment) return self.train_function def _make_test_function(self): if not self.test_function: self.test_function = TPUFunction( self, model_fn_lib.ModeKeys.EVAL, tpu_assignment=self._tpu_assignment) return self.test_function def _make_predict_function(self): if not self.predict_function: self.predict_function = TPUFunction( self, model_fn_lib.ModeKeys.PREDICT, tpu_assignment=self._tpu_assignment) return self.predict_function def _initialize_weights(self, cloned_model): """Initialize TPU weights. This is called on the first compile of the TPU model (first call to fit/predict/evaluate). Args: cloned_model: `keras.Model`, TPU model to initialize. """ if self._tpu_weights_initialized: return self._tpu_model = cloned_model self._tpu_weights_initialized = True weights = self._cpu_model.get_weights() if isinstance(self.cpu_optimizer, keras_optimizers.TFOptimizer): cpu_optimizer_config = {} else: cpu_optimizer_config = self.cpu_optimizer.get_config() logging.info('Setting weights on TPU model.') cloned_model.set_weights(weights) if self._tpu_model.optimizer is None: # tpu_model may not be compiled, e.g., loading weights and then predict. return for k, v in six.iteritems(cpu_optimizer_config): if k == 'name': continue opt_var = getattr(self._tpu_model.optimizer, k) if isinstance(opt_var, variables.Variable): logging.info('CPU -> TPU %s: %s {%s}', k, v, K.get_value(opt_var)) K.get_session().run(opt_var.assign(v)) else: logging.warning('Cannot update non-variable config: %s', k) @property def cpu_optimizer(self): return self._cpu_model.optimizer def sync_to_cpu(self): """Copy weights from the CPU, returning a synchronized CPU model.""" if not self._tpu_weights_initialized: return self._cpu_model logging.info('Copying TPU weights to the CPU') tpu_weights = self._tpu_model.get_weights() # TFOptimizers have no configurable options if isinstance(self.cpu_optimizer, keras_optimizers.TFOptimizer): tpu_optimizer_config = {} else: tpu_optimizer_config = self._tpu_model.optimizer.get_config() self._cpu_model.set_weights(tpu_weights) for k, v in six.iteritems(tpu_optimizer_config): logging.info('TPU -> CPU %s: %s', k, v) if k == 'name': continue opt_var = getattr(self.cpu_optimizer, k) if isinstance(opt_var, variables.Variable): K.get_session().run(opt_var.assign(v)) else: logging.warning('Cannot update non-variable config: %s', k) return self._cpu_model def get_weights(self): return self.sync_to_cpu().get_weights() def save_weights(self, *args, **kw): return self.sync_to_cpu().save_weights(*args, **kw) def save(self, *args, **kw): return self.sync_to_cpu().save(*args, **kw) def set_weights(self, weights): # We may not have a TPU model available if we haven't run fit/predict, so # we can't directly set the TPU weights here. # Instead, reset CPU model weights and force TPU re-initialization at the # next call. self._cpu_model.set_weights(weights) self._tpu_weights_initialized = False def load_weights(self, filepath, by_name=False): self._cpu_model.load_weights(filepath, by_name) self._tpu_weights_initialized = False # pylint: disable=bad-continuation def _validate_shapes(model): """Validate that all layers in `model` have constant shape.""" for layer in model.layers: if isinstance(layer.input_shape, tuple): input_shapes = [layer.input_shape] else: input_shapes = layer.input_shape if isinstance(layer.output_shape, tuple): output_shapes = [layer.output_shape] else: output_shapes = layer.output_shape for shape in input_shapes + output_shapes: for dim in shape[1:]: if dim is None: raise ValueError( """ Layer %(layer)s has a variable shape in a non-batch dimension. TPU models must have constant shapes for all operations. You may have to specify `input_length` for RNN/TimeDistributed layers. Layer: %(layer)s Input shape: %(input_shape)s Output shape: %(output_shape)s """ % { 'layer': layer, 'input_shape': layer.input_shape, 'output_shape': layer.output_shape }) # pylint: enable=bad-continuation @deprecated( '2019-02-20', 'Switch to tf.contrib.distribute.TPUStrategy. ' 'https://www.tensorflow.org/api_docs/python/tf/contrib/distribute/DistributionStrategy' ) def tpu_model(model, strategy=None): """Copy `model` along with weights to the TPU. Returns a TPU model. Usage: ``` a = Input(shape=(32,)) b = Dense(32)(a) model = Model(inputs=a, outputs=b) # If `num_cores_per_host` is greater than one, batch parallelism will be used # to run on multiple TPU cores. strategy = keras_support.TPUDistributionStrategy(tpu_cluster_resolver) model = keras_support.tpu_model(model, strategy) model.compile( optimizer=tf.compat.v1.train.GradientDescentOptimizer(learning_rate=1.0), ...) ``` Args: model: A `tf.keras.Model` instance. strategy: `TPUDistributionStrategy`. The strategy to use for replicating model across multiple TPU cores. Returns: A new `KerasTPUModel` instance. """ _validate_shapes(model) # TODO(xiejw): Validate TPU model. TPUModel only? # TODO(xiejw): Validate replicas. Full or 1. Shall we allow subset? # TODO(xiejw): Adds reduction option. if strategy is None: strategy = TPUDistributionStrategy() else: if not isinstance(strategy, TPUDistributionStrategy): raise TypeError( '`strategy` must have type `tf.contrib.tpu.TPUDistributionStrategy`. ' 'Got: {}'.format(type(strategy))) # If the model has already been initialized, grab the optimizer configuration # and model weights before entering the TPU session. if model.optimizer: if (isinstance(model.optimizer, keras_optimizers.Optimizer) and not isinstance(model.optimizer, keras_optimizers.TFOptimizer)): optimizer_config = model.optimizer.get_config() else: optimizer_config = None model_weights = model.get_weights() else: model_weights = None setup_tpu_session(strategy._tpu_cluster_resolver) # Force initialization of the CPU model in the TPU session. cpu_model = models.clone_model(model) if model.optimizer: cpu_model.compile( _clone_optimizer(model.optimizer, optimizer_config), model.loss, metrics_module.clone_metrics(model._compile_metrics), model.loss_weights, model.sample_weight_mode, metrics_module.clone_metrics(model._compile_weighted_metrics), ) if model_weights: cpu_model.set_weights(model_weights) cpu_model.reset_states() return KerasTPUModel(cpu_model=cpu_model, strategy=strategy)
tensorflow-master
tensorflow/contrib/tpu/python/tpu/keras_support.py
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Stub file to maintain backwards compatibility.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # pylint: disable=wildcard-import,unused-import from tensorflow.python.tpu.tpu_function import * # pylint: enable=wildcard-import,unused-import
tensorflow-master
tensorflow/contrib/tpu/python/tpu/tpu_function.py
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Stub file to maintain backwards compatibility.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # pylint: disable=wildcard-import,unused-import from tensorflow.python.tpu.training_loop import * # pylint: enable=wildcard-import,unused-import
tensorflow-master
tensorflow/contrib/tpu/python/tpu/training_loop.py
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Stub file to maintain backwards compatibility.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # pylint: disable=wildcard-import,unused-import from tensorflow_estimator.python.estimator.tpu.tpu_config import * # pylint: enable=wildcard-import,unused-import
tensorflow-master
tensorflow/contrib/tpu/python/tpu/tpu_config.py
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Stub file to maintain backwards compatibility.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # pylint: disable=wildcard-import,unused-import from tensorflow_estimator.python.estimator.tpu.error_handling import * # pylint: enable=wildcard-import,unused-import
tensorflow-master
tensorflow/contrib/tpu/python/tpu/error_handling.py
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Stub file to maintain backwards compatibility.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # pylint: disable=wildcard-import,unused-import from tensorflow.python.tpu.tpu_optimizer import * # pylint: enable=wildcard-import,unused-import
tensorflow-master
tensorflow/contrib/tpu/python/tpu/tpu_optimizer.py
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Stub file to maintain backwards compatibility.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # pylint: disable=wildcard-import,unused-import from tensorflow.python.tpu.functional import * # pylint: enable=wildcard-import,unused-import
tensorflow-master
tensorflow/contrib/tpu/python/tpu/functional.py
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Stub file to maintain backwards compatibility.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # pylint: disable=wildcard-import,unused-import,redefined-builtin from tensorflow.python.tpu.tpu_sharding import * # pylint: enable=wildcard-import,unused-import,redefined-builtin
tensorflow-master
tensorflow/contrib/tpu/python/tpu/tpu_sharding.py
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Stub file to maintain backwards compatibility.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # pylint: disable=wildcard-import,unused-import,redefined-builtin from tensorflow.python.tpu.tpu import * # used by tests from tensorflow.python.tpu.tpu import _TPU_REPLICATE_ATTR # pylint: enable=wildcard-import,unused-import,redefined-builtin
tensorflow-master
tensorflow/contrib/tpu/python/tpu/tpu.py
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Stub file to maintain backwards compatibility.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # pylint: disable=wildcard-import,unused-import from tensorflow.python.tpu.session_support import * # pylint: enable=wildcard-import,unused-import
tensorflow-master
tensorflow/contrib/tpu/python/tpu/session_support.py
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Stub file to maintain backwards compatibility.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # pylint: disable=wildcard-import,unused-import,redefined-builtin from tensorflow.python.tpu.topology import * # pylint: enable=wildcard-import,unused-import,redefined-builtin
tensorflow-master
tensorflow/contrib/tpu/python/tpu/topology.py
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Stub file to maintain backwards compatibility.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # pylint: disable=wildcard-import,unused-import from tensorflow_estimator.python.estimator.tpu.tpu_context import * # pylint: enable=wildcard-import,unused-import
tensorflow-master
tensorflow/contrib/tpu/python/tpu/tpu_context.py
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Stub file to maintain backwards compatibility.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # pylint: disable=wildcard-import,unused-import from tensorflow.python.tpu.async_checkpoint import * # pylint: enable=wildcard-import,unused-import
tensorflow-master
tensorflow/contrib/tpu/python/tpu/async_checkpoint.py
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Stub file to maintain backwards compatibility.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # pylint: disable=wildcard-import,unused-import from tensorflow.python.tpu.bfloat16 import * # pylint: enable=wildcard-import,unused-import
tensorflow-master
tensorflow/contrib/tpu/python/tpu/bfloat16.py
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Stub file to maintain backwards compatibility.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # pylint: disable=wildcard-import,unused-import from tensorflow.python.tpu.tpu_system_metadata import * # used by tests from tensorflow.python.tpu.tpu_system_metadata import _query_tpu_system_metadata # pylint: enable=wildcard-import,unused-import
tensorflow-master
tensorflow/contrib/tpu/python/tpu/tpu_system_metadata.py
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Stub file to maintain backwards compatibility.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # pylint: disable=wildcard-import,unused-import,redefined-builtin from tensorflow.python.tpu.tpu_feed import * # used by tests from tensorflow.python.tpu.tpu_feed import _PartitionedInfeedQueue # pylint: enable=wildcard-import,unused-import,redefined-builtin
tensorflow-master
tensorflow/contrib/tpu/python/tpu/tpu_feed.py
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Stub file to maintain backwards compatibility.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # pylint: disable=wildcard-import,unused-import from tensorflow.python.tpu.tpu_embedding_gradient import * # pylint: enable=wildcard-import,unused-import
tensorflow-master
tensorflow/contrib/tpu/python/tpu/tpu_embedding_gradient.py
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Stub file to maintain backwards compatibility.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # pylint: disable=wildcard-import,unused-import from tensorflow_estimator.python.estimator.tpu._tpu_estimator_embedding import * # pylint: enable=wildcard-import,unused-import
tensorflow-master
tensorflow/contrib/tpu/python/tpu/_tpu_estimator_embedding.py
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Stub file to maintain backwards compatibility.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # pylint: disable=wildcard-import,unused-import,redefined-builtin from tensorflow_estimator.python.estimator.tpu.tpu_estimator import * # used by tests from tensorflow_estimator.python.estimator.tpu.tpu_estimator import _clone_export_output_with_tensors from tensorflow_estimator.python.estimator.tpu.tpu_estimator import _create_global_step from tensorflow_estimator.python.estimator.tpu.tpu_estimator import _export_output_to_tensors from tensorflow_estimator.python.estimator.tpu.tpu_estimator import _get_scaffold from tensorflow_estimator.python.estimator.tpu.tpu_estimator import _Inputs from tensorflow_estimator.python.estimator.tpu.tpu_estimator import _ITERATIONS_PER_LOOP_VAR from tensorflow_estimator.python.estimator.tpu.tpu_estimator import _TPU_ENQUEUE_OPS from tensorflow_estimator.python.estimator.tpu.tpu_estimator import _TPU_ESTIMATOR from tensorflow_estimator.python.estimator.tpu.tpu_estimator import _TPU_TRAIN_OP # pylint: enable=wildcard-import,unused-import,redefined-builtin
tensorflow-master
tensorflow/contrib/tpu/python/tpu/tpu_estimator.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================= """Cloud TPU profiler package.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from setuptools import setup _VERSION = '1.12.0' CONSOLE_SCRIPTS = [ 'capture_tpu_profile=cloud_tpu_profiler.main:run_main', ] setup( name='cloud_tpu_profiler', version=_VERSION.replace('-', ''), description='Trace and profile Cloud TPU performance', long_description='Tools for capture TPU profile', url='https://www.tensorflow.org/tfrc/', author='Google Inc.', author_email='packages@tensorflow.org', packages=['cloud_tpu_profiler'], package_data={ 'cloud_tpu_profiler': ['data/*'], }, entry_points={ 'console_scripts': CONSOLE_SCRIPTS, }, classifiers=[ # How mature is this project? Common values are # 3 - Alpha # 4 - Beta # 5 - Production/Stable 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Intended Audience :: Education', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Topic :: Scientific/Engineering', 'Topic :: Scientific/Engineering :: Mathematics', 'Topic :: Scientific/Engineering :: Artificial Intelligence', 'Topic :: Software Development', 'Topic :: Software Development :: Libraries', 'Topic :: Software Development :: Libraries :: Python Modules', ], license='Apache 2.0', keywords='tensorflow performance tpu', )
tensorflow-master
tensorflow/contrib/tpu/profiler/pip_package/setup.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================= """Cloud TPU profiler.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function
tensorflow-master
tensorflow/contrib/tpu/profiler/pip_package/cloud_tpu_profiler/__init__.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================= """Wraps capture_tpu_profile binary.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import subprocess import sys from absl import flags from distutils.version import LooseVersion import tensorflow as tf # Cloud TPU Cluster Resolvers flags.DEFINE_string( 'gcp_project', None, 'Project name for the Cloud TPU-enabled project. If not specified, we ' 'will attempt to automatically detect the GCE project from metadata.') flags.DEFINE_string( 'tpu_zone', None, help='GCE zone where the Cloud TPU is located in. If not specified, we ' 'will attempt to automatically detect the GCE project from metadata.') flags.DEFINE_string( 'tpu', None, 'Name of the Cloud TPU for Cluster Resolvers. You must ' 'specify either this flag or --service_addr.') # Tool specific parameters flags.DEFINE_string( 'service_addr', None, 'Address of TPU profiler service e.g. ' 'localhost:8466, you must specify either this flag or --tpu.') flags.DEFINE_string( 'workers_list', None, 'The list of worker TPUs that we are about to profile' ' e.g. 10.0.1.2, 10.0.1.3. You can specify this flag with --tpu or ' '--service_addr to profile a subset of tpu nodes. You can also use only' '--tpu and leave this flag unspecified to profile all the tpus.') flags.DEFINE_string( 'logdir', None, 'Path of TensorBoard log directory e.g. /tmp/tb_log, ' 'gs://tb_bucket') flags.DEFINE_integer('duration_ms', 0, 'Duration of tracing or monitoring in ms.') flags.DEFINE_integer( 'num_tracing_attempts', 3, 'Automatically retry N times when no trace ' 'event is collected.') flags.DEFINE_boolean('include_dataset_ops', True, 'Set to false to profile longer TPU ' 'device traces.') # Monitoring parameters flags.DEFINE_integer( 'monitoring_level', 0, 'Choose a monitoring level between ' '1 and 2 to monitor your TPU job continuously.') flags.DEFINE_integer( 'num_queries', 100, 'This script will run monitoring for num_queries before it stops.') FLAGS = flags.FLAGS EXECUTABLE = 'data/capture_tpu_profile' JOB_NAME = 'worker' def get_workers_list(cluster_resolver): cluster_spec = cluster_resolver.cluster_spec() task_indices = cluster_spec.task_indices(JOB_NAME) workers_list = [ cluster_spec.task_address(JOB_NAME, i).split(':')[0] for i in task_indices ] return ','.join(workers_list) def run_main(): tf.app.run(main) def main(unused_argv=None): tf.logging.set_verbosity(tf.logging.INFO) tf_version = tf.__version__ print('TensorFlow version %s detected' % tf_version) if not FLAGS.service_addr and not FLAGS.tpu: sys.exit('You must specify either --service_addr or --tpu.') tpu_cluster_resolver = None if FLAGS.service_addr: if FLAGS.tpu: tf.logging.warn('Both --service_addr and --tpu are set. Ignoring ' '--tpu and using --service_addr.') service_addr = FLAGS.service_addr else: tpu_cluster_resolver = ( tf.contrib.cluster_resolver.TPUClusterResolver( [FLAGS.tpu], zone=FLAGS.tpu_zone, project=FLAGS.gcp_project)) service_addr = tpu_cluster_resolver.get_master() service_addr = service_addr.replace('grpc://', '').replace(':8470', ':8466') workers_list = '' if LooseVersion(tf_version) < LooseVersion('1.9'): tf.logging.warn('Attempt to profile with legacy support under TensorFlow ' 'version %s' % tf_version) else: if FLAGS.workers_list is not None: workers_list = FLAGS.workers_list elif tpu_cluster_resolver is not None: workers_list = get_workers_list(tpu_cluster_resolver) if not FLAGS.logdir and not FLAGS.monitoring_level: sys.exit('logdir must be provided.') executable_path = os.path.join(os.path.dirname(__file__), EXECUTABLE) cmd = [executable_path] if FLAGS.logdir is not None: logdir = os.path.expandvars(os.path.expanduser(FLAGS.logdir)) cmd.append('--logdir=' + logdir) cmd.append('--service_addr=' + service_addr) cmd.append('--workers_list=' + workers_list) cmd.append('--duration_ms=' + str(FLAGS.duration_ms)) cmd.append('--num_tracing_attempts=' + str(FLAGS.num_tracing_attempts)) cmd.append('--include_dataset_ops=' + str(FLAGS.include_dataset_ops).lower()) cmd.append('--monitoring_level=' + str(FLAGS.monitoring_level)) cmd.append('--num_queries=' + str(FLAGS.num_queries)) subprocess.call(cmd) if __name__ == '__main__': run_main()
tensorflow-master
tensorflow/contrib/tpu/profiler/pip_package/cloud_tpu_profiler/main.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Slim is an interface to contrib functions, examples and models. TODO(nsilberman): flesh out documentation. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function # pylint: disable=unused-import,line-too-long,g-importing-member,wildcard-import # TODO(jart): Delete non-slim imports from tensorflow.contrib import losses from tensorflow.contrib import metrics from tensorflow.contrib.framework.python.ops.arg_scope import * from tensorflow.contrib.framework.python.ops.variables import * from tensorflow.contrib.layers.python.layers import * from tensorflow.contrib.layers.python.layers.initializers import * from tensorflow.contrib.layers.python.layers.regularizers import * from tensorflow.contrib.slim.python.slim import evaluation from tensorflow.contrib.slim.python.slim import learning from tensorflow.contrib.slim.python.slim import model_analyzer from tensorflow.contrib.slim.python.slim import queues from tensorflow.contrib.slim.python.slim import summaries from tensorflow.contrib.slim.python.slim.data import data_decoder from tensorflow.contrib.slim.python.slim.data import data_provider from tensorflow.contrib.slim.python.slim.data import dataset from tensorflow.contrib.slim.python.slim.data import dataset_data_provider from tensorflow.contrib.slim.python.slim.data import parallel_reader from tensorflow.contrib.slim.python.slim.data import prefetch_queue from tensorflow.contrib.slim.python.slim.data import tfexample_decoder from tensorflow.python.util.all_util import make_all # pylint: enable=unused-import,line-too-long,g-importing-member,wildcard-import __all__ = make_all(__name__)
tensorflow-master
tensorflow/contrib/slim/__init__.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """TF-Slim Nets. ## Standard Networks. @@alexnet_v2 @@inception_v1 @@inception_v1_base @@inception_v2 @@inception_v2_base @@inception_v3 @@inception_v3_base @@overfeat @@vgg_a @@vgg_16 """ from __future__ import absolute_import from __future__ import division from __future__ import print_function # pylint: disable=unused-import, # Collapse nets into a single namespace. from tensorflow.contrib.slim.python.slim.nets import alexnet from tensorflow.contrib.slim.python.slim.nets import inception from tensorflow.contrib.slim.python.slim.nets import overfeat from tensorflow.contrib.slim.python.slim.nets import resnet_utils from tensorflow.contrib.slim.python.slim.nets import resnet_v1 from tensorflow.contrib.slim.python.slim.nets import resnet_v2 from tensorflow.contrib.slim.python.slim.nets import vgg from tensorflow.python.util.all_util import make_all # pylint: enable=unused-import __all__ = make_all(__name__)
tensorflow-master
tensorflow/contrib/slim/nets.py
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Contains a helper context for running queue runners. @@NestedQueueRunnerError @@QueueRunners """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from contextlib import contextmanager import threading from tensorflow.python.framework import ops from tensorflow.python.training import coordinator __all__ = [ 'NestedQueueRunnerError', 'QueueRunners', ] _queue_runner_lock = threading.Lock() class NestedQueueRunnerError(Exception): pass @contextmanager def QueueRunners(session): """Creates a context manager that handles starting and stopping queue runners. Args: session: the currently running session. Yields: a context in which queues are run. Raises: NestedQueueRunnerError: if a QueueRunners context is nested within another. """ if not _queue_runner_lock.acquire(False): raise NestedQueueRunnerError('QueueRunners cannot be nested') coord = coordinator.Coordinator() threads = [] for qr in ops.get_collection(ops.GraphKeys.QUEUE_RUNNERS): threads.extend( qr.create_threads( session, coord=coord, daemon=True, start=True)) try: yield finally: coord.request_stop() try: coord.join(threads, stop_grace_period_secs=120) except RuntimeError: session.close() _queue_runner_lock.release()
tensorflow-master
tensorflow/contrib/slim/python/slim/queues.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for tensorflow.contrib.slim.summaries.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import glob import os from tensorflow.contrib.slim.python.slim import summaries from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.platform import gfile from tensorflow.python.platform import test from tensorflow.python.summary import summary from tensorflow.python.summary import summary_iterator class SummariesTest(test.TestCase): def safe_create(self, output_dir): if gfile.Exists(output_dir): gfile.DeleteRecursively(output_dir) gfile.MakeDirs(output_dir) def assert_scalar_summary(self, output_dir, names_to_values): """Asserts that the given output directory contains written summaries. Args: output_dir: The output directory in which to look for even tfiles. names_to_values: A dictionary of summary names to values. """ # The events file may have additional entries, e.g. the event version # stamp, so have to parse things a bit. output_filepath = glob.glob(os.path.join(output_dir, '*')) self.assertEqual(len(output_filepath), 1) events = summary_iterator.summary_iterator(output_filepath[0]) summaries_list = [e.summary for e in events if e.summary.value] values = [] for item in summaries_list: for value in item.value: values.append(value) saved_results = {v.tag: v.simple_value for v in values} for name in names_to_values: self.assertAlmostEqual(names_to_values[name], saved_results[name]) def testScalarSummaryIsPartOfCollectionWithNoPrint(self): tensor = array_ops.ones([]) * 3 name = 'my_score' prefix = 'eval' op = summaries.add_scalar_summary(tensor, name, prefix, print_summary=False) self.assertTrue(op in ops.get_collection(ops.GraphKeys.SUMMARIES)) def testScalarSummaryIsPartOfCollectionWithPrint(self): tensor = array_ops.ones([]) * 3 name = 'my_score' prefix = 'eval' op = summaries.add_scalar_summary(tensor, name, prefix, print_summary=True) self.assertTrue(op in ops.get_collection(ops.GraphKeys.SUMMARIES)) def verify_scalar_summary_is_written(self, print_summary): value = 3 tensor = array_ops.ones([]) * value name = 'my_score' prefix = 'eval' summaries.add_scalar_summary(tensor, name, prefix, print_summary) output_dir = os.path.join(self.get_temp_dir(), 'scalar_summary_no_print_test') self.safe_create(output_dir) summary_op = summary.merge_all() summary_writer = summary.FileWriter(output_dir) with self.cached_session() as sess: new_summary = sess.run(summary_op) summary_writer.add_summary(new_summary, 1) summary_writer.flush() self.assert_scalar_summary(output_dir, { '%s/%s' % (prefix, name): value }) def testScalarSummaryIsWrittenWithNoPrint(self): self.verify_scalar_summary_is_written(print_summary=False) def testScalarSummaryIsWrittenWithPrint(self): self.verify_scalar_summary_is_written(print_summary=True) if __name__ == '__main__': test.main()
tensorflow-master
tensorflow/contrib/slim/python/slim/summaries_test.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Contains functions for evaluation and summarization of metrics. The evaluation.py module contains helper functions for evaluating TensorFlow modules using a variety of metrics and summarizing the results. ********************** * Evaluating Metrics * ********************** In the simplest use case, we use a model to create the predictions, then specify the metrics and choose one model checkpoint, finally call the`evaluation_once` method: # Create model and obtain the predictions: images, labels = LoadData(...) predictions = MyModel(images) # Choose the metrics to compute: names_to_values, names_to_updates = slim.metrics.aggregate_metric_map({ "accuracy": slim.metrics.accuracy(predictions, labels), "mse": slim.metrics.mean_squared_error(predictions, labels), }) checkpoint_path = '/tmp/my_model_dir/my_checkpoint' log_dir = '/tmp/my_model_eval/' initial_op = tf.group( tf.compat.v1.global_variables_initializer(), tf.compat.v1.local_variables_initializer()) metric_values = slim.evaluate_once( master='', checkpoint_path=checkpoint_path, log_dir=log_dir, num_evals=1, initial_op=initial_op, eval_op=names_to_updates.values(), final_op=name_to_values.values()) for metric, value in zip(names_to_values.keys(), metric_values): logging.info('Metric %s has value: %f', metric, value) ************************************************ * Evaluating a Checkpointed Model with Metrics * ************************************************ Often, one wants to evaluate a model checkpoint saved on disk. This can be performed once or repeatedly on a set schedule. To evaluate a particular model, users define zero or more metrics and zero or more summaries and call the evaluation_loop method: # Create model and obtain the predictions: images, labels = LoadData(...) predictions = MyModel(images) # Choose the metrics to compute: names_to_values, names_to_updates = slim.metrics.aggregate_metric_map({ "accuracy": slim.metrics.accuracy(predictions, labels), "mse": slim.metrics.mean_squared_error(predictions, labels), }) # Define the summaries to write: for metric_name, metric_value in metrics_to_values.iteritems(): tf.compat.v1.summary.scalar(metric_name, metric_value) checkpoint_dir = '/tmp/my_model_dir/' log_dir = '/tmp/my_model_eval/' # We'll evaluate 1000 batches: num_evals = 1000 # Evaluate every 10 minutes: slim.evaluation_loop( '', checkpoint_dir, logdir, num_evals=num_evals, eval_op=names_to_updates.values(), summary_op=tf.contrib.deprecated.merge_summary(summary_ops), eval_interval_secs=600) ************************************************** * Evaluating a Checkpointed Model with Summaries * ************************************************** At times, an evaluation can be performed without metrics at all but rather with only summaries. The user need only leave out the 'eval_op' argument: # Create model and obtain the predictions: images, labels = LoadData(...) predictions = MyModel(images) # Define the summaries to write: tf.compat.v1.summary.scalar(...) tf.compat.v1.summary.histogram(...) checkpoint_dir = '/tmp/my_model_dir/' log_dir = '/tmp/my_model_eval/' # Evaluate once every 10 minutes. slim.evaluation_loop( master='', checkpoint_dir, logdir, num_evals=1, summary_op=tf.contrib.deprecated.merge_summary(summary_ops), eval_interval_secs=600) """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.contrib.training.python.training import evaluation from tensorflow.python.summary import summary from tensorflow.python.training import monitored_session from tensorflow.python.training import saver as tf_saver __all__ = [ 'evaluate_once', 'evaluation_loop', 'wait_for_new_checkpoint', 'checkpoints_iterator', ] wait_for_new_checkpoint = evaluation.wait_for_new_checkpoint checkpoints_iterator = evaluation.checkpoints_iterator _USE_DEFAULT = 0 def evaluate_once(master, checkpoint_path, logdir, num_evals=1, initial_op=None, initial_op_feed_dict=None, eval_op=None, eval_op_feed_dict=None, final_op=None, final_op_feed_dict=None, summary_op=_USE_DEFAULT, summary_op_feed_dict=None, variables_to_restore=None, session_config=None, hooks=None): """Evaluates the model at the given checkpoint path. Args: master: The BNS address of the TensorFlow master. checkpoint_path: The path to a checkpoint to use for evaluation. logdir: The directory where the TensorFlow summaries are written to. num_evals: The number of times to run `eval_op`. initial_op: An operation run at the beginning of evaluation. initial_op_feed_dict: A feed dictionary to use when executing `initial_op`. eval_op: A operation run `num_evals` times. eval_op_feed_dict: The feed dictionary to use when executing the `eval_op`. final_op: An operation to execute after all of the `eval_op` executions. The value of `final_op` is returned. final_op_feed_dict: A feed dictionary to use when executing `final_op`. summary_op: The summary_op to evaluate after running TF-Slims metric ops. By default the summary_op is set to tf.compat.v1.summary.merge_all(). summary_op_feed_dict: An optional feed dictionary to use when running the `summary_op`. variables_to_restore: A list of TensorFlow variables to restore during evaluation. If the argument is left as `None` then slim.variables.GetVariablesToRestore() is used. session_config: An instance of `tf.compat.v1.ConfigProto` that will be used to configure the `Session`. If left as `None`, the default will be used. hooks: A list of additional `SessionRunHook` objects to pass during the evaluation. Returns: The value of `final_op` or `None` if `final_op` is `None`. """ if summary_op == _USE_DEFAULT: summary_op = summary.merge_all() all_hooks = [ evaluation.StopAfterNEvalsHook(num_evals), ] if summary_op is not None: all_hooks.append( evaluation.SummaryAtEndHook( log_dir=logdir, summary_op=summary_op, feed_dict=summary_op_feed_dict)) if hooks is not None: all_hooks.extend(hooks) saver = None if variables_to_restore is not None: saver = tf_saver.Saver(variables_to_restore) return evaluation.evaluate_once( checkpoint_path, master=master, scaffold=monitored_session.Scaffold( init_op=initial_op, init_feed_dict=initial_op_feed_dict, saver=saver), eval_ops=eval_op, feed_dict=eval_op_feed_dict, final_ops=final_op, final_ops_feed_dict=final_op_feed_dict, hooks=all_hooks, config=session_config) def evaluation_loop(master, checkpoint_dir, logdir, num_evals=1, initial_op=None, initial_op_feed_dict=None, init_fn=None, eval_op=None, eval_op_feed_dict=None, final_op=None, final_op_feed_dict=None, summary_op=_USE_DEFAULT, summary_op_feed_dict=None, variables_to_restore=None, eval_interval_secs=60, max_number_of_evaluations=None, session_config=None, timeout=None, timeout_fn=None, hooks=None): """Runs TF-Slim's Evaluation Loop. Args: master: The BNS address of the TensorFlow master. checkpoint_dir: The directory where checkpoints are stored. logdir: The directory where the TensorFlow summaries are written to. num_evals: The number of times to run `eval_op`. initial_op: An operation run at the beginning of evaluation. initial_op_feed_dict: A feed dictionary to use when executing `initial_op`. init_fn: An optional callable to be executed after `init_op` is called. The callable must accept one argument, the session being initialized. eval_op: A operation run `num_evals` times. eval_op_feed_dict: The feed dictionary to use when executing the `eval_op`. final_op: An operation to execute after all of the `eval_op` executions. The value of `final_op` is returned. final_op_feed_dict: A feed dictionary to use when executing `final_op`. summary_op: The summary_op to evaluate after running TF-Slims metric ops. By default the summary_op is set to tf.compat.v1.summary.merge_all(). summary_op_feed_dict: An optional feed dictionary to use when running the `summary_op`. variables_to_restore: A list of TensorFlow variables to restore during evaluation. If the argument is left as `None` then slim.variables.GetVariablesToRestore() is used. eval_interval_secs: The minimum number of seconds between evaluations. max_number_of_evaluations: the max number of iterations of the evaluation. If the value is left as 'None', the evaluation continues indefinitely. session_config: An instance of `tf.compat.v1.ConfigProto` that will be used to configure the `Session`. If left as `None`, the default will be used. timeout: The maximum amount of time to wait between checkpoints. If left as `None`, then the process will wait indefinitely. timeout_fn: Optional function to call after a timeout. If the function returns True, then it means that no new checkpoints will be generated and the iterator will exit. The function is called with no arguments. hooks: A list of additional `SessionRunHook` objects to pass during repeated evaluations. Returns: The value of `final_op` or `None` if `final_op` is `None`. """ if summary_op == _USE_DEFAULT: summary_op = summary.merge_all() all_hooks = [ evaluation.StopAfterNEvalsHook(num_evals), ] if summary_op is not None: all_hooks.append( evaluation.SummaryAtEndHook( log_dir=logdir, summary_op=summary_op, feed_dict=summary_op_feed_dict)) if hooks is not None: # Add custom hooks if provided. all_hooks.extend(hooks) saver = None if variables_to_restore is not None: saver = tf_saver.Saver(variables_to_restore) return evaluation.evaluate_repeatedly( checkpoint_dir, master=master, scaffold=monitored_session.Scaffold( init_op=initial_op, init_feed_dict=initial_op_feed_dict, init_fn=init_fn, saver=saver), eval_ops=eval_op, feed_dict=eval_op_feed_dict, final_ops=final_op, final_ops_feed_dict=final_op_feed_dict, eval_interval_secs=eval_interval_secs, hooks=all_hooks, config=session_config, max_number_of_evaluations=max_number_of_evaluations, timeout=timeout, timeout_fn=timeout_fn)
tensorflow-master
tensorflow/contrib/slim/python/slim/evaluation.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for slim.learning.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import glob import os import tempfile import numpy as np from numpy import testing as np_testing from tensorflow.contrib.framework.python.ops import variables as variables_lib2 from tensorflow.contrib.layers.python.layers import layers from tensorflow.contrib.losses.python.losses import loss_ops from tensorflow.contrib.slim.python.slim import learning from tensorflow.core.protobuf import config_pb2 from tensorflow.python.client import session from tensorflow.python.debug.lib import debug_data from tensorflow.python.debug.wrappers import dumping_wrapper as dumping_wrapper_lib from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.framework import random_seed from tensorflow.python.ops import array_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import variables as variables_lib from tensorflow.python.platform import test from tensorflow.python.summary import summary from tensorflow.python.training import gradient_descent from tensorflow.python.training import input as input_lib from tensorflow.python.training import saver as saver_lib class ClipGradientNormsTest(test.TestCase): def clip_values(self, arr): norm = np.sqrt(np.sum(arr**2)) if norm > self._max_norm: return self._max_norm * arr / np.sqrt(np.sum(arr**2)) return arr def setUp(self): np.random.seed(0) self._max_norm = 1.0 self._grad_vec = np.array([1., 2., 3.]) self._clipped_grad_vec = self.clip_values(self._grad_vec) self._zero_vec = np.zeros(self._grad_vec.size) def testOrdinaryGradIsClippedCorrectly(self): gradient = constant_op.constant(self._grad_vec, dtype=dtypes.float32) variable = variables_lib.Variable(self._zero_vec, dtype=dtypes.float32) gradients_to_variables = (gradient, variable) [gradients_to_variables ] = learning.clip_gradient_norms([gradients_to_variables], self._max_norm) # Ensure the variable passed through. self.assertEqual(gradients_to_variables[1], variable) with self.cached_session() as sess: actual_gradient = sess.run(gradients_to_variables[0]) np_testing.assert_almost_equal(actual_gradient, self._clipped_grad_vec) def testNoneGradPassesThroughCorrectly(self): gradient = None variable = variables_lib.Variable(self._zero_vec, dtype=dtypes.float32) gradients_to_variables = (gradient, variable) [gradients_to_variables ] = learning.clip_gradient_norms([gradients_to_variables], self._max_norm) self.assertEqual(gradients_to_variables[0], None) self.assertEqual(gradients_to_variables[1], variable) def testIndexedSlicesGradIsClippedCorrectly(self): sparse_grad_indices = np.array([0, 1, 4]) sparse_grad_dense_shape = [self._grad_vec.size] values = constant_op.constant(self._grad_vec, dtype=dtypes.float32) indices = constant_op.constant(sparse_grad_indices, dtype=dtypes.int32) dense_shape = constant_op.constant( sparse_grad_dense_shape, dtype=dtypes.int32) gradient = ops.IndexedSlices(values, indices, dense_shape) variable = variables_lib.Variable(self._zero_vec, dtype=dtypes.float32) gradients_to_variables = (gradient, variable) gradients_to_variables = learning.clip_gradient_norms( [gradients_to_variables], self._max_norm)[0] # Ensure the built IndexedSlice has the right form. self.assertEqual(gradients_to_variables[1], variable) self.assertEqual(gradients_to_variables[0].indices, indices) self.assertEqual(gradients_to_variables[0].dense_shape, dense_shape) with session.Session() as sess: actual_gradient = sess.run(gradients_to_variables[0].values) np_testing.assert_almost_equal(actual_gradient, self._clipped_grad_vec) class MultiplyGradientsTest(test.TestCase): def setUp(self): np.random.seed(0) self._multiplier = 3.7 self._grad_vec = np.array([1., 2., 3.]) self._multiplied_grad_vec = np.multiply(self._grad_vec, self._multiplier) def testNonListGradsRaisesError(self): gradient = constant_op.constant(self._grad_vec, dtype=dtypes.float32) variable = variables_lib.Variable(array_ops.zeros_like(gradient)) grad_to_var = (gradient, variable) gradient_multipliers = {variable: self._multiplier} with self.assertRaises(ValueError): learning.multiply_gradients(grad_to_var, gradient_multipliers) def testEmptyMultiplesRaisesError(self): gradient = constant_op.constant(self._grad_vec, dtype=dtypes.float32) variable = variables_lib.Variable(array_ops.zeros_like(gradient)) grad_to_var = (gradient, variable) with self.assertRaises(ValueError): learning.multiply_gradients([grad_to_var], {}) def testNonDictMultiplierRaisesError(self): gradient = constant_op.constant(self._grad_vec, dtype=dtypes.float32) variable = variables_lib.Variable(array_ops.zeros_like(gradient)) grad_to_var = (gradient, variable) with self.assertRaises(ValueError): learning.multiply_gradients([grad_to_var], 3) def testMultipleOfNoneGradRaisesError(self): gradient = constant_op.constant(self._grad_vec, dtype=dtypes.float32) variable = variables_lib.Variable(array_ops.zeros_like(gradient)) grad_to_var = (None, variable) gradient_multipliers = {variable: self._multiplier} with self.assertRaises(ValueError): learning.multiply_gradients(grad_to_var, gradient_multipliers) def testMultipleGradientsWithVariables(self): gradient = constant_op.constant(self._grad_vec, dtype=dtypes.float32) variable = variables_lib.Variable(array_ops.zeros_like(gradient)) grad_to_var = (gradient, variable) gradient_multipliers = {variable: self._multiplier} [grad_to_var] = learning.multiply_gradients([grad_to_var], gradient_multipliers) # Ensure the variable passed through. self.assertEqual(grad_to_var[1], variable) with self.cached_session() as sess: actual_gradient = sess.run(grad_to_var[0]) np_testing.assert_almost_equal(actual_gradient, self._multiplied_grad_vec, 5) def testIndexedSlicesGradIsMultiplied(self): values = constant_op.constant(self._grad_vec, dtype=dtypes.float32) indices = constant_op.constant([0, 1, 2], dtype=dtypes.int32) dense_shape = constant_op.constant([self._grad_vec.size], dtype=dtypes.int32) gradient = ops.IndexedSlices(values, indices, dense_shape) variable = variables_lib.Variable(array_ops.zeros((1, 3))) grad_to_var = (gradient, variable) gradient_multipliers = {variable: self._multiplier} [grad_to_var] = learning.multiply_gradients([grad_to_var], gradient_multipliers) # Ensure the built IndexedSlice has the right form. self.assertEqual(grad_to_var[1], variable) self.assertEqual(grad_to_var[0].indices, indices) self.assertEqual(grad_to_var[0].dense_shape, dense_shape) with self.cached_session() as sess: actual_gradient = sess.run(grad_to_var[0].values) np_testing.assert_almost_equal(actual_gradient, self._multiplied_grad_vec, 5) def testTensorMultiplierOfGradient(self): gradient = constant_op.constant(self._grad_vec, dtype=dtypes.float32) variable = variables_lib.Variable(array_ops.zeros_like(gradient)) multiplier_flag = variables_lib.Variable(True) tensor_multiplier = array_ops.where(multiplier_flag, self._multiplier, 1.0) grad_to_var = (gradient, variable) gradient_multipliers = {variable: tensor_multiplier} [grad_to_var] = learning.multiply_gradients([grad_to_var], gradient_multipliers) with self.cached_session() as sess: sess.run(variables_lib.global_variables_initializer()) gradient_true_flag = sess.run(grad_to_var[0]) sess.run(multiplier_flag.assign(False)) gradient_false_flag = sess.run(grad_to_var[0]) np_testing.assert_almost_equal(gradient_true_flag, self._multiplied_grad_vec, 5) np_testing.assert_almost_equal(gradient_false_flag, self._grad_vec, 5) def LogisticClassifier(inputs): return layers.fully_connected(inputs, 1, activation_fn=math_ops.sigmoid) def BatchNormClassifier(inputs): inputs = layers.batch_norm(inputs, decay=0.1, fused=True) return layers.fully_connected(inputs, 1, activation_fn=math_ops.sigmoid) class TrainBNClassifierTest(test.TestCase): def setUp(self): # Create an easy training set: np.random.seed(0) self._inputs = np.zeros((16, 4)) self._labels = np.random.randint(0, 2, size=(16, 1)).astype(np.float32) for i in range(16): j = int(2 * self._labels[i] + np.random.randint(0, 2)) self._inputs[i, j] = 1 def testTrainWithNoInitAssignCanAchieveZeroLoss(self): logdir = os.path.join( tempfile.mkdtemp(prefix=self.get_temp_dir()), 'tmp_logs') g = ops.Graph() with g.as_default(): random_seed.set_random_seed(0) tf_inputs = constant_op.constant(self._inputs, dtype=dtypes.float32) tf_labels = constant_op.constant(self._labels, dtype=dtypes.float32) tf_predictions = BatchNormClassifier(tf_inputs) loss_ops.log_loss(tf_predictions, tf_labels) total_loss = loss_ops.get_total_loss() optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=1.0) train_op = learning.create_train_op(total_loss, optimizer) loss = learning.train( train_op, logdir, number_of_steps=300, log_every_n_steps=10) self.assertLess(loss, .1) class CreateTrainOpTest(test.TestCase): def setUp(self): # Create an easy training set: np.random.seed(0) self._inputs = np.random.rand(16, 4).astype(np.float32) self._labels = np.random.randint(0, 2, size=(16, 1)).astype(np.float32) def _addBesselsCorrection(self, sample_size, expected_var): correction_factor = sample_size / (sample_size - 1) expected_var *= correction_factor return expected_var def testUseUpdateOps(self): with ops.Graph().as_default(): random_seed.set_random_seed(0) tf_inputs = constant_op.constant(self._inputs, dtype=dtypes.float32) tf_labels = constant_op.constant(self._labels, dtype=dtypes.float32) expected_mean = np.mean(self._inputs, axis=(0)) expected_var = np.var(self._inputs, axis=(0)) expected_var = self._addBesselsCorrection(16, expected_var) tf_predictions = BatchNormClassifier(tf_inputs) loss_ops.log_loss(tf_predictions, tf_labels) total_loss = loss_ops.get_total_loss() optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=1.0) train_op = learning.create_train_op(total_loss, optimizer) moving_mean = variables_lib2.get_variables_by_name('moving_mean')[0] moving_variance = variables_lib2.get_variables_by_name( 'moving_variance')[0] with session.Session() as sess: # Initialize all variables sess.run(variables_lib.global_variables_initializer()) mean, variance = sess.run([moving_mean, moving_variance]) # After initialization moving_mean == 0 and moving_variance == 1. self.assertAllClose(mean, [0] * 4) self.assertAllClose(variance, [1] * 4) for _ in range(10): sess.run([train_op]) mean = moving_mean.eval() variance = moving_variance.eval() # After 10 updates with decay 0.1 moving_mean == expected_mean and # moving_variance == expected_var. self.assertAllClose(mean, expected_mean) self.assertAllClose(variance, expected_var) def testEmptyUpdateOps(self): with ops.Graph().as_default(): random_seed.set_random_seed(0) tf_inputs = constant_op.constant(self._inputs, dtype=dtypes.float32) tf_labels = constant_op.constant(self._labels, dtype=dtypes.float32) tf_predictions = BatchNormClassifier(tf_inputs) loss_ops.log_loss(tf_predictions, tf_labels) total_loss = loss_ops.get_total_loss() optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=1.0) train_op = learning.create_train_op(total_loss, optimizer, update_ops=[]) moving_mean = variables_lib2.get_variables_by_name('moving_mean')[0] moving_variance = variables_lib2.get_variables_by_name( 'moving_variance')[0] with session.Session() as sess: # Initialize all variables sess.run(variables_lib.global_variables_initializer()) mean, variance = sess.run([moving_mean, moving_variance]) # After initialization moving_mean == 0 and moving_variance == 1. self.assertAllClose(mean, [0] * 4) self.assertAllClose(variance, [1] * 4) for _ in range(10): sess.run([train_op]) mean = moving_mean.eval() variance = moving_variance.eval() # Since we skip update_ops the moving_vars are not updated. self.assertAllClose(mean, [0] * 4) self.assertAllClose(variance, [1] * 4) def testUseGlobalStep(self): with ops.Graph().as_default(): random_seed.set_random_seed(0) tf_inputs = constant_op.constant(self._inputs, dtype=dtypes.float32) tf_labels = constant_op.constant(self._labels, dtype=dtypes.float32) tf_predictions = BatchNormClassifier(tf_inputs) loss_ops.log_loss(tf_predictions, tf_labels) total_loss = loss_ops.get_total_loss() optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=1.0) train_op = learning.create_train_op(total_loss, optimizer) global_step = variables_lib2.get_or_create_global_step() with session.Session() as sess: # Initialize all variables sess.run(variables_lib.global_variables_initializer()) for _ in range(10): sess.run([train_op]) global_step = global_step.eval() # After 10 updates global_step should be 10. self.assertAllClose(global_step, 10) def testNoneGlobalStep(self): with ops.Graph().as_default(): random_seed.set_random_seed(0) tf_inputs = constant_op.constant(self._inputs, dtype=dtypes.float32) tf_labels = constant_op.constant(self._labels, dtype=dtypes.float32) tf_predictions = BatchNormClassifier(tf_inputs) loss_ops.log_loss(tf_predictions, tf_labels) total_loss = loss_ops.get_total_loss() optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=1.0) train_op = learning.create_train_op( total_loss, optimizer, global_step=None) global_step = variables_lib2.get_or_create_global_step() with session.Session() as sess: # Initialize all variables sess.run(variables_lib.global_variables_initializer()) for _ in range(10): sess.run([train_op]) global_step = global_step.eval() # Since train_op don't use global_step it shouldn't change. self.assertAllClose(global_step, 0) def testRecordTrainOpInCollection(self): with ops.Graph().as_default(): random_seed.set_random_seed(0) tf_inputs = constant_op.constant(self._inputs, dtype=dtypes.float32) tf_labels = constant_op.constant(self._labels, dtype=dtypes.float32) tf_predictions = LogisticClassifier(tf_inputs) loss_ops.log_loss(tf_predictions, tf_labels) total_loss = loss_ops.get_total_loss() optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=1.0) train_op = learning.create_train_op(total_loss, optimizer) # Make sure the training op was recorded in the proper collection self.assertTrue(train_op in ops.get_collection(ops.GraphKeys.TRAIN_OP)) class TrainTest(test.TestCase): def setUp(self): # Create an easy training set: np.random.seed(0) self._inputs = np.zeros((16, 4)) self._labels = np.random.randint(0, 2, size=(16, 1)).astype(np.float32) for i in range(16): j = int(2 * self._labels[i] + np.random.randint(0, 2)) self._inputs[i, j] = 1 def testTrainWithNonDefaultGraph(self): logdir = os.path.join( tempfile.mkdtemp(prefix=self.get_temp_dir()), 'tmp_logs') g = ops.Graph() with g.as_default(): random_seed.set_random_seed(0) tf_inputs = constant_op.constant(self._inputs, dtype=dtypes.float32) tf_labels = constant_op.constant(self._labels, dtype=dtypes.float32) tf_predictions = LogisticClassifier(tf_inputs) loss_ops.log_loss(tf_predictions, tf_labels) total_loss = loss_ops.get_total_loss() optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=1.0) train_op = learning.create_train_op(total_loss, optimizer) loss = learning.train( train_op, logdir, number_of_steps=300, log_every_n_steps=10, graph=g) self.assertIsNotNone(loss) self.assertLess(loss, .015) def testTrainWithNoneAsLogdir(self): with ops.Graph().as_default(): random_seed.set_random_seed(0) tf_inputs = constant_op.constant(self._inputs, dtype=dtypes.float32) tf_labels = constant_op.constant(self._labels, dtype=dtypes.float32) tf_predictions = LogisticClassifier(tf_inputs) loss_ops.log_loss(tf_predictions, tf_labels) total_loss = loss_ops.get_total_loss() optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=1.0) train_op = learning.create_train_op(total_loss, optimizer) loss = learning.train( train_op, None, number_of_steps=300, log_every_n_steps=10) self.assertIsNotNone(loss) self.assertLess(loss, .015) def testTrainWithSessionConfig(self): with ops.Graph().as_default(): random_seed.set_random_seed(0) tf_inputs = constant_op.constant(self._inputs, dtype=dtypes.float32) tf_labels = constant_op.constant(self._labels, dtype=dtypes.float32) tf_predictions = LogisticClassifier(tf_inputs) loss_ops.log_loss(tf_predictions, tf_labels) total_loss = loss_ops.get_total_loss() optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=1.0) train_op = learning.create_train_op(total_loss, optimizer) session_config = config_pb2.ConfigProto(allow_soft_placement=True) loss = learning.train( train_op, None, number_of_steps=300, log_every_n_steps=10, session_config=session_config) self.assertIsNotNone(loss) self.assertLess(loss, .015) def testTrainWithSessionWrapper(self): """Test that slim.learning.train can take `session_wrapper` args. One of the applications of `session_wrapper` is the wrappers of TensorFlow Debugger (tfdbg), which intercept methods calls to `tf.compat.v1.Session` (e.g., run) to achieve debugging. `DumpingDebugWrapperSession` is used here for testing purpose. """ dump_root = tempfile.mkdtemp() def dumping_wrapper(sess): # pylint: disable=invalid-name return dumping_wrapper_lib.DumpingDebugWrapperSession(sess, dump_root) with ops.Graph().as_default(): random_seed.set_random_seed(0) tf_inputs = constant_op.constant(self._inputs, dtype=dtypes.float32) tf_labels = constant_op.constant(self._labels, dtype=dtypes.float32) tf_predictions = LogisticClassifier(tf_inputs) loss_ops.log_loss(tf_predictions, tf_labels) total_loss = loss_ops.get_total_loss() optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=1.0) train_op = learning.create_train_op(total_loss, optimizer) loss = learning.train( train_op, None, number_of_steps=1, session_wrapper=dumping_wrapper) self.assertIsNotNone(loss) run_root = glob.glob(os.path.join(dump_root, 'run_*'))[-1] dump = debug_data.DebugDumpDir(run_root) self.assertAllEqual(0, dump.get_tensors('global_step', 0, 'DebugIdentity')[0]) def testTrainWithTrace(self): logdir = os.path.join( tempfile.mkdtemp(prefix=self.get_temp_dir()), 'tmp_logs') with ops.Graph().as_default(): random_seed.set_random_seed(0) tf_inputs = constant_op.constant(self._inputs, dtype=dtypes.float32) tf_labels = constant_op.constant(self._labels, dtype=dtypes.float32) tf_predictions = LogisticClassifier(tf_inputs) loss_ops.log_loss(tf_predictions, tf_labels) total_loss = loss_ops.get_total_loss() summary.scalar('total_loss', total_loss) optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=1.0) train_op = learning.create_train_op(total_loss, optimizer) loss = learning.train( train_op, logdir, number_of_steps=300, log_every_n_steps=10, trace_every_n_steps=100) self.assertIsNotNone(loss) for trace_step in [1, 101, 201]: trace_filename = 'tf_trace-%d.json' % trace_step self.assertTrue(os.path.isfile(os.path.join(logdir, trace_filename))) def testTrainWithNoneAsLogdirWhenUsingSummariesRaisesError(self): with ops.Graph().as_default(): random_seed.set_random_seed(0) tf_inputs = constant_op.constant(self._inputs, dtype=dtypes.float32) tf_labels = constant_op.constant(self._labels, dtype=dtypes.float32) tf_predictions = LogisticClassifier(tf_inputs) loss_ops.log_loss(tf_predictions, tf_labels) total_loss = loss_ops.get_total_loss() summary.scalar('total_loss', total_loss) optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=1.0) train_op = learning.create_train_op(total_loss, optimizer) summary_op = summary.merge_all() with self.assertRaises(ValueError): learning.train( train_op, None, number_of_steps=300, summary_op=summary_op) def testTrainWithNoneAsLogdirWhenUsingTraceRaisesError(self): with ops.Graph().as_default(): random_seed.set_random_seed(0) tf_inputs = constant_op.constant(self._inputs, dtype=dtypes.float32) tf_labels = constant_op.constant(self._labels, dtype=dtypes.float32) tf_predictions = LogisticClassifier(tf_inputs) loss_ops.log_loss(tf_predictions, tf_labels) total_loss = loss_ops.get_total_loss() optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=1.0) train_op = learning.create_train_op(total_loss, optimizer) with self.assertRaises(ValueError): learning.train( train_op, None, number_of_steps=300, trace_every_n_steps=10) def testTrainWithNoneAsLogdirWhenUsingSaverRaisesError(self): with ops.Graph().as_default(): random_seed.set_random_seed(0) tf_inputs = constant_op.constant(self._inputs, dtype=dtypes.float32) tf_labels = constant_op.constant(self._labels, dtype=dtypes.float32) tf_predictions = LogisticClassifier(tf_inputs) loss_ops.log_loss(tf_predictions, tf_labels) total_loss = loss_ops.get_total_loss() optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=1.0) train_op = learning.create_train_op(total_loss, optimizer) saver = saver_lib.Saver() with self.assertRaises(ValueError): learning.train( train_op, None, init_op=None, number_of_steps=300, saver=saver) def testTrainWithNoneAsInitWhenUsingVarsRaisesError(self): logdir = os.path.join( tempfile.mkdtemp(prefix=self.get_temp_dir()), 'tmp_logs') with ops.Graph().as_default(): random_seed.set_random_seed(0) tf_inputs = constant_op.constant(self._inputs, dtype=dtypes.float32) tf_labels = constant_op.constant(self._labels, dtype=dtypes.float32) tf_predictions = LogisticClassifier(tf_inputs) loss_ops.log_loss(tf_predictions, tf_labels) total_loss = loss_ops.get_total_loss() optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=1.0) train_op = learning.create_train_op(total_loss, optimizer) with self.assertRaises(RuntimeError): learning.train(train_op, logdir, init_op=None, number_of_steps=300) def testTrainWithNoInitAssignCanAchieveZeroLoss(self): logdir = os.path.join( tempfile.mkdtemp(prefix=self.get_temp_dir()), 'tmp_logs') with ops.Graph().as_default(): random_seed.set_random_seed(0) tf_inputs = constant_op.constant(self._inputs, dtype=dtypes.float32) tf_labels = constant_op.constant(self._labels, dtype=dtypes.float32) tf_predictions = LogisticClassifier(tf_inputs) loss_ops.log_loss(tf_predictions, tf_labels) total_loss = loss_ops.get_total_loss() optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=1.0) train_op = learning.create_train_op(total_loss, optimizer) loss = learning.train( train_op, logdir, number_of_steps=300, log_every_n_steps=10) self.assertIsNotNone(loss) self.assertLess(loss, .015) def testTrainWithLocalVariable(self): logdir = os.path.join( tempfile.mkdtemp(prefix=self.get_temp_dir()), 'tmp_logs') with ops.Graph().as_default(): random_seed.set_random_seed(0) tf_inputs = constant_op.constant(self._inputs, dtype=dtypes.float32) tf_labels = constant_op.constant(self._labels, dtype=dtypes.float32) local_multiplier = variables_lib2.local_variable(1.0) tf_predictions = LogisticClassifier(tf_inputs) * local_multiplier loss_ops.log_loss(tf_predictions, tf_labels) total_loss = loss_ops.get_total_loss() optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=1.0) train_op = learning.create_train_op(total_loss, optimizer) loss = learning.train( train_op, logdir, number_of_steps=300, log_every_n_steps=10) self.assertIsNotNone(loss) self.assertLess(loss, .015) def testResumeTrainAchievesRoughlyTheSameLoss(self): logdir = os.path.join( tempfile.mkdtemp(prefix=self.get_temp_dir()), 'tmp_logs') number_of_steps = [300, 301, 305] for i in range(len(number_of_steps)): with ops.Graph().as_default(): random_seed.set_random_seed(i) tf_inputs = constant_op.constant(self._inputs, dtype=dtypes.float32) tf_labels = constant_op.constant(self._labels, dtype=dtypes.float32) tf_predictions = LogisticClassifier(tf_inputs) loss_ops.log_loss(tf_predictions, tf_labels) total_loss = loss_ops.get_total_loss() optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=1.0) train_op = learning.create_train_op(total_loss, optimizer) loss = learning.train( train_op, logdir, number_of_steps=number_of_steps[i], log_every_n_steps=10) self.assertIsNotNone(loss) self.assertLess(loss, .015) def create_train_op(self, learning_rate=1.0, gradient_multiplier=1.0): tf_inputs = constant_op.constant(self._inputs, dtype=dtypes.float32) tf_labels = constant_op.constant(self._labels, dtype=dtypes.float32) tf_predictions = LogisticClassifier(tf_inputs) loss_ops.log_loss(tf_predictions, tf_labels) total_loss = loss_ops.get_total_loss() optimizer = gradient_descent.GradientDescentOptimizer( learning_rate=learning_rate) if gradient_multiplier != 1.0: variables = variables_lib.trainable_variables() gradient_multipliers = {var: gradient_multiplier for var in variables} else: gradient_multipliers = None return learning.create_train_op( total_loss, optimizer, gradient_multipliers=gradient_multipliers) def testTrainWithInitFromCheckpoint(self): logdir1 = os.path.join( tempfile.mkdtemp(prefix=self.get_temp_dir()), 'tmp_logs1') logdir2 = os.path.join( tempfile.mkdtemp(prefix=self.get_temp_dir()), 'tmp_logs2') # First, train the model one step (make sure the error is high). with ops.Graph().as_default(): random_seed.set_random_seed(0) train_op = self.create_train_op() loss = learning.train(train_op, logdir1, number_of_steps=1) self.assertGreater(loss, .5) # Next, train the model to convergence. with ops.Graph().as_default(): random_seed.set_random_seed(1) train_op = self.create_train_op() loss = learning.train( train_op, logdir1, number_of_steps=300, log_every_n_steps=10) self.assertIsNotNone(loss) self.assertLess(loss, .02) # Finally, advance the model a single step and validate that the loss is # still low. with ops.Graph().as_default(): random_seed.set_random_seed(2) train_op = self.create_train_op() model_variables = variables_lib.global_variables() model_path = os.path.join(logdir1, 'model.ckpt-300') init_op = variables_lib.global_variables_initializer() op, init_feed_dict = variables_lib2.assign_from_checkpoint( model_path, model_variables) def InitAssignFn(sess): sess.run(op, init_feed_dict) loss = learning.train( train_op, logdir2, number_of_steps=1, init_op=init_op, init_fn=InitAssignFn) self.assertIsNotNone(loss) self.assertLess(loss, .02) def testTrainWithInitFromFn(self): logdir1 = os.path.join( tempfile.mkdtemp(prefix=self.get_temp_dir()), 'tmp_logs1') logdir2 = os.path.join( tempfile.mkdtemp(prefix=self.get_temp_dir()), 'tmp_logs2') # First, train the model one step (make sure the error is high). with ops.Graph().as_default(): random_seed.set_random_seed(0) train_op = self.create_train_op() loss = learning.train(train_op, logdir1, number_of_steps=1) self.assertGreater(loss, .5) # Next, train the model to convergence. with ops.Graph().as_default(): random_seed.set_random_seed(1) train_op = self.create_train_op() loss = learning.train( train_op, logdir1, number_of_steps=300, log_every_n_steps=10) self.assertIsNotNone(loss) self.assertLess(loss, .015) # Finally, advance the model a single step and validate that the loss is # still low. with ops.Graph().as_default(): random_seed.set_random_seed(2) train_op = self.create_train_op() model_variables = variables_lib.global_variables() model_path = os.path.join(logdir1, 'model.ckpt-300') saver = saver_lib.Saver(model_variables) def RestoreFn(sess): saver.restore(sess, model_path) loss = learning.train( train_op, logdir2, number_of_steps=1, init_fn=RestoreFn) self.assertIsNotNone(loss) self.assertLess(loss, .015) def ModelLoss(self): tf_inputs = constant_op.constant(self._inputs, dtype=dtypes.float32) tf_labels = constant_op.constant(self._labels, dtype=dtypes.float32) tf_predictions = LogisticClassifier(tf_inputs) loss_ops.log_loss(tf_predictions, tf_labels) return loss_ops.get_total_loss() def testTrainAllVarsHasLowerLossThanTrainSubsetOfVars(self): logdir1 = os.path.join( tempfile.mkdtemp(prefix=self.get_temp_dir()), 'tmp_logs1') # First, train only the weights of the model. with ops.Graph().as_default(): random_seed.set_random_seed(0) total_loss = self.ModelLoss() optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=1.0) weights = variables_lib2.get_variables_by_name('weights') train_op = learning.create_train_op( total_loss, optimizer, variables_to_train=weights) loss = learning.train( train_op, logdir1, number_of_steps=200, log_every_n_steps=10) self.assertGreater(loss, .015) self.assertLess(loss, .05) # Next, train the biases of the model. with ops.Graph().as_default(): random_seed.set_random_seed(1) total_loss = self.ModelLoss() optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=1.0) biases = variables_lib2.get_variables_by_name('biases') train_op = learning.create_train_op( total_loss, optimizer, variables_to_train=biases) loss = learning.train( train_op, logdir1, number_of_steps=300, log_every_n_steps=10) self.assertGreater(loss, .015) self.assertLess(loss, .05) # Finally, train both weights and bias to get lower loss. with ops.Graph().as_default(): random_seed.set_random_seed(2) total_loss = self.ModelLoss() optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=1.0) train_op = learning.create_train_op(total_loss, optimizer) loss = learning.train( train_op, logdir1, number_of_steps=400, log_every_n_steps=10) self.assertIsNotNone(loss) self.assertLess(loss, .015) def testTrainingSubsetsOfVariablesOnlyUpdatesThoseVariables(self): # First, train only the weights of the model. with ops.Graph().as_default(): random_seed.set_random_seed(0) total_loss = self.ModelLoss() optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=1.0) weights, biases = variables_lib2.get_variables() train_op = learning.create_train_op(total_loss, optimizer) train_weights = learning.create_train_op( total_loss, optimizer, variables_to_train=[weights]) train_biases = learning.create_train_op( total_loss, optimizer, variables_to_train=[biases]) with session.Session() as sess: # Initialize the variables. sess.run(variables_lib.global_variables_initializer()) # Get the initial weights and biases values. weights_values, biases_values = sess.run([weights, biases]) self.assertGreater(np.linalg.norm(weights_values), 0) self.assertAlmostEqual(np.linalg.norm(biases_values), 0) # Update weights and biases. loss = sess.run(train_op) self.assertGreater(loss, .5) new_weights, new_biases = sess.run([weights, biases]) # Check that the weights and biases have been updated. self.assertGreater(np.linalg.norm(weights_values - new_weights), 0) self.assertGreater(np.linalg.norm(biases_values - new_biases), 0) weights_values, biases_values = new_weights, new_biases # Update only weights. loss = sess.run(train_weights) self.assertGreater(loss, .5) new_weights, new_biases = sess.run([weights, biases]) # Check that the weights have been updated, but biases have not. self.assertGreater(np.linalg.norm(weights_values - new_weights), 0) self.assertAlmostEqual(np.linalg.norm(biases_values - new_biases), 0) weights_values = new_weights # Update only biases. loss = sess.run(train_biases) self.assertGreater(loss, .5) new_weights, new_biases = sess.run([weights, biases]) # Check that the biases have been updated, but weights have not. self.assertAlmostEqual(np.linalg.norm(weights_values - new_weights), 0) self.assertGreater(np.linalg.norm(biases_values - new_biases), 0) def testTrainWithAlteredGradients(self): # Use the same learning rate but different gradient multipliers # to train two models. Model with equivalently larger learning # rate (i.e., learning_rate * gradient_multiplier) has smaller # training loss. logdir1 = os.path.join( tempfile.mkdtemp(prefix=self.get_temp_dir()), 'tmp_logs1') logdir2 = os.path.join( tempfile.mkdtemp(prefix=self.get_temp_dir()), 'tmp_logs2') multipliers = [1., 1000.] number_of_steps = 10 losses = [] learning_rate = 0.001 # First, train the model with equivalently smaller learning rate. with ops.Graph().as_default(): random_seed.set_random_seed(0) train_op = self.create_train_op( learning_rate=learning_rate, gradient_multiplier=multipliers[0]) loss = learning.train(train_op, logdir1, number_of_steps=number_of_steps) losses.append(loss) self.assertGreater(loss, .5) # Second, train the model with equivalently larger learning rate. with ops.Graph().as_default(): random_seed.set_random_seed(0) train_op = self.create_train_op( learning_rate=learning_rate, gradient_multiplier=multipliers[1]) loss = learning.train(train_op, logdir2, number_of_steps=number_of_steps) losses.append(loss) self.assertIsNotNone(loss) self.assertLess(loss, .5) # The loss of the model trained with larger learning rate should # be smaller. self.assertGreater(losses[0], losses[1]) def testTrainWithEpochLimit(self): logdir = os.path.join( tempfile.mkdtemp(prefix=self.get_temp_dir()), 'tmp_logs') with ops.Graph().as_default(): random_seed.set_random_seed(0) tf_inputs = constant_op.constant(self._inputs, dtype=dtypes.float32) tf_labels = constant_op.constant(self._labels, dtype=dtypes.float32) tf_inputs_limited = input_lib.limit_epochs(tf_inputs, num_epochs=300) tf_labels_limited = input_lib.limit_epochs(tf_labels, num_epochs=300) tf_predictions = LogisticClassifier(tf_inputs_limited) loss_ops.log_loss(tf_predictions, tf_labels_limited) total_loss = loss_ops.get_total_loss() optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=1.0) train_op = learning.create_train_op(total_loss, optimizer) loss = learning.train(train_op, logdir, log_every_n_steps=10) self.assertIsNotNone(loss) self.assertLess(loss, .015) self.assertTrue(os.path.isfile('{}/model.ckpt-300.index'.format(logdir))) self.assertTrue( os.path.isfile('{}/model.ckpt-300.data-00000-of-00001'.format(logdir))) if __name__ == '__main__': test.main()
tensorflow-master
tensorflow/contrib/slim/python/slim/learning_test.py