Why Run LLMs on Raspberry Pi?

Imagine having a private AI assistant that: - Works completely offline (no internet needed) - Runs on a $60 single-board computer - Never sends your data to the cloud - Can answer questions about your documents - Controls your smart home via voice

With AirLLM, you can run large language models on Raspberry Pi 5 (8GB version) using only CPU power—no GPU required.


Hardware Requirements

  • Raspberry Pi 5: 8GB RAM model (4GB works for smaller models)
  • Storage: 32GB+ microSD card (USB 3.0 SSD recommended for speed)
  • Cooling: Active cooling fan (Pi 5 runs hot under load)
  • Power: 5V/5A USB-C power supply (quality matters!)

Why Raspberry Pi 5?

The Pi 5 offers significant upgrades over Pi 4: - CPU: BCM2712, quad-core Cortex-A76 @ 2.4GHz (2-3x faster than Pi 4) - Memory: LPDDR4x-4266 with higher bandwidth - USB: 2x USB 3.0 ports (5Gbps theoretical) - PCIe: 1x PCIe 2.0 x1 for fast NVMe SSDs

💡 Note: Raspberry Pi 4 (8GB) can run 3B-7B models but slower. Pi 4 (4GB) is limited to 1B-3B models.


Step 1: System Preparation

Install Raspberry Pi OS (64-bit)

  1. Download Raspberry Pi OS Lite (64-bit)
  2. Flash to microSD card using Raspberry Pi Imager
  3. On first boot, run sudo raspi-config to: - Set locale and timezone - Enable SSH - Expand filesystem

Update and Install Dependencies

BASH
sudo apt update && sudo apt upgrade -y
sudo apt install -y python3-pip python3-venv git build-essential

# Create virtual environment
python3 -m venv airllm-env
source airllm-env/bin/activate

# Upgrade packaging tools
pip install --upgrade pip setuptools wheel

Step 2: Install AirLLM

Install AirLLM and optional dependencies:

BASH
# Core installation
pip install airllm

# Optional: for quantized inference (faster, small precision loss)
pip install -U bitsandbytes

# Verify installation
python3 -c "from airllm import AutoModel; print('AirLLM installed successfully!')"

⚠️ ARM Compatibility Note: If you encounter issues, try: bash pip install numpy torch --index-url https://download.pytorch.org/whl/cpu


Step 3: Download and Run Models

Choosing the Right Model

For Raspberry Pi 5 (8GB), these models work well: - Phi-3-mini-4k-instruct (3.8B): Great balance of speed/quality - Gemma-2-2b-it (2B): Very fast, good for simple tasks - Qwen2.5-3B-Instruct (3B): Strong multilingual capabilities - TinyLlama-1.1B-Chat-v1.0 (1.1B): Fastest but limited capabilities

We'll use Phi-3-mini-4k-instruct (3.8B parameters) as our example:

BASH
# Create models directory
mkdir -p ~/models && cd ~/models

# Download model (first run will be slow - downloads ~7GB)
python3 -c "
from airllm import AutoModel
model = AutoModel.from_pretrained('microsoft/Phi-3-mini-4k-instruct')
print('Model downloaded and initialized!')
"

First Test: Hello World

Create test_airllm.py:

PYTHON
from airllm import AutoModel
import time

print("Loading model...")
start = time.time()
model = AutoModel.from_pretrained("microsoft/Phi-3-mini-4k-instruct")
print(f"Model loaded in {time.time() - start:.1f} seconds")

prompt = "Explain artificial intelligence in one sentence"
print(f"\nPrompt: {prompt}")

print("\nGenerating response...")
start = time.time()
output = model.generate([prompt], max_new_tokens=50, temperature=0.7, do_sample=True)
print(f"Generation took {time.time() - start:.1f} seconds")

response = model.tokenizer.decode(output[0], skip_special_tokens=True)
# Remove the prompt from the response
if prompt in response:
    response = response[len(prompt):].strip()

print(f"\nResponse: {response}")

Run it:

BASH
python3 test_airllm.py

⏱️ First Run Warning: Initial run downloads the model (~7GB for Phi-3), which may take 10-30 minutes depending on your internet speed. Subsequent starts will be much faster as it uses cached model files.


Performance Benchmarks (Pi 5 8GB)

Model Parameters Load Time Tokens/sec RAM Usage
Phi-3-mini 3.8B ~45 sec 2.1-2.8 ~5.2GB
Gemma-2-2b 2B ~20 sec 3.5-4.2 ~3.8GB
Qwen2.5-3B 3B ~30 sec 2.5-3.2 ~4.5GB
TinyLlama 1.1B ~10 sec 5.0-6.5 ~2.5GB

Test Conditions: - Ambient temperature: 25°C with active cooling - Generation length: 50 tokens - Temperature: 0.7 - Storage: USB 3.0 SSD

Optimization Tips

  1. Use USB 3.0 SSD: 5-10x faster than microSD for model loading
  2. Enable zram (compressed RAM swap): sudo apt install zram-config
  3. Reduce GPU memory: Add gpu_mem=16 to /boot/config.txt
  4. Use systemd service: Keep model loaded in memory for instant response

Step 4: Practical Projects

Project 1: Offline Knowledge Base Q&A

PYTHON
# kb_qa.py
from airllm import AutoModel

class OfflineKBQA:
    def __init__(self, model_name="microsoft/Phi-3-mini-4k-instruct"):
        print("Initializing offline knowledge base...")
        self.model = AutoModel.from_pretrained(model_name)
        self.kb = self._load_kb()

    def _load_kb(self):
        """Simple knowledge base - replace with your documents"""
        return {
            "raspberry pi": "Raspberry Pi is a series of small single-board computers developed in the UK.",
            "airllm": "AirLLM enables running large language models on low-VRAM GPUs via layer-wise inference.",
            "llm": "Large Language Models are AI models with billions of parameters trained on vast text corpora."
        }

    def answer(self, question):
        # Simple keyword match (use embeddings/vector DB for production)
        context = "\n".join([f"{k}: {v}" for k, v in self.kb.items() 
                           if any(word in question.lower() for word in k.split())])

        if not context:
            context = "No specific information found in knowledge base."

        prompt = f"""Based on the following information, answer the question:
{context}

Question: {question}
Answer:"""

        output = self.model.generate([prompt], max_new_tokens=100, temperature=0.3)
        response = self.model.tokenizer.decode(output[0], skip_special_tokens=True)

        if "Answer:" in response:
            return response.split("Answer:")[-1].strip()
        return response.strip()

# Example usage
if __name__ == "__main__":
    qa = OfflineKBQA()
    print(qa.answer("What is Raspberry Pi?"))
    print(qa.answer("How does AirLLM work?"))

Project 2: Voice Assistant

PYTHON
# voice_assistant.py
import speech_recognition as sr
import pyttsx3
from airllm import AutoModel

class VoiceAssistant:
    def __init__(self):
        print("Initializing voice assistant...")

        # Speech components
        self.recognizer = sr.Recognizer()
        self.microphone = sr.Microphone()
        self.tts = pyttsx3.init()

        # Configure TTS
        voices = self.tts.getProperty('voices')
        self.tts.setProperty('voice', voices[0].id)
        self.tts.setProperty('rate', 150)

        # Load model
        self.model = AutoModel.from_pretrained("microsoft/Phi-3-mini-4k-instruct")
        self.history = []

        print("Voice assistant ready! Say 'exit' to quit.")

    def listen(self):
        with self.microphone as source:
            print("\n🎤 Listening...")
            self.recognizer.adjust_for_ambient_noise(source, duration=0.5)
            audio = self.recognizer.listen(source, timeout=5, phrase_time_limit=10)

        try:
            return self.recognizer.recognize_google(audio, language='en-US')
        except:
            return None

    def speak(self, text):
        print(f"🤖 Assistant: {text}")
        self.tts.say(text)
        self.tts.runAndWait()

    def respond(self, user_input):
        # Build conversation context
        history = "\n".join(self.history[-4:])  # Last 4 exchanges
        prompt = f"{history}\nUser: {user_input}\nAssistant:" if history else f"User: {user_input}\nAssistant:"

        output = self.model.generate([prompt], max_new_tokens=150, temperature=0.7)
        response = self.model.tokenizer.decode(output[0], skip_special_tokens=True)

        if "Assistant:" in response:
            return response.split("Assistant:")[-1].strip()
        return response.strip()

    def run(self):
        try:
            while True:
                user_input = self.listen()
                if not user_input:
                    continue

                if user_input.lower() in ['exit', 'quit', 'goodbye']:
                    self.speak("Goodbye!")
                    break

                response = self.respond(user_input)
                self.speak(response)

                # Update history
                self.history.extend([f"User: {user_input}", f"Assistant: {response}"])
        except KeyboardInterrupt:
            print("\nAssistant stopped.")

if __name__ == "__main__":
    VoiceAssistant().run()

📝 Install voice dependencies: ```bash pip install SpeechRecognition pyttsx3 pyaudio

May need: sudo apt install portaudio19-dev python3-pyaudio

```

Project 3: Coding Assistant Terminal

BASH
pip install prompt-toolkit
PYTHON
# coding_assistant.py
from airllm import AutoModel
from prompt_toolkit import PromptSession
from prompt_toolkit.history import FileHistory

def main():
    print("🤖 AirLLM Coding Assistant - Type 'exit' to quit\n")

    model = AutoModel.from_pretrained("microsoft/Phi-3-mini-4k-instruct")
    session = PromptSession(history=FileHistory('~/.coding_assistant_history'))

    while True:
        try:
            user_input = session.prompt("💻 You: ")
            if user_input.lower() in ['exit', 'quit']:
                break
            if not user_input.strip():
                continue

            prompt = f"""You are an expert programmer. Provide clear, working code to solve this request:
{user_input}

Code solution:"""

            print("\n🤖 Thinking...")
            output = model.generate([prompt], max_new_tokens=300, temperature=0.2)
            response = model.tokenizer.decode(output[0], skip_special_tokens=True)

            # Extract code blocks if present
            if "```python" in response:
                start = response.find("```python") + 9
                end = response.find("```", start)
                if end != -1:
                    code = response[start:end].strip()
                    print(f"\n💡 Suggested code:\n{code}\n")
                else:
                    print(f"\n💡 Response:\n{response}\n")
            else:
                print(f"\n💡 Response:\n{response}\n")

        except (EOFError, KeyboardInterrupt):
            print("\n👋 Goodbye!")
            break

if __name__ == "__main__":
    main()

Performance Optimization

Model Selection Guide

Use Case Model Size Expected Speed
General chat Phi-3-mini-4k-instruct 3.8B 2-3 tok/s
Fastest response TinyLlama-1.1B-Chat-v1.0 1.1B 5-6 tok/s
Better quality Gemma-2-2b-it 2B 3-4 tok/s
Multilingual Qwen2.5-3B-Instruct 3B 2 Universally accessible

TL;DR: - AirLLM: Run LLMs on modest hardware — perfect for development, edge devices, learning - llama.cpp: Maximum throughput — ideal for production servers, daily drivers


Real-World Applications

1. Offline Research Assistant

  • Load PDFs, documentation, notes into knowledge base
  • Voice query: "What does section 3.2 say about API authentication?"
  • Zero latency, zero data leakage

2. Home Automation Brain

  • Voice control: "Turn on living room lights to 50% brightness"
  • Context awareness: "It's getting dark, close the blinds"
  • Privacy: All processing happens locally

3. Education Companion

  • Homework help: Explain math problems step by step
  • Language practice: Conversation partner for language learners
  • Coding tutor: Debug code, suggest improvements, explain concepts

4. Industrial Edge AI

  • Equipment diagnostics: "Motor vibration abnormal, likely causes?"
  • Quality assurance: Visual inspection assistance via connected camera
  • Workflow guidance: Step-by-step instructions for complex procedures

Troubleshooting

"Model download too slow"

  • Use wired Ethernet or 5GHz WiFi
  • Pre-download on faster machine, copy ~/.cache/huggingface/hub directory
  • Use Hugging Face mirrors: HF_ENDPOINT=https://hf-mirror.com

"Out of memory errors"

  • Try smaller model (TinyLlama 1.1B or Phi-2)
  • Enable zram: sudo apt install zram-config && sudo reboot
  • Add swap file: sudo fallocate -l 4G /swapfile && sudo chmod 600 /swapfile && sudo mkswap /swapfile && sudo swapon /swapfile

"Responses seem low quality"

  • Lower temperature (0.1-0.3) for more focused answers
  • Add instruction to prompt: "Answer concisely and factually. If uncertain, say so."
  • Use retrieval-augmented generation (RAG) with your document collection

"Slow after first few minutes"

  • Check for thermal throttling: vcgencmd measure_temp
  • Improve cooling: add fan, ensure proper ventilation
  • Monitor CPU usage: htop or top

Looking Ahead

As hardware and software evolve: - Raspberry Pi 6 (expected 2027): 2-3x CPU performance gains - Better quantization: New techniques may enable 10B+ models on 8GB RAM - AI accelerators: Future Pi models may include NPUs or Google Coral-style TPUs - Mature ecosystem: More turnkey solutions for common AI applications


Start Your Offline AI Journey Today

You now have everything needed to run private, offline AI on Raspberry Pi:

  1. Verify basics: Run the Hello World test
  2. Build utility: Try the knowledge base Q&A
  3. Create interaction: Build the voice assistant
  4. Share your build: Show the community what you've created

Remember: The most valuable AI isn't always the biggest model in the cloud—it's the one that's available when you need it, keeps your data private, and fits in your project budget.

Your Raspberry Pi 5 is now an AI workstation. What will you build first?


Resources: - AirLLM GitHub - Raspberry Pi Documentation - Hugging Face Models - Phi-3 Model Card