<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Mushtaq on Medium]]></title>
        <description><![CDATA[Stories by Mushtaq on Medium]]></description>
        <link>https://medium.com/@mushtaqsaeed?source=rss-9d5addd9df2e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*tyqgPVQ47oPghd15pxs28A.jpeg</url>
            <title>Stories by Mushtaq on Medium</title>
            <link>https://medium.com/@mushtaqsaeed?source=rss-9d5addd9df2e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 13:57:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mushtaqsaeed/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Your Own Private ChatGPT: How to Run LLMs Locally Quantization, GGUF, and the Right Tools]]></title>
            <link>https://mushtaqsaeed.medium.com/your-own-private-chatgpt-how-to-run-llms-locally-quantization-gguf-and-the-right-tools-ffca7ec14e50?source=rss-9d5addd9df2e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ffca7ec14e50</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Mushtaq]]></dc:creator>
            <pubDate>Wed, 29 Apr 2026 10:48:11 GMT</pubDate>
            <atom:updated>2026-04-29T10:48:11.494Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TBaOnbN_NVuPJqQDrK5xaw.jpeg" /></figure><h3>Why Run LLMs Locally?</h3><p>If you’ve ever used ChatGPT or Claude, you already know how powerful large language models can be. But every time you send a message, something happens behind the scenes that’s worth thinking about your text travels to a remote server, gets processed by a model running on someone else’s hardware, and the response comes back to you.</p><p>That works fine for casual use. But what if you’re building something sensitive? What if your API bill is climbing faster than your user count? What if you just want the thing to work without an internet connection?</p><p>That’s where running LLMs locally comes in.</p><p><strong>Here are the four reasons it matters:</strong></p><p><strong>1. Privacy.</strong> When you run a model on your own machine, your data never leaves it. No prompts are logged, no conversations are stored on a third-party server. For anyone working with medical records, legal documents, or private business data this isn’t a nice-to-have, it’s a requirement.</p><p><strong>2. Cost.</strong> Cloud APIs charge per token. At small scale, that’s fine. At production scale thousands of requests a day it adds up fast. A local model has zero marginal cost per query after setup.</p><p><strong>3. Latency.</strong> A round-trip to a remote API takes time. A model running on your own hardware responds without touching a network. For real-time applications, that difference is noticeable.</p><p><strong>4. Control.</strong> With local models, you choose what runs. You can use open-source models that cloud providers don’t offer, fine-tune them on your own data, and update them on your own schedule no API deprecations, no provider decisions affecting your product.</p><p>The catch? These models are <em>large</em>. Running them efficiently on consumer hardware requires some clever engineering and that’s exactly what this guide is about.</p><h3>The Problem: LLMs Are Huge</h3><p>Before we talk about solutions, we need to understand the problem and it comes down to one thing <strong>memory</strong>.</p><p>When people say a model has “7 billion parameters,” those parameters are just numbers. Weights the model learned during training that determine how it responds to any input. The problem is storing and loading all those numbers at once.</p><p>By default, each parameter is stored as a 32-bit floating point number (float32). That means 4 bytes per parameter.</p><p>The math is simple:</p><pre>7,000,000,000 parameters × 4 bytes per parameter (float32) <br>               = 28,000,000,000 bytes<br><br>28,000,000,000 ÷ 1,000,000,000 = 28 GB</pre><blockquote>One gigabyte equals one billion bytes (in the base-10 system that storage hardware uses), so dividing by one billion converts bytes into gigabytes cleanly. That’s where 28 GB comes from, it’s just unit conversion after the multiplication.</blockquote><blockquote><strong>A quick note</strong>: some tools report memory in GiB (gibibytes), which uses 1,073,741,824 bytes as the base instead of one billion. In that system the same model would show as roughly 26.1 GiB. You’ll see both in the wild. For this guide we’ll stick with GB since that’s what most hardware specs use</blockquote><p>28 gigabytes just to load the model into memory, before it processes a single word. Most consumer GPUs have 8–16 GB of VRAM. A high-end RTX 4090 tops out at 24 GB. A standard laptop? It doesn’t even come close.</p><p>And 7B is considered a <em>small</em> model. GPT-4 is estimated to have over 1 trillion parameters. Meta’s Llama 3 comes in sizes up to 405B. The math scales brutally.</p><p><strong>This is the core problem:</strong> the models that are actually useful are too large to run on the hardware most people own.</p><p>So what do you do when something is too big to fit? You compress it carefully, without destroying what makes it useful. That’s the entire premise behind the techniques we’ll cover in this guide <strong>quantization</strong> and <strong>GGUF</strong>.</p><p>Think of it like packing for a trip with a carry-on only. You can’t bring everything, so you make smart choices fold tighter, leave behind what you don’t need, and still arrive with everything that actually matters.</p><h3>Quantization: Shrinking Without Losing Much</h3><p>If memory is the problem, quantization is the first and most important solution. Let’s break it down.</p><p>Every number stored in a model has a precision level, meaning how many bits are used to represent it. By default, models use 32-bit floating point numbers (float32). That’s a very precise format, capable of representing an enormous range of decimal values.</p><p>But here’s the thing, that level of precision is often overkill.</p><p>Quantization is the process of reducing that precision <strong>intentionally</strong>. Instead of storing each weight as a 32-bit number, you store it as a 16-bit, 8-bit, or even 4-bit number. Less precision per number means less memory overall.</p><p>Here’s how the math plays out on that same 7B model:</p><pre>float32 (32-bit): 7B × 4 bytes  = ~28 GB<br>float16 (16-bit): 7B × 2 bytes  = ~14 GB<br>int8   ( 8-bit): 7B × 1 byte   = ~7 GB<br>int4   ( 4-bit): 7B × 0.5 bytes = ~3.5 GB</pre><p>Going from float32 to int4 shrinks the model from 28 GB down to 3.5 GB. That’s the difference between <strong>“impossible on consumer hardware”</strong> and <strong>“runs on a laptop.”</strong></p><p>Now you might be wondering, doesn’t throwing away precision destroy the model’s quality?</p><p>Surprisingly, not by much. Think of it like audio compression. A raw WAV file and a high-quality MP3 sound nearly identical to most listeners, even though the MP3 is a fraction of the size. The human ear, like a language model, doesn’t need every bit of data to produce a great result.</p><p>The same principle applies here. Most of the weights in a model don’t need extreme precision to do their job well. A weight that was <em>0.37291648</em> at float32 and becomes <em>0.37</em> at int8 still pushes the model in the same direction. The output quality drops slightly, but for most real-world use cases, the difference is barely noticeable.</p><p>This tradeoff, smaller size and faster inference in exchange for a small quality dip, is at the heart of running LLMs on consumer hardware. And it’s why quantization is the first tool in everyone’s local AI toolkit.</p><h3>4-bit vs 8-bit: Which Should You Use?</h3><p>Now that you understand what quantization does, the next question is practical, how far should you go?</p><p>The two most common choices you’ll encounter are 8-bit and 4-bit quantization. Each hits a different point on the tradeoff curve between quality and efficiency, and knowing which to pick will save you a lot of trial and error.</p><p><strong>8-bit quantization</strong> is the conservative choice. You’re cutting the model size roughly in half compared to float16, while preserving most of the original quality. The model behaves very close to its full-precision version, responses feel sharp, reasoning holds up well, and the performance gap is small enough that most users won’t notice it.</p><p>If you have enough VRAM to run an 8-bit model comfortably, it’s often the right default.</p><p><strong>4-bit quantization</strong> is the aggressive choice. You’re cutting the model down to roughly one quarter of its original float16 size. A 7B model that needed 14 GB now fits in around 4 GB. That’s a game changer for anyone with a mid-range GPU or even a modern laptop with <em>unified memory</em>.</p><p>The quality dip is real but manageable. For general conversation, summarization, coding help, and most everyday tasks, a well-quantized 4-bit model performs surprisingly well. Where you start to notice the difference is in complex multi-step reasoning or highly technical domains where precision actually matters.</p><p>Here’s a simple side-by-side to make this concrete:</p><pre>Model: Llama-3 8B-Parameter</pre><pre>float16 (no quantization): ~16 GB VRAM needed<br>8-bit quantization:         ~8 GB  VRAM needed<br>4-bit quantization:         ~4 GB  VRAM needed</pre><p><strong>So which should you use?</strong></p><p>A simple rule of thumb, if your GPU has 16 GB or more, start with 8-bit. If you have 8 GB or less, 4-bit is your friend. If you’re running entirely on CPU or Apple Silicon with shared memory, 4-bit is almost always the right call because speed matters more than marginal quality gains.</p><p>One important nuance, not all 4-bit quantization is equal. The method used to quantize matters a lot. Techniques like <strong>GPTQ</strong> and the newer <strong>GGUF-based quantization</strong> (which we’ll cover next) are significantly smarter than naive rounding, and they recover much of the quality you’d otherwise lose.</p><p>So “4-bit” today is meaningfully better than “4-bit” was two years ago.</p><p>The bottom line, don’t be afraid of 4-bit. For most local use cases, it’s the sweet spot between what your hardware can handle and what the model can deliver.</p><h3>GGUF: The Format That Makes It Possible</h3><p>So you’ve quantized a model down to 4-bit. Great. Now what? You need a way to store it, share it, and load it efficiently on different machines. That’s exactly what GGUF solves.</p><p><strong>GGUF</strong> is a file format, a standardized way of packaging a quantized model into a single self-contained file that contains everything needed to run it, the weights, the tokenizer, the model architecture metadata, and the quantization settings, all bundled together.</p><p>It was created by <em>Georgi Gerganov</em>, the same developer behind <strong>llama.cpp,</strong> one of the most important tools in the local AI ecosystem. GGUF replaced an older format called <strong>GGML</strong> in 2023, solving several practical problems that made GGML frustrating to work with.</p><p><strong>Why GGUF matters:</strong></p><p>The old way of distributing models was messy. Weights lived in one file, tokenizer config in another, architecture details somewhere else. Loading a model meant juggling multiple files and hoping the versions matched. GGUF changed that by making everything self-contained. One file, everything included, ready to run.</p><p>It also made models truly portable. A GGUF file runs on Mac, Windows, and Linux without modification. It works on CPU, GPU, or both at the same time, which is useful when your VRAM isn’t quite large enough to hold the full model and you want to offload some layers to regular RAM.</p><p><strong>The naming convention:</strong></p><p>When you browse for GGUF models on Hugging Face, you’ll see filenames like these:</p><pre>llama-3-8b-Q4_K_M.gguf<br>llama-3-8b-Q8_0.gguf<br>llama-3-8b-Q5_K_S.gguf</pre><p>That naming pattern tells you exactly what you’re getting:</p><pre>Q4    = 4-bit quantization<br>Q8    = 8-bit quantization<br>K     = K-quant method (smarter, higher quality quantization)<br>M / S = Medium or Small variant (quality vs size tradeoff within the same bit level)</pre><p>So “Q4_K_M” means: 4-bit quantization, using the K-quant method, medium quality variant. It’s a very practical format once you know how to read it.</p><p><strong>The community default:</strong></p><p>GGUF has become the standard for sharing and running local models. The entire ecosystem around it, <strong>llama.cpp</strong>, <strong>Ollama</strong>, <strong>LM Studio</strong>, <strong>Jan</strong>, and others, all speak GGUF natively. If you download a local model today, there’s a very good chance it comes as a GGUF file.</p><p>Think of GGUF as the MP3 of AI models. A smart, compressed, universally compatible format that made something previously impractical suddenly accessible to everyone.</p><h3>Running a Model Locally with llama.cpp and Ollama</h3><p>All the theory we’ve covered so far exists to make this moment possible, running a real language model on your own machine, with no API key, no internet connection, no usage bill.</p><p>There are two main tools worth knowing. They solve the same problem in different ways, and understanding both will serve you well.</p><p>llama.cpp is the engine under the hood. It’s a C++ library that loads GGUF models and runs inference efficiently on CPU and GPU. It’s lean, fast, and incredibly well optimized. Most other local AI tools are built on top of it. If you want maximum control and don’t mind a terminal, llama.cpp is the right choice.</p><p>Ollama is the friendly layer on top. It wraps llama.cpp in a clean interface, handles model downloads automatically, and lets you run models with a single command. If you want to get something working in five minutes without fussing over file paths and build flags, Ollama is where you start.</p><p>We’ll cover both.</p><p><strong>Option 1: Ollama (recommended starting point)</strong></p><p>Install Ollama from ollama.com. It’s a single installer on Mac and Windows, and one command on Linux:</p><pre>curl -fsSL https://ollama.com/install.sh | sh</pre><p>Once installed, pulling and running a model is as simple as this:</p><pre>ollama run llama3</pre><p>That one command downloads the Llama 3 8B model in a sensible default quantization (Q4_K_M), loads it, and drops you into an interactive chat session in your terminal. No configuration needed.</p><p>You can also run it non-interactively, passing a prompt directly:</p><pre>ollama run llama3 &quot;Explain what a transformer model is in simple terms&quot;</pre><p>Ollama also exposes a local REST API automatically, which means you can call it from your own code just like you would call OpenAI’s API, just pointed at localhost instead:</p><pre>import requests</pre><pre>response = requests.post(&quot;http://localhost:11434/api/generate&quot;, json={<br>    &quot;model&quot;: &quot;llama3&quot;,<br>    &quot;prompt&quot;: &quot;What is quantization in machine learning?&quot;,<br>    &quot;stream&quot;: False<br>})</pre><pre>print(response.json()[&quot;response&quot;])</pre><p>That’s a fully local, fully private AI call. No keys, no cloud, no cost per token.</p><p><strong>Option 2: llama.cpp (more control)</strong></p><p>If you want to run a specific GGUF file you downloaded manually, llama.cpp gives you direct access. First, build it from source:</p><pre>git clone https://github.com/ggerganov/llama.cpp<br>cd llama.cpp<br>make</pre><p>Then run inference directly against any GGUF file:</p><pre>./llama-cli \<br>  -m ./models/llama-3-8b-Q4_K_M.gguf \<br>  -p &quot;Explain transformers in simple terms&quot; \<br>  -n 512</pre><p>Here’s what each flag does:</p><pre>-m   path to your GGUF model file<br>-p   your prompt<br>-n   maximum number of tokens to generate</pre><p>You can also add “ — n-gpu-layers 35” to offload 35 layers to your GPU, which speeds things up significantly if you have one available. The exact number depends on your VRAM, more layers on GPU means faster inference up to the point your VRAM runs out.</p><p><strong>Where to get models</strong></p><p>Hugging Face is the main hub. A great place to start is searching “GGUF” directly on Hugging Face, where many community contributors upload pre-quantized models ready to run. For Ollama, you can browse available models directly at ollama.com/library.</p><p>A solid starting point for most machines is Llama 3 8B at Q4_K_M. It runs on 6 GB of VRAM or even CPU-only, and the quality is genuinely impressive for its size.</p><h3>Choosing the Right Model for Your Hardware</h3><p>All the theory in the world doesn’t help if you download a model that your machine can’t run. This section is your practical decision guide, the thing you bookmark and come back to every time you’re about to pull a new model.</p><p>The single most important number is your GPU’s VRAM. Everything else follows from that.</p><p><strong>The VRAM decision table:</strong></p><pre>VRAM Available       Recommended Model Size    Best Quantization<br>4 GB                 3B models                 Q4_K_M<br>6 GB                 7B to 8B models           Q4_K_M<br>8 GB                 7B to 8B models           Q5_K_M or Q6_K<br>12 GB                13B models                Q4_K_M to Q5_K_M<br>16 GB                13B to 20B models         Q5_K_M<br>24 GB                33B models                Q4_K_M<br>No GPU (CPU only)    3B to 7B models           Q4_K_S or Q4_K_M<br>Apple Silicon        7B to 13B models          Q4_K_M to Q8_0</pre><p>A few things worth understanding about this table.</p><p>Apple Silicon is a special case because it uses unified memory, meaning RAM and VRAM are the same pool. A MacBook Pro with 32 GB of memory can run a 13B model at Q8_0 comfortably, something a Windows machine with a 16 GB GPU and separate system RAM can’t do as cleanly. If you’re on Apple Silicon, you have more headroom than the spec sheet might suggest.</p><p>CPU-only inference is slow but completely viable for smaller models. Expect roughly 5 to 15 tokens per second on a modern CPU for a 7B Q4 model, which is readable speed even if it’s not instant. For background tasks, document processing, or personal projects where speed isn’t critical, it works perfectly fine.</p><p><strong>Beyond VRAM: the other numbers that matter</strong></p><p>RAM matters too, not just VRAM. When a model is too large to fully fit in VRAM, llama.cpp and Ollama will offload layers to regular system RAM. This works, but those layers run on CPU, so inference slows down proportionally to how many layers get offloaded. A good rule of thumb is to have at least as much system RAM as your model’s file size, ideally twice as much.</p><p>Disk space is easy to overlook. GGUF models at Q4_K_M are roughly:</p><pre>3B model:   ~2 GB on disk<br>7B model:   ~4.5 GB on disk<br>13B model:  ~8 GB on disk<br>33B model:  ~20 GB on disk<br>70B model:  ~40 GB on disk</pre><p>If you plan to experiment with several models, 100 GB of free disk space is a reasonable starting budget.</p><p><strong>A simple decision flow:</strong></p><pre>Start here: How much VRAM do you have?</pre><pre>Under 6 GB:<br>  Use a 3B to 7B model at Q4_K_M.<br>  Good options: Phi-3 Mini, Llama 3.2 3B, Gemma 2 2B.</pre><pre>6 to 12 GB:<br>  Use a 7B to 8B model at Q4_K_M or Q5_K_M.<br>  Good options: Llama 3 8B, Mistral 7B, Gemma 2 9B.</pre><pre>12 to 24 GB:<br>  Use a 13B model at Q5_K_M, or push to a 33B at Q4_K_M.<br>  Good options: Llama 3 70B (quantized down), Mixtral 8x7B.</pre><pre>No GPU:<br>  Stick to 3B to 7B at Q4_K_S for reasonable speed.<br>  Good options: Phi-3 Mini, Llama 3.2 3B.</pre><pre>Apple Silicon:<br>  Use your full unified memory as your budget.<br>  16 GB chip: 7B at Q8_0. 32 GB chip: 13B at Q8_0 or 7B at full precision.</pre><p>The honest advice: start smaller than you think you need. A well-quantized 7B model running fast will feel better than a 13B model that stutters. You can always scale up once you know your hardware’s limits.</p><h3>The Local LLM Ecosystem: Tools Worth Knowing</h3><p>Running a model from the terminal is great for understanding what’s happening under the hood. But for day-to-day use, you’ll want something more comfortable. The good news is that the local LLM ecosystem has matured fast, and there are now excellent tools for every type of user.</p><p>Here’s an honest breakdown of the main ones worth knowing.</p><p><strong>Ollama</strong></p><p>Ollama is the starting point for most people, and for good reason. It handles everything behind the scenes, model downloads, quantization selection, server management, and exposes a clean local API that mirrors OpenAI’s format. That last part matters a lot: any app or script built for OpenAI’s API can be pointed at Ollama with minimal changes.</p><p>Best for: developers who want a reliable local backend they can build on top of.</p><pre># On Linux/Mac<br>curl -fsSL https://ollama.com/install.sh | sh<br><br># On Mac with Homebrew<br>brew upgrade ollama</pre><pre># List what you have installed<br>ollama list</pre><pre># Remove a model<br>ollama rm llama3</pre><p><strong>LM Studio</strong></p><p>LM Studio is the most polished desktop experience in the ecosystem. It has a full GUI, a built-in model browser connected to Hugging Face, a chat interface, and a local server you can toggle on with a single click. If you want to explore local models without touching a terminal at all, LM Studio is the right tool.</p><p>It also lets you load and compare different GGUF files side by side, tweak parameters like temperature and context length visually, and see real-time performance stats while the model runs.</p><p>Best for: non-developers, researchers, or anyone who prefers a visual interface over a terminal.</p><p><strong>Jan</strong></p><p>Jan is the open-source alternative to LM Studio. It’s a desktop app with a clean chat interface, local model management, and a built-in API server. Where LM Studio is proprietary, Jan is fully open source and privacy-first by design, everything runs locally with no telemetry.</p><p>Best for: privacy-conscious users who want a GUI but don’t want closed-source software on their machine.</p><p><strong>Open WebUI</strong></p><p>Open WebUI is what you use when you want a ChatGPT-style browser interface running entirely on your own machine. It connects to Ollama as its backend and gives you a full web app with conversation history, system prompts, model switching, and multi-user support if you’re running a local server for a small team.</p><p>You can run it with a single Docker command:</p><pre>docker run -d \<br>  -p 3000:8080 \<br>  --add-host=host.docker.internal:host-gateway \<br>  -v open-webui:/app/backend/data \<br>  --name open-webui \<br>  ghcr.io/open-webui/open-webui:main</pre><p>Then open your browser at <a href="http://localhost:3000/">http://localhost:3000</a> and you have a full ChatGPT-like interface backed entirely by your local models.</p><p>Best for: users who want a polished chat experience, or teams sharing a local model server.</p><p><strong>llama.cpp</strong></p><p>We covered this earlier, but it belongs in this list too. llama.cpp is the foundation everything else is built on. It’s not a user-facing app, it’s the inference engine that does the actual work. Understanding it gives you the ability to debug anything, optimize performance, and use models in ways the higher-level tools don’t support yet.</p><p>Best for: developers who want full control, or anyone building their own tooling on top of local models.</p><p><strong>A quick comparison:</strong></p><pre>Tool          Interface    Needs Terminal    Open Source    Best Use Case<br>Ollama        CLI + API    Yes              Yes            Developer backend<br>LM Studio     Desktop GUI  No               No             Exploring models visually<br>Jan           Desktop GUI  No               Yes            Privacy-first GUI<br>Open WebUI    Browser      Minimal          Yes            ChatGPT-like experience<br>llama.cpp     CLI          Yes              Yes            Maximum control</pre><p>The most common setup you’ll see in the wild is Ollama as the backend with Open WebUI on top. It gives you a great interface, full local privacy, and a developer-friendly API all at once, without any compromise.</p><h3>Common Mistakes and How to Avoid Them</h3><p>Every developer who has set up local LLMs has made at least a few of these mistakes. This section saves you the frustration of discovering them the hard way.</p><p><strong>1. Downloading a model your hardware can’t run</strong></p><p>This is the most common first mistake. Someone sees a 70B model with impressive benchmarks, downloads 40 GB of data, and then watches their machine either crash, freeze, or produce one token every ten seconds.</p><p>The fix is simple: use the VRAM table from the previous section before you download anything. Start with a 7B or 8B model at Q4_K_M. Get it running well, then scale up from there. Patience at the start saves hours of frustration.</p><p><strong>2. Confusing RAM with VRAM</strong></p><p>Your computer might have 32 GB of RAM and only 8 GB of VRAM. These are not interchangeable in the way you might hope. The model runs on VRAM, not regular RAM. Overflowing into regular RAM is possible but slow. Many beginners check their system RAM, feel confident, and then wonder why inference is crawling.</p><p>The fix: always check your GPU’s VRAM specifically. On Windows you can find it in Task Manager under the Performance tab, on Mac it’s listed in About This Mac under Graphics, on Linux run “nvidia-smi” in the terminal.</p><p><strong>3. Ignoring context length</strong></p><p>Every model has a context window, the maximum number of tokens it can hold in memory at once. When you exceed it, the model starts forgetting the beginning of the conversation. But here’s what most guides don’t tell you: context length also affects VRAM usage significantly.</p><p>Running a 7B model with a 2,048 token context is very different from running the same model with a 32,768 token context. The larger context can push a model that fit comfortably into VRAM straight into overflow territory.</p><p>The fix: start with the default context length your tool sets, usually around 2,048 to 4,096 tokens. Only increase it if you have a specific reason and enough VRAM headroom.</p><p><strong>4. Expecting cloud-level speed</strong></p><p>Local models are fast, but they are not ChatGPT fast. ChatGPT runs on thousands of GPUs in parallel. Your local setup runs on one consumer GPU or a CPU. Expecting the same response speed leads to disappointment.</p><p>Realistic expectations for a 7B Q4 model:</p><pre>RTX 3080 (10 GB VRAM):    ~50 to 80 tokens per second<br>RTX 4090 (24 GB VRAM):    ~100 to 150 tokens per second<br>Apple M2 Pro (unified):   ~40 to 60 tokens per second<br>CPU only (modern laptop): ~5 to 15 tokens per second</pre><p>At 50 tokens per second you’re reading faster than the model generates, which feels fluid. At 10 tokens per second it feels slow but usable. Set expectations accordingly.</p><p><strong>5. Using the wrong quantization for your use case</strong></p><p>Not all tasks need the same quality level. People often default to the lowest quantization to save memory, even when they have headroom for better quality.</p><p>A simple rule:</p><pre>General chat, creative writing:   Q4_K_M is fine<br>Coding assistance:                Q5_K_M or Q6_K recommended<br>Complex reasoning or analysis:    Q8_0 if your VRAM allows</pre><p>The quality difference between Q4 and Q8 is small for casual use but can be meaningful when the task requires precision.</p><p><strong>6. Not keeping Ollama or llama.cpp updated</strong></p><p>This ecosystem moves fast. Performance improvements, new quantization methods, and bug fixes ship regularly. Running an old version means missing real gains. A version of llama.cpp from six months ago might be 20 to 30 percent slower than the current release on the same hardware.</p><p>The fix: check for updates monthly at minimum. With Ollama, updating is one command:</p><pre>ollama pull llama3</pre><p>For llama.cpp, pull the latest from GitHub and rebuild:</p><pre>git pull<br>make clean &amp;&amp; make</pre><p><strong>7. Forgetting that model quality varies independently of size</strong></p><p>Bigger is not always better. A well-trained 8B model can outperform a poorly trained 13B model on many tasks. Model architecture, training data quality, and instruction tuning all matter as much as parameter count.</p><p>Before chasing larger models, try different 7B to 8B options. Mistral 7B, Llama 3 8B, Gemma 2 9B, and Phi-3 Mini all have different strengths. The right model for your use case might already be one that fits easily in your VRAM.</p><h3>Conclusion: You Now Have Everything You Need</h3><p>A few sections ago, running an AI model locally might have felt like something reserved for researchers with expensive hardware and deep ML knowledge. Hopefully it’s clear now that it isn’t.</p><p>Let’s bring everything together.</p><p>You learned that LLMs are large by default because each parameter is stored as a high-precision number, and that a 7B model at full float32 precision needs 28 GB of memory before it can process a single word. You learned that quantization solves this by reducing numerical precision intentionally, shrinking a 28 GB model down to 3 to 4 GB with surprisingly little quality loss.</p><p>You learned the difference between 4-bit and 8-bit quantization, when each makes sense, and why modern quantization methods like Q4_K_M recover most of the quality you’d expect to lose. You learned what GGUF is, why it became the standard format for sharing and running local models, and how to read the naming conventions so you always know exactly what you’re downloading.</p><p>You got hands-on with Ollama and llama.cpp, ran your first local model, and called it from Python with a few lines of code. You learned how to match models to your hardware using VRAM as your primary guide, and you now know the most common mistakes that trip people up and exactly how to avoid them.</p><p><strong>The honest summary of where the ecosystem stands today</strong></p><p>Local LLMs in 2026 are genuinely useful, not just impressive demos. A well-quantized 7B or 8B model running on consumer hardware can handle coding assistance, document summarization, question answering, writing help, and general conversation with quality that would have required cloud APIs just two years ago. The tooling is mature, the community is active, and the models keep improving.</p><p>The gap between local and cloud models is real but narrowing fast. For privacy-sensitive use cases, high-volume applications, or simply the satisfaction of owning your own AI stack, local models are already the right choice.</p><p><strong>Where to go from here</strong></p><p>If you want to go deeper, these are the most valuable next steps in rough order of difficulty:</p><pre>1. Try different models on your hardware, compare quality for your specific use case<br>2. Set up Open WebUI on top of Ollama for a full local chat interface<br>3. Explore the Hugging Face model hub for specialized models (coding, medical, multilingual)<br>4. Learn about model benchmarks (MMLU, HumanEval) to evaluate models objectively<br>5. Experiment with system prompts to customize model behavior without fine-tuning</pre><p><strong>The tools and resources worth bookmarking:</strong></p><pre>ollama.com              Download and run models in one command<br>huggingface.co          The main hub for open-source models<br>github.com/ggerganov/llama.cpp    The engine behind everything<br>lmstudio.ai             Best desktop GUI for exploring models<br>openwebui.com           ChatGPT-style interface for local models</pre><p>The best way to learn this stack is to actually run something. If you haven’t yet, open a terminal, install Ollama, and run:</p><pre>ollama run llama3</pre><p>That single command will download and run a state-of-the-art open-source model on your own machine. No account, no API key, no usage limit, no data leaving your computer.</p><p>That’s the whole point. The tools exist, the models are free, and your hardware is ready. The only thing left is to start.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ffca7ec14e50" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Focal Loss Explained: How to Train Models on Imbalanced Datasets in Machine Learning]]></title>
            <link>https://mushtaqsaeed.medium.com/focal-loss-explained-how-to-train-models-on-imbalanced-datasets-in-machine-learning-6c5081baba2c?source=rss-9d5addd9df2e------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c5081baba2c</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Mushtaq]]></dc:creator>
            <pubDate>Mon, 20 Apr 2026 11:22:22 GMT</pubDate>
            <atom:updated>2026-04-20T11:22:22.290Z</atom:updated>
            <content:encoded><![CDATA[<p>In many real-world machine learning problems, the most important events are also the rarest. Fraudulent transactions, rare diseases, network intrusion attempts, and manufacturing defects often account for less than 1% of the data yet these are precisely the cases we care most about detecting.</p><p>Standard training methods struggle here. They minimize average error across all examples, which means they naturally gravitate toward satisfying the majority. The result: models that look excellent on paper but fail completely when it matters.</p><p>This is where <strong>Focal Loss</strong> comes in. Introduced by Lin et al. in the 2017 paper <em>Focal Loss for Dense Object Detection</em>, it is a carefully designed loss function that dynamically down-weights easy, well-classified examples and forces the model to focus its learning budget on the hard, rare, and informative ones.</p><h3>The Problem of Class Imbalance in Machine Learning</h3><h3>What Is a Class?</h3><p>In a classification problem, a <strong>class</strong> is simply a category the model must predict. Every training example belongs to one class, and the model’s job is to assign each new input to the correct one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*8PDxps1C-LJXzGKVmx_6Kg.png" /></figure><h3>What Is Class Imbalance?</h3><p>A dataset is <strong>imbalanced</strong> when one class appears far more often than another. The dominant category is the <strong>majority class</strong>; the rare one is the <strong>minority class</strong>.</p><p>In fraud detection, a typical real-world dataset looks like this:</p><p>Transaction Type Samples Proportion Legitimate 9,900 99% Fraudulent 100 1%</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oKy3JoL1VC7yRT0AmSTe0w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nThmN8BtKyzXRFSOcGx4DQ.png" /></figure><p>The minority class is almost always the one that matters most which is exactly what makes class imbalance such a dangerous problem.</p><h3>Why High Accuracy Can Be Completely Meaningless</h3><p>Here is a sobering thought experiment. Suppose your fraud detection model learns the simplest possible strategy: <em>predict every transaction as legitimate, always.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*HGWw4qXVfrROQpz8ABWrUA.png" /></figure><p>A 99% accurate model that detects zero fraud. This is not a contrived edge case it is a trap that real systems fall into constantly.</p><p>This is why practitioners working on imbalanced problems replace accuracy with metrics like <strong>Precision</strong> (of all predicted positives, how many are actually positive?), <strong>Recall</strong> (of all actual positives, how many did we catch?), and the <strong>F1-score</strong> (the harmonic mean of both).</p><h3>Real-World Severity of Class Imbalance</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FWYqjp37Z9huM9zpIdteRg.png" /></figure><p>In every case, failing to detect the minority class has severe real-world consequences.</p><h3>Why Cross-Entropy Loss Fails on Imbalanced Datasets</h3><p>Most classification models are trained using <strong>Binary Cross-Entropy</strong> or its multi-class generalisation <strong>Categorical Cross-Entropy</strong>. Before we look at the formula, let’s build the intuition.</p><h3>The Intuition</h3><p>The loss function answers one question: <em>how wrong was the model’s prediction?</em> Cross-entropy does this well in isolation:</p><ul><li>High confidence, correct prediction (p_t ≈ 0.95) → very small loss</li><li>Uncertain prediction (p_t ≈ 0.50) → moderate loss</li><li>Confident wrong prediction (p_t ≈ 0.05) → very large loss</li></ul><h3>The Cross-Entropy Formula</h3><p>We define <strong>p_t</strong> as the model’s predicted probability for the <em>correct</em> class. For a positive example (y=1), p_t = p. For a negative example (y=0), p_t = 1 − p. Cross-entropy then simplifies to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t8WAwIdvMMWFUkdBwJtAdA.png" /></figure><p><strong>The Hidden Problem:</strong> Easy Examples Dominate Training</p><p>The issue is not with any single example it is with the <strong>aggregate</strong> across a heavily imbalanced dataset.</p><p>After a few training iterations, the model learns the majority class well. It starts producing very confident predictions for normal transactions (p_t ≈ 0.97, 0.98, 0.99). Each one produces a tiny individual loss. But multiply tiny by nine thousand examples, and the total swamps everything else. The hundred rare fraud examples even with individually large losses are drowned out numerically.</p><p><strong>The model’s gradient updates therefore spend most of their effort making already-good predictions marginally better, while making almost no progress on the rare cases that actually matter.</strong></p><h3>The Classroom Analogy</h3><p>Imagine a classroom of 100 students preparing for a final exam. Ninety-five already understand the material. Five are genuinely struggling.</p><p>A teacher who allocates attention proportionally ends up tutoring the 95 who raise their hands most. The 5 who need real help stay behind.</p><p>A smarter teacher deliberately redirects attention: spend less time on students who already understand, and more time on those who don’t. This is exactly the philosophy behind Focal Loss.</p><h3>What Cross-Entropy Is Missing</h3><p>Cross-entropy assigns loss based solely on prediction correctness. It has no mechanism to ask:</p><ul><li><em>Is this example easy or hard for the model right now?</em></li><li><em>Is this class rare or common in the dataset?</em></li></ul><p>Focal loss fixes this with two targeted modifications.</p><h3>Understanding p_t — The Key Quantity</h3><p>Before reading the focal loss formula, we need to be fully comfortable with p_t, because the entire mechanism of focal loss is built around it.</p><p><strong>p_t is simply the model’s predicted probability for the correct class.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dgjTnUWpVCs1fnCW_pLpDQ.png" /></figure><p>Here is how to interpret p_t at a glance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*Xdx6gDDs4VegSUSToxsBcA.png" /></figure><p><strong>Easy examples have high p_t. Hard examples have low p_t.</strong> This single quantity is all focal loss needs to distinguish between them.</p><h3>The Focal Loss Formula Built from First Principles</h3><h3>Step 1: Start with cross-entropy</h3><p>We already know this. It penalises wrong predictions but treats every example equally regardless of difficulty.</p><h3>Step 2: Add the modulating factor</h3><p>Focal loss multiplies the cross-entropy by a single extra term called the <strong>modulating factor</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Iubc8P1I1fXLsw8YV05_KA.png" /></figure><p>The new term <strong>(1 − p_t)^γ</strong> is the modulating factor. Here is what it does in practice, with γ = 2:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X03jNIoAqFWF2C6F700tiw.png" /></figure><p>Easy examples get crushed. Hard examples survive. This is the entire mechanism.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o1swXnhBd6agxojwjthNOg.png" /></figure><h3>Step 3: The role of gamma (γ)</h3><p>γ is the single tuning knob that controls how aggressively easy examples are suppressed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aEJEVGyBzrLlHPyKJM11Kw.png" /></figure><p>The original paper found γ = 2 to work best for object detection. For fraud detection and medical imaging, searching γ ∈ [1, 3] is a reasonable starting range.</p><h3>Step 4: Add alpha (α) the class weighting term</h3><p>Here is a subtlety: even with the modulating factor, the model still <em>sees</em> far more majority-class examples during training. Their sheer volume can still dilute the minority signal. Focal loss addresses this with an additional <strong>class weighting factor</strong> α:</p><h3>The Complete Focal Loss Formula:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IPtg-x4OS0WRWCP0aVjbRQ.png" /></figure><h3>Symbol legend:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2PcUwFMrpPmnlEfacfv2dQ.png" /></figure><p><strong>Recommended starting values:</strong> α = 0.25 for the majority class, α = 0.75 for the minority class. γ = 2.</p><p><strong>Gamma vs Alpha two different problems, both needed:</strong></p><ul><li>γ solves the <em>easy vs hard</em> problem: suppresses examples the model already handles well</li><li>α solves the <em>class frequency</em> problem: rebalances the raw count imbalance between classes</li></ul><h3>Step-by-Step Numerical Calculation</h3><p>Let’s put the formula to work with real numbers. Scenario: fraud detection. The model predicts a probability of 0.3 for the correct class (fraud). Parameters: γ = 2, α = 0.75.</p><h3>Calculation A — Medium difficulty (p_t = 0.3)</h3><p><strong>Step 1 — Cross-entropy term:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H_rM5z-BZ_Kihg1-XLSXIQ.png" /></figure><p><strong>Step 2 — Modulating factor:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*atZPFlhil7OYFUXocZ6e4A.png" /></figure><p><strong>Step 3 — Apply alpha and compute final loss:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AEbISu46h5HCSfKiABA1bQ.png" /></figure><p><strong>Calculation B — Hard example</strong> (p_t = 0.1)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gJpp-tKYveJuTBgMHVM0kA.png" /></figure><p><strong>What the Numbers Tell Us</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6lQGqdCKCxBtHY8L-HJUFQ.png" /></figure><p>The harder the example, the more it dominates. The easier the example, the more it is ignored. This is exactly what focal loss is designed to do.</p><h3>A Minimal PyTorch Implementation</h3><pre>import torch<br>import torch.nn.functional as F<br><br>def focal_loss(logits, targets, alpha=0.75, gamma=2.0):<br>    &quot;&quot;&quot;<br>    Focal loss for binary classification.<br>    logits:  raw model outputs before sigmoid, shape (N,)<br>    targets: binary labels 0 or 1, shape (N,)<br>    alpha:   weight for the positive (minority) class<br>    gamma:   focusing parameter<br>    &quot;&quot;&quot;<br>    bce = F.binary_cross_entropy_with_logits(<br>        logits, targets.float(), reduction=&#39;none&#39;<br>    )<br>    probs = torch.sigmoid(logits)<br>    p_t   = probs * targets + (1 - probs) * (1 - targets)<br>    alpha_t = alpha * targets + (1 - alpha) * (1 - targets)<br>    focal_weight = alpha_t * (1 - p_t) ** gamma<br>    return (focal_weight * bce).mean()<br># Quick test<br>logits  = torch.tensor([ 2.0, -1.5,  0.3, -3.0])<br>targets = torch.tensor([   1,    0,    1,    1 ])<br>print(f&quot;Focal Loss: {focal_loss(logits, targets):.4f}&quot;)</pre><p>The key line is focal_weight = alpha_t * (1 - p_t) ** gamma. Everything else is bookkeeping. The formula maps directly to code, symbol for symbol.</p><h3>When to Use Focal Loss and When Not To</h3><h3>Use it when</h3><p><strong>Object detection: </strong>Focal loss was designed for this. In RetinaNet, background regions outnumber object regions by up to 1,000:1. Without focal loss, the background floods the gradients and the model never learns to detect objects.</p><p><strong>Fraud and anomaly detection: </strong>With fraud rates below 1%, standard cross-entropy produces models that appear highly accurate but catch almost no fraud.</p><p><strong>Medical imaging and diagnosis: </strong>Disease prevalence in population screening is often 1–5%. Missing a positive case can have life-or-death consequences.</p><p><strong>Cybersecurity and intrusion detection: </strong>Attack traffic is rare. Focal loss improves recall for malicious events without requiring aggressive oversampling.</p><p><strong>Manufacturing quality control: </strong>Defect rates in high-precision manufacturing are often below 1%.</p><h3>Do not use it when</h3><p><strong>The dataset is balanced: </strong>Focal loss provides no benefit. With γ &gt; 0, it suppresses high-confidence predictions indiscriminately and can harm convergence.</p><p><strong>Data contains noisy labels: </strong>Focal loss cannot distinguish a genuinely hard example from a mislabelled one. Both have low p_t. Aggressive focusing (γ ≥ 2) causes the model to overfit annotation errors.</p><p><strong>Very small datasets: </strong>The variance introduced by down-weighting the majority of examples can destabilise training. Start with class-weighted cross-entropy instead.</p><h3>Advantages and Limitations</h3><h3>What focal loss does well</h3><p><strong>Eliminates the easy-example bottleneck.</strong> By suppressing gradients from already-solved examples, the model’s capacity is directed where it is actually needed.</p><p><strong>Handles imbalance at two levels simultaneously.</strong> γ handles the difficulty dimension; α handles the class frequency dimension. Together they address imbalance more completely than either mechanism alone.</p><p><strong>Requires no data modification.</strong> Unlike oversampling (SMOTE) or undersampling, focal loss operates purely through the loss function. The true data distribution is preserved.</p><p><strong>Computationally free.</strong> Adding (1 − p_t)^γ costs essentially nothing at training scale.</p><h3>Where it falls short</h3><p><strong>Two additional hyperparameters.</strong> γ and α must be tuned per problem. The paper recommends γ = 2, α = 0.25 for object detection, but these are not universal defaults.</p><p><strong>Sensitive to label noise.</strong> Mislabelled examples look exactly like hard examples. Focal loss will confidently learn the wrong thing from them.</p><p><strong>Not always better than simpler approaches.</strong> On moderately imbalanced datasets, class-weighted cross-entropy (focal loss with γ = 0) can achieve comparable performance with less tuning. Always benchmark against the simpler baseline first.</p><h3>Conclusion</h3><p>Focal loss is not a complex idea. It is a focused answer to a specific problem.</p><p>Standard cross-entropy is democratic: every example votes, and the majority rules. In imbalanced datasets, that democracy produces models that serve the majority class excellently and the minority class hardly at all.</p><p>Focal loss introduces two targeted interventions the modulating factor (1 − p_t)^γ to suppress easy examples, and the class weight α_t to counteract raw frequency imbalance packaged into a single expression that drops in as a direct replacement for cross-entropy.</p><p>In practice this means models that detect more fraud, catch more disease, identify more cyberattacks, and spot more defects without modifying the dataset, adding model complexity, or changing the training loop.</p><p>At its core, focal loss is not about making learning harder. It is about making learning <em>smarter</em> spending effort where effort is needed, and ignoring what is already understood.</p><p><em>Reference: Lin et al., “Focal Loss for Dense Object Detection,” ICCV 2017. Practice problem: </em><a href="https://www.deep-ml.com/problems/255"><em>deep-ml.com/problems/255</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c5081baba2c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>