liveBook · Manning

Positional embedding

As explained in Deep Learning with Python, Third Edition

A representation added to sequence elements to preserve order information for models that otherwise treat inputs as a set.

A positional embedding gives a sequence model access to order by combining each token’s embedding with a vector for its position. Attention relates sequence elements to one another, but does not itself identify which element came first, last, or in between. section 15.3.4 section 15.3.5

Adding position to a sentence

For a sentence represented by token IDs, assign positions 0, 1, 2, and so on. Look up a token vector and a position vector for each ID, then add the two vectors. The same word can now have a different input representation at different positions. section 15.3.5

Listing 15.17 A learned position embedding layer
from keras import ops
 
class PositionalEmbedding(keras.Layer):
    def __init__(self, sequence_length, input_dim, output_dim):
        super().__init__()
        self.token_embeddings = layers.Embedding(input_dim, output_dim)
        self.position_embeddings = layers.Embedding(sequence_length, output_dim)
 
    def call(self, inputs):
        positions = ops.cumsum(ops.ones_like(inputs), axis=-1) - 1    #1
        embedded_tokens = self.token_embeddings(inputs)
        embedded_positions = self.position_embeddings(positions)
        return embedded_tokens + embedded_positions

This Keras layer learns separate token and position embedding tables. It generates zero-based positions and adds the two embeddings elementwise; both tables use the same output dimension. section 15.3.5

Set sequence_length large enough for the positions the layer will encounter: it determines the size of the position embedding table. Use the layer like an ordinary embedding layer, before the Transformer encoder or decoder. section 15.3.5

Adding a raw position number as an extra coordinate is less attractive because large integers can disrupt the range of embedding values. An alternative is a cyclic position vector with small values; learned position vectors offer a simpler approach in this implementation. section 15.3.5

Listing 15.18 Building a Transformer model with positional embeddings
hidden_dim = 256
intermediate_dim = 2056
num_heads = 8
 
source = keras.Input(shape=(None,), dtype="int32", name="english")
x = PositionalEmbedding(sequence_length, vocab_size, hidden_dim)(source)
encoder_output = TransformerEncoder(hidden_dim, intermediate_dim, num_heads)(
    source=x,
    source_mask=source != 0,
)
 
target = keras.Input(shape=(None,), dtype="int32", name="spanish")
x = PositionalEmbedding(sequence_length, vocab_size, hidden_dim)(target)
x = TransformerDecoder(hidden_dim, intermediate_dim, num_heads)(
    target=x,
    source=encoder_output,
    source_mask=source != 0,
)
x = layers.Dropout(0.5)(x)
target_predictions = layers.Dense(vocab_size, activation="softmax")(x)
transformer = keras.Model([source, target], target_predictions)

The translation model applies positional embeddings to both English source tokens and Spanish target tokens before passing them to the encoder and decoder. section 15.3.5

With positional information added, the translation model reached 67% next-word accuracy in the reported training run. For text generation, the layer can also reuse its token embedding weights for the output projection; that reverse operation uses the token table, not the position table. section 15.3.5 section 16.2.1

How Deep Learning with Python, Third Edition covers it

How deep it goes
Develops a learned position-embedding layer and compares it with raw position coordinates and cyclic encodings.
Examples
Uses English-to-Spanish translation and a decoder-only text-generation model to illustrate positional embeddings.
What it assumes
Assumes familiarity with token indices and embeddings while introducing position vectors from first principles.
What you can do after
Build a learned positional embedding layer in Keras and apply it to Transformer inputs.
How it connects
Connects positional embeddings with attention, token embeddings, Transformer encoders and decoders, and weight tying.

Also explained in

Compare how 14 books explain positional embedding →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Deep Learning with Python, Third Edition. The section links point to the parts of the book it draws on.