Encoder: 6 layers

Multi-head self-attention

×

Every source position attends to every source position, in 8 heads of 64 features.

Why

Parallel. A recurrent network computes one position after another, each hidden state from the previous one. The authors say this sequential nature precludes parallelization within a training example, which becomes critical at longer sequences, since memory limits batching across examples. The Transformer drops recurrence and relies entirely on attention. Transformer paper §1, p. 2

Short paths. The authors compare layer types on three counts: the computation per layer, how much of it can run in parallel, and the length of the path a signal travels between two positions, since shorter paths make long-range dependencies easier to learn. A self-attention layer connects all positions with a constant number of sequential operations and a path of constant length; a recurrent layer needs O(n)O(n) of each, for a sequence of length nn. Transformer paper §4, p. 6

Heads. Each head has its own learned projections of queries, keys and values, here 8 heads of 64 features, and the heads attend in parallel. The authors say this lets the model jointly attend to information from different representation subspaces at different positions; with a single head, averaging inhibits this. The total computation is similar to that of one head at the full width of 512. Transformer paper §3.2.2, pp. 4–5

Δ=oWO+bO\Delta=oW^{O}+b^{O}
All 16 steps
Prepare Q, K, V:\text{Prepare {\htmlClass{vl-stream-q}{Q}}, {\htmlClass{vl-stream-k}{K}}, {\htmlClass{vl-stream-v}{V}}:}
pQKV=xWQKV+bQKVp^{QKV}=xW^{QKV}+b^{QKV}
q=p1:512QKV{\htmlClass{vl-stream-q}{q}}=p^{QKV}_{1:512}
k=p513:1024QKV{\htmlClass{vl-stream-k}{k}}=p^{QKV}_{513:1024}
v=p1025:1536QKV{\htmlClass{vl-stream-v}{v}}=p^{QKV}_{1025:1536}
Q=reshape⁡(q){\htmlClass{vl-stream-q}{Q}}=\operatorname{reshape}({\htmlClass{vl-stream-q}{q}})
Q~=Q/64\tilde {\htmlClass{vl-stream-q}{Q}}={\htmlClass{vl-stream-q}{Q}}/\sqrt{64}
K=reshape⁡(k){\htmlClass{vl-stream-k}{K}}=\operatorname{reshape}({\htmlClass{vl-stream-k}{k}})
V=reshape⁡(v){\htmlClass{vl-stream-v}{V}}=\operatorname{reshape}({\htmlClass{vl-stream-v}{v}})
S=Q~KTS=\tilde QK^{\mathsf T}
S~=S+M\tilde S=S+{\htmlClass{vl-stream-context}{M}}
A[b,i,t,s]=exp⁡(S~[b,i,t,s])∑u=0S−1exp⁡(S~[b,i,t,u])A[b,i,t,s]=\frac{\exp(\tilde S[b,i,t,s])}{\sum_{u=0}^{S-1}\exp(\tilde S[b,i,t,u])}
O=AVO=AV
Merge and project:\text{Merge and project:}
o=reshape⁡(O)o=\operatorname{reshape}(O)
Δ=oWO+bO\Delta=oW^{O}+b^{O}
in
xnx_n [B batch, S source positions, 512 d]MM [B batch, 1, 1, S keys]
out
Δ\Delta [B batch, S source positions, 512 d]
Parameters1,050,624 × 6 layers

1,050,624 parameters per instance, across its learned components

ComponentParameters
Prepare Q, K, V787,968
Merge and project262,656
Per-instance total1,050,624

One in each of the 6 layers, each with its own weights.

No trained weights were published to check against.

Explanation

Attention(Q,K,V)=softmax⁡(QKT/dk)V(Q,K,V)=\operatorname{softmax}(QK^{\mathsf T}/\sqrt{d_k})V (§3.2.1, eq. 1); the scale is already in the queries here, so the expression has none.

In the encoder, keys, values and queries all come from the output of the previous layer (§3.2.3).

MultiHead(Q,K,V)=Concat⁡(head1,…,head8)WO(Q,K,V)=\operatorname{Concat}(\text{head}_1,\ldots,\text{head}_{8})W^O with dk=dv=dmodel/h=64d_k=d_v=d_{\text{model}}/h=64 (§3.2.2).

Sources

In codecommon_attention.multihead_attention(…, name="encoder_self_attention") · transformer.py 155–165

Open pinned code ↗

Direct evidence

Self-attention projects queries, keys and values with one 1×1 convolution; attention to a memory projects queries from the input and keys and values from the memory; heads are split, queries scaled by depth^-0.5, attended, combined and projected out.

common_attention.py 348–421 ↗ · tensorflow/tensor2tensor @ 0c66117d4297

Excerpt
def multihead_attention(query_antecedent,
                        memory_antecedent,
                        bias,
                        total_key_depth,
                        total_value_depth,
                        output_depth,
                        num_heads,
                        dropout_rate,
                        summaries=False,
                        image_shapes=None,
                        name=None):
  """Multihead scaled-dot-product attention with input/output transformations.

  Args:
    query_antecedent: a Tensor with shape [batch, length_q, channels]
    memory_antecedent: a Tensor with shape [batch, length_m, channels]
    bias: bias Tensor (see attention_bias())
    total_key_depth: an integer
    total_value_depth: an integer
    output_depth: an integer
    num_heads: an integer dividing total_key_depth and total_value_depth
    dropout_rate: a floating point number
    summaries: a boolean
    image_shapes: optional tuple of integer scalars.
      see comments for attention_image_summary()
    name: an optional string

  Returns:
    A Tensor.

  Raises:
    ValueError: if the key depth or value depth are not divisible by the
      number of attention heads.
  """
  if total_key_depth % num_heads != 0:
    raise ValueError("Key depth (%d) must be divisible by the number of "
                     "attention heads (%d)." % (total_key_depth, num_heads))
  if total_value_depth % num_heads != 0:
    raise ValueError("Value depth (%d) must be divisible by the number of "
                     "attention heads (%d)." % (total_value_depth, num_heads))

  with tf.variable_scope(
      name,
      default_name="multihead_attention",
      values=[query_antecedent, memory_antecedent]):
    if memory_antecedent is None:
      # self attention
      combined = common_layers.conv1d(
          query_antecedent,
          total_key_depth * 2 + total_value_depth,
          1,
          name="qkv_transform")
      q, k, v = tf.split(
          combined, [total_key_depth, total_key_depth, total_value_depth],
          axis=2)
    else:
      q = common_layers.conv1d(
          query_antecedent, total_key_depth, 1, name="q_transform")
      combined = common_layers.conv1d(
          memory_antecedent,
          total_key_depth + total_value_depth,
          1,
          name="kv_transform")
      k, v = tf.split(combined, [total_key_depth, total_value_depth], axis=2)
    q = split_heads(q, num_heads)
    k = split_heads(k, num_heads)
    v = split_heads(v, num_heads)
    key_depth_per_head = total_key_depth // num_heads
    q *= key_depth_per_head**-0.5
    x = dot_product_attention(
        q, k, v, bias, dropout_rate, summaries, image_shapes)
    x = combine_heads(x)
    x = common_layers.conv1d(x, output_depth, 1, name="output_transform")
    return x

Each of num_hidden_layers encoder layers: self-attention over the encoder input with the padding bias, then the feed-forward network, each through residual_fn.

transformer.py 129–167 ↗ · tensorflow/tensor2tensor @ 0c66117d4297

Excerpt
def transformer_encoder(encoder_input,
                        residual_fn,
                        encoder_self_attention_bias,
                        hparams,
                        name="encoder"):
  """A stack of transformer layers.

  Args:
    encoder_input: a Tensor
    residual_fn: a function from (layer_input, layer_output) -> combined_output
    encoder_self_attention_bias: bias Tensor for self-attention
       (see common_attention.attention_bias())
    hparams: hyperparameters for model
    name: a string

  Returns:
    y: a Tensors
  """
  x = encoder_input
  # Summaries don't work in multi-problem setting yet.
  summaries = "problems" not in hparams.values() or len(hparams.problems) == 1
  with tf.variable_scope(name):
    for layer in xrange(hparams.num_hidden_layers):
      with tf.variable_scope("layer_%d" % layer):
        x = residual_fn(
            x,
            common_attention.multihead_attention(
                x,
                None,
                encoder_self_attention_bias,
                hparams.attention_key_channels or hparams.hidden_size,
                hparams.attention_value_channels or hparams.hidden_size,
                hparams.hidden_size,
                hparams.num_heads,
                hparams.attention_dropout,
                summaries=summaries,
                name="encoder_self_attention"))
        x = residual_fn(x, transformer_ffn_layer(x, hparams))
  return x