Attention & Transformers

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

A transformer replaces recurrence with attention: every position computes a weighted mix of all other positions in parallel. Keras provides the central operation as keras.layers.MultiHeadAttention, and KerasHub adds ready-made TransformerEncoder and TransformerDecoder layers. This page builds an encoder classifier by hand and shows the reusable blocks. The mathematics (queries, keys, values, scaling, multiple heads) is in Attention and Transformers; the PyTorch version of the same material is Attention & Transformers in PyTorch. Tokenisation and embeddings come from Text, RNNs & Embeddings; pre-trained transformers are on KerasHub.

It targets Python 3.13, TensorFlow 2.21 with Keras 3.15 (TensorFlow 2.22 is "upcoming"), and was checked against the official documentation on 2026-10-30. Examples were run on Python 3.13 with TensorFlow 2.21, Keras 3.15 and KerasHub 0.32 (CPU) on 2026-10-31. The call-signature snippet, which uses mha, query and value defined elsewhere, was run with small synthetic stand-ins.

flowchart LR ids["token ids"] --> emb["token + position embedding"] emb --> mha["MultiHeadAttention (self)"] mha --> add1["add + LayerNormalization"] emb -.-> add1 add1 --> ffn["Dense, activation, Dense"] ffn --> add2["add + LayerNormalization"] add1 -.-> add2 add2 --> out["sequence of vectors"]

MultiHeadAttention

layers.MultiHeadAttention(num_heads, key_dim, value_dim=None, dropout=0.0, use_bias=True, output_shape=None, attention_axes=None) projects queries, keys and values into num_heads subspaces of size key_dim, applies scaled dot-product attention per head, concatenates and projects back. The call signature is:

output, scores = mha(
    query, value, key=None,
    attention_mask=None,
    return_attention_scores=True,
    training=None,
    use_causal_mask=False,
)
  • key defaults to value. For self-attention pass the same tensor as query and value; for cross-attention (decoder reading the encoder) the query comes from the decoder and value from the encoder.

  • attention_mask is a boolean tensor broadcastable to (batch, target_length, source_length); True means "may attend".

  • use_causal_mask=True builds the lower-triangular mask for autoregressive models so a position cannot see the future.

  • With return_attention_scores=True the call returns a tuple, and the scores have shape (batch, heads, target_length, source_length), handy for plots.

  • The output has the same last dimension as query unless output_shape is set. A typical choice is key_dim = embed_dim // num_heads.

import keras
import numpy as np
from keras import layers

mha = layers.MultiHeadAttention(num_heads=4, key_dim=16)
x = np.random.rand(2, 10, 64).astype("float32")      # (batch, time, features)

y = mha(query=x, value=x, use_causal_mask=True)
print(y.shape)                                        # (2, 10, 64)

y, scores = mha(query=x, value=x, return_attention_scores=True)
print(scores.shape)                                   # (2, 4, 10, 10)

Padding masks

When the input comes from Embedding(mask_zero=True), Keras propagates a padding mask that MultiHeadAttention picks up automatically on its query and value inputs. If you build your own attention_mask, remember its shape must broadcast to (batch, target, source):

import keras
from keras import ops

def padding_attention_mask(ids):
    keep = ops.cast(ops.not_equal(ids, 0), "bool")      # (batch, time)
    return keep[:, None, :]                              # broadcast over target positions

Use keras.ops rather than tf. functions inside layers to keep them backend independent.

Positional information

Attention is permutation invariant, so position must be injected. Options:

  • A learned position table: layers.Embedding(max_length, dim) indexed by ops.arange(length) and added to the token embeddings.

  • Sinusoidal encodings, available in KerasHub as keras_hub.layers.SinePositionEncoding.

  • keras_hub.layers.PositionEmbedding (learned) and keras_hub.layers.TokenAndPositionEmbedding which combine token and position embeddings in one layer.

  • Rotary embeddings (RotaryEmbedding in KerasHub) used by many modern language models.

A transformer encoder block

import keras
from keras import layers, ops

class TransformerBlock(layers.Layer):
    def __init__(self, embed_dim, num_heads, ff_dim, rate=0.1, **kwargs):
        super().__init__(**kwargs)
        self.att = layers.MultiHeadAttention(num_heads=num_heads, key_dim=embed_dim // num_heads)
        self.ffn = keras.Sequential([layers.Dense(ff_dim, activation="gelu"), layers.Dense(embed_dim)])
        self.norm1 = layers.LayerNormalization(epsilon=1e-6)
        self.norm2 = layers.LayerNormalization(epsilon=1e-6)
        self.drop1 = layers.Dropout(rate)
        self.drop2 = layers.Dropout(rate)

    def call(self, x, training=False):
        a = self.att(query=x, value=x, training=training)
        x = self.norm1(x + self.drop1(a, training=training))      # post-norm residual
        f = self.ffn(x)
        return self.norm2(x + self.drop2(f, training=training))

class TokenAndPosition(layers.Layer):
    def __init__(self, max_len, vocab, embed_dim, **kwargs):
        super().__init__(**kwargs)
        self.tok = layers.Embedding(vocab, embed_dim)
        self.pos = layers.Embedding(max_len, embed_dim)

    def call(self, ids):
        positions = ops.arange(ops.shape(ids)[-1])
        return self.tok(ids) + self.pos(positions)

VOCAB, MAX_LEN, DIM = 20_000, 200, 64

inputs = keras.Input(shape=(MAX_LEN,), dtype="int32")
x = TokenAndPosition(MAX_LEN, VOCAB, DIM)(inputs)
x = TransformerBlock(DIM, num_heads=4, ff_dim=128)(x)
x = layers.GlobalAveragePooling1D()(x)
x = layers.Dropout(0.1)(x)
outputs = layers.Dense(1)(x)
model = keras.Model(inputs, outputs)

model.compile(
    optimizer=keras.optimizers.Adam(1e-3),
    loss=keras.losses.BinaryCrossentropy(from_logits=True),
    metrics=[keras.metrics.BinaryAccuracy(threshold=0.0)],
)
model.summary()                            # Total params: 1,326,337

Design points:

  • Post-norm (normalise after the residual add) as above follows the original paper; pre-norm (normalise the input of each sub-block) trains more stably at depth and is common in current large models.

  • The feed-forward width is conventionally 4 times the model dimension; GELU is the usual activation.

  • If you give the custom layer constructor arguments, implement get_config() so the model can be saved and reloaded (see Subclassing & Custom Layers and Saving Keras Models).

  • GlobalAveragePooling1D ignores masked positions when a mask is present.

Ready-made layers in KerasHub

import keras
import keras_hub

inputs = keras.Input(shape=(None,), dtype="int32")
x = keras_hub.layers.TokenAndPositionEmbedding(
    vocabulary_size=20_000, sequence_length=200, embedding_dim=64, mask_zero=True,
)(inputs)
x = keras_hub.layers.TransformerEncoder(intermediate_dim=128, num_heads=4)(x)
x = keras.layers.GlobalAveragePooling1D()(x)
outputs = keras.layers.Dense(1)(x)
model = keras.Model(inputs, outputs)

TransformerDecoder adds causal self-attention and optional cross-attention for decoder-only and encoder-decoder models. The KerasHub layers named on this page (TokenAndPositionEmbedding, PositionEmbedding, SinePositionEncoding, RotaryEmbedding, TransformerEncoder and TransformerDecoder) all exist in KerasHub 0.32.

Decoder-only and generation

An autoregressive language model uses causal attention (use_causal_mask=True), trains with next-token cross-entropy on inputs shifted by one, and generates by feeding its own predictions back. Implementing efficient generation requires key/value caching, which KerasHub CausalLM models provide through generate(); hand-written layers recompute the whole prefix every step and are only suitable for teaching.

Cost and scaling

Attention memory and time grow quadratically with sequence length, since the scores matrix is length x length per head. For long sequences use windowed or sparse variants, shorter contexts, or pre-trained models whose implementations use fused attention kernels. Mixed precision (see Mixed Precision) roughly halves activation memory.

Pitfalls

  • Forgetting positional information, which makes the model a bag of words.

  • key_dim confused with the model dimension: it is the per-head size.

  • A mask with the wrong orientation (source and target swapped), so padding leaks in or valid tokens are hidden.

  • Using a causal mask for a classifier encoder, which needlessly hides the right-hand context.

  • Training a transformer from scratch on a small dataset: use a pre-trained checkpoint (KerasHub) and fine-tune instead.

  • No learning-rate warm-up with Adam on deeper models; see Optimizers & Learning-Rate Schedules.