Zero Labs
Industry News / AI

The Ultimate Guide to LoRA: How to Fine-Tune LLMs Correctly, Part 2

Source · Towards AI By Suchitra Malimbada

From the publisher’s feed, collected in the ZeroLabs newsroom.

A deep dive into the mathematics, memory architecture, structural consequences, and deployment decisions behind low-rank adaptationMost engineers who fine-tune language models treat the process as a configuration exercise. Set a rank, pick target modules from a blog post, run the job, and hope the loss curve looks right. That approach works until it does not. Until the model learns nothing despite a clean loss curve, or collapses on day two of training, or generalizes perfectly on the eval set and fails completely in production. At that point, the configuration options stop being enough. What is needed is a precise understanding of what each component inside the fine-tuning system is doing and why modifying it changes behavior in the specific way it does.Read the first episode — The Ultimate Transformer Architecture Guide for Fine-TunersGenerated using notebookLMThis is the second episode in the series. Episode 1 mapped the transformer’s internal structure at the level needed to make principled fine-tuning decisions. It went trough things such as storage in embeddings and FFN layers, routing through attention projections, stability through residual connections and RMSNorm, positional coherence through RoPE, and efficiency through FlashAttention and KV cache management. The transformer is no longer a black box. This episode goes one level deeper into the tool used to modify it.By the end of this article, every parameter in an Unsloth fine-tuning configuration has a derivable justification. Every failure mode has a mechanism. Every deployment decision has a structural reason behind it.Table of ContentsChapter 1: The Modification ToolChapter 2: The Control PanelChapter 3: Running on FumesChapter 4: What the Model Actually LearnsChapter 5: Beyond Standard LoRAChapter 6: Data, Templates, and Response MaskingChapter 7: After Training Conclusion ReferencesChapter 1: The Modification ToolGenerated using notebookLM1.1 The Weight Update ProblemEvery fine-tuning method, whether full or parameter-efficient, has the same ambition, move the model’s weight matrices from where they are after pre-training to a position that produces better behavior on the target task. The conventional approach computes gradients with respect to all parameters and applies updates iteratively until task loss converges.For a 7-billion parameter model, this means computing and storing optimizer states for seven billion scalar values simultaneously. With Adam, that is two additional 32-bit tensors per parameter for the first and second moment estimates, bringing the optimizer-state memory alone to roughly 56 GB at full precision. The model weights add another 14 GB in BF16. No single consumer GPU contains that budget. Training at that scale requires multi-GPU parallelism, gradient offloading, or a fundamentally different approach to what gets updated.The different approach begins with a question about the weight update itself. Is the full-rank ΔW strictly necessary? Does achieving competitive task performance actually require modifying a d×k matrix across all d×k degrees of freedom? The answer is no, and that answer has an empirical proof attached.1.2 Intrinsic Dimensionality: The Geometry Behind the MethodIn 2021, Aghajanyan, Gupta, and Zettlemoyer published research showing that pre-trained language models have a remarkably low intrinsic dimension. Their finding was precise: there exists a low-dimensional reparameterization of the full parameter space that is as effective for fine-tuning as optimizing over all parameters. By optimizing only 200 trainable parameters randomly projected back into the full space, a RoBERTa model achieves 90% of full-parameter performance on the MRPC benchmark.The implication is geometric. A pre-trained model’s weights define a high-dimensional parameter space. During fine-tuning, the optimization trajectory toward a task-optimal solution does not explore that space uniformly. It follows a path confined to a low-dimensional subspace. Most of the parameter space is flat or irrelevant to the adaptation objective. Aghajanyan et al. also showed that larger models tend to have smaller intrinsic dimensionality, meaning the bigger the model, the less of its parameter space the optimizer needs to traverse to achieve task-level performance. This counterintuitive result is one reason well-scaled models respond so cleanly to low-rank adaptation.1.3 The BA Decomposition: From Geometry to CodeHu et al. (2021) translated the intrinsic dimensionality finding into a concrete training modification. Instead of computing ΔW as a full d×k matrix, LoRA constrains it to the product of two smaller matrices: ΔW = BA, where A ∈ R^{r×k} and B ∈ R^{d×r}, with r significantly smaller than d or k.During the forward pass, the hidden representation h is computed as h = W₀x + BAx. The pre-trained weight W₀ is frozen throughout. Gradients never flow through it. The optimizer maintains states only for A and B, whose total parameter count is r(d + k) rather than dk. For a projection matrix with d = k = 4096 and rank 16, the full update matrix contains 16,777,216 parameters. The LoRA decomposition contains 131,072. That is a 128x reduction for a single weight matrix. Applied to GPT-3 175B, Hu et al. showed that LoRA reduces trainable parameters by 10,000 times and GPU memory requirements by 3 times compared to full fine-tuning with Adam, while matching or exceeding fine-tuning quality on RoBERTa, DeBERTa, GPT-2, and GPT-3.The initialization is deliberate. A is drawn from a random Gaussian distribution. B is initialized to zero. The consequence is that ΔW = BA = 0 at training step zero. The adapter contributes nothing at initialization, so training begins from a model that behaves exactly like the base model. The adapter builds its contribution incrementally as gradients update A and B, rather than introducing a random perturbation from the first forward pass.1.4 The Frozen Base Weight as a Geometric AnchorThe frozen base weight W₀ is not merely a memory-saving trick. It is the mechanism that prevents catastrophic forgetting. A fully fine-tuned model updates every weight in response to the task gradient, which means any existing knowledge encoded in those weights is at risk of being overwritten. When the task gradient conflicts with knowledge encoded elsewhere in the network, full fine-tuning sacrifices that knowledge to minimize task loss.With LoRA, W₀ is geometrically fixed throughout training. Optimization occurs entirely in the low-dimensional subspace defined by A and B. The pre-trained knowledge encoded in W₀ cannot be directly overwritten because gradients never reach it. The adapter shifts the model's behavior within the directions that A and B can represent, while the base model's representational foundation remains structurally intact. LoRA matches full fine-tuning performance when adapters are applied to all layers of the network, especially the MLP layers, and the number of trainable parameters exceeds the informational content of the dataset.Chapter 2: The Control PanelGenerated using notebookLM2.1 Rank (r): The Capacity DialRank is the most consequential single decision in a LoRA configuration. It determines the dimensionality of both A and B, controlling the breadth of the weight subspace the adapter can modify. A rank-8 adapter on a 4096-dimensional projection can represent updates living in an 8-dimensional subspace of a 4096-dimensional space. Every additional direction the task requires that falls outside that subspace is inaccessible to the adapter, regardless of how long training runs.Simple classification or output formatting tasks can be handled with ranks in the 4 to 8 range. General instruction following lands between 16 and 32. Complex reasoning, mathematical problem solving, and high-entropy domain adaptation push the justified range to 64, 128, or higher.The failure mode at low rank is an expressive bottleneck. The adapter saturates, the optimizer has no useful directions left to explore, and the loss plateau is misread as convergence. The failure mode at excessively high rank is subtler: the adapter acquires capacity the optimizer cannot fill usefully from the available data, and that excess capacity becomes a vector for overfitting or gradient noise that degrades general reasoning. Rank is a capacity budget to match against task demand, not a quality dial to maximize. The starting point is r=16, adjusted from there based on empirical validation.2.2 Alpha (α) and the Scaling Factor: The Magnitude KnobAlpha is widely misunderstood because it appears to be a second rank parameter. It is not. Rank sets the dimensionality of the adapter. Alpha controls how hard that adapter pushes into the residual stream at every forward pass.The operative quantity is the ratio α/r, not alpha in isolation. Every adapter output is scaled by α/r before being added to the frozen base weight's contribution in h = W₀x + (α/r)BAx. With α = r, the scaling factor is 1.0 and the adapter injects its learned update at unit strength. With α = 2r, the adapter injects at twice the strength, accelerating learning but increasing the risk of destabilizing the residual stream. With α = r/2, the adapter injects conservatively, appropriate when training data is limited or when preserving the base model's default behavior is a higher priority than aggressive task specialization.The residual stream integrity argument from Chapter 1 applies directly here. If α/r is set high while adapters are applied across all targeted layers simultaneously, each layer injects an amplified update into the stream it passes to the next layer. Those amplifications compound across layers. The residual representation can lose coherence with the pre-trained structure entirely, and training collapses. Setting alpha equal to rank, or at most twice rank, is the direct consequence of respecting the residual stream's integrity under simultaneous multi-layer adapter injection.2.3 The α/r Ratio: Why Two Parameters Must Be Reasoned About TogetherSetting alpha and rank independently is a category error. Every configuration decision about either parameter is a decision about their ratio. Consider two configurations: r=16, α=32 gives α/r = 2.0. r=32, α=64 also gives α/r = 2.0. The adapter injection strength is identical. The difference is that the second operates in a 32-dimensional update subspace rather than a 16-dimensional one, which matters for complex tasks but is irrelevant for simple ones. The practical discipline is to set rank first based on task complexity, then set alpha relative to that rank based on how aggressively the adapter should update.The specific configuration that deserves a warning is high alpha with low rank combined with non-zero dropout. That combination concentrates a large injection signal through a narrow subspace while randomly corrupting the gradient at each step. It is one of the fastest ways to produce a training run whose loss curve looks healthy while the model learns nothing useful.2.4 rsLoRA: When Standard Scaling FailsStandard LoRA with the α/r scaling factor has a structural problem at high ranks. As rank increases, the variance of the adapter output scales linearly with r. The 1/r term in the scaling factor over-suppresses the update at high ranks: gradient magnitude collapses, the adapter receives progressively weaker learning signal, and the additional capacity from a higher rank produces no measurable benefit over a lower rank. The model behaves as if the rank were much lower than the configured value.Rank-Stabilized LoRA [rsLoRA] replaces the α/r scaling factor with α/sqrt(r). Theoretical and empirical analysis confirms that 1/sqrt(r) scaling maintains constant output and gradient norms regardless of rank, which means the adapter at r=256 actually behaves like an r=256 adapter rather than a collapsed equivalent. In Unsloth, this is activated with use_rslora=True. rsLoRA is necessary whenever rank is pushed above 64 for complex tasks. Below that threshold, the gradient collapse is modest enough that standard scaling remains serviceable. Enabling rsLoRA unconditionally at any rank introduces no penalty but becomes critical at high ranks where the original scaling breaks down.2.5 Dropout: Why Zero Is Usually the Correct AnswerLoRA dropout zeroes a fraction of adapter input activations during each training step. The intention is regularization. The problem is timing. Dropout helps when the model has had enough training time to develop co-adapted features worth disrupting. LoRA fine-tuning runs are short, typically one to three epochs on curated datasets. At that scale, the adapter has not accumulated the co-adaptation that dropout is designed to break. The stochastic signal corruption adds noise to the gradient without delivering the regularization benefit that justifies it.The interaction with alpha amplifies this. High alpha combined with non-zero dropout produces unstable gradient variance. Unsloth defaults lora_dropout to 0 for a specific reason beyond convention is its custom kernel optimizations produce measurably better performance when dropout is absent. Non-zero dropout forces additional branching in the computation that the optimized kernels cannot fully absorb. The combination of no regularization benefit, increased gradient noise, and reduced kernel efficiency makes dropout=0 the correct default for the vast majority of LoRA fine-tuning runs.2.6 Target Modules: Attention Versus MLP, and Why the Full Set Is the DefaultThe choice of which projection layers receive adapters determines which aspects of the model’s behavior can be modified. Attention projections, q_proj, k_proj, v_proj, and o_proj, control information routing, such as which tokens attend to which other tokens and how head outputs integrate into the residual stream. MLP projections, gate_proj, up_proj, and down_proj, store factual associations and behavioral patterns. As established by Geva et al. (EMNLP 2021), FFN layers function as key-value memories where specific inputs activate stored distributions over output vocabulary.Empirical experiments consistently show that targeting all seven projection types produces higher RougeL and reasoning scores than any partial configuration. For tasks that are pure routing problems, attention-only targeting saves memory with minimal accuracy cost. For tasks requiring new factual associations, MLP targeting is not optional. For most real fine-tuning tasks, the full set is the principled choice. The memory savings from partial targeting are typically modest and rarely justify the accuracy trade-off. In Unsloth, incorrectly spelling a module name produces silent exclusion rather than an error, so the configured list should always be verified against the model’s actual parameter names.2.7 Bias Terms: The Parameter That Adds Noise for No ReturnThe bias parameter accepts "none," "all," or "lora_only," determining whether bias vectors in targeted layers are trained alongside A and B. The performance evidence for bias training is weak. For most fine-tuning tasks, the directional changes captured by A and B subsume whatever correction bias terms would provide. The standard setting is "none." This reflects the consistent finding that bias training adds parameters without adding performance, and it simplifies the computation Unsloth's optimized kernels perform at each forward pass.Chapter 3: Running on FumesGenerated using notebookLM3.1 What QLoRA Actually Is: Two Precision Regimes, One ModelChapter 2 established that LoRA’s adapter parameters are small. The memory that the frozen base weights consume is not. At BF16, a 7B model occupies roughly 14 GB of VRAM before a single training batch is processed. QLoRA addresses this constraint without modifying LoRA’s mathematics. It changes how the frozen base model is stored in memory while the adapter trains on top of it.QLoRA operates two distinct precision regimes simultaneously. The frozen base model weights are stored in 4-bit NF4 quantized format, reducing their memory footprint by approximately 75% compared to BF16. The LoRA adapter matrices A and B remain in BF16. When a forward pass requires a computation involving a base weight, the 4-bit blocks are de-quantized to BF16 on-the-fly, the matrix multiplication runs in BF16, and the BF16 adapter output is added to the result. The 4-bit weights never update. Only the BF16 adapter matrices receive gradients and optimizer state updates.De-quantization happens per-block at compute time, not globally at load time. The base model never exists in BF16 in VRAM simultaneously. A 7B model that required 14 GB in BF16 loads in approximately 4 to 5 GB in NF4, opening the full fine-tuning workflow to hardware that would otherwise be excluded entirely.3.2 NF4: Why the Quantization Type Is Not ArbitraryINT4 and FP4 both distribute their 16 available quantization levels at uniform or near-uniform intervals across the representable range. For data that is uniformly distributed, this is optimal. Pre-trained neural network weights follow an approximately Gaussian distribution centered near zero, with the vast majority of values clustered in a narrow band around the mean and a small fraction of outliers in the tails.NF4 uses quantile quantization calibrated specifically to that distribution. The 16 quantization levels are placed at the quantiles of a standard normal distribution N(0,1), meaning each level represents an equal expected share of actual weight values. Near zero, where density is highest, the levels are tightly spaced, preserving fine distinctions between values where most weights live. NF4 also includes an exact representation of zero, which matters for preserving sparsity patterns in layers where zero-valued weights carry structural significance. The information-theoretic optimality of NF4 for normally distributed data is the mechanism that makes QLoRA's accuracy retention possible, not a marketing claim.3.3 Double Quantization: Compressing the MetadataBlock-wise quantization divides weight tensors into fixed-size blocks and computes a scaling constant for each block. A block size of 64 with 32-bit floating-point scaling constants adds approximately 0.5 bits per parameter in metadata overhead. Double quantization applies a second quantization pass to those scaling constants, reducing them from 32-bit to 8-bit. The average savings is approximately 0.37 bits per parameter. At 65B parameters, this produces approximately 3 GB of recovered VRAM, often the margin that determines whether a large model fits on a single A100 or requires two GPUs. Double quantization is a principled second application of the same quantization logic to a different layer of the memory hierarchy.3.4 Paged Optimizers: The Safety NetEven with NF4 base weights and small BF16 adapters, memory spikes occur during training. Long sequences produce large intermediate activations. Mini-batches longer than average generate optimizer state updates that temporarily exceed the VRAM budget established at initialization. Paged optimizers use NVIDIA’s unified memory system to handle this, when a spike would exceed available VRAM, optimizer state pages transfer to CPU RAM automatically, then page back during the update step. The transfer introduces latency on affected steps, but the training run continues rather than crashing.Paged optimizers are a safety net, not a performance feature. Persistent paging activity during training signals that sequence length, batch size, or model size exceeds what the hardware can handle efficiently. Paging keeps the run alive. It does not make the hardware situation adequate.3.5 Unsloth’s Gradient Checkpointing: The Hidden VRAM CostStandard backpropagation requires storing every intermediate activation from the forward pass for use in the backward pass. For a model with many layers processing long sequences, activation memory can rival or exceed weight memory. Gradient checkpointing discards most intermediate activations during the forward pass and recomputes them on-demand during the backward pass, trading compute for memory.Unsloth implements its own gradient checkpointing variant that saves approximately 30% more VRAM than the standard PyTorch implementation. The flag is use_gradient_checkpointing="unsloth". The practical effect is that sequence lengths of 16,384 or 32,768 tokens, which produce OOM errors under standard gradient checkpointing, become trainable on hardware that fits the base model and adapter comfortably. Additionally, Unsloth's hand-optimized Triton kernels and fused operations provide 2x to 5x speedup for common operations like attention and RMSNorm compared to standard PyTorch.3.6 The Quantization Cliff for Sub-3B ModelsQLoRA works reliably for models above approximately 3 billion parameters. Below that threshold, a failure mode appears that does not announce itself through obvious signals. Large models have high information-theoretic capacity across their weight matrices. When NF4 quantization loses some precision in each block, that lost information is partially recoverable from redundancy elsewhere in the network. Sub-3B models do not have that redundancy to spare. Every parameter carries a higher fraction of the total representational capacity. When NF4 quantization combines with a low-rank adapter constraint, the model can lose the ability to perform coherent reasoning while the training loss continues to decrease toward what looks like clean convergence.This is the insidious version of the failure. A QLoRA run on a 1.5B model with rank 16 can produce a smooth, decreasing loss curve, a healthy-looking final perplexity, and a model that generates incoherent outputs on the target task. The training metrics report success. The model has failed. For models below 3B parameters, prefer 16-bit LoRA over QLoRA when VRAM permits. When VRAM does not permit it, treat rank as a more conservative parameter than it would be for larger models.Chapter 4: What the Model Actually Learns4.1 The Illusion of Equivalence: Spectral Analysis of LoRA vs Full Fine-TuningChapters 1 through 3 described LoRA as a precise, memory-efficient method for adapting a frozen base model. That framing is accurate as far as it goes. What it does not capture is what the adapter actually does to the internal geometry of the weight matrices, and why the solution LoRA produces is structurally distinct from the solution full fine-tuning [FFT] produces, even when both achieve similar benchmark numbers.Singular Value Decomposition [SVD] applied to weight matrices of LoRA-trained and FFT-trained models reveals a fundamental difference in their internal organization. SVD decomposes a weight matrix W into W = UΣVᵀ, where U and V are orthogonal matrices whose columns are singular vectors, and Σ is a diagonal matrix of singular values ordered from largest to smallest.In a fully fine-tuned model, the singular vector structure after training remains spectrally similar to the pre-trained checkpoint. The fine-tuning updates distribute across the existing directional structure of the weight matrix, modifying the magnitudes of existing directions without introducing fundamentally new ones. LoRA-trained models tell a different story. Their weight matrices contain high-magnitude singular vectors with no counterpart in either the pre-trained model or the FFT-trained model. These vectors point in directions highly dissimilar to the pre-trained singular structure. They are new directions injected into the weight space by the low-rank adapter, and they dominate the singular value spectrum in a way that distinguishes LoRA weight matrices unambiguously from both their pre-trained and fully fine-tuned counterparts. These are the intruder dimensions.4.2 Intruder Dimensions: The Primary Mechanism of ForgettingIntruder dimensions are the structural explanation for catastrophic forgetting in LoRA-trained models, established causally rather than correlationally.The mechanism is as follows. The frozen base weight W₀ encodes pre-training knowledge along its principal singular directions. When the adapter BA is added during training, its low-rank structure concentrates update energy into a small number of high-magnitude directions. Those directions are determined by the task gradient and have no particular relationship to the existing singular structure of W₀. They are new, and they are large. In the merged weight W_merged = W₀ + (α/r)BA, those intruder dimensions appear at the top of the singular value spectrum, dominating the matrix's behavior on inputs that activate them.When those inputs come from the pre-training distribution rather than the fine-tuning task, the intruder dimensions produce outputs inconsistent with what the pre-trained model would have generated. The model has not gradually forgotten the pre-training distribution. Specific high-magnitude directions have been injected into its weight matrices that actively misrepresent inputs from that distribution. The forgetting is localized to the subspace spanned by the intruder dimensions.Research confirms this causally, by identifying the singular vectors associated with intruder dimensions after training and scaling their corresponding singular values downward, practitioners can recover a substantial portion of the pre-training distribution’s performance with minimal degradation on the fine-tuning task. The pre-training knowledge was not overwritten. It was suppressed by the intruder dimensions’ dominance in the spectrum. Attenuating those dimensions restores access to the knowledge that was always structurally present in W₀.4.3 The Gradient Subspace Geometry of ForgettingForgetting in any fine-tuned model is governed by the angular relationship between the gradient subspace of the new task and the gradient subspace associated with pre-training knowledge. When the task gradient points in a direction orthogonal to the pre-training gradient subspace, learning the task leaves the pre-training knowledge undisturbed. When it opposes the pre-training gradient subspace, learning the task directly degrades the pre-training knowledge.LoRA provides a structural advantage in this geometry. The frozen W₀ acts as a geometric brake. Because the optimizer cannot modify W₀ directly, the total update to the merged weight is constrained to the low-rank subspace of the adapter. That constraint limits how far the model can deviate from its pre-trained state in any direction, including the directions most damaging to pre-training knowledge. Full fine-tuning has no such constraint. This geometric brake is the principled reason LoRA maintains better source-domain performance than FFT in continual learning scenarios, and the reason LoRA's forgetting takes the specific form of localized intruder dimensions rather than diffuse weight corruption.4.4 C-LoRA and Orthogonality Constraints for Multi-Stage Fine-TuningSequential fine-tuning introduces a compounding problem. Each round of LoRA fine-tuning introduces its own intruder dimensions. If the intruder dimensions from different rounds overlap in the weight space, later adaptations partially overwrite earlier ones. Over multiple rounds, this accumulation produces severe performance decay on the earliest tasks, even though the frozen base weights provide a constant anchor throughout.C-LoRA addresses this by enforcing orthogonality constraints on adapter updates across rounds. Each new adapter is constrained so its update subspace does not intersect with the subspaces occupied by previous adapters. The intruder dimensions introduced by each fine-tuning stage remain geometrically separate, preventing overwriting of earlier adaptations. For single-task fine-tuning, C-LoRA is irrelevant. For any workflow involving sequential adaptation across different data distributions or multi-task specialization through successive training runs, the orthogonality constraint is the mechanism that prevents progressive degradation.4.5 LoRA Versus Full Fine-Tuning: When Each Is Actually the Right ChoiceLoRA is not a universally cheaper approximation to full fine-tuning. It is a different method that produces a structurally different model with different failure modes, different forgetting characteristics, and different performance ceilings.In transfer learning scenarios where the fine-tuning task falls within the pre-training distribution, LoRA tends to produce better-generalized models than FFT, which trades source-domain performance for task optimization.. The frozen base weight preserves generalization capacity that FFT sacrifices to minimize task loss. For tasks that genuinely extend what the base model already knows, LoRA is not just more efficient. It produces a better-generalized model.FFT becomes appropriate when the task requires behavioral shifts so large that the low-rank constraint becomes a hard ceiling on performance. If the adapter capacity is insufficient to represent the full update the task requires, and increasing rank reaches diminishing returns, FFT is the only method that can close the remaining gap. That threshold is task-dependent and model-dependent, and should be determined empirically rather than assumed. The practical escalation path is to start with LoRA, increase rank if performance plateaus, enable rsLoRA when rank exceeds 64, and escalate to FFT only when the maximum rank the hardware supports still falls short.Chapter 5: Beyond Standard LoRAGenerated using notebookLM5.1 PiSSA: SVD Initialization and Faster ConvergenceStandard LoRA initializes A from a random Gaussian and B to zero, which means ΔW = BA = 0 at training step zero. The adapter contributes nothing until gradients have pushed A and B away from their initial values. For QLoRA configurations, where the base model weights carry quantization error from the NF4 compression, this cold-start initialization means the adapter spends early training steps compensating for quantization noise rather than learning the task.Principal Singular Values Adaptation [PiSSA] modifies this initialization by decomposing W₀ using SVD and initializing A and B from the principal singular values and vectors of the pre-trained weight matrix. The adapter begins training already aligned with the most significant structure in W₀, which means it contributes meaningfully from the first forward pass. On the GSM8K math benchmark, a Mistral-7B model fine-tuned with PiSSA achieved 72.86% accuracy compared to 67.7% for standard LoRA initialization under identical experimental conditions. Separately, on LLaMA 2-7B, PiSSA reduces 4-bit quantization error by approximately 18.97% compared to standard QLoRA initialization, because the SVD-based initialization partially absorbs the NF4 compression error into the adapter's starting configuration. In Unsloth, PiSSA is activated via init_lora_weights="pissa".5.2 DoRA: Magnitude-Direction DecompositionStandard LoRA adapts only the directional component of weight updates through the low-rank BA product. The magnitude of the weight matrix, the overall scale of its transformations, is left to the frozen base weight. For tasks where the base model’s weight magnitudes are misaligned with the target task’s requirements, this constraint limits what LoRA can express even at sufficient rank.Weight-Decomposed LoRA [DoRA] decomposes the pre-trained weight matrix into magnitude and direction components and optimizes them separately. The directional component receives standard low-rank LoRA updates. The magnitude component receives its own optimization, allowing the adapter to independently scale the transformation strength in each direction it modifies. Empirical results show DoRA consistently outperforms standard LoRA on commonsense reasoning and visual instruction tuning benchmarks, with DoRA at rank 8 often matching or exceeding LoRA at rank 16. For resource-constrained environments where rank budget is tight and accuracy requirements are high, DoRA offers a meaningful improvement without requiring additional trainable parameters.5.3 LoRA+: Differentiated Learning Rates for A and BA and B are initialized differently and play structurally different roles in the adapter. B is initialized to zero and starts with no gradient signal until A has moved sufficiently from its initial Gaussian values to produce meaningful forward-pass contributions. A is initialized randomly and begins receiving gradient signal immediately. Applying the same learning rate to both matrices is suboptimal because their gradient dynamics are asymmetric from the start.LoRA+ addresses this by setting different learning rates for A and B, with matrix B updated more aggressively than matrix A. The ratio between the two learning rates is a hyperparameter to tune rather than a fixed value, with the appropriate setting depending on the specific model and task. Research shows LoRA+ achieves up to 2x faster convergence and 1 to 2 percentage point accuracy improvements on tasks including MNLI (on RoBERTa) and Llama-7B fine-tuning tasks, with no additional computational overhead or parameter count increase.5.4 aLoRA: Adapter Activation and KV Cache ReuseThe three variants above improve training dynamics. aLoRA solves a different problem that only appears at inference time, specifically in multi-adapter serving scenarios. When an adapter is switched mid-sequence in a conversation, the KV cache computed under the previous adapter becomes inconsistent with the new adapter’s weights. The cache must be invalidated and the full context recomputed. For long conversations, that recomputation cost is substantial and occurs at every adapter switch.Activated LoRA [aLoRA] eliminates this cost by modifying the architecture so that adapter weights do not activate until a specific activation token appears in the input. Before that token, the model runs as the unmodified base model. After it, the adapter applies. The K and V tensors computed before the activation token reflect pure base model weights, which do not change across adapter variants. Those tensors are valid regardless of which adapter activates afterward and can be cached and reused across conversations sharing the same prefix. Measured in a multi-adapter serving engine on complex multi-turn pipelines, aLoRA achieves end-to-end latency reductions of up to 58x and time-to-first-token [TTFT] improvements exceeding 100x compared to systems that invalidate and recompute the full context on each adapter switch. The operational requirement is that the activation token must be present in every training example at the correct position, which connects the serving architecture directly to the data pipeline decisions in Chapter 6.Chapter 6: Data, Templates, and Response Masking6.1 Chat Templates: Why Format Mismatch Degrades Performance Without WarningEvery decoder-only model has a specific set of special tokens that structure its conversational format. Qwen models use ChatML format, with turns wrapped by and tokens and role identifiers attached. Llama-3 uses its own distinct token set. These formats were established during instruction fine-tuning of the base model, and the model has learned to treat them as structural signals rather than content.When training data uses the wrong template, the model receives examples where the structural signals it expects are absent or appear in the wrong positions. The adapter trains on a signal that conflicts with the base model’s existing understanding of conversation structure. The loss decreases because the adapter is learning something, but what it is learning is the wrong representation of the task. At inference time, the model is prompted with the correct template, which it now partially misrecognizes, and output degrades in ways ranging from subtle quality reduction to repetitive generation loops and outright incoherence. This failure does not produce an error. The training run completes and the loss curve looks reasonable. The problem only surfaces on actual prompts. In Unsloth, the correct approach is to apply the template through the tokenizer’s apply_chat_template method, which uses the template stored in the model's tokenizer configuration rather than a manually constructed format string.6.2 train_on_responses_only: What It Does at the Label LevelGenerated using notebookLMA standard instruction-tuning training example contains a user prompt and an assistant response. If the loss is computed across the entire token sequence, the optimizer penalizes the model for failing to predict prompt tokens it was explicitly given, which carries no useful task signal. Every gradient step includes a noise component from prompt token positions.train_on_responses_only removes that noise by setting the label value for all prompt tokens to -100. In PyTorch's cross-entropy loss implementation, positions with a label of -100 are excluded from the loss computation entirely. No gradient flows from those positions. The adapter receives gradient signal exclusively from assistant response tokens, which are the tokens whose behavior the fine-tuning task is trying to shape.The effect on adapter capacity utilization is direct. Every gradient step that includes prompt token loss is a step where some fraction of the adapter’s fixed capacity is being pushed by a gradient that encodes nothing about the target behavior. For tasks with long system prompts and short responses, the unmasked configuration wastes a large fraction of every gradient step.The implementation in Unsloth applies -100 masking by identifying the response start token in each training example. This identification relies on the chat template being correctly applied, connecting this directly to section 6.1. A misapplied template can cause the response start token to be misidentified, either including prompt tokens in the loss or excluding part of the actual response. Template correctness and response masking are not independent decisions.6.3 Data Quality Versus Data QuantityThe relationship between dataset size and adapter quality in LoRA fine-tuning does not follow the scaling intuition from pre-training. Fine-tuning with LoRA operates under a fundamentally different constraint. Which is the fact that the adapter has fixed capacity, the base model’s general representations are already established, and the gradient signal at each step either sharpens the adapter toward the target task or introduces noise that pulls it away.In this regime, data quality dominates quantity. A dataset with 1,000 carefully constructed examples that accurately represent the target task distribution produces better adapter performance than a dataset with 100,000 examples containing noise, inconsistencies, or off-distribution samples. The noise in a large low-quality dataset is not averaged away by the optimizer. It is present in every gradient step, and the adapter with limited capacity absorbs it as signal indistinguishable from genuine task information.Deduplication matters because duplicate examples appear as artificially high-frequency patterns that the adapter overfits to. Consistency in formatting matters because format variation across examples looks like multiple tasks to the adapter, fragmenting the gradient signal. Correctness of target responses matters more than coverage because a wrong answer in the training data is a gradient step in the wrong direction, and the adapter has no mechanism to distinguish it from a correct one. For synthetic data generation, these constraints translate directly into generation guidelines such as, diversity across examples, correctness verification before training, and format consistency enforced at generation time.Chapter 7: After TrainingGenerated using notebookLM7.1 Adapter Merging: Zero Inference OverheadTraining ends with two artifacts: the frozen base model and the adapter matrices A and B for every targeted layer. At inference time, those corrections have to be applied somehow, and the mechanism chosen determines the latency profile, the serving architecture, and the operational flexibility of the deployed system.The mathematically cleanest deployment path is merging. The merge operation computes W_merged = W₀ + (α/r)BA for every targeted weight matrix and writes the result into a single unified set of model weights. The adapter matrices A and B cease to exist as separate entities. The merged model is structurally identical to any other transformer checkpoint of the same architecture. It loads into any inference framework without adapter-aware infrastructure, runs at the same speed as the original base model, and produces no additional compute at inference time. There is no approximation in the merge. The forward pass of the merged model and the forward pass of the unmerged model with the adapter applied are numerically identical.In Unsloth, the merge and export is handled through model.save_pretrained_merged(). The merged checkpoint can then be quantized to GGUF for llama.cpp serving, converted for vLLM, or loaded directly for evaluation. Merging is the correct choice for any single-task deployment where inference latency is a primary constraint.7.2 Multi-Adapter Serving: S-LoRA ArchitectureMerging becomes impractical when a deployment needs to serve multiple task-specific adapters against the same base model. Each merged variant is a full-sized model checkpoint. Serving ten task-specific merged models requires ten times the VRAM of a single model, and the number of tasks a real multi-tenant platform needs to support typically exceeds what that approach can accommodate.S-LoRA keeps the base model in GPU VRAM throughout the serving session. The adapter sets live in CPU RAM. When a request arrives tagged with a specific adapter identity, the relevant A and B matrices are prefetched from CPU RAM to GPU, the forward pass runs with the adapter applied, and the GPU memory used by the adapter is available for the next request’s adapter after the pass completes. One base model serves an effectively unbounded number of adapter variants within the VRAM footprint of a single model plus the working memory required for one adapter at a time.7.3 aLoRA and KV Cache Reuse in ProductionS-LoRA handles the memory and batching problem for multi-adapter serving. It does not address a separate latency problem in multi-turn conversational deployments: KV cache invalidation on adapter switches. In a multi-turn conversation, the KV cache stores computed key and value tensors for every preceding token. When an adapter switch occurs mid-conversation, the cached K and V tensors were computed under a different adapter configuration and are now inconsistent with the new adapter’s weights. The cache must be invalidated and the full context recomputed. For long conversations, that recomputation cost is substantial.aLoRA eliminates this cost through the activation token mechanism described in Chapter 5. The K and V tensors computed before the activation token reflect pure base model weights, which do not change across adapter variants. Those tensors are valid regardless of which adapter activates after the activation token, and they can be cached and reused across conversations that share the same prefix. The 58x end-to-end latency reduction and 100x TTFT improvement for aLoRA are measured in a multi-adapter serving engine evaluated on complex multi-turn pipelines, not general benchmarks. They reflect the specific cost of cache invalidation eliminated in that serving context.The operational requirement aLoRA introduces connects the serving architecture directly back to Chapter 6. The activation token must be present in every training example at the correct position. The chat template must include it, and train_on_responses_only masking must begin at or after that token. A serving-time architectural decision determines a training-time data formatting requirement. These are not independent choices.7.4 The Deployment Decision TreeThe three serving strategies cover distinct operational regimes. A single-task deployment where inference latency is the primary constraint uses merging. The adapter is compiled into the base weights via model.save_pretrained_merged() and the merged checkpoint is served through any standard inference framework.A multi-task platform serving requests that require different task-specific behaviors against a shared base model uses S-LoRA. The base model occupies GPU VRAM. Adapters are stored in CPU RAM and prefetched on demand. The SGMV kernel handles heterogeneous batches without throughput collapse.A multi-turn conversational deployment where the same session requires switching between adapter behaviors uses aLoRA. The base model KV cache covers the shared prefix. The adapter activates at the designated token and applies from that point forward. The recomputation cost of adapter switching is eliminated by cache reuse.The common mistake is treating these three strategies as alternatives of different complexity rather than tools for different problems. Merging is not a simplified version of S-LoRA. S-LoRA is not a generalization of aLoRA. Each addresses a constraint the others do not encounter.ConclusionThis article started with a number 200. Two hundred trainable parameters, randomly projected into a model with hundreds of millions, achieving 90% of full fine-tuning performance on a real benchmark. That result from Aghajanyan et al. is the empirical foundation for everything covered here. Not a trick, not an approximation, but a geometric truth about how pre-trained networks store and access knowledge.From that foundation, every component of LoRA becomes derivable rather than configurable by convention. Rank is a capacity budget matched to task informational demand. Alpha is a residual stream injection magnitude. rsLoRA is the fix for a scaling law failure at high ranks. NF4 is information-theoretically optimal for the specific distribution pre-trained weights follow. Intruder dimensions are the structural fingerprint that distinguishes LoRA-trained models from FFT-trained models and explains precisely where and why forgetting occurs. PiSSA, DoRA, and LoRA+ each solve one specific limitation in the standard adapter. The chat template and response masking decisions determine what gradient signal the adapter actually receives. The merge vs. serve decision determines the inference architecture for the deployed system.The goal of this series is that fine-tuning decisions stop being configuration exercises and start being engineering decisions with derivable reasons. Episode 3 goes to training dynamics such as, learning rate schedules, gradient accumulation, effective batch size, overfitting diagnostics, and what the loss curve is actually telling you at each stage of a run.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/The Ultimate Guide to LoRA: How to Fine-Tune LLMs Correctly, Part 2 was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.