64 / 90

Day 64: LoRA Mathematics: Low-Rank Factorization & Scaling

Derive low-rank updates W = W0 + (alpha/r)*BA, analyze initialization dynamics, and compute exact trainable parameter ledgers.

Models and Pretraining 480 active minutes (8 hours)
01 120 min

Intrinsic Dimensionality and Low-Rank Matrix Factorization

Agent-Assisted Engineering Check

Prerequisites

Day 48 Linear layers and matrix multiplication fundamentals.

Learning Objective

Understand the intrinsic dimensionality hypothesis and express parameter updates as Delta W = (alpha/r) * B @ A where r << min(d, k).

Instructions

1. Review Aghajanyan et al. (2020): overparameterized LLMs have surprisingly low intrinsic dimensionality during downstream adaptation.
2. In standard full fine-tuning, W = W0 + Delta W with Delta W in R^{d x k} (full rank, requiring d*k parameters).
3. In LoRA (Hu et al. 2021), factorize Delta W = B @ A, where B in R^{d x r} and A in R^{r x k} with rank r (typically 4, 8, 16).
4. Note that for d=4096, k=4096, r=8: full fine-tuning requires 16,777,216 params, while LoRA requires only 8*(4096+4096) = 65,536 params.

Practice & Prediction Log

Given a linear projection layer of dimension d_in=1024, d_out=2048. Calculate the number of parameters in full matrix W0 vs rank r=8 LoRA matrices B and A. Compute the percentage reduction in trainable parameters.

Independent Mastery Criterion

Derive parameter counts and dimensional matrix shapes for any arbitrary linear projection.

Authoritative Source Resources & Provenance

linking arXiv non-exclusive license / Open Access

LoRA: Low-Rank Adaptation of Large Language Models

Author: Edward J. Hu, Yelong Shen, Phillip Wallis, Zeyuan Allen-Zhu, Yuanzhi Li, Shean Wang, Lu Wang, Weizhu Chen | Original Source Link ↗

Relevant Section / Range: Section 4.1 Low-Rank-Parametrized Update Matrices; Section 7.2 What Is the Optimal Rank r for LoRA?

Verified Version & Date: ICLR 2022 / arXiv:2106.09685v2 (Verified: 2026-10-30)

Selection Rationale:

Primary literature introducing Low-Rank Adaptation, establishing parameter decomposition W = W0 + (alpha/r)*BA, initialization strategies, and zero inference latency merging.

Source Prerequisites:

Matrix factorization, rank, linear layers, and transformer attention.

Safe Fallback (Offline Resilience):

Complete matrix derivations, tensor dimensions, and pure PyTorch LoRALinear modules are implemented directly in lesson code.

Compared Candidate Sources & Selection Analysis (2)

Introduces bottleneck adapter layers in series, which introduces unavoidable inference latency overhead; LoRA's parallel formulation merges with zero latency.

Prepends virtual prompt tokens; reduces available context length, unlike LoRA which preserves full sequence capacity.

linking Open Access / CC BY 4.0

Intrinsic Dimensionality Explains the Effectiveness of Language Model Fine-Tuning

Author: Armen Aghajanyan, Luke Zettlemoyer, Sonal Gupta | Original Source Link ↗

Relevant Section / Range: Section 3 Intrinsic Dimensionality of Finetuning

Verified Version & Date: ACL 2021 / arXiv:2012.13255v1 (Verified: 2026-10-30)

Selection Rationale:

Key theoretical foundation demonstrating that overparameterized pre-trained language models reside on a low-dimensional manifold, proving why low rank r (e.g. 4 to 16) is sufficient for task adaptation.

Source Prerequisites:

Linear algebra, matrix subspace projection, and pretraining representations.

Safe Fallback (Offline Resilience):

The intrinsic dimensionality concept, subspace projections, and parameter reduction trade-offs are fully explained in lesson text.

Compared Candidate Sources & Selection Analysis (2)

General neural network optimization landscapes; Aghajanyan focuses explicitly on foundation language models.

Measures how low-rank LoRA trades target-domain learning for less forgetting; Aghajanyan provides the direct theoretical motivation for LoRA's low-rank assumption.

02 120 min

Adapter Initialization Dynamics and the Alpha/Rank Scaling Factor

Independent Mastery Check (no AI assistance).

Prerequisites

Day 64 Activity 1 and Gaussian random variable distributions.

Learning Objective

Distinguish the LoRA paper's Gaussian initialization of A (variance unspecified) from the taught implementation's Kaiming-uniform initialization. Explain why B = 0 makes Delta W = 0 initially, and explain alpha/r scaling.

Instructions

1. Examine initialization. The LoRA paper (Section 4.1) uses a random Gaussian initialization for A, without stating its variance, and zero for B. The code this course teaches (act-04, projects/lora/model.py) follows microsoft/LoRA and the Hugging Face PEFT default (init_lora_weights=True): A uses nn.init.kaiming_uniform_(A, a=math.sqrt(5)), the nn.Linear default, and B = 0 (all elements zero). PEFT's init_lora_weights="gaussian" option instead draws A from a normal distribution with standard deviation 1/r. In every variant B = 0.
2. Note why B = 0 is critical: at step 0, Delta W = (alpha/r) * 0 * A = 0, so the model starts with the exact behavior of the pretrained base model without random degradation.
3. Analyze the scaling constant alpha / r: constant alpha (e.g. 16 or 32) scales the adapter output. When experimenting with different rank r, the scaling ensures learning rate does not need extensive retuning.
4. Write the forward pass formula: y = W0 @ x + (alpha / r) * (B @ (A @ x)). Notice order of operations: computing A @ x first costs O(r * k) per token and B @ (A @ x) costs O(d * r), so a batch of b * s tokens costs O(b * s * r * (d + k)) and the large d x k matrix is never formed during the forward pass.

Practice & Prediction Log

Write a pure Python forward pass function lora_forward(x, W0, A, B, alpha, r). Confirm with torch.equal that at initialization where B=0, lora_forward(x, W0, A, B, alpha, r) is exactly equal to x @ W0.T.

Independent Mastery Criterion

Prove mathematically and programmatically that Delta W = 0 at step 0.

Authoritative Source Resources & Provenance

linking arXiv non-exclusive license / Open Access

LoRA: Low-Rank Adaptation of Large Language Models

Author: Edward J. Hu, Yelong Shen, Phillip Wallis, Zeyuan Allen-Zhu, Yuanzhi Li, Shean Wang, Lu Wang, Weizhu Chen | Original Source Link ↗

Relevant Section / Range: Section 4.1 Low-Rank-Parametrized Update Matrices (W0 + BA, B initialized to zero, scaling by alpha/r)

Verified Version & Date: ICLR 2022 / arXiv:2106.09685v2 (Verified: 2026-10-30)

Selection Rationale:

Primary literature introducing Low-Rank Adaptation, establishing parameter decomposition W = W0 + (alpha/r)*BA, initialization strategies, and zero inference latency merging.

Source Prerequisites:

Matrix factorization, rank, linear layers, and transformer attention.

Safe Fallback (Offline Resilience):

Complete matrix derivations, tensor dimensions, and pure PyTorch LoRALinear modules are implemented directly in lesson code.

Compared Candidate Sources & Selection Analysis (2)

Introduces bottleneck adapter layers in series, which introduces unavoidable inference latency overhead; LoRA's parallel formulation merges with zero latency.

Prepends virtual prompt tokens; reduces available context length, unlike LoRA which preserves full sequence capacity.

linking Apache-2.0

PEFT: State-of-the-art Parameter-Efficient Fine-Tuning Methods

Author: Sourab Mangrulkar, Sylvain Gugger, Lysandre Debut, Younes Belkada, Sayak Paul, Benjamin Bossan | Original Source Link ↗

Relevant Section / Range: README 'Quickstart' (LoraConfig, get_peft_model, print_trainable_parameters)

Verified Version & Date: PEFT 0.10.x / GitHub (Verified: 2026-10-30)

Selection Rationale:

Widely adopted open-source library implementing LoRA configuration classes (LoraConfig), get_peft_model, and adapter serialization.

Source Prerequisites:

PyTorch nn.Module, Hugging Face transformers, and LoRA equations.

Safe Fallback (Offline Resilience):

Standalone, zero-dependency PyTorch implementations of LoRALinear layers and save/reload logic are provided in curriculum scripts.

Compared Candidate Sources & Selection Analysis (2)

Original reference code by Hu et al.; PEFT expands this to broader multi-model ecosystem integration.

Lit-GPT LoRA implementation (Lightning AI) ↗ compared_alternative [Apache 2.0]

High-performance clean implementation; compared alongside PEFT for modular code architecture.

03 120 min

Trainable Parameter Ledgers and Theoretical Memory Reductions

Agent-Assisted Engineering Check

Prerequisites

Day 64 Activities 1-2 and Day 56 parameter arithmetic.

Learning Objective

Build comprehensive parameter accounting ledgers across all transformer layers and distinguish standard FP16 LoRA from 4-bit QLoRA with clear mathematical rigor.

Instructions

1. Formulate exact adapter parameter counts across target modules:
- If targeting Wq and Wv (2 matrices per layer): N_lora = n_layer * 2 * r * (d + d) = 4 * n_layer * r * d.
- If targeting all linear projections (Wq, Wk, Wv, Wo, Gate, Up, Down - 7 matrices): N_lora = n_layer * r * sum(d_in + d_out).
2. Compute the parameter ratio for a 7B model (d=4096, MLP width 11008, 32 layers) with all 7 linear projections adapted at r=16: per layer 4 * 16 * (4096 + 4096) + 3 * 16 * (4096 + 11008) = 1,249,280, so total LoRA params = 32 * 1,249,280 = 39,976,960 (~40.0M, about 0.6% of the base model).
3. Clarify terminology boundaries: Standard LoRA maintains base model weights in FP16 or BF16. QLoRA (Dettmers et al. 2023) quantizes base weights into 4-bit NormalFloat (NF4), adds double quantization of the quantization constants, and uses paged optimizers. Do NOT label pure LoRA as QLoRA without actual 4-bit quantization evidence.
4. Calculate checkpoint storage savings: full FP16 checkpoint = 7e9 * 2 bytes = 14 GB; LoRA adapter checkpoint = 39,976,960 * 2 bytes = ~80 MB.

Practice & Prediction Log

For an 8-layer model with d=512, targeting Wq and Wv with rank r=8, calculate the exact number of trainable parameters and the size of the saved adapter weights in FP16.

Independent Mastery Criterion

Calculate exact adapter parameters and disk footprints across any target configuration.

Authoritative Source Resources & Provenance

linking arXiv non-exclusive license / Open Access

LoRA: Low-Rank Adaptation of Large Language Models

Author: Edward J. Hu, Yelong Shen, Phillip Wallis, Zeyuan Allen-Zhu, Yuanzhi Li, Shean Wang, Lu Wang, Weizhu Chen | Original Source Link ↗

Relevant Section / Range: Section 4.2 Applying LoRA to Transformer (frozen W0, VRAM and checkpoint-size reduction)

Verified Version & Date: ICLR 2022 / arXiv:2106.09685v2 (Verified: 2026-10-30)

Selection Rationale:

Primary literature introducing Low-Rank Adaptation, establishing parameter decomposition W = W0 + (alpha/r)*BA, initialization strategies, and zero inference latency merging.

Source Prerequisites:

Matrix factorization, rank, linear layers, and transformer attention.

Safe Fallback (Offline Resilience):

Complete matrix derivations, tensor dimensions, and pure PyTorch LoRALinear modules are implemented directly in lesson code.

Compared Candidate Sources & Selection Analysis (2)

Introduces bottleneck adapter layers in series, which introduces unavoidable inference latency overhead; LoRA's parallel formulation merges with zero latency.

Prepends virtual prompt tokens; reduces available context length, unlike LoRA which preserves full sequence capacity.

linking Open Access / CC BY 4.0

QLoRA: Efficient Finetuning of Quantized LLMs

Author: Tim Dettmers, Artidoro Pagnoni, Ari Holtzman, Luke Zettlemoyer | Original Source Link ↗

Relevant Section / Range: Section 3 QLoRA Finetuning and Appendix G Memory Footprint

Verified Version & Date: NeurIPS 2023 / arXiv:2305.14314v1 (Verified: 2026-10-30)

Selection Rationale:

Primary paper cited to clearly distinguish pure unquantized FP16/BF16 LoRA from 4-bit quantized QLoRA with paged optimizers, preventing misleading terminology conflation.

Source Prerequisites:

Quantization (NF4/FP4), double quantization, and standard LoRA.

Safe Fallback (Offline Resilience):

The mathematical distinction between LoRA adapter updates and 4-bit base weight dequantization is explicitly detailed in curriculum comparisons.

Compared Candidate Sources & Selection Analysis (2)

Post-training quantization only; QLoRA combines backpropagation through quantized weights with LoRA adapters.

Inference quantization; Dettmers QLoRA focuses specifically on parameter-efficient fine-tuning memory reduction.

04 120 min

Assessment: Pure PyTorch LoRALinear Layer and Forward Identity Verification

Independent Mastery Check (no AI assistance).

Prerequisites

Day 64 Activities 1-3.

Learning Objective

Build a self-contained LoRALinear(nn.Module) in pure PyTorch without external PEFT dependencies, verifying forward pass correctness, scaling, and step 0 identity.

Instructions

1. Subclass nn.Module to create LoRALinear(in_features, out_features, r=8, lora_alpha=16).
2. Register the base layer as a frozen nn.Linear: call self.linear.requires_grad_(False) so both the weight W0 and the bias are frozen.
3. Create lora_A as nn.Parameter of shape (r, in_features) and lora_B as nn.Parameter of shape (out_features, r).
4. Initialize A with Kaiming uniform and B with zeros.
5. Write forward(x): base = self.linear(x); adapter = self.scaling * (x @ self.lora_A.T @ self.lora_B.T), where self.scaling = lora_alpha / r; return base + adapter.
6. Assert that with random inputs x, max difference between forward(x) and self.linear(x) is exactly 0.0.

Practice & Prediction Log

Run unit tests for your pure PyTorch LoRALinear implementation. Confirm that parameter count matches 2*r*d and that step 0 identity holds with zero discrepancy.

Independent Mastery Criterion

Implement an independent LoRALinear module achieving 100% test passing on step 0 identity.

Authoritative Source Resources & Provenance

linking arXiv non-exclusive license / Open Access

LoRA: Low-Rank Adaptation of Large Language Models

Author: Edward J. Hu, Yelong Shen, Phillip Wallis, Zeyuan Allen-Zhu, Yuanzhi Li, Shean Wang, Lu Wang, Weizhu Chen | Original Source Link ↗

Relevant Section / Range: Section 4.1 Low-Rank-Parametrized Update Matrices (W0 + BA, B initialized to zero, scaling by alpha/r)

Verified Version & Date: ICLR 2022 / arXiv:2106.09685v2 (Verified: 2026-10-30)

Selection Rationale:

Primary literature introducing Low-Rank Adaptation, establishing parameter decomposition W = W0 + (alpha/r)*BA, initialization strategies, and zero inference latency merging.

Source Prerequisites:

Matrix factorization, rank, linear layers, and transformer attention.

Safe Fallback (Offline Resilience):

Complete matrix derivations, tensor dimensions, and pure PyTorch LoRALinear modules are implemented directly in lesson code.

Compared Candidate Sources & Selection Analysis (2)

Introduces bottleneck adapter layers in series, which introduces unavoidable inference latency overhead; LoRA's parallel formulation merges with zero latency.

Prepends virtual prompt tokens; reduces available context length, unlike LoRA which preserves full sequence capacity.

linking Apache-2.0

PEFT: State-of-the-art Parameter-Efficient Fine-Tuning Methods

Author: Sourab Mangrulkar, Sylvain Gugger, Lysandre Debut, Younes Belkada, Sayak Paul, Benjamin Bossan | Original Source Link ↗

Relevant Section / Range: README 'Quickstart' (LoraConfig, get_peft_model, print_trainable_parameters)

Verified Version & Date: PEFT 0.10.x / GitHub (Verified: 2026-10-30)

Selection Rationale:

Widely adopted open-source library implementing LoRA configuration classes (LoraConfig), get_peft_model, and adapter serialization.

Source Prerequisites:

PyTorch nn.Module, Hugging Face transformers, and LoRA equations.

Safe Fallback (Offline Resilience):

Standalone, zero-dependency PyTorch implementations of LoRALinear layers and save/reload logic are provided in curriculum scripts.

Compared Candidate Sources & Selection Analysis (2)

Original reference code by Hu et al.; PEFT expands this to broader multi-model ecosystem integration.

Lit-GPT LoRA implementation (Lightning AI) ↗ compared_alternative [Apache 2.0]

High-performance clean implementation; compared alongside PEFT for modular code architecture.