Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 28

Word Embeddings: Text to Dense Vectors

This lesson is built with resources from youtube.com, photonlines.substack.com and 1 more site.

Hello! Welcome to the fifth module of our course. We're now diving into the architecture that powers modern AI: Transformers.

In the previous modules, you built a solid foundation in how neural networks are trained. You learned how to define a network in PyTorch, implement a training loop, evaluate its performance, and even tune its hyperparameters. A key theme was that these models operate on numerical data—tensors of numbers.

This brings us to a fundamental question: how do we handle text? An AI model can't understand the word "computer" directly. It needs a numerical representation. This lesson tackles the first and most crucial step in that process, addressing the learning outcome: Explain the concept of word embeddings and their role in representing text as dense vectors.

We will explore how we convert words into meaningful numbers, moving from simple but flawed methods to the sophisticated, context-aware representations used in today's Large Language Models (LLMs).

1. The Challenge: Representing Words as Numbers

Machine learning models, and especially neural networks, are mathematical functions. They process numbers, not characters. So, our first task in Natural Language Processing (NLP) is to find a way to convert text into vectors of numbers.

The Naive Approach: One-Hot Encoding

A straightforward idea is to create a unique vector for each word in our vocabulary. Let's say our total vocabulary has 50,000 words. We could represent each word with a 50,000-dimensional vector. This vector would be all zeros, except for a single 1 at the index corresponding to that specific word. This is called one-hot encoding.

One-Hot Word Vectors vs. Word Embeddings
This image contrasts the sparse, high-dimensional nature of one-hot vectors (left) with the dense, lower-dimensional word embeddings (right) that we will be focusing on.

While simple, this method has two critical flaws:

  1. Inefficiency and Sparsity: As you can imagine from your software engineering background, creating a 50,000-element array for every single word is highly inefficient, especially since almost all of its values are zero. These are called sparse vectors.
  2. Lack of Semantic Meaning: The vectors for "cat" and "kitten" are no more similar to each other than the vectors for "cat" and "database". In one-hot encoding, all vectors are orthogonal; their dot product is zero. The representation provides the model with no information about the relationships between words.

To build intelligent language models, we need a representation that captures the meaning, or semantics, of words.


2. The Solution: Dense Word Embeddings

Instead of sparse, high-dimensional vectors, modern NLP uses word embeddings, which are dense, lower-dimensional vectors of floating-point numbers. For example, a word might be represented by a vector of 768 numbers, rather than 50,000.

The most important property of these embeddings is that they are learned from data. The values in the vector are not arbitrary; they are parameters of the model that are adjusted during training. The goal is to create a "semantic space" where words with similar meanings are positioned close to each other.

Word Embeddings and their 2D Visualization
This diagram illustrates how words are mapped to numerical vectors. Notice in the 2D plot how related words like 'cat' and 'kitten' are clustered together. It also shows how vector arithmetic can capture analogies, like the parallel relationship between (man, king) and (woman, queen).

This geometric arrangement allows embeddings to capture complex relationships. The most famous example is the analogy:

This shows that the model has learned a "gender" dimension and a "royalty" dimension within its embedding space, purely from observing how words are used in text.

Test your understanding!

Imagine you have trained a model and obtained embeddings for the words 'python' (the language), 'java' (the language), and 'snake' (the animal). In the multi-dimensional embedding space, which pair of words would you expect to have the smallest distance between their vectors? Why?

Show answer

You would expect the vectors for 'python' and 'java' to be closest together. Both are programming languages and would likely appear in similar contexts (e.g., "backend development," "software engineer," "code"). The word 'snake' would appear in very different contexts (e.g., "reptile," "jungle," "venom") and its vector would therefore be far from the other two.


3. The Evolution to Contextual Embeddings

The concept of embeddings has evolved significantly. Early methods like Word2Vec produced static embeddings, where each word had exactly one vector representation. This is problematic for words with multiple meanings (polysemy). For example, the word "bank" has the same static vector in both "river bank" and "investment bank."

To understand how we moved past this limitation, the following video provides a concise history of word embeddings, leading up to the methods used in Transformers.

Word Embeddings - EXPLAINED!

This video from CodeEmporium provides an excellent overview of the history and evolution of word embeddings, from early statistical methods to the contextual embeddings used in modern models.

Please watch from the beginning until the 8:27 mark. Pay close attention to the limitations of each approach (N-grams, Word2Vec) and why the move to contextual embeddings with Transformers was such a major breakthrough.

As the video explains, the key innovation of models like ELMo and subsequently Transformers (BERT, GPT) was the introduction of contextual embeddings. In these models, the vector representation for a word is not fixed. Instead, it is generated dynamically based on the entire sentence it appears in. This allows the model to generate different embeddings for "bank" in "river bank" versus "investment bank," resolving the ambiguity.


4. How Transformers Create Embeddings

Now let's focus on how modern Transformer models, the basis for LLMs like GPT, create these powerful contextual representations. This process is the very first step in the Transformer architecture.

The following resource provides a clear, visual explanation of the embedding pipeline in a model like GPT-2.

LLM Transformer Model Visually Explained

Let's walk through the embedding process in a Transformer model. This interactive article, 'LLM Transformer Model Visually Explained', breaks it down into clear, manageable steps.

Please read the section titled 'Embedding', including its four subsections: 'Tokenization', 'Token Embedding', 'Positional Encoding', and 'Final Embedding'. This will walk you through the entire process.

Let's summarize the key stages from that reading:

  1. Tokenization: The input text is first broken down into smaller pieces called tokens. Instead of splitting only on words, modern models use subword tokenization (like Byte-Pair Encoding or BPE). This allows the model to handle rare words and reduces the overall vocabulary size. For example, a word like "empowers" might be tokenized into "em" and "powers". Each token in the vocabulary is assigned a unique integer ID.

  2. Token Embedding: Each token ID is then used as an index to look up a corresponding vector from a large embedding matrix. You can think of this matrix as a large lookup table where each row is the dense vector for a specific token. This matrix holds the initial, pre-trained semantic knowledge and its weights are updated during model training. For GPT-2 (small), this is a matrix of shape (50257, 768), where 50,257 is the vocabulary size and 768 is the dimension of the embedding vector.

  3. Positional Encoding: A core Transformer model, by itself, does not process words sequentially. It looks at all tokens at once. To give the model information about the order of the words, a positional encoding vector is added to each token embedding. This vector encodes the position of the token in the sequence (i.e., is it the first, second, or tenth token?).

  4. Final Embedding: The token embedding and the positional encoding vectors are summed together. The resulting vector is the final input for that token, capturing both its semantic meaning and its position in the sequence. This is the representation that is fed into the first layer of the Transformer.

Test your understanding!

A Transformer model receives two different input sentences: "Order the book" and "Book the order". If we only used token embeddings (step 2) and skipped positional encoding (step 3), how might the model perceive the inputs for these two sentences? Why is this a problem?

Show answer

Without positional encoding, the model would receive an input that is essentially a "bag" of token embeddings. The set of embeddings for "Order", "the", and "book" is identical to the set for "Book", "the", and "order". The model would have no information about the word order and would likely see the two sentences as identical. This is a major problem because word order is critical to meaning in human language. Positional encoding solves this by adding unique, position-specific information to each token's vector.


Conclusion

In this lesson, you've learned how text is transformed from a sequence of characters into a set of meaningful numerical vectors that a neural network can process.

Key Takeaways:

  • AI models require numerical input, so text must be converted into vectors.
  • Simple methods like one-hot encoding are inefficient and fail to capture semantic relationships between words.
  • Dense word embeddings represent words as vectors in a multi-dimensional space where distance corresponds to semantic similarity.
  • These embeddings are learned from data, allowing them to capture complex relationships like analogies.
  • Modern models like Transformers use contextual embeddings, where a word's vector representation changes based on the sentence it's in.
  • The embedding process in a Transformer involves three main steps: tokenization, looking up a token embedding, and adding a positional encoding.

Next up:

We've successfully converted our input text into rich, contextualized vectors. Now, what does the Transformer do with them? In the next lesson, we will explore the revolutionary mechanism at the heart of the Transformer: self-attention. You'll learn how the model uses queries, keys, and values to weigh the importance of every other word in the sequence when processing a single word.