Com funciona GPT: embeddings, atenció i transformers
Una explicació visual de GPT: tokenització, embeddings, autoatenció, múltiples caps, normalització, connexions residuals i entrenament.
GPT sembla una tecnologia gairebé màgica quan genera text, però la seva operació bàsica es pot descompondre en peces entenedores. El vídeo de Caleb Writes Code construeix un transformer petit a partir d’una analogia visual: un tauler de Galton que deixa caure boles i ha de decidir quin serà el token següent. A mesura que s’hi afegeixen embeddings, atenció, capes de processament i connexions residuals, el mecanisme aleatori es converteix en l’esquelet d’un model autoregressiu.
És una explicació conceptual, no una recepta per reproduir els grans models comercials. L’arquitectura només defineix el circuit; la qualitat final depèn de les dades, l’entrenament, la mida, l’optimització i moltes decisions posteriors.
1. Predir el token següent, una vegada i una altra
El punt de partida és el tauler de Galton de 00:41. En un tauler físic, moltes boles cauen cap al centre i formen una distribució previsible. Si cada posició inferior representés un caràcter, però, la seqüència resultant seria soroll: la probabilitat dependria del tauler i no del text anterior.
GPT substitueix aquest mecanisme per una xarxa que calcula una distribució de probabilitat sobre el vocabulari. Rep els tokens que ja hi ha, assigna una probabilitat als possibles continuadors, en tria un i repeteix el procés. “Generatiu” descriu aquesta producció; “preentrenat” indica que abans ha après patrons a partir de moltes dades, i “transformer” identifica l’arquitectura.
A 01:43, el vídeo divideix un text de mostra en lots i blocs. El lot permet entrenar diverses seqüències en paral·lel; el bloc és la longitud de context utilitzada en cada exemple. En un model real, els tokens acostumen a ser fragments de paraula, no necessàriament lletres ASCII.
2. D’un identificador a un vector amb significat
Un token entra al model com un número, però el número només és una etiqueta. Per això, a 03:16, apareix la taula d’embeddings. Cada identificador selecciona un vector amb moltes dimensions que l’entrenament pot ajustar.
Aquest espai dona al model lloc per codificar regularitats útils: contextos en què apareix un símbol, semblances amb altres tokens o patrons gramaticals. El vídeo utilitza vectors de 32 dimensions i un vocabulari de 128 caràcters per mantenir visible la forma de les matrius. Els sistemes moderns fan servir vocabularis i amplades molt més grans.
L’embedding no conté una definició humana escrita a mà. Comença amb valors inicials i es modifica quan l’optimitzador redueix l’error de predicció. El significat és distribuït: no hi ha una dimensió única que digui “això és un verb”, sinó una combinació de valors útil per al càlcul.
3. L’atenció connecta els tokens
Els embeddings representen cada token, però encara falta relacionar-los. A 04:38, el vídeo introdueix l’autoatenció, el mecanisme central del treball Attention Is All You Need, publicat el 2017.
Cada posició genera tres vectors: consulta (query o Q), clau (key o K) i valor (value o V). La consulta expressa què busca una posició; la clau, com pot ser trobada; i el valor, quina informació ofereix. Multiplicar Q per la transposada de K produeix puntuacions de compatibilitat entre parelles de tokens.
A 06:23, aquestes puntuacions s’escalen per evitar valors massa extrems i passen per una funció softmax. Com que GPT és causal, s’aplica una màscara que impedeix mirar tokens futurs: en predir la cinquena posició, només pot consultar les quatre anteriors. Les probabilitats resultants ponderen V i creen una representació contextual.
La clau és que el vector d’un token ja no depèn només de la seva identitat. Canvia segons els elements que l’envolten. Així, la mateixa paraula pot activar relacions diferents en dues frases.
4. Ordre i múltiples caps d’atenció
L’atenció, per si sola, no sap en quin ordre han arribat els elements. A 09:52, el model suma a cada token un vector posicional. D’aquesta manera pot distingir seqüències formades per les mateixes paraules però ordenades de manera diferent.
Després arriba l’atenció multicap a 10:43. En lloc d’una única projecció Q, K i V, diverses projeccions treballen en paral·lel sobre subespais diferents. La intuïció del vídeo és que un cap pot aprendre relacions pròximes, un altre dependències llargues i un altre patrons sintàctics. No se’ls assigna aquesta feina manualment; les especialitzacions emergeixen durant l’entrenament.
Els resultats de cada cap es concatenen i es tornen a projectar. Aquesta divisió permet que una capa consideri simultàniament diferents tipus de relació.
5. Xarxa feed-forward, normalització i residus
A 12:35, cada posició passa per una xarxa feed-forward. L’atenció barreja informació entre tokens; aquesta xarxa transforma la representació de cada posició amb més capacitat no lineal.
La normalització de capa, explicada a 13:21, manté les activacions en escales manejables quan s’apilen molts blocs. Les connexions residuals de 14:10 ofereixen un camí directe: una capa aprèn una modificació que se suma a l’entrada, en comptes d’haver de reconstruir tota la representació. Això facilita que el gradient travessi xarxes profundes.
Un bloc agrupa atenció i xarxa feed-forward, amb normalització i connexions residuals. Repetir-lo moltes vegades augmenta la profunditat. Finalment, una projecció cap al vocabulari i un softmax produeixen la probabilitat del token següent.
Projectes educatius com nanoGPT mostren aquesta estructura en codi relativament compacte. Tot i així, entendre les peces no elimina la dificultat d’entrenar-les a gran escala.
6. L’arquitectura no és encara el model
A 15:02, el vídeo remarca que el circuit acabat encara no sap escriure. Cal presentar-li grans quantitats de tokens, mesurar la diferència entre la predicció i el resultat real, i ajustar els paràmetres mitjançant descens de gradient i un optimitzador.
Els laboratoris també modifiquen tokenització, posicions, atenció, memòria, experts, dades i mètodes d’alineament. Molts productes anomenats LLM comparteixen la família transformer, però no són còpies idèntiques del GPT didàctic. L’eficiència del maquinari i les necessitats de l’aplicació condicionen totes aquestes variants.
Conclusions
GPT es pot entendre com una cadena de transformacions: tokens convertits en vectors, informació d’ordre, autoatenció causal, xarxes feed-forward, normalització, connexions residuals i una projecció final que prediu el següent element.
La gran aportació del vídeo és fer visibles les formes i les funcions de cada peça. La màgia aparent no desapareix, però canvia de lloc: no és en una operació secreta, sinó en l’escala de les dades, el còmput i els ajustos que fan que aquest esquema aprengui patrons útils. Conèixer l’esquelet ajuda a valorar millor tant les capacitats com els límits dels models actuals.
Contrast i context
Fonts consultades
-
01
Caleb Writes Code It's about time we learn Transformers..
- 02
-
03
Andrej Karpathy a GitHub nanoGPT
Font de treball
Transcripció amb marques de temps
Consulta la transcripció
-
0:00
, obre el vídeo en una pestanya nova
Given how fast LLMs are advancing these days, we should really pause to understand how GPT actually works. GPT is what powers LLMs and front-ear labs like OpenAI and Thropic and even Chinese labs like DeepSeek and Minimax all use GPT but tuned in their own way. And the reason why these labs tuned their own version of GPT is when we look at the application layer here. There's a downward pressure since a gented application at this layer want faster token generation, they want longer contact spindle, better to calling and more intelligent models. So everything comes down to GPD. What is this generative pre-chain transformer and how does it actually work under the hood? Let's start with a Gothenboard as an analogy. I'm sure by now, we've all seen this demonstrated before, what initially seemed like it should be random actually starts to show a predictable pattern like this, where you have a higher concentration in the middle. Now, imagine we label the bottom row with the entire American alphabet, including numbers and special characters.
-
1:03
, obre el vídeo en una pestanya nova
And we use this board to start generating sentence left to right, where each ball that drops determine what the next token is. In this case, the sentence will likely sound very gibberish, mostly consisting of letters that happen to be in the middle of the board. Not very great. So how do we tweak this inner mechanics so that I can actually construct a sentence that sounds plausible? What if we swap out the inner mechanics and just insert GPT instead? This way, every ball that drops goes through GPT and we simply let GPT to decide what the next token should be given the current token. The first thing we need to do is to get a bunch of data to train the model. Let's use the script that I'm reading right now for this video to train our GPT to sound like me. We need to first chunk our dataset to feed into the model in pieces instead of dropping the entire dataset. all at once. Since we have to assume that this data is going to be huge, maybe in our example, we can just start by setting four batches that train all in parallel. And within each batch it has eight blocks of tokens. So we're sampling essentially 32 tokens total from the training data and we further split them in four ways to train them in parallel. Okay, let's keep going.
-
2:24
, obre el vídeo en una pestanya nova
Now that we chunked our dataset to start feeding into the model, what we need to do is create what's called a token embedding. Now, you might be wondering why we need token embedding in the first place. Since we have the entire character set labeled at the bottom, these labels help us know what the token actually is. But the token itself actually doesn't mean anything. In other words, the character A all the way to the left here just means position one, be in position 2 and so on. So these IDs don't actually help us understand the nuance behind the token, like whether the letter A tends to appear after space or maybe it tends to repeat itself after or maybe the punctuation tends to appear before them. All these are important nuances to learn from and having just the idea itself doesn't have enough room to store this kind of information. So maybe instead of having just the idea to label the tokens, we can just simply give more room to represent its internal meaning. And this breathing room that we just created for...
-
3:27
, obre el vídeo en una pestanya nova
each token that we created here is why we need token embedding in the first place. So in our example, we're going to give 32 dimensions for each token to now start storing its internal representation here beyond just the ID. Pretty cool. So let's do a quick check on what we have so far. There are 128 different possibilities of labels assuming that we're using the ASCII set. And under each token here, we give 32 dimensions to store its internal representations per token. So we have a vector size of 128 by 32 token embedding table. Now that we just created the plumbing to allow token representation, we have to now look at the data that's coming in. We earlier split our data in four batches. each containing eight blocks of tokens, which means the tokens that are contained in our batch can now sample from the token embedding that we just created. This means that each batch will have eight by 32 vectors, sample directly from the embedding table. And the 32 is a depth that we just added earlier to give the token the ability to represent its internal representation. And now that we have that, we're still missing something critical here, which is attention. But why?
-
4:40
, obre el vídeo en una pestanya nova
Before we even try to understand what attention even is, why do we need attention in the first place? What we just built here is just token representation, but not necessarily how each token within the blocks actually communicate with each other. In other words, we need to actually start capturing how these tokens communicate to each other within the blocks themselves. And this is stored outside of the token embedding table called attention. And I'm sure by now you've heard of the term attention mentioned all the time. And also the highly acclaimed paper attention is all you need from 2017 by Google. Here's how the basic attention mechanism actually works. Since our goal is to find out how the tokens actually communicate with each other, just like how earlier we created the breathing room for token internal representation, we need to also create one for attention as well. But this time, we're creating three different tables instead of one. Now, you might be wondering why exactly three?
-
5:38
, obre el vídeo en una pestanya nova
Having just one table just like earlier won't have enough breathing room for attention to take place because having attention to something means you have to start by separating the act of looking and the act of being looked at. So we have to have one vector that does the searching called Q, another vector that does the labeling called K, and finally another vector that contains a value itself called V. Now this might sound very uninteruitive at first because it seems like we're just making up random vectors and hoping that attention will happen somehow. But once you look at how the actual math is done, it might help you to actually see how each three components here play into its own role when it comes to attention. But feel free to skip this math part, but I promise you, it's not that difficult. We start by creating the same or smaller vector as a sequence of blocks. Now that we have three randomly generated values of vectors q, k, and v, we can actually start calculating the attention score. And the attention score helps us find the strength of relevance within the sequence. So since our sequence is
-
6:42
, obre el vídeo en una pestanya nova
8 tokens long, we need to have at the end 8x8 table where each intersection tells us the strength of its token relevance. We can get there by multiplying the Q vector and the K vector by transposed, then we can have the 8x8 vector and the result showing us the attention score of them. And since this multiplication might end up exploding in values in large numbers, we scale the output by the square root of the head size, which in our case is 32, so roughly 5.66. Now that we have the scale product of the attention score, we can actually convert these numerical values into a percentage to find the probability distribution after setting the future tokens to negative infinity since we're using the coder-only transformer, which means we can't see. future tokens. So all this works well far helps us find the strength of the communication of tokens, which means now we need to find out the value of the actual information each token should receive by multiplying the attention probabilities with the V vectors. This is why we need three different vectors Q, K and V and the entire operation that we just did can be summarized by this magical equation that changed the course of history when it comes to scaling LLMs that we have today. Pretty cool, right?
-
7:59
, obre el vídeo en una pestanya nova
So let's do a quick mental review here and look at what we built so far. We started by labeling the bottom of the board with the alphabet, then we allowed them to have more breeding room to store internal representation by using what's called token embedding table. And then we added the attention mechanism to capture the relational side of how each token communicates by creating three new vectors QK and V to calculate the attention score to find out the weighted information. Perfect. What more could we need? Turns out, in order to call what we just built a GVT model, we actually need a few more components in place because what we have here isn't really good enough. But what could be missing here seems like we already have enough to actually start training the model with our data. But first, thanks to Outskill for sponsoring this video. And Thropic launched Fable 5 recently, and the US government quickly restricted foreign access because of how capable of these frontier models are becoming. And whether you're using Cloud, Chachipiti, cursor, or Cloud Code, one clear thing is that these models are getting more and more powerful. And most people still use them like a search engine, while power users are using them to build, automate, and ship faster than ever.
-
9:07
, obre el vídeo en una pestanya nova
So if you want to learn how to actually maximize these tools, you can check out the Cloud AI Mastery workshop from Outskill, which is a full deep dive into Cloud and its use cases. The workshop is happening this weekend from 10 a.m. to 70 a.m. Eastern Time, and you'll be joining a community of millions of learners with the 4.9 rating on Trust Pilot. In today's, you won't just learn Cloud conceptually, you build your own artifacts and dashboards, create full presentations, and get hands-on experience on Cloud Code. Including how to work with real projects, GitHub, Repos and Developer Work. flows. Outskill is also including three free bonuses, an AI prompt library, 50 Cloud Code Prompts, and a personalized AI tool called Builder. So if you want to get better at using Cloud Beyond Basic Prompting, you can sign up and join the WhatsApp community before Seats Close. Link in the description below. Turns out what we built so far is good, but the model is incapable of knowing the order of tokens that are coming in. In other words, we have the internal representations that carry deeper meaning of the token, and we also have the attention mechanism to learn how each tokens communicate with each other, but there's no inherent mechanism to store the positional order of the sequence itself. For example, we know that the phrase, love your job.
-
10:18
, obre el vídeo en una pestanya nova
carries a vastly different meaning than job your love. So we also need to give breathing room for the model to also learn the positional embedding of the sequence as well. So we need to go ahead and create a vector that represent the position of each token in the sequence and added directly on top of the token embedding we sample from. This way the combined vectors of them mixes in the token embedding as well as the positional embedding. Now, there's actually a bit more groundwork we need to do when we zoom into the attention portion of the architecture. The attention mechanism we just built earlier has three separate vectors Q, K, and V. And in our example, the size of these were the same size as a sequence embedding. Turns out there's a huge benefit in actually segmenting the attention mechanism to essentially divide and conquer this. And you're gonna love this because now we have not just one Q, K, and V vectors. But we have multiple Q, multiple K, and multiple V vectors that each are responsible for a section of the sequence. I know so many acronyms to keep track of now. And you're probably wondering...
-
11:22
, obre el vídeo en una pestanya nova
why on earth are we making this more complicated than it actually is? This kind of segmentation is called multi-headed tension. And it turns out splitting the model this way results in the model actually looking at the same sequence with multiple perspectives in mind. So if you have four attention heads that split up, for example, one might look at how each token communicate in terms of grammar, the other might look at the short range relationships, another one looks at long-range relationships and so on. In the original GPT paper, uses this specialization rather than a generalization method for attention and uses the multi-head attention instead. Now let's zoom back away from attention and look at the GPT architecture we built so far. Not bad, we have the token embedding, positional embedding, and a solid attention mechanism. What more do we want? Comparing our architecture with the paper, we actually are missing three components. First, feed forward network, second, layer normalization and third residual network. Gosh, I know so many things to keep track of, but the individual components aren't that difficult to learn as you saw so far. It's just keeping track of all these components to actually unite them into what's called GPT that takes a lot of mental work. Let's start with this blue box called feed for our network. Why does it even need this thing in the first place? Even though we just implemented our multi-head attention to keep track of how...
-
12:45
, obre el vídeo en una pestanya nova
tokens communicate with each other, we haven't really given them enough room to actually think about them. Similar to earlier, when we added token embedding to give more breathing room at the token level, we have to add breathing room at the attention level as well. And the simple feed forward neural network gives this exact breathing room for the model to use this and learn a much deeper level information. And that's why we need to have this blue box at the end called feed forward network after attention. We also have this term in the yellow box called layer normalization. Same interrogative question here. Why do we need this exactly? Whenever we stack operations like attention and feed-forward networks one after another, the actual numerical representation can start to get out of hand really fast. So in order to reduce this crazy fluctuations in values that might exist in the output, we normalize the values to a much more manageable range. Sweet, now that we have almost everything covered now, the only thing we have left to do is just make the model longer by elongating these blocks. A block might contain an attention layer, followed by a feed for a layer. So essentially, you can repeat these blocks multiple times, chain together, to add more depths to the model for deeper understanding of itself, until you get to the final layer where you project your output to the token embedding, and then they're used to predict the next token represented in our board that are used earlier.
-
14:09
, obre el vídeo en una pestanya nova
There's one last piece here in terms of architecture that's quite easy to miss, which is the very arrow that you're seeing here in the architecture. This arrow allows the input to be bypassed from the normal path and just skips the step entirely and added back on later. This is called residual connection. Because we're elongating the model longer and longer, it has the tendency to get very unstable since every change that we make at each block essentially gets amplified as it passes through all the layers. And this residual connection allows a mechanism where you're essentially teaching the model to apply the modification on top of the input itself rather than modifying the input itself. And this prevents the output from being distorted by the time it reaches the end. This entire thing that we just built is now finally called GPT. And now we can go back to the Gauton Board and replace an interim mechanism and insert GPT instead. And all we have to do is train GPT architecture with our data. In other words, just because we now added the plumbing that resembles GPT, it doesn't mean that it will do the job that it's meant to do. We have to actually put in the work to pass billions and trillions of tokens of data
-
15:24
, obre el vídeo en una pestanya nova
into the model to actually have the model behave like our data set. And there's a huge rabbit hole in the training methods here as well. As we get into different techniques like stochastic gradient descent and optimizers that all play an important role in shaping a better GPT model. And it's this exact GPD architecture that we just built is where many labs optimize essentially every component of the architecture itself, including the training methods. And each lab might choose to optimize different portions of this architecture at the model layer to meet what they think is important demand to listen to at the application layer as they continue to work on with different constraints that might exist at other layers like infrastructure and chip layer. And the decision that we make at the model layer here not only affects the agent layer in terms of context we know speed and intelligence, but also what hardware is needed to get interactivity and throughput at the lower layers.