Building an LLM From Scratch: The Mechanism That Changed AI Forever, Implemented From Zero
From the publisher’s feed, collected in the ZeroLabs newsroom.
AttentionAfter training the embeddings in the previous part, now comes the most important part of LLMs that shifted how the entire field thinks about sequence modeling.Self Attention (What and Why)Building this from character level tokenization all the way to self attention has taught me much in depth about the mathematics used in LLMs, particularly calculus and linear algebra.Basic idea of self attention was that to make the computer know which word is relevant to which word. Let’s take the most common example:“River bank flows” and “Money bank grows”. In these two, bank is the common word but very different meaning.So, if a traditional prediction method is used. it would basically never be able to distinguish between these 2 words. So what was done was surprisingly simple in hindsight.We check each word’s dependency to the preceding words (not only the single previous word like this example but sequence of words like previous 16 words), and see how is the target word relevant to the preceding words and what’s the most relevant word to it. And since machines don’t understand language, we represent all of this as numbers.How Self Attention worksSo, coming to the most important part, how to implement it and make the machines understand the relevance of words with each other.Since we know that words are represented in the form of embeddings, it becomes easier for processing. So, instead of representing the words as their own embeddings we can represent as each word’s relevance with other words, for example:Instead of“River = Embeddings of river” and “Bank = Embeddings of bank”We can represent like:“River = 0.8(River)E + 0.2(Bank)E” and “Bank = 0.4(River)E + 0.6(Bank)E”.This shows how each word is relevant to each other where 0.8 and 0.2 are the attention weights showing how much each word contributes to the final representation.Now the question comes how to make the word embedding like these.As we know that to find the relevance or similarity between 2 embeddings best way is to do dot product between 2 embeddings.So the formula becomes like:(River)E = (river . (river)T)River + (river . (bank)T)Bank &(Bank)E = (bank . (river)T)River + (bank . (bank)T)Bank(Here T is transpose of the matrix)To normalize these weights so that we can see in the scale of 0 to 1 as how each embedding is contributing to the other embedding, we pass these to the SoftMax function.A simple diagram for intuition.If we see this diagram, we can see that a single word plays 3 different role.Let’s take a word money, we take the dot product of the embeddings of money with all the other words, where money is the QUERY and the other words play the role of KEYS. Here QUERY vector asks the KEY vector for how relevant the are to each other. We pass these scores through SoftMax to get the attention weights, then multiply them with the VALUE vectors to get the final representation. Here, we are finding the final VALUE of the embedding so it’s named as VALUENow we can categorize each words into three vectors QUERY- Q, KEY- K and VALUE- V, this also introduced learnable parameters: W_Q, W_K and W_V which the model trains through forward and backward propagation.Summarizing all this mathematics into one formula we get is:Attention(Q, K, V) = SoftMax(QKᵀ)VBut wait that’s not the correct formula according to that Attention is All You Need. But in the actual paper, it something like:The difference is the division of root of the dimensions of the embeddings, let’s understand why.Significance of √dₖSoftMax is best function to convert group of numbers into percentages, but it has one drawback.While applying SoftMax, we have to make sure that the variance of the numbers is the lowest to get the best and optimal result.If the variance is too high or even high, the problem of vanishing gradients arises as the large scores saturate toward 1 where as while smaller scores collapse toward 0.So, before adding SoftMax function to the product of embeddings we need to scale them first.We know that as the dimensions of embeddings increases, the variance between them increases too. So, we need to scale them, but why only √dₖ?This question arises.There is a simple mathematics rule about variance.In our case, the dot product of Q and K scales the variance by d_k. So dividing by √d_k brings it back to 1 and keeps the softmax inputs in a stable range.GeneratedCode ImplementationStarting with the code implementation, we start with Forward propagation first where the model computes all the dot products without knowing the actual answer.Forward Passdef forward(contextToken): X = input_embeddings[contextToken]# each word is now projected into 3 diff vectors i.e. Query, Key, Value. Q = X @ W_Q # (8, 32) @ (32, 32) = (8, 32) (Query vector) K = X @ W_K # " (Key vector) V = X @ W_V # " (Value vector) scores = Q @ K.T / np.sqrt(d_k) # K.T is just the transpose of K (8, 32)@(32, 8) = (8,8) mask = np.triu(np.ones_like(scores), k=1) scores = np.where(mask, -1e9, scores) # this is used to mask the scores of the words that are not in the context.# it makes the matrix of perfect size of no of context tokens x no of context tokens and Cell [i, j] = dot product of Q_i and K_j = "how relevant is word_j to word_i?" attn_w = softmax(scores) # (8,8) context = attn_w @ V # Value of each words to the embeddings i.e. [8,8] @ [8,32] = [8,32] last_context = context[-1] # we need only the last context from the context vector to predict the next word (32,) logits = last_context @ W_O # logits are basically the product of context representaton against each word's learned output weight vector (32,) @ (32, vocab size) = (vocab size,) probs = softmax_vectors(logits) # it gives most probable next word. cache = dict(X = X, Q = Q, K = K, V = V, scores = scores, attn_w = attn_w, context = context, last_context = last_context, logits = logits, probs = probs) return probs, cacheHere we applied causal masking so that the model only sees the words before the current position, not the ones after it. Without this, word 1 could attend to word 8 which hasn’t been generated yet. That would be cheating.The scores matrix is an 8x8 grid where cell [i, j] answers the question: how relevant is word j to word i? We divide by √d_k before SoftMax to keep the variance stable, as explained above.The cache stores every intermediate value from the forward pass. We need all of them during backpropagation to compute the gradients.Backpropagationdef backward(cache, target_idx, lr, ctx_tokens): global W_Q, W_K, W_V, W_O probs = cache['probs'] logits = cache['logits'] last_context = cache['last_context'] context = cache['context'] attn_w = cache['attn_w'] scores = cache['scores'] V = cache['V'] K = cache['K'] Q = cache['Q'] X = cache['X']# Starting from right to left as backpropogation is just the opposite of forward pass d_logits = probs.copy() # d_logits is just the derivative of logits w.r.t. target_index which basically how wrong the predicted vector is d_logits[target_idx] -= 1.0 last_ctx = context[-1] dW_O = np.outer(last_ctx, d_logits) d_last_ctx = W_O @ d_logits d_context = np.zeros_like(context) d_context[-1] = d_last_ctx d_attn_w = d_context @ V.T d_V = attn_w.T @ d_context d_scores = np.zeros_like(attn_w) for i in range(seq_len): a = attn_w[i] jac = np.diag(a) - np.outer(a,a) d_scores[i] = jac @ d_attn_w[i] d_scores /= np.sqrt(d_k) d_Q = d_scores @ K d_K = d_scores.T @ Q dW_Q = X.T @ d_Q dW_K = X.T @ d_K dW_V = X.T @ d_V d_X = d_Q @ W_Q.T + d_K @ W_K.T + d_V @ W_V.T W_Q -= lr * dW_Q W_K -= lr * dW_K W_V -= lr * dW_V W_O -= lr * dW_O # train embeddings too global input_embeddings for j, tok_idx in enumerate(ctx_tokens): input_embeddings[int(tok_idx)] -= lr * d_X[j] # here we convert the token index to int because it is a numpy array and we need to subtract the gradient from the embedding matrix.Backpropagation here follows one simple rule. For any operation Y = A @ B, the gradient flows as dA = dY @ B.T and dB = A.T @ dY. We apply this rule in reverse order through every step of the forward pass.The hardest part is the SoftMax gradient. SoftMax is not a simple element-wise function so its gradient is a full Jacobian matrix.Softmax takes a vector and outputs a vector, so its gradient is a matrix showing how every output changes when every input changes. This matrix is called the Jacobian. For softmax it works out to diag(a) - outer(a, a), where a is the attention weight vector for that row.Everything else is just matrix multiplication rules applied in reverse.One important detail: we compute the embedding gradient before updating W_Q, W_K, W_V. If you update the weights first and then compute the gradient, you are using the wrong weights. The gradient must use the same weights that were active during the forward pass.# Training loopEpochs = 15try: for epoch in range(Epochs): random.shuffle(sequences) total_loss = 0.0 for i, (context, target_idx) in enumerate(sequences): lr = 0.01 / (1 + 0.0001 * i) probs, cache = forward(context) loss = -np.log(probs[target_idx] + 1e-10) total_loss += loss backward(cache, target_idx, lr, context) if i % 20_000 == 0: print(f"Epoch {epoch+1} | step {i:>6}/{len(sequences)} | " f"loss {total_loss / (i + 1):.4f}") avg_loss = total_loss / len(sequences) print(f"Epoch {epoch+1} complete. Avg loss: {avg_loss:.4f}")except KeyboardInterrupt: print("\nTraining interrupted — saving weights...")finally: np.save("W_Q.npy", W_Q) np.save("W_K.npy", W_K) np.save("W_V.npy", W_V) np.save("W_O.npy", W_O) print("Weights saved.")def predict_next(words_in, top_k=5): ctx = [word_to_idx[w] for w in words_in if w in word_to_idx] ctx = ctx[-seq_len:] # take last SEQ_LEN tokens if len(ctx) ctx = [0] * (seq_len - len(ctx)) + ctx # pad with index 0 probs, _ = forward(ctx) top_indices = np.argsort(probs)[::-1][:top_k] print(f"\nContext : {words_in}") print(f"Top-{top_k} predictions:") for idx in top_indices: print(f" '{idx_to_word[idx]}' p={probs[idx]:.4f}")We also train the embeddings here, not just the attention weights. Every token in the context window gets its embedding nudged based on how much it contributed to the wrong prediction.Outputs After TrainingAfter 15 epochs on 969,000 sequences the loss dropped from 7.6 to 5.4. To put that in perspective, random guessing on a 24,000 word vocabulary gives a loss of around 10.1. The model is roughly 100x better than random chance.To test what the model actually learned, I ran random next-word prediction tests across the corpus.TerminalThe hit rate varies between 1 and 5 out of 10 depending on the batch. The misses are mostly unpredictable words like ‘jealousy’ or ‘pestle’ that even a human would struggle to guess from 8 words of context. The hits show the model has learned grammatical structure.TerminalTo understand what attention is actually doing internally, I built a visualization that tracks how much each word’s embedding changes during gradient updates for a specific prediction.Each gradient step means one full forward pass followed by one backpropagation update across all embeddings in the context window.The context given was ‘above all don’t lie to yourself the man’ with the target word being ‘who’.The L2 drift column shows how much each word’s embedding vector moved during 50 gradient steps. The results are striking:“‘man’ drifted 0.508 — by far the largest update”“‘yourself’ drifted 0.021”“‘lie’ drifted 0.021”“‘above’, ‘to’, ‘the’ drifted essentially zero”The cosine similarity of ‘man’ dropped to 0.9925 meaning its direction in embedding space actually shifted, while every other word stayed at 1.0000 meaning they barely moved at all.This confirms that attention is working exactly as needed and all the steps of forward pass, backpropagation, updates, etc are working properly.The model cannot yet predict with high accuracy because the transformer block is incomplete. It is currently missing positional encoding, residual connections, a feed-forward layer, and multi-head attention. These are not optional extras, they are what makes a transformer a transformer.GeneratedIn the next part I will revisit some earlier decisions like embedding dimensions and sequence length, and build the complete transformer block.Part 4 is next. Positional encoding, residual connections, feed forward layer, and multi head attention. That is the full transformer block.If this was useful, follow along. Every part has working code, honest documentation of what broke, and no shortcuts.GithubLinkedinBuilding an LLM From Scratch: The Mechanism That Changed AI Forever, Implemented From Zero was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.