Transformers and Large Language Models
Transcript
Cool. Hello everyone, and welcome to CME 295-- Transformers and Large Language Models. So my name is Afshine. And I will be teaching this class with Shervine, who's in the back. And before I start, I'm just going to introduce ourselves. So we're twin brothers, and we actually had a similar background. So we both went to a school in France called Centrale Paris, and then we each went our way. So on my end, I went to MIT, and then Shervine went to Stanford to do the ICME Master's program.
And after that, I guess our industry background is very similar as well. So I first went to Uber, and then Shervine came to Uber as well, and then Shervine left to Google, and I went to Google. And then very recently, I joined Netflix, and Shervine joined Netflix as well. And we've been working on Large Language Models. So yeah, I guess we have technical backgrounds, and mostly oriented towards LLMs. OK, so why are we doing this class? So since 2020, Shervine and I have been specializing in NLP.
And we've been giving this class in the format of a workshop that was done on a yearly basis. So in 2021, 2022, 2023, 2024, ChatGPT came in 2022, and suddenly there was a lot of interest for LLMs. And so it's actually last spring that we started to offer this class as a Stanford course that is now called CME 295, and this is the second instance.
Cool. So what can you expect from this class? So first of all, LLMs are basically everywhere now. And I guess our goal here is twofold. So the first one is to learn about the underlying mechanism that makes all this work. And we're going to see the transformer, which is the foundational architecture that makes all this work. And then the second thing is to know how these LLMs are trained and where they are applied.
So in case you're still wondering if this class is good for you, I would say that this class is great for people who just in general have an interest in this field, either because you wanted to make it your career goal, if you want to be a research scientist or an ML scientist, or if you want to develop a personal project that relies on LLMs to some extent, to just knowing the caveats, I guess what works, what doesn't, or just say if you're in a separate field
and you just want to know how this whole AI, GenAI, LLMs thing works and how you can apply it to your domain. So now in terms of prerequisites, I would say that at a very minimum you should have some foundations in ML, like basically know how a model is trained, what a neural network is, and also some basics in linear algebra, so basically how matrices are multiplied, for instance. But even if you have a developing, I guess, competency in this field, I guess it's fine, we're still be here to help you out. But I guess this is like the ideal set of prerequisites.
Cool. So still on the logistics, so this class will be held every Friday from 3:30 to 5:20, and it will be held here. So this class is two units. And you have the choice to either take it as a letter or a credit/non-credit. So as you could tell from the setup, we're basically recording this class. And if you cannot for some reason attend this time, this slot, we'll make sure with Shervine to make the recordings available, either tonight, like every Friday night, or on Saturday. So in terms of the grades, so what we're doing for this quarter is to have two exams. So one is the midterm, which will
be happening during our fifth instance, which is October 24. And then the second exam will be the final exam, which will be held in the week of December 8. So date is still TBD. So we'll let you know. Cool. So every time we have a lecture, we'll be posting the slides and the recordings on the website. And in case you're interested, we also have the syllabus in there, so you can know a little bit what are the topics that we'll be talking about. And the class textbook is this Super Study Guide--
Transformer LLMs. So we have a copy here in case you want to take a look. So yeah, I guess a lot of the concepts that we have in this class will actually be in the book. So I guess it's a helpful way to follow this as well. And also, we did some very short, condensed version of this whole class that we called the VIP cheat sheet. So this one is available on GitHub in case you're interested. And yeah, we also translated it into a number of languages now.
By the way, if your language is not there, let us know, and happy to work on that as well together. OK cool. I think it's the last things on the logistics part. So in terms of announcements, we'll be posting things on Canvas. In case you have any questions, you can of course reach out to us. But there is also a tab on Canvas that's called Ed. I'm sure you're familiar. So you just click on that, just post your question, and then Shervine and I will be responding.
And I guess to reach out to us, you have this mailing list. Or we're just two, so just ding us. Cool. So on the logistics, do we have any questions so far? And one thing I forgot to mention is that, given that we're recording this class, I guess if you're asking a question, it may not be super clear for the viewer what your question was. So I'm going to make an effort to just repeat your question. It will sound weird, but I'll try to not forget, but yeah.
So any questions so far on the logistics? Yeah. So the question is whether there are coding parts in the exams. So the answer is no. So the exams will purely focus on concepts that we see in class. And actually, it's not meant to trap you. So I guess if you follow the class, if you see the slides and the concepts that we see, should be fine. Yeah.
Oh yeah. Question is, if you're waitlisted, what do you do? I think, so by experience, a lot of people will finalize their schedule. Some people will drop, some won't. In case you're still waitlisted, come talk to us. But I'm pretty confident it's going to be OK, because I think the waitlist right now is six. So, I think it should be fine. Cool. Yeah. They will be on the website, and we'll make sure to also post a link on Canvas. Yeah. So the question was, where are the slides. And they're on the website. Cool yeah.
So question is on the weighting of the exams. So there is no homework. So 50% is midterm, 50% is final. And no grades-- I mean, no weights are from that. And particular, I mean if this slot is conflicting with something, just keep in mind that we are recording this. So it's fine if you cannot attend this session. Yeah. Sorry?
Oh, is the question that the final is about just the second half of the class? We have not written the exam yet, but I think this is something we are thinking of. So the final is probably going to be about the second half of the topics. Cool. OK, long story short, 50% midterm, 50% final exam. And it's a fun class. Cool. So with that, I'm going to just slowly start the class. So another thing that I want to mention was every time we're talking about something, you will see that at the bottom of the slide there will be a source, and it's mostly for-- so first, to credits, whatever, we're quoting, but also for you to dig into those materials a bit more in case you're interested. Because, of course, we have only two hours per week,
and we only have nine or 10 weeks, so there's nowhere near enough time for us to cover everything. And the second disclaimer is you will see that the field is full of abbreviations. So I myself was completely scared of them when I started. But hopefully by the end of the class, you will have a mental mapping of what these abbreviations mean, respect to what they correspond to. So yes, so if you have a mental mapping towards the end of the class, then we know e did a good job.
So with that, let's start. And I guess we will start at a very high level, because I will just assume that I guess we're starting from scratch. And we're going to talk about NLP in general. So NLP is going to be our first abbreviation. So NLP stands for Natural Language Processing. And it is a field that is around manipulating text, just computing things with text. And at a very high level, can basically classify NLP tasks into three buckets. So the first bucket is what we call classification.
So we have an input text as an input. And then what we want is to predict something. So one example is you have a movie review and you want to predict whether the sentiment is positive, negative, or neutral. So that's one example. You can also have intent detection, just knowing what, for instance, the person wants to do. So let's suppose you say, I want to create an alarm for tomorrow. So the intent here is create an alarm. So also to detect a language-- so for instance,
if you write among French, you want to detect that text is in French, topic modeling. The second category is what we call multi-classification. So we still have a text as input, but this time we predict more than one thing. So you have a number of tasks in that bucket as well. So one that is very popular is called Named Entity Recognition, a.k.a. NER. So what that task does is, given an input text, we want to basically label some specific words, like, for instance, identifying whether something
is a location, or a time, and so on. And then you have some other tasks as well that are a little bit more on the linguistic side. I think they're less trendy now, but I guess 10 years ago it was something that people would study a lot. So part of speech tagging, which is about just figuring out which word is a noun, a verb, et cetera, or some parsing-related tasks, so dependency or constituency parsing. And then the last bucket, which is very popular these days is the generation bucket.
So you have the text as input, and you also have text as output. And here the length can be variable, meaning you don't know what the length of your output text will be beforehand. So here you have several tasks. So for instance, you have machine translation. So for instance, something in English and I wanted to let's say German. Question answering-- so typically the ChatGPT, Gemini that you're using, the assistant. So you ask a question and you have a response.
And then you have other tasks as well, like summarization, you want to summarize an article, let's say, or just generate something. So something can be generate codes, generate a poem, can also be a lot of things. Cool. So now what we will do is go through these tasks one by one to just illustrate what people typically handle with. So we're going to start with the first bucket, which is the classification bucket. And here we're going to illustrate this with the sentiment extraction task. So let's suppose we have a sentence, "this teddy bear is so cute." We want our model to predict this to be a positive sentiment. So typically what you would use is sentiment extraction data sets.
So I mentioned movie reviews, so this is IMDb critiques. But you also have reviews about products, so Amazon reviews or tweets. Now I guess it's called X, so X posts. And the way you would evaluate such outputs would be by typically using traditional classification metrics. So you have accuracy, which is what is the percentage of the observations that you correctly predicted. But you also have two key metrics, which I'm just going to remind. I'm not sure if everyone knows about them.
So one is precision, which is, out of all the positive predictions that you made, which ones were correct? And then the second one is recall. Out of all the true labels, how many of them did you correctly predict as being positive? And you have this metric called the F1 score, which basically takes the harmonic mean of precision and recall to just give you one number. So now you may wonder, why do you need all these metrics? So the short answer is that sometimes you have tasks
and data sets where your classes are very imbalanced. So for instance, you can have 99% of your data set that is a positive label, and then only 1% of the data set which is negative. And so here if you take a metric like accuracy, can be very misleading. Because if you have a model that would predict everything as the majority class, then you will have a great classifier, but that's not the case. So that's why precision and recall really play a role. So that's for the first one.
So now let's move to the second category of NLP tasks. So this one is the multi-classification category. So you have an input text and you predict multiple things. And we're illustrating this with the NER task, which as I mentioned is about identifying the category of given words. And so here, for instance, we want to identify a teddy bear as being an entity. I guess for that, you would use classification metrics, but not at the sentence level, but more either at the token level
or at the entity-type level. And by that I mean, let's suppose you have a category, let's say location. And you want to know how well you're predicting words in that category. So you would typically aggregate these metrics as a function of that. Cool. OK, let's go to the last category, which is, as I mentioned, the most popular one. So this one is text in, text out. So I'm illustrating this with the machine translation task, which is around translating a text from a source language to a target language. So here you have the example with English to French. So cute teddy bear is reading, un ours en peluche mignon lit. So for that, I guess it's harder to get data sets, because here you need to have pairs of texts.
So you have a very popular data set that's called WMT, which stands for Workshop on Machine Translation. And that one contains a bunch of paired sequences in different languages. So for instance, you have the English-French, English-German, coming from the European Parliament data set, for instance. So to evaluate those, to evaluate the performance of your model, it's actually a lot more tricky. Because, as you can imagine, you can have many different ways to translate something.
I'm sure many of us in the room are bilingual, trilingual. So that's what is making it this hard. So in the past, people have used several rule-based metrics to do that. So one that you may have heard is BLEU. BLEU stands for Bilingual Evaluation Under Study. And it is a measure of how well your translation stands with respect to a reference text. Same story for ROUGE, which is actually a suite of metrics, but captures that in a different way. And you will see that the machine learning community
is funny, because BLEU-- I'm not sure if you know French-- means blue, but rouge means red. So I guess they tried to add some fun in this. But the problem with these metrics is that you always need a reference text. So you basically need labels. And in practice, having labels is very cost expensive. It takes a lot of time, a lot of money to get labels. And we will see later in the class that with the progress that we have made in the LLM space, or that the community has made in the LLM space,
we can actually forego of this reference-based metrics and go towards a more reference-free metrics. And we will see that later on. And then the last metric that I will say that people sometimes use is called perplexity. And perplexity only looks at the probabilities that are output by the model. And it basically quantifies how surprised the model is by its output. So BLEU and ROUGE, the higher the better. Perplexity, the lower the better.
And I guess LLMs have been a hot topic since 2022. But actually, the field goes way back, way before that year. So in the '80s, we'll see it in a second, but there's a class of models that were actually thought of, even in the '80s. And the '90s, we had LSTMs that we'll see also in a second. But the problem was, during that time, we didn't have the internet. We didn't have a lot of compute. And I guess this was one of the limiting factors which prevented the models from today from being trained.
And then more recently, we've had several advances. So Word2vec was really one of the pioneering work in just computing meaningful embeddings. And we'll see it in a second. And then, of course, we had the transformers, which were part of a paper that was published in 2017, which is basically at the foundation of all of the models that you see today. And then these models, they just were scaled up, both by compute, but also in terms of the data that was used to train them.
And that's how LLMs were dubbed. And I guess these are more like the 2020s. But yeah, I guess we'll see those. Cool. Any questions on, I guess, the high level? Everyone good? Cool. So I guess the first question that I want to ask ourselves is, what we want to do is to have a model that handles text. But models, they understand numbers, they don't really understand text. So we need to somehow do something with that text to make it more quantifiable, something that a model can understand. So if you look at a sentence, for instance, "a cute teddy bear is reading," you first need to ask yourself,
how can you cut this sentence to pass it to a model? So this part is called tokenization. And what that entails is basically cutting the text with respect to some arbitrary unit of text. So there are several ways of doing this. I guess the first way is doing it completely arbitrarily. So here, for instance, you would have "a." That would be one unit of text. "Cute" could be another unit of text. "Teddy bear" would be another one, and so on. And by the way, the unit of text is called a token, which is why the method is called tokenization.
Another way would be to just separate by words. But I guess we would have always pros and cons. I guess one of the goals that we want to achieve is for us to then be able to represent these tokens in a meaningful way. So one con with doing this at the word level is you will end up with words that look similar, but that are actually considered as different tokens. And I guess the limitation here is you will need to compute embeddings for these similar yet different tokens and somehow make their embeddings similar. So I'll give you an example.
So let's suppose I have the word "bear." And then you have another word, plural form "bears." So these two words, they are very similar. Just one is singular, the other one is plural. If we go ahead with the word-level tokenization, then we will end up with just two different entities, which are basically just considered as different. Same with "run," and then "runs," variations of verbs. So for that reason, people have dug into a category of tokenizers that
are called subword tokenizers, which is around leveraging roots of words in order to find what are the common roots that we can find in these words. So, for instance, for bear and bears, you would have the bear particle that would be shared. And so I guess the pro is that you get to leverage the root of the words. But then the con here is that your sequence would be longer. And we will see why this is a con. I guess later on, I guess I can give you a preview. So the complexity of these models
is also a function of the sequence length. So the more tokens you have to process, the more time it will take for your model to run, because it needs to basically process all these tokens. So that's one con. So pro is it leverages the root of words. Con is it just makes your sequences longer. You have a last category of ways of tokenizing things, which is just going at the character level, just like taking out characters. So here, I guess, you and I when we write a message, we typically have sometimes misspellings. And with the subword way of tokenizing things, you may not be able to recognize the word that has been misspelled. And this is something that the character-level tokenizer can, I guess, take into consideration. But here the problem is you have a sequence length that's
much, much longer, which will make your model, I guess, take much more time to process the sequence. So that's one con. And then the other con is, I guess, when you want to represent each of these tokens, I guess it's very hard to know that a representation of a letter really means. Like, what does the representation of the letter U mean. It's very hard. OK cool. So I have just a quick recap. So word-level is a super naive way, super simple way of,
I guess, dividing your text into arbitrary units. But then the problem is, as we mentioned, we do not leverage the root of words. And I did not mention this, but there is a term. Whenever you cut something and then at inference time when you want to make a prediction, I guess, one prerequisite that you have is that you need to have the token that you saw at training time, you need to have it in your training sets. And the problem is, let's suppose at inference time you cut your text into words.
And let's suppose you have not seen a word at training time. You will need to mark it as unknown. And so this thing is called OOV, Out Of Vocabulary. So luckily, the subword-level tokenizer mitigates that problem. So you have a lower risk of OOV, but still you can have. And as we mentioned, in terms of the pro, you leverage the roots of the words.
And then character-level, it's robust to our misspellings and our casing errors. But the problem is it makes computations just much slower. And your sequences would be very, very long, which will also make your, I guess, inference time much higher. That sound good? I guess this is really the foundation, I guess, how to handle things with text. But yeah, does that make sense overall?
Cool. OK, so now what we did is we took an input text. What we did is we cut it into parts that are basically tokens. So in order for our model to understand these tokens, we need to find a representation for each of them. So here, we're going to take a look at this. So that's called a word representation. Or I guess, in a more correct way, it should be token representation. So we want to find a way to represent each of these tokens.
So the simple and naive way to do this would be to just assign the one hot vector for each word or for each token. So for instance, let's suppose we have a vocabulary of three tokens-- book, soft, and teddy bears. We would have, let's say, soft. That is 1, 0, 0 vector. Teddy bear, that is, let's say a 0, 1, 0 vector. And book, that is, let's say, a 0, 0, 1 vector. So this is called a One-Hot Encoding, OHE. We'll typically see. So cool. This is a way to represent our tokens.
But basically what people want to do is compare these tokens to basically see which ones are more similar to what other ones. So common similarity measure that people use is something called cosine similarity. I'm not sure if you have heard of it. So you can think of it as just seeing what angle these vectors make in the n dimensional space. And if, I guess, they are pointing in the same direction, then maybe they're similar. Maybe if they're orthogonal, maybe they're independent.
And if they're completely opposite, then maybe they're opposite. That's basically the mental model we want to go into. So the problem is, if you represent your tokens in a one hot fashion, you will end up with all your vectors being orthogonal to one another. So that's the problem. So ideally, what we want is for tokens that mean the same or similar to basically have a high similarity. And for tokens that are not similar on about different thing, to be more orthogonal.
So here, just for illustrative purposes, teddy bears are soft. So you want teddy bear and soft to be, I guess, with a high similarity. And let's say teddy bear and book, which is independent, you want them to be closer to 0. So that's what you want. That's what you have with one-hot encoding, and that's what you want. Yeah. Sorry?
Oh, I see. The question is, why do you care about the norm? So I guess cosine similarity is actually normalized by norms. So it's dot products. Oh, you mean why did I just put dot product here instead of 2? Oh, I see. And your question is, why do we not care about the norm? Cool, I guess the viewers know the question. I guess these measures, they are all measures. They are all ways to try to capture these similarity things. So I guess why do you not care about the norm?
I guess it's how people have tried to quantify that. I guess you will need to see how your vectors are trained and whether the norm would be indicative of something. I guess the best answer I can give you is, I guess, this is a measure. This is not the perfect measure. People may use also dot product as a measure, but yeah, I don't have a great answer for you. But as long as you capture, I guess, how these vectors they're pointing, I guess, typically what you care about is the angle between them. But typically, you don't really take into consideration the norm.
Cool, any questions? Any other questions? Yeah yeah yeah yeah. It's a great question. So the question is around size of vocabulary and how that would inform the choice with respect to word, subword, and how that changes across languages. So great question. So I would say it really depends, first of all, on the tasks that you're trying to achieve. If your task is just about one language, you will just take that same language. You would typically go with a subword tokenizer just because of the reasons that we mentioned here.
So I guess subwords is a nice trade-off between being able to identify words by their roots, like leveraging that, but also running less into the OOV risk. So in terms of the size, I know that people have tried different things. I think typically for English, you would target something on the order of tens of thousands of vocabulary size. But nowadays, the models, they are multilingual, they are also about codes. So you will see that the vocabulary size now is sometimes on the order of hundreds of thousands. So with respect to Chinese, so I guess you have this difference in characters that you're using. So for Latin, I guess it's the alphabet
we're all accustomed to. But of course for the other ones, you'd have something similar, but in I guess the target language character. So yeah, I would say order of magnitude, tens of thousands for one language, hundreds of thousands if it's multilingual. These are the order of magnitude that you want to target for. Cool yeah.
Great question. So the question is, how do you get those embeddings? So it's actually the next slide. So I'm going to talk about this. Cool great. So now that we know that the one-hot encoding is not a good way to represent tokens, what we want to do is to learn those embeddings from the data. So I mentioned that there was this paper that came out in the 2010s-- so I think it was 2013-- that was called Word2vec. And the reason why it was so popular
is because they showed a very intuitive and interpretable way of seeing these embeddings, because they were saying something like, OK, king is to queen, what this is to that, like Paris is to France what Berlin is to Germany. So there was basically a way to make sense of the embeddings. So now the question is, how did they do that? So they had two ways of computing these embeddings. So one way was called continuous bag of words. The other one was called skip gram.
But they all rely on the same idea, which is let's just leverage texts that we have, and then try to predict something that is part of the text, based on, let's say, the context. So for instance, continuous bag of words, the goal is you take into consideration the words that are around a given target words. And your goal is to predict that target word. And skip gram is the opposite. You go from a target word and you want to predict the words that are around it.
So I guess this task is commonly called a proxy task. Because at the end of the day, in this exercise, what we care about is not necessarily to predict the next word, or at least not yet. Our goal is to learn a representation of these words that are meaningful. And so here the idea is, if you have a model that somehow knows how to predict, let's say, the next word, then it means that your model has some understanding of how language works, which is basically what you want.
You basically want an embedding that is reflective of, I guess, what language is, which is king and queen, or similar, Paris and France, this is a capital. You want to have these associations embedded in the representation. And let's go through a very simple example of what that looks like. So here in our example, let's suppose that our proxy task is about predicting the next word. So here what we take is a very vanilla neural network model, which basically receives a vector of size v, has multiplication and a bias term to get a hidden state, and then another set of multiplications to get our final vector. So here it's basically a very simple neural network. So the input is of size v. The hidden layer is of size
d, which is typically much smaller than the vocabulary. So vocabulary is typically like tens of thousands or hundreds of thousands. So d is typically hundred. Like, 768, for instance, is one example of dimension. So it's much, much smaller. So what we're trying to do is to learn the word representation through this proxy task. And what we're going to do is try to consider the words as inputs and predict the next word.
So let's go with the first word of the sequence. So by the way, I use token and words interchangeably. So let's suppose we have the word "a," and we want to predict the next word, which is the word "cute." So what we do is we take the word "a," we take the one-hot encoding representation, and we pass it through the network. So here, if you're familiar with neural networks, so here you have, I guess, a multiplication between a matrix and this vector. So you have a hidden state representation,
which is a vector of size d. So here, let's suppose it's 0.2 and 0.9, so D equal 2. And then you have, I guess, another pass here. And then you get, after softmax, a set of probabilities which are around seeing what is the next word. So in this example, we have a vocabulary of size 6. So the first word is predicted with probability 0.2, second word, 0.4, and then the other words are all 0.1 in this example. So let's suppose that we want to somehow be able to maximize our prediction
to be the second word of the vocabulary, which is the 0.4. So we basically compare the prediction with, I guess, 0, 1, 0, 0, 0, which is the representation of the second word of the vocabulary. And then we do the back prop, we update the weights. I'm not sure if everyone is familiar with that part. But the idea here is, once you obtain a prediction, you compute the loss, so typically cross-entropy, which will determine how far off you are from the true answer.
And based on that difference, you're going to update the weights in order to make your prediction closer to the truth. So that's what you do. And then you repeat that process. Let's suppose you take the word "cute," which, as we said, is the second word in the vocabulary. So the one-hot encoding representation is 0, 1, 0, 0, 0. So you go through that network, you have a hidden state, like the vector is 0.8 and 0.4. You do that again. And what you want to do is to predict the next token,
and here is teddy bear. And so you see now your model in this example is predicting the next word to be uniform, but you want to somehow maximize the probability for teddy bear. So you go about doing this again and again for all the words. And at the end of the day, you obtain a model that learns how to predict the next word, which is basically the proxy task. And what you're going to do is to take the representation that the model learns, which is the green units.
So what happens now is every time you have a word, you just represent that as a one-hot encoding representation. And you just multiply this with these weights, and then you obtain the green representation. And that is your word representation. Does that make sense? Yeah yeah.
Yeah, great question, great question. So the question is about what does v correspond to and why there's only six. So yes, in this example we only have six possible words, which is basically the vocabulary size, just like a very toy example, because in practice there is many more. So I guess that's one of the challenges with language. So you can technically have many variations of words, which is why if you take a word-level way to divide your text into tokens, you can end up
with the vocabulary that's very big, because you need to account for all the variations of given words. And the other thing that I want to point out is, let's suppose you have a vocabulary size of 6, and it's the six words that you saw at training time. But what happens if at inference time you have a word that you have not seen at training time? And so the answer for that is typically what people do is they reserve a spot for what they call an unknown token or out-of-vocabulary token,
which is basically you can think of it as a bucket for everything that we were not able to identify. So if let's suppose at inference time you have a token that you were not able to identify, they will all take that representation, which is the unknown token representation. And this is, by the way, something that I guess the word-level tokenizer has trouble to do, because you will have a much bigger chance of having out-of-vocabulary tokens. Subword level will have a lower chance.
And then character level, I guess, you don't have that problem. Does that answer your question? Yeah. Cool yeah. Great, great question. So first question is, when you're done? So the thing with the proxy task is when you train your model, I guess your true objective is to not really learn-- I mean, in this case-- to learn how to predict the next word. Your objective is to have meaningful representations. But what you can do is to somehow track the loss function for the proxy task that you're pursuing, but then also taking into consideration that this is not necessarily your end goal.
So I guess one very reasonable way of going about doing this is just to wait until your model converges. So here, what you do is you track the loss as a function of-- so there's this term "epoch," just how many times your model sees the training set. And so you compare these different curves. And when this converges, this is typically a good time to stop the training process and just see if that makes sense. Depends on your downstream task, of course. But that's one.
So your second question-- sorry, can you repeat the second question? Yeah, yeah, oh, great question. So the question is, how do you know when the generation stops? I guess, otherwise it will never stop. So yeah, exactly. So you have some special tokens. Typically, you have end of sequence, end of sequence. So typically when you have the end of sequence token generated, then it's when it stops.
All right. So second question was what informs the size of the hidden layer? I would say it's a trade-off, because you want the embedding to be rich enough that it can be informative for your downstream task. So for instance, if you want to somehow get an embedding of, let's say, your sentence, and if you want to, let's say, do a very, very specialized task, like with a lot of different outcomes, maybe you want a vector that recaptures that, so maybe you
want a bigger vector, but if you had a very simple task, maybe a smaller vector might make sense. So I guess the size of your hidden dimension also impacts the complexity of whatever you're running after. Because of course, if you have longer vectors, you'll have more computation, so your inference will be probably more expensive, et cetera. So I guess there's a lot of factors. So I guess just to recap, one is how complicated your downstream task is. Second one is how sensitive are you with latency, cost, all these things. So it's really a trade-off. But out there you would typically see embeddings of a pool of hundreds or thousands. Of course, these models, they've been growing, so this number may change. But that's the order of magnitude that you're looking at.
Right. This is indeed empirical. Yeah yeah. I guess you can also rely on what others found and just go from that. But 768, these numbers are things that people typically take. Cool yeah.
Great question. So the question is, how can you distinguish words that are spelled the same but in different contexts? So you're way ahead of me. So this is basically the basics. And we're going to tackle methods that can tackle these problems of just contextualizing the word in the sentence. So yeah, so we'll see that in a bit. Cool.
I'm not on time. So I'll try to get moving. So OK, so now what we did was see how we could learn representations of tokens. But I guess you may also want to get representations of sentences or pieces of text. So one very naive way to do that with what we saw before is to take something like the average of words, let's say, the word representations. But the problem is you lose a lot of meaning, you lose the order, you lose-- and I guess here, I think you pointed out very well,
the representations that you learn are token-specific, regardless of where they're at. So that's why we have a class of models that aim at capturing the sequential nature of how text appears. So we're going to talk about RNNs, which stands for Recurrent Neural Network. So what RNNs do is, instead of processing words one at a time, what they do is they keep a hidden representation of the sentence so far, and they consider tokens one at a time. So as I mentioned before, this technique was actually
introduced a fair amount of time ago, so in the '80s. And what this model does is it takes into consideration the order at which words appeared or tokens appeared. And so in this example, you start the, I guess, processing at the very beginning of the sentence. You have some dummy hidden states that is called A, typically denoted A or H. It's called the hidden state, activation, or even sometimes a context vector. And you have some kind of a module that takes into account the hidden state so far
and the word at time step t, so here time step 1. So here what it does is it takes in the meaning of the sentence so far and takes into consideration the word that is happening now. And it produces an output vector that here can be used to try to predict the next word. So for instance here we have this hidden state and the representation of the word that then you have some matrix multiplications in this blue box. And you have an output vector that you try to train on predicting the next words.
And then you keep on doing that by keeping track of these hidden states. And so you repeat the process. And I guess the way you would interpret these hidden states is it's a representation of the sequence process so far. So the good thing with RNNs is now the word order matters. And you're also able to encode the sentence in a more natural way.
So let's see roughly how it works. So we have the same favorite example, so cute teddy bear is reading. So you would have the token A. You want one-hot encoding vector. You pass it through your network. You compute the hidden state. You try to predict cute. But then you keep track of the hidden state. And then you input that into another module. And then you also consider the next words. So you consider not only the word itself, but also the hidden state of this sentence so far.
And you try to predict the next word again, and again and again. So this is RNN. So RNNs were used for a bunch of tasks, and just like mapping that back to the categories that we saw before. For classification purposes, you can basically use the hidden state of the last word in your sentence. For instance, if you want to predict like the sentiment of a review, you would take basically the last vector here and try to project it into the space of the predictions or the labels that you want to predict on. So for instance, if you want positive or negative,
you basically project that vector onto that space. You can do that here. For multi-classification, so you would basically have the representation of the token of interest, and you would project that. Or for generation, you would basically process the whole source text, and then have a context vector, a.k.a. activation vector, a.k.a. hidden state at the end of your processing, which will then be used to decode the output prediction. So this is how you would use an RNN for each of these tasks.

Ask anything
We've read this whole study set, so questions about it get the best answers.