惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

T
Troy Hunt's Blog
Blog — PlanetScale
Blog — PlanetScale
Engineering at Meta
Engineering at Meta
F
Full Disclosure
Recorded Future
Recorded Future
The GitHub Blog
The GitHub Blog
Microsoft Security Blog
Microsoft Security Blog
GbyAI
GbyAI
博客园_首页
博客园 - 叶小钗
MongoDB | Blog
MongoDB | Blog
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Recent Commits to openclaw:main
Recent Commits to openclaw:main
H
Hacker News: Front Page
人人都是产品经理
人人都是产品经理
The Cloudflare Blog
博客园 - 司徒正美
Webroot Blog
Webroot Blog
Google DeepMind News
Google DeepMind News
Help Net Security
Help Net Security
Cloudbric
Cloudbric
PCI Perspectives
PCI Perspectives
有赞技术团队
有赞技术团队
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
TaoSecurity Blog
TaoSecurity Blog
L
Lohrmann on Cybersecurity
量子位
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
T
Tailwind CSS Blog
Hacker News - Newest:
Hacker News - Newest: "LLM"
B
Blog RSS Feed
Apple Machine Learning Research
Apple Machine Learning Research
大猫的无限游戏
大猫的无限游戏
P
Proofpoint News Feed
N
News and Events Feed by Topic
罗磊的独立博客
T
Threat Research - Cisco Blogs
Schneier on Security
Schneier on Security
T
Tor Project blog
IT之家
IT之家
M
MIT News - Artificial intelligence
S
Security @ Cisco Blogs
O
OpenAI News
AI
AI
S
Securelist
Simon Willison's Weblog
Simon Willison's Weblog
The Last Watchdog
The Last Watchdog
月光博客
月光博客
Security Archives - TechRepublic
Security Archives - TechRepublic
L
LINUX DO - 热门话题

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Fine-Tuning Large Language Models: A Practical Guide
M TOQEER ZIA · 2026-06-16 · via DEV Community

What Is Fine-Tuning?

A pre-trained model learns from billions of tokens of general text. It develops broad language understanding. Fine-tuning takes that base model and trains it further on a smaller, task-specific dataset.

The result: a model that performs well on your specific use case, whether that is medical diagnosis, legal summarization, customer support, or code generation.

Fine-tuning is not training from scratch. You preserve general knowledge and adapt behavior.


How a Neural Network Learns

Before fine-tuning makes sense, you need to understand what happens inside a neural network during training.

A neural network is a system of layers. Each layer contains nodes (neurons). Each connection between nodes has a weight. These weights determine what the network outputs given any input.

At the start, weights are random. Training adjusts them so the network produces correct outputs.

Here is the full training loop:

Training Data
      ↓
Forward Pass
      ↓
Prediction
      ↓
Loss Calculation
      ↓
Backpropagation
      ↓
Gradient Calculation
      ↓
Weight Update
      ↓
Repeat
      ↓
Trained Model


Phase 1: Forward Pass

The model receives an input (a sentence, an image, a token). Data flows forward through every layer. Each neuron applies a mathematical function and passes its result to the next layer.

At the end, the model produces a prediction. For a language model, this is a probability distribution over the next token.

No learning happens here. This phase only produces output.


Phase 2: Loss Calculation

The model's prediction is compared to the correct answer. A loss function measures how wrong the prediction is.

Common loss functions:

  • Cross-entropy loss: used for classification and language modeling
  • Mean squared error: used for regression tasks

A high loss means the model is far off. A loss near zero means the prediction was close to correct.

The loss is a single number. It summarizes the error for one batch of data.


Phase 3: Backpropagation

This is where learning begins.

Backpropagation works backward through the network. It calculates how much each weight contributed to the total loss. The math tool used here is the chain rule from calculus.

Think of it as blame assignment. Each weight receives a gradient: a number that says "changing this weight by X changes the loss by Y."

A large gradient means that weight had a big effect on the error. A small gradient means it had little effect.


Phase 4: Gradient Calculation

After backpropagation, every weight in the network has a gradient.

The gradient is a vector. It points in the direction of steepest increase in loss. To reduce the loss, you move in the opposite direction.


Phase 5: Weight Update (Optimization)

An optimizer uses the gradients to update every weight.

The most basic optimizer is Stochastic Gradient Descent (SGD):

new_weight = old_weight - (learning_rate × gradient)

The learning rate controls the step size. Too large: the model overshoots. Too small: training takes too long.

Modern optimizers like Adam adjust the learning rate automatically for each weight. Adam tracks the history of gradients and adapts accordingly. It converges faster than basic SGD in most cases.


The Full Loop

One pass through the data is one epoch. Training repeats this loop thousands of times across many epochs. With each pass, the weights improve. The loss decreases. The model gets better at the task.


Types of Fine-Tuning

There are three main approaches. They differ in what gets updated during training.


1. Full Fine-Tuning

All weights in the model are updated.

You take the pre-trained model and run the training loop on your dataset. Every parameter is fair game. The optimizer adjusts all of them.

Advantages:

  • Maximum flexibility
  • Best performance ceiling for large datasets

Disadvantages:

  • Requires significant GPU memory (storing the model, gradients, and optimizer states for billions of parameters)
  • Expensive and slow
  • Risk of catastrophic forgetting: the model overwrites general knowledge with task-specific patterns
  • A 7B parameter model at full precision requires roughly 28 GB of GPU memory for weights alone, plus optimizer states

Full fine-tuning makes sense when you have large datasets and substantial compute.


2. PEFT (Parameter-Efficient Fine-Tuning)

PEFT is a family of methods. The core idea: freeze most of the model and only train a small number of parameters.

You add new, trainable components to the frozen model. Only those new components are updated. The original weights stay fixed.

This reduces:

  • GPU memory required (no gradients for frozen weights)
  • Training time
  • Risk of catastrophic forgetting

PEFT methods include LoRA, prefix tuning, prompt tuning, and adapter layers. LoRA is the most widely used.


3. LoRA (Low-Rank Adaptation)

LoRA is the dominant PEFT method in 2024 and 2025.

The insight behind LoRA: weight updates during fine-tuning tend to have low intrinsic rank. You do not need to update a full weight matrix. You approximate the update with two much smaller matrices.

How it works:

For a weight matrix W of size (m × n), instead of updating W directly, LoRA adds two matrices:

  • Matrix A: size (m × r)
  • Matrix B: size (r × n)

Where r is the rank, typically 4, 8, 16, or 64. You only train A and B. The product AB approximates the full weight update.

During inference, the update is merged back: W_new = W + AB

Parameter count comparison:

A weight matrix of size 4096 × 4096 has 16,777,216 parameters.
LoRA with rank 8 adds two matrices: (4096 × 8) + (8 × 4096) = 65,536 parameters.
That is a 256x reduction in trainable parameters for that layer.

Advantages:

  • Trains on consumer GPUs (a 7B model with LoRA fits on 8-16 GB VRAM)
  • Multiple LoRA adapters for different tasks, swapped at inference time
  • The base model stays frozen and reusable

Disadvantages:

  • Slightly below full fine-tuning on performance in some benchmarks
  • Requires choosing rank (r) and which layers to target

4. QLoRA (Quantized LoRA)

QLoRA combines quantization with LoRA. It pushes LoRA further in terms of memory efficiency.

What quantization does:

Standard model weights use 16-bit or 32-bit floating point numbers. Quantization converts them to lower precision: 8-bit, 4-bit, or even 3-bit integers.

A 7B model in 16-bit uses roughly 14 GB of memory. The same model in 4-bit uses roughly 3.5 GB.

QLoRA workflow:

  1. Load the base model in 4-bit precision (NF4 format, designed for neural network weights)
  2. Freeze all quantized weights
  3. Add LoRA adapters in 16-bit precision
  4. Train only the LoRA adapters

The gradients flow through the quantized model, through the LoRA adapters. Only the adapters are updated.

Double quantization: QLoRA applies a second round of quantization to the quantization constants themselves, saving an additional 0.5 GB on a 7B model.

Advantages:

  • Fine-tune a 70B model on a single 48 GB GPU
  • Fine-tune a 7B model on a single 8 GB consumer GPU
  • Performance within 1-2% of full fine-tuning on most benchmarks

Disadvantages:

  • Slower than LoRA (dequantization overhead during forward/backward pass)
  • Quantization introduces approximation errors

Comparison Table

Method Trainable Params VRAM (7B model) Performance Use Case
Full Fine-Tuning 100% 80+ GB Highest Large datasets, max compute
PEFT (general) 0.1 - 1% Varies Good Resource-constrained
LoRA 0.1 - 1% 16-24 GB Near full Most fine-tuning tasks
QLoRA 0.1 - 1% 6-10 GB Near LoRA Consumer GPU fine-tuning

Choosing the Right Method

Start with QLoRA if you are on a single GPU with less than 24 GB VRAM. It lets you work with models up to 13B or 30B parameters.

Use LoRA if you have 24-40 GB VRAM and want faster training than QLoRA.

Use full fine-tuning if you have a multi-GPU setup, a large high-quality dataset (100k+ samples), and need maximum task performance.


Key Hyperparameters in Fine-Tuning

Learning rate: Typically much lower for fine-tuning than pre-training. Common range: 1e-5 to 3e-4. Too high and you destroy pre-trained representations.

Rank (r) in LoRA: Higher rank captures more complex updates but uses more memory. Start with 8 or 16.

LoRA alpha: Scales the LoRA update. Common setting: alpha = 2 × rank.

Epochs: Fine-tuning usually needs far fewer epochs than pre-training. 1 to 5 epochs on domain-specific data is typical.

Batch size: Larger batches give smoother gradients. Use gradient accumulation if your GPU limits batch size.


What Makes Good Fine-Tuning Data

Data quality matters more than quantity.

  • 1,000 high-quality examples often outperform 100,000 noisy ones
  • Format your data to match the task: instruction-response pairs for chat models, completions for base models
  • Balance your dataset across categories to avoid the model over-indexing on one topic
  • Remove duplicates; they waste training compute and bias the model

Summary

Neural networks learn by repeating a loop: forward pass, loss calculation, backpropagation, gradient calculation, weight update. Fine-tuning runs this loop on task-specific data starting from a pre-trained model.

Full fine-tuning updates everything. PEFT methods freeze most weights. LoRA approximates weight updates with low-rank matrices. QLoRA adds quantization to push memory requirements lower.

Your choice depends on your GPU, your dataset size, and your performance target.