Beispiel #1
0
    def infer(self, features):
        """Produce predictions from the model."""
        batch_size = commons.shape_list(features["inputs"])[0]
        length = commons.shape_list(features["inputs"])[1]
        target_length = tf.to_int32(2.0 * tf.to_float(length))
        initial_output = tf.zeros(
            (batch_size, target_length, self._hparams.hidden_size),
            dtype=tf.float32)

        features["targets"] = initial_output
        decoder_outputs, _ = self.body(features)  # pylint: disable=not-callable
        return decoder_outputs
Beispiel #2
0
def vq_nearest_neighbor(x, hparams):
    """Find the nearest element in means to elements in x."""
    bottleneck_size = 2**hparams.bottleneck_bits
    means = hparams.means
    x_sg = tf.stop_gradient(x)
    x_norm_sq = tf.reduce_sum(tf.square(x_sg), axis=-1, keepdims=True)
    means_norm_sq = tf.reduce_sum(tf.square(means), axis=-1, keepdims=True)
    scalar_prod = tf.matmul(x_sg, means, transpose_b=True)
    dist = x_norm_sq + tf.transpose(means_norm_sq) - 2 * scalar_prod
    if hparams.bottleneck_kind in ["em", "mog"]:
        x_means_idx = tf.multinomial(-dist, num_samples=hparams.num_samples)
        x_means_hot = tf.one_hot(x_means_idx, depth=bottleneck_size)
        x_means_hot = tf.reduce_mean(x_means_hot, axis=1)
    else:
        x_means_idx = tf.argmax(-dist, axis=-1)
        x_means_hot = tf.one_hot(x_means_idx, depth=bottleneck_size)
    x_means = tf.matmul(x_means_hot, means)
    e_loss = tf.reduce_mean(tf.square(x - tf.stop_gradient(x_means)))

    if hparams.bottleneck_kind == "mog":
        m_shape = [tf.to_float(x) for x in commons.shape_list(means)]
        logp = -tf.log(m_shape[0]) - .5 * tf.log(
            2 * math.pi) * m_shape[1] + tf.reduce_logsumexp(-.5 * dist, -1)
        e_loss -= hparams.gamma * tf.reduce_mean(logp)
    return x_means_hot, e_loss
Beispiel #3
0
def vq_discrete_bottleneck(x, hparams):
    """Simple vector quantized discrete bottleneck."""
    bottleneck_size = 2**hparams.bottleneck_bits
    x_shape = commons.shape_list(x)
    x = tf.reshape(x, [-1, hparams.hidden_size])
    x_means_hot, e_loss = vq_nearest_neighbor(x, hparams)

    if hparams.bottleneck_kind == "mog":
        loss = hparams.beta * e_loss
    else:
        tf.logging.info("Using EMA with beta = {}".format(hparams.beta))
        means, ema_means, ema_count = (hparams.means, hparams.ema_means,
                                       hparams.ema_count)
        # Update the ema variables
        updated_ema_count = commons.assign_moving_average(ema_count,
                                                          tf.reduce_sum(
                                                              x_means_hot,
                                                              axis=0),
                                                          hparams.decay,
                                                          zero_debias=False)

        dw = tf.matmul(x_means_hot, x, transpose_a=True)
        updated_ema_means = commons.assign_moving_average(ema_means,
                                                          dw,
                                                          hparams.decay,
                                                          zero_debias=False)
        n = tf.reduce_sum(updated_ema_count, axis=-1, keepdims=True)
        updated_ema_count = ((updated_ema_count + hparams.epsilon) /
                             (n + bottleneck_size * hparams.epsilon) * n)
        # pylint: disable=g-no-augmented-assignment
        updated_ema_means = updated_ema_means / tf.expand_dims(
            updated_ema_count, axis=-1)
        # pylint: enable=g-no-augmented-assignment
        with tf.control_dependencies([e_loss]):
            # distribution_strategy
            def update_fn(v, value):
                return tf.assign(v, value)

            tower_context = distribution_strategy_context.get_tower_context()
            if tower_context:

                def merge_fn(strategy, v, value):
                    value = strategy.reduce(tf.VariableAggregation.MEAN, value,
                                            v)
                    return strategy.update(v, update_fn, value)

                update_means = tower_context.merge_call(
                    merge_fn, means, updated_ema_means)
            else:
                strategy = distribution_strategy_context.get_cross_tower_context(
                )
                update_means = strategy.update(means, update_fn,
                                               updated_ema_means)
            with tf.control_dependencies([update_means]):
                loss = hparams.beta * e_loss

    discrete = tf.reshape(x_means_hot, x_shape[:-1] + [bottleneck_size])
    return discrete, loss
Beispiel #4
0
def vq_discrete_unbottleneck(x, hparams):
    """Simple undiscretization from vector quantized representation."""
    x_shape = commons.shape_list(x)
    bottleneck_size = 2**hparams.bottleneck_bits
    means = hparams.means
    x_flat = tf.reshape(x, [-1, bottleneck_size])
    result = tf.matmul(x_flat, means)
    result = tf.reshape(result, x_shape[:-1] + [hparams.hidden_size])
    return result
def _merge_beam_dim(tensor):
    """Reshapes first two dimensions in to single dimension.
  Args:
    tensor: Tensor to reshape of shape [A, B, ...]
  Returns:
    Reshaped tensor of shape [A*B, ...]
  """
    shape = commons.shape_list(tensor)
    shape[0] *= shape[1]  # batch -> batch * beam_size
    shape.pop(1)  # Remove beam dim
    return tf.reshape(tensor, shape)
def _unmerge_beam_dim(tensor, batch_size, beam_size):
    """Reshapes first dimension back to [batch_size, beam_size].
  Args:
    tensor: Tensor to reshape of shape [batch_size*beam_size, ...]
    batch_size: Tensor, original batch size.
    beam_size: int, original beam size.
  Returns:
    Reshaped tensor of shape [batch_size, beam_size, ...]
  """
    shape = commons.shape_list(tensor)
    new_shape = [batch_size] + [beam_size] + shape[1:]
    return tf.reshape(tensor, new_shape)
Beispiel #7
0
def decompress_step(source, hparams, first_relu, name):
    """Decompression function."""
    with tf.variable_scope(name):
        shape = commons.shape_list(source)
        multiplier = 2
        kernel = 1
        thicker = commons.conv_block(source,
                                     hparams.hidden_size * multiplier,
                                     [(1, kernel)],
                                     first_relu=first_relu,
                                     name="decompress_conv")
        return tf.reshape(thicker,
                          [shape[0], shape[1] * 2, hparams.hidden_size])
 def _gather(params, indices):
     """Fast gather using one_hot and batch matmul."""
     if dtype != tf.float32:
         params = tf.to_float(params)
     shape = commons.shape_list(params)
     indices_shape = commons.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
def transformer_prepare_decoder(targets, hparams, features=None):
    """Prepare one shard of the model for the decoder.
  Args:
    targets: a Tensor.
    hparams: run hyperparameters
    features: optionally pass the entire features dictionary as well.
      This is needed now for "packed" datasets.
  Returns:
    decoder_input: a Tensor, bottom of decoder stack
    decoder_self_attention_bias: a bias tensor for use in decoder self-attention
  """
    decoder_self_attention_bias = (commons.attention_bias_lower_triangle(
        commons.shape_list(targets)[1]))

    decoder_input = commons.shift_right_3d(targets)
    decoder_input = commons.add_timing_signal_1d(decoder_input)
    return (decoder_input, decoder_self_attention_bias)
Beispiel #10
0
    def symbols_to_logits_fn(ids):
        """Go from ids to logits."""
        latents_discrete = tf.pad(
            ids[:,
                1:], [[0, 0], [0, 1]
                      ])  # prepare to be right-shifted in 'decode_transformer'
        #latents_discrete = tf.Print(latents_discrete, [tf.shape(latents_discrete), latents_discrete])

        with tf.variable_scope(tf.get_variable_scope(), reuse=False):
            latents_dense = embed(
                tf.one_hot(latents_discrete, depth=2**hparams.bottleneck_bits))
            latents_pred = decode_transformer(inputs, ed, latents_dense,
                                              hparams, "extra")
            logits = tf.layers.dense(latents_pred,
                                     2**hparams.bottleneck_bits,
                                     name="extra_logits")
            current_output_position = commons.shape_list(ids)[1] - 1
            logits = logits[:, current_output_position, :]
        return logits
def beam_search(symbols_to_logits_fn,
                initial_ids,
                beam_size,
                decode_length,
                vocab_size,
                alpha,
                states=None,
                eos_id=EOS_ID,
                stop_early=True,
                use_tpu=False):
    """Beam search with length penalties.
  Requires a function that can take the currently decoded symbols and return
  the logits for the next symbol. The implementation is inspired by
  https://arxiv.org/abs/1609.08144.
  When running, the beam search steps can be visualized by using tfdbg to watch
  the operations generating the output ids for each beam step.  These operations
  have the pattern:
    (alive|finished)_topk_(seq,scores)
  Operations marked `alive` represent the new beam sequences that will be
  processed in the next step.  Operations marked `finished` represent the
  completed beam sequences, which may be padded with 0s if no beams finished.
  Operations marked `seq` store the full beam sequence for the time step.
  Operations marked `scores` store the sequence's final log scores.
  The beam search steps will be processed sequentially in order, so when
  capturing observed from these operations, tensors, clients can make
  assumptions about which step is being recorded.
  WARNING: Assumes 2nd dimension of tensors in `states` and not invariant, this
  means that the shape of the 2nd dimension of these tensors will not be
  available (i.e. set to None) inside symbols_to_logits_fn.
  Args:
    symbols_to_logits_fn: Interface to the model, to provide logits.
        Shoud take [batch_size, decoded_ids] and return [batch_size, vocab_size]
    initial_ids: Ids to start off the decoding, this will be the first thing
        handed to symbols_to_logits_fn (after expanding to beam size)
        [batch_size]
    beam_size: Size of the beam.
    decode_length: Number of steps to decode for.
    vocab_size: Size of the vocab, must equal the size of the logits returned by
        symbols_to_logits_fn
    alpha: alpha for length penalty.
    states: dict (possibly nested) of decoding states.
    eos_id: ID for end of sentence.
    stop_early: a boolean - stop once best sequence is provably determined.
    use_tpu: A bool, whether to do beam search on TPU.
  Returns:
    Tuple of
    (decoded beams [batch_size, beam_size, decode_length]
     decoding probabilities [batch_size, beam_size])
  """
    batch_size = commons.shape_list(initial_ids)[0]

    # Assume initial_ids are prob 1.0
    initial_log_probs = tf.constant([[0.] + [-INF] * (beam_size - 1)])
    # Expand to beam_size (batch_size, beam_size)
    alive_log_probs = tf.tile(initial_log_probs, [batch_size, 1])

    # Expand each batch and state to beam_size
    alive_seq = _expand_to_beam_size(initial_ids, beam_size)
    alive_seq = tf.expand_dims(alive_seq, axis=2)  # (batch_size, beam_size, 1)
    if use_tpu:
        alive_seq = tf.tile(alive_seq, [1, 1, decode_length + 1])
    if states:
        states = nest.map_structure(
            lambda state: _expand_to_beam_size(state, beam_size), states)
    else:
        states = {}

    # Finished will keep track of all the sequences that have finished so far
    # Finished log probs will be negative infinity in the beginning
    # finished_flags will keep track of booleans
    finished_seq = tf.zeros(commons.shape_list(alive_seq), tf.int32)
    # Setting the scores of the initial to negative infinity.
    finished_scores = tf.ones([batch_size, beam_size]) * -INF
    finished_flags = tf.zeros([batch_size, beam_size], tf.bool)

    def grow_finished(finished_seq, finished_scores, finished_flags, curr_seq,
                      curr_scores, curr_finished):
        """Given sequences and scores, will gather the top k=beam size sequences.
    Args:
      finished_seq: Current finished sequences.
        [batch_size, beam_size, current_decoded_length]
      finished_scores: scores for each of these sequences.
        [batch_size, beam_size]
      finished_flags: finished bools for each of these sequences.
        [batch_size, beam_size]
      curr_seq: current topk sequence that has been grown by one position.
        [batch_size, beam_size, current_decoded_length]
      curr_scores: scores for each of these sequences. [batch_size, beam_size]
      curr_finished: Finished flags for each of these sequences.
        [batch_size, beam_size]
    Returns:
      Tuple of
        (Topk sequences based on scores,
         log probs of these sequences,
         Finished flags of these sequences)
    """
        if not use_tpu:
            # First append a column of 0'ids to finished to make the same length with
            # finished scores
            finished_seq = tf.concat(
                [finished_seq,
                 tf.zeros([batch_size, beam_size, 1], tf.int32)],
                axis=2)

        # Set the scores of the unfinished seq in curr_seq to large negative
        # values
        curr_scores += (1. - tf.to_float(curr_finished)) * -INF
        # concatenating the sequences and scores along beam axis
        curr_finished_seq = tf.concat([finished_seq, curr_seq], axis=1)
        curr_finished_scores = tf.concat([finished_scores, curr_scores],
                                         axis=1)
        curr_finished_flags = tf.concat([finished_flags, curr_finished],
                                        axis=1)
        return compute_topk_scores_and_seq(curr_finished_seq,
                                           curr_finished_scores,
                                           curr_finished_scores,
                                           curr_finished_flags,
                                           beam_size,
                                           batch_size,
                                           "grow_finished",
                                           use_tpu=use_tpu)

    def grow_alive(curr_seq, curr_scores, curr_log_probs, curr_finished,
                   states):
        """Given sequences and scores, will gather the top k=beam size sequences.
    Args:
      curr_seq: current topk sequence that has been grown by one position.
        [batch_size, beam_size, i+1]
      curr_scores: scores for each of these sequences. [batch_size, beam_size]
      curr_log_probs: log probs for each of these sequences.
        [batch_size, beam_size]
      curr_finished: Finished flags for each of these sequences.
        [batch_size, beam_size]
      states: dict (possibly nested) of decoding states.
    Returns:
      Tuple of
        (Topk sequences based on scores,
         log probs of these sequences,
         Finished flags of these sequences)
    """
        # Set the scores of the finished seq in curr_seq to large negative
        # values
        curr_scores += tf.to_float(curr_finished) * -INF
        return compute_topk_scores_and_seq(curr_seq,
                                           curr_scores,
                                           curr_log_probs,
                                           curr_finished,
                                           beam_size,
                                           batch_size,
                                           "grow_alive",
                                           states,
                                           use_tpu=use_tpu)

    def grow_topk(i, alive_seq, alive_log_probs, states):
        r"""Inner beam search loop.
    This function takes the current alive sequences, and grows them to topk
    sequences where k = 2*beam. We use 2*beam because, we could have beam_size
    number of sequences that might hit <EOS> and there will be no alive
    sequences to continue. With 2*beam_size, this will not happen. This relies
    on the assumption the vocab size is > beam size. If this is true, we'll
    have at least beam_size non <EOS> extensions if we extract the next top
    2*beam words.
    Length penalty is given by = (5+len(decode)/6) ^ -\alpha. Pls refer to
    https://arxiv.org/abs/1609.08144.
    Args:
      i: loop index
      alive_seq: Topk sequences decoded so far [batch_size, beam_size, i+1]
      alive_log_probs: probabilities of these sequences. [batch_size, beam_size]
      states: dict (possibly nested) of decoding states.
    Returns:
      Tuple of
        (Topk sequences extended by the next word,
         The log probs of these sequences,
         The scores with length penalty of these sequences,
         Flags indicating which of these sequences have finished decoding,
         dict of transformed decoding states)
    """
        # Get the logits for all the possible next symbols
        if use_tpu and states:
            flat_ids = tf.reshape(
                tf.slice(alive_seq, [0, 0, i], [batch_size, beam_size, 1]),
                [batch_size * beam_size, -1])
        else:
            flat_ids = tf.reshape(alive_seq, [batch_size * beam_size, -1])

        # (batch_size * beam_size, decoded_length)
        if states:
            flat_states = nest.map_structure(_merge_beam_dim, states)
            flat_logits, flat_states = symbols_to_logits_fn(
                flat_ids, i, flat_states)
            states = nest.map_structure(
                lambda t: _unmerge_beam_dim(t, batch_size, beam_size),
                flat_states)
        elif use_tpu:
            flat_logits = symbols_to_logits_fn(flat_ids, i)
        else:
            flat_logits = symbols_to_logits_fn(flat_ids)

        logits = tf.reshape(flat_logits, [batch_size, beam_size, -1])

        # Convert logits to normalized log probs
        candidate_log_probs = commons.log_prob_from_logits(logits)

        # Multiply the probabilities by the current probabilities of the beam.
        # (batch_size, beam_size, vocab_size) + (batch_size, beam_size, 1)
        log_probs = candidate_log_probs + tf.expand_dims(alive_log_probs,
                                                         axis=2)

        length_penalty = tf.pow(((5. + tf.to_float(i + 1)) / 6.), alpha)

        curr_scores = log_probs / length_penalty
        # Flatten out (beam_size, vocab_size) probs in to a list of possibilities
        flat_curr_scores = tf.reshape(curr_scores,
                                      [-1, beam_size * vocab_size])

        if use_tpu:
            topk_scores, topk_ids = top_k_with_unique(flat_curr_scores,
                                                      k=beam_size * 2)
        else:
            topk_scores, topk_ids = tf.nn.top_k(flat_curr_scores,
                                                k=beam_size * 2)

        # Recovering the log probs because we will need to send them back
        topk_log_probs = topk_scores * length_penalty

        # Work out what beam the top probs are in.
        topk_beam_index = topk_ids // vocab_size
        topk_ids %= vocab_size  # Unflatten the ids

        if not use_tpu:
            # The next three steps are to create coordinates for tf.gather_nd to pull
            # out the correct sequences from id's that we need to grow.
            # We will also use the coordinates to gather the booleans of the beam
            # items that survived.
            batch_pos = compute_batch_indices(batch_size, beam_size * 2)

            # top beams will give us the actual coordinates to do the gather.
            # stacking will create a tensor of dimension batch * beam * 2, where the
            # last dimension contains the i,j gathering coordinates.
            topk_coordinates = tf.stack([batch_pos, topk_beam_index], axis=2)

            # Gather up the most probable 2*beams both for the ids and
            # finished_in_alive bools
            topk_seq = tf.gather_nd(alive_seq, topk_coordinates)
            if states:
                states = nest.map_structure(
                    lambda state: tf.gather_nd(state, topk_coordinates),
                    states)

            # Append the most probable alive
            topk_seq = tf.concat(
                [topk_seq, tf.expand_dims(topk_ids, axis=2)], axis=2)
        else:
            # Gather up the most probable 2*beams both for the ids and
            # finished_in_alive bools
            topk_seq = fast_tpu_gather(alive_seq, topk_beam_index)

            if states:
                states = nest.map_structure(
                    lambda state: fast_tpu_gather(state, topk_beam_index),
                    states)

            # Update the most probable alive
            topk_seq = tf.transpose(topk_seq, perm=[2, 0, 1])
            topk_seq = inplace_ops.alias_inplace_update(
                topk_seq, i + 1, topk_ids)
            topk_seq = tf.transpose(topk_seq, perm=[1, 2, 0])

        topk_finished = tf.equal(topk_ids, eos_id)

        return topk_seq, topk_log_probs, topk_scores, topk_finished, states

    def inner_loop(i, alive_seq, alive_log_probs, finished_seq,
                   finished_scores, finished_flags, states):
        """Inner beam search loop.
    There are three groups of tensors, alive, finished, and topk.
    The alive group contains information about the current alive sequences
    The topk group contains information about alive + topk current decoded words
    the finished group contains information about finished sentences, that is,
    the ones that have decoded to <EOS>. These are what we return.
    The general beam search algorithm is as follows:
    While we haven't terminated (pls look at termination condition)
      1. Grow the current alive to get beam*2 topk sequences
      2. Among the topk, keep the top beam_size ones that haven't reached EOS
      into alive
      3. Among the topk, keep the top beam_size ones have reached EOS into
      finished
    Repeat
    To make things simple with using fixed size tensors, we will end
    up inserting unfinished sequences into finished in the beginning. To stop
    that we add -ve INF to the score of the unfinished sequence so that when a
    true finished sequence does appear, it will have a higher score than all the
    unfinished ones.
    Args:
      i: loop index
      alive_seq: Topk sequences decoded so far [batch_size, beam_size, i+1]
      alive_log_probs: probabilities of the beams. [batch_size, beam_size]
      finished_seq: Current finished sequences.
        [batch_size, beam_size, i+1]
      finished_scores: scores for each of these sequences.
        [batch_size, beam_size]
      finished_flags: finished bools for each of these sequences.
        [batch_size, beam_size]
      states: dict (possibly nested) of decoding states.
    Returns:
      Tuple of
        (Incremented loop index
         New alive sequences,
         Log probs of the alive sequences,
         New finished sequences,
         Scores of the new finished sequences,
         Flags indicating which sequence in finished as reached EOS,
         dict of final decoding states)
    """

        # Each inner loop, we carry out three steps:
        # 1. Get the current topk items.
        # 2. Extract the ones that have finished and haven't finished
        # 3. Recompute the contents of finished based on scores.
        topk_seq, topk_log_probs, topk_scores, topk_finished, states = grow_topk(
            i, alive_seq, alive_log_probs, states)
        alive_seq, alive_log_probs, _, states = grow_alive(
            topk_seq, topk_scores, topk_log_probs, topk_finished, states)
        finished_seq, finished_scores, finished_flags, _ = grow_finished(
            finished_seq, finished_scores, finished_flags, topk_seq,
            topk_scores, topk_finished)

        return (i + 1, alive_seq, alive_log_probs, finished_seq,
                finished_scores, finished_flags, states)

    def _is_finished(i, unused_alive_seq, alive_log_probs, unused_finished_seq,
                     finished_scores, unused_finished_in_finished,
                     unused_states):
        """Checking termination condition.
    We terminate when we decoded up to decode_length or the lowest scoring item
    in finished has a greater score that the highest prob item in alive divided
    by the max length penalty
    Args:
      i: loop index
      alive_log_probs: probabilities of the beams. [batch_size, beam_size]
      finished_scores: scores for each of these sequences.
        [batch_size, beam_size]
    Returns:
      Bool.
    """
        max_length_penalty = tf.pow(((5. + tf.to_float(decode_length)) / 6.),
                                    alpha)
        # The best possible score of the most likely alive sequence.
        lower_bound_alive_scores = alive_log_probs[:, 0] / max_length_penalty

        if not stop_early:
            # by considering the min score (in the top N beams) we ensure that
            # the decoder will keep decoding until there is at least one beam
            # (in the top N) that can be improved (w.r.t. the alive beams).
            # any unfinished beam will have score -INF - thus the min
            # will always be -INF if there is at least one unfinished beam -
            # which means the bound_is_met condition cannot be true in this case.
            lowest_score_of_finished_in_finished = tf.reduce_min(
                finished_scores)
        else:
            # by taking the max score we only care about the first beam;
            # as soon as this first beam cannot be beaten from the alive beams
            # the beam decoder can stop.
            # similarly to the above, if the top beam is not completed, its
            # finished_score is -INF, thus it will not activate the
            # bound_is_met condition. (i.e., decoder will keep going on).
            # note we need to find the max for every sequence eparately - so, we need
            # to keep the batch dimension (see axis=1)
            lowest_score_of_finished_in_finished = tf.reduce_max(
                finished_scores, axis=1)

        bound_is_met = tf.reduce_all(
            tf.greater(lowest_score_of_finished_in_finished,
                       lower_bound_alive_scores))

        return tf.logical_and(tf.less(i, decode_length),
                              tf.logical_not(bound_is_met))

    inner_shape = tf.TensorShape([None, None, None])
    if use_tpu:
        inner_shape = tf.TensorShape(
            [batch_size, beam_size, decode_length + 1])
    if use_tpu:
        state_struc = nest.map_structure(lambda state: state.get_shape(),
                                         states)
    else:
        state_struc = nest.map_structure(get_state_shape_invariants, states)
    (_, alive_seq, alive_log_probs, finished_seq, finished_scores,
     finished_flags, states) = tf.while_loop(
         _is_finished,
         inner_loop, [
             tf.constant(0), alive_seq, alive_log_probs, finished_seq,
             finished_scores, finished_flags, states
         ],
         shape_invariants=[
             tf.TensorShape([]), inner_shape,
             alive_log_probs.get_shape(), inner_shape,
             finished_scores.get_shape(),
             finished_flags.get_shape(), state_struc
         ],
         parallel_iterations=1,
         back_prop=False)

    alive_seq.set_shape((None, beam_size, None))
    finished_seq.set_shape((None, beam_size, None))

    # Accounting for corner case: It's possible that no sequence in alive for a
    # particular batch item ever reached EOS. In that case, we should just copy
    # the contents of alive for that batch item. tf.reduce_any(finished_flags, 1)
    # if 0, means that no sequence for that batch index had reached EOS. We need
    # to do the same for the scores as well.
    finished_seq = tf.where(tf.reduce_any(finished_flags, 1), finished_seq,
                            alive_seq)
    finished_scores = tf.where(tf.reduce_any(finished_flags, 1),
                               finished_scores, alive_log_probs)
    return finished_seq, finished_scores, states
Beispiel #12
0
    def model_fn(features, labels, mode):
        with tf.variable_scope("transformer_vqvae",
                               initializer=tf.variance_scaling_initializer(
                                   hparams.initializer_gain,
                                   mode="fan_avg",
                                   distribution="uniform")):

            if mode != tf.estimator.ModeKeys.TRAIN:
                for key in hparams.keys():
                    if key.endswith("dropout"):
                        setattr(hparams, key, 0.0)

            with tf.variable_scope("embeddings",
                                   initializer=tf.random_normal_initializer(
                                       0.0, hparams.hidden_size**-0.5)):
                source_embeddings = tf.get_variable(
                    "source_embeddings",
                    [len(hparams.source_vocab), hparams.hidden_size],
                    tf.float32)
                if hparams.shared_embedding:
                    target_embeddings = source_embeddings
                else:
                    target_embeddings = tf.get_variable(
                        "target_embeddings",
                        [len(hparams.target_vocab), hparams.hidden_size],
                        tf.float32)

            encoder_input_layer = commons.input_layer(source_embeddings,
                                                      hparams)
            decoder_input_layer = commons.input_layer(target_embeddings,
                                                      hparams)
            output_layer = tf.layers.Dense(len(hparams.target_vocab),
                                           use_bias=False,
                                           name="output")

            # create model
            x_enc = encoder_input_layer(features["sources"])
            model = TransformerNAT(hparams, mode)

            # decode
            if mode != tf.estimator.ModeKeys.PREDICT:
                x_dec = decoder_input_layer(features["targets"])

                decoder_outputs, losses = model.body(features={
                    'inputs': x_enc,
                    'targets': x_dec
                })
                logits = output_layer(decoder_outputs)
                predictions = tf.argmax(logits, -1)
                tgt_len = commons.shape_list(features["targets"])[1]
                losses["cross_entropy"] = commons.compute_loss(
                    logits[:, :tgt_len], features["targets"])

                # losses
                loss = 0.
                for k, l in losses.items():
                    tf.summary.scalar(k, l)
                    loss += l

            else:
                decoder_outputs = model.infer(features={'inputs': x_enc})
                logits = output_layer(decoder_outputs)
                predictions = tf.argmax(logits, -1)
                loss = None

        if mode == tf.estimator.ModeKeys.TRAIN:
            train_op = commons.get_train_op(loss, hparams)
        else:
            train_op = None

        if mode == tf.estimator.ModeKeys.EVAL:
            # Names tensors to use in the printing tensor hook.
            targets = tf.identity(features["targets"], "targets")
            predictions = tf.identity(predictions, "predictions")

            bleu_score = bleu.bleu_score(predictions, targets)
            eval_metrics = {
                "metrics/approx_bleu_score": tf.metrics.mean(bleu_score)
            }

            # Summaries
            eval_summary_hook = tf.train.SummarySaverHook(
                save_steps=1,
                output_dir=os.path.join(hparams.model_dir, "eval"),
                summary_op=tf.summary.merge_all())
            eval_summary_hooks = [eval_summary_hook]
        else:
            eval_metrics = None
            eval_summary_hooks = None

        return tf.estimator.EstimatorSpec(mode,
                                          predictions=predictions,
                                          loss=loss,
                                          eval_metric_ops=eval_metrics,
                                          evaluation_hooks=eval_summary_hooks,
                                          train_op=train_op)
Beispiel #13
0
def ae_transformer_internal(inputs, targets, hparams, mode, cache=None):
    """Main step used for training."""
    # Encoder.
    inputs, ed = encode(inputs, hparams, "input_enc")

    # Autoencoding.
    losses = {"extra": tf.constant(0.0), "latent_pred": tf.constant(0.0)}

    max_targets_len_from_inputs = tf.concat([inputs, inputs], axis=1)
    targets, _ = commons.pad_to_same_length(
        targets,
        max_targets_len_from_inputs,
        final_length_divisible_by=2**hparams.num_compress_steps)
    targets_c = compress(targets, hparams, "compress")
    if mode != tf.estimator.ModeKeys.PREDICT:
        # Compress and bottleneck.
        latents_discrete_hot, extra_loss = vq_discrete_bottleneck(
            x=targets_c, hparams=hparams)
        latents_dense = vq_discrete_unbottleneck(latents_discrete_hot,
                                                 hparams=hparams)
        latents_dense = targets_c + tf.stop_gradient(latents_dense - targets_c)
        latents_discrete = tf.argmax(latents_discrete_hot, axis=-1)
        tf.summary.histogram("codes", latents_discrete)
        losses["extra"] = extra_loss

        # Extra loss predicting latent code from input.
        latents_pred = decode_transformer(inputs, ed, latents_dense, hparams,
                                          "extra")
        latent_pred_loss = get_latent_pred_loss(latents_pred,
                                                latents_discrete_hot, hparams)
        losses["latent_pred"] = tf.reduce_mean(latent_pred_loss)
    else:
        latent_len = commons.shape_list(targets_c)[1]
        embed = functools.partial(vq_discrete_unbottleneck, hparams=hparams)
        latents_dense = tf.zeros_like(targets_c)
        if cache is None:
            cache = ae_latent_sample_beam(latents_dense, inputs, ed, embed,
                                          hparams)
        cache_hot = tf.one_hot(cache, depth=2**hparams.bottleneck_bits)
        latents_dense = embed(cache_hot)

    # Postprocess
    d = latents_dense
    d = commons.add_timing_signal_1d(d)

    # Decompressing the dense latents
    for i in range(hparams.num_compress_steps):
        j = hparams.num_compress_steps - i - 1
        d = residual_conv(d, 1, 3, hparams, "decompress_rc_%d" % j)
        d = decompress_step(d, hparams, i > 0, "decompress_%d" % j)

    if hparams.shallow_decoder:
        res = tf.layers.conv1d(d,
                               hparams.hidden_size,
                               3,
                               padding="same",
                               name="decoder")
    else:
        masking = commons.inverse_lin_decay(hparams.mask_startup_steps)
        masking *= commons.inverse_exp_decay(hparams.mask_startup_steps //
                                             4)  # Not much at start.
        masking = tf.minimum(tf.maximum(masking, 0.0), 1.0)
        tf.summary.scalar('masking', masking)
        if mode == tf.estimator.ModeKeys.PREDICT:
            masking = 1.0
        mask = tf.less(masking,
                       tf.random_uniform(commons.shape_list(targets)[:-1]))
        mask = tf.expand_dims(tf.to_float(mask), -1)

        # targets is always [batch, length, depth]
        targets = mask * targets + (1.0 - mask) * d

        res = decode_transformer(inputs, ed, targets, hparams, "decoder")
        latent_time = tf.less(hparams.mask_startup_steps,
                              tf.to_int32(tf.train.get_global_step()))
        losses["latent_pred"] *= tf.to_float(latent_time)
    return res, losses, cache