id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
22,100
tensorflow/tensor2tensor
tensor2tensor/utils/diet.py
make_diet_var_getter
def make_diet_var_getter(params): """Create a custom variable getter for diet variables according to params.""" def diet_var_initializer(shape, dtype, partition_info=None): """Initializer for a diet variable.""" del dtype del partition_info with common_layers.fn_device_dependency("diet_init") as out_deps: float_range = math.sqrt(3) ret = tf.random_uniform(shape, -float_range, float_range) if params.quantize: ret = _quantize(ret, params, randomize=False) out_deps.append(ret) return ret def diet_var_getter(getter, **kwargs): """Get diet variable and return it dequantized.""" if params.quantize: kwargs["dtype"] = tf.float16 kwargs["initializer"] = diet_var_initializer kwargs["trainable"] = False base_var = getter(**kwargs) dequantized = _dequantize(base_var, params) if not hasattr(params, "dequantized"): params.dequantized = defaultdict(list) params.dequantized[base_var.name].append(dequantized) return dequantized return diet_var_getter
python
def make_diet_var_getter(params): """Create a custom variable getter for diet variables according to params.""" def diet_var_initializer(shape, dtype, partition_info=None): """Initializer for a diet variable.""" del dtype del partition_info with common_layers.fn_device_dependency("diet_init") as out_deps: float_range = math.sqrt(3) ret = tf.random_uniform(shape, -float_range, float_range) if params.quantize: ret = _quantize(ret, params, randomize=False) out_deps.append(ret) return ret def diet_var_getter(getter, **kwargs): """Get diet variable and return it dequantized.""" if params.quantize: kwargs["dtype"] = tf.float16 kwargs["initializer"] = diet_var_initializer kwargs["trainable"] = False base_var = getter(**kwargs) dequantized = _dequantize(base_var, params) if not hasattr(params, "dequantized"): params.dequantized = defaultdict(list) params.dequantized[base_var.name].append(dequantized) return dequantized return diet_var_getter
[ "def", "make_diet_var_getter", "(", "params", ")", ":", "def", "diet_var_initializer", "(", "shape", ",", "dtype", ",", "partition_info", "=", "None", ")", ":", "\"\"\"Initializer for a diet variable.\"\"\"", "del", "dtype", "del", "partition_info", "with", "common_layers", ".", "fn_device_dependency", "(", "\"diet_init\"", ")", "as", "out_deps", ":", "float_range", "=", "math", ".", "sqrt", "(", "3", ")", "ret", "=", "tf", ".", "random_uniform", "(", "shape", ",", "-", "float_range", ",", "float_range", ")", "if", "params", ".", "quantize", ":", "ret", "=", "_quantize", "(", "ret", ",", "params", ",", "randomize", "=", "False", ")", "out_deps", ".", "append", "(", "ret", ")", "return", "ret", "def", "diet_var_getter", "(", "getter", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Get diet variable and return it dequantized.\"\"\"", "if", "params", ".", "quantize", ":", "kwargs", "[", "\"dtype\"", "]", "=", "tf", ".", "float16", "kwargs", "[", "\"initializer\"", "]", "=", "diet_var_initializer", "kwargs", "[", "\"trainable\"", "]", "=", "False", "base_var", "=", "getter", "(", "*", "*", "kwargs", ")", "dequantized", "=", "_dequantize", "(", "base_var", ",", "params", ")", "if", "not", "hasattr", "(", "params", ",", "\"dequantized\"", ")", ":", "params", ".", "dequantized", "=", "defaultdict", "(", "list", ")", "params", ".", "dequantized", "[", "base_var", ".", "name", "]", ".", "append", "(", "dequantized", ")", "return", "dequantized", "return", "diet_var_getter" ]
Create a custom variable getter for diet variables according to params.
[ "Create", "a", "custom", "variable", "getter", "for", "diet", "variables", "according", "to", "params", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/diet.py#L260-L293
22,101
tensorflow/tensor2tensor
tensor2tensor/utils/diet.py
_fn_with_diet_vars
def _fn_with_diet_vars(fn, args, params): """Call function with args; use diet variables according to params.""" vs_ctr = [] def grad_fn(inputs, variables, outputs, output_grads): """Custom gradient function.""" del outputs # recomputing below with common_layers.fn_device_dependency("diet_grad", output_grads[0].device) as out_dep: with tf.variable_scope(vs_ctr[0], reuse=True): outputs = fn(*inputs) variables = [common_layers.underlying_variable_ref(v) for v in variables] dequantized_variables = [ params.dequantized[v.name][-1] for v in variables ] grads = tf.gradients(outputs, inputs + dequantized_variables, output_grads) grad_inputs = grads[:len(inputs)] grad_variables = grads[len(inputs):] opt = _create_diet_optimizer(params) # Apply grad_variables here var_updates = [] for v, dv in zip(variables, grad_variables): with tf.variable_scope(vs_ctr[0].name): opt.create_slots(v) update_op = opt.update_variable(v, dv) var_updates.append(update_op) with tf.control_dependencies(var_updates): grad_inputs = [tf.identity(dx) for dx in grad_inputs] out_dep.append(grad_inputs) return grad_inputs, [None] * len(variables) @common_layers.fn_with_custom_grad(grad_fn, use_global_vars=True) def forward(*inputs): with tf.variable_scope( None, default_name="diet", custom_getter=make_diet_var_getter(params)) as vs: vs_ctr.append(vs) outputs = fn(*inputs) return outputs with common_layers.fn_device_dependency("diet_forward", args[0].device) as out_dep: outputs = forward(*args) out_dep.append(outputs) return outputs
python
def _fn_with_diet_vars(fn, args, params): """Call function with args; use diet variables according to params.""" vs_ctr = [] def grad_fn(inputs, variables, outputs, output_grads): """Custom gradient function.""" del outputs # recomputing below with common_layers.fn_device_dependency("diet_grad", output_grads[0].device) as out_dep: with tf.variable_scope(vs_ctr[0], reuse=True): outputs = fn(*inputs) variables = [common_layers.underlying_variable_ref(v) for v in variables] dequantized_variables = [ params.dequantized[v.name][-1] for v in variables ] grads = tf.gradients(outputs, inputs + dequantized_variables, output_grads) grad_inputs = grads[:len(inputs)] grad_variables = grads[len(inputs):] opt = _create_diet_optimizer(params) # Apply grad_variables here var_updates = [] for v, dv in zip(variables, grad_variables): with tf.variable_scope(vs_ctr[0].name): opt.create_slots(v) update_op = opt.update_variable(v, dv) var_updates.append(update_op) with tf.control_dependencies(var_updates): grad_inputs = [tf.identity(dx) for dx in grad_inputs] out_dep.append(grad_inputs) return grad_inputs, [None] * len(variables) @common_layers.fn_with_custom_grad(grad_fn, use_global_vars=True) def forward(*inputs): with tf.variable_scope( None, default_name="diet", custom_getter=make_diet_var_getter(params)) as vs: vs_ctr.append(vs) outputs = fn(*inputs) return outputs with common_layers.fn_device_dependency("diet_forward", args[0].device) as out_dep: outputs = forward(*args) out_dep.append(outputs) return outputs
[ "def", "_fn_with_diet_vars", "(", "fn", ",", "args", ",", "params", ")", ":", "vs_ctr", "=", "[", "]", "def", "grad_fn", "(", "inputs", ",", "variables", ",", "outputs", ",", "output_grads", ")", ":", "\"\"\"Custom gradient function.\"\"\"", "del", "outputs", "# recomputing below", "with", "common_layers", ".", "fn_device_dependency", "(", "\"diet_grad\"", ",", "output_grads", "[", "0", "]", ".", "device", ")", "as", "out_dep", ":", "with", "tf", ".", "variable_scope", "(", "vs_ctr", "[", "0", "]", ",", "reuse", "=", "True", ")", ":", "outputs", "=", "fn", "(", "*", "inputs", ")", "variables", "=", "[", "common_layers", ".", "underlying_variable_ref", "(", "v", ")", "for", "v", "in", "variables", "]", "dequantized_variables", "=", "[", "params", ".", "dequantized", "[", "v", ".", "name", "]", "[", "-", "1", "]", "for", "v", "in", "variables", "]", "grads", "=", "tf", ".", "gradients", "(", "outputs", ",", "inputs", "+", "dequantized_variables", ",", "output_grads", ")", "grad_inputs", "=", "grads", "[", ":", "len", "(", "inputs", ")", "]", "grad_variables", "=", "grads", "[", "len", "(", "inputs", ")", ":", "]", "opt", "=", "_create_diet_optimizer", "(", "params", ")", "# Apply grad_variables here", "var_updates", "=", "[", "]", "for", "v", ",", "dv", "in", "zip", "(", "variables", ",", "grad_variables", ")", ":", "with", "tf", ".", "variable_scope", "(", "vs_ctr", "[", "0", "]", ".", "name", ")", ":", "opt", ".", "create_slots", "(", "v", ")", "update_op", "=", "opt", ".", "update_variable", "(", "v", ",", "dv", ")", "var_updates", ".", "append", "(", "update_op", ")", "with", "tf", ".", "control_dependencies", "(", "var_updates", ")", ":", "grad_inputs", "=", "[", "tf", ".", "identity", "(", "dx", ")", "for", "dx", "in", "grad_inputs", "]", "out_dep", ".", "append", "(", "grad_inputs", ")", "return", "grad_inputs", ",", "[", "None", "]", "*", "len", "(", "variables", ")", "@", "common_layers", ".", "fn_with_custom_grad", "(", "grad_fn", ",", "use_global_vars", "=", "True", ")", "def", "forward", "(", "*", "inputs", ")", ":", "with", "tf", ".", "variable_scope", "(", "None", ",", "default_name", "=", "\"diet\"", ",", "custom_getter", "=", "make_diet_var_getter", "(", "params", ")", ")", "as", "vs", ":", "vs_ctr", ".", "append", "(", "vs", ")", "outputs", "=", "fn", "(", "*", "inputs", ")", "return", "outputs", "with", "common_layers", ".", "fn_device_dependency", "(", "\"diet_forward\"", ",", "args", "[", "0", "]", ".", "device", ")", "as", "out_dep", ":", "outputs", "=", "forward", "(", "*", "args", ")", "out_dep", ".", "append", "(", "outputs", ")", "return", "outputs" ]
Call function with args; use diet variables according to params.
[ "Call", "function", "with", "args", ";", "use", "diet", "variables", "according", "to", "params", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/diet.py#L296-L349
22,102
tensorflow/tensor2tensor
tensor2tensor/utils/diet.py
fn_with_diet_vars
def fn_with_diet_vars(params): """Decorator for graph-building function to use diet variables.""" params = copy.copy(params) def dec(fn): def wrapped(*args): return _fn_with_diet_vars(fn, args, params) return wrapped return dec
python
def fn_with_diet_vars(params): """Decorator for graph-building function to use diet variables.""" params = copy.copy(params) def dec(fn): def wrapped(*args): return _fn_with_diet_vars(fn, args, params) return wrapped return dec
[ "def", "fn_with_diet_vars", "(", "params", ")", ":", "params", "=", "copy", ".", "copy", "(", "params", ")", "def", "dec", "(", "fn", ")", ":", "def", "wrapped", "(", "*", "args", ")", ":", "return", "_fn_with_diet_vars", "(", "fn", ",", "args", ",", "params", ")", "return", "wrapped", "return", "dec" ]
Decorator for graph-building function to use diet variables.
[ "Decorator", "for", "graph", "-", "building", "function", "to", "use", "diet", "variables", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/diet.py#L352-L363
22,103
tensorflow/tensor2tensor
tensor2tensor/utils/diet.py
DietAdamOptimizer.create_slots
def create_slots(self, var): """Create the factorized Adam accumulators for diet variables.""" params = self.params shape = var.get_shape().as_list() if not hasattr(params, "slots"): params.slots = defaultdict(dict) name = var.op.name slots = params.slots[name] if params.factored_second_moment_accumulator and len(shape) == 2: slots["adam_vr"] = tf.get_variable( name + "_adam_vr", [shape[0], 1], trainable=False, initializer=tf.zeros_initializer()) slots["adam_vc"] = tf.get_variable( name + "_adam_vc", [1, shape[1]], trainable=False, initializer=tf.zeros_initializer()) else: slots["adam_v"] = tf.get_variable( name + "_adam_v", shape, trainable=False, initializer=tf.zeros_initializer()) if params.beta1 != 0.0: slots["adam_m"] = tf.get_variable( name + "_adam_m", shape, trainable=False, initializer=tf.zeros_initializer())
python
def create_slots(self, var): """Create the factorized Adam accumulators for diet variables.""" params = self.params shape = var.get_shape().as_list() if not hasattr(params, "slots"): params.slots = defaultdict(dict) name = var.op.name slots = params.slots[name] if params.factored_second_moment_accumulator and len(shape) == 2: slots["adam_vr"] = tf.get_variable( name + "_adam_vr", [shape[0], 1], trainable=False, initializer=tf.zeros_initializer()) slots["adam_vc"] = tf.get_variable( name + "_adam_vc", [1, shape[1]], trainable=False, initializer=tf.zeros_initializer()) else: slots["adam_v"] = tf.get_variable( name + "_adam_v", shape, trainable=False, initializer=tf.zeros_initializer()) if params.beta1 != 0.0: slots["adam_m"] = tf.get_variable( name + "_adam_m", shape, trainable=False, initializer=tf.zeros_initializer())
[ "def", "create_slots", "(", "self", ",", "var", ")", ":", "params", "=", "self", ".", "params", "shape", "=", "var", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "if", "not", "hasattr", "(", "params", ",", "\"slots\"", ")", ":", "params", ".", "slots", "=", "defaultdict", "(", "dict", ")", "name", "=", "var", ".", "op", ".", "name", "slots", "=", "params", ".", "slots", "[", "name", "]", "if", "params", ".", "factored_second_moment_accumulator", "and", "len", "(", "shape", ")", "==", "2", ":", "slots", "[", "\"adam_vr\"", "]", "=", "tf", ".", "get_variable", "(", "name", "+", "\"_adam_vr\"", ",", "[", "shape", "[", "0", "]", ",", "1", "]", ",", "trainable", "=", "False", ",", "initializer", "=", "tf", ".", "zeros_initializer", "(", ")", ")", "slots", "[", "\"adam_vc\"", "]", "=", "tf", ".", "get_variable", "(", "name", "+", "\"_adam_vc\"", ",", "[", "1", ",", "shape", "[", "1", "]", "]", ",", "trainable", "=", "False", ",", "initializer", "=", "tf", ".", "zeros_initializer", "(", ")", ")", "else", ":", "slots", "[", "\"adam_v\"", "]", "=", "tf", ".", "get_variable", "(", "name", "+", "\"_adam_v\"", ",", "shape", ",", "trainable", "=", "False", ",", "initializer", "=", "tf", ".", "zeros_initializer", "(", ")", ")", "if", "params", ".", "beta1", "!=", "0.0", ":", "slots", "[", "\"adam_m\"", "]", "=", "tf", ".", "get_variable", "(", "name", "+", "\"_adam_m\"", ",", "shape", ",", "trainable", "=", "False", ",", "initializer", "=", "tf", ".", "zeros_initializer", "(", ")", ")" ]
Create the factorized Adam accumulators for diet variables.
[ "Create", "the", "factorized", "Adam", "accumulators", "for", "diet", "variables", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/diet.py#L144-L175
22,104
tensorflow/tensor2tensor
tensor2tensor/utils/diet.py
DietAdamOptimizer.update_variable
def update_variable(self, var, grad_var): """Update the variable and its slots.""" params = self.params global_step = tf.to_float(self.global_step) + 1 # compute learning rate lrate = params.learning_rate if params.learning_rate_decay_scheme == "noam": lrate *= tf.minimum(global_step * params.learning_rate_warmup_steps**-1.5, global_step**-0.5) else: assert params.learning_rate_decay_scheme == "none" lrate *= tf.minimum(global_step / params.learning_rate_warmup_steps, 1.0) # compute adjustment due to second moment slots = params.slots[var.op.name] grad_squared = tf.square(grad_var) beta2_pow = tf.pow(params.beta2, global_step) if params.factored_second_moment_accumulator and len(var.shape) == 2: vr_update = tf.assign(slots["adam_vr"], slots["adam_vr"] * params.beta2 + tf.reduce_mean(grad_squared, 1, keepdims=True) * (1.0 - params.beta2)) vc_update = tf.assign(slots["adam_vc"], slots["adam_vc"] * params.beta2 + tf.reduce_mean(grad_squared, 0, keepdims=True) * (1.0 - params.beta2)) with tf.control_dependencies([vr_update, vc_update]): vr = tf.sqrt(slots["adam_vr"] / (1.0 - beta2_pow)) + params.epsilon vc = tf.sqrt(slots["adam_vc"] / (1.0 - beta2_pow)) + params.epsilon vc /= tf.reduce_mean(vc) denom = vr * vc else: v_update = tf.assign(slots["adam_v"], slots["adam_v"] * params.beta2 + grad_squared * (1.0 - params.beta2)) with tf.control_dependencies([v_update]): denom = tf.sqrt(slots["adam_v"] / (1.0 - beta2_pow)) + params.epsilon # compute momentum if applicable if params.beta1 != 0.0: m_update = tf.assign(slots["adam_m"], slots["adam_m"] * params.beta1 + grad_var * (1.0 - params.beta1)) with tf.control_dependencies([m_update]): grad_var = slots["adam_m"] # update var subtrahend = lrate * grad_var / denom new_val = _quantize(_dequantize(var, params) - subtrahend, params) return tf.assign(var, new_val)
python
def update_variable(self, var, grad_var): """Update the variable and its slots.""" params = self.params global_step = tf.to_float(self.global_step) + 1 # compute learning rate lrate = params.learning_rate if params.learning_rate_decay_scheme == "noam": lrate *= tf.minimum(global_step * params.learning_rate_warmup_steps**-1.5, global_step**-0.5) else: assert params.learning_rate_decay_scheme == "none" lrate *= tf.minimum(global_step / params.learning_rate_warmup_steps, 1.0) # compute adjustment due to second moment slots = params.slots[var.op.name] grad_squared = tf.square(grad_var) beta2_pow = tf.pow(params.beta2, global_step) if params.factored_second_moment_accumulator and len(var.shape) == 2: vr_update = tf.assign(slots["adam_vr"], slots["adam_vr"] * params.beta2 + tf.reduce_mean(grad_squared, 1, keepdims=True) * (1.0 - params.beta2)) vc_update = tf.assign(slots["adam_vc"], slots["adam_vc"] * params.beta2 + tf.reduce_mean(grad_squared, 0, keepdims=True) * (1.0 - params.beta2)) with tf.control_dependencies([vr_update, vc_update]): vr = tf.sqrt(slots["adam_vr"] / (1.0 - beta2_pow)) + params.epsilon vc = tf.sqrt(slots["adam_vc"] / (1.0 - beta2_pow)) + params.epsilon vc /= tf.reduce_mean(vc) denom = vr * vc else: v_update = tf.assign(slots["adam_v"], slots["adam_v"] * params.beta2 + grad_squared * (1.0 - params.beta2)) with tf.control_dependencies([v_update]): denom = tf.sqrt(slots["adam_v"] / (1.0 - beta2_pow)) + params.epsilon # compute momentum if applicable if params.beta1 != 0.0: m_update = tf.assign(slots["adam_m"], slots["adam_m"] * params.beta1 + grad_var * (1.0 - params.beta1)) with tf.control_dependencies([m_update]): grad_var = slots["adam_m"] # update var subtrahend = lrate * grad_var / denom new_val = _quantize(_dequantize(var, params) - subtrahend, params) return tf.assign(var, new_val)
[ "def", "update_variable", "(", "self", ",", "var", ",", "grad_var", ")", ":", "params", "=", "self", ".", "params", "global_step", "=", "tf", ".", "to_float", "(", "self", ".", "global_step", ")", "+", "1", "# compute learning rate", "lrate", "=", "params", ".", "learning_rate", "if", "params", ".", "learning_rate_decay_scheme", "==", "\"noam\"", ":", "lrate", "*=", "tf", ".", "minimum", "(", "global_step", "*", "params", ".", "learning_rate_warmup_steps", "**", "-", "1.5", ",", "global_step", "**", "-", "0.5", ")", "else", ":", "assert", "params", ".", "learning_rate_decay_scheme", "==", "\"none\"", "lrate", "*=", "tf", ".", "minimum", "(", "global_step", "/", "params", ".", "learning_rate_warmup_steps", ",", "1.0", ")", "# compute adjustment due to second moment", "slots", "=", "params", ".", "slots", "[", "var", ".", "op", ".", "name", "]", "grad_squared", "=", "tf", ".", "square", "(", "grad_var", ")", "beta2_pow", "=", "tf", ".", "pow", "(", "params", ".", "beta2", ",", "global_step", ")", "if", "params", ".", "factored_second_moment_accumulator", "and", "len", "(", "var", ".", "shape", ")", "==", "2", ":", "vr_update", "=", "tf", ".", "assign", "(", "slots", "[", "\"adam_vr\"", "]", ",", "slots", "[", "\"adam_vr\"", "]", "*", "params", ".", "beta2", "+", "tf", ".", "reduce_mean", "(", "grad_squared", ",", "1", ",", "keepdims", "=", "True", ")", "*", "(", "1.0", "-", "params", ".", "beta2", ")", ")", "vc_update", "=", "tf", ".", "assign", "(", "slots", "[", "\"adam_vc\"", "]", ",", "slots", "[", "\"adam_vc\"", "]", "*", "params", ".", "beta2", "+", "tf", ".", "reduce_mean", "(", "grad_squared", ",", "0", ",", "keepdims", "=", "True", ")", "*", "(", "1.0", "-", "params", ".", "beta2", ")", ")", "with", "tf", ".", "control_dependencies", "(", "[", "vr_update", ",", "vc_update", "]", ")", ":", "vr", "=", "tf", ".", "sqrt", "(", "slots", "[", "\"adam_vr\"", "]", "/", "(", "1.0", "-", "beta2_pow", ")", ")", "+", "params", ".", "epsilon", "vc", "=", "tf", ".", "sqrt", "(", "slots", "[", "\"adam_vc\"", "]", "/", "(", "1.0", "-", "beta2_pow", ")", ")", "+", "params", ".", "epsilon", "vc", "/=", "tf", ".", "reduce_mean", "(", "vc", ")", "denom", "=", "vr", "*", "vc", "else", ":", "v_update", "=", "tf", ".", "assign", "(", "slots", "[", "\"adam_v\"", "]", ",", "slots", "[", "\"adam_v\"", "]", "*", "params", ".", "beta2", "+", "grad_squared", "*", "(", "1.0", "-", "params", ".", "beta2", ")", ")", "with", "tf", ".", "control_dependencies", "(", "[", "v_update", "]", ")", ":", "denom", "=", "tf", ".", "sqrt", "(", "slots", "[", "\"adam_v\"", "]", "/", "(", "1.0", "-", "beta2_pow", ")", ")", "+", "params", ".", "epsilon", "# compute momentum if applicable", "if", "params", ".", "beta1", "!=", "0.0", ":", "m_update", "=", "tf", ".", "assign", "(", "slots", "[", "\"adam_m\"", "]", ",", "slots", "[", "\"adam_m\"", "]", "*", "params", ".", "beta1", "+", "grad_var", "*", "(", "1.0", "-", "params", ".", "beta1", ")", ")", "with", "tf", ".", "control_dependencies", "(", "[", "m_update", "]", ")", ":", "grad_var", "=", "slots", "[", "\"adam_m\"", "]", "# update var", "subtrahend", "=", "lrate", "*", "grad_var", "/", "denom", "new_val", "=", "_quantize", "(", "_dequantize", "(", "var", ",", "params", ")", "-", "subtrahend", ",", "params", ")", "return", "tf", ".", "assign", "(", "var", ",", "new_val", ")" ]
Update the variable and its slots.
[ "Update", "the", "variable", "and", "its", "slots", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/diet.py#L177-L225
22,105
tensorflow/tensor2tensor
tensor2tensor/utils/mtf_model.py
MtfModel.estimator_spec_eval
def estimator_spec_eval( self, features, logits, labels, loss, restore_hook, use_tpu): """Construct EstimatorSpec for EVAL mode.""" hparams = self.hparams problem = hparams.problem if logits.get_shape().ndims == 3: logits = tf.expand_dims(tf.expand_dims(logits, 2), 3) # Support for multiproblem task_list = [problem] if hasattr(problem, "task_list"): task_list = problem.task_list eval_metrics_fns = metrics.create_evaluation_metrics(task_list, hparams) if use_tpu: def metric_fn(tf_logits, labels): with tf.device("cpu:0"), mtf.utils.outside_all_rewrites(): eval_metrics = {} for metric_name, metric_fn in six.iteritems(eval_metrics_fns): if metric_name.split("/")[-1] not in t2t_model.TPU_METRIC_BLACKLIST: eval_metrics[metric_name] = metric_fn( tf_logits, None, tf.identity(labels)) return eval_metrics return tpu_estimator.TPUEstimatorSpec( tf.estimator.ModeKeys.EVAL, evaluation_hooks=[restore_hook], loss=loss, eval_metrics=(metric_fn, [logits, labels])) else: eval_metrics = {} predictions = {"predictions": logits} for metric_name, metric_fn in six.iteritems(eval_metrics_fns): eval_metrics[metric_name] = metric_fn(logits, features, features["targets"]) return tf.estimator.EstimatorSpec( tf.estimator.ModeKeys.EVAL, predictions=predictions, eval_metric_ops=eval_metrics, evaluation_hooks=[restore_hook], loss=loss)
python
def estimator_spec_eval( self, features, logits, labels, loss, restore_hook, use_tpu): """Construct EstimatorSpec for EVAL mode.""" hparams = self.hparams problem = hparams.problem if logits.get_shape().ndims == 3: logits = tf.expand_dims(tf.expand_dims(logits, 2), 3) # Support for multiproblem task_list = [problem] if hasattr(problem, "task_list"): task_list = problem.task_list eval_metrics_fns = metrics.create_evaluation_metrics(task_list, hparams) if use_tpu: def metric_fn(tf_logits, labels): with tf.device("cpu:0"), mtf.utils.outside_all_rewrites(): eval_metrics = {} for metric_name, metric_fn in six.iteritems(eval_metrics_fns): if metric_name.split("/")[-1] not in t2t_model.TPU_METRIC_BLACKLIST: eval_metrics[metric_name] = metric_fn( tf_logits, None, tf.identity(labels)) return eval_metrics return tpu_estimator.TPUEstimatorSpec( tf.estimator.ModeKeys.EVAL, evaluation_hooks=[restore_hook], loss=loss, eval_metrics=(metric_fn, [logits, labels])) else: eval_metrics = {} predictions = {"predictions": logits} for metric_name, metric_fn in six.iteritems(eval_metrics_fns): eval_metrics[metric_name] = metric_fn(logits, features, features["targets"]) return tf.estimator.EstimatorSpec( tf.estimator.ModeKeys.EVAL, predictions=predictions, eval_metric_ops=eval_metrics, evaluation_hooks=[restore_hook], loss=loss)
[ "def", "estimator_spec_eval", "(", "self", ",", "features", ",", "logits", ",", "labels", ",", "loss", ",", "restore_hook", ",", "use_tpu", ")", ":", "hparams", "=", "self", ".", "hparams", "problem", "=", "hparams", ".", "problem", "if", "logits", ".", "get_shape", "(", ")", ".", "ndims", "==", "3", ":", "logits", "=", "tf", ".", "expand_dims", "(", "tf", ".", "expand_dims", "(", "logits", ",", "2", ")", ",", "3", ")", "# Support for multiproblem", "task_list", "=", "[", "problem", "]", "if", "hasattr", "(", "problem", ",", "\"task_list\"", ")", ":", "task_list", "=", "problem", ".", "task_list", "eval_metrics_fns", "=", "metrics", ".", "create_evaluation_metrics", "(", "task_list", ",", "hparams", ")", "if", "use_tpu", ":", "def", "metric_fn", "(", "tf_logits", ",", "labels", ")", ":", "with", "tf", ".", "device", "(", "\"cpu:0\"", ")", ",", "mtf", ".", "utils", ".", "outside_all_rewrites", "(", ")", ":", "eval_metrics", "=", "{", "}", "for", "metric_name", ",", "metric_fn", "in", "six", ".", "iteritems", "(", "eval_metrics_fns", ")", ":", "if", "metric_name", ".", "split", "(", "\"/\"", ")", "[", "-", "1", "]", "not", "in", "t2t_model", ".", "TPU_METRIC_BLACKLIST", ":", "eval_metrics", "[", "metric_name", "]", "=", "metric_fn", "(", "tf_logits", ",", "None", ",", "tf", ".", "identity", "(", "labels", ")", ")", "return", "eval_metrics", "return", "tpu_estimator", ".", "TPUEstimatorSpec", "(", "tf", ".", "estimator", ".", "ModeKeys", ".", "EVAL", ",", "evaluation_hooks", "=", "[", "restore_hook", "]", ",", "loss", "=", "loss", ",", "eval_metrics", "=", "(", "metric_fn", ",", "[", "logits", ",", "labels", "]", ")", ")", "else", ":", "eval_metrics", "=", "{", "}", "predictions", "=", "{", "\"predictions\"", ":", "logits", "}", "for", "metric_name", ",", "metric_fn", "in", "six", ".", "iteritems", "(", "eval_metrics_fns", ")", ":", "eval_metrics", "[", "metric_name", "]", "=", "metric_fn", "(", "logits", ",", "features", ",", "features", "[", "\"targets\"", "]", ")", "return", "tf", ".", "estimator", ".", "EstimatorSpec", "(", "tf", ".", "estimator", ".", "ModeKeys", ".", "EVAL", ",", "predictions", "=", "predictions", ",", "eval_metric_ops", "=", "eval_metrics", ",", "evaluation_hooks", "=", "[", "restore_hook", "]", ",", "loss", "=", "loss", ")" ]
Construct EstimatorSpec for EVAL mode.
[ "Construct", "EstimatorSpec", "for", "EVAL", "mode", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/mtf_model.py#L188-L229
22,106
tensorflow/tensor2tensor
tensor2tensor/data_generators/desc2code.py
generator_samples
def generator_samples(tmp_dir, pb_cst): """Generator for the dataset samples. If not present, download and extract the dataset. Args: tmp_dir: path to the directory where to download the dataset. pb_cst: CodingPbConstants object defining paths Yields: A CodingPbInfo object containing the next challenge informations. """ # Step1: Download dataset (eventually) data_zip_path = generator_utils.maybe_download_from_drive( directory=tmp_dir, filename=_DATASET_FILENAME, url=_DATASET_URL, ) tf.logging.info("Data downloaded in: {}".format(data_zip_path)) # Step2: Extract dataset # We could deduce _DATASET_PB_PATH from the zip file (instead of # hardcoded path) data_rootdir = os.path.join(tmp_dir, _DATASET_PB_PATH) if not tf.gfile.Exists(data_rootdir): with zipfile.ZipFile(data_zip_path, "r") as corpus_zip: corpus_zip.extractall(tmp_dir) # We could remove the extracted __MACOSX folder tf.logging.info("Data extracted in: {}".format(tmp_dir)) else: tf.logging.info("Data already extracted in: {}".format(tmp_dir)) # Step3: Extract the problems list on the extracted folder def contains_samples(subdir, dirs, files): # pylint: disable=unused-argument """Check that the folder contains a problem.""" return ( _DESC_DIR_NAME in dirs and pb_cst.code_dir_name in dirs ) def next_sample(subdir, dirs, files): # pylint: disable=unused-argument """Return the filenames of the problem.""" # More could be extracted (like the expected inputs/outputs # pairs, the problem difficulty, the names of the algorithmic techniques # needed) desc_file = os.path.join(subdir, _DESC_DIR_NAME, "description.txt") code_files = [] # As the dataset is noisy, the program deduce the language from the file # content. code_pattern = os.path.join(subdir, pb_cst.code_dir_name, "*.txt") for f in tf.gfile.Glob(code_pattern): with tf.gfile.GFile(f, mode="r") as target_file: # Hack to filter C++/Java files. In theory some python comments could # make the file be considered as C++ but in practice the chance of # getting a false negative is low. content = target_file.read() if not any(p in content for p in pb_cst.filter_patterns): code_files.append(f) return CodingPbInfo( desc_file=desc_file, code_files=code_files ) # The dataset contains problem from two different sources (CodeChef # and CodeForces). Due to the limited number of samples, all problems from # both sources are merged for w in tf.gfile.Walk(data_rootdir): if contains_samples(*w): yield next_sample(*w)
python
def generator_samples(tmp_dir, pb_cst): """Generator for the dataset samples. If not present, download and extract the dataset. Args: tmp_dir: path to the directory where to download the dataset. pb_cst: CodingPbConstants object defining paths Yields: A CodingPbInfo object containing the next challenge informations. """ # Step1: Download dataset (eventually) data_zip_path = generator_utils.maybe_download_from_drive( directory=tmp_dir, filename=_DATASET_FILENAME, url=_DATASET_URL, ) tf.logging.info("Data downloaded in: {}".format(data_zip_path)) # Step2: Extract dataset # We could deduce _DATASET_PB_PATH from the zip file (instead of # hardcoded path) data_rootdir = os.path.join(tmp_dir, _DATASET_PB_PATH) if not tf.gfile.Exists(data_rootdir): with zipfile.ZipFile(data_zip_path, "r") as corpus_zip: corpus_zip.extractall(tmp_dir) # We could remove the extracted __MACOSX folder tf.logging.info("Data extracted in: {}".format(tmp_dir)) else: tf.logging.info("Data already extracted in: {}".format(tmp_dir)) # Step3: Extract the problems list on the extracted folder def contains_samples(subdir, dirs, files): # pylint: disable=unused-argument """Check that the folder contains a problem.""" return ( _DESC_DIR_NAME in dirs and pb_cst.code_dir_name in dirs ) def next_sample(subdir, dirs, files): # pylint: disable=unused-argument """Return the filenames of the problem.""" # More could be extracted (like the expected inputs/outputs # pairs, the problem difficulty, the names of the algorithmic techniques # needed) desc_file = os.path.join(subdir, _DESC_DIR_NAME, "description.txt") code_files = [] # As the dataset is noisy, the program deduce the language from the file # content. code_pattern = os.path.join(subdir, pb_cst.code_dir_name, "*.txt") for f in tf.gfile.Glob(code_pattern): with tf.gfile.GFile(f, mode="r") as target_file: # Hack to filter C++/Java files. In theory some python comments could # make the file be considered as C++ but in practice the chance of # getting a false negative is low. content = target_file.read() if not any(p in content for p in pb_cst.filter_patterns): code_files.append(f) return CodingPbInfo( desc_file=desc_file, code_files=code_files ) # The dataset contains problem from two different sources (CodeChef # and CodeForces). Due to the limited number of samples, all problems from # both sources are merged for w in tf.gfile.Walk(data_rootdir): if contains_samples(*w): yield next_sample(*w)
[ "def", "generator_samples", "(", "tmp_dir", ",", "pb_cst", ")", ":", "# Step1: Download dataset (eventually)", "data_zip_path", "=", "generator_utils", ".", "maybe_download_from_drive", "(", "directory", "=", "tmp_dir", ",", "filename", "=", "_DATASET_FILENAME", ",", "url", "=", "_DATASET_URL", ",", ")", "tf", ".", "logging", ".", "info", "(", "\"Data downloaded in: {}\"", ".", "format", "(", "data_zip_path", ")", ")", "# Step2: Extract dataset", "# We could deduce _DATASET_PB_PATH from the zip file (instead of", "# hardcoded path)", "data_rootdir", "=", "os", ".", "path", ".", "join", "(", "tmp_dir", ",", "_DATASET_PB_PATH", ")", "if", "not", "tf", ".", "gfile", ".", "Exists", "(", "data_rootdir", ")", ":", "with", "zipfile", ".", "ZipFile", "(", "data_zip_path", ",", "\"r\"", ")", "as", "corpus_zip", ":", "corpus_zip", ".", "extractall", "(", "tmp_dir", ")", "# We could remove the extracted __MACOSX folder", "tf", ".", "logging", ".", "info", "(", "\"Data extracted in: {}\"", ".", "format", "(", "tmp_dir", ")", ")", "else", ":", "tf", ".", "logging", ".", "info", "(", "\"Data already extracted in: {}\"", ".", "format", "(", "tmp_dir", ")", ")", "# Step3: Extract the problems list on the extracted folder", "def", "contains_samples", "(", "subdir", ",", "dirs", ",", "files", ")", ":", "# pylint: disable=unused-argument", "\"\"\"Check that the folder contains a problem.\"\"\"", "return", "(", "_DESC_DIR_NAME", "in", "dirs", "and", "pb_cst", ".", "code_dir_name", "in", "dirs", ")", "def", "next_sample", "(", "subdir", ",", "dirs", ",", "files", ")", ":", "# pylint: disable=unused-argument", "\"\"\"Return the filenames of the problem.\"\"\"", "# More could be extracted (like the expected inputs/outputs", "# pairs, the problem difficulty, the names of the algorithmic techniques", "# needed)", "desc_file", "=", "os", ".", "path", ".", "join", "(", "subdir", ",", "_DESC_DIR_NAME", ",", "\"description.txt\"", ")", "code_files", "=", "[", "]", "# As the dataset is noisy, the program deduce the language from the file", "# content.", "code_pattern", "=", "os", ".", "path", ".", "join", "(", "subdir", ",", "pb_cst", ".", "code_dir_name", ",", "\"*.txt\"", ")", "for", "f", "in", "tf", ".", "gfile", ".", "Glob", "(", "code_pattern", ")", ":", "with", "tf", ".", "gfile", ".", "GFile", "(", "f", ",", "mode", "=", "\"r\"", ")", "as", "target_file", ":", "# Hack to filter C++/Java files. In theory some python comments could", "# make the file be considered as C++ but in practice the chance of", "# getting a false negative is low.", "content", "=", "target_file", ".", "read", "(", ")", "if", "not", "any", "(", "p", "in", "content", "for", "p", "in", "pb_cst", ".", "filter_patterns", ")", ":", "code_files", ".", "append", "(", "f", ")", "return", "CodingPbInfo", "(", "desc_file", "=", "desc_file", ",", "code_files", "=", "code_files", ")", "# The dataset contains problem from two different sources (CodeChef", "# and CodeForces). Due to the limited number of samples, all problems from", "# both sources are merged", "for", "w", "in", "tf", ".", "gfile", ".", "Walk", "(", "data_rootdir", ")", ":", "if", "contains_samples", "(", "*", "w", ")", ":", "yield", "next_sample", "(", "*", "w", ")" ]
Generator for the dataset samples. If not present, download and extract the dataset. Args: tmp_dir: path to the directory where to download the dataset. pb_cst: CodingPbConstants object defining paths Yields: A CodingPbInfo object containing the next challenge informations.
[ "Generator", "for", "the", "dataset", "samples", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/desc2code.py#L240-L308
22,107
tensorflow/tensor2tensor
tensor2tensor/models/lstm.py
lstm
def lstm(inputs, sequence_length, hparams, train, name, initial_state=None): """Adds a stack of LSTM layers on top of input. Args: inputs: The input `Tensor`, shaped `[batch_size, time_steps, hidden_size]`. sequence_length: Lengths of the actual input sequence, excluding padding; a `Tensor` shaped `[batch_size]`. hparams: HParams; hyperparameters. train: bool; `True` when constructing training graph to enable dropout. name: string; Create variable names under this scope. initial_state: tuple of `LSTMStateTuple`s; the initial state of each layer. Returns: A tuple (outputs, states), where: outputs: The output `Tensor`, shaped `[batch_size, time_steps, hidden_size]`. states: A tuple of `LSTMStateTuple`s; the final state of each layer. Bidirectional LSTM returns a concatenation of last forward and backward state, reduced to the original dimensionality. """ layers = [_dropout_lstm_cell(hparams, train) for _ in range(hparams.num_hidden_layers)] with tf.variable_scope(name): return tf.nn.dynamic_rnn( tf.nn.rnn_cell.MultiRNNCell(layers), inputs, sequence_length, initial_state=initial_state, dtype=tf.float32, time_major=False)
python
def lstm(inputs, sequence_length, hparams, train, name, initial_state=None): """Adds a stack of LSTM layers on top of input. Args: inputs: The input `Tensor`, shaped `[batch_size, time_steps, hidden_size]`. sequence_length: Lengths of the actual input sequence, excluding padding; a `Tensor` shaped `[batch_size]`. hparams: HParams; hyperparameters. train: bool; `True` when constructing training graph to enable dropout. name: string; Create variable names under this scope. initial_state: tuple of `LSTMStateTuple`s; the initial state of each layer. Returns: A tuple (outputs, states), where: outputs: The output `Tensor`, shaped `[batch_size, time_steps, hidden_size]`. states: A tuple of `LSTMStateTuple`s; the final state of each layer. Bidirectional LSTM returns a concatenation of last forward and backward state, reduced to the original dimensionality. """ layers = [_dropout_lstm_cell(hparams, train) for _ in range(hparams.num_hidden_layers)] with tf.variable_scope(name): return tf.nn.dynamic_rnn( tf.nn.rnn_cell.MultiRNNCell(layers), inputs, sequence_length, initial_state=initial_state, dtype=tf.float32, time_major=False)
[ "def", "lstm", "(", "inputs", ",", "sequence_length", ",", "hparams", ",", "train", ",", "name", ",", "initial_state", "=", "None", ")", ":", "layers", "=", "[", "_dropout_lstm_cell", "(", "hparams", ",", "train", ")", "for", "_", "in", "range", "(", "hparams", ".", "num_hidden_layers", ")", "]", "with", "tf", ".", "variable_scope", "(", "name", ")", ":", "return", "tf", ".", "nn", ".", "dynamic_rnn", "(", "tf", ".", "nn", ".", "rnn_cell", ".", "MultiRNNCell", "(", "layers", ")", ",", "inputs", ",", "sequence_length", ",", "initial_state", "=", "initial_state", ",", "dtype", "=", "tf", ".", "float32", ",", "time_major", "=", "False", ")" ]
Adds a stack of LSTM layers on top of input. Args: inputs: The input `Tensor`, shaped `[batch_size, time_steps, hidden_size]`. sequence_length: Lengths of the actual input sequence, excluding padding; a `Tensor` shaped `[batch_size]`. hparams: HParams; hyperparameters. train: bool; `True` when constructing training graph to enable dropout. name: string; Create variable names under this scope. initial_state: tuple of `LSTMStateTuple`s; the initial state of each layer. Returns: A tuple (outputs, states), where: outputs: The output `Tensor`, shaped `[batch_size, time_steps, hidden_size]`. states: A tuple of `LSTMStateTuple`s; the final state of each layer. Bidirectional LSTM returns a concatenation of last forward and backward state, reduced to the original dimensionality.
[ "Adds", "a", "stack", "of", "LSTM", "layers", "on", "top", "of", "input", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/lstm.py#L38-L67
22,108
tensorflow/tensor2tensor
tensor2tensor/models/lstm.py
lstm_seq2seq_internal
def lstm_seq2seq_internal(inputs, targets, hparams, train): """The basic LSTM seq2seq model, main step used for training.""" with tf.variable_scope("lstm_seq2seq"): if inputs is not None: inputs_length = common_layers.length_from_embedding(inputs) # Flatten inputs. inputs = common_layers.flatten4d3d(inputs) # LSTM encoder. inputs = tf.reverse_sequence(inputs, inputs_length, seq_axis=1) _, final_encoder_state = lstm(inputs, inputs_length, hparams, train, "encoder") else: final_encoder_state = None # LSTM decoder. shifted_targets = common_layers.shift_right(targets) # Add 1 to account for the padding added to the left from shift_right targets_length = common_layers.length_from_embedding(shifted_targets) + 1 decoder_outputs, _ = lstm( common_layers.flatten4d3d(shifted_targets), targets_length, hparams, train, "decoder", initial_state=final_encoder_state) return tf.expand_dims(decoder_outputs, axis=2)
python
def lstm_seq2seq_internal(inputs, targets, hparams, train): """The basic LSTM seq2seq model, main step used for training.""" with tf.variable_scope("lstm_seq2seq"): if inputs is not None: inputs_length = common_layers.length_from_embedding(inputs) # Flatten inputs. inputs = common_layers.flatten4d3d(inputs) # LSTM encoder. inputs = tf.reverse_sequence(inputs, inputs_length, seq_axis=1) _, final_encoder_state = lstm(inputs, inputs_length, hparams, train, "encoder") else: final_encoder_state = None # LSTM decoder. shifted_targets = common_layers.shift_right(targets) # Add 1 to account for the padding added to the left from shift_right targets_length = common_layers.length_from_embedding(shifted_targets) + 1 decoder_outputs, _ = lstm( common_layers.flatten4d3d(shifted_targets), targets_length, hparams, train, "decoder", initial_state=final_encoder_state) return tf.expand_dims(decoder_outputs, axis=2)
[ "def", "lstm_seq2seq_internal", "(", "inputs", ",", "targets", ",", "hparams", ",", "train", ")", ":", "with", "tf", ".", "variable_scope", "(", "\"lstm_seq2seq\"", ")", ":", "if", "inputs", "is", "not", "None", ":", "inputs_length", "=", "common_layers", ".", "length_from_embedding", "(", "inputs", ")", "# Flatten inputs.", "inputs", "=", "common_layers", ".", "flatten4d3d", "(", "inputs", ")", "# LSTM encoder.", "inputs", "=", "tf", ".", "reverse_sequence", "(", "inputs", ",", "inputs_length", ",", "seq_axis", "=", "1", ")", "_", ",", "final_encoder_state", "=", "lstm", "(", "inputs", ",", "inputs_length", ",", "hparams", ",", "train", ",", "\"encoder\"", ")", "else", ":", "final_encoder_state", "=", "None", "# LSTM decoder.", "shifted_targets", "=", "common_layers", ".", "shift_right", "(", "targets", ")", "# Add 1 to account for the padding added to the left from shift_right", "targets_length", "=", "common_layers", ".", "length_from_embedding", "(", "shifted_targets", ")", "+", "1", "decoder_outputs", ",", "_", "=", "lstm", "(", "common_layers", ".", "flatten4d3d", "(", "shifted_targets", ")", ",", "targets_length", ",", "hparams", ",", "train", ",", "\"decoder\"", ",", "initial_state", "=", "final_encoder_state", ")", "return", "tf", ".", "expand_dims", "(", "decoder_outputs", ",", "axis", "=", "2", ")" ]
The basic LSTM seq2seq model, main step used for training.
[ "The", "basic", "LSTM", "seq2seq", "model", "main", "step", "used", "for", "training", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/lstm.py#L177-L203
22,109
tensorflow/tensor2tensor
tensor2tensor/models/lstm.py
lstm_seq2seq_internal_bid_encoder
def lstm_seq2seq_internal_bid_encoder(inputs, targets, hparams, train): """The basic LSTM seq2seq model with bidirectional encoder.""" with tf.variable_scope("lstm_seq2seq_bid_encoder"): if inputs is not None: inputs_length = common_layers.length_from_embedding(inputs) # Flatten inputs. inputs = common_layers.flatten4d3d(inputs) # LSTM encoder. _, final_encoder_state = lstm_bid_encoder( inputs, inputs_length, hparams, train, "encoder") else: inputs_length = None final_encoder_state = None # LSTM decoder. shifted_targets = common_layers.shift_right(targets) # Add 1 to account for the padding added to the left from shift_right targets_length = common_layers.length_from_embedding(shifted_targets) + 1 hparams_decoder = copy.copy(hparams) hparams_decoder.hidden_size = 2 * hparams.hidden_size decoder_outputs, _ = lstm( common_layers.flatten4d3d(shifted_targets), targets_length, hparams_decoder, train, "decoder", initial_state=final_encoder_state) return tf.expand_dims(decoder_outputs, axis=2)
python
def lstm_seq2seq_internal_bid_encoder(inputs, targets, hparams, train): """The basic LSTM seq2seq model with bidirectional encoder.""" with tf.variable_scope("lstm_seq2seq_bid_encoder"): if inputs is not None: inputs_length = common_layers.length_from_embedding(inputs) # Flatten inputs. inputs = common_layers.flatten4d3d(inputs) # LSTM encoder. _, final_encoder_state = lstm_bid_encoder( inputs, inputs_length, hparams, train, "encoder") else: inputs_length = None final_encoder_state = None # LSTM decoder. shifted_targets = common_layers.shift_right(targets) # Add 1 to account for the padding added to the left from shift_right targets_length = common_layers.length_from_embedding(shifted_targets) + 1 hparams_decoder = copy.copy(hparams) hparams_decoder.hidden_size = 2 * hparams.hidden_size decoder_outputs, _ = lstm( common_layers.flatten4d3d(shifted_targets), targets_length, hparams_decoder, train, "decoder", initial_state=final_encoder_state) return tf.expand_dims(decoder_outputs, axis=2)
[ "def", "lstm_seq2seq_internal_bid_encoder", "(", "inputs", ",", "targets", ",", "hparams", ",", "train", ")", ":", "with", "tf", ".", "variable_scope", "(", "\"lstm_seq2seq_bid_encoder\"", ")", ":", "if", "inputs", "is", "not", "None", ":", "inputs_length", "=", "common_layers", ".", "length_from_embedding", "(", "inputs", ")", "# Flatten inputs.", "inputs", "=", "common_layers", ".", "flatten4d3d", "(", "inputs", ")", "# LSTM encoder.", "_", ",", "final_encoder_state", "=", "lstm_bid_encoder", "(", "inputs", ",", "inputs_length", ",", "hparams", ",", "train", ",", "\"encoder\"", ")", "else", ":", "inputs_length", "=", "None", "final_encoder_state", "=", "None", "# LSTM decoder.", "shifted_targets", "=", "common_layers", ".", "shift_right", "(", "targets", ")", "# Add 1 to account for the padding added to the left from shift_right", "targets_length", "=", "common_layers", ".", "length_from_embedding", "(", "shifted_targets", ")", "+", "1", "hparams_decoder", "=", "copy", ".", "copy", "(", "hparams", ")", "hparams_decoder", ".", "hidden_size", "=", "2", "*", "hparams", ".", "hidden_size", "decoder_outputs", ",", "_", "=", "lstm", "(", "common_layers", ".", "flatten4d3d", "(", "shifted_targets", ")", ",", "targets_length", ",", "hparams_decoder", ",", "train", ",", "\"decoder\"", ",", "initial_state", "=", "final_encoder_state", ")", "return", "tf", ".", "expand_dims", "(", "decoder_outputs", ",", "axis", "=", "2", ")" ]
The basic LSTM seq2seq model with bidirectional encoder.
[ "The", "basic", "LSTM", "seq2seq", "model", "with", "bidirectional", "encoder", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/lstm.py#L276-L302
22,110
tensorflow/tensor2tensor
tensor2tensor/models/lstm.py
lstm_seq2seq
def lstm_seq2seq(): """hparams for LSTM.""" hparams = common_hparams.basic_params1() hparams.daisy_chain_variables = False hparams.batch_size = 1024 hparams.hidden_size = 128 hparams.num_hidden_layers = 2 hparams.initializer = "uniform_unit_scaling" hparams.initializer_gain = 1.0 hparams.weight_decay = 0.0 return hparams
python
def lstm_seq2seq(): """hparams for LSTM.""" hparams = common_hparams.basic_params1() hparams.daisy_chain_variables = False hparams.batch_size = 1024 hparams.hidden_size = 128 hparams.num_hidden_layers = 2 hparams.initializer = "uniform_unit_scaling" hparams.initializer_gain = 1.0 hparams.weight_decay = 0.0 return hparams
[ "def", "lstm_seq2seq", "(", ")", ":", "hparams", "=", "common_hparams", ".", "basic_params1", "(", ")", "hparams", ".", "daisy_chain_variables", "=", "False", "hparams", ".", "batch_size", "=", "1024", "hparams", ".", "hidden_size", "=", "128", "hparams", ".", "num_hidden_layers", "=", "2", "hparams", ".", "initializer", "=", "\"uniform_unit_scaling\"", "hparams", ".", "initializer_gain", "=", "1.0", "hparams", ".", "weight_decay", "=", "0.0", "return", "hparams" ]
hparams for LSTM.
[ "hparams", "for", "LSTM", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/lstm.py#L410-L420
22,111
tensorflow/tensor2tensor
tensor2tensor/models/lstm.py
lstm_attention_base
def lstm_attention_base(): """Base attention params.""" hparams = lstm_seq2seq() hparams.add_hparam("attention_layer_size", hparams.hidden_size) hparams.add_hparam("output_attention", True) hparams.add_hparam("num_heads", 1) return hparams
python
def lstm_attention_base(): """Base attention params.""" hparams = lstm_seq2seq() hparams.add_hparam("attention_layer_size", hparams.hidden_size) hparams.add_hparam("output_attention", True) hparams.add_hparam("num_heads", 1) return hparams
[ "def", "lstm_attention_base", "(", ")", ":", "hparams", "=", "lstm_seq2seq", "(", ")", "hparams", ".", "add_hparam", "(", "\"attention_layer_size\"", ",", "hparams", ".", "hidden_size", ")", "hparams", ".", "add_hparam", "(", "\"output_attention\"", ",", "True", ")", "hparams", ".", "add_hparam", "(", "\"num_heads\"", ",", "1", ")", "return", "hparams" ]
Base attention params.
[ "Base", "attention", "params", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/lstm.py#L423-L429
22,112
tensorflow/tensor2tensor
tensor2tensor/models/lstm.py
lstm_asr_v1
def lstm_asr_v1(): """Basic LSTM Params.""" hparams = lstm_bahdanau_attention() hparams.num_hidden_layers = 2 hparams.hidden_size = 256 hparams.batch_size = 36 hparams.max_input_seq_length = 600000 hparams.max_target_seq_length = 350 hparams.max_length = hparams.max_input_seq_length hparams.min_length_bucket = hparams.max_input_seq_length // 2 hparams.learning_rate = 0.05 return hparams
python
def lstm_asr_v1(): """Basic LSTM Params.""" hparams = lstm_bahdanau_attention() hparams.num_hidden_layers = 2 hparams.hidden_size = 256 hparams.batch_size = 36 hparams.max_input_seq_length = 600000 hparams.max_target_seq_length = 350 hparams.max_length = hparams.max_input_seq_length hparams.min_length_bucket = hparams.max_input_seq_length // 2 hparams.learning_rate = 0.05 return hparams
[ "def", "lstm_asr_v1", "(", ")", ":", "hparams", "=", "lstm_bahdanau_attention", "(", ")", "hparams", ".", "num_hidden_layers", "=", "2", "hparams", ".", "hidden_size", "=", "256", "hparams", ".", "batch_size", "=", "36", "hparams", ".", "max_input_seq_length", "=", "600000", "hparams", ".", "max_target_seq_length", "=", "350", "hparams", ".", "max_length", "=", "hparams", ".", "max_input_seq_length", "hparams", ".", "min_length_bucket", "=", "hparams", ".", "max_input_seq_length", "//", "2", "hparams", ".", "learning_rate", "=", "0.05", "return", "hparams" ]
Basic LSTM Params.
[ "Basic", "LSTM", "Params", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/lstm.py#L471-L482
22,113
tensorflow/tensor2tensor
tensor2tensor/models/lstm.py
lstm_area_attention_base
def lstm_area_attention_base(): """Hparams for LSTM with area attention.""" hparams = lstm_luong_attention() hparams.batch_size = 16384 hparams.num_hidden_layers = 2 hparams.hidden_size = 1024 hparams.num_heads = 4 hparams.dropout = 0.2 hparams.learning_rate = 0.1 hparams.max_area_width = 2 hparams.area_key_mode = "mean" hparams.area_value_mode = "sum" return hparams
python
def lstm_area_attention_base(): """Hparams for LSTM with area attention.""" hparams = lstm_luong_attention() hparams.batch_size = 16384 hparams.num_hidden_layers = 2 hparams.hidden_size = 1024 hparams.num_heads = 4 hparams.dropout = 0.2 hparams.learning_rate = 0.1 hparams.max_area_width = 2 hparams.area_key_mode = "mean" hparams.area_value_mode = "sum" return hparams
[ "def", "lstm_area_attention_base", "(", ")", ":", "hparams", "=", "lstm_luong_attention", "(", ")", "hparams", ".", "batch_size", "=", "16384", "hparams", ".", "num_hidden_layers", "=", "2", "hparams", ".", "hidden_size", "=", "1024", "hparams", ".", "num_heads", "=", "4", "hparams", ".", "dropout", "=", "0.2", "hparams", ".", "learning_rate", "=", "0.1", "hparams", ".", "max_area_width", "=", "2", "hparams", ".", "area_key_mode", "=", "\"mean\"", "hparams", ".", "area_value_mode", "=", "\"sum\"", "return", "hparams" ]
Hparams for LSTM with area attention.
[ "Hparams", "for", "LSTM", "with", "area", "attention", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/lstm.py#L486-L498
22,114
tensorflow/tensor2tensor
tensor2tensor/bin/t2t_attack.py
prepare_data
def prepare_data(problem, hparams, params, config): """Construct input pipeline.""" input_fn = problem.make_estimator_input_fn( tf.estimator.ModeKeys.EVAL, hparams, force_repeat=True) dataset = input_fn(params, config) features, _ = dataset.make_one_shot_iterator().get_next() inputs, labels = features["targets"], features["inputs"] inputs = tf.to_float(inputs) input_shape = inputs.shape.as_list() inputs = tf.reshape(inputs, [hparams.batch_size] + input_shape[1:]) labels = tf.reshape(labels, [hparams.batch_size]) return inputs, labels, features
python
def prepare_data(problem, hparams, params, config): """Construct input pipeline.""" input_fn = problem.make_estimator_input_fn( tf.estimator.ModeKeys.EVAL, hparams, force_repeat=True) dataset = input_fn(params, config) features, _ = dataset.make_one_shot_iterator().get_next() inputs, labels = features["targets"], features["inputs"] inputs = tf.to_float(inputs) input_shape = inputs.shape.as_list() inputs = tf.reshape(inputs, [hparams.batch_size] + input_shape[1:]) labels = tf.reshape(labels, [hparams.batch_size]) return inputs, labels, features
[ "def", "prepare_data", "(", "problem", ",", "hparams", ",", "params", ",", "config", ")", ":", "input_fn", "=", "problem", ".", "make_estimator_input_fn", "(", "tf", ".", "estimator", ".", "ModeKeys", ".", "EVAL", ",", "hparams", ",", "force_repeat", "=", "True", ")", "dataset", "=", "input_fn", "(", "params", ",", "config", ")", "features", ",", "_", "=", "dataset", ".", "make_one_shot_iterator", "(", ")", ".", "get_next", "(", ")", "inputs", ",", "labels", "=", "features", "[", "\"targets\"", "]", ",", "features", "[", "\"inputs\"", "]", "inputs", "=", "tf", ".", "to_float", "(", "inputs", ")", "input_shape", "=", "inputs", ".", "shape", ".", "as_list", "(", ")", "inputs", "=", "tf", ".", "reshape", "(", "inputs", ",", "[", "hparams", ".", "batch_size", "]", "+", "input_shape", "[", "1", ":", "]", ")", "labels", "=", "tf", ".", "reshape", "(", "labels", ",", "[", "hparams", ".", "batch_size", "]", ")", "return", "inputs", ",", "labels", ",", "features" ]
Construct input pipeline.
[ "Construct", "input", "pipeline", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/bin/t2t_attack.py#L134-L145
22,115
tensorflow/tensor2tensor
tensor2tensor/data_generators/audio_encoder.py
AudioEncoder.encode
def encode(self, s): """Transform a string with a filename into a list of float32. Args: s: path to the file with a waveform. Returns: samples: list of int16s """ # Make sure that the data is a single channel, 16bit, 16kHz wave. # TODO(chorowski): the directory may not be writable, this should fallback # to a temp path, and provide instructions for installing sox. if s.endswith(".mp3"): # TODO(dliebling) On Linux, check if libsox-fmt-mp3 is installed. out_filepath = s[:-4] + ".wav" call([ "sox", "--guard", s, "-r", "16k", "-b", "16", "-c", "1", out_filepath ]) s = out_filepath elif not s.endswith(".wav"): out_filepath = s + ".wav" if not os.path.exists(out_filepath): call(["sox", "-r", "16k", "-b", "16", "-c", "1", s, out_filepath]) s = out_filepath rate, data = wavfile.read(s) assert rate == self._sample_rate assert len(data.shape) == 1 if data.dtype not in [np.float32, np.float64]: data = data.astype(np.float32) / np.iinfo(data.dtype).max return data.tolist()
python
def encode(self, s): """Transform a string with a filename into a list of float32. Args: s: path to the file with a waveform. Returns: samples: list of int16s """ # Make sure that the data is a single channel, 16bit, 16kHz wave. # TODO(chorowski): the directory may not be writable, this should fallback # to a temp path, and provide instructions for installing sox. if s.endswith(".mp3"): # TODO(dliebling) On Linux, check if libsox-fmt-mp3 is installed. out_filepath = s[:-4] + ".wav" call([ "sox", "--guard", s, "-r", "16k", "-b", "16", "-c", "1", out_filepath ]) s = out_filepath elif not s.endswith(".wav"): out_filepath = s + ".wav" if not os.path.exists(out_filepath): call(["sox", "-r", "16k", "-b", "16", "-c", "1", s, out_filepath]) s = out_filepath rate, data = wavfile.read(s) assert rate == self._sample_rate assert len(data.shape) == 1 if data.dtype not in [np.float32, np.float64]: data = data.astype(np.float32) / np.iinfo(data.dtype).max return data.tolist()
[ "def", "encode", "(", "self", ",", "s", ")", ":", "# Make sure that the data is a single channel, 16bit, 16kHz wave.", "# TODO(chorowski): the directory may not be writable, this should fallback", "# to a temp path, and provide instructions for installing sox.", "if", "s", ".", "endswith", "(", "\".mp3\"", ")", ":", "# TODO(dliebling) On Linux, check if libsox-fmt-mp3 is installed.", "out_filepath", "=", "s", "[", ":", "-", "4", "]", "+", "\".wav\"", "call", "(", "[", "\"sox\"", ",", "\"--guard\"", ",", "s", ",", "\"-r\"", ",", "\"16k\"", ",", "\"-b\"", ",", "\"16\"", ",", "\"-c\"", ",", "\"1\"", ",", "out_filepath", "]", ")", "s", "=", "out_filepath", "elif", "not", "s", ".", "endswith", "(", "\".wav\"", ")", ":", "out_filepath", "=", "s", "+", "\".wav\"", "if", "not", "os", ".", "path", ".", "exists", "(", "out_filepath", ")", ":", "call", "(", "[", "\"sox\"", ",", "\"-r\"", ",", "\"16k\"", ",", "\"-b\"", ",", "\"16\"", ",", "\"-c\"", ",", "\"1\"", ",", "s", ",", "out_filepath", "]", ")", "s", "=", "out_filepath", "rate", ",", "data", "=", "wavfile", ".", "read", "(", "s", ")", "assert", "rate", "==", "self", ".", "_sample_rate", "assert", "len", "(", "data", ".", "shape", ")", "==", "1", "if", "data", ".", "dtype", "not", "in", "[", "np", ".", "float32", ",", "np", ".", "float64", "]", ":", "data", "=", "data", ".", "astype", "(", "np", ".", "float32", ")", "/", "np", ".", "iinfo", "(", "data", ".", "dtype", ")", ".", "max", "return", "data", ".", "tolist", "(", ")" ]
Transform a string with a filename into a list of float32. Args: s: path to the file with a waveform. Returns: samples: list of int16s
[ "Transform", "a", "string", "with", "a", "filename", "into", "a", "list", "of", "float32", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/audio_encoder.py#L36-L65
22,116
tensorflow/tensor2tensor
tensor2tensor/data_generators/audio_encoder.py
AudioEncoder.decode
def decode(self, ids): """Transform a sequence of float32 into a waveform. Args: ids: list of integers to be converted. Returns: Path to the temporary file where the waveform was saved. Raises: ValueError: if the ids are not of the appropriate size. """ _, tmp_file_path = tempfile.mkstemp() wavfile.write(tmp_file_path, self._sample_rate, np.asarray(ids)) return tmp_file_path
python
def decode(self, ids): """Transform a sequence of float32 into a waveform. Args: ids: list of integers to be converted. Returns: Path to the temporary file where the waveform was saved. Raises: ValueError: if the ids are not of the appropriate size. """ _, tmp_file_path = tempfile.mkstemp() wavfile.write(tmp_file_path, self._sample_rate, np.asarray(ids)) return tmp_file_path
[ "def", "decode", "(", "self", ",", "ids", ")", ":", "_", ",", "tmp_file_path", "=", "tempfile", ".", "mkstemp", "(", ")", "wavfile", ".", "write", "(", "tmp_file_path", ",", "self", ".", "_sample_rate", ",", "np", ".", "asarray", "(", "ids", ")", ")", "return", "tmp_file_path" ]
Transform a sequence of float32 into a waveform. Args: ids: list of integers to be converted. Returns: Path to the temporary file where the waveform was saved. Raises: ValueError: if the ids are not of the appropriate size.
[ "Transform", "a", "sequence", "of", "float32", "into", "a", "waveform", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/audio_encoder.py#L67-L81
22,117
tensorflow/tensor2tensor
tensor2tensor/insights/graph.py
Graph.new_vertex
def new_vertex(self): """Creates and returns a new vertex. Returns: A new Vertex instance with a unique index. """ vertex = Vertex(len(self.vertices)) self.vertices.append(vertex) return vertex
python
def new_vertex(self): """Creates and returns a new vertex. Returns: A new Vertex instance with a unique index. """ vertex = Vertex(len(self.vertices)) self.vertices.append(vertex) return vertex
[ "def", "new_vertex", "(", "self", ")", ":", "vertex", "=", "Vertex", "(", "len", "(", "self", ".", "vertices", ")", ")", "self", ".", "vertices", ".", "append", "(", "vertex", ")", "return", "vertex" ]
Creates and returns a new vertex. Returns: A new Vertex instance with a unique index.
[ "Creates", "and", "returns", "a", "new", "vertex", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/insights/graph.py#L102-L110
22,118
tensorflow/tensor2tensor
tensor2tensor/insights/graph.py
Graph.get_vertex
def get_vertex(self, key): """Returns or Creates a Vertex mapped by key. Args: key: A string reference for a vertex. May refer to a new Vertex in which case it will be created. Returns: A the Vertex mapped to by key. """ if key in self.vertex_map: return self.vertex_map[key] vertex = self.new_vertex() self.vertex_map[key] = vertex return vertex
python
def get_vertex(self, key): """Returns or Creates a Vertex mapped by key. Args: key: A string reference for a vertex. May refer to a new Vertex in which case it will be created. Returns: A the Vertex mapped to by key. """ if key in self.vertex_map: return self.vertex_map[key] vertex = self.new_vertex() self.vertex_map[key] = vertex return vertex
[ "def", "get_vertex", "(", "self", ",", "key", ")", ":", "if", "key", "in", "self", ".", "vertex_map", ":", "return", "self", ".", "vertex_map", "[", "key", "]", "vertex", "=", "self", ".", "new_vertex", "(", ")", "self", ".", "vertex_map", "[", "key", "]", "=", "vertex", "return", "vertex" ]
Returns or Creates a Vertex mapped by key. Args: key: A string reference for a vertex. May refer to a new Vertex in which case it will be created. Returns: A the Vertex mapped to by key.
[ "Returns", "or", "Creates", "a", "Vertex", "mapped", "by", "key", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/insights/graph.py#L112-L126
22,119
tensorflow/tensor2tensor
tensor2tensor/insights/graph.py
Graph.add_edge
def add_edge(self, source, target): """Returns a new edge connecting source and target vertices. Args: source: The source Vertex. target: The target Vertex. Returns: A new Edge linking source to target. """ edge = Edge(len(self.edges)) self.edges.append(edge) source.out_edges.append(edge.idx) target.in_edges.append(edge.idx) edge.source = source.idx edge.target = target.idx return edge
python
def add_edge(self, source, target): """Returns a new edge connecting source and target vertices. Args: source: The source Vertex. target: The target Vertex. Returns: A new Edge linking source to target. """ edge = Edge(len(self.edges)) self.edges.append(edge) source.out_edges.append(edge.idx) target.in_edges.append(edge.idx) edge.source = source.idx edge.target = target.idx return edge
[ "def", "add_edge", "(", "self", ",", "source", ",", "target", ")", ":", "edge", "=", "Edge", "(", "len", "(", "self", ".", "edges", ")", ")", "self", ".", "edges", ".", "append", "(", "edge", ")", "source", ".", "out_edges", ".", "append", "(", "edge", ".", "idx", ")", "target", ".", "in_edges", ".", "append", "(", "edge", ".", "idx", ")", "edge", ".", "source", "=", "source", ".", "idx", "edge", ".", "target", "=", "target", ".", "idx", "return", "edge" ]
Returns a new edge connecting source and target vertices. Args: source: The source Vertex. target: The target Vertex. Returns: A new Edge linking source to target.
[ "Returns", "a", "new", "edge", "connecting", "source", "and", "target", "vertices", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/insights/graph.py#L128-L144
22,120
tensorflow/tensor2tensor
tensor2tensor/insights/graph.py
Graph.to_dict
def to_dict(self): """Returns a simplified dictionary representing the Graph. Returns: A dictionary that can easily be serialized to JSON. """ return { "node": [v.to_dict() for v in self.vertices], "edge": [e.to_dict() for e in self.edges] }
python
def to_dict(self): """Returns a simplified dictionary representing the Graph. Returns: A dictionary that can easily be serialized to JSON. """ return { "node": [v.to_dict() for v in self.vertices], "edge": [e.to_dict() for e in self.edges] }
[ "def", "to_dict", "(", "self", ")", ":", "return", "{", "\"node\"", ":", "[", "v", ".", "to_dict", "(", ")", "for", "v", "in", "self", ".", "vertices", "]", ",", "\"edge\"", ":", "[", "e", ".", "to_dict", "(", ")", "for", "e", "in", "self", ".", "edges", "]", "}" ]
Returns a simplified dictionary representing the Graph. Returns: A dictionary that can easily be serialized to JSON.
[ "Returns", "a", "simplified", "dictionary", "representing", "the", "Graph", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/insights/graph.py#L146-L155
22,121
tensorflow/tensor2tensor
tensor2tensor/models/research/transformer_vae.py
attend
def attend(x, source, hparams, name): """Self-attention layer with source as memory antecedent.""" with tf.variable_scope(name): x = tf.squeeze(x, axis=2) if len(source.get_shape()) > 3: source = tf.squeeze(source, axis=2) source = common_attention.add_timing_signal_1d(source) y = common_attention.multihead_attention( common_layers.layer_preprocess(x, hparams), source, None, hparams.attention_key_channels or hparams.hidden_size, hparams.attention_value_channels or hparams.hidden_size, hparams.hidden_size, hparams.num_heads, hparams.attention_dropout) res = common_layers.layer_postprocess(x, y, hparams) return tf.expand_dims(res, axis=2)
python
def attend(x, source, hparams, name): """Self-attention layer with source as memory antecedent.""" with tf.variable_scope(name): x = tf.squeeze(x, axis=2) if len(source.get_shape()) > 3: source = tf.squeeze(source, axis=2) source = common_attention.add_timing_signal_1d(source) y = common_attention.multihead_attention( common_layers.layer_preprocess(x, hparams), source, None, hparams.attention_key_channels or hparams.hidden_size, hparams.attention_value_channels or hparams.hidden_size, hparams.hidden_size, hparams.num_heads, hparams.attention_dropout) res = common_layers.layer_postprocess(x, y, hparams) return tf.expand_dims(res, axis=2)
[ "def", "attend", "(", "x", ",", "source", ",", "hparams", ",", "name", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ")", ":", "x", "=", "tf", ".", "squeeze", "(", "x", ",", "axis", "=", "2", ")", "if", "len", "(", "source", ".", "get_shape", "(", ")", ")", ">", "3", ":", "source", "=", "tf", ".", "squeeze", "(", "source", ",", "axis", "=", "2", ")", "source", "=", "common_attention", ".", "add_timing_signal_1d", "(", "source", ")", "y", "=", "common_attention", ".", "multihead_attention", "(", "common_layers", ".", "layer_preprocess", "(", "x", ",", "hparams", ")", ",", "source", ",", "None", ",", "hparams", ".", "attention_key_channels", "or", "hparams", ".", "hidden_size", ",", "hparams", ".", "attention_value_channels", "or", "hparams", ".", "hidden_size", ",", "hparams", ".", "hidden_size", ",", "hparams", ".", "num_heads", ",", "hparams", ".", "attention_dropout", ")", "res", "=", "common_layers", ".", "layer_postprocess", "(", "x", ",", "y", ",", "hparams", ")", "return", "tf", ".", "expand_dims", "(", "res", ",", "axis", "=", "2", ")" ]
Self-attention layer with source as memory antecedent.
[ "Self", "-", "attention", "layer", "with", "source", "as", "memory", "antecedent", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_vae.py#L62-L76
22,122
tensorflow/tensor2tensor
tensor2tensor/models/research/transformer_vae.py
ae_latent_sample
def ae_latent_sample(latents_dense, inputs, ed, embed, iters, hparams): """Sample from the latent space in the autoencoder.""" if hparams.num_decode_blocks < 2 and hparams.sampling_temp == 0.0: # TODO(lukaszkaiser): beam-search only works in non-blocked mode for now. tf.logging.info("Running beam-search for latents with beam size 1.") return ae_latent_sample_beam(latents_dense, inputs, ed, embed, hparams) latents_pred = decode_transformer(inputs, ed, latents_dense, hparams, "extra") latents_discrete, _ = ae_latent_softmax(latents_pred, None, hparams) def next_bit(latents_discrete, i): latents_discrete_prev = latents_discrete with tf.variable_scope(tf.get_variable_scope(), reuse=True): latents_dense = embed(latents_discrete) latents_pred = decode_transformer( inputs, ed, latents_dense, hparams, "extra") latents_discrete, _ = ae_latent_softmax(latents_pred, None, hparams) return tf.concat([latents_discrete_prev[:, :(i+1), :], latents_discrete[:, (i+1):, :]], axis=1) for i in range(iters): latents_discrete = next_bit(latents_discrete, i) return latents_discrete
python
def ae_latent_sample(latents_dense, inputs, ed, embed, iters, hparams): """Sample from the latent space in the autoencoder.""" if hparams.num_decode_blocks < 2 and hparams.sampling_temp == 0.0: # TODO(lukaszkaiser): beam-search only works in non-blocked mode for now. tf.logging.info("Running beam-search for latents with beam size 1.") return ae_latent_sample_beam(latents_dense, inputs, ed, embed, hparams) latents_pred = decode_transformer(inputs, ed, latents_dense, hparams, "extra") latents_discrete, _ = ae_latent_softmax(latents_pred, None, hparams) def next_bit(latents_discrete, i): latents_discrete_prev = latents_discrete with tf.variable_scope(tf.get_variable_scope(), reuse=True): latents_dense = embed(latents_discrete) latents_pred = decode_transformer( inputs, ed, latents_dense, hparams, "extra") latents_discrete, _ = ae_latent_softmax(latents_pred, None, hparams) return tf.concat([latents_discrete_prev[:, :(i+1), :], latents_discrete[:, (i+1):, :]], axis=1) for i in range(iters): latents_discrete = next_bit(latents_discrete, i) return latents_discrete
[ "def", "ae_latent_sample", "(", "latents_dense", ",", "inputs", ",", "ed", ",", "embed", ",", "iters", ",", "hparams", ")", ":", "if", "hparams", ".", "num_decode_blocks", "<", "2", "and", "hparams", ".", "sampling_temp", "==", "0.0", ":", "# TODO(lukaszkaiser): beam-search only works in non-blocked mode for now.", "tf", ".", "logging", ".", "info", "(", "\"Running beam-search for latents with beam size 1.\"", ")", "return", "ae_latent_sample_beam", "(", "latents_dense", ",", "inputs", ",", "ed", ",", "embed", ",", "hparams", ")", "latents_pred", "=", "decode_transformer", "(", "inputs", ",", "ed", ",", "latents_dense", ",", "hparams", ",", "\"extra\"", ")", "latents_discrete", ",", "_", "=", "ae_latent_softmax", "(", "latents_pred", ",", "None", ",", "hparams", ")", "def", "next_bit", "(", "latents_discrete", ",", "i", ")", ":", "latents_discrete_prev", "=", "latents_discrete", "with", "tf", ".", "variable_scope", "(", "tf", ".", "get_variable_scope", "(", ")", ",", "reuse", "=", "True", ")", ":", "latents_dense", "=", "embed", "(", "latents_discrete", ")", "latents_pred", "=", "decode_transformer", "(", "inputs", ",", "ed", ",", "latents_dense", ",", "hparams", ",", "\"extra\"", ")", "latents_discrete", ",", "_", "=", "ae_latent_softmax", "(", "latents_pred", ",", "None", ",", "hparams", ")", "return", "tf", ".", "concat", "(", "[", "latents_discrete_prev", "[", ":", ",", ":", "(", "i", "+", "1", ")", ",", ":", "]", ",", "latents_discrete", "[", ":", ",", "(", "i", "+", "1", ")", ":", ",", ":", "]", "]", ",", "axis", "=", "1", ")", "for", "i", "in", "range", "(", "iters", ")", ":", "latents_discrete", "=", "next_bit", "(", "latents_discrete", ",", "i", ")", "return", "latents_discrete" ]
Sample from the latent space in the autoencoder.
[ "Sample", "from", "the", "latent", "space", "in", "the", "autoencoder", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_vae.py#L301-L322
22,123
tensorflow/tensor2tensor
tensor2tensor/models/research/transformer_vae.py
imagetransformer_ae_cifar
def imagetransformer_ae_cifar(): """Hyperparameters for CIFAR-10 experiments.""" hparams = transformer_ae_small() hparams.filter_size = 512 hparams.num_compress_steps = 3 hparams.startup_steps = 10000 hparams.is_2d = 0 hparams.learning_rate_warmup_steps = 8000 hparams.learning_rate = 0.2 hparams.hidden_size = 512 hparams.batch_size = 1 hparams.max_length = 256 hparams.dropout = 0.0 hparams.clip_grad_norm = 0. # i.e. no gradient clipping hparams.optimizer_adam_epsilon = 1e-9 hparams.learning_rate_decay_scheme = "noam" hparams.learning_rate = 0.1 hparams.initializer_gain = 0.2 hparams.num_hidden_layers = 6 hparams.initializer = "uniform_unit_scaling" hparams.weight_decay = 0.0 hparams.optimizer_adam_beta1 = 0.9 hparams.optimizer_adam_beta2 = 0.98 hparams.label_smoothing = 0.0 hparams.norm_type = "layer" hparams.layer_prepostprocess_dropout = 0.0 hparams.num_heads = 8 hparams.task = "image" hparams.ffn_layer = "conv_hidden_relu" # All hyperparameters ending in "dropout" are automatically set to 0.0 # when not in training mode. hparams.attention_dropout = 0.0 hparams.relu_dropout = 0. hparams.pos = "timing" # timing, none hparams.nbr_decoder_problems = 1 hparams.num_output_layers = 3 # TODO(trandustin): semhash doesn't work if filter_size != hidden_size. For # now, set default to dvq. hparams.bottleneck_kind = "dvq" hparams.add_hparam("block_size", 1) # dilated attention based flags hparams.add_hparam("gap_sizes", [2, 4, 8, 16, 32, 64, 2, 4, 8, 16, 32, 64]) hparams.add_hparam("dilated_attention", False) # image size related flags # assuming that the image has same height and width hparams.add_hparam("img_len", 32) hparams.add_hparam("num_channels", 3) # Local attention params hparams.add_hparam("local_and_global_att", False) hparams.add_hparam("block_length", 256) hparams.add_hparam("block_width", 128) hparams.num_encoder_layers = 4 hparams.num_decoder_layers = 12 hparams.add_hparam("dec_attention_type", cia.AttentionType.LOCAL_1D) hparams.add_hparam("block_raster_scan", False) hparams.add_hparam("shared_rel", False) # multipos attention params hparams.add_hparam("q_filter_width", 1) hparams.add_hparam("kv_filter_width", 1) hparams.add_hparam("unconditional", False) # unconditional generation hparams.bottom["targets"] = modalities.image_channel_embeddings_bottom hparams.top["targets"] = modalities.image_channel_embeddings_top hparams.drop_inputs = True hparams.do_attend_compress = False hparams.do_attend_decompress = False return hparams
python
def imagetransformer_ae_cifar(): """Hyperparameters for CIFAR-10 experiments.""" hparams = transformer_ae_small() hparams.filter_size = 512 hparams.num_compress_steps = 3 hparams.startup_steps = 10000 hparams.is_2d = 0 hparams.learning_rate_warmup_steps = 8000 hparams.learning_rate = 0.2 hparams.hidden_size = 512 hparams.batch_size = 1 hparams.max_length = 256 hparams.dropout = 0.0 hparams.clip_grad_norm = 0. # i.e. no gradient clipping hparams.optimizer_adam_epsilon = 1e-9 hparams.learning_rate_decay_scheme = "noam" hparams.learning_rate = 0.1 hparams.initializer_gain = 0.2 hparams.num_hidden_layers = 6 hparams.initializer = "uniform_unit_scaling" hparams.weight_decay = 0.0 hparams.optimizer_adam_beta1 = 0.9 hparams.optimizer_adam_beta2 = 0.98 hparams.label_smoothing = 0.0 hparams.norm_type = "layer" hparams.layer_prepostprocess_dropout = 0.0 hparams.num_heads = 8 hparams.task = "image" hparams.ffn_layer = "conv_hidden_relu" # All hyperparameters ending in "dropout" are automatically set to 0.0 # when not in training mode. hparams.attention_dropout = 0.0 hparams.relu_dropout = 0. hparams.pos = "timing" # timing, none hparams.nbr_decoder_problems = 1 hparams.num_output_layers = 3 # TODO(trandustin): semhash doesn't work if filter_size != hidden_size. For # now, set default to dvq. hparams.bottleneck_kind = "dvq" hparams.add_hparam("block_size", 1) # dilated attention based flags hparams.add_hparam("gap_sizes", [2, 4, 8, 16, 32, 64, 2, 4, 8, 16, 32, 64]) hparams.add_hparam("dilated_attention", False) # image size related flags # assuming that the image has same height and width hparams.add_hparam("img_len", 32) hparams.add_hparam("num_channels", 3) # Local attention params hparams.add_hparam("local_and_global_att", False) hparams.add_hparam("block_length", 256) hparams.add_hparam("block_width", 128) hparams.num_encoder_layers = 4 hparams.num_decoder_layers = 12 hparams.add_hparam("dec_attention_type", cia.AttentionType.LOCAL_1D) hparams.add_hparam("block_raster_scan", False) hparams.add_hparam("shared_rel", False) # multipos attention params hparams.add_hparam("q_filter_width", 1) hparams.add_hparam("kv_filter_width", 1) hparams.add_hparam("unconditional", False) # unconditional generation hparams.bottom["targets"] = modalities.image_channel_embeddings_bottom hparams.top["targets"] = modalities.image_channel_embeddings_top hparams.drop_inputs = True hparams.do_attend_compress = False hparams.do_attend_decompress = False return hparams
[ "def", "imagetransformer_ae_cifar", "(", ")", ":", "hparams", "=", "transformer_ae_small", "(", ")", "hparams", ".", "filter_size", "=", "512", "hparams", ".", "num_compress_steps", "=", "3", "hparams", ".", "startup_steps", "=", "10000", "hparams", ".", "is_2d", "=", "0", "hparams", ".", "learning_rate_warmup_steps", "=", "8000", "hparams", ".", "learning_rate", "=", "0.2", "hparams", ".", "hidden_size", "=", "512", "hparams", ".", "batch_size", "=", "1", "hparams", ".", "max_length", "=", "256", "hparams", ".", "dropout", "=", "0.0", "hparams", ".", "clip_grad_norm", "=", "0.", "# i.e. no gradient clipping", "hparams", ".", "optimizer_adam_epsilon", "=", "1e-9", "hparams", ".", "learning_rate_decay_scheme", "=", "\"noam\"", "hparams", ".", "learning_rate", "=", "0.1", "hparams", ".", "initializer_gain", "=", "0.2", "hparams", ".", "num_hidden_layers", "=", "6", "hparams", ".", "initializer", "=", "\"uniform_unit_scaling\"", "hparams", ".", "weight_decay", "=", "0.0", "hparams", ".", "optimizer_adam_beta1", "=", "0.9", "hparams", ".", "optimizer_adam_beta2", "=", "0.98", "hparams", ".", "label_smoothing", "=", "0.0", "hparams", ".", "norm_type", "=", "\"layer\"", "hparams", ".", "layer_prepostprocess_dropout", "=", "0.0", "hparams", ".", "num_heads", "=", "8", "hparams", ".", "task", "=", "\"image\"", "hparams", ".", "ffn_layer", "=", "\"conv_hidden_relu\"", "# All hyperparameters ending in \"dropout\" are automatically set to 0.0", "# when not in training mode.", "hparams", ".", "attention_dropout", "=", "0.0", "hparams", ".", "relu_dropout", "=", "0.", "hparams", ".", "pos", "=", "\"timing\"", "# timing, none", "hparams", ".", "nbr_decoder_problems", "=", "1", "hparams", ".", "num_output_layers", "=", "3", "# TODO(trandustin): semhash doesn't work if filter_size != hidden_size. For", "# now, set default to dvq.", "hparams", ".", "bottleneck_kind", "=", "\"dvq\"", "hparams", ".", "add_hparam", "(", "\"block_size\"", ",", "1", ")", "# dilated attention based flags", "hparams", ".", "add_hparam", "(", "\"gap_sizes\"", ",", "[", "2", ",", "4", ",", "8", ",", "16", ",", "32", ",", "64", ",", "2", ",", "4", ",", "8", ",", "16", ",", "32", ",", "64", "]", ")", "hparams", ".", "add_hparam", "(", "\"dilated_attention\"", ",", "False", ")", "# image size related flags", "# assuming that the image has same height and width", "hparams", ".", "add_hparam", "(", "\"img_len\"", ",", "32", ")", "hparams", ".", "add_hparam", "(", "\"num_channels\"", ",", "3", ")", "# Local attention params", "hparams", ".", "add_hparam", "(", "\"local_and_global_att\"", ",", "False", ")", "hparams", ".", "add_hparam", "(", "\"block_length\"", ",", "256", ")", "hparams", ".", "add_hparam", "(", "\"block_width\"", ",", "128", ")", "hparams", ".", "num_encoder_layers", "=", "4", "hparams", ".", "num_decoder_layers", "=", "12", "hparams", ".", "add_hparam", "(", "\"dec_attention_type\"", ",", "cia", ".", "AttentionType", ".", "LOCAL_1D", ")", "hparams", ".", "add_hparam", "(", "\"block_raster_scan\"", ",", "False", ")", "hparams", ".", "add_hparam", "(", "\"shared_rel\"", ",", "False", ")", "# multipos attention params", "hparams", ".", "add_hparam", "(", "\"q_filter_width\"", ",", "1", ")", "hparams", ".", "add_hparam", "(", "\"kv_filter_width\"", ",", "1", ")", "hparams", ".", "add_hparam", "(", "\"unconditional\"", ",", "False", ")", "# unconditional generation", "hparams", ".", "bottom", "[", "\"targets\"", "]", "=", "modalities", ".", "image_channel_embeddings_bottom", "hparams", ".", "top", "[", "\"targets\"", "]", "=", "modalities", ".", "image_channel_embeddings_top", "hparams", ".", "drop_inputs", "=", "True", "hparams", ".", "do_attend_compress", "=", "False", "hparams", ".", "do_attend_decompress", "=", "False", "return", "hparams" ]
Hyperparameters for CIFAR-10 experiments.
[ "Hyperparameters", "for", "CIFAR", "-", "10", "experiments", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_vae.py#L834-L904
22,124
tensorflow/tensor2tensor
tensor2tensor/models/research/transformer_vae.py
imagetransformer_ae_imagenet
def imagetransformer_ae_imagenet(): """For 64x64 ImageNet. ~56M trainable variables.""" hparams = imagetransformer_ae_cifar() hparams.max_length = int(64 * 64 * 3) hparams.img_len = 64 hparams.num_heads = 4 # Heads are expensive on TPUs. # Reduce architecture from 32x32 CIFAR-10 in order to fit in memory. hparams.num_decoder_layers = 8 hparams.num_compress_steps = 2 return hparams
python
def imagetransformer_ae_imagenet(): """For 64x64 ImageNet. ~56M trainable variables.""" hparams = imagetransformer_ae_cifar() hparams.max_length = int(64 * 64 * 3) hparams.img_len = 64 hparams.num_heads = 4 # Heads are expensive on TPUs. # Reduce architecture from 32x32 CIFAR-10 in order to fit in memory. hparams.num_decoder_layers = 8 hparams.num_compress_steps = 2 return hparams
[ "def", "imagetransformer_ae_imagenet", "(", ")", ":", "hparams", "=", "imagetransformer_ae_cifar", "(", ")", "hparams", ".", "max_length", "=", "int", "(", "64", "*", "64", "*", "3", ")", "hparams", ".", "img_len", "=", "64", "hparams", ".", "num_heads", "=", "4", "# Heads are expensive on TPUs.", "# Reduce architecture from 32x32 CIFAR-10 in order to fit in memory.", "hparams", ".", "num_decoder_layers", "=", "8", "hparams", ".", "num_compress_steps", "=", "2", "return", "hparams" ]
For 64x64 ImageNet. ~56M trainable variables.
[ "For", "64x64", "ImageNet", ".", "~56M", "trainable", "variables", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_vae.py#L907-L916
22,125
tensorflow/tensor2tensor
tensor2tensor/models/research/transformer_sketch.py
transformer_sketch
def transformer_sketch(): """Basic transformer_sketch hparams.""" hparams = transformer.transformer_small() hparams.num_compress_steps = 4 hparams.batch_size = 32 hparams.clip_grad_norm = 2. hparams.sampling_method = "random" return hparams
python
def transformer_sketch(): """Basic transformer_sketch hparams.""" hparams = transformer.transformer_small() hparams.num_compress_steps = 4 hparams.batch_size = 32 hparams.clip_grad_norm = 2. hparams.sampling_method = "random" return hparams
[ "def", "transformer_sketch", "(", ")", ":", "hparams", "=", "transformer", ".", "transformer_small", "(", ")", "hparams", ".", "num_compress_steps", "=", "4", "hparams", ".", "batch_size", "=", "32", "hparams", ".", "clip_grad_norm", "=", "2.", "hparams", ".", "sampling_method", "=", "\"random\"", "return", "hparams" ]
Basic transformer_sketch hparams.
[ "Basic", "transformer_sketch", "hparams", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_sketch.py#L55-L62
22,126
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
layers
def layers(): """Get the layers module good for TF 1 and TF 2 work for now.""" global _cached_layers if _cached_layers is not None: return _cached_layers layers_module = tf.layers try: from tensorflow.python import tf2 # pylint: disable=g-direct-tensorflow-import,g-import-not-at-top if tf2.enabled(): tf.logging.info("Running in V2 mode, using Keras layers.") layers_module = tf.keras.layers except ImportError: pass _cached_layers = layers_module return layers_module
python
def layers(): """Get the layers module good for TF 1 and TF 2 work for now.""" global _cached_layers if _cached_layers is not None: return _cached_layers layers_module = tf.layers try: from tensorflow.python import tf2 # pylint: disable=g-direct-tensorflow-import,g-import-not-at-top if tf2.enabled(): tf.logging.info("Running in V2 mode, using Keras layers.") layers_module = tf.keras.layers except ImportError: pass _cached_layers = layers_module return layers_module
[ "def", "layers", "(", ")", ":", "global", "_cached_layers", "if", "_cached_layers", "is", "not", "None", ":", "return", "_cached_layers", "layers_module", "=", "tf", ".", "layers", "try", ":", "from", "tensorflow", ".", "python", "import", "tf2", "# pylint: disable=g-direct-tensorflow-import,g-import-not-at-top", "if", "tf2", ".", "enabled", "(", ")", ":", "tf", ".", "logging", ".", "info", "(", "\"Running in V2 mode, using Keras layers.\"", ")", "layers_module", "=", "tf", ".", "keras", ".", "layers", "except", "ImportError", ":", "pass", "_cached_layers", "=", "layers_module", "return", "layers_module" ]
Get the layers module good for TF 1 and TF 2 work for now.
[ "Get", "the", "layers", "module", "good", "for", "TF", "1", "and", "TF", "2", "work", "for", "now", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L42-L56
22,127
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
dropout_with_broadcast_dims
def dropout_with_broadcast_dims(x, keep_prob, broadcast_dims=None, **kwargs): """Like tf.nn.dropout but takes broadcast_dims instead of noise_shape. Instead of specifying noise_shape, this function takes broadcast_dims - a list of dimension numbers in which noise_shape should be 1. The random keep/drop tensor has dimensionality 1 along these dimensions. Args: x: a floating point tensor. keep_prob: A scalar Tensor with the same type as x. The probability that each element is kept. broadcast_dims: an optional list of integers the dimensions along which to broadcast the keep/drop flags. **kwargs: keyword arguments to tf.nn.dropout other than "noise_shape". Returns: Tensor of the same shape as x. """ assert "noise_shape" not in kwargs if broadcast_dims: shape = tf.shape(x) ndims = len(x.get_shape()) # Allow dimensions like "-1" as well. broadcast_dims = [dim + ndims if dim < 0 else dim for dim in broadcast_dims] kwargs["noise_shape"] = [ 1 if i in broadcast_dims else shape[i] for i in range(ndims) ] return tf.nn.dropout(x, keep_prob, **kwargs)
python
def dropout_with_broadcast_dims(x, keep_prob, broadcast_dims=None, **kwargs): """Like tf.nn.dropout but takes broadcast_dims instead of noise_shape. Instead of specifying noise_shape, this function takes broadcast_dims - a list of dimension numbers in which noise_shape should be 1. The random keep/drop tensor has dimensionality 1 along these dimensions. Args: x: a floating point tensor. keep_prob: A scalar Tensor with the same type as x. The probability that each element is kept. broadcast_dims: an optional list of integers the dimensions along which to broadcast the keep/drop flags. **kwargs: keyword arguments to tf.nn.dropout other than "noise_shape". Returns: Tensor of the same shape as x. """ assert "noise_shape" not in kwargs if broadcast_dims: shape = tf.shape(x) ndims = len(x.get_shape()) # Allow dimensions like "-1" as well. broadcast_dims = [dim + ndims if dim < 0 else dim for dim in broadcast_dims] kwargs["noise_shape"] = [ 1 if i in broadcast_dims else shape[i] for i in range(ndims) ] return tf.nn.dropout(x, keep_prob, **kwargs)
[ "def", "dropout_with_broadcast_dims", "(", "x", ",", "keep_prob", ",", "broadcast_dims", "=", "None", ",", "*", "*", "kwargs", ")", ":", "assert", "\"noise_shape\"", "not", "in", "kwargs", "if", "broadcast_dims", ":", "shape", "=", "tf", ".", "shape", "(", "x", ")", "ndims", "=", "len", "(", "x", ".", "get_shape", "(", ")", ")", "# Allow dimensions like \"-1\" as well.", "broadcast_dims", "=", "[", "dim", "+", "ndims", "if", "dim", "<", "0", "else", "dim", "for", "dim", "in", "broadcast_dims", "]", "kwargs", "[", "\"noise_shape\"", "]", "=", "[", "1", "if", "i", "in", "broadcast_dims", "else", "shape", "[", "i", "]", "for", "i", "in", "range", "(", "ndims", ")", "]", "return", "tf", ".", "nn", ".", "dropout", "(", "x", ",", "keep_prob", ",", "*", "*", "kwargs", ")" ]
Like tf.nn.dropout but takes broadcast_dims instead of noise_shape. Instead of specifying noise_shape, this function takes broadcast_dims - a list of dimension numbers in which noise_shape should be 1. The random keep/drop tensor has dimensionality 1 along these dimensions. Args: x: a floating point tensor. keep_prob: A scalar Tensor with the same type as x. The probability that each element is kept. broadcast_dims: an optional list of integers the dimensions along which to broadcast the keep/drop flags. **kwargs: keyword arguments to tf.nn.dropout other than "noise_shape". Returns: Tensor of the same shape as x.
[ "Like", "tf", ".", "nn", ".", "dropout", "but", "takes", "broadcast_dims", "instead", "of", "noise_shape", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L103-L130
22,128
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
inverse_exp_decay
def inverse_exp_decay(max_step, min_value=0.01, step=None): """Inverse-decay exponentially from 0.01 to 1.0 reached at max_step.""" inv_base = tf.exp(tf.log(min_value) / float(max_step)) if step is None: step = tf.train.get_global_step() if step is None: return 1.0 step = to_float(step) return inv_base**tf.maximum(float(max_step) - step, 0.0)
python
def inverse_exp_decay(max_step, min_value=0.01, step=None): """Inverse-decay exponentially from 0.01 to 1.0 reached at max_step.""" inv_base = tf.exp(tf.log(min_value) / float(max_step)) if step is None: step = tf.train.get_global_step() if step is None: return 1.0 step = to_float(step) return inv_base**tf.maximum(float(max_step) - step, 0.0)
[ "def", "inverse_exp_decay", "(", "max_step", ",", "min_value", "=", "0.01", ",", "step", "=", "None", ")", ":", "inv_base", "=", "tf", ".", "exp", "(", "tf", ".", "log", "(", "min_value", ")", "/", "float", "(", "max_step", ")", ")", "if", "step", "is", "None", ":", "step", "=", "tf", ".", "train", ".", "get_global_step", "(", ")", "if", "step", "is", "None", ":", "return", "1.0", "step", "=", "to_float", "(", "step", ")", "return", "inv_base", "**", "tf", ".", "maximum", "(", "float", "(", "max_step", ")", "-", "step", ",", "0.0", ")" ]
Inverse-decay exponentially from 0.01 to 1.0 reached at max_step.
[ "Inverse", "-", "decay", "exponentially", "from", "0", ".", "01", "to", "1", ".", "0", "reached", "at", "max_step", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L155-L163
22,129
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
inverse_lin_decay
def inverse_lin_decay(max_step, min_value=0.01, step=None): """Inverse-decay linearly from 0.01 to 1.0 reached at max_step.""" if step is None: step = tf.train.get_global_step() if step is None: return 1.0 step = to_float(step) progress = tf.minimum(step / float(max_step), 1.0) return progress * (1.0 - min_value) + min_value
python
def inverse_lin_decay(max_step, min_value=0.01, step=None): """Inverse-decay linearly from 0.01 to 1.0 reached at max_step.""" if step is None: step = tf.train.get_global_step() if step is None: return 1.0 step = to_float(step) progress = tf.minimum(step / float(max_step), 1.0) return progress * (1.0 - min_value) + min_value
[ "def", "inverse_lin_decay", "(", "max_step", ",", "min_value", "=", "0.01", ",", "step", "=", "None", ")", ":", "if", "step", "is", "None", ":", "step", "=", "tf", ".", "train", ".", "get_global_step", "(", ")", "if", "step", "is", "None", ":", "return", "1.0", "step", "=", "to_float", "(", "step", ")", "progress", "=", "tf", ".", "minimum", "(", "step", "/", "float", "(", "max_step", ")", ",", "1.0", ")", "return", "progress", "*", "(", "1.0", "-", "min_value", ")", "+", "min_value" ]
Inverse-decay linearly from 0.01 to 1.0 reached at max_step.
[ "Inverse", "-", "decay", "linearly", "from", "0", ".", "01", "to", "1", ".", "0", "reached", "at", "max_step", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L166-L174
22,130
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
shakeshake2_py
def shakeshake2_py(x, y, equal=False, individual=False): """The shake-shake sum of 2 tensors, python version.""" if equal: alpha = 0.5 elif individual: alpha = tf.random_uniform(tf.get_shape(x)[:1]) else: alpha = tf.random_uniform([]) return alpha * x + (1.0 - alpha) * y
python
def shakeshake2_py(x, y, equal=False, individual=False): """The shake-shake sum of 2 tensors, python version.""" if equal: alpha = 0.5 elif individual: alpha = tf.random_uniform(tf.get_shape(x)[:1]) else: alpha = tf.random_uniform([]) return alpha * x + (1.0 - alpha) * y
[ "def", "shakeshake2_py", "(", "x", ",", "y", ",", "equal", "=", "False", ",", "individual", "=", "False", ")", ":", "if", "equal", ":", "alpha", "=", "0.5", "elif", "individual", ":", "alpha", "=", "tf", ".", "random_uniform", "(", "tf", ".", "get_shape", "(", "x", ")", "[", ":", "1", "]", ")", "else", ":", "alpha", "=", "tf", ".", "random_uniform", "(", "[", "]", ")", "return", "alpha", "*", "x", "+", "(", "1.0", "-", "alpha", ")", "*", "y" ]
The shake-shake sum of 2 tensors, python version.
[ "The", "shake", "-", "shake", "sum", "of", "2", "tensors", "python", "version", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L177-L186
22,131
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
shakeshake
def shakeshake(xs, equal_grad=False): """Multi-argument shake-shake, currently approximated by sums of 2.""" if len(xs) == 1: return xs[0] div = (len(xs) + 1) // 2 arg1 = shakeshake(xs[:div], equal_grad=equal_grad) arg2 = shakeshake(xs[div:], equal_grad=equal_grad) if equal_grad: return shakeshake2_eqgrad(arg1, arg2) return shakeshake2(arg1, arg2)
python
def shakeshake(xs, equal_grad=False): """Multi-argument shake-shake, currently approximated by sums of 2.""" if len(xs) == 1: return xs[0] div = (len(xs) + 1) // 2 arg1 = shakeshake(xs[:div], equal_grad=equal_grad) arg2 = shakeshake(xs[div:], equal_grad=equal_grad) if equal_grad: return shakeshake2_eqgrad(arg1, arg2) return shakeshake2(arg1, arg2)
[ "def", "shakeshake", "(", "xs", ",", "equal_grad", "=", "False", ")", ":", "if", "len", "(", "xs", ")", "==", "1", ":", "return", "xs", "[", "0", "]", "div", "=", "(", "len", "(", "xs", ")", "+", "1", ")", "//", "2", "arg1", "=", "shakeshake", "(", "xs", "[", ":", "div", "]", ",", "equal_grad", "=", "equal_grad", ")", "arg2", "=", "shakeshake", "(", "xs", "[", "div", ":", "]", ",", "equal_grad", "=", "equal_grad", ")", "if", "equal_grad", ":", "return", "shakeshake2_eqgrad", "(", "arg1", ",", "arg2", ")", "return", "shakeshake2", "(", "arg1", ",", "arg2", ")" ]
Multi-argument shake-shake, currently approximated by sums of 2.
[ "Multi", "-", "argument", "shake", "-", "shake", "currently", "approximated", "by", "sums", "of", "2", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L230-L239
22,132
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
expand_squeeze_to_nd
def expand_squeeze_to_nd(x, n, squeeze_dim=2, expand_dim=-1): """Make x n-d with squeeze and expand_dims.""" if len(x.shape) > n: while len(x.shape) != n: x = tf.squeeze(x, [squeeze_dim]) else: while len(x.shape) != n: x = tf.expand_dims(x, expand_dim) return x
python
def expand_squeeze_to_nd(x, n, squeeze_dim=2, expand_dim=-1): """Make x n-d with squeeze and expand_dims.""" if len(x.shape) > n: while len(x.shape) != n: x = tf.squeeze(x, [squeeze_dim]) else: while len(x.shape) != n: x = tf.expand_dims(x, expand_dim) return x
[ "def", "expand_squeeze_to_nd", "(", "x", ",", "n", ",", "squeeze_dim", "=", "2", ",", "expand_dim", "=", "-", "1", ")", ":", "if", "len", "(", "x", ".", "shape", ")", ">", "n", ":", "while", "len", "(", "x", ".", "shape", ")", "!=", "n", ":", "x", "=", "tf", ".", "squeeze", "(", "x", ",", "[", "squeeze_dim", "]", ")", "else", ":", "while", "len", "(", "x", ".", "shape", ")", "!=", "n", ":", "x", "=", "tf", ".", "expand_dims", "(", "x", ",", "expand_dim", ")", "return", "x" ]
Make x n-d with squeeze and expand_dims.
[ "Make", "x", "n", "-", "d", "with", "squeeze", "and", "expand_dims", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L267-L275
22,133
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
standardize_images
def standardize_images(x): """Image standardization on batches and videos.""" with tf.name_scope("standardize_images", values=[x]): x_shape = shape_list(x) x = to_float(tf.reshape(x, [-1] + x_shape[-3:])) x_mean = tf.reduce_mean(x, axis=[1, 2], keepdims=True) x_variance = tf.reduce_mean( tf.squared_difference(x, x_mean), axis=[1, 2], keepdims=True) num_pixels = to_float(x_shape[-2] * x_shape[-3]) x = (x - x_mean) / tf.maximum(tf.sqrt(x_variance), tf.rsqrt(num_pixels)) return tf.reshape(x, x_shape)
python
def standardize_images(x): """Image standardization on batches and videos.""" with tf.name_scope("standardize_images", values=[x]): x_shape = shape_list(x) x = to_float(tf.reshape(x, [-1] + x_shape[-3:])) x_mean = tf.reduce_mean(x, axis=[1, 2], keepdims=True) x_variance = tf.reduce_mean( tf.squared_difference(x, x_mean), axis=[1, 2], keepdims=True) num_pixels = to_float(x_shape[-2] * x_shape[-3]) x = (x - x_mean) / tf.maximum(tf.sqrt(x_variance), tf.rsqrt(num_pixels)) return tf.reshape(x, x_shape)
[ "def", "standardize_images", "(", "x", ")", ":", "with", "tf", ".", "name_scope", "(", "\"standardize_images\"", ",", "values", "=", "[", "x", "]", ")", ":", "x_shape", "=", "shape_list", "(", "x", ")", "x", "=", "to_float", "(", "tf", ".", "reshape", "(", "x", ",", "[", "-", "1", "]", "+", "x_shape", "[", "-", "3", ":", "]", ")", ")", "x_mean", "=", "tf", ".", "reduce_mean", "(", "x", ",", "axis", "=", "[", "1", ",", "2", "]", ",", "keepdims", "=", "True", ")", "x_variance", "=", "tf", ".", "reduce_mean", "(", "tf", ".", "squared_difference", "(", "x", ",", "x_mean", ")", ",", "axis", "=", "[", "1", ",", "2", "]", ",", "keepdims", "=", "True", ")", "num_pixels", "=", "to_float", "(", "x_shape", "[", "-", "2", "]", "*", "x_shape", "[", "-", "3", "]", ")", "x", "=", "(", "x", "-", "x_mean", ")", "/", "tf", ".", "maximum", "(", "tf", ".", "sqrt", "(", "x_variance", ")", ",", "tf", ".", "rsqrt", "(", "num_pixels", ")", ")", "return", "tf", ".", "reshape", "(", "x", ",", "x_shape", ")" ]
Image standardization on batches and videos.
[ "Image", "standardization", "on", "batches", "and", "videos", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L278-L288
22,134
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
flatten4d3d
def flatten4d3d(x): """Flatten a 4d-tensor into a 3d-tensor by joining width and height.""" xshape = shape_list(x) result = tf.reshape(x, [xshape[0], xshape[1] * xshape[2], xshape[3]]) return result
python
def flatten4d3d(x): """Flatten a 4d-tensor into a 3d-tensor by joining width and height.""" xshape = shape_list(x) result = tf.reshape(x, [xshape[0], xshape[1] * xshape[2], xshape[3]]) return result
[ "def", "flatten4d3d", "(", "x", ")", ":", "xshape", "=", "shape_list", "(", "x", ")", "result", "=", "tf", ".", "reshape", "(", "x", ",", "[", "xshape", "[", "0", "]", ",", "xshape", "[", "1", "]", "*", "xshape", "[", "2", "]", ",", "xshape", "[", "3", "]", "]", ")", "return", "result" ]
Flatten a 4d-tensor into a 3d-tensor by joining width and height.
[ "Flatten", "a", "4d", "-", "tensor", "into", "a", "3d", "-", "tensor", "by", "joining", "width", "and", "height", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L291-L295
22,135
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
gather
def gather(params, indices, dtype=tf.float32): """Version of tf.gather that works faster on tpu.""" if not is_xla_compiled(): return tf.gather(params, indices) vocab_size = params.get_shape().as_list()[0] indices_flat = tf.reshape(indices, [-1]) out = tf.matmul(tf.one_hot(indices_flat, vocab_size, dtype=dtype), params) out = reshape_like(out, tf.expand_dims(indices, -1)) return out
python
def gather(params, indices, dtype=tf.float32): """Version of tf.gather that works faster on tpu.""" if not is_xla_compiled(): return tf.gather(params, indices) vocab_size = params.get_shape().as_list()[0] indices_flat = tf.reshape(indices, [-1]) out = tf.matmul(tf.one_hot(indices_flat, vocab_size, dtype=dtype), params) out = reshape_like(out, tf.expand_dims(indices, -1)) return out
[ "def", "gather", "(", "params", ",", "indices", ",", "dtype", "=", "tf", ".", "float32", ")", ":", "if", "not", "is_xla_compiled", "(", ")", ":", "return", "tf", ".", "gather", "(", "params", ",", "indices", ")", "vocab_size", "=", "params", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "[", "0", "]", "indices_flat", "=", "tf", ".", "reshape", "(", "indices", ",", "[", "-", "1", "]", ")", "out", "=", "tf", ".", "matmul", "(", "tf", ".", "one_hot", "(", "indices_flat", ",", "vocab_size", ",", "dtype", "=", "dtype", ")", ",", "params", ")", "out", "=", "reshape_like", "(", "out", ",", "tf", ".", "expand_dims", "(", "indices", ",", "-", "1", ")", ")", "return", "out" ]
Version of tf.gather that works faster on tpu.
[ "Version", "of", "tf", ".", "gather", "that", "works", "faster", "on", "tpu", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L299-L307
22,136
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
cumsum
def cumsum(x, axis=0, exclusive=False): """TPU hack for tf.cumsum. This is equivalent to tf.cumsum and is faster on TPU as of 04/2018 unless the axis dimension is very large. Args: x: a Tensor axis: an integer exclusive: a boolean Returns: Tensor of the same shape as x. """ if not is_xla_compiled(): return tf.cumsum(x, axis=axis, exclusive=exclusive) x_shape = shape_list(x) rank = len(x_shape) length = x_shape[axis] my_range = tf.range(length) comparator = tf.less if exclusive else tf.less_equal mask = tf.cast( comparator(tf.expand_dims(my_range, 1), tf.expand_dims(my_range, 0)), x.dtype) ret = tf.tensordot(x, mask, axes=[[axis], [0]]) if axis != rank - 1: ret = tf.transpose( ret, list(range(axis)) + [rank - 1] + list(range(axis, rank - 1))) return ret
python
def cumsum(x, axis=0, exclusive=False): """TPU hack for tf.cumsum. This is equivalent to tf.cumsum and is faster on TPU as of 04/2018 unless the axis dimension is very large. Args: x: a Tensor axis: an integer exclusive: a boolean Returns: Tensor of the same shape as x. """ if not is_xla_compiled(): return tf.cumsum(x, axis=axis, exclusive=exclusive) x_shape = shape_list(x) rank = len(x_shape) length = x_shape[axis] my_range = tf.range(length) comparator = tf.less if exclusive else tf.less_equal mask = tf.cast( comparator(tf.expand_dims(my_range, 1), tf.expand_dims(my_range, 0)), x.dtype) ret = tf.tensordot(x, mask, axes=[[axis], [0]]) if axis != rank - 1: ret = tf.transpose( ret, list(range(axis)) + [rank - 1] + list(range(axis, rank - 1))) return ret
[ "def", "cumsum", "(", "x", ",", "axis", "=", "0", ",", "exclusive", "=", "False", ")", ":", "if", "not", "is_xla_compiled", "(", ")", ":", "return", "tf", ".", "cumsum", "(", "x", ",", "axis", "=", "axis", ",", "exclusive", "=", "exclusive", ")", "x_shape", "=", "shape_list", "(", "x", ")", "rank", "=", "len", "(", "x_shape", ")", "length", "=", "x_shape", "[", "axis", "]", "my_range", "=", "tf", ".", "range", "(", "length", ")", "comparator", "=", "tf", ".", "less", "if", "exclusive", "else", "tf", ".", "less_equal", "mask", "=", "tf", ".", "cast", "(", "comparator", "(", "tf", ".", "expand_dims", "(", "my_range", ",", "1", ")", ",", "tf", ".", "expand_dims", "(", "my_range", ",", "0", ")", ")", ",", "x", ".", "dtype", ")", "ret", "=", "tf", ".", "tensordot", "(", "x", ",", "mask", ",", "axes", "=", "[", "[", "axis", "]", ",", "[", "0", "]", "]", ")", "if", "axis", "!=", "rank", "-", "1", ":", "ret", "=", "tf", ".", "transpose", "(", "ret", ",", "list", "(", "range", "(", "axis", ")", ")", "+", "[", "rank", "-", "1", "]", "+", "list", "(", "range", "(", "axis", ",", "rank", "-", "1", ")", ")", ")", "return", "ret" ]
TPU hack for tf.cumsum. This is equivalent to tf.cumsum and is faster on TPU as of 04/2018 unless the axis dimension is very large. Args: x: a Tensor axis: an integer exclusive: a boolean Returns: Tensor of the same shape as x.
[ "TPU", "hack", "for", "tf", ".", "cumsum", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L311-L340
22,137
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
dropout_no_scaling
def dropout_no_scaling(x, keep_prob): """Like tf.nn.dropout, but does not scale up. Works on integers also. Args: x: a Tensor keep_prob: a floating point number Returns: Tensor of the same shape as x. """ if keep_prob == 1.0: return x mask = tf.less(tf.random_uniform(tf.shape(x)), keep_prob) return x * cast_like(mask, x)
python
def dropout_no_scaling(x, keep_prob): """Like tf.nn.dropout, but does not scale up. Works on integers also. Args: x: a Tensor keep_prob: a floating point number Returns: Tensor of the same shape as x. """ if keep_prob == 1.0: return x mask = tf.less(tf.random_uniform(tf.shape(x)), keep_prob) return x * cast_like(mask, x)
[ "def", "dropout_no_scaling", "(", "x", ",", "keep_prob", ")", ":", "if", "keep_prob", "==", "1.0", ":", "return", "x", "mask", "=", "tf", ".", "less", "(", "tf", ".", "random_uniform", "(", "tf", ".", "shape", "(", "x", ")", ")", ",", "keep_prob", ")", "return", "x", "*", "cast_like", "(", "mask", ",", "x", ")" ]
Like tf.nn.dropout, but does not scale up. Works on integers also. Args: x: a Tensor keep_prob: a floating point number Returns: Tensor of the same shape as x.
[ "Like", "tf", ".", "nn", ".", "dropout", "but", "does", "not", "scale", "up", ".", "Works", "on", "integers", "also", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L343-L356
22,138
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
embedding
def embedding(x, vocab_size, dense_size, name=None, reuse=None, multiplier=1.0, symbol_dropout_rate=0.0, embedding_var=None, dtype=tf.float32): """Embed x of type int64 into dense vectors, reducing to max 4 dimensions.""" with tf.variable_scope( name, default_name="embedding", values=[x], reuse=reuse, dtype=dtype): if embedding_var is None: embedding_var = tf.get_variable("kernel", [vocab_size, dense_size]) # On the backwards pass, we want to convert the gradient from # an indexed-slices to a regular tensor before sending it back to the # parameter server. This avoids excess computation on the parameter server. if not tf.executing_eagerly(): embedding_var = convert_gradient_to_tensor(embedding_var) x = dropout_no_scaling(x, 1.0 - symbol_dropout_rate) emb_x = gather(embedding_var, x, dtype) if multiplier != 1.0: emb_x *= multiplier static_shape = emb_x.shape.as_list() if len(static_shape) < 5: return emb_x assert len(static_shape) == 5 # If we had an extra channel dimension, assume it's 1, i.e. shape[3] == 1. return tf.squeeze(emb_x, 3)
python
def embedding(x, vocab_size, dense_size, name=None, reuse=None, multiplier=1.0, symbol_dropout_rate=0.0, embedding_var=None, dtype=tf.float32): """Embed x of type int64 into dense vectors, reducing to max 4 dimensions.""" with tf.variable_scope( name, default_name="embedding", values=[x], reuse=reuse, dtype=dtype): if embedding_var is None: embedding_var = tf.get_variable("kernel", [vocab_size, dense_size]) # On the backwards pass, we want to convert the gradient from # an indexed-slices to a regular tensor before sending it back to the # parameter server. This avoids excess computation on the parameter server. if not tf.executing_eagerly(): embedding_var = convert_gradient_to_tensor(embedding_var) x = dropout_no_scaling(x, 1.0 - symbol_dropout_rate) emb_x = gather(embedding_var, x, dtype) if multiplier != 1.0: emb_x *= multiplier static_shape = emb_x.shape.as_list() if len(static_shape) < 5: return emb_x assert len(static_shape) == 5 # If we had an extra channel dimension, assume it's 1, i.e. shape[3] == 1. return tf.squeeze(emb_x, 3)
[ "def", "embedding", "(", "x", ",", "vocab_size", ",", "dense_size", ",", "name", "=", "None", ",", "reuse", "=", "None", ",", "multiplier", "=", "1.0", ",", "symbol_dropout_rate", "=", "0.0", ",", "embedding_var", "=", "None", ",", "dtype", "=", "tf", ".", "float32", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ",", "default_name", "=", "\"embedding\"", ",", "values", "=", "[", "x", "]", ",", "reuse", "=", "reuse", ",", "dtype", "=", "dtype", ")", ":", "if", "embedding_var", "is", "None", ":", "embedding_var", "=", "tf", ".", "get_variable", "(", "\"kernel\"", ",", "[", "vocab_size", ",", "dense_size", "]", ")", "# On the backwards pass, we want to convert the gradient from", "# an indexed-slices to a regular tensor before sending it back to the", "# parameter server. This avoids excess computation on the parameter server.", "if", "not", "tf", ".", "executing_eagerly", "(", ")", ":", "embedding_var", "=", "convert_gradient_to_tensor", "(", "embedding_var", ")", "x", "=", "dropout_no_scaling", "(", "x", ",", "1.0", "-", "symbol_dropout_rate", ")", "emb_x", "=", "gather", "(", "embedding_var", ",", "x", ",", "dtype", ")", "if", "multiplier", "!=", "1.0", ":", "emb_x", "*=", "multiplier", "static_shape", "=", "emb_x", ".", "shape", ".", "as_list", "(", ")", "if", "len", "(", "static_shape", ")", "<", "5", ":", "return", "emb_x", "assert", "len", "(", "static_shape", ")", "==", "5", "# If we had an extra channel dimension, assume it's 1, i.e. shape[3] == 1.", "return", "tf", ".", "squeeze", "(", "emb_x", ",", "3", ")" ]
Embed x of type int64 into dense vectors, reducing to max 4 dimensions.
[ "Embed", "x", "of", "type", "int64", "into", "dense", "vectors", "reducing", "to", "max", "4", "dimensions", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L359-L387
22,139
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
conv_stride2_multistep
def conv_stride2_multistep(x, nbr_steps, output_filters, name=None, reuse=None): """Use a strided convolution to downsample x by 2, `nbr_steps` times. We use stride and filter size 2 to avoid the checkerboard problem of deconvs. As detailed in http://distill.pub/2016/deconv-checkerboard/. Args: x: a `Tensor` with shape `[batch, spatial, depth]` or `[batch, spatial_1, spatial_2, depth]` nbr_steps: number of halving downsample rounds to apply output_filters: an int specifying the filter count for the convolutions name: a string reuse: a boolean Returns: a `Tensor` with shape `[batch, spatial / (2**nbr_steps), output_filters]` or `[batch, spatial_1 / (2**nbr_steps), spatial_2 / (2**nbr_steps), output_filters]` """ with tf.variable_scope( name, default_name="conv_stride2_multistep", values=[x], reuse=reuse): if nbr_steps == 0: out = conv(x, output_filters, (1, 1)) return out, [out] hidden_layers = [x] for i in range(nbr_steps): hidden_layers.append( conv( hidden_layers[-1], output_filters, (2, 2), strides=2, activation=tf.nn.relu, name="conv" + str(i))) return hidden_layers[-1], hidden_layers
python
def conv_stride2_multistep(x, nbr_steps, output_filters, name=None, reuse=None): """Use a strided convolution to downsample x by 2, `nbr_steps` times. We use stride and filter size 2 to avoid the checkerboard problem of deconvs. As detailed in http://distill.pub/2016/deconv-checkerboard/. Args: x: a `Tensor` with shape `[batch, spatial, depth]` or `[batch, spatial_1, spatial_2, depth]` nbr_steps: number of halving downsample rounds to apply output_filters: an int specifying the filter count for the convolutions name: a string reuse: a boolean Returns: a `Tensor` with shape `[batch, spatial / (2**nbr_steps), output_filters]` or `[batch, spatial_1 / (2**nbr_steps), spatial_2 / (2**nbr_steps), output_filters]` """ with tf.variable_scope( name, default_name="conv_stride2_multistep", values=[x], reuse=reuse): if nbr_steps == 0: out = conv(x, output_filters, (1, 1)) return out, [out] hidden_layers = [x] for i in range(nbr_steps): hidden_layers.append( conv( hidden_layers[-1], output_filters, (2, 2), strides=2, activation=tf.nn.relu, name="conv" + str(i))) return hidden_layers[-1], hidden_layers
[ "def", "conv_stride2_multistep", "(", "x", ",", "nbr_steps", ",", "output_filters", ",", "name", "=", "None", ",", "reuse", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ",", "default_name", "=", "\"conv_stride2_multistep\"", ",", "values", "=", "[", "x", "]", ",", "reuse", "=", "reuse", ")", ":", "if", "nbr_steps", "==", "0", ":", "out", "=", "conv", "(", "x", ",", "output_filters", ",", "(", "1", ",", "1", ")", ")", "return", "out", ",", "[", "out", "]", "hidden_layers", "=", "[", "x", "]", "for", "i", "in", "range", "(", "nbr_steps", ")", ":", "hidden_layers", ".", "append", "(", "conv", "(", "hidden_layers", "[", "-", "1", "]", ",", "output_filters", ",", "(", "2", ",", "2", ")", ",", "strides", "=", "2", ",", "activation", "=", "tf", ".", "nn", ".", "relu", ",", "name", "=", "\"conv\"", "+", "str", "(", "i", ")", ")", ")", "return", "hidden_layers", "[", "-", "1", "]", ",", "hidden_layers" ]
Use a strided convolution to downsample x by 2, `nbr_steps` times. We use stride and filter size 2 to avoid the checkerboard problem of deconvs. As detailed in http://distill.pub/2016/deconv-checkerboard/. Args: x: a `Tensor` with shape `[batch, spatial, depth]` or `[batch, spatial_1, spatial_2, depth]` nbr_steps: number of halving downsample rounds to apply output_filters: an int specifying the filter count for the convolutions name: a string reuse: a boolean Returns: a `Tensor` with shape `[batch, spatial / (2**nbr_steps), output_filters]` or `[batch, spatial_1 / (2**nbr_steps), spatial_2 / (2**nbr_steps), output_filters]`
[ "Use", "a", "strided", "convolution", "to", "downsample", "x", "by", "2", "nbr_steps", "times", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L417-L450
22,140
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
conv_internal
def conv_internal(conv_fn, inputs, filters, kernel_size, **kwargs): """Conditional conv_fn making kernel 1d or 2d depending on inputs shape.""" static_shape = inputs.get_shape() if not static_shape or len(static_shape) != 4: raise ValueError("Inputs to conv must have statically known rank 4. " "Shape: " + str(static_shape)) # Add support for left padding. if kwargs.get("padding") == "LEFT": dilation_rate = (1, 1) if "dilation_rate" in kwargs: dilation_rate = kwargs["dilation_rate"] assert kernel_size[0] % 2 == 1 and kernel_size[1] % 2 == 1 height_padding = 2 * (kernel_size[0] // 2) * dilation_rate[0] cond_padding = tf.cond( tf.equal(shape_list(inputs)[2], 1), lambda: tf.constant(0), lambda: tf.constant(2 * (kernel_size[1] // 2) * dilation_rate[1])) width_padding = 0 if static_shape[2] == 1 else cond_padding padding = [[0, 0], [height_padding, 0], [width_padding, 0], [0, 0]] inputs = tf.pad(inputs, padding) # Set middle two dimensions to None to prevent convolution from complaining inputs.set_shape([static_shape[0], None, None, static_shape[3]]) kwargs["padding"] = "VALID" def conv2d_kernel(kernel_size_arg, name_suffix): """Call conv2d but add suffix to name.""" name = "{}_{}".format(kwargs.get("name", "conv"), name_suffix) original_name = kwargs.pop("name", None) original_force2d = kwargs.pop("force2d", None) result = conv_fn(inputs, filters, kernel_size_arg, name=name, **kwargs) if original_name is not None: kwargs["name"] = original_name # Restore for other calls. if original_force2d is not None: kwargs["force2d"] = original_force2d return result return conv2d_kernel(kernel_size, "single")
python
def conv_internal(conv_fn, inputs, filters, kernel_size, **kwargs): """Conditional conv_fn making kernel 1d or 2d depending on inputs shape.""" static_shape = inputs.get_shape() if not static_shape or len(static_shape) != 4: raise ValueError("Inputs to conv must have statically known rank 4. " "Shape: " + str(static_shape)) # Add support for left padding. if kwargs.get("padding") == "LEFT": dilation_rate = (1, 1) if "dilation_rate" in kwargs: dilation_rate = kwargs["dilation_rate"] assert kernel_size[0] % 2 == 1 and kernel_size[1] % 2 == 1 height_padding = 2 * (kernel_size[0] // 2) * dilation_rate[0] cond_padding = tf.cond( tf.equal(shape_list(inputs)[2], 1), lambda: tf.constant(0), lambda: tf.constant(2 * (kernel_size[1] // 2) * dilation_rate[1])) width_padding = 0 if static_shape[2] == 1 else cond_padding padding = [[0, 0], [height_padding, 0], [width_padding, 0], [0, 0]] inputs = tf.pad(inputs, padding) # Set middle two dimensions to None to prevent convolution from complaining inputs.set_shape([static_shape[0], None, None, static_shape[3]]) kwargs["padding"] = "VALID" def conv2d_kernel(kernel_size_arg, name_suffix): """Call conv2d but add suffix to name.""" name = "{}_{}".format(kwargs.get("name", "conv"), name_suffix) original_name = kwargs.pop("name", None) original_force2d = kwargs.pop("force2d", None) result = conv_fn(inputs, filters, kernel_size_arg, name=name, **kwargs) if original_name is not None: kwargs["name"] = original_name # Restore for other calls. if original_force2d is not None: kwargs["force2d"] = original_force2d return result return conv2d_kernel(kernel_size, "single")
[ "def", "conv_internal", "(", "conv_fn", ",", "inputs", ",", "filters", ",", "kernel_size", ",", "*", "*", "kwargs", ")", ":", "static_shape", "=", "inputs", ".", "get_shape", "(", ")", "if", "not", "static_shape", "or", "len", "(", "static_shape", ")", "!=", "4", ":", "raise", "ValueError", "(", "\"Inputs to conv must have statically known rank 4. \"", "\"Shape: \"", "+", "str", "(", "static_shape", ")", ")", "# Add support for left padding.", "if", "kwargs", ".", "get", "(", "\"padding\"", ")", "==", "\"LEFT\"", ":", "dilation_rate", "=", "(", "1", ",", "1", ")", "if", "\"dilation_rate\"", "in", "kwargs", ":", "dilation_rate", "=", "kwargs", "[", "\"dilation_rate\"", "]", "assert", "kernel_size", "[", "0", "]", "%", "2", "==", "1", "and", "kernel_size", "[", "1", "]", "%", "2", "==", "1", "height_padding", "=", "2", "*", "(", "kernel_size", "[", "0", "]", "//", "2", ")", "*", "dilation_rate", "[", "0", "]", "cond_padding", "=", "tf", ".", "cond", "(", "tf", ".", "equal", "(", "shape_list", "(", "inputs", ")", "[", "2", "]", ",", "1", ")", ",", "lambda", ":", "tf", ".", "constant", "(", "0", ")", ",", "lambda", ":", "tf", ".", "constant", "(", "2", "*", "(", "kernel_size", "[", "1", "]", "//", "2", ")", "*", "dilation_rate", "[", "1", "]", ")", ")", "width_padding", "=", "0", "if", "static_shape", "[", "2", "]", "==", "1", "else", "cond_padding", "padding", "=", "[", "[", "0", ",", "0", "]", ",", "[", "height_padding", ",", "0", "]", ",", "[", "width_padding", ",", "0", "]", ",", "[", "0", ",", "0", "]", "]", "inputs", "=", "tf", ".", "pad", "(", "inputs", ",", "padding", ")", "# Set middle two dimensions to None to prevent convolution from complaining", "inputs", ".", "set_shape", "(", "[", "static_shape", "[", "0", "]", ",", "None", ",", "None", ",", "static_shape", "[", "3", "]", "]", ")", "kwargs", "[", "\"padding\"", "]", "=", "\"VALID\"", "def", "conv2d_kernel", "(", "kernel_size_arg", ",", "name_suffix", ")", ":", "\"\"\"Call conv2d but add suffix to name.\"\"\"", "name", "=", "\"{}_{}\"", ".", "format", "(", "kwargs", ".", "get", "(", "\"name\"", ",", "\"conv\"", ")", ",", "name_suffix", ")", "original_name", "=", "kwargs", ".", "pop", "(", "\"name\"", ",", "None", ")", "original_force2d", "=", "kwargs", ".", "pop", "(", "\"force2d\"", ",", "None", ")", "result", "=", "conv_fn", "(", "inputs", ",", "filters", ",", "kernel_size_arg", ",", "name", "=", "name", ",", "*", "*", "kwargs", ")", "if", "original_name", "is", "not", "None", ":", "kwargs", "[", "\"name\"", "]", "=", "original_name", "# Restore for other calls.", "if", "original_force2d", "is", "not", "None", ":", "kwargs", "[", "\"force2d\"", "]", "=", "original_force2d", "return", "result", "return", "conv2d_kernel", "(", "kernel_size", ",", "\"single\"", ")" ]
Conditional conv_fn making kernel 1d or 2d depending on inputs shape.
[ "Conditional", "conv_fn", "making", "kernel", "1d", "or", "2d", "depending", "on", "inputs", "shape", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L516-L551
22,141
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
subseparable_conv
def subseparable_conv(inputs, filters, kernel_size, **kwargs): """Sub-separable convolution. If separability == 0 it's a separable_conv.""" def conv_fn(inputs, filters, kernel_size, **kwargs): """Sub-separable convolution, splits into separability-many blocks.""" separability = None if "separability" in kwargs: separability = kwargs.pop("separability") if separability: parts = [] abs_sep = separability if separability > 0 else -1 * separability for split_idx, split in enumerate(tf.split(inputs, abs_sep, axis=3)): with tf.variable_scope("part_%d" % split_idx): if separability > 0: parts.append( layers().Conv2D(filters // separability, kernel_size, **kwargs)(split)) else: parts.append( layers().SeparableConv2D(filters // abs_sep, kernel_size, **kwargs)(split)) if separability > 1: result = layers().Conv2D(filters, (1, 1))(tf.concat(parts, axis=3)) elif abs_sep == 1: # If we have just one block, return it. assert len(parts) == 1 result = parts[0] else: result = tf.concat(parts, axis=3) else: result = layers().SeparableConv2D(filters, kernel_size, **kwargs)(inputs) if separability is not None: kwargs["separability"] = separability return result return conv_internal(conv_fn, inputs, filters, kernel_size, **kwargs)
python
def subseparable_conv(inputs, filters, kernel_size, **kwargs): """Sub-separable convolution. If separability == 0 it's a separable_conv.""" def conv_fn(inputs, filters, kernel_size, **kwargs): """Sub-separable convolution, splits into separability-many blocks.""" separability = None if "separability" in kwargs: separability = kwargs.pop("separability") if separability: parts = [] abs_sep = separability if separability > 0 else -1 * separability for split_idx, split in enumerate(tf.split(inputs, abs_sep, axis=3)): with tf.variable_scope("part_%d" % split_idx): if separability > 0: parts.append( layers().Conv2D(filters // separability, kernel_size, **kwargs)(split)) else: parts.append( layers().SeparableConv2D(filters // abs_sep, kernel_size, **kwargs)(split)) if separability > 1: result = layers().Conv2D(filters, (1, 1))(tf.concat(parts, axis=3)) elif abs_sep == 1: # If we have just one block, return it. assert len(parts) == 1 result = parts[0] else: result = tf.concat(parts, axis=3) else: result = layers().SeparableConv2D(filters, kernel_size, **kwargs)(inputs) if separability is not None: kwargs["separability"] = separability return result return conv_internal(conv_fn, inputs, filters, kernel_size, **kwargs)
[ "def", "subseparable_conv", "(", "inputs", ",", "filters", ",", "kernel_size", ",", "*", "*", "kwargs", ")", ":", "def", "conv_fn", "(", "inputs", ",", "filters", ",", "kernel_size", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Sub-separable convolution, splits into separability-many blocks.\"\"\"", "separability", "=", "None", "if", "\"separability\"", "in", "kwargs", ":", "separability", "=", "kwargs", ".", "pop", "(", "\"separability\"", ")", "if", "separability", ":", "parts", "=", "[", "]", "abs_sep", "=", "separability", "if", "separability", ">", "0", "else", "-", "1", "*", "separability", "for", "split_idx", ",", "split", "in", "enumerate", "(", "tf", ".", "split", "(", "inputs", ",", "abs_sep", ",", "axis", "=", "3", ")", ")", ":", "with", "tf", ".", "variable_scope", "(", "\"part_%d\"", "%", "split_idx", ")", ":", "if", "separability", ">", "0", ":", "parts", ".", "append", "(", "layers", "(", ")", ".", "Conv2D", "(", "filters", "//", "separability", ",", "kernel_size", ",", "*", "*", "kwargs", ")", "(", "split", ")", ")", "else", ":", "parts", ".", "append", "(", "layers", "(", ")", ".", "SeparableConv2D", "(", "filters", "//", "abs_sep", ",", "kernel_size", ",", "*", "*", "kwargs", ")", "(", "split", ")", ")", "if", "separability", ">", "1", ":", "result", "=", "layers", "(", ")", ".", "Conv2D", "(", "filters", ",", "(", "1", ",", "1", ")", ")", "(", "tf", ".", "concat", "(", "parts", ",", "axis", "=", "3", ")", ")", "elif", "abs_sep", "==", "1", ":", "# If we have just one block, return it.", "assert", "len", "(", "parts", ")", "==", "1", "result", "=", "parts", "[", "0", "]", "else", ":", "result", "=", "tf", ".", "concat", "(", "parts", ",", "axis", "=", "3", ")", "else", ":", "result", "=", "layers", "(", ")", ".", "SeparableConv2D", "(", "filters", ",", "kernel_size", ",", "*", "*", "kwargs", ")", "(", "inputs", ")", "if", "separability", "is", "not", "None", ":", "kwargs", "[", "\"separability\"", "]", "=", "separability", "return", "result", "return", "conv_internal", "(", "conv_fn", ",", "inputs", ",", "filters", ",", "kernel_size", ",", "*", "*", "kwargs", ")" ]
Sub-separable convolution. If separability == 0 it's a separable_conv.
[ "Sub", "-", "separable", "convolution", ".", "If", "separability", "==", "0", "it", "s", "a", "separable_conv", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L579-L614
22,142
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
layer_norm_vars
def layer_norm_vars(filters): """Create Variables for layer norm.""" scale = tf.get_variable( "layer_norm_scale", [filters], initializer=tf.ones_initializer()) bias = tf.get_variable( "layer_norm_bias", [filters], initializer=tf.zeros_initializer()) return scale, bias
python
def layer_norm_vars(filters): """Create Variables for layer norm.""" scale = tf.get_variable( "layer_norm_scale", [filters], initializer=tf.ones_initializer()) bias = tf.get_variable( "layer_norm_bias", [filters], initializer=tf.zeros_initializer()) return scale, bias
[ "def", "layer_norm_vars", "(", "filters", ")", ":", "scale", "=", "tf", ".", "get_variable", "(", "\"layer_norm_scale\"", ",", "[", "filters", "]", ",", "initializer", "=", "tf", ".", "ones_initializer", "(", ")", ")", "bias", "=", "tf", ".", "get_variable", "(", "\"layer_norm_bias\"", ",", "[", "filters", "]", ",", "initializer", "=", "tf", ".", "zeros_initializer", "(", ")", ")", "return", "scale", ",", "bias" ]
Create Variables for layer norm.
[ "Create", "Variables", "for", "layer", "norm", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L651-L657
22,143
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
layer_norm_compute
def layer_norm_compute(x, epsilon, scale, bias, layer_collection=None): """Layer norm raw computation.""" # Save these before they get converted to tensors by the casting below params = (scale, bias) epsilon, scale, bias = [cast_like(t, x) for t in [epsilon, scale, bias]] mean = tf.reduce_mean(x, axis=[-1], keepdims=True) variance = tf.reduce_mean( tf.squared_difference(x, mean), axis=[-1], keepdims=True) norm_x = (x - mean) * tf.rsqrt(variance + epsilon) output = norm_x * scale + bias return output
python
def layer_norm_compute(x, epsilon, scale, bias, layer_collection=None): """Layer norm raw computation.""" # Save these before they get converted to tensors by the casting below params = (scale, bias) epsilon, scale, bias = [cast_like(t, x) for t in [epsilon, scale, bias]] mean = tf.reduce_mean(x, axis=[-1], keepdims=True) variance = tf.reduce_mean( tf.squared_difference(x, mean), axis=[-1], keepdims=True) norm_x = (x - mean) * tf.rsqrt(variance + epsilon) output = norm_x * scale + bias return output
[ "def", "layer_norm_compute", "(", "x", ",", "epsilon", ",", "scale", ",", "bias", ",", "layer_collection", "=", "None", ")", ":", "# Save these before they get converted to tensors by the casting below", "params", "=", "(", "scale", ",", "bias", ")", "epsilon", ",", "scale", ",", "bias", "=", "[", "cast_like", "(", "t", ",", "x", ")", "for", "t", "in", "[", "epsilon", ",", "scale", ",", "bias", "]", "]", "mean", "=", "tf", ".", "reduce_mean", "(", "x", ",", "axis", "=", "[", "-", "1", "]", ",", "keepdims", "=", "True", ")", "variance", "=", "tf", ".", "reduce_mean", "(", "tf", ".", "squared_difference", "(", "x", ",", "mean", ")", ",", "axis", "=", "[", "-", "1", "]", ",", "keepdims", "=", "True", ")", "norm_x", "=", "(", "x", "-", "mean", ")", "*", "tf", ".", "rsqrt", "(", "variance", "+", "epsilon", ")", "output", "=", "norm_x", "*", "scale", "+", "bias", "return", "output" ]
Layer norm raw computation.
[ "Layer", "norm", "raw", "computation", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L660-L675
22,144
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
layer_norm
def layer_norm(x, filters=None, epsilon=1e-6, name=None, reuse=None, layer_collection=None): """Layer normalize the tensor x, averaging over the last dimension.""" if filters is None: filters = shape_list(x)[-1] with tf.variable_scope( name, default_name="layer_norm", values=[x], reuse=reuse): scale, bias = layer_norm_vars(filters) return layer_norm_compute(x, epsilon, scale, bias, layer_collection=layer_collection)
python
def layer_norm(x, filters=None, epsilon=1e-6, name=None, reuse=None, layer_collection=None): """Layer normalize the tensor x, averaging over the last dimension.""" if filters is None: filters = shape_list(x)[-1] with tf.variable_scope( name, default_name="layer_norm", values=[x], reuse=reuse): scale, bias = layer_norm_vars(filters) return layer_norm_compute(x, epsilon, scale, bias, layer_collection=layer_collection)
[ "def", "layer_norm", "(", "x", ",", "filters", "=", "None", ",", "epsilon", "=", "1e-6", ",", "name", "=", "None", ",", "reuse", "=", "None", ",", "layer_collection", "=", "None", ")", ":", "if", "filters", "is", "None", ":", "filters", "=", "shape_list", "(", "x", ")", "[", "-", "1", "]", "with", "tf", ".", "variable_scope", "(", "name", ",", "default_name", "=", "\"layer_norm\"", ",", "values", "=", "[", "x", "]", ",", "reuse", "=", "reuse", ")", ":", "scale", ",", "bias", "=", "layer_norm_vars", "(", "filters", ")", "return", "layer_norm_compute", "(", "x", ",", "epsilon", ",", "scale", ",", "bias", ",", "layer_collection", "=", "layer_collection", ")" ]
Layer normalize the tensor x, averaging over the last dimension.
[ "Layer", "normalize", "the", "tensor", "x", "averaging", "over", "the", "last", "dimension", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L678-L691
22,145
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
noam_norm
def noam_norm(x, epsilon=1.0, name=None): """One version of layer normalization.""" with tf.name_scope(name, default_name="noam_norm", values=[x]): shape = x.get_shape() ndims = len(shape) return (tf.nn.l2_normalize(x, ndims - 1, epsilon=epsilon) * tf.sqrt( to_float(shape[-1])))
python
def noam_norm(x, epsilon=1.0, name=None): """One version of layer normalization.""" with tf.name_scope(name, default_name="noam_norm", values=[x]): shape = x.get_shape() ndims = len(shape) return (tf.nn.l2_normalize(x, ndims - 1, epsilon=epsilon) * tf.sqrt( to_float(shape[-1])))
[ "def", "noam_norm", "(", "x", ",", "epsilon", "=", "1.0", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "name_scope", "(", "name", ",", "default_name", "=", "\"noam_norm\"", ",", "values", "=", "[", "x", "]", ")", ":", "shape", "=", "x", ".", "get_shape", "(", ")", "ndims", "=", "len", "(", "shape", ")", "return", "(", "tf", ".", "nn", ".", "l2_normalize", "(", "x", ",", "ndims", "-", "1", ",", "epsilon", "=", "epsilon", ")", "*", "tf", ".", "sqrt", "(", "to_float", "(", "shape", "[", "-", "1", "]", ")", ")", ")" ]
One version of layer normalization.
[ "One", "version", "of", "layer", "normalization", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L715-L721
22,146
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
l2_norm
def l2_norm(x, filters=None, epsilon=1e-6, name=None, reuse=None): """Layer normalization with l2 norm.""" if filters is None: filters = shape_list(x)[-1] with tf.variable_scope(name, default_name="l2_norm", values=[x], reuse=reuse): scale = tf.get_variable( "l2_norm_scale", [filters], initializer=tf.ones_initializer()) bias = tf.get_variable( "l2_norm_bias", [filters], initializer=tf.zeros_initializer()) epsilon, scale, bias = [cast_like(t, x) for t in [epsilon, scale, bias]] mean = tf.reduce_mean(x, axis=[-1], keepdims=True) l2norm = tf.reduce_sum( tf.squared_difference(x, mean), axis=[-1], keepdims=True) norm_x = (x - mean) * tf.rsqrt(l2norm + epsilon) return norm_x * scale + bias
python
def l2_norm(x, filters=None, epsilon=1e-6, name=None, reuse=None): """Layer normalization with l2 norm.""" if filters is None: filters = shape_list(x)[-1] with tf.variable_scope(name, default_name="l2_norm", values=[x], reuse=reuse): scale = tf.get_variable( "l2_norm_scale", [filters], initializer=tf.ones_initializer()) bias = tf.get_variable( "l2_norm_bias", [filters], initializer=tf.zeros_initializer()) epsilon, scale, bias = [cast_like(t, x) for t in [epsilon, scale, bias]] mean = tf.reduce_mean(x, axis=[-1], keepdims=True) l2norm = tf.reduce_sum( tf.squared_difference(x, mean), axis=[-1], keepdims=True) norm_x = (x - mean) * tf.rsqrt(l2norm + epsilon) return norm_x * scale + bias
[ "def", "l2_norm", "(", "x", ",", "filters", "=", "None", ",", "epsilon", "=", "1e-6", ",", "name", "=", "None", ",", "reuse", "=", "None", ")", ":", "if", "filters", "is", "None", ":", "filters", "=", "shape_list", "(", "x", ")", "[", "-", "1", "]", "with", "tf", ".", "variable_scope", "(", "name", ",", "default_name", "=", "\"l2_norm\"", ",", "values", "=", "[", "x", "]", ",", "reuse", "=", "reuse", ")", ":", "scale", "=", "tf", ".", "get_variable", "(", "\"l2_norm_scale\"", ",", "[", "filters", "]", ",", "initializer", "=", "tf", ".", "ones_initializer", "(", ")", ")", "bias", "=", "tf", ".", "get_variable", "(", "\"l2_norm_bias\"", ",", "[", "filters", "]", ",", "initializer", "=", "tf", ".", "zeros_initializer", "(", ")", ")", "epsilon", ",", "scale", ",", "bias", "=", "[", "cast_like", "(", "t", ",", "x", ")", "for", "t", "in", "[", "epsilon", ",", "scale", ",", "bias", "]", "]", "mean", "=", "tf", ".", "reduce_mean", "(", "x", ",", "axis", "=", "[", "-", "1", "]", ",", "keepdims", "=", "True", ")", "l2norm", "=", "tf", ".", "reduce_sum", "(", "tf", ".", "squared_difference", "(", "x", ",", "mean", ")", ",", "axis", "=", "[", "-", "1", "]", ",", "keepdims", "=", "True", ")", "norm_x", "=", "(", "x", "-", "mean", ")", "*", "tf", ".", "rsqrt", "(", "l2norm", "+", "epsilon", ")", "return", "norm_x", "*", "scale", "+", "bias" ]
Layer normalization with l2 norm.
[ "Layer", "normalization", "with", "l2", "norm", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L724-L738
22,147
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
apply_spectral_norm
def apply_spectral_norm(x): """Normalizes x using the spectral norm. The implementation follows Algorithm 1 of https://arxiv.org/abs/1802.05957. If x is not a 2-D Tensor, then it is reshaped such that the number of channels (last-dimension) is the same. Args: x: Tensor with the last dimension equal to the number of filters. Returns: x: Tensor with the same shape as x normalized by the spectral norm. assign_op: Op to be run after every step to update the vector "u". """ weights_shape = shape_list(x) other, num_filters = tf.reduce_prod(weights_shape[:-1]), weights_shape[-1] # Reshape into a 2-D matrix with outer size num_filters. weights_2d = tf.reshape(x, (other, num_filters)) # v = Wu / ||W u|| with tf.variable_scope("u", reuse=tf.AUTO_REUSE): u = tf.get_variable( "u", [num_filters, 1], initializer=tf.truncated_normal_initializer(), trainable=False) v = tf.nn.l2_normalize(tf.matmul(weights_2d, u)) # u_new = vW / ||v W|| u_new = tf.nn.l2_normalize(tf.matmul(tf.transpose(v), weights_2d)) # s = v*W*u spectral_norm = tf.squeeze( tf.matmul(tf.transpose(v), tf.matmul(weights_2d, tf.transpose(u_new)))) # set u equal to u_new in the next iteration. assign_op = tf.assign(u, tf.transpose(u_new)) return tf.divide(x, spectral_norm), assign_op
python
def apply_spectral_norm(x): """Normalizes x using the spectral norm. The implementation follows Algorithm 1 of https://arxiv.org/abs/1802.05957. If x is not a 2-D Tensor, then it is reshaped such that the number of channels (last-dimension) is the same. Args: x: Tensor with the last dimension equal to the number of filters. Returns: x: Tensor with the same shape as x normalized by the spectral norm. assign_op: Op to be run after every step to update the vector "u". """ weights_shape = shape_list(x) other, num_filters = tf.reduce_prod(weights_shape[:-1]), weights_shape[-1] # Reshape into a 2-D matrix with outer size num_filters. weights_2d = tf.reshape(x, (other, num_filters)) # v = Wu / ||W u|| with tf.variable_scope("u", reuse=tf.AUTO_REUSE): u = tf.get_variable( "u", [num_filters, 1], initializer=tf.truncated_normal_initializer(), trainable=False) v = tf.nn.l2_normalize(tf.matmul(weights_2d, u)) # u_new = vW / ||v W|| u_new = tf.nn.l2_normalize(tf.matmul(tf.transpose(v), weights_2d)) # s = v*W*u spectral_norm = tf.squeeze( tf.matmul(tf.transpose(v), tf.matmul(weights_2d, tf.transpose(u_new)))) # set u equal to u_new in the next iteration. assign_op = tf.assign(u, tf.transpose(u_new)) return tf.divide(x, spectral_norm), assign_op
[ "def", "apply_spectral_norm", "(", "x", ")", ":", "weights_shape", "=", "shape_list", "(", "x", ")", "other", ",", "num_filters", "=", "tf", ".", "reduce_prod", "(", "weights_shape", "[", ":", "-", "1", "]", ")", ",", "weights_shape", "[", "-", "1", "]", "# Reshape into a 2-D matrix with outer size num_filters.", "weights_2d", "=", "tf", ".", "reshape", "(", "x", ",", "(", "other", ",", "num_filters", ")", ")", "# v = Wu / ||W u||", "with", "tf", ".", "variable_scope", "(", "\"u\"", ",", "reuse", "=", "tf", ".", "AUTO_REUSE", ")", ":", "u", "=", "tf", ".", "get_variable", "(", "\"u\"", ",", "[", "num_filters", ",", "1", "]", ",", "initializer", "=", "tf", ".", "truncated_normal_initializer", "(", ")", ",", "trainable", "=", "False", ")", "v", "=", "tf", ".", "nn", ".", "l2_normalize", "(", "tf", ".", "matmul", "(", "weights_2d", ",", "u", ")", ")", "# u_new = vW / ||v W||", "u_new", "=", "tf", ".", "nn", ".", "l2_normalize", "(", "tf", ".", "matmul", "(", "tf", ".", "transpose", "(", "v", ")", ",", "weights_2d", ")", ")", "# s = v*W*u", "spectral_norm", "=", "tf", ".", "squeeze", "(", "tf", ".", "matmul", "(", "tf", ".", "transpose", "(", "v", ")", ",", "tf", ".", "matmul", "(", "weights_2d", ",", "tf", ".", "transpose", "(", "u_new", ")", ")", ")", ")", "# set u equal to u_new in the next iteration.", "assign_op", "=", "tf", ".", "assign", "(", "u", ",", "tf", ".", "transpose", "(", "u_new", ")", ")", "return", "tf", ".", "divide", "(", "x", ",", "spectral_norm", ")", ",", "assign_op" ]
Normalizes x using the spectral norm. The implementation follows Algorithm 1 of https://arxiv.org/abs/1802.05957. If x is not a 2-D Tensor, then it is reshaped such that the number of channels (last-dimension) is the same. Args: x: Tensor with the last dimension equal to the number of filters. Returns: x: Tensor with the same shape as x normalized by the spectral norm. assign_op: Op to be run after every step to update the vector "u".
[ "Normalizes", "x", "using", "the", "spectral", "norm", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L741-L778
22,148
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
apply_norm
def apply_norm(x, norm_type, depth, epsilon, layer_collection=None): """Apply Normalization.""" if layer_collection is not None: assert norm_type == "layer" if norm_type == "layer": return layer_norm( x, filters=depth, epsilon=epsilon, layer_collection=layer_collection) if norm_type == "group": return group_norm(x, filters=depth, epsilon=epsilon) if norm_type == "batch": return layers().BatchNormalization(epsilon=epsilon)(x) if norm_type == "noam": return noam_norm(x, epsilon) if norm_type == "l2": return l2_norm(x, filters=depth, epsilon=epsilon) if norm_type == "none": return x raise ValueError("Parameter normalizer_fn must be one of: 'layer', 'batch'," "'noam', 'lr', 'none'.")
python
def apply_norm(x, norm_type, depth, epsilon, layer_collection=None): """Apply Normalization.""" if layer_collection is not None: assert norm_type == "layer" if norm_type == "layer": return layer_norm( x, filters=depth, epsilon=epsilon, layer_collection=layer_collection) if norm_type == "group": return group_norm(x, filters=depth, epsilon=epsilon) if norm_type == "batch": return layers().BatchNormalization(epsilon=epsilon)(x) if norm_type == "noam": return noam_norm(x, epsilon) if norm_type == "l2": return l2_norm(x, filters=depth, epsilon=epsilon) if norm_type == "none": return x raise ValueError("Parameter normalizer_fn must be one of: 'layer', 'batch'," "'noam', 'lr', 'none'.")
[ "def", "apply_norm", "(", "x", ",", "norm_type", ",", "depth", ",", "epsilon", ",", "layer_collection", "=", "None", ")", ":", "if", "layer_collection", "is", "not", "None", ":", "assert", "norm_type", "==", "\"layer\"", "if", "norm_type", "==", "\"layer\"", ":", "return", "layer_norm", "(", "x", ",", "filters", "=", "depth", ",", "epsilon", "=", "epsilon", ",", "layer_collection", "=", "layer_collection", ")", "if", "norm_type", "==", "\"group\"", ":", "return", "group_norm", "(", "x", ",", "filters", "=", "depth", ",", "epsilon", "=", "epsilon", ")", "if", "norm_type", "==", "\"batch\"", ":", "return", "layers", "(", ")", ".", "BatchNormalization", "(", "epsilon", "=", "epsilon", ")", "(", "x", ")", "if", "norm_type", "==", "\"noam\"", ":", "return", "noam_norm", "(", "x", ",", "epsilon", ")", "if", "norm_type", "==", "\"l2\"", ":", "return", "l2_norm", "(", "x", ",", "filters", "=", "depth", ",", "epsilon", "=", "epsilon", ")", "if", "norm_type", "==", "\"none\"", ":", "return", "x", "raise", "ValueError", "(", "\"Parameter normalizer_fn must be one of: 'layer', 'batch',\"", "\"'noam', 'lr', 'none'.\"", ")" ]
Apply Normalization.
[ "Apply", "Normalization", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L781-L799
22,149
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
zero_add
def zero_add(previous_value, x, name=None, reuse=None): """Resnet connection with zero initialization. Another type of resnet connection which returns previous_value + gamma * x. gamma is a trainable scalar and initialized with zero. It is useful when a module is plugged into a trained model and we want to make sure it matches the original model's performance. Args: previous_value: A tensor. x: A tensor. name: name of variable scope; defaults to zero_add. reuse: reuse scope. Returns: previous_value + gamma * x. """ with tf.variable_scope(name, default_name="zero_add", reuse=reuse): gamma = tf.get_variable("gamma", (), initializer=tf.zeros_initializer()) return previous_value + gamma * x
python
def zero_add(previous_value, x, name=None, reuse=None): """Resnet connection with zero initialization. Another type of resnet connection which returns previous_value + gamma * x. gamma is a trainable scalar and initialized with zero. It is useful when a module is plugged into a trained model and we want to make sure it matches the original model's performance. Args: previous_value: A tensor. x: A tensor. name: name of variable scope; defaults to zero_add. reuse: reuse scope. Returns: previous_value + gamma * x. """ with tf.variable_scope(name, default_name="zero_add", reuse=reuse): gamma = tf.get_variable("gamma", (), initializer=tf.zeros_initializer()) return previous_value + gamma * x
[ "def", "zero_add", "(", "previous_value", ",", "x", ",", "name", "=", "None", ",", "reuse", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ",", "default_name", "=", "\"zero_add\"", ",", "reuse", "=", "reuse", ")", ":", "gamma", "=", "tf", ".", "get_variable", "(", "\"gamma\"", ",", "(", ")", ",", "initializer", "=", "tf", ".", "zeros_initializer", "(", ")", ")", "return", "previous_value", "+", "gamma", "*", "x" ]
Resnet connection with zero initialization. Another type of resnet connection which returns previous_value + gamma * x. gamma is a trainable scalar and initialized with zero. It is useful when a module is plugged into a trained model and we want to make sure it matches the original model's performance. Args: previous_value: A tensor. x: A tensor. name: name of variable scope; defaults to zero_add. reuse: reuse scope. Returns: previous_value + gamma * x.
[ "Resnet", "connection", "with", "zero", "initialization", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L802-L821
22,150
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
layer_prepostprocess
def layer_prepostprocess(previous_value, x, sequence, dropout_rate, norm_type, depth, epsilon, default_name, name=None, dropout_broadcast_dims=None, layer_collection=None): """Apply a sequence of functions to the input or output of a layer. The sequence is specified as a string which may contain the following characters: a: add previous_value n: apply normalization d: apply dropout z: zero add For example, if sequence=="dna", then the output is previous_value + normalize(dropout(x)) Args: previous_value: A Tensor, to be added as a residual connection ('a') x: A Tensor to be transformed. sequence: a string. dropout_rate: a float norm_type: a string (see apply_norm()) depth: an integer (size of last dimension of x). epsilon: a float (parameter for normalization) default_name: a string name: a string dropout_broadcast_dims: an optional list of integers less than 3 specifying in which dimensions to broadcast the dropout decisions. saves memory. layer_collection: A tensorflow_kfac.LayerCollection. Only used by the KFAC optimizer. Default is None. Returns: a Tensor """ with tf.variable_scope(name, default_name=default_name): if sequence == "none": return x for c in sequence: if c == "a": x += previous_value elif c == "z": x = zero_add(previous_value, x) elif c == "n": x = apply_norm( x, norm_type, depth, epsilon, layer_collection=layer_collection) else: assert c == "d", ("Unknown sequence step %s" % c) x = dropout_with_broadcast_dims( x, 1.0 - dropout_rate, broadcast_dims=dropout_broadcast_dims) return x
python
def layer_prepostprocess(previous_value, x, sequence, dropout_rate, norm_type, depth, epsilon, default_name, name=None, dropout_broadcast_dims=None, layer_collection=None): """Apply a sequence of functions to the input or output of a layer. The sequence is specified as a string which may contain the following characters: a: add previous_value n: apply normalization d: apply dropout z: zero add For example, if sequence=="dna", then the output is previous_value + normalize(dropout(x)) Args: previous_value: A Tensor, to be added as a residual connection ('a') x: A Tensor to be transformed. sequence: a string. dropout_rate: a float norm_type: a string (see apply_norm()) depth: an integer (size of last dimension of x). epsilon: a float (parameter for normalization) default_name: a string name: a string dropout_broadcast_dims: an optional list of integers less than 3 specifying in which dimensions to broadcast the dropout decisions. saves memory. layer_collection: A tensorflow_kfac.LayerCollection. Only used by the KFAC optimizer. Default is None. Returns: a Tensor """ with tf.variable_scope(name, default_name=default_name): if sequence == "none": return x for c in sequence: if c == "a": x += previous_value elif c == "z": x = zero_add(previous_value, x) elif c == "n": x = apply_norm( x, norm_type, depth, epsilon, layer_collection=layer_collection) else: assert c == "d", ("Unknown sequence step %s" % c) x = dropout_with_broadcast_dims( x, 1.0 - dropout_rate, broadcast_dims=dropout_broadcast_dims) return x
[ "def", "layer_prepostprocess", "(", "previous_value", ",", "x", ",", "sequence", ",", "dropout_rate", ",", "norm_type", ",", "depth", ",", "epsilon", ",", "default_name", ",", "name", "=", "None", ",", "dropout_broadcast_dims", "=", "None", ",", "layer_collection", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ",", "default_name", "=", "default_name", ")", ":", "if", "sequence", "==", "\"none\"", ":", "return", "x", "for", "c", "in", "sequence", ":", "if", "c", "==", "\"a\"", ":", "x", "+=", "previous_value", "elif", "c", "==", "\"z\"", ":", "x", "=", "zero_add", "(", "previous_value", ",", "x", ")", "elif", "c", "==", "\"n\"", ":", "x", "=", "apply_norm", "(", "x", ",", "norm_type", ",", "depth", ",", "epsilon", ",", "layer_collection", "=", "layer_collection", ")", "else", ":", "assert", "c", "==", "\"d\"", ",", "(", "\"Unknown sequence step %s\"", "%", "c", ")", "x", "=", "dropout_with_broadcast_dims", "(", "x", ",", "1.0", "-", "dropout_rate", ",", "broadcast_dims", "=", "dropout_broadcast_dims", ")", "return", "x" ]
Apply a sequence of functions to the input or output of a layer. The sequence is specified as a string which may contain the following characters: a: add previous_value n: apply normalization d: apply dropout z: zero add For example, if sequence=="dna", then the output is previous_value + normalize(dropout(x)) Args: previous_value: A Tensor, to be added as a residual connection ('a') x: A Tensor to be transformed. sequence: a string. dropout_rate: a float norm_type: a string (see apply_norm()) depth: an integer (size of last dimension of x). epsilon: a float (parameter for normalization) default_name: a string name: a string dropout_broadcast_dims: an optional list of integers less than 3 specifying in which dimensions to broadcast the dropout decisions. saves memory. layer_collection: A tensorflow_kfac.LayerCollection. Only used by the KFAC optimizer. Default is None. Returns: a Tensor
[ "Apply", "a", "sequence", "of", "functions", "to", "the", "input", "or", "output", "of", "a", "layer", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L824-L881
22,151
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
layer_preprocess
def layer_preprocess(layer_input, hparams, layer_collection=None): """Apply layer preprocessing. See layer_prepostprocess() for details. A hyperparameters object is passed for convenience. The hyperparameters that may be used are: layer_preprocess_sequence layer_prepostprocess_dropout norm_type hidden_size norm_epsilon Args: layer_input: a Tensor hparams: a hyperparameters object. layer_collection: A tensorflow_kfac.LayerCollection. Only used by the KFAC optimizer. Default is None. Returns: a Tensor """ assert "a" not in hparams.layer_preprocess_sequence, ( "No residual connections allowed in hparams.layer_preprocess_sequence") assert "z" not in hparams.layer_preprocess_sequence, ( "No residual connections allowed in hparams.layer_preprocess_sequence") return layer_prepostprocess( None, layer_input, sequence=hparams.layer_preprocess_sequence, dropout_rate=hparams.layer_prepostprocess_dropout, norm_type=hparams.norm_type, depth=None, epsilon=hparams.norm_epsilon, dropout_broadcast_dims=comma_separated_string_to_integer_list( getattr(hparams, "layer_prepostprocess_dropout_broadcast_dims", "")), default_name="layer_prepostprocess", layer_collection=layer_collection)
python
def layer_preprocess(layer_input, hparams, layer_collection=None): """Apply layer preprocessing. See layer_prepostprocess() for details. A hyperparameters object is passed for convenience. The hyperparameters that may be used are: layer_preprocess_sequence layer_prepostprocess_dropout norm_type hidden_size norm_epsilon Args: layer_input: a Tensor hparams: a hyperparameters object. layer_collection: A tensorflow_kfac.LayerCollection. Only used by the KFAC optimizer. Default is None. Returns: a Tensor """ assert "a" not in hparams.layer_preprocess_sequence, ( "No residual connections allowed in hparams.layer_preprocess_sequence") assert "z" not in hparams.layer_preprocess_sequence, ( "No residual connections allowed in hparams.layer_preprocess_sequence") return layer_prepostprocess( None, layer_input, sequence=hparams.layer_preprocess_sequence, dropout_rate=hparams.layer_prepostprocess_dropout, norm_type=hparams.norm_type, depth=None, epsilon=hparams.norm_epsilon, dropout_broadcast_dims=comma_separated_string_to_integer_list( getattr(hparams, "layer_prepostprocess_dropout_broadcast_dims", "")), default_name="layer_prepostprocess", layer_collection=layer_collection)
[ "def", "layer_preprocess", "(", "layer_input", ",", "hparams", ",", "layer_collection", "=", "None", ")", ":", "assert", "\"a\"", "not", "in", "hparams", ".", "layer_preprocess_sequence", ",", "(", "\"No residual connections allowed in hparams.layer_preprocess_sequence\"", ")", "assert", "\"z\"", "not", "in", "hparams", ".", "layer_preprocess_sequence", ",", "(", "\"No residual connections allowed in hparams.layer_preprocess_sequence\"", ")", "return", "layer_prepostprocess", "(", "None", ",", "layer_input", ",", "sequence", "=", "hparams", ".", "layer_preprocess_sequence", ",", "dropout_rate", "=", "hparams", ".", "layer_prepostprocess_dropout", ",", "norm_type", "=", "hparams", ".", "norm_type", ",", "depth", "=", "None", ",", "epsilon", "=", "hparams", ".", "norm_epsilon", ",", "dropout_broadcast_dims", "=", "comma_separated_string_to_integer_list", "(", "getattr", "(", "hparams", ",", "\"layer_prepostprocess_dropout_broadcast_dims\"", ",", "\"\"", ")", ")", ",", "default_name", "=", "\"layer_prepostprocess\"", ",", "layer_collection", "=", "layer_collection", ")" ]
Apply layer preprocessing. See layer_prepostprocess() for details. A hyperparameters object is passed for convenience. The hyperparameters that may be used are: layer_preprocess_sequence layer_prepostprocess_dropout norm_type hidden_size norm_epsilon Args: layer_input: a Tensor hparams: a hyperparameters object. layer_collection: A tensorflow_kfac.LayerCollection. Only used by the KFAC optimizer. Default is None. Returns: a Tensor
[ "Apply", "layer", "preprocessing", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L884-L922
22,152
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
layer_postprocess
def layer_postprocess(layer_input, layer_output, hparams): """Apply layer postprocessing. See layer_prepostprocess() for details. A hyperparameters object is passed for convenience. The hyperparameters that may be used are: layer_postprocess_sequence layer_prepostprocess_dropout norm_type hidden_size norm_epsilon Args: layer_input: a Tensor layer_output: a Tensor hparams: a hyperparameters object. Returns: a Tensor """ return layer_prepostprocess( layer_input, layer_output, sequence=hparams.layer_postprocess_sequence, dropout_rate=hparams.layer_prepostprocess_dropout, norm_type=hparams.norm_type, depth=None, epsilon=hparams.norm_epsilon, dropout_broadcast_dims=comma_separated_string_to_integer_list( getattr(hparams, "layer_prepostprocess_dropout_broadcast_dims", "")), default_name="layer_postprocess")
python
def layer_postprocess(layer_input, layer_output, hparams): """Apply layer postprocessing. See layer_prepostprocess() for details. A hyperparameters object is passed for convenience. The hyperparameters that may be used are: layer_postprocess_sequence layer_prepostprocess_dropout norm_type hidden_size norm_epsilon Args: layer_input: a Tensor layer_output: a Tensor hparams: a hyperparameters object. Returns: a Tensor """ return layer_prepostprocess( layer_input, layer_output, sequence=hparams.layer_postprocess_sequence, dropout_rate=hparams.layer_prepostprocess_dropout, norm_type=hparams.norm_type, depth=None, epsilon=hparams.norm_epsilon, dropout_broadcast_dims=comma_separated_string_to_integer_list( getattr(hparams, "layer_prepostprocess_dropout_broadcast_dims", "")), default_name="layer_postprocess")
[ "def", "layer_postprocess", "(", "layer_input", ",", "layer_output", ",", "hparams", ")", ":", "return", "layer_prepostprocess", "(", "layer_input", ",", "layer_output", ",", "sequence", "=", "hparams", ".", "layer_postprocess_sequence", ",", "dropout_rate", "=", "hparams", ".", "layer_prepostprocess_dropout", ",", "norm_type", "=", "hparams", ".", "norm_type", ",", "depth", "=", "None", ",", "epsilon", "=", "hparams", ".", "norm_epsilon", ",", "dropout_broadcast_dims", "=", "comma_separated_string_to_integer_list", "(", "getattr", "(", "hparams", ",", "\"layer_prepostprocess_dropout_broadcast_dims\"", ",", "\"\"", ")", ")", ",", "default_name", "=", "\"layer_postprocess\"", ")" ]
Apply layer postprocessing. See layer_prepostprocess() for details. A hyperparameters object is passed for convenience. The hyperparameters that may be used are: layer_postprocess_sequence layer_prepostprocess_dropout norm_type hidden_size norm_epsilon Args: layer_input: a Tensor layer_output: a Tensor hparams: a hyperparameters object. Returns: a Tensor
[ "Apply", "layer", "postprocessing", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L925-L957
22,153
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
conv_block_internal
def conv_block_internal(conv_fn, inputs, filters, dilation_rates_and_kernel_sizes, first_relu=True, use_elu=False, separabilities=None, **kwargs): """A block of convolutions. Args: conv_fn: convolution function, e.g. conv or separable_conv. inputs: a Tensor filters: an Integer dilation_rates_and_kernel_sizes: a list of tuples (dilation, (k_w, k_h)) first_relu: whether to do a relu at start (defaults to True) use_elu: whether to use ELUs instead of ReLUs (defaults to False) separabilities: list of separability factors (per-layer). **kwargs: additional arguments (e.g., pooling) Returns: a Tensor. """ name = kwargs.pop("name") if "name" in kwargs else None mask = kwargs.pop("mask") if "mask" in kwargs else None # Usage for normalize_fn kwarg: # if not specified, use layer norm # if given normalize_fn=None, don't use any normalization # if given normalize_fn=norm, use the specified norm function use_layer_norm = "normalizer_fn" not in kwargs norm = kwargs.pop("normalizer_fn", None) use_normalizer_fn = use_layer_norm or norm if use_layer_norm: norm = lambda x, name: layer_norm(x, filters, name=name) with tf.variable_scope(name, "conv_block", [inputs]): cur, counter = inputs, -1 for dilation_rate, kernel_size in dilation_rates_and_kernel_sizes: counter += 1 if first_relu or counter > 0: cur = tf.nn.elu(cur) if use_elu else tf.nn.relu(cur) if mask is not None: cur *= mask if separabilities: cur = conv_fn( cur, filters, kernel_size, dilation_rate=dilation_rate, name="conv_block_%d" % counter, use_bias=norm is None, separability=separabilities[counter], **kwargs) else: cur = conv_fn( cur, filters, kernel_size, dilation_rate=dilation_rate, name="conv_block_%d" % counter, use_bias=norm is None, **kwargs) if use_normalizer_fn: cur = norm(cur, name="conv_block_norm_%d" % counter) return cur
python
def conv_block_internal(conv_fn, inputs, filters, dilation_rates_and_kernel_sizes, first_relu=True, use_elu=False, separabilities=None, **kwargs): """A block of convolutions. Args: conv_fn: convolution function, e.g. conv or separable_conv. inputs: a Tensor filters: an Integer dilation_rates_and_kernel_sizes: a list of tuples (dilation, (k_w, k_h)) first_relu: whether to do a relu at start (defaults to True) use_elu: whether to use ELUs instead of ReLUs (defaults to False) separabilities: list of separability factors (per-layer). **kwargs: additional arguments (e.g., pooling) Returns: a Tensor. """ name = kwargs.pop("name") if "name" in kwargs else None mask = kwargs.pop("mask") if "mask" in kwargs else None # Usage for normalize_fn kwarg: # if not specified, use layer norm # if given normalize_fn=None, don't use any normalization # if given normalize_fn=norm, use the specified norm function use_layer_norm = "normalizer_fn" not in kwargs norm = kwargs.pop("normalizer_fn", None) use_normalizer_fn = use_layer_norm or norm if use_layer_norm: norm = lambda x, name: layer_norm(x, filters, name=name) with tf.variable_scope(name, "conv_block", [inputs]): cur, counter = inputs, -1 for dilation_rate, kernel_size in dilation_rates_and_kernel_sizes: counter += 1 if first_relu or counter > 0: cur = tf.nn.elu(cur) if use_elu else tf.nn.relu(cur) if mask is not None: cur *= mask if separabilities: cur = conv_fn( cur, filters, kernel_size, dilation_rate=dilation_rate, name="conv_block_%d" % counter, use_bias=norm is None, separability=separabilities[counter], **kwargs) else: cur = conv_fn( cur, filters, kernel_size, dilation_rate=dilation_rate, name="conv_block_%d" % counter, use_bias=norm is None, **kwargs) if use_normalizer_fn: cur = norm(cur, name="conv_block_norm_%d" % counter) return cur
[ "def", "conv_block_internal", "(", "conv_fn", ",", "inputs", ",", "filters", ",", "dilation_rates_and_kernel_sizes", ",", "first_relu", "=", "True", ",", "use_elu", "=", "False", ",", "separabilities", "=", "None", ",", "*", "*", "kwargs", ")", ":", "name", "=", "kwargs", ".", "pop", "(", "\"name\"", ")", "if", "\"name\"", "in", "kwargs", "else", "None", "mask", "=", "kwargs", ".", "pop", "(", "\"mask\"", ")", "if", "\"mask\"", "in", "kwargs", "else", "None", "# Usage for normalize_fn kwarg:", "# if not specified, use layer norm", "# if given normalize_fn=None, don't use any normalization", "# if given normalize_fn=norm, use the specified norm function", "use_layer_norm", "=", "\"normalizer_fn\"", "not", "in", "kwargs", "norm", "=", "kwargs", ".", "pop", "(", "\"normalizer_fn\"", ",", "None", ")", "use_normalizer_fn", "=", "use_layer_norm", "or", "norm", "if", "use_layer_norm", ":", "norm", "=", "lambda", "x", ",", "name", ":", "layer_norm", "(", "x", ",", "filters", ",", "name", "=", "name", ")", "with", "tf", ".", "variable_scope", "(", "name", ",", "\"conv_block\"", ",", "[", "inputs", "]", ")", ":", "cur", ",", "counter", "=", "inputs", ",", "-", "1", "for", "dilation_rate", ",", "kernel_size", "in", "dilation_rates_and_kernel_sizes", ":", "counter", "+=", "1", "if", "first_relu", "or", "counter", ">", "0", ":", "cur", "=", "tf", ".", "nn", ".", "elu", "(", "cur", ")", "if", "use_elu", "else", "tf", ".", "nn", ".", "relu", "(", "cur", ")", "if", "mask", "is", "not", "None", ":", "cur", "*=", "mask", "if", "separabilities", ":", "cur", "=", "conv_fn", "(", "cur", ",", "filters", ",", "kernel_size", ",", "dilation_rate", "=", "dilation_rate", ",", "name", "=", "\"conv_block_%d\"", "%", "counter", ",", "use_bias", "=", "norm", "is", "None", ",", "separability", "=", "separabilities", "[", "counter", "]", ",", "*", "*", "kwargs", ")", "else", ":", "cur", "=", "conv_fn", "(", "cur", ",", "filters", ",", "kernel_size", ",", "dilation_rate", "=", "dilation_rate", ",", "name", "=", "\"conv_block_%d\"", "%", "counter", ",", "use_bias", "=", "norm", "is", "None", ",", "*", "*", "kwargs", ")", "if", "use_normalizer_fn", ":", "cur", "=", "norm", "(", "cur", ",", "name", "=", "\"conv_block_norm_%d\"", "%", "counter", ")", "return", "cur" ]
A block of convolutions. Args: conv_fn: convolution function, e.g. conv or separable_conv. inputs: a Tensor filters: an Integer dilation_rates_and_kernel_sizes: a list of tuples (dilation, (k_w, k_h)) first_relu: whether to do a relu at start (defaults to True) use_elu: whether to use ELUs instead of ReLUs (defaults to False) separabilities: list of separability factors (per-layer). **kwargs: additional arguments (e.g., pooling) Returns: a Tensor.
[ "A", "block", "of", "convolutions", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L960-L1028
22,154
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
conv_block
def conv_block(inputs, filters, dilation_rates_and_kernel_sizes, **kwargs): """A block of standard 2d convolutions.""" return conv_block_internal(conv, inputs, filters, dilation_rates_and_kernel_sizes, **kwargs)
python
def conv_block(inputs, filters, dilation_rates_and_kernel_sizes, **kwargs): """A block of standard 2d convolutions.""" return conv_block_internal(conv, inputs, filters, dilation_rates_and_kernel_sizes, **kwargs)
[ "def", "conv_block", "(", "inputs", ",", "filters", ",", "dilation_rates_and_kernel_sizes", ",", "*", "*", "kwargs", ")", ":", "return", "conv_block_internal", "(", "conv", ",", "inputs", ",", "filters", ",", "dilation_rates_and_kernel_sizes", ",", "*", "*", "kwargs", ")" ]
A block of standard 2d convolutions.
[ "A", "block", "of", "standard", "2d", "convolutions", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L1031-L1034
22,155
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
conv1d_block
def conv1d_block(inputs, filters, dilation_rates_and_kernel_sizes, **kwargs): """A block of standard 1d convolutions.""" return conv_block_internal(conv1d, inputs, filters, dilation_rates_and_kernel_sizes, **kwargs)
python
def conv1d_block(inputs, filters, dilation_rates_and_kernel_sizes, **kwargs): """A block of standard 1d convolutions.""" return conv_block_internal(conv1d, inputs, filters, dilation_rates_and_kernel_sizes, **kwargs)
[ "def", "conv1d_block", "(", "inputs", ",", "filters", ",", "dilation_rates_and_kernel_sizes", ",", "*", "*", "kwargs", ")", ":", "return", "conv_block_internal", "(", "conv1d", ",", "inputs", ",", "filters", ",", "dilation_rates_and_kernel_sizes", ",", "*", "*", "kwargs", ")" ]
A block of standard 1d convolutions.
[ "A", "block", "of", "standard", "1d", "convolutions", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L1037-L1040
22,156
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
conv_block_downsample
def conv_block_downsample(x, kernel, strides, padding, separability=0, name=None, reuse=None): """Implements a downwards-striding conv block, like Xception exit flow.""" with tf.variable_scope( name, default_name="conv_block_downsample", values=[x], reuse=reuse): hidden_size = int(x.get_shape()[-1]) res = conv_block( x, int(1.25 * hidden_size), [((1, 1), kernel)], padding=padding, strides=strides, name="res_conv") x = subseparable_conv_block( x, hidden_size, [((1, 1), kernel)], padding=padding, separability=separability, name="conv0") x = subseparable_conv_block( x, int(1.25 * hidden_size), [((1, 1), kernel)], padding=padding, separability=separability, name="conv1") x = pool(x, kernel, "MAX", padding, strides=strides) x += res x = subseparable_conv_block( x, 2 * hidden_size, [((1, 1), kernel)], first_relu=False, padding=padding, separability=separability, name="conv2") x = subseparable_conv_block( x, int(2.5 * hidden_size), [((1, 1), kernel)], padding=padding, separability=separability, name="conv3") return x
python
def conv_block_downsample(x, kernel, strides, padding, separability=0, name=None, reuse=None): """Implements a downwards-striding conv block, like Xception exit flow.""" with tf.variable_scope( name, default_name="conv_block_downsample", values=[x], reuse=reuse): hidden_size = int(x.get_shape()[-1]) res = conv_block( x, int(1.25 * hidden_size), [((1, 1), kernel)], padding=padding, strides=strides, name="res_conv") x = subseparable_conv_block( x, hidden_size, [((1, 1), kernel)], padding=padding, separability=separability, name="conv0") x = subseparable_conv_block( x, int(1.25 * hidden_size), [((1, 1), kernel)], padding=padding, separability=separability, name="conv1") x = pool(x, kernel, "MAX", padding, strides=strides) x += res x = subseparable_conv_block( x, 2 * hidden_size, [((1, 1), kernel)], first_relu=False, padding=padding, separability=separability, name="conv2") x = subseparable_conv_block( x, int(2.5 * hidden_size), [((1, 1), kernel)], padding=padding, separability=separability, name="conv3") return x
[ "def", "conv_block_downsample", "(", "x", ",", "kernel", ",", "strides", ",", "padding", ",", "separability", "=", "0", ",", "name", "=", "None", ",", "reuse", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ",", "default_name", "=", "\"conv_block_downsample\"", ",", "values", "=", "[", "x", "]", ",", "reuse", "=", "reuse", ")", ":", "hidden_size", "=", "int", "(", "x", ".", "get_shape", "(", ")", "[", "-", "1", "]", ")", "res", "=", "conv_block", "(", "x", ",", "int", "(", "1.25", "*", "hidden_size", ")", ",", "[", "(", "(", "1", ",", "1", ")", ",", "kernel", ")", "]", ",", "padding", "=", "padding", ",", "strides", "=", "strides", ",", "name", "=", "\"res_conv\"", ")", "x", "=", "subseparable_conv_block", "(", "x", ",", "hidden_size", ",", "[", "(", "(", "1", ",", "1", ")", ",", "kernel", ")", "]", ",", "padding", "=", "padding", ",", "separability", "=", "separability", ",", "name", "=", "\"conv0\"", ")", "x", "=", "subseparable_conv_block", "(", "x", ",", "int", "(", "1.25", "*", "hidden_size", ")", ",", "[", "(", "(", "1", ",", "1", ")", ",", "kernel", ")", "]", ",", "padding", "=", "padding", ",", "separability", "=", "separability", ",", "name", "=", "\"conv1\"", ")", "x", "=", "pool", "(", "x", ",", "kernel", ",", "\"MAX\"", ",", "padding", ",", "strides", "=", "strides", ")", "x", "+=", "res", "x", "=", "subseparable_conv_block", "(", "x", ",", "2", "*", "hidden_size", ",", "[", "(", "(", "1", ",", "1", ")", ",", "kernel", ")", "]", ",", "first_relu", "=", "False", ",", "padding", "=", "padding", ",", "separability", "=", "separability", ",", "name", "=", "\"conv2\"", ")", "x", "=", "subseparable_conv_block", "(", "x", ",", "int", "(", "2.5", "*", "hidden_size", ")", ",", "[", "(", "(", "1", ",", "1", ")", ",", "kernel", ")", "]", ",", "padding", "=", "padding", ",", "separability", "=", "separability", ",", "name", "=", "\"conv3\"", ")", "return", "x" ]
Implements a downwards-striding conv block, like Xception exit flow.
[ "Implements", "a", "downwards", "-", "striding", "conv", "block", "like", "Xception", "exit", "flow", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L1083-L1130
22,157
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
get_timing_signal
def get_timing_signal(length, min_timescale=1, max_timescale=1e4, num_timescales=16): """Create Tensor of sinusoids of different frequencies. Args: length: Length of the Tensor to create, i.e. Number of steps. min_timescale: a float max_timescale: a float num_timescales: an int Returns: Tensor of shape (length, 2*num_timescales) """ positions = to_float(tf.range(length)) log_timescale_increment = ( math.log(max_timescale / min_timescale) / (num_timescales - 1)) inv_timescales = min_timescale * tf.exp( to_float(tf.range(num_timescales)) * -log_timescale_increment) scaled_time = tf.expand_dims(positions, 1) * tf.expand_dims(inv_timescales, 0) return tf.concat([tf.sin(scaled_time), tf.cos(scaled_time)], axis=1)
python
def get_timing_signal(length, min_timescale=1, max_timescale=1e4, num_timescales=16): """Create Tensor of sinusoids of different frequencies. Args: length: Length of the Tensor to create, i.e. Number of steps. min_timescale: a float max_timescale: a float num_timescales: an int Returns: Tensor of shape (length, 2*num_timescales) """ positions = to_float(tf.range(length)) log_timescale_increment = ( math.log(max_timescale / min_timescale) / (num_timescales - 1)) inv_timescales = min_timescale * tf.exp( to_float(tf.range(num_timescales)) * -log_timescale_increment) scaled_time = tf.expand_dims(positions, 1) * tf.expand_dims(inv_timescales, 0) return tf.concat([tf.sin(scaled_time), tf.cos(scaled_time)], axis=1)
[ "def", "get_timing_signal", "(", "length", ",", "min_timescale", "=", "1", ",", "max_timescale", "=", "1e4", ",", "num_timescales", "=", "16", ")", ":", "positions", "=", "to_float", "(", "tf", ".", "range", "(", "length", ")", ")", "log_timescale_increment", "=", "(", "math", ".", "log", "(", "max_timescale", "/", "min_timescale", ")", "/", "(", "num_timescales", "-", "1", ")", ")", "inv_timescales", "=", "min_timescale", "*", "tf", ".", "exp", "(", "to_float", "(", "tf", ".", "range", "(", "num_timescales", ")", ")", "*", "-", "log_timescale_increment", ")", "scaled_time", "=", "tf", ".", "expand_dims", "(", "positions", ",", "1", ")", "*", "tf", ".", "expand_dims", "(", "inv_timescales", ",", "0", ")", "return", "tf", ".", "concat", "(", "[", "tf", ".", "sin", "(", "scaled_time", ")", ",", "tf", ".", "cos", "(", "scaled_time", ")", "]", ",", "axis", "=", "1", ")" ]
Create Tensor of sinusoids of different frequencies. Args: length: Length of the Tensor to create, i.e. Number of steps. min_timescale: a float max_timescale: a float num_timescales: an int Returns: Tensor of shape (length, 2*num_timescales)
[ "Create", "Tensor", "of", "sinusoids", "of", "different", "frequencies", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L1133-L1154
22,158
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
mask_from_embedding
def mask_from_embedding(emb): """Input embeddings -> padding mask. We have hacked symbol_modality to return all-zero embeddings for padding. Returns a mask with 0.0 in the padding positions and 1.0 elsewhere. Args: emb: a Tensor with shape [batch, width, height, depth]. Returns: a 0.0/1.0 Tensor with shape [batch, width, height, 1]. """ return weights_nonzero(tf.reduce_sum(tf.abs(emb), axis=3, keepdims=True))
python
def mask_from_embedding(emb): """Input embeddings -> padding mask. We have hacked symbol_modality to return all-zero embeddings for padding. Returns a mask with 0.0 in the padding positions and 1.0 elsewhere. Args: emb: a Tensor with shape [batch, width, height, depth]. Returns: a 0.0/1.0 Tensor with shape [batch, width, height, 1]. """ return weights_nonzero(tf.reduce_sum(tf.abs(emb), axis=3, keepdims=True))
[ "def", "mask_from_embedding", "(", "emb", ")", ":", "return", "weights_nonzero", "(", "tf", ".", "reduce_sum", "(", "tf", ".", "abs", "(", "emb", ")", ",", "axis", "=", "3", ",", "keepdims", "=", "True", ")", ")" ]
Input embeddings -> padding mask. We have hacked symbol_modality to return all-zero embeddings for padding. Returns a mask with 0.0 in the padding positions and 1.0 elsewhere. Args: emb: a Tensor with shape [batch, width, height, depth]. Returns: a 0.0/1.0 Tensor with shape [batch, width, height, 1].
[ "Input", "embeddings", "-", ">", "padding", "mask", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L1191-L1202
22,159
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
length_from_embedding
def length_from_embedding(emb): """Compute the length of each sequence in the batch. Args: emb: a sequence embedding Tensor with shape [batch, max_time, 1, depth]. Returns: a Tensor with shape [batch]. """ return tf.cast(tf.reduce_sum(mask_from_embedding(emb), [1, 2, 3]), tf.int32)
python
def length_from_embedding(emb): """Compute the length of each sequence in the batch. Args: emb: a sequence embedding Tensor with shape [batch, max_time, 1, depth]. Returns: a Tensor with shape [batch]. """ return tf.cast(tf.reduce_sum(mask_from_embedding(emb), [1, 2, 3]), tf.int32)
[ "def", "length_from_embedding", "(", "emb", ")", ":", "return", "tf", ".", "cast", "(", "tf", ".", "reduce_sum", "(", "mask_from_embedding", "(", "emb", ")", ",", "[", "1", ",", "2", ",", "3", "]", ")", ",", "tf", ".", "int32", ")" ]
Compute the length of each sequence in the batch. Args: emb: a sequence embedding Tensor with shape [batch, max_time, 1, depth]. Returns: a Tensor with shape [batch].
[ "Compute", "the", "length", "of", "each", "sequence", "in", "the", "batch", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L1205-L1213
22,160
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
maybe_zero_out_padding
def maybe_zero_out_padding(inputs, kernel_size, nonpadding_mask): """If necessary, zero out inputs to a conv for padding positions. Args: inputs: a Tensor with shape [batch, length, ...] kernel_size: an integer or pair of integers nonpadding_mask: a Tensor with shape [batch, length] Returns: Tensor of the same shape as inputs. """ if (kernel_size != 1 and kernel_size != (1, 1) and nonpadding_mask is not None): while nonpadding_mask.get_shape().ndims < inputs.get_shape().ndims: nonpadding_mask = tf.expand_dims(nonpadding_mask, -1) return inputs * nonpadding_mask return inputs
python
def maybe_zero_out_padding(inputs, kernel_size, nonpadding_mask): """If necessary, zero out inputs to a conv for padding positions. Args: inputs: a Tensor with shape [batch, length, ...] kernel_size: an integer or pair of integers nonpadding_mask: a Tensor with shape [batch, length] Returns: Tensor of the same shape as inputs. """ if (kernel_size != 1 and kernel_size != (1, 1) and nonpadding_mask is not None): while nonpadding_mask.get_shape().ndims < inputs.get_shape().ndims: nonpadding_mask = tf.expand_dims(nonpadding_mask, -1) return inputs * nonpadding_mask return inputs
[ "def", "maybe_zero_out_padding", "(", "inputs", ",", "kernel_size", ",", "nonpadding_mask", ")", ":", "if", "(", "kernel_size", "!=", "1", "and", "kernel_size", "!=", "(", "1", ",", "1", ")", "and", "nonpadding_mask", "is", "not", "None", ")", ":", "while", "nonpadding_mask", ".", "get_shape", "(", ")", ".", "ndims", "<", "inputs", ".", "get_shape", "(", ")", ".", "ndims", ":", "nonpadding_mask", "=", "tf", ".", "expand_dims", "(", "nonpadding_mask", ",", "-", "1", ")", "return", "inputs", "*", "nonpadding_mask", "return", "inputs" ]
If necessary, zero out inputs to a conv for padding positions. Args: inputs: a Tensor with shape [batch, length, ...] kernel_size: an integer or pair of integers nonpadding_mask: a Tensor with shape [batch, length] Returns: Tensor of the same shape as inputs.
[ "If", "necessary", "zero", "out", "inputs", "to", "a", "conv", "for", "padding", "positions", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L1250-L1267
22,161
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
dense_dropconnect
def dense_dropconnect(inputs, output_size, dropconnect_dropout=0.0, name="dense_dropconnect", **kwargs): """Dense layer with dropconnect.""" if dropconnect_dropout != 0.0: tf.logging.info("Applying dropconnect as the kernel regularization.") kwargs["kernel_regularizer"] = functools.partial( tf.nn.dropout, keep_prob=1.0 - dropconnect_dropout) return dense(inputs, output_size, use_bias=True, name=name, **kwargs)
python
def dense_dropconnect(inputs, output_size, dropconnect_dropout=0.0, name="dense_dropconnect", **kwargs): """Dense layer with dropconnect.""" if dropconnect_dropout != 0.0: tf.logging.info("Applying dropconnect as the kernel regularization.") kwargs["kernel_regularizer"] = functools.partial( tf.nn.dropout, keep_prob=1.0 - dropconnect_dropout) return dense(inputs, output_size, use_bias=True, name=name, **kwargs)
[ "def", "dense_dropconnect", "(", "inputs", ",", "output_size", ",", "dropconnect_dropout", "=", "0.0", ",", "name", "=", "\"dense_dropconnect\"", ",", "*", "*", "kwargs", ")", ":", "if", "dropconnect_dropout", "!=", "0.0", ":", "tf", ".", "logging", ".", "info", "(", "\"Applying dropconnect as the kernel regularization.\"", ")", "kwargs", "[", "\"kernel_regularizer\"", "]", "=", "functools", ".", "partial", "(", "tf", ".", "nn", ".", "dropout", ",", "keep_prob", "=", "1.0", "-", "dropconnect_dropout", ")", "return", "dense", "(", "inputs", ",", "output_size", ",", "use_bias", "=", "True", ",", "name", "=", "name", ",", "*", "*", "kwargs", ")" ]
Dense layer with dropconnect.
[ "Dense", "layer", "with", "dropconnect", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L1303-L1315
22,162
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
conv_gru
def conv_gru(x, kernel_size, filters, padding="SAME", dilation_rate=(1, 1), name=None, reuse=None): """Convolutional GRU in 1 dimension.""" # Let's make a shorthand for conv call first. def do_conv(args, name, bias_start, padding): return conv( args, filters, kernel_size, padding=padding, dilation_rate=dilation_rate, bias_initializer=tf.constant_initializer(bias_start), name=name) # Here comes the GRU gate. with tf.variable_scope( name, default_name="conv_gru", values=[x], reuse=reuse): reset = saturating_sigmoid(do_conv(x, "reset", 1.0, padding)) gate = saturating_sigmoid(do_conv(x, "gate", 1.0, padding)) candidate = tf.tanh(do_conv(reset * x, "candidate", 0.0, padding)) return gate * x + (1 - gate) * candidate
python
def conv_gru(x, kernel_size, filters, padding="SAME", dilation_rate=(1, 1), name=None, reuse=None): """Convolutional GRU in 1 dimension.""" # Let's make a shorthand for conv call first. def do_conv(args, name, bias_start, padding): return conv( args, filters, kernel_size, padding=padding, dilation_rate=dilation_rate, bias_initializer=tf.constant_initializer(bias_start), name=name) # Here comes the GRU gate. with tf.variable_scope( name, default_name="conv_gru", values=[x], reuse=reuse): reset = saturating_sigmoid(do_conv(x, "reset", 1.0, padding)) gate = saturating_sigmoid(do_conv(x, "gate", 1.0, padding)) candidate = tf.tanh(do_conv(reset * x, "candidate", 0.0, padding)) return gate * x + (1 - gate) * candidate
[ "def", "conv_gru", "(", "x", ",", "kernel_size", ",", "filters", ",", "padding", "=", "\"SAME\"", ",", "dilation_rate", "=", "(", "1", ",", "1", ")", ",", "name", "=", "None", ",", "reuse", "=", "None", ")", ":", "# Let's make a shorthand for conv call first.", "def", "do_conv", "(", "args", ",", "name", ",", "bias_start", ",", "padding", ")", ":", "return", "conv", "(", "args", ",", "filters", ",", "kernel_size", ",", "padding", "=", "padding", ",", "dilation_rate", "=", "dilation_rate", ",", "bias_initializer", "=", "tf", ".", "constant_initializer", "(", "bias_start", ")", ",", "name", "=", "name", ")", "# Here comes the GRU gate.", "with", "tf", ".", "variable_scope", "(", "name", ",", "default_name", "=", "\"conv_gru\"", ",", "values", "=", "[", "x", "]", ",", "reuse", "=", "reuse", ")", ":", "reset", "=", "saturating_sigmoid", "(", "do_conv", "(", "x", ",", "\"reset\"", ",", "1.0", ",", "padding", ")", ")", "gate", "=", "saturating_sigmoid", "(", "do_conv", "(", "x", ",", "\"gate\"", ",", "1.0", ",", "padding", ")", ")", "candidate", "=", "tf", ".", "tanh", "(", "do_conv", "(", "reset", "*", "x", ",", "\"candidate\"", ",", "0.0", ",", "padding", ")", ")", "return", "gate", "*", "x", "+", "(", "1", "-", "gate", ")", "*", "candidate" ]
Convolutional GRU in 1 dimension.
[ "Convolutional", "GRU", "in", "1", "dimension", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L1452-L1478
22,163
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
gru_feedfwd
def gru_feedfwd(a_t, h_prev, filters, name=None): """position-wise Feed-fwd GRU gates following the MPNN. Args: a_t: Tensor of shape [batch, length, depth] of current input h_prev: Tensor of shape [batch, length, depth] of prev input filters: an integer specifying number of dimensions of the filters name: A string Returns: h_t: [batch, length, filters] hidden state """ with tf.variable_scope(name, default_name="GRU", values=[a_t, h_prev]): # we use right matrix multiplication to handle batches # W_z and W_r have shape 2d, d. U_z U_r have shape d,d z_t = ( tf.sigmoid( tpu_conv1d(a_t, filters, 1, padding="SAME", name="W_z") + tpu_conv1d(h_prev, filters, 1, padding="SAME", name="U_z"))) r_t = ( tf.sigmoid( tpu_conv1d(a_t, filters, 1, padding="SAME", name="W_r") + tpu_conv1d(h_prev, filters, 1, padding="SAME", name="U_r"))) h_tilde = ( tf.tanh( tpu_conv1d(a_t, filters, 1, padding="SAME", name="W") + tpu_conv1d(r_t * h_prev, filters, 1, padding="SAME", name="U"))) h_t = (1. - z_t) * h_prev + z_t * h_tilde return h_t
python
def gru_feedfwd(a_t, h_prev, filters, name=None): """position-wise Feed-fwd GRU gates following the MPNN. Args: a_t: Tensor of shape [batch, length, depth] of current input h_prev: Tensor of shape [batch, length, depth] of prev input filters: an integer specifying number of dimensions of the filters name: A string Returns: h_t: [batch, length, filters] hidden state """ with tf.variable_scope(name, default_name="GRU", values=[a_t, h_prev]): # we use right matrix multiplication to handle batches # W_z and W_r have shape 2d, d. U_z U_r have shape d,d z_t = ( tf.sigmoid( tpu_conv1d(a_t, filters, 1, padding="SAME", name="W_z") + tpu_conv1d(h_prev, filters, 1, padding="SAME", name="U_z"))) r_t = ( tf.sigmoid( tpu_conv1d(a_t, filters, 1, padding="SAME", name="W_r") + tpu_conv1d(h_prev, filters, 1, padding="SAME", name="U_r"))) h_tilde = ( tf.tanh( tpu_conv1d(a_t, filters, 1, padding="SAME", name="W") + tpu_conv1d(r_t * h_prev, filters, 1, padding="SAME", name="U"))) h_t = (1. - z_t) * h_prev + z_t * h_tilde return h_t
[ "def", "gru_feedfwd", "(", "a_t", ",", "h_prev", ",", "filters", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ",", "default_name", "=", "\"GRU\"", ",", "values", "=", "[", "a_t", ",", "h_prev", "]", ")", ":", "# we use right matrix multiplication to handle batches", "# W_z and W_r have shape 2d, d. U_z U_r have shape d,d", "z_t", "=", "(", "tf", ".", "sigmoid", "(", "tpu_conv1d", "(", "a_t", ",", "filters", ",", "1", ",", "padding", "=", "\"SAME\"", ",", "name", "=", "\"W_z\"", ")", "+", "tpu_conv1d", "(", "h_prev", ",", "filters", ",", "1", ",", "padding", "=", "\"SAME\"", ",", "name", "=", "\"U_z\"", ")", ")", ")", "r_t", "=", "(", "tf", ".", "sigmoid", "(", "tpu_conv1d", "(", "a_t", ",", "filters", ",", "1", ",", "padding", "=", "\"SAME\"", ",", "name", "=", "\"W_r\"", ")", "+", "tpu_conv1d", "(", "h_prev", ",", "filters", ",", "1", ",", "padding", "=", "\"SAME\"", ",", "name", "=", "\"U_r\"", ")", ")", ")", "h_tilde", "=", "(", "tf", ".", "tanh", "(", "tpu_conv1d", "(", "a_t", ",", "filters", ",", "1", ",", "padding", "=", "\"SAME\"", ",", "name", "=", "\"W\"", ")", "+", "tpu_conv1d", "(", "r_t", "*", "h_prev", ",", "filters", ",", "1", ",", "padding", "=", "\"SAME\"", ",", "name", "=", "\"U\"", ")", ")", ")", "h_t", "=", "(", "1.", "-", "z_t", ")", "*", "h_prev", "+", "z_t", "*", "h_tilde", "return", "h_t" ]
position-wise Feed-fwd GRU gates following the MPNN. Args: a_t: Tensor of shape [batch, length, depth] of current input h_prev: Tensor of shape [batch, length, depth] of prev input filters: an integer specifying number of dimensions of the filters name: A string Returns: h_t: [batch, length, filters] hidden state
[ "position", "-", "wise", "Feed", "-", "fwd", "GRU", "gates", "following", "the", "MPNN", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L1481-L1510
22,164
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
conv_lstm
def conv_lstm(x, kernel_size, filters, padding="SAME", dilation_rate=(1, 1), name=None, reuse=None): """Convolutional LSTM in 1 dimension.""" with tf.variable_scope( name, default_name="conv_lstm", values=[x], reuse=reuse): gates = conv( x, 4 * filters, kernel_size, padding=padding, dilation_rate=dilation_rate) g = tf.split(layer_norm(gates, 4 * filters), 4, axis=3) new_cell = tf.sigmoid(g[0]) * x + tf.sigmoid(g[1]) * tf.tanh(g[3]) return tf.sigmoid(g[2]) * tf.tanh(new_cell)
python
def conv_lstm(x, kernel_size, filters, padding="SAME", dilation_rate=(1, 1), name=None, reuse=None): """Convolutional LSTM in 1 dimension.""" with tf.variable_scope( name, default_name="conv_lstm", values=[x], reuse=reuse): gates = conv( x, 4 * filters, kernel_size, padding=padding, dilation_rate=dilation_rate) g = tf.split(layer_norm(gates, 4 * filters), 4, axis=3) new_cell = tf.sigmoid(g[0]) * x + tf.sigmoid(g[1]) * tf.tanh(g[3]) return tf.sigmoid(g[2]) * tf.tanh(new_cell)
[ "def", "conv_lstm", "(", "x", ",", "kernel_size", ",", "filters", ",", "padding", "=", "\"SAME\"", ",", "dilation_rate", "=", "(", "1", ",", "1", ")", ",", "name", "=", "None", ",", "reuse", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ",", "default_name", "=", "\"conv_lstm\"", ",", "values", "=", "[", "x", "]", ",", "reuse", "=", "reuse", ")", ":", "gates", "=", "conv", "(", "x", ",", "4", "*", "filters", ",", "kernel_size", ",", "padding", "=", "padding", ",", "dilation_rate", "=", "dilation_rate", ")", "g", "=", "tf", ".", "split", "(", "layer_norm", "(", "gates", ",", "4", "*", "filters", ")", ",", "4", ",", "axis", "=", "3", ")", "new_cell", "=", "tf", ".", "sigmoid", "(", "g", "[", "0", "]", ")", "*", "x", "+", "tf", ".", "sigmoid", "(", "g", "[", "1", "]", ")", "*", "tf", ".", "tanh", "(", "g", "[", "3", "]", ")", "return", "tf", ".", "sigmoid", "(", "g", "[", "2", "]", ")", "*", "tf", ".", "tanh", "(", "new_cell", ")" ]
Convolutional LSTM in 1 dimension.
[ "Convolutional", "LSTM", "in", "1", "dimension", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L1513-L1531
22,165
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
pad_to_same_length
def pad_to_same_length(x, y, final_length_divisible_by=1, axis=1): """Pad tensors x and y on axis 1 so that they have the same length.""" if axis not in [1, 2]: raise ValueError("Only axis=1 and axis=2 supported for now.") with tf.name_scope("pad_to_same_length", values=[x, y]): x_length = shape_list(x)[axis] y_length = shape_list(y)[axis] if (isinstance(x_length, int) and isinstance(y_length, int) and x_length == y_length and final_length_divisible_by == 1): return x, y max_length = tf.maximum(x_length, y_length) if final_length_divisible_by > 1: # Find the nearest larger-or-equal integer divisible by given number. max_length += final_length_divisible_by - 1 max_length //= final_length_divisible_by max_length *= final_length_divisible_by length_diff1 = max_length - x_length length_diff2 = max_length - y_length def padding_list(length_diff, arg): if axis == 1: return [[[0, 0], [0, length_diff]], tf.zeros([tf.rank(arg) - 2, 2], dtype=tf.int32)] return [[[0, 0], [0, 0], [0, length_diff]], tf.zeros([tf.rank(arg) - 3, 2], dtype=tf.int32)] paddings1 = tf.concat(padding_list(length_diff1, x), axis=0) paddings2 = tf.concat(padding_list(length_diff2, y), axis=0) res_x = tf.pad(x, paddings1) res_y = tf.pad(y, paddings2) # Static shapes are the same except for axis=1. x_shape = x.shape.as_list() x_shape[axis] = None res_x.set_shape(x_shape) y_shape = y.shape.as_list() y_shape[axis] = None res_y.set_shape(y_shape) return res_x, res_y
python
def pad_to_same_length(x, y, final_length_divisible_by=1, axis=1): """Pad tensors x and y on axis 1 so that they have the same length.""" if axis not in [1, 2]: raise ValueError("Only axis=1 and axis=2 supported for now.") with tf.name_scope("pad_to_same_length", values=[x, y]): x_length = shape_list(x)[axis] y_length = shape_list(y)[axis] if (isinstance(x_length, int) and isinstance(y_length, int) and x_length == y_length and final_length_divisible_by == 1): return x, y max_length = tf.maximum(x_length, y_length) if final_length_divisible_by > 1: # Find the nearest larger-or-equal integer divisible by given number. max_length += final_length_divisible_by - 1 max_length //= final_length_divisible_by max_length *= final_length_divisible_by length_diff1 = max_length - x_length length_diff2 = max_length - y_length def padding_list(length_diff, arg): if axis == 1: return [[[0, 0], [0, length_diff]], tf.zeros([tf.rank(arg) - 2, 2], dtype=tf.int32)] return [[[0, 0], [0, 0], [0, length_diff]], tf.zeros([tf.rank(arg) - 3, 2], dtype=tf.int32)] paddings1 = tf.concat(padding_list(length_diff1, x), axis=0) paddings2 = tf.concat(padding_list(length_diff2, y), axis=0) res_x = tf.pad(x, paddings1) res_y = tf.pad(y, paddings2) # Static shapes are the same except for axis=1. x_shape = x.shape.as_list() x_shape[axis] = None res_x.set_shape(x_shape) y_shape = y.shape.as_list() y_shape[axis] = None res_y.set_shape(y_shape) return res_x, res_y
[ "def", "pad_to_same_length", "(", "x", ",", "y", ",", "final_length_divisible_by", "=", "1", ",", "axis", "=", "1", ")", ":", "if", "axis", "not", "in", "[", "1", ",", "2", "]", ":", "raise", "ValueError", "(", "\"Only axis=1 and axis=2 supported for now.\"", ")", "with", "tf", ".", "name_scope", "(", "\"pad_to_same_length\"", ",", "values", "=", "[", "x", ",", "y", "]", ")", ":", "x_length", "=", "shape_list", "(", "x", ")", "[", "axis", "]", "y_length", "=", "shape_list", "(", "y", ")", "[", "axis", "]", "if", "(", "isinstance", "(", "x_length", ",", "int", ")", "and", "isinstance", "(", "y_length", ",", "int", ")", "and", "x_length", "==", "y_length", "and", "final_length_divisible_by", "==", "1", ")", ":", "return", "x", ",", "y", "max_length", "=", "tf", ".", "maximum", "(", "x_length", ",", "y_length", ")", "if", "final_length_divisible_by", ">", "1", ":", "# Find the nearest larger-or-equal integer divisible by given number.", "max_length", "+=", "final_length_divisible_by", "-", "1", "max_length", "//=", "final_length_divisible_by", "max_length", "*=", "final_length_divisible_by", "length_diff1", "=", "max_length", "-", "x_length", "length_diff2", "=", "max_length", "-", "y_length", "def", "padding_list", "(", "length_diff", ",", "arg", ")", ":", "if", "axis", "==", "1", ":", "return", "[", "[", "[", "0", ",", "0", "]", ",", "[", "0", ",", "length_diff", "]", "]", ",", "tf", ".", "zeros", "(", "[", "tf", ".", "rank", "(", "arg", ")", "-", "2", ",", "2", "]", ",", "dtype", "=", "tf", ".", "int32", ")", "]", "return", "[", "[", "[", "0", ",", "0", "]", ",", "[", "0", ",", "0", "]", ",", "[", "0", ",", "length_diff", "]", "]", ",", "tf", ".", "zeros", "(", "[", "tf", ".", "rank", "(", "arg", ")", "-", "3", ",", "2", "]", ",", "dtype", "=", "tf", ".", "int32", ")", "]", "paddings1", "=", "tf", ".", "concat", "(", "padding_list", "(", "length_diff1", ",", "x", ")", ",", "axis", "=", "0", ")", "paddings2", "=", "tf", ".", "concat", "(", "padding_list", "(", "length_diff2", ",", "y", ")", ",", "axis", "=", "0", ")", "res_x", "=", "tf", ".", "pad", "(", "x", ",", "paddings1", ")", "res_y", "=", "tf", ".", "pad", "(", "y", ",", "paddings2", ")", "# Static shapes are the same except for axis=1.", "x_shape", "=", "x", ".", "shape", ".", "as_list", "(", ")", "x_shape", "[", "axis", "]", "=", "None", "res_x", ".", "set_shape", "(", "x_shape", ")", "y_shape", "=", "y", ".", "shape", ".", "as_list", "(", ")", "y_shape", "[", "axis", "]", "=", "None", "res_y", ".", "set_shape", "(", "y_shape", ")", "return", "res_x", ",", "res_y" ]
Pad tensors x and y on axis 1 so that they have the same length.
[ "Pad", "tensors", "x", "and", "y", "on", "axis", "1", "so", "that", "they", "have", "the", "same", "length", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L1576-L1613
22,166
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
pad_with_zeros
def pad_with_zeros(logits, labels): """Pad labels on the length dimension to match logits length.""" with tf.name_scope("pad_with_zeros", values=[logits, labels]): logits, labels = pad_to_same_length(logits, labels) if len(labels.shape) == 3: # 2-d labels. logits, labels = pad_to_same_length(logits, labels, axis=2) return logits, labels
python
def pad_with_zeros(logits, labels): """Pad labels on the length dimension to match logits length.""" with tf.name_scope("pad_with_zeros", values=[logits, labels]): logits, labels = pad_to_same_length(logits, labels) if len(labels.shape) == 3: # 2-d labels. logits, labels = pad_to_same_length(logits, labels, axis=2) return logits, labels
[ "def", "pad_with_zeros", "(", "logits", ",", "labels", ")", ":", "with", "tf", ".", "name_scope", "(", "\"pad_with_zeros\"", ",", "values", "=", "[", "logits", ",", "labels", "]", ")", ":", "logits", ",", "labels", "=", "pad_to_same_length", "(", "logits", ",", "labels", ")", "if", "len", "(", "labels", ".", "shape", ")", "==", "3", ":", "# 2-d labels.", "logits", ",", "labels", "=", "pad_to_same_length", "(", "logits", ",", "labels", ",", "axis", "=", "2", ")", "return", "logits", ",", "labels" ]
Pad labels on the length dimension to match logits length.
[ "Pad", "labels", "on", "the", "length", "dimension", "to", "match", "logits", "length", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L1616-L1622
22,167
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
check_nonnegative
def check_nonnegative(value): """Check that the value is nonnegative.""" if isinstance(value, tf.Tensor): with tf.control_dependencies([tf.assert_greater_equal(value, 0)]): value = tf.identity(value) elif value < 0: raise ValueError("Value must be non-negative.") return value
python
def check_nonnegative(value): """Check that the value is nonnegative.""" if isinstance(value, tf.Tensor): with tf.control_dependencies([tf.assert_greater_equal(value, 0)]): value = tf.identity(value) elif value < 0: raise ValueError("Value must be non-negative.") return value
[ "def", "check_nonnegative", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "tf", ".", "Tensor", ")", ":", "with", "tf", ".", "control_dependencies", "(", "[", "tf", ".", "assert_greater_equal", "(", "value", ",", "0", ")", "]", ")", ":", "value", "=", "tf", ".", "identity", "(", "value", ")", "elif", "value", "<", "0", ":", "raise", "ValueError", "(", "\"Value must be non-negative.\"", ")", "return", "value" ]
Check that the value is nonnegative.
[ "Check", "that", "the", "value", "is", "nonnegative", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L1647-L1654
22,168
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
weights_multi_problem_all
def weights_multi_problem_all(labels, taskid=-1): """Assign weight 1.0 to only examples from the given task.""" taskid = check_nonnegative(taskid) weights = to_float(tf.not_equal(labels, 0)) past_taskid = tf.cumsum(to_float(tf.equal(labels, taskid)), axis=1) # Additionally zero out the task id location past_taskid *= to_float(tf.not_equal(labels, taskid)) non_taskid = to_float(labels) example_mask = to_float(tf.not_equal(past_taskid * non_taskid, 0)) example_mask = tf.reduce_sum(example_mask, axis=1) example_mask = to_float( tf.greater(example_mask, tf.zeros_like(example_mask))) return weights * tf.expand_dims(example_mask, axis=-1)
python
def weights_multi_problem_all(labels, taskid=-1): """Assign weight 1.0 to only examples from the given task.""" taskid = check_nonnegative(taskid) weights = to_float(tf.not_equal(labels, 0)) past_taskid = tf.cumsum(to_float(tf.equal(labels, taskid)), axis=1) # Additionally zero out the task id location past_taskid *= to_float(tf.not_equal(labels, taskid)) non_taskid = to_float(labels) example_mask = to_float(tf.not_equal(past_taskid * non_taskid, 0)) example_mask = tf.reduce_sum(example_mask, axis=1) example_mask = to_float( tf.greater(example_mask, tf.zeros_like(example_mask))) return weights * tf.expand_dims(example_mask, axis=-1)
[ "def", "weights_multi_problem_all", "(", "labels", ",", "taskid", "=", "-", "1", ")", ":", "taskid", "=", "check_nonnegative", "(", "taskid", ")", "weights", "=", "to_float", "(", "tf", ".", "not_equal", "(", "labels", ",", "0", ")", ")", "past_taskid", "=", "tf", ".", "cumsum", "(", "to_float", "(", "tf", ".", "equal", "(", "labels", ",", "taskid", ")", ")", ",", "axis", "=", "1", ")", "# Additionally zero out the task id location", "past_taskid", "*=", "to_float", "(", "tf", ".", "not_equal", "(", "labels", ",", "taskid", ")", ")", "non_taskid", "=", "to_float", "(", "labels", ")", "example_mask", "=", "to_float", "(", "tf", ".", "not_equal", "(", "past_taskid", "*", "non_taskid", ",", "0", ")", ")", "example_mask", "=", "tf", ".", "reduce_sum", "(", "example_mask", ",", "axis", "=", "1", ")", "example_mask", "=", "to_float", "(", "tf", ".", "greater", "(", "example_mask", ",", "tf", ".", "zeros_like", "(", "example_mask", ")", ")", ")", "return", "weights", "*", "tf", ".", "expand_dims", "(", "example_mask", ",", "axis", "=", "-", "1", ")" ]
Assign weight 1.0 to only examples from the given task.
[ "Assign", "weight", "1", ".", "0", "to", "only", "examples", "from", "the", "given", "task", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L1680-L1693
22,169
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
weights_multi_problem_input
def weights_multi_problem_input(labels, taskid=-1): """Assign weight 1.0 to only the inputs for the given task.""" taskid = check_nonnegative(taskid) weights_all_tokens = weights_multi_problem_all(labels, taskid) weights_target = weights_multi_problem(labels, taskid) return weights_all_tokens - weights_target
python
def weights_multi_problem_input(labels, taskid=-1): """Assign weight 1.0 to only the inputs for the given task.""" taskid = check_nonnegative(taskid) weights_all_tokens = weights_multi_problem_all(labels, taskid) weights_target = weights_multi_problem(labels, taskid) return weights_all_tokens - weights_target
[ "def", "weights_multi_problem_input", "(", "labels", ",", "taskid", "=", "-", "1", ")", ":", "taskid", "=", "check_nonnegative", "(", "taskid", ")", "weights_all_tokens", "=", "weights_multi_problem_all", "(", "labels", ",", "taskid", ")", "weights_target", "=", "weights_multi_problem", "(", "labels", ",", "taskid", ")", "return", "weights_all_tokens", "-", "weights_target" ]
Assign weight 1.0 to only the inputs for the given task.
[ "Assign", "weight", "1", ".", "0", "to", "only", "the", "inputs", "for", "the", "given", "task", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L1696-L1701
22,170
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
weights_concatenated
def weights_concatenated(labels): """Assign weight 1.0 to the "target" part of the concatenated labels. The labels look like: source English I love you . ID1 target French Je t'aime . ID1 source English the cat ID1 target French le chat ID1 source English ... We want to assign weight 1.0 to all words in the target text (including the ID1 end symbol), but not to the source text or the boilerplate. In the above example, the target words that get positive weight are: Je t'aime . ID1 le chat ID1 Args: labels: a Tensor Returns: a Tensor """ eos_mask = tf.to_int32(tf.equal(labels, 1)) sentence_num = tf.cumsum(eos_mask, axis=1, exclusive=True) in_target = tf.equal(tf.mod(sentence_num, 2), 1) # first two tokens of each sentence are boilerplate. sentence_num_plus_one = sentence_num + 1 shifted = tf.pad(sentence_num_plus_one, [[0, 0], [2, 0], [0, 0], [0, 0]])[:, :-2, :, :] nonboilerplate = tf.equal(sentence_num_plus_one, shifted) ret = to_float(tf.logical_and(nonboilerplate, in_target)) return ret
python
def weights_concatenated(labels): """Assign weight 1.0 to the "target" part of the concatenated labels. The labels look like: source English I love you . ID1 target French Je t'aime . ID1 source English the cat ID1 target French le chat ID1 source English ... We want to assign weight 1.0 to all words in the target text (including the ID1 end symbol), but not to the source text or the boilerplate. In the above example, the target words that get positive weight are: Je t'aime . ID1 le chat ID1 Args: labels: a Tensor Returns: a Tensor """ eos_mask = tf.to_int32(tf.equal(labels, 1)) sentence_num = tf.cumsum(eos_mask, axis=1, exclusive=True) in_target = tf.equal(tf.mod(sentence_num, 2), 1) # first two tokens of each sentence are boilerplate. sentence_num_plus_one = sentence_num + 1 shifted = tf.pad(sentence_num_plus_one, [[0, 0], [2, 0], [0, 0], [0, 0]])[:, :-2, :, :] nonboilerplate = tf.equal(sentence_num_plus_one, shifted) ret = to_float(tf.logical_and(nonboilerplate, in_target)) return ret
[ "def", "weights_concatenated", "(", "labels", ")", ":", "eos_mask", "=", "tf", ".", "to_int32", "(", "tf", ".", "equal", "(", "labels", ",", "1", ")", ")", "sentence_num", "=", "tf", ".", "cumsum", "(", "eos_mask", ",", "axis", "=", "1", ",", "exclusive", "=", "True", ")", "in_target", "=", "tf", ".", "equal", "(", "tf", ".", "mod", "(", "sentence_num", ",", "2", ")", ",", "1", ")", "# first two tokens of each sentence are boilerplate.", "sentence_num_plus_one", "=", "sentence_num", "+", "1", "shifted", "=", "tf", ".", "pad", "(", "sentence_num_plus_one", ",", "[", "[", "0", ",", "0", "]", ",", "[", "2", ",", "0", "]", ",", "[", "0", ",", "0", "]", ",", "[", "0", ",", "0", "]", "]", ")", "[", ":", ",", ":", "-", "2", ",", ":", ",", ":", "]", "nonboilerplate", "=", "tf", ".", "equal", "(", "sentence_num_plus_one", ",", "shifted", ")", "ret", "=", "to_float", "(", "tf", ".", "logical_and", "(", "nonboilerplate", ",", "in_target", ")", ")", "return", "ret" ]
Assign weight 1.0 to the "target" part of the concatenated labels. The labels look like: source English I love you . ID1 target French Je t'aime . ID1 source English the cat ID1 target French le chat ID1 source English ... We want to assign weight 1.0 to all words in the target text (including the ID1 end symbol), but not to the source text or the boilerplate. In the above example, the target words that get positive weight are: Je t'aime . ID1 le chat ID1 Args: labels: a Tensor Returns: a Tensor
[ "Assign", "weight", "1", ".", "0", "to", "the", "target", "part", "of", "the", "concatenated", "labels", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L1709-L1735
22,171
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
dml_loss
def dml_loss(pred, labels, weights_fn=_weights_one_third, reduce_sum=True): """Discretized mixture of logistics loss. Args: pred: A [batch, height, width, num_mixtures*10] tensor of floats comprising one unconstrained mixture probability, three means (one per channel), three standard deviations (one per channel), and three coefficients which linearly parameterize dependence across channels. labels: A [batch, height, width, channels] tensor of 8-bit pixel intensities. The computation assumes channels is 3. weights_fn: A function of labels, returning a Tensor of shape [batch, height, width] which weights each loss term. Default is to scale each loss term by 1/3 so that they capture the average across channels. reduce_sum: A boolean, to return scalar loss instead of per position. Returns: Tuple of loss tensors for numerator and denominator, each a scalar if reduce_sum else of shape [batch, height, width]. The sum of their divisions is the number of nats for each pixel in labels. """ real_labels = convert_rgb_to_symmetric_real(labels) dml_loss_value = discretized_mix_logistic_loss(pred=pred, labels=real_labels) weights = weights_fn(labels) loss_num = weights * dml_loss_value loss_den = weights_nonzero(weights) if reduce_sum: loss_num = tf.reduce_sum(loss_num) loss_den = tf.reduce_sum(loss_den) return loss_num, loss_den
python
def dml_loss(pred, labels, weights_fn=_weights_one_third, reduce_sum=True): """Discretized mixture of logistics loss. Args: pred: A [batch, height, width, num_mixtures*10] tensor of floats comprising one unconstrained mixture probability, three means (one per channel), three standard deviations (one per channel), and three coefficients which linearly parameterize dependence across channels. labels: A [batch, height, width, channels] tensor of 8-bit pixel intensities. The computation assumes channels is 3. weights_fn: A function of labels, returning a Tensor of shape [batch, height, width] which weights each loss term. Default is to scale each loss term by 1/3 so that they capture the average across channels. reduce_sum: A boolean, to return scalar loss instead of per position. Returns: Tuple of loss tensors for numerator and denominator, each a scalar if reduce_sum else of shape [batch, height, width]. The sum of their divisions is the number of nats for each pixel in labels. """ real_labels = convert_rgb_to_symmetric_real(labels) dml_loss_value = discretized_mix_logistic_loss(pred=pred, labels=real_labels) weights = weights_fn(labels) loss_num = weights * dml_loss_value loss_den = weights_nonzero(weights) if reduce_sum: loss_num = tf.reduce_sum(loss_num) loss_den = tf.reduce_sum(loss_den) return loss_num, loss_den
[ "def", "dml_loss", "(", "pred", ",", "labels", ",", "weights_fn", "=", "_weights_one_third", ",", "reduce_sum", "=", "True", ")", ":", "real_labels", "=", "convert_rgb_to_symmetric_real", "(", "labels", ")", "dml_loss_value", "=", "discretized_mix_logistic_loss", "(", "pred", "=", "pred", ",", "labels", "=", "real_labels", ")", "weights", "=", "weights_fn", "(", "labels", ")", "loss_num", "=", "weights", "*", "dml_loss_value", "loss_den", "=", "weights_nonzero", "(", "weights", ")", "if", "reduce_sum", ":", "loss_num", "=", "tf", ".", "reduce_sum", "(", "loss_num", ")", "loss_den", "=", "tf", ".", "reduce_sum", "(", "loss_den", ")", "return", "loss_num", ",", "loss_den" ]
Discretized mixture of logistics loss. Args: pred: A [batch, height, width, num_mixtures*10] tensor of floats comprising one unconstrained mixture probability, three means (one per channel), three standard deviations (one per channel), and three coefficients which linearly parameterize dependence across channels. labels: A [batch, height, width, channels] tensor of 8-bit pixel intensities. The computation assumes channels is 3. weights_fn: A function of labels, returning a Tensor of shape [batch, height, width] which weights each loss term. Default is to scale each loss term by 1/3 so that they capture the average across channels. reduce_sum: A boolean, to return scalar loss instead of per position. Returns: Tuple of loss tensors for numerator and denominator, each a scalar if reduce_sum else of shape [batch, height, width]. The sum of their divisions is the number of nats for each pixel in labels.
[ "Discretized", "mixture", "of", "logistics", "loss", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L1905-L1934
22,172
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
split_to_discretized_mix_logistic_params
def split_to_discretized_mix_logistic_params(inputs): """Splits input tensor into parameters of discretized mixture logistic. Args: inputs: A [batch, height, width, num_mixtures*10] tensor of floats comprising one unconstrained mixture probability, three means (one per channel), three standard deviations (one per channel), and three coefficients which linearly parameterize dependence across channels. Returns: Tuple of unconstrained mixture probabilities, locations, scales, and coefficient parameters of the distribution. The mixture probability has shape [batch, height, width, num_mixtures]. Other parameters have shape [batch, height, width, num_mixtures, 3]. """ batch, height, width, output_dim = shape_list(inputs) # pylint: disable=unbalanced-tuple-unpacking num_mixtures = output_dim // 10 logits, locs, log_scales, coeffs = tf.split( inputs, num_or_size_splits=[ num_mixtures, num_mixtures * 3, num_mixtures * 3, num_mixtures * 3 ], axis=-1) split_shape = [batch, height, width, num_mixtures, 3] locs = tf.reshape(locs, split_shape) log_scales = tf.reshape(log_scales, split_shape) log_scales = tf.maximum(log_scales, -7.) coeffs = tf.reshape(coeffs, split_shape) coeffs = tf.tanh(coeffs) return logits, locs, log_scales, coeffs
python
def split_to_discretized_mix_logistic_params(inputs): """Splits input tensor into parameters of discretized mixture logistic. Args: inputs: A [batch, height, width, num_mixtures*10] tensor of floats comprising one unconstrained mixture probability, three means (one per channel), three standard deviations (one per channel), and three coefficients which linearly parameterize dependence across channels. Returns: Tuple of unconstrained mixture probabilities, locations, scales, and coefficient parameters of the distribution. The mixture probability has shape [batch, height, width, num_mixtures]. Other parameters have shape [batch, height, width, num_mixtures, 3]. """ batch, height, width, output_dim = shape_list(inputs) # pylint: disable=unbalanced-tuple-unpacking num_mixtures = output_dim // 10 logits, locs, log_scales, coeffs = tf.split( inputs, num_or_size_splits=[ num_mixtures, num_mixtures * 3, num_mixtures * 3, num_mixtures * 3 ], axis=-1) split_shape = [batch, height, width, num_mixtures, 3] locs = tf.reshape(locs, split_shape) log_scales = tf.reshape(log_scales, split_shape) log_scales = tf.maximum(log_scales, -7.) coeffs = tf.reshape(coeffs, split_shape) coeffs = tf.tanh(coeffs) return logits, locs, log_scales, coeffs
[ "def", "split_to_discretized_mix_logistic_params", "(", "inputs", ")", ":", "batch", ",", "height", ",", "width", ",", "output_dim", "=", "shape_list", "(", "inputs", ")", "# pylint: disable=unbalanced-tuple-unpacking", "num_mixtures", "=", "output_dim", "//", "10", "logits", ",", "locs", ",", "log_scales", ",", "coeffs", "=", "tf", ".", "split", "(", "inputs", ",", "num_or_size_splits", "=", "[", "num_mixtures", ",", "num_mixtures", "*", "3", ",", "num_mixtures", "*", "3", ",", "num_mixtures", "*", "3", "]", ",", "axis", "=", "-", "1", ")", "split_shape", "=", "[", "batch", ",", "height", ",", "width", ",", "num_mixtures", ",", "3", "]", "locs", "=", "tf", ".", "reshape", "(", "locs", ",", "split_shape", ")", "log_scales", "=", "tf", ".", "reshape", "(", "log_scales", ",", "split_shape", ")", "log_scales", "=", "tf", ".", "maximum", "(", "log_scales", ",", "-", "7.", ")", "coeffs", "=", "tf", ".", "reshape", "(", "coeffs", ",", "split_shape", ")", "coeffs", "=", "tf", ".", "tanh", "(", "coeffs", ")", "return", "logits", ",", "locs", ",", "log_scales", ",", "coeffs" ]
Splits input tensor into parameters of discretized mixture logistic. Args: inputs: A [batch, height, width, num_mixtures*10] tensor of floats comprising one unconstrained mixture probability, three means (one per channel), three standard deviations (one per channel), and three coefficients which linearly parameterize dependence across channels. Returns: Tuple of unconstrained mixture probabilities, locations, scales, and coefficient parameters of the distribution. The mixture probability has shape [batch, height, width, num_mixtures]. Other parameters have shape [batch, height, width, num_mixtures, 3].
[ "Splits", "input", "tensor", "into", "parameters", "of", "discretized", "mixture", "logistic", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L1937-L1967
22,173
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
discretized_mix_logistic_loss
def discretized_mix_logistic_loss(pred, labels): """Computes negative log probability for the discretized mixture of logistics. The distribution of a whole pixel is a mixture of 3-dimensional discretized logistic distributions. The 3-D discretized logistic factorizes as 3 1-D discretized logistic distributions, one for each channel. It defines ```none P(X = x) = sum_{k=1}^K probs[k] * P(X = x | locs[k], scales[k]) = sum_{k=1}^K probs[k] * [ prod_{c=1}^3 DiscretizedLogistic(X[c] = x[c] | means[k][c], scales[k]) ] ``` The means tensor is a linear combination of location parameters and previous channels. The discretized logistic distribution assigns probability mass to an event P(X=x) via logistic CDFs: P(X <= x + 0.5) - P(X < x - 0.5) for 1 < x < 254; P(X <= 0.5) for x = 0; and 1 - P(X < 245.5) for x = 255. Instead of 8-bit inputs, this implementation assumes the events are rescaled to [-1, 1]. Args: pred: A [batch, height, width, num_mixtures*10] tensor of floats comprising one unconstrained mixture probability, three means (one per channel), three standard deviations (one per channel), and three coefficients which linearly parameterize dependence across channels. labels: A [batch, height, width, channels] tensor of true pixel intensities rescaled to [-1, 1]. The computation assumes channels is 3. Returns: A [batch, height, width] tensor of the negative log conditional probability of each pixel given all previous pixels. """ logits, locs, log_scales, coeffs = split_to_discretized_mix_logistic_params( pred) # Tile labels to broadcast compute across the mixture dimension. batch, height, width, num_mixtures = shape_list(logits) # pylint: disable=unbalanced-tuple-unpacking labels = tf.tile( tf.reshape(labels, [batch, height, width, 1, 3]), [1, 1, 1, num_mixtures, 1]) # p(x) = sigmoid((x - means_i + 1/255.)/scale_i) - # sigmoid((x - means_i - 1/255.)/scale_i) # for each channel i. The means are linearly parameterized. means_0 = locs[..., 0] means_1 = locs[..., 1] + coeffs[..., 0] * labels[..., 0] means_2 = ( locs[..., 2] + coeffs[..., 1] * labels[..., 0] + coeffs[..., 2] * labels[..., 1]) means = tf.stack([means_0, means_1, means_2], axis=-1) centered_labels = labels - means inv_stdv = tf.exp(-log_scales) plus_in = inv_stdv * (centered_labels + 1. / 255.) min_in = inv_stdv * (centered_labels - 1. / 255.) cdf_plus = tf.nn.sigmoid(plus_in) cdf_min = tf.nn.sigmoid(min_in) # Compute log probability for edge case of 0 (before scaling), 255 (before # scaling), and all other cases respectively. log_prob_0 = plus_in - tf.nn.softplus(plus_in) log_prob_255 = -tf.nn.softplus(min_in) prob_event = tf.maximum(cdf_plus - cdf_min, 1e-12) log_prob_event = tf.log(prob_event) # Robustly select log-prob based on numerical edge-cases: (a) [-1, -1+eps); # (b) (1-eps, 1]; (c) NaNs during `tf.gradients` of `tf.select`, which may # cause `tf.log(0.)`; (d) p(x) < 1e-5. mid_in = inv_stdv * centered_labels log_prob_event_approx = ( mid_in - log_scales - 2. * tf.nn.softplus(mid_in) - np.log(127.5)) log_probs = tf.where( labels < -0.999, log_prob_0, tf.where( labels > 0.999, log_prob_255, tf.where(prob_event > 1e-5, log_prob_event, log_prob_event_approx))) # Sum over channels and compute log-probability of each mixture. log_probs = tf.reduce_sum(log_probs, -1) + tf.nn.log_softmax(logits, axis=-1) output = -tf.reduce_logsumexp(log_probs, axis=-1) return output
python
def discretized_mix_logistic_loss(pred, labels): """Computes negative log probability for the discretized mixture of logistics. The distribution of a whole pixel is a mixture of 3-dimensional discretized logistic distributions. The 3-D discretized logistic factorizes as 3 1-D discretized logistic distributions, one for each channel. It defines ```none P(X = x) = sum_{k=1}^K probs[k] * P(X = x | locs[k], scales[k]) = sum_{k=1}^K probs[k] * [ prod_{c=1}^3 DiscretizedLogistic(X[c] = x[c] | means[k][c], scales[k]) ] ``` The means tensor is a linear combination of location parameters and previous channels. The discretized logistic distribution assigns probability mass to an event P(X=x) via logistic CDFs: P(X <= x + 0.5) - P(X < x - 0.5) for 1 < x < 254; P(X <= 0.5) for x = 0; and 1 - P(X < 245.5) for x = 255. Instead of 8-bit inputs, this implementation assumes the events are rescaled to [-1, 1]. Args: pred: A [batch, height, width, num_mixtures*10] tensor of floats comprising one unconstrained mixture probability, three means (one per channel), three standard deviations (one per channel), and three coefficients which linearly parameterize dependence across channels. labels: A [batch, height, width, channels] tensor of true pixel intensities rescaled to [-1, 1]. The computation assumes channels is 3. Returns: A [batch, height, width] tensor of the negative log conditional probability of each pixel given all previous pixels. """ logits, locs, log_scales, coeffs = split_to_discretized_mix_logistic_params( pred) # Tile labels to broadcast compute across the mixture dimension. batch, height, width, num_mixtures = shape_list(logits) # pylint: disable=unbalanced-tuple-unpacking labels = tf.tile( tf.reshape(labels, [batch, height, width, 1, 3]), [1, 1, 1, num_mixtures, 1]) # p(x) = sigmoid((x - means_i + 1/255.)/scale_i) - # sigmoid((x - means_i - 1/255.)/scale_i) # for each channel i. The means are linearly parameterized. means_0 = locs[..., 0] means_1 = locs[..., 1] + coeffs[..., 0] * labels[..., 0] means_2 = ( locs[..., 2] + coeffs[..., 1] * labels[..., 0] + coeffs[..., 2] * labels[..., 1]) means = tf.stack([means_0, means_1, means_2], axis=-1) centered_labels = labels - means inv_stdv = tf.exp(-log_scales) plus_in = inv_stdv * (centered_labels + 1. / 255.) min_in = inv_stdv * (centered_labels - 1. / 255.) cdf_plus = tf.nn.sigmoid(plus_in) cdf_min = tf.nn.sigmoid(min_in) # Compute log probability for edge case of 0 (before scaling), 255 (before # scaling), and all other cases respectively. log_prob_0 = plus_in - tf.nn.softplus(plus_in) log_prob_255 = -tf.nn.softplus(min_in) prob_event = tf.maximum(cdf_plus - cdf_min, 1e-12) log_prob_event = tf.log(prob_event) # Robustly select log-prob based on numerical edge-cases: (a) [-1, -1+eps); # (b) (1-eps, 1]; (c) NaNs during `tf.gradients` of `tf.select`, which may # cause `tf.log(0.)`; (d) p(x) < 1e-5. mid_in = inv_stdv * centered_labels log_prob_event_approx = ( mid_in - log_scales - 2. * tf.nn.softplus(mid_in) - np.log(127.5)) log_probs = tf.where( labels < -0.999, log_prob_0, tf.where( labels > 0.999, log_prob_255, tf.where(prob_event > 1e-5, log_prob_event, log_prob_event_approx))) # Sum over channels and compute log-probability of each mixture. log_probs = tf.reduce_sum(log_probs, -1) + tf.nn.log_softmax(logits, axis=-1) output = -tf.reduce_logsumexp(log_probs, axis=-1) return output
[ "def", "discretized_mix_logistic_loss", "(", "pred", ",", "labels", ")", ":", "logits", ",", "locs", ",", "log_scales", ",", "coeffs", "=", "split_to_discretized_mix_logistic_params", "(", "pred", ")", "# Tile labels to broadcast compute across the mixture dimension.", "batch", ",", "height", ",", "width", ",", "num_mixtures", "=", "shape_list", "(", "logits", ")", "# pylint: disable=unbalanced-tuple-unpacking", "labels", "=", "tf", ".", "tile", "(", "tf", ".", "reshape", "(", "labels", ",", "[", "batch", ",", "height", ",", "width", ",", "1", ",", "3", "]", ")", ",", "[", "1", ",", "1", ",", "1", ",", "num_mixtures", ",", "1", "]", ")", "# p(x) = sigmoid((x - means_i + 1/255.)/scale_i) -", "# sigmoid((x - means_i - 1/255.)/scale_i)", "# for each channel i. The means are linearly parameterized.", "means_0", "=", "locs", "[", "...", ",", "0", "]", "means_1", "=", "locs", "[", "...", ",", "1", "]", "+", "coeffs", "[", "...", ",", "0", "]", "*", "labels", "[", "...", ",", "0", "]", "means_2", "=", "(", "locs", "[", "...", ",", "2", "]", "+", "coeffs", "[", "...", ",", "1", "]", "*", "labels", "[", "...", ",", "0", "]", "+", "coeffs", "[", "...", ",", "2", "]", "*", "labels", "[", "...", ",", "1", "]", ")", "means", "=", "tf", ".", "stack", "(", "[", "means_0", ",", "means_1", ",", "means_2", "]", ",", "axis", "=", "-", "1", ")", "centered_labels", "=", "labels", "-", "means", "inv_stdv", "=", "tf", ".", "exp", "(", "-", "log_scales", ")", "plus_in", "=", "inv_stdv", "*", "(", "centered_labels", "+", "1.", "/", "255.", ")", "min_in", "=", "inv_stdv", "*", "(", "centered_labels", "-", "1.", "/", "255.", ")", "cdf_plus", "=", "tf", ".", "nn", ".", "sigmoid", "(", "plus_in", ")", "cdf_min", "=", "tf", ".", "nn", ".", "sigmoid", "(", "min_in", ")", "# Compute log probability for edge case of 0 (before scaling), 255 (before", "# scaling), and all other cases respectively.", "log_prob_0", "=", "plus_in", "-", "tf", ".", "nn", ".", "softplus", "(", "plus_in", ")", "log_prob_255", "=", "-", "tf", ".", "nn", ".", "softplus", "(", "min_in", ")", "prob_event", "=", "tf", ".", "maximum", "(", "cdf_plus", "-", "cdf_min", ",", "1e-12", ")", "log_prob_event", "=", "tf", ".", "log", "(", "prob_event", ")", "# Robustly select log-prob based on numerical edge-cases: (a) [-1, -1+eps);", "# (b) (1-eps, 1]; (c) NaNs during `tf.gradients` of `tf.select`, which may", "# cause `tf.log(0.)`; (d) p(x) < 1e-5.", "mid_in", "=", "inv_stdv", "*", "centered_labels", "log_prob_event_approx", "=", "(", "mid_in", "-", "log_scales", "-", "2.", "*", "tf", ".", "nn", ".", "softplus", "(", "mid_in", ")", "-", "np", ".", "log", "(", "127.5", ")", ")", "log_probs", "=", "tf", ".", "where", "(", "labels", "<", "-", "0.999", ",", "log_prob_0", ",", "tf", ".", "where", "(", "labels", ">", "0.999", ",", "log_prob_255", ",", "tf", ".", "where", "(", "prob_event", ">", "1e-5", ",", "log_prob_event", ",", "log_prob_event_approx", ")", ")", ")", "# Sum over channels and compute log-probability of each mixture.", "log_probs", "=", "tf", ".", "reduce_sum", "(", "log_probs", ",", "-", "1", ")", "+", "tf", ".", "nn", ".", "log_softmax", "(", "logits", ",", "axis", "=", "-", "1", ")", "output", "=", "-", "tf", ".", "reduce_logsumexp", "(", "log_probs", ",", "axis", "=", "-", "1", ")", "return", "output" ]
Computes negative log probability for the discretized mixture of logistics. The distribution of a whole pixel is a mixture of 3-dimensional discretized logistic distributions. The 3-D discretized logistic factorizes as 3 1-D discretized logistic distributions, one for each channel. It defines ```none P(X = x) = sum_{k=1}^K probs[k] * P(X = x | locs[k], scales[k]) = sum_{k=1}^K probs[k] * [ prod_{c=1}^3 DiscretizedLogistic(X[c] = x[c] | means[k][c], scales[k]) ] ``` The means tensor is a linear combination of location parameters and previous channels. The discretized logistic distribution assigns probability mass to an event P(X=x) via logistic CDFs: P(X <= x + 0.5) - P(X < x - 0.5) for 1 < x < 254; P(X <= 0.5) for x = 0; and 1 - P(X < 245.5) for x = 255. Instead of 8-bit inputs, this implementation assumes the events are rescaled to [-1, 1]. Args: pred: A [batch, height, width, num_mixtures*10] tensor of floats comprising one unconstrained mixture probability, three means (one per channel), three standard deviations (one per channel), and three coefficients which linearly parameterize dependence across channels. labels: A [batch, height, width, channels] tensor of true pixel intensities rescaled to [-1, 1]. The computation assumes channels is 3. Returns: A [batch, height, width] tensor of the negative log conditional probability of each pixel given all previous pixels.
[ "Computes", "negative", "log", "probability", "for", "the", "discretized", "mixture", "of", "logistics", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L1970-L2051
22,174
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
sample_from_discretized_mix_logistic
def sample_from_discretized_mix_logistic(pred, seed=None): """Sampling from a discretized mixture of logistics. Args: pred: A [batch, height, width, num_mixtures*10] tensor of floats comprising one unconstrained mixture probability, three means (one per channel), three standard deviations (one per channel), and three coefficients which linearly parameterize dependence across channels. seed: Random seed. Returns: A tensor of shape [batch, height, width, 3] with real intensities scaled between -1 and 1. """ logits, locs, log_scales, coeffs = split_to_discretized_mix_logistic_params( pred) # Sample mixture indicator given logits using the gumbel max trick. num_mixtures = shape_list(logits)[-1] gumbel_noise = -tf.log(-tf.log( tf.random_uniform( tf.shape(logits), minval=1e-5, maxval=1. - 1e-5, seed=seed))) sel = tf.one_hot( tf.argmax(logits + gumbel_noise, -1), depth=num_mixtures, dtype=tf.float32) # Select mixture component's parameters. sel = tf.expand_dims(sel, -1) locs = tf.reduce_sum(locs * sel, 3) log_scales = tf.reduce_sum(log_scales * sel, 3) coeffs = tf.reduce_sum(coeffs * sel, 3) # Sample from 3-D logistic & clip to interval. Note we don't round to the # nearest 8-bit value when sampling. uniform_noise = tf.random_uniform( tf.shape(locs), minval=1e-5, maxval=1. - 1e-5, seed=seed) logistic_noise = tf.log(uniform_noise) - tf.log1p(-uniform_noise) x = locs + tf.exp(log_scales) * logistic_noise x0 = x[..., 0] x1 = x[..., 1] + coeffs[..., 0] * x0 x2 = x[..., 2] + coeffs[..., 1] * x0 + coeffs[..., 2] * x1 x = tf.stack([x0, x1, x2], axis=-1) x = tf.clip_by_value(x, -1., 1.) return x
python
def sample_from_discretized_mix_logistic(pred, seed=None): """Sampling from a discretized mixture of logistics. Args: pred: A [batch, height, width, num_mixtures*10] tensor of floats comprising one unconstrained mixture probability, three means (one per channel), three standard deviations (one per channel), and three coefficients which linearly parameterize dependence across channels. seed: Random seed. Returns: A tensor of shape [batch, height, width, 3] with real intensities scaled between -1 and 1. """ logits, locs, log_scales, coeffs = split_to_discretized_mix_logistic_params( pred) # Sample mixture indicator given logits using the gumbel max trick. num_mixtures = shape_list(logits)[-1] gumbel_noise = -tf.log(-tf.log( tf.random_uniform( tf.shape(logits), minval=1e-5, maxval=1. - 1e-5, seed=seed))) sel = tf.one_hot( tf.argmax(logits + gumbel_noise, -1), depth=num_mixtures, dtype=tf.float32) # Select mixture component's parameters. sel = tf.expand_dims(sel, -1) locs = tf.reduce_sum(locs * sel, 3) log_scales = tf.reduce_sum(log_scales * sel, 3) coeffs = tf.reduce_sum(coeffs * sel, 3) # Sample from 3-D logistic & clip to interval. Note we don't round to the # nearest 8-bit value when sampling. uniform_noise = tf.random_uniform( tf.shape(locs), minval=1e-5, maxval=1. - 1e-5, seed=seed) logistic_noise = tf.log(uniform_noise) - tf.log1p(-uniform_noise) x = locs + tf.exp(log_scales) * logistic_noise x0 = x[..., 0] x1 = x[..., 1] + coeffs[..., 0] * x0 x2 = x[..., 2] + coeffs[..., 1] * x0 + coeffs[..., 2] * x1 x = tf.stack([x0, x1, x2], axis=-1) x = tf.clip_by_value(x, -1., 1.) return x
[ "def", "sample_from_discretized_mix_logistic", "(", "pred", ",", "seed", "=", "None", ")", ":", "logits", ",", "locs", ",", "log_scales", ",", "coeffs", "=", "split_to_discretized_mix_logistic_params", "(", "pred", ")", "# Sample mixture indicator given logits using the gumbel max trick.", "num_mixtures", "=", "shape_list", "(", "logits", ")", "[", "-", "1", "]", "gumbel_noise", "=", "-", "tf", ".", "log", "(", "-", "tf", ".", "log", "(", "tf", ".", "random_uniform", "(", "tf", ".", "shape", "(", "logits", ")", ",", "minval", "=", "1e-5", ",", "maxval", "=", "1.", "-", "1e-5", ",", "seed", "=", "seed", ")", ")", ")", "sel", "=", "tf", ".", "one_hot", "(", "tf", ".", "argmax", "(", "logits", "+", "gumbel_noise", ",", "-", "1", ")", ",", "depth", "=", "num_mixtures", ",", "dtype", "=", "tf", ".", "float32", ")", "# Select mixture component's parameters.", "sel", "=", "tf", ".", "expand_dims", "(", "sel", ",", "-", "1", ")", "locs", "=", "tf", ".", "reduce_sum", "(", "locs", "*", "sel", ",", "3", ")", "log_scales", "=", "tf", ".", "reduce_sum", "(", "log_scales", "*", "sel", ",", "3", ")", "coeffs", "=", "tf", ".", "reduce_sum", "(", "coeffs", "*", "sel", ",", "3", ")", "# Sample from 3-D logistic & clip to interval. Note we don't round to the", "# nearest 8-bit value when sampling.", "uniform_noise", "=", "tf", ".", "random_uniform", "(", "tf", ".", "shape", "(", "locs", ")", ",", "minval", "=", "1e-5", ",", "maxval", "=", "1.", "-", "1e-5", ",", "seed", "=", "seed", ")", "logistic_noise", "=", "tf", ".", "log", "(", "uniform_noise", ")", "-", "tf", ".", "log1p", "(", "-", "uniform_noise", ")", "x", "=", "locs", "+", "tf", ".", "exp", "(", "log_scales", ")", "*", "logistic_noise", "x0", "=", "x", "[", "...", ",", "0", "]", "x1", "=", "x", "[", "...", ",", "1", "]", "+", "coeffs", "[", "...", ",", "0", "]", "*", "x0", "x2", "=", "x", "[", "...", ",", "2", "]", "+", "coeffs", "[", "...", ",", "1", "]", "*", "x0", "+", "coeffs", "[", "...", ",", "2", "]", "*", "x1", "x", "=", "tf", ".", "stack", "(", "[", "x0", ",", "x1", ",", "x2", "]", ",", "axis", "=", "-", "1", ")", "x", "=", "tf", ".", "clip_by_value", "(", "x", ",", "-", "1.", ",", "1.", ")", "return", "x" ]
Sampling from a discretized mixture of logistics. Args: pred: A [batch, height, width, num_mixtures*10] tensor of floats comprising one unconstrained mixture probability, three means (one per channel), three standard deviations (one per channel), and three coefficients which linearly parameterize dependence across channels. seed: Random seed. Returns: A tensor of shape [batch, height, width, 3] with real intensities scaled between -1 and 1.
[ "Sampling", "from", "a", "discretized", "mixture", "of", "logistics", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L2054-L2100
22,175
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
smoothing_cross_entropy
def smoothing_cross_entropy(logits, labels, vocab_size, confidence, gaussian=False): """Cross entropy with label smoothing to limit over-confidence. Args: logits: Tensor of shape [batch_size, ?, ?, ?, vocab_size]. labels: Tensor of shape [batch_size, ?, ?, ?]. vocab_size: Tensor representing the size of the vocabulary. confidence: Used to determine on and off values for label smoothing. If `gaussian` is true, `confidence` is the variance to the Gaussian distribution. gaussian: Uses a Gaussian distribution for label smoothing Returns: Tensor of shape [batch_size, ?, ?, ?]. """ with tf.name_scope("smoothing_cross_entropy", values=[logits, labels]): # Low confidence is given to all non-true labels, uniformly. low_confidence = (1.0 - confidence) / to_float(vocab_size - 1) # Normalizing constant is the best cross-entropy value with soft targets. # We subtract it just for readability, makes no difference on learning. normalizing = -( confidence * tf.log(confidence) + to_float(vocab_size - 1) * low_confidence * tf.log(low_confidence + 1e-20)) if gaussian and confidence > 0.0: labels = tf.cast(labels, tf.float32) normal_dist = tfp.distributions.Normal(loc=labels, scale=confidence) # Locations to evaluate the probability distributions. soft_targets = normal_dist.prob( tf.cast(tf.range(vocab_size), tf.float32)[:, None, None, None, None]) # Reordering soft_targets from [vocab_size, batch_size, ?, ?, ?] to match # logits: [batch_size, ?, ?, ?, vocab_size] soft_targets = tf.transpose(soft_targets, perm=[1, 2, 3, 4, 0]) else: soft_targets = tf.one_hot( tf.cast(labels, tf.int32), depth=vocab_size, on_value=confidence, off_value=low_confidence) xentropy = tf.nn.softmax_cross_entropy_with_logits_v2( logits=logits, labels=soft_targets) return xentropy - normalizing
python
def smoothing_cross_entropy(logits, labels, vocab_size, confidence, gaussian=False): """Cross entropy with label smoothing to limit over-confidence. Args: logits: Tensor of shape [batch_size, ?, ?, ?, vocab_size]. labels: Tensor of shape [batch_size, ?, ?, ?]. vocab_size: Tensor representing the size of the vocabulary. confidence: Used to determine on and off values for label smoothing. If `gaussian` is true, `confidence` is the variance to the Gaussian distribution. gaussian: Uses a Gaussian distribution for label smoothing Returns: Tensor of shape [batch_size, ?, ?, ?]. """ with tf.name_scope("smoothing_cross_entropy", values=[logits, labels]): # Low confidence is given to all non-true labels, uniformly. low_confidence = (1.0 - confidence) / to_float(vocab_size - 1) # Normalizing constant is the best cross-entropy value with soft targets. # We subtract it just for readability, makes no difference on learning. normalizing = -( confidence * tf.log(confidence) + to_float(vocab_size - 1) * low_confidence * tf.log(low_confidence + 1e-20)) if gaussian and confidence > 0.0: labels = tf.cast(labels, tf.float32) normal_dist = tfp.distributions.Normal(loc=labels, scale=confidence) # Locations to evaluate the probability distributions. soft_targets = normal_dist.prob( tf.cast(tf.range(vocab_size), tf.float32)[:, None, None, None, None]) # Reordering soft_targets from [vocab_size, batch_size, ?, ?, ?] to match # logits: [batch_size, ?, ?, ?, vocab_size] soft_targets = tf.transpose(soft_targets, perm=[1, 2, 3, 4, 0]) else: soft_targets = tf.one_hot( tf.cast(labels, tf.int32), depth=vocab_size, on_value=confidence, off_value=low_confidence) xentropy = tf.nn.softmax_cross_entropy_with_logits_v2( logits=logits, labels=soft_targets) return xentropy - normalizing
[ "def", "smoothing_cross_entropy", "(", "logits", ",", "labels", ",", "vocab_size", ",", "confidence", ",", "gaussian", "=", "False", ")", ":", "with", "tf", ".", "name_scope", "(", "\"smoothing_cross_entropy\"", ",", "values", "=", "[", "logits", ",", "labels", "]", ")", ":", "# Low confidence is given to all non-true labels, uniformly.", "low_confidence", "=", "(", "1.0", "-", "confidence", ")", "/", "to_float", "(", "vocab_size", "-", "1", ")", "# Normalizing constant is the best cross-entropy value with soft targets.", "# We subtract it just for readability, makes no difference on learning.", "normalizing", "=", "-", "(", "confidence", "*", "tf", ".", "log", "(", "confidence", ")", "+", "to_float", "(", "vocab_size", "-", "1", ")", "*", "low_confidence", "*", "tf", ".", "log", "(", "low_confidence", "+", "1e-20", ")", ")", "if", "gaussian", "and", "confidence", ">", "0.0", ":", "labels", "=", "tf", ".", "cast", "(", "labels", ",", "tf", ".", "float32", ")", "normal_dist", "=", "tfp", ".", "distributions", ".", "Normal", "(", "loc", "=", "labels", ",", "scale", "=", "confidence", ")", "# Locations to evaluate the probability distributions.", "soft_targets", "=", "normal_dist", ".", "prob", "(", "tf", ".", "cast", "(", "tf", ".", "range", "(", "vocab_size", ")", ",", "tf", ".", "float32", ")", "[", ":", ",", "None", ",", "None", ",", "None", ",", "None", "]", ")", "# Reordering soft_targets from [vocab_size, batch_size, ?, ?, ?] to match", "# logits: [batch_size, ?, ?, ?, vocab_size]", "soft_targets", "=", "tf", ".", "transpose", "(", "soft_targets", ",", "perm", "=", "[", "1", ",", "2", ",", "3", ",", "4", ",", "0", "]", ")", "else", ":", "soft_targets", "=", "tf", ".", "one_hot", "(", "tf", ".", "cast", "(", "labels", ",", "tf", ".", "int32", ")", ",", "depth", "=", "vocab_size", ",", "on_value", "=", "confidence", ",", "off_value", "=", "low_confidence", ")", "xentropy", "=", "tf", ".", "nn", ".", "softmax_cross_entropy_with_logits_v2", "(", "logits", "=", "logits", ",", "labels", "=", "soft_targets", ")", "return", "xentropy", "-", "normalizing" ]
Cross entropy with label smoothing to limit over-confidence. Args: logits: Tensor of shape [batch_size, ?, ?, ?, vocab_size]. labels: Tensor of shape [batch_size, ?, ?, ?]. vocab_size: Tensor representing the size of the vocabulary. confidence: Used to determine on and off values for label smoothing. If `gaussian` is true, `confidence` is the variance to the Gaussian distribution. gaussian: Uses a Gaussian distribution for label smoothing Returns: Tensor of shape [batch_size, ?, ?, ?].
[ "Cross", "entropy", "with", "label", "smoothing", "to", "limit", "over", "-", "confidence", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L2103-L2149
22,176
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
global_pool_1d
def global_pool_1d(inputs, pooling_type="MAX", mask=None): """Pool elements across the last dimension. Useful to convert a list of vectors into a single vector so as to get a representation of a set. Args: inputs: A tensor of shape [batch_size, sequence_length, input_dims] containing the sequences of input vectors. pooling_type: the pooling type to use, MAX or AVR mask: A tensor of shape [batch_size, sequence_length] containing a mask for the inputs with 1's for existing elements, and 0's elsewhere. Returns: A tensor of shape [batch_size, input_dims] containing the sequences of transformed vectors. """ with tf.name_scope("global_pool", values=[inputs]): if mask is not None: mask = tf.expand_dims(mask, axis=2) inputs = tf.multiply(inputs, mask) if pooling_type == "MAX": # A tf.pool can be used here, but reduce is cleaner output = tf.reduce_max(inputs, axis=1) elif pooling_type == "AVR": if mask is not None: # Some elems are dummy elems so we can't just reduce the average. output = tf.reduce_sum(inputs, axis=1) num_elems = tf.reduce_sum(mask, axis=1, keepdims=True) output = tf.div(output, tf.maximum(num_elems, 1)) else: output = tf.reduce_mean(inputs, axis=1) return output
python
def global_pool_1d(inputs, pooling_type="MAX", mask=None): """Pool elements across the last dimension. Useful to convert a list of vectors into a single vector so as to get a representation of a set. Args: inputs: A tensor of shape [batch_size, sequence_length, input_dims] containing the sequences of input vectors. pooling_type: the pooling type to use, MAX or AVR mask: A tensor of shape [batch_size, sequence_length] containing a mask for the inputs with 1's for existing elements, and 0's elsewhere. Returns: A tensor of shape [batch_size, input_dims] containing the sequences of transformed vectors. """ with tf.name_scope("global_pool", values=[inputs]): if mask is not None: mask = tf.expand_dims(mask, axis=2) inputs = tf.multiply(inputs, mask) if pooling_type == "MAX": # A tf.pool can be used here, but reduce is cleaner output = tf.reduce_max(inputs, axis=1) elif pooling_type == "AVR": if mask is not None: # Some elems are dummy elems so we can't just reduce the average. output = tf.reduce_sum(inputs, axis=1) num_elems = tf.reduce_sum(mask, axis=1, keepdims=True) output = tf.div(output, tf.maximum(num_elems, 1)) else: output = tf.reduce_mean(inputs, axis=1) return output
[ "def", "global_pool_1d", "(", "inputs", ",", "pooling_type", "=", "\"MAX\"", ",", "mask", "=", "None", ")", ":", "with", "tf", ".", "name_scope", "(", "\"global_pool\"", ",", "values", "=", "[", "inputs", "]", ")", ":", "if", "mask", "is", "not", "None", ":", "mask", "=", "tf", ".", "expand_dims", "(", "mask", ",", "axis", "=", "2", ")", "inputs", "=", "tf", ".", "multiply", "(", "inputs", ",", "mask", ")", "if", "pooling_type", "==", "\"MAX\"", ":", "# A tf.pool can be used here, but reduce is cleaner", "output", "=", "tf", ".", "reduce_max", "(", "inputs", ",", "axis", "=", "1", ")", "elif", "pooling_type", "==", "\"AVR\"", ":", "if", "mask", "is", "not", "None", ":", "# Some elems are dummy elems so we can't just reduce the average.", "output", "=", "tf", ".", "reduce_sum", "(", "inputs", ",", "axis", "=", "1", ")", "num_elems", "=", "tf", ".", "reduce_sum", "(", "mask", ",", "axis", "=", "1", ",", "keepdims", "=", "True", ")", "output", "=", "tf", ".", "div", "(", "output", ",", "tf", ".", "maximum", "(", "num_elems", ",", "1", ")", ")", "else", ":", "output", "=", "tf", ".", "reduce_mean", "(", "inputs", ",", "axis", "=", "1", ")", "return", "output" ]
Pool elements across the last dimension. Useful to convert a list of vectors into a single vector so as to get a representation of a set. Args: inputs: A tensor of shape [batch_size, sequence_length, input_dims] containing the sequences of input vectors. pooling_type: the pooling type to use, MAX or AVR mask: A tensor of shape [batch_size, sequence_length] containing a mask for the inputs with 1's for existing elements, and 0's elsewhere. Returns: A tensor of shape [batch_size, input_dims] containing the sequences of transformed vectors.
[ "Pool", "elements", "across", "the", "last", "dimension", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L2152-L2186
22,177
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
running_global_pool_1d
def running_global_pool_1d(inputs, pooling_type="MAX"): """Same global pool, but only for the elements up to the current element. Useful for outputs where the state of future elements is not known. Takes no mask as all elements up to the current element are assumed to exist. Currently only supports maximum. Equivalent to using a lower triangle bias. Args: inputs: A tensor of shape [batch_size, sequence_length, input_dims] containing the sequences of input vectors. pooling_type: Pooling type to use. Currently only supports 'MAX'. Returns: A tensor of shape [batch_size, sequence_length, input_dims] containing the running 'totals'. """ del pooling_type with tf.name_scope("running_global_pool", values=[inputs]): scan_fct = tf.maximum # Permute inputs so seq_length is first. elems = tf.transpose(inputs, [1, 0, 2]) # Perform scan. cumulatives = tf.scan(scan_fct, elems, swap_memory=True) # Permute output to get back to original order. output = tf.transpose(cumulatives, [1, 0, 2]) return output
python
def running_global_pool_1d(inputs, pooling_type="MAX"): """Same global pool, but only for the elements up to the current element. Useful for outputs where the state of future elements is not known. Takes no mask as all elements up to the current element are assumed to exist. Currently only supports maximum. Equivalent to using a lower triangle bias. Args: inputs: A tensor of shape [batch_size, sequence_length, input_dims] containing the sequences of input vectors. pooling_type: Pooling type to use. Currently only supports 'MAX'. Returns: A tensor of shape [batch_size, sequence_length, input_dims] containing the running 'totals'. """ del pooling_type with tf.name_scope("running_global_pool", values=[inputs]): scan_fct = tf.maximum # Permute inputs so seq_length is first. elems = tf.transpose(inputs, [1, 0, 2]) # Perform scan. cumulatives = tf.scan(scan_fct, elems, swap_memory=True) # Permute output to get back to original order. output = tf.transpose(cumulatives, [1, 0, 2]) return output
[ "def", "running_global_pool_1d", "(", "inputs", ",", "pooling_type", "=", "\"MAX\"", ")", ":", "del", "pooling_type", "with", "tf", ".", "name_scope", "(", "\"running_global_pool\"", ",", "values", "=", "[", "inputs", "]", ")", ":", "scan_fct", "=", "tf", ".", "maximum", "# Permute inputs so seq_length is first.", "elems", "=", "tf", ".", "transpose", "(", "inputs", ",", "[", "1", ",", "0", ",", "2", "]", ")", "# Perform scan.", "cumulatives", "=", "tf", ".", "scan", "(", "scan_fct", ",", "elems", ",", "swap_memory", "=", "True", ")", "# Permute output to get back to original order.", "output", "=", "tf", ".", "transpose", "(", "cumulatives", ",", "[", "1", ",", "0", ",", "2", "]", ")", "return", "output" ]
Same global pool, but only for the elements up to the current element. Useful for outputs where the state of future elements is not known. Takes no mask as all elements up to the current element are assumed to exist. Currently only supports maximum. Equivalent to using a lower triangle bias. Args: inputs: A tensor of shape [batch_size, sequence_length, input_dims] containing the sequences of input vectors. pooling_type: Pooling type to use. Currently only supports 'MAX'. Returns: A tensor of shape [batch_size, sequence_length, input_dims] containing the running 'totals'.
[ "Same", "global", "pool", "but", "only", "for", "the", "elements", "up", "to", "the", "current", "element", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L2189-L2214
22,178
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
gated_linear_unit_layer
def gated_linear_unit_layer(x, name=None): """Gated linear unit layer. Paper: Language Modeling with Gated Convolutional Networks. Link: https://arxiv.org/abs/1612.08083 x = Wx * sigmoid(W'x). Args: x: A tensor name: A string Returns: A tensor of the same shape as x. """ with tf.variable_scope(name, default_name="glu_layer", values=[x]): depth = shape_list(x)[-1] x = layers().Dense(depth * 2, activation=None)(x) x, gating_x = tf.split(x, 2, axis=-1) return x * tf.nn.sigmoid(gating_x)
python
def gated_linear_unit_layer(x, name=None): """Gated linear unit layer. Paper: Language Modeling with Gated Convolutional Networks. Link: https://arxiv.org/abs/1612.08083 x = Wx * sigmoid(W'x). Args: x: A tensor name: A string Returns: A tensor of the same shape as x. """ with tf.variable_scope(name, default_name="glu_layer", values=[x]): depth = shape_list(x)[-1] x = layers().Dense(depth * 2, activation=None)(x) x, gating_x = tf.split(x, 2, axis=-1) return x * tf.nn.sigmoid(gating_x)
[ "def", "gated_linear_unit_layer", "(", "x", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ",", "default_name", "=", "\"glu_layer\"", ",", "values", "=", "[", "x", "]", ")", ":", "depth", "=", "shape_list", "(", "x", ")", "[", "-", "1", "]", "x", "=", "layers", "(", ")", ".", "Dense", "(", "depth", "*", "2", ",", "activation", "=", "None", ")", "(", "x", ")", "x", ",", "gating_x", "=", "tf", ".", "split", "(", "x", ",", "2", ",", "axis", "=", "-", "1", ")", "return", "x", "*", "tf", ".", "nn", ".", "sigmoid", "(", "gating_x", ")" ]
Gated linear unit layer. Paper: Language Modeling with Gated Convolutional Networks. Link: https://arxiv.org/abs/1612.08083 x = Wx * sigmoid(W'x). Args: x: A tensor name: A string Returns: A tensor of the same shape as x.
[ "Gated", "linear", "unit", "layer", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L2217-L2235
22,179
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
linear_set_layer
def linear_set_layer(layer_size, inputs, context=None, activation_fn=tf.nn.relu, dropout=0.0, name=None): """Basic layer type for doing funky things with sets. Applies a linear transformation to each element in the input set. If a context is supplied, it is concatenated with the inputs. e.g. One can use global_pool_1d to get a representation of the set which can then be used as the context for the next layer. TODO: Add bias add (or control the biases used). Args: layer_size: Dimension to transform the input vectors to. inputs: A tensor of shape [batch_size, sequence_length, input_dims] containing the sequences of input vectors. context: A tensor of shape [batch_size, context_dims] containing a global statistic about the set. activation_fn: The activation function to use. dropout: Dropout probability. name: name. Returns: Tensor of shape [batch_size, sequence_length, output_dims] containing the sequences of transformed vectors. """ with tf.variable_scope( name, default_name="linear_set_layer", values=[inputs]): # Apply 1D convolution to apply linear filter to each element # along the 2nd dimension. outputs = conv1d(inputs, layer_size, 1, activation=None, name="set_conv") # Apply the context if it exists. if context is not None: # Unfortunately tf doesn't support broadcasting via concat, but we can # simply add the transformed context to get the same effect. if len(context.get_shape().as_list()) == 2: context = tf.expand_dims(context, axis=1) cont_tfm = conv1d( context, layer_size, 1, activation=None, name="cont_conv") outputs += cont_tfm if activation_fn is not None: outputs = activation_fn(outputs) if dropout != 0.0: outputs = tf.nn.dropout(outputs, 1.0 - dropout) return outputs
python
def linear_set_layer(layer_size, inputs, context=None, activation_fn=tf.nn.relu, dropout=0.0, name=None): """Basic layer type for doing funky things with sets. Applies a linear transformation to each element in the input set. If a context is supplied, it is concatenated with the inputs. e.g. One can use global_pool_1d to get a representation of the set which can then be used as the context for the next layer. TODO: Add bias add (or control the biases used). Args: layer_size: Dimension to transform the input vectors to. inputs: A tensor of shape [batch_size, sequence_length, input_dims] containing the sequences of input vectors. context: A tensor of shape [batch_size, context_dims] containing a global statistic about the set. activation_fn: The activation function to use. dropout: Dropout probability. name: name. Returns: Tensor of shape [batch_size, sequence_length, output_dims] containing the sequences of transformed vectors. """ with tf.variable_scope( name, default_name="linear_set_layer", values=[inputs]): # Apply 1D convolution to apply linear filter to each element # along the 2nd dimension. outputs = conv1d(inputs, layer_size, 1, activation=None, name="set_conv") # Apply the context if it exists. if context is not None: # Unfortunately tf doesn't support broadcasting via concat, but we can # simply add the transformed context to get the same effect. if len(context.get_shape().as_list()) == 2: context = tf.expand_dims(context, axis=1) cont_tfm = conv1d( context, layer_size, 1, activation=None, name="cont_conv") outputs += cont_tfm if activation_fn is not None: outputs = activation_fn(outputs) if dropout != 0.0: outputs = tf.nn.dropout(outputs, 1.0 - dropout) return outputs
[ "def", "linear_set_layer", "(", "layer_size", ",", "inputs", ",", "context", "=", "None", ",", "activation_fn", "=", "tf", ".", "nn", ".", "relu", ",", "dropout", "=", "0.0", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ",", "default_name", "=", "\"linear_set_layer\"", ",", "values", "=", "[", "inputs", "]", ")", ":", "# Apply 1D convolution to apply linear filter to each element", "# along the 2nd dimension.", "outputs", "=", "conv1d", "(", "inputs", ",", "layer_size", ",", "1", ",", "activation", "=", "None", ",", "name", "=", "\"set_conv\"", ")", "# Apply the context if it exists.", "if", "context", "is", "not", "None", ":", "# Unfortunately tf doesn't support broadcasting via concat, but we can", "# simply add the transformed context to get the same effect.", "if", "len", "(", "context", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", ")", "==", "2", ":", "context", "=", "tf", ".", "expand_dims", "(", "context", ",", "axis", "=", "1", ")", "cont_tfm", "=", "conv1d", "(", "context", ",", "layer_size", ",", "1", ",", "activation", "=", "None", ",", "name", "=", "\"cont_conv\"", ")", "outputs", "+=", "cont_tfm", "if", "activation_fn", "is", "not", "None", ":", "outputs", "=", "activation_fn", "(", "outputs", ")", "if", "dropout", "!=", "0.0", ":", "outputs", "=", "tf", ".", "nn", ".", "dropout", "(", "outputs", ",", "1.0", "-", "dropout", ")", "return", "outputs" ]
Basic layer type for doing funky things with sets. Applies a linear transformation to each element in the input set. If a context is supplied, it is concatenated with the inputs. e.g. One can use global_pool_1d to get a representation of the set which can then be used as the context for the next layer. TODO: Add bias add (or control the biases used). Args: layer_size: Dimension to transform the input vectors to. inputs: A tensor of shape [batch_size, sequence_length, input_dims] containing the sequences of input vectors. context: A tensor of shape [batch_size, context_dims] containing a global statistic about the set. activation_fn: The activation function to use. dropout: Dropout probability. name: name. Returns: Tensor of shape [batch_size, sequence_length, output_dims] containing the sequences of transformed vectors.
[ "Basic", "layer", "type", "for", "doing", "funky", "things", "with", "sets", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L2389-L2440
22,180
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
fn_device_dependency_dict
def fn_device_dependency_dict(): """State container for fn_device_dependency.""" default_graph = tf.get_default_graph() if not hasattr(default_graph, "dependency_dict"): default_graph.dependency_dict = collections.defaultdict(list) return default_graph.dependency_dict
python
def fn_device_dependency_dict(): """State container for fn_device_dependency.""" default_graph = tf.get_default_graph() if not hasattr(default_graph, "dependency_dict"): default_graph.dependency_dict = collections.defaultdict(list) return default_graph.dependency_dict
[ "def", "fn_device_dependency_dict", "(", ")", ":", "default_graph", "=", "tf", ".", "get_default_graph", "(", ")", "if", "not", "hasattr", "(", "default_graph", ",", "\"dependency_dict\"", ")", ":", "default_graph", ".", "dependency_dict", "=", "collections", ".", "defaultdict", "(", "list", ")", "return", "default_graph", ".", "dependency_dict" ]
State container for fn_device_dependency.
[ "State", "container", "for", "fn_device_dependency", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L2486-L2491
22,181
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
fn_device_dependency
def fn_device_dependency(name, device=""): """Add control deps for name and device.""" key = name + "_" + device outs = [] def body(): with tf.control_dependencies(fn_device_dependency_dict()[key]): yield outs assert outs deps = outs if isinstance(outs[0], (list, tuple)): assert len(outs) == 1 deps = outs[0] fn_device_dependency_dict()[key] = deps if device: with tf.device(device): return body() else: return body()
python
def fn_device_dependency(name, device=""): """Add control deps for name and device.""" key = name + "_" + device outs = [] def body(): with tf.control_dependencies(fn_device_dependency_dict()[key]): yield outs assert outs deps = outs if isinstance(outs[0], (list, tuple)): assert len(outs) == 1 deps = outs[0] fn_device_dependency_dict()[key] = deps if device: with tf.device(device): return body() else: return body()
[ "def", "fn_device_dependency", "(", "name", ",", "device", "=", "\"\"", ")", ":", "key", "=", "name", "+", "\"_\"", "+", "device", "outs", "=", "[", "]", "def", "body", "(", ")", ":", "with", "tf", ".", "control_dependencies", "(", "fn_device_dependency_dict", "(", ")", "[", "key", "]", ")", ":", "yield", "outs", "assert", "outs", "deps", "=", "outs", "if", "isinstance", "(", "outs", "[", "0", "]", ",", "(", "list", ",", "tuple", ")", ")", ":", "assert", "len", "(", "outs", ")", "==", "1", "deps", "=", "outs", "[", "0", "]", "fn_device_dependency_dict", "(", ")", "[", "key", "]", "=", "deps", "if", "device", ":", "with", "tf", ".", "device", "(", "device", ")", ":", "return", "body", "(", ")", "else", ":", "return", "body", "(", ")" ]
Add control deps for name and device.
[ "Add", "control", "deps", "for", "name", "and", "device", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L2495-L2515
22,182
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
underlying_variable_ref
def underlying_variable_ref(t): """Find the underlying variable ref. Traverses through Identity, ReadVariableOp, and Enter ops. Stops when op type has Variable or VarHandle in name. Args: t: a Tensor Returns: a Tensor that is a variable ref, or None on error. """ while t.op.type in ["Identity", "ReadVariableOp", "Enter"]: t = t.op.inputs[0] op_type = t.op.type if "Variable" in op_type or "VarHandle" in op_type: return t else: return None
python
def underlying_variable_ref(t): """Find the underlying variable ref. Traverses through Identity, ReadVariableOp, and Enter ops. Stops when op type has Variable or VarHandle in name. Args: t: a Tensor Returns: a Tensor that is a variable ref, or None on error. """ while t.op.type in ["Identity", "ReadVariableOp", "Enter"]: t = t.op.inputs[0] op_type = t.op.type if "Variable" in op_type or "VarHandle" in op_type: return t else: return None
[ "def", "underlying_variable_ref", "(", "t", ")", ":", "while", "t", ".", "op", ".", "type", "in", "[", "\"Identity\"", ",", "\"ReadVariableOp\"", ",", "\"Enter\"", "]", ":", "t", "=", "t", ".", "op", ".", "inputs", "[", "0", "]", "op_type", "=", "t", ".", "op", ".", "type", "if", "\"Variable\"", "in", "op_type", "or", "\"VarHandle\"", "in", "op_type", ":", "return", "t", "else", ":", "return", "None" ]
Find the underlying variable ref. Traverses through Identity, ReadVariableOp, and Enter ops. Stops when op type has Variable or VarHandle in name. Args: t: a Tensor Returns: a Tensor that is a variable ref, or None on error.
[ "Find", "the", "underlying", "variable", "ref", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L2518-L2537
22,183
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
underlying_variable
def underlying_variable(t): """Find the underlying tf.Variable object. Args: t: a Tensor Returns: tf.Variable. """ t = underlying_variable_ref(t) assert t is not None # make sure that the graph has a variable index and that it is up-to-date if not hasattr(tf.get_default_graph(), "var_index"): tf.get_default_graph().var_index = {} var_index = tf.get_default_graph().var_index for v in tf.global_variables()[len(var_index):]: var_index[v.name] = v return var_index[t.name]
python
def underlying_variable(t): """Find the underlying tf.Variable object. Args: t: a Tensor Returns: tf.Variable. """ t = underlying_variable_ref(t) assert t is not None # make sure that the graph has a variable index and that it is up-to-date if not hasattr(tf.get_default_graph(), "var_index"): tf.get_default_graph().var_index = {} var_index = tf.get_default_graph().var_index for v in tf.global_variables()[len(var_index):]: var_index[v.name] = v return var_index[t.name]
[ "def", "underlying_variable", "(", "t", ")", ":", "t", "=", "underlying_variable_ref", "(", "t", ")", "assert", "t", "is", "not", "None", "# make sure that the graph has a variable index and that it is up-to-date", "if", "not", "hasattr", "(", "tf", ".", "get_default_graph", "(", ")", ",", "\"var_index\"", ")", ":", "tf", ".", "get_default_graph", "(", ")", ".", "var_index", "=", "{", "}", "var_index", "=", "tf", ".", "get_default_graph", "(", ")", ".", "var_index", "for", "v", "in", "tf", ".", "global_variables", "(", ")", "[", "len", "(", "var_index", ")", ":", "]", ":", "var_index", "[", "v", ".", "name", "]", "=", "v", "return", "var_index", "[", "t", ".", "name", "]" ]
Find the underlying tf.Variable object. Args: t: a Tensor Returns: tf.Variable.
[ "Find", "the", "underlying", "tf", ".", "Variable", "object", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L2540-L2557
22,184
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
approximate_split
def approximate_split(x, num_splits, axis=0): """Split approximately equally into num_splits parts. Args: x: a Tensor num_splits: an integer axis: an integer. Returns: a list of num_splits Tensors. """ size = shape_list(x)[axis] size_splits = [tf.div(size + i, num_splits) for i in range(num_splits)] return tf.split(x, size_splits, axis=axis)
python
def approximate_split(x, num_splits, axis=0): """Split approximately equally into num_splits parts. Args: x: a Tensor num_splits: an integer axis: an integer. Returns: a list of num_splits Tensors. """ size = shape_list(x)[axis] size_splits = [tf.div(size + i, num_splits) for i in range(num_splits)] return tf.split(x, size_splits, axis=axis)
[ "def", "approximate_split", "(", "x", ",", "num_splits", ",", "axis", "=", "0", ")", ":", "size", "=", "shape_list", "(", "x", ")", "[", "axis", "]", "size_splits", "=", "[", "tf", ".", "div", "(", "size", "+", "i", ",", "num_splits", ")", "for", "i", "in", "range", "(", "num_splits", ")", "]", "return", "tf", ".", "split", "(", "x", ",", "size_splits", ",", "axis", "=", "axis", ")" ]
Split approximately equally into num_splits parts. Args: x: a Tensor num_splits: an integer axis: an integer. Returns: a list of num_splits Tensors.
[ "Split", "approximately", "equally", "into", "num_splits", "parts", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L2560-L2573
22,185
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
smoothing_cross_entropy_factored_grad
def smoothing_cross_entropy_factored_grad(op, dy): """Gradient function for smoothing_cross_entropy_factored.""" a = op.inputs[0] b = op.inputs[1] labels = op.inputs[2] confidence = op.inputs[3] num_splits = 16 vocab_size = shape_list(b)[0] labels = approximate_split(labels, num_splits) a = approximate_split(a, num_splits) dy = approximate_split(dy, num_splits) b_grad = None a_grad_parts = [] deps = [] for part in range(num_splits): with tf.control_dependencies(deps): logits = tf.matmul(a[part], b, transpose_b=True) output_part = smoothing_cross_entropy(logits, labels[part], vocab_size, confidence) a_grad_part, b_grad_part = tf.gradients( ys=[output_part], xs=[a[part], b], grad_ys=[dy[part]]) a_grad_parts.append(a_grad_part) if part > 0: b_grad += b_grad_part else: b_grad = b_grad_part deps = [b_grad, a_grad_part] a_grad = tf.concat(a_grad_parts, 0) return a_grad, b_grad, None, None
python
def smoothing_cross_entropy_factored_grad(op, dy): """Gradient function for smoothing_cross_entropy_factored.""" a = op.inputs[0] b = op.inputs[1] labels = op.inputs[2] confidence = op.inputs[3] num_splits = 16 vocab_size = shape_list(b)[0] labels = approximate_split(labels, num_splits) a = approximate_split(a, num_splits) dy = approximate_split(dy, num_splits) b_grad = None a_grad_parts = [] deps = [] for part in range(num_splits): with tf.control_dependencies(deps): logits = tf.matmul(a[part], b, transpose_b=True) output_part = smoothing_cross_entropy(logits, labels[part], vocab_size, confidence) a_grad_part, b_grad_part = tf.gradients( ys=[output_part], xs=[a[part], b], grad_ys=[dy[part]]) a_grad_parts.append(a_grad_part) if part > 0: b_grad += b_grad_part else: b_grad = b_grad_part deps = [b_grad, a_grad_part] a_grad = tf.concat(a_grad_parts, 0) return a_grad, b_grad, None, None
[ "def", "smoothing_cross_entropy_factored_grad", "(", "op", ",", "dy", ")", ":", "a", "=", "op", ".", "inputs", "[", "0", "]", "b", "=", "op", ".", "inputs", "[", "1", "]", "labels", "=", "op", ".", "inputs", "[", "2", "]", "confidence", "=", "op", ".", "inputs", "[", "3", "]", "num_splits", "=", "16", "vocab_size", "=", "shape_list", "(", "b", ")", "[", "0", "]", "labels", "=", "approximate_split", "(", "labels", ",", "num_splits", ")", "a", "=", "approximate_split", "(", "a", ",", "num_splits", ")", "dy", "=", "approximate_split", "(", "dy", ",", "num_splits", ")", "b_grad", "=", "None", "a_grad_parts", "=", "[", "]", "deps", "=", "[", "]", "for", "part", "in", "range", "(", "num_splits", ")", ":", "with", "tf", ".", "control_dependencies", "(", "deps", ")", ":", "logits", "=", "tf", ".", "matmul", "(", "a", "[", "part", "]", ",", "b", ",", "transpose_b", "=", "True", ")", "output_part", "=", "smoothing_cross_entropy", "(", "logits", ",", "labels", "[", "part", "]", ",", "vocab_size", ",", "confidence", ")", "a_grad_part", ",", "b_grad_part", "=", "tf", ".", "gradients", "(", "ys", "=", "[", "output_part", "]", ",", "xs", "=", "[", "a", "[", "part", "]", ",", "b", "]", ",", "grad_ys", "=", "[", "dy", "[", "part", "]", "]", ")", "a_grad_parts", ".", "append", "(", "a_grad_part", ")", "if", "part", ">", "0", ":", "b_grad", "+=", "b_grad_part", "else", ":", "b_grad", "=", "b_grad_part", "deps", "=", "[", "b_grad", ",", "a_grad_part", "]", "a_grad", "=", "tf", ".", "concat", "(", "a_grad_parts", ",", "0", ")", "return", "a_grad", ",", "b_grad", ",", "None", ",", "None" ]
Gradient function for smoothing_cross_entropy_factored.
[ "Gradient", "function", "for", "smoothing_cross_entropy_factored", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L2625-L2653
22,186
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
fn_with_custom_grad
def fn_with_custom_grad(grad_fn, use_global_vars=False): """Decorator to create a subgraph with a custom gradient function. The subgraph created by the decorated function is NOT put in a Defun and so does not suffer from the limitations of the Defun (all subgraph ops on the same device, no summaries). Args: grad_fn: function with signature (inputs, variables, outputs, output_grads) -> (grad_inputs, grad_vars), all of which are lists of Tensors. use_global_vars: if True, variables will be the global variables created. If False, will be the trainable variables. Returns: Decorator for function such that the gradient is defined by grad_fn. """ def dec(fn): @functools.wraps(fn) def wrapped(*args): return _fn_with_custom_grad( fn, args, grad_fn, use_global_vars=use_global_vars) return wrapped return dec
python
def fn_with_custom_grad(grad_fn, use_global_vars=False): """Decorator to create a subgraph with a custom gradient function. The subgraph created by the decorated function is NOT put in a Defun and so does not suffer from the limitations of the Defun (all subgraph ops on the same device, no summaries). Args: grad_fn: function with signature (inputs, variables, outputs, output_grads) -> (grad_inputs, grad_vars), all of which are lists of Tensors. use_global_vars: if True, variables will be the global variables created. If False, will be the trainable variables. Returns: Decorator for function such that the gradient is defined by grad_fn. """ def dec(fn): @functools.wraps(fn) def wrapped(*args): return _fn_with_custom_grad( fn, args, grad_fn, use_global_vars=use_global_vars) return wrapped return dec
[ "def", "fn_with_custom_grad", "(", "grad_fn", ",", "use_global_vars", "=", "False", ")", ":", "def", "dec", "(", "fn", ")", ":", "@", "functools", ".", "wraps", "(", "fn", ")", "def", "wrapped", "(", "*", "args", ")", ":", "return", "_fn_with_custom_grad", "(", "fn", ",", "args", ",", "grad_fn", ",", "use_global_vars", "=", "use_global_vars", ")", "return", "wrapped", "return", "dec" ]
Decorator to create a subgraph with a custom gradient function. The subgraph created by the decorated function is NOT put in a Defun and so does not suffer from the limitations of the Defun (all subgraph ops on the same device, no summaries). Args: grad_fn: function with signature (inputs, variables, outputs, output_grads) -> (grad_inputs, grad_vars), all of which are lists of Tensors. use_global_vars: if True, variables will be the global variables created. If False, will be the trainable variables. Returns: Decorator for function such that the gradient is defined by grad_fn.
[ "Decorator", "to", "create", "a", "subgraph", "with", "a", "custom", "gradient", "function", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L2724-L2751
22,187
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
_fn_with_custom_grad
def _fn_with_custom_grad(fn, inputs, grad_fn, use_global_vars=False): """Create a subgraph with a custom gradient. Args: fn: function that takes inputs as arguments and produces 1 or more Tensors. inputs: list<Tensor>, will be passed as fn(*inputs). grad_fn: function with signature (inputs, vars, outputs, output_grads) -> (grad_inputs, grad_vars), all of which are lists of Tensors. use_global_vars: if True, variables will be the global variables created. If False, will be the trainable variables. Returns: fn(*inputs) """ vs = tf.get_variable_scope() get_vars_fn = ( vs.global_variables if use_global_vars else vs.trainable_variables) len_before_vars = len(get_vars_fn()) inputs = list(inputs) outputs = fn(*inputs) train_vars = get_vars_fn()[len_before_vars:] if grad_fn is None: return outputs if not isinstance(outputs, (tuple, list)): outputs = [outputs] outputs = list(outputs) defun_inputs = [inputs, train_vars, outputs] def custom_grad_fn(op, *dys): """Custom grad fn applying grad_fn for identity Defun.""" fn_inputs, fn_vars, fn_outputs = tf.contrib.framework.nest.pack_sequence_as( defun_inputs, list(op.inputs)) dys = list(dys) assert len(fn_outputs) == len(outputs) assert len(fn_outputs) == len(dys) grad_inputs, grad_vars = grad_fn(fn_inputs, fn_vars, fn_outputs, dys) grad_outputs = [None] * len(fn_outputs) return tuple(grad_inputs + grad_vars + grad_outputs) # The Defun takes as input the original inputs, the trainable variables # created in fn, and the outputs. In the forward it passes through the # outputs. In the backwards, it produces gradients for the original inputs # and the trainable variables. in_types = [t.dtype for t in inputs] out_types = [t.dtype for t in outputs] var_types = [t.dtype for t in train_vars] @function.Defun( *(in_types + var_types + out_types), func_name="identity_custom_grad%d" % ops.uid(), python_grad_func=custom_grad_fn, shape_func=lambda _: [t.get_shape() for t in outputs]) def identity(*args): _, _, outs = tf.contrib.framework.nest.pack_sequence_as(defun_inputs, args) return tuple([tf.identity(t) for t in outs]) flat_inputs = tf.contrib.framework.nest.flatten(defun_inputs) id_out = identity(*flat_inputs) return id_out
python
def _fn_with_custom_grad(fn, inputs, grad_fn, use_global_vars=False): """Create a subgraph with a custom gradient. Args: fn: function that takes inputs as arguments and produces 1 or more Tensors. inputs: list<Tensor>, will be passed as fn(*inputs). grad_fn: function with signature (inputs, vars, outputs, output_grads) -> (grad_inputs, grad_vars), all of which are lists of Tensors. use_global_vars: if True, variables will be the global variables created. If False, will be the trainable variables. Returns: fn(*inputs) """ vs = tf.get_variable_scope() get_vars_fn = ( vs.global_variables if use_global_vars else vs.trainable_variables) len_before_vars = len(get_vars_fn()) inputs = list(inputs) outputs = fn(*inputs) train_vars = get_vars_fn()[len_before_vars:] if grad_fn is None: return outputs if not isinstance(outputs, (tuple, list)): outputs = [outputs] outputs = list(outputs) defun_inputs = [inputs, train_vars, outputs] def custom_grad_fn(op, *dys): """Custom grad fn applying grad_fn for identity Defun.""" fn_inputs, fn_vars, fn_outputs = tf.contrib.framework.nest.pack_sequence_as( defun_inputs, list(op.inputs)) dys = list(dys) assert len(fn_outputs) == len(outputs) assert len(fn_outputs) == len(dys) grad_inputs, grad_vars = grad_fn(fn_inputs, fn_vars, fn_outputs, dys) grad_outputs = [None] * len(fn_outputs) return tuple(grad_inputs + grad_vars + grad_outputs) # The Defun takes as input the original inputs, the trainable variables # created in fn, and the outputs. In the forward it passes through the # outputs. In the backwards, it produces gradients for the original inputs # and the trainable variables. in_types = [t.dtype for t in inputs] out_types = [t.dtype for t in outputs] var_types = [t.dtype for t in train_vars] @function.Defun( *(in_types + var_types + out_types), func_name="identity_custom_grad%d" % ops.uid(), python_grad_func=custom_grad_fn, shape_func=lambda _: [t.get_shape() for t in outputs]) def identity(*args): _, _, outs = tf.contrib.framework.nest.pack_sequence_as(defun_inputs, args) return tuple([tf.identity(t) for t in outs]) flat_inputs = tf.contrib.framework.nest.flatten(defun_inputs) id_out = identity(*flat_inputs) return id_out
[ "def", "_fn_with_custom_grad", "(", "fn", ",", "inputs", ",", "grad_fn", ",", "use_global_vars", "=", "False", ")", ":", "vs", "=", "tf", ".", "get_variable_scope", "(", ")", "get_vars_fn", "=", "(", "vs", ".", "global_variables", "if", "use_global_vars", "else", "vs", ".", "trainable_variables", ")", "len_before_vars", "=", "len", "(", "get_vars_fn", "(", ")", ")", "inputs", "=", "list", "(", "inputs", ")", "outputs", "=", "fn", "(", "*", "inputs", ")", "train_vars", "=", "get_vars_fn", "(", ")", "[", "len_before_vars", ":", "]", "if", "grad_fn", "is", "None", ":", "return", "outputs", "if", "not", "isinstance", "(", "outputs", ",", "(", "tuple", ",", "list", ")", ")", ":", "outputs", "=", "[", "outputs", "]", "outputs", "=", "list", "(", "outputs", ")", "defun_inputs", "=", "[", "inputs", ",", "train_vars", ",", "outputs", "]", "def", "custom_grad_fn", "(", "op", ",", "*", "dys", ")", ":", "\"\"\"Custom grad fn applying grad_fn for identity Defun.\"\"\"", "fn_inputs", ",", "fn_vars", ",", "fn_outputs", "=", "tf", ".", "contrib", ".", "framework", ".", "nest", ".", "pack_sequence_as", "(", "defun_inputs", ",", "list", "(", "op", ".", "inputs", ")", ")", "dys", "=", "list", "(", "dys", ")", "assert", "len", "(", "fn_outputs", ")", "==", "len", "(", "outputs", ")", "assert", "len", "(", "fn_outputs", ")", "==", "len", "(", "dys", ")", "grad_inputs", ",", "grad_vars", "=", "grad_fn", "(", "fn_inputs", ",", "fn_vars", ",", "fn_outputs", ",", "dys", ")", "grad_outputs", "=", "[", "None", "]", "*", "len", "(", "fn_outputs", ")", "return", "tuple", "(", "grad_inputs", "+", "grad_vars", "+", "grad_outputs", ")", "# The Defun takes as input the original inputs, the trainable variables", "# created in fn, and the outputs. In the forward it passes through the", "# outputs. In the backwards, it produces gradients for the original inputs", "# and the trainable variables.", "in_types", "=", "[", "t", ".", "dtype", "for", "t", "in", "inputs", "]", "out_types", "=", "[", "t", ".", "dtype", "for", "t", "in", "outputs", "]", "var_types", "=", "[", "t", ".", "dtype", "for", "t", "in", "train_vars", "]", "@", "function", ".", "Defun", "(", "*", "(", "in_types", "+", "var_types", "+", "out_types", ")", ",", "func_name", "=", "\"identity_custom_grad%d\"", "%", "ops", ".", "uid", "(", ")", ",", "python_grad_func", "=", "custom_grad_fn", ",", "shape_func", "=", "lambda", "_", ":", "[", "t", ".", "get_shape", "(", ")", "for", "t", "in", "outputs", "]", ")", "def", "identity", "(", "*", "args", ")", ":", "_", ",", "_", ",", "outs", "=", "tf", ".", "contrib", ".", "framework", ".", "nest", ".", "pack_sequence_as", "(", "defun_inputs", ",", "args", ")", "return", "tuple", "(", "[", "tf", ".", "identity", "(", "t", ")", "for", "t", "in", "outs", "]", ")", "flat_inputs", "=", "tf", ".", "contrib", ".", "framework", ".", "nest", ".", "flatten", "(", "defun_inputs", ")", "id_out", "=", "identity", "(", "*", "flat_inputs", ")", "return", "id_out" ]
Create a subgraph with a custom gradient. Args: fn: function that takes inputs as arguments and produces 1 or more Tensors. inputs: list<Tensor>, will be passed as fn(*inputs). grad_fn: function with signature (inputs, vars, outputs, output_grads) -> (grad_inputs, grad_vars), all of which are lists of Tensors. use_global_vars: if True, variables will be the global variables created. If False, will be the trainable variables. Returns: fn(*inputs)
[ "Create", "a", "subgraph", "with", "a", "custom", "gradient", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L2754-L2817
22,188
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
shape_list
def shape_list(x): """Return list of dims, statically where possible.""" x = tf.convert_to_tensor(x) # If unknown rank, return dynamic shape if x.get_shape().dims is None: return tf.shape(x) static = x.get_shape().as_list() shape = tf.shape(x) ret = [] for i, dim in enumerate(static): if dim is None: dim = shape[i] ret.append(dim) return ret
python
def shape_list(x): """Return list of dims, statically where possible.""" x = tf.convert_to_tensor(x) # If unknown rank, return dynamic shape if x.get_shape().dims is None: return tf.shape(x) static = x.get_shape().as_list() shape = tf.shape(x) ret = [] for i, dim in enumerate(static): if dim is None: dim = shape[i] ret.append(dim) return ret
[ "def", "shape_list", "(", "x", ")", ":", "x", "=", "tf", ".", "convert_to_tensor", "(", "x", ")", "# If unknown rank, return dynamic shape", "if", "x", ".", "get_shape", "(", ")", ".", "dims", "is", "None", ":", "return", "tf", ".", "shape", "(", "x", ")", "static", "=", "x", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "shape", "=", "tf", ".", "shape", "(", "x", ")", "ret", "=", "[", "]", "for", "i", ",", "dim", "in", "enumerate", "(", "static", ")", ":", "if", "dim", "is", "None", ":", "dim", "=", "shape", "[", "i", "]", "ret", ".", "append", "(", "dim", ")", "return", "ret" ]
Return list of dims, statically where possible.
[ "Return", "list", "of", "dims", "statically", "where", "possible", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L2933-L2949
22,189
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
ones_matrix_band_part
def ones_matrix_band_part(rows, cols, num_lower, num_upper, out_shape=None): """Matrix band part of ones. Args: rows: int determining number of rows in output cols: int num_lower: int, maximum distance backward. Negative values indicate unlimited. num_upper: int, maximum distance forward. Negative values indicate unlimited. out_shape: shape to reshape output by. Returns: Tensor of size rows * cols reshaped into shape out_shape. """ if all([isinstance(el, int) for el in [rows, cols, num_lower, num_upper]]): # Needed info is constant, so we construct in numpy if num_lower < 0: num_lower = rows - 1 if num_upper < 0: num_upper = cols - 1 lower_mask = np.tri(cols, rows, num_lower).T upper_mask = np.tri(rows, cols, num_upper) band = np.ones((rows, cols)) * lower_mask * upper_mask if out_shape: band = band.reshape(out_shape) band = tf.constant(band, tf.float32) else: band = tf.matrix_band_part( tf.ones([rows, cols]), tf.cast(num_lower, tf.int64), tf.cast(num_upper, tf.int64)) if out_shape: band = tf.reshape(band, out_shape) return band
python
def ones_matrix_band_part(rows, cols, num_lower, num_upper, out_shape=None): """Matrix band part of ones. Args: rows: int determining number of rows in output cols: int num_lower: int, maximum distance backward. Negative values indicate unlimited. num_upper: int, maximum distance forward. Negative values indicate unlimited. out_shape: shape to reshape output by. Returns: Tensor of size rows * cols reshaped into shape out_shape. """ if all([isinstance(el, int) for el in [rows, cols, num_lower, num_upper]]): # Needed info is constant, so we construct in numpy if num_lower < 0: num_lower = rows - 1 if num_upper < 0: num_upper = cols - 1 lower_mask = np.tri(cols, rows, num_lower).T upper_mask = np.tri(rows, cols, num_upper) band = np.ones((rows, cols)) * lower_mask * upper_mask if out_shape: band = band.reshape(out_shape) band = tf.constant(band, tf.float32) else: band = tf.matrix_band_part( tf.ones([rows, cols]), tf.cast(num_lower, tf.int64), tf.cast(num_upper, tf.int64)) if out_shape: band = tf.reshape(band, out_shape) return band
[ "def", "ones_matrix_band_part", "(", "rows", ",", "cols", ",", "num_lower", ",", "num_upper", ",", "out_shape", "=", "None", ")", ":", "if", "all", "(", "[", "isinstance", "(", "el", ",", "int", ")", "for", "el", "in", "[", "rows", ",", "cols", ",", "num_lower", ",", "num_upper", "]", "]", ")", ":", "# Needed info is constant, so we construct in numpy", "if", "num_lower", "<", "0", ":", "num_lower", "=", "rows", "-", "1", "if", "num_upper", "<", "0", ":", "num_upper", "=", "cols", "-", "1", "lower_mask", "=", "np", ".", "tri", "(", "cols", ",", "rows", ",", "num_lower", ")", ".", "T", "upper_mask", "=", "np", ".", "tri", "(", "rows", ",", "cols", ",", "num_upper", ")", "band", "=", "np", ".", "ones", "(", "(", "rows", ",", "cols", ")", ")", "*", "lower_mask", "*", "upper_mask", "if", "out_shape", ":", "band", "=", "band", ".", "reshape", "(", "out_shape", ")", "band", "=", "tf", ".", "constant", "(", "band", ",", "tf", ".", "float32", ")", "else", ":", "band", "=", "tf", ".", "matrix_band_part", "(", "tf", ".", "ones", "(", "[", "rows", ",", "cols", "]", ")", ",", "tf", ".", "cast", "(", "num_lower", ",", "tf", ".", "int64", ")", ",", "tf", ".", "cast", "(", "num_upper", ",", "tf", ".", "int64", ")", ")", "if", "out_shape", ":", "band", "=", "tf", ".", "reshape", "(", "band", ",", "out_shape", ")", "return", "band" ]
Matrix band part of ones. Args: rows: int determining number of rows in output cols: int num_lower: int, maximum distance backward. Negative values indicate unlimited. num_upper: int, maximum distance forward. Negative values indicate unlimited. out_shape: shape to reshape output by. Returns: Tensor of size rows * cols reshaped into shape out_shape.
[ "Matrix", "band", "part", "of", "ones", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3000-L3034
22,190
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
reshape_like_all_dims
def reshape_like_all_dims(a, b): """Reshapes a to match the shape of b.""" ret = tf.reshape(a, tf.shape(b)) if not tf.executing_eagerly(): ret.set_shape(b.get_shape()) return ret
python
def reshape_like_all_dims(a, b): """Reshapes a to match the shape of b.""" ret = tf.reshape(a, tf.shape(b)) if not tf.executing_eagerly(): ret.set_shape(b.get_shape()) return ret
[ "def", "reshape_like_all_dims", "(", "a", ",", "b", ")", ":", "ret", "=", "tf", ".", "reshape", "(", "a", ",", "tf", ".", "shape", "(", "b", ")", ")", "if", "not", "tf", ".", "executing_eagerly", "(", ")", ":", "ret", ".", "set_shape", "(", "b", ".", "get_shape", "(", ")", ")", "return", "ret" ]
Reshapes a to match the shape of b.
[ "Reshapes", "a", "to", "match", "the", "shape", "of", "b", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3037-L3042
22,191
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
recompute_grad
def recompute_grad(fn): """Decorator that recomputes the function on the backwards pass. Args: fn: a function that takes Tensors (all as positional arguments) and returns a tuple of Tensors. Returns: A wrapped fn that is identical to fn when called, but its activations will be discarded and recomputed on the backwards pass (i.e. on a call to tf.gradients). """ @functools.wraps(fn) def wrapped(*args): return _recompute_grad(fn, args) return wrapped
python
def recompute_grad(fn): """Decorator that recomputes the function on the backwards pass. Args: fn: a function that takes Tensors (all as positional arguments) and returns a tuple of Tensors. Returns: A wrapped fn that is identical to fn when called, but its activations will be discarded and recomputed on the backwards pass (i.e. on a call to tf.gradients). """ @functools.wraps(fn) def wrapped(*args): return _recompute_grad(fn, args) return wrapped
[ "def", "recompute_grad", "(", "fn", ")", ":", "@", "functools", ".", "wraps", "(", "fn", ")", "def", "wrapped", "(", "*", "args", ")", ":", "return", "_recompute_grad", "(", "fn", ",", "args", ")", "return", "wrapped" ]
Decorator that recomputes the function on the backwards pass. Args: fn: a function that takes Tensors (all as positional arguments) and returns a tuple of Tensors. Returns: A wrapped fn that is identical to fn when called, but its activations will be discarded and recomputed on the backwards pass (i.e. on a call to tf.gradients).
[ "Decorator", "that", "recomputes", "the", "function", "on", "the", "backwards", "pass", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3045-L3062
22,192
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
_recompute_grad
def _recompute_grad(fn, args): """See recompute_grad.""" cached_vs = [] cached_arg_scope = [] def grad_fn(inputs, variables, outputs, output_grads): """Recompute outputs for gradient computation.""" del outputs variables = [underlying_variable_ref(v) for v in variables] # Recompute outputs with tf.control_dependencies(output_grads): with tf.contrib.framework.arg_scope(cached_arg_scope[0]): with tf.variable_scope(cached_vs[0], reuse=True): outputs = fn(*inputs) if not isinstance(outputs, (list, tuple)): outputs = [outputs] outputs = list(outputs) grads = tf.gradients(outputs, inputs + variables, output_grads) grad_inputs = grads[:len(inputs)] grad_vars = grads[len(inputs):] # TODO(rsepassi): Make fn_with_custom_grad work with bfloat16. # If the input gradients are bfloat16, it's assumed the variables are # bfloat16. This is a hack to ensure that grad_vars are the right type. if grad_inputs[0].dtype == tf.bfloat16: grad_vars = [tf.cast(grad_var, tf.bfloat16) for grad_var in grad_vars] return grad_inputs, grad_vars @fn_with_custom_grad(grad_fn) def fn_with_recompute(*args): cached_vs.append(tf.get_variable_scope()) cached_arg_scope.append(tf.contrib.framework.current_arg_scope()) return fn(*args) return fn_with_recompute(*args)
python
def _recompute_grad(fn, args): """See recompute_grad.""" cached_vs = [] cached_arg_scope = [] def grad_fn(inputs, variables, outputs, output_grads): """Recompute outputs for gradient computation.""" del outputs variables = [underlying_variable_ref(v) for v in variables] # Recompute outputs with tf.control_dependencies(output_grads): with tf.contrib.framework.arg_scope(cached_arg_scope[0]): with tf.variable_scope(cached_vs[0], reuse=True): outputs = fn(*inputs) if not isinstance(outputs, (list, tuple)): outputs = [outputs] outputs = list(outputs) grads = tf.gradients(outputs, inputs + variables, output_grads) grad_inputs = grads[:len(inputs)] grad_vars = grads[len(inputs):] # TODO(rsepassi): Make fn_with_custom_grad work with bfloat16. # If the input gradients are bfloat16, it's assumed the variables are # bfloat16. This is a hack to ensure that grad_vars are the right type. if grad_inputs[0].dtype == tf.bfloat16: grad_vars = [tf.cast(grad_var, tf.bfloat16) for grad_var in grad_vars] return grad_inputs, grad_vars @fn_with_custom_grad(grad_fn) def fn_with_recompute(*args): cached_vs.append(tf.get_variable_scope()) cached_arg_scope.append(tf.contrib.framework.current_arg_scope()) return fn(*args) return fn_with_recompute(*args)
[ "def", "_recompute_grad", "(", "fn", ",", "args", ")", ":", "cached_vs", "=", "[", "]", "cached_arg_scope", "=", "[", "]", "def", "grad_fn", "(", "inputs", ",", "variables", ",", "outputs", ",", "output_grads", ")", ":", "\"\"\"Recompute outputs for gradient computation.\"\"\"", "del", "outputs", "variables", "=", "[", "underlying_variable_ref", "(", "v", ")", "for", "v", "in", "variables", "]", "# Recompute outputs", "with", "tf", ".", "control_dependencies", "(", "output_grads", ")", ":", "with", "tf", ".", "contrib", ".", "framework", ".", "arg_scope", "(", "cached_arg_scope", "[", "0", "]", ")", ":", "with", "tf", ".", "variable_scope", "(", "cached_vs", "[", "0", "]", ",", "reuse", "=", "True", ")", ":", "outputs", "=", "fn", "(", "*", "inputs", ")", "if", "not", "isinstance", "(", "outputs", ",", "(", "list", ",", "tuple", ")", ")", ":", "outputs", "=", "[", "outputs", "]", "outputs", "=", "list", "(", "outputs", ")", "grads", "=", "tf", ".", "gradients", "(", "outputs", ",", "inputs", "+", "variables", ",", "output_grads", ")", "grad_inputs", "=", "grads", "[", ":", "len", "(", "inputs", ")", "]", "grad_vars", "=", "grads", "[", "len", "(", "inputs", ")", ":", "]", "# TODO(rsepassi): Make fn_with_custom_grad work with bfloat16.", "# If the input gradients are bfloat16, it's assumed the variables are", "# bfloat16. This is a hack to ensure that grad_vars are the right type.", "if", "grad_inputs", "[", "0", "]", ".", "dtype", "==", "tf", ".", "bfloat16", ":", "grad_vars", "=", "[", "tf", ".", "cast", "(", "grad_var", ",", "tf", ".", "bfloat16", ")", "for", "grad_var", "in", "grad_vars", "]", "return", "grad_inputs", ",", "grad_vars", "@", "fn_with_custom_grad", "(", "grad_fn", ")", "def", "fn_with_recompute", "(", "*", "args", ")", ":", "cached_vs", ".", "append", "(", "tf", ".", "get_variable_scope", "(", ")", ")", "cached_arg_scope", ".", "append", "(", "tf", ".", "contrib", ".", "framework", ".", "current_arg_scope", "(", ")", ")", "return", "fn", "(", "*", "args", ")", "return", "fn_with_recompute", "(", "*", "args", ")" ]
See recompute_grad.
[ "See", "recompute_grad", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3065-L3100
22,193
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
dense
def dense(x, units, **kwargs): """Identical to layers.dense.""" layer_collection = kwargs.pop("layer_collection", None) activations = layers().Dense(units, **kwargs)(x) if layer_collection: # We need to find the layer parameters using scope name for the layer, so # check that the layer is named. Otherwise parameters for different layers # may get mixed up. layer_name = tf.get_variable_scope().name if (not layer_name) or ("name" not in kwargs): raise ValueError( "Variable scope and layer name cannot be empty. Actual: " "variable_scope={}, layer name={}".format( layer_name, kwargs.get("name", None))) layer_name += "/" + kwargs["name"] layer_params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=layer_name) assert layer_params if len(layer_params) == 1: layer_params = layer_params[0] tf.logging.info( "Registering dense layer to collection for tensor: {}".format( layer_params)) x_shape = x.shape.as_list() if len(x_shape) == 3: # Handle [batch, time, depth] inputs by folding batch and time into # one dimension: reshaping inputs to [batchxtime, depth]. x_2d = tf.reshape(x, [-1, x_shape[2]]) activations_shape = activations.shape.as_list() activations_2d = tf.reshape(activations, [-1, activations_shape[2]]) layer_collection.register_fully_connected_multi( layer_params, x_2d, activations_2d, num_uses=x_shape[1]) activations = tf.reshape(activations_2d, activations_shape) else: layer_collection.register_fully_connected(layer_params, x, activations) return activations
python
def dense(x, units, **kwargs): """Identical to layers.dense.""" layer_collection = kwargs.pop("layer_collection", None) activations = layers().Dense(units, **kwargs)(x) if layer_collection: # We need to find the layer parameters using scope name for the layer, so # check that the layer is named. Otherwise parameters for different layers # may get mixed up. layer_name = tf.get_variable_scope().name if (not layer_name) or ("name" not in kwargs): raise ValueError( "Variable scope and layer name cannot be empty. Actual: " "variable_scope={}, layer name={}".format( layer_name, kwargs.get("name", None))) layer_name += "/" + kwargs["name"] layer_params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=layer_name) assert layer_params if len(layer_params) == 1: layer_params = layer_params[0] tf.logging.info( "Registering dense layer to collection for tensor: {}".format( layer_params)) x_shape = x.shape.as_list() if len(x_shape) == 3: # Handle [batch, time, depth] inputs by folding batch and time into # one dimension: reshaping inputs to [batchxtime, depth]. x_2d = tf.reshape(x, [-1, x_shape[2]]) activations_shape = activations.shape.as_list() activations_2d = tf.reshape(activations, [-1, activations_shape[2]]) layer_collection.register_fully_connected_multi( layer_params, x_2d, activations_2d, num_uses=x_shape[1]) activations = tf.reshape(activations_2d, activations_shape) else: layer_collection.register_fully_connected(layer_params, x, activations) return activations
[ "def", "dense", "(", "x", ",", "units", ",", "*", "*", "kwargs", ")", ":", "layer_collection", "=", "kwargs", ".", "pop", "(", "\"layer_collection\"", ",", "None", ")", "activations", "=", "layers", "(", ")", ".", "Dense", "(", "units", ",", "*", "*", "kwargs", ")", "(", "x", ")", "if", "layer_collection", ":", "# We need to find the layer parameters using scope name for the layer, so", "# check that the layer is named. Otherwise parameters for different layers", "# may get mixed up.", "layer_name", "=", "tf", ".", "get_variable_scope", "(", ")", ".", "name", "if", "(", "not", "layer_name", ")", "or", "(", "\"name\"", "not", "in", "kwargs", ")", ":", "raise", "ValueError", "(", "\"Variable scope and layer name cannot be empty. Actual: \"", "\"variable_scope={}, layer name={}\"", ".", "format", "(", "layer_name", ",", "kwargs", ".", "get", "(", "\"name\"", ",", "None", ")", ")", ")", "layer_name", "+=", "\"/\"", "+", "kwargs", "[", "\"name\"", "]", "layer_params", "=", "tf", ".", "get_collection", "(", "tf", ".", "GraphKeys", ".", "GLOBAL_VARIABLES", ",", "scope", "=", "layer_name", ")", "assert", "layer_params", "if", "len", "(", "layer_params", ")", "==", "1", ":", "layer_params", "=", "layer_params", "[", "0", "]", "tf", ".", "logging", ".", "info", "(", "\"Registering dense layer to collection for tensor: {}\"", ".", "format", "(", "layer_params", ")", ")", "x_shape", "=", "x", ".", "shape", ".", "as_list", "(", ")", "if", "len", "(", "x_shape", ")", "==", "3", ":", "# Handle [batch, time, depth] inputs by folding batch and time into", "# one dimension: reshaping inputs to [batchxtime, depth].", "x_2d", "=", "tf", ".", "reshape", "(", "x", ",", "[", "-", "1", ",", "x_shape", "[", "2", "]", "]", ")", "activations_shape", "=", "activations", ".", "shape", ".", "as_list", "(", ")", "activations_2d", "=", "tf", ".", "reshape", "(", "activations", ",", "[", "-", "1", ",", "activations_shape", "[", "2", "]", "]", ")", "layer_collection", ".", "register_fully_connected_multi", "(", "layer_params", ",", "x_2d", ",", "activations_2d", ",", "num_uses", "=", "x_shape", "[", "1", "]", ")", "activations", "=", "tf", ".", "reshape", "(", "activations_2d", ",", "activations_shape", ")", "else", ":", "layer_collection", ".", "register_fully_connected", "(", "layer_params", ",", "x", ",", "activations", ")", "return", "activations" ]
Identical to layers.dense.
[ "Identical", "to", "layers", ".", "dense", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3103-L3141
22,194
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
batch_dense
def batch_dense(inputs, units, activation=None, kernel_initializer=None, reuse=None, name=None): """Multiply a batch of input matrices by a batch of parameter matrices. Each input matrix is multiplied by the corresponding parameter matrix. This is useful in a mixture-of-experts where the batch represents different experts with different inputs. Args: inputs: a Tensor with shape [batch, length, input_units] units: an integer activation: an optional activation function to apply to the output kernel_initializer: an optional initializer reuse: whether to reuse the varaible scope name: an optional string Returns: a Tensor with shape [batch, length, units] Raises: ValueError: if the "batch" or "input_units" dimensions of inputs are not statically known. """ inputs_shape = shape_list(inputs) if len(inputs_shape) != 3: raise ValueError("inputs must have 3 dimensions") batch = inputs_shape[0] input_units = inputs_shape[2] if not isinstance(batch, int) or not isinstance(input_units, int): raise ValueError("inputs must have static dimensions 0 and 2") with tf.variable_scope( name, default_name="batch_dense", values=[inputs], reuse=reuse, dtype=inputs.dtype): if kernel_initializer is None: kernel_initializer = tf.random_normal_initializer( stddev=input_units**-0.5) w = tf.get_variable( "w", [batch, input_units, units], initializer=kernel_initializer, dtype=inputs.dtype) y = tf.matmul(inputs, w) if activation is not None: y = activation(y) return y
python
def batch_dense(inputs, units, activation=None, kernel_initializer=None, reuse=None, name=None): """Multiply a batch of input matrices by a batch of parameter matrices. Each input matrix is multiplied by the corresponding parameter matrix. This is useful in a mixture-of-experts where the batch represents different experts with different inputs. Args: inputs: a Tensor with shape [batch, length, input_units] units: an integer activation: an optional activation function to apply to the output kernel_initializer: an optional initializer reuse: whether to reuse the varaible scope name: an optional string Returns: a Tensor with shape [batch, length, units] Raises: ValueError: if the "batch" or "input_units" dimensions of inputs are not statically known. """ inputs_shape = shape_list(inputs) if len(inputs_shape) != 3: raise ValueError("inputs must have 3 dimensions") batch = inputs_shape[0] input_units = inputs_shape[2] if not isinstance(batch, int) or not isinstance(input_units, int): raise ValueError("inputs must have static dimensions 0 and 2") with tf.variable_scope( name, default_name="batch_dense", values=[inputs], reuse=reuse, dtype=inputs.dtype): if kernel_initializer is None: kernel_initializer = tf.random_normal_initializer( stddev=input_units**-0.5) w = tf.get_variable( "w", [batch, input_units, units], initializer=kernel_initializer, dtype=inputs.dtype) y = tf.matmul(inputs, w) if activation is not None: y = activation(y) return y
[ "def", "batch_dense", "(", "inputs", ",", "units", ",", "activation", "=", "None", ",", "kernel_initializer", "=", "None", ",", "reuse", "=", "None", ",", "name", "=", "None", ")", ":", "inputs_shape", "=", "shape_list", "(", "inputs", ")", "if", "len", "(", "inputs_shape", ")", "!=", "3", ":", "raise", "ValueError", "(", "\"inputs must have 3 dimensions\"", ")", "batch", "=", "inputs_shape", "[", "0", "]", "input_units", "=", "inputs_shape", "[", "2", "]", "if", "not", "isinstance", "(", "batch", ",", "int", ")", "or", "not", "isinstance", "(", "input_units", ",", "int", ")", ":", "raise", "ValueError", "(", "\"inputs must have static dimensions 0 and 2\"", ")", "with", "tf", ".", "variable_scope", "(", "name", ",", "default_name", "=", "\"batch_dense\"", ",", "values", "=", "[", "inputs", "]", ",", "reuse", "=", "reuse", ",", "dtype", "=", "inputs", ".", "dtype", ")", ":", "if", "kernel_initializer", "is", "None", ":", "kernel_initializer", "=", "tf", ".", "random_normal_initializer", "(", "stddev", "=", "input_units", "**", "-", "0.5", ")", "w", "=", "tf", ".", "get_variable", "(", "\"w\"", ",", "[", "batch", ",", "input_units", ",", "units", "]", ",", "initializer", "=", "kernel_initializer", ",", "dtype", "=", "inputs", ".", "dtype", ")", "y", "=", "tf", ".", "matmul", "(", "inputs", ",", "w", ")", "if", "activation", "is", "not", "None", ":", "y", "=", "activation", "(", "y", ")", "return", "y" ]
Multiply a batch of input matrices by a batch of parameter matrices. Each input matrix is multiplied by the corresponding parameter matrix. This is useful in a mixture-of-experts where the batch represents different experts with different inputs. Args: inputs: a Tensor with shape [batch, length, input_units] units: an integer activation: an optional activation function to apply to the output kernel_initializer: an optional initializer reuse: whether to reuse the varaible scope name: an optional string Returns: a Tensor with shape [batch, length, units] Raises: ValueError: if the "batch" or "input_units" dimensions of inputs are not statically known.
[ "Multiply", "a", "batch", "of", "input", "matrices", "by", "a", "batch", "of", "parameter", "matrices", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3144-L3195
22,195
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
mix
def mix(x1, x2, steps, is_training, min_prob=0.0, max_prob=1.0, mode="lin", simple=False, broadcast_last=False): """Mix starting with x2, mixing mixing, going towards x1.""" with tf.name_scope("mix"): if not is_training: if max_prob >= 1.0: return x1 alpha_shape = shape_list(x1) if broadcast_last: alpha_shape = alpha_shape[:-1] + [1] alpha = tf.random_uniform(alpha_shape) alpha = to_float(tf.less(alpha, max_prob)) return alpha * x1 + (1.0 - alpha) * x2 def get_res(): """Create the result. Separate function to speed it up later (see below). Returns: Tensor of mixed inputs. """ if mode == "lin": alpha_p = inverse_lin_decay(steps) else: alpha_p = inverse_exp_decay(steps) alpha_p = alpha_p * (max_prob - min_prob) + min_prob if simple: return alpha_p * x1 + (1.0 - alpha_p) * x2 alpha_shape = shape_list(x1) if broadcast_last: alpha_shape = alpha_shape[:-1] + [1] alpha = tf.random_uniform(alpha_shape) alpha = to_float(tf.less(alpha, alpha_p)) return alpha * x1 + (1.0 - alpha) * x2 if max_prob < 1.0: return get_res() # Prevent sampling after steps is passed to speed it up. if is_xla_compiled(): return get_res() else: cur_step = tf.train.get_global_step() if cur_step is None: return x1 # Step not available, probably eval mode, don't mix. return tf.cond(tf.less(cur_step, steps), get_res, lambda: x1)
python
def mix(x1, x2, steps, is_training, min_prob=0.0, max_prob=1.0, mode="lin", simple=False, broadcast_last=False): """Mix starting with x2, mixing mixing, going towards x1.""" with tf.name_scope("mix"): if not is_training: if max_prob >= 1.0: return x1 alpha_shape = shape_list(x1) if broadcast_last: alpha_shape = alpha_shape[:-1] + [1] alpha = tf.random_uniform(alpha_shape) alpha = to_float(tf.less(alpha, max_prob)) return alpha * x1 + (1.0 - alpha) * x2 def get_res(): """Create the result. Separate function to speed it up later (see below). Returns: Tensor of mixed inputs. """ if mode == "lin": alpha_p = inverse_lin_decay(steps) else: alpha_p = inverse_exp_decay(steps) alpha_p = alpha_p * (max_prob - min_prob) + min_prob if simple: return alpha_p * x1 + (1.0 - alpha_p) * x2 alpha_shape = shape_list(x1) if broadcast_last: alpha_shape = alpha_shape[:-1] + [1] alpha = tf.random_uniform(alpha_shape) alpha = to_float(tf.less(alpha, alpha_p)) return alpha * x1 + (1.0 - alpha) * x2 if max_prob < 1.0: return get_res() # Prevent sampling after steps is passed to speed it up. if is_xla_compiled(): return get_res() else: cur_step = tf.train.get_global_step() if cur_step is None: return x1 # Step not available, probably eval mode, don't mix. return tf.cond(tf.less(cur_step, steps), get_res, lambda: x1)
[ "def", "mix", "(", "x1", ",", "x2", ",", "steps", ",", "is_training", ",", "min_prob", "=", "0.0", ",", "max_prob", "=", "1.0", ",", "mode", "=", "\"lin\"", ",", "simple", "=", "False", ",", "broadcast_last", "=", "False", ")", ":", "with", "tf", ".", "name_scope", "(", "\"mix\"", ")", ":", "if", "not", "is_training", ":", "if", "max_prob", ">=", "1.0", ":", "return", "x1", "alpha_shape", "=", "shape_list", "(", "x1", ")", "if", "broadcast_last", ":", "alpha_shape", "=", "alpha_shape", "[", ":", "-", "1", "]", "+", "[", "1", "]", "alpha", "=", "tf", ".", "random_uniform", "(", "alpha_shape", ")", "alpha", "=", "to_float", "(", "tf", ".", "less", "(", "alpha", ",", "max_prob", ")", ")", "return", "alpha", "*", "x1", "+", "(", "1.0", "-", "alpha", ")", "*", "x2", "def", "get_res", "(", ")", ":", "\"\"\"Create the result.\n\n Separate function to speed it up later (see below).\n\n Returns:\n Tensor of mixed inputs.\n \"\"\"", "if", "mode", "==", "\"lin\"", ":", "alpha_p", "=", "inverse_lin_decay", "(", "steps", ")", "else", ":", "alpha_p", "=", "inverse_exp_decay", "(", "steps", ")", "alpha_p", "=", "alpha_p", "*", "(", "max_prob", "-", "min_prob", ")", "+", "min_prob", "if", "simple", ":", "return", "alpha_p", "*", "x1", "+", "(", "1.0", "-", "alpha_p", ")", "*", "x2", "alpha_shape", "=", "shape_list", "(", "x1", ")", "if", "broadcast_last", ":", "alpha_shape", "=", "alpha_shape", "[", ":", "-", "1", "]", "+", "[", "1", "]", "alpha", "=", "tf", ".", "random_uniform", "(", "alpha_shape", ")", "alpha", "=", "to_float", "(", "tf", ".", "less", "(", "alpha", ",", "alpha_p", ")", ")", "return", "alpha", "*", "x1", "+", "(", "1.0", "-", "alpha", ")", "*", "x2", "if", "max_prob", "<", "1.0", ":", "return", "get_res", "(", ")", "# Prevent sampling after steps is passed to speed it up.", "if", "is_xla_compiled", "(", ")", ":", "return", "get_res", "(", ")", "else", ":", "cur_step", "=", "tf", ".", "train", ".", "get_global_step", "(", ")", "if", "cur_step", "is", "None", ":", "return", "x1", "# Step not available, probably eval mode, don't mix.", "return", "tf", ".", "cond", "(", "tf", ".", "less", "(", "cur_step", ",", "steps", ")", ",", "get_res", ",", "lambda", ":", "x1", ")" ]
Mix starting with x2, mixing mixing, going towards x1.
[ "Mix", "starting", "with", "x2", "mixing", "mixing", "going", "towards", "x1", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3198-L3251
22,196
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
gelu
def gelu(x): """Gaussian Error Linear Unit. This is a smoother version of the RELU. Original paper: https://arxiv.org/abs/1606.08415 Args: x: float Tensor to perform activation. Returns: x with the GELU activation applied. """ cdf = 0.5 * (1.0 + tf.tanh( (np.sqrt(2 / np.pi) * (x + 0.044715 * tf.pow(x, 3))))) return x * cdf
python
def gelu(x): """Gaussian Error Linear Unit. This is a smoother version of the RELU. Original paper: https://arxiv.org/abs/1606.08415 Args: x: float Tensor to perform activation. Returns: x with the GELU activation applied. """ cdf = 0.5 * (1.0 + tf.tanh( (np.sqrt(2 / np.pi) * (x + 0.044715 * tf.pow(x, 3))))) return x * cdf
[ "def", "gelu", "(", "x", ")", ":", "cdf", "=", "0.5", "*", "(", "1.0", "+", "tf", ".", "tanh", "(", "(", "np", ".", "sqrt", "(", "2", "/", "np", ".", "pi", ")", "*", "(", "x", "+", "0.044715", "*", "tf", ".", "pow", "(", "x", ",", "3", ")", ")", ")", ")", ")", "return", "x", "*", "cdf" ]
Gaussian Error Linear Unit. This is a smoother version of the RELU. Original paper: https://arxiv.org/abs/1606.08415 Args: x: float Tensor to perform activation. Returns: x with the GELU activation applied.
[ "Gaussian", "Error", "Linear", "Unit", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3272-L3286
22,197
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
argmax_with_score
def argmax_with_score(logits, axis=None): """Argmax along with the value.""" axis = axis or len(logits.get_shape()) - 1 predictions = tf.argmax(logits, axis=axis) logits_shape = shape_list(logits) prefix_shape, vocab_size = logits_shape[:-1], logits_shape[-1] prefix_size = 1 for d in prefix_shape: prefix_size *= d # Flatten to extract scores flat_logits = tf.reshape(logits, [prefix_size, vocab_size]) flat_predictions = tf.reshape(predictions, [prefix_size]) flat_indices = tf.stack( [tf.range(tf.to_int64(prefix_size)), tf.to_int64(flat_predictions)], axis=1) flat_scores = tf.gather_nd(flat_logits, flat_indices) # Unflatten scores = tf.reshape(flat_scores, prefix_shape) return predictions, scores
python
def argmax_with_score(logits, axis=None): """Argmax along with the value.""" axis = axis or len(logits.get_shape()) - 1 predictions = tf.argmax(logits, axis=axis) logits_shape = shape_list(logits) prefix_shape, vocab_size = logits_shape[:-1], logits_shape[-1] prefix_size = 1 for d in prefix_shape: prefix_size *= d # Flatten to extract scores flat_logits = tf.reshape(logits, [prefix_size, vocab_size]) flat_predictions = tf.reshape(predictions, [prefix_size]) flat_indices = tf.stack( [tf.range(tf.to_int64(prefix_size)), tf.to_int64(flat_predictions)], axis=1) flat_scores = tf.gather_nd(flat_logits, flat_indices) # Unflatten scores = tf.reshape(flat_scores, prefix_shape) return predictions, scores
[ "def", "argmax_with_score", "(", "logits", ",", "axis", "=", "None", ")", ":", "axis", "=", "axis", "or", "len", "(", "logits", ".", "get_shape", "(", ")", ")", "-", "1", "predictions", "=", "tf", ".", "argmax", "(", "logits", ",", "axis", "=", "axis", ")", "logits_shape", "=", "shape_list", "(", "logits", ")", "prefix_shape", ",", "vocab_size", "=", "logits_shape", "[", ":", "-", "1", "]", ",", "logits_shape", "[", "-", "1", "]", "prefix_size", "=", "1", "for", "d", "in", "prefix_shape", ":", "prefix_size", "*=", "d", "# Flatten to extract scores", "flat_logits", "=", "tf", ".", "reshape", "(", "logits", ",", "[", "prefix_size", ",", "vocab_size", "]", ")", "flat_predictions", "=", "tf", ".", "reshape", "(", "predictions", ",", "[", "prefix_size", "]", ")", "flat_indices", "=", "tf", ".", "stack", "(", "[", "tf", ".", "range", "(", "tf", ".", "to_int64", "(", "prefix_size", ")", ")", ",", "tf", ".", "to_int64", "(", "flat_predictions", ")", "]", ",", "axis", "=", "1", ")", "flat_scores", "=", "tf", ".", "gather_nd", "(", "flat_logits", ",", "flat_indices", ")", "# Unflatten", "scores", "=", "tf", ".", "reshape", "(", "flat_scores", ",", "prefix_shape", ")", "return", "predictions", ",", "scores" ]
Argmax along with the value.
[ "Argmax", "along", "with", "the", "value", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3315-L3338
22,198
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
top_kth_iterative
def top_kth_iterative(x, k): """Compute the k-th top element of x on the last axis iteratively. This assumes values in x are non-negative, rescale if needed. It is often faster than tf.nn.top_k for small k, especially if k < 30. Note: this does not support back-propagation, it stops gradients! Args: x: a Tensor of non-negative numbers of type float. k: a python integer. Returns: a float tensor of the same shape as x but with 1 on the last axis that contains the k-th largest number in x. """ # The iterative computation is as follows: # # cur_x = x # for _ in range(k): # top_x = maximum of elements of cur_x on the last axis # cur_x = cur_x where cur_x < top_x and 0 everywhere else (top elements) # # We encode this computation in a TF graph using tf.foldl, so the inner # part of the above loop is called "next_x" and tf.foldl does the loop. def next_x(cur_x, _): top_x = tf.reduce_max(cur_x, axis=-1, keep_dims=True) return cur_x * to_float(cur_x < top_x) # We only do k-1 steps of the loop and compute the final max separately. fin_x = tf.foldl(next_x, tf.range(k - 1), initializer=tf.stop_gradient(x), parallel_iterations=2, back_prop=False) return tf.stop_gradient(tf.reduce_max(fin_x, axis=-1, keep_dims=True))
python
def top_kth_iterative(x, k): """Compute the k-th top element of x on the last axis iteratively. This assumes values in x are non-negative, rescale if needed. It is often faster than tf.nn.top_k for small k, especially if k < 30. Note: this does not support back-propagation, it stops gradients! Args: x: a Tensor of non-negative numbers of type float. k: a python integer. Returns: a float tensor of the same shape as x but with 1 on the last axis that contains the k-th largest number in x. """ # The iterative computation is as follows: # # cur_x = x # for _ in range(k): # top_x = maximum of elements of cur_x on the last axis # cur_x = cur_x where cur_x < top_x and 0 everywhere else (top elements) # # We encode this computation in a TF graph using tf.foldl, so the inner # part of the above loop is called "next_x" and tf.foldl does the loop. def next_x(cur_x, _): top_x = tf.reduce_max(cur_x, axis=-1, keep_dims=True) return cur_x * to_float(cur_x < top_x) # We only do k-1 steps of the loop and compute the final max separately. fin_x = tf.foldl(next_x, tf.range(k - 1), initializer=tf.stop_gradient(x), parallel_iterations=2, back_prop=False) return tf.stop_gradient(tf.reduce_max(fin_x, axis=-1, keep_dims=True))
[ "def", "top_kth_iterative", "(", "x", ",", "k", ")", ":", "# The iterative computation is as follows:", "#", "# cur_x = x", "# for _ in range(k):", "# top_x = maximum of elements of cur_x on the last axis", "# cur_x = cur_x where cur_x < top_x and 0 everywhere else (top elements)", "#", "# We encode this computation in a TF graph using tf.foldl, so the inner", "# part of the above loop is called \"next_x\" and tf.foldl does the loop.", "def", "next_x", "(", "cur_x", ",", "_", ")", ":", "top_x", "=", "tf", ".", "reduce_max", "(", "cur_x", ",", "axis", "=", "-", "1", ",", "keep_dims", "=", "True", ")", "return", "cur_x", "*", "to_float", "(", "cur_x", "<", "top_x", ")", "# We only do k-1 steps of the loop and compute the final max separately.", "fin_x", "=", "tf", ".", "foldl", "(", "next_x", ",", "tf", ".", "range", "(", "k", "-", "1", ")", ",", "initializer", "=", "tf", ".", "stop_gradient", "(", "x", ")", ",", "parallel_iterations", "=", "2", ",", "back_prop", "=", "False", ")", "return", "tf", ".", "stop_gradient", "(", "tf", ".", "reduce_max", "(", "fin_x", ",", "axis", "=", "-", "1", ",", "keep_dims", "=", "True", ")", ")" ]
Compute the k-th top element of x on the last axis iteratively. This assumes values in x are non-negative, rescale if needed. It is often faster than tf.nn.top_k for small k, especially if k < 30. Note: this does not support back-propagation, it stops gradients! Args: x: a Tensor of non-negative numbers of type float. k: a python integer. Returns: a float tensor of the same shape as x but with 1 on the last axis that contains the k-th largest number in x.
[ "Compute", "the", "k", "-", "th", "top", "element", "of", "x", "on", "the", "last", "axis", "iteratively", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3345-L3375
22,199
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
top_1_tpu
def top_1_tpu(inputs): """find max and argmax over the last dimension. Works well on TPU Args: inputs: A tensor with shape [..., depth] Returns: values: a Tensor with shape [...] indices: a Tensor with shape [...] """ inputs_max = tf.reduce_max(inputs, axis=-1, keepdims=True) mask = tf.to_int32(tf.equal(inputs_max, inputs)) index = tf.range(tf.shape(inputs)[-1]) * mask return tf.squeeze(inputs_max, -1), tf.reduce_max(index, axis=-1)
python
def top_1_tpu(inputs): """find max and argmax over the last dimension. Works well on TPU Args: inputs: A tensor with shape [..., depth] Returns: values: a Tensor with shape [...] indices: a Tensor with shape [...] """ inputs_max = tf.reduce_max(inputs, axis=-1, keepdims=True) mask = tf.to_int32(tf.equal(inputs_max, inputs)) index = tf.range(tf.shape(inputs)[-1]) * mask return tf.squeeze(inputs_max, -1), tf.reduce_max(index, axis=-1)
[ "def", "top_1_tpu", "(", "inputs", ")", ":", "inputs_max", "=", "tf", ".", "reduce_max", "(", "inputs", ",", "axis", "=", "-", "1", ",", "keepdims", "=", "True", ")", "mask", "=", "tf", ".", "to_int32", "(", "tf", ".", "equal", "(", "inputs_max", ",", "inputs", ")", ")", "index", "=", "tf", ".", "range", "(", "tf", ".", "shape", "(", "inputs", ")", "[", "-", "1", "]", ")", "*", "mask", "return", "tf", ".", "squeeze", "(", "inputs_max", ",", "-", "1", ")", ",", "tf", ".", "reduce_max", "(", "index", ",", "axis", "=", "-", "1", ")" ]
find max and argmax over the last dimension. Works well on TPU Args: inputs: A tensor with shape [..., depth] Returns: values: a Tensor with shape [...] indices: a Tensor with shape [...]
[ "find", "max", "and", "argmax", "over", "the", "last", "dimension", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3378-L3393