text_prompt
stringlengths
100
17.7k
code_prompt
stringlengths
7
9.86k
<SYSTEM_TASK:> Train the given model on the given dataset. <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Main function to train the given model on the given dataset. <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Decode from estimator. Interactive, from file, or from dataset. <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Score each line in a file and return the scores. <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Put time dimension on channels in an embedded video. <END_TASK> <USER_TASK:> Description: 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] ])
<SYSTEM_TASK:> Residual discrete autoencoder model, big version. <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Ordered discrete autoencoder model for text. <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Ordered discrete autoencoder model for text, small version. <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Discrete autoencoder model for compressing pong frames. <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Discrete autoencoder model for compressing pong frames for testing. <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Tuning grid of the main autoencoder params. <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Question encoder, run LSTM encoder and get the last output as encoding. <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Get the history for the given metric and mode. <END_TASK> <USER_TASK:> Description: 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])
<SYSTEM_TASK:> Performs a batch normalization followed by a ReLU. <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Standard building block for residual networks with BN before convolutions. <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Resnet model. <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Returns the length of the Longest Common Subsequence between two seqs. <END_TASK> <USER_TASK:> Description: 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]
<SYSTEM_TASK:> Computes the length of the LCS between two seqs. <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> A list of examples to a dataset containing mixed examples. <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> LM loss for multiproblems. <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Generate task_ids for each problem. <END_TASK> <USER_TASK:> Description: 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))
<SYSTEM_TASK:> Compute the maximum number of classes any subtask has. <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Address the memory based on content similarity. <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Read from the memory. <END_TASK> <USER_TASK:> Description: def read(self, x): """Read from the memory. An external component can use the results via a simple MLP, e.g., fn(x W_x + retrieved_mem W_m). Args: x: a tensor in the shape of [batch_size, length, depth]. Returns: access_logits: the logits for accessing the memory in shape of [batch_size, length, memory_size]. retrieved_mem: the retrieved results in the shape of [batch_size, length, val_depth]. """
access_logits = self._address_content(x) weights = tf.nn.softmax(access_logits) retrieved_mem = tf.reduce_sum( tf.multiply(tf.expand_dims(weights, 3), tf.expand_dims(self.mem_vals, axis=1)), axis=2) return access_logits, retrieved_mem
<SYSTEM_TASK:> Write to the memory based on a combination of similarity and least used. <END_TASK> <USER_TASK:> Description: def write(self, x, access_logits): """Write to the memory based on a combination of similarity and least used. Based on arXiv:1607.00036v2 [cs.LG]. Args: x: a tensor in the shape of [batch_size, length, depth]. access_logits: the logits for accessing the memory. Returns: the update op. """
gamma = tf.layers.dense(x, 1, activation=tf.sigmoid, name="gamma") write_logits = access_logits - gamma * tf.expand_dims(self.mean_logits, 1) candidate_value = tf.layers.dense(x, self.val_depth, activation=tf.nn.relu, name="candidate_value") erase_gates = tf.layers.dense(x, self.memory_size, activation=tf.nn.sigmoid, name="erase") write_weights = tf.nn.softmax(write_logits) erase_weights = tf.expand_dims(1 - erase_gates * write_weights, 3) erase = tf.multiply(erase_weights, tf.expand_dims(self.mem_vals, 1)) addition = tf.multiply( tf.expand_dims(write_weights, 3), tf.expand_dims(candidate_value, 2)) update_value_op = self.mem_vals.assign( tf.reduce_mean(erase + addition, axis=1)) with tf.control_dependencies([update_value_op]): write_op = self.mean_logits.assign( self.mean_logits * 0.1 + tf.reduce_mean(write_logits * 0.9, axis=1)) return write_op
<SYSTEM_TASK:> Reset the entries in the memory. <END_TASK> <USER_TASK:> Description: def reset(self, entries_to_reset): """Reset the entries in the memory. Args: entries_to_reset: a 1D tensor. Returns: the reset op. """
num_updates = tf.size(entries_to_reset) update_vals = tf.scatter_update( self.mem_vals, entries_to_reset, tf.tile(tf.expand_dims( tf.fill([self.memory_size, self.val_depth], .0), 0), [num_updates, 1, 1])) update_logits = tf.scatter_update( self.mean_logits, entries_to_reset, tf.tile(tf.expand_dims( tf.fill([self.memory_size], .0), 0), [num_updates, 1])) reset_op = tf.group([update_vals, update_logits]) return reset_op
<SYSTEM_TASK:> Basic parameters for a vanilla_gan. <END_TASK> <USER_TASK:> Description: def sliced_gan(): """Basic parameters for a vanilla_gan."""
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 = 128 hparams.initializer = "uniform_unit_scaling" hparams.initializer_gain = 1.0 hparams.weight_decay = 1e-6 hparams.kernel_height = 4 hparams.kernel_width = 4 hparams.bottleneck_bits = 128 hparams.add_hparam("discriminator_batchnorm", True) hparams.add_hparam("num_sliced_vecs", 4096) return hparams
<SYSTEM_TASK:> Body of the model. <END_TASK> <USER_TASK:> Description: def body(self, features): """Body of the model. Args: features: a dictionary with the tensors. Returns: A pair (predictions, losses) where predictions is the generated image and losses is a dictionary of losses (that get added for the final loss). """
features["targets"] = features["inputs"] is_training = self.hparams.mode == tf.estimator.ModeKeys.TRAIN # Input images. inputs = tf.to_float(features["targets_raw"]) # Noise vector. z = tf.random_uniform([self.hparams.batch_size, self.hparams.bottleneck_bits], minval=-1, maxval=1, name="z") # Generator output: fake images. out_shape = common_layers.shape_list(inputs)[1:4] g = self.generator(z, is_training, out_shape) losses = self.losses(inputs, g) # pylint: disable=not-callable summary_g_image = tf.reshape( g[0, :], [1] + common_layers.shape_list(inputs)[1:]) tf.summary.image("generated", summary_g_image, max_outputs=1) if is_training: # Returns an dummy output and the losses dictionary. return tf.zeros_like(inputs), losses return tf.reshape(g, tf.shape(inputs)), losses
<SYSTEM_TASK:> Make Inputs for built-in datasets. <END_TASK> <USER_TASK:> Description: def inputs(num_devices, dataset_name, data_dir=None, input_name=None, num_chunks=0, append_targets=False): """Make Inputs for built-in datasets. Args: num_devices: how many devices to build the inputs for. dataset_name: a TFDS or T2T dataset name. If it's a T2T dataset name, prefix with "t2t_". data_dir: data directory. input_name: optional, name of the inputs from the dictionary. num_chunks: optional, into how many pieces should we chunk (large inputs). append_targets: optional, instead of inputs return a pair (inputs, targets) which is useful for autoregressive models. Returns: trax.inputs.Inputs """
assert data_dir, "Must provide a data directory" data_dir = os.path.expanduser(data_dir) (train_batches, train_eval_batches, eval_batches, input_name, input_shape) = _train_and_eval_batches( dataset_name, data_dir, input_name, num_devices) def numpy_stream(dataset): return dataset_to_stream( dataset, input_name, num_chunks=num_chunks, append_targets=append_targets) if num_chunks > 0: length = input_shape[0] input_shape = tuple( [tuple([length // num_chunks] + list(input_shape)[1:])] * num_chunks) return Inputs(train_stream=lambda: numpy_stream(train_batches), train_eval_stream=lambda: numpy_stream(train_eval_batches), eval_stream=lambda: numpy_stream(eval_batches), input_shape=input_shape)
<SYSTEM_TASK:> Make random Inputs for debugging. <END_TASK> <USER_TASK:> Description: def random_inputs( num_devices, input_shape=gin.REQUIRED, input_dtype=np.int32, input_range=(0, 255), output_shape=gin.REQUIRED, output_dtype=np.int32, output_range=(0, 9)): """Make random Inputs for debugging. Args: num_devices: how many devices to build the inputs for. input_shape: the shape of inputs (including batch dimension). input_dtype: the type of the inputs (int32 by default). input_range: the range of inputs (defaults to (0, 255)). output_shape: the shape of outputs (including batch dimension). output_dtype: the type of the outputs (int32 by default). output_range: the range of outputs (defaults to (0, 9)). Returns: trax.inputs.Inputs """
if input_shape[0] % num_devices != 0: tf.logging.fatal( "num_devices[%d] should divide the first dimension of input_shape[%s]", num_devices, input_shape) if output_shape[0] % num_devices != 0: tf.logging.fatal( "num_devices[%d] should divide the first dimension of output_shape[%s]", num_devices, output_shape) def random_minibatches(): """Generate a stream of random mini-batches.""" if input_dtype in [np.float16, np.float32, np.float64]: rand = np.random.uniform else: rand = np.random.random_integers while True: inp = rand(input_range[0], input_range[1], input_shape) inp = inp.astype(input_dtype) out = rand(output_range[0], output_range[1], output_shape) out = out.astype(output_dtype) yield inp, out input_shape_without_batch = list(input_shape)[1:] return Inputs(train_stream=random_minibatches, train_eval_stream=random_minibatches, eval_stream=random_minibatches, input_shape=input_shape_without_batch)
<SYSTEM_TASK:> Takes a tf.Dataset and creates a numpy stream of ready batches. <END_TASK> <USER_TASK:> Description: def dataset_to_stream(dataset, input_name, num_chunks=0, append_targets=False): """Takes a tf.Dataset and creates a numpy stream of ready batches."""
for example in tfds.as_numpy(dataset): inp, out = example[0][input_name], example[1] if len(out.shape) > 1 and out.shape[-1] == 1: out = np.squeeze(out, axis=-1) if num_chunks > 0: inp = np.split(inp, num_chunks, axis=1) out = np.split(out, num_chunks, axis=1) if append_targets: inp = (inp, out) yield inp, out
<SYSTEM_TASK:> Return train and eval batches with input name and shape. <END_TASK> <USER_TASK:> Description: def _train_and_eval_batches(dataset, data_dir, input_name, num_devices): """Return train and eval batches with input name and shape."""
(train_data, eval_data, features_info, keys) = train_and_eval_dataset( dataset, data_dir) input_names, target_names = keys[0], keys[1] train_batches = shuffle_and_batch_data( train_data, target_names, features_info, training=True, num_devices=num_devices) train_eval_batches = shuffle_and_batch_data( # Data for eval-on-train. train_data, target_names, features_info, training=False, num_devices=num_devices) eval_batches = shuffle_and_batch_data( eval_data, target_names, features_info, training=False, num_devices=num_devices) input_name = input_name or input_names[0] input_shape = features_info[input_name].shape return (train_batches, train_eval_batches, eval_batches, input_name, list(input_shape))
<SYSTEM_TASK:> Returns a Dataset that samples records from one or more Datasets. <END_TASK> <USER_TASK:> Description: def get_multi_dataset(datasets, pmf=None): """Returns a Dataset that samples records from one or more Datasets. Args: datasets: A list of one or more Dataset objects to sample from. pmf: A tensor of shape [len(datasets)], the probabilities to sample each dataset with. This tensor is often constructed with the global_step. If this is None, we sample from the datasets uniformly at random. Returns: A Dataset object containing records from multiple datasets. Note that because this dataset iterates through other datasets it is stateful, thus you will need to call make_initializable_iterator instead of make_one_shot_iterator. """
pmf = tf.fill([len(datasets)], 1.0 / len(datasets)) if pmf is None else pmf samplers = [d.repeat().make_one_shot_iterator().get_next for d in datasets] sample = lambda _: categorical_case(pmf, samplers) return tf.data.Dataset.from_tensors([]).repeat().map(sample)
<SYSTEM_TASK:> Computes the pmf of a schedule given the global_step. <END_TASK> <USER_TASK:> Description: def get_schedule_distribution(schedule, global_step=None): """Computes the pmf of a schedule given the global_step. Args: schedule: A schedule tuple, see encode_schedule for details. global_step: A scalar tensor, the step to query the schedule. Returns: A 1-D tensor of probs, the sampling distribution of the global_step. """
interpolation, steps, pmfs = schedule if len(pmfs) == 1: # py_func doesn't seem to work on TPU - at least get the constant case to # run. # TODO(noam): get the general case working. return pmfs[0] if global_step is None: global_step = tf.train.get_or_create_global_step() if interpolation == 'step': interpolation_fn = step_interpolation elif interpolation == 'linear': interpolation_fn = linear_interpolation else: raise ValueError('Invalid interpolation strategy: %s' % interpolation) return tf.reshape( tf.py_func( func=lambda x: interpolation_fn(x, np.array(steps), np.array(pmfs)), inp=[global_step], Tout=tf.float32), [len(pmfs[0])])
<SYSTEM_TASK:> Multi-dimensional linear interpolation. <END_TASK> <USER_TASK:> Description: def linear_interpolation(x, xp, fp, **kwargs): """Multi-dimensional linear interpolation. Returns the multi-dimensional piecewise linear interpolant to a function with given discrete data points (xp, fp), evaluated at x. Note that *N and *M indicate zero or more dimensions. Args: x: An array of shape [*N], the x-coordinates of the interpolated values. xp: An np.array of shape [D], the x-coordinates of the data points, must be increasing. fp: An np.array of shape [D, *M], the y-coordinates of the data points. **kwargs: Keywords for np.interp. Returns: An array of shape [*N, *M], the interpolated values. """
yp = fp.reshape([fp.shape[0], -1]).transpose() y = np.stack([np.interp(x, xp, zp, **kwargs) for zp in yp]).transpose() return y.reshape(x.shape[:1] + fp.shape[1:]).astype(np.float32)
<SYSTEM_TASK:> Multi-dimensional step interpolation. <END_TASK> <USER_TASK:> Description: def step_interpolation(x, xp, fp, **kwargs): """Multi-dimensional step interpolation. Returns the multi-dimensional step interpolant to a function with given discrete data points (xp, fp), evaluated at x. Note that *N and *M indicate zero or more dimensions. Args: x: An array of shape [*N], the x-coordinates of the interpolated values. xp: An np.array of shape [D], the x-coordinates of the data points, must be increasing. fp: An np.array of shape [D, *M], the y-coordinates of the data points. **kwargs: Unused. Returns: An array of shape [*N, *M], the interpolated values. """
del kwargs # Unused. xp = np.expand_dims(xp, -1) lower, upper = xp[:-1], xp[1:] conditions = (x >= lower) & (x < upper) # Underflow and overflow conditions and values. Values default to fp[0] and # fp[-1] respectively. conditions = np.concatenate([[x < xp[0]], conditions, [x >= xp[-1]]]) values = np.concatenate([[fp[0]], fp]) assert np.all(np.sum(conditions, 0) == 1), 'xp must be increasing.' indices = np.argmax(conditions, 0) return values[indices].astype(np.float32)
<SYSTEM_TASK:> Create a probability-mass-function based on relative epoch rates. <END_TASK> <USER_TASK:> Description: def epoch_rates_to_pmf(problems, epoch_rates=None): """Create a probability-mass-function based on relative epoch rates. if epoch_rates=None, then we use uniform epoch rates [1.0] * len(problems) i.e. it takes each problem the same time to go through one epoch. If epoch_rates is given, then these are the relative numbers of epochs of each problem to go through in a given amount of time. Each must have problem.num_training_examples implemented. Args: problems: a list of Problem instances. epoch_rates: an optional list of float Returns: a list of floating point values. """
if epoch_rates is None: epoch_rates = [1.0] * len(problems) example_rates = [epoch_rate * p.num_training_examples for p, epoch_rate in zip(problems, epoch_rates)] return example_rates_to_pmf(example_rates)
<SYSTEM_TASK:> Encodes a schedule tuple into a string. <END_TASK> <USER_TASK:> Description: def encode_schedule(schedule): """Encodes a schedule tuple into a string. Args: schedule: A tuple containing (interpolation, steps, pmfs), where interpolation is a string specifying the interpolation strategy, steps is an int array_like of shape [N] specifying the global steps, and pmfs is an array_like of shape [N, M] where pmf[i] is the sampling distribution at global step steps[i]. N is the number of schedule requirements to interpolate and M is the size of the probability space. Returns: The string encoding of the schedule tuple. """
interpolation, steps, pmfs = schedule return interpolation + ' ' + ' '.join( '@' + str(s) + ' ' + ' '.join(map(str, p)) for s, p in zip(steps, pmfs))
<SYSTEM_TASK:> Decodes a string into a schedule tuple. <END_TASK> <USER_TASK:> Description: def decode_schedule(string): """Decodes a string into a schedule tuple. Args: string: The string encoding of a schedule tuple. Returns: A schedule tuple, see encode_schedule for details. """
splits = string.split() steps = [int(x[1:]) for x in splits[1:] if x[0] == '@'] pmfs = np.reshape( [float(x) for x in splits[1:] if x[0] != '@'], [len(steps), -1]) return splits[0], tuplize(steps), tuplize(pmfs)
<SYSTEM_TASK:> Recursively converts iterables into tuples. <END_TASK> <USER_TASK:> Description: def tuplize(nested): """Recursively converts iterables into tuples. Args: nested: A nested structure of items and iterables. Returns: A nested structure of items and tuples. """
if isinstance(nested, str): return nested try: return tuple(map(tuplize, nested)) except TypeError: return nested
<SYSTEM_TASK:> Returns a list of filepatterns, one for each problem. <END_TASK> <USER_TASK:> Description: def filepattern(self, *args, **kwargs): """Returns a list of filepatterns, one for each problem."""
return [p.filepattern(*args, **kwargs) for p in self.problems]
<SYSTEM_TASK:> Generates data for each problem. <END_TASK> <USER_TASK:> Description: def generate_data(self, *args, **kwargs): """Generates data for each problem."""
for p in self.problems: p.generate_data(*args, **kwargs)
<SYSTEM_TASK:> Returns a dataset containing examples from multiple problems. <END_TASK> <USER_TASK:> Description: def dataset(self, mode, hparams=None, global_step=None, **kwargs): """Returns a dataset containing examples from multiple problems. Args: mode: A member of problem.DatasetSplit. hparams: A tf.HParams object, the model hparams. global_step: A scalar tensor used to compute the sampling distribution. If global_step is None, we call tf.train.get_or_create_global_step by default. **kwargs: Keywords for problem.Problem.Dataset. Returns: A dataset containing examples from multiple problems. """
datasets = [p.dataset(mode, **kwargs) for p in self.problems] datasets = [ d.map(lambda x, i=j: self.normalize_example( # pylint: disable=g-long-lambda dict(x, problem_id=tf.constant([i])), hparams)) for j, d in enumerate(datasets) # Tag examples with a problem_id. ] if mode is problem.DatasetSplit.TRAIN: if global_step is None: global_step = tf.train.get_or_create_global_step() pmf = get_schedule_distribution(self.schedule, global_step) return get_multi_dataset(datasets, pmf) elif self.only_eval_first_problem: return datasets[0] else: datasets = [d.repeat() for d in datasets] return tf.data.Dataset.zip(tuple(datasets)).flat_map( lambda *x: functools.reduce( # pylint: disable=g-long-lambda tf.data.Dataset.concatenate, map(tf.data.Dataset.from_tensors, x)))
<SYSTEM_TASK:> Assumes that example contains both inputs and targets. <END_TASK> <USER_TASK:> Description: def normalize_example(self, example, hparams): """Assumes that example contains both inputs and targets."""
length = self.max_length(hparams) def _to_constant_shape(tensor): tensor = tensor[:length] tensor = tf.pad(tensor, [(0, length - tf.shape(tensor)[0])]) return tf.reshape(tensor, [length]) if self.has_inputs: example['inputs'] = _to_constant_shape(example['inputs']) example['targets'] = _to_constant_shape(example['targets']) elif 'inputs' in example: if self.packed_length: raise ValueError('cannot concatenate packed examples on the fly.') inputs = example.pop('inputs')[:-1] # Remove EOS token. targets = tf.concat([inputs, example['targets']], 0) example['targets'] = _to_constant_shape(targets) else: example['targets'] = _to_constant_shape(example['targets']) if self.packed_length: if self.has_inputs: if 'inputs_segmentation' in example: example['inputs_segmentation'] = _to_constant_shape( example['inputs_segmentation']) example['inputs_position'] = _to_constant_shape( example['inputs_position']) else: example['inputs_segmentation'] = tf.to_int64( tf.not_equal(example['inputs'], 0)) example['inputs_position'] = ( example['inputs_segmentation'] * tf.range(length, dtype=tf.int64)) if 'targets_segmentation' in example: example['targets_segmentation'] = _to_constant_shape( example['targets_segmentation']) example['targets_position'] = _to_constant_shape( example['targets_position']) else: example['targets_segmentation'] = tf.to_int64( tf.not_equal(example['targets'], 0)) example['targets_position'] = ( example['targets_segmentation'] * tf.range(length, dtype=tf.int64)) return example
<SYSTEM_TASK:> Generates TF-Records for problems using a global vocabulary file. <END_TASK> <USER_TASK:> Description: def generate_data_with_shared_vocab(self, data_dir, tmp_dir, task_id=-1): """Generates TF-Records for problems using a global vocabulary file."""
global_vocab_filename = os.path.join(data_dir, self.vocab_filename) if not tf.gfile.Exists(global_vocab_filename): raise ValueError( 'Global vocabulary file: %s does not exist, ' 'please create one using build_vocab.py' % global_vocab_filename) # Before generating data, we copy the global vocabulary file to the children # locations. Although this is not the most disk efficient strategy, it # imposes the fewest changes to the text-to-text API. for p in self.problems: local_vocab_filename = os.path.join(data_dir, p.vocab_filename) if not tf.gfile.Exists(local_vocab_filename): tf.gfile.Copy(global_vocab_filename, local_vocab_filename) p.generate_data(data_dir, tmp_dir, task_id)
<SYSTEM_TASK:> Generates a non-padding mask for areas based on lengths. <END_TASK> <USER_TASK:> Description: def lengths_to_area_mask(feature_length, length, max_area_size): """Generates a non-padding mask for areas based on lengths. Args: feature_length: a tensor of [batch_size] length: the length of the batch max_area_size: the maximum area size considered Returns: mask: a tensor in shape of [batch_size, num_areas] """
paddings = tf.cast(tf.expand_dims( tf.logical_not( tf.sequence_mask(feature_length, maxlen=length)), 2), tf.float32) _, _, area_sum, _, _ = compute_area_features(paddings, max_area_width=max_area_size) mask = tf.squeeze(tf.logical_not(tf.cast(area_sum, tf.bool)), [2]) return mask
<SYSTEM_TASK:> Pools for an area in features_2d. <END_TASK> <USER_TASK:> Description: def _pool_one_shape(features_2d, area_width, area_height, batch_size, width, height, depth, fn=tf.reduce_max, name=None): """Pools for an area in features_2d. Args: features_2d: a Tensor in a shape of [batch_size, height, width, depth]. area_width: the max width allowed for an area. area_height: the max height allowed for an area. batch_size: the batch size. width: the width of the memory. height: the height of the memory. depth: the depth of the features. fn: the TF function for the pooling. name: the op name. Returns: pool_tensor: A Tensor of shape [batch_size, num_areas, depth] """
with tf.name_scope(name, default_name="pool_one_shape"): images = [] for y_shift in range(area_height): image_height = tf.maximum(height - area_height + 1 + y_shift, 0) for x_shift in range(area_width): image_width = tf.maximum(width - area_width + 1 + x_shift, 0) area = features_2d[:, y_shift:image_height, x_shift:image_width, :] flatten_area = tf.reshape(area, [batch_size, -1, depth, 1]) images.append(flatten_area) image_tensor = tf.concat(images, axis=3) max_tensor = fn(image_tensor, axis=3) return max_tensor
<SYSTEM_TASK:> Computes features for each area. <END_TASK> <USER_TASK:> Description: def compute_area_features(features, max_area_width, max_area_height=1, height=1, epsilon=1e-6): """Computes features for each area. Args: features: a Tensor in a shape of [batch_size, height * width, depth]. max_area_width: the max width allowed for an area. max_area_height: the max height allowed for an area. height: the height of the image. epsilon: the epsilon added to the variance for computing standard deviation. Returns: area_mean: A Tensor of shape [batch_size, num_areas, depth] area_std: A Tensor of shape [batch_size, num_areas, depth] area_sum: A Tensor of shape [batch_size, num_areas, depth] area_heights: A Tensor of shape [batch_size, num_areas, 1] area_widths: A Tensor of shape [batch_size, num_areas, 1] """
with tf.name_scope("compute_area_features"): tf.logging.info("area_attention compute_area_features: %d x %d", max_area_height, max_area_width) area_sum, area_heights, area_widths = _compute_sum_image( features, max_area_width=max_area_width, max_area_height=max_area_height, height=height) area_squared_sum, _, _ = _compute_sum_image( tf.pow(features, 2), max_area_width=max_area_width, max_area_height=max_area_height, height=height) sizes = tf.multiply(area_heights, area_widths) float_area_sizes = tf.to_float(sizes) area_mean = tf.div(area_sum, float_area_sizes) s2_n = tf.div(area_squared_sum, float_area_sizes) area_variance = tf.subtract(s2_n, tf.pow(area_mean, 2)) area_std = tf.sqrt(tf.abs(area_variance) + epsilon) return area_mean, area_std, area_sum, area_heights, area_widths
<SYSTEM_TASK:> Computes the key for each area. <END_TASK> <USER_TASK:> Description: def compute_area_key(features, max_area_width, max_area_height=1, height=1, mode="mean", training=True, name=None): """Computes the key for each area. Args: features: a Tensor in a shape of [batch_size, height * width, depth]. max_area_width: the max width allowed for an area. max_area_height: the max height allowed for an area. height: the height of the image. mode: whether to combine different area features or only use the vector mean of each area, which can be "mean", "concat", "sum", "sample_concat", and "sample_sum". training: indicating if it is in the training mode. name: the name for setting the variable scope. Returns: area_key: a Tensor in the shape of [batch_size, num_areas, depth] """
tf.logging.info("area_attention mode=%s", mode) area_mean, area_std, _, area_heights, area_widths =\ compute_area_features(features, max_area_width=max_area_width, max_area_height=max_area_height, height=height) if mode == "mean": return area_mean elif mode == "max": area_max, _, _ = basic_pool(features, max_area_width=max_area_width, max_area_height=max_area_height, height=height) return area_max elif mode == "sample": if training: area_mean += (area_std * tf.random_normal(tf.shape(area_std))) return area_mean with tf.variable_scope( name, default_name="combine_area_features", values=[area_mean, area_std, area_heights, area_widths]): depth = common_layers.shape_list(area_mean)[-1] height_embed = tf.nn.embedding_lookup( params=tf.get_variable("area_height_emb", [max_area_height, depth // 2]), ids=area_heights[:, :, 0] - 1) width_embed = tf.nn.embedding_lookup( params=tf.get_variable("area_width_emb", [max_area_width, depth // 2]), ids=area_widths[:, :, 0] - 1) size_embed = tf.concat([height_embed, width_embed], -1) if mode == "concat": feature_concat = tf.concat([area_mean, area_std, size_embed], -1) elif mode == "max_concat": area_max, _, _ = basic_pool(features, max_area_width=max_area_width, max_area_height=max_area_height, height=height) feature_concat = tf.concat([area_max, size_embed], -1) elif mode == "sum": feature_concat = size_embed + area_mean + area_std elif mode == "sample_concat": if training: area_mean += (area_std * tf.random_normal(tf.shape(area_std))) feature_concat = tf.concat([area_mean, size_embed], -1) elif mode == "sample_sum": if training: area_mean += (area_std * tf.random_normal(tf.shape(area_std))) feature_concat = area_mean + size_embed else: raise ValueError("Unsupported area key mode=%s" % mode) feature_hidden = tf.layers.dense(inputs=feature_concat, units=depth, activation=tf.nn.relu) area_key = tf.layers.dense(feature_hidden, units=depth) return area_key
<SYSTEM_TASK:> Make a function that logs the duration since it was made. <END_TASK> <USER_TASK:> Description: def make_relative_timing_fn(): """Make a function that logs the duration since it was made."""
start_time = time.time() def format_relative_time(): time_delta = time.time() - start_time return str(datetime.timedelta(seconds=time_delta)) def log_relative_time(): tf.logging.info("Timing: %s", format_relative_time()) return log_relative_time
<SYSTEM_TASK:> Train the PPO agent in the simulated environment. <END_TASK> <USER_TASK:> Description: def train_agent(real_env, learner, world_model_dir, hparams, epoch): """Train the PPO agent in the simulated environment."""
initial_frame_chooser = rl_utils.make_initial_frame_chooser( real_env, hparams.frame_stack_size, hparams.simulation_random_starts, hparams.simulation_flip_first_random_for_beginning ) env_fn = rl.make_simulated_env_fn_from_hparams( real_env, hparams, batch_size=hparams.simulated_batch_size, initial_frame_chooser=initial_frame_chooser, model_dir=world_model_dir, sim_video_dir=os.path.join( learner.agent_model_dir, "sim_videos_{}".format(epoch) ) ) base_algo_str = hparams.base_algo train_hparams = trainer_lib.create_hparams(hparams.base_algo_params) if hparams.wm_policy_param_sharing: train_hparams.optimizer_zero_grads = True rl_utils.update_hparams_from_hparams( train_hparams, hparams, base_algo_str + "_" ) final_epoch = hparams.epochs - 1 is_special_epoch = (epoch + 3) == final_epoch or (epoch + 7) == final_epoch is_final_epoch = epoch == final_epoch env_step_multiplier = 3 if is_final_epoch else 2 if is_special_epoch else 1 learner.train( env_fn, train_hparams, simulated=True, save_continuously=True, epoch=epoch, env_step_multiplier=env_step_multiplier )
<SYSTEM_TASK:> Train the PPO agent in the real environment. <END_TASK> <USER_TASK:> Description: def train_agent_real_env(env, learner, hparams, epoch): """Train the PPO agent in the real environment."""
base_algo_str = hparams.base_algo train_hparams = trainer_lib.create_hparams(hparams.base_algo_params) rl_utils.update_hparams_from_hparams( train_hparams, hparams, "real_" + base_algo_str + "_" ) if hparams.wm_policy_param_sharing: train_hparams.optimizer_zero_grads = True env_fn = rl.make_real_env_fn(env) num_env_steps = real_env_step_increment(hparams) learner.train( env_fn, train_hparams, simulated=False, save_continuously=False, epoch=epoch, sampling_temp=hparams.real_sampling_temp, num_env_steps=num_env_steps, ) # Save unfinished rollouts to history. env.reset()
<SYSTEM_TASK:> Loads metrics for this epoch if they have already been written. <END_TASK> <USER_TASK:> Description: def load_metrics(event_dir, epoch): """Loads metrics for this epoch if they have already been written. This reads the entire event file but it's small with just per-epoch metrics. Args: event_dir: TODO(koz4k): Document this. epoch: TODO(koz4k): Document this. Returns: metrics. """
metrics = {} for filename in tf.gfile.ListDirectory(event_dir): path = os.path.join(event_dir, filename) for event in tf.train.summary_iterator(path): if event.step == epoch and event.HasField("summary"): value = event.summary.value[0] metrics[value.tag] = value.simple_value return metrics
<SYSTEM_TASK:> Single conv layer with relu, optional pooling, and dropout. <END_TASK> <USER_TASK:> Description: def conv_layer(x, hidden_size, kernel_size, stride, pooling_window, dropout_rate, dilation_rate, name="conv"): """Single conv layer with relu, optional pooling, and dropout."""
with tf.variable_scope(name): out = x out = common_layers.conv1d_block( out, hidden_size, [(dilation_rate, kernel_size)], strides=stride, first_relu=False, padding="same") out = tf.nn.relu(out) if pooling_window: out = tf.layers.max_pooling1d( out, pooling_window, pooling_window, padding="same") out = tf.layers.dropout(out, dropout_rate) return out
<SYSTEM_TASK:> Computes negative ELBO, which is an upper bound on the negative likelihood. <END_TASK> <USER_TASK:> Description: def compute_nats_and_bits_per_dim(data_dim, latent_dim, average_reconstruction, average_prior): """Computes negative ELBO, which is an upper bound on the negative likelihood. Args: data_dim: int-like indicating data dimensionality. latent_dim: int-like indicating latent dimensionality. average_reconstruction: Scalar Tensor indicating the reconstruction cost averaged over all data dimensions and any data batches. average_prior: Scalar Tensor indicating the negative log-prior probability averaged over all latent dimensions and any data batches. Returns: Tuple of scalar Tensors, representing the nats and bits per data dimension (e.g., subpixels) respectively. """
with tf.name_scope(None, default_name="compute_nats_per_dim"): data_dim = tf.cast(data_dim, average_reconstruction.dtype) latent_dim = tf.cast(latent_dim, average_prior.dtype) negative_log_likelihood = data_dim * average_reconstruction negative_log_prior = latent_dim * average_prior negative_elbo = negative_log_likelihood + negative_log_prior nats_per_dim = tf.divide(negative_elbo, data_dim, name="nats_per_dim") bits_per_dim = tf.divide(nats_per_dim, tf.log(2.), name="bits_per_dim") return nats_per_dim, bits_per_dim
<SYSTEM_TASK:> Multinomial sampling from a n-dimensional tensor. <END_TASK> <USER_TASK:> Description: def multinomial_sample(x, vocab_size=None, sampling_method="random", temperature=1.0): """Multinomial sampling from a n-dimensional tensor. Args: x: Tensor of shape [..., vocab_size]. Parameterizes logits of multinomial. vocab_size: Number of classes in multinomial distribution. sampling_method: String, "random" or otherwise deterministic. temperature: Positive float. Returns: Tensor of shape [...]. """
vocab_size = vocab_size or common_layers.shape_list(x)[-1] if sampling_method == "random" and temperature > 0.0: samples = tf.multinomial(tf.reshape(x, [-1, vocab_size]) / temperature, 1) else: samples = tf.argmax(x, axis=-1) reshaped_samples = tf.reshape(samples, common_layers.shape_list(x)[:-1]) return reshaped_samples
<SYSTEM_TASK:> Samples from the latent space in the autoencoder. <END_TASK> <USER_TASK:> Description: def ae_latent_sample_beam(latents_dense_in, inputs, ed, embed, hparams): """Samples from the latent space in the autoencoder. Args: latents_dense_in: Tensor of shape [batch, length_q, ...]. Only the shape of its first two dimensions are used. length_q is the latent length, which is height * width * hparams.num_latents / (2**hparams.num_compress_steps). inputs: Tensor of shape [batch, length_kv, hparams.hidden_size]. Encodings to attend to in decoder. ed: Tensor which broadcasts with shape [batch, hparams.num_heads, length_q, length_kv]. Encoder-decoder attention bias. embed: Callable which embeds discrete latent hot-vectors and a hidden size and returns dense vectors. hparams: HParams. Returns: Tensor of shape [batch, length]. """
def symbols_to_logits_fn(ids): """Go from ids to logits.""" ids = tf.expand_dims(ids, axis=2) # Ids start with added all-zeros. latents_discrete = tf.pad(ids[:, 1:], [[0, 0], [0, 1], [0, 0]]) with tf.variable_scope(tf.get_variable_scope(), reuse=False): latents_dense = embed( tf.one_hot(latents_discrete, depth=2**hparams.bottleneck_bits), hparams.hidden_size) latents_pred = transformer_latent_decoder( latents_dense, inputs, ed, hparams, name="latent_prediction") logits = tf.layers.dense( latents_pred, 2**hparams.bottleneck_bits, name="logits_dense") current_output_position = common_layers.shape_list(ids)[1] - 1 logits = logits[:, current_output_position, :] return logits initial_ids = tf.zeros([tf.shape(latents_dense_in)[0]], dtype=tf.int32) length = tf.shape(latents_dense_in)[1] ids, _, _ = beam_search.beam_search( symbols_to_logits_fn, initial_ids, 1, length, 2**hparams.bottleneck_bits, alpha=0.0, eos_id=-1, stop_early=False) res = tf.expand_dims(ids[:, 0, :], axis=2) # Pick first beam. return res[:, 1:]
<SYSTEM_TASK:> Residual block over inputs. <END_TASK> <USER_TASK:> Description: def residual_block_layer(inputs, hparams): """Residual block over inputs. Runs a residual block consisting of conv: kernel_size x kernel_size conv: 1x1 dropout, add and normalize according to hparams.layer_postprocess_sequence. Args: inputs: Tensor of shape [batch, height, width, hparams.hidden_size]. hparams: HParams. Returns: Tensor of shape [batch, height, width, hparams.hidden_size]. """
kernel = (hparams.res_kernel_size, hparams.res_kernel_size) x = inputs for i in range(hparams.num_res_layers): with tf.variable_scope("res_conv_%d" % i): # kernel_size x kernel_size conv block y = common_layers.conv_block( common_layers.layer_norm(x, hparams.hidden_size, name="lnorm"), hparams.hidden_size, [((1, 1), kernel)], strides=(1, 1), padding="SAME", name="residual_conv") # 1x1 conv block y = common_layers.conv_block( y, hparams.hidden_size, [((1, 1), (1, 1))], strides=(1, 1), padding="SAME", name="residual_dense") x = common_layers.layer_postprocess(x, y, hparams) return x
<SYSTEM_TASK:> Transformer text encoder over inputs with unmasked full attention. <END_TASK> <USER_TASK:> Description: def transformer_text_encoder(inputs, target_space, hparams, name=None): """Transformer text encoder over inputs with unmasked full attention. Args: inputs: Tensor of shape [batch, length, 1, hparams.hidden_size]. target_space: int. Used for encoding inputs under a target space id. hparams: HParams. name: string, variable scope. Returns: encoder_output: Tensor of shape [batch, length, hparams.hidden_size]. ed: Tensor of shape [batch, 1, 1, length]. Encoder-decoder attention bias for any padded tokens. """
with tf.variable_scope(name, default_name="transformer_text_encoder"): inputs = common_layers.flatten4d3d(inputs) [ encoder_input, encoder_self_attention_bias, ed, ] = transformer_layers.transformer_prepare_encoder( inputs, target_space=target_space, hparams=hparams) encoder_input = tf.nn.dropout(encoder_input, 1.0 - hparams.dropout) encoder_output = transformer_layers.transformer_encoder( encoder_input, encoder_self_attention_bias, hparams) return encoder_output, ed
<SYSTEM_TASK:> Transformer image decoder over targets with local attention. <END_TASK> <USER_TASK:> Description: def transformer_image_decoder(targets, encoder_output, ed_attention_bias, hparams, name=None): """Transformer image decoder over targets with local attention. Args: targets: Tensor of shape [batch, ...], and whose size is batch * height * width * hparams.num_channels * hparams.hidden_size. encoder_output: Tensor of shape [batch, length_kv, hparams.hidden_size]. ed_attention_bias: Tensor which broadcasts with shape [batch, hparams.num_heads, length_q, length_kv]. Encoder-decoder attention bias. hparams: HParams. name: string, variable scope. Returns: Tensor of shape [batch, height, width * hparams.num_channels, hparams.hidden_size]. """
with tf.variable_scope(name, default_name="transformer_dec"): batch_size = common_layers.shape_list(targets)[0] targets = tf.reshape(targets, [batch_size, hparams.img_len, hparams.img_len, hparams.num_channels * hparams.hidden_size]) decoder_input, _, _ = cia.prepare_decoder(targets, hparams) decoder_output = cia.transformer_decoder_layers( decoder_input, encoder_output, hparams.num_decoder_layers or hparams.num_hidden_layers, hparams, attention_type=hparams.dec_attention_type, encoder_decoder_attention_bias=ed_attention_bias, name="decoder") decoder_output = tf.reshape(decoder_output, [batch_size, hparams.img_len, hparams.img_len * hparams.num_channels, hparams.hidden_size]) return decoder_output
<SYSTEM_TASK:> Transformer decoder over latents using latent_attention_type. <END_TASK> <USER_TASK:> Description: def transformer_latent_decoder(x, encoder_output, ed_attention_bias, hparams, name=None): """Transformer decoder over latents using latent_attention_type. Args: x: Tensor of shape [batch, length_q, hparams.hidden_size]. length_q is the latent length, which is height * width * hparams.num_latents / (2**hparams.num_compress_steps). encoder_output: Tensor of shape [batch, length_kv, hparams.hidden_size]. ed_attention_bias: Tensor which broadcasts with shape [batch, hparams.num_heads, length_q, length_kv]. Encoder-decoder attention bias. hparams: HParams. name: string, variable scope. Returns: Tensor of shape [batch, length_q, hparams.hidden_size]. """
with tf.variable_scope(name, default_name="transformer_latent_dec"): batch_size = common_layers.shape_list(x)[0] compressed_img_len = (hparams.img_len // 2**(hparams.num_compress_steps // 2)) x = tf.reshape(x, [batch_size, compressed_img_len, compressed_img_len * hparams.num_latents, hparams.hidden_size]) decoder_input, _, _ = cia.prepare_decoder(x, hparams) decoder_output = cia.transformer_decoder_layers( decoder_input, encoder_output, hparams.num_latent_layers or hparams.num_hidden_layers, hparams, attention_type=hparams.latent_attention_type, encoder_decoder_attention_bias=ed_attention_bias, name="decoder") decoder_output = tf.reshape(decoder_output, [batch_size, compressed_img_len**2 * hparams.num_latents, hparams.hidden_size]) return decoder_output
<SYSTEM_TASK:> Transformer-based latent prediction model. <END_TASK> <USER_TASK:> Description: def latent_prediction_model(inputs, ed_attention_bias, latents_discrete, latents_dense, hparams, vocab_size=None, name=None): """Transformer-based latent prediction model. It is an autoregressive decoder over latents_discrete given inputs. Args: inputs: Tensor of shape [batch, length_kv, hparams.hidden_size]. Inputs to attend to for the decoder on latents. ed_attention_bias: Tensor which broadcasts with shape [batch, hparams.num_heads, length_q, length_kv]. Encoder-decoder attention bias. latents_discrete: Tensor of shape [batch, length_q, vocab_size]. One-hot latents to compute log-probability of given inputs. latents_dense: Tensor of shape [batch, length_q, hparams.hidden_size]. length_q is the latent length, which is height * width * hparams.num_latents / (2**hparams.num_compress_steps). hparams: HParams. vocab_size: int or None. If None, it is 2**hparams.bottleneck_bits. name: string, variable scope. Returns: latents_pred: Tensor of shape [batch, length_q, hparams.hidden_size]. latents_pred_loss: Tensor of shape [batch, length_q]. """
with tf.variable_scope(name, default_name="latent_prediction"): if hparams.mode != tf.estimator.ModeKeys.PREDICT: latents_pred = transformer_latent_decoder(tf.stop_gradient(latents_dense), inputs, ed_attention_bias, hparams, name) if vocab_size is None: vocab_size = 2**hparams.bottleneck_bits if not hparams.soft_em: # TODO(trandustin): latents_discrete is not one-hot from # discrete_bottleneck unless hparams.soft_em is True. Refactor. latents_discrete = tf.one_hot(latents_discrete, depth=vocab_size) _, latent_pred_loss = ae_latent_softmax( latents_pred, tf.stop_gradient(latents_discrete), vocab_size, hparams) return latents_pred, latent_pred_loss
<SYSTEM_TASK:> Performs a single IAF flow using scale and normalization transformations. <END_TASK> <USER_TASK:> Description: def iaf_flow(one_hot_assignments, scale_weights, scale_bias, num_codes, summary=True, name=None): """Performs a single IAF flow using scale and normalization transformations. Args: one_hot_assignments: Assignments Tensor with shape [num_samples, batch_size, latent_size, num_codes]. scale_weights: Tensor corresponding to lower triangular matrix used to autoregressively generate scale matrix from assignments. To ensure the lower-triangular matrix has length of latent_size, scale_weights should be a rank-one tensor with size latent_size * (latent_size + 1) / 2. scale_bias: Bias tensor to be added to scale tensor, with shape [latent_size, num_codes]. If scale weights are zero, initialize scale_bias to be log(exp(1.) / 2. - 1) so initial transformation is identity. num_codes: Number of codes in codebook. summary: Whether to save summaries. name: String used for name scope. Returns: flow_output: Transformed one-hot assignments. inverse_log_det_jacobian: Inverse log deteriminant of Jacobian corresponding to transformation. """
with tf.name_scope(name, default_name="iaf"): # Pad the one_hot_assignments by zeroing out the first latent dimension and # shifting the rest down by one (and removing the last dimension). padded_assignments = tf.pad( one_hot_assignments, [[0, 0], [0, 0], [1, 0], [0, 0]])[:, :, :-1, :] scale_bijector = tfp.distributions.bijectors.Affine( scale_tril=tfp.distributions.fill_triangular(scale_weights)) scale = scale_bijector.forward( tf.transpose(padded_assignments, [0, 1, 3, 2])) # Transpose the bijector output since it performs a batch matmul. scale = tf.transpose(scale, [0, 1, 3, 2]) scale = tf.nn.softplus(scale) scale = scale + tf.nn.softplus(scale_bias[tf.newaxis, tf.newaxis, ...]) # Don't need last dimension since the transformation keeps it constant. scale = scale[..., :-1] z = one_hot_assignments[..., :-1] unnormalized_probs = tf.concat([z * scale, one_hot_assignments[..., -1, tf.newaxis]], axis=-1) normalizer = tf.reduce_sum(unnormalized_probs, axis=-1) flow_output = unnormalized_probs / (normalizer[..., tf.newaxis]) inverse_log_det_jacobian = (-tf.reduce_sum(tf.log(scale), axis=-1) + num_codes * tf.log(normalizer)) if summary: tf.summary.histogram("iaf/scale", tf.reshape(scale, [-1])) tf.summary.histogram("iaf/inverse_log_det_jacobian", tf.reshape(inverse_log_det_jacobian, [-1])) return flow_output, inverse_log_det_jacobian
<SYSTEM_TASK:> Downloads all lsun files to directory unless they are there. <END_TASK> <USER_TASK:> Description: def _get_lsun(directory, category, split_name): """Downloads all lsun files to directory unless they are there."""
generator_utils.maybe_download(directory, _LSUN_DATA_FILENAME % (category, split_name), _LSUN_URL % (category, split_name))
<SYSTEM_TASK:> Should be the same as in common_attention, avoiding import. <END_TASK> <USER_TASK:> Description: def _mixed_precision_is_enabled(hparams): """Should be the same as in common_attention, avoiding import."""
activation_dtype = hparams.activation_dtype weight_dtype = hparams.weight_dtype return activation_dtype == tf.float16 and weight_dtype == tf.float32
<SYSTEM_TASK:> Apply weight decay and weight noise. <END_TASK> <USER_TASK:> Description: def weight_decay_and_noise(loss, hparams, learning_rate, var_list=None): """Apply weight decay and weight noise."""
if var_list is None: var_list = tf.trainable_variables() decay_vars = [v for v in var_list] noise_vars = [v for v in var_list if "/body/" in v.name] weight_decay_loss = weight_decay(hparams.weight_decay, decay_vars) if hparams.weight_decay and common_layers.should_generate_summaries(): tf.summary.scalar("losses/weight_decay", weight_decay_loss) weight_noise_ops = weight_noise(hparams.weight_noise, learning_rate, noise_vars) with tf.control_dependencies(weight_noise_ops): loss = tf.identity(loss) loss += weight_decay_loss return loss
<SYSTEM_TASK:> Apply weight noise to vars in var_list. <END_TASK> <USER_TASK:> Description: def weight_noise(noise_rate, learning_rate, var_list): """Apply weight noise to vars in var_list."""
if not noise_rate: return [tf.no_op()] tf.logging.info("Applying weight noise scaled by learning rate, " "noise_rate: %0.5f", noise_rate) noise_ops = [] for v in var_list: with tf.device(v.device): # pylint: disable=protected-access scale = noise_rate * learning_rate * 0.001 if common_layers.should_generate_summaries(): tf.summary.scalar("weight_noise_scale", scale) noise = tf.truncated_normal(v.shape) * scale noise_op = v.assign_add(noise) noise_ops.append(noise_op) return noise_ops
<SYSTEM_TASK:> Apply weight decay to vars in var_list. <END_TASK> <USER_TASK:> Description: def weight_decay(decay_rate, var_list, skip_biases=True): """Apply weight decay to vars in var_list."""
if not decay_rate: return 0. tf.logging.info("Applying weight decay, decay_rate: %0.5f", decay_rate) weight_decays = [] for v in var_list: # Weight decay. # This is a heuristic way to detect biases that works for main tf.layers. is_bias = len(v.shape.as_list()) == 1 and v.name.endswith("bias:0") if not (skip_biases and is_bias): with tf.device(v.device): v_loss = tf.nn.l2_loss(v) weight_decays.append(v_loss) return tf.add_n(weight_decays) * decay_rate
<SYSTEM_TASK:> Summarize the variables. <END_TASK> <USER_TASK:> Description: def summarize_variables(var_list=None, tag=None): """Summarize the variables. Args: var_list: a list of variables; defaults to trainable_variables. tag: name scope of the summary; defaults to training_variables/. """
if var_list is None: var_list = tf.trainable_variables() if tag is None: tag = "training_variables/" name_to_var = {v.name: v for v in var_list} for v_name in list(name_to_var): v = name_to_var[v_name] tf.summary.histogram(tag + v_name, v)
<SYSTEM_TASK:> Get variable initializer from hparams. <END_TASK> <USER_TASK:> Description: def get_variable_initializer(hparams): """Get variable initializer from hparams."""
if not hparams.initializer: return None mlperf_log.transformer_print(key=mlperf_log.MODEL_HP_INITIALIZER_GAIN, value=hparams.initializer_gain, hparams=hparams) if not tf.executing_eagerly(): tf.logging.info("Using variable initializer: %s", hparams.initializer) if hparams.initializer == "orthogonal": return tf.orthogonal_initializer(gain=hparams.initializer_gain) elif hparams.initializer == "uniform": max_val = 0.1 * hparams.initializer_gain return tf.random_uniform_initializer(-max_val, max_val) elif hparams.initializer == "normal_unit_scaling": return tf.variance_scaling_initializer( hparams.initializer_gain, mode="fan_avg", distribution="normal") elif hparams.initializer == "uniform_unit_scaling": return tf.variance_scaling_initializer( hparams.initializer_gain, mode="fan_avg", distribution="uniform") elif hparams.initializer == "xavier": return tf.initializers.glorot_uniform() else: raise ValueError("Unrecognized initializer: %s" % hparams.initializer)
<SYSTEM_TASK:> Extract image features from pretrained resnet model. <END_TASK> <USER_TASK:> Description: def image_embedding(images, model_fn=resnet_v1_152, trainable=True, is_training=True, weight_decay=0.0001, batch_norm_decay=0.997, batch_norm_epsilon=1e-5, batch_norm_scale=True, add_summaries=False, reuse=False): """Extract image features from pretrained resnet model."""
is_resnet_training = trainable and is_training batch_norm_params = { "is_training": is_resnet_training, "trainable": trainable, "decay": batch_norm_decay, "epsilon": batch_norm_epsilon, "scale": batch_norm_scale, } if trainable: weights_regularizer = tf.contrib.layers.l2_regularizer(weight_decay) else: weights_regularizer = None with tf.variable_scope(model_fn.__name__, [images], reuse=reuse) as scope: with slim.arg_scope( [slim.conv2d], weights_regularizer=weights_regularizer, trainable=trainable): with slim.arg_scope( [slim.conv2d], weights_initializer=slim.variance_scaling_initializer(), activation_fn=tf.nn.relu, normalizer_fn=slim.batch_norm, normalizer_params=batch_norm_params): with slim.arg_scope([slim.batch_norm], is_training=is_resnet_training, trainable=trainable): with slim.arg_scope([slim.max_pool2d], padding="SAME"): net, end_points = model_fn( images, num_classes=None, global_pool=False, is_training=is_resnet_training, reuse=reuse, scope=scope) if add_summaries: for v in end_points.values(): tf.contrib.layers.summaries.summarize_activation(v) return net
<SYSTEM_TASK:> Data generator for TIMIT transcription problem. <END_TASK> <USER_TASK:> Description: def timit_generator(data_dir, tmp_dir, training, how_many, start_from=0, eos_list=None, vocab_filename=None, vocab_size=0): """Data generator for TIMIT transcription problem. Args: data_dir: path to the data directory. tmp_dir: path to temporary storage directory. training: a Boolean; if true, we use the train set, otherwise the test set. how_many: how many inputs and labels to generate. start_from: from which input to start. eos_list: optional list of end of sentence tokens, otherwise use default value `1`. vocab_filename: file within `tmp_dir` to read vocabulary from. If this is not provided then the target sentence will be encoded by character. vocab_size: integer target to generate vocabulary size to. Yields: A dictionary representing the images with the following fields: * inputs: a float sequence containing the audio data * audio/channel_count: an integer * audio/sample_count: an integer * audio/sample_width: an integer * targets: an integer sequence representing the encoded sentence """
del data_dir eos_list = [1] if eos_list is None else eos_list if vocab_filename is not None: # TODO(lukaszkaiser): Correct this call to generate a vocabulary. No data # sources are being passed. # vocab_symbolizer = generator_utils.get_or_generate_vocab( # data_dir, tmp_dir, vocab_filename, vocab_size) del vocab_size vocab_symbolizer = None assert False _get_timit(tmp_dir) datasets = (_TIMIT_TRAIN_DATASETS if training else _TIMIT_TEST_DATASETS) i = 0 for timit_data_dir, (audio_ext, transcription_ext) in datasets: timit_data_dir = os.path.join(tmp_dir, timit_data_dir) data_files = _collect_data(timit_data_dir, audio_ext, transcription_ext) data_pairs = data_files.values() for input_file, target_file in sorted(data_pairs)[start_from:]: if i == how_many: return i += 1 audio_data, sample_count, sample_width, num_channels = _get_audio_data( input_file) text_data = _get_text_data(target_file) if vocab_filename is None: label = [ord(c) for c in text_data] + eos_list else: label = vocab_symbolizer.encode(text_data) + eos_list yield { "inputs": audio_data, "audio/channel_count": [num_channels], "audio/sample_count": [sample_count], "audio/sample_width": [sample_width], "targets": label }
<SYSTEM_TASK:> Reads a file to build a vocabulary. <END_TASK> <USER_TASK:> Description: def _build_vocab(filename, vocab_dir, vocab_name): """Reads a file to build a vocabulary. Args: filename: file to read list of words from. vocab_dir: directory where to save the vocabulary. vocab_name: vocab file name. Returns: text encoder. """
vocab_path = os.path.join(vocab_dir, vocab_name) if not tf.gfile.Exists(vocab_path): with tf.gfile.GFile(filename, "r") as f: data = f.read().split() counter = collections.Counter(data) count_pairs = sorted(counter.items(), key=lambda x: (-x[1], x[0])) words, _ = list(zip(*count_pairs)) encoder = text_encoder.TokenTextEncoder(None, vocab_list=words) encoder.store_to_file(vocab_path) else: encoder = text_encoder.TokenTextEncoder(vocab_path) return encoder
<SYSTEM_TASK:> version for languagemodel_wiki_scramble8k50. <END_TASK> <USER_TASK:> Description: def aligned_8k_grouped(): """version for languagemodel_wiki_scramble8k50. languagemodel_wiki_scramble1k50, 1gpu, 7k steps: log(ppl)_eval = 2.92 3.3 steps/sec on P100 8gpu (8x batch), 7k steps: log(ppl)_eval = 2.15 Returns: a hparams object """
hparams = aligned_grouped() hparams.batch_size = 8192 # hparams.attention_image_summary = False hparams.num_groups = 16 hparams.multiplicative_overhead = 1.1 return hparams
<SYSTEM_TASK:> Tiles a given tensor by beam_size. <END_TASK> <USER_TASK:> Description: def _expand_to_beam_size(tensor, beam_size): """Tiles a given tensor by beam_size. Args: tensor: tensor to tile [batch_size, ...] beam_size: How much to tile the tensor by. Returns: Tiled tensor [batch_size, beam_size, ...] """
tensor = tf.expand_dims(tensor, axis=1) tile_dims = [1] * tensor.shape.ndims tile_dims[1] = beam_size return tf.tile(tensor, tile_dims)
<SYSTEM_TASK:> Returns the shape of the tensor but sets middle dims to None. <END_TASK> <USER_TASK:> Description: def get_state_shape_invariants(tensor): """Returns the shape of the tensor but sets middle dims to None."""
shape = tensor.shape.as_list() for i in range(1, len(shape) - 1): shape[i] = None return tf.TensorShape(shape)
<SYSTEM_TASK:> Computes the i'th coordinate that contains the batch index for gathers. <END_TASK> <USER_TASK:> Description: def compute_batch_indices(batch_size, beam_size): """Computes the i'th coordinate that contains the batch index for gathers. Batch pos is a tensor like [[0,0,0,0,],[1,1,1,1],..]. It says which batch the beam item is in. This will create the i of the i,j coordinate needed for the gather. Args: batch_size: Batch size beam_size: Size of the beam. Returns: batch_pos: [batch_size, beam_size] tensor of ids """
batch_pos = tf.range(batch_size * beam_size) // beam_size batch_pos = tf.reshape(batch_pos, [batch_size, beam_size]) return batch_pos
<SYSTEM_TASK:> Fast gather implementation for models running on TPU. <END_TASK> <USER_TASK:> Description: def fast_tpu_gather(params, indices, name=None): """Fast gather implementation for models running on TPU. This function use one_hot and batch matmul to do gather, which is faster than gather_nd on TPU. For params that have dtype of int32 (sequences to gather from), batch_gather is used to keep accuracy. Args: params: A tensor from which to gather values. [batch_size, original_size, ...] indices: A tensor used as the index to gather values. [batch_size, selected_size]. name: A string, name of the operation (optional). Returns: gather_result: A tensor that has the same rank as params. [batch_size, selected_size, ...] """
with tf.name_scope(name): dtype = params.dtype def _gather(params, indices): """Fast gather using one_hot and batch matmul.""" if dtype != tf.float32: params = tf.to_float(params) shape = common_layers.shape_list(params) indices_shape = common_layers.shape_list(indices) ndims = params.shape.ndims # Adjust the shape of params to match one-hot indices, which is the # requirement of Batch MatMul. if ndims == 2: params = tf.expand_dims(params, axis=-1) if ndims > 3: params = tf.reshape(params, [shape[0], shape[1], -1]) gather_result = tf.matmul( tf.one_hot(indices, shape[1], dtype=params.dtype), params) if ndims == 2: gather_result = tf.squeeze(gather_result, axis=-1) if ndims > 3: shape[1] = indices_shape[1] gather_result = tf.reshape(gather_result, shape) if dtype != tf.float32: gather_result = tf.cast(gather_result, dtype) return gather_result # If the dtype is int, use the gather instead of one_hot matmul to avoid # precision loss. The max int value can be represented by bfloat16 in MXU is # 256, which is smaller than the possible id values. Encoding/decoding can # potentially used to make it work, but the benenfit is small right now. if dtype.is_integer: gather_result = tf.batch_gather(params, indices) else: gather_result = _gather(params, indices) return gather_result
<SYSTEM_TASK:> Replaces the lower bits of each element with iota. <END_TASK> <USER_TASK:> Description: def _create_make_unique(inputs): """Replaces the lower bits of each element with iota. The iota is used to derive the index, and also serves the purpose to make each element unique to break ties. Args: inputs: A tensor with rank of 2 and dtype of tf.float32. [batch_size, original_size]. Returns: A tensor after element wise transformation, with dtype the same as inputs. [batch_size, original_size]. Raises: ValueError: If the rank of the input tensor does not equal 2. """
if inputs.shape.ndims != 2: raise ValueError("Input of top_k_with_unique must be rank-2 " "but got: %s" % inputs.shape) height = inputs.shape[0] width = inputs.shape[1] zeros = tf.zeros([height, width], dtype=tf.int32) # Count_mask is used to mask away the low order bits to ensure that every # element is distinct. log2_ceiling = int(math.ceil(math.log(int(width), 2))) next_power_of_two = 1 << log2_ceiling count_mask = ~(next_power_of_two - 1) count_mask_r0 = tf.constant(count_mask) count_mask_r2 = tf.fill([height, width], count_mask_r0) # Smallest_normal is the bit representation of the smallest positive normal # floating point number. The sign is zero, exponent is one, and the fraction # is zero. smallest_normal = 1 << 23 smallest_normal_r0 = tf.constant(smallest_normal, dtype=tf.int32) smallest_normal_r2 = tf.fill([height, width], smallest_normal_r0) # Low_bit_mask is used to mask away the sign bit when computing the absolute # value. low_bit_mask = ~(1 << 31) low_bit_mask_r0 = tf.constant(low_bit_mask, dtype=tf.int32) low_bit_mask_r2 = tf.fill([height, width], low_bit_mask_r0) iota = tf.tile(tf.expand_dims(tf.range(width, dtype=tf.int32), 0), [height, 1]) # Compare the absolute value with positive zero to handle negative zero. input_r2 = tf.bitcast(inputs, tf.int32) abs_r2 = tf.bitwise.bitwise_and(input_r2, low_bit_mask_r2) if_zero_r2 = tf.equal(abs_r2, zeros) smallest_normal_preserving_sign_r2 = tf.bitwise.bitwise_or( input_r2, smallest_normal_r2) input_no_zeros_r2 = tf.where( if_zero_r2, smallest_normal_preserving_sign_r2, input_r2) # Discard the low-order bits and replace with iota. and_r2 = tf.bitwise.bitwise_and(input_no_zeros_r2, count_mask_r2) or_r2 = tf.bitwise.bitwise_or(and_r2, iota) return tf.bitcast(or_r2, tf.float32)
<SYSTEM_TASK:> Creates the top k values in sorted order with indices. <END_TASK> <USER_TASK:> Description: def _create_topk_unique(inputs, k): """Creates the top k values in sorted order with indices. Args: inputs: A tensor with rank of 2. [batch_size, original_size]. k: An integer, number of top elements to select. Returns: topk_r2: A tensor, the k largest elements. [batch_size, k]. topk_indices_r2: A tensor, indices of the top k values. [batch_size, k]. """
height = inputs.shape[0] width = inputs.shape[1] neg_inf_r0 = tf.constant(-np.inf, dtype=tf.float32) ones = tf.ones([height, width], dtype=tf.float32) neg_inf_r2 = ones * neg_inf_r0 inputs = tf.where(tf.is_nan(inputs), neg_inf_r2, inputs) # Select the current largest value k times and keep them in topk_r2. The # selected largest values are marked as the smallest value to avoid being # selected again. tmp = inputs topk_r2 = tf.zeros([height, k], dtype=tf.float32) for i in range(k): kth_order_statistic = tf.reduce_max(tmp, axis=1, keepdims=True) k_mask = tf.tile(tf.expand_dims(tf.equal(tf.range(k), tf.fill([k], i)), 0), [height, 1]) topk_r2 = tf.where(k_mask, tf.tile(kth_order_statistic, [1, k]), topk_r2) ge_r2 = tf.greater_equal(inputs, tf.tile(kth_order_statistic, [1, width])) tmp = tf.where(ge_r2, neg_inf_r2, inputs) log2_ceiling = int(math.ceil(math.log(float(int(width)), 2))) next_power_of_two = 1 << log2_ceiling count_mask = next_power_of_two - 1 mask_r0 = tf.constant(count_mask) mask_r2 = tf.fill([height, k], mask_r0) topk_r2_s32 = tf.bitcast(topk_r2, tf.int32) topk_indices_r2 = tf.bitwise.bitwise_and(topk_r2_s32, mask_r2) return topk_r2, topk_indices_r2
<SYSTEM_TASK:> Finds the values and indices of the k largests entries. <END_TASK> <USER_TASK:> Description: def top_k_with_unique(inputs, k): """Finds the values and indices of the k largests entries. Instead of doing sort like tf.nn.top_k, this function finds the max value k times. The running time is proportional to k, which is be faster when k is small. The current implementation supports only inputs of rank 2. In addition, iota is used to replace the lower bits of each element, this makes the selection more stable when there are equal elements. The overhead is that output values are approximated. Args: inputs: A tensor with rank of 2. [batch_size, original_size]. k: An integer, number of top elements to select. Returns: top_values: A tensor, the k largest elements in sorted order. [batch_size, k]. indices: A tensor, indices of the top_values. [batch_size, k]. """
unique_inputs = _create_make_unique(tf.cast(inputs, tf.float32)) top_values, indices = _create_topk_unique(unique_inputs, k) top_values = tf.cast(top_values, inputs.dtype) return top_values, indices
<SYSTEM_TASK:> Augments video with optional hue, saturation and constrast. <END_TASK> <USER_TASK:> Description: def video_augmentation(features, hue=False, saturate=False, contrast=False): """Augments video with optional hue, saturation and constrast. Args: features: dict, with keys "inputs", "targets". features["inputs"], 4-D Tensor, shape=(THWC) features["targets"], 4-D Tensor, shape=(THWC) hue: bool, apply hue_transform. saturate: bool, apply saturation transform. contrast: bool, apply constrast transform. Returns: augment_features: dict with transformed "inputs" and "targets". """
inputs, targets = features["inputs"], features["targets"] in_steps = common_layers.shape_list(inputs)[0] # makes sure that the same augmentation is applied to both input and targets. # if input is 4-D, then tf.image applies the same transform across the batch. video = tf.concat((inputs, targets), axis=0) if hue: video = tf.image.random_hue(video, max_delta=0.2) if saturate: video = tf.image.random_saturation(video, lower=0.5, upper=1.5) if contrast: video = tf.image.random_contrast(video, lower=0.5, upper=1.5) features["inputs"], features["targets"] = video[:in_steps], video[in_steps:] return features
<SYSTEM_TASK:> Creates a border around each frame to differentiate input and target. <END_TASK> <USER_TASK:> Description: def create_border(video, color="blue", border_percent=2): """Creates a border around each frame to differentiate input and target. Args: video: 5-D NumPy array. color: string, "blue", "red" or "green". border_percent: Percentarge of the frame covered by the border. Returns: video: 5-D NumPy array. """
# Do not create border if the video is not in RGB format if video.shape[-1] != 3: return video color_to_axis = {"blue": 2, "red": 0, "green": 1} axis = color_to_axis[color] _, _, height, width, _ = video.shape border_height = np.ceil(border_percent * height / 100.0).astype(np.int) border_width = np.ceil(border_percent * width / 100.0).astype(np.int) video[:, :, :border_height, :, axis] = 255 video[:, :, -border_height:, :, axis] = 255 video[:, :, :, :border_width, axis] = 255 video[:, :, :, -border_width:, axis] = 255 return video
<SYSTEM_TASK:> Converts input, output and target videos into video summaries. <END_TASK> <USER_TASK:> Description: def convert_videos_to_summaries(input_videos, output_videos, target_videos, tag, decode_hparams, display_ground_truth=False): """Converts input, output and target videos into video summaries. Args: input_videos: 5-D NumPy array, (NTHWC) conditioning frames. output_videos: 5-D NumPy array, (NTHWC) model predictions. target_videos: 5-D NumPy array, (NTHWC) target frames. tag: tf summary tag. decode_hparams: HParams. display_ground_truth: Whether or not to display ground truth videos. Returns: summaries: a list of tf frame-by-frame and video summaries. """
fps = decode_hparams.frames_per_second border_percent = decode_hparams.border_percent max_outputs = decode_hparams.max_display_outputs target_steps = target_videos.shape[1] all_summaries = [] input_videos = create_border( input_videos, color="blue", border_percent=border_percent) target_videos = create_border( target_videos, color="red", border_percent=border_percent) output_videos = create_border( output_videos, color="red", border_percent=border_percent) all_input = np.concatenate((input_videos, target_videos), axis=1) all_output = np.concatenate((input_videos, output_videos), axis=1) output_summ_vals, _ = common_video.py_gif_summary( "%s/output" % tag, all_output, max_outputs=max_outputs, fps=fps, return_summary_value=True) all_summaries.extend(output_summ_vals) # Optionally display ground truth. if display_ground_truth: input_summ_vals, _ = common_video.py_gif_summary( "%s/input" % tag, all_input, max_outputs=max_outputs, fps=fps, return_summary_value=True) all_summaries.extend(input_summ_vals) # Frame-by-frame summaries iterable = zip(output_videos[:max_outputs, :target_steps], target_videos[:max_outputs]) for ind, (input_video, output_video) in enumerate(iterable): t, h, w, c = input_video.shape # Tile vertically input_frames = np.reshape(input_video, (t*h, w, c)) output_frames = np.reshape(output_video, (t*h, w, c)) # Concat across width. all_frames = np.concatenate((input_frames, output_frames), axis=1) tag = "input/output/%s_sample_%d" % (tag, ind) frame_by_frame_summ = image_utils.image_to_tf_summary_value( all_frames, tag=tag) all_summaries.append(frame_by_frame_summ) return all_summaries
<SYSTEM_TASK:> Hooks to display videos at decode time. <END_TASK> <USER_TASK:> Description: def display_video_hooks(hook_args): """Hooks to display videos at decode time."""
predictions = hook_args.predictions max_outputs = hook_args.decode_hparams.max_display_outputs max_decodes = hook_args.decode_hparams.max_display_decodes with tf.Graph().as_default(): _, best_decodes = video_metrics.compute_video_metrics_from_predictions( predictions, decode_hparams=hook_args.decode_hparams) all_summaries = [] # Displays decodes corresponding to the best/worst metric, for metric, metric_decode_inds in best_decodes.items(): curr_metric_inds = metric_decode_inds[:max_outputs] best_inputs, best_outputs, best_targets = [], [], [] for sample_ind, decode_ind in enumerate(curr_metric_inds): curr_decode = predictions[decode_ind][sample_ind] best_inputs.append(curr_decode["inputs"]) best_outputs.append(curr_decode["outputs"]) best_targets.append(curr_decode["targets"]) best_inputs = np.array(best_inputs, dtype=np.uint8) best_outputs = np.array(best_outputs, dtype=np.uint8) best_targets = np.array(best_targets, dtype=np.uint8) summaries = convert_videos_to_summaries( best_inputs, best_outputs, best_targets, tag=metric, decode_hparams=hook_args.decode_hparams) all_summaries.extend(summaries) # Display random decodes for ten conditioning frames. for decode_ind, decode in enumerate(predictions[: max_decodes]): target_videos = video_metrics.stack_data_given_key(decode, "targets") output_videos = video_metrics.stack_data_given_key(decode, "outputs") input_videos = video_metrics.stack_data_given_key(decode, "inputs") target_videos = np.asarray(target_videos, dtype=np.uint8) output_videos = np.asarray(output_videos, dtype=np.uint8) input_videos = np.asarray(input_videos, dtype=np.uint8) summaries = convert_videos_to_summaries( input_videos, output_videos, target_videos, tag="decode_%d" % decode_ind, decode_hparams=hook_args.decode_hparams, display_ground_truth=decode_ind == 0) all_summaries.extend(summaries) return all_summaries
<SYSTEM_TASK:> Computes video metrics summaries using the decoder output. <END_TASK> <USER_TASK:> Description: def summarize_video_metrics(hook_args): """Computes video metrics summaries using the decoder output."""
problem_name = hook_args.problem.name current_problem = hook_args.problem hparams = hook_args.hparams output_dirs = hook_args.output_dirs predictions = hook_args.predictions frame_shape = [ current_problem.frame_height, current_problem.frame_width, current_problem.num_channels ] metrics_graph = tf.Graph() with metrics_graph.as_default(): if predictions: metrics_results, _ = video_metrics.compute_video_metrics_from_predictions( predictions, decode_hparams=hook_args.decode_hparams) else: metrics_results, _ = video_metrics.compute_video_metrics_from_png_files( output_dirs, problem_name, hparams.video_num_target_frames, frame_shape) summary_values = [] for name, array in six.iteritems(metrics_results): for ind, val in enumerate(array): tag = "metric_{}/{}".format(name, ind) summary_values.append(tf.Summary.Value(tag=tag, simple_value=val)) return summary_values
<SYSTEM_TASK:> Generate samples of the encoded frames with possible extra data. <END_TASK> <USER_TASK:> Description: def generate_encoded_samples(self, data_dir, tmp_dir, dataset_split): """Generate samples of the encoded frames with possible extra data. By default this function just encodes the numpy array returned as "frame" from `self.generate_samples` into a PNG image. Override this function to get other encodings on disk. Args: data_dir: final data directory. Typically only used in this method to copy over user-supplied vocab files if there are extra fields needing them. tmp_dir: temporary directory that you can use for downloading and scratch. dataset_split: problem.DatasetSplit, which data split to generate samples for (for example, training and evaluation). Yields: Sample: dict<str feature_name, feature value> which is in disk encoding. Raises: ValueError: if the frame has a different number of channels than required. """
writer = None with tf.Graph().as_default(): image_t = tf.placeholder(dtype=tf.uint8, shape=(None, None, None)) encoded_image_t = tf.image.encode_png(image_t) with tf.Session() as sess: for features in self.generate_samples(data_dir, tmp_dir, dataset_split): unencoded_frame = features.pop("frame") self.validate_frame(unencoded_frame) height, width, _ = unencoded_frame.shape encoded_frame = sess.run( encoded_image_t, feed_dict={image_t: unencoded_frame}) features["image/encoded"] = [encoded_frame] features["image/format"] = ["png"] features["image/height"] = [height] features["image/width"] = [width] has_debug_image = "image/debug" in features if has_debug_image: unencoded_debug = features.pop("image/debug") encoded_debug = sess.run( encoded_image_t, feed_dict={image_t: unencoded_debug}) features["image/encoded_debug"] = [encoded_debug] if self.debug_dump_frames_path: # Defer creating debug writer until we know debug_dump_frames_path. if writer is None: if not tf.gfile.Exists(self.debug_dump_frames_path): tf.gfile.MkDir(self.debug_dump_frames_path) writer = debug_video_writer_factory(self.debug_dump_frames_path) img = unencoded_debug if has_debug_image else unencoded_frame encoded_img = encoded_debug if has_debug_image else encoded_frame writer.write(img, encoded_img) yield features if self.debug_dump_frames_path: writer.finish_to_disk()
<SYSTEM_TASK:> Proxy methods of underlying variable. <END_TASK> <USER_TASK:> Description: def _add_variable_proxy_methods(var, proxy_tensor): """Proxy methods of underlying variable. This enables our custom getters to still work with, e.g., batch norm. Args: var: Variable to proxy proxy_tensor: Tensor that is identity of var """
proxy_tensor.read_value = lambda: tf.identity(proxy_tensor) proxy_tensor.assign_sub = var.assign_sub proxy_tensor.assign = var.assign proxy_tensor.initialized_value = var.initialized_value
<SYSTEM_TASK:> UnsortedSegmentSum on each row. <END_TASK> <USER_TASK:> Description: def _rowwise_unsorted_segment_sum(values, indices, n): """UnsortedSegmentSum on each row. Args: values: a `Tensor` with shape `[batch_size, k]`. indices: an integer `Tensor` with shape `[batch_size, k]`. n: an integer. Returns: A `Tensor` with the same type as `values` and shape `[batch_size, n]`. """
batch, k = tf.unstack(tf.shape(indices), num=2) indices_flat = tf.reshape(indices, [-1]) + tf.div(tf.range(batch * k), k) * n ret_flat = tf.unsorted_segment_sum( tf.reshape(values, [-1]), indices_flat, batch * n) return tf.reshape(ret_flat, [batch, n])
<SYSTEM_TASK:> Helper function to NoisyTopKGating. <END_TASK> <USER_TASK:> Description: def _prob_in_top_k( clean_values, noisy_values, noise_stddev, noisy_top_values, k): """Helper function to NoisyTopKGating. Computes the probability that value is in top k, given different random noise. This gives us a way of backpropagating from a loss that balances the number of times each expert is in the top k experts per example. In the case of no noise, pass in None for noise_stddev, and the result will not be differentiable. Args: clean_values: a `Tensor` of shape [batch, n]. noisy_values: a `Tensor` of shape [batch, n]. Equal to clean values plus normally distributed noise with standard deviation noise_stddev. noise_stddev: a `Tensor` of shape [batch, n], or None noisy_top_values: a `Tensor` of shape [batch, m]. "values" Output of tf.top_k(noisy_top_values, m). m >= k+1 k: an integer. Returns: a `Tensor` of shape [batch, n]. """
batch = tf.shape(clean_values)[0] m = tf.shape(noisy_top_values)[1] top_values_flat = tf.reshape(noisy_top_values, [-1]) # we want to compute the threshold that a particular value would have to # exceed in order to make the top k. This computation differs depending # on whether the value is already in the top k. threshold_positions_if_in = tf.range(batch) * m + k threshold_if_in = tf.expand_dims( tf.gather(top_values_flat, threshold_positions_if_in), 1) is_in = tf.greater(noisy_values, threshold_if_in) if noise_stddev is None: return tf.to_float(is_in) threshold_positions_if_out = threshold_positions_if_in - 1 threshold_if_out = tf.expand_dims( tf.gather(top_values_flat, threshold_positions_if_out), 1) # is each value currently in the top k. prob_if_in = _normal_distribution_cdf(clean_values - threshold_if_in, noise_stddev) prob_if_out = _normal_distribution_cdf(clean_values - threshold_if_out, noise_stddev) prob = tf.where(is_in, prob_if_in, prob_if_out) return prob
<SYSTEM_TASK:> The squared coefficient of variation of a sample. <END_TASK> <USER_TASK:> Description: def cv_squared(x): """The squared coefficient of variation of a sample. Useful as a loss to encourage a positive distribution to be more uniform. Epsilons added for numerical stability. Returns 0 for an empty Tensor. Args: x: a `Tensor`. Returns: a `Scalar`. """
epsilon = 1e-10 float_size = tf.to_float(tf.size(x)) + epsilon mean = tf.reduce_sum(x) / float_size variance = tf.reduce_sum(tf.squared_difference(x, mean)) / float_size return variance / (tf.square(mean) + epsilon)
<SYSTEM_TASK:> GPU-compatible version of top-k that works for very small constant k. <END_TASK> <USER_TASK:> Description: def _my_top_k(x, k): """GPU-compatible version of top-k that works for very small constant k. Calls argmax repeatedly. tf.nn.top_k is implemented for GPU, but the gradient, sparse_to_dense, seems not to be, so if we use tf.nn.top_k, then both the top_k and its gradient go on cpu. Once this is not an issue, this function becomes obsolete and should be replaced by tf.nn.top_k. Args: x: a 2d Tensor. k: a small integer. Returns: values: a Tensor of shape [batch_size, k] indices: a int32 Tensor of shape [batch_size, k] """
if k > 10: return tf.nn.top_k(x, k) values = [] indices = [] depth = tf.shape(x)[1] for i in range(k): values.append(tf.reduce_max(x, 1)) argmax = tf.argmax(x, 1) indices.append(argmax) if i + 1 < k: x += tf.one_hot(argmax, depth, -1e9) return tf.stack(values, axis=1), tf.to_int32(tf.stack(indices, axis=1))
<SYSTEM_TASK:> VQ gating. <END_TASK> <USER_TASK:> Description: def vq_gating(x, num_experts, k, bneck, hparams=None, name="vq_gating"): """VQ gating. Args: x: input Tensor with shape [batch_size, input_size] num_experts: an integer k: an integer - number of experts per example bneck: a bottleneck object hparams: optional hparams name: an optional string Returns: gates: a Tensor with shape [batch_size, num_experts] load: a Tensor with shape [num_experts] """
with tf.variable_scope(name, reuse=tf.AUTO_REUSE): if hparams.use_scales: scales = tf.get_variable( "scales", [num_experts], tf.float32, initializer=tf.ones_initializer()) scales = tf.nn.softmax(scales) hparams.scales = scales input_size = x.get_shape().as_list()[-1] batch_size = common_layers.shape_list(x)[0] if k > 1: # first project into two dense layers, chop and discretize, and gate # TODO(avaswani): Maybe scale the embeddings flowing out of the experts. # We might want to do this to match the computation being done by topk x = tf.layers.dense(x, input_size * k) # x goes from [batch_size, input_size*k] to [batch_size*k, input_size] x = tf.reshape(x, [batch_size * k, input_size]) inputs = tf.expand_dims(x, axis=1) inputs = tf.expand_dims(inputs, axis=1) # VQ hparams hparams.z_size = int(math.log(num_experts, 2)) hparams.hidden_size = input_size hparams.top_k = k d = bneck.discrete_bottleneck(inputs) centroids = None exp_discrete = d["discrete"] embed_lookup = d["embed"] extra_loss = d["loss"] if hparams.residual_centroids: centroids = embed_lookup(exp_discrete) # gives the centroids top_k_indices = tf.squeeze(exp_discrete, axis=1) tf.summary.histogram("discrete_counts", top_k_indices) # if k > 1, then we need to reshape top_k_indices from [batch_size*k, 1] # to [batch_size, k] if k > 1: top_k_indices = tf.reshape(top_k_indices, [batch_size, k]) # get the top k gates top_k_gates = tf.ones([batch_size, k]) # This will be a `Tensor` of shape `[batch_size, n]`, with zeros in the # positions corresponding to all but the top k experts per example. gates = _rowwise_unsorted_segment_sum(top_k_gates, top_k_indices, num_experts) # Compute count per expert from the gates. # gates has shape [batch_size, num_experts] # count per expert has shape [num_experts, 1] count_per_expert = tf.reduce_sum(gates, axis=0) if hparams.use_scales: scale_loss = tf.reduce_mean(tf.to_float(count_per_expert) * scales) extra_loss += scale_loss if common_layers.should_generate_summaries(): tf.summary.histogram("vq_loss", extra_loss) tf.summary.historgram("scale_loss", scale_loss) return gates, extra_loss, centroids
<SYSTEM_TASK:> Noisy top-k gating. <END_TASK> <USER_TASK:> Description: def noisy_top_k_gating(x, num_experts, train, k=2, initializer=tf.zeros_initializer(), noisy_gating=True, noise_epsilon=1e-2, name=None): """Noisy top-k gating. See paper: https://arxiv.org/abs/1701.06538. Args: x: input Tensor with shape [batch_size, input_size] num_experts: an integer train: a boolean - we only add noise at training time. k: an integer - number of experts per example initializer: an initializer noisy_gating: a boolean noise_epsilon: a float name: an optional string Returns: gates: a Tensor with shape [batch_size, num_experts] load: a Tensor with shape [num_experts] """
with tf.variable_scope(name, default_name="noisy_top_k_gating"): input_size = x.get_shape().as_list()[-1] w_gate = tf.get_variable( "w_gate", [input_size, num_experts], tf.float32, initializer) if noisy_gating: w_noise = tf.get_variable("w_noise", [input_size, num_experts], tf.float32, initializer) clean_logits = tf.matmul(x, w_gate) if noisy_gating: raw_noise_stddev = tf.matmul(x, w_noise) noise_stddev = ((tf.nn.softplus(raw_noise_stddev) + noise_epsilon) * (tf.to_float(train))) noisy_logits = clean_logits + ( tf.random_normal(tf.shape(clean_logits)) * noise_stddev) logits = noisy_logits if common_layers.should_generate_summaries(): tf.summary.histogram("noisy_logits", noisy_logits) tf.summary.histogram("noise_stddev", noise_stddev) else: logits = clean_logits top_logits, top_indices = _my_top_k(logits, min(k + 1, num_experts)) # top k logits has shape [batch, k] top_k_logits = tf.slice(top_logits, [0, 0], [-1, k]) top_k_indices = tf.slice(top_indices, [0, 0], [-1, k]) top_k_gates = tf.nn.softmax(top_k_logits) # This will be a `Tensor` of shape `[batch_size, n]`, with zeros in the # positions corresponding to all but the top k experts per example. gates = _rowwise_unsorted_segment_sum(top_k_gates, top_k_indices, num_experts) if noisy_gating and k < num_experts: load = tf.reduce_sum( _prob_in_top_k(clean_logits, noisy_logits, noise_stddev, top_logits, k), 0) else: load = _gates_to_load(gates) if common_layers.should_generate_summaries(): tf.summary.histogram("importance", tf.reduce_sum(gates, 0)) tf.summary.histogram("load", load) return gates, load
<SYSTEM_TASK:> Apply a function to each coordinate ids of a multidimensional tensor. <END_TASK> <USER_TASK:> Description: def map_ids(x, indices, map_fn): """Apply a function to each coordinate ids of a multidimensional tensor. This allows to process each sequence of a batch independently. This is similar to tf.map_fn but with tensor where the batch dim has been flatten. Warning: The indices ids have to be contiguous and ordered in memory as the output vector for each of the ids are simply concatenated after being processed. Ex: if your indices are [0,2,2,1,2,0], the output will contains the processed rows in the following order: [0,0,1,2,2,2] Args: x (Tensor): The tensor to be dispatched of shape [length,...] indices (Tensor): A int32 tensor of size [length, 1] containing the batch coordinate of x map_fn (fct): Function called for every ids of the original tensor. Take as input a tensor of same rank than x and from shape [length_id,...] with length_id <= length. Isn't called if length_id == 0 Returns: a tensor of same shape as x, where each elements has been processed """
indices = tf.reshape(indices, [-1]) t_i = tf.constant(0) # batch_coordinates start at 0 t_batch_size = tf.reduce_max(indices) + 1 # ta_stack_out will store the intermediate results for each individual id # As alternative to tf.TensorArray, scatter_update could potentially be used # but that would require an additional mutable tensor. ta_stack_out = tf.TensorArray( x.dtype, size=t_batch_size, ) # Then we iterate over each sequence individually and compute the # transformation for each id while_condition = lambda t_i, *args: tf.less(t_i, t_batch_size) def body(t_i, ta_stack_out): """Loop body.""" # Gather the ids current_ids = tf.to_int32(tf.where(tf.equal(indices, t_i))) t_row = tf.gather_nd(x, indices=current_ids) # TODO(epot): Should not call map_fn if t_row size is 0 # Apply transformation to each id # Restore batch_dim=1 as most function expect [batch_dim, length, ...] as # input t_row = tf.expand_dims(t_row, axis=0) t_row = map_fn(t_row) t_row = tf.squeeze(t_row, axis=0) # Squeeze for concatenation ta_stack_out = ta_stack_out.write(t_i, t_row) return [tf.add(t_i, 1), ta_stack_out] # ++i # Run the loop, equivalent to: # stack_out = [] # while i < batch_size: # stack_out.expand(map_fn(x[indices==i])) _, ta_stack_out = tf.while_loop(while_condition, body, [t_i, ta_stack_out]) # Merge all results return ta_stack_out.concat()
<SYSTEM_TASK:> Returns a function that creates a feed-forward network. <END_TASK> <USER_TASK:> Description: def ffn_expert_fn(input_size, hidden_sizes, output_size, hidden_activation=tf.nn.relu): """Returns a function that creates a feed-forward network. Use this function to create the expert_fn argument to distributed_moe. Args: input_size: an integer hidden_sizes: a list of integers output_size: an integer hidden_activation: a unary function. Returns: a unary function """
def my_fn(x): layer_sizes = [input_size] + hidden_sizes + [output_size] for i in range(1 + len(hidden_sizes)): w = tf.get_variable("w_%d" % i, layer_sizes[i:i+2], tf.float32) x = tf.matmul(x, w) if i < len(hidden_sizes): x = hidden_activation(x) if layer_sizes[i] != input_size: x *= (layer_sizes[i] / float(input_size))**-0.5 return x return my_fn
<SYSTEM_TASK:> Flatten all dimensions of a except the last. <END_TASK> <USER_TASK:> Description: def flatten_all_but_last(a): """Flatten all dimensions of a except the last."""
ret = tf.reshape(a, [-1, tf.shape(a)[-1]]) if not tf.executing_eagerly(): ret.set_shape([None] + a.get_shape().as_list()[-1:]) return ret
<SYSTEM_TASK:> Call a local mixture of experts. <END_TASK> <USER_TASK:> Description: def local_moe(x, train, expert_fn, num_experts, k=1, loss_coef=1e-2, hparams=None, pass_x=True, pass_gates=False, additional_dispatch_params=None, name=None): """Call a local mixture of experts. Args: x: a tensors with shape [... , input_size] train: a boolean scalar. expert_fn: a function. num_experts: an integer - number of experts k: an integer - how many experts to use for each batch element loss_coef: a scalar - multiplier on load-balancing losses hparams: optional hparams for vq gating pass_x: a boolean. If true, x will also be dispatched to the experts. pass_gates: a boolean. If true, gates will be passed to experts. Might be necessary when dealing with sparse encoder-encoder decoder attention additional_dispatch_params: The extra tensors that need to be sent to each expert. Examples include batch batch coordinates (see common_attention.local_expert_attention) name: a string Returns: y: a tensor. Has the same shape as x, except for the last dimension, which is output_size. extra_training_loss: a scalar. This should be added into the overall training loss of the model. The backpropagation of this loss encourages all experts to be approximately equally used across a batch. """
bneck = DiscreteBottleneck(hparams) with tf.variable_scope(name, default_name="local_moe"): centroids = None x_flat = flatten_all_but_last(x) if hparams.gating_type == "topk": tf.logging.info("Using noisy top_k with k = {}".format(k)) # The gates indicate which batch elements go to which tensors. # load is a measure of approximately how many examples go to each expert gates, load = noisy_top_k_gating( x_flat, num_experts, train, k, initializer=tf.zeros_initializer(), noisy_gating=True, noise_epsilon=1e-2) importance = tf.reduce_sum(gates, 0) loss = loss_coef * (cv_squared(importance) + cv_squared(load)) else: assert hparams.gating_type == "vq" tf.logging.info("Using VQ gating") gates, loss, centroids = vq_gating( x_flat, num_experts, k, bneck, hparams=hparams) loss *= loss_coef # Shuffle data between datashards and experts. dispatcher = SparseDispatcher(num_experts, gates) # Set up expert_fn arguments expert_kwargs = {} if pass_x: expert_kwargs["x"] = dispatcher.dispatch(x_flat) if pass_gates: expert_kwargs["gates"] = dispatcher.expert_to_gates() for key, val in six.iteritems(additional_dispatch_params or {}): val = flatten_all_but_last(val) expert_kwargs[key] = dispatcher.dispatch(val) ep = Parallelism([DEFAULT_DEV_STRING] * num_experts, reuse=None) expert_outputs = ep(expert_fn, **expert_kwargs) y_flat = dispatcher.combine(expert_outputs) if centroids is not None: centroids = tf.squeeze(centroids, axis=[1, 2]) y_flat += centroids y = common_layers.reshape_like(y_flat, x) return y, loss
<SYSTEM_TASK:> Reduces data per device. <END_TASK> <USER_TASK:> Description: def reduce_by_device(parallelism, data, reduce_fn): """Reduces data per device. This can be useful, for example, if we want to all-reduce n tensors on k<n devices (like during eval when we have only one device). We call reduce_by_device() to first sum the tensors per device, then call our usual all-reduce operation to create one sum per device, followed by expand_by_device, to create the appropriate number of pointers to these results. See all_reduce_ring() below for an example of how this is used. Args: parallelism: a expert_utils.Parallelism object data: a list of Tensors with length parallelism.n reduce_fn: a function taking a list of Tensors. e.g. tf.add_n Returns: device_parallelism: a Parallelism object with each device listed only once. reduced_data: A list of Tensors, one per device. """
unique_devices = [] device_to_data = {} for dev, datum in zip(parallelism.devices, data): if dev not in device_to_data: unique_devices.append(dev) device_to_data[dev] = [datum] else: device_to_data[dev].append(datum) device_parallelism = Parallelism(unique_devices) grouped_data = [device_to_data[dev] for dev in unique_devices] return device_parallelism, device_parallelism(reduce_fn, grouped_data)
<SYSTEM_TASK:> Compute the sum of all Tensors and put the result everywhere. <END_TASK> <USER_TASK:> Description: def all_reduce_ring(x, parallelism, maybe_reduce=True, use_bfloat16=True): """Compute the sum of all Tensors and put the result everywhere. Assumes that the devices are connected in a ring. Args: x: a list of Tensors with length parallelism.n parallelism: a expert_utils.Parallelism object. maybe_reduce: a boolean - first reduce per device. use_bfloat16: a boolean - saves bandwidth but loses precision Returns: a list of Tensors with length parallelism.n """
if parallelism.n == 1: return x if maybe_reduce: original_parallelism = parallelism parallelism, x = reduce_by_device(parallelism, x, tf.add_n) if parallelism.n == 1: y = x else: # first shard the input: x_flat = parallelism(tf.reshape, x, [[-1]] * parallelism.n) # [device, shard] x_split = parallelism( common_layers.approximate_split, x_flat, parallelism.n, 0) def _step(source_replica, target_replica, x_split, op="plus_eq"): """Helper function - one step of summing or copying. If op == "plus_eq", then adds source_replica into target_replica If op == "copy", then copies source_replica onto target_replica These operations happen for all shards. The replica numbers are offset by the shard numbers to keep all physical links busy. Args: source_replica: an integer target_replica: an integer x_split: a list of lists of tensors op: a string """ for shard in range(parallelism.n): source_device = (shard + source_replica) % parallelism.n target_device = (shard + target_replica) % parallelism.n source = x_split[source_device][shard] if use_bfloat16: with tf.device(parallelism.devices[source_device]): source = tf.to_bfloat16(source) with tf.device(parallelism.devices[target_device]): source = tf.to_float(source) if op == "plus_eq": x_split[target_device][shard] += source else: assert op == "copy" x_split[target_device][shard] = tf.identity(source) center = parallelism.n // 2 # accumulate everything towards the center. for i in reversed(range(center, parallelism.n - 1)): _step(i + 1, i, x_split, op="plus_eq") for i in range(center): _step(i, i + 1, x_split, op="plus_eq") # copy everything away from the center. for i in range(center, parallelism.n - 1): _step(i, i + 1, x_split, op="copy") for i in reversed(range(center)): _step(i + 1, i, x_split, op="copy") x_concat = parallelism(tf.concat, x_split, 0) y = parallelism(common_layers.reshape_like_all_dims, x_concat, x) if maybe_reduce: y = expand_by_device(original_parallelism, parallelism, y) return y