404 Not Found

404 Not Found


nginx

On-Premises Model Deployment

"Data never leaves the machine"—this isn’t science fiction; it’s the reality of on-premises AI. When privacy regulations prohibit uploading data to the cloud, network instability affects service, or API call fees become prohibitively expensive, deploying AI models on-premises becomes a practical choice. This chapter will help you understand the differences between on-premises deployment and cloud APIs, install Ollama to run open-source LLMs, call local models using Python, and experience the benefits of privacy protection and offline AI.

1. What You'll Learn


2. Story: Charlie’s Privacy Dilemma

(1) Pain Point: Data Cannot Be Migrated to the Cloud

Charlie's medical AI project requires analyzing patient medical records to extract key symptoms and medication information. He had originally planned to use the OpenAI API for this, but the compliance team raised a red flag:

"Patient medical records are considered sensitive personal data and, in accordance with the GDPR and the Personal Information Protection Act, cannot be sent to third-party cloud APIs."

The API proposal was rejected outright. Charlie was in a bind—the AI was very powerful, but the data couldn’t be uploaded to the cloud.

(2) Bob's Approach: Running the Model Locally

After hearing about the situation, Bob made a suggestion: "Use Ollama to run Llama 3 locally—the data stays on the machine, which is both compliant and cost-effective."

One command:

BASH
ollama run llama3

The >>> prompt appears on the screen—a large language model running entirely locally is now ready. The medical records do not need to leave Charlie’s laptop.

(3) Benefits: Privacy, cost savings, and offline access—all in one

After testing, Charlie found that while the local model isn’t as powerful as GPT-4, it’s perfectly adequate for the medical record summarization task, saves $50 in API fees each month, and works even without an internet connection.


3. On-Premises Deployment vs. Cloud API

(1) Key Differences

On-premises deployment and cloud APIs represent two distinctly different AI usage paradigms—the former is “own and run,” while the latter is “rent and call.”

(2) Comparison Table: On-Premises vs. Cloud API

Dimension On-premises Cloud API
Privacy Data remains on the device and is fully under your control Data is sent to third-party servers
Cost One-time hardware investment; no ongoing API fees Billed per token; high long-term costs
Latency Consistent inference latency, no network fluctuations Depends on the network; latency varies between 1 and 5 seconds
Model Size Limited by local memory/GPU memory; typically 7B–70B No restrictions; supports GPT-4-level large models
Offline Fully available offline Internet connection required
Operations and Maintenance Requires managing hardware and updates yourself Zero O&M; ready to use and configure
Model Quality Open-source models, not on par with GPT-4 Commercial models, highest quality
Customization Finely tunable; all parameters can be controlled Black box; adjustments made only through API parameters

(3) How to Choose?


4. Installing and Using Ollama

(1) What is Ollama?

Ollama is an open-source framework for running local LLMs that wraps model downloads, quantization, loading, and API services into minimal command-line operations. It uses the llama.cpp inference engine under the hood and supports both GPU-accelerated and CPU-based inference.

(2) Install Ollama

macOS / Linux:

BASH
curl -fsSL https://ollama.com/install.sh | sh

Windows:

Download the installer from ollama.com and double-click it to install.

Manual Installation on Linux:

BASH
sudo systemctl start ollama

After installation, Ollama starts the REST API service on http://localhost:11434 by default.

(3) Ollama Workflow

100%
graph TB
    A["ollama pull llama3<br/>Download model"] --> B["Quantized GGUF<br/>Auto-quantized"]
    B --> C["Load to Memory/VRAM<br/>Model loading"]
    C --> D["API Server :11434<br/>REST API endpoint"]
    D --> E["Python / CLI / App<br/>Client calls"]
    E --> F["Inference<br/>Generate response"]
    F --> D

▶ Example: Downloading a Model (Difficulty: ⭐)

BASH
# Download Llama 3 8B model (about 4.7 GB)
ollama pull llama3

# Download Qwen2 7B
ollama pull qwen2

# Download Mistral 7B
ollama pull mistral

The download progress bar displays the speed and remaining time. The models are stored in the ~/.ollama/models directory.

▶ Example: Command-Line Dialogue (Difficulty: ⭐)

BASH
# Start interactive chat with Llama 3
ollama run llama3

# >>> Hello! Can you explain what a neural network is in one paragraph?
# A neural network is a computational model inspired by the way biological
# neurons work in the human brain. It consists of layers of interconnected
# nodes (neurons) that process information...

# Type /bye to exit
# >>> /bye

▶ Example: View Installed Models (Difficulty ⭐)

BASH
# List all downloaded models
ollama list

# Output example:
# NAME            ID              SIZE    MODIFIED
# llama3:latest   365c0bd3c000    4.7 GB  2 hours ago
# mistral:latest  2b3e8435e228    4.1 GB  5 days ago
# qwen2:latest    e3d7e5e5e5e5    4.4 GB  1 day ago

5. Open-Source LLM Families

(1) Major Open-Source Models

The open-source LLM ecosystem experienced explosive growth in 2023–2024, giving rise to several model families:

(2) Comparison Table of Open-Source LLMs

Model Number of Parameters Developer Context Length Features
Llama 3 8B / 70B Meta 8K Strong general-purpose capabilities, richest ecosystem
Mistral 7B / 8x7B Mistral AI 32K High-efficiency inference, support for long context
Qwen2 7B / 72B Alibaba Cloud 32K–128K Excellent Chinese language capabilities, strong multilingual capabilities
Gemma 2 9B / 27B Google 8K Good security, lightweight and efficient
Phi-3 3.8B / 14B Microsoft 4K-128K Compact yet high-performance, suitable for edge computing

(3) How do you choose a model?


6. Model Quantification and Hardware Requirements

(1) What is quantitative analysis?

Quantization is the process of compressing model weights from high precision (such as FP16, where each weight is 16 bits) to low precision (such as Q4, where each weight is 4 bits). It significantly reduces memory usage at the cost of a slight loss in quality.

Ollama uses quantization models in GGUF format (based on llama.cpp) by default. Common quantization levels:

(2) Comparison Table of Quantification Levels

Quantization Level Bits per Weight 7B Model Size Quality Loss Applicable Scenarios
FP16 16-bit ~14 GB None Quality-first, with ample VRAM
Q8 8-bit ~7 GB Very small Balances quality and size
Q5 5 bits ~5 GB Minor Balanced Choice
Q4 4-bit ~4 GB Acceptable Preferred when memory is tight

(3) Hardware Requirements Reference Table

Number of Model Parameters Q4 Quantization Size Minimum Memory/VRAM Recommended Configuration
3B ~2 GB 4 GB Laptops with integrated graphics
7B-8B ~4-5 GB 8 GB 8 GB VRAM GPU or 16 GB RAM
13B-14B ~8 GB 16 GB 16 GB VRAM GPU
70B-72B ~40 GB 48 GB 2×24 GB GPU or 64 GB RAM + CPU

The quantized 7B model (Q4) requires only about 4 GB of memory and can run on most modern laptops. This is key to significantly lowering the barrier to entry for on-device AI.


7. Calling a Local Model Using Python

(1) Install the ollama library

BASH
pip install ollama

(2) Two Ways to Call It

Ollama supports two ways to call Python:

▶ Example: Calling a Local Model in Python (Difficulty: ⭐)

PYTHON
import ollama

# Simple chat with local Llama 3
response = ollama.chat(
    model="llama3",
    messages=[
        {"role": "user", "content": "Explain quantum computing in one sentence."},
    ],
)

print(response["message"]["content"])

▶ Example: Comparing Local and Cloud API Latency (Difficulty: ⭐⭐)

PYTHON
import time
import ollama
from openai import OpenAI

# Local model latency
start = time.time()
local_response = ollama.chat(
    model="llama3",
    messages=[{"role": "user", "content": "What is machine learning?"}],
)
local_time = time.time() - start

# Cloud API latency
client = OpenAI()
start = time.time()
cloud_response = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[{"role": "user", "content": "What is machine learning?"}],
)
cloud_time = time.time() - start

print(f"Local model: {local_time:.2f}s")
print(f"Cloud API:   {cloud_time:.2f}s")
print(f"Local output: {local_response['message']['content'][:100]}")
print(f"Cloud output: {cloud_response.choices[0].message.content[:100]}")

▶ Example: Direct Call via REST API (Difficulty: ⭐⭐)

PYTHON
import requests
import json

# Call Ollama REST API directly
url = "http://localhost:11434/api/chat"
payload = {
    "model": "llama3",
    "messages": [{"role": "user", "content": "Write a haiku about programming."}],
    "stream": False,
}

response = requests.post(url, json=payload)
result = response.json()
print(result["message"]["content"])

8. Comprehensive Example: Local AI Translator

▶ Example: Complete Translator—From Installation to Runtime (Difficulty: ⭐⭐)

This comprehensive example demonstrates: installing Ollama → downloading Llama 3 → implementing a "local AI translator" using the Python ollama library → comparing the differences in output quality with the OpenAI API.

PYTHON
import ollama
from openai import OpenAI

def local_translate(text: str, source: str = "English", target: str = "Chinese") -> str:
    prompt = (
        f"You are a professional {source}-{target} translator. "
        f"Translate the following {source} text to {target}. "
        f"Only output the translation, no explanation.\n\n{text}"
    )
    response = ollama.chat(
        model="llama3",
        messages=[{"role": "user", "content": prompt}],
    )
    return response["message"]["content"]

def cloud_translate(text: str, source: str = "English", target: str = "Chinese") -> str:
    client = OpenAI()
    prompt = (
        f"You are a professional {source}-{target} translator. "
        f"Translate the following {source} text to {target}. "
        f"Only output the translation, no explanation.\n\n{text}"
    )
    response = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[{"role": "user", "content": prompt}],
    )
    return response.choices[0].message.content

test_sentences = [
    "The patient presented with persistent cough and mild fever for three days.",
    "Artificial intelligence is transforming healthcare diagnostics.",
    "The stock market rallied after the central bank announced rate cuts.",
]

print("=" * 60)
print("Local AI Translator vs Cloud API Translator")
print("=" * 60)

for i, sentence in enumerate(test_sentences, 1):
    local_result = local_translate(sentence)
    cloud_result = cloud_translate(sentence)
    print(f"\n[{i}] EN: {sentence}")
    print(f"    Local:  {local_result}")
    print(f"    Cloud:  {cloud_result}")
    print(f"    {'--- Match ---' if local_result.strip() == cloud_result.strip() else '--- Different ---'}")

Before running, make sure:

BASH
# Step 1: Install and start Ollama
ollama serve

# Step 2: Download model (in another terminal)
ollama pull llama3

# Step 3: Install Python dependencies
pip install ollama openai

# Step 4: Run the translator
python local_translator.py

Example of Expected Output:

TEXT
============================================================
Local AI Translator vs Cloud API Translator
============================================================

[1] EN: The patient presented with persistent cough and mild fever for three days.
    Local:  Patient presents with persistent cough and mild fever for three days.
    Cloud:  Patient shows persistent cough and mild fever for three days.
    --- Different ---

[2] EN: Artificial intelligence is transforming healthcare diagnostics.
    Local:  AI is transforming medical diagnosis.
    Cloud:  AI is revolutionizing the medical diagnosis field.
    --- Different ---

Both translations are accurate, but the wording and style differ—the local model is fully capable of meeting everyday translation needs.


❓ FAQ

Q What hardware requirements are needed to run an LLM locally?
A A minimum of 8 GB of RAM is required to run the 7B Q4 quantized model (approximately 4 GB); 16 GB of RAM or a GPU with 8 GB of VRAM is recommended for a smoother experience. The 70B model requires at least 48 GB of VRAM.
Q Is Ollama free?
A Yes, Ollama is completely free and open source (under the MIT license), and all supported models are also open source and free, with no hidden fees.
Q Does quantization reduce model quality?
A Yes, but the impact is minimal. Q4 quantization typically results in a loss of only 1–3% on benchmark scores, and the difference is virtually imperceptible in most practical tasks. Q8 quantization is virtually lossless.
Q Is there a significant gap between local models and GPT-4?
A 7B-level local models lag significantly behind GPT-4 in complex reasoning and long-text generation, but they have already reached levels close to GPT-3.5 for tasks such as translation, summarization, and classification. 70B-level models can approach the performance of GPT-4.
Q What models can run on 8 GB of RAM?
A 8 GB of RAM can run the 3B Q4 model (Phi-3 mini) smoothly, while the 7B Q4 model can run on it, albeit slowly. We recommend at least 16 GB of RAM or a GPU with 8 GB of VRAM to run the 7B model.
Q Does Ollama support GPU acceleration?
A Yes. macOS automatically uses Metal for acceleration, and Linux/Windows automatically use CUDA acceleration when an NVIDIA GPU is detected. No additional configuration is required.

📖 Summary


📝 Exercises

Basics (⭐)

Install Ollama and download a model, then carry out a conversation in the command line:

BASH
# Step 1: Install Ollama from https://ollama.com

# Step 2: Download a model
ollama pull llama3

# Step 3: Start a chat
ollama run llama3

# >>> Tell me three interesting facts about the planet Mars.

# Step 4: List installed models
ollama list

Advanced (⭐⭐)

Use the Python ollama library to call a local model for translation and implement an interactive translator:

PYTHON
import ollama

def interactive_translator():
    print("Local AI Translator (type 'quit' to exit)")
    print("-" * 40)
    while True:
        text = input("EN> ")
        if text.lower() == "quit":
            break
        response = ollama.chat(
            model="llama3",
            messages=[
                {
                    "role": "user",
                    "content": f"Translate to Chinese, only output the translation:\n\n{text}",
                },
            ],
        )
        print(f"CN> {response['message']['content']}\n")

interactive_translator()

Challenge (⭐⭐⭐)

Compare the differences in output between the local model and the cloud API for the same prompt, and write an analysis report:

PYTHON
import ollama
from openai import OpenAI
import time

PROMPT = """Analyze the following customer review and extract:
1. Sentiment (Positive/Negative/Neutral)
2. Key complaint or praise
3. Suggested action for the company

Review: "The headphones sound amazing but the Bluetooth keeps disconnecting every 10 minutes. I have to restart them constantly. Great audio quality but unusable for calls."
"""

def compare_outputs():
    # Local model
    start = time.time()
    local = ollama.chat(
        model="llama3",
        messages=[{"role": "user", "content": PROMPT}],
    )
    local_time = time.time() - start
    local_text = local["message"]["content"]

    # Cloud API
    client = OpenAI()
    start = time.time()
    cloud = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[{"role": "user", "content": PROMPT}],
    )
    cloud_time = time.time() - start
    cloud_text = cloud.choices[0].message.content

    print("PROMPT:", PROMPT[:80], "...")
    print("=" * 60)
    print(f"[Local - {local_time:.1f}s]\n{local_text}")
    print("=" * 60)
    print(f"[Cloud - {cloud_time:.1f}s]\n{cloud_text}")
    print("=" * 60)

    # TODO: Write a brief analysis comparing:
    # - Accuracy of sentiment extraction
    # - Completeness of key points
    # - Actionability of suggestions
    # - Response time difference

compare_outputs()
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏