repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
tensorflow/tensor2tensor
tensor2tensor/utils/metrics.py
create_eager_metrics_internal
def create_eager_metrics_internal(metric_fns, weights_fn=common_layers.weights_all): """Create metrics accumulators and averager for Eager mode. Args: metric_fns: dict<metric name, metric function> weights_fn: function that takes labels and returns a weights mask. Defaults to weights of all 1, i.e. common_layers.weights_all. Use common_layers.weights_nonzero if labels have 0-padding. Returns: (accum_fn(predictions, targets) => None, result_fn() => dict<str metric_name, float avg_val> """ tfe_metrics = {} for name in metric_fns: tfe_metrics[name] = tfe.metrics.Mean(name=name) def metric_accum(predictions, targets): for name, metric_fn in metric_fns.items(): val, weight = metric_fn(predictions, targets, weights_fn=weights_fn) tfe_metrics[name](np.squeeze(val), np.squeeze(weight)) def metric_means(): avgs = {} for name in metric_fns: avgs[name] = tfe_metrics[name].result().numpy() return avgs return metric_accum, metric_means
python
def create_eager_metrics_internal(metric_fns, weights_fn=common_layers.weights_all): """Create metrics accumulators and averager for Eager mode. Args: metric_fns: dict<metric name, metric function> weights_fn: function that takes labels and returns a weights mask. Defaults to weights of all 1, i.e. common_layers.weights_all. Use common_layers.weights_nonzero if labels have 0-padding. Returns: (accum_fn(predictions, targets) => None, result_fn() => dict<str metric_name, float avg_val> """ tfe_metrics = {} for name in metric_fns: tfe_metrics[name] = tfe.metrics.Mean(name=name) def metric_accum(predictions, targets): for name, metric_fn in metric_fns.items(): val, weight = metric_fn(predictions, targets, weights_fn=weights_fn) tfe_metrics[name](np.squeeze(val), np.squeeze(weight)) def metric_means(): avgs = {} for name in metric_fns: avgs[name] = tfe_metrics[name].result().numpy() return avgs return metric_accum, metric_means
[ "def", "create_eager_metrics_internal", "(", "metric_fns", ",", "weights_fn", "=", "common_layers", ".", "weights_all", ")", ":", "tfe_metrics", "=", "{", "}", "for", "name", "in", "metric_fns", ":", "tfe_metrics", "[", "name", "]", "=", "tfe", ".", "metrics", ".", "Mean", "(", "name", "=", "name", ")", "def", "metric_accum", "(", "predictions", ",", "targets", ")", ":", "for", "name", ",", "metric_fn", "in", "metric_fns", ".", "items", "(", ")", ":", "val", ",", "weight", "=", "metric_fn", "(", "predictions", ",", "targets", ",", "weights_fn", "=", "weights_fn", ")", "tfe_metrics", "[", "name", "]", "(", "np", ".", "squeeze", "(", "val", ")", ",", "np", ".", "squeeze", "(", "weight", ")", ")", "def", "metric_means", "(", ")", ":", "avgs", "=", "{", "}", "for", "name", "in", "metric_fns", ":", "avgs", "[", "name", "]", "=", "tfe_metrics", "[", "name", "]", ".", "result", "(", ")", ".", "numpy", "(", ")", "return", "avgs", "return", "metric_accum", ",", "metric_means" ]
Create metrics accumulators and averager for Eager mode. Args: metric_fns: dict<metric name, metric function> weights_fn: function that takes labels and returns a weights mask. Defaults to weights of all 1, i.e. common_layers.weights_all. Use common_layers.weights_nonzero if labels have 0-padding. Returns: (accum_fn(predictions, targets) => None, result_fn() => dict<str metric_name, float avg_val>
[ "Create", "metrics", "accumulators", "and", "averager", "for", "Eager", "mode", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L670-L701
train
tensorflow/tensor2tensor
tensor2tensor/utils/metrics.py
word_error_rate
def word_error_rate(raw_predictions, labels, lookup=None, weights_fn=common_layers.weights_nonzero): """Calculate word error rate. Args: raw_predictions: The raw predictions. labels: The actual labels. lookup: A tf.constant mapping indices to output tokens. weights_fn: Weighting function. Returns: The word error rate. """ def from_tokens(raw, lookup_): gathered = tf.gather(lookup_, tf.cast(raw, tf.int32)) joined = tf.regex_replace(tf.reduce_join(gathered, axis=1), b"<EOS>.*", b"") cleaned = tf.regex_replace(joined, b"_", b" ") tokens = tf.string_split(cleaned, " ") return tokens def from_characters(raw, lookup_): """Convert ascii+2 encoded codes to string-tokens.""" corrected = tf.bitcast( tf.clip_by_value(tf.subtract(raw, 2), 0, 255), tf.uint8) gathered = tf.gather(lookup_, tf.cast(corrected, tf.int32))[:, :, 0] joined = tf.reduce_join(gathered, axis=1) cleaned = tf.regex_replace(joined, b"\0", b"") tokens = tf.string_split(cleaned, " ") return tokens if lookup is None: lookup = tf.constant([chr(i) for i in range(256)]) convert_fn = from_characters else: convert_fn = from_tokens if weights_fn is not common_layers.weights_nonzero: raise ValueError("Only weights_nonzero can be used for this metric.") with tf.variable_scope("word_error_rate", values=[raw_predictions, labels]): raw_predictions = tf.squeeze( tf.argmax(raw_predictions, axis=-1), axis=(2, 3)) labels = tf.squeeze(labels, axis=(2, 3)) reference = convert_fn(labels, lookup) predictions = convert_fn(raw_predictions, lookup) distance = tf.reduce_sum( tf.edit_distance(predictions, reference, normalize=False)) reference_length = tf.cast( tf.size(reference.values, out_type=tf.int32), dtype=tf.float32) return distance / reference_length, reference_length
python
def word_error_rate(raw_predictions, labels, lookup=None, weights_fn=common_layers.weights_nonzero): """Calculate word error rate. Args: raw_predictions: The raw predictions. labels: The actual labels. lookup: A tf.constant mapping indices to output tokens. weights_fn: Weighting function. Returns: The word error rate. """ def from_tokens(raw, lookup_): gathered = tf.gather(lookup_, tf.cast(raw, tf.int32)) joined = tf.regex_replace(tf.reduce_join(gathered, axis=1), b"<EOS>.*", b"") cleaned = tf.regex_replace(joined, b"_", b" ") tokens = tf.string_split(cleaned, " ") return tokens def from_characters(raw, lookup_): """Convert ascii+2 encoded codes to string-tokens.""" corrected = tf.bitcast( tf.clip_by_value(tf.subtract(raw, 2), 0, 255), tf.uint8) gathered = tf.gather(lookup_, tf.cast(corrected, tf.int32))[:, :, 0] joined = tf.reduce_join(gathered, axis=1) cleaned = tf.regex_replace(joined, b"\0", b"") tokens = tf.string_split(cleaned, " ") return tokens if lookup is None: lookup = tf.constant([chr(i) for i in range(256)]) convert_fn = from_characters else: convert_fn = from_tokens if weights_fn is not common_layers.weights_nonzero: raise ValueError("Only weights_nonzero can be used for this metric.") with tf.variable_scope("word_error_rate", values=[raw_predictions, labels]): raw_predictions = tf.squeeze( tf.argmax(raw_predictions, axis=-1), axis=(2, 3)) labels = tf.squeeze(labels, axis=(2, 3)) reference = convert_fn(labels, lookup) predictions = convert_fn(raw_predictions, lookup) distance = tf.reduce_sum( tf.edit_distance(predictions, reference, normalize=False)) reference_length = tf.cast( tf.size(reference.values, out_type=tf.int32), dtype=tf.float32) return distance / reference_length, reference_length
[ "def", "word_error_rate", "(", "raw_predictions", ",", "labels", ",", "lookup", "=", "None", ",", "weights_fn", "=", "common_layers", ".", "weights_nonzero", ")", ":", "def", "from_tokens", "(", "raw", ",", "lookup_", ")", ":", "gathered", "=", "tf", ".", "gather", "(", "lookup_", ",", "tf", ".", "cast", "(", "raw", ",", "tf", ".", "int32", ")", ")", "joined", "=", "tf", ".", "regex_replace", "(", "tf", ".", "reduce_join", "(", "gathered", ",", "axis", "=", "1", ")", ",", "b\"<EOS>.*\"", ",", "b\"\"", ")", "cleaned", "=", "tf", ".", "regex_replace", "(", "joined", ",", "b\"_\"", ",", "b\" \"", ")", "tokens", "=", "tf", ".", "string_split", "(", "cleaned", ",", "\" \"", ")", "return", "tokens", "def", "from_characters", "(", "raw", ",", "lookup_", ")", ":", "\"\"\"Convert ascii+2 encoded codes to string-tokens.\"\"\"", "corrected", "=", "tf", ".", "bitcast", "(", "tf", ".", "clip_by_value", "(", "tf", ".", "subtract", "(", "raw", ",", "2", ")", ",", "0", ",", "255", ")", ",", "tf", ".", "uint8", ")", "gathered", "=", "tf", ".", "gather", "(", "lookup_", ",", "tf", ".", "cast", "(", "corrected", ",", "tf", ".", "int32", ")", ")", "[", ":", ",", ":", ",", "0", "]", "joined", "=", "tf", ".", "reduce_join", "(", "gathered", ",", "axis", "=", "1", ")", "cleaned", "=", "tf", ".", "regex_replace", "(", "joined", ",", "b\"\\0\"", ",", "b\"\"", ")", "tokens", "=", "tf", ".", "string_split", "(", "cleaned", ",", "\" \"", ")", "return", "tokens", "if", "lookup", "is", "None", ":", "lookup", "=", "tf", ".", "constant", "(", "[", "chr", "(", "i", ")", "for", "i", "in", "range", "(", "256", ")", "]", ")", "convert_fn", "=", "from_characters", "else", ":", "convert_fn", "=", "from_tokens", "if", "weights_fn", "is", "not", "common_layers", ".", "weights_nonzero", ":", "raise", "ValueError", "(", "\"Only weights_nonzero can be used for this metric.\"", ")", "with", "tf", ".", "variable_scope", "(", "\"word_error_rate\"", ",", "values", "=", "[", "raw_predictions", ",", "labels", "]", ")", ":", "raw_predictions", "=", "tf", ".", "squeeze", "(", "tf", ".", "argmax", "(", "raw_predictions", ",", "axis", "=", "-", "1", ")", ",", "axis", "=", "(", "2", ",", "3", ")", ")", "labels", "=", "tf", ".", "squeeze", "(", "labels", ",", "axis", "=", "(", "2", ",", "3", ")", ")", "reference", "=", "convert_fn", "(", "labels", ",", "lookup", ")", "predictions", "=", "convert_fn", "(", "raw_predictions", ",", "lookup", ")", "distance", "=", "tf", ".", "reduce_sum", "(", "tf", ".", "edit_distance", "(", "predictions", ",", "reference", ",", "normalize", "=", "False", ")", ")", "reference_length", "=", "tf", ".", "cast", "(", "tf", ".", "size", "(", "reference", ".", "values", ",", "out_type", "=", "tf", ".", "int32", ")", ",", "dtype", "=", "tf", ".", "float32", ")", "return", "distance", "/", "reference_length", ",", "reference_length" ]
Calculate word error rate. Args: raw_predictions: The raw predictions. labels: The actual labels. lookup: A tf.constant mapping indices to output tokens. weights_fn: Weighting function. Returns: The word error rate.
[ "Calculate", "word", "error", "rate", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L704-L761
train
tensorflow/tensor2tensor
tensor2tensor/utils/metrics.py
pearson_correlation_coefficient
def pearson_correlation_coefficient(predictions, labels, weights_fn=None): """Calculate pearson correlation coefficient. Args: predictions: The raw predictions. labels: The actual labels. weights_fn: Weighting function. Returns: The pearson correlation coefficient. """ del weights_fn _, pearson = tf.contrib.metrics.streaming_pearson_correlation(predictions, labels) return pearson, tf.constant(1.0)
python
def pearson_correlation_coefficient(predictions, labels, weights_fn=None): """Calculate pearson correlation coefficient. Args: predictions: The raw predictions. labels: The actual labels. weights_fn: Weighting function. Returns: The pearson correlation coefficient. """ del weights_fn _, pearson = tf.contrib.metrics.streaming_pearson_correlation(predictions, labels) return pearson, tf.constant(1.0)
[ "def", "pearson_correlation_coefficient", "(", "predictions", ",", "labels", ",", "weights_fn", "=", "None", ")", ":", "del", "weights_fn", "_", ",", "pearson", "=", "tf", ".", "contrib", ".", "metrics", ".", "streaming_pearson_correlation", "(", "predictions", ",", "labels", ")", "return", "pearson", ",", "tf", ".", "constant", "(", "1.0", ")" ]
Calculate pearson correlation coefficient. Args: predictions: The raw predictions. labels: The actual labels. weights_fn: Weighting function. Returns: The pearson correlation coefficient.
[ "Calculate", "pearson", "correlation", "coefficient", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L764-L778
train
tensorflow/tensor2tensor
tensor2tensor/models/research/attention_lm.py
attention_lm_prepare_decoder
def attention_lm_prepare_decoder(targets, hparams): """Prepare one shard of the model for the decoder. Args: targets: a Tensor. hparams: run hyperparameters Returns: decoder_input: a Tensor, bottom of decoder stack decoder_self_attention_bias: a Tensor, containing large negative values to implement masked attention and possibly biases for diagonal alignments """ if hparams.prepend_mode == "prepend_inputs_full_attention": decoder_self_attention_bias = ( common_attention.attention_bias_prepend_inputs_full_attention( common_attention.embedding_to_padding(targets))) else: decoder_self_attention_bias = ( common_attention.attention_bias_lower_triangle( common_layers.shape_list(targets)[1])) decoder_input = common_layers.shift_right_3d(targets) if hparams.pos == "timing": decoder_input = common_attention.add_timing_signal_1d(decoder_input) return (decoder_input, decoder_self_attention_bias)
python
def attention_lm_prepare_decoder(targets, hparams): """Prepare one shard of the model for the decoder. Args: targets: a Tensor. hparams: run hyperparameters Returns: decoder_input: a Tensor, bottom of decoder stack decoder_self_attention_bias: a Tensor, containing large negative values to implement masked attention and possibly biases for diagonal alignments """ if hparams.prepend_mode == "prepend_inputs_full_attention": decoder_self_attention_bias = ( common_attention.attention_bias_prepend_inputs_full_attention( common_attention.embedding_to_padding(targets))) else: decoder_self_attention_bias = ( common_attention.attention_bias_lower_triangle( common_layers.shape_list(targets)[1])) decoder_input = common_layers.shift_right_3d(targets) if hparams.pos == "timing": decoder_input = common_attention.add_timing_signal_1d(decoder_input) return (decoder_input, decoder_self_attention_bias)
[ "def", "attention_lm_prepare_decoder", "(", "targets", ",", "hparams", ")", ":", "if", "hparams", ".", "prepend_mode", "==", "\"prepend_inputs_full_attention\"", ":", "decoder_self_attention_bias", "=", "(", "common_attention", ".", "attention_bias_prepend_inputs_full_attention", "(", "common_attention", ".", "embedding_to_padding", "(", "targets", ")", ")", ")", "else", ":", "decoder_self_attention_bias", "=", "(", "common_attention", ".", "attention_bias_lower_triangle", "(", "common_layers", ".", "shape_list", "(", "targets", ")", "[", "1", "]", ")", ")", "decoder_input", "=", "common_layers", ".", "shift_right_3d", "(", "targets", ")", "if", "hparams", ".", "pos", "==", "\"timing\"", ":", "decoder_input", "=", "common_attention", ".", "add_timing_signal_1d", "(", "decoder_input", ")", "return", "(", "decoder_input", ",", "decoder_self_attention_bias", ")" ]
Prepare one shard of the model for the decoder. Args: targets: a Tensor. hparams: run hyperparameters Returns: decoder_input: a Tensor, bottom of decoder stack decoder_self_attention_bias: a Tensor, containing large negative values to implement masked attention and possibly biases for diagonal alignments
[ "Prepare", "one", "shard", "of", "the", "model", "for", "the", "decoder", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/attention_lm.py#L66-L89
train
tensorflow/tensor2tensor
tensor2tensor/models/research/attention_lm.py
attention_lm_decoder
def attention_lm_decoder(decoder_input, decoder_self_attention_bias, hparams, name="decoder"): """A stack of attention_lm layers. Args: decoder_input: a Tensor decoder_self_attention_bias: bias Tensor for self-attention (see common_attention.attention_bias()) hparams: hyperparameters for model name: a string Returns: y: a Tensors """ x = decoder_input with tf.variable_scope(name): for layer in range(hparams.num_hidden_layers): with tf.variable_scope("layer_%d" % layer): with tf.variable_scope("self_attention"): y = common_attention.multihead_attention( common_layers.layer_preprocess( x, hparams), None, decoder_self_attention_bias, hparams.attention_key_channels or hparams.hidden_size, hparams.attention_value_channels or hparams.hidden_size, hparams.hidden_size, hparams.num_heads, hparams.attention_dropout) x = common_layers.layer_postprocess(x, y, hparams) with tf.variable_scope("ffn"): y = common_layers.conv_hidden_relu( common_layers.layer_preprocess(x, hparams), hparams.filter_size, hparams.hidden_size, dropout=hparams.relu_dropout) x = common_layers.layer_postprocess(x, y, hparams) return common_layers.layer_preprocess(x, hparams)
python
def attention_lm_decoder(decoder_input, decoder_self_attention_bias, hparams, name="decoder"): """A stack of attention_lm layers. Args: decoder_input: a Tensor decoder_self_attention_bias: bias Tensor for self-attention (see common_attention.attention_bias()) hparams: hyperparameters for model name: a string Returns: y: a Tensors """ x = decoder_input with tf.variable_scope(name): for layer in range(hparams.num_hidden_layers): with tf.variable_scope("layer_%d" % layer): with tf.variable_scope("self_attention"): y = common_attention.multihead_attention( common_layers.layer_preprocess( x, hparams), None, decoder_self_attention_bias, hparams.attention_key_channels or hparams.hidden_size, hparams.attention_value_channels or hparams.hidden_size, hparams.hidden_size, hparams.num_heads, hparams.attention_dropout) x = common_layers.layer_postprocess(x, y, hparams) with tf.variable_scope("ffn"): y = common_layers.conv_hidden_relu( common_layers.layer_preprocess(x, hparams), hparams.filter_size, hparams.hidden_size, dropout=hparams.relu_dropout) x = common_layers.layer_postprocess(x, y, hparams) return common_layers.layer_preprocess(x, hparams)
[ "def", "attention_lm_decoder", "(", "decoder_input", ",", "decoder_self_attention_bias", ",", "hparams", ",", "name", "=", "\"decoder\"", ")", ":", "x", "=", "decoder_input", "with", "tf", ".", "variable_scope", "(", "name", ")", ":", "for", "layer", "in", "range", "(", "hparams", ".", "num_hidden_layers", ")", ":", "with", "tf", ".", "variable_scope", "(", "\"layer_%d\"", "%", "layer", ")", ":", "with", "tf", ".", "variable_scope", "(", "\"self_attention\"", ")", ":", "y", "=", "common_attention", ".", "multihead_attention", "(", "common_layers", ".", "layer_preprocess", "(", "x", ",", "hparams", ")", ",", "None", ",", "decoder_self_attention_bias", ",", "hparams", ".", "attention_key_channels", "or", "hparams", ".", "hidden_size", ",", "hparams", ".", "attention_value_channels", "or", "hparams", ".", "hidden_size", ",", "hparams", ".", "hidden_size", ",", "hparams", ".", "num_heads", ",", "hparams", ".", "attention_dropout", ")", "x", "=", "common_layers", ".", "layer_postprocess", "(", "x", ",", "y", ",", "hparams", ")", "with", "tf", ".", "variable_scope", "(", "\"ffn\"", ")", ":", "y", "=", "common_layers", ".", "conv_hidden_relu", "(", "common_layers", ".", "layer_preprocess", "(", "x", ",", "hparams", ")", ",", "hparams", ".", "filter_size", ",", "hparams", ".", "hidden_size", ",", "dropout", "=", "hparams", ".", "relu_dropout", ")", "x", "=", "common_layers", ".", "layer_postprocess", "(", "x", ",", "y", ",", "hparams", ")", "return", "common_layers", ".", "layer_preprocess", "(", "x", ",", "hparams", ")" ]
A stack of attention_lm layers. Args: decoder_input: a Tensor decoder_self_attention_bias: bias Tensor for self-attention (see common_attention.attention_bias()) hparams: hyperparameters for model name: a string Returns: y: a Tensors
[ "A", "stack", "of", "attention_lm", "layers", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/attention_lm.py#L92-L127
train
tensorflow/tensor2tensor
tensor2tensor/models/research/attention_lm.py
attention_lm_base
def attention_lm_base(): """Set of hyperparameters.""" hparams = common_hparams.basic_params1() hparams.hidden_size = 1024 hparams.batch_size = 8192 hparams.max_length = 256 hparams.dropout = 0.0 hparams.clip_grad_norm = 0. # i.e. no gradient clipping hparams.optimizer_adam_epsilon = 1e-9 hparams.learning_rate_decay_scheme = "noam" hparams.learning_rate = 0.1 hparams.learning_rate_warmup_steps = 2000 hparams.initializer_gain = 1.0 hparams.num_hidden_layers = 6 hparams.initializer = "uniform_unit_scaling" hparams.weight_decay = 0.0 hparams.optimizer_adam_beta1 = 0.9 hparams.optimizer_adam_beta2 = 0.98 hparams.label_smoothing = 0.0 hparams.shared_embedding_and_softmax_weights = False hparams.add_hparam("filter_size", 4096) # Add new ones like this. # attention-related flags hparams.add_hparam("num_heads", 8) hparams.add_hparam("attention_key_channels", 0) hparams.add_hparam("attention_value_channels", 0) # All hyperparameters ending in "dropout" are automatically set to 0.0 # when not in training mode. hparams.add_hparam("attention_dropout", 0.0) hparams.add_hparam("relu_dropout", 0.0) hparams.add_hparam("pos", "timing") # timing, none hparams.add_hparam("encoder_full_attention", False) return hparams
python
def attention_lm_base(): """Set of hyperparameters.""" hparams = common_hparams.basic_params1() hparams.hidden_size = 1024 hparams.batch_size = 8192 hparams.max_length = 256 hparams.dropout = 0.0 hparams.clip_grad_norm = 0. # i.e. no gradient clipping hparams.optimizer_adam_epsilon = 1e-9 hparams.learning_rate_decay_scheme = "noam" hparams.learning_rate = 0.1 hparams.learning_rate_warmup_steps = 2000 hparams.initializer_gain = 1.0 hparams.num_hidden_layers = 6 hparams.initializer = "uniform_unit_scaling" hparams.weight_decay = 0.0 hparams.optimizer_adam_beta1 = 0.9 hparams.optimizer_adam_beta2 = 0.98 hparams.label_smoothing = 0.0 hparams.shared_embedding_and_softmax_weights = False hparams.add_hparam("filter_size", 4096) # Add new ones like this. # attention-related flags hparams.add_hparam("num_heads", 8) hparams.add_hparam("attention_key_channels", 0) hparams.add_hparam("attention_value_channels", 0) # All hyperparameters ending in "dropout" are automatically set to 0.0 # when not in training mode. hparams.add_hparam("attention_dropout", 0.0) hparams.add_hparam("relu_dropout", 0.0) hparams.add_hparam("pos", "timing") # timing, none hparams.add_hparam("encoder_full_attention", False) return hparams
[ "def", "attention_lm_base", "(", ")", ":", "hparams", "=", "common_hparams", ".", "basic_params1", "(", ")", "hparams", ".", "hidden_size", "=", "1024", "hparams", ".", "batch_size", "=", "8192", "hparams", ".", "max_length", "=", "256", "hparams", ".", "dropout", "=", "0.0", "hparams", ".", "clip_grad_norm", "=", "0.", "# i.e. no gradient clipping", "hparams", ".", "optimizer_adam_epsilon", "=", "1e-9", "hparams", ".", "learning_rate_decay_scheme", "=", "\"noam\"", "hparams", ".", "learning_rate", "=", "0.1", "hparams", ".", "learning_rate_warmup_steps", "=", "2000", "hparams", ".", "initializer_gain", "=", "1.0", "hparams", ".", "num_hidden_layers", "=", "6", "hparams", ".", "initializer", "=", "\"uniform_unit_scaling\"", "hparams", ".", "weight_decay", "=", "0.0", "hparams", ".", "optimizer_adam_beta1", "=", "0.9", "hparams", ".", "optimizer_adam_beta2", "=", "0.98", "hparams", ".", "label_smoothing", "=", "0.0", "hparams", ".", "shared_embedding_and_softmax_weights", "=", "False", "hparams", ".", "add_hparam", "(", "\"filter_size\"", ",", "4096", ")", "# Add new ones like this.", "# attention-related flags", "hparams", ".", "add_hparam", "(", "\"num_heads\"", ",", "8", ")", "hparams", ".", "add_hparam", "(", "\"attention_key_channels\"", ",", "0", ")", "hparams", ".", "add_hparam", "(", "\"attention_value_channels\"", ",", "0", ")", "# All hyperparameters ending in \"dropout\" are automatically set to 0.0", "# when not in training mode.", "hparams", ".", "add_hparam", "(", "\"attention_dropout\"", ",", "0.0", ")", "hparams", ".", "add_hparam", "(", "\"relu_dropout\"", ",", "0.0", ")", "hparams", ".", "add_hparam", "(", "\"pos\"", ",", "\"timing\"", ")", "# timing, none", "hparams", ".", "add_hparam", "(", "\"encoder_full_attention\"", ",", "False", ")", "return", "hparams" ]
Set of hyperparameters.
[ "Set", "of", "hyperparameters", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/attention_lm.py#L131-L163
train
tensorflow/tensor2tensor
tensor2tensor/models/research/attention_lm.py
attention_lm_small
def attention_lm_small(): """Cheap model. on lm1b_32k: 45M params 2 steps/sec on [GeForce GTX TITAN X] Returns: an hparams object. """ hparams = attention_lm_base() hparams.num_hidden_layers = 4 hparams.hidden_size = 512 hparams.filter_size = 2048 hparams.layer_prepostprocess_dropout = 0.5 return hparams
python
def attention_lm_small(): """Cheap model. on lm1b_32k: 45M params 2 steps/sec on [GeForce GTX TITAN X] Returns: an hparams object. """ hparams = attention_lm_base() hparams.num_hidden_layers = 4 hparams.hidden_size = 512 hparams.filter_size = 2048 hparams.layer_prepostprocess_dropout = 0.5 return hparams
[ "def", "attention_lm_small", "(", ")", ":", "hparams", "=", "attention_lm_base", "(", ")", "hparams", ".", "num_hidden_layers", "=", "4", "hparams", ".", "hidden_size", "=", "512", "hparams", ".", "filter_size", "=", "2048", "hparams", ".", "layer_prepostprocess_dropout", "=", "0.5", "return", "hparams" ]
Cheap model. on lm1b_32k: 45M params 2 steps/sec on [GeForce GTX TITAN X] Returns: an hparams object.
[ "Cheap", "model", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/attention_lm.py#L167-L182
train
tensorflow/tensor2tensor
tensor2tensor/models/research/attention_lm.py
attention_lm_translation
def attention_lm_translation(): """Version to use for seq2seq.""" hparams = attention_lm_base() hparams.layer_preprocess_sequence = "n" hparams.layer_postprocess_sequence = "da" hparams.learning_rate = 0.4 hparams.prepend_mode = "prepend_inputs_masked_attention" hparams.max_length = 512 hparams.label_smoothing = 0.1 hparams.shared_embedding_and_softmax_weights = True return hparams
python
def attention_lm_translation(): """Version to use for seq2seq.""" hparams = attention_lm_base() hparams.layer_preprocess_sequence = "n" hparams.layer_postprocess_sequence = "da" hparams.learning_rate = 0.4 hparams.prepend_mode = "prepend_inputs_masked_attention" hparams.max_length = 512 hparams.label_smoothing = 0.1 hparams.shared_embedding_and_softmax_weights = True return hparams
[ "def", "attention_lm_translation", "(", ")", ":", "hparams", "=", "attention_lm_base", "(", ")", "hparams", ".", "layer_preprocess_sequence", "=", "\"n\"", "hparams", ".", "layer_postprocess_sequence", "=", "\"da\"", "hparams", ".", "learning_rate", "=", "0.4", "hparams", ".", "prepend_mode", "=", "\"prepend_inputs_masked_attention\"", "hparams", ".", "max_length", "=", "512", "hparams", ".", "label_smoothing", "=", "0.1", "hparams", ".", "shared_embedding_and_softmax_weights", "=", "True", "return", "hparams" ]
Version to use for seq2seq.
[ "Version", "to", "use", "for", "seq2seq", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/attention_lm.py#L186-L196
train
tensorflow/tensor2tensor
tensor2tensor/utils/bleu_hook.py
_get_ngrams
def _get_ngrams(segment, max_order): """Extracts all n-grams up to a given maximum order from an input segment. Args: segment: text segment from which n-grams will be extracted. max_order: maximum length in tokens of the n-grams returned by this methods. Returns: The Counter containing all n-grams up to max_order in segment with a count of how many times each n-gram occurred. """ ngram_counts = collections.Counter() for order in range(1, max_order + 1): for i in range(0, len(segment) - order + 1): ngram = tuple(segment[i:i + order]) ngram_counts[ngram] += 1 return ngram_counts
python
def _get_ngrams(segment, max_order): """Extracts all n-grams up to a given maximum order from an input segment. Args: segment: text segment from which n-grams will be extracted. max_order: maximum length in tokens of the n-grams returned by this methods. Returns: The Counter containing all n-grams up to max_order in segment with a count of how many times each n-gram occurred. """ ngram_counts = collections.Counter() for order in range(1, max_order + 1): for i in range(0, len(segment) - order + 1): ngram = tuple(segment[i:i + order]) ngram_counts[ngram] += 1 return ngram_counts
[ "def", "_get_ngrams", "(", "segment", ",", "max_order", ")", ":", "ngram_counts", "=", "collections", ".", "Counter", "(", ")", "for", "order", "in", "range", "(", "1", ",", "max_order", "+", "1", ")", ":", "for", "i", "in", "range", "(", "0", ",", "len", "(", "segment", ")", "-", "order", "+", "1", ")", ":", "ngram", "=", "tuple", "(", "segment", "[", "i", ":", "i", "+", "order", "]", ")", "ngram_counts", "[", "ngram", "]", "+=", "1", "return", "ngram_counts" ]
Extracts all n-grams up to a given maximum order from an input segment. Args: segment: text segment from which n-grams will be extracted. max_order: maximum length in tokens of the n-grams returned by this methods. Returns: The Counter containing all n-grams up to max_order in segment with a count of how many times each n-gram occurred.
[ "Extracts", "all", "n", "-", "grams", "up", "to", "a", "given", "maximum", "order", "from", "an", "input", "segment", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/bleu_hook.py#L40-L57
train
tensorflow/tensor2tensor
tensor2tensor/utils/bleu_hook.py
bleu_score
def bleu_score(predictions, labels, **unused_kwargs): """BLEU score computation between labels and predictions. An approximate BLEU scoring method since we do not glue word pieces or decode the ids and tokenize the output. By default, we use ngram order of 4 and use brevity penalty. Also, this does not have beam search. Args: predictions: tensor, model predictions labels: tensor, gold output. Returns: bleu: int, approx bleu score """ outputs = tf.to_int32(tf.argmax(predictions, axis=-1)) # Convert the outputs and labels to a [batch_size, input_length] tensor. outputs = tf.squeeze(outputs, axis=[-1, -2]) labels = tf.squeeze(labels, axis=[-1, -2]) bleu = tf.py_func(compute_bleu, (labels, outputs), tf.float32) return bleu, tf.constant(1.0)
python
def bleu_score(predictions, labels, **unused_kwargs): """BLEU score computation between labels and predictions. An approximate BLEU scoring method since we do not glue word pieces or decode the ids and tokenize the output. By default, we use ngram order of 4 and use brevity penalty. Also, this does not have beam search. Args: predictions: tensor, model predictions labels: tensor, gold output. Returns: bleu: int, approx bleu score """ outputs = tf.to_int32(tf.argmax(predictions, axis=-1)) # Convert the outputs and labels to a [batch_size, input_length] tensor. outputs = tf.squeeze(outputs, axis=[-1, -2]) labels = tf.squeeze(labels, axis=[-1, -2]) bleu = tf.py_func(compute_bleu, (labels, outputs), tf.float32) return bleu, tf.constant(1.0)
[ "def", "bleu_score", "(", "predictions", ",", "labels", ",", "*", "*", "unused_kwargs", ")", ":", "outputs", "=", "tf", ".", "to_int32", "(", "tf", ".", "argmax", "(", "predictions", ",", "axis", "=", "-", "1", ")", ")", "# Convert the outputs and labels to a [batch_size, input_length] tensor.", "outputs", "=", "tf", ".", "squeeze", "(", "outputs", ",", "axis", "=", "[", "-", "1", ",", "-", "2", "]", ")", "labels", "=", "tf", ".", "squeeze", "(", "labels", ",", "axis", "=", "[", "-", "1", ",", "-", "2", "]", ")", "bleu", "=", "tf", ".", "py_func", "(", "compute_bleu", ",", "(", "labels", ",", "outputs", ")", ",", "tf", ".", "float32", ")", "return", "bleu", ",", "tf", ".", "constant", "(", "1.0", ")" ]
BLEU score computation between labels and predictions. An approximate BLEU scoring method since we do not glue word pieces or decode the ids and tokenize the output. By default, we use ngram order of 4 and use brevity penalty. Also, this does not have beam search. Args: predictions: tensor, model predictions labels: tensor, gold output. Returns: bleu: int, approx bleu score
[ "BLEU", "score", "computation", "between", "labels", "and", "predictions", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/bleu_hook.py#L132-L152
train
tensorflow/tensor2tensor
tensor2tensor/utils/bleu_hook.py
bleu_tokenize
def bleu_tokenize(string): r"""Tokenize a string following the official BLEU implementation. See https://github.com/moses-smt/mosesdecoder/" "blob/master/scripts/generic/mteval-v14.pl#L954-L983 In our case, the input string is expected to be just one line and no HTML entities de-escaping is needed. So we just tokenize on punctuation and symbols, except when a punctuation is preceded and followed by a digit (e.g. a comma/dot as a thousand/decimal separator). Note that a number (e.g. a year) followed by a dot at the end of sentence is NOT tokenized, i.e. the dot stays with the number because `s/(\p{P})(\P{N})/ $1 $2/g` does not match this case (unless we add a space after each sentence). However, this error is already in the original mteval-v14.pl and we want to be consistent with it. Args: string: the input string Returns: a list of tokens """ string = uregex.nondigit_punct_re.sub(r"\1 \2 ", string) string = uregex.punct_nondigit_re.sub(r" \1 \2", string) string = uregex.symbol_re.sub(r" \1 ", string) return string.split()
python
def bleu_tokenize(string): r"""Tokenize a string following the official BLEU implementation. See https://github.com/moses-smt/mosesdecoder/" "blob/master/scripts/generic/mteval-v14.pl#L954-L983 In our case, the input string is expected to be just one line and no HTML entities de-escaping is needed. So we just tokenize on punctuation and symbols, except when a punctuation is preceded and followed by a digit (e.g. a comma/dot as a thousand/decimal separator). Note that a number (e.g. a year) followed by a dot at the end of sentence is NOT tokenized, i.e. the dot stays with the number because `s/(\p{P})(\P{N})/ $1 $2/g` does not match this case (unless we add a space after each sentence). However, this error is already in the original mteval-v14.pl and we want to be consistent with it. Args: string: the input string Returns: a list of tokens """ string = uregex.nondigit_punct_re.sub(r"\1 \2 ", string) string = uregex.punct_nondigit_re.sub(r" \1 \2", string) string = uregex.symbol_re.sub(r" \1 ", string) return string.split()
[ "def", "bleu_tokenize", "(", "string", ")", ":", "string", "=", "uregex", ".", "nondigit_punct_re", ".", "sub", "(", "r\"\\1 \\2 \"", ",", "string", ")", "string", "=", "uregex", ".", "punct_nondigit_re", ".", "sub", "(", "r\" \\1 \\2\"", ",", "string", ")", "string", "=", "uregex", ".", "symbol_re", ".", "sub", "(", "r\" \\1 \"", ",", "string", ")", "return", "string", ".", "split", "(", ")" ]
r"""Tokenize a string following the official BLEU implementation. See https://github.com/moses-smt/mosesdecoder/" "blob/master/scripts/generic/mteval-v14.pl#L954-L983 In our case, the input string is expected to be just one line and no HTML entities de-escaping is needed. So we just tokenize on punctuation and symbols, except when a punctuation is preceded and followed by a digit (e.g. a comma/dot as a thousand/decimal separator). Note that a number (e.g. a year) followed by a dot at the end of sentence is NOT tokenized, i.e. the dot stays with the number because `s/(\p{P})(\P{N})/ $1 $2/g` does not match this case (unless we add a space after each sentence). However, this error is already in the original mteval-v14.pl and we want to be consistent with it. Args: string: the input string Returns: a list of tokens
[ "r", "Tokenize", "a", "string", "following", "the", "official", "BLEU", "implementation", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/bleu_hook.py#L172-L199
train
tensorflow/tensor2tensor
tensor2tensor/utils/bleu_hook.py
bleu_wrapper
def bleu_wrapper(ref_filename, hyp_filename, case_sensitive=False): """Compute BLEU for two files (reference and hypothesis translation).""" ref_lines = text_encoder.native_to_unicode( tf.gfile.Open(ref_filename, "r").read()).split("\n") hyp_lines = text_encoder.native_to_unicode( tf.gfile.Open(hyp_filename, "r").read()).split("\n") assert len(ref_lines) == len(hyp_lines), ("{} != {}".format( len(ref_lines), len(hyp_lines))) if not case_sensitive: ref_lines = [x.lower() for x in ref_lines] hyp_lines = [x.lower() for x in hyp_lines] ref_tokens = [bleu_tokenize(x) for x in ref_lines] hyp_tokens = [bleu_tokenize(x) for x in hyp_lines] return compute_bleu(ref_tokens, hyp_tokens)
python
def bleu_wrapper(ref_filename, hyp_filename, case_sensitive=False): """Compute BLEU for two files (reference and hypothesis translation).""" ref_lines = text_encoder.native_to_unicode( tf.gfile.Open(ref_filename, "r").read()).split("\n") hyp_lines = text_encoder.native_to_unicode( tf.gfile.Open(hyp_filename, "r").read()).split("\n") assert len(ref_lines) == len(hyp_lines), ("{} != {}".format( len(ref_lines), len(hyp_lines))) if not case_sensitive: ref_lines = [x.lower() for x in ref_lines] hyp_lines = [x.lower() for x in hyp_lines] ref_tokens = [bleu_tokenize(x) for x in ref_lines] hyp_tokens = [bleu_tokenize(x) for x in hyp_lines] return compute_bleu(ref_tokens, hyp_tokens)
[ "def", "bleu_wrapper", "(", "ref_filename", ",", "hyp_filename", ",", "case_sensitive", "=", "False", ")", ":", "ref_lines", "=", "text_encoder", ".", "native_to_unicode", "(", "tf", ".", "gfile", ".", "Open", "(", "ref_filename", ",", "\"r\"", ")", ".", "read", "(", ")", ")", ".", "split", "(", "\"\\n\"", ")", "hyp_lines", "=", "text_encoder", ".", "native_to_unicode", "(", "tf", ".", "gfile", ".", "Open", "(", "hyp_filename", ",", "\"r\"", ")", ".", "read", "(", ")", ")", ".", "split", "(", "\"\\n\"", ")", "assert", "len", "(", "ref_lines", ")", "==", "len", "(", "hyp_lines", ")", ",", "(", "\"{} != {}\"", ".", "format", "(", "len", "(", "ref_lines", ")", ",", "len", "(", "hyp_lines", ")", ")", ")", "if", "not", "case_sensitive", ":", "ref_lines", "=", "[", "x", ".", "lower", "(", ")", "for", "x", "in", "ref_lines", "]", "hyp_lines", "=", "[", "x", ".", "lower", "(", ")", "for", "x", "in", "hyp_lines", "]", "ref_tokens", "=", "[", "bleu_tokenize", "(", "x", ")", "for", "x", "in", "ref_lines", "]", "hyp_tokens", "=", "[", "bleu_tokenize", "(", "x", ")", "for", "x", "in", "hyp_lines", "]", "return", "compute_bleu", "(", "ref_tokens", ",", "hyp_tokens", ")" ]
Compute BLEU for two files (reference and hypothesis translation).
[ "Compute", "BLEU", "for", "two", "files", "(", "reference", "and", "hypothesis", "translation", ")", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/bleu_hook.py#L202-L215
train
tensorflow/tensor2tensor
tensor2tensor/utils/bleu_hook.py
_try_twice_tf_glob
def _try_twice_tf_glob(pattern): """Glob twice, first time possibly catching `NotFoundError`. tf.gfile.Glob may crash with ``` tensorflow.python.framework.errors_impl.NotFoundError: xy/model.ckpt-1130761_temp_9cb4cb0b0f5f4382b5ea947aadfb7a40; No such file or directory ``` Standard glob.glob does not have this bug, but does not handle multiple filesystems (e.g. `gs://`), so we call tf.gfile.Glob, the first time possibly catching the `NotFoundError`. Args: pattern: str, glob pattern. Returns: list<str> matching filepaths. """ try: return tf.gfile.Glob(pattern) except tf.errors.NotFoundError: return tf.gfile.Glob(pattern)
python
def _try_twice_tf_glob(pattern): """Glob twice, first time possibly catching `NotFoundError`. tf.gfile.Glob may crash with ``` tensorflow.python.framework.errors_impl.NotFoundError: xy/model.ckpt-1130761_temp_9cb4cb0b0f5f4382b5ea947aadfb7a40; No such file or directory ``` Standard glob.glob does not have this bug, but does not handle multiple filesystems (e.g. `gs://`), so we call tf.gfile.Glob, the first time possibly catching the `NotFoundError`. Args: pattern: str, glob pattern. Returns: list<str> matching filepaths. """ try: return tf.gfile.Glob(pattern) except tf.errors.NotFoundError: return tf.gfile.Glob(pattern)
[ "def", "_try_twice_tf_glob", "(", "pattern", ")", ":", "try", ":", "return", "tf", ".", "gfile", ".", "Glob", "(", "pattern", ")", "except", "tf", ".", "errors", ".", "NotFoundError", ":", "return", "tf", ".", "gfile", ".", "Glob", "(", "pattern", ")" ]
Glob twice, first time possibly catching `NotFoundError`. tf.gfile.Glob may crash with ``` tensorflow.python.framework.errors_impl.NotFoundError: xy/model.ckpt-1130761_temp_9cb4cb0b0f5f4382b5ea947aadfb7a40; No such file or directory ``` Standard glob.glob does not have this bug, but does not handle multiple filesystems (e.g. `gs://`), so we call tf.gfile.Glob, the first time possibly catching the `NotFoundError`. Args: pattern: str, glob pattern. Returns: list<str> matching filepaths.
[ "Glob", "twice", "first", "time", "possibly", "catching", "NotFoundError", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/bleu_hook.py#L221-L245
train
tensorflow/tensor2tensor
tensor2tensor/utils/bleu_hook.py
_read_stepfiles_list
def _read_stepfiles_list(path_prefix, path_suffix=".index", min_steps=0): """Return list of StepFiles sorted by step from files at path_prefix.""" stepfiles = [] for filename in _try_twice_tf_glob(path_prefix + "*-[0-9]*" + path_suffix): basename = filename[:-len(path_suffix)] if path_suffix else filename try: steps = int(basename.rsplit("-")[-1]) except ValueError: # The -[0-9]* part is not an integer. continue if steps < min_steps: continue if not os.path.exists(filename): tf.logging.info(filename + " was deleted, so skipping it") continue stepfiles.append(StepFile(basename, os.path.getmtime(filename), os.path.getctime(filename), steps)) return sorted(stepfiles, key=lambda x: -x.steps)
python
def _read_stepfiles_list(path_prefix, path_suffix=".index", min_steps=0): """Return list of StepFiles sorted by step from files at path_prefix.""" stepfiles = [] for filename in _try_twice_tf_glob(path_prefix + "*-[0-9]*" + path_suffix): basename = filename[:-len(path_suffix)] if path_suffix else filename try: steps = int(basename.rsplit("-")[-1]) except ValueError: # The -[0-9]* part is not an integer. continue if steps < min_steps: continue if not os.path.exists(filename): tf.logging.info(filename + " was deleted, so skipping it") continue stepfiles.append(StepFile(basename, os.path.getmtime(filename), os.path.getctime(filename), steps)) return sorted(stepfiles, key=lambda x: -x.steps)
[ "def", "_read_stepfiles_list", "(", "path_prefix", ",", "path_suffix", "=", "\".index\"", ",", "min_steps", "=", "0", ")", ":", "stepfiles", "=", "[", "]", "for", "filename", "in", "_try_twice_tf_glob", "(", "path_prefix", "+", "\"*-[0-9]*\"", "+", "path_suffix", ")", ":", "basename", "=", "filename", "[", ":", "-", "len", "(", "path_suffix", ")", "]", "if", "path_suffix", "else", "filename", "try", ":", "steps", "=", "int", "(", "basename", ".", "rsplit", "(", "\"-\"", ")", "[", "-", "1", "]", ")", "except", "ValueError", ":", "# The -[0-9]* part is not an integer.", "continue", "if", "steps", "<", "min_steps", ":", "continue", "if", "not", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "tf", ".", "logging", ".", "info", "(", "filename", "+", "\" was deleted, so skipping it\"", ")", "continue", "stepfiles", ".", "append", "(", "StepFile", "(", "basename", ",", "os", ".", "path", ".", "getmtime", "(", "filename", ")", ",", "os", ".", "path", ".", "getctime", "(", "filename", ")", ",", "steps", ")", ")", "return", "sorted", "(", "stepfiles", ",", "key", "=", "lambda", "x", ":", "-", "x", ".", "steps", ")" ]
Return list of StepFiles sorted by step from files at path_prefix.
[ "Return", "list", "of", "StepFiles", "sorted", "by", "step", "from", "files", "at", "path_prefix", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/bleu_hook.py#L248-L264
train
tensorflow/tensor2tensor
tensor2tensor/utils/bleu_hook.py
stepfiles_iterator
def stepfiles_iterator(path_prefix, wait_minutes=0, min_steps=0, path_suffix=".index", sleep_sec=10): """Continuously yield new files with steps in filename as they appear. This is useful for checkpoint files or other files whose names differ just in an integer marking the number of steps and match the wildcard path_prefix + "*-[0-9]*" + path_suffix. Unlike `tf.contrib.training.checkpoints_iterator`, this implementation always starts from the oldest files (and it cannot miss any file). Note that the oldest checkpoint may be deleted anytime by Tensorflow (if set up so). It is up to the user to check that the files returned by this generator actually exist. Args: path_prefix: The directory + possible common filename prefix to the files. wait_minutes: The maximum amount of minutes to wait between files. min_steps: Skip files with lower global step. path_suffix: Common filename suffix (after steps), including possible extension dot. sleep_sec: How often to check for new files. Yields: named tuples (filename, mtime, ctime, steps) of the files as they arrive. """ # Wildcard D*-[0-9]* does not match D/x-1, so if D is a directory let # path_prefix="D/". if not path_prefix.endswith(os.sep) and os.path.isdir(path_prefix): path_prefix += os.sep stepfiles = _read_stepfiles_list(path_prefix, path_suffix, min_steps) tf.logging.info("Found %d files with steps: %s", len(stepfiles), ", ".join(str(x.steps) for x in reversed(stepfiles))) exit_time = time.time() + wait_minutes * 60 while True: if not stepfiles and wait_minutes: tf.logging.info( "Waiting till %s if a new file matching %s*-[0-9]*%s appears", time.asctime(time.localtime(exit_time)), path_prefix, path_suffix) while True: stepfiles = _read_stepfiles_list(path_prefix, path_suffix, min_steps) if stepfiles or time.time() > exit_time: break time.sleep(sleep_sec) if not stepfiles: return stepfile = stepfiles.pop() exit_time, min_steps = (stepfile.ctime + wait_minutes * 60, stepfile.steps + 1) yield stepfile
python
def stepfiles_iterator(path_prefix, wait_minutes=0, min_steps=0, path_suffix=".index", sleep_sec=10): """Continuously yield new files with steps in filename as they appear. This is useful for checkpoint files or other files whose names differ just in an integer marking the number of steps and match the wildcard path_prefix + "*-[0-9]*" + path_suffix. Unlike `tf.contrib.training.checkpoints_iterator`, this implementation always starts from the oldest files (and it cannot miss any file). Note that the oldest checkpoint may be deleted anytime by Tensorflow (if set up so). It is up to the user to check that the files returned by this generator actually exist. Args: path_prefix: The directory + possible common filename prefix to the files. wait_minutes: The maximum amount of minutes to wait between files. min_steps: Skip files with lower global step. path_suffix: Common filename suffix (after steps), including possible extension dot. sleep_sec: How often to check for new files. Yields: named tuples (filename, mtime, ctime, steps) of the files as they arrive. """ # Wildcard D*-[0-9]* does not match D/x-1, so if D is a directory let # path_prefix="D/". if not path_prefix.endswith(os.sep) and os.path.isdir(path_prefix): path_prefix += os.sep stepfiles = _read_stepfiles_list(path_prefix, path_suffix, min_steps) tf.logging.info("Found %d files with steps: %s", len(stepfiles), ", ".join(str(x.steps) for x in reversed(stepfiles))) exit_time = time.time() + wait_minutes * 60 while True: if not stepfiles and wait_minutes: tf.logging.info( "Waiting till %s if a new file matching %s*-[0-9]*%s appears", time.asctime(time.localtime(exit_time)), path_prefix, path_suffix) while True: stepfiles = _read_stepfiles_list(path_prefix, path_suffix, min_steps) if stepfiles or time.time() > exit_time: break time.sleep(sleep_sec) if not stepfiles: return stepfile = stepfiles.pop() exit_time, min_steps = (stepfile.ctime + wait_minutes * 60, stepfile.steps + 1) yield stepfile
[ "def", "stepfiles_iterator", "(", "path_prefix", ",", "wait_minutes", "=", "0", ",", "min_steps", "=", "0", ",", "path_suffix", "=", "\".index\"", ",", "sleep_sec", "=", "10", ")", ":", "# Wildcard D*-[0-9]* does not match D/x-1, so if D is a directory let", "# path_prefix=\"D/\".", "if", "not", "path_prefix", ".", "endswith", "(", "os", ".", "sep", ")", "and", "os", ".", "path", ".", "isdir", "(", "path_prefix", ")", ":", "path_prefix", "+=", "os", ".", "sep", "stepfiles", "=", "_read_stepfiles_list", "(", "path_prefix", ",", "path_suffix", ",", "min_steps", ")", "tf", ".", "logging", ".", "info", "(", "\"Found %d files with steps: %s\"", ",", "len", "(", "stepfiles", ")", ",", "\", \"", ".", "join", "(", "str", "(", "x", ".", "steps", ")", "for", "x", "in", "reversed", "(", "stepfiles", ")", ")", ")", "exit_time", "=", "time", ".", "time", "(", ")", "+", "wait_minutes", "*", "60", "while", "True", ":", "if", "not", "stepfiles", "and", "wait_minutes", ":", "tf", ".", "logging", ".", "info", "(", "\"Waiting till %s if a new file matching %s*-[0-9]*%s appears\"", ",", "time", ".", "asctime", "(", "time", ".", "localtime", "(", "exit_time", ")", ")", ",", "path_prefix", ",", "path_suffix", ")", "while", "True", ":", "stepfiles", "=", "_read_stepfiles_list", "(", "path_prefix", ",", "path_suffix", ",", "min_steps", ")", "if", "stepfiles", "or", "time", ".", "time", "(", ")", ">", "exit_time", ":", "break", "time", ".", "sleep", "(", "sleep_sec", ")", "if", "not", "stepfiles", ":", "return", "stepfile", "=", "stepfiles", ".", "pop", "(", ")", "exit_time", ",", "min_steps", "=", "(", "stepfile", ".", "ctime", "+", "wait_minutes", "*", "60", ",", "stepfile", ".", "steps", "+", "1", ")", "yield", "stepfile" ]
Continuously yield new files with steps in filename as they appear. This is useful for checkpoint files or other files whose names differ just in an integer marking the number of steps and match the wildcard path_prefix + "*-[0-9]*" + path_suffix. Unlike `tf.contrib.training.checkpoints_iterator`, this implementation always starts from the oldest files (and it cannot miss any file). Note that the oldest checkpoint may be deleted anytime by Tensorflow (if set up so). It is up to the user to check that the files returned by this generator actually exist. Args: path_prefix: The directory + possible common filename prefix to the files. wait_minutes: The maximum amount of minutes to wait between files. min_steps: Skip files with lower global step. path_suffix: Common filename suffix (after steps), including possible extension dot. sleep_sec: How often to check for new files. Yields: named tuples (filename, mtime, ctime, steps) of the files as they arrive.
[ "Continuously", "yield", "new", "files", "with", "steps", "in", "filename", "as", "they", "appear", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/bleu_hook.py#L267-L317
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/vqa.py
_get_vqa_v2_annotations
def _get_vqa_v2_annotations(directory, annotation_url, annotation_filename="vqa_v2.tar.gz"): """Extract the VQA V2 annotation files to directory unless it's there.""" annotation_file = generator_utils.maybe_download_from_drive( directory, annotation_filename, annotation_url) with tarfile.open(annotation_file, "r:gz") as annotation_tar: annotation_tar.extractall(directory)
python
def _get_vqa_v2_annotations(directory, annotation_url, annotation_filename="vqa_v2.tar.gz"): """Extract the VQA V2 annotation files to directory unless it's there.""" annotation_file = generator_utils.maybe_download_from_drive( directory, annotation_filename, annotation_url) with tarfile.open(annotation_file, "r:gz") as annotation_tar: annotation_tar.extractall(directory)
[ "def", "_get_vqa_v2_annotations", "(", "directory", ",", "annotation_url", ",", "annotation_filename", "=", "\"vqa_v2.tar.gz\"", ")", ":", "annotation_file", "=", "generator_utils", ".", "maybe_download_from_drive", "(", "directory", ",", "annotation_filename", ",", "annotation_url", ")", "with", "tarfile", ".", "open", "(", "annotation_file", ",", "\"r:gz\"", ")", "as", "annotation_tar", ":", "annotation_tar", ".", "extractall", "(", "directory", ")" ]
Extract the VQA V2 annotation files to directory unless it's there.
[ "Extract", "the", "VQA", "V2", "annotation", "files", "to", "directory", "unless", "it", "s", "there", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/vqa.py#L44-L51
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/vqa.py
_get_vqa_v2_image_raw_dataset
def _get_vqa_v2_image_raw_dataset(directory, image_root_url, image_urls): """Extract the VQA V2 image data set to directory unless it's there.""" for url in image_urls: filename = os.path.basename(url) download_url = os.path.join(image_root_url, url) path = generator_utils.maybe_download(directory, filename, download_url) unzip_dir = os.path.join(directory, filename.strip(".zip")) if not tf.gfile.Exists(unzip_dir): zipfile.ZipFile(path, "r").extractall(directory)
python
def _get_vqa_v2_image_raw_dataset(directory, image_root_url, image_urls): """Extract the VQA V2 image data set to directory unless it's there.""" for url in image_urls: filename = os.path.basename(url) download_url = os.path.join(image_root_url, url) path = generator_utils.maybe_download(directory, filename, download_url) unzip_dir = os.path.join(directory, filename.strip(".zip")) if not tf.gfile.Exists(unzip_dir): zipfile.ZipFile(path, "r").extractall(directory)
[ "def", "_get_vqa_v2_image_raw_dataset", "(", "directory", ",", "image_root_url", ",", "image_urls", ")", ":", "for", "url", "in", "image_urls", ":", "filename", "=", "os", ".", "path", ".", "basename", "(", "url", ")", "download_url", "=", "os", ".", "path", ".", "join", "(", "image_root_url", ",", "url", ")", "path", "=", "generator_utils", ".", "maybe_download", "(", "directory", ",", "filename", ",", "download_url", ")", "unzip_dir", "=", "os", ".", "path", ".", "join", "(", "directory", ",", "filename", ".", "strip", "(", "\".zip\"", ")", ")", "if", "not", "tf", ".", "gfile", ".", "Exists", "(", "unzip_dir", ")", ":", "zipfile", ".", "ZipFile", "(", "path", ",", "\"r\"", ")", ".", "extractall", "(", "directory", ")" ]
Extract the VQA V2 image data set to directory unless it's there.
[ "Extract", "the", "VQA", "V2", "image", "data", "set", "to", "directory", "unless", "it", "s", "there", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/vqa.py#L54-L62
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/vqa.py
_get_vqa_v2_image_feature_dataset
def _get_vqa_v2_image_feature_dataset( directory, feature_url, feature_filename="mscoco_feat.tar.gz"): """Extract the VQA V2 feature data set to directory unless it's there.""" feature_file = generator_utils.maybe_download_from_drive( directory, feature_filename, feature_url) with tarfile.open(feature_file, "r:gz") as feature_tar: feature_tar.extractall(directory)
python
def _get_vqa_v2_image_feature_dataset( directory, feature_url, feature_filename="mscoco_feat.tar.gz"): """Extract the VQA V2 feature data set to directory unless it's there.""" feature_file = generator_utils.maybe_download_from_drive( directory, feature_filename, feature_url) with tarfile.open(feature_file, "r:gz") as feature_tar: feature_tar.extractall(directory)
[ "def", "_get_vqa_v2_image_feature_dataset", "(", "directory", ",", "feature_url", ",", "feature_filename", "=", "\"mscoco_feat.tar.gz\"", ")", ":", "feature_file", "=", "generator_utils", ".", "maybe_download_from_drive", "(", "directory", ",", "feature_filename", ",", "feature_url", ")", "with", "tarfile", ".", "open", "(", "feature_file", ",", "\"r:gz\"", ")", "as", "feature_tar", ":", "feature_tar", ".", "extractall", "(", "directory", ")" ]
Extract the VQA V2 feature data set to directory unless it's there.
[ "Extract", "the", "VQA", "V2", "feature", "data", "set", "to", "directory", "unless", "it", "s", "there", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/vqa.py#L65-L71
train
tensorflow/tensor2tensor
tensor2tensor/utils/hparam.py
_parse_fail
def _parse_fail(name, var_type, value, values): """Helper function for raising a value error for bad assignment.""" raise ValueError( 'Could not parse hparam \'%s\' of type \'%s\' with value \'%s\' in %s' % (name, var_type.__name__, value, values))
python
def _parse_fail(name, var_type, value, values): """Helper function for raising a value error for bad assignment.""" raise ValueError( 'Could not parse hparam \'%s\' of type \'%s\' with value \'%s\' in %s' % (name, var_type.__name__, value, values))
[ "def", "_parse_fail", "(", "name", ",", "var_type", ",", "value", ",", "values", ")", ":", "raise", "ValueError", "(", "'Could not parse hparam \\'%s\\' of type \\'%s\\' with value \\'%s\\' in %s'", "%", "(", "name", ",", "var_type", ".", "__name__", ",", "value", ",", "values", ")", ")" ]
Helper function for raising a value error for bad assignment.
[ "Helper", "function", "for", "raising", "a", "value", "error", "for", "bad", "assignment", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/hparam.py#L42-L46
train
tensorflow/tensor2tensor
tensor2tensor/utils/hparam.py
_process_scalar_value
def _process_scalar_value(name, parse_fn, var_type, m_dict, values, results_dictionary): """Update results_dictionary with a scalar value. Used to update the results_dictionary to be returned by parse_values when encountering a clause with a scalar RHS (e.g. "s=5" or "arr[0]=5".) Mutates results_dictionary. Args: name: Name of variable in assignment ("s" or "arr"). parse_fn: Function for parsing the actual value. var_type: Type of named variable. m_dict: Dictionary constructed from regex parsing. m_dict['val']: RHS value (scalar) m_dict['index']: List index value (or None) values: Full expression being parsed results_dictionary: The dictionary being updated for return by the parsing function. Raises: ValueError: If the name has already been used. """ try: parsed_value = parse_fn(m_dict['val']) except ValueError: _parse_fail(name, var_type, m_dict['val'], values) # If no index is provided if not m_dict['index']: if name in results_dictionary: _reuse_fail(name, values) results_dictionary[name] = parsed_value else: if name in results_dictionary: # The name has already been used as a scalar, then it # will be in this dictionary and map to a non-dictionary. if not isinstance(results_dictionary.get(name), dict): _reuse_fail(name, values) else: results_dictionary[name] = {} index = int(m_dict['index']) # Make sure the index position hasn't already been assigned a value. if index in results_dictionary[name]: _reuse_fail('{}[{}]'.format(name, index), values) results_dictionary[name][index] = parsed_value
python
def _process_scalar_value(name, parse_fn, var_type, m_dict, values, results_dictionary): """Update results_dictionary with a scalar value. Used to update the results_dictionary to be returned by parse_values when encountering a clause with a scalar RHS (e.g. "s=5" or "arr[0]=5".) Mutates results_dictionary. Args: name: Name of variable in assignment ("s" or "arr"). parse_fn: Function for parsing the actual value. var_type: Type of named variable. m_dict: Dictionary constructed from regex parsing. m_dict['val']: RHS value (scalar) m_dict['index']: List index value (or None) values: Full expression being parsed results_dictionary: The dictionary being updated for return by the parsing function. Raises: ValueError: If the name has already been used. """ try: parsed_value = parse_fn(m_dict['val']) except ValueError: _parse_fail(name, var_type, m_dict['val'], values) # If no index is provided if not m_dict['index']: if name in results_dictionary: _reuse_fail(name, values) results_dictionary[name] = parsed_value else: if name in results_dictionary: # The name has already been used as a scalar, then it # will be in this dictionary and map to a non-dictionary. if not isinstance(results_dictionary.get(name), dict): _reuse_fail(name, values) else: results_dictionary[name] = {} index = int(m_dict['index']) # Make sure the index position hasn't already been assigned a value. if index in results_dictionary[name]: _reuse_fail('{}[{}]'.format(name, index), values) results_dictionary[name][index] = parsed_value
[ "def", "_process_scalar_value", "(", "name", ",", "parse_fn", ",", "var_type", ",", "m_dict", ",", "values", ",", "results_dictionary", ")", ":", "try", ":", "parsed_value", "=", "parse_fn", "(", "m_dict", "[", "'val'", "]", ")", "except", "ValueError", ":", "_parse_fail", "(", "name", ",", "var_type", ",", "m_dict", "[", "'val'", "]", ",", "values", ")", "# If no index is provided", "if", "not", "m_dict", "[", "'index'", "]", ":", "if", "name", "in", "results_dictionary", ":", "_reuse_fail", "(", "name", ",", "values", ")", "results_dictionary", "[", "name", "]", "=", "parsed_value", "else", ":", "if", "name", "in", "results_dictionary", ":", "# The name has already been used as a scalar, then it", "# will be in this dictionary and map to a non-dictionary.", "if", "not", "isinstance", "(", "results_dictionary", ".", "get", "(", "name", ")", ",", "dict", ")", ":", "_reuse_fail", "(", "name", ",", "values", ")", "else", ":", "results_dictionary", "[", "name", "]", "=", "{", "}", "index", "=", "int", "(", "m_dict", "[", "'index'", "]", ")", "# Make sure the index position hasn't already been assigned a value.", "if", "index", "in", "results_dictionary", "[", "name", "]", ":", "_reuse_fail", "(", "'{}[{}]'", ".", "format", "(", "name", ",", "index", ")", ",", "values", ")", "results_dictionary", "[", "name", "]", "[", "index", "]", "=", "parsed_value" ]
Update results_dictionary with a scalar value. Used to update the results_dictionary to be returned by parse_values when encountering a clause with a scalar RHS (e.g. "s=5" or "arr[0]=5".) Mutates results_dictionary. Args: name: Name of variable in assignment ("s" or "arr"). parse_fn: Function for parsing the actual value. var_type: Type of named variable. m_dict: Dictionary constructed from regex parsing. m_dict['val']: RHS value (scalar) m_dict['index']: List index value (or None) values: Full expression being parsed results_dictionary: The dictionary being updated for return by the parsing function. Raises: ValueError: If the name has already been used.
[ "Update", "results_dictionary", "with", "a", "scalar", "value", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/hparam.py#L55-L101
train
tensorflow/tensor2tensor
tensor2tensor/utils/hparam.py
_process_list_value
def _process_list_value(name, parse_fn, var_type, m_dict, values, results_dictionary): """Update results_dictionary from a list of values. Used to update results_dictionary to be returned by parse_values when encountering a clause with a list RHS (e.g. "arr=[1,2,3]".) Mutates results_dictionary. Args: name: Name of variable in assignment ("arr"). parse_fn: Function for parsing individual values. var_type: Type of named variable. m_dict: Dictionary constructed from regex parsing. m_dict['val']: RHS value (scalar) values: Full expression being parsed results_dictionary: The dictionary being updated for return by the parsing function. Raises: ValueError: If the name has an index or the values cannot be parsed. """ if m_dict['index'] is not None: raise ValueError('Assignment of a list to a list index.') elements = filter(None, re.split('[ ,]', m_dict['vals'])) # Make sure the name hasn't already been assigned a value if name in results_dictionary: raise _reuse_fail(name, values) try: results_dictionary[name] = [parse_fn(e) for e in elements] except ValueError: _parse_fail(name, var_type, m_dict['vals'], values)
python
def _process_list_value(name, parse_fn, var_type, m_dict, values, results_dictionary): """Update results_dictionary from a list of values. Used to update results_dictionary to be returned by parse_values when encountering a clause with a list RHS (e.g. "arr=[1,2,3]".) Mutates results_dictionary. Args: name: Name of variable in assignment ("arr"). parse_fn: Function for parsing individual values. var_type: Type of named variable. m_dict: Dictionary constructed from regex parsing. m_dict['val']: RHS value (scalar) values: Full expression being parsed results_dictionary: The dictionary being updated for return by the parsing function. Raises: ValueError: If the name has an index or the values cannot be parsed. """ if m_dict['index'] is not None: raise ValueError('Assignment of a list to a list index.') elements = filter(None, re.split('[ ,]', m_dict['vals'])) # Make sure the name hasn't already been assigned a value if name in results_dictionary: raise _reuse_fail(name, values) try: results_dictionary[name] = [parse_fn(e) for e in elements] except ValueError: _parse_fail(name, var_type, m_dict['vals'], values)
[ "def", "_process_list_value", "(", "name", ",", "parse_fn", ",", "var_type", ",", "m_dict", ",", "values", ",", "results_dictionary", ")", ":", "if", "m_dict", "[", "'index'", "]", "is", "not", "None", ":", "raise", "ValueError", "(", "'Assignment of a list to a list index.'", ")", "elements", "=", "filter", "(", "None", ",", "re", ".", "split", "(", "'[ ,]'", ",", "m_dict", "[", "'vals'", "]", ")", ")", "# Make sure the name hasn't already been assigned a value", "if", "name", "in", "results_dictionary", ":", "raise", "_reuse_fail", "(", "name", ",", "values", ")", "try", ":", "results_dictionary", "[", "name", "]", "=", "[", "parse_fn", "(", "e", ")", "for", "e", "in", "elements", "]", "except", "ValueError", ":", "_parse_fail", "(", "name", ",", "var_type", ",", "m_dict", "[", "'vals'", "]", ",", "values", ")" ]
Update results_dictionary from a list of values. Used to update results_dictionary to be returned by parse_values when encountering a clause with a list RHS (e.g. "arr=[1,2,3]".) Mutates results_dictionary. Args: name: Name of variable in assignment ("arr"). parse_fn: Function for parsing individual values. var_type: Type of named variable. m_dict: Dictionary constructed from regex parsing. m_dict['val']: RHS value (scalar) values: Full expression being parsed results_dictionary: The dictionary being updated for return by the parsing function. Raises: ValueError: If the name has an index or the values cannot be parsed.
[ "Update", "results_dictionary", "from", "a", "list", "of", "values", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/hparam.py#L104-L135
train
tensorflow/tensor2tensor
tensor2tensor/utils/hparam.py
_cast_to_type_if_compatible
def _cast_to_type_if_compatible(name, param_type, value): """Cast hparam to the provided type, if compatible. Args: name: Name of the hparam to be cast. param_type: The type of the hparam. value: The value to be cast, if compatible. Returns: The result of casting `value` to `param_type`. Raises: ValueError: If the type of `value` is not compatible with param_type. * If `param_type` is a string type, but `value` is not. * If `param_type` is a boolean, but `value` is not, or vice versa. * If `param_type` is an integer type, but `value` is not. * If `param_type` is a float type, but `value` is not a numeric type. """ fail_msg = ( "Could not cast hparam '%s' of type '%s' from value %r" % (name, param_type, value)) # Some callers use None, for which we can't do any casting/checking. :( if issubclass(param_type, type(None)): return value # Avoid converting a non-string type to a string. if (issubclass(param_type, (six.string_types, six.binary_type)) and not isinstance(value, (six.string_types, six.binary_type))): raise ValueError(fail_msg) # Avoid converting a number or string type to a boolean or vice versa. if issubclass(param_type, bool) != isinstance(value, bool): raise ValueError(fail_msg) # Avoid converting float to an integer (the reverse is fine). if (issubclass(param_type, numbers.Integral) and not isinstance(value, numbers.Integral)): raise ValueError(fail_msg) # Avoid converting a non-numeric type to a numeric type. if (issubclass(param_type, numbers.Number) and not isinstance(value, numbers.Number)): raise ValueError(fail_msg) return param_type(value)
python
def _cast_to_type_if_compatible(name, param_type, value): """Cast hparam to the provided type, if compatible. Args: name: Name of the hparam to be cast. param_type: The type of the hparam. value: The value to be cast, if compatible. Returns: The result of casting `value` to `param_type`. Raises: ValueError: If the type of `value` is not compatible with param_type. * If `param_type` is a string type, but `value` is not. * If `param_type` is a boolean, but `value` is not, or vice versa. * If `param_type` is an integer type, but `value` is not. * If `param_type` is a float type, but `value` is not a numeric type. """ fail_msg = ( "Could not cast hparam '%s' of type '%s' from value %r" % (name, param_type, value)) # Some callers use None, for which we can't do any casting/checking. :( if issubclass(param_type, type(None)): return value # Avoid converting a non-string type to a string. if (issubclass(param_type, (six.string_types, six.binary_type)) and not isinstance(value, (six.string_types, six.binary_type))): raise ValueError(fail_msg) # Avoid converting a number or string type to a boolean or vice versa. if issubclass(param_type, bool) != isinstance(value, bool): raise ValueError(fail_msg) # Avoid converting float to an integer (the reverse is fine). if (issubclass(param_type, numbers.Integral) and not isinstance(value, numbers.Integral)): raise ValueError(fail_msg) # Avoid converting a non-numeric type to a numeric type. if (issubclass(param_type, numbers.Number) and not isinstance(value, numbers.Number)): raise ValueError(fail_msg) return param_type(value)
[ "def", "_cast_to_type_if_compatible", "(", "name", ",", "param_type", ",", "value", ")", ":", "fail_msg", "=", "(", "\"Could not cast hparam '%s' of type '%s' from value %r\"", "%", "(", "name", ",", "param_type", ",", "value", ")", ")", "# Some callers use None, for which we can't do any casting/checking. :(", "if", "issubclass", "(", "param_type", ",", "type", "(", "None", ")", ")", ":", "return", "value", "# Avoid converting a non-string type to a string.", "if", "(", "issubclass", "(", "param_type", ",", "(", "six", ".", "string_types", ",", "six", ".", "binary_type", ")", ")", "and", "not", "isinstance", "(", "value", ",", "(", "six", ".", "string_types", ",", "six", ".", "binary_type", ")", ")", ")", ":", "raise", "ValueError", "(", "fail_msg", ")", "# Avoid converting a number or string type to a boolean or vice versa.", "if", "issubclass", "(", "param_type", ",", "bool", ")", "!=", "isinstance", "(", "value", ",", "bool", ")", ":", "raise", "ValueError", "(", "fail_msg", ")", "# Avoid converting float to an integer (the reverse is fine).", "if", "(", "issubclass", "(", "param_type", ",", "numbers", ".", "Integral", ")", "and", "not", "isinstance", "(", "value", ",", "numbers", ".", "Integral", ")", ")", ":", "raise", "ValueError", "(", "fail_msg", ")", "# Avoid converting a non-numeric type to a numeric type.", "if", "(", "issubclass", "(", "param_type", ",", "numbers", ".", "Number", ")", "and", "not", "isinstance", "(", "value", ",", "numbers", ".", "Number", ")", ")", ":", "raise", "ValueError", "(", "fail_msg", ")", "return", "param_type", "(", "value", ")" ]
Cast hparam to the provided type, if compatible. Args: name: Name of the hparam to be cast. param_type: The type of the hparam. value: The value to be cast, if compatible. Returns: The result of casting `value` to `param_type`. Raises: ValueError: If the type of `value` is not compatible with param_type. * If `param_type` is a string type, but `value` is not. * If `param_type` is a boolean, but `value` is not, or vice versa. * If `param_type` is an integer type, but `value` is not. * If `param_type` is a float type, but `value` is not a numeric type.
[ "Cast", "hparam", "to", "the", "provided", "type", "if", "compatible", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/hparam.py#L138-L183
train
tensorflow/tensor2tensor
tensor2tensor/utils/hparam.py
parse_values
def parse_values(values, type_map, ignore_unknown=False): """Parses hyperparameter values from a string into a python map. `values` is a string containing comma-separated `name=value` pairs. For each pair, the value of the hyperparameter named `name` is set to `value`. If a hyperparameter name appears multiple times in `values`, a ValueError is raised (e.g. 'a=1,a=2', 'a[1]=1,a[1]=2'). If a hyperparameter name in both an index assignment and scalar assignment, a ValueError is raised. (e.g. 'a=[1,2,3],a[0] = 1'). The hyperparameter name may contain '.' symbols, which will result in an attribute name that is only accessible through the getattr and setattr functions. (And must be first explicit added through add_hparam.) WARNING: Use of '.' in your variable names is allowed, but is not well supported and not recommended. The `value` in `name=value` must follows the syntax according to the type of the parameter: * Scalar integer: A Python-parsable integer point value. E.g.: 1, 100, -12. * Scalar float: A Python-parsable floating point value. E.g.: 1.0, -.54e89. * Boolean: Either true or false. * Scalar string: A non-empty sequence of characters, excluding comma, spaces, and square brackets. E.g.: foo, bar_1. * List: A comma separated list of scalar values of the parameter type enclosed in square brackets. E.g.: [1,2,3], [1.0,1e-12], [high,low]. When index assignment is used, the corresponding type_map key should be the list name. E.g. for "arr[1]=0" the type_map must have the key "arr" (not "arr[1]"). Args: values: String. Comma separated list of `name=value` pairs where 'value' must follow the syntax described above. type_map: A dictionary mapping hyperparameter names to types. Note every parameter name in values must be a key in type_map. The values must conform to the types indicated, where a value V is said to conform to a type T if either V has type T, or V is a list of elements of type T. Hence, for a multidimensional parameter 'x' taking float values, 'x=[0.1,0.2]' will parse successfully if type_map['x'] = float. ignore_unknown: Bool. Whether values that are missing a type in type_map should be ignored. If set to True, a ValueError will not be raised for unknown hyperparameter type. Returns: A python map mapping each name to either: * A scalar value. * A list of scalar values. * A dictionary mapping index numbers to scalar values. (e.g. "x=5,L=[1,2],arr[1]=3" results in {'x':5,'L':[1,2],'arr':{1:3}}") Raises: ValueError: If there is a problem with input. * If `values` cannot be parsed. * If a list is assigned to a list index (e.g. 'a[1] = [1,2,3]'). * If the same rvalue is assigned two different values (e.g. 'a=1,a=2', 'a[1]=1,a[1]=2', or 'a=1,a=[1]') """ results_dictionary = {} pos = 0 while pos < len(values): m = PARAM_RE.match(values, pos) if not m: raise ValueError('Malformed hyperparameter value: %s' % values[pos:]) # Check that there is a comma between parameters and move past it. pos = m.end() # Parse the values. m_dict = m.groupdict() name = m_dict['name'] if name not in type_map: if ignore_unknown: continue raise ValueError('Unknown hyperparameter type for %s' % name) type_ = type_map[name] # Set up correct parsing function (depending on whether type_ is a bool) if type_ == bool: def parse_bool(value): if value in ['true', 'True']: return True elif value in ['false', 'False']: return False else: try: return bool(int(value)) except ValueError: _parse_fail(name, type_, value, values) parse = parse_bool else: parse = type_ # If a singe value is provided if m_dict['val'] is not None: _process_scalar_value(name, parse, type_, m_dict, values, results_dictionary) # If the assigned value is a list: elif m_dict['vals'] is not None: _process_list_value(name, parse, type_, m_dict, values, results_dictionary) else: # Not assigned a list or value _parse_fail(name, type_, '', values) return results_dictionary
python
def parse_values(values, type_map, ignore_unknown=False): """Parses hyperparameter values from a string into a python map. `values` is a string containing comma-separated `name=value` pairs. For each pair, the value of the hyperparameter named `name` is set to `value`. If a hyperparameter name appears multiple times in `values`, a ValueError is raised (e.g. 'a=1,a=2', 'a[1]=1,a[1]=2'). If a hyperparameter name in both an index assignment and scalar assignment, a ValueError is raised. (e.g. 'a=[1,2,3],a[0] = 1'). The hyperparameter name may contain '.' symbols, which will result in an attribute name that is only accessible through the getattr and setattr functions. (And must be first explicit added through add_hparam.) WARNING: Use of '.' in your variable names is allowed, but is not well supported and not recommended. The `value` in `name=value` must follows the syntax according to the type of the parameter: * Scalar integer: A Python-parsable integer point value. E.g.: 1, 100, -12. * Scalar float: A Python-parsable floating point value. E.g.: 1.0, -.54e89. * Boolean: Either true or false. * Scalar string: A non-empty sequence of characters, excluding comma, spaces, and square brackets. E.g.: foo, bar_1. * List: A comma separated list of scalar values of the parameter type enclosed in square brackets. E.g.: [1,2,3], [1.0,1e-12], [high,low]. When index assignment is used, the corresponding type_map key should be the list name. E.g. for "arr[1]=0" the type_map must have the key "arr" (not "arr[1]"). Args: values: String. Comma separated list of `name=value` pairs where 'value' must follow the syntax described above. type_map: A dictionary mapping hyperparameter names to types. Note every parameter name in values must be a key in type_map. The values must conform to the types indicated, where a value V is said to conform to a type T if either V has type T, or V is a list of elements of type T. Hence, for a multidimensional parameter 'x' taking float values, 'x=[0.1,0.2]' will parse successfully if type_map['x'] = float. ignore_unknown: Bool. Whether values that are missing a type in type_map should be ignored. If set to True, a ValueError will not be raised for unknown hyperparameter type. Returns: A python map mapping each name to either: * A scalar value. * A list of scalar values. * A dictionary mapping index numbers to scalar values. (e.g. "x=5,L=[1,2],arr[1]=3" results in {'x':5,'L':[1,2],'arr':{1:3}}") Raises: ValueError: If there is a problem with input. * If `values` cannot be parsed. * If a list is assigned to a list index (e.g. 'a[1] = [1,2,3]'). * If the same rvalue is assigned two different values (e.g. 'a=1,a=2', 'a[1]=1,a[1]=2', or 'a=1,a=[1]') """ results_dictionary = {} pos = 0 while pos < len(values): m = PARAM_RE.match(values, pos) if not m: raise ValueError('Malformed hyperparameter value: %s' % values[pos:]) # Check that there is a comma between parameters and move past it. pos = m.end() # Parse the values. m_dict = m.groupdict() name = m_dict['name'] if name not in type_map: if ignore_unknown: continue raise ValueError('Unknown hyperparameter type for %s' % name) type_ = type_map[name] # Set up correct parsing function (depending on whether type_ is a bool) if type_ == bool: def parse_bool(value): if value in ['true', 'True']: return True elif value in ['false', 'False']: return False else: try: return bool(int(value)) except ValueError: _parse_fail(name, type_, value, values) parse = parse_bool else: parse = type_ # If a singe value is provided if m_dict['val'] is not None: _process_scalar_value(name, parse, type_, m_dict, values, results_dictionary) # If the assigned value is a list: elif m_dict['vals'] is not None: _process_list_value(name, parse, type_, m_dict, values, results_dictionary) else: # Not assigned a list or value _parse_fail(name, type_, '', values) return results_dictionary
[ "def", "parse_values", "(", "values", ",", "type_map", ",", "ignore_unknown", "=", "False", ")", ":", "results_dictionary", "=", "{", "}", "pos", "=", "0", "while", "pos", "<", "len", "(", "values", ")", ":", "m", "=", "PARAM_RE", ".", "match", "(", "values", ",", "pos", ")", "if", "not", "m", ":", "raise", "ValueError", "(", "'Malformed hyperparameter value: %s'", "%", "values", "[", "pos", ":", "]", ")", "# Check that there is a comma between parameters and move past it.", "pos", "=", "m", ".", "end", "(", ")", "# Parse the values.", "m_dict", "=", "m", ".", "groupdict", "(", ")", "name", "=", "m_dict", "[", "'name'", "]", "if", "name", "not", "in", "type_map", ":", "if", "ignore_unknown", ":", "continue", "raise", "ValueError", "(", "'Unknown hyperparameter type for %s'", "%", "name", ")", "type_", "=", "type_map", "[", "name", "]", "# Set up correct parsing function (depending on whether type_ is a bool)", "if", "type_", "==", "bool", ":", "def", "parse_bool", "(", "value", ")", ":", "if", "value", "in", "[", "'true'", ",", "'True'", "]", ":", "return", "True", "elif", "value", "in", "[", "'false'", ",", "'False'", "]", ":", "return", "False", "else", ":", "try", ":", "return", "bool", "(", "int", "(", "value", ")", ")", "except", "ValueError", ":", "_parse_fail", "(", "name", ",", "type_", ",", "value", ",", "values", ")", "parse", "=", "parse_bool", "else", ":", "parse", "=", "type_", "# If a singe value is provided", "if", "m_dict", "[", "'val'", "]", "is", "not", "None", ":", "_process_scalar_value", "(", "name", ",", "parse", ",", "type_", ",", "m_dict", ",", "values", ",", "results_dictionary", ")", "# If the assigned value is a list:", "elif", "m_dict", "[", "'vals'", "]", "is", "not", "None", ":", "_process_list_value", "(", "name", ",", "parse", ",", "type_", ",", "m_dict", ",", "values", ",", "results_dictionary", ")", "else", ":", "# Not assigned a list or value", "_parse_fail", "(", "name", ",", "type_", ",", "''", ",", "values", ")", "return", "results_dictionary" ]
Parses hyperparameter values from a string into a python map. `values` is a string containing comma-separated `name=value` pairs. For each pair, the value of the hyperparameter named `name` is set to `value`. If a hyperparameter name appears multiple times in `values`, a ValueError is raised (e.g. 'a=1,a=2', 'a[1]=1,a[1]=2'). If a hyperparameter name in both an index assignment and scalar assignment, a ValueError is raised. (e.g. 'a=[1,2,3],a[0] = 1'). The hyperparameter name may contain '.' symbols, which will result in an attribute name that is only accessible through the getattr and setattr functions. (And must be first explicit added through add_hparam.) WARNING: Use of '.' in your variable names is allowed, but is not well supported and not recommended. The `value` in `name=value` must follows the syntax according to the type of the parameter: * Scalar integer: A Python-parsable integer point value. E.g.: 1, 100, -12. * Scalar float: A Python-parsable floating point value. E.g.: 1.0, -.54e89. * Boolean: Either true or false. * Scalar string: A non-empty sequence of characters, excluding comma, spaces, and square brackets. E.g.: foo, bar_1. * List: A comma separated list of scalar values of the parameter type enclosed in square brackets. E.g.: [1,2,3], [1.0,1e-12], [high,low]. When index assignment is used, the corresponding type_map key should be the list name. E.g. for "arr[1]=0" the type_map must have the key "arr" (not "arr[1]"). Args: values: String. Comma separated list of `name=value` pairs where 'value' must follow the syntax described above. type_map: A dictionary mapping hyperparameter names to types. Note every parameter name in values must be a key in type_map. The values must conform to the types indicated, where a value V is said to conform to a type T if either V has type T, or V is a list of elements of type T. Hence, for a multidimensional parameter 'x' taking float values, 'x=[0.1,0.2]' will parse successfully if type_map['x'] = float. ignore_unknown: Bool. Whether values that are missing a type in type_map should be ignored. If set to True, a ValueError will not be raised for unknown hyperparameter type. Returns: A python map mapping each name to either: * A scalar value. * A list of scalar values. * A dictionary mapping index numbers to scalar values. (e.g. "x=5,L=[1,2],arr[1]=3" results in {'x':5,'L':[1,2],'arr':{1:3}}") Raises: ValueError: If there is a problem with input. * If `values` cannot be parsed. * If a list is assigned to a list index (e.g. 'a[1] = [1,2,3]'). * If the same rvalue is assigned two different values (e.g. 'a=1,a=2', 'a[1]=1,a[1]=2', or 'a=1,a=[1]')
[ "Parses", "hyperparameter", "values", "from", "a", "string", "into", "a", "python", "map", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/hparam.py#L186-L298
train
tensorflow/tensor2tensor
tensor2tensor/utils/hparam.py
HParams.add_hparam
def add_hparam(self, name, value): """Adds {name, value} pair to hyperparameters. Args: name: Name of the hyperparameter. value: Value of the hyperparameter. Can be one of the following types: int, float, string, int list, float list, or string list. Raises: ValueError: if one of the arguments is invalid. """ # Keys in kwargs are unique, but 'name' could the name of a pre-existing # attribute of this object. In that case we refuse to use it as a # hyperparameter name. if getattr(self, name, None) is not None: raise ValueError('Hyperparameter name is reserved: %s' % name) if isinstance(value, (list, tuple)): if not value: raise ValueError( 'Multi-valued hyperparameters cannot be empty: %s' % name) self._hparam_types[name] = (type(value[0]), True) else: self._hparam_types[name] = (type(value), False) setattr(self, name, value)
python
def add_hparam(self, name, value): """Adds {name, value} pair to hyperparameters. Args: name: Name of the hyperparameter. value: Value of the hyperparameter. Can be one of the following types: int, float, string, int list, float list, or string list. Raises: ValueError: if one of the arguments is invalid. """ # Keys in kwargs are unique, but 'name' could the name of a pre-existing # attribute of this object. In that case we refuse to use it as a # hyperparameter name. if getattr(self, name, None) is not None: raise ValueError('Hyperparameter name is reserved: %s' % name) if isinstance(value, (list, tuple)): if not value: raise ValueError( 'Multi-valued hyperparameters cannot be empty: %s' % name) self._hparam_types[name] = (type(value[0]), True) else: self._hparam_types[name] = (type(value), False) setattr(self, name, value)
[ "def", "add_hparam", "(", "self", ",", "name", ",", "value", ")", ":", "# Keys in kwargs are unique, but 'name' could the name of a pre-existing", "# attribute of this object. In that case we refuse to use it as a", "# hyperparameter name.", "if", "getattr", "(", "self", ",", "name", ",", "None", ")", "is", "not", "None", ":", "raise", "ValueError", "(", "'Hyperparameter name is reserved: %s'", "%", "name", ")", "if", "isinstance", "(", "value", ",", "(", "list", ",", "tuple", ")", ")", ":", "if", "not", "value", ":", "raise", "ValueError", "(", "'Multi-valued hyperparameters cannot be empty: %s'", "%", "name", ")", "self", ".", "_hparam_types", "[", "name", "]", "=", "(", "type", "(", "value", "[", "0", "]", ")", ",", "True", ")", "else", ":", "self", ".", "_hparam_types", "[", "name", "]", "=", "(", "type", "(", "value", ")", ",", "False", ")", "setattr", "(", "self", ",", "name", ",", "value", ")" ]
Adds {name, value} pair to hyperparameters. Args: name: Name of the hyperparameter. value: Value of the hyperparameter. Can be one of the following types: int, float, string, int list, float list, or string list. Raises: ValueError: if one of the arguments is invalid.
[ "Adds", "{", "name", "value", "}", "pair", "to", "hyperparameters", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/hparam.py#L418-L441
train
tensorflow/tensor2tensor
tensor2tensor/utils/hparam.py
HParams.set_hparam
def set_hparam(self, name, value): """Set the value of an existing hyperparameter. This function verifies that the type of the value matches the type of the existing hyperparameter. Args: name: Name of the hyperparameter. value: New value of the hyperparameter. Raises: KeyError: If the hyperparameter doesn't exist. ValueError: If there is a type mismatch. """ param_type, is_list = self._hparam_types[name] if isinstance(value, list): if not is_list: raise ValueError( 'Must not pass a list for single-valued parameter: %s' % name) setattr(self, name, [ _cast_to_type_if_compatible(name, param_type, v) for v in value]) else: if is_list: raise ValueError( 'Must pass a list for multi-valued parameter: %s.' % name) setattr(self, name, _cast_to_type_if_compatible(name, param_type, value))
python
def set_hparam(self, name, value): """Set the value of an existing hyperparameter. This function verifies that the type of the value matches the type of the existing hyperparameter. Args: name: Name of the hyperparameter. value: New value of the hyperparameter. Raises: KeyError: If the hyperparameter doesn't exist. ValueError: If there is a type mismatch. """ param_type, is_list = self._hparam_types[name] if isinstance(value, list): if not is_list: raise ValueError( 'Must not pass a list for single-valued parameter: %s' % name) setattr(self, name, [ _cast_to_type_if_compatible(name, param_type, v) for v in value]) else: if is_list: raise ValueError( 'Must pass a list for multi-valued parameter: %s.' % name) setattr(self, name, _cast_to_type_if_compatible(name, param_type, value))
[ "def", "set_hparam", "(", "self", ",", "name", ",", "value", ")", ":", "param_type", ",", "is_list", "=", "self", ".", "_hparam_types", "[", "name", "]", "if", "isinstance", "(", "value", ",", "list", ")", ":", "if", "not", "is_list", ":", "raise", "ValueError", "(", "'Must not pass a list for single-valued parameter: %s'", "%", "name", ")", "setattr", "(", "self", ",", "name", ",", "[", "_cast_to_type_if_compatible", "(", "name", ",", "param_type", ",", "v", ")", "for", "v", "in", "value", "]", ")", "else", ":", "if", "is_list", ":", "raise", "ValueError", "(", "'Must pass a list for multi-valued parameter: %s.'", "%", "name", ")", "setattr", "(", "self", ",", "name", ",", "_cast_to_type_if_compatible", "(", "name", ",", "param_type", ",", "value", ")", ")" ]
Set the value of an existing hyperparameter. This function verifies that the type of the value matches the type of the existing hyperparameter. Args: name: Name of the hyperparameter. value: New value of the hyperparameter. Raises: KeyError: If the hyperparameter doesn't exist. ValueError: If there is a type mismatch.
[ "Set", "the", "value", "of", "an", "existing", "hyperparameter", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/hparam.py#L443-L468
train
tensorflow/tensor2tensor
tensor2tensor/utils/hparam.py
HParams.del_hparam
def del_hparam(self, name): """Removes the hyperparameter with key 'name'. Does nothing if it isn't present. Args: name: Name of the hyperparameter. """ if hasattr(self, name): delattr(self, name) del self._hparam_types[name]
python
def del_hparam(self, name): """Removes the hyperparameter with key 'name'. Does nothing if it isn't present. Args: name: Name of the hyperparameter. """ if hasattr(self, name): delattr(self, name) del self._hparam_types[name]
[ "def", "del_hparam", "(", "self", ",", "name", ")", ":", "if", "hasattr", "(", "self", ",", "name", ")", ":", "delattr", "(", "self", ",", "name", ")", "del", "self", ".", "_hparam_types", "[", "name", "]" ]
Removes the hyperparameter with key 'name'. Does nothing if it isn't present. Args: name: Name of the hyperparameter.
[ "Removes", "the", "hyperparameter", "with", "key", "name", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/hparam.py#L470-L480
train
tensorflow/tensor2tensor
tensor2tensor/utils/hparam.py
HParams.parse
def parse(self, values): """Override existing hyperparameter values, parsing new values from a string. See parse_values for more detail on the allowed format for values. Args: values: String. Comma separated list of `name=value` pairs where 'value' must follow the syntax described above. Returns: The `HParams` instance. Raises: ValueError: If `values` cannot be parsed or a hyperparameter in `values` doesn't exist. """ type_map = {} for name, t in self._hparam_types.items(): param_type, _ = t type_map[name] = param_type values_map = parse_values(values, type_map) return self.override_from_dict(values_map)
python
def parse(self, values): """Override existing hyperparameter values, parsing new values from a string. See parse_values for more detail on the allowed format for values. Args: values: String. Comma separated list of `name=value` pairs where 'value' must follow the syntax described above. Returns: The `HParams` instance. Raises: ValueError: If `values` cannot be parsed or a hyperparameter in `values` doesn't exist. """ type_map = {} for name, t in self._hparam_types.items(): param_type, _ = t type_map[name] = param_type values_map = parse_values(values, type_map) return self.override_from_dict(values_map)
[ "def", "parse", "(", "self", ",", "values", ")", ":", "type_map", "=", "{", "}", "for", "name", ",", "t", "in", "self", ".", "_hparam_types", ".", "items", "(", ")", ":", "param_type", ",", "_", "=", "t", "type_map", "[", "name", "]", "=", "param_type", "values_map", "=", "parse_values", "(", "values", ",", "type_map", ")", "return", "self", ".", "override_from_dict", "(", "values_map", ")" ]
Override existing hyperparameter values, parsing new values from a string. See parse_values for more detail on the allowed format for values. Args: values: String. Comma separated list of `name=value` pairs where 'value' must follow the syntax described above. Returns: The `HParams` instance. Raises: ValueError: If `values` cannot be parsed or a hyperparameter in `values` doesn't exist.
[ "Override", "existing", "hyperparameter", "values", "parsing", "new", "values", "from", "a", "string", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/hparam.py#L482-L504
train
tensorflow/tensor2tensor
tensor2tensor/utils/hparam.py
HParams.override_from_dict
def override_from_dict(self, values_dict): """Override existing hyperparameter values, parsing new values from a dictionary. Args: values_dict: Dictionary of name:value pairs. Returns: The `HParams` instance. Raises: KeyError: If a hyperparameter in `values_dict` doesn't exist. ValueError: If `values_dict` cannot be parsed. """ for name, value in values_dict.items(): self.set_hparam(name, value) return self
python
def override_from_dict(self, values_dict): """Override existing hyperparameter values, parsing new values from a dictionary. Args: values_dict: Dictionary of name:value pairs. Returns: The `HParams` instance. Raises: KeyError: If a hyperparameter in `values_dict` doesn't exist. ValueError: If `values_dict` cannot be parsed. """ for name, value in values_dict.items(): self.set_hparam(name, value) return self
[ "def", "override_from_dict", "(", "self", ",", "values_dict", ")", ":", "for", "name", ",", "value", "in", "values_dict", ".", "items", "(", ")", ":", "self", ".", "set_hparam", "(", "name", ",", "value", ")", "return", "self" ]
Override existing hyperparameter values, parsing new values from a dictionary. Args: values_dict: Dictionary of name:value pairs. Returns: The `HParams` instance. Raises: KeyError: If a hyperparameter in `values_dict` doesn't exist. ValueError: If `values_dict` cannot be parsed.
[ "Override", "existing", "hyperparameter", "values", "parsing", "new", "values", "from", "a", "dictionary", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/hparam.py#L506-L521
train
tensorflow/tensor2tensor
tensor2tensor/utils/hparam.py
HParams.to_json
def to_json(self, indent=None, separators=None, sort_keys=False): """Serializes the hyperparameters into JSON. Args: indent: If a non-negative integer, JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0, or negative, will only insert newlines. `None` (the default) selects the most compact representation. separators: Optional `(item_separator, key_separator)` tuple. Default is `(', ', ': ')`. sort_keys: If `True`, the output dictionaries will be sorted by key. Returns: A JSON string. """ def remove_callables(x): """Omit callable elements from input with arbitrary nesting.""" if isinstance(x, dict): return {k: remove_callables(v) for k, v in six.iteritems(x) if not callable(v)} elif isinstance(x, list): return [remove_callables(i) for i in x if not callable(i)] return x return json.dumps( remove_callables(self.values()), indent=indent, separators=separators, sort_keys=sort_keys)
python
def to_json(self, indent=None, separators=None, sort_keys=False): """Serializes the hyperparameters into JSON. Args: indent: If a non-negative integer, JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0, or negative, will only insert newlines. `None` (the default) selects the most compact representation. separators: Optional `(item_separator, key_separator)` tuple. Default is `(', ', ': ')`. sort_keys: If `True`, the output dictionaries will be sorted by key. Returns: A JSON string. """ def remove_callables(x): """Omit callable elements from input with arbitrary nesting.""" if isinstance(x, dict): return {k: remove_callables(v) for k, v in six.iteritems(x) if not callable(v)} elif isinstance(x, list): return [remove_callables(i) for i in x if not callable(i)] return x return json.dumps( remove_callables(self.values()), indent=indent, separators=separators, sort_keys=sort_keys)
[ "def", "to_json", "(", "self", ",", "indent", "=", "None", ",", "separators", "=", "None", ",", "sort_keys", "=", "False", ")", ":", "def", "remove_callables", "(", "x", ")", ":", "\"\"\"Omit callable elements from input with arbitrary nesting.\"\"\"", "if", "isinstance", "(", "x", ",", "dict", ")", ":", "return", "{", "k", ":", "remove_callables", "(", "v", ")", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "x", ")", "if", "not", "callable", "(", "v", ")", "}", "elif", "isinstance", "(", "x", ",", "list", ")", ":", "return", "[", "remove_callables", "(", "i", ")", "for", "i", "in", "x", "if", "not", "callable", "(", "i", ")", "]", "return", "x", "return", "json", ".", "dumps", "(", "remove_callables", "(", "self", ".", "values", "(", ")", ")", ",", "indent", "=", "indent", ",", "separators", "=", "separators", ",", "sort_keys", "=", "sort_keys", ")" ]
Serializes the hyperparameters into JSON. Args: indent: If a non-negative integer, JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0, or negative, will only insert newlines. `None` (the default) selects the most compact representation. separators: Optional `(item_separator, key_separator)` tuple. Default is `(', ', ': ')`. sort_keys: If `True`, the output dictionaries will be sorted by key. Returns: A JSON string.
[ "Serializes", "the", "hyperparameters", "into", "JSON", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/hparam.py#L529-L556
train
tensorflow/tensor2tensor
tensor2tensor/utils/hparam.py
HParams.parse_json
def parse_json(self, values_json): """Override existing hyperparameter values, parsing new values from a json object. Args: values_json: String containing a json object of name:value pairs. Returns: The `HParams` instance. Raises: KeyError: If a hyperparameter in `values_json` doesn't exist. ValueError: If `values_json` cannot be parsed. """ values_map = json.loads(values_json) return self.override_from_dict(values_map)
python
def parse_json(self, values_json): """Override existing hyperparameter values, parsing new values from a json object. Args: values_json: String containing a json object of name:value pairs. Returns: The `HParams` instance. Raises: KeyError: If a hyperparameter in `values_json` doesn't exist. ValueError: If `values_json` cannot be parsed. """ values_map = json.loads(values_json) return self.override_from_dict(values_map)
[ "def", "parse_json", "(", "self", ",", "values_json", ")", ":", "values_map", "=", "json", ".", "loads", "(", "values_json", ")", "return", "self", ".", "override_from_dict", "(", "values_map", ")" ]
Override existing hyperparameter values, parsing new values from a json object. Args: values_json: String containing a json object of name:value pairs. Returns: The `HParams` instance. Raises: KeyError: If a hyperparameter in `values_json` doesn't exist. ValueError: If `values_json` cannot be parsed.
[ "Override", "existing", "hyperparameter", "values", "parsing", "new", "values", "from", "a", "json", "object", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/hparam.py#L558-L572
train
tensorflow/tensor2tensor
tensor2tensor/utils/hparam.py
HParams.values
def values(self): """Return the hyperparameter values as a Python dictionary. Returns: A dictionary with hyperparameter names as keys. The values are the hyperparameter values. """ return {n: getattr(self, n) for n in self._hparam_types.keys()}
python
def values(self): """Return the hyperparameter values as a Python dictionary. Returns: A dictionary with hyperparameter names as keys. The values are the hyperparameter values. """ return {n: getattr(self, n) for n in self._hparam_types.keys()}
[ "def", "values", "(", "self", ")", ":", "return", "{", "n", ":", "getattr", "(", "self", ",", "n", ")", "for", "n", "in", "self", ".", "_hparam_types", ".", "keys", "(", ")", "}" ]
Return the hyperparameter values as a Python dictionary. Returns: A dictionary with hyperparameter names as keys. The values are the hyperparameter values.
[ "Return", "the", "hyperparameter", "values", "as", "a", "Python", "dictionary", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/hparam.py#L574-L581
train
tensorflow/tensor2tensor
tensor2tensor/utils/hparam.py
HParams.get
def get(self, key, default=None): """Returns the value of `key` if it exists, else `default`.""" if key in self._hparam_types: # Ensure that default is compatible with the parameter type. if default is not None: param_type, is_param_list = self._hparam_types[key] type_str = 'list<%s>' % param_type if is_param_list else str(param_type) fail_msg = ("Hparam '%s' of type '%s' is incompatible with " 'default=%s' % (key, type_str, default)) is_default_list = isinstance(default, list) if is_param_list != is_default_list: raise ValueError(fail_msg) try: if is_default_list: for value in default: _cast_to_type_if_compatible(key, param_type, value) else: _cast_to_type_if_compatible(key, param_type, default) except ValueError as e: raise ValueError('%s. %s' % (fail_msg, e)) return getattr(self, key) return default
python
def get(self, key, default=None): """Returns the value of `key` if it exists, else `default`.""" if key in self._hparam_types: # Ensure that default is compatible with the parameter type. if default is not None: param_type, is_param_list = self._hparam_types[key] type_str = 'list<%s>' % param_type if is_param_list else str(param_type) fail_msg = ("Hparam '%s' of type '%s' is incompatible with " 'default=%s' % (key, type_str, default)) is_default_list = isinstance(default, list) if is_param_list != is_default_list: raise ValueError(fail_msg) try: if is_default_list: for value in default: _cast_to_type_if_compatible(key, param_type, value) else: _cast_to_type_if_compatible(key, param_type, default) except ValueError as e: raise ValueError('%s. %s' % (fail_msg, e)) return getattr(self, key) return default
[ "def", "get", "(", "self", ",", "key", ",", "default", "=", "None", ")", ":", "if", "key", "in", "self", ".", "_hparam_types", ":", "# Ensure that default is compatible with the parameter type.", "if", "default", "is", "not", "None", ":", "param_type", ",", "is_param_list", "=", "self", ".", "_hparam_types", "[", "key", "]", "type_str", "=", "'list<%s>'", "%", "param_type", "if", "is_param_list", "else", "str", "(", "param_type", ")", "fail_msg", "=", "(", "\"Hparam '%s' of type '%s' is incompatible with \"", "'default=%s'", "%", "(", "key", ",", "type_str", ",", "default", ")", ")", "is_default_list", "=", "isinstance", "(", "default", ",", "list", ")", "if", "is_param_list", "!=", "is_default_list", ":", "raise", "ValueError", "(", "fail_msg", ")", "try", ":", "if", "is_default_list", ":", "for", "value", "in", "default", ":", "_cast_to_type_if_compatible", "(", "key", ",", "param_type", ",", "value", ")", "else", ":", "_cast_to_type_if_compatible", "(", "key", ",", "param_type", ",", "default", ")", "except", "ValueError", "as", "e", ":", "raise", "ValueError", "(", "'%s. %s'", "%", "(", "fail_msg", ",", "e", ")", ")", "return", "getattr", "(", "self", ",", "key", ")", "return", "default" ]
Returns the value of `key` if it exists, else `default`.
[ "Returns", "the", "value", "of", "key", "if", "it", "exists", "else", "default", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/hparam.py#L583-L608
train
tensorflow/tensor2tensor
tensor2tensor/utils/hparam.py
HParams._get_kind_name
def _get_kind_name(param_type, is_list): """Returns the field name given parameter type and is_list. Args: param_type: Data type of the hparam. is_list: Whether this is a list. Returns: A string representation of the field name. Raises: ValueError: If parameter type is not recognized. """ if issubclass(param_type, bool): # This check must happen before issubclass(param_type, six.integer_types), # since Python considers bool to be a subclass of int. typename = 'bool' elif issubclass(param_type, six.integer_types): # Setting 'int' and 'long' types to be 'int64' to ensure the type is # compatible with both Python2 and Python3. typename = 'int64' elif issubclass(param_type, (six.string_types, six.binary_type)): # Setting 'string' and 'bytes' types to be 'bytes' to ensure the type is # compatible with both Python2 and Python3. typename = 'bytes' elif issubclass(param_type, float): typename = 'float' else: raise ValueError('Unsupported parameter type: %s' % str(param_type)) suffix = 'list' if is_list else 'value' return '_'.join([typename, suffix])
python
def _get_kind_name(param_type, is_list): """Returns the field name given parameter type and is_list. Args: param_type: Data type of the hparam. is_list: Whether this is a list. Returns: A string representation of the field name. Raises: ValueError: If parameter type is not recognized. """ if issubclass(param_type, bool): # This check must happen before issubclass(param_type, six.integer_types), # since Python considers bool to be a subclass of int. typename = 'bool' elif issubclass(param_type, six.integer_types): # Setting 'int' and 'long' types to be 'int64' to ensure the type is # compatible with both Python2 and Python3. typename = 'int64' elif issubclass(param_type, (six.string_types, six.binary_type)): # Setting 'string' and 'bytes' types to be 'bytes' to ensure the type is # compatible with both Python2 and Python3. typename = 'bytes' elif issubclass(param_type, float): typename = 'float' else: raise ValueError('Unsupported parameter type: %s' % str(param_type)) suffix = 'list' if is_list else 'value' return '_'.join([typename, suffix])
[ "def", "_get_kind_name", "(", "param_type", ",", "is_list", ")", ":", "if", "issubclass", "(", "param_type", ",", "bool", ")", ":", "# This check must happen before issubclass(param_type, six.integer_types),", "# since Python considers bool to be a subclass of int.", "typename", "=", "'bool'", "elif", "issubclass", "(", "param_type", ",", "six", ".", "integer_types", ")", ":", "# Setting 'int' and 'long' types to be 'int64' to ensure the type is", "# compatible with both Python2 and Python3.", "typename", "=", "'int64'", "elif", "issubclass", "(", "param_type", ",", "(", "six", ".", "string_types", ",", "six", ".", "binary_type", ")", ")", ":", "# Setting 'string' and 'bytes' types to be 'bytes' to ensure the type is", "# compatible with both Python2 and Python3.", "typename", "=", "'bytes'", "elif", "issubclass", "(", "param_type", ",", "float", ")", ":", "typename", "=", "'float'", "else", ":", "raise", "ValueError", "(", "'Unsupported parameter type: %s'", "%", "str", "(", "param_type", ")", ")", "suffix", "=", "'list'", "if", "is_list", "else", "'value'", "return", "'_'", ".", "join", "(", "[", "typename", ",", "suffix", "]", ")" ]
Returns the field name given parameter type and is_list. Args: param_type: Data type of the hparam. is_list: Whether this is a list. Returns: A string representation of the field name. Raises: ValueError: If parameter type is not recognized.
[ "Returns", "the", "field", "name", "given", "parameter", "type", "and", "is_list", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/hparam.py#L620-L651
train
tensorflow/tensor2tensor
tensor2tensor/insights/transformer_model.py
TransformerModel.process
def process(self, query): """Returns the visualizations for query. Args: query: The query to process. Returns: A dictionary of results with processing and graph visualizations. """ tf.logging.info("Processing new query [%s]" %query) # Create the new TFDBG hook directory. hook_dir = "/tmp/t2t_server_dump/request_%d" %int(time.time()) os.makedirs(hook_dir) hooks = [tfdbg.DumpingDebugHook(hook_dir, watch_fn=topk_watch_fn)] # TODO(kstevens): This is extremely hacky and slow for responding to # queries. Figure out a reasonable way to pre-load the model weights before # forking and run queries through the estimator quickly. def server_input_fn(): """Generator that returns just the current query.""" for _ in range(1): input_ids = self.source_vocab.encode(query) input_ids.append(text_encoder.EOS_ID) x = [1, 100, len(input_ids)] + input_ids x += [0] * (self.const_array_size - len(x)) d = { "inputs": np.array(x).astype(np.int32), } yield d def input_fn(): """Generator that returns just the current query.""" gen_fn = decoding.make_input_fn_from_generator(server_input_fn()) example = gen_fn() # TODO(kstevens): Make this method public # pylint: disable=protected-access return decoding._interactive_input_tensor_to_features_dict( example, self.hparams) # Make the prediction for the current query. result_iter = self.estimator.predict(input_fn, hooks=hooks) result = None for result in result_iter: break # Extract the beam search information by reading the dumped TFDBG event # tensors. We first read and record the per step beam sequences then record # the beam scores. Afterwards we align the two sets of values to create the # full graph vertices and edges. decoding_graph = graph.Graph() run_dirs = sorted(glob.glob(os.path.join(hook_dir, "run_*"))) for run_dir in run_dirs: # Record the different completed and active beam sequence ids. alive_sequences = deque() finished_sequences = deque() # Make the root vertex since it always needs to exist. decoding_graph.get_vertex(sequence_key([0])) # Create the initial vertices and edges for the active and finished # sequences. We uniquely define each vertex using it's full sequence path # as a string to ensure there's no collisions when the same step has two # instances of an output id. dump_dir = tfdbg.DebugDumpDir(run_dir, validate=False) seq_datums = dump_dir.find(predicate=seq_filter) for seq_datum in seq_datums: sequences = np.array(seq_datum.get_tensor()).astype(int)[0] if "alive" in seq_datum.node_name: alive_sequences.append(sequences) if "finished" in seq_datum.node_name: finished_sequences.append(sequences) for sequence in sequences: pieces = self.targets_vocab.decode_list(sequence) index = sequence[-1] if index == 0: continue parent = decoding_graph.get_vertex(sequence_key(sequence[:-1])) current = decoding_graph.get_vertex(sequence_key(sequence)) edge = decoding_graph.add_edge(parent, current) edge.data["label"] = pieces[-1] edge.data["label_id"] = index # Coerce the type to be a python bool. Numpy bools can't be easily # converted to JSON. edge.data["completed"] = bool(index == 1) # Examine the score results and store the scores with the associated edges # in the graph. We fetch the vertices (and relevant edges) by looking # into the saved beam sequences stored above. score_datums = dump_dir.find(predicate=scores_filter) for score_datum in score_datums: if "alive" in score_datum.node_name: sequences = alive_sequences.popleft() if "finished" in score_datum.node_name: sequences = finished_sequences.popleft() scores = np.array(score_datum.get_tensor()).astype(float)[0] for i, score in enumerate(scores): sequence = sequences[i] if sequence[-1] == 0: continue vertex = decoding_graph.get_vertex(sequence_key(sequence)) edge = decoding_graph.edges[vertex.in_edges[0]] edge.data["score"] = score edge.data["log_probability"] = score edge.data["total_log_probability"] = score # Delete the hook dir to save disk space shutil.rmtree(hook_dir) # Create the graph visualization data structure. graph_vis = { "visualization_name": "graph", "title": "Graph", "name": "graph", "search_graph": decoding_graph.to_dict(), } # Create the processing visualization data structure. # TODO(kstevens): Make this method public # pylint: disable=protected-access output_ids = decoding._save_until_eos(result["outputs"].flatten(), False) output_pieces = self.targets_vocab.decode_list(output_ids) output_token = [{"text": piece} for piece in output_pieces] output = self.targets_vocab.decode(output_ids) source_steps = [{ "step_name": "Initial", "segment": [{ "text": query }], }] target_steps = [{ "step_name": "Initial", "segment": output_token, }, { "step_name": "Final", "segment": [{ "text": output }], }] processing_vis = { "visualization_name": "processing", "title": "Processing", "name": "processing", "query_processing": { "source_processing": source_steps, "target_processing": target_steps, }, } return { "result": [processing_vis, graph_vis], }
python
def process(self, query): """Returns the visualizations for query. Args: query: The query to process. Returns: A dictionary of results with processing and graph visualizations. """ tf.logging.info("Processing new query [%s]" %query) # Create the new TFDBG hook directory. hook_dir = "/tmp/t2t_server_dump/request_%d" %int(time.time()) os.makedirs(hook_dir) hooks = [tfdbg.DumpingDebugHook(hook_dir, watch_fn=topk_watch_fn)] # TODO(kstevens): This is extremely hacky and slow for responding to # queries. Figure out a reasonable way to pre-load the model weights before # forking and run queries through the estimator quickly. def server_input_fn(): """Generator that returns just the current query.""" for _ in range(1): input_ids = self.source_vocab.encode(query) input_ids.append(text_encoder.EOS_ID) x = [1, 100, len(input_ids)] + input_ids x += [0] * (self.const_array_size - len(x)) d = { "inputs": np.array(x).astype(np.int32), } yield d def input_fn(): """Generator that returns just the current query.""" gen_fn = decoding.make_input_fn_from_generator(server_input_fn()) example = gen_fn() # TODO(kstevens): Make this method public # pylint: disable=protected-access return decoding._interactive_input_tensor_to_features_dict( example, self.hparams) # Make the prediction for the current query. result_iter = self.estimator.predict(input_fn, hooks=hooks) result = None for result in result_iter: break # Extract the beam search information by reading the dumped TFDBG event # tensors. We first read and record the per step beam sequences then record # the beam scores. Afterwards we align the two sets of values to create the # full graph vertices and edges. decoding_graph = graph.Graph() run_dirs = sorted(glob.glob(os.path.join(hook_dir, "run_*"))) for run_dir in run_dirs: # Record the different completed and active beam sequence ids. alive_sequences = deque() finished_sequences = deque() # Make the root vertex since it always needs to exist. decoding_graph.get_vertex(sequence_key([0])) # Create the initial vertices and edges for the active and finished # sequences. We uniquely define each vertex using it's full sequence path # as a string to ensure there's no collisions when the same step has two # instances of an output id. dump_dir = tfdbg.DebugDumpDir(run_dir, validate=False) seq_datums = dump_dir.find(predicate=seq_filter) for seq_datum in seq_datums: sequences = np.array(seq_datum.get_tensor()).astype(int)[0] if "alive" in seq_datum.node_name: alive_sequences.append(sequences) if "finished" in seq_datum.node_name: finished_sequences.append(sequences) for sequence in sequences: pieces = self.targets_vocab.decode_list(sequence) index = sequence[-1] if index == 0: continue parent = decoding_graph.get_vertex(sequence_key(sequence[:-1])) current = decoding_graph.get_vertex(sequence_key(sequence)) edge = decoding_graph.add_edge(parent, current) edge.data["label"] = pieces[-1] edge.data["label_id"] = index # Coerce the type to be a python bool. Numpy bools can't be easily # converted to JSON. edge.data["completed"] = bool(index == 1) # Examine the score results and store the scores with the associated edges # in the graph. We fetch the vertices (and relevant edges) by looking # into the saved beam sequences stored above. score_datums = dump_dir.find(predicate=scores_filter) for score_datum in score_datums: if "alive" in score_datum.node_name: sequences = alive_sequences.popleft() if "finished" in score_datum.node_name: sequences = finished_sequences.popleft() scores = np.array(score_datum.get_tensor()).astype(float)[0] for i, score in enumerate(scores): sequence = sequences[i] if sequence[-1] == 0: continue vertex = decoding_graph.get_vertex(sequence_key(sequence)) edge = decoding_graph.edges[vertex.in_edges[0]] edge.data["score"] = score edge.data["log_probability"] = score edge.data["total_log_probability"] = score # Delete the hook dir to save disk space shutil.rmtree(hook_dir) # Create the graph visualization data structure. graph_vis = { "visualization_name": "graph", "title": "Graph", "name": "graph", "search_graph": decoding_graph.to_dict(), } # Create the processing visualization data structure. # TODO(kstevens): Make this method public # pylint: disable=protected-access output_ids = decoding._save_until_eos(result["outputs"].flatten(), False) output_pieces = self.targets_vocab.decode_list(output_ids) output_token = [{"text": piece} for piece in output_pieces] output = self.targets_vocab.decode(output_ids) source_steps = [{ "step_name": "Initial", "segment": [{ "text": query }], }] target_steps = [{ "step_name": "Initial", "segment": output_token, }, { "step_name": "Final", "segment": [{ "text": output }], }] processing_vis = { "visualization_name": "processing", "title": "Processing", "name": "processing", "query_processing": { "source_processing": source_steps, "target_processing": target_steps, }, } return { "result": [processing_vis, graph_vis], }
[ "def", "process", "(", "self", ",", "query", ")", ":", "tf", ".", "logging", ".", "info", "(", "\"Processing new query [%s]\"", "%", "query", ")", "# Create the new TFDBG hook directory.", "hook_dir", "=", "\"/tmp/t2t_server_dump/request_%d\"", "%", "int", "(", "time", ".", "time", "(", ")", ")", "os", ".", "makedirs", "(", "hook_dir", ")", "hooks", "=", "[", "tfdbg", ".", "DumpingDebugHook", "(", "hook_dir", ",", "watch_fn", "=", "topk_watch_fn", ")", "]", "# TODO(kstevens): This is extremely hacky and slow for responding to", "# queries. Figure out a reasonable way to pre-load the model weights before", "# forking and run queries through the estimator quickly.", "def", "server_input_fn", "(", ")", ":", "\"\"\"Generator that returns just the current query.\"\"\"", "for", "_", "in", "range", "(", "1", ")", ":", "input_ids", "=", "self", ".", "source_vocab", ".", "encode", "(", "query", ")", "input_ids", ".", "append", "(", "text_encoder", ".", "EOS_ID", ")", "x", "=", "[", "1", ",", "100", ",", "len", "(", "input_ids", ")", "]", "+", "input_ids", "x", "+=", "[", "0", "]", "*", "(", "self", ".", "const_array_size", "-", "len", "(", "x", ")", ")", "d", "=", "{", "\"inputs\"", ":", "np", ".", "array", "(", "x", ")", ".", "astype", "(", "np", ".", "int32", ")", ",", "}", "yield", "d", "def", "input_fn", "(", ")", ":", "\"\"\"Generator that returns just the current query.\"\"\"", "gen_fn", "=", "decoding", ".", "make_input_fn_from_generator", "(", "server_input_fn", "(", ")", ")", "example", "=", "gen_fn", "(", ")", "# TODO(kstevens): Make this method public", "# pylint: disable=protected-access", "return", "decoding", ".", "_interactive_input_tensor_to_features_dict", "(", "example", ",", "self", ".", "hparams", ")", "# Make the prediction for the current query.", "result_iter", "=", "self", ".", "estimator", ".", "predict", "(", "input_fn", ",", "hooks", "=", "hooks", ")", "result", "=", "None", "for", "result", "in", "result_iter", ":", "break", "# Extract the beam search information by reading the dumped TFDBG event", "# tensors. We first read and record the per step beam sequences then record", "# the beam scores. Afterwards we align the two sets of values to create the", "# full graph vertices and edges.", "decoding_graph", "=", "graph", ".", "Graph", "(", ")", "run_dirs", "=", "sorted", "(", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "hook_dir", ",", "\"run_*\"", ")", ")", ")", "for", "run_dir", "in", "run_dirs", ":", "# Record the different completed and active beam sequence ids.", "alive_sequences", "=", "deque", "(", ")", "finished_sequences", "=", "deque", "(", ")", "# Make the root vertex since it always needs to exist.", "decoding_graph", ".", "get_vertex", "(", "sequence_key", "(", "[", "0", "]", ")", ")", "# Create the initial vertices and edges for the active and finished", "# sequences. We uniquely define each vertex using it's full sequence path", "# as a string to ensure there's no collisions when the same step has two", "# instances of an output id.", "dump_dir", "=", "tfdbg", ".", "DebugDumpDir", "(", "run_dir", ",", "validate", "=", "False", ")", "seq_datums", "=", "dump_dir", ".", "find", "(", "predicate", "=", "seq_filter", ")", "for", "seq_datum", "in", "seq_datums", ":", "sequences", "=", "np", ".", "array", "(", "seq_datum", ".", "get_tensor", "(", ")", ")", ".", "astype", "(", "int", ")", "[", "0", "]", "if", "\"alive\"", "in", "seq_datum", ".", "node_name", ":", "alive_sequences", ".", "append", "(", "sequences", ")", "if", "\"finished\"", "in", "seq_datum", ".", "node_name", ":", "finished_sequences", ".", "append", "(", "sequences", ")", "for", "sequence", "in", "sequences", ":", "pieces", "=", "self", ".", "targets_vocab", ".", "decode_list", "(", "sequence", ")", "index", "=", "sequence", "[", "-", "1", "]", "if", "index", "==", "0", ":", "continue", "parent", "=", "decoding_graph", ".", "get_vertex", "(", "sequence_key", "(", "sequence", "[", ":", "-", "1", "]", ")", ")", "current", "=", "decoding_graph", ".", "get_vertex", "(", "sequence_key", "(", "sequence", ")", ")", "edge", "=", "decoding_graph", ".", "add_edge", "(", "parent", ",", "current", ")", "edge", ".", "data", "[", "\"label\"", "]", "=", "pieces", "[", "-", "1", "]", "edge", ".", "data", "[", "\"label_id\"", "]", "=", "index", "# Coerce the type to be a python bool. Numpy bools can't be easily", "# converted to JSON.", "edge", ".", "data", "[", "\"completed\"", "]", "=", "bool", "(", "index", "==", "1", ")", "# Examine the score results and store the scores with the associated edges", "# in the graph. We fetch the vertices (and relevant edges) by looking", "# into the saved beam sequences stored above.", "score_datums", "=", "dump_dir", ".", "find", "(", "predicate", "=", "scores_filter", ")", "for", "score_datum", "in", "score_datums", ":", "if", "\"alive\"", "in", "score_datum", ".", "node_name", ":", "sequences", "=", "alive_sequences", ".", "popleft", "(", ")", "if", "\"finished\"", "in", "score_datum", ".", "node_name", ":", "sequences", "=", "finished_sequences", ".", "popleft", "(", ")", "scores", "=", "np", ".", "array", "(", "score_datum", ".", "get_tensor", "(", ")", ")", ".", "astype", "(", "float", ")", "[", "0", "]", "for", "i", ",", "score", "in", "enumerate", "(", "scores", ")", ":", "sequence", "=", "sequences", "[", "i", "]", "if", "sequence", "[", "-", "1", "]", "==", "0", ":", "continue", "vertex", "=", "decoding_graph", ".", "get_vertex", "(", "sequence_key", "(", "sequence", ")", ")", "edge", "=", "decoding_graph", ".", "edges", "[", "vertex", ".", "in_edges", "[", "0", "]", "]", "edge", ".", "data", "[", "\"score\"", "]", "=", "score", "edge", ".", "data", "[", "\"log_probability\"", "]", "=", "score", "edge", ".", "data", "[", "\"total_log_probability\"", "]", "=", "score", "# Delete the hook dir to save disk space", "shutil", ".", "rmtree", "(", "hook_dir", ")", "# Create the graph visualization data structure.", "graph_vis", "=", "{", "\"visualization_name\"", ":", "\"graph\"", ",", "\"title\"", ":", "\"Graph\"", ",", "\"name\"", ":", "\"graph\"", ",", "\"search_graph\"", ":", "decoding_graph", ".", "to_dict", "(", ")", ",", "}", "# Create the processing visualization data structure.", "# TODO(kstevens): Make this method public", "# pylint: disable=protected-access", "output_ids", "=", "decoding", ".", "_save_until_eos", "(", "result", "[", "\"outputs\"", "]", ".", "flatten", "(", ")", ",", "False", ")", "output_pieces", "=", "self", ".", "targets_vocab", ".", "decode_list", "(", "output_ids", ")", "output_token", "=", "[", "{", "\"text\"", ":", "piece", "}", "for", "piece", "in", "output_pieces", "]", "output", "=", "self", ".", "targets_vocab", ".", "decode", "(", "output_ids", ")", "source_steps", "=", "[", "{", "\"step_name\"", ":", "\"Initial\"", ",", "\"segment\"", ":", "[", "{", "\"text\"", ":", "query", "}", "]", ",", "}", "]", "target_steps", "=", "[", "{", "\"step_name\"", ":", "\"Initial\"", ",", "\"segment\"", ":", "output_token", ",", "}", ",", "{", "\"step_name\"", ":", "\"Final\"", ",", "\"segment\"", ":", "[", "{", "\"text\"", ":", "output", "}", "]", ",", "}", "]", "processing_vis", "=", "{", "\"visualization_name\"", ":", "\"processing\"", ",", "\"title\"", ":", "\"Processing\"", ",", "\"name\"", ":", "\"processing\"", ",", "\"query_processing\"", ":", "{", "\"source_processing\"", ":", "source_steps", ",", "\"target_processing\"", ":", "target_steps", ",", "}", ",", "}", "return", "{", "\"result\"", ":", "[", "processing_vis", ",", "graph_vis", "]", ",", "}" ]
Returns the visualizations for query. Args: query: The query to process. Returns: A dictionary of results with processing and graph visualizations.
[ "Returns", "the", "visualizations", "for", "query", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/insights/transformer_model.py#L141-L301
train
tensorflow/tensor2tensor
tensor2tensor/trax/trainer.py
_default_output_dir
def _default_output_dir(): """Default output directory.""" try: dataset_name = gin.query_parameter("inputs.dataset_name") except ValueError: dataset_name = "random" dir_name = "{model_name}_{dataset_name}_{timestamp}".format( model_name=gin.query_parameter("train.model").configurable.name, dataset_name=dataset_name, timestamp=datetime.datetime.now().strftime("%Y%m%d_%H%M"), ) dir_path = os.path.join("~", "trax", dir_name) print() trax.log("No --output_dir specified") return dir_path
python
def _default_output_dir(): """Default output directory.""" try: dataset_name = gin.query_parameter("inputs.dataset_name") except ValueError: dataset_name = "random" dir_name = "{model_name}_{dataset_name}_{timestamp}".format( model_name=gin.query_parameter("train.model").configurable.name, dataset_name=dataset_name, timestamp=datetime.datetime.now().strftime("%Y%m%d_%H%M"), ) dir_path = os.path.join("~", "trax", dir_name) print() trax.log("No --output_dir specified") return dir_path
[ "def", "_default_output_dir", "(", ")", ":", "try", ":", "dataset_name", "=", "gin", ".", "query_parameter", "(", "\"inputs.dataset_name\"", ")", "except", "ValueError", ":", "dataset_name", "=", "\"random\"", "dir_name", "=", "\"{model_name}_{dataset_name}_{timestamp}\"", ".", "format", "(", "model_name", "=", "gin", ".", "query_parameter", "(", "\"train.model\"", ")", ".", "configurable", ".", "name", ",", "dataset_name", "=", "dataset_name", ",", "timestamp", "=", "datetime", ".", "datetime", ".", "now", "(", ")", ".", "strftime", "(", "\"%Y%m%d_%H%M\"", ")", ",", ")", "dir_path", "=", "os", ".", "path", ".", "join", "(", "\"~\"", ",", "\"trax\"", ",", "dir_name", ")", "print", "(", ")", "trax", ".", "log", "(", "\"No --output_dir specified\"", ")", "return", "dir_path" ]
Default output directory.
[ "Default", "output", "directory", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/trainer.py#L48-L62
train
tensorflow/tensor2tensor
tensor2tensor/trax/trainer.py
_setup_gin
def _setup_gin(): """Setup gin configuration.""" # Imports for configurables # pylint: disable=g-import-not-at-top,unused-import,g-bad-import-order,reimported,unused-variable from tensor2tensor.trax import models as _trax_models from tensor2tensor.trax import optimizers as _trax_opt # pylint: disable=g-import-not-at-top,unused-import,g-bad-import-order,reimported,unused-variable configs = FLAGS.config or [] # Override with --dataset and --model if FLAGS.dataset: configs.append("inputs.dataset_name='%s'" % FLAGS.dataset) if FLAGS.data_dir: configs.append("inputs.data_dir='%s'" % FLAGS.data_dir) if FLAGS.model: configs.append("train.model=@trax.models.%s" % FLAGS.model) gin.parse_config_files_and_bindings(FLAGS.config_file, configs)
python
def _setup_gin(): """Setup gin configuration.""" # Imports for configurables # pylint: disable=g-import-not-at-top,unused-import,g-bad-import-order,reimported,unused-variable from tensor2tensor.trax import models as _trax_models from tensor2tensor.trax import optimizers as _trax_opt # pylint: disable=g-import-not-at-top,unused-import,g-bad-import-order,reimported,unused-variable configs = FLAGS.config or [] # Override with --dataset and --model if FLAGS.dataset: configs.append("inputs.dataset_name='%s'" % FLAGS.dataset) if FLAGS.data_dir: configs.append("inputs.data_dir='%s'" % FLAGS.data_dir) if FLAGS.model: configs.append("train.model=@trax.models.%s" % FLAGS.model) gin.parse_config_files_and_bindings(FLAGS.config_file, configs)
[ "def", "_setup_gin", "(", ")", ":", "# Imports for configurables", "# pylint: disable=g-import-not-at-top,unused-import,g-bad-import-order,reimported,unused-variable", "from", "tensor2tensor", ".", "trax", "import", "models", "as", "_trax_models", "from", "tensor2tensor", ".", "trax", "import", "optimizers", "as", "_trax_opt", "# pylint: disable=g-import-not-at-top,unused-import,g-bad-import-order,reimported,unused-variable", "configs", "=", "FLAGS", ".", "config", "or", "[", "]", "# Override with --dataset and --model", "if", "FLAGS", ".", "dataset", ":", "configs", ".", "append", "(", "\"inputs.dataset_name='%s'\"", "%", "FLAGS", ".", "dataset", ")", "if", "FLAGS", ".", "data_dir", ":", "configs", ".", "append", "(", "\"inputs.data_dir='%s'\"", "%", "FLAGS", ".", "data_dir", ")", "if", "FLAGS", ".", "model", ":", "configs", ".", "append", "(", "\"train.model=@trax.models.%s\"", "%", "FLAGS", ".", "model", ")", "gin", ".", "parse_config_files_and_bindings", "(", "FLAGS", ".", "config_file", ",", "configs", ")" ]
Setup gin configuration.
[ "Setup", "gin", "configuration", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/trainer.py#L65-L81
train
tensorflow/tensor2tensor
tensor2tensor/v2/t2t.py
train_and_eval_dataset
def train_and_eval_dataset(dataset_name, data_dir): """Return train and evaluation datasets, feature info and supervised keys. Args: dataset_name: a string, the name of the dataset; if it starts with "v1_" then we'll search T2T Problem registry for it, otherwise we assume it is a dataset from TFDS and load it from there. data_dir: directory where the data is located. Returns: a 4-tuple consisting of: * the train tf.data.Dataset * the eval tf.data.Dataset * information about features: a python dictionary with feature names as keys and an object as value that provides .shape and .num_classes. * supervised_keys: information what's the input and what's the target, ie., a pair of lists with input and target feature names. """ if dataset_name.startswith("v1_"): return _train_and_eval_dataset_v1(dataset_name[3:], data_dir) dataset_builder = tfds.builder(dataset_name, data_dir=data_dir) info = dataset_builder.info splits = dataset_builder.info.splits if tfds.Split.TRAIN not in splits: raise ValueError("To train we require a train split in the dataset.") if tfds.Split.VALIDATION not in splits and "test" not in splits: raise ValueError("We require a validation or test split in the dataset.") eval_split = tfds.Split.VALIDATION if tfds.Split.VALIDATION not in splits: eval_split = tfds.Split.TEST train, valid = tfds.load( name=dataset_name, split=[tfds.Split.TRAIN, eval_split]) keys = None if info.supervised_keys: keys = ([info.supervised_keys[0]], [info.supervised_keys[1]]) return train, valid, info.features, keys
python
def train_and_eval_dataset(dataset_name, data_dir): """Return train and evaluation datasets, feature info and supervised keys. Args: dataset_name: a string, the name of the dataset; if it starts with "v1_" then we'll search T2T Problem registry for it, otherwise we assume it is a dataset from TFDS and load it from there. data_dir: directory where the data is located. Returns: a 4-tuple consisting of: * the train tf.data.Dataset * the eval tf.data.Dataset * information about features: a python dictionary with feature names as keys and an object as value that provides .shape and .num_classes. * supervised_keys: information what's the input and what's the target, ie., a pair of lists with input and target feature names. """ if dataset_name.startswith("v1_"): return _train_and_eval_dataset_v1(dataset_name[3:], data_dir) dataset_builder = tfds.builder(dataset_name, data_dir=data_dir) info = dataset_builder.info splits = dataset_builder.info.splits if tfds.Split.TRAIN not in splits: raise ValueError("To train we require a train split in the dataset.") if tfds.Split.VALIDATION not in splits and "test" not in splits: raise ValueError("We require a validation or test split in the dataset.") eval_split = tfds.Split.VALIDATION if tfds.Split.VALIDATION not in splits: eval_split = tfds.Split.TEST train, valid = tfds.load( name=dataset_name, split=[tfds.Split.TRAIN, eval_split]) keys = None if info.supervised_keys: keys = ([info.supervised_keys[0]], [info.supervised_keys[1]]) return train, valid, info.features, keys
[ "def", "train_and_eval_dataset", "(", "dataset_name", ",", "data_dir", ")", ":", "if", "dataset_name", ".", "startswith", "(", "\"v1_\"", ")", ":", "return", "_train_and_eval_dataset_v1", "(", "dataset_name", "[", "3", ":", "]", ",", "data_dir", ")", "dataset_builder", "=", "tfds", ".", "builder", "(", "dataset_name", ",", "data_dir", "=", "data_dir", ")", "info", "=", "dataset_builder", ".", "info", "splits", "=", "dataset_builder", ".", "info", ".", "splits", "if", "tfds", ".", "Split", ".", "TRAIN", "not", "in", "splits", ":", "raise", "ValueError", "(", "\"To train we require a train split in the dataset.\"", ")", "if", "tfds", ".", "Split", ".", "VALIDATION", "not", "in", "splits", "and", "\"test\"", "not", "in", "splits", ":", "raise", "ValueError", "(", "\"We require a validation or test split in the dataset.\"", ")", "eval_split", "=", "tfds", ".", "Split", ".", "VALIDATION", "if", "tfds", ".", "Split", ".", "VALIDATION", "not", "in", "splits", ":", "eval_split", "=", "tfds", ".", "Split", ".", "TEST", "train", ",", "valid", "=", "tfds", ".", "load", "(", "name", "=", "dataset_name", ",", "split", "=", "[", "tfds", ".", "Split", ".", "TRAIN", ",", "eval_split", "]", ")", "keys", "=", "None", "if", "info", ".", "supervised_keys", ":", "keys", "=", "(", "[", "info", ".", "supervised_keys", "[", "0", "]", "]", ",", "[", "info", ".", "supervised_keys", "[", "1", "]", "]", ")", "return", "train", ",", "valid", ",", "info", ".", "features", ",", "keys" ]
Return train and evaluation datasets, feature info and supervised keys. Args: dataset_name: a string, the name of the dataset; if it starts with "v1_" then we'll search T2T Problem registry for it, otherwise we assume it is a dataset from TFDS and load it from there. data_dir: directory where the data is located. Returns: a 4-tuple consisting of: * the train tf.data.Dataset * the eval tf.data.Dataset * information about features: a python dictionary with feature names as keys and an object as value that provides .shape and .num_classes. * supervised_keys: information what's the input and what's the target, ie., a pair of lists with input and target feature names.
[ "Return", "train", "and", "evaluation", "datasets", "feature", "info", "and", "supervised", "keys", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/v2/t2t.py#L48-L83
train
tensorflow/tensor2tensor
tensor2tensor/v2/t2t.py
_make_info
def _make_info(shape_list, num_classes): """Create an info-like tuple for feature given some shapes and vocab size.""" feature_info = collections.namedtuple("FeatureInfo", ["shape", "num_classes"]) cur_shape = list(shape_list[0]) # We need to merge the provided shapes, put None where they disagree. for shape in shape_list: if len(shape) != len(cur_shape): raise ValueError("Shapes need to have the same number of dimensions.") for i in range(len(shape)): if cur_shape[i] is not None: if shape[i] != cur_shape[i]: cur_shape[i] = None return feature_info(cur_shape, num_classes)
python
def _make_info(shape_list, num_classes): """Create an info-like tuple for feature given some shapes and vocab size.""" feature_info = collections.namedtuple("FeatureInfo", ["shape", "num_classes"]) cur_shape = list(shape_list[0]) # We need to merge the provided shapes, put None where they disagree. for shape in shape_list: if len(shape) != len(cur_shape): raise ValueError("Shapes need to have the same number of dimensions.") for i in range(len(shape)): if cur_shape[i] is not None: if shape[i] != cur_shape[i]: cur_shape[i] = None return feature_info(cur_shape, num_classes)
[ "def", "_make_info", "(", "shape_list", ",", "num_classes", ")", ":", "feature_info", "=", "collections", ".", "namedtuple", "(", "\"FeatureInfo\"", ",", "[", "\"shape\"", ",", "\"num_classes\"", "]", ")", "cur_shape", "=", "list", "(", "shape_list", "[", "0", "]", ")", "# We need to merge the provided shapes, put None where they disagree.", "for", "shape", "in", "shape_list", ":", "if", "len", "(", "shape", ")", "!=", "len", "(", "cur_shape", ")", ":", "raise", "ValueError", "(", "\"Shapes need to have the same number of dimensions.\"", ")", "for", "i", "in", "range", "(", "len", "(", "shape", ")", ")", ":", "if", "cur_shape", "[", "i", "]", "is", "not", "None", ":", "if", "shape", "[", "i", "]", "!=", "cur_shape", "[", "i", "]", ":", "cur_shape", "[", "i", "]", "=", "None", "return", "feature_info", "(", "cur_shape", ",", "num_classes", ")" ]
Create an info-like tuple for feature given some shapes and vocab size.
[ "Create", "an", "info", "-", "like", "tuple", "for", "feature", "given", "some", "shapes", "and", "vocab", "size", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/v2/t2t.py#L86-L98
train
tensorflow/tensor2tensor
tensor2tensor/v2/t2t.py
_select_features
def _select_features(example, feature_list=None): """Select a subset of features from the example dict.""" feature_list = feature_list or ["inputs", "targets"] return {f: example[f] for f in feature_list}
python
def _select_features(example, feature_list=None): """Select a subset of features from the example dict.""" feature_list = feature_list or ["inputs", "targets"] return {f: example[f] for f in feature_list}
[ "def", "_select_features", "(", "example", ",", "feature_list", "=", "None", ")", ":", "feature_list", "=", "feature_list", "or", "[", "\"inputs\"", ",", "\"targets\"", "]", "return", "{", "f", ":", "example", "[", "f", "]", "for", "f", "in", "feature_list", "}" ]
Select a subset of features from the example dict.
[ "Select", "a", "subset", "of", "features", "from", "the", "example", "dict", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/v2/t2t.py#L101-L104
train
tensorflow/tensor2tensor
tensor2tensor/v2/t2t.py
_train_and_eval_dataset_v1
def _train_and_eval_dataset_v1(problem_name, data_dir): """Return train and evaluation datasets, feature info and supervised keys.""" problem = problems.problem(problem_name) train_dataset = problem.dataset(tf.estimator.ModeKeys.TRAIN, data_dir) train_dataset = train_dataset.map(_select_features) eval_dataset = problem.dataset(tf.estimator.ModeKeys.EVAL, data_dir) eval_dataset = eval_dataset.map(_select_features) supervised_keys = (["inputs"], ["targets"]) hparams = problem.get_hparams() # We take a few training examples to guess the shapes. input_shapes, target_shapes = [], [] for example in train_dataset.take(3): input_shapes.append(example["inputs"].shape.as_list()) target_shapes.append(example["targets"].shape.as_list()) input_vocab_size = hparams.vocab_size["inputs"] target_vocab_size = hparams.vocab_size["targets"] input_info = _make_info(input_shapes, input_vocab_size) target_info = _make_info(target_shapes, target_vocab_size) info = {"inputs": input_info, "targets": target_info} return train_dataset, eval_dataset, info, supervised_keys
python
def _train_and_eval_dataset_v1(problem_name, data_dir): """Return train and evaluation datasets, feature info and supervised keys.""" problem = problems.problem(problem_name) train_dataset = problem.dataset(tf.estimator.ModeKeys.TRAIN, data_dir) train_dataset = train_dataset.map(_select_features) eval_dataset = problem.dataset(tf.estimator.ModeKeys.EVAL, data_dir) eval_dataset = eval_dataset.map(_select_features) supervised_keys = (["inputs"], ["targets"]) hparams = problem.get_hparams() # We take a few training examples to guess the shapes. input_shapes, target_shapes = [], [] for example in train_dataset.take(3): input_shapes.append(example["inputs"].shape.as_list()) target_shapes.append(example["targets"].shape.as_list()) input_vocab_size = hparams.vocab_size["inputs"] target_vocab_size = hparams.vocab_size["targets"] input_info = _make_info(input_shapes, input_vocab_size) target_info = _make_info(target_shapes, target_vocab_size) info = {"inputs": input_info, "targets": target_info} return train_dataset, eval_dataset, info, supervised_keys
[ "def", "_train_and_eval_dataset_v1", "(", "problem_name", ",", "data_dir", ")", ":", "problem", "=", "problems", ".", "problem", "(", "problem_name", ")", "train_dataset", "=", "problem", ".", "dataset", "(", "tf", ".", "estimator", ".", "ModeKeys", ".", "TRAIN", ",", "data_dir", ")", "train_dataset", "=", "train_dataset", ".", "map", "(", "_select_features", ")", "eval_dataset", "=", "problem", ".", "dataset", "(", "tf", ".", "estimator", ".", "ModeKeys", ".", "EVAL", ",", "data_dir", ")", "eval_dataset", "=", "eval_dataset", ".", "map", "(", "_select_features", ")", "supervised_keys", "=", "(", "[", "\"inputs\"", "]", ",", "[", "\"targets\"", "]", ")", "hparams", "=", "problem", ".", "get_hparams", "(", ")", "# We take a few training examples to guess the shapes.", "input_shapes", ",", "target_shapes", "=", "[", "]", ",", "[", "]", "for", "example", "in", "train_dataset", ".", "take", "(", "3", ")", ":", "input_shapes", ".", "append", "(", "example", "[", "\"inputs\"", "]", ".", "shape", ".", "as_list", "(", ")", ")", "target_shapes", ".", "append", "(", "example", "[", "\"targets\"", "]", ".", "shape", ".", "as_list", "(", ")", ")", "input_vocab_size", "=", "hparams", ".", "vocab_size", "[", "\"inputs\"", "]", "target_vocab_size", "=", "hparams", ".", "vocab_size", "[", "\"targets\"", "]", "input_info", "=", "_make_info", "(", "input_shapes", ",", "input_vocab_size", ")", "target_info", "=", "_make_info", "(", "target_shapes", ",", "target_vocab_size", ")", "info", "=", "{", "\"inputs\"", ":", "input_info", ",", "\"targets\"", ":", "target_info", "}", "return", "train_dataset", ",", "eval_dataset", ",", "info", ",", "supervised_keys" ]
Return train and evaluation datasets, feature info and supervised keys.
[ "Return", "train", "and", "evaluation", "datasets", "feature", "info", "and", "supervised", "keys", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/v2/t2t.py#L107-L126
train
tensorflow/tensor2tensor
tensor2tensor/v2/t2t.py
batch_fn
def batch_fn(dataset, training, shapes, target_names, batch_size=32, eval_batch_size=32, bucket_batch_length=32, bucket_max_length=256, bucket_min_length=8, bucket_length_step=1.1, buckets=None): """Batching function.""" del target_names # If bucketing is not specified, check if target shapes are variable. cur_batch_size = batch_size if training else eval_batch_size if buckets is None: variable_target_shapes = False target_shape = shapes[1] for dim in target_shape: if dim is None: variable_target_shapes = True tf.logging.info("Heuristically setting bucketing to %s based on shapes " "of target tensors." % variable_target_shapes) if variable_target_shapes: batch_size_per_token = cur_batch_size * bucket_batch_length scheme = data_reader.batching_scheme(batch_size_per_token, bucket_max_length, bucket_min_length, bucket_length_step, drop_long_sequences=training) buckets = (scheme["boundaries"], scheme["batch_sizes"]) if buckets: tf.logging.info("Bucketing with buckets %s." % str(buckets)) def example_length(_, target): return tf.shape(target)[0] boundaries, batch_sizes = buckets dataset = dataset.apply(tf.data.experimental.bucket_by_sequence_length( example_length, boundaries, batch_sizes)) else: dataset = dataset.padded_batch(cur_batch_size, shapes) return dataset
python
def batch_fn(dataset, training, shapes, target_names, batch_size=32, eval_batch_size=32, bucket_batch_length=32, bucket_max_length=256, bucket_min_length=8, bucket_length_step=1.1, buckets=None): """Batching function.""" del target_names # If bucketing is not specified, check if target shapes are variable. cur_batch_size = batch_size if training else eval_batch_size if buckets is None: variable_target_shapes = False target_shape = shapes[1] for dim in target_shape: if dim is None: variable_target_shapes = True tf.logging.info("Heuristically setting bucketing to %s based on shapes " "of target tensors." % variable_target_shapes) if variable_target_shapes: batch_size_per_token = cur_batch_size * bucket_batch_length scheme = data_reader.batching_scheme(batch_size_per_token, bucket_max_length, bucket_min_length, bucket_length_step, drop_long_sequences=training) buckets = (scheme["boundaries"], scheme["batch_sizes"]) if buckets: tf.logging.info("Bucketing with buckets %s." % str(buckets)) def example_length(_, target): return tf.shape(target)[0] boundaries, batch_sizes = buckets dataset = dataset.apply(tf.data.experimental.bucket_by_sequence_length( example_length, boundaries, batch_sizes)) else: dataset = dataset.padded_batch(cur_batch_size, shapes) return dataset
[ "def", "batch_fn", "(", "dataset", ",", "training", ",", "shapes", ",", "target_names", ",", "batch_size", "=", "32", ",", "eval_batch_size", "=", "32", ",", "bucket_batch_length", "=", "32", ",", "bucket_max_length", "=", "256", ",", "bucket_min_length", "=", "8", ",", "bucket_length_step", "=", "1.1", ",", "buckets", "=", "None", ")", ":", "del", "target_names", "# If bucketing is not specified, check if target shapes are variable.", "cur_batch_size", "=", "batch_size", "if", "training", "else", "eval_batch_size", "if", "buckets", "is", "None", ":", "variable_target_shapes", "=", "False", "target_shape", "=", "shapes", "[", "1", "]", "for", "dim", "in", "target_shape", ":", "if", "dim", "is", "None", ":", "variable_target_shapes", "=", "True", "tf", ".", "logging", ".", "info", "(", "\"Heuristically setting bucketing to %s based on shapes \"", "\"of target tensors.\"", "%", "variable_target_shapes", ")", "if", "variable_target_shapes", ":", "batch_size_per_token", "=", "cur_batch_size", "*", "bucket_batch_length", "scheme", "=", "data_reader", ".", "batching_scheme", "(", "batch_size_per_token", ",", "bucket_max_length", ",", "bucket_min_length", ",", "bucket_length_step", ",", "drop_long_sequences", "=", "training", ")", "buckets", "=", "(", "scheme", "[", "\"boundaries\"", "]", ",", "scheme", "[", "\"batch_sizes\"", "]", ")", "if", "buckets", ":", "tf", ".", "logging", ".", "info", "(", "\"Bucketing with buckets %s.\"", "%", "str", "(", "buckets", ")", ")", "def", "example_length", "(", "_", ",", "target", ")", ":", "return", "tf", ".", "shape", "(", "target", ")", "[", "0", "]", "boundaries", ",", "batch_sizes", "=", "buckets", "dataset", "=", "dataset", ".", "apply", "(", "tf", ".", "data", ".", "experimental", ".", "bucket_by_sequence_length", "(", "example_length", ",", "boundaries", ",", "batch_sizes", ")", ")", "else", ":", "dataset", "=", "dataset", ".", "padded_batch", "(", "cur_batch_size", ",", "shapes", ")", "return", "dataset" ]
Batching function.
[ "Batching", "function", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/v2/t2t.py#L140-L174
train
tensorflow/tensor2tensor
tensor2tensor/v2/t2t.py
shuffle_and_batch_data
def shuffle_and_batch_data(dataset, target_names, features_info, training): """Shuffle and batch the given dataset.""" def append_targets(example): """Append targets to the example dictionary. Needed for Keras.""" if len(target_names) == 1: return (example, example[target_names[0]]) targets = {} for name in target_names: targets[name] = example[name] return (example, targets) dataset = dataset.map(append_targets) if training: dataset = dataset.repeat() shapes = {k: features_info[k].shape for k in features_info} shapes = (shapes, shapes[target_names[0]]) dataset = dataset.shuffle(128) dataset = preprocess_fn(dataset, training) dataset = batch_fn(dataset, training, shapes, target_names) return dataset.prefetch(8)
python
def shuffle_and_batch_data(dataset, target_names, features_info, training): """Shuffle and batch the given dataset.""" def append_targets(example): """Append targets to the example dictionary. Needed for Keras.""" if len(target_names) == 1: return (example, example[target_names[0]]) targets = {} for name in target_names: targets[name] = example[name] return (example, targets) dataset = dataset.map(append_targets) if training: dataset = dataset.repeat() shapes = {k: features_info[k].shape for k in features_info} shapes = (shapes, shapes[target_names[0]]) dataset = dataset.shuffle(128) dataset = preprocess_fn(dataset, training) dataset = batch_fn(dataset, training, shapes, target_names) return dataset.prefetch(8)
[ "def", "shuffle_and_batch_data", "(", "dataset", ",", "target_names", ",", "features_info", ",", "training", ")", ":", "def", "append_targets", "(", "example", ")", ":", "\"\"\"Append targets to the example dictionary. Needed for Keras.\"\"\"", "if", "len", "(", "target_names", ")", "==", "1", ":", "return", "(", "example", ",", "example", "[", "target_names", "[", "0", "]", "]", ")", "targets", "=", "{", "}", "for", "name", "in", "target_names", ":", "targets", "[", "name", "]", "=", "example", "[", "name", "]", "return", "(", "example", ",", "targets", ")", "dataset", "=", "dataset", ".", "map", "(", "append_targets", ")", "if", "training", ":", "dataset", "=", "dataset", ".", "repeat", "(", ")", "shapes", "=", "{", "k", ":", "features_info", "[", "k", "]", ".", "shape", "for", "k", "in", "features_info", "}", "shapes", "=", "(", "shapes", ",", "shapes", "[", "target_names", "[", "0", "]", "]", ")", "dataset", "=", "dataset", ".", "shuffle", "(", "128", ")", "dataset", "=", "preprocess_fn", "(", "dataset", ",", "training", ")", "dataset", "=", "batch_fn", "(", "dataset", ",", "training", ",", "shapes", ",", "target_names", ")", "return", "dataset", ".", "prefetch", "(", "8", ")" ]
Shuffle and batch the given dataset.
[ "Shuffle", "and", "batch", "the", "given", "dataset", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/v2/t2t.py#L177-L195
train
tensorflow/tensor2tensor
tensor2tensor/v2/t2t.py
optimize_fn
def optimize_fn(model, optimizer=None, learning_rate_schedule=None, loss=None, metrics=None): """Compile the model in Keras.""" learning_rate_schedule = learning_rate_schedule or T2TLearningRateSchedule() if optimizer: optimizer = optimizer(learning_rate=learning_rate_schedule) else: # We use Adam by default with adjusted parameters. optimizer = tf.keras.optimizers.Adam( learning_rate=learning_rate_schedule, beta_1=0.9, beta_2=0.997, epsilon=1e-9) metrics = metrics or [tf.keras.metrics.sparse_categorical_accuracy] def xent_loss(y, x): return tf.keras.backend.sparse_categorical_crossentropy( y, x, from_logits=True) loss = loss or xent_loss return model.compile(optimizer=optimizer, loss=loss, metrics=metrics)
python
def optimize_fn(model, optimizer=None, learning_rate_schedule=None, loss=None, metrics=None): """Compile the model in Keras.""" learning_rate_schedule = learning_rate_schedule or T2TLearningRateSchedule() if optimizer: optimizer = optimizer(learning_rate=learning_rate_schedule) else: # We use Adam by default with adjusted parameters. optimizer = tf.keras.optimizers.Adam( learning_rate=learning_rate_schedule, beta_1=0.9, beta_2=0.997, epsilon=1e-9) metrics = metrics or [tf.keras.metrics.sparse_categorical_accuracy] def xent_loss(y, x): return tf.keras.backend.sparse_categorical_crossentropy( y, x, from_logits=True) loss = loss or xent_loss return model.compile(optimizer=optimizer, loss=loss, metrics=metrics)
[ "def", "optimize_fn", "(", "model", ",", "optimizer", "=", "None", ",", "learning_rate_schedule", "=", "None", ",", "loss", "=", "None", ",", "metrics", "=", "None", ")", ":", "learning_rate_schedule", "=", "learning_rate_schedule", "or", "T2TLearningRateSchedule", "(", ")", "if", "optimizer", ":", "optimizer", "=", "optimizer", "(", "learning_rate", "=", "learning_rate_schedule", ")", "else", ":", "# We use Adam by default with adjusted parameters.", "optimizer", "=", "tf", ".", "keras", ".", "optimizers", ".", "Adam", "(", "learning_rate", "=", "learning_rate_schedule", ",", "beta_1", "=", "0.9", ",", "beta_2", "=", "0.997", ",", "epsilon", "=", "1e-9", ")", "metrics", "=", "metrics", "or", "[", "tf", ".", "keras", ".", "metrics", ".", "sparse_categorical_accuracy", "]", "def", "xent_loss", "(", "y", ",", "x", ")", ":", "return", "tf", ".", "keras", ".", "backend", ".", "sparse_categorical_crossentropy", "(", "y", ",", "x", ",", "from_logits", "=", "True", ")", "loss", "=", "loss", "or", "xent_loss", "return", "model", ".", "compile", "(", "optimizer", "=", "optimizer", ",", "loss", "=", "loss", ",", "metrics", "=", "metrics", ")" ]
Compile the model in Keras.
[ "Compile", "the", "model", "in", "Keras", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/v2/t2t.py#L233-L253
train
tensorflow/tensor2tensor
tensor2tensor/v2/t2t.py
train_fn
def train_fn(data_dir=None, output_dir=None, model_class=gin.REQUIRED, dataset=gin.REQUIRED, input_names=None, target_names=None, train_steps=1000, eval_steps=1, eval_frequency=100): """Train the given model on the given dataset. Args: data_dir: Directory where the data is located. output_dir: Directory where to put the logs and checkpoints. model_class: The model class to train. dataset: The name of the dataset to train on. input_names: List of strings with the names of the features on input. target_names: List of strings with the names of the target features. train_steps: for how many steps to train. eval_steps: for how many steps to do evaluation. eval_frequency: how often (every this many steps) to run evaluation. """ train_data, eval_data, features_info, keys = train_and_eval_dataset( dataset, data_dir) if input_names is None: input_names = keys[0] if target_names is None: target_names = keys[1] # TODO(lukaszkaiser): The use of distribution strategy below fails like this: # .../keras/models.py", line 93, in _clone_functional_model # for layer in model._input_layers: # AttributeError: 'BasicFcRelu' object has no attribute '_input_layers' # strategy = tf.distribute.MirroredStrategy() # with strategy.scope(): model = model_class(features_info=features_info, input_names=input_names, target_names=target_names) optimize_fn(model) train_batches = shuffle_and_batch_data( train_data, target_names, features_info, training=True) eval_batches = shuffle_and_batch_data( eval_data, target_names, features_info, training=False) # Need to run one training step just to get optimizer variables to load. model.fit(train_batches, epochs=1, steps_per_epoch=1) # Training loop. callbacks = [] callbacks.append(tf.keras.callbacks.History()) callbacks.append(tf.keras.callbacks.BaseLogger()) last_epoch = 0 if output_dir is not None: callbacks.append(tf.keras.callbacks.TensorBoard(log_dir=output_dir)) output_format = os.path.join(output_dir, "model-{epoch:05d}") callbacks.append(tf.keras.callbacks.ModelCheckpoint( filepath=output_format, save_weights_only=True)) checkpoints = tf.gfile.Glob(os.path.join(output_dir, "model-*")) # Take basenames and strip the "model-" prefix. checkpoints = [os.path.basename(ckpt)[6:] for ckpt in checkpoints] # Get epoch numbers from the filenames and sort to obtain last epoch. epoch_numbers = [int(ckpt[:5]) for ckpt in checkpoints if len(ckpt) > 4] epoch_numbers.sort() if epoch_numbers: last_epoch = epoch_numbers[-1] saved_path = os.path.join(output_dir, "model-%05d" % last_epoch) model.load_weights(saved_path) model.fit(train_batches, epochs=train_steps // eval_frequency, steps_per_epoch=eval_frequency, validation_data=eval_batches, validation_steps=eval_steps, initial_epoch=last_epoch, callbacks=callbacks)
python
def train_fn(data_dir=None, output_dir=None, model_class=gin.REQUIRED, dataset=gin.REQUIRED, input_names=None, target_names=None, train_steps=1000, eval_steps=1, eval_frequency=100): """Train the given model on the given dataset. Args: data_dir: Directory where the data is located. output_dir: Directory where to put the logs and checkpoints. model_class: The model class to train. dataset: The name of the dataset to train on. input_names: List of strings with the names of the features on input. target_names: List of strings with the names of the target features. train_steps: for how many steps to train. eval_steps: for how many steps to do evaluation. eval_frequency: how often (every this many steps) to run evaluation. """ train_data, eval_data, features_info, keys = train_and_eval_dataset( dataset, data_dir) if input_names is None: input_names = keys[0] if target_names is None: target_names = keys[1] # TODO(lukaszkaiser): The use of distribution strategy below fails like this: # .../keras/models.py", line 93, in _clone_functional_model # for layer in model._input_layers: # AttributeError: 'BasicFcRelu' object has no attribute '_input_layers' # strategy = tf.distribute.MirroredStrategy() # with strategy.scope(): model = model_class(features_info=features_info, input_names=input_names, target_names=target_names) optimize_fn(model) train_batches = shuffle_and_batch_data( train_data, target_names, features_info, training=True) eval_batches = shuffle_and_batch_data( eval_data, target_names, features_info, training=False) # Need to run one training step just to get optimizer variables to load. model.fit(train_batches, epochs=1, steps_per_epoch=1) # Training loop. callbacks = [] callbacks.append(tf.keras.callbacks.History()) callbacks.append(tf.keras.callbacks.BaseLogger()) last_epoch = 0 if output_dir is not None: callbacks.append(tf.keras.callbacks.TensorBoard(log_dir=output_dir)) output_format = os.path.join(output_dir, "model-{epoch:05d}") callbacks.append(tf.keras.callbacks.ModelCheckpoint( filepath=output_format, save_weights_only=True)) checkpoints = tf.gfile.Glob(os.path.join(output_dir, "model-*")) # Take basenames and strip the "model-" prefix. checkpoints = [os.path.basename(ckpt)[6:] for ckpt in checkpoints] # Get epoch numbers from the filenames and sort to obtain last epoch. epoch_numbers = [int(ckpt[:5]) for ckpt in checkpoints if len(ckpt) > 4] epoch_numbers.sort() if epoch_numbers: last_epoch = epoch_numbers[-1] saved_path = os.path.join(output_dir, "model-%05d" % last_epoch) model.load_weights(saved_path) model.fit(train_batches, epochs=train_steps // eval_frequency, steps_per_epoch=eval_frequency, validation_data=eval_batches, validation_steps=eval_steps, initial_epoch=last_epoch, callbacks=callbacks)
[ "def", "train_fn", "(", "data_dir", "=", "None", ",", "output_dir", "=", "None", ",", "model_class", "=", "gin", ".", "REQUIRED", ",", "dataset", "=", "gin", ".", "REQUIRED", ",", "input_names", "=", "None", ",", "target_names", "=", "None", ",", "train_steps", "=", "1000", ",", "eval_steps", "=", "1", ",", "eval_frequency", "=", "100", ")", ":", "train_data", ",", "eval_data", ",", "features_info", ",", "keys", "=", "train_and_eval_dataset", "(", "dataset", ",", "data_dir", ")", "if", "input_names", "is", "None", ":", "input_names", "=", "keys", "[", "0", "]", "if", "target_names", "is", "None", ":", "target_names", "=", "keys", "[", "1", "]", "# TODO(lukaszkaiser): The use of distribution strategy below fails like this:", "# .../keras/models.py\", line 93, in _clone_functional_model", "# for layer in model._input_layers:", "# AttributeError: 'BasicFcRelu' object has no attribute '_input_layers'", "# strategy = tf.distribute.MirroredStrategy()", "# with strategy.scope():", "model", "=", "model_class", "(", "features_info", "=", "features_info", ",", "input_names", "=", "input_names", ",", "target_names", "=", "target_names", ")", "optimize_fn", "(", "model", ")", "train_batches", "=", "shuffle_and_batch_data", "(", "train_data", ",", "target_names", ",", "features_info", ",", "training", "=", "True", ")", "eval_batches", "=", "shuffle_and_batch_data", "(", "eval_data", ",", "target_names", ",", "features_info", ",", "training", "=", "False", ")", "# Need to run one training step just to get optimizer variables to load.", "model", ".", "fit", "(", "train_batches", ",", "epochs", "=", "1", ",", "steps_per_epoch", "=", "1", ")", "# Training loop.", "callbacks", "=", "[", "]", "callbacks", ".", "append", "(", "tf", ".", "keras", ".", "callbacks", ".", "History", "(", ")", ")", "callbacks", ".", "append", "(", "tf", ".", "keras", ".", "callbacks", ".", "BaseLogger", "(", ")", ")", "last_epoch", "=", "0", "if", "output_dir", "is", "not", "None", ":", "callbacks", ".", "append", "(", "tf", ".", "keras", ".", "callbacks", ".", "TensorBoard", "(", "log_dir", "=", "output_dir", ")", ")", "output_format", "=", "os", ".", "path", ".", "join", "(", "output_dir", ",", "\"model-{epoch:05d}\"", ")", "callbacks", ".", "append", "(", "tf", ".", "keras", ".", "callbacks", ".", "ModelCheckpoint", "(", "filepath", "=", "output_format", ",", "save_weights_only", "=", "True", ")", ")", "checkpoints", "=", "tf", ".", "gfile", ".", "Glob", "(", "os", ".", "path", ".", "join", "(", "output_dir", ",", "\"model-*\"", ")", ")", "# Take basenames and strip the \"model-\" prefix.", "checkpoints", "=", "[", "os", ".", "path", ".", "basename", "(", "ckpt", ")", "[", "6", ":", "]", "for", "ckpt", "in", "checkpoints", "]", "# Get epoch numbers from the filenames and sort to obtain last epoch.", "epoch_numbers", "=", "[", "int", "(", "ckpt", "[", ":", "5", "]", ")", "for", "ckpt", "in", "checkpoints", "if", "len", "(", "ckpt", ")", ">", "4", "]", "epoch_numbers", ".", "sort", "(", ")", "if", "epoch_numbers", ":", "last_epoch", "=", "epoch_numbers", "[", "-", "1", "]", "saved_path", "=", "os", ".", "path", ".", "join", "(", "output_dir", ",", "\"model-%05d\"", "%", "last_epoch", ")", "model", ".", "load_weights", "(", "saved_path", ")", "model", ".", "fit", "(", "train_batches", ",", "epochs", "=", "train_steps", "//", "eval_frequency", ",", "steps_per_epoch", "=", "eval_frequency", ",", "validation_data", "=", "eval_batches", ",", "validation_steps", "=", "eval_steps", ",", "initial_epoch", "=", "last_epoch", ",", "callbacks", "=", "callbacks", ")" ]
Train the given model on the given dataset. Args: data_dir: Directory where the data is located. output_dir: Directory where to put the logs and checkpoints. model_class: The model class to train. dataset: The name of the dataset to train on. input_names: List of strings with the names of the features on input. target_names: List of strings with the names of the target features. train_steps: for how many steps to train. eval_steps: for how many steps to do evaluation. eval_frequency: how often (every this many steps) to run evaluation.
[ "Train", "the", "given", "model", "on", "the", "given", "dataset", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/v2/t2t.py#L259-L324
train
tensorflow/tensor2tensor
tensor2tensor/v2/t2t.py
t2t_train
def t2t_train(model_name, dataset_name, data_dir=None, output_dir=None, config_file=None, config=None): """Main function to train the given model on the given dataset. Args: model_name: The name of the model to train. dataset_name: The name of the dataset to train on. data_dir: Directory where the data is located. output_dir: Directory where to put the logs and checkpoints. config_file: the gin configuration file to use. config: string (in gin format) to override gin parameters. """ if model_name not in _MODEL_REGISTRY: raise ValueError("Model %s not in registry. Available models:\n * %s." % (model_name, "\n * ".join(_MODEL_REGISTRY.keys()))) model_class = _MODEL_REGISTRY[model_name]() gin.bind_parameter("train_fn.model_class", model_class) gin.bind_parameter("train_fn.dataset", dataset_name) gin.parse_config_files_and_bindings(config_file, config) # TODO(lukaszkaiser): save gin config in output_dir if provided? train_fn(data_dir, output_dir=output_dir)
python
def t2t_train(model_name, dataset_name, data_dir=None, output_dir=None, config_file=None, config=None): """Main function to train the given model on the given dataset. Args: model_name: The name of the model to train. dataset_name: The name of the dataset to train on. data_dir: Directory where the data is located. output_dir: Directory where to put the logs and checkpoints. config_file: the gin configuration file to use. config: string (in gin format) to override gin parameters. """ if model_name not in _MODEL_REGISTRY: raise ValueError("Model %s not in registry. Available models:\n * %s." % (model_name, "\n * ".join(_MODEL_REGISTRY.keys()))) model_class = _MODEL_REGISTRY[model_name]() gin.bind_parameter("train_fn.model_class", model_class) gin.bind_parameter("train_fn.dataset", dataset_name) gin.parse_config_files_and_bindings(config_file, config) # TODO(lukaszkaiser): save gin config in output_dir if provided? train_fn(data_dir, output_dir=output_dir)
[ "def", "t2t_train", "(", "model_name", ",", "dataset_name", ",", "data_dir", "=", "None", ",", "output_dir", "=", "None", ",", "config_file", "=", "None", ",", "config", "=", "None", ")", ":", "if", "model_name", "not", "in", "_MODEL_REGISTRY", ":", "raise", "ValueError", "(", "\"Model %s not in registry. Available models:\\n * %s.\"", "%", "(", "model_name", ",", "\"\\n * \"", ".", "join", "(", "_MODEL_REGISTRY", ".", "keys", "(", ")", ")", ")", ")", "model_class", "=", "_MODEL_REGISTRY", "[", "model_name", "]", "(", ")", "gin", ".", "bind_parameter", "(", "\"train_fn.model_class\"", ",", "model_class", ")", "gin", ".", "bind_parameter", "(", "\"train_fn.dataset\"", ",", "dataset_name", ")", "gin", ".", "parse_config_files_and_bindings", "(", "config_file", ",", "config", ")", "# TODO(lukaszkaiser): save gin config in output_dir if provided?", "train_fn", "(", "data_dir", ",", "output_dir", "=", "output_dir", ")" ]
Main function to train the given model on the given dataset. Args: model_name: The name of the model to train. dataset_name: The name of the dataset to train on. data_dir: Directory where the data is located. output_dir: Directory where to put the logs and checkpoints. config_file: the gin configuration file to use. config: string (in gin format) to override gin parameters.
[ "Main", "function", "to", "train", "the", "given", "model", "on", "the", "given", "dataset", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/v2/t2t.py#L327-L347
train
tensorflow/tensor2tensor
tensor2tensor/bin/t2t_decoder.py
decode
def decode(estimator, hparams, decode_hp): """Decode from estimator. Interactive, from file, or from dataset.""" if FLAGS.decode_interactive: if estimator.config.use_tpu: raise ValueError("TPU can only decode from dataset.") decoding.decode_interactively(estimator, hparams, decode_hp, checkpoint_path=FLAGS.checkpoint_path) elif FLAGS.decode_from_file: decoding.decode_from_file(estimator, FLAGS.decode_from_file, hparams, decode_hp, FLAGS.decode_to_file, checkpoint_path=FLAGS.checkpoint_path) if FLAGS.checkpoint_path and FLAGS.keep_timestamp: ckpt_time = os.path.getmtime(FLAGS.checkpoint_path + ".index") os.utime(FLAGS.decode_to_file, (ckpt_time, ckpt_time)) else: decoding.decode_from_dataset( estimator, FLAGS.problem, hparams, decode_hp, decode_to_file=FLAGS.decode_to_file, dataset_split="test" if FLAGS.eval_use_test_set else None, checkpoint_path=FLAGS.checkpoint_path)
python
def decode(estimator, hparams, decode_hp): """Decode from estimator. Interactive, from file, or from dataset.""" if FLAGS.decode_interactive: if estimator.config.use_tpu: raise ValueError("TPU can only decode from dataset.") decoding.decode_interactively(estimator, hparams, decode_hp, checkpoint_path=FLAGS.checkpoint_path) elif FLAGS.decode_from_file: decoding.decode_from_file(estimator, FLAGS.decode_from_file, hparams, decode_hp, FLAGS.decode_to_file, checkpoint_path=FLAGS.checkpoint_path) if FLAGS.checkpoint_path and FLAGS.keep_timestamp: ckpt_time = os.path.getmtime(FLAGS.checkpoint_path + ".index") os.utime(FLAGS.decode_to_file, (ckpt_time, ckpt_time)) else: decoding.decode_from_dataset( estimator, FLAGS.problem, hparams, decode_hp, decode_to_file=FLAGS.decode_to_file, dataset_split="test" if FLAGS.eval_use_test_set else None, checkpoint_path=FLAGS.checkpoint_path)
[ "def", "decode", "(", "estimator", ",", "hparams", ",", "decode_hp", ")", ":", "if", "FLAGS", ".", "decode_interactive", ":", "if", "estimator", ".", "config", ".", "use_tpu", ":", "raise", "ValueError", "(", "\"TPU can only decode from dataset.\"", ")", "decoding", ".", "decode_interactively", "(", "estimator", ",", "hparams", ",", "decode_hp", ",", "checkpoint_path", "=", "FLAGS", ".", "checkpoint_path", ")", "elif", "FLAGS", ".", "decode_from_file", ":", "decoding", ".", "decode_from_file", "(", "estimator", ",", "FLAGS", ".", "decode_from_file", ",", "hparams", ",", "decode_hp", ",", "FLAGS", ".", "decode_to_file", ",", "checkpoint_path", "=", "FLAGS", ".", "checkpoint_path", ")", "if", "FLAGS", ".", "checkpoint_path", "and", "FLAGS", ".", "keep_timestamp", ":", "ckpt_time", "=", "os", ".", "path", ".", "getmtime", "(", "FLAGS", ".", "checkpoint_path", "+", "\".index\"", ")", "os", ".", "utime", "(", "FLAGS", ".", "decode_to_file", ",", "(", "ckpt_time", ",", "ckpt_time", ")", ")", "else", ":", "decoding", ".", "decode_from_dataset", "(", "estimator", ",", "FLAGS", ".", "problem", ",", "hparams", ",", "decode_hp", ",", "decode_to_file", "=", "FLAGS", ".", "decode_to_file", ",", "dataset_split", "=", "\"test\"", "if", "FLAGS", ".", "eval_use_test_set", "else", "None", ",", "checkpoint_path", "=", "FLAGS", ".", "checkpoint_path", ")" ]
Decode from estimator. Interactive, from file, or from dataset.
[ "Decode", "from", "estimator", ".", "Interactive", "from", "file", "or", "from", "dataset", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/bin/t2t_decoder.py#L82-L104
train
tensorflow/tensor2tensor
tensor2tensor/bin/t2t_decoder.py
score_file
def score_file(filename): """Score each line in a file and return the scores.""" # Prepare model. hparams = create_hparams() encoders = registry.problem(FLAGS.problem).feature_encoders(FLAGS.data_dir) has_inputs = "inputs" in encoders # Prepare features for feeding into the model. if has_inputs: inputs_ph = tf.placeholder(dtype=tf.int32) # Just length dimension. batch_inputs = tf.reshape(inputs_ph, [1, -1, 1, 1]) # Make it 4D. targets_ph = tf.placeholder(dtype=tf.int32) # Just length dimension. batch_targets = tf.reshape(targets_ph, [1, -1, 1, 1]) # Make it 4D. if has_inputs: features = {"inputs": batch_inputs, "targets": batch_targets} else: features = {"targets": batch_targets} # Prepare the model and the graph when model runs on features. model = registry.model(FLAGS.model)(hparams, tf.estimator.ModeKeys.EVAL) _, losses = model(features) saver = tf.train.Saver() with tf.Session() as sess: # Load weights from checkpoint. if FLAGS.checkpoint_path is None: ckpts = tf.train.get_checkpoint_state(FLAGS.output_dir) ckpt = ckpts.model_checkpoint_path else: ckpt = FLAGS.checkpoint_path saver.restore(sess, ckpt) # Run on each line. with tf.gfile.Open(filename) as f: lines = f.readlines() results = [] for line in lines: tab_split = line.split("\t") if len(tab_split) > 2: raise ValueError("Each line must have at most one tab separator.") if len(tab_split) == 1: targets = tab_split[0].strip() else: targets = tab_split[1].strip() inputs = tab_split[0].strip() # Run encoders and append EOS symbol. targets_numpy = encoders["targets"].encode( targets) + [text_encoder.EOS_ID] if has_inputs: inputs_numpy = encoders["inputs"].encode(inputs) + [text_encoder.EOS_ID] # Prepare the feed. if has_inputs: feed = {inputs_ph: inputs_numpy, targets_ph: targets_numpy} else: feed = {targets_ph: targets_numpy} # Get the score. np_loss = sess.run(losses["training"], feed) results.append(np_loss) return results
python
def score_file(filename): """Score each line in a file and return the scores.""" # Prepare model. hparams = create_hparams() encoders = registry.problem(FLAGS.problem).feature_encoders(FLAGS.data_dir) has_inputs = "inputs" in encoders # Prepare features for feeding into the model. if has_inputs: inputs_ph = tf.placeholder(dtype=tf.int32) # Just length dimension. batch_inputs = tf.reshape(inputs_ph, [1, -1, 1, 1]) # Make it 4D. targets_ph = tf.placeholder(dtype=tf.int32) # Just length dimension. batch_targets = tf.reshape(targets_ph, [1, -1, 1, 1]) # Make it 4D. if has_inputs: features = {"inputs": batch_inputs, "targets": batch_targets} else: features = {"targets": batch_targets} # Prepare the model and the graph when model runs on features. model = registry.model(FLAGS.model)(hparams, tf.estimator.ModeKeys.EVAL) _, losses = model(features) saver = tf.train.Saver() with tf.Session() as sess: # Load weights from checkpoint. if FLAGS.checkpoint_path is None: ckpts = tf.train.get_checkpoint_state(FLAGS.output_dir) ckpt = ckpts.model_checkpoint_path else: ckpt = FLAGS.checkpoint_path saver.restore(sess, ckpt) # Run on each line. with tf.gfile.Open(filename) as f: lines = f.readlines() results = [] for line in lines: tab_split = line.split("\t") if len(tab_split) > 2: raise ValueError("Each line must have at most one tab separator.") if len(tab_split) == 1: targets = tab_split[0].strip() else: targets = tab_split[1].strip() inputs = tab_split[0].strip() # Run encoders and append EOS symbol. targets_numpy = encoders["targets"].encode( targets) + [text_encoder.EOS_ID] if has_inputs: inputs_numpy = encoders["inputs"].encode(inputs) + [text_encoder.EOS_ID] # Prepare the feed. if has_inputs: feed = {inputs_ph: inputs_numpy, targets_ph: targets_numpy} else: feed = {targets_ph: targets_numpy} # Get the score. np_loss = sess.run(losses["training"], feed) results.append(np_loss) return results
[ "def", "score_file", "(", "filename", ")", ":", "# Prepare model.", "hparams", "=", "create_hparams", "(", ")", "encoders", "=", "registry", ".", "problem", "(", "FLAGS", ".", "problem", ")", ".", "feature_encoders", "(", "FLAGS", ".", "data_dir", ")", "has_inputs", "=", "\"inputs\"", "in", "encoders", "# Prepare features for feeding into the model.", "if", "has_inputs", ":", "inputs_ph", "=", "tf", ".", "placeholder", "(", "dtype", "=", "tf", ".", "int32", ")", "# Just length dimension.", "batch_inputs", "=", "tf", ".", "reshape", "(", "inputs_ph", ",", "[", "1", ",", "-", "1", ",", "1", ",", "1", "]", ")", "# Make it 4D.", "targets_ph", "=", "tf", ".", "placeholder", "(", "dtype", "=", "tf", ".", "int32", ")", "# Just length dimension.", "batch_targets", "=", "tf", ".", "reshape", "(", "targets_ph", ",", "[", "1", ",", "-", "1", ",", "1", ",", "1", "]", ")", "# Make it 4D.", "if", "has_inputs", ":", "features", "=", "{", "\"inputs\"", ":", "batch_inputs", ",", "\"targets\"", ":", "batch_targets", "}", "else", ":", "features", "=", "{", "\"targets\"", ":", "batch_targets", "}", "# Prepare the model and the graph when model runs on features.", "model", "=", "registry", ".", "model", "(", "FLAGS", ".", "model", ")", "(", "hparams", ",", "tf", ".", "estimator", ".", "ModeKeys", ".", "EVAL", ")", "_", ",", "losses", "=", "model", "(", "features", ")", "saver", "=", "tf", ".", "train", ".", "Saver", "(", ")", "with", "tf", ".", "Session", "(", ")", "as", "sess", ":", "# Load weights from checkpoint.", "if", "FLAGS", ".", "checkpoint_path", "is", "None", ":", "ckpts", "=", "tf", ".", "train", ".", "get_checkpoint_state", "(", "FLAGS", ".", "output_dir", ")", "ckpt", "=", "ckpts", ".", "model_checkpoint_path", "else", ":", "ckpt", "=", "FLAGS", ".", "checkpoint_path", "saver", ".", "restore", "(", "sess", ",", "ckpt", ")", "# Run on each line.", "with", "tf", ".", "gfile", ".", "Open", "(", "filename", ")", "as", "f", ":", "lines", "=", "f", ".", "readlines", "(", ")", "results", "=", "[", "]", "for", "line", "in", "lines", ":", "tab_split", "=", "line", ".", "split", "(", "\"\\t\"", ")", "if", "len", "(", "tab_split", ")", ">", "2", ":", "raise", "ValueError", "(", "\"Each line must have at most one tab separator.\"", ")", "if", "len", "(", "tab_split", ")", "==", "1", ":", "targets", "=", "tab_split", "[", "0", "]", ".", "strip", "(", ")", "else", ":", "targets", "=", "tab_split", "[", "1", "]", ".", "strip", "(", ")", "inputs", "=", "tab_split", "[", "0", "]", ".", "strip", "(", ")", "# Run encoders and append EOS symbol.", "targets_numpy", "=", "encoders", "[", "\"targets\"", "]", ".", "encode", "(", "targets", ")", "+", "[", "text_encoder", ".", "EOS_ID", "]", "if", "has_inputs", ":", "inputs_numpy", "=", "encoders", "[", "\"inputs\"", "]", ".", "encode", "(", "inputs", ")", "+", "[", "text_encoder", ".", "EOS_ID", "]", "# Prepare the feed.", "if", "has_inputs", ":", "feed", "=", "{", "inputs_ph", ":", "inputs_numpy", ",", "targets_ph", ":", "targets_numpy", "}", "else", ":", "feed", "=", "{", "targets_ph", ":", "targets_numpy", "}", "# Get the score.", "np_loss", "=", "sess", ".", "run", "(", "losses", "[", "\"training\"", "]", ",", "feed", ")", "results", ".", "append", "(", "np_loss", ")", "return", "results" ]
Score each line in a file and return the scores.
[ "Score", "each", "line", "in", "a", "file", "and", "return", "the", "scores", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/bin/t2t_decoder.py#L107-L164
train
tensorflow/tensor2tensor
tensor2tensor/models/research/autoencoders.py
time_to_channels
def time_to_channels(embedded_video): """Put time dimension on channels in an embedded video.""" video_shape = common_layers.shape_list(embedded_video) if len(video_shape) != 5: raise ValueError("Assuming videos given as tensors in the format " "[batch, time, height, width, channels] but got one " "of shape: %s" % str(video_shape)) transposed = tf.transpose(embedded_video, [0, 2, 3, 1, 4]) return tf.reshape(transposed, [ video_shape[0], video_shape[2], video_shape[3], video_shape[1] * video_shape[4] ])
python
def time_to_channels(embedded_video): """Put time dimension on channels in an embedded video.""" video_shape = common_layers.shape_list(embedded_video) if len(video_shape) != 5: raise ValueError("Assuming videos given as tensors in the format " "[batch, time, height, width, channels] but got one " "of shape: %s" % str(video_shape)) transposed = tf.transpose(embedded_video, [0, 2, 3, 1, 4]) return tf.reshape(transposed, [ video_shape[0], video_shape[2], video_shape[3], video_shape[1] * video_shape[4] ])
[ "def", "time_to_channels", "(", "embedded_video", ")", ":", "video_shape", "=", "common_layers", ".", "shape_list", "(", "embedded_video", ")", "if", "len", "(", "video_shape", ")", "!=", "5", ":", "raise", "ValueError", "(", "\"Assuming videos given as tensors in the format \"", "\"[batch, time, height, width, channels] but got one \"", "\"of shape: %s\"", "%", "str", "(", "video_shape", ")", ")", "transposed", "=", "tf", ".", "transpose", "(", "embedded_video", ",", "[", "0", ",", "2", ",", "3", ",", "1", ",", "4", "]", ")", "return", "tf", ".", "reshape", "(", "transposed", ",", "[", "video_shape", "[", "0", "]", ",", "video_shape", "[", "2", "]", ",", "video_shape", "[", "3", "]", ",", "video_shape", "[", "1", "]", "*", "video_shape", "[", "4", "]", "]", ")" ]
Put time dimension on channels in an embedded video.
[ "Put", "time", "dimension", "on", "channels", "in", "an", "embedded", "video", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/autoencoders.py#L38-L49
train
tensorflow/tensor2tensor
tensor2tensor/models/research/autoencoders.py
autoencoder_basic
def autoencoder_basic(): """Basic autoencoder model.""" hparams = common_hparams.basic_params1() hparams.optimizer = "adam" hparams.learning_rate_constant = 0.0002 hparams.learning_rate_warmup_steps = 500 hparams.learning_rate_schedule = "constant * linear_warmup" hparams.label_smoothing = 0.0 hparams.batch_size = 128 hparams.hidden_size = 64 hparams.num_hidden_layers = 5 hparams.initializer = "uniform_unit_scaling" hparams.initializer_gain = 1.0 hparams.weight_decay = 0.0 hparams.kernel_height = 4 hparams.kernel_width = 4 hparams.dropout = 0.05 hparams.add_hparam("max_hidden_size", 1024) hparams.add_hparam("bottleneck_bits", 128) hparams.add_hparam("bottleneck_shared_bits", 0) hparams.add_hparam("bottleneck_shared_bits_start_warmup", 0) hparams.add_hparam("bottleneck_shared_bits_stop_warmup", 0) hparams.add_hparam("bottleneck_noise", 0.1) hparams.add_hparam("bottleneck_warmup_steps", 2000) hparams.add_hparam("sample_height", 32) hparams.add_hparam("sample_width", 32) hparams.add_hparam("discriminator_batchnorm", True) hparams.add_hparam("num_sliced_vecs", 20000) hparams.add_hparam("sliced_do_tanh", int(True)) hparams.add_hparam("discriminator_size", 256) hparams.add_hparam("discriminator_kernel_size", 6) hparams.add_hparam("discriminator_strides", 4) hparams.add_hparam("discriminator_pure_mean", int(False)) hparams.add_hparam("code_loss_factor", 1.0) hparams.add_hparam("gan_codes_warmup_steps", 16000) hparams.add_hparam("gan_loss_factor", 0.0) hparams.add_hparam("bottleneck_l2_factor", 0.05) hparams.add_hparam("gumbel_temperature", 0.5) hparams.add_hparam("gumbel_noise_factor", 0.5) hparams.add_hparam("vq_temperature", 0.001) hparams.add_hparam("use_vq_loss", int(False)) hparams.add_hparam("discriminator", "double") return hparams
python
def autoencoder_basic(): """Basic autoencoder model.""" hparams = common_hparams.basic_params1() hparams.optimizer = "adam" hparams.learning_rate_constant = 0.0002 hparams.learning_rate_warmup_steps = 500 hparams.learning_rate_schedule = "constant * linear_warmup" hparams.label_smoothing = 0.0 hparams.batch_size = 128 hparams.hidden_size = 64 hparams.num_hidden_layers = 5 hparams.initializer = "uniform_unit_scaling" hparams.initializer_gain = 1.0 hparams.weight_decay = 0.0 hparams.kernel_height = 4 hparams.kernel_width = 4 hparams.dropout = 0.05 hparams.add_hparam("max_hidden_size", 1024) hparams.add_hparam("bottleneck_bits", 128) hparams.add_hparam("bottleneck_shared_bits", 0) hparams.add_hparam("bottleneck_shared_bits_start_warmup", 0) hparams.add_hparam("bottleneck_shared_bits_stop_warmup", 0) hparams.add_hparam("bottleneck_noise", 0.1) hparams.add_hparam("bottleneck_warmup_steps", 2000) hparams.add_hparam("sample_height", 32) hparams.add_hparam("sample_width", 32) hparams.add_hparam("discriminator_batchnorm", True) hparams.add_hparam("num_sliced_vecs", 20000) hparams.add_hparam("sliced_do_tanh", int(True)) hparams.add_hparam("discriminator_size", 256) hparams.add_hparam("discriminator_kernel_size", 6) hparams.add_hparam("discriminator_strides", 4) hparams.add_hparam("discriminator_pure_mean", int(False)) hparams.add_hparam("code_loss_factor", 1.0) hparams.add_hparam("gan_codes_warmup_steps", 16000) hparams.add_hparam("gan_loss_factor", 0.0) hparams.add_hparam("bottleneck_l2_factor", 0.05) hparams.add_hparam("gumbel_temperature", 0.5) hparams.add_hparam("gumbel_noise_factor", 0.5) hparams.add_hparam("vq_temperature", 0.001) hparams.add_hparam("use_vq_loss", int(False)) hparams.add_hparam("discriminator", "double") return hparams
[ "def", "autoencoder_basic", "(", ")", ":", "hparams", "=", "common_hparams", ".", "basic_params1", "(", ")", "hparams", ".", "optimizer", "=", "\"adam\"", "hparams", ".", "learning_rate_constant", "=", "0.0002", "hparams", ".", "learning_rate_warmup_steps", "=", "500", "hparams", ".", "learning_rate_schedule", "=", "\"constant * linear_warmup\"", "hparams", ".", "label_smoothing", "=", "0.0", "hparams", ".", "batch_size", "=", "128", "hparams", ".", "hidden_size", "=", "64", "hparams", ".", "num_hidden_layers", "=", "5", "hparams", ".", "initializer", "=", "\"uniform_unit_scaling\"", "hparams", ".", "initializer_gain", "=", "1.0", "hparams", ".", "weight_decay", "=", "0.0", "hparams", ".", "kernel_height", "=", "4", "hparams", ".", "kernel_width", "=", "4", "hparams", ".", "dropout", "=", "0.05", "hparams", ".", "add_hparam", "(", "\"max_hidden_size\"", ",", "1024", ")", "hparams", ".", "add_hparam", "(", "\"bottleneck_bits\"", ",", "128", ")", "hparams", ".", "add_hparam", "(", "\"bottleneck_shared_bits\"", ",", "0", ")", "hparams", ".", "add_hparam", "(", "\"bottleneck_shared_bits_start_warmup\"", ",", "0", ")", "hparams", ".", "add_hparam", "(", "\"bottleneck_shared_bits_stop_warmup\"", ",", "0", ")", "hparams", ".", "add_hparam", "(", "\"bottleneck_noise\"", ",", "0.1", ")", "hparams", ".", "add_hparam", "(", "\"bottleneck_warmup_steps\"", ",", "2000", ")", "hparams", ".", "add_hparam", "(", "\"sample_height\"", ",", "32", ")", "hparams", ".", "add_hparam", "(", "\"sample_width\"", ",", "32", ")", "hparams", ".", "add_hparam", "(", "\"discriminator_batchnorm\"", ",", "True", ")", "hparams", ".", "add_hparam", "(", "\"num_sliced_vecs\"", ",", "20000", ")", "hparams", ".", "add_hparam", "(", "\"sliced_do_tanh\"", ",", "int", "(", "True", ")", ")", "hparams", ".", "add_hparam", "(", "\"discriminator_size\"", ",", "256", ")", "hparams", ".", "add_hparam", "(", "\"discriminator_kernel_size\"", ",", "6", ")", "hparams", ".", "add_hparam", "(", "\"discriminator_strides\"", ",", "4", ")", "hparams", ".", "add_hparam", "(", "\"discriminator_pure_mean\"", ",", "int", "(", "False", ")", ")", "hparams", ".", "add_hparam", "(", "\"code_loss_factor\"", ",", "1.0", ")", "hparams", ".", "add_hparam", "(", "\"gan_codes_warmup_steps\"", ",", "16000", ")", "hparams", ".", "add_hparam", "(", "\"gan_loss_factor\"", ",", "0.0", ")", "hparams", ".", "add_hparam", "(", "\"bottleneck_l2_factor\"", ",", "0.05", ")", "hparams", ".", "add_hparam", "(", "\"gumbel_temperature\"", ",", "0.5", ")", "hparams", ".", "add_hparam", "(", "\"gumbel_noise_factor\"", ",", "0.5", ")", "hparams", ".", "add_hparam", "(", "\"vq_temperature\"", ",", "0.001", ")", "hparams", ".", "add_hparam", "(", "\"use_vq_loss\"", ",", "int", "(", "False", ")", ")", "hparams", ".", "add_hparam", "(", "\"discriminator\"", ",", "\"double\"", ")", "return", "hparams" ]
Basic autoencoder model.
[ "Basic", "autoencoder", "model", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/autoencoders.py#L1027-L1069
train
tensorflow/tensor2tensor
tensor2tensor/models/research/autoencoders.py
autoencoder_autoregressive
def autoencoder_autoregressive(): """Autoregressive autoencoder model.""" hparams = autoencoder_basic() hparams.add_hparam("autoregressive_forget_base", False) hparams.add_hparam("autoregressive_mode", "none") hparams.add_hparam("autoregressive_decode_steps", 0) hparams.add_hparam("autoregressive_eval_pure_autoencoder", False) hparams.add_hparam("autoregressive_gumbel_sample", False) return hparams
python
def autoencoder_autoregressive(): """Autoregressive autoencoder model.""" hparams = autoencoder_basic() hparams.add_hparam("autoregressive_forget_base", False) hparams.add_hparam("autoregressive_mode", "none") hparams.add_hparam("autoregressive_decode_steps", 0) hparams.add_hparam("autoregressive_eval_pure_autoencoder", False) hparams.add_hparam("autoregressive_gumbel_sample", False) return hparams
[ "def", "autoencoder_autoregressive", "(", ")", ":", "hparams", "=", "autoencoder_basic", "(", ")", "hparams", ".", "add_hparam", "(", "\"autoregressive_forget_base\"", ",", "False", ")", "hparams", ".", "add_hparam", "(", "\"autoregressive_mode\"", ",", "\"none\"", ")", "hparams", ".", "add_hparam", "(", "\"autoregressive_decode_steps\"", ",", "0", ")", "hparams", ".", "add_hparam", "(", "\"autoregressive_eval_pure_autoencoder\"", ",", "False", ")", "hparams", ".", "add_hparam", "(", "\"autoregressive_gumbel_sample\"", ",", "False", ")", "return", "hparams" ]
Autoregressive autoencoder model.
[ "Autoregressive", "autoencoder", "model", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/autoencoders.py#L1073-L1081
train
tensorflow/tensor2tensor
tensor2tensor/models/research/autoencoders.py
autoencoder_residual
def autoencoder_residual(): """Residual autoencoder model.""" hparams = autoencoder_autoregressive() hparams.optimizer = "Adafactor" hparams.clip_grad_norm = 1.0 hparams.learning_rate_constant = 0.5 hparams.learning_rate_warmup_steps = 500 hparams.learning_rate_schedule = "constant * linear_warmup * rsqrt_decay" hparams.num_hidden_layers = 5 hparams.hidden_size = 64 hparams.max_hidden_size = 1024 hparams.add_hparam("num_residual_layers", 2) hparams.add_hparam("residual_kernel_height", 3) hparams.add_hparam("residual_kernel_width", 3) hparams.add_hparam("residual_filter_multiplier", 2.0) hparams.add_hparam("residual_dropout", 0.2) hparams.add_hparam("residual_use_separable_conv", int(True)) hparams.add_hparam("kl_beta", 1.0) return hparams
python
def autoencoder_residual(): """Residual autoencoder model.""" hparams = autoencoder_autoregressive() hparams.optimizer = "Adafactor" hparams.clip_grad_norm = 1.0 hparams.learning_rate_constant = 0.5 hparams.learning_rate_warmup_steps = 500 hparams.learning_rate_schedule = "constant * linear_warmup * rsqrt_decay" hparams.num_hidden_layers = 5 hparams.hidden_size = 64 hparams.max_hidden_size = 1024 hparams.add_hparam("num_residual_layers", 2) hparams.add_hparam("residual_kernel_height", 3) hparams.add_hparam("residual_kernel_width", 3) hparams.add_hparam("residual_filter_multiplier", 2.0) hparams.add_hparam("residual_dropout", 0.2) hparams.add_hparam("residual_use_separable_conv", int(True)) hparams.add_hparam("kl_beta", 1.0) return hparams
[ "def", "autoencoder_residual", "(", ")", ":", "hparams", "=", "autoencoder_autoregressive", "(", ")", "hparams", ".", "optimizer", "=", "\"Adafactor\"", "hparams", ".", "clip_grad_norm", "=", "1.0", "hparams", ".", "learning_rate_constant", "=", "0.5", "hparams", ".", "learning_rate_warmup_steps", "=", "500", "hparams", ".", "learning_rate_schedule", "=", "\"constant * linear_warmup * rsqrt_decay\"", "hparams", ".", "num_hidden_layers", "=", "5", "hparams", ".", "hidden_size", "=", "64", "hparams", ".", "max_hidden_size", "=", "1024", "hparams", ".", "add_hparam", "(", "\"num_residual_layers\"", ",", "2", ")", "hparams", ".", "add_hparam", "(", "\"residual_kernel_height\"", ",", "3", ")", "hparams", ".", "add_hparam", "(", "\"residual_kernel_width\"", ",", "3", ")", "hparams", ".", "add_hparam", "(", "\"residual_filter_multiplier\"", ",", "2.0", ")", "hparams", ".", "add_hparam", "(", "\"residual_dropout\"", ",", "0.2", ")", "hparams", ".", "add_hparam", "(", "\"residual_use_separable_conv\"", ",", "int", "(", "True", ")", ")", "hparams", ".", "add_hparam", "(", "\"kl_beta\"", ",", "1.0", ")", "return", "hparams" ]
Residual autoencoder model.
[ "Residual", "autoencoder", "model", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/autoencoders.py#L1085-L1103
train
tensorflow/tensor2tensor
tensor2tensor/models/research/autoencoders.py
autoencoder_residual_text
def autoencoder_residual_text(): """Residual autoencoder model for text.""" hparams = autoencoder_residual() hparams.bottleneck_bits = 32 hparams.batch_size = 1024 hparams.hidden_size = 64 hparams.max_hidden_size = 512 hparams.bottleneck_noise = 0.0 hparams.bottom = { "inputs": modalities.identity_bottom, "targets": modalities.identity_bottom, } hparams.top = { "targets": modalities.identity_top, } hparams.autoregressive_mode = "none" hparams.sample_width = 1 return hparams
python
def autoencoder_residual_text(): """Residual autoencoder model for text.""" hparams = autoencoder_residual() hparams.bottleneck_bits = 32 hparams.batch_size = 1024 hparams.hidden_size = 64 hparams.max_hidden_size = 512 hparams.bottleneck_noise = 0.0 hparams.bottom = { "inputs": modalities.identity_bottom, "targets": modalities.identity_bottom, } hparams.top = { "targets": modalities.identity_top, } hparams.autoregressive_mode = "none" hparams.sample_width = 1 return hparams
[ "def", "autoencoder_residual_text", "(", ")", ":", "hparams", "=", "autoencoder_residual", "(", ")", "hparams", ".", "bottleneck_bits", "=", "32", "hparams", ".", "batch_size", "=", "1024", "hparams", ".", "hidden_size", "=", "64", "hparams", ".", "max_hidden_size", "=", "512", "hparams", ".", "bottleneck_noise", "=", "0.0", "hparams", ".", "bottom", "=", "{", "\"inputs\"", ":", "modalities", ".", "identity_bottom", ",", "\"targets\"", ":", "modalities", ".", "identity_bottom", ",", "}", "hparams", ".", "top", "=", "{", "\"targets\"", ":", "modalities", ".", "identity_top", ",", "}", "hparams", ".", "autoregressive_mode", "=", "\"none\"", "hparams", ".", "sample_width", "=", "1", "return", "hparams" ]
Residual autoencoder model for text.
[ "Residual", "autoencoder", "model", "for", "text", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/autoencoders.py#L1107-L1124
train
tensorflow/tensor2tensor
tensor2tensor/models/research/autoencoders.py
autoencoder_basic_discrete
def autoencoder_basic_discrete(): """Basic autoencoder model.""" hparams = autoencoder_autoregressive() hparams.num_hidden_layers = 5 hparams.hidden_size = 64 hparams.bottleneck_bits = 1024 hparams.bottleneck_noise = 0.1 hparams.add_hparam("discretize_warmup_steps", 16000) return hparams
python
def autoencoder_basic_discrete(): """Basic autoencoder model.""" hparams = autoencoder_autoregressive() hparams.num_hidden_layers = 5 hparams.hidden_size = 64 hparams.bottleneck_bits = 1024 hparams.bottleneck_noise = 0.1 hparams.add_hparam("discretize_warmup_steps", 16000) return hparams
[ "def", "autoencoder_basic_discrete", "(", ")", ":", "hparams", "=", "autoencoder_autoregressive", "(", ")", "hparams", ".", "num_hidden_layers", "=", "5", "hparams", ".", "hidden_size", "=", "64", "hparams", ".", "bottleneck_bits", "=", "1024", "hparams", ".", "bottleneck_noise", "=", "0.1", "hparams", ".", "add_hparam", "(", "\"discretize_warmup_steps\"", ",", "16000", ")", "return", "hparams" ]
Basic autoencoder model.
[ "Basic", "autoencoder", "model", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/autoencoders.py#L1128-L1136
train
tensorflow/tensor2tensor
tensor2tensor/models/research/autoencoders.py
autoencoder_residual_discrete
def autoencoder_residual_discrete(): """Residual discrete autoencoder model.""" hparams = autoencoder_residual() hparams.bottleneck_bits = 1024 hparams.bottleneck_noise = 0.05 hparams.add_hparam("discretize_warmup_steps", 16000) hparams.add_hparam("bottleneck_kind", "tanh_discrete") hparams.add_hparam("isemhash_noise_dev", 0.5) hparams.add_hparam("isemhash_mix_prob", 0.5) hparams.add_hparam("isemhash_filter_size_multiplier", 2.0) hparams.add_hparam("vq_beta", 0.25) hparams.add_hparam("vq_decay", 0.999) hparams.add_hparam("vq_epsilon", 1e-5) return hparams
python
def autoencoder_residual_discrete(): """Residual discrete autoencoder model.""" hparams = autoencoder_residual() hparams.bottleneck_bits = 1024 hparams.bottleneck_noise = 0.05 hparams.add_hparam("discretize_warmup_steps", 16000) hparams.add_hparam("bottleneck_kind", "tanh_discrete") hparams.add_hparam("isemhash_noise_dev", 0.5) hparams.add_hparam("isemhash_mix_prob", 0.5) hparams.add_hparam("isemhash_filter_size_multiplier", 2.0) hparams.add_hparam("vq_beta", 0.25) hparams.add_hparam("vq_decay", 0.999) hparams.add_hparam("vq_epsilon", 1e-5) return hparams
[ "def", "autoencoder_residual_discrete", "(", ")", ":", "hparams", "=", "autoencoder_residual", "(", ")", "hparams", ".", "bottleneck_bits", "=", "1024", "hparams", ".", "bottleneck_noise", "=", "0.05", "hparams", ".", "add_hparam", "(", "\"discretize_warmup_steps\"", ",", "16000", ")", "hparams", ".", "add_hparam", "(", "\"bottleneck_kind\"", ",", "\"tanh_discrete\"", ")", "hparams", ".", "add_hparam", "(", "\"isemhash_noise_dev\"", ",", "0.5", ")", "hparams", ".", "add_hparam", "(", "\"isemhash_mix_prob\"", ",", "0.5", ")", "hparams", ".", "add_hparam", "(", "\"isemhash_filter_size_multiplier\"", ",", "2.0", ")", "hparams", ".", "add_hparam", "(", "\"vq_beta\"", ",", "0.25", ")", "hparams", ".", "add_hparam", "(", "\"vq_decay\"", ",", "0.999", ")", "hparams", ".", "add_hparam", "(", "\"vq_epsilon\"", ",", "1e-5", ")", "return", "hparams" ]
Residual discrete autoencoder model.
[ "Residual", "discrete", "autoencoder", "model", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/autoencoders.py#L1140-L1153
train
tensorflow/tensor2tensor
tensor2tensor/models/research/autoencoders.py
autoencoder_residual_discrete_big
def autoencoder_residual_discrete_big(): """Residual discrete autoencoder model, big version.""" hparams = autoencoder_residual_discrete() hparams.hidden_size = 128 hparams.max_hidden_size = 4096 hparams.bottleneck_noise = 0.1 hparams.residual_dropout = 0.4 return hparams
python
def autoencoder_residual_discrete_big(): """Residual discrete autoencoder model, big version.""" hparams = autoencoder_residual_discrete() hparams.hidden_size = 128 hparams.max_hidden_size = 4096 hparams.bottleneck_noise = 0.1 hparams.residual_dropout = 0.4 return hparams
[ "def", "autoencoder_residual_discrete_big", "(", ")", ":", "hparams", "=", "autoencoder_residual_discrete", "(", ")", "hparams", ".", "hidden_size", "=", "128", "hparams", ".", "max_hidden_size", "=", "4096", "hparams", ".", "bottleneck_noise", "=", "0.1", "hparams", ".", "residual_dropout", "=", "0.4", "return", "hparams" ]
Residual discrete autoencoder model, big version.
[ "Residual", "discrete", "autoencoder", "model", "big", "version", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/autoencoders.py#L1157-L1164
train
tensorflow/tensor2tensor
tensor2tensor/models/research/autoencoders.py
autoencoder_ordered_discrete
def autoencoder_ordered_discrete(): """Ordered discrete autoencoder model.""" hparams = autoencoder_residual_discrete() hparams.bottleneck_noise = 0.05 # Use 0.8 for ordered. hparams.gan_loss_factor = 0.05 hparams.add_hparam("unordered", True) return hparams
python
def autoencoder_ordered_discrete(): """Ordered discrete autoencoder model.""" hparams = autoencoder_residual_discrete() hparams.bottleneck_noise = 0.05 # Use 0.8 for ordered. hparams.gan_loss_factor = 0.05 hparams.add_hparam("unordered", True) return hparams
[ "def", "autoencoder_ordered_discrete", "(", ")", ":", "hparams", "=", "autoencoder_residual_discrete", "(", ")", "hparams", ".", "bottleneck_noise", "=", "0.05", "# Use 0.8 for ordered.", "hparams", ".", "gan_loss_factor", "=", "0.05", "hparams", ".", "add_hparam", "(", "\"unordered\"", ",", "True", ")", "return", "hparams" ]
Ordered discrete autoencoder model.
[ "Ordered", "discrete", "autoencoder", "model", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/autoencoders.py#L1168-L1174
train
tensorflow/tensor2tensor
tensor2tensor/models/research/autoencoders.py
autoencoder_ordered_discrete_image64
def autoencoder_ordered_discrete_image64(): """Ordered discrete autoencoder model.""" hparams = autoencoder_ordered_discrete() hparams.batch_size = 32 hparams.num_hidden_layers = 6 hparams.bottleneck_warmup_steps *= 2 hparams.gan_codes_warmup_steps *= 2 return hparams
python
def autoencoder_ordered_discrete_image64(): """Ordered discrete autoencoder model.""" hparams = autoencoder_ordered_discrete() hparams.batch_size = 32 hparams.num_hidden_layers = 6 hparams.bottleneck_warmup_steps *= 2 hparams.gan_codes_warmup_steps *= 2 return hparams
[ "def", "autoencoder_ordered_discrete_image64", "(", ")", ":", "hparams", "=", "autoencoder_ordered_discrete", "(", ")", "hparams", ".", "batch_size", "=", "32", "hparams", ".", "num_hidden_layers", "=", "6", "hparams", ".", "bottleneck_warmup_steps", "*=", "2", "hparams", ".", "gan_codes_warmup_steps", "*=", "2", "return", "hparams" ]
Ordered discrete autoencoder model.
[ "Ordered", "discrete", "autoencoder", "model", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/autoencoders.py#L1178-L1186
train
tensorflow/tensor2tensor
tensor2tensor/models/research/autoencoders.py
autoencoder_ordered_text
def autoencoder_ordered_text(): """Ordered discrete autoencoder model for text.""" hparams = autoencoder_ordered_discrete() hparams.bottleneck_bits = 1024 hparams.bottleneck_shared_bits = 1024-64 hparams.bottleneck_shared_bits_start_warmup = 75000 hparams.bottleneck_shared_bits_stop_warmup = 275000 hparams.num_hidden_layers = 7 hparams.batch_size = 1024 hparams.autoregressive_mode = "conv5" hparams.max_hidden_size = 1024 hparams.bottom = { "inputs": modalities.identity_bottom, "targets": modalities.identity_bottom, } hparams.top = { "targets": modalities.identity_top, } hparams.sample_height = 128 hparams.sample_width = 1 return hparams
python
def autoencoder_ordered_text(): """Ordered discrete autoencoder model for text.""" hparams = autoencoder_ordered_discrete() hparams.bottleneck_bits = 1024 hparams.bottleneck_shared_bits = 1024-64 hparams.bottleneck_shared_bits_start_warmup = 75000 hparams.bottleneck_shared_bits_stop_warmup = 275000 hparams.num_hidden_layers = 7 hparams.batch_size = 1024 hparams.autoregressive_mode = "conv5" hparams.max_hidden_size = 1024 hparams.bottom = { "inputs": modalities.identity_bottom, "targets": modalities.identity_bottom, } hparams.top = { "targets": modalities.identity_top, } hparams.sample_height = 128 hparams.sample_width = 1 return hparams
[ "def", "autoencoder_ordered_text", "(", ")", ":", "hparams", "=", "autoencoder_ordered_discrete", "(", ")", "hparams", ".", "bottleneck_bits", "=", "1024", "hparams", ".", "bottleneck_shared_bits", "=", "1024", "-", "64", "hparams", ".", "bottleneck_shared_bits_start_warmup", "=", "75000", "hparams", ".", "bottleneck_shared_bits_stop_warmup", "=", "275000", "hparams", ".", "num_hidden_layers", "=", "7", "hparams", ".", "batch_size", "=", "1024", "hparams", ".", "autoregressive_mode", "=", "\"conv5\"", "hparams", ".", "max_hidden_size", "=", "1024", "hparams", ".", "bottom", "=", "{", "\"inputs\"", ":", "modalities", ".", "identity_bottom", ",", "\"targets\"", ":", "modalities", ".", "identity_bottom", ",", "}", "hparams", ".", "top", "=", "{", "\"targets\"", ":", "modalities", ".", "identity_top", ",", "}", "hparams", ".", "sample_height", "=", "128", "hparams", ".", "sample_width", "=", "1", "return", "hparams" ]
Ordered discrete autoencoder model for text.
[ "Ordered", "discrete", "autoencoder", "model", "for", "text", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/autoencoders.py#L1214-L1234
train
tensorflow/tensor2tensor
tensor2tensor/models/research/autoencoders.py
autoencoder_ordered_text_small
def autoencoder_ordered_text_small(): """Ordered discrete autoencoder model for text, small version.""" hparams = autoencoder_ordered_text() hparams.bottleneck_bits = 32 hparams.num_hidden_layers = 3 hparams.hidden_size = 64 hparams.max_hidden_size = 512 hparams.bottleneck_noise = 0.0 hparams.autoregressive_mode = "conv5" hparams.sample_height = 4 return hparams
python
def autoencoder_ordered_text_small(): """Ordered discrete autoencoder model for text, small version.""" hparams = autoencoder_ordered_text() hparams.bottleneck_bits = 32 hparams.num_hidden_layers = 3 hparams.hidden_size = 64 hparams.max_hidden_size = 512 hparams.bottleneck_noise = 0.0 hparams.autoregressive_mode = "conv5" hparams.sample_height = 4 return hparams
[ "def", "autoencoder_ordered_text_small", "(", ")", ":", "hparams", "=", "autoencoder_ordered_text", "(", ")", "hparams", ".", "bottleneck_bits", "=", "32", "hparams", ".", "num_hidden_layers", "=", "3", "hparams", ".", "hidden_size", "=", "64", "hparams", ".", "max_hidden_size", "=", "512", "hparams", ".", "bottleneck_noise", "=", "0.0", "hparams", ".", "autoregressive_mode", "=", "\"conv5\"", "hparams", ".", "sample_height", "=", "4", "return", "hparams" ]
Ordered discrete autoencoder model for text, small version.
[ "Ordered", "discrete", "autoencoder", "model", "for", "text", "small", "version", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/autoencoders.py#L1238-L1248
train
tensorflow/tensor2tensor
tensor2tensor/models/research/autoencoders.py
autoencoder_discrete_pong
def autoencoder_discrete_pong(): """Discrete autoencoder model for compressing pong frames.""" hparams = autoencoder_ordered_discrete() hparams.num_hidden_layers = 3 hparams.bottleneck_bits = 24 hparams.batch_size = 2 hparams.gan_loss_factor = 0.01 hparams.bottleneck_l2_factor = 0.001 hparams.add_hparam("video_modality_loss_cutoff", 0.02) return hparams
python
def autoencoder_discrete_pong(): """Discrete autoencoder model for compressing pong frames.""" hparams = autoencoder_ordered_discrete() hparams.num_hidden_layers = 3 hparams.bottleneck_bits = 24 hparams.batch_size = 2 hparams.gan_loss_factor = 0.01 hparams.bottleneck_l2_factor = 0.001 hparams.add_hparam("video_modality_loss_cutoff", 0.02) return hparams
[ "def", "autoencoder_discrete_pong", "(", ")", ":", "hparams", "=", "autoencoder_ordered_discrete", "(", ")", "hparams", ".", "num_hidden_layers", "=", "3", "hparams", ".", "bottleneck_bits", "=", "24", "hparams", ".", "batch_size", "=", "2", "hparams", ".", "gan_loss_factor", "=", "0.01", "hparams", ".", "bottleneck_l2_factor", "=", "0.001", "hparams", ".", "add_hparam", "(", "\"video_modality_loss_cutoff\"", ",", "0.02", ")", "return", "hparams" ]
Discrete autoencoder model for compressing pong frames.
[ "Discrete", "autoencoder", "model", "for", "compressing", "pong", "frames", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/autoencoders.py#L1261-L1270
train
tensorflow/tensor2tensor
tensor2tensor/models/research/autoencoders.py
autoencoder_discrete_tiny
def autoencoder_discrete_tiny(): """Discrete autoencoder model for compressing pong frames for testing.""" hparams = autoencoder_ordered_discrete() hparams.num_hidden_layers = 2 hparams.bottleneck_bits = 24 hparams.batch_size = 2 hparams.gan_loss_factor = 0. hparams.bottleneck_l2_factor = 0.001 hparams.add_hparam("video_modality_loss_cutoff", 0.02) hparams.num_residual_layers = 1 hparams.hidden_size = 32 hparams.max_hidden_size = 64 return hparams
python
def autoencoder_discrete_tiny(): """Discrete autoencoder model for compressing pong frames for testing.""" hparams = autoencoder_ordered_discrete() hparams.num_hidden_layers = 2 hparams.bottleneck_bits = 24 hparams.batch_size = 2 hparams.gan_loss_factor = 0. hparams.bottleneck_l2_factor = 0.001 hparams.add_hparam("video_modality_loss_cutoff", 0.02) hparams.num_residual_layers = 1 hparams.hidden_size = 32 hparams.max_hidden_size = 64 return hparams
[ "def", "autoencoder_discrete_tiny", "(", ")", ":", "hparams", "=", "autoencoder_ordered_discrete", "(", ")", "hparams", ".", "num_hidden_layers", "=", "2", "hparams", ".", "bottleneck_bits", "=", "24", "hparams", ".", "batch_size", "=", "2", "hparams", ".", "gan_loss_factor", "=", "0.", "hparams", ".", "bottleneck_l2_factor", "=", "0.001", "hparams", ".", "add_hparam", "(", "\"video_modality_loss_cutoff\"", ",", "0.02", ")", "hparams", ".", "num_residual_layers", "=", "1", "hparams", ".", "hidden_size", "=", "32", "hparams", ".", "max_hidden_size", "=", "64", "return", "hparams" ]
Discrete autoencoder model for compressing pong frames for testing.
[ "Discrete", "autoencoder", "model", "for", "compressing", "pong", "frames", "for", "testing", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/autoencoders.py#L1274-L1286
train
tensorflow/tensor2tensor
tensor2tensor/models/research/autoencoders.py
autoencoder_discrete_cifar
def autoencoder_discrete_cifar(): """Discrete autoencoder model for compressing cifar.""" hparams = autoencoder_ordered_discrete() hparams.bottleneck_noise = 0.0 hparams.bottleneck_bits = 90 hparams.num_hidden_layers = 2 hparams.hidden_size = 256 hparams.num_residual_layers = 4 hparams.batch_size = 32 hparams.learning_rate_constant = 1.0 return hparams
python
def autoencoder_discrete_cifar(): """Discrete autoencoder model for compressing cifar.""" hparams = autoencoder_ordered_discrete() hparams.bottleneck_noise = 0.0 hparams.bottleneck_bits = 90 hparams.num_hidden_layers = 2 hparams.hidden_size = 256 hparams.num_residual_layers = 4 hparams.batch_size = 32 hparams.learning_rate_constant = 1.0 return hparams
[ "def", "autoencoder_discrete_cifar", "(", ")", ":", "hparams", "=", "autoencoder_ordered_discrete", "(", ")", "hparams", ".", "bottleneck_noise", "=", "0.0", "hparams", ".", "bottleneck_bits", "=", "90", "hparams", ".", "num_hidden_layers", "=", "2", "hparams", ".", "hidden_size", "=", "256", "hparams", ".", "num_residual_layers", "=", "4", "hparams", ".", "batch_size", "=", "32", "hparams", ".", "learning_rate_constant", "=", "1.0", "return", "hparams" ]
Discrete autoencoder model for compressing cifar.
[ "Discrete", "autoencoder", "model", "for", "compressing", "cifar", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/autoencoders.py#L1290-L1300
train
tensorflow/tensor2tensor
tensor2tensor/models/research/autoencoders.py
autoencoder_range
def autoencoder_range(rhp): """Tuning grid of the main autoencoder params.""" rhp.set_float("dropout", 0.01, 0.3) rhp.set_float("gan_loss_factor", 0.01, 0.1) rhp.set_float("bottleneck_l2_factor", 0.001, 0.1, scale=rhp.LOG_SCALE) rhp.set_discrete("bottleneck_warmup_steps", [200, 2000]) rhp.set_float("gumbel_temperature", 0, 1) rhp.set_float("gumbel_noise_factor", 0, 0.5)
python
def autoencoder_range(rhp): """Tuning grid of the main autoencoder params.""" rhp.set_float("dropout", 0.01, 0.3) rhp.set_float("gan_loss_factor", 0.01, 0.1) rhp.set_float("bottleneck_l2_factor", 0.001, 0.1, scale=rhp.LOG_SCALE) rhp.set_discrete("bottleneck_warmup_steps", [200, 2000]) rhp.set_float("gumbel_temperature", 0, 1) rhp.set_float("gumbel_noise_factor", 0, 0.5)
[ "def", "autoencoder_range", "(", "rhp", ")", ":", "rhp", ".", "set_float", "(", "\"dropout\"", ",", "0.01", ",", "0.3", ")", "rhp", ".", "set_float", "(", "\"gan_loss_factor\"", ",", "0.01", ",", "0.1", ")", "rhp", ".", "set_float", "(", "\"bottleneck_l2_factor\"", ",", "0.001", ",", "0.1", ",", "scale", "=", "rhp", ".", "LOG_SCALE", ")", "rhp", ".", "set_discrete", "(", "\"bottleneck_warmup_steps\"", ",", "[", "200", ",", "2000", "]", ")", "rhp", ".", "set_float", "(", "\"gumbel_temperature\"", ",", "0", ",", "1", ")", "rhp", ".", "set_float", "(", "\"gumbel_noise_factor\"", ",", "0", ",", "0.5", ")" ]
Tuning grid of the main autoencoder params.
[ "Tuning", "grid", "of", "the", "main", "autoencoder", "params", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/autoencoders.py#L1304-L1311
train
tensorflow/tensor2tensor
tensor2tensor/models/research/vqa_attention.py
image_encoder
def image_encoder(image_feat, hparams, name="image_encoder", save_weights_to=None, make_image_summary=True): """A stack of self attention layers.""" x = image_feat with tf.variable_scope(name): for layer in range(hparams.num_encoder_layers or hparams.num_hidden_layers): with tf.variable_scope("layer_%d" % layer): with tf.variable_scope("self_attention"): y = vqa_layers.multihead_attention( common_layers.layer_preprocess(x, hparams), None, None, hparams.attention_key_channels or hparams.image_hidden_size, hparams.attention_value_channels or hparams.image_hidden_size, hparams.image_hidden_size, hparams.num_heads, hparams.attention_dropout, attention_type=hparams.self_attention_type, save_weights_to=save_weights_to, max_relative_position=None, make_image_summary=make_image_summary, dropout_broadcast_dims=None, max_length=None, vars_3d=False, scale_otproduct=hparams.scale_dotproduct) utils.collect_named_outputs("norms", "image_feat_self_attention", tf.norm(y, axis=-1)) x = common_layers.layer_postprocess(x, y, hparams) utils.collect_named_outputs( "norms", "image_feat_self_attention_zero_add", tf.norm(x, axis=-1)) with tf.variable_scope("ffn"): y = common_layers.dense_relu_dense( common_layers.layer_preprocess(x, hparams), hparams.image_filter_size, hparams.image_hidden_size, dropout=hparams.relu_dropout, dropout_broadcast_dims=None) utils.collect_named_outputs("norms", "image_feat_ffn", tf.norm(y, axis=-1)) x = common_layers.layer_postprocess(x, y, hparams) utils.collect_named_outputs("norms", "image_feat_ffn_zero_add", tf.norm(x, axis=-1)) # if normalization is done in layer_preprocess, then it should also be done # on the output, since the output can grow very large, being the sum of # a whole stack of unnormalized layer outputs. return common_layers.layer_preprocess(x, hparams)
python
def image_encoder(image_feat, hparams, name="image_encoder", save_weights_to=None, make_image_summary=True): """A stack of self attention layers.""" x = image_feat with tf.variable_scope(name): for layer in range(hparams.num_encoder_layers or hparams.num_hidden_layers): with tf.variable_scope("layer_%d" % layer): with tf.variable_scope("self_attention"): y = vqa_layers.multihead_attention( common_layers.layer_preprocess(x, hparams), None, None, hparams.attention_key_channels or hparams.image_hidden_size, hparams.attention_value_channels or hparams.image_hidden_size, hparams.image_hidden_size, hparams.num_heads, hparams.attention_dropout, attention_type=hparams.self_attention_type, save_weights_to=save_weights_to, max_relative_position=None, make_image_summary=make_image_summary, dropout_broadcast_dims=None, max_length=None, vars_3d=False, scale_otproduct=hparams.scale_dotproduct) utils.collect_named_outputs("norms", "image_feat_self_attention", tf.norm(y, axis=-1)) x = common_layers.layer_postprocess(x, y, hparams) utils.collect_named_outputs( "norms", "image_feat_self_attention_zero_add", tf.norm(x, axis=-1)) with tf.variable_scope("ffn"): y = common_layers.dense_relu_dense( common_layers.layer_preprocess(x, hparams), hparams.image_filter_size, hparams.image_hidden_size, dropout=hparams.relu_dropout, dropout_broadcast_dims=None) utils.collect_named_outputs("norms", "image_feat_ffn", tf.norm(y, axis=-1)) x = common_layers.layer_postprocess(x, y, hparams) utils.collect_named_outputs("norms", "image_feat_ffn_zero_add", tf.norm(x, axis=-1)) # if normalization is done in layer_preprocess, then it should also be done # on the output, since the output can grow very large, being the sum of # a whole stack of unnormalized layer outputs. return common_layers.layer_preprocess(x, hparams)
[ "def", "image_encoder", "(", "image_feat", ",", "hparams", ",", "name", "=", "\"image_encoder\"", ",", "save_weights_to", "=", "None", ",", "make_image_summary", "=", "True", ")", ":", "x", "=", "image_feat", "with", "tf", ".", "variable_scope", "(", "name", ")", ":", "for", "layer", "in", "range", "(", "hparams", ".", "num_encoder_layers", "or", "hparams", ".", "num_hidden_layers", ")", ":", "with", "tf", ".", "variable_scope", "(", "\"layer_%d\"", "%", "layer", ")", ":", "with", "tf", ".", "variable_scope", "(", "\"self_attention\"", ")", ":", "y", "=", "vqa_layers", ".", "multihead_attention", "(", "common_layers", ".", "layer_preprocess", "(", "x", ",", "hparams", ")", ",", "None", ",", "None", ",", "hparams", ".", "attention_key_channels", "or", "hparams", ".", "image_hidden_size", ",", "hparams", ".", "attention_value_channels", "or", "hparams", ".", "image_hidden_size", ",", "hparams", ".", "image_hidden_size", ",", "hparams", ".", "num_heads", ",", "hparams", ".", "attention_dropout", ",", "attention_type", "=", "hparams", ".", "self_attention_type", ",", "save_weights_to", "=", "save_weights_to", ",", "max_relative_position", "=", "None", ",", "make_image_summary", "=", "make_image_summary", ",", "dropout_broadcast_dims", "=", "None", ",", "max_length", "=", "None", ",", "vars_3d", "=", "False", ",", "scale_otproduct", "=", "hparams", ".", "scale_dotproduct", ")", "utils", ".", "collect_named_outputs", "(", "\"norms\"", ",", "\"image_feat_self_attention\"", ",", "tf", ".", "norm", "(", "y", ",", "axis", "=", "-", "1", ")", ")", "x", "=", "common_layers", ".", "layer_postprocess", "(", "x", ",", "y", ",", "hparams", ")", "utils", ".", "collect_named_outputs", "(", "\"norms\"", ",", "\"image_feat_self_attention_zero_add\"", ",", "tf", ".", "norm", "(", "x", ",", "axis", "=", "-", "1", ")", ")", "with", "tf", ".", "variable_scope", "(", "\"ffn\"", ")", ":", "y", "=", "common_layers", ".", "dense_relu_dense", "(", "common_layers", ".", "layer_preprocess", "(", "x", ",", "hparams", ")", ",", "hparams", ".", "image_filter_size", ",", "hparams", ".", "image_hidden_size", ",", "dropout", "=", "hparams", ".", "relu_dropout", ",", "dropout_broadcast_dims", "=", "None", ")", "utils", ".", "collect_named_outputs", "(", "\"norms\"", ",", "\"image_feat_ffn\"", ",", "tf", ".", "norm", "(", "y", ",", "axis", "=", "-", "1", ")", ")", "x", "=", "common_layers", ".", "layer_postprocess", "(", "x", ",", "y", ",", "hparams", ")", "utils", ".", "collect_named_outputs", "(", "\"norms\"", ",", "\"image_feat_ffn_zero_add\"", ",", "tf", ".", "norm", "(", "x", ",", "axis", "=", "-", "1", ")", ")", "# if normalization is done in layer_preprocess, then it should also be done", "# on the output, since the output can grow very large, being the sum of", "# a whole stack of unnormalized layer outputs.", "return", "common_layers", ".", "layer_preprocess", "(", "x", ",", "hparams", ")" ]
A stack of self attention layers.
[ "A", "stack", "of", "self", "attention", "layers", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/vqa_attention.py#L182-L232
train
tensorflow/tensor2tensor
tensor2tensor/models/research/vqa_attention.py
question_encoder
def question_encoder(question, hparams, name="encoder"): """Question encoder, run LSTM encoder and get the last output as encoding.""" with tf.variable_scope(name, "encoder", values=[question]): question = common_layers.flatten4d3d(question) padding = common_attention.embedding_to_padding(question) length = common_attention.padding_to_length(padding) max_question_length = hparams.max_question_length question = question[:, :max_question_length, :] actual_question_length = common_layers.shape_list(question)[1] length = tf.minimum(length, max_question_length) padding = [[0, 0], [0, max_question_length-actual_question_length], [0, 0]] question = tf.pad(question, padding) question_shape = question.get_shape().as_list() question_shape[1] = max_question_length question.set_shape(question_shape) # apply tanh dropout on question embedding question = tf.tanh(question) question = tf.nn.dropout(question, keep_prob=1.-hparams.dropout) question = [question[:, i, :] for i in range(max_question_length)] # rnn_layers = [_get_rnn_cell(hparams) # for _ in range(hparams.num_rnn_layers)] # rnn_multi_cell = tf.nn.rnn_cell.MultiRNNCell(rnn_layers) rnn_cell = _get_rnn_cell(hparams) # outputs, _ = tf.nn.dynamic_rnn( # rnn_cell, question, length, dtype=tf.float32) _, state = tf.nn.static_rnn(rnn_cell, question, sequence_length=length, dtype=tf.float32) # outputs = [tf.expand_dims(output, axis=1) for output in outputs] # outputs = tf.concat(outputs, axis=1) # utils.collect_named_outputs("vqa_attention_debug", "question_output", # outputs) # utils.collect_named_outputs("vqa_attention_debug", "question_state", # state.h) # batch_size = common_layers.shape_list(outputs)[0] # row_indices = tf.range(batch_size) # # length - 1 as index # indices = tf.transpose([row_indices, tf.maximum(length-1, 0)]) # last_output = tf.gather_nd(outputs, indices) # utils.collect_named_outputs("vqa_attention_debug", # "question_final_output", last_output) return state.h
python
def question_encoder(question, hparams, name="encoder"): """Question encoder, run LSTM encoder and get the last output as encoding.""" with tf.variable_scope(name, "encoder", values=[question]): question = common_layers.flatten4d3d(question) padding = common_attention.embedding_to_padding(question) length = common_attention.padding_to_length(padding) max_question_length = hparams.max_question_length question = question[:, :max_question_length, :] actual_question_length = common_layers.shape_list(question)[1] length = tf.minimum(length, max_question_length) padding = [[0, 0], [0, max_question_length-actual_question_length], [0, 0]] question = tf.pad(question, padding) question_shape = question.get_shape().as_list() question_shape[1] = max_question_length question.set_shape(question_shape) # apply tanh dropout on question embedding question = tf.tanh(question) question = tf.nn.dropout(question, keep_prob=1.-hparams.dropout) question = [question[:, i, :] for i in range(max_question_length)] # rnn_layers = [_get_rnn_cell(hparams) # for _ in range(hparams.num_rnn_layers)] # rnn_multi_cell = tf.nn.rnn_cell.MultiRNNCell(rnn_layers) rnn_cell = _get_rnn_cell(hparams) # outputs, _ = tf.nn.dynamic_rnn( # rnn_cell, question, length, dtype=tf.float32) _, state = tf.nn.static_rnn(rnn_cell, question, sequence_length=length, dtype=tf.float32) # outputs = [tf.expand_dims(output, axis=1) for output in outputs] # outputs = tf.concat(outputs, axis=1) # utils.collect_named_outputs("vqa_attention_debug", "question_output", # outputs) # utils.collect_named_outputs("vqa_attention_debug", "question_state", # state.h) # batch_size = common_layers.shape_list(outputs)[0] # row_indices = tf.range(batch_size) # # length - 1 as index # indices = tf.transpose([row_indices, tf.maximum(length-1, 0)]) # last_output = tf.gather_nd(outputs, indices) # utils.collect_named_outputs("vqa_attention_debug", # "question_final_output", last_output) return state.h
[ "def", "question_encoder", "(", "question", ",", "hparams", ",", "name", "=", "\"encoder\"", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ",", "\"encoder\"", ",", "values", "=", "[", "question", "]", ")", ":", "question", "=", "common_layers", ".", "flatten4d3d", "(", "question", ")", "padding", "=", "common_attention", ".", "embedding_to_padding", "(", "question", ")", "length", "=", "common_attention", ".", "padding_to_length", "(", "padding", ")", "max_question_length", "=", "hparams", ".", "max_question_length", "question", "=", "question", "[", ":", ",", ":", "max_question_length", ",", ":", "]", "actual_question_length", "=", "common_layers", ".", "shape_list", "(", "question", ")", "[", "1", "]", "length", "=", "tf", ".", "minimum", "(", "length", ",", "max_question_length", ")", "padding", "=", "[", "[", "0", ",", "0", "]", ",", "[", "0", ",", "max_question_length", "-", "actual_question_length", "]", ",", "[", "0", ",", "0", "]", "]", "question", "=", "tf", ".", "pad", "(", "question", ",", "padding", ")", "question_shape", "=", "question", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "question_shape", "[", "1", "]", "=", "max_question_length", "question", ".", "set_shape", "(", "question_shape", ")", "# apply tanh dropout on question embedding", "question", "=", "tf", ".", "tanh", "(", "question", ")", "question", "=", "tf", ".", "nn", ".", "dropout", "(", "question", ",", "keep_prob", "=", "1.", "-", "hparams", ".", "dropout", ")", "question", "=", "[", "question", "[", ":", ",", "i", ",", ":", "]", "for", "i", "in", "range", "(", "max_question_length", ")", "]", "# rnn_layers = [_get_rnn_cell(hparams)", "# for _ in range(hparams.num_rnn_layers)]", "# rnn_multi_cell = tf.nn.rnn_cell.MultiRNNCell(rnn_layers)", "rnn_cell", "=", "_get_rnn_cell", "(", "hparams", ")", "# outputs, _ = tf.nn.dynamic_rnn(", "# rnn_cell, question, length, dtype=tf.float32)", "_", ",", "state", "=", "tf", ".", "nn", ".", "static_rnn", "(", "rnn_cell", ",", "question", ",", "sequence_length", "=", "length", ",", "dtype", "=", "tf", ".", "float32", ")", "# outputs = [tf.expand_dims(output, axis=1) for output in outputs]", "# outputs = tf.concat(outputs, axis=1)", "# utils.collect_named_outputs(\"vqa_attention_debug\", \"question_output\",", "# outputs)", "# utils.collect_named_outputs(\"vqa_attention_debug\", \"question_state\",", "# state.h)", "# batch_size = common_layers.shape_list(outputs)[0]", "# row_indices = tf.range(batch_size)", "# # length - 1 as index", "# indices = tf.transpose([row_indices, tf.maximum(length-1, 0)])", "# last_output = tf.gather_nd(outputs, indices)", "# utils.collect_named_outputs(\"vqa_attention_debug\",", "# \"question_final_output\", last_output)", "return", "state", ".", "h" ]
Question encoder, run LSTM encoder and get the last output as encoding.
[ "Question", "encoder", "run", "LSTM", "encoder", "and", "get", "the", "last", "output", "as", "encoding", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/vqa_attention.py#L245-L295
train
tensorflow/tensor2tensor
tensor2tensor/models/research/vqa_attention.py
attn
def attn(image_feat, query, hparams, name="attn"): """Attention on image feature with question as query.""" with tf.variable_scope(name, "attn", values=[image_feat, query]): attn_dim = hparams.attn_dim num_glimps = hparams.num_glimps num_channels = common_layers.shape_list(image_feat)[-1] if len(common_layers.shape_list(image_feat)) == 4: image_feat = common_layers.flatten4d3d(image_feat) query = tf.expand_dims(query, 1) image_proj = common_attention.compute_attention_component( image_feat, attn_dim, name="image_proj") query_proj = common_attention.compute_attention_component( query, attn_dim, name="query_proj") h = tf.nn.relu(image_proj + query_proj) h_proj = common_attention.compute_attention_component( h, num_glimps, name="h_proj") p = tf.nn.softmax(h_proj, axis=1) image_ave = tf.matmul(image_feat, p, transpose_a=True) image_ave = tf.reshape(image_ave, [-1, num_channels*num_glimps]) return image_ave
python
def attn(image_feat, query, hparams, name="attn"): """Attention on image feature with question as query.""" with tf.variable_scope(name, "attn", values=[image_feat, query]): attn_dim = hparams.attn_dim num_glimps = hparams.num_glimps num_channels = common_layers.shape_list(image_feat)[-1] if len(common_layers.shape_list(image_feat)) == 4: image_feat = common_layers.flatten4d3d(image_feat) query = tf.expand_dims(query, 1) image_proj = common_attention.compute_attention_component( image_feat, attn_dim, name="image_proj") query_proj = common_attention.compute_attention_component( query, attn_dim, name="query_proj") h = tf.nn.relu(image_proj + query_proj) h_proj = common_attention.compute_attention_component( h, num_glimps, name="h_proj") p = tf.nn.softmax(h_proj, axis=1) image_ave = tf.matmul(image_feat, p, transpose_a=True) image_ave = tf.reshape(image_ave, [-1, num_channels*num_glimps]) return image_ave
[ "def", "attn", "(", "image_feat", ",", "query", ",", "hparams", ",", "name", "=", "\"attn\"", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ",", "\"attn\"", ",", "values", "=", "[", "image_feat", ",", "query", "]", ")", ":", "attn_dim", "=", "hparams", ".", "attn_dim", "num_glimps", "=", "hparams", ".", "num_glimps", "num_channels", "=", "common_layers", ".", "shape_list", "(", "image_feat", ")", "[", "-", "1", "]", "if", "len", "(", "common_layers", ".", "shape_list", "(", "image_feat", ")", ")", "==", "4", ":", "image_feat", "=", "common_layers", ".", "flatten4d3d", "(", "image_feat", ")", "query", "=", "tf", ".", "expand_dims", "(", "query", ",", "1", ")", "image_proj", "=", "common_attention", ".", "compute_attention_component", "(", "image_feat", ",", "attn_dim", ",", "name", "=", "\"image_proj\"", ")", "query_proj", "=", "common_attention", ".", "compute_attention_component", "(", "query", ",", "attn_dim", ",", "name", "=", "\"query_proj\"", ")", "h", "=", "tf", ".", "nn", ".", "relu", "(", "image_proj", "+", "query_proj", ")", "h_proj", "=", "common_attention", ".", "compute_attention_component", "(", "h", ",", "num_glimps", ",", "name", "=", "\"h_proj\"", ")", "p", "=", "tf", ".", "nn", ".", "softmax", "(", "h_proj", ",", "axis", "=", "1", ")", "image_ave", "=", "tf", ".", "matmul", "(", "image_feat", ",", "p", ",", "transpose_a", "=", "True", ")", "image_ave", "=", "tf", ".", "reshape", "(", "image_ave", ",", "[", "-", "1", ",", "num_channels", "*", "num_glimps", "]", ")", "return", "image_ave" ]
Attention on image feature with question as query.
[ "Attention", "on", "image", "feature", "with", "question", "as", "query", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/vqa_attention.py#L298-L318
train
tensorflow/tensor2tensor
tensor2tensor/models/research/vqa_attention.py
mlp
def mlp(feature, hparams, name="mlp"): """Multi layer perceptron with dropout and relu activation.""" with tf.variable_scope(name, "mlp", values=[feature]): num_mlp_layers = hparams.num_mlp_layers mlp_dim = hparams.mlp_dim for _ in range(num_mlp_layers): feature = common_layers.dense(feature, mlp_dim, activation=tf.nn.relu) feature = tf.nn.dropout(feature, keep_prob=1.-hparams.dropout) return feature
python
def mlp(feature, hparams, name="mlp"): """Multi layer perceptron with dropout and relu activation.""" with tf.variable_scope(name, "mlp", values=[feature]): num_mlp_layers = hparams.num_mlp_layers mlp_dim = hparams.mlp_dim for _ in range(num_mlp_layers): feature = common_layers.dense(feature, mlp_dim, activation=tf.nn.relu) feature = tf.nn.dropout(feature, keep_prob=1.-hparams.dropout) return feature
[ "def", "mlp", "(", "feature", ",", "hparams", ",", "name", "=", "\"mlp\"", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ",", "\"mlp\"", ",", "values", "=", "[", "feature", "]", ")", ":", "num_mlp_layers", "=", "hparams", ".", "num_mlp_layers", "mlp_dim", "=", "hparams", ".", "mlp_dim", "for", "_", "in", "range", "(", "num_mlp_layers", ")", ":", "feature", "=", "common_layers", ".", "dense", "(", "feature", ",", "mlp_dim", ",", "activation", "=", "tf", ".", "nn", ".", "relu", ")", "feature", "=", "tf", ".", "nn", ".", "dropout", "(", "feature", ",", "keep_prob", "=", "1.", "-", "hparams", ".", "dropout", ")", "return", "feature" ]
Multi layer perceptron with dropout and relu activation.
[ "Multi", "layer", "perceptron", "with", "dropout", "and", "relu", "activation", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/vqa_attention.py#L321-L329
train
tensorflow/tensor2tensor
tensor2tensor/models/research/vqa_attention.py
vqa_attention_base
def vqa_attention_base(): """VQA attention baseline hparams.""" hparams = common_hparams.basic_params1() hparams.batch_size = 128 hparams.use_fixed_batch_size = True, hparams.optimizer = "adam" hparams.optimizer_adam_beta1 = 0.9 hparams.optimizer_adam_beta2 = 0.999 hparams.optimizer_adam_epsilon = 1e-8 hparams.weight_decay = 0. hparams.clip_grad_norm = 0. hparams.initializer = "xavier" hparams.learning_rate = 0.5 hparams.learning_rate_schedule = "legacy" hparams.learning_rate_warmup_steps = 0 hparams.learning_rate_decay_scheme = "exp" hparams.learning_rate_decay_rate = 0.5 hparams.learning_rate_decay_steps = 50000 hparams.dropout = 0.5 hparams.summarize_grads = True hparams.summarize_vars = True # not used hparams hparams.label_smoothing = 0. hparams.multiply_embedding_mode = "" # add new hparams # preprocess hparams.add_hparam("resize_side", 512) hparams.add_hparam("height", 448) hparams.add_hparam("width", 448) hparams.add_hparam("distort", True) hparams.add_hparam("train_resnet", False) hparams.add_hparam("rnn_type", "lstm") hparams.add_hparam("num_rnn_layers", 1) hparams.add_hparam("max_question_length", 15) # lstm hidden size hparams.hidden_size = 512 hparams.add_hparam("attn_dim", 512) hparams.add_hparam("num_glimps", 2) hparams.add_hparam("num_mlp_layers", 1) hparams.add_hparam("mlp_dim", 1024) hparams.add_hparam("image_input_type", "image") hparams.add_hparam("image_model_fn", "resnet_v1_152") hparams.add_hparam("image_feat_size", 0) # self attention parts hparams.norm_type = "layer" hparams.layer_preprocess_sequence = "n" hparams.layer_postprocess_sequence = "da" hparams.layer_prepostprocess_dropout = 0.3 hparams.attention_dropout = 0.1 hparams.relu_dropout = 0.1 hparams.image_hidden_size = 2048 hparams.add_hparam("num_encoder_layers", 1) # Attention-related flags. hparams.add_hparam("num_heads", 8) hparams.add_hparam("attention_key_channels", 0) hparams.add_hparam("attention_value_channels", 0) hparams.add_hparam("image_filter_size", 1024) hparams.add_hparam("self_attention_type", "dot_product") hparams.add_hparam("scale_dotproduct", True) return hparams
python
def vqa_attention_base(): """VQA attention baseline hparams.""" hparams = common_hparams.basic_params1() hparams.batch_size = 128 hparams.use_fixed_batch_size = True, hparams.optimizer = "adam" hparams.optimizer_adam_beta1 = 0.9 hparams.optimizer_adam_beta2 = 0.999 hparams.optimizer_adam_epsilon = 1e-8 hparams.weight_decay = 0. hparams.clip_grad_norm = 0. hparams.initializer = "xavier" hparams.learning_rate = 0.5 hparams.learning_rate_schedule = "legacy" hparams.learning_rate_warmup_steps = 0 hparams.learning_rate_decay_scheme = "exp" hparams.learning_rate_decay_rate = 0.5 hparams.learning_rate_decay_steps = 50000 hparams.dropout = 0.5 hparams.summarize_grads = True hparams.summarize_vars = True # not used hparams hparams.label_smoothing = 0. hparams.multiply_embedding_mode = "" # add new hparams # preprocess hparams.add_hparam("resize_side", 512) hparams.add_hparam("height", 448) hparams.add_hparam("width", 448) hparams.add_hparam("distort", True) hparams.add_hparam("train_resnet", False) hparams.add_hparam("rnn_type", "lstm") hparams.add_hparam("num_rnn_layers", 1) hparams.add_hparam("max_question_length", 15) # lstm hidden size hparams.hidden_size = 512 hparams.add_hparam("attn_dim", 512) hparams.add_hparam("num_glimps", 2) hparams.add_hparam("num_mlp_layers", 1) hparams.add_hparam("mlp_dim", 1024) hparams.add_hparam("image_input_type", "image") hparams.add_hparam("image_model_fn", "resnet_v1_152") hparams.add_hparam("image_feat_size", 0) # self attention parts hparams.norm_type = "layer" hparams.layer_preprocess_sequence = "n" hparams.layer_postprocess_sequence = "da" hparams.layer_prepostprocess_dropout = 0.3 hparams.attention_dropout = 0.1 hparams.relu_dropout = 0.1 hparams.image_hidden_size = 2048 hparams.add_hparam("num_encoder_layers", 1) # Attention-related flags. hparams.add_hparam("num_heads", 8) hparams.add_hparam("attention_key_channels", 0) hparams.add_hparam("attention_value_channels", 0) hparams.add_hparam("image_filter_size", 1024) hparams.add_hparam("self_attention_type", "dot_product") hparams.add_hparam("scale_dotproduct", True) return hparams
[ "def", "vqa_attention_base", "(", ")", ":", "hparams", "=", "common_hparams", ".", "basic_params1", "(", ")", "hparams", ".", "batch_size", "=", "128", "hparams", ".", "use_fixed_batch_size", "=", "True", ",", "hparams", ".", "optimizer", "=", "\"adam\"", "hparams", ".", "optimizer_adam_beta1", "=", "0.9", "hparams", ".", "optimizer_adam_beta2", "=", "0.999", "hparams", ".", "optimizer_adam_epsilon", "=", "1e-8", "hparams", ".", "weight_decay", "=", "0.", "hparams", ".", "clip_grad_norm", "=", "0.", "hparams", ".", "initializer", "=", "\"xavier\"", "hparams", ".", "learning_rate", "=", "0.5", "hparams", ".", "learning_rate_schedule", "=", "\"legacy\"", "hparams", ".", "learning_rate_warmup_steps", "=", "0", "hparams", ".", "learning_rate_decay_scheme", "=", "\"exp\"", "hparams", ".", "learning_rate_decay_rate", "=", "0.5", "hparams", ".", "learning_rate_decay_steps", "=", "50000", "hparams", ".", "dropout", "=", "0.5", "hparams", ".", "summarize_grads", "=", "True", "hparams", ".", "summarize_vars", "=", "True", "# not used hparams", "hparams", ".", "label_smoothing", "=", "0.", "hparams", ".", "multiply_embedding_mode", "=", "\"\"", "# add new hparams", "# preprocess", "hparams", ".", "add_hparam", "(", "\"resize_side\"", ",", "512", ")", "hparams", ".", "add_hparam", "(", "\"height\"", ",", "448", ")", "hparams", ".", "add_hparam", "(", "\"width\"", ",", "448", ")", "hparams", ".", "add_hparam", "(", "\"distort\"", ",", "True", ")", "hparams", ".", "add_hparam", "(", "\"train_resnet\"", ",", "False", ")", "hparams", ".", "add_hparam", "(", "\"rnn_type\"", ",", "\"lstm\"", ")", "hparams", ".", "add_hparam", "(", "\"num_rnn_layers\"", ",", "1", ")", "hparams", ".", "add_hparam", "(", "\"max_question_length\"", ",", "15", ")", "# lstm hidden size", "hparams", ".", "hidden_size", "=", "512", "hparams", ".", "add_hparam", "(", "\"attn_dim\"", ",", "512", ")", "hparams", ".", "add_hparam", "(", "\"num_glimps\"", ",", "2", ")", "hparams", ".", "add_hparam", "(", "\"num_mlp_layers\"", ",", "1", ")", "hparams", ".", "add_hparam", "(", "\"mlp_dim\"", ",", "1024", ")", "hparams", ".", "add_hparam", "(", "\"image_input_type\"", ",", "\"image\"", ")", "hparams", ".", "add_hparam", "(", "\"image_model_fn\"", ",", "\"resnet_v1_152\"", ")", "hparams", ".", "add_hparam", "(", "\"image_feat_size\"", ",", "0", ")", "# self attention parts", "hparams", ".", "norm_type", "=", "\"layer\"", "hparams", ".", "layer_preprocess_sequence", "=", "\"n\"", "hparams", ".", "layer_postprocess_sequence", "=", "\"da\"", "hparams", ".", "layer_prepostprocess_dropout", "=", "0.3", "hparams", ".", "attention_dropout", "=", "0.1", "hparams", ".", "relu_dropout", "=", "0.1", "hparams", ".", "image_hidden_size", "=", "2048", "hparams", ".", "add_hparam", "(", "\"num_encoder_layers\"", ",", "1", ")", "# Attention-related flags.", "hparams", ".", "add_hparam", "(", "\"num_heads\"", ",", "8", ")", "hparams", ".", "add_hparam", "(", "\"attention_key_channels\"", ",", "0", ")", "hparams", ".", "add_hparam", "(", "\"attention_value_channels\"", ",", "0", ")", "hparams", ".", "add_hparam", "(", "\"image_filter_size\"", ",", "1024", ")", "hparams", ".", "add_hparam", "(", "\"self_attention_type\"", ",", "\"dot_product\"", ")", "hparams", ".", "add_hparam", "(", "\"scale_dotproduct\"", ",", "True", ")", "return", "hparams" ]
VQA attention baseline hparams.
[ "VQA", "attention", "baseline", "hparams", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/vqa_attention.py#L333-L400
train
tensorflow/tensor2tensor
tensor2tensor/models/research/vqa_attention.py
vqa_attention_base_range
def vqa_attention_base_range(rhp): """Small range of hyperparameters.""" # After starting from base, set intervals for some parameters. rhp.set_float("learning_rate", 0.1, 1.0, scale=rhp.LOG_SCALE) rhp.set_float("clip_grad_norm", 0.1, 10, scale=rhp.LOG_SCALE) rhp.set_discrete("batch_size", [128, 256, 512, 1024]) rhp.set_float("weight_decay", 0.0, 1e-4) rhp.set_categorical("rnn_type", ["lstm", "lstm_layernorm"])
python
def vqa_attention_base_range(rhp): """Small range of hyperparameters.""" # After starting from base, set intervals for some parameters. rhp.set_float("learning_rate", 0.1, 1.0, scale=rhp.LOG_SCALE) rhp.set_float("clip_grad_norm", 0.1, 10, scale=rhp.LOG_SCALE) rhp.set_discrete("batch_size", [128, 256, 512, 1024]) rhp.set_float("weight_decay", 0.0, 1e-4) rhp.set_categorical("rnn_type", ["lstm", "lstm_layernorm"])
[ "def", "vqa_attention_base_range", "(", "rhp", ")", ":", "# After starting from base, set intervals for some parameters.", "rhp", ".", "set_float", "(", "\"learning_rate\"", ",", "0.1", ",", "1.0", ",", "scale", "=", "rhp", ".", "LOG_SCALE", ")", "rhp", ".", "set_float", "(", "\"clip_grad_norm\"", ",", "0.1", ",", "10", ",", "scale", "=", "rhp", ".", "LOG_SCALE", ")", "rhp", ".", "set_discrete", "(", "\"batch_size\"", ",", "[", "128", ",", "256", ",", "512", ",", "1024", "]", ")", "rhp", ".", "set_float", "(", "\"weight_decay\"", ",", "0.0", ",", "1e-4", ")", "rhp", ".", "set_categorical", "(", "\"rnn_type\"", ",", "[", "\"lstm\"", ",", "\"lstm_layernorm\"", "]", ")" ]
Small range of hyperparameters.
[ "Small", "range", "of", "hyperparameters", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/vqa_attention.py#L580-L587
train
tensorflow/tensor2tensor
tensor2tensor/trax/history.py
History.append
def append(self, mode, metric, step, value): """Append (step, value) pair to history for the given mode and metric.""" if mode not in self._values: self._values[mode] = collections.defaultdict(list) self._values[mode][metric].append((step, value))
python
def append(self, mode, metric, step, value): """Append (step, value) pair to history for the given mode and metric.""" if mode not in self._values: self._values[mode] = collections.defaultdict(list) self._values[mode][metric].append((step, value))
[ "def", "append", "(", "self", ",", "mode", ",", "metric", ",", "step", ",", "value", ")", ":", "if", "mode", "not", "in", "self", ".", "_values", ":", "self", ".", "_values", "[", "mode", "]", "=", "collections", ".", "defaultdict", "(", "list", ")", "self", ".", "_values", "[", "mode", "]", "[", "metric", "]", ".", "append", "(", "(", "step", ",", "value", ")", ")" ]
Append (step, value) pair to history for the given mode and metric.
[ "Append", "(", "step", "value", ")", "pair", "to", "history", "for", "the", "given", "mode", "and", "metric", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/history.py#L52-L56
train
tensorflow/tensor2tensor
tensor2tensor/trax/history.py
History.get
def get(self, mode, metric): """Get the history for the given metric and mode.""" if mode not in self._values: logging.info("Metric %s not found for mode %s", metric, mode) return [] return list(self._values[mode][metric])
python
def get(self, mode, metric): """Get the history for the given metric and mode.""" if mode not in self._values: logging.info("Metric %s not found for mode %s", metric, mode) return [] return list(self._values[mode][metric])
[ "def", "get", "(", "self", ",", "mode", ",", "metric", ")", ":", "if", "mode", "not", "in", "self", ".", "_values", ":", "logging", ".", "info", "(", "\"Metric %s not found for mode %s\"", ",", "metric", ",", "mode", ")", "return", "[", "]", "return", "list", "(", "self", ".", "_values", "[", "mode", "]", "[", "metric", "]", ")" ]
Get the history for the given metric and mode.
[ "Get", "the", "history", "for", "the", "given", "metric", "and", "mode", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/history.py#L58-L63
train
tensorflow/tensor2tensor
tensor2tensor/trax/history.py
History.metrics_for_mode
def metrics_for_mode(self, mode): """Metrics available for a given mode.""" if mode not in self._values: logging.info("Mode %s not found", mode) return [] return sorted(list(self._values[mode].keys()))
python
def metrics_for_mode(self, mode): """Metrics available for a given mode.""" if mode not in self._values: logging.info("Mode %s not found", mode) return [] return sorted(list(self._values[mode].keys()))
[ "def", "metrics_for_mode", "(", "self", ",", "mode", ")", ":", "if", "mode", "not", "in", "self", ".", "_values", ":", "logging", ".", "info", "(", "\"Mode %s not found\"", ",", "mode", ")", "return", "[", "]", "return", "sorted", "(", "list", "(", "self", ".", "_values", "[", "mode", "]", ".", "keys", "(", ")", ")", ")" ]
Metrics available for a given mode.
[ "Metrics", "available", "for", "a", "given", "mode", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/history.py#L70-L75
train
tensorflow/tensor2tensor
tensor2tensor/models/resnet.py
batch_norm_relu
def batch_norm_relu(inputs, is_training, relu=True, init_zero=False, data_format="channels_first"): """Performs a batch normalization followed by a ReLU. Args: inputs: `Tensor` of shape `[batch, channels, ...]`. is_training: `bool` for whether the model is training. relu: `bool` if False, omits the ReLU operation. init_zero: `bool` if True, initializes scale parameter of batch normalization with 0 instead of 1 (default). data_format: `str` either "channels_first" for `[batch, channels, height, width]` or "channels_last for `[batch, height, width, channels]`. Returns: A normalized `Tensor` with the same `data_format`. """ if init_zero: gamma_initializer = tf.zeros_initializer() else: gamma_initializer = tf.ones_initializer() if data_format == "channels_first": axis = 1 else: axis = 3 inputs = layers().BatchNormalization( axis=axis, momentum=BATCH_NORM_DECAY, epsilon=BATCH_NORM_EPSILON, center=True, scale=True, fused=True, gamma_initializer=gamma_initializer)(inputs, training=is_training) if relu: inputs = tf.nn.relu(inputs) return inputs
python
def batch_norm_relu(inputs, is_training, relu=True, init_zero=False, data_format="channels_first"): """Performs a batch normalization followed by a ReLU. Args: inputs: `Tensor` of shape `[batch, channels, ...]`. is_training: `bool` for whether the model is training. relu: `bool` if False, omits the ReLU operation. init_zero: `bool` if True, initializes scale parameter of batch normalization with 0 instead of 1 (default). data_format: `str` either "channels_first" for `[batch, channels, height, width]` or "channels_last for `[batch, height, width, channels]`. Returns: A normalized `Tensor` with the same `data_format`. """ if init_zero: gamma_initializer = tf.zeros_initializer() else: gamma_initializer = tf.ones_initializer() if data_format == "channels_first": axis = 1 else: axis = 3 inputs = layers().BatchNormalization( axis=axis, momentum=BATCH_NORM_DECAY, epsilon=BATCH_NORM_EPSILON, center=True, scale=True, fused=True, gamma_initializer=gamma_initializer)(inputs, training=is_training) if relu: inputs = tf.nn.relu(inputs) return inputs
[ "def", "batch_norm_relu", "(", "inputs", ",", "is_training", ",", "relu", "=", "True", ",", "init_zero", "=", "False", ",", "data_format", "=", "\"channels_first\"", ")", ":", "if", "init_zero", ":", "gamma_initializer", "=", "tf", ".", "zeros_initializer", "(", ")", "else", ":", "gamma_initializer", "=", "tf", ".", "ones_initializer", "(", ")", "if", "data_format", "==", "\"channels_first\"", ":", "axis", "=", "1", "else", ":", "axis", "=", "3", "inputs", "=", "layers", "(", ")", ".", "BatchNormalization", "(", "axis", "=", "axis", ",", "momentum", "=", "BATCH_NORM_DECAY", ",", "epsilon", "=", "BATCH_NORM_EPSILON", ",", "center", "=", "True", ",", "scale", "=", "True", ",", "fused", "=", "True", ",", "gamma_initializer", "=", "gamma_initializer", ")", "(", "inputs", ",", "training", "=", "is_training", ")", "if", "relu", ":", "inputs", "=", "tf", ".", "nn", ".", "relu", "(", "inputs", ")", "return", "inputs" ]
Performs a batch normalization followed by a ReLU. Args: inputs: `Tensor` of shape `[batch, channels, ...]`. is_training: `bool` for whether the model is training. relu: `bool` if False, omits the ReLU operation. init_zero: `bool` if True, initializes scale parameter of batch normalization with 0 instead of 1 (default). data_format: `str` either "channels_first" for `[batch, channels, height, width]` or "channels_last for `[batch, height, width, channels]`. Returns: A normalized `Tensor` with the same `data_format`.
[ "Performs", "a", "batch", "normalization", "followed", "by", "a", "ReLU", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/resnet.py#L41-L81
train
tensorflow/tensor2tensor
tensor2tensor/models/resnet.py
conv2d_fixed_padding
def conv2d_fixed_padding(inputs, filters, kernel_size, strides, data_format="channels_first", use_td=False, targeting_rate=None, keep_prob=None, is_training=None): """Strided 2-D convolution with explicit padding. The padding is consistent and is based only on `kernel_size`, not on the dimensions of `inputs` (as opposed to using `tf.layers.conv2d` alone). Args: inputs: `Tensor` of size `[batch, channels, height_in, width_in]`. filters: `int` number of filters in the convolution. kernel_size: `int` size of the kernel to be used in the convolution. strides: `int` strides of the convolution. data_format: `str` either "channels_first" for `[batch, channels, height, width]` or "channels_last for `[batch, height, width, channels]`. use_td: `str` one of "weight" or "unit". Set to False or "" to disable targeted dropout. targeting_rate: `float` proportion of weights to target with targeted dropout. keep_prob: `float` keep probability for targeted dropout. is_training: `bool` for whether the model is in training. Returns: A `Tensor` of shape `[batch, filters, height_out, width_out]`. Raises: Exception: if use_td is not valid. """ if strides > 1: inputs = fixed_padding(inputs, kernel_size, data_format=data_format) if use_td: inputs_shape = common_layers.shape_list(inputs) if use_td == "weight": if data_format == "channels_last": size = kernel_size * kernel_size * inputs_shape[-1] else: size = kernel_size * kernel_size * inputs_shape[1] targeting_count = targeting_rate * tf.to_float(size) targeting_fn = common_layers.weight_targeting elif use_td == "unit": targeting_count = targeting_rate * filters targeting_fn = common_layers.unit_targeting else: raise Exception("Unrecognized targeted dropout type: %s" % use_td) y = common_layers.td_conv( inputs, filters, kernel_size, targeting_count, targeting_fn, keep_prob, is_training, do_prune=True, strides=strides, padding=("SAME" if strides == 1 else "VALID"), data_format=data_format, use_bias=False, kernel_initializer=tf.variance_scaling_initializer()) else: y = layers().Conv2D( filters=filters, kernel_size=kernel_size, strides=strides, padding=("SAME" if strides == 1 else "VALID"), use_bias=False, kernel_initializer=tf.variance_scaling_initializer(), data_format=data_format)(inputs) return y
python
def conv2d_fixed_padding(inputs, filters, kernel_size, strides, data_format="channels_first", use_td=False, targeting_rate=None, keep_prob=None, is_training=None): """Strided 2-D convolution with explicit padding. The padding is consistent and is based only on `kernel_size`, not on the dimensions of `inputs` (as opposed to using `tf.layers.conv2d` alone). Args: inputs: `Tensor` of size `[batch, channels, height_in, width_in]`. filters: `int` number of filters in the convolution. kernel_size: `int` size of the kernel to be used in the convolution. strides: `int` strides of the convolution. data_format: `str` either "channels_first" for `[batch, channels, height, width]` or "channels_last for `[batch, height, width, channels]`. use_td: `str` one of "weight" or "unit". Set to False or "" to disable targeted dropout. targeting_rate: `float` proportion of weights to target with targeted dropout. keep_prob: `float` keep probability for targeted dropout. is_training: `bool` for whether the model is in training. Returns: A `Tensor` of shape `[batch, filters, height_out, width_out]`. Raises: Exception: if use_td is not valid. """ if strides > 1: inputs = fixed_padding(inputs, kernel_size, data_format=data_format) if use_td: inputs_shape = common_layers.shape_list(inputs) if use_td == "weight": if data_format == "channels_last": size = kernel_size * kernel_size * inputs_shape[-1] else: size = kernel_size * kernel_size * inputs_shape[1] targeting_count = targeting_rate * tf.to_float(size) targeting_fn = common_layers.weight_targeting elif use_td == "unit": targeting_count = targeting_rate * filters targeting_fn = common_layers.unit_targeting else: raise Exception("Unrecognized targeted dropout type: %s" % use_td) y = common_layers.td_conv( inputs, filters, kernel_size, targeting_count, targeting_fn, keep_prob, is_training, do_prune=True, strides=strides, padding=("SAME" if strides == 1 else "VALID"), data_format=data_format, use_bias=False, kernel_initializer=tf.variance_scaling_initializer()) else: y = layers().Conv2D( filters=filters, kernel_size=kernel_size, strides=strides, padding=("SAME" if strides == 1 else "VALID"), use_bias=False, kernel_initializer=tf.variance_scaling_initializer(), data_format=data_format)(inputs) return y
[ "def", "conv2d_fixed_padding", "(", "inputs", ",", "filters", ",", "kernel_size", ",", "strides", ",", "data_format", "=", "\"channels_first\"", ",", "use_td", "=", "False", ",", "targeting_rate", "=", "None", ",", "keep_prob", "=", "None", ",", "is_training", "=", "None", ")", ":", "if", "strides", ">", "1", ":", "inputs", "=", "fixed_padding", "(", "inputs", ",", "kernel_size", ",", "data_format", "=", "data_format", ")", "if", "use_td", ":", "inputs_shape", "=", "common_layers", ".", "shape_list", "(", "inputs", ")", "if", "use_td", "==", "\"weight\"", ":", "if", "data_format", "==", "\"channels_last\"", ":", "size", "=", "kernel_size", "*", "kernel_size", "*", "inputs_shape", "[", "-", "1", "]", "else", ":", "size", "=", "kernel_size", "*", "kernel_size", "*", "inputs_shape", "[", "1", "]", "targeting_count", "=", "targeting_rate", "*", "tf", ".", "to_float", "(", "size", ")", "targeting_fn", "=", "common_layers", ".", "weight_targeting", "elif", "use_td", "==", "\"unit\"", ":", "targeting_count", "=", "targeting_rate", "*", "filters", "targeting_fn", "=", "common_layers", ".", "unit_targeting", "else", ":", "raise", "Exception", "(", "\"Unrecognized targeted dropout type: %s\"", "%", "use_td", ")", "y", "=", "common_layers", ".", "td_conv", "(", "inputs", ",", "filters", ",", "kernel_size", ",", "targeting_count", ",", "targeting_fn", ",", "keep_prob", ",", "is_training", ",", "do_prune", "=", "True", ",", "strides", "=", "strides", ",", "padding", "=", "(", "\"SAME\"", "if", "strides", "==", "1", "else", "\"VALID\"", ")", ",", "data_format", "=", "data_format", ",", "use_bias", "=", "False", ",", "kernel_initializer", "=", "tf", ".", "variance_scaling_initializer", "(", ")", ")", "else", ":", "y", "=", "layers", "(", ")", ".", "Conv2D", "(", "filters", "=", "filters", ",", "kernel_size", "=", "kernel_size", ",", "strides", "=", "strides", ",", "padding", "=", "(", "\"SAME\"", "if", "strides", "==", "1", "else", "\"VALID\"", ")", ",", "use_bias", "=", "False", ",", "kernel_initializer", "=", "tf", ".", "variance_scaling_initializer", "(", ")", ",", "data_format", "=", "data_format", ")", "(", "inputs", ")", "return", "y" ]
Strided 2-D convolution with explicit padding. The padding is consistent and is based only on `kernel_size`, not on the dimensions of `inputs` (as opposed to using `tf.layers.conv2d` alone). Args: inputs: `Tensor` of size `[batch, channels, height_in, width_in]`. filters: `int` number of filters in the convolution. kernel_size: `int` size of the kernel to be used in the convolution. strides: `int` strides of the convolution. data_format: `str` either "channels_first" for `[batch, channels, height, width]` or "channels_last for `[batch, height, width, channels]`. use_td: `str` one of "weight" or "unit". Set to False or "" to disable targeted dropout. targeting_rate: `float` proportion of weights to target with targeted dropout. keep_prob: `float` keep probability for targeted dropout. is_training: `bool` for whether the model is in training. Returns: A `Tensor` of shape `[batch, filters, height_out, width_out]`. Raises: Exception: if use_td is not valid.
[ "Strided", "2", "-", "D", "convolution", "with", "explicit", "padding", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/resnet.py#L112-L188
train
tensorflow/tensor2tensor
tensor2tensor/models/resnet.py
residual_block
def residual_block(inputs, filters, is_training, projection_shortcut, strides, final_block, data_format="channels_first", use_td=False, targeting_rate=None, keep_prob=None): """Standard building block for residual networks with BN before convolutions. Args: inputs: `Tensor` of size `[batch, channels, height, width]`. filters: `int` number of filters for the first two convolutions. Note that the third and final convolution will use 4 times as many filters. is_training: `bool` for whether the model is in training. projection_shortcut: `function` to use for projection shortcuts (typically a 1x1 convolution to match the filter dimensions). If None, no projection is used and the input is passed as unchanged through the shortcut connection. strides: `int` block stride. If greater than 1, this block will ultimately downsample the input. final_block: unused parameter to keep the same function signature as `bottleneck_block`. data_format: `str` either "channels_first" for `[batch, channels, height, width]` or "channels_last for `[batch, height, width, channels]`. use_td: `str` one of "weight" or "unit". Set to False or "" to disable targeted dropout. targeting_rate: `float` proportion of weights to target with targeted dropout. keep_prob: `float` keep probability for targeted dropout. Returns: The output `Tensor` of the block. """ del final_block shortcut = inputs inputs = batch_norm_relu(inputs, is_training, data_format=data_format) if projection_shortcut is not None: shortcut = projection_shortcut(inputs) inputs = conv2d_fixed_padding( inputs=inputs, filters=filters, kernel_size=3, strides=strides, data_format=data_format, use_td=use_td, targeting_rate=targeting_rate, keep_prob=keep_prob, is_training=is_training) inputs = batch_norm_relu(inputs, is_training, data_format=data_format) inputs = conv2d_fixed_padding( inputs=inputs, filters=filters, kernel_size=3, strides=1, data_format=data_format, use_td=use_td, targeting_rate=targeting_rate, keep_prob=keep_prob, is_training=is_training) return inputs + shortcut
python
def residual_block(inputs, filters, is_training, projection_shortcut, strides, final_block, data_format="channels_first", use_td=False, targeting_rate=None, keep_prob=None): """Standard building block for residual networks with BN before convolutions. Args: inputs: `Tensor` of size `[batch, channels, height, width]`. filters: `int` number of filters for the first two convolutions. Note that the third and final convolution will use 4 times as many filters. is_training: `bool` for whether the model is in training. projection_shortcut: `function` to use for projection shortcuts (typically a 1x1 convolution to match the filter dimensions). If None, no projection is used and the input is passed as unchanged through the shortcut connection. strides: `int` block stride. If greater than 1, this block will ultimately downsample the input. final_block: unused parameter to keep the same function signature as `bottleneck_block`. data_format: `str` either "channels_first" for `[batch, channels, height, width]` or "channels_last for `[batch, height, width, channels]`. use_td: `str` one of "weight" or "unit". Set to False or "" to disable targeted dropout. targeting_rate: `float` proportion of weights to target with targeted dropout. keep_prob: `float` keep probability for targeted dropout. Returns: The output `Tensor` of the block. """ del final_block shortcut = inputs inputs = batch_norm_relu(inputs, is_training, data_format=data_format) if projection_shortcut is not None: shortcut = projection_shortcut(inputs) inputs = conv2d_fixed_padding( inputs=inputs, filters=filters, kernel_size=3, strides=strides, data_format=data_format, use_td=use_td, targeting_rate=targeting_rate, keep_prob=keep_prob, is_training=is_training) inputs = batch_norm_relu(inputs, is_training, data_format=data_format) inputs = conv2d_fixed_padding( inputs=inputs, filters=filters, kernel_size=3, strides=1, data_format=data_format, use_td=use_td, targeting_rate=targeting_rate, keep_prob=keep_prob, is_training=is_training) return inputs + shortcut
[ "def", "residual_block", "(", "inputs", ",", "filters", ",", "is_training", ",", "projection_shortcut", ",", "strides", ",", "final_block", ",", "data_format", "=", "\"channels_first\"", ",", "use_td", "=", "False", ",", "targeting_rate", "=", "None", ",", "keep_prob", "=", "None", ")", ":", "del", "final_block", "shortcut", "=", "inputs", "inputs", "=", "batch_norm_relu", "(", "inputs", ",", "is_training", ",", "data_format", "=", "data_format", ")", "if", "projection_shortcut", "is", "not", "None", ":", "shortcut", "=", "projection_shortcut", "(", "inputs", ")", "inputs", "=", "conv2d_fixed_padding", "(", "inputs", "=", "inputs", ",", "filters", "=", "filters", ",", "kernel_size", "=", "3", ",", "strides", "=", "strides", ",", "data_format", "=", "data_format", ",", "use_td", "=", "use_td", ",", "targeting_rate", "=", "targeting_rate", ",", "keep_prob", "=", "keep_prob", ",", "is_training", "=", "is_training", ")", "inputs", "=", "batch_norm_relu", "(", "inputs", ",", "is_training", ",", "data_format", "=", "data_format", ")", "inputs", "=", "conv2d_fixed_padding", "(", "inputs", "=", "inputs", ",", "filters", "=", "filters", ",", "kernel_size", "=", "3", ",", "strides", "=", "1", ",", "data_format", "=", "data_format", ",", "use_td", "=", "use_td", ",", "targeting_rate", "=", "targeting_rate", ",", "keep_prob", "=", "keep_prob", ",", "is_training", "=", "is_training", ")", "return", "inputs", "+", "shortcut" ]
Standard building block for residual networks with BN before convolutions. Args: inputs: `Tensor` of size `[batch, channels, height, width]`. filters: `int` number of filters for the first two convolutions. Note that the third and final convolution will use 4 times as many filters. is_training: `bool` for whether the model is in training. projection_shortcut: `function` to use for projection shortcuts (typically a 1x1 convolution to match the filter dimensions). If None, no projection is used and the input is passed as unchanged through the shortcut connection. strides: `int` block stride. If greater than 1, this block will ultimately downsample the input. final_block: unused parameter to keep the same function signature as `bottleneck_block`. data_format: `str` either "channels_first" for `[batch, channels, height, width]` or "channels_last for `[batch, height, width, channels]`. use_td: `str` one of "weight" or "unit". Set to False or "" to disable targeted dropout. targeting_rate: `float` proportion of weights to target with targeted dropout. keep_prob: `float` keep probability for targeted dropout. Returns: The output `Tensor` of the block.
[ "Standard", "building", "block", "for", "residual", "networks", "with", "BN", "before", "convolutions", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/resnet.py#L191-L257
train
tensorflow/tensor2tensor
tensor2tensor/models/resnet.py
bottleneck_block
def bottleneck_block(inputs, filters, is_training, projection_shortcut, strides, final_block, data_format="channels_first", use_td=False, targeting_rate=None, keep_prob=None): """Bottleneck block variant for residual networks with BN after convolutions. Args: inputs: `Tensor` of size `[batch, channels, height, width]`. filters: `int` number of filters for the first two convolutions. Note that the third and final convolution will use 4 times as many filters. is_training: `bool` for whether the model is in training. projection_shortcut: `function` to use for projection shortcuts (typically a 1x1 convolution to match the filter dimensions). If None, no projection is used and the input is passed as unchanged through the shortcut connection. strides: `int` block stride. If greater than 1, this block will ultimately downsample the input. final_block: `bool` set to True if it is this the final block in the group. This is changes the behavior of batch normalization initialization for the final batch norm in a block. data_format: `str` either "channels_first" for `[batch, channels, height, width]` or "channels_last for `[batch, height, width, channels]`. use_td: `str` one of "weight" or "unit". Set to False or "" to disable targeted dropout. targeting_rate: `float` proportion of weights to target with targeted dropout. keep_prob: `float` keep probability for targeted dropout. Returns: The output `Tensor` of the block. """ # TODO(chrisying): this block is technically the post-activation resnet-v1 # bottleneck unit. Test with v2 (pre-activation) and replace if there is no # difference for consistency. shortcut = inputs if projection_shortcut is not None: shortcut = projection_shortcut(inputs) inputs = conv2d_fixed_padding( inputs=inputs, filters=filters, kernel_size=1, strides=1, data_format=data_format, use_td=use_td, targeting_rate=targeting_rate, keep_prob=keep_prob, is_training=is_training) inputs = batch_norm_relu(inputs, is_training, data_format=data_format) inputs = conv2d_fixed_padding( inputs=inputs, filters=filters, kernel_size=3, strides=strides, data_format=data_format, use_td=use_td, targeting_rate=targeting_rate, keep_prob=keep_prob, is_training=is_training) inputs = batch_norm_relu(inputs, is_training, data_format=data_format) inputs = conv2d_fixed_padding( inputs=inputs, filters=4 * filters, kernel_size=1, strides=1, data_format=data_format, use_td=use_td, targeting_rate=targeting_rate, keep_prob=keep_prob, is_training=is_training) inputs = batch_norm_relu( inputs, is_training, relu=False, init_zero=final_block, data_format=data_format) return tf.nn.relu(inputs + shortcut)
python
def bottleneck_block(inputs, filters, is_training, projection_shortcut, strides, final_block, data_format="channels_first", use_td=False, targeting_rate=None, keep_prob=None): """Bottleneck block variant for residual networks with BN after convolutions. Args: inputs: `Tensor` of size `[batch, channels, height, width]`. filters: `int` number of filters for the first two convolutions. Note that the third and final convolution will use 4 times as many filters. is_training: `bool` for whether the model is in training. projection_shortcut: `function` to use for projection shortcuts (typically a 1x1 convolution to match the filter dimensions). If None, no projection is used and the input is passed as unchanged through the shortcut connection. strides: `int` block stride. If greater than 1, this block will ultimately downsample the input. final_block: `bool` set to True if it is this the final block in the group. This is changes the behavior of batch normalization initialization for the final batch norm in a block. data_format: `str` either "channels_first" for `[batch, channels, height, width]` or "channels_last for `[batch, height, width, channels]`. use_td: `str` one of "weight" or "unit". Set to False or "" to disable targeted dropout. targeting_rate: `float` proportion of weights to target with targeted dropout. keep_prob: `float` keep probability for targeted dropout. Returns: The output `Tensor` of the block. """ # TODO(chrisying): this block is technically the post-activation resnet-v1 # bottleneck unit. Test with v2 (pre-activation) and replace if there is no # difference for consistency. shortcut = inputs if projection_shortcut is not None: shortcut = projection_shortcut(inputs) inputs = conv2d_fixed_padding( inputs=inputs, filters=filters, kernel_size=1, strides=1, data_format=data_format, use_td=use_td, targeting_rate=targeting_rate, keep_prob=keep_prob, is_training=is_training) inputs = batch_norm_relu(inputs, is_training, data_format=data_format) inputs = conv2d_fixed_padding( inputs=inputs, filters=filters, kernel_size=3, strides=strides, data_format=data_format, use_td=use_td, targeting_rate=targeting_rate, keep_prob=keep_prob, is_training=is_training) inputs = batch_norm_relu(inputs, is_training, data_format=data_format) inputs = conv2d_fixed_padding( inputs=inputs, filters=4 * filters, kernel_size=1, strides=1, data_format=data_format, use_td=use_td, targeting_rate=targeting_rate, keep_prob=keep_prob, is_training=is_training) inputs = batch_norm_relu( inputs, is_training, relu=False, init_zero=final_block, data_format=data_format) return tf.nn.relu(inputs + shortcut)
[ "def", "bottleneck_block", "(", "inputs", ",", "filters", ",", "is_training", ",", "projection_shortcut", ",", "strides", ",", "final_block", ",", "data_format", "=", "\"channels_first\"", ",", "use_td", "=", "False", ",", "targeting_rate", "=", "None", ",", "keep_prob", "=", "None", ")", ":", "# TODO(chrisying): this block is technically the post-activation resnet-v1", "# bottleneck unit. Test with v2 (pre-activation) and replace if there is no", "# difference for consistency.", "shortcut", "=", "inputs", "if", "projection_shortcut", "is", "not", "None", ":", "shortcut", "=", "projection_shortcut", "(", "inputs", ")", "inputs", "=", "conv2d_fixed_padding", "(", "inputs", "=", "inputs", ",", "filters", "=", "filters", ",", "kernel_size", "=", "1", ",", "strides", "=", "1", ",", "data_format", "=", "data_format", ",", "use_td", "=", "use_td", ",", "targeting_rate", "=", "targeting_rate", ",", "keep_prob", "=", "keep_prob", ",", "is_training", "=", "is_training", ")", "inputs", "=", "batch_norm_relu", "(", "inputs", ",", "is_training", ",", "data_format", "=", "data_format", ")", "inputs", "=", "conv2d_fixed_padding", "(", "inputs", "=", "inputs", ",", "filters", "=", "filters", ",", "kernel_size", "=", "3", ",", "strides", "=", "strides", ",", "data_format", "=", "data_format", ",", "use_td", "=", "use_td", ",", "targeting_rate", "=", "targeting_rate", ",", "keep_prob", "=", "keep_prob", ",", "is_training", "=", "is_training", ")", "inputs", "=", "batch_norm_relu", "(", "inputs", ",", "is_training", ",", "data_format", "=", "data_format", ")", "inputs", "=", "conv2d_fixed_padding", "(", "inputs", "=", "inputs", ",", "filters", "=", "4", "*", "filters", ",", "kernel_size", "=", "1", ",", "strides", "=", "1", ",", "data_format", "=", "data_format", ",", "use_td", "=", "use_td", ",", "targeting_rate", "=", "targeting_rate", ",", "keep_prob", "=", "keep_prob", ",", "is_training", "=", "is_training", ")", "inputs", "=", "batch_norm_relu", "(", "inputs", ",", "is_training", ",", "relu", "=", "False", ",", "init_zero", "=", "final_block", ",", "data_format", "=", "data_format", ")", "return", "tf", ".", "nn", ".", "relu", "(", "inputs", "+", "shortcut", ")" ]
Bottleneck block variant for residual networks with BN after convolutions. Args: inputs: `Tensor` of size `[batch, channels, height, width]`. filters: `int` number of filters for the first two convolutions. Note that the third and final convolution will use 4 times as many filters. is_training: `bool` for whether the model is in training. projection_shortcut: `function` to use for projection shortcuts (typically a 1x1 convolution to match the filter dimensions). If None, no projection is used and the input is passed as unchanged through the shortcut connection. strides: `int` block stride. If greater than 1, this block will ultimately downsample the input. final_block: `bool` set to True if it is this the final block in the group. This is changes the behavior of batch normalization initialization for the final batch norm in a block. data_format: `str` either "channels_first" for `[batch, channels, height, width]` or "channels_last for `[batch, height, width, channels]`. use_td: `str` one of "weight" or "unit". Set to False or "" to disable targeted dropout. targeting_rate: `float` proportion of weights to target with targeted dropout. keep_prob: `float` keep probability for targeted dropout. Returns: The output `Tensor` of the block.
[ "Bottleneck", "block", "variant", "for", "residual", "networks", "with", "BN", "after", "convolutions", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/resnet.py#L260-L345
train
tensorflow/tensor2tensor
tensor2tensor/models/resnet.py
block_layer
def block_layer(inputs, filters, block_fn, blocks, strides, is_training, name, data_format="channels_first", use_td=False, targeting_rate=None, keep_prob=None): """Creates one layer of blocks for the ResNet model. Args: inputs: `Tensor` of size `[batch, channels, height, width]`. filters: `int` number of filters for the first convolution of the layer. block_fn: `function` for the block to use within the model blocks: `int` number of blocks contained in the layer. strides: `int` stride to use for the first convolution of the layer. If greater than 1, this layer will downsample the input. is_training: `bool` for whether the model is training. name: `str`name for the Tensor output of the block layer. data_format: `str` either "channels_first" for `[batch, channels, height, width]` or "channels_last for `[batch, height, width, channels]`. use_td: `str` one of "weight" or "unit". Set to False or "" to disable targeted dropout. targeting_rate: `float` proportion of weights to target with targeted dropout. keep_prob: `float` keep probability for targeted dropout. Returns: The output `Tensor` of the block layer. """ # Bottleneck blocks end with 4x the number of filters as they start with filters_out = 4 * filters if block_fn is bottleneck_block else filters def projection_shortcut(inputs): """Project identity branch.""" inputs = conv2d_fixed_padding( inputs=inputs, filters=filters_out, kernel_size=1, strides=strides, data_format=data_format, use_td=use_td, targeting_rate=targeting_rate, keep_prob=keep_prob, is_training=is_training) return batch_norm_relu( inputs, is_training, relu=False, data_format=data_format) # Only the first block per block_layer uses projection_shortcut and strides inputs = block_fn( inputs, filters, is_training, projection_shortcut, strides, False, data_format, use_td=use_td, targeting_rate=targeting_rate, keep_prob=keep_prob) for i in range(1, blocks): inputs = block_fn( inputs, filters, is_training, None, 1, (i + 1 == blocks), data_format, use_td=use_td, targeting_rate=targeting_rate, keep_prob=keep_prob) return tf.identity(inputs, name)
python
def block_layer(inputs, filters, block_fn, blocks, strides, is_training, name, data_format="channels_first", use_td=False, targeting_rate=None, keep_prob=None): """Creates one layer of blocks for the ResNet model. Args: inputs: `Tensor` of size `[batch, channels, height, width]`. filters: `int` number of filters for the first convolution of the layer. block_fn: `function` for the block to use within the model blocks: `int` number of blocks contained in the layer. strides: `int` stride to use for the first convolution of the layer. If greater than 1, this layer will downsample the input. is_training: `bool` for whether the model is training. name: `str`name for the Tensor output of the block layer. data_format: `str` either "channels_first" for `[batch, channels, height, width]` or "channels_last for `[batch, height, width, channels]`. use_td: `str` one of "weight" or "unit". Set to False or "" to disable targeted dropout. targeting_rate: `float` proportion of weights to target with targeted dropout. keep_prob: `float` keep probability for targeted dropout. Returns: The output `Tensor` of the block layer. """ # Bottleneck blocks end with 4x the number of filters as they start with filters_out = 4 * filters if block_fn is bottleneck_block else filters def projection_shortcut(inputs): """Project identity branch.""" inputs = conv2d_fixed_padding( inputs=inputs, filters=filters_out, kernel_size=1, strides=strides, data_format=data_format, use_td=use_td, targeting_rate=targeting_rate, keep_prob=keep_prob, is_training=is_training) return batch_norm_relu( inputs, is_training, relu=False, data_format=data_format) # Only the first block per block_layer uses projection_shortcut and strides inputs = block_fn( inputs, filters, is_training, projection_shortcut, strides, False, data_format, use_td=use_td, targeting_rate=targeting_rate, keep_prob=keep_prob) for i in range(1, blocks): inputs = block_fn( inputs, filters, is_training, None, 1, (i + 1 == blocks), data_format, use_td=use_td, targeting_rate=targeting_rate, keep_prob=keep_prob) return tf.identity(inputs, name)
[ "def", "block_layer", "(", "inputs", ",", "filters", ",", "block_fn", ",", "blocks", ",", "strides", ",", "is_training", ",", "name", ",", "data_format", "=", "\"channels_first\"", ",", "use_td", "=", "False", ",", "targeting_rate", "=", "None", ",", "keep_prob", "=", "None", ")", ":", "# Bottleneck blocks end with 4x the number of filters as they start with", "filters_out", "=", "4", "*", "filters", "if", "block_fn", "is", "bottleneck_block", "else", "filters", "def", "projection_shortcut", "(", "inputs", ")", ":", "\"\"\"Project identity branch.\"\"\"", "inputs", "=", "conv2d_fixed_padding", "(", "inputs", "=", "inputs", ",", "filters", "=", "filters_out", ",", "kernel_size", "=", "1", ",", "strides", "=", "strides", ",", "data_format", "=", "data_format", ",", "use_td", "=", "use_td", ",", "targeting_rate", "=", "targeting_rate", ",", "keep_prob", "=", "keep_prob", ",", "is_training", "=", "is_training", ")", "return", "batch_norm_relu", "(", "inputs", ",", "is_training", ",", "relu", "=", "False", ",", "data_format", "=", "data_format", ")", "# Only the first block per block_layer uses projection_shortcut and strides", "inputs", "=", "block_fn", "(", "inputs", ",", "filters", ",", "is_training", ",", "projection_shortcut", ",", "strides", ",", "False", ",", "data_format", ",", "use_td", "=", "use_td", ",", "targeting_rate", "=", "targeting_rate", ",", "keep_prob", "=", "keep_prob", ")", "for", "i", "in", "range", "(", "1", ",", "blocks", ")", ":", "inputs", "=", "block_fn", "(", "inputs", ",", "filters", ",", "is_training", ",", "None", ",", "1", ",", "(", "i", "+", "1", "==", "blocks", ")", ",", "data_format", ",", "use_td", "=", "use_td", ",", "targeting_rate", "=", "targeting_rate", ",", "keep_prob", "=", "keep_prob", ")", "return", "tf", ".", "identity", "(", "inputs", ",", "name", ")" ]
Creates one layer of blocks for the ResNet model. Args: inputs: `Tensor` of size `[batch, channels, height, width]`. filters: `int` number of filters for the first convolution of the layer. block_fn: `function` for the block to use within the model blocks: `int` number of blocks contained in the layer. strides: `int` stride to use for the first convolution of the layer. If greater than 1, this layer will downsample the input. is_training: `bool` for whether the model is training. name: `str`name for the Tensor output of the block layer. data_format: `str` either "channels_first" for `[batch, channels, height, width]` or "channels_last for `[batch, height, width, channels]`. use_td: `str` one of "weight" or "unit". Set to False or "" to disable targeted dropout. targeting_rate: `float` proportion of weights to target with targeted dropout. keep_prob: `float` keep probability for targeted dropout. Returns: The output `Tensor` of the block layer.
[ "Creates", "one", "layer", "of", "blocks", "for", "the", "ResNet", "model", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/resnet.py#L348-L424
train
tensorflow/tensor2tensor
tensor2tensor/models/resnet.py
resnet_v2
def resnet_v2(inputs, block_fn, layer_blocks, filters, data_format="channels_first", is_training=False, is_cifar=False, use_td=False, targeting_rate=None, keep_prob=None): """Resnet model. Args: inputs: `Tensor` images. block_fn: `function` for the block to use within the model. Either `residual_block` or `bottleneck_block`. layer_blocks: list of 3 or 4 `int`s denoting the number of blocks to include in each of the 3 or 4 block groups. Each group consists of blocks that take inputs of the same resolution. filters: list of 4 or 5 `int`s denoting the number of filter to include in block. data_format: `str`, "channels_first" `[batch, channels, height, width]` or "channels_last" `[batch, height, width, channels]`. is_training: bool, build in training mode or not. is_cifar: bool, whether the data is CIFAR or not. use_td: `str` one of "weight" or "unit". Set to False or "" to disable targeted dropout. targeting_rate: `float` proportion of weights to target with targeted dropout. keep_prob: `float` keep probability for targeted dropout. Returns: Pre-logit activations. """ inputs = block_layer( inputs=inputs, filters=filters[1], block_fn=block_fn, blocks=layer_blocks[0], strides=1, is_training=is_training, name="block_layer1", data_format=data_format, use_td=use_td, targeting_rate=targeting_rate, keep_prob=keep_prob) inputs = block_layer( inputs=inputs, filters=filters[2], block_fn=block_fn, blocks=layer_blocks[1], strides=2, is_training=is_training, name="block_layer2", data_format=data_format, use_td=use_td, targeting_rate=targeting_rate, keep_prob=keep_prob) inputs = block_layer( inputs=inputs, filters=filters[3], block_fn=block_fn, blocks=layer_blocks[2], strides=2, is_training=is_training, name="block_layer3", data_format=data_format, use_td=use_td, targeting_rate=targeting_rate, keep_prob=keep_prob) if not is_cifar: inputs = block_layer( inputs=inputs, filters=filters[4], block_fn=block_fn, blocks=layer_blocks[3], strides=2, is_training=is_training, name="block_layer4", data_format=data_format, use_td=use_td, targeting_rate=targeting_rate, keep_prob=keep_prob) return inputs
python
def resnet_v2(inputs, block_fn, layer_blocks, filters, data_format="channels_first", is_training=False, is_cifar=False, use_td=False, targeting_rate=None, keep_prob=None): """Resnet model. Args: inputs: `Tensor` images. block_fn: `function` for the block to use within the model. Either `residual_block` or `bottleneck_block`. layer_blocks: list of 3 or 4 `int`s denoting the number of blocks to include in each of the 3 or 4 block groups. Each group consists of blocks that take inputs of the same resolution. filters: list of 4 or 5 `int`s denoting the number of filter to include in block. data_format: `str`, "channels_first" `[batch, channels, height, width]` or "channels_last" `[batch, height, width, channels]`. is_training: bool, build in training mode or not. is_cifar: bool, whether the data is CIFAR or not. use_td: `str` one of "weight" or "unit". Set to False or "" to disable targeted dropout. targeting_rate: `float` proportion of weights to target with targeted dropout. keep_prob: `float` keep probability for targeted dropout. Returns: Pre-logit activations. """ inputs = block_layer( inputs=inputs, filters=filters[1], block_fn=block_fn, blocks=layer_blocks[0], strides=1, is_training=is_training, name="block_layer1", data_format=data_format, use_td=use_td, targeting_rate=targeting_rate, keep_prob=keep_prob) inputs = block_layer( inputs=inputs, filters=filters[2], block_fn=block_fn, blocks=layer_blocks[1], strides=2, is_training=is_training, name="block_layer2", data_format=data_format, use_td=use_td, targeting_rate=targeting_rate, keep_prob=keep_prob) inputs = block_layer( inputs=inputs, filters=filters[3], block_fn=block_fn, blocks=layer_blocks[2], strides=2, is_training=is_training, name="block_layer3", data_format=data_format, use_td=use_td, targeting_rate=targeting_rate, keep_prob=keep_prob) if not is_cifar: inputs = block_layer( inputs=inputs, filters=filters[4], block_fn=block_fn, blocks=layer_blocks[3], strides=2, is_training=is_training, name="block_layer4", data_format=data_format, use_td=use_td, targeting_rate=targeting_rate, keep_prob=keep_prob) return inputs
[ "def", "resnet_v2", "(", "inputs", ",", "block_fn", ",", "layer_blocks", ",", "filters", ",", "data_format", "=", "\"channels_first\"", ",", "is_training", "=", "False", ",", "is_cifar", "=", "False", ",", "use_td", "=", "False", ",", "targeting_rate", "=", "None", ",", "keep_prob", "=", "None", ")", ":", "inputs", "=", "block_layer", "(", "inputs", "=", "inputs", ",", "filters", "=", "filters", "[", "1", "]", ",", "block_fn", "=", "block_fn", ",", "blocks", "=", "layer_blocks", "[", "0", "]", ",", "strides", "=", "1", ",", "is_training", "=", "is_training", ",", "name", "=", "\"block_layer1\"", ",", "data_format", "=", "data_format", ",", "use_td", "=", "use_td", ",", "targeting_rate", "=", "targeting_rate", ",", "keep_prob", "=", "keep_prob", ")", "inputs", "=", "block_layer", "(", "inputs", "=", "inputs", ",", "filters", "=", "filters", "[", "2", "]", ",", "block_fn", "=", "block_fn", ",", "blocks", "=", "layer_blocks", "[", "1", "]", ",", "strides", "=", "2", ",", "is_training", "=", "is_training", ",", "name", "=", "\"block_layer2\"", ",", "data_format", "=", "data_format", ",", "use_td", "=", "use_td", ",", "targeting_rate", "=", "targeting_rate", ",", "keep_prob", "=", "keep_prob", ")", "inputs", "=", "block_layer", "(", "inputs", "=", "inputs", ",", "filters", "=", "filters", "[", "3", "]", ",", "block_fn", "=", "block_fn", ",", "blocks", "=", "layer_blocks", "[", "2", "]", ",", "strides", "=", "2", ",", "is_training", "=", "is_training", ",", "name", "=", "\"block_layer3\"", ",", "data_format", "=", "data_format", ",", "use_td", "=", "use_td", ",", "targeting_rate", "=", "targeting_rate", ",", "keep_prob", "=", "keep_prob", ")", "if", "not", "is_cifar", ":", "inputs", "=", "block_layer", "(", "inputs", "=", "inputs", ",", "filters", "=", "filters", "[", "4", "]", ",", "block_fn", "=", "block_fn", ",", "blocks", "=", "layer_blocks", "[", "3", "]", ",", "strides", "=", "2", ",", "is_training", "=", "is_training", ",", "name", "=", "\"block_layer4\"", ",", "data_format", "=", "data_format", ",", "use_td", "=", "use_td", ",", "targeting_rate", "=", "targeting_rate", ",", "keep_prob", "=", "keep_prob", ")", "return", "inputs" ]
Resnet model. Args: inputs: `Tensor` images. block_fn: `function` for the block to use within the model. Either `residual_block` or `bottleneck_block`. layer_blocks: list of 3 or 4 `int`s denoting the number of blocks to include in each of the 3 or 4 block groups. Each group consists of blocks that take inputs of the same resolution. filters: list of 4 or 5 `int`s denoting the number of filter to include in block. data_format: `str`, "channels_first" `[batch, channels, height, width]` or "channels_last" `[batch, height, width, channels]`. is_training: bool, build in training mode or not. is_cifar: bool, whether the data is CIFAR or not. use_td: `str` one of "weight" or "unit". Set to False or "" to disable targeted dropout. targeting_rate: `float` proportion of weights to target with targeted dropout. keep_prob: `float` keep probability for targeted dropout. Returns: Pre-logit activations.
[ "Resnet", "model", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/resnet.py#L427-L511
train
tensorflow/tensor2tensor
tensor2tensor/models/resnet.py
resnet_imagenet_34_td_weight_05_05
def resnet_imagenet_34_td_weight_05_05(): """Set of hyperparameters.""" hp = resnet_imagenet_34() hp.use_td = "weight" hp.targeting_rate = 0.5 hp.keep_prob = 0.5 return hp
python
def resnet_imagenet_34_td_weight_05_05(): """Set of hyperparameters.""" hp = resnet_imagenet_34() hp.use_td = "weight" hp.targeting_rate = 0.5 hp.keep_prob = 0.5 return hp
[ "def", "resnet_imagenet_34_td_weight_05_05", "(", ")", ":", "hp", "=", "resnet_imagenet_34", "(", ")", "hp", ".", "use_td", "=", "\"weight\"", "hp", ".", "targeting_rate", "=", "0.5", "hp", ".", "keep_prob", "=", "0.5", "return", "hp" ]
Set of hyperparameters.
[ "Set", "of", "hyperparameters", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/resnet.py#L679-L686
train
tensorflow/tensor2tensor
tensor2tensor/models/resnet.py
resnet_imagenet_34_td_unit_05_05
def resnet_imagenet_34_td_unit_05_05(): """Set of hyperparameters.""" hp = resnet_imagenet_34() hp.use_td = "unit" hp.targeting_rate = 0.5 hp.keep_prob = 0.5 return hp
python
def resnet_imagenet_34_td_unit_05_05(): """Set of hyperparameters.""" hp = resnet_imagenet_34() hp.use_td = "unit" hp.targeting_rate = 0.5 hp.keep_prob = 0.5 return hp
[ "def", "resnet_imagenet_34_td_unit_05_05", "(", ")", ":", "hp", "=", "resnet_imagenet_34", "(", ")", "hp", ".", "use_td", "=", "\"unit\"", "hp", ".", "targeting_rate", "=", "0.5", "hp", ".", "keep_prob", "=", "0.5", "return", "hp" ]
Set of hyperparameters.
[ "Set", "of", "hyperparameters", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/resnet.py#L690-L697
train
tensorflow/tensor2tensor
tensor2tensor/models/resnet.py
resnet_imagenet_34_td_unit_no_drop
def resnet_imagenet_34_td_unit_no_drop(): """Set of hyperparameters.""" hp = resnet_imagenet_34() hp.use_td = "unit" hp.targeting_rate = 0.0 hp.keep_prob = 1.0 return hp
python
def resnet_imagenet_34_td_unit_no_drop(): """Set of hyperparameters.""" hp = resnet_imagenet_34() hp.use_td = "unit" hp.targeting_rate = 0.0 hp.keep_prob = 1.0 return hp
[ "def", "resnet_imagenet_34_td_unit_no_drop", "(", ")", ":", "hp", "=", "resnet_imagenet_34", "(", ")", "hp", ".", "use_td", "=", "\"unit\"", "hp", ".", "targeting_rate", "=", "0.0", "hp", ".", "keep_prob", "=", "1.0", "return", "hp" ]
Set of hyperparameters.
[ "Set", "of", "hyperparameters", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/resnet.py#L701-L708
train
tensorflow/tensor2tensor
tensor2tensor/models/resnet.py
resnet_cifar_15
def resnet_cifar_15(): """Set of hyperparameters.""" hp = resnet_base() hp.block_fn = "residual" hp.is_cifar = True hp.layer_sizes = [2, 2, 2] hp.filter_sizes = [16, 32, 64, 128] return hp
python
def resnet_cifar_15(): """Set of hyperparameters.""" hp = resnet_base() hp.block_fn = "residual" hp.is_cifar = True hp.layer_sizes = [2, 2, 2] hp.filter_sizes = [16, 32, 64, 128] return hp
[ "def", "resnet_cifar_15", "(", ")", ":", "hp", "=", "resnet_base", "(", ")", "hp", ".", "block_fn", "=", "\"residual\"", "hp", ".", "is_cifar", "=", "True", "hp", ".", "layer_sizes", "=", "[", "2", ",", "2", ",", "2", "]", "hp", ".", "filter_sizes", "=", "[", "16", ",", "32", ",", "64", ",", "128", "]", "return", "hp" ]
Set of hyperparameters.
[ "Set", "of", "hyperparameters", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/resnet.py#L719-L727
train
tensorflow/tensor2tensor
tensor2tensor/utils/rouge.py
_len_lcs
def _len_lcs(x, y): """Returns the length of the Longest Common Subsequence between two seqs. Source: http://www.algorithmist.com/index.php/Longest_Common_Subsequence Args: x: sequence of words y: sequence of words Returns integer: Length of LCS between x and y """ table = _lcs(x, y) n, m = len(x), len(y) return table[n, m]
python
def _len_lcs(x, y): """Returns the length of the Longest Common Subsequence between two seqs. Source: http://www.algorithmist.com/index.php/Longest_Common_Subsequence Args: x: sequence of words y: sequence of words Returns integer: Length of LCS between x and y """ table = _lcs(x, y) n, m = len(x), len(y) return table[n, m]
[ "def", "_len_lcs", "(", "x", ",", "y", ")", ":", "table", "=", "_lcs", "(", "x", ",", "y", ")", "n", ",", "m", "=", "len", "(", "x", ")", ",", "len", "(", "y", ")", "return", "table", "[", "n", ",", "m", "]" ]
Returns the length of the Longest Common Subsequence between two seqs. Source: http://www.algorithmist.com/index.php/Longest_Common_Subsequence Args: x: sequence of words y: sequence of words Returns integer: Length of LCS between x and y
[ "Returns", "the", "length", "of", "the", "Longest", "Common", "Subsequence", "between", "two", "seqs", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/rouge.py#L33-L47
train
tensorflow/tensor2tensor
tensor2tensor/utils/rouge.py
_lcs
def _lcs(x, y): """Computes the length of the LCS between two seqs. The implementation below uses a DP programming algorithm and runs in O(nm) time where n = len(x) and m = len(y). Source: http://www.algorithmist.com/index.php/Longest_Common_Subsequence Args: x: collection of words y: collection of words Returns: Table of dictionary of coord and len lcs """ n, m = len(x), len(y) table = {} for i in range(n + 1): for j in range(m + 1): if i == 0 or j == 0: table[i, j] = 0 elif x[i - 1] == y[j - 1]: table[i, j] = table[i - 1, j - 1] + 1 else: table[i, j] = max(table[i - 1, j], table[i, j - 1]) return table
python
def _lcs(x, y): """Computes the length of the LCS between two seqs. The implementation below uses a DP programming algorithm and runs in O(nm) time where n = len(x) and m = len(y). Source: http://www.algorithmist.com/index.php/Longest_Common_Subsequence Args: x: collection of words y: collection of words Returns: Table of dictionary of coord and len lcs """ n, m = len(x), len(y) table = {} for i in range(n + 1): for j in range(m + 1): if i == 0 or j == 0: table[i, j] = 0 elif x[i - 1] == y[j - 1]: table[i, j] = table[i - 1, j - 1] + 1 else: table[i, j] = max(table[i - 1, j], table[i, j - 1]) return table
[ "def", "_lcs", "(", "x", ",", "y", ")", ":", "n", ",", "m", "=", "len", "(", "x", ")", ",", "len", "(", "y", ")", "table", "=", "{", "}", "for", "i", "in", "range", "(", "n", "+", "1", ")", ":", "for", "j", "in", "range", "(", "m", "+", "1", ")", ":", "if", "i", "==", "0", "or", "j", "==", "0", ":", "table", "[", "i", ",", "j", "]", "=", "0", "elif", "x", "[", "i", "-", "1", "]", "==", "y", "[", "j", "-", "1", "]", ":", "table", "[", "i", ",", "j", "]", "=", "table", "[", "i", "-", "1", ",", "j", "-", "1", "]", "+", "1", "else", ":", "table", "[", "i", ",", "j", "]", "=", "max", "(", "table", "[", "i", "-", "1", ",", "j", "]", ",", "table", "[", "i", ",", "j", "-", "1", "]", ")", "return", "table" ]
Computes the length of the LCS between two seqs. The implementation below uses a DP programming algorithm and runs in O(nm) time where n = len(x) and m = len(y). Source: http://www.algorithmist.com/index.php/Longest_Common_Subsequence Args: x: collection of words y: collection of words Returns: Table of dictionary of coord and len lcs
[ "Computes", "the", "length", "of", "the", "LCS", "between", "two", "seqs", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/rouge.py#L50-L74
train
tensorflow/tensor2tensor
tensor2tensor/utils/rouge.py
rouge_l_sentence_level
def rouge_l_sentence_level(eval_sentences, ref_sentences): """Computes ROUGE-L (sentence level) of two collections of sentences. Source: https://www.microsoft.com/en-us/research/publication/ rouge-a-package-for-automatic-evaluation-of-summaries/ Calculated according to: R_lcs = LCS(X,Y)/m P_lcs = LCS(X,Y)/n F_lcs = ((1 + beta^2)*R_lcs*P_lcs) / (R_lcs + (beta^2) * P_lcs) where: X = reference summary Y = Candidate summary m = length of reference summary n = length of candidate summary Args: eval_sentences: The sentences that have been picked by the summarizer ref_sentences: The sentences from the reference set Returns: A float: F_lcs """ f1_scores = [] for eval_sentence, ref_sentence in zip(eval_sentences, ref_sentences): m = len(ref_sentence) n = len(eval_sentence) lcs = _len_lcs(eval_sentence, ref_sentence) f1_scores.append(_f_lcs(lcs, m, n)) return np.mean(f1_scores, dtype=np.float32)
python
def rouge_l_sentence_level(eval_sentences, ref_sentences): """Computes ROUGE-L (sentence level) of two collections of sentences. Source: https://www.microsoft.com/en-us/research/publication/ rouge-a-package-for-automatic-evaluation-of-summaries/ Calculated according to: R_lcs = LCS(X,Y)/m P_lcs = LCS(X,Y)/n F_lcs = ((1 + beta^2)*R_lcs*P_lcs) / (R_lcs + (beta^2) * P_lcs) where: X = reference summary Y = Candidate summary m = length of reference summary n = length of candidate summary Args: eval_sentences: The sentences that have been picked by the summarizer ref_sentences: The sentences from the reference set Returns: A float: F_lcs """ f1_scores = [] for eval_sentence, ref_sentence in zip(eval_sentences, ref_sentences): m = len(ref_sentence) n = len(eval_sentence) lcs = _len_lcs(eval_sentence, ref_sentence) f1_scores.append(_f_lcs(lcs, m, n)) return np.mean(f1_scores, dtype=np.float32)
[ "def", "rouge_l_sentence_level", "(", "eval_sentences", ",", "ref_sentences", ")", ":", "f1_scores", "=", "[", "]", "for", "eval_sentence", ",", "ref_sentence", "in", "zip", "(", "eval_sentences", ",", "ref_sentences", ")", ":", "m", "=", "len", "(", "ref_sentence", ")", "n", "=", "len", "(", "eval_sentence", ")", "lcs", "=", "_len_lcs", "(", "eval_sentence", ",", "ref_sentence", ")", "f1_scores", ".", "append", "(", "_f_lcs", "(", "lcs", ",", "m", ",", "n", ")", ")", "return", "np", ".", "mean", "(", "f1_scores", ",", "dtype", "=", "np", ".", "float32", ")" ]
Computes ROUGE-L (sentence level) of two collections of sentences. Source: https://www.microsoft.com/en-us/research/publication/ rouge-a-package-for-automatic-evaluation-of-summaries/ Calculated according to: R_lcs = LCS(X,Y)/m P_lcs = LCS(X,Y)/n F_lcs = ((1 + beta^2)*R_lcs*P_lcs) / (R_lcs + (beta^2) * P_lcs) where: X = reference summary Y = Candidate summary m = length of reference summary n = length of candidate summary Args: eval_sentences: The sentences that have been picked by the summarizer ref_sentences: The sentences from the reference set Returns: A float: F_lcs
[ "Computes", "ROUGE", "-", "L", "(", "sentence", "level", ")", "of", "two", "collections", "of", "sentences", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/rouge.py#L100-L131
train
tensorflow/tensor2tensor
tensor2tensor/utils/rouge.py
rouge_l_fscore
def rouge_l_fscore(predictions, labels, **unused_kwargs): """ROUGE scores computation between labels and predictions. This is an approximate ROUGE scoring method since we do not glue word pieces or decode the ids and tokenize the output. Args: predictions: tensor, model predictions labels: tensor, gold output. Returns: rouge_l_fscore: approx rouge-l f1 score. """ outputs = tf.to_int32(tf.argmax(predictions, axis=-1)) # Convert the outputs and labels to a [batch_size, input_length] tensor. outputs = tf.squeeze(outputs, axis=[-1, -2]) labels = tf.squeeze(labels, axis=[-1, -2]) rouge_l_f_score = tf.py_func(rouge_l_sentence_level, (outputs, labels), tf.float32) return rouge_l_f_score, tf.constant(1.0)
python
def rouge_l_fscore(predictions, labels, **unused_kwargs): """ROUGE scores computation between labels and predictions. This is an approximate ROUGE scoring method since we do not glue word pieces or decode the ids and tokenize the output. Args: predictions: tensor, model predictions labels: tensor, gold output. Returns: rouge_l_fscore: approx rouge-l f1 score. """ outputs = tf.to_int32(tf.argmax(predictions, axis=-1)) # Convert the outputs and labels to a [batch_size, input_length] tensor. outputs = tf.squeeze(outputs, axis=[-1, -2]) labels = tf.squeeze(labels, axis=[-1, -2]) rouge_l_f_score = tf.py_func(rouge_l_sentence_level, (outputs, labels), tf.float32) return rouge_l_f_score, tf.constant(1.0)
[ "def", "rouge_l_fscore", "(", "predictions", ",", "labels", ",", "*", "*", "unused_kwargs", ")", ":", "outputs", "=", "tf", ".", "to_int32", "(", "tf", ".", "argmax", "(", "predictions", ",", "axis", "=", "-", "1", ")", ")", "# Convert the outputs and labels to a [batch_size, input_length] tensor.", "outputs", "=", "tf", ".", "squeeze", "(", "outputs", ",", "axis", "=", "[", "-", "1", ",", "-", "2", "]", ")", "labels", "=", "tf", ".", "squeeze", "(", "labels", ",", "axis", "=", "[", "-", "1", ",", "-", "2", "]", ")", "rouge_l_f_score", "=", "tf", ".", "py_func", "(", "rouge_l_sentence_level", ",", "(", "outputs", ",", "labels", ")", ",", "tf", ".", "float32", ")", "return", "rouge_l_f_score", ",", "tf", ".", "constant", "(", "1.0", ")" ]
ROUGE scores computation between labels and predictions. This is an approximate ROUGE scoring method since we do not glue word pieces or decode the ids and tokenize the output. Args: predictions: tensor, model predictions labels: tensor, gold output. Returns: rouge_l_fscore: approx rouge-l f1 score.
[ "ROUGE", "scores", "computation", "between", "labels", "and", "predictions", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/rouge.py#L134-L153
train
tensorflow/tensor2tensor
tensor2tensor/utils/rouge.py
_get_ngrams
def _get_ngrams(n, text): """Calculates n-grams. Args: n: which n-grams to calculate text: An array of tokens Returns: A set of n-grams """ ngram_set = set() text_length = len(text) max_index_ngram_start = text_length - n for i in range(max_index_ngram_start + 1): ngram_set.add(tuple(text[i:i + n])) return ngram_set
python
def _get_ngrams(n, text): """Calculates n-grams. Args: n: which n-grams to calculate text: An array of tokens Returns: A set of n-grams """ ngram_set = set() text_length = len(text) max_index_ngram_start = text_length - n for i in range(max_index_ngram_start + 1): ngram_set.add(tuple(text[i:i + n])) return ngram_set
[ "def", "_get_ngrams", "(", "n", ",", "text", ")", ":", "ngram_set", "=", "set", "(", ")", "text_length", "=", "len", "(", "text", ")", "max_index_ngram_start", "=", "text_length", "-", "n", "for", "i", "in", "range", "(", "max_index_ngram_start", "+", "1", ")", ":", "ngram_set", ".", "add", "(", "tuple", "(", "text", "[", "i", ":", "i", "+", "n", "]", ")", ")", "return", "ngram_set" ]
Calculates n-grams. Args: n: which n-grams to calculate text: An array of tokens Returns: A set of n-grams
[ "Calculates", "n", "-", "grams", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/rouge.py#L156-L171
train
tensorflow/tensor2tensor
tensor2tensor/utils/rouge.py
rouge_2_fscore
def rouge_2_fscore(predictions, labels, **unused_kwargs): """ROUGE-2 F1 score computation between labels and predictions. This is an approximate ROUGE scoring method since we do not glue word pieces or decode the ids and tokenize the output. Args: predictions: tensor, model predictions labels: tensor, gold output. Returns: rouge2_fscore: approx rouge-2 f1 score. """ outputs = tf.to_int32(tf.argmax(predictions, axis=-1)) # Convert the outputs and labels to a [batch_size, input_length] tensor. outputs = tf.squeeze(outputs, axis=[-1, -2]) labels = tf.squeeze(labels, axis=[-1, -2]) rouge_2_f_score = tf.py_func(rouge_n, (outputs, labels), tf.float32) return rouge_2_f_score, tf.constant(1.0)
python
def rouge_2_fscore(predictions, labels, **unused_kwargs): """ROUGE-2 F1 score computation between labels and predictions. This is an approximate ROUGE scoring method since we do not glue word pieces or decode the ids and tokenize the output. Args: predictions: tensor, model predictions labels: tensor, gold output. Returns: rouge2_fscore: approx rouge-2 f1 score. """ outputs = tf.to_int32(tf.argmax(predictions, axis=-1)) # Convert the outputs and labels to a [batch_size, input_length] tensor. outputs = tf.squeeze(outputs, axis=[-1, -2]) labels = tf.squeeze(labels, axis=[-1, -2]) rouge_2_f_score = tf.py_func(rouge_n, (outputs, labels), tf.float32) return rouge_2_f_score, tf.constant(1.0)
[ "def", "rouge_2_fscore", "(", "predictions", ",", "labels", ",", "*", "*", "unused_kwargs", ")", ":", "outputs", "=", "tf", ".", "to_int32", "(", "tf", ".", "argmax", "(", "predictions", ",", "axis", "=", "-", "1", ")", ")", "# Convert the outputs and labels to a [batch_size, input_length] tensor.", "outputs", "=", "tf", ".", "squeeze", "(", "outputs", ",", "axis", "=", "[", "-", "1", ",", "-", "2", "]", ")", "labels", "=", "tf", ".", "squeeze", "(", "labels", ",", "axis", "=", "[", "-", "1", ",", "-", "2", "]", ")", "rouge_2_f_score", "=", "tf", ".", "py_func", "(", "rouge_n", ",", "(", "outputs", ",", "labels", ")", ",", "tf", ".", "float32", ")", "return", "rouge_2_f_score", ",", "tf", ".", "constant", "(", "1.0", ")" ]
ROUGE-2 F1 score computation between labels and predictions. This is an approximate ROUGE scoring method since we do not glue word pieces or decode the ids and tokenize the output. Args: predictions: tensor, model predictions labels: tensor, gold output. Returns: rouge2_fscore: approx rouge-2 f1 score.
[ "ROUGE", "-", "2", "F1", "score", "computation", "between", "labels", "and", "predictions", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/rouge.py#L217-L236
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/multi_problem.py
normalize_example_nlp
def normalize_example_nlp(task, example, is_infer, vocab_type, vocab_offset, max_input_length, max_target_length, fixed_train_length): """Normalize the examples from different tasks so they can be merged. This function is specific to NLP tasks and normalizes them so that in the end the example only has "targets" and "task_id". For tasks that originally have inputs, this is done by appending task_id to the inputs and prepending targets, so normalized_targets = inputs task_id targets. For classification tasks, targets are constructed by spelling out the class. Args: task: the Problem class of the task we are normalizing. example: a dictionary of tensors, the example to normalize. is_infer: bool, whether we are performing inference or not. vocab_type: the type of vocabulary in use. vocab_offset: integer, offset index for subword vocabularies. max_input_length: maximum length to cut inputs to. max_target_length: maximum length to cut targets to. fixed_train_length: set length to this size if > 0. Returns: a dictionary of tensors, like example, after normalizing, which in this case means that it only has "targets" and "task_id" as feature. """ if task.has_inputs: example["inputs"] = example["inputs"][:-1] # remove EOS token if hasattr(task, "class_labels"): if vocab_type == text_problems.VocabType.CHARACTER: # TODO(urvashik): handle the case where num_labels > 9 example["targets"] = tf.cast(discretization.int_to_bit( example["targets"], 1, base=10) + 50, tf.int64) example["targets"] = tf.squeeze(example["targets"], axis=[-1]) elif vocab_type == text_problems.VocabType.SUBWORD: example["targets"] = vocab_offset + example["targets"] else: # sequence with inputs and targets eg: summarization if task.has_inputs: if max_input_length > 0: example["inputs"] = example["inputs"][:max_input_length] # Do not truncate targets during inference with beam decoding. if max_target_length > 0 and not is_infer: example["targets"] = example["targets"][:max_target_length] def make_constant_shape(x, size): x = x[:size] xlen = tf.shape(x)[0] x = tf.pad(x, [[0, size - xlen]]) return tf.reshape(x, [size]) if task.has_inputs: if is_infer: concat_list = [example["inputs"], [task.task_id]] example["inputs"] = tf.concat(concat_list, axis=0) else: inputs = example.pop("inputs") concat_list = [inputs, [task.task_id], example["targets"]] example["targets"] = tf.concat(concat_list, axis=0) if fixed_train_length > 0: example["targets"] = make_constant_shape( example["targets"], fixed_train_length) else: concat_list = [[task.task_id], example["targets"]] example["targets"] = tf.concat(concat_list, axis=0) if not is_infer and fixed_train_length > 0: example["targets"] = make_constant_shape( example["targets"], fixed_train_length) example["task_id"] = tf.constant([task.task_id], dtype=tf.int64) return example
python
def normalize_example_nlp(task, example, is_infer, vocab_type, vocab_offset, max_input_length, max_target_length, fixed_train_length): """Normalize the examples from different tasks so they can be merged. This function is specific to NLP tasks and normalizes them so that in the end the example only has "targets" and "task_id". For tasks that originally have inputs, this is done by appending task_id to the inputs and prepending targets, so normalized_targets = inputs task_id targets. For classification tasks, targets are constructed by spelling out the class. Args: task: the Problem class of the task we are normalizing. example: a dictionary of tensors, the example to normalize. is_infer: bool, whether we are performing inference or not. vocab_type: the type of vocabulary in use. vocab_offset: integer, offset index for subword vocabularies. max_input_length: maximum length to cut inputs to. max_target_length: maximum length to cut targets to. fixed_train_length: set length to this size if > 0. Returns: a dictionary of tensors, like example, after normalizing, which in this case means that it only has "targets" and "task_id" as feature. """ if task.has_inputs: example["inputs"] = example["inputs"][:-1] # remove EOS token if hasattr(task, "class_labels"): if vocab_type == text_problems.VocabType.CHARACTER: # TODO(urvashik): handle the case where num_labels > 9 example["targets"] = tf.cast(discretization.int_to_bit( example["targets"], 1, base=10) + 50, tf.int64) example["targets"] = tf.squeeze(example["targets"], axis=[-1]) elif vocab_type == text_problems.VocabType.SUBWORD: example["targets"] = vocab_offset + example["targets"] else: # sequence with inputs and targets eg: summarization if task.has_inputs: if max_input_length > 0: example["inputs"] = example["inputs"][:max_input_length] # Do not truncate targets during inference with beam decoding. if max_target_length > 0 and not is_infer: example["targets"] = example["targets"][:max_target_length] def make_constant_shape(x, size): x = x[:size] xlen = tf.shape(x)[0] x = tf.pad(x, [[0, size - xlen]]) return tf.reshape(x, [size]) if task.has_inputs: if is_infer: concat_list = [example["inputs"], [task.task_id]] example["inputs"] = tf.concat(concat_list, axis=0) else: inputs = example.pop("inputs") concat_list = [inputs, [task.task_id], example["targets"]] example["targets"] = tf.concat(concat_list, axis=0) if fixed_train_length > 0: example["targets"] = make_constant_shape( example["targets"], fixed_train_length) else: concat_list = [[task.task_id], example["targets"]] example["targets"] = tf.concat(concat_list, axis=0) if not is_infer and fixed_train_length > 0: example["targets"] = make_constant_shape( example["targets"], fixed_train_length) example["task_id"] = tf.constant([task.task_id], dtype=tf.int64) return example
[ "def", "normalize_example_nlp", "(", "task", ",", "example", ",", "is_infer", ",", "vocab_type", ",", "vocab_offset", ",", "max_input_length", ",", "max_target_length", ",", "fixed_train_length", ")", ":", "if", "task", ".", "has_inputs", ":", "example", "[", "\"inputs\"", "]", "=", "example", "[", "\"inputs\"", "]", "[", ":", "-", "1", "]", "# remove EOS token", "if", "hasattr", "(", "task", ",", "\"class_labels\"", ")", ":", "if", "vocab_type", "==", "text_problems", ".", "VocabType", ".", "CHARACTER", ":", "# TODO(urvashik): handle the case where num_labels > 9", "example", "[", "\"targets\"", "]", "=", "tf", ".", "cast", "(", "discretization", ".", "int_to_bit", "(", "example", "[", "\"targets\"", "]", ",", "1", ",", "base", "=", "10", ")", "+", "50", ",", "tf", ".", "int64", ")", "example", "[", "\"targets\"", "]", "=", "tf", ".", "squeeze", "(", "example", "[", "\"targets\"", "]", ",", "axis", "=", "[", "-", "1", "]", ")", "elif", "vocab_type", "==", "text_problems", ".", "VocabType", ".", "SUBWORD", ":", "example", "[", "\"targets\"", "]", "=", "vocab_offset", "+", "example", "[", "\"targets\"", "]", "else", ":", "# sequence with inputs and targets eg: summarization", "if", "task", ".", "has_inputs", ":", "if", "max_input_length", ">", "0", ":", "example", "[", "\"inputs\"", "]", "=", "example", "[", "\"inputs\"", "]", "[", ":", "max_input_length", "]", "# Do not truncate targets during inference with beam decoding.", "if", "max_target_length", ">", "0", "and", "not", "is_infer", ":", "example", "[", "\"targets\"", "]", "=", "example", "[", "\"targets\"", "]", "[", ":", "max_target_length", "]", "def", "make_constant_shape", "(", "x", ",", "size", ")", ":", "x", "=", "x", "[", ":", "size", "]", "xlen", "=", "tf", ".", "shape", "(", "x", ")", "[", "0", "]", "x", "=", "tf", ".", "pad", "(", "x", ",", "[", "[", "0", ",", "size", "-", "xlen", "]", "]", ")", "return", "tf", ".", "reshape", "(", "x", ",", "[", "size", "]", ")", "if", "task", ".", "has_inputs", ":", "if", "is_infer", ":", "concat_list", "=", "[", "example", "[", "\"inputs\"", "]", ",", "[", "task", ".", "task_id", "]", "]", "example", "[", "\"inputs\"", "]", "=", "tf", ".", "concat", "(", "concat_list", ",", "axis", "=", "0", ")", "else", ":", "inputs", "=", "example", ".", "pop", "(", "\"inputs\"", ")", "concat_list", "=", "[", "inputs", ",", "[", "task", ".", "task_id", "]", ",", "example", "[", "\"targets\"", "]", "]", "example", "[", "\"targets\"", "]", "=", "tf", ".", "concat", "(", "concat_list", ",", "axis", "=", "0", ")", "if", "fixed_train_length", ">", "0", ":", "example", "[", "\"targets\"", "]", "=", "make_constant_shape", "(", "example", "[", "\"targets\"", "]", ",", "fixed_train_length", ")", "else", ":", "concat_list", "=", "[", "[", "task", ".", "task_id", "]", ",", "example", "[", "\"targets\"", "]", "]", "example", "[", "\"targets\"", "]", "=", "tf", ".", "concat", "(", "concat_list", ",", "axis", "=", "0", ")", "if", "not", "is_infer", "and", "fixed_train_length", ">", "0", ":", "example", "[", "\"targets\"", "]", "=", "make_constant_shape", "(", "example", "[", "\"targets\"", "]", ",", "fixed_train_length", ")", "example", "[", "\"task_id\"", "]", "=", "tf", ".", "constant", "(", "[", "task", ".", "task_id", "]", ",", "dtype", "=", "tf", ".", "int64", ")", "return", "example" ]
Normalize the examples from different tasks so they can be merged. This function is specific to NLP tasks and normalizes them so that in the end the example only has "targets" and "task_id". For tasks that originally have inputs, this is done by appending task_id to the inputs and prepending targets, so normalized_targets = inputs task_id targets. For classification tasks, targets are constructed by spelling out the class. Args: task: the Problem class of the task we are normalizing. example: a dictionary of tensors, the example to normalize. is_infer: bool, whether we are performing inference or not. vocab_type: the type of vocabulary in use. vocab_offset: integer, offset index for subword vocabularies. max_input_length: maximum length to cut inputs to. max_target_length: maximum length to cut targets to. fixed_train_length: set length to this size if > 0. Returns: a dictionary of tensors, like example, after normalizing, which in this case means that it only has "targets" and "task_id" as feature.
[ "Normalize", "the", "examples", "from", "different", "tasks", "so", "they", "can", "be", "merged", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/multi_problem.py#L38-L108
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/multi_problem.py
flatten_zip_dataset
def flatten_zip_dataset(*args): """A list of examples to a dataset containing mixed examples. Given a list of `n` dataset examples, flatten them by converting each element into a dataset and concatenating them to convert into a single dataset. Args: *args: A list containing one example each from `n` different datasets. Returns: flattened: A new dataset containing the examples from the list as part of a single dataset. """ flattened = tf.data.Dataset.from_tensors(args[0]) for ex in args[1:]: flattened = flattened.concatenate(tf.data.Dataset.from_tensors(ex)) return flattened
python
def flatten_zip_dataset(*args): """A list of examples to a dataset containing mixed examples. Given a list of `n` dataset examples, flatten them by converting each element into a dataset and concatenating them to convert into a single dataset. Args: *args: A list containing one example each from `n` different datasets. Returns: flattened: A new dataset containing the examples from the list as part of a single dataset. """ flattened = tf.data.Dataset.from_tensors(args[0]) for ex in args[1:]: flattened = flattened.concatenate(tf.data.Dataset.from_tensors(ex)) return flattened
[ "def", "flatten_zip_dataset", "(", "*", "args", ")", ":", "flattened", "=", "tf", ".", "data", ".", "Dataset", ".", "from_tensors", "(", "args", "[", "0", "]", ")", "for", "ex", "in", "args", "[", "1", ":", "]", ":", "flattened", "=", "flattened", ".", "concatenate", "(", "tf", ".", "data", ".", "Dataset", ".", "from_tensors", "(", "ex", ")", ")", "return", "flattened" ]
A list of examples to a dataset containing mixed examples. Given a list of `n` dataset examples, flatten them by converting each element into a dataset and concatenating them to convert into a single dataset. Args: *args: A list containing one example each from `n` different datasets. Returns: flattened: A new dataset containing the examples from the list as part of a single dataset.
[ "A", "list", "of", "examples", "to", "a", "dataset", "containing", "mixed", "examples", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/multi_problem.py#L111-L128
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/multi_problem.py
aggregate_task_losses
def aggregate_task_losses(hparams, problem_hparams, logits, feature_name, feature): """Multiproblem loss function.""" # If no reweighting, we want the default loss to mimic the LM loss. if not hparams.multiproblem_reweight_label_loss: return aggregate_task_lm_losses(hparams=hparams, problem_hparams=problem_hparams, logits=logits, feature_name=feature_name, feature=feature) summaries = [] main_task_id = hparams.problem.task_list[0].task_id vocab_size = problem_hparams.vocab_size[feature_name] if vocab_size is not None and hasattr(hparams, "vocab_divisor"): vocab_size += (-vocab_size) % hparams.vocab_divisor modality = problem_hparams.modality[feature_name] loss = hparams.loss.get(feature_name, modalities.get_loss(modality)) weights_fn = hparams.weights_fn.get( feature_name, modalities.get_weights_fn(modality)) # Primary task loss loss_num, loss_den = loss( logits, feature, lambda x: common_layers.weights_multi_problem_all(x, main_task_id), hparams, vocab_size, weights_fn) loss_val = loss_num / tf.maximum(1.0, loss_den) summaries.append([hparams.problem.task_list[0].name+"_loss", loss_val]) # Since the losses may undergo rescaling, they cannot exist as separate # numerators and denominators. Set the denominators to 1 in order to faciliate # loss averaging. loss_num = loss_val loss_den = tf.minimum(tf.convert_to_tensor(1, dtype=tf.float32), loss_den) for task in hparams.problem.task_list[1:]: # Loss only from the input sequence -- the auxiliary LM loss. seq_loss_num, seq_loss_den = loss( logits, feature, lambda x: common_layers.weights_multi_problem_input(x, task.task_id), # pylint: disable=cell-var-from-loop hparams, vocab_size) seq_loss_num *= problem_hparams.loss_multiplier # Unscaled sequence loss. seq_loss = seq_loss_num / tf.maximum(1.0, seq_loss_den) summaries.append([task.name+"_seq_loss", seq_loss]) if hasattr(task, "num_classes"): # Loss only from the classification label. label_loss_num, label_loss_den = loss( logits, feature, lambda x: common_layers.weights_multi_problem(x, task.task_id), # pylint: disable=cell-var-from-loop hparams, vocab_size) label_loss_num *= problem_hparams.loss_multiplier # Unscaled classification label loss. label_loss = label_loss_num / tf.maximum(1.0, label_loss_den) summaries.append([task.name+"_label_loss", label_loss]) # Scaling. if hparams.multiproblem_reweight_label_loss: label_loss *= hparams.multiproblem_label_weight seq_loss *= (1 - hparams.multiproblem_label_weight) # This is the training loss for the optimizer after scaling. task_loss_val = seq_loss + label_loss loss_den_ = label_loss_den else: # Loss only from the target sequence. target_loss_num, target_loss_den = loss( logits, feature, lambda x: common_layers.weights_multi_problem(x, task.task_id), # pylint: disable=cell-var-from-loop hparams, vocab_size) target_loss_num *= problem_hparams.loss_multiplier # Unscaled target sequence loss. target_loss = target_loss_num / tf.maximum(1.0, target_loss_den) summaries.append([task.name+"_target_loss", target_loss]) # Scaling. if hparams.multiproblem_reweight_label_loss: target_loss *= hparams.multiproblem_label_weight seq_loss *= (1 - hparams.multiproblem_label_weight) # This is the training loss for the optimizer after all the scaling. task_loss_val = seq_loss + target_loss loss_den_ = target_loss_den summaries.append([task.name+"_loss", task_loss_val]) # Adding 1 to the loss den for each task leads to averaging task losses. # TODO(urvashik): Fix combination with other task losses - weighted # average based on the number of examples from that task. loss_num += task_loss_val loss_den += tf.minimum(tf.convert_to_tensor(1, dtype=tf.float32), loss_den_) return loss_num, loss_den, summaries
python
def aggregate_task_losses(hparams, problem_hparams, logits, feature_name, feature): """Multiproblem loss function.""" # If no reweighting, we want the default loss to mimic the LM loss. if not hparams.multiproblem_reweight_label_loss: return aggregate_task_lm_losses(hparams=hparams, problem_hparams=problem_hparams, logits=logits, feature_name=feature_name, feature=feature) summaries = [] main_task_id = hparams.problem.task_list[0].task_id vocab_size = problem_hparams.vocab_size[feature_name] if vocab_size is not None and hasattr(hparams, "vocab_divisor"): vocab_size += (-vocab_size) % hparams.vocab_divisor modality = problem_hparams.modality[feature_name] loss = hparams.loss.get(feature_name, modalities.get_loss(modality)) weights_fn = hparams.weights_fn.get( feature_name, modalities.get_weights_fn(modality)) # Primary task loss loss_num, loss_den = loss( logits, feature, lambda x: common_layers.weights_multi_problem_all(x, main_task_id), hparams, vocab_size, weights_fn) loss_val = loss_num / tf.maximum(1.0, loss_den) summaries.append([hparams.problem.task_list[0].name+"_loss", loss_val]) # Since the losses may undergo rescaling, they cannot exist as separate # numerators and denominators. Set the denominators to 1 in order to faciliate # loss averaging. loss_num = loss_val loss_den = tf.minimum(tf.convert_to_tensor(1, dtype=tf.float32), loss_den) for task in hparams.problem.task_list[1:]: # Loss only from the input sequence -- the auxiliary LM loss. seq_loss_num, seq_loss_den = loss( logits, feature, lambda x: common_layers.weights_multi_problem_input(x, task.task_id), # pylint: disable=cell-var-from-loop hparams, vocab_size) seq_loss_num *= problem_hparams.loss_multiplier # Unscaled sequence loss. seq_loss = seq_loss_num / tf.maximum(1.0, seq_loss_den) summaries.append([task.name+"_seq_loss", seq_loss]) if hasattr(task, "num_classes"): # Loss only from the classification label. label_loss_num, label_loss_den = loss( logits, feature, lambda x: common_layers.weights_multi_problem(x, task.task_id), # pylint: disable=cell-var-from-loop hparams, vocab_size) label_loss_num *= problem_hparams.loss_multiplier # Unscaled classification label loss. label_loss = label_loss_num / tf.maximum(1.0, label_loss_den) summaries.append([task.name+"_label_loss", label_loss]) # Scaling. if hparams.multiproblem_reweight_label_loss: label_loss *= hparams.multiproblem_label_weight seq_loss *= (1 - hparams.multiproblem_label_weight) # This is the training loss for the optimizer after scaling. task_loss_val = seq_loss + label_loss loss_den_ = label_loss_den else: # Loss only from the target sequence. target_loss_num, target_loss_den = loss( logits, feature, lambda x: common_layers.weights_multi_problem(x, task.task_id), # pylint: disable=cell-var-from-loop hparams, vocab_size) target_loss_num *= problem_hparams.loss_multiplier # Unscaled target sequence loss. target_loss = target_loss_num / tf.maximum(1.0, target_loss_den) summaries.append([task.name+"_target_loss", target_loss]) # Scaling. if hparams.multiproblem_reweight_label_loss: target_loss *= hparams.multiproblem_label_weight seq_loss *= (1 - hparams.multiproblem_label_weight) # This is the training loss for the optimizer after all the scaling. task_loss_val = seq_loss + target_loss loss_den_ = target_loss_den summaries.append([task.name+"_loss", task_loss_val]) # Adding 1 to the loss den for each task leads to averaging task losses. # TODO(urvashik): Fix combination with other task losses - weighted # average based on the number of examples from that task. loss_num += task_loss_val loss_den += tf.minimum(tf.convert_to_tensor(1, dtype=tf.float32), loss_den_) return loss_num, loss_den, summaries
[ "def", "aggregate_task_losses", "(", "hparams", ",", "problem_hparams", ",", "logits", ",", "feature_name", ",", "feature", ")", ":", "# If no reweighting, we want the default loss to mimic the LM loss.", "if", "not", "hparams", ".", "multiproblem_reweight_label_loss", ":", "return", "aggregate_task_lm_losses", "(", "hparams", "=", "hparams", ",", "problem_hparams", "=", "problem_hparams", ",", "logits", "=", "logits", ",", "feature_name", "=", "feature_name", ",", "feature", "=", "feature", ")", "summaries", "=", "[", "]", "main_task_id", "=", "hparams", ".", "problem", ".", "task_list", "[", "0", "]", ".", "task_id", "vocab_size", "=", "problem_hparams", ".", "vocab_size", "[", "feature_name", "]", "if", "vocab_size", "is", "not", "None", "and", "hasattr", "(", "hparams", ",", "\"vocab_divisor\"", ")", ":", "vocab_size", "+=", "(", "-", "vocab_size", ")", "%", "hparams", ".", "vocab_divisor", "modality", "=", "problem_hparams", ".", "modality", "[", "feature_name", "]", "loss", "=", "hparams", ".", "loss", ".", "get", "(", "feature_name", ",", "modalities", ".", "get_loss", "(", "modality", ")", ")", "weights_fn", "=", "hparams", ".", "weights_fn", ".", "get", "(", "feature_name", ",", "modalities", ".", "get_weights_fn", "(", "modality", ")", ")", "# Primary task loss", "loss_num", ",", "loss_den", "=", "loss", "(", "logits", ",", "feature", ",", "lambda", "x", ":", "common_layers", ".", "weights_multi_problem_all", "(", "x", ",", "main_task_id", ")", ",", "hparams", ",", "vocab_size", ",", "weights_fn", ")", "loss_val", "=", "loss_num", "/", "tf", ".", "maximum", "(", "1.0", ",", "loss_den", ")", "summaries", ".", "append", "(", "[", "hparams", ".", "problem", ".", "task_list", "[", "0", "]", ".", "name", "+", "\"_loss\"", ",", "loss_val", "]", ")", "# Since the losses may undergo rescaling, they cannot exist as separate", "# numerators and denominators. Set the denominators to 1 in order to faciliate", "# loss averaging.", "loss_num", "=", "loss_val", "loss_den", "=", "tf", ".", "minimum", "(", "tf", ".", "convert_to_tensor", "(", "1", ",", "dtype", "=", "tf", ".", "float32", ")", ",", "loss_den", ")", "for", "task", "in", "hparams", ".", "problem", ".", "task_list", "[", "1", ":", "]", ":", "# Loss only from the input sequence -- the auxiliary LM loss.", "seq_loss_num", ",", "seq_loss_den", "=", "loss", "(", "logits", ",", "feature", ",", "lambda", "x", ":", "common_layers", ".", "weights_multi_problem_input", "(", "x", ",", "task", ".", "task_id", ")", ",", "# pylint: disable=cell-var-from-loop", "hparams", ",", "vocab_size", ")", "seq_loss_num", "*=", "problem_hparams", ".", "loss_multiplier", "# Unscaled sequence loss.", "seq_loss", "=", "seq_loss_num", "/", "tf", ".", "maximum", "(", "1.0", ",", "seq_loss_den", ")", "summaries", ".", "append", "(", "[", "task", ".", "name", "+", "\"_seq_loss\"", ",", "seq_loss", "]", ")", "if", "hasattr", "(", "task", ",", "\"num_classes\"", ")", ":", "# Loss only from the classification label.", "label_loss_num", ",", "label_loss_den", "=", "loss", "(", "logits", ",", "feature", ",", "lambda", "x", ":", "common_layers", ".", "weights_multi_problem", "(", "x", ",", "task", ".", "task_id", ")", ",", "# pylint: disable=cell-var-from-loop", "hparams", ",", "vocab_size", ")", "label_loss_num", "*=", "problem_hparams", ".", "loss_multiplier", "# Unscaled classification label loss.", "label_loss", "=", "label_loss_num", "/", "tf", ".", "maximum", "(", "1.0", ",", "label_loss_den", ")", "summaries", ".", "append", "(", "[", "task", ".", "name", "+", "\"_label_loss\"", ",", "label_loss", "]", ")", "# Scaling.", "if", "hparams", ".", "multiproblem_reweight_label_loss", ":", "label_loss", "*=", "hparams", ".", "multiproblem_label_weight", "seq_loss", "*=", "(", "1", "-", "hparams", ".", "multiproblem_label_weight", ")", "# This is the training loss for the optimizer after scaling.", "task_loss_val", "=", "seq_loss", "+", "label_loss", "loss_den_", "=", "label_loss_den", "else", ":", "# Loss only from the target sequence.", "target_loss_num", ",", "target_loss_den", "=", "loss", "(", "logits", ",", "feature", ",", "lambda", "x", ":", "common_layers", ".", "weights_multi_problem", "(", "x", ",", "task", ".", "task_id", ")", ",", "# pylint: disable=cell-var-from-loop", "hparams", ",", "vocab_size", ")", "target_loss_num", "*=", "problem_hparams", ".", "loss_multiplier", "# Unscaled target sequence loss.", "target_loss", "=", "target_loss_num", "/", "tf", ".", "maximum", "(", "1.0", ",", "target_loss_den", ")", "summaries", ".", "append", "(", "[", "task", ".", "name", "+", "\"_target_loss\"", ",", "target_loss", "]", ")", "# Scaling.", "if", "hparams", ".", "multiproblem_reweight_label_loss", ":", "target_loss", "*=", "hparams", ".", "multiproblem_label_weight", "seq_loss", "*=", "(", "1", "-", "hparams", ".", "multiproblem_label_weight", ")", "# This is the training loss for the optimizer after all the scaling.", "task_loss_val", "=", "seq_loss", "+", "target_loss", "loss_den_", "=", "target_loss_den", "summaries", ".", "append", "(", "[", "task", ".", "name", "+", "\"_loss\"", ",", "task_loss_val", "]", ")", "# Adding 1 to the loss den for each task leads to averaging task losses.", "# TODO(urvashik): Fix combination with other task losses - weighted", "# average based on the number of examples from that task.", "loss_num", "+=", "task_loss_val", "loss_den", "+=", "tf", ".", "minimum", "(", "tf", ".", "convert_to_tensor", "(", "1", ",", "dtype", "=", "tf", ".", "float32", ")", ",", "loss_den_", ")", "return", "loss_num", ",", "loss_den", ",", "summaries" ]
Multiproblem loss function.
[ "Multiproblem", "loss", "function", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/multi_problem.py#L419-L522
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/multi_problem.py
aggregate_task_lm_losses
def aggregate_task_lm_losses(hparams, problem_hparams, logits, feature_name, feature): """LM loss for multiproblems.""" summaries = [] vocab_size = problem_hparams.vocab_size[feature_name] if vocab_size is not None and hasattr(hparams, "vocab_divisor"): vocab_size += (-vocab_size) % hparams.vocab_divisor modality = problem_hparams.modality[feature_name] loss = hparams.loss.get(feature_name, modalities.get_loss(modality)) weights_fn = hparams.weights_fn.get( feature_name, modalities.get_weights_fn(modality)) loss_num = 0. loss_den = 0. for task in hparams.problem.task_list: loss_num_, loss_den_ = loss( logits, feature, lambda x: common_layers.weights_multi_problem_all(x, task.task_id), # pylint: disable=cell-var-from-loop hparams, vocab_size, weights_fn) loss_num += loss_num_ loss_den += loss_den_ loss_val = loss_num_ / tf.maximum(1.0, loss_den_) summaries.append([task.name+"_loss", loss_val]) return loss_num, loss_den, summaries
python
def aggregate_task_lm_losses(hparams, problem_hparams, logits, feature_name, feature): """LM loss for multiproblems.""" summaries = [] vocab_size = problem_hparams.vocab_size[feature_name] if vocab_size is not None and hasattr(hparams, "vocab_divisor"): vocab_size += (-vocab_size) % hparams.vocab_divisor modality = problem_hparams.modality[feature_name] loss = hparams.loss.get(feature_name, modalities.get_loss(modality)) weights_fn = hparams.weights_fn.get( feature_name, modalities.get_weights_fn(modality)) loss_num = 0. loss_den = 0. for task in hparams.problem.task_list: loss_num_, loss_den_ = loss( logits, feature, lambda x: common_layers.weights_multi_problem_all(x, task.task_id), # pylint: disable=cell-var-from-loop hparams, vocab_size, weights_fn) loss_num += loss_num_ loss_den += loss_den_ loss_val = loss_num_ / tf.maximum(1.0, loss_den_) summaries.append([task.name+"_loss", loss_val]) return loss_num, loss_den, summaries
[ "def", "aggregate_task_lm_losses", "(", "hparams", ",", "problem_hparams", ",", "logits", ",", "feature_name", ",", "feature", ")", ":", "summaries", "=", "[", "]", "vocab_size", "=", "problem_hparams", ".", "vocab_size", "[", "feature_name", "]", "if", "vocab_size", "is", "not", "None", "and", "hasattr", "(", "hparams", ",", "\"vocab_divisor\"", ")", ":", "vocab_size", "+=", "(", "-", "vocab_size", ")", "%", "hparams", ".", "vocab_divisor", "modality", "=", "problem_hparams", ".", "modality", "[", "feature_name", "]", "loss", "=", "hparams", ".", "loss", ".", "get", "(", "feature_name", ",", "modalities", ".", "get_loss", "(", "modality", ")", ")", "weights_fn", "=", "hparams", ".", "weights_fn", ".", "get", "(", "feature_name", ",", "modalities", ".", "get_weights_fn", "(", "modality", ")", ")", "loss_num", "=", "0.", "loss_den", "=", "0.", "for", "task", "in", "hparams", ".", "problem", ".", "task_list", ":", "loss_num_", ",", "loss_den_", "=", "loss", "(", "logits", ",", "feature", ",", "lambda", "x", ":", "common_layers", ".", "weights_multi_problem_all", "(", "x", ",", "task", ".", "task_id", ")", ",", "# pylint: disable=cell-var-from-loop", "hparams", ",", "vocab_size", ",", "weights_fn", ")", "loss_num", "+=", "loss_num_", "loss_den", "+=", "loss_den_", "loss_val", "=", "loss_num_", "/", "tf", ".", "maximum", "(", "1.0", ",", "loss_den_", ")", "summaries", ".", "append", "(", "[", "task", ".", "name", "+", "\"_loss\"", ",", "loss_val", "]", ")", "return", "loss_num", ",", "loss_den", ",", "summaries" ]
LM loss for multiproblems.
[ "LM", "loss", "for", "multiproblems", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/multi_problem.py#L525-L553
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/multi_problem.py
MultiProblem.normalize_example
def normalize_example(self, task, example, encoder, hparams, is_infer): """Normalize the examples from different tasks so they can be merged.""" # Here we use the default function for NLP tasks that makes everything # a part of "targets" feature. Override in your subclasses for other uses. vocab_offset = encoder.vocab_size + len(self.task_list) return normalize_example_nlp( task, example, is_infer, self.vocab_type, vocab_offset, hparams.multiproblem_max_input_length, hparams.multiproblem_max_target_length, hparams.multiproblem_fixed_train_length)
python
def normalize_example(self, task, example, encoder, hparams, is_infer): """Normalize the examples from different tasks so they can be merged.""" # Here we use the default function for NLP tasks that makes everything # a part of "targets" feature. Override in your subclasses for other uses. vocab_offset = encoder.vocab_size + len(self.task_list) return normalize_example_nlp( task, example, is_infer, self.vocab_type, vocab_offset, hparams.multiproblem_max_input_length, hparams.multiproblem_max_target_length, hparams.multiproblem_fixed_train_length)
[ "def", "normalize_example", "(", "self", ",", "task", ",", "example", ",", "encoder", ",", "hparams", ",", "is_infer", ")", ":", "# Here we use the default function for NLP tasks that makes everything", "# a part of \"targets\" feature. Override in your subclasses for other uses.", "vocab_offset", "=", "encoder", ".", "vocab_size", "+", "len", "(", "self", ".", "task_list", ")", "return", "normalize_example_nlp", "(", "task", ",", "example", ",", "is_infer", ",", "self", ".", "vocab_type", ",", "vocab_offset", ",", "hparams", ".", "multiproblem_max_input_length", ",", "hparams", ".", "multiproblem_max_target_length", ",", "hparams", ".", "multiproblem_fixed_train_length", ")" ]
Normalize the examples from different tasks so they can be merged.
[ "Normalize", "the", "examples", "from", "different", "tasks", "so", "they", "can", "be", "merged", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/multi_problem.py#L145-L154
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/multi_problem.py
MultiProblem.update_task_ids
def update_task_ids(self, encoder_vocab_size): """Generate task_ids for each problem. These ids correspond to the index of the task in the task_list. Args: encoder_vocab_size: the size of the vocab which is used to compute the index offset. """ for idx, task in enumerate(self.task_list): task.set_task_id(idx + encoder_vocab_size) tf.logging.info("Task %d (%s) has id %d." % (idx, task.name, task.task_id))
python
def update_task_ids(self, encoder_vocab_size): """Generate task_ids for each problem. These ids correspond to the index of the task in the task_list. Args: encoder_vocab_size: the size of the vocab which is used to compute the index offset. """ for idx, task in enumerate(self.task_list): task.set_task_id(idx + encoder_vocab_size) tf.logging.info("Task %d (%s) has id %d." % (idx, task.name, task.task_id))
[ "def", "update_task_ids", "(", "self", ",", "encoder_vocab_size", ")", ":", "for", "idx", ",", "task", "in", "enumerate", "(", "self", ".", "task_list", ")", ":", "task", ".", "set_task_id", "(", "idx", "+", "encoder_vocab_size", ")", "tf", ".", "logging", ".", "info", "(", "\"Task %d (%s) has id %d.\"", "%", "(", "idx", ",", "task", ".", "name", ",", "task", ".", "task_id", ")", ")" ]
Generate task_ids for each problem. These ids correspond to the index of the task in the task_list. Args: encoder_vocab_size: the size of the vocab which is used to compute the index offset.
[ "Generate", "task_ids", "for", "each", "problem", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/multi_problem.py#L385-L397
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/multi_problem.py
MultiProblem.get_max_num_classes
def get_max_num_classes(self): """Compute the maximum number of classes any subtask has. This is useful for modifying the size of the softmax to include the output labels for the classification tasks. Currently, labels from different tasks are overloaded. Returns: num: Highest number of output classes in any text classification sub-task within this MultiProblem. """ num = 0 for task in self.task_list: if hasattr(task, "num_classes"): if num < task.num_classes: num = task.num_classes return num
python
def get_max_num_classes(self): """Compute the maximum number of classes any subtask has. This is useful for modifying the size of the softmax to include the output labels for the classification tasks. Currently, labels from different tasks are overloaded. Returns: num: Highest number of output classes in any text classification sub-task within this MultiProblem. """ num = 0 for task in self.task_list: if hasattr(task, "num_classes"): if num < task.num_classes: num = task.num_classes return num
[ "def", "get_max_num_classes", "(", "self", ")", ":", "num", "=", "0", "for", "task", "in", "self", ".", "task_list", ":", "if", "hasattr", "(", "task", ",", "\"num_classes\"", ")", ":", "if", "num", "<", "task", ".", "num_classes", ":", "num", "=", "task", ".", "num_classes", "return", "num" ]
Compute the maximum number of classes any subtask has. This is useful for modifying the size of the softmax to include the output labels for the classification tasks. Currently, labels from different tasks are overloaded. Returns: num: Highest number of output classes in any text classification sub-task within this MultiProblem.
[ "Compute", "the", "maximum", "number", "of", "classes", "any", "subtask", "has", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/multi_problem.py#L399-L416
train
tensorflow/tensor2tensor
tensor2tensor/layers/transformer_memory.py
RecurrentMemory.pre_attention
def pre_attention(self, segment, query_antecedent, memory_antecedent, bias): """Called prior to self-attention, to incorporate memory items. Args: segment: an integer Tensor with shape [batch] query_antecedent: a Tensor with shape [batch, length_q, channels] memory_antecedent: must be None. Attention normally allows this to be a Tensor with shape [batch, length_m, channels], but we currently only support memory for decoder-side self-attention. bias: bias Tensor (see attention_bias()) Returns: (data, new_query_antecedent, new_memory_antecedent, new_bias) """ del segment return None, query_antecedent, memory_antecedent, bias
python
def pre_attention(self, segment, query_antecedent, memory_antecedent, bias): """Called prior to self-attention, to incorporate memory items. Args: segment: an integer Tensor with shape [batch] query_antecedent: a Tensor with shape [batch, length_q, channels] memory_antecedent: must be None. Attention normally allows this to be a Tensor with shape [batch, length_m, channels], but we currently only support memory for decoder-side self-attention. bias: bias Tensor (see attention_bias()) Returns: (data, new_query_antecedent, new_memory_antecedent, new_bias) """ del segment return None, query_antecedent, memory_antecedent, bias
[ "def", "pre_attention", "(", "self", ",", "segment", ",", "query_antecedent", ",", "memory_antecedent", ",", "bias", ")", ":", "del", "segment", "return", "None", ",", "query_antecedent", ",", "memory_antecedent", ",", "bias" ]
Called prior to self-attention, to incorporate memory items. Args: segment: an integer Tensor with shape [batch] query_antecedent: a Tensor with shape [batch, length_q, channels] memory_antecedent: must be None. Attention normally allows this to be a Tensor with shape [batch, length_m, channels], but we currently only support memory for decoder-side self-attention. bias: bias Tensor (see attention_bias()) Returns: (data, new_query_antecedent, new_memory_antecedent, new_bias)
[ "Called", "prior", "to", "self", "-", "attention", "to", "incorporate", "memory", "items", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/transformer_memory.py#L31-L45
train
tensorflow/tensor2tensor
tensor2tensor/layers/transformer_memory.py
RecentTokensMemory.pre_attention
def pre_attention(self, segment, query_antecedent, memory_antecedent, bias): """Called prior to self-attention, to incorporate memory items. Args: segment: an integer Tensor with shape [batch] query_antecedent: a Tensor with shape [batch, length_q, channels] memory_antecedent: must be None. Attention normally allows this to be a Tensor with shape [batch, length_m, channels], but we currently only support memory for decoder-side self-attention. bias: bias Tensor (see attention_bias()) Returns: (data, new_query_antecedent, new_memory_antecedent, new_bias) """ assert memory_antecedent is None, "We only support language modeling" # In eval mode, batch size may be variable memory_batch_size = tf.shape(self.previous_vals)[0] current_batch_size = tf.shape(query_antecedent)[0] amount_to_pad = memory_batch_size - current_batch_size # If segment id is zero, don't attend back to the memory previous_bias = self.previous_bias[:current_batch_size, :, :, :] + tf.cast( tf.equal(segment[:, None, None, None], 0), tf.float32) * -1e9 sliced_previous_vals = self.previous_vals[:current_batch_size, :, :] new_memory_antecedent = tf.concat( [tf.stop_gradient(sliced_previous_vals), query_antecedent], 1) new_bias = tf.concat([ tf.tile(tf.stop_gradient(previous_bias), [1, 1, self.chunk_length, 1]), tf.tile(bias, [current_batch_size, 1, 1, 1]), ], -1) remember_segment = tf.pad(segment, [[0, amount_to_pad]]) # TODO(kitaev): The code assumes that we always either increment the chunk # number or reset it to zero. This assumption will not hold if we re-run the # model for each token, e.g. for autoregressive greedy/beam/sampling decode. remember_vals = tf.pad(query_antecedent, [[0, amount_to_pad], [0, 0], [0, 0]]) # Query position is on axis -2 for bias: as long as a token can be attended # to from at least one query position (i.e. it's not padding), memorize it. remember_bias = tf.tile( tf.reduce_max(bias, -2, keepdims=True), [memory_batch_size, 1, 1, 1]) # Assume that query_antecedent is always a full chunk (i.e. not truncated) if self.chunk_length < self.tokens_to_cache: remember_vals = tf.concat([self.previous_vals, remember_vals], 1) remember_bias = tf.concat([ self.previous_bias - 1e9 * tf.cast( tf.equal( tf.pad(segment, [[0, amount_to_pad]])[:, None, None, None], 0), tf.float32), remember_bias ], -1) if self.chunk_length != self.tokens_to_cache: remember_vals = remember_vals[:, -self.tokens_to_cache:, :] remember_bias = remember_bias[:, :, :, -self.tokens_to_cache:] token = (remember_segment, remember_vals, remember_bias) return token, query_antecedent, new_memory_antecedent, new_bias
python
def pre_attention(self, segment, query_antecedent, memory_antecedent, bias): """Called prior to self-attention, to incorporate memory items. Args: segment: an integer Tensor with shape [batch] query_antecedent: a Tensor with shape [batch, length_q, channels] memory_antecedent: must be None. Attention normally allows this to be a Tensor with shape [batch, length_m, channels], but we currently only support memory for decoder-side self-attention. bias: bias Tensor (see attention_bias()) Returns: (data, new_query_antecedent, new_memory_antecedent, new_bias) """ assert memory_antecedent is None, "We only support language modeling" # In eval mode, batch size may be variable memory_batch_size = tf.shape(self.previous_vals)[0] current_batch_size = tf.shape(query_antecedent)[0] amount_to_pad = memory_batch_size - current_batch_size # If segment id is zero, don't attend back to the memory previous_bias = self.previous_bias[:current_batch_size, :, :, :] + tf.cast( tf.equal(segment[:, None, None, None], 0), tf.float32) * -1e9 sliced_previous_vals = self.previous_vals[:current_batch_size, :, :] new_memory_antecedent = tf.concat( [tf.stop_gradient(sliced_previous_vals), query_antecedent], 1) new_bias = tf.concat([ tf.tile(tf.stop_gradient(previous_bias), [1, 1, self.chunk_length, 1]), tf.tile(bias, [current_batch_size, 1, 1, 1]), ], -1) remember_segment = tf.pad(segment, [[0, amount_to_pad]]) # TODO(kitaev): The code assumes that we always either increment the chunk # number or reset it to zero. This assumption will not hold if we re-run the # model for each token, e.g. for autoregressive greedy/beam/sampling decode. remember_vals = tf.pad(query_antecedent, [[0, amount_to_pad], [0, 0], [0, 0]]) # Query position is on axis -2 for bias: as long as a token can be attended # to from at least one query position (i.e. it's not padding), memorize it. remember_bias = tf.tile( tf.reduce_max(bias, -2, keepdims=True), [memory_batch_size, 1, 1, 1]) # Assume that query_antecedent is always a full chunk (i.e. not truncated) if self.chunk_length < self.tokens_to_cache: remember_vals = tf.concat([self.previous_vals, remember_vals], 1) remember_bias = tf.concat([ self.previous_bias - 1e9 * tf.cast( tf.equal( tf.pad(segment, [[0, amount_to_pad]])[:, None, None, None], 0), tf.float32), remember_bias ], -1) if self.chunk_length != self.tokens_to_cache: remember_vals = remember_vals[:, -self.tokens_to_cache:, :] remember_bias = remember_bias[:, :, :, -self.tokens_to_cache:] token = (remember_segment, remember_vals, remember_bias) return token, query_antecedent, new_memory_antecedent, new_bias
[ "def", "pre_attention", "(", "self", ",", "segment", ",", "query_antecedent", ",", "memory_antecedent", ",", "bias", ")", ":", "assert", "memory_antecedent", "is", "None", ",", "\"We only support language modeling\"", "# In eval mode, batch size may be variable", "memory_batch_size", "=", "tf", ".", "shape", "(", "self", ".", "previous_vals", ")", "[", "0", "]", "current_batch_size", "=", "tf", ".", "shape", "(", "query_antecedent", ")", "[", "0", "]", "amount_to_pad", "=", "memory_batch_size", "-", "current_batch_size", "# If segment id is zero, don't attend back to the memory", "previous_bias", "=", "self", ".", "previous_bias", "[", ":", "current_batch_size", ",", ":", ",", ":", ",", ":", "]", "+", "tf", ".", "cast", "(", "tf", ".", "equal", "(", "segment", "[", ":", ",", "None", ",", "None", ",", "None", "]", ",", "0", ")", ",", "tf", ".", "float32", ")", "*", "-", "1e9", "sliced_previous_vals", "=", "self", ".", "previous_vals", "[", ":", "current_batch_size", ",", ":", ",", ":", "]", "new_memory_antecedent", "=", "tf", ".", "concat", "(", "[", "tf", ".", "stop_gradient", "(", "sliced_previous_vals", ")", ",", "query_antecedent", "]", ",", "1", ")", "new_bias", "=", "tf", ".", "concat", "(", "[", "tf", ".", "tile", "(", "tf", ".", "stop_gradient", "(", "previous_bias", ")", ",", "[", "1", ",", "1", ",", "self", ".", "chunk_length", ",", "1", "]", ")", ",", "tf", ".", "tile", "(", "bias", ",", "[", "current_batch_size", ",", "1", ",", "1", ",", "1", "]", ")", ",", "]", ",", "-", "1", ")", "remember_segment", "=", "tf", ".", "pad", "(", "segment", ",", "[", "[", "0", ",", "amount_to_pad", "]", "]", ")", "# TODO(kitaev): The code assumes that we always either increment the chunk", "# number or reset it to zero. This assumption will not hold if we re-run the", "# model for each token, e.g. for autoregressive greedy/beam/sampling decode.", "remember_vals", "=", "tf", ".", "pad", "(", "query_antecedent", ",", "[", "[", "0", ",", "amount_to_pad", "]", ",", "[", "0", ",", "0", "]", ",", "[", "0", ",", "0", "]", "]", ")", "# Query position is on axis -2 for bias: as long as a token can be attended", "# to from at least one query position (i.e. it's not padding), memorize it.", "remember_bias", "=", "tf", ".", "tile", "(", "tf", ".", "reduce_max", "(", "bias", ",", "-", "2", ",", "keepdims", "=", "True", ")", ",", "[", "memory_batch_size", ",", "1", ",", "1", ",", "1", "]", ")", "# Assume that query_antecedent is always a full chunk (i.e. not truncated)", "if", "self", ".", "chunk_length", "<", "self", ".", "tokens_to_cache", ":", "remember_vals", "=", "tf", ".", "concat", "(", "[", "self", ".", "previous_vals", ",", "remember_vals", "]", ",", "1", ")", "remember_bias", "=", "tf", ".", "concat", "(", "[", "self", ".", "previous_bias", "-", "1e9", "*", "tf", ".", "cast", "(", "tf", ".", "equal", "(", "tf", ".", "pad", "(", "segment", ",", "[", "[", "0", ",", "amount_to_pad", "]", "]", ")", "[", ":", ",", "None", ",", "None", ",", "None", "]", ",", "0", ")", ",", "tf", ".", "float32", ")", ",", "remember_bias", "]", ",", "-", "1", ")", "if", "self", ".", "chunk_length", "!=", "self", ".", "tokens_to_cache", ":", "remember_vals", "=", "remember_vals", "[", ":", ",", "-", "self", ".", "tokens_to_cache", ":", ",", ":", "]", "remember_bias", "=", "remember_bias", "[", ":", ",", ":", ",", ":", ",", "-", "self", ".", "tokens_to_cache", ":", "]", "token", "=", "(", "remember_segment", ",", "remember_vals", ",", "remember_bias", ")", "return", "token", ",", "query_antecedent", ",", "new_memory_antecedent", ",", "new_bias" ]
Called prior to self-attention, to incorporate memory items. Args: segment: an integer Tensor with shape [batch] query_antecedent: a Tensor with shape [batch, length_q, channels] memory_antecedent: must be None. Attention normally allows this to be a Tensor with shape [batch, length_m, channels], but we currently only support memory for decoder-side self-attention. bias: bias Tensor (see attention_bias()) Returns: (data, new_query_antecedent, new_memory_antecedent, new_bias)
[ "Called", "prior", "to", "self", "-", "attention", "to", "incorporate", "memory", "items", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/transformer_memory.py#L110-L168
train
tensorflow/tensor2tensor
tensor2tensor/layers/transformer_memory.py
RecentTokensMemory.post_attention
def post_attention(self, token, x): """Called after self-attention. The memory can be updated here. Args: token: Data returned by pre_attention, which can be used to carry over state related to the current memory operation. x: a Tensor of data after self-attention and feed-forward Returns: a (possibly modified) version of the input x """ with tf.control_dependencies([ self.previous_segment.assign(token[0]), self.previous_vals.assign(token[1]), self.previous_bias.assign(token[2]), ]): return tf.identity(x)
python
def post_attention(self, token, x): """Called after self-attention. The memory can be updated here. Args: token: Data returned by pre_attention, which can be used to carry over state related to the current memory operation. x: a Tensor of data after self-attention and feed-forward Returns: a (possibly modified) version of the input x """ with tf.control_dependencies([ self.previous_segment.assign(token[0]), self.previous_vals.assign(token[1]), self.previous_bias.assign(token[2]), ]): return tf.identity(x)
[ "def", "post_attention", "(", "self", ",", "token", ",", "x", ")", ":", "with", "tf", ".", "control_dependencies", "(", "[", "self", ".", "previous_segment", ".", "assign", "(", "token", "[", "0", "]", ")", ",", "self", ".", "previous_vals", ".", "assign", "(", "token", "[", "1", "]", ")", ",", "self", ".", "previous_bias", ".", "assign", "(", "token", "[", "2", "]", ")", ",", "]", ")", ":", "return", "tf", ".", "identity", "(", "x", ")" ]
Called after self-attention. The memory can be updated here. Args: token: Data returned by pre_attention, which can be used to carry over state related to the current memory operation. x: a Tensor of data after self-attention and feed-forward Returns: a (possibly modified) version of the input x
[ "Called", "after", "self", "-", "attention", ".", "The", "memory", "can", "be", "updated", "here", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/transformer_memory.py#L170-L185
train
tensorflow/tensor2tensor
tensor2tensor/layers/transformer_memory.py
TransformerMemory._norm
def _norm(self, x): """Compute the safe norm.""" return tf.sqrt(tf.reduce_sum(tf.square(x), keepdims=True, axis=-1) + 1e-7)
python
def _norm(self, x): """Compute the safe norm.""" return tf.sqrt(tf.reduce_sum(tf.square(x), keepdims=True, axis=-1) + 1e-7)
[ "def", "_norm", "(", "self", ",", "x", ")", ":", "return", "tf", ".", "sqrt", "(", "tf", ".", "reduce_sum", "(", "tf", ".", "square", "(", "x", ")", ",", "keepdims", "=", "True", ",", "axis", "=", "-", "1", ")", "+", "1e-7", ")" ]
Compute the safe norm.
[ "Compute", "the", "safe", "norm", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/transformer_memory.py#L226-L228
train
tensorflow/tensor2tensor
tensor2tensor/layers/transformer_memory.py
TransformerMemory._address_content
def _address_content(self, x): """Address the memory based on content similarity. Args: x: a tensor in the shape of [batch_size, length, depth]. Returns: the logits for each memory entry [batch_size, length, memory_size]. """ mem_keys = tf.layers.dense(self.mem_vals, self.key_depth, bias_initializer=tf.constant_initializer(1.0), name="mem_key") mem_query = tf.layers.dense(x, self.key_depth, bias_initializer=tf.constant_initializer(1.0), name="mem_query") norm = tf.matmul(self._norm(mem_query), self._norm(mem_keys), transpose_b=True) dot_product = tf.matmul(mem_query, mem_keys, transpose_b=True) cos_dist = tf.div(dot_product, norm + 1e-7, name="cos_dist") access_logits = self.sharpen_factor * cos_dist return access_logits
python
def _address_content(self, x): """Address the memory based on content similarity. Args: x: a tensor in the shape of [batch_size, length, depth]. Returns: the logits for each memory entry [batch_size, length, memory_size]. """ mem_keys = tf.layers.dense(self.mem_vals, self.key_depth, bias_initializer=tf.constant_initializer(1.0), name="mem_key") mem_query = tf.layers.dense(x, self.key_depth, bias_initializer=tf.constant_initializer(1.0), name="mem_query") norm = tf.matmul(self._norm(mem_query), self._norm(mem_keys), transpose_b=True) dot_product = tf.matmul(mem_query, mem_keys, transpose_b=True) cos_dist = tf.div(dot_product, norm + 1e-7, name="cos_dist") access_logits = self.sharpen_factor * cos_dist return access_logits
[ "def", "_address_content", "(", "self", ",", "x", ")", ":", "mem_keys", "=", "tf", ".", "layers", ".", "dense", "(", "self", ".", "mem_vals", ",", "self", ".", "key_depth", ",", "bias_initializer", "=", "tf", ".", "constant_initializer", "(", "1.0", ")", ",", "name", "=", "\"mem_key\"", ")", "mem_query", "=", "tf", ".", "layers", ".", "dense", "(", "x", ",", "self", ".", "key_depth", ",", "bias_initializer", "=", "tf", ".", "constant_initializer", "(", "1.0", ")", ",", "name", "=", "\"mem_query\"", ")", "norm", "=", "tf", ".", "matmul", "(", "self", ".", "_norm", "(", "mem_query", ")", ",", "self", ".", "_norm", "(", "mem_keys", ")", ",", "transpose_b", "=", "True", ")", "dot_product", "=", "tf", ".", "matmul", "(", "mem_query", ",", "mem_keys", ",", "transpose_b", "=", "True", ")", "cos_dist", "=", "tf", ".", "div", "(", "dot_product", ",", "norm", "+", "1e-7", ",", "name", "=", "\"cos_dist\"", ")", "access_logits", "=", "self", ".", "sharpen_factor", "*", "cos_dist", "return", "access_logits" ]
Address the memory based on content similarity. Args: x: a tensor in the shape of [batch_size, length, depth]. Returns: the logits for each memory entry [batch_size, length, memory_size].
[ "Address", "the", "memory", "based", "on", "content", "similarity", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/transformer_memory.py#L230-L249
train