Fine-Tuning LLMs, Part 1: The Transformer Architecture Guide Nobody Wrote for Fine-Tuners
From the publisher’s feed, collected in the ZeroLabs newsroom.
A complete architectural guide for ML practitioners who need to understand what they are modifying before they modify it.Generated using notebookLMMost engineers who fine-tune language models treat the model as a black box with knobs. They set a rank, pick some target modules from a blog post, run the job, and hope the loss curve looks right. That works, until it doesn’t. Until the model learns nothing despite a clean loss curve, or collapses on day two of training, or generalizes perfectly on eval and fails completely in production. At that point, the knobs stop being enough. What is needed is a precise understanding of what each component inside the model is doing and why modifying it changes behavior in the specific way it does. This series builds that understanding, from the ground up, with every concept connected directly to a parameter in Unsloth. By the end of this first episode, the transformer is no longer a black box. It is a readable, navigable structure where every decision has a derivable reason.Table of ContentsIntroductionChapter 1: How a Transformer Stores KnowledgeChapter 2: How a Transformer Routes InformationChapter 3: How a Transformer Stays StableChapter 4: How a Transformer Knows Where It IsChapter 5: How a Transformer Scales EfficientlyChapter 6: Putting It All TogetherChapter 1: How a Transformer Stores KnowledgeEmbeddings, Weight Matrices, and FFN MemoryBefore a transformer can route information between tokens, attend to context, or generate a single output, it has to store things. Parameters have to mean something. Representations have to live somewhere. This chapter is about that somewhere. The routing, the attention, the stability mechanisms come later. This chapter builds the floor everything else stands on.1.1 Token Embeddings: The Coordinate SystemText enters a transformer as integers. The tokenizer converts a string into a sequence of token IDs, each corresponding to a position in a vocabulary. The vocabulary is built during pre-training using subword algorithms such as Byte-Pair Encoding [BPE] or SentencePiece, which iteratively merge frequent character sequences into subword units until a target vocabulary size is reached. Modern open-weight models operate with vocabularies typically between 32,000 and 152,000 tokens. Mistral 7B sits at the lower end with 32,000, while Llama 3 uses 128,256 and Qwen3 uses 151,936.The embedding layer converts those IDs into dense floating-point vectors. Structurally it is a lookup table with shape [vocab_size, hidden_dim]. Token 4,712 maps to row 4,712 of that table. The resulting vector is a learned coordinate in a high-dimensional semantic space, and it is the only input the rest of the network ever sees. Every layer that follows builds on these initial coordinates.The practical consequence of this for fine-tuning is easy to underestimate. A tokenizer is fixed before a fine-tuning run begins. If the base model’s vocabulary handles the target domain well, the initial embedding coordinates will already be semantically coherent, and fine-tuning can do its job cleanly. If the tokenizer handles domain vocabulary poorly, for example fragmenting a specialized term into five nonsensical subword pieces where a better tokenizer would assign a single token, the model faces a fundamentally harder learning problem. The representations start incoherent, and no amount of fine-tuning recovers the signal that was lost at tokenization. The decision about which base model to use is partly a decision about which tokenizer to accept.This is why, by default, Unsloth and most LoRA implementations exclude the embedding layer from target_modules. The embedding layer is the semantic foundation every subsequent layer depends on. Disrupting it with aggressive gradient updates risks destabilizing the representational basis of the entire model. When domain vocabulary extension is genuinely necessary, new token embeddings should be initialized and fine-tuned while the rest of the embedding table remains frozen, or the entire layer should be updated at a substantially lower learning rate to maintain stability.1.2 Weight Matrix Anatomy: Reading Model Files Like a MapGenerated using notebookLMOnce the model is loaded, its parameters exist as a collection of named tensors. A Llama or Qwen model exposes names like model.layers.0.self_attn.q_proj.weight and model.layers.11.mlp.gate_proj.weight. Reading these names precisely is not a matter of style. It is how every subsequent decision in fine-tuning gets made.The naming convention is a path through the model’s structure. model.layers.0 identifies the first transformer block. self_attn specifies the self-attention sub-layer within that block. q_proj identifies which projection matrix inside attention is being referenced. .weight distinguishes the weight tensor from a bias term.The shapes of these tensors carry equally important information. A q_proj.weight tensor with shape [4096, 4096] means that projection maps a 4096-dimensional input to a 4096-dimensional query space. In a model using Grouped Query Attention, the k_proj.weight tensor will have a smaller first dimension, reflecting that fewer key heads exist per layer. This is not a formatting detail. When configuring target_modules in Unsloth, incorrectly assigning the same rank to matrices of vastly different sizes can produce adapters that are either underpowered or wasteful. Knowing the shapes informs the rank choice.Merging LoRA adapters also becomes concrete once the underlying tensor structure is understood. LoRA trains two small matrices, A and B, alongside the frozen base weight W. The update is computed as the product AB, which has the same shape as W, and is added directly into the named weight tensor at merge time. The base model file changes. The tensor at model.layers.0.self_attn.q_proj.weight now contains W plus the learned AB contribution. Nothing about this is mysterious once the structure is visible.1.3 FFN Layers: The Model’s Long-Term MemoryFeed-forward network [FFN] layers constitute approximately two-thirds of a transformer’s total parameter count. That ratio alone suggests they are not secondary infrastructure. They are the model’s primary storage medium.Geva, Schuster, Berant, and Levy (EMNLP 2021, pages 5484–5495) provided the most useful interpretive framework for this storage. FFN layers operate as key-value memories, where each key correlates with textual patterns in the training data, and each value induces a distribution over the output vocabulary. The first weight matrix in the FFN acts as a pattern detector. When an input token activates a pattern, a memory coefficient fires. The second weight matrix holds the corresponding value, a distribution over tokens likely to appear after that pattern. Lower layers tend to capture shallow textual patterns such as n-grams, while upper layers capture semantic patterns indicated by variations in textual forms pointing to the same underlying concept.This framework has a direct implication for fine-tuning strategy that most practitioners ignore. Attention layers control which tokens influence which other tokens. FFN layers store what the model knows about the world. If a fine-tuning task requires the model to learn a new behavioral pattern, a classification structure, a response format, a reasoning style, attention projections are the primary lever. If the task requires injecting new factual associations that were absent from pre-training, FFN layers are where that knowledge needs to be written. Targeting all modules, both attention and FFN, is the safe default in Unsloth because it updates both the routing logic and the knowledge store simultaneously. The distinction matters most when debugging a model that learned the wrong thing.Modern LLMs including Llama, Qwen, and Mistral do not use a simple two-layer FFN. They use the SwiGLU activation function, which introduces a gating mechanism into the feed-forward computation. Instead of one transformation path, the input token representation is split across two parallel linear projections. One produces a transformed representation of the token in a higher-dimensional space. The other produces a learned gate, a set of values that determines how much of the first representation passes forward. The two are multiplied element-wise and then projected back to the model’s hidden dimension.This gating mechanism requires three distinct weight matrices instead of two. gate_proj generates the gate signal. up_proj produces the data representation. down_proj projects the combined gated output back into the residual stream. To maintain parameter count parity with a standard two-layer FFN, architectures using SwiGLU expand the intermediate dimension to approximately two-thirds of what a ReLU-based FFN would use for the same hidden size. In Unsloth, the target_modules list for a full-coverage configuration includes all three. Omitting any of them leaves the FFN's adaptation incomplete. up_proj is the primary factual storage matrix, gate_proj controls what gets retrieved, and down_proj integrates the result into the residual stream. Modifying two of three without the third is like editing a database record without updating its index.Chapter 2: How a Transformer Routes InformationAttention, Multi-Head Specialization, Masking, and ArchitectureChapter 1 established what a transformer stores and where. The embedding layer provides initial coordinates. The FFN layers hold factual associations. The named weight tensors provide the navigable structure that LoRA adapters modify. But storage is inert without retrieval. The question every transformer layer has to answer, for every token in every position, is which stored information is relevant right now. That is the job of attention.2.1 Q, K, V Projections: The Geometry of AttentionGenerated using geminiThe attention mechanism begins with three linear projections applied to the same input. Given an input sequence represented as a matrix X of shape [sequence_length, hidden_dim], three separate weight matrices transform X into Q, K, and V. Q is the query projection, representing what a token is searching for. K is the key projection, representing what properties a token advertises about itself. V is the value projection, carrying the actual content that will be extracted if a match is found.The matching operation between Q and K is a dot product. For token A attending to token B, the score is the dot product of A’s query vector and B’s key vector. This measures the signed similarity between the two vectors in the projected subspace: when vectors point in similar directions, their dot product is large, producing a high attention score and a large weight on B’s value vector in the final output. The attention mechanism is, at its core, a learned similarity search over the sequence.Before those scores are converted into weights via softmax, they are scaled by the reciprocal of the square root of the key dimension. This scaling step is not cosmetic. When vectors have high dimensionality, their dot products grow large in magnitude simply due to accumulation across many components. Large inputs to softmax produce extremely peaked distributions where one token absorbs nearly all the attention weight and the rest approach zero. The gradient of softmax in that regime approaches zero, which means backpropagation delivers almost no learning signal. Scaling by 1/sqrt(d_k) keeps the variance of the scores stable regardless of dimensionality, preserving the softmax in a regime where gradients remain useful.The same mathematical principle appears during inference as temperature. Inference temperature divides the logits before the final softmax over vocabulary, controlling whether the output distribution is sharp and deterministic or diffuse and varied. Both the training-time sqrt(d_k) scaling and the inference-time temperature are doing the same thing: controlling the sharpness of a softmax over a dot-product space. Understanding one is understanding both.For fine-tuning with LoRA, the four projection matrices, q_proj, k_proj, v_proj, and o_proj, are the most direct levers on attention behavior. Modifying q_proj changes what the model searches for. Modifying k_proj changes what it identifies as relevant. Modifying v_proj changes the content that flows forward when a match occurs. These are genuinely distinct levers with distinct effects on model behavior, not interchangeable targets.2.2 Multi-Head Attention: Parallel SpecializationA single attention operation produces one attention pattern over the sequence. Multi-Head Attention [MHA] runs several independent attention operations in parallel, each with its own Q, K, and V projection weights, over distinct learned subspaces of the input. The outputs of all heads are concatenated and then projected back to the model dimension through o_proj.The functional consequence of this design is specialization. Research consistently shows that individual attention heads learn distinct tasks. Some heads track syntactic dependencies. Others follow entity coreference across long distances. Others track proximity or positional adjacency. A single head cannot simultaneously optimize for all of these, but a collection of heads can distribute the work.This specialization has a direct implication for how LoRA rank should be chosen. Rank controls the dimensionality of the A and B matrices, which determines how much of the weight space a LoRA adapter can modify. For a narrow fine-tuning task, only a small subset of attention heads need adjustment, and a low rank may be sufficient. For a task requiring a broad domain shift, where many heads need to relearn what constitutes relevant context, a higher rank is warranted.The output projection o_proj deserves specific attention. After each head produces its output, o_proj integrates all of them into a single representation that feeds into the residual stream. Modifying o_proj with a LoRA adapter applies a correction at the point of integration, affecting how all heads' contributions are combined. This makes it an efficient target for cross-head behavioral change, often as impactful as targeting the individual Q, K, V projections directly.2.3 Causal Masking and Padding MasksGenerated using notebookLMDecoder-only transformer training has a non-negotiable constraint: a token cannot use information from tokens that appear after it in the sequence. During training, the entire sequence is processed in parallel for efficiency, but the loss must be computed as if the model were generating each token without knowing the future. A causal mask enforces this. It is a lower-triangular binary matrix applied to the attention scores before softmax, setting all scores above the diagonal to negative infinity so they contribute zero weight after the softmax operation.Padding masks address a separate problem. Sequences in a training batch rarely have identical lengths. Shorter sequences are padded with a special token to fill the batch dimension. Without a padding mask, the model attends to those padding tokens and trains on them, introducing noise into the learning signal. A padding mask sets the attention scores for padding positions to negative infinity, removing them from the computation.Both of these masking mechanisms are foundational to how Unsloth’s train_on_responses_only function works. In instruction-following fine-tuning, the training example consists of a prompt followed by a response. train_on_responses_only sets the labels for all prompt tokens to -100, which is the conventional index that cross-entropy loss ignores during computation. Those tokens are still present in the input and still influence the KV computation, but they contribute nothing to the gradient. Computing loss on prompt tokens forces the model to predict tokens it cannot affect, which adds gradient noise without any corresponding benefit. Every gradient step with prompt tokens included is a noisier gradient step than it needs to be.2.4 Decoder-Only vs. Other ArchitecturesTransformers were introduced in an encoder-decoder configuration, where an encoder processes the full input bidirectionally and a decoder generates the output token by token with cross-attention to the encoder’s representations. Encoder-only models such as BERT removed the decoder entirely, enabling fully bidirectional attention over the input, which makes them well-suited for classification and retrieval tasks where the full sequence is available at inference time. Decoder-only models removed the encoder, leaving only the autoregressive generation stack with causal masking throughout.Virtually every high-performance open-weight model in active use today, including the Qwen and Llama families, is decoder-only. Decoder-only models have proven more tractable to scale efficiently, and the generative versatility of a well-scaled decoder-only model has made the bidirectional advantage of encoder-only models largely irrelevant for most production tasks.The architectural choice has a training consequence that matters directly. Decoder-only models are pre-trained with next-token prediction loss, where the model predicts each token given all preceding tokens. Applying a masked language modeling objective, the training procedure for BERT-style models, to a decoder-only architecture is a category error. The causal mask renders the training signal incoherent, and the resulting model will not function. This is an obvious mistake in theory but a real failure mode when practitioners attempt to port training recipes across architectures without understanding what the loss function assumes about the model’s attention pattern.Chapter 3: How a Transformer Stays StableResidual Streams, Normalization, Precision, and Gradient FlowChapters 1 and 2 described what the model knows and how it decides what to look at. Both of those operations are only useful if the underlying computation stays numerically coherent across dozens of layers, thousands of training steps, and multiple precision formats simultaneously. Chapter 3 is about the mechanisms that make that coherence possible, and what happens when they break.3.1 The Residual Stream: Why Deep Networks Train At AllGenerated using notebookLMThe defining structural feature of every modern transformer is not attention. It is the residual connection. Every sub-layer, whether attention or FFN, adds its output to its input rather than replacing it. The formula is x_{l+1} = x_l + Sublayer(x_l). The original representation persists. The sub-layer contributes an incremental update.The gradient flow consequence of this design is what makes training very deep networks viable at all. Without residual connections, gradients backpropagating through a sequence of non-linear layers decay exponentially. By the time the gradient reaches early layers, it carries almost no useful signal. The residual path bypasses this problem by providing an identity mapping, a direct route for gradients to flow backward through the addition operation without passing through any non-linearity. Earlier layers receive meaningful gradients. Training converges.For fine-tuning with LoRA, the residual stream is not just relevant background. It is the conceptual reason LoRA is possible at all. Because each layer’s job is to add a small update to a persistent representation, an adapter can change model behavior by injecting its own small update, the product AB, into that same stream. The base model’s pre-trained knowledge lives in the residual. The adapter nudges it in a task-relevant direction.The fragility of this mechanism comes from the alpha/rank ratio. LoRA scales its output by alpha divided by rank before injecting it into the residual stream. If alpha is set too high relative to rank, the adapter injects a large signal at every layer simultaneously. That large signal overwhelms the pre-trained residual representation, the identity path loses coherence, and training collapses. The common practice of setting alpha equal to rank, or at most twice rank, is not arbitrary conservatism. It is a direct consequence of preserving the residual stream’s integrity under simultaneous adapter injection across all targeted layers. In Unsloth, lora_alpha and r are the two parameters that jointly control this ratio, and they should always be set with their relationship in mind.3.2 RMSNorm: Keeping Activations in a Trainable RangeA different failure mode emerges without normalization. As representations flow through multiple transformer layers, their magnitudes can grow or shrink with each transformation. Unchecked growth produces activations that saturate non-linearities and overflow precision formats. Unchecked shrinkage produces activations that lose discriminative signal entirely. Normalization layers prevent both.Standard Layer Normalization centers and rescales activations by subtracting the mean and dividing by the standard deviation across the feature dimension, then applying learned scale and shift parameters. Root Mean Square Normalization [RMSNorm] removes the mean subtraction and bias terms entirely, normalizing only to unit root-mean-square. The result is fewer arithmetic operations and fewer memory reads and writes per normalization step.This matters more at runtime than the FLOPs count suggests. Matrix multiplications dominate total FLOPs in a transformer forward pass, but normalization layers involve element-wise operations over large tensors that stress memory bandwidth rather than compute. RMSNorm’s reduced memory traffic produces measurable latency improvements in inference-critical deployments.The precision interaction is where RMSNorm becomes a debugging concern during fine-tuning. Normalization involves computing a sum of squared values followed by a reciprocal square root. In BF16 or FP16, intermediate values in this computation are prone to overflow or underflow when activation magnitudes are large or small. A single overflowed normalization result propagates through the residual stream and produces NaN losses, sometimes within the first few hundred steps. Unsloth keeps normalization layers in FP32 even when the base model weights are quantized to NF4 and the LoRA adapters train in BF16. This is the specific fix for a specific numerical failure mode. When a fine-tuning run produces NaN losses early in training, the normalization layer precision is the first place to check.3.3 Floating Point Formats: The Precision StackGenerated using notebookLMFloating point formats differ along two dimensions: dynamic range, controlled by the number of exponent bits, and precision, controlled by the number of mantissa bits. FP32 allocates 8 exponent bits and 23 mantissa bits. BF16 preserves the 8 exponent bits but reduces mantissa bits to 7. FP16 uses 5 exponent bits and 10 mantissa bits.For training, dynamic range matters more than precision. Gradients span a wide range of magnitudes across layers and optimization steps. BF16 matches FP32’s exponent range exactly, which means it can represent the same range of values with lower numerical resolution. FP16’s smaller exponent range produces overflow errors when gradients or activations exceed its representable range, which happens regularly in deep model training. This is why BF16 displaced FP16 as the standard training format for modern LLMs.NF4 is a different kind of format. It is a 4-bit quantization scheme designed around the empirical observation that the weight distributions in pre-trained neural networks are approximately Gaussian. NF4 places its quantization levels at the quantiles of a standard normal distribution rather than at uniform intervals, which means more levels are allocated where the density of actual weight values is highest. This is what “information-theoretically optimal for normally distributed weights” means in practice. It is not optimal for arbitrary data. It is optimal for the specific distribution that pre-trained LLM weights happen to follow.Unsloth’s precision stack at runtime is layered. The base model weights are loaded in NF4 to minimize VRAM consumption. The LoRA adapter matrices A and B are trained in BF16 to maintain gradient health. Normalization layers are pinned to FP32. Gradients are accumulated in FP32. Understanding this stack converts mysterious training behavior into diagnosable events. A loss that oscillates wildly in early steps is likely a gradient accumulation precision problem. A loss that suddenly hits NaN around step 200 is more likely a normalization overflow. A model that trains cleanly but produces incoherent outputs at inference is often a precision mismatch between training and serving formats.3.4 Cross-Entropy Loss and Perplexity: Reading the SignalEvery fine-tuning run optimizes one number: the cross-entropy loss between the model’s predicted token distribution and the actual next token in the training data. At each position in the sequence, the model produces a probability distribution over the entire vocabulary. Cross-entropy measures the negative log probability assigned to the correct token. If the model assigns high probability to the right token, the loss contribution from that position is small. If it assigns low probability, the contribution is large.Perplexity is the exponential of the mean cross-entropy loss over a sequence. A perplexity of 10 means the model is as uncertain at each step as if it were choosing uniformly from 10 equally likely options. Perplexity is useful as a relative metric during training. A decreasing perplexity on a held-out validation set indicates genuine generalization. A perplexity that decreases on training data but stagnates or increases on validation data is the diagnostic signature of overfitting.train_on_responses_only connects directly to loss quality. When loss is computed across both prompt and response tokens, the model is penalized for failing to predict prompt tokens it was given as input, which is uninformative by construction. The gradient from those positions adds noise without adding task-relevant signal. Restricting loss computation to response tokens removes that noise, producing cleaner gradients and typically faster convergence on the target task.Chapter 4: How a Transformer Knows Where It IsPositional Encoding, RoPE, and Context LengthChapter 3 established the mechanisms that keep numerical computation stable across deep layers and mixed precision formats. Those mechanisms assume the model is processing a coherent sequence. But there is a structural problem that none of the components covered so far address. The attention operation is defined entirely in terms of dot products between token vectors. A dot product has no knowledge of order. Feed the same ten tokens to an attention layer in ten different permutations and the attention scores are identical every time. The model cannot distinguish word order without an external mechanism for encoding position. Chapter 4 is about that mechanism, and why the specific solution used in modern LLMs is worth understanding precisely.4.1 Why Transformers Need Positional InformationThe permutation invariance of attention is a feature in some contexts and a fundamental problem in others. It is a feature because it allows the attention mechanism to learn relationships between tokens regardless of their distance in the sequence. It is a problem because sequence order is semantically critical for language, and the model has no way to recover it from attention scores alone.The original transformer paper introduced absolute sinusoidal positional embeddings as the fix. A fixed vector encoding each position was added directly to the token embedding before the first layer. The model then had access to positional information through the token representation itself. This approach works at the scales it was designed for, but it has a hard limitation: the positional encodings are defined for a fixed maximum sequence length at training time. Generalizing to longer sequences requires either re-training or accepting degraded behavior at positions the model has never seen. Every modern open-weight model has moved away from this approach.4.2 RoPE: Rotating Position Into Q and KGenerated using notebookLMRotary Positional Embeddings [RoPE] do not add positional information to the token embedding. RoPE injects positional information directly into the query and key vectors at each attention layer, immediately before the dot product is computed. The mechanism is a rotation in a complex-valued vector space. Each query and key vector is rotated by an angle proportional to the token’s position and the frequency assigned to each dimension. Nearby tokens receive similar rotations. Distant tokens receive increasingly different ones.The elegant consequence of this design is that the dot product between a rotated query and a rotated key depends only on the relative distance between the two tokens, not their absolute positions. A query at position 50 attending to a key at position 43 produces the same attention score as the same query at position 200 attending to the same key at position 193. The attention mechanism becomes sensitive to how far apart tokens are rather than where they sit absolutely. This is the translational relativity property, and it is why RoPE generalizes better to varied sequence lengths than fixed absolute encodings.RoPE also preserves vector norms. The rotations are applied as orthogonal transformations, which means the magnitude of each query and key vector is unchanged. Only the direction changes. The scaling by 1/sqrt(d_k) from Chapter 2 depends on the assumption that query and key vectors have consistent magnitudes. An encoding scheme that distorted those magnitudes would interact badly with the scaling and undermine the variance normalization that keeps softmax in a useful gradient regime. RoPE avoids this problem by construction.RoPE is active in every modern model Unsloth supports, including all Qwen and Llama variants. The max_seq_length parameter directly controls how far the RoPE rotations extend during training. Setting it higher than the base model's pre-training length is where the interaction between RoPE and context extension becomes the central concern.4.3 rope_theta and Context Window ExtensionGenerated using notebookLMThe frequency at which each dimension of the query and key vectors rotates is determined by a base parameter called rope_theta. The rotation angle for dimension pair i at position t is t divided by theta raised to the power of 2i divided by the head dimension. Higher theta values produce slower rotation rates, meaning positions accumulate angular difference more slowly. The practical effect is that a higher theta allows the model to represent longer sequences before rotational aliasing, where distant positions begin to resemble near positions, becomes a problem.Llama 2 used theta equal to 10,000. Llama 3 increased it to 500,000 to support longer contexts natively. When fine-tuning requires extending a model beyond its original context length, modifying theta is the primary lever. The wrong theta does not produce an immediate error. It produces subtle positional incoherence at long ranges, where tokens at positions the model has not seen stop relating to each other correctly, and performance degrades in ways that can look like an unrelated problem.Four scaling strategies have emerged for extending context via RoPE modification. Position Interpolation [PI] compresses the position indices to fit within the original training range by dividing each index by a scale factor. It is simple to implement but removes high-frequency positional components, reducing performance on standard-length sequences. NTK-Aware scaling applies different frequency adjustments across dimensions, preserving high-frequency positional details in lower dimensions while extending the range of higher dimensions. Dynamic NTK scaling adjusts the scale factor at inference time based on the actual sequence length being processed, which is useful when sequence lengths vary widely across requests. YaRN combines NTK-aware scaling with a temperature adjustment to the attention scores, compensating for the distributional shift that context extension induces.Llama 3.1’s expansion to 131,072 tokens illustrates the full picture of a production context extension. The model retained the theta value of 500,000 established in Llama 3 and applied a model-specific scaling factor of 8.0 combined with frequency-dependent adjustments controlled by low_freq_factor and high_freq_factor parameters, with original_max_position_embeddings set to 8,192 as the reference window. This is the actual config: multiple parameters working together, not a single number change. The reason understanding the mechanics matters is precisely this, cargo-culting any one of those values without the others produces a broken result, and the model will not immediately tell you something is wrong.In Unsloth, context extension is configured through max_seq_length and, where needed, the rope_scaling configuration passed at model load time. Setting max_seq_length beyond the base model's training length without also adjusting RoPE parameters produces a model that accepts longer inputs but processes them incorrectly.Chapter 5: How a Transformer Scales EfficientlyFlashAttention, GQA, KV Cache, and Architecture Choices That Affect LatencyThe previous four chapters described a transformer that is correct. This chapter describes making it fast. The distinction matters because correctness and efficiency pull in opposite directions at almost every design decision. Standard attention is mathematically clean but computationally brutal at scale. Full KV storage across all heads is accurate but memory-prohibitive at long contexts. The mechanisms in this chapter are the engineering responses to those tensions, and every one of them surfaces directly in Unsloth configuration choices or in the failure modes practitioners encounter when pushing models toward production latency requirements.5.1 Attention Complexity: The O(n²) WallStandard self-attention computes a score between every token and every other token in the sequence. For a sequence of length n, that is n-squared score computations per attention layer per forward pass. A sequence of 4,096 tokens produces over 16 million scores per layer. A sequence of 32,768 tokens produces over a billion. The computation scales with the square of the input length, and the memory required to store the full attention score matrix scales identically.The memory problem is actually more severe than the compute problem. Attention scores must be materialized as a full n by n matrix in GPU high-bandwidth memory [HBM] before softmax can be applied. For long sequences, this matrix exceeds available HBM even when the model weights themselves fit comfortably. Practitioners attempting to train on 8,192-token sequences with a mid-range GPU hit this wall not because the model is too large, but because the attention score matrix for a single layer at that sequence length overflows memory independently of model size.5.2 FlashAttention v2: Kernel-Level FixGenerated using notebookLMFlashAttention, introduced by Dao et al. (2022) and refined in v2 (2023), solves the memory problem without changing the mathematical result. The key insight is that the full n by n attention matrix never needs to exist in HBM simultaneously. By tiling the computation into blocks that fit in GPU SRAM [static random-access memory], FlashAttention computes attention scores, applies softmax, and accumulates the output incrementally, flushing results back to HBM without ever writing the full score matrix. The numerical output is identical to standard attention. The memory footprint is not, dropping from quadratic to linear in sequence length.FlashAttention-2 achieves approximately 2x speedup over FlashAttention v1, and up to 9–10x speedup over a standard PyTorch attention implementation, reaching up to 73% of the theoretical maximum FLOPs per second on A100 GPUs. The gains are not uniform: they compound at longer sequence lengths because the memory savings are proportional to n-squared, and longer sequences benefit more. For fine-tuning, this translates directly into the ability to train at sequence lengths that would otherwise produce out-of-memory errors, not through any change to the model or the data, but through a smarter execution of the same computation.Unsloth enables FlashAttention v2 by default on compatible hardware. When max_seq_length is set in a training configuration, the practical upper bound on that value is determined partly by available HBM and partly by what FlashAttention's tiling implementation can handle given the head dimension and batch size. OOM errors at long sequences, even when the model itself fits in memory, are typically FlashAttention constraint errors rather than model size errors.5.3 Grouped Query Attention: KV Head SharingGenerated using notebookLMMulti-Head Attention [MHA] assigns every attention head its own independent key and value projection matrices. A model with 32 attention heads maintains 32 independent K and V representations per token per layer. During inference, all of those representations must be stored in the KV cache for every token in the sequence. At long context lengths with large batch sizes, the KV cache for MHA can consume more memory than the model weights themselves.Multi-Query Attention [MQA] addressed this by collapsing all query heads to share a single K and V head. The memory savings are substantial but the accuracy cost is measurable, particularly on tasks requiring fine-grained attention differentiation across heads. Grouped Query Attention [GQA] is the intermediate solution. Query heads are divided into groups, and each group shares one K and V head. The number of groups is a hyperparameter that trades off between MHA accuracy and MQA memory efficiency.Qwen3 1.5B uses GQA, as do the Llama 3 family and most other recent open-weight models. The fine-tuning consequence is concrete. In a GQA model, k_proj and v_proj have fewer rows than q_proj because there are fewer K and V heads than Q heads. When inspecting weight tensor shapes to configure target_modules, the asymmetry between Q and K/V projection shapes is not an anomaly or an error. It is GQA. Applying the same LoRA rank to all three projections remains generally effective, but understanding why the shapes differ prevents confusion and informs rank allocation decisions when memory is tight.5.4 The KV Cache: Inference Latency’s Binding ConstraintAutoregressive generation computes each new token by running a full forward pass through the model. Without caching, every forward pass recomputes the key and value vectors for every preceding token in the sequence from scratch. The KV cache eliminates this redundancy by storing computed K and V tensors for all previous positions and retrieving them directly on subsequent steps.The cost of this optimization is memory. KV cache size scales linearly with sequence length, batch size, number of KV heads, head dimension, and the number of layers. For a 7-billion parameter model serving a batch of 16 requests at 4,096 tokens per request, the KV cache can require tens of gigabytes of VRAM, often exceeding the memory footprint of the model weights. This is the binding constraint on serving throughput in production deployments, not the model size.For fine-tuning, the KV cache creates an indirect constraint. The max_seq_length chosen during training determines the maximum sequence length the model is trained to handle, and that same length determines the KV cache memory requirement at inference time. A model fine-tuned at 8,192 tokens cannot be served efficiently in an environment sized for 2,048-token KV caches. The training configuration and the serving configuration are not independent decisions.5.5 Pre-Norm Architecture: Why Unsloth Defaults WorkThe original transformer used Post-Norm placement, where layer normalization was applied after the attention or FFN sub-layer and after the residual addition. Every modern open-weight model uses Pre-Norm, where normalization is applied before each sub-layer, to the input rather than the output.The training stability difference between these two placements is significant. In Post-Norm architectures, the residual stream receives unnormalized sub-layer outputs before the addition, which means the magnitude of the residual can vary substantially across layers and training steps. This makes Post-Norm models sensitive to learning rate and prone to divergence in deep configurations. In Pre-Norm architectures, each sub-layer receives a normalized input, which keeps activation magnitudes bounded at the start of every attention and FFN computation. The residual stream accumulates updates over a more controlled range, and training is correspondingly more stable.Pre-Norm is the assumption baked into Unsloth’s default hyperparameters. An older Post-Norm model brought into the same training setup would require a different learning rate schedule and tighter gradient clipping to avoid the instabilities that Pre-Norm architecture naturally suppresses.Chapter 6: Putting It All TogetherThe Mental Model Used Every Time Unsloth OpensFive chapters built a complete structural picture of the transformer. Storage in embeddings and FFN layers. Routing through Q, K, V attention projections. Stability through residual connections, RMSNorm, and a layered precision stack. Positional coherence through RoPE and theta scaling. Efficiency through FlashAttention, GQA, and KV cache management. This chapter connects all of it to the moment a fine-tuning run needs to be configured.6.1 The Decision MapEvery fine-tuning configuration starts with a question about the task. The answer to that question determines which layers to target, which rank to use, and which architectural properties of the base model need to be accounted for.The storage-versus-routing distinction from Chapters 1 and 2 is the first fork in the decision. A task that requires the model to adopt a new behavioral pattern, a specific output structure, a classification schema, a reasoning format, is fundamentally a routing problem. The model already has the relevant knowledge in its FFN layers. What needs to change is which information gets attended to, how context is weighted, and how the output projection integrates across heads. Attention projections are the primary target. A task that requires injecting factual associations the base model does not have, domain-specific terminology with precise meanings, entity relationships outside the pre-training distribution, is a storage problem. The FFN layers need to be updated. Most of the times and when the task type is ambiguous or genuinely composite, targeting all modules, the full set of q_proj, k_proj, v_proj, o_proj, gate_proj, up_proj, and down_proj, is the correct default.The model architecture is the second fork. Before setting target_modules, inspect the shapes of the K and V projection tensors. A model using GQA will show k_proj.weight and v_proj.weight with smaller first dimensions than q_proj.weight. This is the expected structure of a GQA model, and it means fewer K and V heads will receive adapter updates. The same rank applied to K/V projections in a GQA model covers a proportionally larger share of that projection's capacity than in an MHA model.The context length requirement is the third fork. If the fine-tuning task involves sequences longer than the base model’s pre-training context, max_seq_length must be set to accommodate them, and the RoPE configuration must be adjusted accordingly. Setting max_seq_length beyond the training context without modifying the RoPE theta or scaling strategy produces a model that accepts the longer input without understanding the positional relationships within it.6.2 The Five Numbers Every Fine-Tuning Run Starts WithGenerated using notebookLMFive parameters collectively define the character of a LoRA fine-tuning run in Unsloth. Each one now has a derivable justification rather than a copied value.r is the LoRA rank. It controls the dimensionality of the A and B adapter matrices and therefore the breadth of the weight subspace the adapter can modify. Low rank, typically in the range of 8 to 16, is appropriate for narrow behavioral tasks where only a small subset of attention heads needs adjustment. Higher rank is warranted when the task requires broad adaptation across many heads or when the domain shift is large. Rank is not a quality dial that should always be turned up. Higher rank increases memory consumption and training time, and for many tasks it adds capacity the optimizer will not usefully fill.lora_alpha is the scaling factor applied to the adapter output before it enters the residual stream. The effective injection strength is alpha divided by rank. Setting alpha equal to rank produces a scaling factor of 1.0, a conservative and stable default. Setting alpha to twice rank doubles the injection strength and accelerates adaptation, with a corresponding increase in the risk of destabilizing the residual stream. The relationship between alpha and rank should always be set deliberately.target_modules is the list of named weight tensors that receive LoRA adapters. The decision map above governs this choice. The full set covering both attention and FFN projections is the safe default. Narrower targeting is appropriate when memory constraints require it or when the task type is clearly identified as either routing or storage.max_seq_length controls both the RoPE extension and the KV cache memory footprint during training. The right value is the 95th or 99th percentile length of the training data, not the maximum possible value the hardware can support. Setting it higher than the task requires wastes VRAM on KV cache storage for sequence positions that the training data never fills.The dtype stack, the combination of load_in_4bit, bnb_4bit_compute_dtype, and the LoRA adapter dtype, should reflect a deliberate choice about the precision-performance trade-off. The Unsloth default of NF4 base weights with BF16 adapter training and FP32 normalization layers is the correct choice for the vast majority of single-GPU fine-tuning runs. Deviating from it requires a specific reason grounded in the precision format trade-offs from Chapter 3.6.3 What Episode 2 CoversThis episode mapped the transformer’s internal structure at the level needed to make principled fine-tuning decisions. The five structural dimensions, storage, routing, stability, position, and efficiency, are now a navigable map rather than a black box.Episode 2 goes one level deeper into LoRA itself. The mathematical derivation of the low-rank update, the intrinsic dimensionality research that explains why low-rank adaptation works at all, the full set of LoRA hyperparameters including dropout and bias terms, and practical experiments on a real model showing how rank, alpha, and target module choices produce measurably different outcomes. The architecture is now understood. Next, the modification tool gets the same treatment.Note — The primary purpose of the images (slides) is to provide intuition. As a result, some oversimplifications or minor inaccuracies may be present.Connect with me — https://www.linkedin.com/in/suchitra-idumina/Fine-Tuning LLMs, Part 1: The Transformer Architecture Guide Nobody Wrote for Fine-Tuners was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.