65 / 90

Day 65: LoRA Engineering: Weight Freezing, Gradients & Optimizer Collapse

Enforce strict base model parameter freezing, trace adapter gradient routing, and model optimizer VRAM collapse.

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

Base Model Freezing Semantics and Gradient Path Isolation

Agent-Assisted Engineering Check

Prerequisites

Day 64 LoRA forward equation and PyTorch autograd mechanics.

Learning Objective

Understand autograd graph construction during LoRA training: trace why base parameters require no gradients while adapter parameters receive valid backpropagation updates.

Instructions

1. Write the forward pass with its two paths: y = W0 @ x + (alpha/r) * B @ A @ x. The first path uses only the frozen W0; the second uses the trainable A (r x d_in) and B (d_out x r).
2. Freeze W0 with requires_grad_(False) before the forward pass. Autograd then records no gradient edge into W0 and never allocates W0.grad.
3. Derive the adapter gradients: dL/dB = (alpha/r) * (dL/dy) @ (A @ x).T and dL/dA = (alpha/r) * B.T @ (dL/dy) @ x.T. Note the shapes.
4. Predict what happens at step 0, when B is initialized to zero: which of the two gradients is exactly zero?
5. Run one backward pass and assert the three gradient facts from the prompt, then check your prediction from step 4.
6. Count the gradient memory you did not allocate: frozen parameters times 2 bytes in bf16 (or 4 bytes in fp32).

Time plan (120 min): reading 25 + exercise 65 + check 30. Reading: Hu et al. Section 4.1 (the LoRA update and its initialization) and the PEFT LoRA conceptual guide. Exercise: steps 1-6 with the reference model. Check: explain without notes why lora_A.grad is zero at step 0.

Practice & Prediction Log

Instantiate a model with a frozen linear layer and a trainable LoRA adapter. Run a backward pass. Assert that model.linear.weight.grad is None while lora_A.grad and lora_B.grad are non-None tensors.

Independent Mastery Criterion

Confirm gradient isolation between frozen base weights and trainable adapter matrices.

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 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.

02 120 min

Optimizer Footprint Collapse: AdamW VRAM Under Adapter Training

Independent Mastery Check (no AI assistance).

Prerequisites

Day 65 Activity 1 and Day 56 AdamW 16-bytes/param rule.

Learning Objective

Analyze the radical reduction of optimizer states under LoRA: from 16 bytes per base parameter (FP32 master weights, momentum, variance) to only 16 bytes per adapter parameter.

Instructions

1. Recall the Day 56 breakdown: each trainable parameter costs 16 bytes of static training state under mixed-precision AdamW: 4 B fp32 master weight + 4 B first moment + 4 B second moment + 4 B gradient.
2. Full fine-tuning of a 7B model: 7 * 10^9 * 16 bytes = 112 GB, before activations.
3. LoRA with r=16 on all 7 linear projections trains 39,976,960 parameters (about 40.0M, Day 64), so its optimizer state is 39,976,960 * 16 bytes ≈ 640 MB.
4. That is a ~99.4% reduction in optimizer memory. The frozen base weights are still needed: about 14 GB for 7B in bf16, which is why the model fits a single 16 GB or 24 GB GPU only with small batches or a quantized base (QLoRA).
5. Do the prompt calculation in bytes first, then convert to both decimal units (MB, GB) and binary units (MiB, GiB), and label each.
6. Add the frozen base to compare total static memory, not only the optimizer part.

Time plan (120 min): reading 25 + exercise 60 + check 35. Reading: Dettmers et al. (QLoRA) Section 2 on memory and the Day 56 AdamW breakdown. Exercise: the prompt calculation plus items (b) and (c). Check: redo item (c) unaided and state every unit.

Practice & Prediction Log

Calculate the exact optimizer memory (in MB) for an AdamW optimizer managing a LoRA-adapted 1B model with 10M trainable parameters vs full fine-tuning with 1B parameters. (b) Add the frozen 1B base stored in bf16 to the LoRA case and compare total static memory with full fine-tuning. (c) Apply the same rule to the 7B all-linear adapter with 39,976,960 trainable parameters and give the result in MB and MiB.

Independent Mastery Criterion

Calculate exact optimizer memory footprints demonstrating the multi-gigabyte savings of LoRA.

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.

03 120 min

Target Module Selection: Attention Projections vs Feed-Forward Layers

Agent-Assisted Engineering Check

Prerequisites

Day 65 Activities 1-2 and Transformer block architecture.

Learning Objective

Evaluate target module adaptation tradeoffs: compare adapting only Wq, Wv (Hu et al. 2021) versus adapting all linear projections (Wq, Wk, Wv, Wo, Gate, Up, Down).

Instructions

1. Start from the history: Hu et al. adapted only Wq and Wv to keep the parameter budget small.
2. Read the later evidence: QLoRA (Dettmers et al. 2023) found that adapting all linear layers, attention and MLP, was needed to match full fine-tuning, even at a low rank such as r=8 or 16.
3. Write count_target_params(model, targets, rank): sum rank * (in_features + out_features) over every nn.Linear whose last name component is in the target set. Match the whole component, not a substring.
4. Test it on the LLaMA-7B shapes (d=4096, MLP width 11008, 32 layers) built on the meta device, so no memory is allocated.
5. Compare the two configurations: target_modules=['q_proj', 'v_proj'] against all seven projections ('q_proj', 'k_proj', 'v_proj', 'o_proj', 'gate_proj', 'up_proj', 'down_proj'). All seven give ~4.8x the adapter parameters (39,976,960 vs 8,388,608 at r=16), still below 1% of the base.
6. Check that the count is linear in the rank: doubling r doubles it.

Time plan (120 min): reading 25 + exercise 65 + check 30. Reading: Hu et al. Section 7.1 (which weight matrices to adapt), QLoRA Section 4, and the PEFT target_modules documentation. Exercise: the helper and its three checks. Check: compute the per-layer count by hand and compare with the script.

Practice & Prediction Log

Inspect a transformer block and write a helper function count_target_params(model, target_module_names, rank). Verify that targeting all projections scales parameter count proportionally.

Independent Mastery Criterion

Demonstrate understanding of target module coverage trade-offs across attention and MLP projections.

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 7.1 Which Weight Matrices in Transformer Should We Apply LoRA To?

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.

04 120 min

Assessment: Frozen Base Verification and Gradient Routing Unit Tests

Independent Mastery Check (no AI assistance).

Prerequisites

Day 65 Activities 1-3.

Learning Objective

Construct and run comprehensive unit tests asserting that base weights remain untouched, optimizer only tracks adapter parameters, and loss decreases over 10 training steps.

Instructions

1. Build a small model with a frozen embedding, a frozen output layer W0 (model.linear) and trainable LoRA matrices lora_A and lora_B.
2. Before training, store detached clones of W0, lora_A and lora_B.
3. Give AdamW only the parameters with requires_grad=True.
4. Train for 10 steps on a toy next-token batch (inputs are tokens[:, :-1], targets are tokens[:, 1:]) and record the loss of every step.
5. Assert the four properties: W0.grad is None; W0 is bit-for-bit equal to its clone (torch.equal, not allclose); lora_A and lora_B changed and the loss decreased; the optimizer holds exactly lora_A and lora_B.
6. Mutation check: delete the freeze line once and confirm that the first two assertions now fail. A test that still passes is not testing the freeze.

Time plan (120 min): reading 15 + exercise 75 + check 30. Reading: your Activity 1 notes and the PEFT troubleshooting notes on trainable parameters. Exercise: the test suite and the mutation check. Check: the mastery run with every assertion passing.

Practice & Prediction Log

Run your LoRA freezing and gradient verification test suite. Confirm that base weights never mutate while adapter weights optimize successfully.

Independent Mastery Criterion

Pass 100% of freezing and gradient routing tests with zero parameter mutation in the base model.

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 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.