Dev.to AI πŸ€– Ai πŸ‘ 0 πŸ“– 8 min read

From cloud to control: Run Local LLMs on Google Colab

SLM vs. LLM at a Glance: Small Language Models (SLMs): Compact enough to run on your laptop or a local machine, and useful as focused specialists when paired with your own dataset. Large Language Models (LLMs): Large

From cloud to control: Run Local LLMs on Google Colab

SLM vs. LLM at a Glance:

  • Small Language Models (SLMs): Compact enough to run on your laptop or a local machine, and useful as focused specialists when paired with your own dataset.
  • Large Language Models (LLMs): Large generalist models trained on vast amounts of internet data.

The Technical Bridge: Model Distillation

How large models can be compressed into smaller ones that keep much of their capability.

Running capable models locally starts with understanding how big models get shrunk without losing too much of their ability. One technique that makes this possible is model distillation, introduced by Hinton and colleagues in 2015 (Distilling the Knowledge in a Neural Network):

  • Teacher β†’ Student Architecture:
    • The Teacher: A large model whose outputs guide the training of a smaller one.
    • The Transfer Mechanism (Soft Targets): Instead of learning only from hard right/wrong labels, the smaller model learns from soft targets, the teacher's full probability distributions over possible outputs. These carry information about how the teacher weighs alternatives.
    • The Student: A compact Small Language Model (SLM, typically under about 15B parameters) that keeps much of the teacher's behavior in a smaller footprint.

Note: Distillation is one way to build an SLM. Many open-weight SLMs are trained from scratch, and others combine distillation with other techniques.

Why Distillation Matters for Local & Colab Workflows

  1. Lower Cost: Fine-tuning or distilling a smaller model is far cheaper than pre-training a large foundation model from scratch.
  2. Edge Hardware Compatibility: Combined with quantization (INT4 / INT8), many small models run in roughly 4 GB of GPU or system RAM. That's enough for standard desktops, edge boards, or free-tier Google Colab instances, though accuracy usually drops somewhat compared with full-precision models.

Model Distillation: Teacher to Student Architecture

The 2026 SLM Market Landscape

Mapping open-weight and proprietary models across generalist and specialist roles.

Before spinning up a local model on Google Colab, it helps to see how the 2026 Small Language Model (SLM) ecosystem breaks down along two axes: Proprietary/API vs. Open Weights (horizontal) and Generalist vs. Domain Specialization (vertical).

Model Licensing / Access Orientation Primary Strength / Use Case
GPT-5.4 mini & nano Proprietary / API Domain / Specialized Coding, tool use, and subagents
Nemotron 3 Nano Omni Hybrid / Mid-spectrum Domain / Specialized Agentic reasoning and multimodal tasks
Granite 4.1 Hybrid / Mid-spectrum Domain / Specialized Enterprise tools
Ministral 3 Hybrid / Mid-spectrum Generalist Local assistants
SmolLM3 Open-leaning Generalist Research and fine-tuning
North Mini Code Open Weights Domain / Specialized Sovereign coding agents
Phi-4 Open Weights Domain / Specialized Math, science, and visual reasoning
Tiny Aya Open Weights Balanced / Mid-vertical Multilingual regional tasks
Gemma 4 Open Weights Generalist Local AI and reasoning
Qwen3 Open Weights Generalist Multilingual reasoning

Key Takeaway for Colab Builders: If your goal is moving "from cloud to control," the open-weights side of the chart gives you the most ownership. You can pick general-purpose options like Gemma 4 or Qwen3, or domain-focused models like Phi-4 (STEM and reasoning) and North Mini Code (coding agents), without depending on a proprietary API. Check each model's license before using it commercially.

The 2026 SLM Market Landscape

Enterprise Applications in Action

Production use cases for on-premises and edge Small Language Models.

Moving from cloud APIs to local or edge SLMs helps in four enterprise scenarios where latency, privacy, or connectivity make cloud inference a poor fit:

  1. Healthcare: Privacy-First
    • Runs medical image analysis and patient outcome prediction on hospital edge devices.
    • Keeps patient data inside the facility's own infrastructure. Local deployment supports HIPAA compliance, but it doesn't guarantee it. Compliance depends on the full system, including access controls, audit logging, and agreements with any vendors involved.
  2. Financial Services: Regulated Risk
    • Deploys fraud detection and credit risk models on-premises.
    • Keeps sensitive transaction data, personally identifiable information (PII), and proprietary trading logic inside corporate firewalls.
  3. Industrial IoT: Low Latency
    • Powers predictive maintenance and robotics by processing sensor data directly on factory equipment.
    • Enables fast, offline anomaly detection when waiting for a cloud round trip isn't practical.
  4. DevOps: Sovereign Coding
    • Integrates open-weight code models into local CI/CD pipelines.
    • Helps identify vulnerabilities, generate regression tests, and refactor scripts without sending proprietary source code to a third party.

Enterprise Applications in Action

The Problem: The API Trap

Commercial AI tools are powerful, but relying on them can trap developers in three ways:

  1. Cost: Pay-per-token fees add up quickly during development.
  2. Privacy: Sending proprietary code or internal data to commercial cloud models can violate corporate security policies.
  3. Control: Rate limits, model deprecations, and hidden system prompts limit what you can build.

The Solution: The Private AI Stack

You don't need a commercial API for many projects. You can build a private, customizable AI pipeline with standard tools.

The Private AI Stack Overview

The stack combines three low-cost building blocks:

  1. Google Colab: Compute Layer: Provides cloud access to NVIDIA T4 GPUs on the free tier, subject to availability and usage limits. That's enough VRAM for quantized SLMs without local hardware.
  2. Ollama: Model Runtime: Downloads, manages, and serves open-weight models through a local REST API on port 11434.
  3. Python: Orchestration Layer: Uses Python, either the ollama SDK or plain HTTP requests, to prompt, chain, and control the model from your notebook or application.

The Private AI Stack Architecture

Why Now? The 2026 Open-Source Boom

Local models have gotten good enough for many practical tasks.

Two shifts make running local models practical now:

  1. Hardware Efficiency:
    • Smaller open models now perform well on coding benchmarks and approach some commercial models on certain tasks.
    • Quantization and model compression let tasks that once needed multi-GPU servers run on a single free-tier Colab T4 or a consumer laptop.
  2. Accessible Model Families:
    • llava: Vision-language models that analyze images alongside text.
    • deepseek: Reasoning and coding models.
    • llama: Meta's general-purpose and instruction-tuned models.
    • qwen: Multilingual and coding models across several parameter sizes.

Why Now? The 2026 Open-Source Boom

Open-Source Small Language Models (SLMs)

Efficient, specialized models that run on local and resource-constrained devices.

Instead of sending every task to a large cloud model, open-source SLMs offer four main advantages:

  1. Local Hardware Efficiency:
    • Compact architectures run on consumer GPUs, laptops, and edge devices with modest memory and compute.
  2. Task-Specific Fine-Tuning:
    • Parameter-efficient methods like LoRA and QLoRA let you adapt a small model to a narrow task such as coding help, data analysis, or structured extraction, often at a fraction of the cost of full fine-tuning.
  3. Low Latency:
    • Tokens are generated locally with no cloud round trip, which suits interactive and agentic applications.
  4. Data Control:
    • Running locally keeps data on your own machine or private infrastructure and avoids recurring per-token API costs and vendor lock-in.

Open-Source Small Language Models (SLMs)

Google Colab: Cloud-Based Python Environment

Zero-setup cloud compute for experimenting with local models.

Google Colab is a convenient sandbox for running local LLMs without an expensive workstation. Key features:

  1. Free GPU Access:
    • The free tier provides NVIDIA T4 GPUs subject to quota and availability. Paid tiers offer faster GPUs such as the A100. Sessions can be reclaimed when idle, so save your work.
  2. Pre-Configured Environment:
    • Comes with common machine learning libraries like TensorFlow, PyTorch, and OpenCV, so you can start coding without setting up CUDA drivers.
  3. Easy Sharing:
    • Notebooks live in Google Drive and support real-time co-editing and comments for team work.
  4. Ecosystem Integration:
    • Connects to Google Cloud Storage, BigQuery, and GitHub for data pipelines and reproducible workflows.

Google Colab: Cloud-Based Python Environment

Setting Up Ollama in Colab

Install the runtime and pull a model before you make any API calls.

Ollama runs inside the Colab virtual machine, so localhost works from your notebook cells. Run these in a Colab cell:

# Install Ollama
!curl -fsSL https://ollama.com/install.sh | sh

# Start the server in the background
!nohup ollama serve > ollama.log 2>&1 &

# Download a model (llama3 is used in the examples below)
!ollama pull llama3

Wait a few seconds after starting the server before sending requests. Model downloads can take several minutes, and the Colab session resets when it ends, so you'll need to reinstall and re-pull each time.

Ollama API Code Walkthrough

Calling local models with plain Python requests.

Once Ollama is running on http://localhost:11434, you can call it with standard HTTP requests and no proprietary SDK. The two main endpoints are described in the Ollama API docs.

1. Generate API (POST /api/generate)

Best for single-turn prompts.

import requests

res = requests.post(
    'http://localhost:11434/api/generate',
    json={
        'model': 'llama3',
        'prompt': 'Why is the sky blue?',
        'stream': False
    }
)
print(res.json()['response'])

2. Chat API (POST /api/chat)

Best for multi-turn conversations where you need to keep message history and roles (system, user, assistant).

import requests

response = requests.post(
    'http://localhost:11434/api/chat',
    json={
        'model': 'llama3',
        'messages': [
            {'role': 'user', 'content': 'Hello!'}
        ],
        'stream': False
    }
)
print(response.json()['message']['content'])

Tip: Setting 'stream': False returns the full response in one JSON payload instead of streaming tokens.

Hands-On Examples & Patterns

Example 1: Log Analysis

DevOps Data Processing on Local Hardware

  • The Problem: Pasting proprietary server logs into a public cloud API is a security risk.
  • The Solution: Use a local model to parse messy, unformatted system errors without sending them off the machine.
  • The Concept (System Prompts): Tell the model to "act as a DevOps engineer" and extract the critical failure points.
  • Colab Challenge: Feed the model simulated Apache server logs and ask it to summarize the root cause of the crash in exactly one sentence.

Example 2: Chaos-to-JSON Converter

Bridging AI and Traditional Databases

  • The Problem: Chatty model output ("Here is your data!") doesn't fit into a database, which needs strict structure.
  • The Solution: Force the model to return valid JSON.
  • The Concept (format="json"): Setting format to "json" in Ollama's API constrains the output so it parses as JSON. It doesn't guarantee the content is correct, so validate the fields you need.
  • Colab Challenge: Give the model a rambling voicemail transcript and extract customer_name, item_requested, and urgency_level into a clean JSON object.

Example 3: Agentic QnA Pipeline

Researcher β†’ Writer β†’ Auditor

  • The Problem: Single-prompt answers to complex questions about long documents often hallucinate facts.
  • The Solution: A multi-step agent workflow that checks its own work:
    1. Researcher: Extracts only the relevant raw facts.
    2. Writer: Drafts an answer using only those facts.
    3. Auditor: Compares the draft against the extracted facts to catch unsupported claims.
  • Colab Challenge: Run a tricky question through a single prompt, then through the three-agent pipeline, and see whether the Auditor catches the error.

The Reality Check: SLM Limitations

Small models have real trade-offs. Knowing where they fail helps you design around those failures.

Smaller parameter counts come with limits:

  • Limited World Knowledge

    • The Problem: SLMs can't store as much information as larger models and may invent details about obscure topics.
    • The Fix: Don't treat an SLM as an encyclopedia. Retrieve the relevant facts and include them in the prompt with Retrieval-Augmented Generation (RAG).
  • Complex Reasoning Limits

    • The Problem: Small models often struggle with multi-step logic, advanced math, and open-ended problem solving.
    • The Fix: Give them structured tasks they handle well, such as extracting, routing, summarizing, or formatting.
  • Context Degradation

    • The Problem: Models often miss information placed in the middle of long prompts. This "lost in the middle" effect has been documented across LLMs, and it tends to be more pronounced in smaller models.
    • The Fix: Keep inputs short and focused, and split long documents into smaller pieces.
  • Prompt Brittleness

    • The Problem: Smaller models follow instructions literally, so complex multi-part prompts can break.
    • The Fix: Use prompt chaining. Break the workflow into smaller prompts, each with one job.

Try It Yourself

Open the interactive Colab notebook

πŸ“° Read the original article on Dev.to AI

Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.