Esempio n. 1
0
 def _my_concat(a, b):
   a = mtf.rename_dimension(a, "beam", "triple_beam")
   b = mtf.rename_dimension(b, "double_beam", "triple_beam")
   return mtf.concat([a, b], "triple_beam")
Esempio n. 2
0
def local_self_attention_spatial_blocks(query_antecedent,
                                        kv_channels,
                                        heads,
                                        memory_w_dim=None,
                                        mask_right=False,
                                        name=None):
    """Attention to the source position and a neighborhood to the left or right.

  The sequence is divided into blocks of length block_size.
  Attention for a given query position can only see memory positions
  less than or equal to the query position, in the corresponding block
  and the previous block.

  Args:
    query_antecedent: a mtf.Tensor with shape
      [batch, num_h_blocks, num_w_blocks, h_dim, w_dim, io_channels]
      must have the same size as query_length, but a different name.
    kv_channels: a mtf.Dimension (the size of the key and value vectors)
    heads: a mtf.Dimension (the number of heads)
    memory_w_dim: mtf Dimension, for the memory width block.
    mask_right: bool, flag specifying whether we mask out attention to the right
      for the decoder.
    name: an optional string.

  Returns:
    a Tensor of shape
        [batch, num_h_blocks, num_w_blocks, h_dim, w_dim, io_channels]

  Raises:
    ValueError: if channels or depth don't match.
  """
    with tf.variable_scope(name,
                           default_name="multihead_attention",
                           values=[query_antecedent]):

        w_dim, io_channels = query_antecedent.shape.dims[-2:]
        batch, num_w_blocks = query_antecedent.shape.dims[:2]
        q_var, k_var, v_var, o_var = multihead_attention_vars(
            query_antecedent.mesh, heads, io_channels, kv_channels,
            query_antecedent.dtype)

        # Rename dimensions for the memory height and width.
        memory_antecedent = mtf.rename_dimension(query_antecedent, w_dim.name,
                                                 memory_w_dim.name)

        # Call einsum over the query and memory to get query q, keys k and values v.
        q = mtf.einsum([query_antecedent, q_var],
                       mtf.Shape(
                           [batch, heads, num_w_blocks, w_dim, kv_channels]))
        k = mtf.einsum([memory_antecedent, k_var],
                       mtf.Shape(
                           [batch, heads, num_w_blocks, w_dim, kv_channels]))
        v = mtf.einsum([memory_antecedent, v_var],
                       mtf.Shape(
                           [batch, heads, num_w_blocks, w_dim, kv_channels]))

        # Halo exchange for memory blocks.
        if memory_w_dim is not None:
            k, v = local_1d_halo_exchange(k, v, num_w_blocks, w_dim,
                                          memory_w_dim, mask_right)

        # Calculate the causal mask to avoid peeking into the future. We compute
        # this once and reuse it for all blocks since the block_size is known.
        mask = None
        if mask_right:
            mask = attention_bias_local_block(query_antecedent.mesh, w_dim,
                                              memory_w_dim)

        output = dot_product_attention(q, k, v, mask=mask)

        return mtf.einsum([output, o_var],
                          mtf.Shape([batch, num_w_blocks, w_dim, io_channels]))
Esempio n. 3
0
def rename_length_to_memory_length(x,
                                   length_name="length",
                                   memory_length_name="memory_length"):
    return mtf.rename_dimension(x, length_name, memory_length_name)
Esempio n. 4
0
    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: mtf Tensors

    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.
        (top2k_seq, top2k_log_probs, top2k_scores, top2k_finished, new_states,
         first_selector) = grow_topk(i, alive_seq, alive_log_probs, states)
        alive_seq, alive_log_probs, _, second_selector = grow_alive(
            top2k_seq, top2k_scores, top2k_log_probs, top2k_finished)
        finished_seq, finished_scores, finished_flags, _ = grow_finished(
            finished_seq, finished_scores, finished_flags, top2k_seq,
            top2k_scores, top2k_finished)
        old_beam_dim = mtf.Dimension("old_beam", beam_dim.size)
        selector = mtf.einsum([
            mtf.rename_dimension(first_selector, beam_dim.name,
                                 old_beam_dim.name), second_selector
        ],
                              output_shape=[batch_dim, old_beam_dim, beam_dim])
        new_states = [
            mtf.einsum([
                mtf.rename_dimension(state, beam_dim.name, old_beam_dim.name),
                mtf.cast(selector, state.dtype)
            ],
                       reduced_dims=[old_beam_dim],
                       output_shape=state.shape) for state in new_states
        ]
        return (i + 1, alive_seq, alive_log_probs, finished_seq,
                finished_scores, finished_flags) + tuple(new_states)