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 o...
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 o...
[ "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_la...
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", ...
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", ...
[ "def", "_fn_with_diet_vars", "(", "fn", ",", "args", ",", "params", ")", ":", "vs_ctr", "=", "[", "]", "def", "grad_fn", "(", "inputs", ",", "variables", ",", "outputs", ",", "output_grads", ")", ":", "\"\"\"Custom gradient function.\"\"\"", "del", "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", ",",...
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_se...
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_se...
[ "def", "create_slots", "(", "self", ",", "var", ")", ":", "params", "=", "self", ".", "params", "shape", "=", "var", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "if", "not", "hasattr", "(", "params", ",", "\"slots\"", ")", ":", "params", ...
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 * pa...
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 * pa...
[ "def", "update_variable", "(", "self", ",", "var", ",", "grad_var", ")", ":", "params", "=", "self", ".", "params", "global_step", "=", "tf", ".", "to_float", "(", "self", ".", "global_step", ")", "+", "1", "# compute learning rate", "lrate", "=", "params"...
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 mult...
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 mult...
[ "def", "estimator_spec_eval", "(", "self", ",", "features", ",", "logits", ",", "labels", ",", "loss", ",", "restore_hook", ",", "use_tpu", ")", ":", "hparams", "=", "self", ".", "hparams", "problem", "=", "hparams", ".", "problem", "if", "logits", ".", ...
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 cha...
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 cha...
[ "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", ",", "u...
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 ...
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 ...
[ "def", "lstm", "(", "inputs", ",", "sequence_length", ",", "hparams", ",", "train", ",", "name", ",", "initial_state", "=", "None", ")", ":", "layers", "=", "[", "_dropout_lstm_cell", "(", "hparams", ",", "train", ")", "for", "_", "in", "range", "(", "...
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` whe...
[ "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.flatt...
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.flatt...
[ "def", "lstm_seq2seq_internal", "(", "inputs", ",", "targets", ",", "hparams", ",", "train", ")", ":", "with", "tf", ".", "variable_scope", "(", "\"lstm_seq2seq\"", ")", ":", "if", "inputs", "is", "not", "None", ":", "inputs_length", "=", "common_layers", "....
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...
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...
[ "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", "=",...
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 ...
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 ...
[ "def", "lstm_seq2seq", "(", ")", ":", "hparams", "=", "common_hparams", ".", "basic_params1", "(", ")", "hparams", ".", "daisy_chain_variables", "=", "False", "hparams", ".", "batch_size", "=", "1024", "hparams", ".", "hidden_size", "=", "128", "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", ...
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...
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...
[ "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", ...
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....
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....
[ "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"...
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["...
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["...
[ "def", "prepare_data", "(", "problem", ",", "hparams", ",", "params", ",", "config", ")", ":", "input_fn", "=", "problem", ".", "make_estimator_input_fn", "(", "tf", ".", "estimator", ".", "ModeKeys", ".", "EVAL", ",", "hparams", ",", "force_repeat", "=", ...
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,...
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,...
[ "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...
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 = te...
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 = te...
[ "def", "decode", "(", "self", ",", "ids", ")", ":", "_", ",", "tmp_file_path", "=", "tempfile", ".", "mkstemp", "(", ")", "wavfile", ".", "write", "(", "tmp_file_path", ",", "self", ".", "_sample_rate", ",", "np", ".", "asarray", "(", "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.
[ "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[ke...
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[ke...
[ "def", "get_vertex", "(", "self", ",", "key", ")", ":", "if", "key", "in", "self", ".", "vertex_map", ":", "return", "self", ".", "vertex_map", "[", "key", "]", "vertex", "=", "self", ".", "new_vertex", "(", ")", "self", ".", "vertex_map", "[", "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.
[ "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_e...
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_e...
[ "def", "add_edge", "(", "self", ",", "source", ",", "target", ")", ":", "edge", "=", "Edge", "(", "len", "(", "self", ".", "edges", ")", ")", "self", ".", "edges", ".", "append", "(", "edge", ")", "source", ".", "out_edges", ".", "append", "(", "...
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", "."...
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_atten...
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_atten...
[ "def", "attend", "(", "x", ",", "source", ",", "hparams", ",", "name", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ")", ":", "x", "=", "tf", ".", "squeeze", "(", "x", ",", "axis", "=", "2", ")", "if", "len", "(", "source", ".", ...
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...
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...
[ "def", "ae_latent_sample", "(", "latents_dense", ",", "inputs", ",", "ed", ",", "embed", ",", "iters", ",", "hparams", ")", ":", "if", "hparams", ".", "num_decode_blocks", "<", "2", "and", "hparams", ".", "sampling_temp", "==", "0.0", ":", "# TODO(lukaszkais...
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.hidde...
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.hidde...
[ "def", "imagetransformer_ae_cifar", "(", ")", ":", "hparams", "=", "transformer_ae_small", "(", ")", "hparams", ".", "filter_size", "=", "512", "hparams", ".", "num_compress_steps", "=", "3", "hparams", ".", "startup_steps", "=", "10000", "hparams", ".", "is_2d"...
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. ...
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. ...
[ "def", "imagetransformer_ae_imagenet", "(", ")", ":", "hparams", "=", "imagetransformer_ae_cifar", "(", ")", "hparams", ".", "max_length", "=", "int", "(", "64", "*", "64", "*", "3", ")", "hparams", ".", "img_len", "=", "64", "hparams", ".", "num_heads", "...
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", ".",...
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.enable...
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.enable...
[ "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: di...
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...
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...
[ "def", "dropout_with_broadcast_dims", "(", "x", ",", "keep_prob", ",", "broadcast_dims", "=", "None", ",", "*", "*", "kwargs", ")", ":", "assert", "\"noise_shape\"", "not", "in", "kwargs", "if", "broadcast_dims", ":", "shape", "=", "tf", ".", "shape", "(", ...
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 tens...
[ "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_b...
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_b...
[ "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", ...
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....
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....
[ "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", ":", "retu...
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_sh...
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_...
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_...
[ "def", "shakeshake", "(", "xs", ",", "equal_grad", "=", "False", ")", ":", "if", "len", "(", "xs", ")", "==", "1", ":", "return", "xs", "[", "0", "]", "div", "=", "(", "len", "(", "xs", ")", "+", "1", ")", "//", "2", "arg1", "=", "shakeshake"...
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", ":", ...
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....
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....
[ "def", "standardize_images", "(", "x", ")", ":", "with", "tf", ".", "name_scope", "(", "\"standardize_images\"", ",", "values", "=", "[", "x", "]", ")", ":", "x_shape", "=", "shape_list", "(", "x", ")", "x", "=", "to_float", "(", "tf", ".", "reshape", ...
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", ...
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=d...
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=d...
[ "def", "gather", "(", "params", ",", "indices", ",", "dtype", "=", "tf", ".", "float32", ")", ":", "if", "not", "is_xla_compiled", "(", ")", ":", "return", "tf", ".", "gather", "(", "params", ",", "indices", ")", "vocab_size", "=", "params", ".", "ge...
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_xl...
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_xl...
[ "def", "cumsum", "(", "x", ",", "axis", "=", "0", ",", "exclusive", "=", "False", ")", ":", "if", "not", "is_xla_compiled", "(", ")", ":", "return", "tf", ".", "cumsum", "(", "x", ",", "axis", "=", "axis", ",", "exclusive", "=", "exclusive", ")", ...
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_pr...
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_pr...
[ "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", ...
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...
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...
[ "def", "embedding", "(", "x", ",", "vocab_size", ",", "dense_size", ",", "name", "=", "None", ",", "reuse", "=", "None", ",", "multiplier", "=", "1.0", ",", "symbol_dropout_rate", "=", "0.0", ",", "embedding_var", "=", "None", ",", "dtype", "=", "tf", ...
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 `Tens...
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 `Tens...
[ "def", "conv_stride2_multistep", "(", "x", ",", "nbr_steps", ",", "output_filters", ",", "name", "=", "None", ",", "reuse", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ",", "default_name", "=", "\"conv_stride2_multistep\"", ",", ...
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]...
[ "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. " ...
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. " ...
[ "def", "conv_internal", "(", "conv_fn", ",", "inputs", ",", "filters", ",", "kernel_size", ",", "*", "*", "kwargs", ")", ":", "static_shape", "=", "inputs", ".", "get_shape", "(", ")", "if", "not", "static_shape", "or", "len", "(", "static_shape", ")", "...
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" i...
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" i...
[ "def", "subseparable_conv", "(", "inputs", ",", "filters", ",", "kernel_size", ",", "*", "*", "kwargs", ")", ":", "def", "conv_fn", "(", "inputs", ",", "filters", ",", "kernel_size", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Sub-separable convolution, splits i...
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...
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],...
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],...
[ "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", ",",...
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(...
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(...
[ "def", "layer_norm", "(", "x", ",", "filters", "=", "None", ",", "epsilon", "=", "1e-6", ",", "name", "=", "None", ",", "reuse", "=", "None", ",", "layer_collection", "=", "None", ")", ":", "if", "filters", "is", "None", ":", "filters", "=", "shape_l...
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", ...
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...
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...
[ "def", "l2_norm", "(", "x", ",", "filters", "=", "None", ",", "epsilon", "=", "1e-6", ",", "name", "=", "None", ",", "reuse", "=", "None", ")", ":", "if", "filters", "is", "None", ":", "filters", "=", "shape_list", "(", "x", ")", "[", "-", "1", ...
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 t...
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 t...
[ "def", "apply_spectral_norm", "(", "x", ")", ":", "weights_shape", "=", "shape_list", "(", "x", ")", "other", ",", "num_filters", "=", "tf", ".", "reduce_prod", "(", "weights_shape", "[", ":", "-", "1", "]", ")", ",", "weights_shape", "[", "-", "1", "]...
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:...
[ "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": ...
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": ...
[ "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\"",...
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 mak...
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 mak...
[ "def", "zero_add", "(", "previous_value", ",", "x", ",", "name", "=", "None", ",", "reuse", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ",", "default_name", "=", "\"zero_add\"", ",", "reuse", "=", "reuse", ")", ":", "gamma"...
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...
[ "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, ...
python
def layer_prepostprocess(previous_value, x, sequence, dropout_rate, norm_type, depth, epsilon, default_name, name=None, ...
[ "def", "layer_prepostprocess", "(", "previous_value", ",", "x", ",", "sequence", ",", "dropout_rate", ",", "norm_type", ",", "depth", ",", "epsilon", ",", "default_name", ",", "name", "=", "None", ",", "dropout_broadcast_dims", "=", "None", ",", "layer_collectio...
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 + no...
[ "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 ...
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 ...
[ "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\"", ...
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 ...
[ "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 hi...
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 hi...
[ "def", "layer_postprocess", "(", "layer_input", ",", "layer_output", ",", "hparams", ")", ":", "return", "layer_prepostprocess", "(", "layer_input", ",", "layer_output", ",", "sequence", "=", "hparams", ".", "layer_postprocess_sequence", ",", "dropout_rate", "=", "h...
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 ...
[ "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): """...
python
def conv_block_internal(conv_fn, inputs, filters, dilation_rates_and_kernel_sizes, first_relu=True, use_elu=False, separabilities=None, **kwargs): """...
[ "def", "conv_block_internal", "(", "conv_fn", ",", "inputs", ",", "filters", ",", "dilation_rates_and_kernel_sizes", ",", "first_relu", "=", "True", ",", "use_elu", "=", "False", ",", "separabilities", "=", "None", ",", "*", "*", "kwargs", ")", ":", "name", ...
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 in...
[ "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", ",", "*", "*", "kw...
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", ",", "*", "*", ...
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 f...
python
def conv_block_downsample(x, kernel, strides, padding, separability=0, name=None, reuse=None): """Implements a downwards-striding conv block, like Xception exit f...
[ "def", "conv_block_downsample", "(", "x", ",", "kernel", ",", "strides", ",", "padding", ",", "separability", "=", "0", ",", "name", "=", "None", ",", "reuse", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ",", "default_name", ...
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_...
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_...
[ "def", "get_timing_signal", "(", "length", ",", "min_timescale", "=", "1", ",", "max_timescale", "=", "1e4", ",", "num_timescales", "=", "16", ")", ":", "positions", "=", "to_float", "(", "tf", ".", "range", "(", "length", ")", ")", "log_timescale_increment"...
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 wit...
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 wit...
[ "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: Ten...
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: Ten...
[ "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"...
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...
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...
[ "def", "dense_dropconnect", "(", "inputs", ",", "output_size", ",", "dropconnect_dropout", "=", "0.0", ",", "name", "=", "\"dense_dropconnect\"", ",", "*", "*", "kwargs", ")", ":", "if", "dropconnect_dropout", "!=", "0.0", ":", "tf", ".", "logging", ".", "in...
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): ...
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): ...
[ "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 fir...
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 ...
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 ...
[ "def", "gru_feedfwd", "(", "a_t", ",", "h_prev", ",", "filters", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ",", "default_name", "=", "\"GRU\"", ",", "values", "=", "[", "a_t", ",", "h_prev", "]", ")", ":", ...
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, fi...
[ "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): ...
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): ...
[ "def", "conv_lstm", "(", "x", ",", "kernel_size", ",", "filters", ",", "padding", "=", "\"SAME\"", ",", "dilation_rate", "=", "(", "1", ",", "1", ")", ",", "name", "=", "None", ",", "reuse", "=", "None", ")", ":", "with", "tf", ".", "variable_scope",...
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)[a...
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)[a...
[ "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.\""...
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, ...
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, ...
[ "def", "pad_with_zeros", "(", "logits", ",", "labels", ")", ":", "with", "tf", ".", "name_scope", "(", "\"pad_with_zeros\"", ",", "values", "=", "[", "logits", ",", "labels", "]", ")", ":", "logits", ",", "labels", "=", "pad_to_same_length", "(", "logits",...
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", ")", "]", ")", ":"...
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...
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...
[ "def", "weights_multi_problem_all", "(", "labels", ",", "taskid", "=", "-", "1", ")", ":", "taskid", "=", "check_nonnegative", "(", "taskid", ")", "weights", "=", "to_float", "(", "tf", ".", "not_equal", "(", "labels", ",", "0", ")", ")", "past_taskid", ...
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", "=", ...
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 ...
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 ...
[ "def", "weights_concatenated", "(", "labels", ")", ":", "eos_mask", "=", "tf", ".", "to_int32", "(", "tf", ".", "equal", "(", "labels", ",", "1", ")", ")", "sentence_num", "=", "tf", ".", "cumsum", "(", "eos_mask", ",", "axis", "=", "1", ",", "exclus...
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...
[ "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 (on...
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 (on...
[ "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", "(...
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 dependen...
[ "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 devi...
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 devi...
[ "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", "...
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 whic...
[ "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...
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...
[ "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.", "bat...
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 = ...
[ "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 ...
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 ...
[ "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 g...
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 parameteri...
[ "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, ?, ?, ?...
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, ?, ?, ?...
[ "def", "smoothing_cross_entropy", "(", "logits", ",", "labels", ",", "vocab_size", ",", "confidence", ",", "gaussian", "=", "False", ")", ":", "with", "tf", ".", "name_scope", "(", "\"smoothing_cross_entropy\"", ",", "values", "=", "[", "logits", ",", "labels"...
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....
[ "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 o...
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 o...
[ "def", "global_pool_1d", "(", "inputs", ",", "pooling_type", "=", "\"MAX\"", ",", "mask", "=", "None", ")", ":", "with", "tf", ".", "name_scope", "(", "\"global_pool\"", ",", "values", "=", "[", "inputs", "]", ")", ":", "if", "mask", "is", "not", "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 ...
[ "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. Eq...
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. Eq...
[ "def", "running_global_pool_1d", "(", "inputs", ",", "pooling_type", "=", "\"MAX\"", ")", ":", "del", "pooling_type", "with", "tf", ".", "name_scope", "(", "\"running_global_pool\"", ",", "values", "=", "[", "inputs", "]", ")", ":", "scan_fct", "=", "tf", "....
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:...
[ "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_...
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_...
[ "def", "gated_linear_unit_layer", "(", "x", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ",", "default_name", "=", "\"glu_layer\"", ",", "values", "=", "[", "x", "]", ")", ":", "depth", "=", "shape_list", "(", "...
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...
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...
[ "def", "linear_set_layer", "(", "layer_size", ",", "inputs", ",", "context", "=", "None", ",", "activation_fn", "=", "tf", ".", "nn", ".", "relu", ",", "dropout", "=", "0.0", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(",...
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. ...
[ "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", ".",...
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)): a...
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)): a...
[ "def", "fn_device_dependency", "(", "name", ",", "device", "=", "\"\"", ")", ":", "key", "=", "name", "+", "\"_\"", "+", "device", "outs", "=", "[", "]", "def", "body", "(", ")", ":", "with", "tf", ".", "control_dependencies", "(", "fn_device_dependency_...
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",...
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",...
[ "def", "underlying_variable_ref", "(", "t", ")", ":", "while", "t", ".", "op", ".", "type", "in", "[", "\"Identity\"", ",", "\"ReadVariableOp\"", ",", "\"Enter\"", "]", ":", "t", "=", "t", ".", "op", ".", "inputs", "[", "0", "]", "op_type", "=", "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.
[ "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"): ...
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"): ...
[ "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_...
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(nu...
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(nu...
[ "def", "approximate_split", "(", "x", ",", "num_splits", ",", "axis", "=", "0", ")", ":", "size", "=", "shape_list", "(", "x", ")", "[", "axis", "]", "size_splits", "=", "[", "tf", ".", "div", "(", "size", "+", "i", ",", "num_splits", ")", "for", ...
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 = approximat...
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 = approximat...
[ "def", "smoothing_cross_entropy_factored_grad", "(", "op", ",", "dy", ")", ":", "a", "=", "op", ".", "inputs", "[", "0", "]", "b", "=", "op", ".", "inputs", "[", "1", "]", "labels", "=", "op", ".", "inputs", "[", "2", "]", "confidence", "=", "op", ...
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:...
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:...
[ "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...
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...
[ "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,...
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,...
[ "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", "e...
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...
[ "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 ...
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 ...
[ "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", ...
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. Neg...
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. Neg...
[ "def", "ones_matrix_band_part", "(", "rows", ",", "cols", ",", "num_lower", ",", "num_upper", ",", "out_shape", "=", "None", ")", ":", "if", "all", "(", "[", "isinstance", "(", "el", ",", "int", ")", "for", "el", "in", "[", "rows", ",", "cols", ",", ...
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. ...
[ "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", ...
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 re...
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 re...
[ "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 pas...
[ "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 ...
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 ...
[ "def", "_recompute_grad", "(", "fn", ",", "args", ")", ":", "cached_vs", "=", "[", "]", "cached_arg_scope", "=", "[", "]", "def", "grad_fn", "(", "inputs", ",", "variables", ",", "outputs", ",", "output_grads", ")", ":", "\"\"\"Recompute outputs for gradient c...
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. Otherwi...
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. Otherwi...
[ "def", "dense", "(", "x", ",", "units", ",", "*", "*", "kwargs", ")", ":", "layer_collection", "=", "kwargs", ".", "pop", "(", "\"layer_collection\"", ",", "None", ")", "activations", "=", "layers", "(", ")", ".", "Dense", "(", "units", ",", "*", "*"...
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 mat...
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 mat...
[ "def", "batch_dense", "(", "inputs", ",", "units", ",", "activation", "=", "None", ",", "kernel_initializer", "=", "None", ",", "reuse", "=", "None", ",", "name", "=", "None", ")", ":", "inputs_shape", "=", "shape_list", "(", "inputs", ")", "if", "len", ...
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_un...
[ "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: ...
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: ...
[ "def", "mix", "(", "x1", ",", "x2", ",", "steps", ",", "is_training", ",", "min_prob", "=", "0.0", ",", "max_prob", "=", "1.0", ",", "mode", "=", "\"lin\"", ",", "simple", "=", "False", ",", "broadcast_last", "=", "False", ")", ":", "with", "tf", "...
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.04471...
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.04471...
[ "def", "gelu", "(", "x", ")", ":", "cdf", "=", "0.5", "*", "(", "1.0", "+", "tf", ".", "tanh", "(", "(", "np", ".", "sqrt", "(", "2", "/", "np", ".", "pi", ")", "*", "(", "x", "+", "0.044715", "*", "tf", ".", "pow", "(", "x", ",", "3", ...
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: pr...
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: pr...
[ "def", "argmax_with_score", "(", "logits", ",", "axis", "=", "None", ")", ":", "axis", "=", "axis", "or", "len", "(", "logits", ".", "get_shape", "(", ")", ")", "-", "1", "predictions", "=", "tf", ".", "argmax", "(", "logits", ",", "axis", "=", "ax...
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: ...
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: ...
[ "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)", "...
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 o...
[ "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_i...
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_i...
[ "def", "top_1_tpu", "(", "inputs", ")", ":", "inputs_max", "=", "tf", ".", "reduce_max", "(", "inputs", ",", "axis", "=", "-", "1", ",", "keepdims", "=", "True", ")", "mask", "=", "tf", ".", "to_int32", "(", "tf", ".", "equal", "(", "inputs_max", "...
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