66 / 90

Day 66: Adapter Lifecycles: Serialization, Merging & Zero-Latency Serving

Fold adapter weights into base models for zero-latency inference, implement unmerging for multi-task hot-swapping, and package artifacts.

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

Weight Merging Mathematics and Zero-Latency Inference Deployment

Agent-Assisted Engineering Check

Prerequisites

Day 64-65 LoRA mathematics and matrix addition.

Learning Objective

Derive and implement the weight merging equation W_merged = W0 + (alpha/r)*B@A, folding the adapter into base weights to eliminate inference latency.

Instructions

1. Write the unmerged forward: y = W0 @ x + b + (alpha/r) * B @ (A @ x). Serving it costs two extra small matrix products and extra memory reads per layer.
2. Derive the merged weight: W_merged = W0 + (alpha/r) * B @ A. Check the shapes: B @ A is (out, r) @ (r, in) = (out, in), the shape of W0.
3. Prove the equivalence with linearity: W_merged @ x = W0 @ x + (alpha/r) * B @ A @ x.
4. Implement merge() with a guard flag, so that merging twice does not add the delta twice, and make forward() skip the adapter path once merged.
5. Compare outputs before and after the merge on random inputs. Exact arithmetic gives equality; fp32 rounds the sums in a different order, so measure the maximum difference and compare it with the 1e-6 target.
6. Count the latency saved for in = out = 4096 and r = 16: the FLOPs per token per layer that the unmerged path adds.

Time plan (120 min): reading 25 + exercise 65 + check 30. Reading: Hu et al. Section 4.1 (no additional inference latency) and the PEFT merge_and_unload documentation. Exercise: steps 1-6. Check: derive the merge equation and its shapes from memory.

Practice & Prediction Log

Write a merge() method for LoRALinear that updates self.linear.weight.data with the folded delta. Verify that for any input x, self.linear(x) after merging matches the unmerged lora_forward(x) to 1e-6 precision.

Independent Mastery Criterion

Demonstrate bit-level output equivalence between unmerged and merged models.

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, paragraph 'No Additional Inference Latency' (store W = W0 + BA)

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

Weight Unmerging Dynamics and Multi-Tenant Adapter Hot-Swapping

Independent Mastery Check (no AI assistance).

Prerequisites

Day 66 Activity 1, reversible weight operations.

Learning Objective

Implement unmerge operations W0 = W_merged - (alpha/r)*B@A, enabling dynamic adapter swapping on a single shared GPU instance across diverse user tasks.

Instructions

1. Compute the serving economics: ten separate 7B models in bf16 need 10 * 14 GB = 140 GB. One shared 14 GB base plus ten adapters needs far less: r=16 on all 7 projections is 39,976,960 parameters, about 80 MB each in bf16.
2. Implement unmerge() as the exact inverse of merge(): subtract (alpha/r) * B @ A with the same A, B and scale, guarded so that an unmerged layer is never unmerged again.
3. Run the swap cycle: load Adapter_Medical, merge, serve, unmerge; load Adapter_Legal, merge, serve, unmerge. Repeat it for several cycles.
4. After every unmerge, measure the maximum difference between the base weight and the original W0, and check it stays within 1e-6.
5. Explain why the drift is small but not always zero: (w0 + d) - d is not always w0 in floating point.
6. Repeat one cycle in bf16 and record the drift. Conclude when it is unsafe to merge into weights you plan to unmerge.

Time plan (120 min): reading 20 + exercise 70 + check 30. Reading: the PEFT documentation on loading several adapters and switching between them, and your Activity 1 notes. Exercise: unmerge(), the swap cycle and the bf16 comparison. Check: explain the drift result without notes.

Practice & Prediction Log

Execute a cycle: merge Adapter A -> verify -> unmerge -> verify base equals original W0 -> merge Adapter B. Prove that W0 undergoes zero floating-point drift.

Independent Mastery Criterion

Implement reversible unmerging and multi-tenant adapter hot-swapping with zero numerical degradation.

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, paragraph 'No Additional Inference Latency' (store W = W0 + BA)

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

Lightweight Adapter Serialization and Configuration Schema Standards

Agent-Assisted Engineering Check

Prerequisites

Day 66 Activities 1-2 and JSON/Safetensors serialization.

Learning Objective

Standardize the saving and reloading of adapter checkpoints: isolate adapter tensors from base weights, emit adapter_config.json metadata, and verify safe reloading.

Instructions

1. Define the artifact layout: adapter_model.safetensors plus adapter_config.json, nothing else. Older exports used adapter_model.bin (a pickle); use safetensors (Day 60).
2. Write the config with r, lora_alpha, target_modules, lora_dropout and base_model_name_or_path.
3. Filter the state dict to keys containing 'lora_' so the frozen base weights never enter the file.
4. Write save_adapter(model, path, ...) and load_adapter(model, path). Load with strict=False, because the file deliberately lacks the base weights, then assert that no adapter key was missed and nothing unexpected was loaded.
5. Measure the directory size and compare it with the predicted size: r * (in + out) values times 4 bytes in fp32.
6. Reload into a fresh model and check that its outputs equal the trained model's outputs.

Time plan (120 min): reading 20 + exercise 70 + check 30. Reading: the PEFT save_pretrained/from_pretrained documentation and the safetensors format notes. Exercise: both functions, the size check and the reload check. Check: predict the file size for a 1024 x 1024 layer at r=8, then verify it.

Practice & Prediction Log

Save an adapter from a fine-tuned model into an isolated directory. Inspect the directory: confirm total size is <1 MB and that adapter_config.json contains valid JSON schema keys.

Independent Mastery Criterion

Standardize lightweight adapter artifact packaging with strict separation from base weights.

Authoritative Source Resources & Provenance

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.

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.

04 120 min

Assessment: End-to-End LoRA Training, Merge Equivalence & Adapter Export

Independent Mastery Check (no AI assistance).

Prerequisites

Day 66 Activities 1-3.

Learning Objective

Execute a full end-to-end integration test: train an adapter on synthetic data, export artifacts, reload into a fresh model, merge weights, and prove 1e-6 numerical equivalence.

Instructions

1. Reuse the pieces: LoRALinear from Day 64, merge() and unmerge() from Activities 1-2, and save_adapter/load_adapter from Activity 3.
2. Train only lora_A and lora_B for 15 steps on synthetic data and record the loss of every step.
3. Export the adapter to 'exported_adapter/'.
4. Build a fresh model with the same base weights, load the adapter, and compute y_unmerged = model(x).
5. Call merge() and compute y_merged = model(x).
6. Assert that the loss decreased, that the base weight changed after merging, that max(abs(y_unmerged - y_merged)) < 1e-5 (merging in fp32 reorders the additions, so allow 1e-5), and that the reloaded model reproduces the trained one.

Time plan (120 min): reading 15 + exercise 75 + check 30. Reading: your notes from Activities 1-3. Exercise: the full lifecycle script. Check: the mastery run with every assertion passing, then a fresh-process rerun.

Practice & Prediction Log

Run the complete end-to-end verification suite. Confirm that loss drops during training, adapter export succeeds, and merged forward outputs match unmerged outputs to floating-point tolerance.

Independent Mastery Criterion

Demonstrate a complete, tested LoRA lifecycle with mathematical merge equivalence.

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, paragraph 'No Additional Inference Latency' (store W = W0 + BA)

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.