Skip to main content
← CONCEPTS / AI & MACHINE LEARNING
An end-to-end domain learning journey

LLM Fine-Tuning
& LoRA.

Low-Rank Adaptation (LoRA) freezes a pretrained LLM's weights and trains tiny rank-decomposed adapter matrices, cutting fine-tuning VRAM by 3–10x while preserving base capabilities.
Start the journey7 sections· Last modified Oct 23, 2026
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

When batching and tail latency compete for accelerator cycles, use LoRA/QLoRA when you need consistent domain formatting, tone, or latency-critical distillation into smaller models—not to inject rapidly changing facts (use RAG for that).

TL;DR30-second simplified summary
▾

Core Mechanics: LoRA freezes the pretrained weight matrix W0∈Rd×kW_0 \in \mathbb{R}^{d \times k} and injects a trainable low-rank decomposition ΔW=αrBA\Delta W = \frac{\alpha}{r} B A, where A∈Rr×kA \in \mathbb{R}^{r \times k}, $B \in \mathbb{R}^{d \times.

Visual & Structural Flow: Depicts Frozen Base Weights (W0) + Low-Rank Trainable Branch (B x A) (Hidden State x -> Frozen W0 (NF4) -> Trainable B * A -> Merged h = W0x + dWx); LoRA Training, Eval Gate & Serving Promotion (CURATE DATA -> QLORA TRAIN -> EVAL HARNESS).

Trade-Offs & Production: Choose the lightest adaptation method that matches accuracy and latency SLOs. In production (e.g., vLLM / SGLang), a single GPU cluster hosts one shared base model in HBM while batching requests across dozens of hot-swapped LoRA adapters—or merges a single.

Failure Modes & Application: Explore training stability, GPU KV-cache serving, and model quantization.

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
Prompt Engineering, LLM Reasoning & Thinking Models
Systematic design of system instructions, context layout, delimiters, and constrained output schemas to make LLM behavior reliable, cache-friendly, and production-grade.
Full walkthrough · 7 stages
01
STAGE 01 · WHAT IT ISL4 · FUNDAMENTALS

What is Low-Rank Adaptation (LoRA).

Why this matters: The mechanism: understand how Low-Rank Adaptation (LoRA) works from first principles.

LoRA freezes the pretrained weight matrix W0∈Rd×kW_0 \in \mathbb{R}^{d \times k} and injects a trainable low-rank decomposition ΔW=αrBA\Delta W = \frac{\alpha}{r} B A, where A∈Rr×kA \in \mathbb{R}^{r \times k}, B∈Rd×rB \in \mathbb{R}^{d \times r}, and r≪min⁡(d,k)r \ll \min(d, k) (typically r=8r = 8 to $64$).

Because only AA and BB (<1% of total parameters) receive gradients and AdamW optimizer states, QLoRA (4-bit NF4 frozen base weights + paged optimizers) fits a 70B model into ~48 GB VRAM instead of >1 TB.

LoRA Forward & Adapter Merge

Frozen Base Weights (W0) + Low-Rank Trainable Branch (B x A)

Hidden State xd-dim activationFrozen W0 (NF4)No grad / optimizerTrainable B * ARank r=16 (alpha/r)Merged h = W0x +dWxZero inference…

1.1. All Linear Layers: Targeting q/k/v/o_proj plus MLP gate/up/down_proj consistently beats attention-only LoRA.

2.2. Zero-Latency Merge: At serving time, W' = W0 + (alpha/r)BA merges offline so inference adds zero extra FLOPs.

3.3. Multi-Tenant Adapters: Keep W0 shared in VRAM and hot-swap tiny 50 MB LoRA adapters per tenant.

LoRA slashes optimizer VRAM by 3–10x during training and merges cleanly into W0 for zero-overhead serving.

02
STAGE 02 · WHY WE NEED ITL4 · FUNDAMENTALS

Why full fine-tuning is prohibitive—and where LoRA fails.

Why this matters: The problem: see what breaks without Why full fine-tuning is prohibitive—and where LoRA fails under real concurrency or scale.

Full fine-tuning of a 70B model requires >1 TB of GPU memory for FP16 weights, gradients, and 8-byte AdamW momentum/variance states, while risking catastrophic forgetting.

Even with LoRA, two failure modes dominate production runs: chat template / EOS token mismatch (omitting <|eot_id|> causes endless rambling) and overfitting after 8–10 epochs on narrow datasets.

Engineering Decision Framework
Problem
How to implement LLM Fine-Tuning & LoRA without hitting unbounded tail latency, state divergence, or operational fragility.
Naive Solution
Use a single unpartitioned path with unbounded retries and synchronous global coordination.
Why It Fails
Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
Alternatives
Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
Engineering Decision
When batching and tail latency compete for accelerator cycles, use LoRA/QLoRA when you need consistent domain formatting, tone, or latency-critical distillation into smaller models—not to inject rapidly changing facts (use RAG for that).
Trade-Offs
Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
Decision Exercise · Make the Call

When LLM Fine-Tuning & LoRA experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

1–3 Epochs + Replay Mix

Train for 1–3 epochs and mix in 10–20% general instruction replay data to preserve general reasoning and refusal behavior.

Completion-Only Loss Masking

Use DataCollatorForCompletionOnlyLM so loss is computed only on assistant tokens, not system/user prompt boilerplate.

03
STAGE 03 · WHERE IT IS USEDL5 · APPLIED DESIGN

When to Fine-Tune vs. When to Use RAG.

Why this matters: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

Think of When to Fine-Tune vs. When to Use RAG as the intuition layer for LLM Fine-Tuning & LoRA: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

Fine-tuning teaches form, style, DSL syntax, and distilled reasoning; RAG supplies fresh, mutable facts.

Design Trade-Off

When to Fine-Tune vs. When to Use RAG

Before · Static Batch + Raw Prompt
  • Head-of-line blocking on long prompts
  • O(N^2) KV fragmentation
  • Unfiltered RAG leaks ACLs
After · PagedAttention + Guardrails
  • Zero-waste paged KV blocks
  • Pre-retrieval ACL & RRF rerank
  • Continuous batching boosts tok/s
ChoiceWhat it buysWhat it costs
Good Candidate: Schema / DSL & DistillationDistilling frontier traces into an 8B–14B model cuts serving latency and cost by 5–15x.Requires 500+ clean, diverse, verified training examples.
Avoid: Mutable Facts & Product CatalogsUse RAG + vector retrieval when knowledge changes daily; fine-tuning still hallucinates facts.Re-training adapters for every policy or inventory update is slow and brittle.
04
STAGE 04 · HOW IT IS MANAGEDL5 · APPLIED DESIGN

Configuring QLoRA with PEFT & Target Linear Modules.

Why this matters: Operational control: configure bounds, failure handling, and safe production defaults.

Think of Configuring QLoRA with PEFT & Target Linear Modules as the intuition layer for LLM Fine-Tuning & LoRA: Operational control: configure bounds, failure handling, and safe production defaults.

Quantize the frozen base model to 4-bit NF4, attach LoRA across all attention and MLP linear projections, and initialize B=0B = 0 so ΔW=0\Delta W = 0 at step 0.

Request & State Flow

Configuring QLoRA with PEFT & Target Linear Modules

User / AgentModel RouterVector / PrefixCacheGPU InferenceWorker1. Submit prompt + ACL context2. Fetch KV prefix / hybrid RAGchunks3. Prefill & continuous-batcheddecode4. Stream tokens via SSE +guardrails
from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training

model = prepare_model_for_kbit_training(base_4bit_model)
lora_cfg = LoraConfig(
    r=16,
    lora_alpha=32,
    lora_dropout=0.05,
    bias="none",
    task_type="CAUSAL_LM",
    target_modules=["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"],
)
model = get_peft_model(model, lora_cfg)
model.print_trainable_parameters()  # Typically ~0.5% - 1.2% of total weights
05
STAGE 05 · ALTERNATIVESL6 · SCALE & TRADE-OFFS

Alternatives: BF16 LoRA vs. QLoRA (NF4) vs. Prompt + RAG.

Why this matters: The trade-off: compare competing approaches across latency, consistency, and operational cost.

Think of Alternatives: BF16 LoRA vs. QLoRA (NF4) vs. Prompt + RAG as the intuition layer for LLM Fine-Tuning & LoRA: The trade-off: compare competing approaches across latency, consistency, and operational cost.

Choose the lightest adaptation method that matches accuracy and latency SLOs.

ChoiceWhat it buysWhat it costs
QLoRA (4-bit NF4 Base)Slashes base VRAM ~70% (70B fits in ~48 GB vs ~140 GB).Dequantization slows training throughput by ~20–35% vs BF16.
BF16 LoRA (Rank r=16–64)Faster training step time and higher capacity for complex code/DSL tasks.Requires multi-GPU VRAM for 30B–70B base weights.
Prompt Engineering + Prefix CachingZero training pipeline; instant iteration in minutes.Long few-shot prompts increase input token cost and TTFT.
06
STAGE 06 · PRODUCTION ARCHITECTUREL7 · STAFF / PRINCIPAL

Multi-LoRA Serving & Eval-Gated Promotion.

Why this matters: Production architecture: see how the components compose end to end under real load.

Think of Multi-LoRA Serving & Eval-Gated Promotion as the intuition layer for LLM Fine-Tuning & LoRA: Production architecture: see how the components compose end to end under real load.

In production (e.g., vLLM / SGLang), a single GPU cluster hosts one shared base model in HBM while batching requests across dozens of hot-swapped LoRA adapters—or merges a single high-traffic distilled adapter directly into W0 for peak throughput.

Adapter Lifecycle

LoRA Training, Eval Gate & Serving Promotion

Mask prompt tokensCheckpoint adapterForgetting -> add replayCURATE DATAChat template + dedupQLORA TRAIN1-3 epochs + replayEVAL HARNESSTask + general suite

Every LoRA checkpoint must pass both task-specific accuracy and general-capability regression evals before serving.

07
STAGE 07 · PROBLEMS SOLVED & FURTHER DEEP DIVEL7 · STAFF / PRINCIPAL

Related ML Systems Problems & Concepts.

Why this matters: Applied problems: connect these internals to concrete system design and debugging scenarios.

Think of Related ML Systems Problems & Concepts as the intuition layer for LLM Fine-Tuning & LoRA: Applied problems: connect these internals to concrete system design and debugging scenarios.

Explore training stability, GPU KV-cache serving, and model quantization.

Component Topology

Related ML Systems Problems & Concepts

Caller / AgentingressLLM GatewaycomputeRadix / VectorstorageGPU Poolcontrolpromptprefix / RAGbatched decode
Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

When is RAG a better choice than LoRA fine-tuning?

Recommended Learning Flow