Transformers with Keras
What is a Transformer?
The Transformer is a model design built on attention and no recurrence. It is behind BERT, GPT and most modern language and vision models.
Parts of a Transformer Encoder Block
- Multi-head self-attention to relate all words to each other
- Add and normalize: a residual connection and layer normalization
- Feed-forward network: two Dense layers applied to each position
- Add and normalize again
Position problem: Attention itself does not know the order of the words. So we add positional embeddings, which tell the model where each word sits in the sentence.
Transformer Block as a Layer
python
import keras
from keras import layers
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="relu"),
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(x, x)
a = self.drop1(a, training=training)
x = self.norm1(x + a) # residual + normalize
f = self.ffn(x)
f = self.drop2(f, training=training)
return self.norm2(x + f)
Token and Position Embedding
python
import tensorflow as tf
class TokenAndPosition(layers.Layer):
def __init__(self, maxlen, vocab_size, embed_dim, **kwargs):
super().__init__(**kwargs)
self.token_emb = layers.Embedding(vocab_size, embed_dim)
self.pos_emb = layers.Embedding(maxlen, embed_dim)
def call(self, x):
positions = tf.range(start=0, limit=tf.shape(x)[-1], delta=1)
return self.token_emb(x) + self.pos_emb(positions)
Build the Classifier
python
maxlen, vocab_size, embed_dim = 200, 20000, 64
inputs = keras.Input(shape=(maxlen,), dtype="int32")
x = TokenAndPosition(maxlen, vocab_size, embed_dim)(inputs)
x = TransformerBlock(embed_dim, num_heads=4, ff_dim=128)(x)
x = layers.GlobalAveragePooling1D()(x)
x = layers.Dropout(0.1)(x)
x = layers.Dense(20, activation="relu")(x)
outputs = layers.Dense(1, activation="sigmoid")(x)
model = keras.Model(inputs, outputs)
model.compile(optimizer="adam", loss="binary_crossentropy", metrics=["accuracy"])
Train on IMDB (Integer Version)
python
(x_train, y_train), (x_val, y_val) = keras.datasets.imdb.load_data(num_words=vocab_size)
x_train = keras.utils.pad_sequences(x_train, maxlen=maxlen)
x_val = keras.utils.pad_sequences(x_val, maxlen=maxlen)
model.fit(x_train, y_train, batch_size=32, epochs=2, validation_data=(x_val, y_val))
Accuracy is usually around 85 to 88 percent after two epochs. Transformers shine when they are large and pretrained.
In practice: You rarely train Transformers from scratch. Use pretrained models from KerasHub or Hugging Face and fine-tune them on your task. The next lesson shows how.
Conclusion
A Transformer block is attention plus a small feed-forward network with residual connections and normalization. Stack more blocks to build bigger models.
Quick Summary: Transformer = token and position embeddings, multi-head attention, feed-forward layer, residual connections and layer normalization.

