Fine-Tuning Small Language Models

From classic neural networks to LLMs — and a live demo



Jude Michael Teves

Introduction

What if your dev tools knew your codebase?

Generic LLM today

  • Trained on massive public datasets
  • Doesn't know your ticket format
  • Doesn't know your conventions
  • Answers everything — even off-topic

Fine-tuned model

  • Responds in your team's format
  • Calls tools you define
  • Refuses off-topic questions
  • Runs locally — data stays with you

Fine-tuning doesn't change what the model knows.
It changes how it behaves — format, tone, tools, and guardrails.

Mental Model

Two Very Different Things

Pretraining

📚 Trained on a massive corpus

  • Web pages, books, code, Wikipedia, papers
  • Trillions of tokens — not literally the whole internet
  • Filtered, curated subsets of public data
  • Months on thousands of GPUs — massive capital expenditure
  • Major AI labs and big tech companies do this
Fine-Tuning

🎯 Customizing to your use case

  • Your examples, your format, your tools
  • Hours on one GPU — or minutes for SLMs
  • The model already knows how to reason
  • We teach it how to respond, not what to know
  • Smaller teams and companies can do this

We're not teaching it Python. It already knows Python.
We're teaching it your version of how to respond.

A Brief History

The Lineage That Got Us Here

🔵 Early DL & CV (2012–2017) 🟣 Language & Scale (2018–2022) 🟢 Open & Efficient Era (2023–now)
1

2012 — AlexNet

Deep CNNs prove learned features transfer. CV leads the transfer learning wave.

2

2013–14 — Word2Vec + Seq2Seq

Language gets vector representations. Encoder-decoder for translation (attention added by Bahdanau 2015). Generative models (GANs) emerge.

3

2014–15 — VGG + ResNet

VGGNet (2014) and ResNet (2015) become the go-to pretrained backbones. Skip connections unlock very deep networks. CV transfer learning — freeze pretrained base, retrain head — becomes the standard recipe. Demo uses this era.

4

2017 — Transformers

Attention is All You Need. Self-attention proved superior to RNNs at scale and eventually displaced them. Everything modern runs on this architecture.

5

2018 — BERT / GPT-1 / ULMFiT

Transfer learning arrives in NLP. Pretrain on text → SFT (supervised fine-tuning) on tasks. Same paradigm as CV, 3 years later.

6

2020 — GPT-3 + Scaling Laws

175B params. Emergent few-shot capability without fine-tuning. Performance scales predictably with data, compute, and model size.

7

2022 — InstructGPT → ChatGPT

OpenAI's SFT + RLHF pipeline teaches the model to follow instructions — not just predict text. The recipe behind ChatGPT. LoRA (2021 paper) is a separate, unrelated development.

8

2023 — LoRA + open model ecosystem

LoRA paper (2021) took off when Llama, Mistral, Falcon were released openly. Suddenly anyone could fine-tune a capable model cheaply. This is what we're doing today.

9

2024–25 — Reasoning + MoE

o1 (Sept 2024): chain-of-thought as trained behavior. DeepSeek-V3 (MoE, 671B, Dec 2024) + DeepSeek-R1 (reasoning, Jan 2025): frontier-level results from open models. MoE enables massive models on manageable hardware.

10

2025–26 — Agentic AI + SLMs go local

Models now plan, use tools, and act autonomously — not just chat. SLMs run locally* on consumer hardware. Phi-3 Mini (3.8B, 2024) ≈ GPT-3.5 on specific tasks. Quantization compresses 754B models to fit a workstation.

Context — Small Language Models

What is an SLM — and why use one?

Large Language Models (LLMs)

  • GPT-4: undisclosed size — likely MoE, estimated hundreds of billions
  • Llama 3 70B — requires multi-GPU servers
  • Powerful but expensive to run and fine-tune
  • Can't run on a laptop or cheap cloud GPU

Small Language Models (SLMs)

  • Typically <7B params — often 1B–3B for demos
  • Phi-3 Mini (3.8B), Llama 3.2 (1B/3B), Qwen2.5 (0.5B–7B)
  • Run on a laptop, a phone, or a Colab free-tier GPU
  • Fast to fine-tune — minutes to hours with LoRA
  • Getting more capable fast — data quality beats raw scale

SLMs are closing the gap: Phi-3 Mini (3.8B) matches GPT-3.5 on many benchmarks. A focused, well-trained small model today can match a large one from 1–2 years ago — on specific tasks. For broad reasoning, bigger still wins.

Why SLM for Fine-tuning?

FactorSLM ✓LLM ✗
HardwareFree T4 GPUMulti-GPU cluster
Training timemins–hours (config-dependent)Days–weeks
PrivacyFully localOften cloud API
Data neededDozens of examplesThousands+
CostLow compute (fits free tier)$$–$$$

The tradeoff: SLMs are less capable. For a proof-of-concept or behavior tuning, they're more than enough.

Context — Training Time Then vs Now

How Long Does It Actually Take?

Task Era Hardware Time
Train ResNet from scratch (ImageNet) 2015–2016 4–8 GPUs Days
Fine-tune ResNet (CV transfer learning) 2016–2018 1–2 GPUs Hours–days
Pretrain BERT (full) 2018 64 TPUs, 4 days Days
Fine-tune BERT (downstream task) 2018–2020 1 GPU Hours
Pretrain GPT-3 / Llama 70B 2020–2023 Thousands of GPUs Months
Full fine-tune large LLM (7B+) 2023–now Multi-GPU server Days–weeks
LoRA fine-tune SLM (1B–3B) ← today 2023–now Free T4 GPU Minutes–hours
Context — Approaches to Fine-Tuning

Full Retraining vs Fine-Tuning vs LoRA

Approach What changes When to use Cost
Full Pretraining from scratch All weights, random init Building a new model entirely. Nobody does this casually. Millions of $$$
Full Fine-Tuning All weights, pretrained init You have lots of domain data and serious compute. Risk: catastrophic forgetting. $$–$$$
Partial Fine-Tuning Top layers only (like classic CV) Classic transfer learning approach. Faster than full, but still touches the base model. $–$$
LoRA (Parameter-Efficient) Tiny adapter only — base frozen Fine-tuning behavior, format, tools. Small datasets. Local hardware. Low compute
RAG (not fine-tuning) Nothing — retrieves at inference When you need live facts, doc search, or a knowledge base. Different tool entirely. $

Fine-tuning shapes behavior. RAG shapes knowledge. They solve different problems and often complement each other.

02
The Old Way

Transfer Learning
in Computer Vision

MobileNetV2 · CIFAR-10 · Keras

Part 2 — Context

Image Classification: From Scratch vs. Pretrained

Baseline: CNN from scratch
  • CIFAR-10 dataset — 5k train / 1k test
  • Conv2D → MaxPool → Dense stack
  • 89k trainable params, random init
  • 10 epochs → ~52% accuracy
With Transfer Learning: MobileNetV2
  • Pretrained on ImageNet (1.2M images)
  • Freeze base → add classification head
  • Only top layers retrained
  • Same 5k samples → ~89% accuracy
# Freeze pretrained weights — base model not modified
base_model = keras.applications.MobileNetV2(include_top=False, weights='imagenet')
base_model.trainable = False   # conceptually similar to LoRA, but less efficient

# Add your task-specific head on top
x = layers.GlobalAveragePooling2D()(base_model.output)
x = layers.Dropout(0.2)(x)
predictions = layers.Dense(10, activation='softmax')(x)
Part 2 — Demo

🎬 Let's look at the notebook

What to watch for

  • Training a CNN from scratch — ~52% accuracy ceiling on small data
  • Loading MobileNetV2 weights pretrained on ImageNet
  • base_model.trainable = False — freezing the base
  • Adding a custom classification head on top
  • Same 5k samples — accuracy jumps to ~89%

This required understanding CNN architectures, Keras APIs, preprocessing, and training dynamics. Technical depth was — and still is — required. The tools got faster; the understanding needed to use them well hasn't gone away.

github.com/Cyntwikip/Machine-Learning — transfer_learning.ipynb

Bridge

Three Eras of ML in Practice

Era 1 · Classic Fine-tuning

Pre-2022 — CV & NLP

  • Full weight updates, GPU clusters
  • Weeks to months per iteration
  • Heavy ML engineering overhead
  • Separate full model per task
  • Catastrophic forgetting on small data

Agents: not yet a practical concept at scale

Era 2 · The API Era

2022–2023 — LLMs + RAG

  • "Just call the API" — no model training
  • Prompt engineering + vector DBs + RAG
  • SWE-friendly, minimal ML needed
  • Full vendor dependency, black-box behavior
  • Data stays on their infra

Agents: possible but API-dependent — vendor controls the model's behavior

Era 3 · Fine-tuning Returns

2024–now — LoRA + SLMs

  • Train only ~1% of parameters
  • Single GPU, minutes–hours for SLMs
  • Own your weights and behavior
  • Reduce vendor lock-in
  • Tiny adapter file, swappable per task

Agents: SLMs run locally as agents — sovereign, controllable, no API dependency

The tooling is faster. The expertise required to use it well isn't going away.
DE gets you the data. SWE brings it to production. The layer in between — quality judgment, evaluation design, training dynamics, statistical interpretation — is where DS/ML expertise takes over.

03
The Highlight

SLM Fine-Tuning
Today

LoRA · Coding Assistant · Tool Calling · Guardrails

Part 3 — LoRA

LoRA: Low-Rank Adaptation

Instead of retraining all 1 billion weights, you attach a small adapter to specific layers and only train that.


Think of it as sticky notes on a textbook — you're not rewriting the book, just adding annotations that change how it answers you.


~10-12M trainable params 1B base frozen ~20-25MB adapter file this demo: ~3 min on T4

What LoRA attaches to

  • q_proj, k_proj, v_proj — attention queries, keys, values
  • o_proj — attention output projection
  • gate_proj, up_proj, down_proj — feed-forward layers

All other weights stay frozen. The adapter is a separate file — can be loaded onto any copy of the same base model.

Part 3 — LoRA vs Full Fine-Tuning

Comparing Approaches

Full Fine-TuningLoRA (what we're doing)
Params updatedAll — 1B+ weights~10-12M (~1% of model)
GPU requirementMultiple high-end GPUsSingle T4 (Colab free tier)
Training timeHours to daysMinutes to hours
Storage per taskFull model copy (~2GB+)Small adapter (~20-25MB)
Base modelModified — needs separate backupUntouched — adapter is separate
Catastrophic forgettingReal risk on small datasetsMinimized — base frozen
Multi-taskSeparate full model per taskSwap adapters on same base
Part 3 — What Matters Most

Key Parameters to Know

ParameterValueWhy it matters
r (rank)16Size of adapter matrices. Higher = more expressive, slower. 16 is a safe default for behavior/format tuning.
load_in_4bitTrueQuantizes base model to 4-bit (from 16-bit) — reduces weight storage ~4×. Without this, 1B model won't fit on a T4.
max_steps60Total gradient updates. Overrides epochs. With 31 examples, batch 8 → ~4 steps/epoch → 15 epochs total.
gradient_accumulation4Effective batch = 2 × 4 = 8. Simulates larger batches without extra VRAM — common trick on constrained hardware.
train_on_responses_onlyenabledGuardrail — masks user/system tokens. Model only learns from assistant outputs.

Full parameter list in appendix →

Part 3 — The Skills That Don't Go Away

The Tools Got Faster. The Judgment Didn't.

Data quality — a statistics problem, not a pipeline problem

  • Is your sample representative of what the model will see in production?
  • Are labels consistent? Inter-rater agreement matters even with one labeler
  • Writing examples that teach the intended pattern — not a surface shortcut the model exploits
  • Knowing when 31 is enough for behavior, and when you need hundreds more

This is where DE hands off to DS/ML — and where the work stops being a pipeline problem.

Evaluation — not just vibes

  • Choosing the right metric for your task — accuracy, F1, ROUGE, perplexity all measure different things
  • Statistical significance — did it actually improve or did you get lucky?
  • Eval set leakage — one of the most common silent mistakes
  • Knowing when a model is overfitting vs. genuinely generalizing

Training dynamics

  • Reading a loss curve — when to stop, when it's diverging
  • Recognizing catastrophic forgetting vs. expected behavior shift
  • Understanding what each hyperparameter actually does, not just copying defaults
  • Debugging when the model learns the wrong thing

Reality: Developing intuition for all of this — data quality, training dynamics, meaningful eval — takes weeks to months of hands-on iteration. The fine-tuning loop can run in minutes for a small demo config. The judgment to run it well still doesn't come fast.

Part 3 — Dataset

Training Dataset: 31 Examples, 3 Categories

Direct Answers ×12

Model answers immediately. No tool needed.


"How do I reverse a list?"
"What is a decorator?"
"Explain list comprehensions"

Tool Calls ×16

Model outputs a <tool_call> block.


lookup_error run_snippet fetch_docs suggest_library search_codebase code_and_run ✨

Refusals ×3

Off-topic questions get a polite decline.


"What's the weather today?"
"Write me a poem."
"What should I have for lunch?"

code_and_run — natural language → model generates Python → executes it → returns output. End-to-end in one tool call.

Part 3 — Live Demo

🎬 Notebook Demo

01_train.ipynb

  • Load Llama-3.2-1B-Instruct
  • Attach LoRA adapter (~10-12M params)
  • Load dataset.json from Drive
  • Train — 60 steps (~3 min on T4 for this config)
  • Save adapter to Drive

02_inference.ipynb

  • Run 4 prompts on base model
  • Load fine-tuned adapter from Drive
  • Run same 4 prompts on fine-tuned
  • Side-by-side pandas comparison table
  • Live code_and_run execution

WATCH FOR

Base model answers the weather question Fine-tuned refuses it cleanly Raw <tool_call> block in output code_and_run actually executes Python
Part 3 — Guardrails

Built-in Guardrails

train_on_responses_only

Masks all user and system tokens during training. The model only learns from assistant outputs — can't accidentally learn to act like a user or repeat the system prompt.

Adapter isolation

The LoRA adapter is a separate file. Roll back, swap, or A/B test multiple adapters on the same base without touching the original weights.

System prompt alignment

Every training example carries a system prompt. The model internalizes this as default behavior: only answer coding questions, decline everything else.

Runs entirely locally. No data leaves your machine.
Relevant when working with internal codebases or sensitive data.

04
So What?

Where This Goes
for Dev Work

…and what to keep in mind

Part 4 — Applications

What This Enables (eventually)

Code workflows

  • Commit message generation
  • PR / diff summaries
  • Code review in your team's style

Internal knowledge

  • Ticket triage / classification
  • Domain-specific Q&A (paired with RAG)
  • Log parsing and error summarization

Team conventions

  • Enforces your naming standards
  • Responds in your ticket format
  • Trained on your patterns, not the internet's

All trainable on your own data, on your own machine —
but this is prototyping scale, not a production deployment.

Part 4 — Why It Matters Beyond the Demo

Owning Your Models: AI Sovereignty

The risk of full API dependency

  • GPT-3 deprecated March 2024 — products built on it had to migrate
  • PaLM API deprecated October 2024
  • Pricing, rate limits, and model behavior can change unilaterally
  • Your data and prompts may leave your environment
  • You can't audit what changed between model versions

What a fine-tuned SLM gives you

  • Fixed, auditable behavior — your adapter, your weights
  • Runs fully offline — no data leaves your infra
  • No vendor deprecation can break your pipeline
  • Portable: swap it onto any copy of the same base model
  • A starting point for genuine internal AI tooling

Sovereign AI is an emerging institutional priority — the goal is reducing dependency on vendor infrastructure and keeping critical AI workflows under your own control. Owning a fine-tuned model is a concrete first step toward that.

Part 4 — Before You Ship

Things Worth Knowing before going to prod

Toy dataset = toy results

31 examples teaches format and behavior. Real production fine-tuning needs hundreds to thousands of quality examples and a proper evaluation pipeline — not just eyeballing the output.

Fine-tuning ≠ knowledge base

Fine-tuning shapes how it responds, not what facts it reliably knows. Small static policies can be baked in — but the model may still paraphrase or partially hallucinate them with confidence. RAG gives you exact retrieval and auditability even for static docs. Best practice: fine-tune for behavior, RAG for facts.

Still hallucinates

Fine-tuning doesn't fix hallucination. A 1B model will still produce plausible-sounding wrong answers. Always verify generated code before running it in production.

Technical understanding is still required. The tools got faster —
knowing what good training data looks like and how to evaluate results doesn't go away.

Q&A

Thanks! Questions?

unsloth.ai/docs Llama 3.2 Colab: unsloth.ai/docs/get-started MLX local: github.com/ml-explore/mlx-examples

Jude Michael Teves

Appendix
Full Parameter Reference

All Training Parameters

LORA CONFIG

ParamValue
r16
lora_alpha16
lora_dropout0
bias"none"
use_gradient_checkpointing"unsloth"
load_in_4bitTrue

TRAINING CONFIG

ParamValue
max_steps60
per_device_train_batch_size2
gradient_accumulation_steps4
learning_rate2e-4
warmup_steps5
weight_decay0.01
lr_scheduler_type"linear"
optim"adamw_8bit"
train_on_responses_onlyenabled