Transformers, the tech behind LLMs | Deep Learning Chapter 5

3Blue1Brown www.youtube.com

简要概述

本视频深入探讨了生成式预训练Transformer(GPT)的工作原理,这是当前人工智能繁荣的核心技术。视频通过可视化方式解释了Transformer的内部运作,包括数据如何流动、如何进行预测和采样,以及如何通过词嵌入和注意力机制理解上下文。

  • Transformer是一种神经网络,是当前AI繁荣的核心。
  • 通过预测和采样,模型可以生成连贯的文本。
  • 词嵌入将词语转化为高维空间中的向量,相似含义的词语在空间中位置接近。
  • 注意力机制使模型能够理解上下文中不同词语之间的关系。

预测、采样、重复

GPT代表生成式预训练Transformer,是一种生成新文本的机器人。模型通过从大量数据中学习,并可以针对特定任务进行微调。Transformer是一种特定的神经网络,也是当前人工智能繁荣的核心技术。本视频旨在通过可视化方式解释Transformer的内部运作,逐步展示数据如何在其中流动。许多模型都使用Transformer,例如将音频转换为文本、根据文本生成语音,以及根据文本描述生成图像(如DALL-E和Midjourney)。最初的Transformer由Google于2017年推出,用于将文本从一种语言翻译成另一种语言。本视频重点关注的模型类型是ChatGPT的基础,它接受一段文本(可能伴随图像或声音),并预测接下来会出现什么内容。预测的形式是各种可能的文本块的概率分布。通过给模型一个初始片段,让它重复预测和采样下一个文本块,可以将这种预测模型用于生成更长的文本。

Transformer内部

数据在Transformer中的流动过程可以概括为:首先,输入被分解成称为token的小块,对于文本来说,这些token通常是单词或单词片段。每个token都与一个向量相关联,该向量旨在编码该片段的含义。这些向量可以被视为在高维空间中的坐标,含义相似的词语倾向于落在彼此接近的向量上。然后,向量序列通过一个称为注意力块的操作,允许向量相互通信并传递信息以更新它们的值。例如,“机器学习模型”中的“模型”与“时装模特”中的“模型”含义不同。注意力块负责确定上下文中哪些词语与更新哪些其他词语的含义相关,以及这些含义应该如何更新。这些向量随后通过另一种操作,称为多层感知器或前馈层。在这里,向量不相互通信,而是并行地通过相同的操作。这个步骤类似于询问关于每个向量的一长串问题,然后根据这些问题的答案更新它们。所有这些操作都类似于大量的矩阵乘法。这个过程会重复进行,在注意力块和多层感知器块之间来回切换,直到最后,段落的所有基本含义都被烘焙到序列中的最后一个向量中。然后,对最后一个向量执行特定操作,以生成所有可能的token(即可能出现的下一个文本块)的概率分布。

章节布局

本章将详细介绍网络开始和结束时发生的事情,并回顾一些重要的背景知识,这些知识对于机器学习工程师来说是理所当然的。如果你对这些背景知识很熟悉,可以直接跳到下一章,该章将重点介绍注意力块,这通常被认为是Transformer的核心。之后,将讨论多层感知器块、训练方式以及其他一些细节。这些视频是对深度学习迷你系列的补充,即使你没有看过之前的视频也可以理解。

深度学习的前提

深度学习是一种机器学习方法,它使用数据来确定模型的行为。例如,你可能需要一个函数,该函数接收图像并生成描述它的标签,或者预测给定文本段落中的下一个单词,或者执行任何其他似乎需要某种直觉和模式识别的任务。机器学习的思想是,与其明确定义如何在代码中执行该任务的过程(这是早期人工智能的做法),不如设置一个具有可调参数的非常灵活的结构,然后使用大量示例来调整这些参数的值,以模仿这种行为。例如,最简单的机器学习形式可能是线性回归,其中输入和输出都是单个数字,例如房屋的平方英尺及其价格,而你想要找到一条最适合这些数据的线,以预测未来的房价。这条线由两个连续参数(例如斜率和y轴截距)描述,线性回归的目标是确定这些参数以紧密匹配数据。深度学习模型要复杂得多。例如,GPT-3有1750亿个参数。深度学习描述了一类模型,这些模型在过去几十年中已被证明可以很好地扩展。它们都使用相同的训练算法,称为反向传播。为了使这种训练算法能够大规模地良好工作,这些模型必须遵循某种特定的格式。

词嵌入

文本处理的第一个步骤是将输入分解成小块,并将这些小块转换成向量。这些小块被称为token,可能是单词或标点符号。模型有一个预定义的词汇表,其中包含所有可能的单词列表,比如50,000个。遇到的第一个矩阵,称为嵌入矩阵,每个单词都有一列。这些列决定了每个单词在第一步中转换成的向量。将单词转换成向量在Transformer出现之前在机器学习中很常见。这种嵌入单词的做法,可以被认为是将这些向量看作是高维空间中的点。GPT-3中的词嵌入有12,288维,在高维空间中工作非常重要。模型在训练过程中调整其权重,以确定如何将单词嵌入为向量,它倾向于确定一组嵌入,其中空间中的方向具有某种语义含义。例如,如果搜索所有嵌入最接近“tower”的单词,你会注意到它们都给出了非常相似的塔式氛围。一个经典的例子是,如果你取女人和男人向量之间的差,它与国王和女王之间的差非常相似。如果在训练过程中,模型发现选择嵌入是有利的,那么这个空间中的一个方向编码了性别信息。另一个例子是,如果你取意大利的嵌入,减去德国的嵌入,然后将其添加到希特勒的嵌入中,你会得到非常接近墨索里尼的嵌入。模型似乎学会将某些方向与意大利性联系起来,而另一些方向与二战轴心国领导人联系起来。点积可以被认为是一种衡量向量对齐程度的方法。点积在计算上涉及将所有对应的分量相乘,然后将结果相加。几何上,当向量指向相似的方向时,点积为正;当它们垂直时,点积为零;当它们指向相反的方向时,点积为负。嵌入矩阵的列告诉我们每个单词会发生什么,这是模型中的第一堆权重。GPT-3的词汇量为50,257,嵌入维度为12,288,这意味着它包含约6.17亿个权重。

词嵌入之外

在Transformer中,应该将嵌入空间中的向量视为不仅代表单个单词,还应该将它们视为具有吸收上下文的能力。例如,一个最初是“king”的嵌入的向量,可能会逐渐被网络中的各种块拉动,因此最终指向一个更具体和细微的方向,该方向以某种方式编码了它是一位住在苏格兰的国王,他在谋杀了前任国王后获得了他的职位,并且正在用莎士比亚的语言描述。单词的含义显然受到周围环境的影响,有时包括来自远距离的上下文,因此在构建一个能够预测下一个单词的模型时,目标是以某种方式使其能够有效地整合上下文。在第一步中,当基于输入文本创建向量数组时,每个向量都只是从嵌入矩阵中提取出来的,因此最初每个向量只能编码单个单词的含义,而没有任何来自周围环境的输入。网络一次只能处理固定数量的向量,这被称为其上下文大小。对于GPT-3,它接受了2048的上下文大小的训练,因此通过网络的数据始终看起来像这个2048列的数组,每列有12,000个维度。上下文大小限制了Transformer在预测下一个单词时可以合并多少文本。这就是为什么与某些聊天机器人的长时间对话(例如早期版本的ChatGPT)通常会让人感觉机器人在你继续太长时间时会失去对话的线索。

Unembedding

所需的输出是所有可能出现的token的概率分布。例如,如果最后一个词是“Professor”,并且上下文包括“Harry Potter”这样的词,并且紧接之前我们看到“least favorite teacher”,那么一个训练有素的网络,已经建立了关于哈利波特的知识,可能会给“Snape”这个词分配一个很高的数字。这涉及两个不同的步骤。第一步是使用另一个矩阵将上下文中最后一个向量映射到包含50,000个值的列表,每个值对应词汇表中的一个token。然后有一个函数将这个列表归一化为概率分布,它被称为softmax。只使用最后一个嵌入来进行预测似乎有点奇怪,因为在最后一步中,该层中还有数千个其他向量,它们都有自己的上下文丰富的含义。这与训练过程中的一个事实有关,即如果你使用最后一层中的每个向量同时预测紧随其后的内容,那么训练过程会更有效率。这个矩阵被称为Unembedding矩阵。这个Unembedding矩阵的每一行对应词汇表中的一个单词,并且每一行包含的元素数量与嵌入维度相同。它与嵌入矩阵非常相似,只是顺序颠倒了,因此它为网络增加了另外6.17亿个参数。

Softmax与温度

如果希望一系列数字充当概率分布(例如,所有可能的下一个单词的分布),那么每个值必须介于0和1之间,并且所有值的总和也必须为1。但是,如果你正在玩深度学习游戏,其中你所做的一切看起来都像矩阵向量乘法,那么你默认获得的输出根本不遵守这一点。这些值通常为负数,或远大于1,并且它们几乎肯定不会加起来为1。Softmax是将任意数字列表转换为有效分布的标准方法,这样最大的值最终最接近1,而较小的值最终非常接近0。它的工作方式是首先将e提高到每个数字的幂,这意味着你现在有一个正值列表,然后你可以取所有这些正值的总和,并将每个项除以该总和,这会将其归一化为加起来为1的列表。如果在输入中有一个数字明显大于其余数字,那么在输出中,相应的项将主导分布,因此如果你从中采样,你几乎肯定只会选择最大化输入。但它比仅仅选择最大值更柔和,因为当其他值同样大时,它们也会在分布中获得有意义的权重,并且当你连续改变输入时,一切都会连续变化。在某些情况下,比如ChatGPT使用此分布来创建下一个单词时,可以通过在此函数中添加一个常数T来增加一些额外的乐趣,该常数T被抛入这些指数的分母中。我们称之为温度,因为它模糊地类似于温度在某些热力学方程中的作用,其效果是当T较大时,你会给较低的值更多的权重,这意味着分布会更均匀一些,如果T较小,那么较大的值将更积极地占主导地位,在极端情况下,将T设置为零意味着所有权重都将分配给最大值。温度为零意味着它总是使用最可预测的单词,并且你最终得到的是Goldilocks的陈词滥调的衍生品。较高的温度使其有机会选择不太可能的单词,但它伴随着风险。在这种情况下,故事的开头更具原创性,讲述了一位来自韩国的年轻网络艺术家,但它很快就变成了无稽之谈。从技术上讲,API实际上不允许你选择大于2的温度。这没有数学上的原因,这只是为了防止他们的工具被视为生成过于荒谬的东西而施加的任意约束。

接下来

本章的很多目标是为理解注意力机制奠定基础。如果你对词嵌入、softmax、点积如何衡量相似性以及大多数计算必须看起来像具有可调参数的矩阵的矩阵乘法的基本前提有很强的直觉,那么理解注意力机制(这是整个人工智能现代繁荣的基石)应该相对顺利。

几秒总结任意 YouTube 视频

用免费的 Summ App,为任意视频生成这样的摘要,支持你的语言。

在 App Store 下载
在 Google Play 下载

文字稿

“Transformers, the tech behind LLMs | Deep Learning Chapter 5”的完整文字稿。点击时间戳即可从该位置打开视频。想要其他视频的字幕?试试 YouTube 字幕提取工具。

0:00 The initials GPT stand for Generative Pretrained Transformer. So that first word is straightforward enough, these are bots that generate new text. Pretrained refers to how the model went through a process of learning from a massive amount of data, and the prefix insinuates that there's more room to fine-tune it on specific tasks with additional training. But the last word, that's the real key piece. A transformer is a specific kind of neural network, a machine learning model, and it's the core invention underlying the current boom in AI. What I want to do with this video and the following chapters is go through a visually-driven explanation for what actually happens inside a transformer. We're going to follow the data that flows through it and go step by step. There are many different kinds of models that you can build using transformers. Some models take in audio and produce a transcript. This sentence comes from a model going the other way around,

0:54 producing synthetic speech just from text. All those tools that took the world by storm in 2022 like DALL-E and Midjourney that take in a text description and produce an image are based on transformers. Even if I can't quite get it to understand what a pi creature is supposed to be, I'm still blown away that this kind of thing is even remotely possible. And the original transformer introduced in 2017 by Google was invented for the specific use case of translating text from one language into another. But the variant that you and I will focus on, which is the type that underlies tools like ChatGPT, will be a model that's trained to take in a piece of text, maybe even with some surrounding images or sound accompanying it, and produce a prediction for what comes next in the passage. That prediction takes the form of a probability distribution over many different chunks of text that might follow.

1:45 At first glance, you might think that predicting the next word feels like a very different goal from generating new text. But once you have a prediction model like this, a simple thing you could try to make it generate, a longer piece of text, is to give it an initial snippet to work with, have it take a random sample from the distribution it just generated, append that sample to the text, and then run the whole process again to make a new prediction based on all the new text, including what it just added. I don't know about you, but it really doesn't feel like this should actually work. In this animation, for example, I'm running GPT-2 on my laptop and having it repeatedly predict and sample the next chunk of text to generate a story based on the seed text. The story just doesn't actually really make that much sense. But if I swap it out for API calls to GPT-3 instead, which is the same basic model, just much bigger, suddenly almost magically we do get a sensible story,

2:35 one that even seems to infer that a pi creature would live in a land of math and computation. This process here of repeated prediction and sampling is essentially what's happening when you interact with ChatGPT, or any of these other large language models, and you see them producing one word at a time. In fact, one feature that I would very much enjoy is the ability to see the underlying distribution for each new word that it chooses. Let's kick things off with a very high level preview of how data flows through a transformer. We will spend much more time motivating and interpreting and expanding on the details of each step, but in broad strokes, when one of these chatbots generates a given word, here's what's going on under the hood. First, the input is broken up into a bunch of little pieces. These pieces are called tokens, and in the case of text these tend to be

3:26 words or little pieces of words or other common character combinations. If images or sound are involved, then tokens could be little patches of that image or little chunks of that sound. Each one of these tokens is then associated with a vector, meaning some list of numbers, which is meant to somehow encode the meaning of that piece. If you think of these vectors as giving coordinates in some very high dimensional space, words with similar meanings tend to land on vectors that are close to each other in that space. This sequence of vectors then passes through an operation that's known as an attention block, and this allows the vectors to talk to each other and pass information back and forth to update their values. For example, the meaning of the word model in the phrase "a machine learning model" is different from its meaning in the phrase "a fashion model". The attention block is what's responsible for figuring out which

4:15 words in context are relevant to updating the meanings of which other words, and how exactly those meanings should be updated. And again, whenever I use the word meaning, this is somehow entirely encoded in the entries of those vectors. After that, these vectors pass through a different kind of operation, and depending on the source that you're reading this will be referred to as a multi-layer perceptron or maybe a feed-forward layer. And here the vectors don't talk to each other, they all go through the same operation in parallel. And while this block is a little bit harder to interpret, later on we'll talk about how the step is a little bit like asking a long list of questions about each vector, and then updating them based on the answers to those questions. All of the operations in both of these blocks look like a giant pile of matrix multiplications, and our primary job is going to be to understand how to read the underlying matrices.

5:06 I'm glossing over some details about some normalization steps that happen in between, but this is after all a high-level preview. After that, the process essentially repeats, you go back and forth between attention blocks and multi-layer perceptron blocks, until at the very end the hope is that all of the essential meaning of the passage has somehow been baked into the very last vector in the sequence. We then perform a certain operation on that last vector that produces a probability distribution over all possible tokens, all possible little chunks of text that might come next. And like I said, once you have a tool that predicts what comes next given a snippet of text, you can feed it a little bit of seed text and have it repeatedly play this game of predicting what comes next, sampling from the distribution, appending it, and then repeating over and over. Some of you in the know may remember how long before ChatGPT came into the scene,

5:57 this is what early demos of GPT-3 looked like, you would have it autocomplete stories and essays based on an initial snippet. To make a tool like this into a chatbot, the easiest starting point is to have a little bit of text that establishes the setting of a user interacting with a helpful AI assistant, what you would call the system prompt, and then you would use the user's initial question or prompt as the first bit of dialogue, and then you have it start predicting what such a helpful AI assistant would say in response. There is more to say about an added step of training that's required to make this work well, but at a high level this is the idea. In this chapter, you and I are going to expand on the details of what happens at the very beginning of the network, at the very end of the network, and I also want to spend a lot of time reviewing some important bits of background knowledge, things that would have been second nature to any machine learning engineer by

6:50 the time transformers came around. If you're comfortable with that background knowledge and a little impatient, you could probably feel free to skip to the next chapter, which is going to focus on the attention blocks, generally considered the heart of the transformer. After that, I want to talk more about these multi-layer perceptron blocks, how training works, and a number of other details that will have been skipped up to that point. For broader context, these videos are additions to a mini-series about deep learning, and it's okay if you haven't watched the previous ones, I think you can do it out of order, but before diving into transformers specifically, I do think it's worth making sure that we're on the same page about the basic premise and structure of deep learning. At the risk of stating the obvious, this is one approach to machine learning, which describes any model where you're using data to somehow determine how a model behaves. What I mean by that is, let's say you want a function that takes in

7:42 an image and it produces a label describing it, or our example of predicting the next word given a passage of text, or any other task that seems to require some element of intuition and pattern recognition. We almost take this for granted these days, but the idea with machine learning is that rather than trying to explicitly define a procedure for how to do that task in code, which is what people would have done in the earliest days of AI, instead you set up a very flexible structure with tunable parameters, like a bunch of knobs and dials, and then, somehow, you use many examples of what the output should look like for a given input to tweak and tune the values of those parameters to mimic this behavior. For example, maybe the simplest form of machine learning is linear regression, where your inputs and outputs are each single numbers, something like the square footage of a house and its price,

8:30 and what you want is to find a line of best fit through this data, you know, to predict future house prices. That line is described by two continuous parameters, say the slope and the y-intercept, and the goal of linear regression is to determine those parameters to closely match the data. Needless to say, deep learning models get much more complicated. GPT-3, for example, has not two, but 175 billion parameters. But here's the thing, it's not a given that you can create some giant model with a huge number of parameters without it either grossly overfitting the training data or being completely intractable to train. Deep learning describes a class of models that in the last couple decades have proven to scale remarkably well.

9:16 What unifies them is that they all use the same training algorithm, it's called backpropagation, we talked about it in previous chapters, and the context that I want you to have as we go in is that in order for this training algorithm to work well at scale, these models have to follow a certain specific format. And if you know this format going in, it helps to explain many of the choices for how a transformer processes language, which otherwise run the risk of feeling kinda arbitrary. First, whatever kind of model you're making, the input has to be formatted as an array of real numbers. This could simply mean a list of numbers, it could be a two-dimensional array, or very often you deal with higher dimensional arrays, where the general term used is tensor. You often think of that input data as being progressively transformed into many distinct layers, where again, each layer is always structured as some kind of array of real numbers, until you get to a final layer which you consider the output.

10:09 For example, the final layer in our text processing model is a list of numbers representing the probability distribution for all possible next tokens. In deep learning, these model parameters are almost always referred to as weights, and this is because a key feature of these models is that the only way these parameters interact with the data being processed is through weighted sums. You also sprinkle some non-linear functions throughout, but they won't depend on parameters. Typically, though, instead of seeing the weighted sums all naked and written out explicitly like this, you'll instead find them packaged together as various components in a matrix vector product. It amounts to saying the same thing, if you think back to how matrix vector multiplication works, each component in the output looks like a weighted sum.

10:54 It's just often conceptually cleaner for you and me to think about matrices that are filled with tunable parameters that transform vectors that are drawn from the data being processed. For example, those 175 billion weights in GPT-3 are organized into just under 28,000 distinct matrices. Those matrices in turn fall into eight different categories, and what you and I are going to do is step through each one of those categories to understand what that type does. As we go through, I think it's kind of fun to reference the specific numbers from GPT-3 to count up exactly where those 175 billion come from. Even if nowadays there are bigger and better models, this one has a certain charm as the first large-language model to really capture the world's attention outside of ML communities. Also, practically speaking, companies tend to keep much tighter lips around the specific numbers for more modern networks.

11:47 I just want to set the scene going in, that as you peek under the hood to see what happens inside a tool like ChatGPT, almost all of the actual computation looks like matrix vector multiplication. There's a little bit of a risk getting lost in the sea of billions of numbers, but you should draw a very sharp distinction in your mind between the weights of the model, which I'll always color in blue or red, and the data being processed, which I'll always color in gray. The weights are the actual brains, they are the things learned during training, and they determine how it behaves. The data being processed simply encodes whatever specific input is fed into the model for a given run, like an example snippet of text. With all of that as foundation, let's dig into the first step of this text processing example, which is to break up the input into little chunks and turn those chunks into vectors. I mentioned how those chunks are called tokens, which might be pieces of words or punctuation,

12:41 but every now and then in this chapter and especially in the next one, I'd like to just pretend that it's broken more cleanly into words. Because we humans think in words, this will just make it much easier to reference little examples and clarify each step. The model has a predefined vocabulary, some list of all possible words, say 50,000 of them, and the first matrix that we'll encounter, known as the embedding matrix, has a single column for each one of these words. These columns are what determines what vector each word turns into in that first step. We label it W_E, and like all the matrices we see, its values begin random, but they're going to be learned based on data. Turning words into vectors was common practice in machine learning long before transformers, but it's a little weird if you've never seen it before,

13:30 and it sets the foundation for everything that follows, so let's take a moment to get familiar with it. We often call this embedding a word, which invites you to think of these vectors very geometrically as points in some high dimensional space. Visualizing a list of three numbers as coordinates for points in 3D space would be no problem, but word embeddings tend to be much much higher dimensional. In GPT-3 they have 12,288 dimensions, and as you'll see, it matters to work in a space that has a lot of distinct directions. In the same way that you could take a two-dimensional slice through a 3D space and project all the points onto that slice, for the sake of animating word embeddings that a simple model is giving me, I'm going to do an analogous thing by choosing a three-dimensional slice through this very high dimensional space, and projecting the word vectors down onto that and displaying the results.

14:21 The big idea here is that as a model tweaks and tunes its weights to determine how exactly words get embedded as vectors during training, it tends to settle on a set of embeddings where directions in the space have a kind of semantic meaning. For the simple word-to-vector model I'm running here, if I run a search for all the words whose embeddings are closest to that of tower, you'll notice how they all seem to give very similar tower-ish vibes. And if you want to pull up some Python and play along at home, this is the specific model that I'm using to make the animations. It's not a transformer, but it's enough to illustrate the idea that directions in the space can carry semantic meaning. A very classic example of this is how if you take the difference between the vectors for woman and man, something you would visualize as a little vector in the space connecting the tip of one to the tip of the other, it's very similar to the difference between king and queen.

15:15 So let's say you didn't know the word for a female monarch, you could find it by taking king, adding this woman minus man direction, and searching for the embedding closest to that point. At least, kind of. Despite this being a classic example for the model I'm playing with, the true embedding of queen is actually a little farther off than this would suggest, presumably because the way queen is used in training data is not merely a feminine version of king. When I played around, family relations seemed to illustrate the idea much better. The point is, it looks like during training the model found it advantageous to choose embeddings such that one direction in this space encodes gender information. Another example is that if you take the embedding of Italy, and you subtract the embedding of Germany, and add that to the embedding of Hitler,

16:04 you get something very close to the embedding of Mussolini. It's as if the model learned to associate some directions with Italian-ness, and others with WWII axis leaders. Maybe my favorite example in this vein is how in some models, if you take the difference between Germany and Japan, and add it to sushi, you end up very close to bratwurst. Also in playing this game of finding nearest neighbors, I was very pleased to see how close cat was to both beast and monster. One bit of mathematical intuition that's helpful to have in mind, especially for the next chapter, is how the dot product of two vectors can be thought of as a way to measure how well they align. Computationally, dot products involve multiplying all the corresponding components and then adding the results, which is good, since so much of our computation has to look like weighted sums.

16:55 Geometrically, the dot product is positive when vectors point in similar directions, it's zero if they're perpendicular, and it's negative whenever they point in opposite directions. For example, let's say you were playing with this model, and you hypothesize that the embedding of cats minus cat might represent a sort of plurality direction in this space. To test this, I'm going to take this vector and compute its dot product against the embeddings of certain singular nouns, and compare it to the dot products with the corresponding plural nouns. If you play around with this, you'll notice that the plural ones do indeed seem to consistently give higher values than the singular ones, indicating that they align more with this direction. It's also fun how if you take this dot product with the embeddings of the words one, two, three, and so on, they give increasing values,

17:44 so it's as if we can quantitatively measure how plural the model finds a given word. Again, the specifics for how words get embedded is learned using data. This embedding matrix, whose columns tell us what happens to each word, is the first pile of weights in our model. Using the GPT-3 numbers, the vocabulary size specifically is 50,257, and again, technically this consists not of words per se, but of tokens. The embedding dimension is 12,288, and multiplying those tells us this consists of about 617 million weights. Let's go ahead and add this to a running tally, remembering that by the end we should count up to 175 billion. In the case of transformers, you really want to think of the vectors in this embedding space as not merely representing individual words.

18:32 For one thing, they also encode information about the position of that word, which we'll talk about later, but more importantly, you should think of them as having the capacity to soak in context. A vector that started its life as the embedding of the word king, for example, might progressively get tugged and pulled by various blocks in this network, so that by the end it points in a much more specific and nuanced direction that somehow encodes that it was a king who lived in Scotland, and who had achieved his post after murdering the previous king, and who's being described in Shakespearean language. Think about your own understanding of a given word. The meaning of that word is clearly informed by the surroundings, and sometimes this includes context from a long distance away, so in putting together a model that has the ability to predict what word comes next, the goal is to somehow empower it to incorporate context efficiently.

19:24 To be clear, in that very first step, when you create the array of vectors based on the input text, each one of those is simply plucked out of the embedding matrix, so initially each one can only encode the meaning of a single word without any input from its surroundings. But you should think of the primary goal of this network that it flows through as being to enable each one of those vectors to soak up a meaning that's much more rich and specific than what mere individual words could represent. The network can only process a fixed number of vectors at a time, known as its context size. For GPT-3 it was trained with a context size of 2048, so the data flowing through the network always looks like this array of 2048 columns, each of which has 12,000 dimensions. This context size limits how much text the transformer can incorporate when it's making a prediction of the next word. This is why long conversations with certain chatbots,

20:15 like the early versions of ChatGPT, often gave the feeling of the bot kind of losing the thread of conversation as you continued too long. We'll go into the details of attention in due time, but skipping ahead I want to talk for a minute about what happens at the very end. Remember, the desired output is a probability distribution over all tokens that might come next. For example, if the very last word is Professor, and the context includes words like Harry Potter, and immediately preceding we see least favorite teacher, and also if you give me some leeway by letting me pretend that tokens simply look like full words, then a well-trained network that had built up knowledge of Harry Potter would presumably assign a high number to the word Snape. This involves two different steps. The first one is to use another matrix that maps the very last vector in that

21:03 context to a list of 50,000 values, one for each token in the vocabulary. Then there's a function that normalizes this into a probability distribution, it's called softmax and we'll talk more about it in just a second, but before that it might seem a little bit weird to only use this last embedding to make a prediction, when after all in that last step there are thousands of other vectors in the layer just sitting there with their own context-rich meanings. This has to do with the fact that in the training process it turns out to be much more efficient if you use each one of those vectors in the final layer to simultaneously make a prediction for what would come immediately after it. There's a lot more to be said about training later on, but I just want to call that out right now. This matrix is called the Unembedding matrix and we give it the label WU. Again, like all the weight matrices we see, its entries begin at random, but they are learned during the training process.

21:56 Keeping score on our total parameter count, this Unembedding matrix has one row for each word in the vocabulary, and each row has the same number of elements as the embedding dimension. It's very similar to the embedding matrix, just with the order swapped, so it adds another 617 million parameters to the network, meaning our count so far is a little over a billion, a small but not wholly insignificant fraction of the 175 billion we'll end up with in total. As the very last mini-lesson for this chapter, I want to talk more about this softmax function, since it makes another appearance for us once we dive into the attention blocks. The idea is that if you want a sequence of numbers to act as a probability distribution, say a distribution over all possible next words, then each value has to be between 0 and 1, and you also need all of them to add up to 1.

22:45 However, if you're playing the deep learning game where everything you do looks like matrix-vector multiplication, the outputs you get by default don't abide by this at all. The values are often negative, or much bigger than 1, and they almost certainly don't add up to 1. Softmax is the standard way to turn an arbitrary list of numbers into a valid distribution in such a way that the largest values end up closest to 1, and the smaller values end up very close to 0. That's all you really need to know. But if you're curious, the way it works is to first raise e to the power of each of the numbers, which means you now have a list of positive values, and then you can take the sum of all those positive values and divide each term by that sum, which normalizes it into a list that adds up to 1. You'll notice that if one of the numbers in the input is meaningfully bigger than the rest, then in the output the corresponding term dominates the distribution,

23:37 so if you were sampling from it you'd almost certainly just be picking the maximizing input. But it's softer than just picking the max in the sense that when other values are similarly large, they also get meaningful weight in the distribution, and everything changes continuously as you continuously vary the inputs. In some situations, like when ChatGPT is using this distribution to create a next word, there's room for a little bit of extra fun by adding a little extra spice into this function, with a constant T thrown into the denominator of those exponents. We call it the temperature, since it vaguely resembles the role of temperature in certain thermodynamics equations, and the effect is that when T is larger, you give more weight to the lower values, meaning the distribution is a little bit more uniform, and if T is smaller, then the bigger values will dominate more aggressively, where in the extreme, setting T equal to zero means all of the weight goes to maximum value.

24:33 For example, I'll have GPT-3 generate a story with the seed text, "once upon a time there was A", but I'll use different temperatures in each case. Temperature zero means that it always goes with the most predictable word, and what you get ends up being a trite derivative of Goldilocks. A higher temperature gives it a chance to choose less likely words, but it comes with a risk. In this case, the story starts out more originally, about a young web artist from South Korea, but it quickly degenerates into nonsense. Technically speaking, the API doesn't actually let you pick a temperature bigger than 2. There's no mathematical reason for this, it's just an arbitrary constraint imposed to keep their tool from being seen generating things that are too nonsensical.

25:19 So if you're curious, the way this animation is actually working is I'm taking the 20 most probable next tokens that GPT-3 generates, which seems to be the maximum they'll give me, and then I tweak the probabilities based on an exponent of 1/5. As another bit of jargon, in the same way that you might call the components of the output of this function probabilities, people often refer to the inputs as logits, or some people say logits, some people say logits, I'm gonna say logits. So for instance, when you feed in some text, you have all these word embeddings flow through the network, and you do this final multiplication with the unembedding matrix, machine learning people would refer to the components in that raw, unnormalized output as the logits for the next word prediction. A lot of the goal with this chapter was to lay the foundations for understanding the attention mechanism, Karate Kid wax-on-wax-off style.

26:10 You see, if you have a strong intuition for word embeddings, for softmax, for how dot products measure similarity, and also the underlying premise that most of the calculations have to look like matrix multiplication with matrices full of tunable parameters, then understanding the attention mechanism, this cornerstone piece in the whole modern boom in AI, should be relatively smooth. For that, come join me in the next chapter. As I'm publishing this, a draft of that next chapter is available for review by Patreon supporters. A final version should be up in public in a week or two, it usually depends on how much I end up changing based on that review. In the meantime, if you want to dive into attention, and if you want to help the channel out a little bit, it's there waiting.

Share

更多视频摘要