<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>PyImageSearch</title>
	<atom:link href="https://pyimagesearch.com/feed/" rel="self" type="application/rss+xml" />
	<link>https://pyimagesearch.com/</link>
	<description>You can master Computer Vision, Deep Learning, and OpenCV - PyImageSearch</description>
	<lastBuildDate>Mon, 03 Aug 2026 15:43:16 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.8.6</generator>
	<item>
		<title>Training with PyTorch Lightning: Structured MLOps Development</title>
		<link>https://pyimagesearch.com/2026/08/03/training-with-pytorch-lightning-structured-mlops-development/</link>
		
		<dc:creator><![CDATA[Vikram Singh]]></dc:creator>
		<pubDate>Mon, 03 Aug 2026 12:45:00 +0000</pubDate>
				<category><![CDATA[Deep Learning]]></category>
		<category><![CDATA[MLOps]]></category>
		<category><![CDATA[Natural Language Processing]]></category>
		<category><![CDATA[PyTorch]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[checkpointing]]></category>
		<category><![CDATA[deep learning]]></category>
		<category><![CDATA[distilbert]]></category>
		<category><![CDATA[huggingface transformers]]></category>
		<category><![CDATA[hydra]]></category>
		<category><![CDATA[mlops]]></category>
		<category><![CDATA[model training]]></category>
		<category><![CDATA[nlp]]></category>
		<category><![CDATA[pytorch lightning]]></category>
		<category><![CDATA[reproducible ml]]></category>
		<category><![CDATA[sentiment analysis]]></category>
		<category><![CDATA[tensorboard]]></category>
		<category><![CDATA[tutorial]]></category>
		<guid isPermaLink="false">https://pyimagesearch.com/?p=54839</guid>

					<description><![CDATA[<p>Table of Contents Training with PyTorch Lightning: Structured MLOps Development Why PyTorch Lightning Improves Reproducible MLOps Training Pipelines Configuring Your Development Environment Project Structure PyTorch LightningDataModule Explained: Building Efficient Data Pipelines PyTorch LightningModule Explained: Building Modular Deep Learning Models Using&#8230;</p>
<p>The post <a rel="nofollow" href="https://pyimagesearch.com/2026/08/03/training-with-pytorch-lightning-structured-mlops-development/">Training with PyTorch Lightning: Structured MLOps Development</a> appeared first on <a rel="nofollow" href="https://pyimagesearch.com">PyImageSearch</a>.</p>
]]></description>
										<content:encoded><![CDATA[<div class="yoast-breadcrumbs"><span><span><a href="https://pyimagesearch.com/">Home</a></span></div>


<div class="toc">
<hr class="TOC"/>
<p class="has-large-font-size"><strong>Table of Contents</strong></p>
<ul>
    <li id="TOC-h1-Training-PyTorch-Lightning-Structured-MLOps-Development"><a rel="noopener" target="_blank" href="#h1-Training-PyTorch-Lightning-Structured-MLOps-Development">Training with PyTorch Lightning: Structured MLOps Development</a></li>

    <li id="TOC-h2-Why-PyTorch-Lightning-Improves-Reproducible-MLOps-Training-Pipelines"><a rel="noopener" target="_blank" href="#h2-Why-PyTorch-Lightning-Improves-Reproducible-MLOps-Training-Pipelines">Why PyTorch Lightning Improves Reproducible MLOps Training Pipelines</a></li>

    <li id="TOC-h2-Configuring-Development-Environment"><a rel="noopener" target="_blank" href="#h2-Configuring-Development-Environment">Configuring Your Development Environment</a></li>

    <li id="TOC-h2-Project-Structure"><a rel="noopener" target="_blank" href="#h2-Project-Structure">Project Structure</a></li>

    <li id="TOC-h2-PyTorch-LightningDataModule-Explained-Building-Efficient-Data-Pipelines"><a rel="noopener" target="_blank" href="#h2-PyTorch-LightningDataModule-Explained-Building-Efficient-Data-Pipelines">PyTorch LightningDataModule Explained: Building Efficient Data Pipelines</a></li>

    <li id="TOC-h2-PyTorch-LightningModule-Explained-Building-Modular-Deep-Learning-Models"><a rel="noopener" target="_blank" href="#h2-PyTorch-LightningModule-Explained-Building-Modular-Deep-Learning-Models">PyTorch LightningModule Explained: Building Modular Deep Learning Models</a></li>

    <li id="TOC-h2-Using-Hydra-Python-Configuration-Files-Reproducible-ML-Training"><a rel="noopener" target="_blank" href="#h2-Using-Hydra-Python-Configuration-Files-Reproducible-ML-Training">Using Hydra Python Configuration Files for Reproducible ML Training</a></li>

    <li id="TOC-h2-Building-PyTorch-Lightning-Training-Pipeline-train-py"><a rel="noopener" target="_blank" href="#h2-Building-PyTorch-Lightning-Training-Pipeline-train-py">Building a PyTorch Lightning Training Pipeline with train.py</a></li>

    <li id="TOC-h2-Running-Model-Inference-PyTorch-Lightning-DistilBERT"><a rel="noopener" target="_blank" href="#h2-Running-Model-Inference-PyTorch-Lightning-DistilBERT">Running Model Inference with PyTorch Lightning and DistilBERT</a></li>

    <li id="TOC-h2-Training-Evaluating-DistilBERT-Model-PyTorch-Lightning-Hydra"><a rel="noopener" target="_blank" href="#h2-Training-Evaluating-DistilBERT-Model-PyTorch-Lightning-Hydra">Training and Evaluating a DistilBERT Model with PyTorch Lightning and Hydra</a></li>

    <li id="TOC-h2-Summary"><a rel="noopener" target="_blank" href="#h2-Summary">Summary</a></li>
</ul>
</div>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h1-Training-PyTorch-Lightning-Structured-MLOps-Development"/>



<h2 class="wp-block-heading"><a href="#TOC-h1-Training-PyTorch-Lightning-Structured-MLOps-Development">Training with PyTorch Lightning: Structured MLOps Development</a></h2>



<p>In this lesson, you will learn how to build a fully modular, reproducible, and production-friendly training pipeline using PyTorch Lightning and Hydra. We will train a sentiment-classification model with a clean MLOps-ready structure that scales as your projects grow.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://pyimagesearch.com/wp-content/uploads/2026/08/training-w-pytorch-lightning-structured-mlops-development-featured.png" target="_blank" rel=" noreferrer noopener"><img fetchpriority="high" decoding="async" width="940" height="780" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/08/training-w-pytorch-lightning-structured-mlops-development-featured.png?lossy=2&strip=1&webp=1" alt="training-w-pytorch-lightning-structured-mlops-development-featured.png" class="wp-image-54855"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/08/training-w-pytorch-lightning-structured-mlops-development-featured.png?size=126x105&lossy=2&strip=1&webp=1 126w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/08/training-w-pytorch-lightning-structured-mlops-development-featured-300x249.png?lossy=2&strip=1&webp=1 300w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/08/training-w-pytorch-lightning-structured-mlops-development-featured.png?size=378x314&lossy=2&strip=1&webp=1 378w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/08/training-w-pytorch-lightning-structured-mlops-development-featured.png?size=504x418&lossy=2&strip=1&webp=1 504w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/08/training-w-pytorch-lightning-structured-mlops-development-featured.png?size=630x523&lossy=2&strip=1&webp=1 630w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/08/training-w-pytorch-lightning-structured-mlops-development-featured-768x637.png?lossy=2&strip=1&webp=1 768w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/08/training-w-pytorch-lightning-structured-mlops-development-featured.png?lossy=2&strip=1&webp=1 940w" sizes="(max-width: 940px) 100vw, 940px" /></a></figure></div>


<p>This lesson is the 1st in a 2-part series on <strong>PyTorch Lightning</strong>:</p>



<ol class="wp-block-list">
<li><em><strong><a href="https://pyimg.co/5fe4l" target="_blank" rel="noreferrer noopener">Training with PyTorch Lightning: Structured MLOps Development</a></strong></em> <strong>(this tutorial)</strong></li>



<li><em>Lesson 2</em></li>
</ol>



<p><strong>To learn how to structure deep learning code for reliable, maintainable training workflows,</strong><em><strong> just keep reading.</strong></em></p>



<div id="pyi-source-code-block" class="source-code-wrap"><div class="gpd-source-code">
    <div class="gpd-source-code-content">
        <img decoding="async" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2020/01/source-code-icon.png?lossy=2&strip=1&webp=1" alt="">
        <h4>Looking for the source code to this post?</h4>
                    <a href="#download-the-code" class="pyis-cta-modal-open-modal">Jump Right To The Downloads Section <svg class="svg-icon arrow-right" width="12" height="12" aria-hidden="true" role="img" focusable="false" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M6.8125 0.1875C6.875 0.125 6.96875 0.09375 7.09375 0.09375C7.1875 0.09375 7.28125 0.125 7.34375 0.1875L13.875 6.75C13.9375 6.8125 14 6.90625 14 7C14 7.125 13.9375 7.1875 13.875 7.25L7.34375 13.8125C7.28125 13.875 7.1875 13.9062 7.09375 13.9062C6.96875 13.9062 6.875 13.875 6.8125 13.8125L6.1875 13.1875C6.125 13.125 6.09375 13.0625 6.09375 12.9375C6.09375 12.8438 6.125 12.75 6.1875 12.6562L11.0312 7.8125H0.375C0.25 7.8125 0.15625 7.78125 0.09375 7.71875C0.03125 7.65625 0 7.5625 0 7.4375V6.5625C0 6.46875 0.03125 6.375 0.09375 6.3125C0.15625 6.25 0.25 6.1875 0.375 6.1875H11.0312L6.1875 1.34375C6.125 1.28125 6.09375 1.1875 6.09375 1.0625C6.09375 0.96875 6.125 0.875 6.1875 0.8125L6.8125 0.1875Z" fill="#169FE6"></path></svg></a>
            </div>
</div>
</div>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Why-PyTorch-Lightning-Improves-Reproducible-MLOps-Training-Pipelines"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Why-PyTorch-Lightning-Improves-Reproducible-MLOps-Training-Pipelines">Why PyTorch Lightning Improves Reproducible MLOps Training Pipelines</a></h2>



<p>Deep learning projects begin as small experiments (e.g., a single script, a few functions, and a quick training loop). But as your model grows, your dataset expands, and your experimentation increases, that simple script becomes a bottleneck. It collects data loading, model code, training logic, metrics, logging, and CLI arguments all in one place. This makes the code harder to debug, harder to reproduce, and nearly impossible to scale.</p>



<p>From an MLOps perspective, this is a critical issue. Reproducibility, modularity, logging, version control, and collaboration all depend on a clean separation of concerns. When data, modeling, and training logic live inside one file, versioning becomes fragile. Dockerization becomes harder. Running distributed or mixed-precision training becomes messy. And experiment tracking ends up inconsistent.</p>



<p>This is exactly where <strong>PyTorch Lightning</strong> shines. Instead of mixing everything together, Lightning organizes your training workflow into well-defined components:</p>



<ul class="wp-block-list">
<li><strong>LightningModule:</strong> contains your model and training/validation/test logic</li>



<li><strong>LightningDataModule:</strong> manages data downloading, tokenization, and data loaders</li>



<li><strong>Trainer:</strong> handles the engineering: GPUs, mixed precision, checkpointing, logging, and training loops</li>
</ul>



<p>You keep your PyTorch code. Lightning handles the boilerplate.</p>



<p>This separation is not just “clean code.” It is an MLOps superpower. With structure in place, you can:</p>



<ul class="wp-block-list">
<li>Version your data, model code, and configs separately</li>



<li>Run consistent experiments across environments</li>



<li>Scale from CPU → single GPU → multi-GPU → multi-node without changing code</li>



<li>Produce reproducible artifacts for DVC and deployment</li>



<li>Integrate Hydra configs for repeatable pipelines</li>
</ul>



<p>In this lesson, you will see how Lightning transforms a typical sentiment-classification workflow into a modular, reproducible, production-ready training pipeline (i.e., the kind expected in real-world MLOps and LLMOps teams).</p>



<p>To learn how to structure reproducible ML training with PyTorch Lightning, just keep reading.</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p>Would you like immediate access to 3,457 images curated and labeled with hand gestures to train, explore, and experiment with &#8230; for free? Head over to <a href="https://universe.roboflow.com/isl/az-6mqow?ref=pyimagesearch" target="_blank" rel="noreferrer noopener">Roboflow</a> and get a free account to grab these hand gesture images. </p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Configuring-Development-Environment"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Configuring-Development-Environment">Configuring Your Development Environment</a></h2>



<p>Before we begin implementing the training pipeline, let’s configure the development environment. This project uses modern versions of PyTorch, PyTorch Lightning, and the Hugging Face ecosystem, along with Hydra for configuration management. Installing the correct dependencies ensures that your training, data loading, and model export workflows run smoothly.</p>



<p>All the required libraries are pip-installable. Below is the full list of dependencies used in this lesson:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Training with PyTorch Lightning: Structured MLOps Development" data-enlighter-group="1"># PyTorch and Lightning
torch>=2.1.0
torchvision>=0.16.0
torchaudio>=2.1.0
pytorch-lightning>=2.1.0

# Hugging Face ecosystem
transformers>=4.35.0
datasets>=2.14.0
tokenizers>=0.15.0

# Configuration management
hydra-core>=1.3.0
omegaconf>=2.3.0

# Metrics and monitoring
torchmetrics>=1.2.0
tensorboard>=2.15.0

# Data processing
numpy>=1.24.0
pandas>=2.0.0

# Utilities
tqdm>=4.66.0
pyyaml>=6.0.0</pre>



<p>You can install everything with a single command:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Training with PyTorch Lightning: Structured MLOps Development" data-enlighter-group="2">!pip install -r requirements.txt</pre>



<p>Your project folder includes a <code data-enlighter-language="python" class="EnlighterJSRAW">requirements.txt</code> file containing all of the dependencies above. If you are working inside a clean virtual environment (e.g., <code data-enlighter-language="python" class="EnlighterJSRAW">venv</code> or <code data-enlighter-language="python" class="EnlighterJSRAW">Conda</code>), this setup will give you everything needed to train the sentiment-classification model in Lesson 1.</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<!-- wp:paragraph -->
<h3>Need Help Configuring Your Development Environment?</h3>
<!-- /wp:paragraph -->

<!-- wp:image {"align":"center","id":18137,"sizeSlug":"large","linkDestination":"custom"} -->
<figure class="wp-block-image aligncenter size-large"><a href="https://pyimagesearch.com/pyimagesearch-university/" target="_blank" rel="noreferrer noopener"><img decoding="async" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2021/01/pyimagesearch_plus_jupyter.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-18137" srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2021/01/pyimagesearch_plus_jupyter.png?lossy=2&strip=1&webp=1 500w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2021/01/pyimagesearch_plus_jupyter.png?size=126x84&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2021/01/pyimagesearch_plus_jupyter.png?size=252x168&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2021/01/pyimagesearch_plus_jupyter.png?size=378x253&lossy=2&strip=1&webp=1 378w" sizes="(max-width: 500px) 100vw, 500px" /></a><figcaption>Having trouble configuring your development environment? Want access to pre-configured Jupyter Notebooks running on Google Colab? Be sure to join <a href="https://pyimagesearch.com/pyimagesearch-university/" target="_blank" rel="noreferrer noopener" aria-label=" (opens in a new tab)">PyImageSearch University</a> — you will be up and running with this tutorial in a matter of minutes. </figcaption></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>All that said, are you:</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li>Short on time?</li><li>Learning on your employer’s administratively locked system?</li><li>Wanting to skip the hassle of fighting with the command line, package managers, and virtual environments?</li><li><strong>Ready to run the code immediately on your Windows, macOS, or Linux system?</strong></li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>Then join <a href="https://pyimagesearch.com/pyimagesearch-university/" target="_blank">PyImageSearch University</a> today!</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><strong>Gain access to Jupyter Notebooks for this tutorial and other PyImageSearch guides pre-configured to run on Google Colab’s ecosystem right in your web browser!</strong> No installation required.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>And best of all, these Jupyter Notebooks will run on Windows, macOS, and Linux!</p>
<!-- /wp:paragraph -->



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Project-Structure"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Project-Structure">Project Structure</a></h2>



<p>Before we write any code, it is important to understand how a real MLOps-ready training workflow is organized. A clean project structure makes your training pipeline easier to maintain, debug, scale across machines, and integrate later with DVC, MLflow, and CI/CD. PyTorch Lightning encourages this modular layout (e.g., through structured components), and Hydra takes care of configuration management in a clean, reproducible way.</p>



<p>Below is the project structure we will use for Lesson 1:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Training with PyTorch Lightning: Structured MLOps Development" data-enlighter-group="3">lesson1/
├── configs/
│   ├── config.yaml
│   ├── model/
│   │   └── distilbert.yaml
│   ├── data/
│   │   └── imdb.yaml
│   └── trainer/
│       └── default.yaml
└── src/
    ├── data_module.py
    ├── model_module.py
    ├── train.py
    └── inference.py</pre>



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">src/</code> folder contains all the Python logic:</p>



<ul class="wp-block-list">
<li><code data-enlighter-language="python" class="EnlighterJSRAW">data_module.py</code>: handles dataset loading, tokenization, and data loaders</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">model_module.py</code>: defines the DistilBERT-based classifier</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">train.py</code>: orchestrates the training loop using PyTorch Lightning</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">inference.py</code>: allows you to test the trained model interactively</li>
</ul>



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">configs/</code> directory is where we store all configuration files, grouped by purpose (model, data, trainer). This keeps hyperparameters and training settings cleanly separated from code, which is a fundamental principle in MLOps.</p>



<h3 class="wp-block-heading">Hydra in 60 Seconds (All You Need for This Lesson)</h3>



<p>Hydra is a configuration framework from Facebook Research that lets us manage all training settings (e.g., model hyperparameters, data parameters, and trainer options) in clean, reusable YAML files. Instead of hard-coding values inside Python, Hydra loads these configs automatically and lets you override anything from the command line.</p>



<p>This makes your training pipeline more reproducible, easier to maintain, and far more MLOps-friendly.</p>



<p>For example, you can change batch size, learning rate, or precision without editing the code:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Training with PyTorch Lightning: Structured MLOps Development" data-enlighter-group="4">python src/train.py data.batch_size=16 model.lr=3e-5 trainer.precision=16-mixed</pre>



<p>Hydra merges the YAML configs at runtime (using <code data-enlighter-language="python" class="EnlighterJSRAW">config.yaml</code> as the root), giving us a clean and scalable way to manage experiments.</p>



<p>Now that we understand how the project is organized and how Hydra helps us control training behavior, let us implement the <code data-enlighter-language="python" class="EnlighterJSRAW">LightningDataModule</code> and build the first part of our training pipeline.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-PyTorch-LightningDataModule-Explained-Building-Efficient-Data-Pipelines"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-PyTorch-LightningDataModule-Explained-Building-Efficient-Data-Pipelines">PyTorch LightningDataModule Explained: Building Efficient Data Pipelines</a></h2>



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">LightningDataModule</code> is one of the most important building blocks in PyTorch Lightning. It packages every data-related responsibility (e.g., downloading, preprocessing, tokenizing, and creating data loaders) into a single reusable module. This keeps your training loop clean and preserves a sharp separation between <em>data code</em> and <em>model code</em>, which is essential in any production-ready MLOps workflow.</p>



<p>In sentiment classification, the DataModule encapsulates 3 main tasks:</p>



<ul class="wp-block-list">
<li><strong>loading the IMDB dataset:</strong> from Hugging Face</li>



<li><strong>tokenizing text:</strong> using a pretrained Transformer tokenizer</li>



<li><strong>producing data loaders:</strong> for train, validation, and test splits</li>
</ul>



<p>Let us walk through the implementation step-by-step.</p>



<p>Before we start examining the class, let us begin with the imports that power this component of the pipeline:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Training with PyTorch Lightning: Structured MLOps Development" data-enlighter-group="5">import pytorch_lightning as pl
from datasets import load_dataset
from torch.utils.data import DataLoader
from transformers import AutoTokenizer</pre>



<p>These 4 imports define everything the DataModule needs. <code data-enlighter-language="python" class="EnlighterJSRAW">pytorch_lightning</code> gives us the <code data-enlighter-language="python" class="EnlighterJSRAW">LightningDataModule</code> base class, which enforces a structured, reproducible way to manage data. <code data-enlighter-language="python" class="EnlighterJSRAW">load_dataset</code> from Hugging Face handles downloading and preparing the IMDB dataset.</p>



<p>PyTorch’s <code data-enlighter-language="python" class="EnlighterJSRAW">DataLoader</code> will assemble batches and handle multiprocessing, and <code data-enlighter-language="python" class="EnlighterJSRAW">AutoTokenizer</code> loads the correct tokenizer for whichever transformer model we choose in the configuration.</p>



<p>Now that the foundations are clear, let us walk through the class itself.</p>



<h3 class="wp-block-heading">Initializing the DataModule (__init__)</h3>



<p>The constructor sets up every configurable part of the data pipeline.</p>



<p>Here is the code block we are examining:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Training with PyTorch Lightning: Structured MLOps Development" data-enlighter-group="6">class SentimentDataModule(pl.LightningDataModule):
    def __init__(
        self,
        model_name: str = "distilbert-base-uncased",
        dataset_name: str = "imdb",
        max_length: int = 128,
        batch_size: int = 8,
        num_workers: int = 4,
        **kwargs
    ):
        super().__init__()
        self.save_hyperparameters()
        
        self.model_name = model_name
        self.dataset_name = dataset_name
        self.max_length = max_length
        self.batch_size = batch_size
        self.num_workers = num_workers
        
        self.tokenizer = None
        self.train_dataset = None
        self.val_dataset = None
        self.test_dataset = None</pre>



<p>The class inherits from <code data-enlighter-language="python" class="EnlighterJSRAW">pl.LightningDataModule</code>, which means Lightning expects this object to implement the standard methods (<code data-enlighter-language="python" class="EnlighterJSRAW">prepare_data</code>, <code data-enlighter-language="python" class="EnlighterJSRAW">setup</code>, and the data loaders). The constructor receives all runtime-configurable parameters (e.g., which model tokenizer to use, which dataset to load, how long sequences should be, and what batch size to apply). These values are stored as instance attributes, but they are also captured automatically through <code data-enlighter-language="python" class="EnlighterJSRAW">self.save_hyperparameters()</code>, enabling 2 important MLOps behaviors: experiment reproducibility and checkpoint metadata tracking.</p>



<p>The module initializes empty placeholders for the tokenizer and each dataset split. Nothing is loaded at this point. This keeps initialization fast, makes the DataModule safe for multiprocessing, and follows Lightning’s recommended pattern where all heavyweight work happens in the next 2 methods: <code data-enlighter-language="python" class="EnlighterJSRAW">prepare_data()</code> and <code data-enlighter-language="python" class="EnlighterJSRAW">setup()</code>.</p>



<h3 class="wp-block-heading">prepare_data(): One-Time Download Step</h3>



<p>Next is the method <code data-enlighter-language="python" class="EnlighterJSRAW">prepare_data()</code> that Lightning calls exactly once on a single process:</p>



<p>The constructor receives all hyperparameters needed to configure data preprocessing. Hydra will pass these values at runtime.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Training with PyTorch Lightning: Structured MLOps Development" data-enlighter-group="7">def prepare_data(self):
    load_dataset(self.dataset_name)
    AutoTokenizer.from_pretrained(self.model_name)</pre>



<p><code data-enlighter-language="python" class="EnlighterJSRAW">prepare_data()</code> is responsible only for downloading the dataset and the tokenizer files. It does <strong>not</strong> tokenize or process anything; that comes later. The logic here intentionally has no side effects and does not assign anything to self. Lightning enforces this behavior because, in distributed training, only one GPU should perform downloads, while every GPU should independently run tokenization and data setup.</p>



<p>This separation is crucial for large-scale MLOps workflows because it prevents race conditions, avoids repetitive downloads, and maintains determinism across runs regardless of device or environment.</p>



<h3 class="wp-block-heading">The setup() Method: Tokenization and Dataset Preparation</h3>



<p>After the one-time download step in <code data-enlighter-language="python" class="EnlighterJSRAW">prepare_data()</code>, Lightning calls the <code data-enlighter-language="python" class="EnlighterJSRAW">setup()</code> method on <strong>every GPU</strong> (or CPU worker) participating in training. This is where the real work happens: tokenization, dataset formatting, and creating the train/validation/test splits. Because each device executes this method independently, the logic inside must be deterministic and side-effect-free, which is a core requirement when building reproducible training pipelines in distributed environments.</p>



<p>Here is the method we are explaining:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Training with PyTorch Lightning: Structured MLOps Development" data-enlighter-group="8">def setup(self, stage=None):
    self.tokenizer = AutoTokenizer.from_pretrained(self.model_name)
    
    if stage == "fit" or stage is None:
        dataset = load_dataset(self.dataset_name)

        self.train_dataset = dataset["train"].map(
            self._tokenize_function,
            batched=True,
            remove_columns=dataset["train"].column_names,
            desc="Tokenizing train set"
        )
        self.train_dataset.set_format("torch")

        self.val_dataset = dataset["test"].map(
            self._tokenize_function,
            batched=True,
            remove_columns=dataset["test"].column_names,
            desc="Tokenizing validation set"
        )
        self.val_dataset.set_format("torch")
    
    if stage == "test" or stage is None:
        dataset = load_dataset(self.dataset_name)
        self.test_dataset = dataset["test"].map(
            self._tokenize_function,
            batched=True,
            remove_columns=dataset["test"].column_names,
            desc="Tokenizing test set"
        )
        self.test_dataset.set_format("torch")</pre>



<p>The first line initializes a fresh tokenizer instance. Lightning may spawn <strong>multiple processes</strong> in Distributed Data Parallel (DDP) or Fully Sharded Data Parallel (FSDP) mode, so each process needs its own tokenizer object. Tokenizers are stateless, lightweight, and safe to re-create, making them ideal for device-local initialization.</p>



<p>Lightning passes a stage identifier depending on what it is doing:</p>



<ul class="wp-block-list">
<li><code data-enlighter-language="python" class="EnlighterJSRAW">fit</code>: when calling <code data-enlighter-language="python" class="EnlighterJSRAW">trainer.fit()</code></li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">validate</code>: when calling <code data-enlighter-language="python" class="EnlighterJSRAW">trainer.validate()</code></li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">test</code>: when calling <code data-enlighter-language="python" class="EnlighterJSRAW">trainer.test()</code></li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">predict</code>: when calling <code data-enlighter-language="python" class="EnlighterJSRAW">trainer.predict()</code></li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">None</code>: Lightning did not specify a stage (certain internal flows)</li>
</ul>



<p>Handling the <code data-enlighter-language="python" class="EnlighterJSRAW">None</code> stage ensures the DataModule works correctly in all cases.</p>



<p>Inside the <code data-enlighter-language="python" class="EnlighterJSRAW">fit</code> stage, we load the Hugging Face dataset. IMDB contains only <code data-enlighter-language="python" class="EnlighterJSRAW">train</code> and <code data-enlighter-language="python" class="EnlighterJSRAW">test</code> splits. Since it does not ship with an official validation set, this lesson uses the <code data-enlighter-language="python" class="EnlighterJSRAW">test</code> split as validation. (In a real production MLOps pipeline, you would do a train/validation split yourself. This note will be added in the blog.)</p>



<p>Next comes tokenization. Hugging Face Datasets operates like a high-performance dataframe.</p>



<p><code data-enlighter-language="python" class="EnlighterJSRAW">.map()</code> applies <code data-enlighter-language="python" class="EnlighterJSRAW">_tokenize_function</code> to <strong>every example or batch</strong>, efficiently processing the dataset:</p>



<ul class="wp-block-list">
<li>processes data in batches automatically</li>



<li>parallelizes when possible</li>



<li>avoids loading everything into memory</li>
</ul>



<p>This is far more efficient and cleaner than writing custom loops.</p>



<p>After tokenization, we call <code data-enlighter-language="python" class="EnlighterJSRAW">self.train_dataset.set_format("torch")</code>. This converts the dataset to output:</p>



<ul class="wp-block-list">
<li><code data-enlighter-language="python" class="EnlighterJSRAW">torch.Tensor</code> for inputs</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">torch.Tensor</code> for labels</li>
</ul>



<p>which is exactly what PyTorch Lightning and the data loader expect. A nearly identical process prepares the validation dataset.</p>



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">test</code> stage works the same way. Lightning may call <code data-enlighter-language="python" class="EnlighterJSRAW">fit</code> and <code data-enlighter-language="python" class="EnlighterJSRAW">test</code> <strong>separately</strong>, so we load and tokenize test data inside its own conditional block.</p>



<p>The logic inside <code data-enlighter-language="python" class="EnlighterJSRAW">setup()</code> must be safe to run:</p>



<ul class="wp-block-list">
<li>once per GPU</li>



<li>once per CPU worker</li>



<li>once per stage</li>
</ul>



<p>This is why nothing is written to disk or downloaded in this method. Everything is device-local: load → tokenize → return.</p>



<p>This is essential for:</p>



<ul class="wp-block-list">
<li>reproducibility</li>



<li>distributed training</li>



<li>multi-node training</li>



<li>deterministic behavior in automated pipelines</li>
</ul>



<h3 class="wp-block-heading">Tokenization Logic: The Heart of Text Preprocessing</h3>



<p>Tokenization is the most important preprocessing step in any natural language processing (NLP) pipeline. It converts raw text into numerical tensors that a Transformer model like DistilBERT can understand. Unlike image data (where pixel arrays are already numeric), text needs to be transformed from variable-length strings into fixed-length integer sequences.</p>



<p>In our DataModule, all tokenization runs through a single helper method:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Training with PyTorch Lightning: Structured MLOps Development" data-enlighter-group="9">def _tokenize_function(self, examples):
    tokenized = self.tokenizer(
        examples["text"],
        truncation=True,
        padding="max_length",
        max_length=self.max_length,
    )
    tokenized["labels"] = examples["label"]
    return tokenized</pre>



<p>Let us break this down step-by-step.</p>



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">_tokenize_function</code> handles the core preprocessing step for every text sample in the dataset. Hugging Face Datasets calls this function in batched mode, so <code data-enlighter-language="python" class="EnlighterJSRAW">examples["text"]</code> is a list of movie reviews rather than a single string. The tokenizer processes the entire batch at once, which is significantly faster than looping over rows individually and also plays nicely with multiprocessing when multiple workers are specified in the data loader.</p>



<p>Inside the tokenizer call, we enable truncation and padding to a fixed <code data-enlighter-language="python" class="EnlighterJSRAW">max_length</code>. Truncation ensures that very long reviews do not exceed the model’s maximum input window, keeping GPU memory usage predictable. Padding ensures that shorter reviews still produce fixed-length tensors, which is not only important for creating uniform batches but also becomes essential later when exporting the model to ONNX or TorchScript in Lesson 2 because both formats expect consistent input shapes.</p>



<p>After tokenization, we attach the corresponding labels by copying <code data-enlighter-language="python" class="EnlighterJSRAW">examples["label"]</code> into the labels field. Hugging Face models expect this exact key during the forward pass when computing classification loss. This small remapping keeps the training step clean because the LightningModule can simply read <code data-enlighter-language="python" class="EnlighterJSRAW">batch["labels"]</code> without any additional preprocessing or renaming logic.</p>



<p>The method finally returns a dictionary containing <code data-enlighter-language="python" class="EnlighterJSRAW">input_ids</code>, <code data-enlighter-language="python" class="EnlighterJSRAW">attention_mask</code>, and <code data-enlighter-language="python" class="EnlighterJSRAW">labels</code>. Lightning and Hugging Face Datasets take care of converting these into PyTorch tensors later when we call <code data-enlighter-language="python" class="EnlighterJSRAW">.set_format("torch")</code> in the <code data-enlighter-language="python" class="EnlighterJSRAW">setup()</code> method. This tokenization pattern is highly scalable because it supports parallel CPU tokenization, remains deterministic for reproducibility, and works seamlessly in multi-GPU environments like DDP or FSDP. It is the same preprocessing approach used in large-scale NLP pipelines, from academic benchmarks to production systems handling millions of records.</p>



<h3 class="wp-block-heading">Why This Approach Scales Well (MLOps Insight)</h3>



<p>A major advantage of this design is how well it scales in real-world MLOps environments. Because <code data-enlighter-language="python" class="EnlighterJSRAW">_tokenize_function</code> is used together with the Hugging Face <code data-enlighter-language="python" class="EnlighterJSRAW">.map()</code> API, tokenization automatically runs in parallel across CPU workers. This gives you high throughput even when preprocessing millions of text samples. More importantly, the transformation is deterministic (the same input will always produce the same tokenized output), which is critical when you need reproducibility across training runs, machines, or distributed setups.</p>



<p>This pattern also integrates cleanly with multi-GPU training strategies (e.g., DDP and FSDP). Each GPU receives its own shard of the dataset and applies the exact same preprocessing logic, avoiding subtle mismatches between processes. Memory usage stays efficient as well, because batches are generated lazily and only the final tensorized output is kept in memory.</p>



<p>Finally, centralizing all preprocessing logic inside a single helper function makes the pipeline easy to maintain. Whether you’re training on a single GPU, scaling out to multiple nodes, or running the same preprocessing for offline batch inference, this structure remains robust. It’s the same approach used in production NLP systems where datasets can reach tens of millions of records and preprocessing needs to remain both fast and reliable.</p>



<h3 class="wp-block-heading">Data Loaders: Batching Data for Training, Validation, and Testing</h3>



<p>Once the dataset has been downloaded, tokenized, and formatted as tensors, the final component of the DataModule is producing PyTorch data loaders. These data loaders handle shuffling, batching, multiprocessing, and memory pinning, which are all needed to efficiently feed data into the model during training.</p>



<p>Here are the 3 data loader methods in our DataModule:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Training with PyTorch Lightning: Structured MLOps Development" data-enlighter-group="10">def train_dataloader(self):
    return DataLoader(
        self.train_dataset,
        batch_size=self.batch_size,
        shuffle=True,
        num_workers=self.num_workers,
        pin_memory=True
    )

def val_dataloader(self):
    return DataLoader(
        self.val_dataset,
        batch_size=self.batch_size,
        shuffle=False,
        num_workers=self.num_workers,
        pin_memory=True
    )

def test_dataloader(self):
    return DataLoader(
        self.test_dataset,
        batch_size=self.batch_size,
        shuffle=False,
        num_workers=self.num_workers,
        pin_memory=True
    )</pre>



<p>Let us walk through these line-by-line.</p>



<p>The final part of the DataModule defines the 3 data loaders Lightning will use for training, validation, and testing. Each method returns a standard PyTorch <code data-enlighter-language="python" class="EnlighterJSRAW">DataLoader</code>, but Lightning wires them together automatically inside <code data-enlighter-language="python" class="EnlighterJSRAW">trainer.fit()</code>, so you do not need to manually pass datasets around.</p>



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">train_dataloader()</code> creates batches from the tokenized training set and enables <code data-enlighter-language="python" class="EnlighterJSRAW">shuffle=True</code>. Shuffling is essential for training stability because it prevents the model from seeing samples in the same order every epoch, which helps it generalize better. The batch size and number of workers come directly from the DataModule’s configuration, allowing Hydra to control them externally.</p>



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">val_dataloader()</code> follows the same structure, except it disables shuffling. Validation should always process data in a fixed order because we want deterministic metrics that reflect model performance, not random input order.</p>



<p>Finally, the <code data-enlighter-language="python" class="EnlighterJSRAW">test_dataloader()</code> mirrors the validation setup (no shuffling and the same batching logic), ensuring that evaluation on the test set is consistent and repeatable.</p>



<p>All 3 data loaders also set <code data-enlighter-language="python" class="EnlighterJSRAW">pin_memory=True</code>, a small but meaningful performance optimization. When using GPUs, pinned memory allows faster host-to-device transfers, reducing input bottlenecks during training. Lightning will automatically handle device placement of data, so the data loaders simply provide ready-to-consume batches.</p>



<p>Overall, these 3 methods complete the DataModule’s lifecycle: downloading, tokenizing, splitting, and packaging the data into efficient data loaders. With these in place, the Trainer can run end-to-end training without any additional data plumbing from your side, which provides exactly the modularity and cleanliness we want in an MLOps-focused codebase.</p>



<h3 class="wp-block-heading">Why This Loader Setup Works Well for MLOps</h3>



<p>This pattern brings several production advantages:</p>



<ul class="wp-block-list">
<li><strong>Works seamlessly with DDP/FSDP across multiple GPUs:</strong> Lightning automatically replicates data loaders across processes</li>



<li><strong>Fully deterministic:</strong> Regenerating the same batches across runs supports experiment reproducibility</li>



<li><strong>Fast I/O due to multiprocessing + pinned memory:</strong> Critical for high-speed training workloads</li>



<li><strong>Clear boundaries for debugging:</strong> If a batch is wrong, you know the issue is in the DataModule, not the model</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-PyTorch-LightningModule-Explained-Building-Modular-Deep-Learning-Models"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-PyTorch-LightningModule-Explained-Building-Modular-Deep-Learning-Models">PyTorch LightningModule Explained: Building Modular Deep Learning Models</a></h2>



<p>The LightningModule is the heart of the training pipeline.</p>



<p>While the DataModule organizes <em>data</em>, the LightningModule organizes <em>learning</em> (the model architecture, forward pass, loss computation, metrics, and optimization strategy).</p>



<p>In plain terms, the LightningModule is where “what the model is” and “how the model learns” are defined.</p>



<p>For sentiment classification, the module wraps a pretrained DistilBERT encoder, adds a small classification head, and implements the training/validation/test logic needed for stable and reproducible NLP experiments.</p>



<h3 class="wp-block-heading">Initialization: Building the Model Architecture</h3>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Training with PyTorch Lightning: Structured MLOps Development" data-enlighter-group="11">class SentimentClassifier(pl.LightningModule):
    def __init__(
        self,
        model_name: str = "distilbert-base-uncased",
        num_labels: int = 2,
        dropout: float = 0.1,
        lr: float = 2e-5,
        weight_decay: float = 0.01,
        **kwargs
    ):
        super().__init__()
        self.save_hyperparameters()

        config = AutoConfig.from_pretrained(model_name)
        self.encoder = AutoModel.from_pretrained(model_name, config=config)

        self.dropout = nn.Dropout(dropout)
        self.classifier = nn.Linear(config.hidden_size, num_labels)

        self.criterion = nn.CrossEntropyLoss()

        self.train_acc = Accuracy(task="multiclass", num_classes=num_labels)
        self.val_acc = Accuracy(task="multiclass", num_classes=num_labels)
        self.val_f1 = F1Score(task="multiclass", num_classes=num_labels, average="macro")</pre>



<p>The constructor defines the core architecture and all hyperparameters needed for training. The use of <code data-enlighter-language="python" class="EnlighterJSRAW">self.save_hyperparameters()</code> ensures that every setting (from model name to learning rate) is automatically captured in Lightning’s checkpoint files. This is extremely valuable in MLOps workflows because it makes every experiment self-describing and fully reproducible.</p>



<p>A DistilBERT encoder is loaded using the Hugging Face <code data-enlighter-language="python" class="EnlighterJSRAW">AutoModel</code>, which instantly gives the model robust language understanding without any manual feature engineering. On top of that encoder, the model adds a simple dropout layer for regularization and a linear classifier to convert the encoded representation into sentiment logits. This small, clean architecture keeps training fast while still benefiting from the power of modern transformers.</p>



<p>Loss and metrics are also initialized here. Cross-entropy is the standard loss function for classification, while Accuracy and F1Score track performance during training and validation. Storing metrics inside the LightningModule keeps the entire training logic encapsulated cleanly in one place.</p>



<h3 class="wp-block-heading">Forward Pass: How the Model Produces Predictions</h3>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Training with PyTorch Lightning: Structured MLOps Development" data-enlighter-group="12">def forward(self, input_ids, attention_mask):
    outputs = self.encoder(
        input_ids=input_ids,
        attention_mask=attention_mask
    )
    pooled = outputs.last_hidden_state[:, 0]
    logits = self.classifier(self.dropout(pooled))
    return logits</pre>



<p>The forward method defines how a batch of tokenized text moves through the model. DistilBERT returns hidden states for all tokens, but for classification tasks it is sufficient to use the representation of the first token (the CLS token). The dropout + linear layer converts this pooled representation into raw class logits. Because we return logits directly, the LightningModule maintains full flexibility for computing loss and metrics in the training, validation, and test loops.</p>



<h3 class="wp-block-heading">Training Step: Computing Loss and Logging Metrics</h3>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Training with PyTorch Lightning: Structured MLOps Development" data-enlighter-group="13">def training_step(self, batch, batch_idx):
    logits = self(batch["input_ids"], batch["attention_mask"])
    loss = self.criterion(logits, batch["labels"])
    preds = torch.argmax(logits, dim=1)
    acc = self.train_acc(preds, batch["labels"])

    self.log("train_loss", loss, on_step=True, on_epoch=True, prog_bar=True)
    self.log("train_acc", acc, on_step=True, on_epoch=True, prog_bar=True)
    return loss</pre>



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">training_step</code> defines exactly how the model learns from each batch. It runs a forward pass, computes the loss against the ground-truth labels, and updates accuracy. Lightning’s <code data-enlighter-language="python" class="EnlighterJSRAW">self.log</code> handles aggregation across GPUs and ensures clean output in both the console and TensorBoard. Because Lightning abstracts away the optimizer step and gradient handling, this method focuses purely on the model’s learning logic rather than the boilerplate.</p>



<h3 class="wp-block-heading">Validation Step: Tracking Generalization</h3>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Training with PyTorch Lightning: Structured MLOps Development" data-enlighter-group="14">def validation_step(self, batch, batch_idx):
    logits = self(batch["input_ids"], batch["attention_mask"])
    loss = self.criterion(logits, batch["labels"])

    preds = torch.argmax(logits, dim=1)
    acc = self.val_acc(preds, batch["labels"])
    f1 = self.val_f1(preds, batch["labels"])

    self.log("val_loss", loss, on_epoch=True, prog_bar=True)
    self.log("val_acc", acc, on_epoch=True, prog_bar=True)
    self.log("val_f1", f1, on_epoch=True)
    return loss</pre>



<p>The validation step mirrors the training step but excludes gradient updates. It focuses entirely on monitoring how well the model generalizes. The addition of F1Score is especially useful in sentiment classification, where class imbalance is common and accuracy alone may hide poor performance on minority classes. Lightning automatically runs this method at the end of each epoch.</p>



<h3 class="wp-block-heading">Test Step: Final Evaluation</h3>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Training with PyTorch Lightning: Structured MLOps Development" data-enlighter-group="15">def test_step(self, batch, batch_idx):
    logits = self(batch["input_ids"], batch["attention_mask"])
    loss = self.criterion(logits, batch["labels"])

    preds = torch.argmax(logits, dim=1)
    acc = Accuracy(task="multiclass", num_classes=self.num_labels).to(self.device)
    test_acc = acc(preds, batch["labels"])

    self.log("test_loss", loss, on_epoch=True)
    self.log("test_acc", test_acc, on_epoch=True)
    return loss</pre>



<p>The test step follows the same pattern but uses dedicated metrics. This design keeps test evaluation separate from training and validation behaviors, which is useful when training and testing happen in different environments (e.g., offline batch scoring in production).</p>



<h3 class="wp-block-heading">Optimizer Configuration: How the Model Learns</h3>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Training with PyTorch Lightning: Structured MLOps Development" data-enlighter-group="16">def configure_optimizers(self):
    no_decay = ["bias", "LayerNorm.weight"]
    optimizer_grouped_parameters = [
        {
            "params": [p for n, p in self.named_parameters()
                       if not any(nd in n for nd in no_decay)],
            "weight_decay": self.weight_decay,
        },
        {
            "params": [p for n, p in self.named_parameters()
                       if any(nd in n for nd in no_decay)],
            "weight_decay": 0.0,
        },
    ]
    return torch.optim.AdamW(optimizer_grouped_parameters, lr=self.lr)</pre>



<p>This method defines how parameters update during training. Transformer models benefit from <code data-enlighter-language="python" class="EnlighterJSRAW">AdamW</code>, but they also require careful separation of weights that should and should not receive weight decay. Lightning lets you return the optimizer directly and handles everything else (e.g., multi-GPU synchronization, gradient scaling, and checkpointing). This keeps optimization logic concise while still following the best practices used in modern NLP training.</p>



<h3 class="wp-block-heading">Why This Optimizer Pattern Matters in MLOps</h3>



<p>This optimizer setup does more than just “train the model.”</p>



<p>By grouping parameters with and without weight decay, you ensure that every training run behaves consistently (regardless of hardware, environment, or number of GPUs). This is important for reproducibility because small optimizer differences can lead to diverging results in downstream evaluations.</p>



<p>Lightning also tracks the optimizer state inside checkpoints, which means that if training is resumed (perhaps in a new environment or after a failure), the run picks up with the exact same momentum buffers and learning dynamics. This is essential for building reliable training pipelines in real MLOps workflows.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Using-Hydra-Python-Configuration-Files-Reproducible-ML-Training"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Using-Hydra-Python-Configuration-Files-Reproducible-ML-Training">Using Hydra Python Configuration Files for Reproducible ML Training</a></h2>



<p>Hydra is the backbone of the training workflow in Lesson 1. Instead of hard-coding hyperparameters inside Python scripts, all settings for the model, data pipeline, and Trainer are stored cleanly inside YAML files. This keeps the codebase flexible, reproducible, and highly MLOps-friendly.</p>



<p>Hydra loads and composes these files automatically through the decorator in <code data-enlighter-language="python" class="EnlighterJSRAW">train.py</code>, and you can override any value at runtime from the command line.</p>



<p>Let’s walk through each configuration file used in Lesson 1.</p>



<h3 class="wp-block-heading">Root Configuration: configs/config.yaml</h3>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Training with PyTorch Lightning: Structured MLOps Development" data-enlighter-group="17">defaults:
  - model: distilbert
  - data: imdb
  - trainer: default
  - _self_

seed: 42</pre>



<p>This is the entry point Hydra reads first.</p>



<p>The defaults block instructs Hydra to compose the final configuration from:</p>



<ul class="wp-block-list">
<li><code data-enlighter-language="python" class="EnlighterJSRAW">configs/model/distilbert.yaml</code></li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">configs/data/imdb.yaml</code></li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">configs/trainer/default.yaml</code></li>
</ul>



<p>The final line, <code data-enlighter-language="python" class="EnlighterJSRAW">seed: 42</code>, becomes <code data-enlighter-language="python" class="EnlighterJSRAW">cfg.seed</code> inside <code data-enlighter-language="python" class="EnlighterJSRAW">train.py</code>, and controls reproducibility through <code data-enlighter-language="python" class="EnlighterJSRAW">pl.seed_everything()</code>.</p>



<p>This root file defines <strong>what experiment you’re running</strong>, while the nested configs define <strong>how each component behaves</strong>.</p>



<h3 class="wp-block-heading">Model Configuration: configs/model/distilbert.yaml</h3>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Training with PyTorch Lightning: Structured MLOps Development" data-enlighter-group="18">model_name: distilbert-base-uncased
num_labels: 2
learning_rate: 2e-5
weight_decay: 0.01
dropout: 0.1</pre>



<p>These values are passed directly into:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Training with PyTorch Lightning: Structured MLOps Development" data-enlighter-group="19">model = SentimentClassifier(**cfg.model)</pre>



<p>Meaning:</p>



<ul class="wp-block-list">
<li><code data-enlighter-language="python" class="EnlighterJSRAW">model_name</code>: selects the Hugging Face backbone.</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">num_labels</code>: controls the classification head.</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">learning_rate</code>, <code data-enlighter-language="python" class="EnlighterJSRAW">weight_decay</code>, and <code data-enlighter-language="python" class="EnlighterJSRAW">dropout</code>: feed into the optimizer and architecture.</li>
</ul>



<p>No values are hard-coded in Python, which is a major MLOps best practice that simplifies experiment tracking and hyperparameter sweeps.</p>



<h3 class="wp-block-heading">Data Configuration: configs/data/imdb.yaml</h3>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Training with PyTorch Lightning: Structured MLOps Development" data-enlighter-group="20">batch_size: 8
max_length: 128
num_workers: 4</pre>



<p>These values are injected directly into the DataModule:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Training with PyTorch Lightning: Structured MLOps Development" data-enlighter-group="21">datamodule = SentimentDataModule(
    model_name=cfg.model.model_name,
    **cfg.data
)</pre>



<p>They control:</p>



<ul class="wp-block-list">
<li>how the data loader batches samples</li>



<li>how long each sequence can be after tokenization</li>



<li>how many CPU workers are used for preprocessing</li>
</ul>



<p>This separation keeps the data pipeline reusable across models and experiments.</p>



<h3 class="wp-block-heading">Trainer Configuration: configs/trainer/default.yaml</h3>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Training with PyTorch Lightning: Structured MLOps Development" data-enlighter-group="22">max_epochs: 3
devices: 1
accelerator: auto
precision: 32</pre>



<p>These settings define how Lightning’s Trainer behaves:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Training with PyTorch Lightning: Structured MLOps Development" data-enlighter-group="23">trainer = pl.Trainer(**cfg.trainer, ...)</pre>



<p>The values specify:</p>



<ul class="wp-block-list">
<li>number of training epochs</li>



<li>how many devices (CPUs/GPUs) to use</li>



<li>mixed precision strategy (FP32 for Lesson 1)</li>



<li>automatic device selection (auto chooses CPU or GPU as available)</li>
</ul>



<p>In Lesson 2, this same configuration pattern will allow you to enable DDP, FSDP, and mixed precision with <strong>zero Python code changes</strong>, requiring only new YAML overrides.</p>



<h3 class="wp-block-heading">Why This Configuration System Is Critical for MLOps</h3>



<p>Hydra gives you:</p>



<ul class="wp-block-list">
<li>clean separation of concerns</li>



<li>reproducible experiments (config + code define a run)</li>



<li>easy command-line overrides</li>



<li>composable, hierarchical configurations</li>



<li>effortless scaling for future lessons (distributed training, mixed precision, exports)</li>
</ul>



<p>This structure is what makes the whole training pipeline “industrial-ready” instead of being a one-off script.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Building-PyTorch-Lightning-Training-Pipeline-train-py"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Building-PyTorch-Lightning-Training-Pipeline-train-py">Building a PyTorch Lightning Training Pipeline with train.py</a></h2>



<p>The training script is the glue that brings the entire pipeline together. Up to this point, you built a clean DataModule for handling data, a LightningModule for modeling logic, and a Hydra configuration system for reproducibility. Now, <code data-enlighter-language="python" class="EnlighterJSRAW">train.py</code> uses all three to create a fully configurable training workflow without requiring manual training loops.</p>



<p>This script intentionally contains <strong>no data processing, no model logic, and no hard-coded hyperparameters</strong>. Instead, everything is driven by Hydra configs and Lightning abstractions, making the training pipeline reproducible, maintainable, and MLOps-friendly.</p>



<p>Let us walk through each component.</p>



<h3 class="wp-block-heading">Hydra Configuration Loading</h3>



<p>The script begins with Hydra’s decorator:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Training with PyTorch Lightning: Structured MLOps Development" data-enlighter-group="24">@hydra.main(config_path="../configs", config_name="config", version_base=None)
def main(cfg: DictConfig):</pre>



<p>This single line gives the entire training pipeline a powerful configuration system. Hydra automatically:</p>



<ul class="wp-block-list">
<li>loads all YAML files under <code data-enlighter-language="python" class="EnlighterJSRAW">configs/</code></li>



<li>composes them into a single cfg object</li>



<li>injects trainer, data, and model settings dynamically</li>



<li>allows overrides at runtime:</li>
</ul>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Training with PyTorch Lightning: Structured MLOps Development" data-enlighter-group="25">python src/train.py trainer.max_epochs=5 model.lr=3e-5</pre>



<p>This configuration-first approach is a hallmark of modern MLOps workflows: the training script stays stable while configs change between runs.</p>



<h3 class="wp-block-heading">Ensuring Reproducibility</h3>



<p>Before building any components, you fix the training seed:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Training with PyTorch Lightning: Structured MLOps Development" data-enlighter-group="26">pl.seed_everything(cfg.seed, workers=True)</pre>



<p>This sets random seeds across PyTorch, CUDA, NumPy, and Python itself. With <code data-enlighter-language="python" class="EnlighterJSRAW">workers=True</code>, Lightning synchronizes DataLoader workers as well.</p>



<p>In MLOps pipelines, deterministic behavior is essential for:</p>



<ul class="wp-block-list">
<li>debugging</li>



<li>regression testing</li>



<li>comparing experiments fairly</li>



<li>tracking drift in downstream metrics</li>
</ul>



<p>Seeding makes every run repeatable.</p>



<h3 class="wp-block-heading">Initializing the DataModule and Model</h3>



<p>Next, the script constructs the full data pipeline:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Training with PyTorch Lightning: Structured MLOps Development" data-enlighter-group="27">datamodule = SentimentDataModule(
    model_name=cfg.model.model_name,
    **cfg.data
)</pre>



<p>Hydra provides the dataset name, batch size, sequence length, tokenizer model, and <code data-enlighter-language="python" class="EnlighterJSRAW">num_workers</code>.</p>



<p>Because all preprocessing logic is encapsulated inside the DataModule, the training script remains clean and focused.</p>



<p>Then the model is initialized:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Training with PyTorch Lightning: Structured MLOps Development" data-enlighter-group="28">model = SentimentClassifier(**cfg.model)</pre>



<p>Every hyperparameter (e.g., learning rate, dropout, and number of labels) flows directly from the configuration. This separation between code and configuration makes the training pipeline:</p>



<ul class="wp-block-list">
<li>easier to maintain</li>



<li>safer to scale</li>



<li>more reproducible across teams and environments</li>
</ul>



<h3 class="wp-block-heading">Configuring Callbacks (Checkpointing + LR Monitoring)</h3>



<p>Callbacks enable essential training behaviors without cluttering the model code.</p>



<h4 class="wp-block-heading">ModelCheckpoint</h4>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Training with PyTorch Lightning: Structured MLOps Development" data-enlighter-group="29">checkpoint_callback = ModelCheckpoint(
    dirpath="checkpoints",
    filename="best-{epoch:02d}-{val_acc:.4f}",
    monitor="val_acc",
    mode="max",
    save_top_k=1,
    save_last=True,
    verbose=True
)</pre>



<p>This callback:</p>



<ul class="wp-block-list">
<li>saves the best model based on validation accuracy</li>



<li>keeps the last checkpoint for safety</li>



<li>stores everything in a structured directory (checkpoints/)</li>



<li>generates readable filenames</li>
</ul>



<p>This makes it trivial to reload the best model for evaluation or deployment.</p>



<h4 class="wp-block-heading">LearningRateMonitor</h4>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Training with PyTorch Lightning: Structured MLOps Development" data-enlighter-group="30">lr_monitor = LearningRateMonitor(logging_interval="step")</pre>



<p>This tracks how the learning rate changes during training. LR patterns are important indicators of:</p>



<ul class="wp-block-list">
<li>instability</li>



<li>vanishing gradients</li>



<li>misconfigured schedulers</li>



<li>early plateauing</li>
</ul>



<p>Both callbacks are added to the Trainer:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Training with PyTorch Lightning: Structured MLOps Development" data-enlighter-group="31">callbacks = [checkpoint_callback, lr_monitor]</pre>



<h3 class="wp-block-heading">Logging with TensorBoard</h3>



<p>Lightning integrates cleanly with TensorBoard through:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Training with PyTorch Lightning: Structured MLOps Development" data-enlighter-group="32">logger = TensorBoardLogger(
    save_dir="logs",
    name="sentiment_classifier"
)</pre>



<p>The logger records:</p>



<ul class="wp-block-list">
<li>loss curves</li>



<li>accuracy</li>



<li>learning rate</li>



<li>hyperparameters (optional)</li>
</ul>



<p>You can visualize results with:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Training with PyTorch Lightning: Structured MLOps Development" data-enlighter-group="33">tensorboard --logdir logs/</pre>



<p>In Lesson 2 and later modules, this logging layer leads naturally into MLflow, W&amp;B, or Langfuse for real MLOps observability.</p>



<h3 class="wp-block-heading">Constructing the Trainer</h3>



<p>Lightning’s Trainer consolidates all runtime behavior into one object:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Training with PyTorch Lightning: Structured MLOps Development" data-enlighter-group="34">trainer = pl.Trainer(
    **cfg.trainer,
    callbacks=callbacks,
    logger=logger,
    enable_progress_bar=True
)</pre>



<p>Hydra injects:</p>



<ul class="wp-block-list">
<li>accelerator (cpu/gpu)</li>



<li>devices</li>



<li>precision</li>



<li>max epochs</li>



<li>gradient clipping</li>



<li>logging frequency</li>
</ul>



<p>This makes the script hardware-agnostic. In Lesson 2, you will enable DDP, FSDP, and mixed precision simply by changing the trainer config without modifying the Python code.</p>



<h3 class="wp-block-heading">Launching Training</h3>



<p>Finally, the entire pipeline is executed with:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Training with PyTorch Lightning: Structured MLOps Development" data-enlighter-group="35">trainer.fit(model, datamodule)</pre>



<p>This one method call triggers:</p>



<ul class="wp-block-list">
<li>dataset downloading (<code data-enlighter-language="python" class="EnlighterJSRAW">prepare_data</code>)</li>



<li>tokenization (<code data-enlighter-language="python" class="EnlighterJSRAW">setup</code>)</li>



<li>data loader creation</li>



<li>training and validation loops</li>



<li>checkpointing</li>



<li>logging</li>
</ul>



<p>After training completes, the script prints useful summary information:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Training with PyTorch Lightning: Structured MLOps Development" data-enlighter-group="36">best_checkpoint = checkpoint_callback.best_model_path
val_acc = trainer.callback_metrics.get("val_acc", 0)
val_loss = trainer.callback_metrics.get("val_loss", 0)</pre>



<p>This delivers the key metrics needed for evaluation or comparison with future runs.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Running-Model-Inference-PyTorch-Lightning-DistilBERT"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Running-Model-Inference-PyTorch-Lightning-DistilBERT">Running Model Inference with PyTorch Lightning and DistilBERT</a></h2>



<p>Once training is complete, the next step in any ML or MLOps workflow is deploying the model for inference. Lesson 1 focuses on offline inference (i.e., running predictions locally using the saved checkpoints). Your inference script is flexible and production-ready, supporting 4 different usage modes:</p>



<ul class="wp-block-list">
<li><strong>Single-text prediction</strong></li>



<li><strong>Batch prediction from a file</strong></li>



<li><strong>Interactive command-line mode</strong></li>



<li><strong>Demo mode with predefined reviews</strong></li>
</ul>



<p>This section walks through every component of the script and explains how it all fits together.</p>



<p>Here is the full header and imports:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Training with PyTorch Lightning: Structured MLOps Development" data-enlighter-group="37">import argparse
from pathlib import Path
import torch
from transformers import AutoTokenizer
from model_module import SentimentClassifier</pre>



<p>The imports bring in <code data-enlighter-language="python" class="EnlighterJSRAW">argparse</code> for command-line parsing, torch for tensor and device management, <code data-enlighter-language="python" class="EnlighterJSRAW">AutoTokenizer</code> for text preprocessing, and your trained LightningModule class <code data-enlighter-language="python" class="EnlighterJSRAW">SentimentClassifier</code>. <code data-enlighter-language="python" class="EnlighterJSRAW">Path</code> is imported but not strictly required in this version; that’s fine and easy to reuse later.</p>



<h3 class="wp-block-heading">Loading the Trained Model</h3>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Training with PyTorch Lightning: Structured MLOps Development" data-enlighter-group="38">def load_model(checkpoint_path: str):
    """Load trained model from checkpoint."""
    print(f"Loading model from {checkpoint_path}...")
    # Load to CPU first to avoid device mismatch issues
    # Works for checkpoints saved on any device (CPU/CUDA/MPS/multi-GPU)
    model = SentimentClassifier.load_from_checkpoint(
        checkpoint_path,
        map_location="cpu"
    )
    model.eval()
    model.freeze()
    print("✅ Model loaded successfully!\n")
    return model</pre>



<p><code data-enlighter-language="python" class="EnlighterJSRAW">load_model()</code> encapsulates everything needed to restore the model from disk. It prints which checkpoint is being loaded for transparency, then uses Lightning’s <code data-enlighter-language="python" class="EnlighterJSRAW">load_from_checkpoint()</code> to rebuild the full <code data-enlighter-language="python" class="EnlighterJSRAW">SentimentClassifier</code> with weights and hyperparameters. </p>



<p>Setting <code data-enlighter-language="python" class="EnlighterJSRAW">map_location="cpu"</code> guarantees that the checkpoint can be loaded no matter where it was trained (single GPU, multi-GPU, CPU, MPS). Calling <code data-enlighter-language="python" class="EnlighterJSRAW">eval()</code> puts the model into inference mode, turning off dropout and other training-only behaviors, and <code data-enlighter-language="python" class="EnlighterJSRAW">freeze()</code> disables gradients so the model becomes a pure forward-pass computation graph. Finally, it prints a success message and returns the ready-to-use model.</p>



<h3 class="wp-block-heading">Predicting Sentiment for a Single Text</h3>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Training with PyTorch Lightning: Structured MLOps Development" data-enlighter-group="39">def predict_sentiment(model, tokenizer, text: str, device: str = "auto"):
    """Predict sentiment for a single text."""
    # Tokenize input
    encoding = tokenizer(
        text,
        max_length=128,
        padding="max_length",
        truncation=True,
        return_tensors="pt"
    )
    
    # Move to device
    if device == "auto":
        device = "cuda" if torch.cuda.is_available() else "cpu"
    
    input_ids = encoding["input_ids"].to(device)
    attention_mask = encoding["attention_mask"].to(device)
    model = model.to(device)
    
    # Get prediction
    with torch.no_grad():
        logits = model(input_ids, attention_mask)
        probs = torch.softmax(logits, dim=1)
        pred_class = torch.argmax(probs, dim=1).item()
        confidence = probs[0, pred_class].item()
    
    sentiment = "Positive 😊" if pred_class == 1 else "Negative 😞"
    
    return {
        "text": text,
        "sentiment": sentiment,
        "confidence": confidence,
        "label": pred_class
    }</pre>



<p><code data-enlighter-language="python" class="EnlighterJSRAW">predict_sentiment()</code> is the core prediction helper. It starts by tokenizing the input text using the same tokenizer settings as training: <code data-enlighter-language="python" class="EnlighterJSRAW">max_length=128</code>, <code data-enlighter-language="python" class="EnlighterJSRAW">truncation=True</code>, and <code data-enlighter-language="python" class="EnlighterJSRAW">padding="max_length"</code>. This ensures the input tensor shape is fixed and consistent with what DistilBERT expects, which is also helpful later when exporting to ONNX/TorchScript.</p>



<p>The device argument defaults to <code data-enlighter-language="python" class="EnlighterJSRAW">"auto"</code>, which makes the function portable. If <code data-enlighter-language="python" class="EnlighterJSRAW">"auto"</code> is requested, it checks whether CUDA is available and chooses GPU when possible, otherwise falls back to CPU. Both the <code data-enlighter-language="python" class="EnlighterJSRAW">input_ids</code> and <code data-enlighter-language="python" class="EnlighterJSRAW">attention_masktensors</code> are moved onto that device, and the model itself is also transferred using <code data-enlighter-language="python" class="EnlighterJSRAW">model.to(device)</code>. This guarantees that all tensors and the model live on the same device, avoiding runtime errors.</p>



<p>Inside a <code data-enlighter-language="python" class="EnlighterJSRAW">torch.no_grad()</code> block, the function performs a forward pass: it feeds <code data-enlighter-language="python" class="EnlighterJSRAW">input_ids</code> and <code data-enlighter-language="python" class="EnlighterJSRAW">attention_mask</code> into the model, gets raw logits, converts them into probabilities with <code data-enlighter-language="python" class="EnlighterJSRAW">torch.softmax</code>, and then finds the predicted class with <code data-enlighter-language="python" class="EnlighterJSRAW">torch.argmax</code>. The <code data-enlighter-language="python" class="EnlighterJSRAW">.item()</code> calls convert these tiny tensors into regular Python scalars. The sentiment string maps class 1 to positive and everything else to negative, adding emoji for an immediately readable result. Finally, the function returns a dictionary containing the original text, the sentiment label, confidence score, and numeric class. This output is easy to print, log, or send through an API.</p>



<h3 class="wp-block-heading">Interactive Inference Mode</h3>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Training with PyTorch Lightning: Structured MLOps Development" data-enlighter-group="40">def interactive_mode(model, tokenizer):
    """Interactive inference mode."""
    print("=" * 70)
    print("Interactive Sentiment Analysis")
    print("=" * 70)
    print("\nType your movie review and press Enter.")
    print("Type 'quit' or 'exit' to stop.\n")
    
    while True:
        text = input(" Review: ").strip()
        
        if text.lower() in ['quit', 'exit', 'q']:
            print("\n Goodbye!")
            break
        
        if not text:
            continue
        
        result = predict_sentiment(model, tokenizer, text)
        
        print(f"\n{'='*70}")
        print(f"Sentiment: {result['sentiment']}")
        print(f"Confidence: {result['confidence']:.2%}")
        print(f"{'='*70}\n")</pre>



<p><code data-enlighter-language="python" class="EnlighterJSRAW">interactive_mode()</code> turns the script into a small command-line app. It prints a header and basic instructions, then enters an infinite loop. Each iteration reads a line from <code data-enlighter-language="python" class="EnlighterJSRAW">input()</code>, trims whitespace, and checks for exit commands (<code data-enlighter-language="python" class="EnlighterJSRAW">quit</code>, <code data-enlighter-language="python" class="EnlighterJSRAW">exit</code>, <code data-enlighter-language="python" class="EnlighterJSRAW">q</code>). Empty lines are ignored so the user doesn’t accidentally trigger computation.</p>



<p>For valid text, it calls <code data-enlighter-language="python" class="EnlighterJSRAW">predict_sentiment()</code> with the provided model and tokenizer. The results are printed in a nicely formatted block, showing the sentiment label and confidence percentage. This mode is perfect for quickly sanity-checking the model, exploring its behavior, and giving students an immediate feel for how the classifier responds to different reviews.</p>



<h3 class="wp-block-heading">Batch Inference from a Text File</h3>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Training with PyTorch Lightning: Structured MLOps Development" data-enlighter-group="41">def batch_inference(model, tokenizer, input_file: str):
    """Run inference on multiple texts from file."""
    print(f"Reading texts from {input_file}...")
    
    with open(input_file, 'r') as f:
        texts = [line.strip() for line in f if line.strip()]
    
    print(f"Running inference on {len(texts)} samples...\n")
    print("=" * 70)
    
    results = []
    for i, text in enumerate(texts, 1):
        result = predict_sentiment(model, tokenizer, text)
        results.append(result)
        
        print(f"\n{i}. {text[:60]}{'...' if len(text) > 60 else ''}")
        print(f"   → {result['sentiment']} ({result['confidence']:.2%})")
    
    print("\n" + "=" * 70)
    print(f"\n Processed {len(results)} samples")
    
    # Summary statistics
    positive = sum(1 for r in results if r['label'] == 1)
    negative = len(results) - positive
    avg_confidence = sum(r['confidence'] for r in results) / len(results)
    
    print(f"\n Summary:")
    print(f"   Positive: {positive} ({positive/len(results):.1%})")
    print(f"   Negative: {negative} ({negative/len(results):.1%})")
    print(f"   Avg Confidence: {avg_confidence:.2%}")</pre>



<p><code data-enlighter-language="python" class="EnlighterJSRAW">batch_inference()</code> is designed for real-world workflows where you want to score multiple reviews at once. It accepts a path to a file, reads all non-empty lines into a list, and reports how many samples it found. For each line, it calls <code data-enlighter-language="python" class="EnlighterJSRAW">predict_sentiment()</code> and prints out a truncated version of the text plus its predicted sentiment and confidence. Results are collected into a list so you can compute summary statistics afterward.</p>



<p>At the end, it computes how many predictions were positive vs negative and the average confidence across all samples. Those aggregate metrics are useful when running offline evaluations, batch scoring jobs, or quick experiments. This pattern also generalizes well to production pipelines where you might later replace the file input with a database, message queue, or data warehouse.</p>



<h3 class="wp-block-heading">Demo Mode with Sample Reviews</h3>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Training with PyTorch Lightning: Structured MLOps Development" data-enlighter-group="42">def demo_mode(model, tokenizer):
    """Run demo with sample reviews."""
    print("=" * 70)
    print("Demo: Sample Movie Reviews")
    print("=" * 70)
    
    sample_reviews = [
        "This movie was absolutely fantastic! Best film I've seen this year.",
        "Terrible movie, complete waste of time. Boring and poorly acted.",
        "The plot was confusing and the ending made no sense."
    ]
    
    print(f"\nTesting {len(sample_reviews)} sample reviews...\n")
    
    for i, text in enumerate(sample_reviews, 1):
        result = predict_sentiment(model, tokenizer, text)
        print(f"{i}. {text}")
        print(f"   → {result['sentiment']} ({result['confidence']:.2%})\n")
    
    print("=" * 70)</pre>



<p><code data-enlighter-language="python" class="EnlighterJSRAW">demo_mode()</code> is a curated, zero-configuration way to showcase the model. It defines a fixed list of sample movie reviews that cover positive, negative, and neutral-ish cases. It prints a header, shows how many samples will be tested, and then iterates through each review, calling <code data-enlighter-language="python" class="EnlighterJSRAW">predict_sentiment()</code> under the hood. The output is a neat numbered list with the original sentence and the corresponding sentiment and confidence.</p>



<p>This is ideal for teaching, demos, and quick regression checks after changing code or dependencies. If the demo suddenly behaves strangely, you know something is wrong.</p>



<h3 class="wp-block-heading">Command-Line Interface and Mode Routing</h3>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Training with PyTorch Lightning: Structured MLOps Development" data-enlighter-group="43">def main():
    parser = argparse.ArgumentParser(description="Sentiment Classification Inference")
    parser.add_argument(
        "--checkpoint",
        type=str,
        required=True,
        help="Path to model checkpoint (e.g., checkpoints/best-*.ckpt)"
    )
    parser.add_argument(
        "--text",
        type=str,
        help="Single text to classify"
    )
    parser.add_argument(
        "--input-file",
        type=str,
        help="File with texts to classify (one per line)"
    )
    parser.add_argument(
        "--demo",
        action="store_true",
        help="Run demo with sample reviews"
    )
    parser.add_argument(
        "--device",
        type=str,
        default="auto",
        choices=["auto", "cpu", "cuda", "mps"],
        help="Device to run inference on"
    )
    
    args = parser.parse_args()
    
    # Load model
    model = load_model(args.checkpoint)
    
    # Load tokenizer
    print("Loading tokenizer...")
    tokenizer = AutoTokenizer.from_pretrained(model.hparams.model_name)
    print("Tokenizer loaded\n")
    
    # Run appropriate mode
    if args.demo:
        demo_mode(model, tokenizer)
    elif args.text:
        result = predict_sentiment(model, tokenizer, args.text, args.device)
        print("=" * 70)
        print(f"Text: {result['text']}")
        print(f"Sentiment: {result['sentiment']}")
        print(f"Confidence: {result['confidence']:.2%}")
        print("=" * 70)
    elif args.input_file:
        batch_inference(model, tokenizer, args.input_file)
    else:
        interactive_mode(model, tokenizer)


if __name__ == "__main__":
    main()</pre>



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">main()</code> function wires everything into a clean CLI interface. argparse defines all supported flags:</p>



<ul class="wp-block-list">
<li><code data-enlighter-language="python" class="EnlighterJSRAW">--checkpoint</code> (required): tells the script which <code data-enlighter-language="python" class="EnlighterJSRAW">.ckpt</code> file to load</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">--text</code>: enables single-text prediction</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">--input-file</code>: enables batch inference from a file</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">--demo</code>: triggers the curated demo mode</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">--device</code>: lets you override the device choice (auto, cpu, cuda, mps)</li>
</ul>



<p>After parsing arguments, <code data-enlighter-language="python" class="EnlighterJSRAW">main()</code> calls <code data-enlighter-language="python" class="EnlighterJSRAW">load_model()</code> to restore the trained Lightning model. It then loads the tokenizer using <code data-enlighter-language="python" class="EnlighterJSRAW">AutoTokenizer.from_pretrained(model.hparams.model_name)</code>, which reads the model name stored in the checkpoint hyperparameters. This ensures inference uses the exact same tokenizer that training used.</p>



<p>Finally, it chooses which mode to run based on the arguments:</p>



<ul class="wp-block-list">
<li>If <code data-enlighter-language="python" class="EnlighterJSRAW">--demo</code> is set: run <code data-enlighter-language="python" class="EnlighterJSRAW">demo_mode()</code></li>



<li>Else if <code data-enlighter-language="python" class="EnlighterJSRAW">--text</code> is provided: run <code data-enlighter-language="python" class="EnlighterJSRAW">predict_sentiment()</code> once and print the result</li>



<li>Else if <code data-enlighter-language="python" class="EnlighterJSRAW">--input-file</code> is provided: run <code data-enlighter-language="python" class="EnlighterJSRAW">batch_inference()</code></li>



<li>Else: fall back to <code data-enlighter-language="python" class="EnlighterJSRAW">interactive_mode()</code></li>
</ul>



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">if __name__ == "__main__":</code> guard makes this file executable as a script and keeps it import-safe if you ever reuse these helpers in a larger app or API.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Training-Evaluating-DistilBERT-Model-PyTorch-Lightning-Hydra"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Training-Evaluating-DistilBERT-Model-PyTorch-Lightning-Hydra">Training and Evaluating a DistilBERT Model with PyTorch Lightning and Hydra</a></h2>



<p>Now that we have built our DataModule, LightningModule, and training script, it is time to run everything end-to-end.</p>



<p>This section walks you through:</p>



<ul class="wp-block-list">
<li>launching training with Hydra</li>



<li>visualizing metrics in TensorBoard</li>



<li>running inference in multiple modes</li>



<li>understanding how Lightning automatically selects the best available device (CUDA, MPS, or CPU)</li>
</ul>



<p>To learn how to run and evaluate your sentiment classifier, just keep reading.</p>



<h3 class="wp-block-heading">Running Training from the Command Line</h3>



<p>You can start a basic training run using:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Training with PyTorch Lightning: Structured MLOps Development" data-enlighter-group="44">$ python src/train.py</pre>



<p>Lightning will automatically download the IMDB dataset, initialize DistilBERT, set seeds, and begin training.
</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Training with PyTorch Lightning: Structured MLOps Development" data-enlighter-group="45">$ python src/train.py
================================================================================
LESSON 1: PyTorch Lightning Fundamentals with Hydra
================================================================================
📋 Configuration:
model:
  model_name: distilbert-base-uncased
  num_labels: 2
  dropout: 0.1
  lr: 2.0e-05
  weight_decay: 0.01
data:
  dataset_name: imdb
  max_length: 128
  batch_size: 8
  num_workers: 4
trainer:
  max_epochs: 3
  accelerator: auto
  devices: 1
  precision: 32
  log_every_n_steps: 10
  check_val_every_n_epoch: 1
  deterministic: false
seed: 42
Seed set to 42
🌱 Seed set to: 42
   → Ensures reproducible results across runs
📊 Initializing DataModule...
   Dataset: imdb
   Batch size: 8
   Max sequence length: 128
🤖 Initializing Model...
   Model: distilbert-base-uncased
   Learning rate: 2e-05
   Number of labels: 2
config.json: 100%|██████████████████████████████| 483/483 [00:00&lt;00:00, 682kB/s]
model.safetensors:   0%|                             | 0.00/268M [00:00&lt;?, ?B/s]</pre>



<p>This screenshot typically includes:</p>



<ul class="wp-block-list">
<li>Hydra-composed config</li>



<li>“Seed set to …”</li>



<li>DataModule initialization logs</li>



<li>Model initialization</li>



<li>Trainer configuration summary</li>
</ul>



<p>It gives readers immediate confidence that the training pipeline is well-structured and reproducible.</p>



<h3 class="wp-block-heading">Overriding Hyperparameters with Hydra</h3>



<p>One of Hydra’s biggest strengths is that it allows you to change any configuration value without modifying a single line of code.</p>



<p>For example, you can increase the number of training epochs:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Training with PyTorch Lightning: Structured MLOps Development" data-enlighter-group="46">$ python src/train.py trainer.max_epochs=5</pre>



<p>Or explore a different learning rate:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Training with PyTorch Lightning: Structured MLOps Development" data-enlighter-group="47">$ python src/train.py model.lr=3e-5</pre>



<p>Or change the batch size:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Training with PyTorch Lightning: Structured MLOps Development" data-enlighter-group="48">$ python src/train.py data.batch_size=16</pre>



<p>Hydra composes the full configuration at runtime and applies the CLI override (<code data-enlighter-language="python" class="EnlighterJSRAW">data.batch_size=16</code>). The screenshot shows the merged YAML, seed setup, DataModule initialization, model initialization, and callback configuration, all without changing a single line of code. This illustrates the core MLOps benefit of configuration-driven training.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://pyimagesearch.com/wp-content/uploads/2026/08/image-7.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="584" height="641" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/08/image-7.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54859"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/08/image-7.png?size=126x138&lossy=2&strip=1&webp=1 126w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/08/image-7-273x300.png?lossy=2&strip=1&webp=1 273w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/08/image-7.png?size=378x415&lossy=2&strip=1&webp=1 378w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/08/image-7.png?size=504x553&lossy=2&strip=1&webp=1 504w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/08/image-7.png?lossy=2&strip=1&webp=1 584w" sizes="(max-width: 584px) 100vw, 584px" /></a><figcaption class="wp-element-caption"><strong>Figure 1:</strong> Hydra Override in Action</figcaption></figure></div>


<p>This is a major <strong>MLOps advantage</strong> because configuration-driven training allows experiments to be repeated, compared, and automated easily.</p>



<h3 class="wp-block-heading">Viewing Logs and Metrics in TensorBoard</h3>



<p>All training metrics are logged to:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Training with PyTorch Lightning: Structured MLOps Development" data-enlighter-group="49">logs/sentiment_classifier/</pre>



<p>You can launch TensorBoard using:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Training with PyTorch Lightning: Structured MLOps Development" data-enlighter-group="50">$ tensorboard --logdir logs/</pre>



<p>This screenshot shows how TensorBoard automatically tracks metrics (e.g., <code data-enlighter-language="python" class="EnlighterJSRAW">val_acc</code> and <code data-enlighter-language="python" class="EnlighterJSRAW">val_loss</code>) for each Hydra-versioned training run. Because the entire pipeline is configuration-driven, you can compare experiments side-by-side by smoothing curves, inspecting run histories, and validating that model performance trends remain consistent across seeds or hyperparameter overrides.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/08/image-8-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="531" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/08/image-8-1024x531.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54860"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/08/image-8-1024x531.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/08/image-8-1024x531.png?size=126x65&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/08/image-8-1024x531.png?size=252x131&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/08/image-8-1024x531.png?size=378x196&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/08/image-8-1024x531.png?size=504x261&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/08/image-8-1024x531.png?size=630x327&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 2:</strong> TensorBoard Visualization of Validation Accuracy and Loss Across Multiple Runs</figcaption></figure></div>


<p>A typical figure here would show:</p>



<ul class="wp-block-list">
<li>Training vs. validation loss</li>



<li>Validation accuracy</li>



<li>Learning rate</li>



<li>Iteration timeline</li>
</ul>



<p>This screenshot reinforces that Lightning + TensorBoard gives you well-structured experiment tracking out of the box.</p>



<h3 class="wp-block-heading">Where Checkpoints Are Saved</h3>



<p>Lightning automatically saves your best checkpoint based on validation accuracy:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Training with PyTorch Lightning: Structured MLOps Development" data-enlighter-group="51">checkpoints/best-epoch=XX-val_acc=YY.ckpt</pre>



<p>It also saves a <code data-enlighter-language="python" class="EnlighterJSRAW">last.ckpt</code> for safety.</p>



<p>Lightning’s ModelCheckpoint callback saves the best-performing model (based on <code data-enlighter-language="python" class="EnlighterJSRAW">val_acc</code>) and the final “<code data-enlighter-language="python" class="EnlighterJSRAW">last.ckpt</code>” snapshot for safety. Because training is fully configuration-driven, each Hydra-run creates its own versioned checkpoint set, making it easy to resume, compare, or deploy models in a reproducible MLOps workflow.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/08/image-9-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="115" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/08/image-9-1024x115.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54862"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/08/image-9-1024x115.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/08/image-9-1024x115.png?size=126x14&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/08/image-9-1024x115.png?size=252x28&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/08/image-9-1024x115.png?size=378x42&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/08/image-9-1024x115.png?size=504x57&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/08/image-9-1024x115.png?size=630x71&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 3:</strong> Checkpoints Generated Automatically by PyTorch Lightning</figcaption></figure></div>


<p>This is often the moment readers see how cleanly Lightning organizes artifacts, which ties directly into the next DVC module.</p>



<h3 class="wp-block-heading">Running Inference (Multiple Modes)</h3>



<p>Once training completes, you can use the inference script in 3 different modes.</p>



<h4 class="wp-block-heading">A) Single-Text Prediction</h4>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Training with PyTorch Lightning: Structured MLOps Development" data-enlighter-group="52">$ python src/inference.py --checkpoint "checkpoints/best-epoch=00-val_acc=0.8797.ckpt" --text "This movie was amazing!"</pre>



<p>The screenshot shows the model being loaded from the selected checkpoint, the tokenizer initialization, and the final prediction with confidence for the given input text.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/08/image-10-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="357" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/08/image-10-1024x357.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54865"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/08/image-10-1024x357.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/08/image-10-1024x357.png?size=126x44&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/08/image-10-1024x357.png?size=252x88&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/08/image-10-1024x357.png?size=378x132&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/08/image-10-1024x357.png?size=504x176&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/08/image-10-1024x357.png?size=630x220&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 4:</strong> Command-line inference using the trained Lightning model</figcaption></figure></div>


<p>Lightning auto-loads the checkpoint, loads the tokenizer, moves tensors to the correct device, and returns a structured prediction.</p>



<h4 class="wp-block-heading">B) Batch Inference from File</h4>



<p>Create a file such as the following:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Training with PyTorch Lightning: Structured MLOps Development" data-enlighter-group="53">samples.txt
This movie was incredible.
The film was a disappointment.
I loved every character!</pre>



<p>Then run:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Training with PyTorch Lightning: Structured MLOps Development" data-enlighter-group="54">$ python src/inference.py \
    --checkpoint checkpoints/best-epoch=*.ckpt \
    --input-file samples.txt</pre>



<p>The screenshot shows the model loading, tokenizer initialization, per-review predictions with confidence scores, and a final summary of positive and negative counts. This demonstrates how the inference pipeline scales cleanly from single inputs to larger batches, which is a key requirement in practical MLOps workflows.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/08/image-11-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="939" height="1024" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/08/image-11-939x1024.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54867"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/08/image-11-939x1024.png?lossy=2&strip=1&webp=1 939w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/08/image-11-939x1024.png?size=126x137&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/08/image-11-939x1024.png?size=252x275&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/08/image-11-939x1024.png?size=378x412&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/08/image-11-939x1024.png?size=504x550&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/08/image-11-939x1024.png?size=630x687&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 939px) 100vw, 939px" /></a><figcaption class="wp-element-caption"><strong>Figure 5:</strong> Batch inference on a text file using the trained sentiment classifier</figcaption></figure></div>


<p>The script also prints a small summary (positive %, negative %, average confidence).</p>



<h4 class="wp-block-heading">C) Interactive Mode</h4>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Training with PyTorch Lightning: Structured MLOps Development" data-enlighter-group="55">$ python src/inference.py \
    --checkpoint checkpoints/best-epoch=*.ckpt</pre>



<p>You can then type reviews manually.</p>



<p><strong>Figure 6</strong> shows the interactive prompt, a sample user review (“The movie was good — just not great.”), and the model’s corresponding prediction with confidence. This mode is ideal for quick testing and showcasing the end-to-end inference flow after training your Lightning model.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/08/image-12-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="642" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/08/image-12-1024x642.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54870"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/08/image-12-1024x642.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/08/image-12-1024x642.png?size=126x79&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/08/image-12-1024x642.png?size=252x158&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/08/image-12-1024x642.png?size=378x237&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/08/image-12-1024x642.png?size=504x316&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/08/image-12-1024x642.png?size=630x395&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 6:</strong> Real-time interactive sentiment analysis from the terminal</figcaption></figure></div>


<p>This mode is great for demos, lightweight testing, or API prototyping.</p>



<h3 class="wp-block-heading">Device Auto-Selection (CPU, GPU, and MPS)</h3>



<p>Your inference script includes this logic:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Training with PyTorch Lightning: Structured MLOps Development" data-enlighter-group="56">if device == "auto":
    device = "cuda" if torch.cuda.is_available() else "cpu"</pre>



<p>When <code data-enlighter-language="python" class="EnlighterJSRAW">device</code> is set to <code data-enlighter-language="python" class="EnlighterJSRAW">"auto"</code>, the script selects a CUDA-enabled graphics processing unit (GPU) if one is available. Otherwise, it selects the central processing unit (CPU). On Macs with Apple Silicon, you can also choose Metal Performance Shaders (MPS) explicitly by setting the device to <code data-enlighter-language="python" class="EnlighterJSRAW">"mps"</code>.</p>



<p>Lightning also handles device selection on the training side:</p>



<ul class="wp-block-list">
<li>If a GPU is available and the trainer is configured to use it, Lightning uses the GPU.</li>



<li>If multiple GPUs are configured, Lightning uses DDP (Lesson 2).</li>



<li>If no supported GPU is available, Lightning falls back to the CPU.</li>
</ul>



<p><strong>Figure 7</strong> confirms that Lightning detected an MPS-capable GPU on macOS and will use it for training. It also reports that no Tensor Processing Unit (TPU) cores are available. This automation allows the training code to run across different hardware configurations without modification.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://pyimagesearch.com/wp-content/uploads/2026/08/image-13.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1022" height="408" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/08/image-13.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54873"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/08/image-13.png?size=126x50&lossy=2&strip=1&webp=1 126w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/08/image-13-300x120.png?lossy=2&strip=1&webp=1 300w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/08/image-13.png?size=378x151&lossy=2&strip=1&webp=1 378w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/08/image-13.png?size=504x201&lossy=2&strip=1&webp=1 504w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/08/image-13.png?size=630x252&lossy=2&strip=1&webp=1 630w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/08/image-13-768x307.png?lossy=2&strip=1&webp=1 768w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/08/image-13.png?lossy=2&strip=1&webp=1 1022w" sizes="(max-width: 1022px) 100vw, 1022px" /></a><figcaption class="wp-element-caption"><strong>Figure 7:</strong> Trainer initialization showing automatic MPS GPU detection</figcaption></figure></div>


<p>This flexibility dramatically improves <strong>developer experience (DX)</strong> because your code can run on any machine.</p>



<h3 class="wp-block-heading">Summary: Why This Section Matters for MLOps</h3>



<p>This “Run and Evaluate” section ties the entire workflow together:</p>



<ul class="wp-block-list">
<li>Hydra makes experiments repeatable and configurable.</li>



<li>Lightning makes training structured and supports deterministic execution when configured appropriately.</li>



<li>TensorBoard provides observability.</li>



<li>Checkpoints preserve model state for downstream deployment.</li>



<li>The inference script demonstrates end-to-end functionality.</li>
</ul>



<p>This is precisely the level of workflow maturity expected in modern MLOps and LLMOps environments.</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<div id="pitch" style="padding: 40px; width: 100%; background-color: #F4F6FA;">
	<h3>What's next? We recommend <a target="_blank" href="https://pyimagesearch.com/pyimagesearch-university/?utm_source=blogPost&utm_medium=bottomBanner&utm_campaign=What%27s%20next%3F%20I%20recommend">PyImageSearch University</a>.</h3>

	<script src="https://fast.wistia.com/embed/medias/kno0cmko2z.jsonp" async></script><script src="https://fast.wistia.com/assets/external/E-v1.js" async></script><div class="wistia_responsive_padding" style="padding:56.25% 0 0 0;position:relative;"><div class="wistia_responsive_wrapper" style="height:100%;left:0;position:absolute;top:0;width:100%;"><div class="wistia_embed wistia_async_kno0cmko2z videoFoam=true" style="height:100%;position:relative;width:100%"><div class="wistia_swatch" style="height:100%;left:0;opacity:0;overflow:hidden;position:absolute;top:0;transition:opacity 200ms;width:100%;"><img decoding="async" src="https://fast.wistia.com/embed/medias/kno0cmko2z/swatch" style="filter:blur(5px);height:100%;object-fit:contain;width:100%;" alt="" aria-hidden="true" onload="this.parentNode.style.opacity=1;" /></div></div></div></div>

	<div style="margin-top: 32px; margin-bottom: 32px; ">
		<strong>Course information:</strong><br/>
		120+ total classes • 115+ hours hours of on-demand code walkthrough videos • Last updated: August 2026<br/>
		<span style="color: #169FE6;">★★★★★</span> 4.84 (128 Ratings) • 16,000+ Students Enrolled
	</div>

	<p><strong>I strongly believe that if you had the right teacher you could <em>master</em> computer vision and deep learning.</strong></p>

	<p>Do you think learning computer vision and deep learning has to be time-consuming, overwhelming, and complicated? Or has to involve complex mathematics and equations? Or requires a degree in computer science?</p>

	<p>That’s <em>not</em> the case.</p>

	<p>All you need to master computer vision and deep learning is for someone to explain things to you in <em>simple, intuitive</em> terms. <em>And that’s exactly what I do</em>. My mission is to change education and how complex Artificial Intelligence topics are taught.</p>

	<p>If you're serious about learning computer vision, your next stop should be PyImageSearch University, the most comprehensive computer vision, deep learning, and OpenCV course online today. Here you’ll learn how to <em>successfully</em> and <em>confidently</em> apply computer vision to your work, research, and projects. Join me in computer vision mastery.</p>

	<p><strong>Inside PyImageSearch University you'll find:</strong></p>

	<ul style="margin-left: 0px;">
		<li style="list-style: none;">&check; <strong>120+ courses</strong> on essential computer vision, deep learning, and OpenCV topics</li>
		<li style="list-style: none;">&check; <strong>94+ Certificates</strong> of Completion</li>
		<li style="list-style: none;">&check; <strong>115+ hours hours</strong> of on-demand video</li>
		<li style="list-style: none;">&check; <strong>Brand new courses released <em>regularly</em></strong>, ensuring you can keep up with state-of-the-art techniques</li>
		<li style="list-style: none;">&check; <strong>Pre-configured Jupyter Notebooks in Google Colab</strong></li>
		<li style="list-style: none;">&check; Run all code examples in your web browser — works on Windows, macOS, and Linux (no dev environment configuration required!)</li>
		<li style="list-style: none;">&check; Access to <strong>centralized code repos for <em>all</em> 540+ tutorials</strong> on PyImageSearch</li>
		<li style="list-style: none;">&check; <strong> Easy one-click downloads</strong> for code, datasets, pre-trained models, etc.</li>
		<li style="list-style: none;">&check; <strong>Access</strong> on mobile, laptop, desktop, etc.</li>
	</ul>

	<p style="text-align: center;">
		<a target="_blank" class="button link" href="https://pyimagesearch.com/pyimagesearch-university/?utm_source=blogPost&utm_medium=bottomBanner&utm_campaign=What%27s%20next%3F%20I%20recommend" style="background-color: #6DC713; border-bottom: none;">Click here to join PyImageSearch University</a>
	</p>
</div>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Summary"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Summary">Summary</a></h2>



<p>In this lesson, you learned how PyTorch Lightning and Hydra work together to bring structure, reproducibility, and MLOps-friendly practices to a modern NLP training pipeline. Instead of writing long, error-prone training loops, Lightning allowed you to organize your project into clean, isolated components: the <code data-enlighter-language="python" class="EnlighterJSRAW">LightningDataModule</code> for handling all data operations and the <code data-enlighter-language="python" class="EnlighterJSRAW">LightningModule</code> for model logic, optimization, and metrics. Hydra completed the picture by giving you a powerful configuration system that let you change hyperparameters, batch sizes, model choices, or even hardware strategies from the command line without touching a single line of Python.</p>



<p>You trained a sentiment classifier on the IMDB dataset using a fully modular workflow, ran experiments with different overrides, visualized metrics in TensorBoard, and saved reproducible checkpoints automatically. Most importantly, you saw how clean architecture and configuration-driven design make your training pipeline easier to extend, debug, monitor, and deploy. These capabilities are exactly what real-world MLOps demands.</p>



<p>In the next lesson, we will take this foundation and push it into production territory. You will learn how to scale the same codebase with distributed training (DDP and FSDP), mixed precision, and model export to ONNX and TorchScript, all while keeping the project structure identical. If you want to turn this into a robust, deployment-ready training workflow, just keep reading.</p>



<h3 class="wp-block-heading">Citation Information</h3>



<p><strong>Singh, V</strong><strong>. </strong>“Training with PyTorch Lightning: Structured MLOps Development,” <em>PyImageSearch</em>, S. Huot, A. Sharma, and P. Thakur, eds., 2026, <a href="https://pyimg.co/5fe4l" target="_blank" rel="noreferrer noopener">https://pyimg.co/5fe4l</a> </p>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="classic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="Training with PyTorch Lightning: Structured MLOps Development" data-enlighter-group="57">@incollection{Singh_2026_training-w-pytorch-lightning-structured-mlops-development,
  author = {Vikram Singh},
  title = {{Training with PyTorch Lightning: Structured MLOps Development}},
  booktitle = {PyImageSearch},
  editor = {Susan Huot and Aditya Sharma and Piyush Thakur},
  year = {2026},
  url = {https://pyimg.co/5fe4l},
}
</pre>



<p><strong>To download the source code to this post (and be notified when future tutorials are published here on PyImageSearch), </strong><em><strong>simply enter your email address in the form below!</strong></em></p>



<div id="download-the-code" class="post-cta-wrap">
<div class="gpd-post-cta">
	<div class="gpd-post-cta-content">
		

			<div class="gpd-post-cta-top">
				<div class="gpd-post-cta-top-image"><img decoding="async" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2020/01/cta-source-guide-1.png?lossy=2&strip=1&webp=1" alt="" srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2020/01/cta-source-guide-1.png?lossy=2&strip=1&webp=1 410w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2020/01/cta-source-guide-1.png?size=126x174&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2020/01/cta-source-guide-1.png?size=252x348&lossy=2&strip=1&webp=1 252w" sizes="(max-width: 410px) 100vw, 410px" /></div>
				
				<div class="gpd-post-cta-top-title"><h4>Download the Source Code and FREE 17-page Resource Guide</h4></div>
				<div class="gpd-post-cta-top-desc"><p>Enter your email address below to get a .zip of the code and a <strong>FREE 17-page Resource Guide on Computer Vision, OpenCV, and Deep Learning.</strong> Inside you'll find my hand-picked tutorials, books, courses, and libraries to help you master CV and DL!</p></div>


			</div>

			<div class="gpd-post-cta-bottom">
				<form id="footer-cta-code" class="footer-cta" action="https://www.getdrip.com/forms/4130035/submissions" method="post" target="blank" data-drip-embedded-form="4130035">
					<input name="fields[email]" type="email" value="" placeholder="Your email address" class="form-control" />

					<button type="submit">Download the code!</button>

					<div style="display: none;" aria-hidden="true"><label for="website">Website</label><br /><input type="text" id="website" name="website" tabindex="-1" autocomplete="false" value="" /></div>
				</form>
			</div>


		
	</div>

</div>
</div>
<p>The post <a rel="nofollow" href="https://pyimagesearch.com/2026/08/03/training-with-pytorch-lightning-structured-mlops-development/">Training with PyTorch Lightning: Structured MLOps Development</a> appeared first on <a rel="nofollow" href="https://pyimagesearch.com">PyImageSearch</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Running Gemma 4 in the Browser with Transformers.js and WebGPU</title>
		<link>https://pyimagesearch.com/2026/07/27/running-gemma-4-in-the-browser-with-transformers-js-and-webgpu/</link>
		
		<dc:creator><![CDATA[Piyush Thakur]]></dc:creator>
		<pubDate>Mon, 27 Jul 2026 12:45:00 +0000</pubDate>
				<category><![CDATA[Artificial Intelligence]]></category>
		<category><![CDATA[Google Gemma]]></category>
		<category><![CDATA[Hugging Face]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[ai deployment]]></category>
		<category><![CDATA[browser ai]]></category>
		<category><![CDATA[client-side ai]]></category>
		<category><![CDATA[gemma 4]]></category>
		<category><![CDATA[hugging face]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[local inference]]></category>
		<category><![CDATA[multimodal ai]]></category>
		<category><![CDATA[multimodal inference]]></category>
		<category><![CDATA[onnx]]></category>
		<category><![CDATA[onnx runtime web]]></category>
		<category><![CDATA[transformers.js]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[web llm]]></category>
		<category><![CDATA[webgpu]]></category>
		<guid isPermaLink="false">https://pyimagesearch.com/?p=54773</guid>

					<description><![CDATA[<p>Table of Contents Running Gemma 4 in the Browser with Transformers.js and WebGPU Building a Browser-Based Gemma 4 AI Application Creating the HTML Document and Styling the Interface Creating the Application Layout Loading Transformers.js for Browser-Based Gemma 4 Inference Checking&#8230;</p>
<p>The post <a rel="nofollow" href="https://pyimagesearch.com/2026/07/27/running-gemma-4-in-the-browser-with-transformers-js-and-webgpu/">Running Gemma 4 in the Browser with Transformers.js and WebGPU</a> appeared first on <a rel="nofollow" href="https://pyimagesearch.com">PyImageSearch</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<hr class="wp-block-separator has-alpha-channel-opacity" id="TOC"/>


<div class="yoast-breadcrumbs"><span><span><a href="https://pyimagesearch.com/">Home</a></span></div>


<script src="https://fast.wistia.com/embed/medias/xpdhvg0nfc.jsonp" async></script><script src="https://fast.wistia.com/assets/external/E-v1.js" async></script><div class="wistia_responsive_padding" style="padding:56.25% 0 0 0;position:relative;"><div class="wistia_responsive_wrapper" style="height:100%;left:0;position:absolute;top:0;width:100%;"><div class="wistia_embed wistia_async_xpdhvg0nfc seo=true videoFoam=true" style="height:100%;position:relative;width:100%"><div class="wistia_swatch" style="height:100%;left:0;opacity:0;overflow:hidden;position:absolute;top:0;transition:opacity 200ms;width:100%;"><img decoding="async" src="https://fast.wistia.com/embed/medias/xpdhvg0nfc/swatch" style="filter:blur(5px);height:100%;object-fit:contain;width:100%;" alt="" aria-hidden="true" onload="this.parentNode.style.opacity=1;" /></div></div></div></div>



<div class="toc">
<hr class="TOC"/>
<p class="has-large-font-size"><strong>Table of Contents</strong></p>
<ul>
    <li id="TOC-h1-Running-Gemma-4-Browser-Transformers-js-WebGPU"><a rel="noopener" target="_blank" href="#h1-Running-Gemma-4-Browser-Transformers-js-WebGPU">Running Gemma 4 in the Browser with Transformers.js and WebGPU</a></li>

    <li id="TOC-h2-Building-Browser-Based-Gemma-4-AI-Application"><a rel="noopener" target="_blank" href="#h2-Building-Browser-Based-Gemma-4-AI-Application">Building a Browser-Based Gemma 4 AI Application</a></li>

    <li id="TOC-h2-Creating-HTML-Document-Styling-Interface"><a rel="noopener" target="_blank" href="#h2-Creating-HTML-Document-Styling-Interface">Creating the HTML Document and Styling the Interface</a></li>

    <li id="TOC-h2-Creating-Application-Layout"><a rel="noopener" target="_blank" href="#h2-Creating-Application-Layout">Creating the Application Layout</a></li>

    <li id="TOC-h2-Loading-Transformers-js-Browser-Based-Gemma-4-Inference"><a rel="noopener" target="_blank" href="#h2-Loading-Transformers-js-Browser-Based-Gemma-4-Inference">Loading Transformers.js for Browser-Based Gemma 4 Inference</a></li>

    <li id="TOC-h2-Checking-WebGPU-Support"><a rel="noopener" target="_blank" href="#h2-Checking-WebGPU-Support">Checking for WebGPU Support</a></li>

    <li id="TOC-h2-Referencing-User-Interface"><a rel="noopener" target="_blank" href="#h2-Referencing-User-Interface">Referencing the User Interface</a></li>

    <li id="TOC-h2-Creating-Helper-Functions"><a rel="noopener" target="_blank" href="#h2-Creating-Helper-Functions">Creating Helper Functions</a></li>

    <li id="TOC-h2-Previewing-Images-URL"><a rel="noopener" target="_blank" href="#h2-Previewing-Images-URL">Previewing Images from a URL</a></li>

    <li id="TOC-h2-Processing-Local-Image-Audio-Inputs-Gemma-4-Multimodal-AI"><a rel="noopener" target="_blank" href="#h2-Processing-Local-Image-Audio-Inputs-Gemma-4-Multimodal-AI">Processing Local Image and Audio Inputs for Gemma 4 Multimodal AI</a></li>

    <li id="TOC-h2-Processing-Audio-Inputs-Browser-Web-Audio-API"><a rel="noopener" target="_blank" href="#h2-Processing-Audio-Inputs-Browser-Web-Audio-API">Processing Audio Inputs in the Browser with Web Audio API</a></li>

    <li id="TOC-h2-Loading-Processor-Gemma-4-Model"><a rel="noopener" target="_blank" href="#h2-Loading-Processor-Gemma-4-Model">Loading the Processor and Gemma 4 Model</a></li>
    <ul>
        <li id="TOC-h3-Initializing-Gemma-4-Multimodal-Processor"><a rel="noopener" target="_blank" href="#h3-Initializing-Gemma-4-Multimodal-Processor">Initializing the Gemma 4 Multimodal Processor</a></li>
        <li id="TOC-h3-Loading-Gemma-4-ONNX-Model-WebGPU-Inference"><a rel="noopener" target="_blank" href="#h3-Loading-Gemma-4-ONNX-Model-WebGPU-Inference">Loading the Gemma 4 ONNX Model for WebGPU Inference</a></li>
        <li id="TOC-h3-Updating-Browser-Interface-Gemma-4-Model-Loading"><a rel="noopener" target="_blank" href="#h3-Updating-Browser-Interface-Gemma-4-Model-Loading">Updating the Browser Interface During Gemma 4 Model Loading</a></li>
    </ul>

    <li id="TOC-h2-Running-Gemma-4-Multimodal-Inference-Directly-Browser"><a rel="noopener" target="_blank" href="#h2-Running-Gemma-4-Multimodal-Inference-Directly-Browser">Running Gemma 4 Multimodal Inference Directly in the Browser</a></li>
    <ul>
        <li id="TOC-h3-Building-Prompt"><a rel="noopener" target="_blank" href="#h3-Building-Prompt">Building the Prompt</a></li>
        <li id="TOC-h3-Processing-Image-Audio-Inputs-Transformers-js"><a rel="noopener" target="_blank" href="#h3-Processing-Image-Audio-Inputs-Transformers-js">Processing Image and Audio Inputs with Transformers.js</a></li>
        <li id="TOC-h3-Generating-Response"><a rel="noopener" target="_blank" href="#h3-Generating-Response">Generating the Response</a></li>
    </ul>

    <li id="TOC-h2-Output"><a rel="noopener" target="_blank" href="#h2-Output">Output</a></li>

    <li id="TOC-h2-Summary"><a rel="noopener" target="_blank" href="#h2-Summary">Summary</a></li>
    <ul>
        <li id="TOC-h3-Citation-Information"><a rel="noopener" target="_blank" href="#h3-Citation-Information">Citation Information</a></li>
    </ul>
</ul>
</div>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h1-Running-Gemma-4-Browser-Transformers-js-WebGPU"/>



<h2 class="wp-block-heading"><a href="#TOC-h1-Running-Gemma-4-Browser-Transformers-js-WebGPU">Running Gemma 4 in the Browser with Transformers.js and WebGPU</a></h2>



<p>In the first part of this series, we explored the architecture behind Gemma 4, including its multimodal design, Mixture-of-Experts routing, long-context capabilities, and the innovations that make it one of Google&#8217;s most capable open-weight model families.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://pyimagesearch.com/wp-content/uploads/2026/07/running-gemma-4-in-browser-transformers-js-webgpu-featured.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="940" height="780" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/running-gemma-4-in-browser-transformers-js-webgpu-featured.png?lossy=2&strip=1&webp=1" alt="running-gemma-4-in-browser-transformers-js-webgpu-featured.png" class="wp-image-54793"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/running-gemma-4-in-browser-transformers-js-webgpu-featured.png?size=126x105&lossy=2&strip=1&webp=1 126w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/running-gemma-4-in-browser-transformers-js-webgpu-featured-300x249.png?lossy=2&strip=1&webp=1 300w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/running-gemma-4-in-browser-transformers-js-webgpu-featured.png?size=378x314&lossy=2&strip=1&webp=1 378w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/running-gemma-4-in-browser-transformers-js-webgpu-featured.png?size=504x418&lossy=2&strip=1&webp=1 504w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/running-gemma-4-in-browser-transformers-js-webgpu-featured.png?size=630x523&lossy=2&strip=1&webp=1 630w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/running-gemma-4-in-browser-transformers-js-webgpu-featured-768x637.png?lossy=2&strip=1&webp=1 768w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/running-gemma-4-in-browser-transformers-js-webgpu-featured.png?lossy=2&strip=1&webp=1 940w" sizes="(max-width: 940px) 100vw, 940px" /></a></figure></div>


<p>In the second part, we put those capabilities into practice using Hugging Face Transformers, building multimodal applications that processed images, videos, audio, and structured outputs from a unified Python interface.</p>



<p>Next, we shifted our focus to deployment. In the previous tutorial, we explored multiple ways to run Gemma 4 locally using <strong>Ollama</strong>, <strong>llama.cpp</strong>, <strong>MLX</strong>, <strong>LM Studio</strong>, and <strong>Transformers.js</strong>. Along the way, we learned how to download models, perform local multimodal inference, and expose OpenAI-compatible APIs without relying on cloud-hosted services.</p>



<p>But there is one final step that takes local AI even further:</p>



<p>Can we run Gemma 4 entirely inside a web browser?</p>



<p>Until recently, running multimodal large language models required native applications, Python environments, or dedicated inference servers. Modern browser technologies, however, have changed that. With <strong>Transformers.js</strong>, ONNX Runtime, and hardware acceleration through <strong>WebGPU</strong> and <strong>WebAssembly</strong>, we can now execute state-of-the-art models directly inside modern web browsers without sending data to external servers.</p>



<p>Running models entirely in the browser offers several advantages. It improves user privacy by keeping data on the client device, reduces infrastructure costs by eliminating backend inference servers, enables offline AI experiences, and simplifies deployment by allowing applications to run anywhere a modern browser is available.</p>



<p>In this tutorial, we will build a fully client-side multimodal application using <strong>Transformers.js</strong>. We will learn how to load an ONNX version of Gemma 4 inside the browser, process image inputs, perform local inference using browser hardware acceleration, and build an interactive web application that runs entirely on the user&#8217;s machine.</p>



<p>By the end of this guide, you will understand how to deploy Gemma 4 as a browser-native AI application without Python, without a backend inference server, and without sacrificing the multimodal capabilities we&#8217;ve explored throughout this series.</p>



<p>This lesson is the 4th in a 5-part series on <strong>Google DeepMind&#8217;s Gemma 4</strong>:</p>



<ol class="wp-block-list">
<li><em><strong><a href="https://pyimg.co/uqxzw" target="_blank" rel="noreferrer noopener">Google DeepMind’s Gemma 4: MoE, Efficiency Tricks, and Benchmarks</a></strong></em></li>



<li><em><strong><a href="https://pyimg.co/09dks" target="_blank" rel="noreferrer noopener">Building Multimodal AI Applications with Gemma 4 and Transformers</a></strong></em></li>



<li><em><strong><a href="https://pyimg.co/1rpad" target="_blank" rel="noreferrer noopener">Running Gemma 4 Locally: Ollama, llama.cpp, MLX, and More</a></strong></em></li>



<li><em><strong><a href="https://pyimg.co/gx0fr" target="_blank" rel="noreferrer noopener">Running Gemma 4 in the Browser with Transformers.js and WebGPU</a></strong></em><strong> (this tutorial)</strong></li>



<li><em>Lesson 5</em></li>
</ol>



<p><strong>To learn how to </strong><strong>build fully client-side multimodal AI applications with Gemma 4</strong><strong>, </strong><em><strong>just keep reading.</strong></em></p>



<div id="pyi-source-code-block" class="source-code-wrap"><div class="gpd-source-code">
    <div class="gpd-source-code-content">
        <img decoding="async" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2020/01/source-code-icon.png?lossy=2&strip=1&webp=1" alt="">
        <h4>Looking for the source code to this post?</h4>
                    <a href="#download-the-code" class="pyis-cta-modal-open-modal">Jump Right To The Downloads Section <svg class="svg-icon arrow-right" width="12" height="12" aria-hidden="true" role="img" focusable="false" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M6.8125 0.1875C6.875 0.125 6.96875 0.09375 7.09375 0.09375C7.1875 0.09375 7.28125 0.125 7.34375 0.1875L13.875 6.75C13.9375 6.8125 14 6.90625 14 7C14 7.125 13.9375 7.1875 13.875 7.25L7.34375 13.8125C7.28125 13.875 7.1875 13.9062 7.09375 13.9062C6.96875 13.9062 6.875 13.875 6.8125 13.8125L6.1875 13.1875C6.125 13.125 6.09375 13.0625 6.09375 12.9375C6.09375 12.8438 6.125 12.75 6.1875 12.6562L11.0312 7.8125H0.375C0.25 7.8125 0.15625 7.78125 0.09375 7.71875C0.03125 7.65625 0 7.5625 0 7.4375V6.5625C0 6.46875 0.03125 6.375 0.09375 6.3125C0.15625 6.25 0.25 6.1875 0.375 6.1875H11.0312L6.1875 1.34375C6.125 1.28125 6.09375 1.1875 6.09375 1.0625C6.09375 0.96875 6.125 0.875 6.1875 0.8125L6.8125 0.1875Z" fill="#169FE6"></path></svg></a>
            </div>
</div>
</div>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Building-Browser-Based-Gemma-4-AI-Application"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Building-Browser-Based-Gemma-4-AI-Application">Building a Browser-Based Gemma 4 AI Application</a></h2>



<p>Unlike the previous tutorial, where we interacted with Gemma 4 through the terminal, we will build a browser-based application that allows users to provide multimodal inputs and run inference directly from a web page.</p>



<p>The application consists of 3 primary components:</p>



<ul class="wp-block-list">
<li><strong>An input panel</strong> for entering image and audio URLs, uploading local files, and specifying the text prompt.</li>



<li><strong>A status panel</strong> that displays the current stage of the inference pipeline, download progress, and elapsed execution time.</li>



<li><strong>An output panel</strong> where Gemma 4 streams its response as it is generated.</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Creating-HTML-Document-Styling-Interface"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Creating-HTML-Document-Styling-Interface">Creating the HTML Document and Styling the Interface</a></h2>



<p>We begin by creating a standard HTML5 document that serves as the foundation for our browser application.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="html" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Running Gemma 4 in the Browser with Transformers.js and WebGPU" data-enlighter-group="1">&lt;!DOCTYPE html>
&lt;html lang="en">
&lt;head>
&lt;meta charset="UTF-8"/>
&lt;meta name="viewport" content="width=device-width, initial-scale=1.0"/>
&lt;title>Gemma 4 · WebGPU&lt;/title>
&lt;style>/* CSS styling */&lt;/style>
&lt;/head>
&lt;body>

&lt;header>
 &lt;h1>Gemma 4 · E2B&lt;/h1>
 &lt;span class="badge">WebGPU&lt;/span>
&lt;/header>
</pre>



<p>Here, <code data-enlighter-language="python" class="EnlighterJSRAW">&lt;!DOCTYPE html&gt;</code> declares an HTML5 document, while the <code data-enlighter-language="python" class="EnlighterJSRAW">&lt;html&gt;</code> element serves as the root of the page. The <code data-enlighter-language="python" class="EnlighterJSRAW">&lt;head&gt;</code> section contains metadata such as the character encoding, viewport configuration, page title, and CSS styles that define the application&#8217;s appearance. The <code data-enlighter-language="python" class="EnlighterJSRAW">&lt;body&gt;</code> section contains the visible content displayed in the browser, and the <code data-enlighter-language="python" class="EnlighterJSRAW">&lt;header&gt;</code> provides a simple title and badge identifying the application.</p>



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">&lt;style&gt;</code> section defines the application&#8217;s layout, typography, color palette, progress indicators, animations, and responsive behavior. Since the focus of this tutorial is browser-based AI inference rather than frontend development, we won&#8217;t discuss the styling in detail. Instead, we will concentrate on the JavaScript code that loads Gemma 4 and performs multimodal inference directly in the browser.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Creating-Application-Layout"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Creating-Application-Layout">Creating the Application Layout</a></h2>



<p>Next, we create the main layout of our browser application.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="html" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="15" data-enlighter-title="Running Gemma 4 in the Browser with Transformers.js and WebGPU" data-enlighter-group="2">&lt;div class="main">...&lt;/div>
</pre>



<p>The interface is divided into 3 primary sections that guide users through the entire inference workflow:</p>



<ul class="wp-block-list">
<li><strong>Input Panel:</strong> Allows users to provide an image and audio either by entering a URL or uploading local files. It also includes a text area for entering the prompt and a button for loading the model and starting inference.</li>



<li><strong>Status Panel:</strong> Displays the progress of the inference pipeline, including processor initialization, model loading, input preprocessing, token generation, and download progress.</li>



<li><strong>Output Panel:</strong> Displays the response generated by Gemma 4 as it is streamed to the browser in real time.</li>
</ul>



<p>This layout separates user inputs, model status, and generated outputs into dedicated sections, making the application easier to navigate while providing clear feedback throughout the inference process.</p>



<p>With the user interface in place, we can now implement the JavaScript code responsible for loading Gemma 4 and running multimodal inference directly inside the browser.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Loading-Transformers-js-Browser-Based-Gemma-4-Inference"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Loading-Transformers-js-Browser-Based-Gemma-4-Inference">Loading Transformers.js for Browser-Based Gemma 4 Inference</a></h2>



<p>With the user interface in place, we can begin implementing the browser-based inference pipeline. We start by importing the components required from <strong>Transformers.js</strong> and specifying the Gemma 4 model that will be loaded throughout the application.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="16" data-enlighter-title="Running Gemma 4 in the Browser with Transformers.js and WebGPU" data-enlighter-group="3">&lt;script type="module">
import {
 AutoProcessor,
 Gemma4ForConditionalGeneration,
 TextStreamer,
 load_image,
} from "https://cdn.jsdelivr.net/npm/@huggingface/transformers@4/dist/transformers.min.js";

const MODEL_ID = "onnx-community/gemma-4-E2B-it-ONNX";
</pre>



<p>Unlike the previous tutorial, where we installed Transformers.js locally using <strong>npm</strong>, the browser version imports the library directly from the <strong>jsDelivr CDN</strong>. This allows the application to download the required JavaScript modules automatically when the page loads, eliminating the need for a local Node.js environment or build process.</p>



<p>The imported classes serve the same purpose as before:</p>



<ul class="wp-block-list">
<li><code data-enlighter-language="python" class="EnlighterJSRAW">AutoProcessor</code>: loads the preprocessing pipeline for Gemma 4, preparing text, images, and audio before they are passed to the model.</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">Gemma4ForConditionalGeneration</code>: loads the ONNX version of Gemma 4 and provides the API used for multimodal generation.</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">TextStreamer</code>: streams generated tokens to the browser as they are produced, enabling real-time output instead of waiting for the entire response.</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">load_image</code>: downloads and preprocesses images from either URLs or user-uploaded files.</li>
</ul>



<p>Finally, we define the <code data-enlighter-language="python" class="EnlighterJSRAW">MODEL_ID</code>, which points to the <strong>Gemma 4 E2B Instruct ONNX</strong> model hosted on the Hugging Face Hub. This is the same model used in the previous tutorial, ensuring consistent behavior across both the Node.js and browser implementations.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Checking-WebGPU-Support"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Checking-WebGPU-Support">Checking for WebGPU Support</a></h2>



<p>Before loading Gemma 4, we first verify that the user&#8217;s browser supports <strong>WebGPU</strong>. Unlike the Node.js implementation, which executes the model on the CPU, browser-based inference relies on WebGPU to accelerate model execution using the client&#8217;s GPU.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="25" data-enlighter-title="Running Gemma 4 in the Browser with Transformers.js and WebGPU" data-enlighter-group="4">// ── WebGPU check ──
if (!navigator.gpu) {
 document.getElementById("error-msg").textContent = "WebGPU is not supported in this browser. Please use Chrome 113+ or Edge 113+.";
 document.getElementById("error-msg").classList.add("visible");
 document.getElementById("run-btn").disabled = true;
 document.getElementById("run-btn").textContent = "WebGPU not available";
}
</pre>



<p>The browser exposes WebGPU support through the <code data-enlighter-language="python" class="EnlighterJSRAW">navigator.gpu</code> property. If this property is unavailable, the application assumes that the browser or hardware does not support GPU-accelerated inference.</p>



<p>Rather than allowing the application to continue and fail later when loading the model, we perform this check upfront. If WebGPU is unavailable, the application:</p>



<ul class="wp-block-list">
<li>displays an informative error message</li>



<li>disables the <strong>Run Inference</strong> button</li>



<li>prevents the user from attempting to load Gemma 4 on an unsupported browser</li>
</ul>



<p>This early validation provides a better user experience by clearly communicating the requirements for running the application.</p>



<p><em><strong>Note:</strong></em><em> At the time of writing, WebGPU is supported by modern Chromium-based browsers such as </em><em><strong>Google Chrome</strong></em><em> and </em><em><strong>Microsoft Edge</strong></em><em>. If your browser does not support WebGPU, consider updating to the latest version or enabling the appropriate experimental features.</em></p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Referencing-User-Interface"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Referencing-User-Interface">Referencing the User Interface</a></h2>



<p>Next, we create references to the HTML elements that we will interact with throughout the application.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="32" data-enlighter-title="Running Gemma 4 in the Browser with Transformers.js and WebGPU" data-enlighter-group="5">// ── UI refs ──
const runBtn       = document.getElementById("run-btn");
const outputEl     = document.getElementById("output-text");
const errorEl      = document.getElementById("error-msg");
const progressWrap = document.getElementById("progress-wrap");
const progressFill = document.getElementById("progress-fill");
const progressPct  = document.getElementById("progress-pct");
const progressLbl  = document.getElementById("progress-label-text");
const elapsedEl    = document.getElementById("elapsed-text");
const imgPreview   = document.getElementById("img-preview");
const imgUrlInput  = document.getElementById("image-url");
</pre>



<p>These variables store references to the application&#8217;s user interface elements, including the <strong>Run Inference</strong> button, output panel, progress bar, status indicators, image preview, and input fields.</p>



<p>By retrieving these elements once at the beginning of the script, we can efficiently update the interface during model loading and inference without repeatedly querying the Document Object Model (DOM). This keeps the code cleaner, improves readability, and avoids unnecessary DOM lookups throughout the application.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Creating-Helper-Functions"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Creating-Helper-Functions">Creating Helper Functions</a></h2>



<p>Next, we define a few helper functions that simplify updating the application&#8217;s user interface during model loading and inference.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="43" data-enlighter-title="Running Gemma 4 in the Browser with Transformers.js and WebGPU" data-enlighter-group="6">// ── Step helpers ──
function setStep(n, state) { // state: 'active' | 'done' | ''
 const el = document.getElementById(`step-${n}`);
 el.className = "step" + (state ? ` ${state}` : "");
}
function setProgress(pct, label) {
 progressWrap.classList.add("visible");
 progressFill.style.width = `${pct}%`;
 progressPct.textContent = `${Math.round(pct)}%`;
 if (label) progressLbl.textContent = label;
}
function showError(msg) {
 errorEl.textContent = msg;
 errorEl.classList.add("visible");
}
function clearError() { errorEl.classList.remove("visible"); }
</pre>



<p>Each helper is responsible for a specific aspect of the interface:</p>



<ul class="wp-block-list">
<li><code data-enlighter-language="python" class="EnlighterJSRAW">setStep()</code>: updates the status indicator for each stage of the inference pipeline, allowing users to see whether a step is currently running or has completed</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">setProgress()</code>: updates the model download progress bar and percentage value while the ONNX model is being downloaded and initialized</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">showError()</code>: displays error messages whenever model loading or inference fails</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">clearError()</code>: removes any previously displayed error messages before a new operation begins</li>
</ul>



<p>Although these functions are not directly involved in running Gemma 4, they provide real-time feedback throughout the application&#8217;s execution, making it easier for users to monitor model loading and inference progress.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Previewing-Images-URL"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Previewing-Images-URL">Previewing Images from a URL</a></h2>



<p>To provide immediate visual feedback, we update the image preview whenever the user enters a new image URL.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="59" data-enlighter-title="Running Gemma 4 in the Browser with Transformers.js and WebGPU" data-enlighter-group="7">// ── Image preview from URL ──
imgUrlInput.addEventListener("input", () => {
 const url = imgUrlInput.value.trim();
 if (url) { imgPreview.src = url; imgPreview.classList.add("visible"); }
 else imgPreview.classList.remove("visible");
});
// show default on load
imgPreview.src = imgUrlInput.value;
imgPreview.classList.add("visible");
</pre>



<p>This event listener monitors changes to the <strong>Image URL</strong> input field. Whenever the user enters a valid URL, the application updates the preview image so that the selected input can be verified before running inference. If the input is cleared, the preview is automatically hidden.</p>



<p>When the page first loads, the script also displays the default sample image specified in the input field, allowing users to run the application immediately without providing their own image.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Processing-Local-Image-Audio-Inputs-Gemma-4-Multimodal-AI"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Processing-Local-Image-Audio-Inputs-Gemma-4-Multimodal-AI">Processing Local Image and Audio Inputs for Gemma 4 Multimodal AI</a></h2>



<p>In addition to accepting image and audio URLs, our application also allows users to upload local files directly from their computer. This provides greater flexibility by supporting both online resources and locally stored media.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="68" data-enlighter-title="Running Gemma 4 in the Browser with Transformers.js and WebGPU" data-enlighter-group="8">// ── File upload handling ──
let uploadedImageData = null; // base64 data URL
let uploadedAudioBuffer = null; // Float32Array

document.getElementById("img-file").addEventListener("change", (e) => {
 const file = e.target.files[0];
 if (!file) return;
 const reader = new FileReader();
 reader.onload = (ev) => {
   uploadedImageData = ev.target.result;
   imgPreview.src = uploadedImageData;
   imgPreview.classList.add("visible");
   imgUrlInput.value = "";
 };
 reader.readAsDataURL(file);
});
</pre>



<p>When an image is uploaded, the browser reads the selected file using the <strong>FileReader API</strong> and converts it into a Base64-encoded data URL. The resulting image is stored in <code data-enlighter-language="python" class="EnlighterJSRAW">uploadedImageData</code>, displayed in the preview panel, and later passed to Transformers.js for inference.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="84" data-enlighter-title="Running Gemma 4 in the Browser with Transformers.js and WebGPU" data-enlighter-group="9">document.getElementById("audio-file").addEventListener("change", async (e) => {
 const file = e.target.files[0];
 if (!file) return;
 const arrayBuffer = await file.arrayBuffer();
 const audioCtx = new AudioContext({ sampleRate: 16000 });
 const decoded = await audioCtx.decodeAudioData(arrayBuffer);
 uploadedAudioBuffer = decoded.getChannelData(0);
 document.getElementById("audio-url").value = "";
});
</pre>



<p>For audio files, the preprocessing pipeline is slightly different.</p>



<p>Instead of using <code data-enlighter-language="python" class="EnlighterJSRAW">FileReader</code>, the browser loads the audio into an <code data-enlighter-language="python" class="EnlighterJSRAW">ArrayBuffer</code> and decodes it using the <strong>Web Audio API</strong> (<code data-enlighter-language="python" class="EnlighterJSRAW">AudioContext</code>). The decoded waveform is then extracted as a <code data-enlighter-language="python" class="EnlighterJSRAW">Float32Array</code> using <code data-enlighter-language="python" class="EnlighterJSRAW">getChannelData(0)</code> and stored in <code data-enlighter-language="python" class="EnlighterJSRAW">uploadedAudioBuffer</code>.</p>



<p>This preprocessing step converts the uploaded audio into the numerical waveform representation expected by Gemma 4. By handling image and audio uploads within the browser, users can perform multimodal inference on their own files without relying on external servers or additional preprocessing tools.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Processing-Audio-Inputs-Browser-Web-Audio-API"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Processing-Audio-Inputs-Browser-Web-Audio-API">Processing Audio Inputs in the Browser with Web Audio API</a></h2>



<p>Earlier, we implemented a helper function for loading audio in a Node.js environment. In the browser, however, we can leverage the <strong>Web Audio API</strong>, which provides native support for decoding and processing audio files.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="93" data-enlighter-title="Running Gemma 4 in the Browser with Transformers.js and WebGPU" data-enlighter-group="10">// ── Load audio via AudioContext (browser-native) ──
async function loadAudioBrowser(url) {
 const res = await fetch(url);
 const arrayBuffer = await res.arrayBuffer();
 const audioCtx = new AudioContext({ sampleRate: 16000 });
 const decoded = await audioCtx.decodeAudioData(arrayBuffer);
 return decoded.getChannelData(0); // Float32Array @ 16kHz
}
</pre>



<p>This helper first downloads the audio file using the Fetch API and stores it as an <code data-enlighter-language="python" class="EnlighterJSRAW">ArrayBuffer</code>. The browser&#8217;s <code data-enlighter-language="python" class="EnlighterJSRAW">AudioContext</code> then decodes the audio and resamples it to <strong>16 kHz</strong>, matching the sampling rate expected by Gemma 4. Finally, <code data-enlighter-language="python" class="EnlighterJSRAW">getChannelData(0)</code> extracts the waveform as a <code data-enlighter-language="python" class="EnlighterJSRAW">Float32Array</code>, which is passed directly to the processor during inference.</p>



<p>Using the browser&#8217;s native audio processing capabilities eliminates the need for external libraries while providing the model with audio in the format required for multimodal inference.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Loading-Processor-Gemma-4-Model"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Loading-Processor-Gemma-4-Model">Loading the Processor and Gemma 4 Model</a></h2>



<p>With the user interface and helper functions in place, we can now load the processor and Gemma 4 model. Since downloading and initializing a large multimodal model can take some time, the application also displays a progress bar and status updates throughout the loading process.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Running Gemma 4 in the Browser with Transformers.js and WebGPU" data-enlighter-group="11">// State
let processor, model;
let modelLoaded = false;

async function loadModel() {
    ...
}
</pre>



<p>We begin by defining three variables that manage the model&#8217;s state. The <code data-enlighter-language="python" class="EnlighterJSRAW">processor</code> and <code data-enlighter-language="python" class="EnlighterJSRAW">model</code> variables store the initialized processor and Gemma 4 model, while the <code data-enlighter-language="python" class="EnlighterJSRAW">modelLoaded</code> flag tracks whether the model has already been loaded. This prevents the application from downloading and initializing the model multiple times during a single browser session.</p>



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">loadModel()</code> function is responsible for downloading, initializing, and preparing Gemma 4 for inference.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Initializing-Gemma-4-Multimodal-Processor"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Initializing-Gemma-4-Multimodal-Processor">Initializing the Gemma 4 Multimodal Processor</a></h3>



<p>The first step is loading the processor.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Running Gemma 4 in the Browser with Transformers.js and WebGPU" data-enlighter-group="12">setStep(1, "active");

processor = await AutoProcessor.from_pretrained(MODEL_ID);

setStep(1, "done");
</pre>



<p>As in the previous tutorial, <code data-enlighter-language="python" class="EnlighterJSRAW">AutoProcessor.from_pretrained()</code> downloads the preprocessing pipeline associated with Gemma 4. The processor prepares text, images, and audio before they are passed to the model, ensuring that all three modalities are converted into the format expected during inference.</p>



<p>The status panel is updated before and after loading so users can track the application&#8217;s progress.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Loading-Gemma-4-ONNX-Model-WebGPU-Inference"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Loading-Gemma-4-ONNX-Model-WebGPU-Inference">Loading the Gemma 4 ONNX Model for WebGPU Inference</a></h3>



<p>Once the processor is ready, we initialize the Gemma 4 model.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Running Gemma 4 in the Browser with Transformers.js and WebGPU" data-enlighter-group="13">model = await Gemma4ForConditionalGeneration.from_pretrained(
    MODEL_ID,
    {
        dtype: "q4f16",
        device: "webgpu",
        progress_callback: (info) => {
            ...
        },
    }
);
</pre>



<p>Here, <code data-enlighter-language="python" class="EnlighterJSRAW">Gemma4ForConditionalGeneration.from_pretrained()</code> downloads the ONNX model and initializes it for browser-based inference.</p>



<p>Several important parameters are specified:</p>



<ul class="wp-block-list">
<li><code data-enlighter-language="python" class="EnlighterJSRAW">dtype: "q4f16"</code>: loads a <strong>4-bit </strong><strong>floating-point </strong><strong>quantized</strong> version of Gemma 4, reducing memory consumption while maintaining strong inference performance.</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">device: "webgpu"</code>: instructs Transformers.js to execute the model using the browser&#8217;s <strong>WebGPU</strong> backend. Instead of performing inference on the CPU, computations are offloaded to the client&#8217;s GPU, resulting in significantly faster execution on supported hardware.</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">progress_callback</code>: receives download progress updates as the model files are fetched from the Hugging Face Hub. We use these updates to drive the application&#8217;s progress bar, allowing users to monitor the download in real time.</li>
</ul>



<p>Since Gemma 4 consists of multiple ONNX weight files, the first execution may take several minutes depending on the user&#8217;s internet connection. Once downloaded, however, the browser caches these files, allowing subsequent executions to start much more quickly.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Updating-Browser-Interface-Gemma-4-Model-Loading"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Updating-Browser-Interface-Gemma-4-Model-Loading">Updating the Browser Interface During Gemma 4 Model Loading</a></h3>



<p>While the model is loading, the application continuously updates the elapsed time and download progress, giving users immediate feedback throughout the initialization process.</p>



<p>Once the download completes successfully, the progress indicator is updated, the <strong>Run Inference</strong> button is enabled, and the <code data-enlighter-language="python" class="EnlighterJSRAW">modelLoaded</code> flag is set to <code data-enlighter-language="python" class="EnlighterJSRAW">true</code>, indicating that Gemma 4 is ready to process user inputs.</p>



<p>If any step fails (e.g., due to a network issue or an unsupported browser), the exception is caught, an informative error message is displayed, and the application is reset so that the user can safely retry loading the model.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Running-Gemma-4-Multimodal-Inference-Directly-Browser"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Running-Gemma-4-Multimodal-Inference-Directly-Browser">Running Gemma 4 Multimodal Inference Directly in the Browser</a></h2>



<p>With the processor and model loaded, we are ready to perform multimodal inference. The application waits for the user to click the <strong>Run Inference</strong> button before preparing the inputs, generating a response, and streaming the output back to the browser.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Running Gemma 4 in the Browser with Transformers.js and WebGPU" data-enlighter-group="14">// Run inference
runBtn.addEventListener("click", async () => {
    ...
});
</pre>



<p>The event listener serves as the entry point for the inference pipeline. Before performing any computation, it first checks whether Gemma 4 has already been loaded. If the model has not been initialized, the application automatically downloads and loads it. Otherwise, it immediately begins processing the user&#8217;s inputs.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Building-Prompt"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Building-Prompt">Building the Prompt</a></h3>



<p>The first stage constructs the multimodal conversation that will be passed to Gemma 4.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Running Gemma 4 in the Browser with Transformers.js and WebGPU" data-enlighter-group="15">const prompt_text = document.getElementById("prompt-input").value.trim();

const messages = [{
    role: "user",
    content: [
        { type: "image" },
        { type: "audio" },
        { type: "text", text: prompt_text },
    ],
}];

const prompt = processor.apply_chat_template(
    messages,
    {
        enable_thinking: false,
        add_generation_prompt: true,
    }
);
</pre>



<p>As in the previous tutorial, we represent the input as a chat conversation. The user message contains placeholders for an image and an audio clip, along with the text instruction entered through the interface.</p>



<p>The conversation is then passed to <code data-enlighter-language="python" class="EnlighterJSRAW">apply_chat_template()</code>, which formats the prompt according to Gemma 4&#8217;s expected conversational template. Setting <code data-enlighter-language="python" class="EnlighterJSRAW">enable_thinking</code> to <code data-enlighter-language="python" class="EnlighterJSRAW">false</code> disables thinking mode, while <code data-enlighter-language="python" class="EnlighterJSRAW">add_generation_prompt</code> appends the appropriate generation token, indicating where the model should begin producing its response.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Processing-Image-Audio-Inputs-Transformers-js"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Processing-Image-Audio-Inputs-Transformers-js">Processing Image and Audio Inputs with Transformers.js</a></h3>



<p>Next, the application prepares the multimodal inputs.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Running Gemma 4 in the Browser with Transformers.js and WebGPU" data-enlighter-group="16">// Load image
...

// Load audio
...

const inputs = await processor(
    prompt,
    image,
    audio,
    {
        add_special_tokens: false,
    }
);
</pre>



<p>The application supports both <strong>URLs</strong> and <strong>locally uploaded files</strong>. If the user has uploaded an image or audio clip, those inputs are used directly. Otherwise, the application downloads the resources from the URLs provided in the input fields.</p>



<p>Once the image, audio, and prompt are available, the processor converts them into the tensor representations expected by Gemma 4. This preprocessing step combines all three modalities into a unified set of model inputs, allowing the model to reason over text, images, and audio simultaneously.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Generating-Response"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Generating-Response">Generating the Response</a></h3>



<p>With the inputs prepared, we can finally generate a response.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Running Gemma 4 in the Browser with Transformers.js and WebGPU" data-enlighter-group="17">const outputs = await model.generate({
    ...inputs,
    max_new_tokens: 512,
    do_sample: false,
    streamer: new TextStreamer(
        processor.tokenizer,
        {
            skip_prompt: true,
            skip_special_tokens: true,
            callback_function: (text) => {
                ...
            },
        }
    ),
});
</pre>



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">generate()</code> method performs autoregressive text generation using the processed multimodal inputs.</p>



<p>Several parameters control the generation process:</p>



<ul class="wp-block-list">
<li><code data-enlighter-language="python" class="EnlighterJSRAW">max_new_tokens: 512</code>: limits the maximum number of tokens that Gemma 4 can generate.</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">do_sample: false</code>: disables stochastic sampling, producing deterministic responses for identical inputs.</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">TextStreamer</code>: streams generated tokens to the browser as soon as they are produced instead of waiting for the entire response to complete.</li>
</ul>



<p>Inside the streamer&#8217;s callback function, each newly generated token is appended to the output panel, allowing users to watch the response appear in real time. This creates a significantly more interactive experience, particularly when generating longer responses.</p>



<p>Once generation completes, the application removes the animated cursor, updates the elapsed execution time, reports the total number of generated tokens, and re-enables the <strong>Run Inference</strong> button for the next request.</p>



<p>If an error occurs at any point during preprocessing or generation, the exception is caught, an informative error message is displayed, and the application is reset so that inference can be attempted again.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Output"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Output">Output</a></h2>



<p>After opening the HTML file in a WebGPU-enabled browser, you will see an interface similar to the one shown in <strong>Figure 1</strong>. The left panel allows you to provide an image and audio either by entering their URLs or by uploading local files. You can also customize the prompt that will be sent to Gemma 4.</p>



<figure style="text-align: center; max-width: 700px; margin: auto;">
<iframe width="700" height="267" src="https://www.youtube.com/embed/oDmgXzo7-uk" title="" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
  <figcaption style="align: center; margin-top: 8px;">
    <strong>Figure 1:</strong> Browser-Based Gemma 4 Application with Transformers.js and WebGPU (source: author).
  </figcaption>
</figure>



<p>Click <strong>Load Model</strong> to download the ONNX version of Gemma 4 into the browser. During the first run, the application displays the download progress along with the status of each stage in the inference pipeline. Once the model has been loaded, the button changes to <strong>Run Inference</strong>.</p>



<p>Clicking <strong>Run Inference</strong> processes the image, audio, and prompt entirely within the browser using WebGPU acceleration. As Gemma 4 generates its response, the output is streamed token by token into the output panel, allowing you to see the answer appear in real time rather than waiting for the entire generation to finish.</p>



<p>The first execution may take a few minutes because the model weights must be downloaded and initialized. Subsequent runs are significantly faster since the model is already cached by the browser, requiring only the preprocessing and inference steps to complete.</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<div id="pitch" style="padding: 40px; width: 100%; background-color: #F4F6FA;">
	<h3>What's next? We recommend <a target="_blank" href="https://pyimagesearch.com/pyimagesearch-university/?utm_source=blogPost&utm_medium=bottomBanner&utm_campaign=What%27s%20next%3F%20I%20recommend">PyImageSearch University</a>.</h3>

	<script src="https://fast.wistia.com/embed/medias/kno0cmko2z.jsonp" async></script><script src="https://fast.wistia.com/assets/external/E-v1.js" async></script><div class="wistia_responsive_padding" style="padding:56.25% 0 0 0;position:relative;"><div class="wistia_responsive_wrapper" style="height:100%;left:0;position:absolute;top:0;width:100%;"><div class="wistia_embed wistia_async_kno0cmko2z videoFoam=true" style="height:100%;position:relative;width:100%"><div class="wistia_swatch" style="height:100%;left:0;opacity:0;overflow:hidden;position:absolute;top:0;transition:opacity 200ms;width:100%;"><img decoding="async" src="https://fast.wistia.com/embed/medias/kno0cmko2z/swatch" style="filter:blur(5px);height:100%;object-fit:contain;width:100%;" alt="" aria-hidden="true" onload="this.parentNode.style.opacity=1;" /></div></div></div></div>

	<div style="margin-top: 32px; margin-bottom: 32px; ">
		<strong>Course information:</strong><br/>
		120+ total classes • 115+ hours hours of on-demand code walkthrough videos • Last updated: August 2026<br/>
		<span style="color: #169FE6;">★★★★★</span> 4.84 (128 Ratings) • 16,000+ Students Enrolled
	</div>

	<p><strong>I strongly believe that if you had the right teacher you could <em>master</em> computer vision and deep learning.</strong></p>

	<p>Do you think learning computer vision and deep learning has to be time-consuming, overwhelming, and complicated? Or has to involve complex mathematics and equations? Or requires a degree in computer science?</p>

	<p>That’s <em>not</em> the case.</p>

	<p>All you need to master computer vision and deep learning is for someone to explain things to you in <em>simple, intuitive</em> terms. <em>And that’s exactly what I do</em>. My mission is to change education and how complex Artificial Intelligence topics are taught.</p>

	<p>If you're serious about learning computer vision, your next stop should be PyImageSearch University, the most comprehensive computer vision, deep learning, and OpenCV course online today. Here you’ll learn how to <em>successfully</em> and <em>confidently</em> apply computer vision to your work, research, and projects. Join me in computer vision mastery.</p>

	<p><strong>Inside PyImageSearch University you'll find:</strong></p>

	<ul style="margin-left: 0px;">
		<li style="list-style: none;">&check; <strong>120+ courses</strong> on essential computer vision, deep learning, and OpenCV topics</li>
		<li style="list-style: none;">&check; <strong>94+ Certificates</strong> of Completion</li>
		<li style="list-style: none;">&check; <strong>115+ hours hours</strong> of on-demand video</li>
		<li style="list-style: none;">&check; <strong>Brand new courses released <em>regularly</em></strong>, ensuring you can keep up with state-of-the-art techniques</li>
		<li style="list-style: none;">&check; <strong>Pre-configured Jupyter Notebooks in Google Colab</strong></li>
		<li style="list-style: none;">&check; Run all code examples in your web browser — works on Windows, macOS, and Linux (no dev environment configuration required!)</li>
		<li style="list-style: none;">&check; Access to <strong>centralized code repos for <em>all</em> 540+ tutorials</strong> on PyImageSearch</li>
		<li style="list-style: none;">&check; <strong> Easy one-click downloads</strong> for code, datasets, pre-trained models, etc.</li>
		<li style="list-style: none;">&check; <strong>Access</strong> on mobile, laptop, desktop, etc.</li>
	</ul>

	<p style="text-align: center;">
		<a target="_blank" class="button link" href="https://pyimagesearch.com/pyimagesearch-university/?utm_source=blogPost&utm_medium=bottomBanner&utm_campaign=What%27s%20next%3F%20I%20recommend" style="background-color: #6DC713; border-bottom: none;">Click here to join PyImageSearch University</a>
	</p>
</div>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Summary"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Summary">Summary</a></h2>



<p>In this tutorial, we explored how to run <strong>Gemma 4 entirely inside a web browser</strong> using <strong>Transformers.js</strong> and <strong>WebGPU</strong>, without relying on Python, Node.js, or any external inference server. Starting from a simple HTML page, we built a complete multimodal application capable of loading an ONNX version of Gemma 4, accepting image and audio inputs, tracking model download progress, and streaming responses directly in the browser.</p>



<p>Along the way, we learned how to initialize the model with <code data-enlighter-language="python" class="EnlighterJSRAW">AutoProcessor</code> and <code data-enlighter-language="python" class="EnlighterJSRAW">Gemma4ForConditionalGeneration</code>, verify WebGPU support, preprocess multimodal inputs, construct prompts using the chat template, and perform real-time token streaming with <code data-enlighter-language="python" class="EnlighterJSRAW">TextStreamer</code>. By leveraging ONNX Runtime Web and the browser&#8217;s GPU, we were able to execute the entire inference pipeline locally while keeping all data on the user&#8217;s device.</p>



<p>With this tutorial, we have now covered the complete Gemma 4 deployment landscape, from Python applications using Hugging Face Transformers to local inference with <strong>Ollama</strong>, <strong>llama.cpp</strong>, <strong>MLX</strong>, <strong>LM Studio</strong>, <strong>Transformers.js for Node.js</strong>, and finally <strong>Transformers.js running directly in the browser</strong>. Together, these tutorials demonstrate how the same Gemma 4 model can be deployed across a wide range of environments, from research notebooks and desktop applications to fully client-side web experiences.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Citation-Information"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Citation-Information">Citation Information</a></h3>



<p><strong>Thakur, P</strong><strong>. </strong>“Running Gemma 4 in the Browser with Transformers.js and WebGPU,” <em>PyImageSearch</em>, S. Huot, G. Kudriavtsev, and A. Sharma, eds., 2026, <a href="https://pyimg.co/gx0fr" target="_blank" rel="noreferrer noopener">https://pyimg.co/gx0fr</a> </p>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="classic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="Running Gemma 4 in the Browser with Transformers.js and WebGPU" data-enlighter-group="18">@incollection{Thakur_2026_running-gemma-4-in-browser-transformers-js-webgpu,
  author = {Piyush Thakur},
  title = {{Running Gemma 4 in the Browser with Transformers.js and WebGPU}},
  booktitle = {PyImageSearch},
  editor = {Susan Huot and Georgii Kudriavtsev and Aditya Sharma},
  year = {2026},
  url = {https://pyimg.co/gx0fr},
}
</pre>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p><strong>To download the source code to this post (and be notified when future tutorials are published here on PyImageSearch), </strong><em><strong>simply enter your email address in the form below!</strong></em></p>



<div id="download-the-code" class="post-cta-wrap">
<div class="gpd-post-cta">
	<div class="gpd-post-cta-content">
		

			<div class="gpd-post-cta-top">
				<div class="gpd-post-cta-top-image"><img decoding="async" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2020/01/cta-source-guide-1.png?lossy=2&strip=1&webp=1" alt="" srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2020/01/cta-source-guide-1.png?lossy=2&strip=1&webp=1 410w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2020/01/cta-source-guide-1.png?size=126x174&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2020/01/cta-source-guide-1.png?size=252x348&lossy=2&strip=1&webp=1 252w" sizes="(max-width: 410px) 100vw, 410px" /></div>
				
				<div class="gpd-post-cta-top-title"><h4>Download the Source Code and FREE 17-page Resource Guide</h4></div>
				<div class="gpd-post-cta-top-desc"><p>Enter your email address below to get a .zip of the code and a <strong>FREE 17-page Resource Guide on Computer Vision, OpenCV, and Deep Learning.</strong> Inside you'll find my hand-picked tutorials, books, courses, and libraries to help you master CV and DL!</p></div>


			</div>

			<div class="gpd-post-cta-bottom">
				<form id="footer-cta-code" class="footer-cta" action="https://www.getdrip.com/forms/4130035/submissions" method="post" target="blank" data-drip-embedded-form="4130035">
					<input name="fields[email]" type="email" value="" placeholder="Your email address" class="form-control" />

					<button type="submit">Download the code!</button>

					<div style="display: none;" aria-hidden="true"><label for="website">Website</label><br /><input type="text" id="website" name="website" tabindex="-1" autocomplete="false" value="" /></div>
				</form>
			</div>


		
	</div>

</div>
</div>
<p>The post <a rel="nofollow" href="https://pyimagesearch.com/2026/07/27/running-gemma-4-in-the-browser-with-transformers-js-and-webgpu/">Running Gemma 4 in the Browser with Transformers.js and WebGPU</a> appeared first on <a rel="nofollow" href="https://pyimagesearch.com">PyImageSearch</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Running Gemma 4 Locally: Ollama, llama.cpp, MLX, and More</title>
		<link>https://pyimagesearch.com/2026/07/20/running-gemma-4-locally-ollama-llama-cpp-mlx-and-more/</link>
		
		<dc:creator><![CDATA[Piyush Thakur]]></dc:creator>
		<pubDate>Mon, 20 Jul 2026 12:45:00 +0000</pubDate>
				<category><![CDATA[Artificial Intelligence]]></category>
		<category><![CDATA[Deployment]]></category>
		<category><![CDATA[Google Gemma]]></category>
		<category><![CDATA[Large Language Models]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[ai deployment]]></category>
		<category><![CDATA[apple silicon]]></category>
		<category><![CDATA[gemma 4]]></category>
		<category><![CDATA[gguf]]></category>
		<category><![CDATA[google gemma]]></category>
		<category><![CDATA[llama.cpp]]></category>
		<category><![CDATA[lm studio]]></category>
		<category><![CDATA[local inference]]></category>
		<category><![CDATA[local llm]]></category>
		<category><![CDATA[mlx]]></category>
		<category><![CDATA[mlx-vlm]]></category>
		<category><![CDATA[multimodal ai]]></category>
		<category><![CDATA[ollama]]></category>
		<category><![CDATA[on-device ai]]></category>
		<category><![CDATA[openai compatible api]]></category>
		<category><![CDATA[transformers.js]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[vision language model]]></category>
		<guid isPermaLink="false">https://pyimagesearch.com/?p=54541</guid>

					<description><![CDATA[<p>Table of Contents Running Gemma 4 Locally: Ollama, llama.cpp, MLX, and More Running Gemma 4 with Ollama for Local AI Inference Running Gemma 4 with llama.cpp and GGUF Models Running Gemma 4 with MLX on Apple Silicon Macs Running Gemma&#8230;</p>
<p>The post <a rel="nofollow" href="https://pyimagesearch.com/2026/07/20/running-gemma-4-locally-ollama-llama-cpp-mlx-and-more/">Running Gemma 4 Locally: Ollama, llama.cpp, MLX, and More</a> appeared first on <a rel="nofollow" href="https://pyimagesearch.com">PyImageSearch</a>.</p>
]]></description>
										<content:encoded><![CDATA[<div class="yoast-breadcrumbs"><span><span><a href="https://pyimagesearch.com/">Home</a></span></div>


<script src="https://fast.wistia.com/embed/medias/srgcawrsso.jsonp" async></script><script src="https://fast.wistia.com/assets/external/E-v1.js" async></script><div class="wistia_responsive_padding" style="padding:56.25% 0 0 0;position:relative;"><div class="wistia_responsive_wrapper" style="height:100%;left:0;position:absolute;top:0;width:100%;"><div class="wistia_embed wistia_async_srgcawrsso seo=true videoFoam=true" style="height:100%;position:relative;width:100%"><div class="wistia_swatch" style="height:100%;left:0;opacity:0;overflow:hidden;position:absolute;top:0;transition:opacity 200ms;width:100%;"><img decoding="async" src="https://fast.wistia.com/embed/medias/srgcawrsso/swatch" style="filter:blur(5px);height:100%;object-fit:contain;width:100%;" alt="" aria-hidden="true" onload="this.parentNode.style.opacity=1;" /></div></div></div></div>



<div class="toc">
<hr class="TOC"/>
<p class="has-large-font-size"><strong>Table of Contents</strong></p>
<ul>
    <li id="TOC-h1-Running-Gemma-4-Locally-Ollama-llama-cpp-MLX-More"><a rel="noopener" target="_blank" href="#h1-Running-Gemma-4-Locally-Ollama-llama-cpp-MLX-More">Running Gemma 4 Locally: Ollama, llama.cpp, MLX, and More</a></li>

    <li id="TOC-h2-Running-Gemma-4-Ollama-Local-AI-Inference"><a rel="noopener" target="_blank" href="#h2-Running-Gemma-4-Ollama-Local-AI-Inference">Running Gemma 4 with Ollama for Local AI Inference</a></li>

    <li id="TOC-h2-Running-Gemma-4-llama-cpp-GGUF-Models"><a rel="noopener" target="_blank" href="#h2-Running-Gemma-4-llama-cpp-GGUF-Models">Running Gemma 4 with llama.cpp and GGUF Models</a></li>

    <li id="TOC-h2-Running-Gemma-4-MLX-Apple-Silicon-Macs"><a rel="noopener" target="_blank" href="#h2-Running-Gemma-4-MLX-Apple-Silicon-Macs">Running Gemma 4 with MLX on Apple Silicon Macs</a></li>

    <li id="TOC-h2-Running-Gemma-4-LM-Studio-Desktop-App"><a rel="noopener" target="_blank" href="#h2-Running-Gemma-4-LM-Studio-Desktop-App">Running Gemma 4 with LM Studio&#8217;s Desktop App</a></li>

    <li id="TOC-h2-Running-Gemma-4-Locally-Transformers-js"><a rel="noopener" target="_blank" href="#h2-Running-Gemma-4-Locally-Transformers-js">Running Gemma 4 Locally with Transformers.js</a></li>

    <li id="TOC-h2-Choosing-Right-Runtime-Running-Gemma-4-Locally"><a rel="noopener" target="_blank" href="#h2-Choosing-Right-Runtime-Running-Gemma-4-Locally">Choosing the Right Runtime for Running Gemma 4 Locally</a></li>

    <li id="TOC-h2-Summary"><a rel="noopener" target="_blank" href="#h2-Summary">Summary</a></li>
</ul>
</div>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h1-Running-Gemma-4-Locally-Ollama-llama-cpp-MLX-More"/>



<h2 class="wp-block-heading"><a href="#TOC-h1-Running-Gemma-4-Locally-Ollama-llama-cpp-MLX-More">Running Gemma 4 Locally: Ollama, llama.cpp, MLX, and More</a></h2>



<p>In the first part of this series, we explored the architecture behind Gemma 4, including its multimodal design, long-context capabilities, Mixture-of-Experts routing, Per-Layer Embeddings, and the engineering decisions that allow the model family to scale from lightweight on-device deployments to large production systems. We also examined the different Gemma 4 variants, their hardware requirements, and the reasoning capabilities that make the model family one of the most compelling open-weight releases available today.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://pyimagesearch.com/wp-content/uploads/2026/07/running-gemma-4-locally-ollama-llama-cpp-mlx-featured-1.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="940" height="780" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/running-gemma-4-locally-ollama-llama-cpp-mlx-featured-1.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54649"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/running-gemma-4-locally-ollama-llama-cpp-mlx-featured-1.png?size=126x105&lossy=2&strip=1&webp=1 126w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/running-gemma-4-locally-ollama-llama-cpp-mlx-featured-1-300x249.png?lossy=2&strip=1&webp=1 300w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/running-gemma-4-locally-ollama-llama-cpp-mlx-featured-1.png?size=378x314&lossy=2&strip=1&webp=1 378w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/running-gemma-4-locally-ollama-llama-cpp-mlx-featured-1.png?size=504x418&lossy=2&strip=1&webp=1 504w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/running-gemma-4-locally-ollama-llama-cpp-mlx-featured-1.png?size=630x523&lossy=2&strip=1&webp=1 630w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/running-gemma-4-locally-ollama-llama-cpp-mlx-featured-1-768x637.png?lossy=2&strip=1&webp=1 768w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/running-gemma-4-locally-ollama-llama-cpp-mlx-featured-1.png?lossy=2&strip=1&webp=1 940w" sizes="(max-width: 940px) 100vw, 940px" /></a></figure></div>


<p>In the second part, we moved from theory to practice. Using <code data-enlighter-language="python" class="EnlighterJSRAW">Hugging Face Transformers</code>, we built multimodal applications capable of processing images, videos, audio, and structured outputs. Along the way, we saw how Gemma 4 handles tasks such as screenshot-to-code generation, object detection, image captioning, multimodal function calling, and audio understanding from a single unified interface.</p>



<p>But there is still an important question left unanswered:</p>



<p><strong>How do we actually run Gemma 4 outside of a Python notebook?</strong></p>



<p>For many developers, deploying and interacting with a model is just as important as understanding its architecture or capabilities. A model that performs well inside a notebook is useful, but a model that can run locally on a laptop, power desktop applications, expose APIs, or operate entirely offline opens up an entirely different set of possibilities.</p>



<p>Fortunately, Gemma 4 has quickly gained support across the local AI ecosystem. Whether you prefer a simple one-command setup, a graphical desktop interface, a highly optimized C++ inference engine, a runtime specifically designed for Apple Silicon, or even JavaScript-based local inference, there is already a mature deployment path available.</p>



<p>In this lesson, we will explore five of the most popular ways to run Gemma 4 locally:</p>



<ul class="wp-block-list">
<li><code data-enlighter-language="python" class="EnlighterJSRAW">Ollama</code>: fast setup and developer-friendly APIs</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">LM Studio</code>: a graphical desktop experience</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">llama.cpp</code>: efficient GGUF (GPT-Generated Unified Format)-based inference and maximum control</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">MLX</code>: optimized performance on Apple Silicon devices</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">Transformers.js</code>: running Gemma 4 directly from <code data-enlighter-language="python" class="EnlighterJSRAW">Node.js</code> using ONNX models</li>
</ul>



<p>By the end of this guide, you will know how to download Gemma 4, perform local text and multimodal inference, expose OpenAI-compatible APIs, and choose the deployment runtime that best fits your workflow.</p>



<p>In the next lesson, we will build upon the <code data-enlighter-language="python" class="EnlighterJSRAW">Transformers.js</code> foundation introduced here and take things one step further by running Gemma 4 <strong>entirely inside the browser</strong>, enabling fully client-side AI applications without requiring a Python backend or native inference runtime.</p>



<p>This lesson is the 3rd in a 5-part series on <strong>Google DeepMind&#8217;s Gemma 4</strong>:</p>



<ol class="wp-block-list">
<li><em><strong><a href="https://pyimg.co/uqxzw" target="_blank" rel="noreferrer noopener">Google DeepMind’s Gemma 4: MoE, Efficiency Tricks, and Benchmarks</a></strong></em></li>



<li><em><strong><a href="https://pyimg.co/09dks" target="_blank" rel="noreferrer noopener">Building Multimodal AI Applications with Gemma 4 and Transformers</a></strong></em></li>



<li><em><strong><a href="https://pyimg.co/1rpad" target="_blank" rel="noreferrer noopener">Running Gemma 4 Locally: Ollama, llama.cpp, MLX, and More</a></strong></em><strong> (this tutorial)</strong></li>



<li><em>Lesson 4</em></li>



<li><em>Lesson 5</em></li>
</ol>



<p><strong>To learn how to </strong><strong>run Gemma 4 entirely on your own hardware</strong><strong>, </strong><em><strong>just keep reading.</strong></em></p>



<div id="pyi-source-code-block" class="source-code-wrap"><div class="gpd-source-code">
    <div class="gpd-source-code-content">
        <img decoding="async" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2020/01/source-code-icon.png?lossy=2&strip=1&webp=1" alt="">
        <h4>Looking for the source code to this post?</h4>
                    <a href="#download-the-code" class="pyis-cta-modal-open-modal">Jump Right To The Downloads Section <svg class="svg-icon arrow-right" width="12" height="12" aria-hidden="true" role="img" focusable="false" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M6.8125 0.1875C6.875 0.125 6.96875 0.09375 7.09375 0.09375C7.1875 0.09375 7.28125 0.125 7.34375 0.1875L13.875 6.75C13.9375 6.8125 14 6.90625 14 7C14 7.125 13.9375 7.1875 13.875 7.25L7.34375 13.8125C7.28125 13.875 7.1875 13.9062 7.09375 13.9062C6.96875 13.9062 6.875 13.875 6.8125 13.8125L6.1875 13.1875C6.125 13.125 6.09375 13.0625 6.09375 12.9375C6.09375 12.8438 6.125 12.75 6.1875 12.6562L11.0312 7.8125H0.375C0.25 7.8125 0.15625 7.78125 0.09375 7.71875C0.03125 7.65625 0 7.5625 0 7.4375V6.5625C0 6.46875 0.03125 6.375 0.09375 6.3125C0.15625 6.25 0.25 6.1875 0.375 6.1875H11.0312L6.1875 1.34375C6.125 1.28125 6.09375 1.1875 6.09375 1.0625C6.09375 0.96875 6.125 0.875 6.1875 0.8125L6.8125 0.1875Z" fill="#169FE6"></path></svg></a>
            </div>
</div>
</div>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Running-Gemma-4-Ollama-Local-AI-Inference"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Running-Gemma-4-Ollama-Local-AI-Inference">Running Gemma 4 with Ollama for Local AI Inference</a></h2>



<p>Among all the local inference solutions available today, <strong><a href="https://ollama.com" target="_blank" rel="noreferrer noopener">Ollama</a></strong> is arguably the fastest and easiest way to get started with Gemma 4. With just a few terminal commands, it can download the model, manage different versions, launch a local inference server, and expose an OpenAI-compatible API (Application Programming Interface), all without requiring any manual configuration.</p>



<p>Instead of downloading model weights, setting up inference backends, or configuring server endpoints yourself, <code data-enlighter-language="python" class="EnlighterJSRAW">Ollama</code> automates the entire deployment process behind a simple command-line interface. This makes it an excellent choice for developers who want to start experimenting with Gemma 4 immediately while still having access to production-friendly APIs.</p>



<p>In this section, we will install <code data-enlighter-language="python" class="EnlighterJSRAW">Ollama</code>, download the <code data-enlighter-language="python" class="EnlighterJSRAW">Gemma 4</code> model, perform both text and vision inference from the terminal, and interact with the model through its built-in <code data-enlighter-language="python" class="EnlighterJSRAW">REST API</code>.</p>



<h3 class="wp-block-heading">Installing Ollama</h3>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/07/image-38-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="893" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-38-1024x893.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54652"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-38-1024x893.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-38-1024x893.png?size=126x110&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-38-1024x893.png?size=252x220&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-38-1024x893.png?size=378x330&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-38-1024x893.png?size=504x440&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-38-1024x893.png?size=630x549&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 1:</strong> <code>Ollama</code> Download Page (source: <a href="https://ollama.com/download" target="_blank" rel="noreferrer noopener">Ollama website</a>)</figcaption></figure></div>


<p>The first step is installing <code data-enlighter-language="python" class="EnlighterJSRAW">Ollama</code> on your machine.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Running Gemma 4 Locally: Ollama, llama.cpp, MLX, and More" data-enlighter-group="1">curl -fsSL https://ollama.com/install.sh | sh
</pre>



<p>This command downloads the official installation script directly from the <code data-enlighter-language="python" class="EnlighterJSRAW">Ollama</code> website and executes it locally.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/07/image-39-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="150" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-39-1024x150.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54655"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-39-1024x150.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-39-1024x150.png?size=126x18&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-39-1024x150.png?size=252x37&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-39-1024x150.png?size=378x55&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-39-1024x150.png?size=504x74&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-39-1024x150.png?size=630x92&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 2:</strong> Terminal Command to Download <code>Ollama</code> (source: author)</figcaption></figure></div>


<p>After the installation completes, we can verify that <code data-enlighter-language="python" class="EnlighterJSRAW">Ollama</code> was installed successfully:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Running Gemma 4 Locally: Ollama, llama.cpp, MLX, and More" data-enlighter-group="2">ollama --version
</pre>



<p>If the command prints a version number, the installation is working correctly and we are ready to download Gemma 4.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/07/image-40-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="50" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-40-1024x50.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54658"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-40-1024x50.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-40-1024x50.png?size=126x6&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-40-1024x50.png?size=252x12&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-40-1024x50.png?size=378x18&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-40-1024x50.png?size=504x25&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-40-1024x50.png?size=630x31&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 3:</strong> Verifying <code>Ollama</code> version (source: author)</figcaption></figure></div>


<h3 class="wp-block-heading">Downloading the Gemma 4 Model</h3>



<p><code data-enlighter-language="python" class="EnlighterJSRAW">Ollama</code> stores models locally and downloads them on demand.</p>



<p>To pull the Gemma 4 E2B model, run:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Running Gemma 4 Locally: Ollama, llama.cpp, MLX, and More" data-enlighter-group="3">ollama pull gemma4:e2b
</pre>



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">pull</code> command downloads the model weights and stores them inside Ollama&#8217;s local model registry.</p>



<p>Here:</p>



<ul class="wp-block-list">
<li><code data-enlighter-language="python" class="EnlighterJSRAW">gemma4</code>: specifies the model family</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">e2b</code>: refers to the Gemma 4 E2B variant</li>
</ul>



<p>Once the download finishes, the model becomes available for local inference without requiring any additional configuration.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/07/image-41-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="228" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-41-1024x228.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54662"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-41-1024x228.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-41-1024x228.png?size=126x28&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-41-1024x228.png?size=252x56&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-41-1024x228.png?size=378x84&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-41-1024x228.png?size=504x112&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-41-1024x228.png?size=630x140&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 4:</strong> Command to Download Gemma 4 E2B model (source: author)</figcaption></figure></div>


<h3 class="wp-block-heading">Running Gemma 4 Interactively</h3>



<p>With the model downloaded, we can launch an interactive chat session:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Running Gemma 4 Locally: Ollama, llama.cpp, MLX, and More" data-enlighter-group="4">ollama run gemma4:e2b
</pre>



<p>This command starts Gemma 4 and opens a terminal-based conversation interface.</p>



<p>You can now enter prompts directly into the terminal and receive responses from the model in real time.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Running Gemma 4 Locally: Ollama, llama.cpp, MLX, and More" data-enlighter-group="101">>>> explain the mixture-of-experts architecture.
Thinking...
Here's a thinking process that leads to the suggested explanation:
1.  **Deconstruct the Request:** The user wants an explanation of the "Mixture-of-Experts (MoE) architecture."
2.  **Determine the Core Context (Where does MoE live?):** MoE is primarily a model architecture, most famously applied to Large Language Models (LLMs) like those from Google (GLaM/PaLM/Gemini) 
and Meta.
3.  **Establish the Problem MoE Solves (Why MoE?):** Standard dense models (like a traditional Transformer) are computationally expensive. They require massive parameter counts and massive 
computations for *every* input, even for simple tasks.
    *   *Goal:* Make models larger (more capable) without increasing the computational cost per inference/training step proportionally.
….
….</pre>



<p>To exit the session, type:</p>



<p><code data-enlighter-language="python" class="EnlighterJSRAW">/bye</code></p>



<p>or press:</p>



<p><code data-enlighter-language="python" class="EnlighterJSRAW">Ctrl + D</code></p>



<p>This interactive mode is useful when experimenting with prompts, testing reasoning capabilities, or quickly validating model behavior before integrating it into an application.</p>



<h3 class="wp-block-heading">Image Understanding with Gemma 4</h3>



<p>Gemma 4 is a multimodal model, meaning it can process both text and images.</p>



<p><code data-enlighter-language="python" class="EnlighterJSRAW">Ollama</code> exposes this capability through a simple command:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Running Gemma 4 Locally: Ollama, llama.cpp, MLX, and More" data-enlighter-group="6">ollama run gemma4:e2b "caption this image /Users/cosmo3769/Desktop/venice.jpg"
</pre>



<p>In this example, Gemma 4 receives an image and generates a textual description of its contents.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/07/image-23-scaled.jpeg" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="674" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-23-1024x674.jpeg?lossy=2&strip=1&webp=1" alt="" class="wp-image-54667"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-23-1024x674.jpeg?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-23-1024x674.jpeg?size=126x83&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-23-1024x674.jpeg?size=252x166&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-23-1024x674.jpeg?size=378x249&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-23-1024x674.jpeg?size=504x332&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-23-1024x674.jpeg?size=630x415&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 5:</strong> Input Image (source: <a href="https://huggingface.co/datasets/merve/vlm_test_images/blob/main/venice.jpg" target="_blank" rel="noreferrer noopener">Hugging Face</a>)</figcaption></figure></div>


<p>Behind the scenes, <code data-enlighter-language="python" class="EnlighterJSRAW">Ollama</code> loads the image, converts it into visual embeddings using Gemma 4&#8217;s vision encoder, and passes those embeddings into the language model alongside the text prompt.</p>



<p>From the user&#8217;s perspective, image understanding works exactly like a standard text prompt.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Running Gemma 4 Locally: Ollama, llama.cpp, MLX, and More" data-enlighter-group="102">Added image '/Users/cosmo3769/Desktop/venice.jpg'
Thinking...
Here's a thinking process for generating the caption:
1.  **Analyze the Image:**
    *   **Subject:** A large, classical-style building (a temple/fascia) situated over water.
    *   **Setting:** A canal/river scene. There are wooden pilings in the water, suggesting a waterfront or mooring area.
    *   **Architecture:** The building is ornate, stone, and features columns and pediments. It looks like a palazzo or a significant public structure.
    *   **Context/Location Clues (Inferred):** The architecture style strongly suggests Italy, likely Venice or a similar canal city.
    *   **Foreground/Background:** Wooden waterboats/barges are visible. There are old European buildings lining the far bank. A bridge/structure is visible on the right. The light suggests a 
sunny day.
2.  **Identify Key Themes &amp; Mood:**
    *   History/Antiquity
    *   Waterways/Canals
    *   European Charm
    *   Architecture/Grandeur
3.  **Determine the Goal:** Create a compelling caption for this scenic, historical photo.
4.  **Draft Caption Options (Categorized):**
    *   *Descriptive/Literal:* Focus on what is seen.
    *   *Evocative/Poetic:* Focus on the feeling and atmosphere.
    *   *Location-Specific (If known):* If we assume Venice/Italy.
    *   *Travel/Wanderlust Focused:* Encouraging travel.
5.  **Refine and Select the Best Options (Adding specific details):**
    *   *Focus on the contrast:* The grandeur of the building vs. the water.
    *   *Focus on the atmosphere:* Serene, timeless.
    *   *Focus on the setting:* Venetian/Italian canals.
6.  **Final Polish (Generating a variety of styles):** (This leads to the suggested captions below.)
...done thinking.
Here are several options for captioning this beautiful image, depending on the tone you want to convey:
**1. Descriptive &amp; Historical:**
*   "A glimpse of timeless elegance and history along the canals. The grandeur of the architecture reflected in the calm waters."
*   "Ancient beauty meets the waterways. Exploring the historic facades and hidden corners of this European city."
*   "The stunning architecture overlooking the tranquil waters. A true masterpiece of history."
**2. Evocative &amp; Poetic:**
*   "Where history flows on water. Serenity and splendor in every frame."
*   "Lost in the charm of the canals, where old stones whisper tales of the past."
*   "Golden light on ancient waters. A perfect moment of European serenity."
**3. Travel &amp; Wanderlust Focused:**
*   "Dreaming of Italian canals and timeless beauty. 🇮🇹"
*   "Wanderlust activated! Finding magic in the waterways of Europe."
*   "Exploring the hidden gems of a historic city by the water."
**4. Short &amp; Punchy (Good for Instagram):**
*   "Canal views and classical charm."
*   "Waterways of wonder."
*   "Historic beauty afloat."
*   "Venetian dreams."
***
**✨ Pro-Tip: Add Relevant Hashtags**
#Venice #Italy #Canals #History #Architecture #Travel #Europe #HistoricCity #WaterViews #TravelGram
</pre>



<h3 class="wp-block-heading">Using the OpenAI-Compatible API</h3>



<p>One of Ollama&#8217;s most useful features is its OpenAI-compatible API.</p>



<p>When <code data-enlighter-language="python" class="EnlighterJSRAW">Ollama</code> is running, it automatically exposes an HTTP endpoint that mimics the OpenAI Chat Completions API. This means existing applications built for OpenAI often require only a single URL change to work with local models.</p>



<p>We can send a request using cURL:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Running Gemma 4 Locally: Ollama, llama.cpp, MLX, and More" data-enlighter-group="8">curl http://localhost:11434/v1/chat/completions \
 -H "Content-Type: application/json" \
 -d '{
   "model": "gemma4:e2b",
   "messages": [
     {"role": "user", "content": "Explain how transformers work in two sentences."}
   ]
 }'
</pre>



<p>Let us break down the request:</p>



<ul class="wp-block-list">
<li><code data-enlighter-language="python" class="EnlighterJSRAW">model</code>: specifies which local model should handle the request</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">messages</code>: contains the conversation history</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">role</code>: identifies whether a message comes from the user, assistant, or system</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">content</code>: contains the actual prompt</li>
</ul>



<p>The response format mirrors OpenAI&#8217;s API structure, making it straightforward to integrate <code data-enlighter-language="python" class="EnlighterJSRAW">Ollama</code> into existing AI applications.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/07/image-42-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="191" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-42-1024x191.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54674"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-42-1024x191.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-42-1024x191.png?size=126x24&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-42-1024x191.png?size=252x47&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-42-1024x191.png?size=378x71&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-42-1024x191.png?size=504x94&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-42-1024x191.png?size=630x118&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 6:</strong> OpenAI-Compatible API script to run inference (source: author)</figcaption></figure></div>


<h3 class="wp-block-heading">Sending Images via the Ollama API</h3>



<p><code data-enlighter-language="python" class="EnlighterJSRAW">Ollama</code> also supports multimodal requests through its native API.</p>



<p>The following example sends an image directly to Gemma 4:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/07/image-24-scaled.jpeg" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="674" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-24-1024x674.jpeg?lossy=2&strip=1&webp=1" alt="" class="wp-image-54677"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-24-1024x674.jpeg?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-24-1024x674.jpeg?size=126x83&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-24-1024x674.jpeg?size=252x166&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-24-1024x674.jpeg?size=378x249&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-24-1024x674.jpeg?size=504x332&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-24-1024x674.jpeg?size=630x415&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 7:</strong> Input Image (source: <a href="https://huggingface.co/datasets/merve/vlm_test_images/blob/main/venice.jpg" target="_blank" rel="noreferrer noopener">Hugging Face</a>)</figcaption></figure></div>


<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Running Gemma 4 Locally: Ollama, llama.cpp, MLX, and More" data-enlighter-group="9">curl http://localhost:11434/api/generate -d "{
 \"model\": \"gemma4:e2b\",
 \"prompt\": \"Describe what you see in this image\",
 \"images\": [\"$(base64 -i /Users/cosmo3769/Desktop/venice.jpg)\"],
 \"stream\": false
}"
</pre>



<p>Unlike the OpenAI-compatible endpoint, this API accepts image data directly.</p>



<p>Notice the use of:</p>



<p><code data-enlighter-language="python" class="EnlighterJSRAW">base64 -i image.jpg</code></p>



<p>Images cannot be transmitted directly inside JSON payloads, so we first encode the image as a Base64 string. <code data-enlighter-language="python" class="EnlighterJSRAW">Ollama</code> then decodes the image, processes it through Gemma 4&#8217;s vision encoder, and generates a textual response describing what it sees.</p>



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">"stream": false</code> parameter tells <code data-enlighter-language="python" class="EnlighterJSRAW">Ollama</code> to return the complete response in a single payload instead of streaming tokens incrementally.</p>



<p>At this point, we have already covered the majority of day-to-day Gemma 4 workflows:</p>



<ul class="wp-block-list">
<li>Interactive chat</li>



<li>Text generation</li>



<li>Multimodal image understanding</li>



<li>OpenAI-compatible APIs</li>



<li>Programmatic image inference</li>
</ul>



<p>For many developers, <code data-enlighter-language="python" class="EnlighterJSRAW">Ollama</code> is all that is needed to begin building local Gemma 4 applications.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/07/image-43.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="417" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-43-1024x417.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54679"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-43-1024x417.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-43-1024x417.png?size=126x51&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-43-1024x417.png?size=252x103&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-43-1024x417.png?size=378x154&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-43-1024x417.png?size=504x205&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-43-1024x417.png?size=630x257&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 8:</strong> Sending Images via the <code>Ollama</code> API (source: author)</figcaption></figure></div>


<p>To learn more about <code data-enlighter-language="python" class="EnlighterJSRAW">Ollama</code>, you can refer to this <a href="https://pyimg.co/16eu7" target="_blank" rel="noreferrer noopener">blog from PyImageSearch</a>.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Running-Gemma-4-llama-cpp-GGUF-Models"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Running-Gemma-4-llama-cpp-GGUF-Models">Running Gemma 4 with llama.cpp and GGUF Models</a></h2>



<p>While <code data-enlighter-language="python" class="EnlighterJSRAW">Ollama</code> prioritizes simplicity and ease of use, <strong><a href="https://llama-cpp.com" target="_blank" rel="noreferrer noopener">llama.cpp</a></strong> is built for performance, flexibility, and fine-grained control. It is one of the most popular inference engines for running large language models locally, offering efficient CPU execution, hardware acceleration, and native support for <code data-enlighter-language="python" class="EnlighterJSRAW">GGUF</code> models.</p>



<p>Unlike <code data-enlighter-language="python" class="EnlighterJSRAW">Ollama</code>, which abstracts away much of the deployment process, <code data-enlighter-language="python" class="EnlighterJSRAW">llama.cpp</code> gives us direct control over every aspect of inference. We explicitly choose the model file, configure hardware acceleration, launch inference servers, and customize runtime parameters to suit our hardware and workload. This level of control makes <code data-enlighter-language="python" class="EnlighterJSRAW">llama.cpp</code> an excellent choice for developers who want to optimize performance or integrate local models into custom applications.</p>



<p>In this section, we will build <code data-enlighter-language="python" class="EnlighterJSRAW">llama.cpp</code> from source, download a Gemma 4 <code data-enlighter-language="python" class="EnlighterJSRAW">GGUF</code> model, run inference from the command line, launch an OpenAI-compatible API server, and finally enable multimodal image understanding using Gemma 4&#8217;s <strong>MMProj</strong> (multimodal projector) model.</p>



<h3 class="wp-block-heading">Installing Build Dependencies</h3>



<p>Before building <code data-enlighter-language="python" class="EnlighterJSRAW">llama.cpp</code>, we first need to install the required development tools.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Running Gemma 4 Locally: Ollama, llama.cpp, MLX, and More" data-enlighter-group="10">xcode-select --install
clang --version
</pre>



<p>The first command installs Apple&#8217;s Command Line Tools, which include the Clang compiler and other utilities required for compiling C++ projects.</p>



<p>After the installation completes, we can verify that Clang is available by checking its version.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/07/image-44-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="126" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-44-1024x126.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54681"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-44-1024x126.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-44-1024x126.png?size=126x16&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-44-1024x126.png?size=252x31&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-44-1024x126.png?size=378x47&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-44-1024x126.png?size=504x62&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-44-1024x126.png?size=630x78&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 9:</strong> Verifying Clang version (source: author)</figcaption></figure></div>


<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Running Gemma 4 Locally: Ollama, llama.cpp, MLX, and More" data-enlighter-group="11">brew install git cmake
git --version
cmake --version
</pre>



<p>Next, install Git and CMake using Homebrew.</p>



<p>Here:</p>



<ul class="wp-block-list">
<li><strong>Git:</strong> is used to clone the <code data-enlighter-language="python" class="EnlighterJSRAW">llama.cpp</code> source code.</li>



<li><strong>CMake:</strong> generates platform-specific build files and manages the compilation process.</li>
</ul>



<p>Running the version commands confirms that both tools were installed successfully.</p>



<h3 class="wp-block-heading">Cloning the Repository</h3>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Running Gemma 4 Locally: Ollama, llama.cpp, MLX, and More" data-enlighter-group="12">git clone https://github.com/ggerganov/llama.cpp
cd llama.cpp
</pre>



<p>Once the required tools are installed, we can download the <code data-enlighter-language="python" class="EnlighterJSRAW">llama.cpp</code> source code directly from GitHub.</p>



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">git clone</code> command downloads the latest version of the repository to your local machine.</p>



<p>We then change into the project directory, where all remaining build and inference commands will be executed.</p>



<h3 class="wp-block-heading">Building llama.cpp</h3>



<p>Next, we compile <code data-enlighter-language="python" class="EnlighterJSRAW">llama.cpp</code> from source.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Running Gemma 4 Locally: Ollama, llama.cpp, MLX, and More" data-enlighter-group="13">mkdir build
cd build
cmake ..
</pre>



<p>Let us briefly examine these commands.</p>



<p>First, we create a separate <code data-enlighter-language="python" class="EnlighterJSRAW">build</code> directory. Keeping compiled files separate from the source code makes it easier to rebuild or clean the project later.</p>



<p>The command: <code data-enlighter-language="python" class="EnlighterJSRAW">cmake ..</code> configures the project and generates the appropriate build files for your system.</p>



<p>After configuration completes, we compile the project using: </p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Running Gemma 4 Locally: Ollama, llama.cpp, MLX, and More" data-enlighter-group="14">cmake --build . --config Release
</pre>



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">Release</code> configuration enables compiler optimizations, resulting in faster inference performance than a debug build.</p>



<p>Once the compilation finishes, the generated executables can be found inside the <code data-enlighter-language="python" class="EnlighterJSRAW">build/bin</code> directory.</p>



<p>This directory contains utilities such as:</p>



<ul class="wp-block-list">
<li><code data-enlighter-language="python" class="EnlighterJSRAW">llama-cli</code></li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">llama-server</code></li>



<li>model conversion tools</li>



<li>quantization utilities</li>
</ul>



<p>These binaries form the core of the <code data-enlighter-language="python" class="EnlighterJSRAW">llama.cpp</code> inference ecosystem.</p>



<h3 class="wp-block-heading">Enabling Apple Metal Acceleration</h3>



<p>If you are using an Apple Silicon Mac, <code data-enlighter-language="python" class="EnlighterJSRAW">llama.cpp</code> can offload model computation to the GPU through Apple&#8217;s Metal framework.</p>



<p>To enable <code data-enlighter-language="python" class="EnlighterJSRAW">Metal</code> support, rebuild <code data-enlighter-language="python" class="EnlighterJSRAW">llama.cpp</code> with the following configuration:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Running Gemma 4 Locally: Ollama, llama.cpp, MLX, and More" data-enlighter-group="15">cmake -B build -DGGML_METAL=ON
cmake --build build --config Release
</pre>



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">GGML_METAL=ON</code> flag enables GPU acceleration during compilation.</p>



<p>Compared to CPU-only inference, <code data-enlighter-language="python" class="EnlighterJSRAW">Metal</code> acceleration can significantly improve generation speed, particularly for larger Gemma 4 models.</p>



<h3 class="wp-block-heading">Verifying the Installation</h3>



<p>Before downloading a model, it is a good idea to verify that the build completed successfully.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Running Gemma 4 Locally: Ollama, llama.cpp, MLX, and More" data-enlighter-group="16">./build/bin/llama-cli --help
</pre>



<p>If the installation is successful, <code data-enlighter-language="python" class="EnlighterJSRAW">llama.cpp</code> prints the available command-line options for <code data-enlighter-language="python" class="EnlighterJSRAW">llama-cli</code>.</p>



<p>This confirms that the executable was built correctly and is ready to load Gemma 4.</p>



<h3 class="wp-block-heading">Downloading and Locating a Gemma GGUF Model</h3>



<p>Unlike <code data-enlighter-language="python" class="EnlighterJSRAW">Ollama</code>, <code data-enlighter-language="python" class="EnlighterJSRAW">llama.cpp</code> works directly with <code data-enlighter-language="python" class="EnlighterJSRAW">GGUF</code> model files.</p>



<p><code data-enlighter-language="python" class="EnlighterJSRAW">GGUF</code> is a binary model format optimized for fast local inference and supports multiple quantization levels, allowing models to run efficiently on CPUs and consumer GPUs while reducing memory usage.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Running Gemma 4 Locally: Ollama, llama.cpp, MLX, and More" data-enlighter-group="17">python3 -m venv .venv
source .venv/bin/activate
</pre>



<p>We first create a Python virtual environment:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Running Gemma 4 Locally: Ollama, llama.cpp, MLX, and More" data-enlighter-group="18">./build/bin/llama-server -hf ggml-org/gemma-4-E2B-it-GGUF
</pre>



<p>Next, download the Gemma 4 <code data-enlighter-language="python" class="EnlighterJSRAW">GGUF</code> model directly from Hugging Face:</p>



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">-hf</code> option downloads the specified repository automatically and stores the model locally.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Running Gemma 4 Locally: Ollama, llama.cpp, MLX, and More" data-enlighter-group="19">find ~ -name "*gemma*.gguf" 2>/dev/null
</pre>



<p>If you already have the model on your machine, you can locate it using:</p>



<p>This searches your home directory for all <code data-enlighter-language="python" class="EnlighterJSRAW">GGUF</code> files containing &#8220;gemma&#8221; in their filename.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/07/image-45-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="78" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-45-1024x78.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54683"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-45-1024x78.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-45-1024x78.png?size=126x10&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-45-1024x78.png?size=252x19&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-45-1024x78.png?size=378x29&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-45-1024x78.png?size=504x38&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-45-1024x78.png?size=630x48&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 10:</strong> Locating a Gemma <code>GGUF</code> model in local system (source: author)</figcaption></figure></div>


<h3 class="wp-block-heading">Running Gemma 4 from the Command Line</h3>



<p>Once the model has been downloaded, we can perform inference directly from the terminal.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Running Gemma 4 Locally: Ollama, llama.cpp, MLX, and More" data-enlighter-group="20">./build/bin/llama-cli \
 -m /Users/cosmo3769/.lmstudio/models/lmstudio-community/gemma-4-E2B-it-GGUF/gemma-4-E2B-it-Q4_K_M.gguf \
 -p "Explain the Mixture of Experts architecture" \
 -n 512 \
 -ngl 99
</pre>



<p>Here:</p>



<ul class="wp-block-list">
<li><code data-enlighter-language="python" class="EnlighterJSRAW">-m</code>: specifies the path to the <code data-enlighter-language="python" class="EnlighterJSRAW">GGUF</code> model.</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">-p</code>: provides the prompt sent to Gemma 4.</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">-n 512</code>: allows the model to generate up to 512 new tokens.</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">-ngl 99</code>: offloads supported transformer layers to the GPU for faster inference. The exact value depends on your available GPU memory and hardware configuration.</li>
</ul>



<p><em><strong>NOTE: </strong></em><em>We are using the GGUF model from </em><em>LM S</em><em>tudio which we downloaded earlier. We can also use it from hf but it will be the same.</em></p>



<p>After executing the command, Gemma 4 generates a response directly inside the terminal without requiring a separate inference server.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/07/image-46-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="591" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-46-1024x591.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54684"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-46-1024x591.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-46-1024x591.png?size=126x73&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-46-1024x591.png?size=252x145&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-46-1024x591.png?size=378x218&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-46-1024x591.png?size=504x291&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-46-1024x591.png?size=630x364&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 11:</strong> Running Gemma 4 from the command line (source: author)</figcaption></figure></div>

<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/07/image-47.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="378" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-47-1024x378.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54685"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-47-1024x378.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-47-1024x378.png?size=126x47&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-47-1024x378.png?size=252x93&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-47-1024x378.png?size=378x140&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-47-1024x378.png?size=504x186&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-47-1024x378.png?size=630x233&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 12:</strong> Generated response by Gemma 4 inside terminal (source: author)</figcaption></figure></div>


<h3 class="wp-block-heading">Starting a Local API Server</h3>



<p>Instead of running one prompt at a time, we can expose Gemma 4 through a local HTTP server.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Running Gemma 4 Locally: Ollama, llama.cpp, MLX, and More" data-enlighter-group="21">./build/bin/llama-server \
 -m /Users/cosmo3769/.lmstudio/models/lmstudio-community/gemma-4-E2B-it-GGUF/gemma-4-E2B-it-Q4_K_M.gguf \
 --host 0.0.0.0 \
 --port 8080 \
 -n 512
</pre>



<p>Here:</p>



<ul class="wp-block-list">
<li><code data-enlighter-language="python" class="EnlighterJSRAW">--host 0.0.0.0</code>: makes the server accessible on all network interfaces</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">--port 8080</code>: specifies the port used for incoming requests</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">-n 512</code>: sets the default maximum number of generated tokens</li>
</ul>



<p>Once the server starts successfully, it can be accessed at: <code data-enlighter-language="python" class="EnlighterJSRAW">http://127.0.0.1:8080</code>.</p>



<p>This allows other applications, scripts, or web interfaces to communicate with Gemma 4 through a local API instead of launching a new inference process for every request.</p>



<figure style="text-align: center; max-width: 700px; margin: auto;">
<iframe width="700" height="394" src="https://www.youtube.com/embed/qtt_OdsZsS0" title="" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
  <figcaption style="align: center; margin-top: 8px;">    <strong>Figure 13:</strong> Running Gemma 4 Locally Using the <code>llama.cpp</code> Web Interface (source: author)
  </figcaption>
</figure>



<h3 class="wp-block-heading">Enabling Vision Support with MMProj</h3>



<p>Although Gemma 4 is a multimodal model, image understanding requires an additional <strong>MMProj</strong> model when running through <code data-enlighter-language="python" class="EnlighterJSRAW">llama.cpp</code>.</p>



<p>The MMProj model converts visual features produced by the vision encoder into the embedding space expected by the language model, allowing Gemma 4 to reason jointly over images and text.</p>



<p>To enable vision support, launch the server with the additional <code data-enlighter-language="python" class="EnlighterJSRAW">--mmproj</code> argument.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Running Gemma 4 Locally: Ollama, llama.cpp, MLX, and More" data-enlighter-group="22">./build/bin/llama-server \
 -m /Users/cosmo3769/.lmstudio/models/lmstudio-community/gemma-4-E2B-it-GGUF/gemma-4-E2B-it-Q4_K_M.gguf \
 --mmproj /Users/cosmo3769/.lmstudio/models/lmstudio-community/gemma-4-E2B-it-GGUF/mmproj-gemma-4-E2B-it-BF16.gguf \
 --host 0.0.0.0 \
 --port 8080 \
 -n 512
</pre>



<p>Once the MMProj model is loaded, the server can process multimodal requests containing both text and images, enabling tasks such as image captioning, visual question answering, and general image understanding while continuing to use the same GGUF language model.</p>



<p>To learn more about <code data-enlighter-language="python" class="EnlighterJSRAW">llama.cpp</code>, you can refer to this <a href="https://pyimagesearch.com/2024/08/26/llama-cpp-the-ultimate-guide-to-efficient-llm-inference-and-applications/" target="_blank" rel="noreferrer noopener">blog from PyImageSearch</a>.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Running-Gemma-4-MLX-Apple-Silicon-Macs"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Running-Gemma-4-MLX-Apple-Silicon-Macs">Running Gemma 4 with MLX on Apple Silicon Macs</a></h2>



<p>If you are using an Apple Silicon Mac, <strong><a href="https://github.com/ml-explore/mlx" target="_blank" rel="noreferrer noopener">MLX</a></strong> is one of the most efficient ways to run Gemma 4 locally. Developed by Apple, <code data-enlighter-language="python" class="EnlighterJSRAW">MLX</code> is a machine learning framework built specifically for Apple Silicon, enabling models to take full advantage of the unified memory architecture and GPU acceleration available on M-series chips.</p>



<p>Building on top of <code data-enlighter-language="python" class="EnlighterJSRAW">MLX</code>, <strong><a href="https://github.com/Blaizzy/mlx-vlm" target="_blank" rel="noreferrer noopener">MLX-VLM</a></strong> extends the framework with support for vision-language models, making it straightforward to run multimodal models such as Gemma 4 with just a few commands. It also provides an OpenAI-compatible server, allowing locally hosted models to integrate seamlessly with existing applications and tools that already support the OpenAI API.</p>



<p>In this section, we will install <code data-enlighter-language="python" class="EnlighterJSRAW">MLX-VLM</code>, perform multimodal inference from the command line, launch a local OpenAI-compatible server, and interact with Gemma 4 using both cURL and the official OpenAI Python SDK (Software Development Kit).</p>



<h3 class="wp-block-heading">Creating a Python Environment</h3>



<p>We begin by creating a dedicated Python virtual environment.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Running Gemma 4 Locally: Ollama, llama.cpp, MLX, and More" data-enlighter-group="23">python3 -m venv .venv
source .venv/bin/activate
</pre>



<p>The first command creates an isolated Python environment named <code data-enlighter-language="python" class="EnlighterJSRAW">.venv</code>, while the second activates it.</p>



<p>Using a virtual environment keeps project dependencies separate from the system-wide Python installation and helps avoid version conflicts between different machine learning projects.</p>



<h3 class="wp-block-heading">Installing MLX-VLM</h3>



<p>Next, install the <code data-enlighter-language="python" class="EnlighterJSRAW">MLX-VLM</code> package.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Running Gemma 4 Locally: Ollama, llama.cpp, MLX, and More" data-enlighter-group="24">pip install mlx-vlm
</pre>



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">mlx-vlm</code> package includes everything needed to download, load, and run multimodal vision-language models on Apple Silicon devices.</p>



<p>Once installed, we can immediately begin running Gemma 4 without manually downloading model files or compiling inference engines.</p>



<h3 class="wp-block-heading">Running Single-Image Inference</h3>



<p><code data-enlighter-language="python" class="EnlighterJSRAW">MLX-VLM</code> provides a convenient command-line interface for performing multimodal inference.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Running Gemma 4 Locally: Ollama, llama.cpp, MLX, and More" data-enlighter-group="25">mlx_vlm.generate \
 --model mlx-community/gemma-4-e2b-it-4bit \
 --image https://huggingface.co/datasets/huggingface/documentation-images/resolve/0052a70beed5bf71b92610a43a52df6d286cd5f3/diffusers/rabbit.jpg \
 --prompt "Describe this image in detail"
</pre>



<p>Let us examine the command:</p>



<ul class="wp-block-list">
<li><code data-enlighter-language="python" class="EnlighterJSRAW">--model</code>: specifies the Gemma 4 checkpoint to load</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">--image</code>: points to the image that will be analyzed</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">--prompt</code>: provides the accompanying text instruction for the model</li>
</ul>



<p>If the model is not already available locally, <code data-enlighter-language="python" class="EnlighterJSRAW">MLX</code> automatically downloads it from Hugging Face before performing inference.</p>



<p>After loading the image and prompt, Gemma 4 processes both inputs together and generates a detailed textual description of the image.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/07/image-48.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="447" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-48-1024x447.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54694"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-48-1024x447.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-48-1024x447.png?size=126x55&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-48-1024x447.png?size=252x110&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-48-1024x447.png?size=378x165&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-48-1024x447.png?size=504x220&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-48-1024x447.png?size=630x275&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 14:</strong> Single-Image Inference using <code>MLX-VLM</code> (source: author)</figcaption></figure></div>


<h3 class="wp-block-heading">Launching an OpenAI-Compatible Server</h3>



<p>Instead of running one inference at a time, we can launch a local server that exposes an OpenAI-compatible API.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Running Gemma 4 Locally: Ollama, llama.cpp, MLX, and More" data-enlighter-group="26">mlx_vlm.server \
 --model mlx-community/gemma-4-e2b-it-4bit \
 --port 8080
</pre>



<p>This command loads the model into memory and starts a local inference server listening on port <strong>8080</strong>.</p>



<p>Once running, any application capable of communicating with the OpenAI Chat Completions API can send requests directly to the local server without requiring changes to the overall application logic.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/07/image-49-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="171" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-49-1024x171.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54696"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-49-1024x171.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-49-1024x171.png?size=126x21&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-49-1024x171.png?size=252x42&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-49-1024x171.png?size=378x63&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-49-1024x171.png?size=504x84&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-49-1024x171.png?size=630x105&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 15:</strong> Launching an OpenAI-Compatible Server (source: author)</figcaption></figure></div>


<h3 class="wp-block-heading">Querying the Server with cURL</h3>



<p>With the server running, we can send requests using standard HTTP calls.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Running Gemma 4 Locally: Ollama, llama.cpp, MLX, and More" data-enlighter-group="27">curl http://localhost:8080/v1/chat/completions \
 -H "Content-Type: application/json" \
 -d '{
   "model": "mlx-community/gemma-4-e2b-it-4bit",
   "messages": [
     {
       "role": "user",
       "content": [
         {"type": "text", "text": "Describe this image in detail"},
         {"type": "image_url", "image_url": {"url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/0052a70beed5bf71b92610a43a52df6d286cd5f3/diffusers/rabbit.jpg"}}
       ]
     }
   ],
   "max_tokens": 500
 }'
</pre>



<p>The request closely mirrors the OpenAI Chat Completions API.</p>



<p>Unlike text-only requests, the <code data-enlighter-language="python" class="EnlighterJSRAW">content</code> field now contains a list consisting of both:</p>



<ul class="wp-block-list">
<li>a text instruction</li>



<li>an image URL</li>
</ul>



<p>Gemma 4 processes the image and prompt together before generating a multimodal response.</p>



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">max_tokens</code> parameter specifies the maximum number of tokens the model may generate.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/07/image-50.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="298" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-50-1024x298.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54698"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-50-1024x298.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-50-1024x298.png?size=126x37&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-50-1024x298.png?size=252x73&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-50-1024x298.png?size=378x110&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-50-1024x298.png?size=504x147&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-50-1024x298.png?size=630x183&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 16:</strong> Querying the Server with cURL (source: author)</figcaption></figure></div>


<h3 class="wp-block-heading">Querying the Server with Python and OpenAI SDK</h3>



<p>Since <code data-enlighter-language="python" class="EnlighterJSRAW">MLX-VLM</code> exposes an OpenAI-compatible endpoint, we can also interact with it using the official OpenAI Python SDK.</p>



<p>First, install the SDK:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Running Gemma 4 Locally: Ollama, llama.cpp, MLX, and More" data-enlighter-group="28">pip install openai --break-system-packages
</pre>



<p>Next, create an OpenAI client that points to the locally running server.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Running Gemma 4 Locally: Ollama, llama.cpp, MLX, and More" data-enlighter-group="29">from openai import OpenAI

client = OpenAI(base_url="http://localhost:8080/v1", api_key="fake")
</pre>



<p>Notice that the API key is simply a placeholder. Authentication is not required because the server is running locally on our machine.</p>



<p>Once the client has been initialized, sending multimodal requests is almost identical to interacting with OpenAI-hosted models.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Running Gemma 4 Locally: Ollama, llama.cpp, MLX, and More" data-enlighter-group="30">response = client.chat.completions.create(
   model="mlx-community/gemma-4-e2b-it-4bit",
   messages=[
       {
           "role": "user",
           "content": [
               {"type": "text", "text": "Describe this image"},
               {"type": "image_url", "image_url": {"url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/0052a70beed5bf71b92610a43a52df6d286cd5f3/diffusers/rabbit.jpg
"}}
           ]
       }
   ],
   max_tokens=500
)
</pre>



<p>The request contains both text and image inputs inside the <code data-enlighter-language="python" class="EnlighterJSRAW">messages</code> field, following the same structure used by the OpenAI Vision API.</p>



<p>After the request is sent, Gemma 4 analyzes the image, combines it with the accompanying prompt, and returns a textual response, which we print using:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Running Gemma 4 Locally: Ollama, llama.cpp, MLX, and More" data-enlighter-group="31">print(response.choices[0].message.content)
</pre>



<p>One of the biggest advantages of <code data-enlighter-language="python" class="EnlighterJSRAW">MLX-VLM</code> is that developers already using the OpenAI SDK can switch to a fully local Gemma 4 deployment with minimal code changes. In many cases, updating the <code data-enlighter-language="python" class="EnlighterJSRAW">base_url</code> to point to the local server is all that is required, making it straightforward to move between cloud-hosted and on-device inference while keeping the rest of the application unchanged.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/07/image-51-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="378" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-51-1024x378.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54701"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-51-1024x378.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-51-1024x378.png?size=126x47&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-51-1024x378.png?size=252x93&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-51-1024x378.png?size=378x140&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-51-1024x378.png?size=504x186&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-51-1024x378.png?size=630x233&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 17:</strong> Processing Images Through the OpenAI SDK (source: author)</figcaption></figure></div>


<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Running-Gemma-4-LM-Studio-Desktop-App"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Running-Gemma-4-LM-Studio-Desktop-App">Running Gemma 4 with LM Studio&#8217;s Desktop App</a></h2>



<p>If you are looking for the easiest way to run Gemma 4 locally without using the command line, <strong><a href="https://lmstudio.ai" target="_blank" rel="noreferrer noopener">LM Studio</a></strong> is an excellent choice. It provides an intuitive graphical interface for downloading, managing, and interacting with local language models, while handling much of the underlying configuration automatically.</p>



<p>Behind the scenes, <code data-enlighter-language="python" class="EnlighterJSRAW">LM Studio</code> uses <code data-enlighter-language="python" class="EnlighterJSRAW">llama.cpp</code> as its inference engine for <code data-enlighter-language="python" class="EnlighterJSRAW">GGUF</code> models, allowing you to benefit from efficient CPU and GPU inference without manually compiling the runtime or configuring model files. This makes it an ideal option for developers who want a streamlined setup while still taking advantage of the performance offered by <code data-enlighter-language="python" class="EnlighterJSRAW">llama.cpp</code>.</p>



<p>In this section, we will install <code data-enlighter-language="python" class="EnlighterJSRAW">LM Studio</code>, download a Gemma 4 model, configure the local runtime, and begin interacting with Gemma 4 through its built-in chat interface.</p>



<h3 class="wp-block-heading">Installing LM Studio</h3>



<p>Begin by downloading and installing <code data-enlighter-language="python" class="EnlighterJSRAW">LM Studio</code> from its official website. Once the installation is complete, launch the application.</p>



<p>On the first launch, you will be greeted with the welcome screen shown in <strong>Figure </strong><strong>18</strong>.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/07/image-52-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="659" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-52-1024x659.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54703"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-52-1024x659.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-52-1024x659.png?size=126x81&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-52-1024x659.png?size=252x162&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-52-1024x659.png?size=378x243&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-52-1024x659.png?size=504x324&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-52-1024x659.png?size=630x405&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 18:</strong> Welcome screen displayed when launching <code>LM Studio</code> for the first time (source: LM Studio Application)</figcaption></figure></div>


<p>Click <strong>Get Started</strong> to begin the setup process.</p>



<h3 class="wp-block-heading">Downloading Your First Model</h3>



<p><code data-enlighter-language="python" class="EnlighterJSRAW">LM Studio</code> guides you through downloading your first local model.</p>



<p>As shown in <strong>Figure </strong><strong>19</strong>, it recommends downloading a Gemma 4 model directly from within the application.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/07/image-53-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="659" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-53-1024x659.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54705"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-53-1024x659.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-53-1024x659.png?size=126x81&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-53-1024x659.png?size=252x162&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-53-1024x659.png?size=378x243&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-53-1024x659.png?size=504x324&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-53-1024x659.png?size=630x405&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 19:</strong> <code>LM Studio</code> recommends downloading a Gemma 4 model during the initial setup (source: LM Studio Application)</figcaption></figure></div>


<p>Click <strong>Download gemma-4-e4b</strong> to begin downloading the model. During the download, <code data-enlighter-language="python" class="EnlighterJSRAW">LM Studio</code> displays the current progress while allowing you to continue using the application.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/07/image-54-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="659" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-54-1024x659.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54707"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-54-1024x659.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-54-1024x659.png?size=126x81&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-54-1024x659.png?size=252x162&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-54-1024x659.png?size=378x243&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-54-1024x659.png?size=504x324&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-54-1024x659.png?size=630x405&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 20:</strong> Download progress for the selected Gemma 4 model (source: LM Studio Application)</figcaption></figure></div>


<p>Once the download finishes, you will see a confirmation screen indicating that the model is ready for use.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/07/image-55-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="659" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-55-1024x659.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54708"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-55-1024x659.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-55-1024x659.png?size=126x81&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-55-1024x659.png?size=252x162&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-55-1024x659.png?size=378x243&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-55-1024x659.png?size=504x324&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-55-1024x659.png?size=630x405&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 21:</strong> Model download completed successfully (source: LM Studio Application)</figcaption></figure></div>


<p>Click <strong>Continue</strong> to proceed to the final setup step.</p>



<h3 class="wp-block-heading">Enabling Developer Mode</h3>



<p>Before entering the main interface, <code data-enlighter-language="python" class="EnlighterJSRAW">LM Studio</code> presents several optional developer settings.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/07/image-56-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="659" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-56-1024x659.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54709"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-56-1024x659.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-56-1024x659.png?size=126x81&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-56-1024x659.png?size=252x162&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-56-1024x659.png?size=378x243&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-56-1024x659.png?size=504x324&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-56-1024x659.png?size=630x405&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 22:</strong> Advanced settings available during the initial configuration (source: LM Studio Application)</figcaption></figure></div>


<p>For this lesson, enable both options:</p>



<ul class="wp-block-list">
<li><strong>Turn on Developer Mode</strong></li>



<li><strong>Start local LLM service on login</strong></li>
</ul>



<p><code data-enlighter-language="python" class="EnlighterJSRAW">Developer Mode</code> exposes additional features useful for developers, while automatically starting the local server makes it easier to access your models from external applications through an OpenAI-compatible API.</p>



<p>After enabling these options, click <strong>Continue to LM Studio</strong>.</p>



<h3 class="wp-block-heading">Loading Gemma 4</h3>



<p>Once <code data-enlighter-language="python" class="EnlighterJSRAW">LM Studio</code> opens, you will see an empty workspace similar to <strong>Figure </strong><strong>23</strong>.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/07/image-57-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="644" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-57-1024x644.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54710"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-57-1024x644.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-57-1024x644.png?size=126x79&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-57-1024x644.png?size=252x158&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-57-1024x644.png?size=378x238&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-57-1024x644.png?size=504x317&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-57-1024x644.png?size=630x396&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 23:</strong> Main <code>LM Studio</code> interface after completing the setup (source: LM Studio Application)</figcaption></figure></div>


<p>To begin chatting with Gemma 4, create a new conversation by clicking <strong>New Chat</strong>.</p>



<p>Next, click <strong>Select a model to load</strong> at the top of the window.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/07/image-58-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="644" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-58-1024x644.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54712"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-58-1024x644.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-58-1024x644.png?size=126x79&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-58-1024x644.png?size=252x158&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-58-1024x644.png?size=378x238&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-58-1024x644.png?size=504x317&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-58-1024x644.png?size=630x396&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 24:</strong> Creating a new chat before selecting a model (source: LM Studio Application)</figcaption></figure></div>


<p>If you have already downloaded Gemma 4 during setup, you can simply select it from the available models.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/07/image-59-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="644" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-59-1024x644.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54714"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-59-1024x644.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-59-1024x644.png?size=126x79&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-59-1024x644.png?size=252x158&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-59-1024x644.png?size=378x238&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-59-1024x644.png?size=504x317&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-59-1024x644.png?size=630x396&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 25: </strong>Downloaded model selected (source: LM Studio Application)</figcaption></figure></div>


<p>Otherwise, use the search bar to search for <strong>gemma-4-e2b</strong>. <code data-enlighter-language="python" class="EnlighterJSRAW">LM Studio</code> displays several compatible model variants, including <code data-enlighter-language="python" class="EnlighterJSRAW">GGUF</code> and <code data-enlighter-language="python" class="EnlighterJSRAW">MLX</code> versions.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/07/image-60-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="644" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-60-1024x644.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54716"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-60-1024x644.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-60-1024x644.png?size=126x79&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-60-1024x644.png?size=252x158&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-60-1024x644.png?size=378x238&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-60-1024x644.png?size=504x317&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-60-1024x644.png?size=630x396&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 26:</strong> Searching for Gemma 4 models inside <code>LM Studio</code> (source: LM Studio Application)</figcaption></figure></div>


<p>For this lesson, select the <strong>gemma-4-E2B-it-GGUF</strong> model and click <strong>Download</strong>. <code data-enlighter-language="python" class="EnlighterJSRAW">LM Studio</code> automatically downloads the model and stores it in its local model library.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/07/image-61-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="644" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-61-1024x644.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54718"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-61-1024x644.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-61-1024x644.png?size=126x79&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-61-1024x644.png?size=252x158&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-61-1024x644.png?size=378x238&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-61-1024x644.png?size=504x317&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-61-1024x644.png?size=630x396&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 27: </strong>Model Downloading (source: LM Studio Application)</figcaption></figure></div>


<p>After the download completes, load the model into memory by selecting it from the model picker.</p>



<p>Once loaded successfully, the model name appears at the top of the interface, and the chat window becomes active.</p>



<h3 class="wp-block-heading">Running Inference</h3>



<p>You can now interact with Gemma 4 just like any other chat assistant. Simply enter your prompt into the message box and press <strong>Enter</strong> to generate a response.</p>



<p>For example, asking:</p>



<p><code data-enlighter-language="raw" class="EnlighterJSRAW">What is an LLM?</code></p>



<p>produces the response shown in <strong>Figure </strong><strong>28</strong>.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/07/image-62-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="571" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-62-1024x571.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54719"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-62-1024x571.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-62-1024x571.png?size=126x70&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-62-1024x571.png?size=252x141&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-62-1024x571.png?size=378x211&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-62-1024x571.png?size=504x281&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-62-1024x571.png?size=630x351&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 28:</strong> Gemma 4 loaded and ready for inference (source: LM Studio Application)</figcaption></figure></div>


<p>In <strong>Figure </strong><strong>29</strong>, we can also see that we can input an image and prompt together to generate a response. </p>



<figure style="text-align: center; max-width: 700px; margin: auto;">
<iframe width="700" height="394" src="https://www.youtube.com/embed/7X5DFxGPsjg" title="" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
  <figcaption style="align: center; margin-top: 8px;">
    <strong>Figure 29:</strong> Running inference locally with Gemma 4 inside <code>LM Studio</code> (source: LM Studio Application)
  </figcaption>
</figure>



<p>At this point, we have a fully functional local Gemma 4 environment capable of running entirely on our own machine, without relying on external APIs or cloud services.</p>



<p>To learn more about <code data-enlighter-language="python" class="EnlighterJSRAW">LM Studio</code>, you can refer to this <a href="https://pyimagesearch.com/2024/06/24/integrating-local-llm-frameworks-a-deep-dive-into-lm-studio-and-anythingllm/" target="_blank" rel="noreferrer noopener">blog from PyImageSearch</a>.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Running-Gemma-4-Locally-Transformers-js"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Running-Gemma-4-Locally-Transformers-js">Running Gemma 4 Locally with Transformers.js</a></h2>



<p>Unlike the deployment options we have explored so far, <strong><a href="https://github.com/huggingface/transformers.js" target="_blank" rel="noreferrer noopener">Transformers.js</a></strong> allows us to run Gemma 4 entirely from JavaScript. Instead of relying on Python or a native inference engine, it enables developers to load and run Hugging Face models directly within <code data-enlighter-language="python" class="EnlighterJSRAW">Node.js</code> applications using familiar JavaScript APIs.</p>



<p>Under the hood, <code data-enlighter-language="python" class="EnlighterJSRAW">Transformers.js</code> executes <strong>ONNX</strong> versions of Hugging Face models through ONNX Runtime, making it possible to perform local inference without leaving the JavaScript ecosystem. This makes it an excellent choice for JavaScript developers who want to build AI-powered applications without introducing a separate Python backend or external inference service.</p>



<p>In this section, we will install <code data-enlighter-language="python" class="EnlighterJSRAW">Transformers.js</code>, download an ONNX version of Gemma 4, load the model locally, process both image and audio inputs, and perform multimodal inference entirely from JavaScript.</p>



<h3 class="wp-block-heading">Setting Up the Project</h3>



<p>We begin by creating a new <code data-enlighter-language="python" class="EnlighterJSRAW">Node.js</code> project.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Running Gemma 4 Locally: Ollama, llama.cpp, MLX, and More" data-enlighter-group="32">npm init -y
</pre>



<p>This command initializes a new <code data-enlighter-language="python" class="EnlighterJSRAW">Node.js</code> project and creates a <code data-enlighter-language="python" class="EnlighterJSRAW">package.json</code> file containing the project&#8217;s metadata, dependencies, and configuration.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Running Gemma 4 Locally: Ollama, llama.cpp, MLX, and More" data-enlighter-group="33">npm install @huggingface/transformers wavefile
</pre>



<p>Next, install the required packages.</p>



<p>This installs 2 packages that our application depends on:</p>



<ul class="wp-block-list">
<li><code data-enlighter-language="python" class="EnlighterJSRAW">@huggingface/transformers</code>: provides the <code data-enlighter-language="python" class="EnlighterJSRAW">Transformers.js</code> library for downloading, loading, and running Hugging Face models directly from JavaScript.</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">wavefile</code>: is a lightweight library for reading and preprocessing WAV audio files before they are passed to Gemma 4.</li>
</ul>



<p>Once the installation completes, create a file named <code data-enlighter-language="python" class="EnlighterJSRAW">index.mjs</code>. This file will contain our entire multimodal inference pipeline, including model loading, input preprocessing, and response generation.</p>



<h3 class="wp-block-heading">Importing the Required Libraries</h3>



<p>We begin by importing the libraries needed throughout the application.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Running Gemma 4 Locally: Ollama, llama.cpp, MLX, and More" data-enlighter-group="34">import {
 AutoProcessor,
 Gemma4ForConditionalGeneration,
 TextStreamer,
 load_image,
} from "@huggingface/transformers";
import pkg from "wavefile";
const { WaveFile } = pkg;
import { readFileSync, existsSync, createWriteStream } from "fs";
import { pipeline } from "stream/promises";
import { tmpdir } from "os";
import { join } from "path";
</pre>



<p>Let us understand the purpose of each import.</p>



<p>The first group of imports comes from <code data-enlighter-language="python" class="EnlighterJSRAW">Transformers.js</code>.</p>



<ul class="wp-block-list">
<li><code data-enlighter-language="python" class="EnlighterJSRAW">AutoProcessor</code>: loads the preprocessing pipeline associated with Gemma 4. It prepares text, images, and audio before they are passed to the model.</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">Gemma4ForConditionalGeneration</code>: loads the Gemma 4 ONNX model and provides the generation API that we will use for multimodal inference.</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">TextStreamer</code>: streams generated tokens to the terminal as they are produced instead of waiting for the entire response to finish. This creates a more interactive experience, especially for longer generations.</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">load_image</code>: simplifies loading images from either local files or remote URLs.</li>
</ul>



<p>Next, we import the <code data-enlighter-language="python" class="EnlighterJSRAW">wavefile</code> package.</p>



<p>Unlike images, audio inputs require additional preprocessing before they can be passed to Gemma 4. The <code data-enlighter-language="python" class="EnlighterJSRAW">WaveFile</code> class allows us to read WAV (Waveform Audio File Format) files, convert them to the required bit depth, resample them to the appropriate sampling rate, and extract the raw audio samples expected by the model.</p>



<p>Finally, we import several built-in <code data-enlighter-language="python" class="EnlighterJSRAW">Node.js</code> modules. These utilities help us manage files and temporary resources during inference.</p>



<p>Here:</p>



<ul class="wp-block-list">
<li><code data-enlighter-language="python" class="EnlighterJSRAW">fs</code>: provides functions for reading files from disk and creating temporary files</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">pipeline</code>: enables efficient streaming of downloaded data, such as audio files, directly into a file</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">tmpdir</code>: returns the operating system&#8217;s temporary directory, which we use for storing downloaded files during preprocessing</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">join</code>: constructs platform-independent file paths, ensuring the script works consistently across different operating systems</li>
</ul>



<p>Together, these libraries provide everything needed to load Gemma 4, preprocess multimodal inputs, and perform inference entirely from a JavaScript application.</p>



<h3 class="wp-block-heading">Creating Helper Functions</h3>



<p>Before loading the model, let us define a few helper functions that make our script easier to read and improve the overall user experience.</p>



<p>These functions are not directly involved in running Gemma 4. Instead, they provide utilities for formatting terminal output, displaying download progress, measuring execution time, and preprocessing audio before it is passed to the model.</p>



<h4 class="wp-block-heading">Formatting Console Output</h4>



<p>We begin by defining several ANSI (American National Standards Institute) escape codes.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="13" data-enlighter-title="Running Gemma 4 Locally: Ollama, llama.cpp, MLX, and More" data-enlighter-group="35">const RESET  = "\x1b[0m";
const BOLD   = "\x1b[1m";
const GREEN  = "\x1b[32m";
const CYAN   = "\x1b[36m";
const YELLOW = "\x1b[33m";
const DIM    = "\x1b[2m";
</pre>



<p>ANSI escape codes allow us to style text printed to the terminal. Throughout the script, we use them to distinguish different types of messages by applying colors and formatting.</p>



<p>For example:</p>



<ul class="wp-block-list">
<li><strong>Cyan:</strong> is used for informational messages.</li>



<li><strong>Green:</strong> indicates successful operations.</li>



<li><strong>Yellow:</strong> highlights warnings.</li>



<li><strong>Bold:</strong> makes important messages easier to identify.</li>



<li><strong>Dim:</strong> is used when displaying elapsed execution times.</li>
</ul>



<p>Although optional, these formatting codes make the script much easier to follow, especially since downloading and loading large language models can take several minutes.</p>



<h4 class="wp-block-heading">Logging Progress</h4>



<p>Next, we define 3 small helper functions.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="19" data-enlighter-title="Running Gemma 4 Locally: Ollama, llama.cpp, MLX, and More" data-enlighter-group="36">function log(label, msg = "") {
 console.log(`${BOLD}${CYAN}[${label}]${RESET} ${msg}`);
}

function success(label, msg = "") {
 console.log(`${BOLD}${GREEN}[${label}]${RESET} ${msg}`);
}

function warn(msg) {
 console.log(`${BOLD}${YELLOW}[WARN]${RESET} ${msg}`);
}
</pre>



<p>Rather than repeatedly writing lengthy <code data-enlighter-language="python" class="EnlighterJSRAW">console.log()</code> statements throughout the program, these helper functions provide a consistent way to display messages.</p>



<p>For example:</p>



<ul class="wp-block-list">
<li><code data-enlighter-language="python" class="EnlighterJSRAW">log()</code>: prints general progress updates</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">success()</code>: indicates that a step completed successfully</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">warn()</code>: displays warning messages that the user should be aware of</li>
</ul>



<p>Using dedicated helper functions also keeps the main inference pipeline much cleaner and easier to read.</p>



<h4 class="wp-block-heading">Measuring Execution Time</h4>



<p>The next helper measures how long each stage of the pipeline takes to execute.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="30" data-enlighter-title="Running Gemma 4 Locally: Ollama, llama.cpp, MLX, and More" data-enlighter-group="37">function elapsed(start) {
 return `${DIM}(${((Date.now() - start) / 1000).toFixed(1)}s)${RESET}`;
}
</pre>



<p>This function accepts a starting timestamp, computes the elapsed time using <code data-enlighter-language="python" class="EnlighterJSRAW">Date.now()</code>, converts the result to seconds, and formats it for display.</p>



<p>We will use this helper throughout the script to report how long it takes to load the processor, initialize the model, preprocess inputs, and generate responses.</p>



<h4 class="wp-block-heading">Displaying Model Download Progress</h4>



<p>The first time the script runs, <code data-enlighter-language="python" class="EnlighterJSRAW">Transformers.js</code> must download the ONNX (Open Neural Network Exchange) model files from Hugging Face. Depending on your network connection and the model size, this process may take several minutes.</p>



<p>To provide better feedback during the download, we define a helper function that renders a progress bar inside the terminal.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="33" data-enlighter-title="Running Gemma 4 Locally: Ollama, llama.cpp, MLX, and More" data-enlighter-group="38">// Single overall progress bar that updates in place
let progressStarted = false;
function renderOverallProgress(pct) {
 const clamped = Math.min(Math.round(pct ?? 0), 100);
 const filled = Math.round(clamped / 2);
 const bar = "█".repeat(filled) + "░".repeat(50 - filled);
 if (!progressStarted) {
   process.stdout.write("\n");
   progressStarted = true;
 }
 process.stdout.write(`\r  Downloading  [${CYAN}${bar}${RESET}] ${clamped.toString().padStart(3)}%`);
 if (clamped >= 100) process.stdout.write(`  ${GREEN}✓${RESET}\n`);
}
</pre>



<p>The function receives the current download percentage, converts it into a visual progress bar, and continuously updates the same terminal line as the download progresses.</p>



<p>Instead of printing hundreds of individual progress messages, the user sees a single progress bar that gradually fills until the download completes.</p>



<p>This provides a much cleaner and more user-friendly experience while large model files are being retrieved.</p>



<h4 class="wp-block-heading">Loading and Preprocessing Audio</h4>



<p>Finally, we define the <code data-enlighter-language="python" class="EnlighterJSRAW">loadAudioNode()</code> helper.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="46" data-enlighter-title="Running Gemma 4 Locally: Ollama, llama.cpp, MLX, and More" data-enlighter-group="39">// Load WAV audio manually for Node.js (no AudioContext needed)
async function loadAudioNode(url) {
 const tmpPath = join(tmpdir(), "audio_input.wav");
 const res = await fetch(url);
 if (!res.ok) throw new Error(`Failed to fetch audio: ${res.statusText}`);
 const dest = createWriteStream(tmpPath);
 await pipeline(res.body, dest);
 const wav = new WaveFile(readFileSync(tmpPath));
 wav.toBitDepth("32f");
 wav.toSampleRate(16000);
 let samples = wav.getSamples();
 // If stereo, use only the first channel
 if (Array.isArray(samples)) samples = samples[0];
 return new Float32Array(samples);
}
</pre>



<p>Unlike images, audio requires several preprocessing steps before it can be passed into Gemma 4.</p>



<p>This helper performs the entire pipeline automatically.</p>



<p>Specifically, it:</p>



<ul class="wp-block-list">
<li>downloads the audio file from the provided URL</li>



<li>saves it to a temporary location on disk</li>



<li>opens the WAV file using the <code data-enlighter-language="python" class="EnlighterJSRAW">WaveFile</code> library</li>



<li>converts the audio to <strong>32-bit floating-point</strong> samples</li>



<li>resamples the audio to <strong>16 kHz</strong>, which is the sampling rate expected by Gemma 4</li>



<li>If the audio contains multiple channels (e.g., stereo), it keeps only the first channel and converts the result into a <code data-enlighter-language="python" class="EnlighterJSRAW">Float32Array</code>.</li>
</ul>



<p>The returned <code data-enlighter-language="python" class="EnlighterJSRAW">Float32Array</code> contains the raw waveform samples that will later be passed to the processor alongside the text prompt and image.</p>



<p>By moving all of this logic into a dedicated helper function, the main inference pipeline remains concise and focused on the high-level workflow rather than the details of audio preprocessing.</p>



<h3 class="wp-block-heading">Loading the Gemma 4 Processor</h3>



<p>With the helper functions in place, we are ready to load the processor and the Gemma 4 model.</p>



<p>We begin by specifying the model that we will use throughout this lesson.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="61" data-enlighter-title="Running Gemma 4 Locally: Ollama, llama.cpp, MLX, and More" data-enlighter-group="40">const model_id = "onnx-community/gemma-4-E2B-it-ONNX";
</pre>



<p>Unlike the previous lessons that used Hugging Face Transformers in Python, <code data-enlighter-language="python" class="EnlighterJSRAW">Transformers.js</code> works with <strong>ONNX</strong> models. Here, we are loading the <strong>Gemma 4 E2B Instruct</strong> model that has been converted to the ONNX format and published by the Hugging Face community.</p>



<p>Using a single <code data-enlighter-language="python" class="EnlighterJSRAW">model_id</code> variable also makes it easy to switch to another compatible model later by changing just one line of code.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="62" data-enlighter-title="Running Gemma 4 Locally: Ollama, llama.cpp, MLX, and More" data-enlighter-group="41">// 1. Processor
log("1/5", `Loading processor from ${BOLD}${model_id}${RESET} ...`);
let t = Date.now();
const processor = await AutoProcessor.from_pretrained(model_id);
success("1/5", `Processor ready ${elapsed(t)}`);
</pre>



<p>Next, we load the processor.</p>



<p>The processor is responsible for converting our multimodal inputs into the format expected by Gemma 4.</p>



<p>Depending on the task, it handles operations such as:</p>



<ul class="wp-block-list">
<li>tokenizing text</li>



<li>preprocessing images</li>



<li>extracting audio features</li>



<li>packaging all modalities into tensors that can be passed directly to the model</li>
</ul>



<p>Calling <code data-enlighter-language="python" class="EnlighterJSRAW">AutoProcessor.from_pretrained()</code> automatically downloads the processor configuration (if it is not already available locally) and initializes the preprocessing pipeline associated with the selected model.</p>



<p>We also record the start time using <code data-enlighter-language="python" class="EnlighterJSRAW">Date.now()</code> so that our helper function can report how long the processor takes to load.</p>



<h3 class="wp-block-heading">Loading the Gemma 4 Model</h3>



<p>After the processor has been initialized, we can load the Gemma 4 model itself.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="67" data-enlighter-title="Running Gemma 4 Locally: Ollama, llama.cpp, MLX, and More" data-enlighter-group="42">// 2. Model
log("2/5", `Loading model (dtype=q4f16, device=cpu) — this may take several minutes on first run ...`);
warn("The ONNX model files are large. Progress bar will appear below as files download/load.");
t = Date.now();

const model = await Gemma4ForConditionalGeneration.from_pretrained(model_id, {
 dtype: "q4f16",
 device: "cpu",
 progress_callback: (info) => {
   if (info.status === "progress_total") {
     renderOverallProgress(info.progress);
   }
   // suppress all other per-file noise
 },
});
success("2/5", `Model loaded ${elapsed(t)}`);
</pre>



<p>Unlike the processor, loading the model can take noticeably longer because <code data-enlighter-language="python" class="EnlighterJSRAW">Transformers.js</code> may need to download several large ONNX weight files before inference can begin.</p>



<p>Let us look at the most important arguments passed to <code data-enlighter-language="python" class="EnlighterJSRAW">from_pretrained()</code>:</p>



<ul class="wp-block-list">
<li><code data-enlighter-language="python" class="EnlighterJSRAW">dtype: "q4f16"</code>: loads a <strong>4-bit quantized</strong> version of the model. Quantization significantly reduces memory usage and improves inference speed while maintaining good generation quality.</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">device: "cpu"</code>: instructs <code data-enlighter-language="python" class="EnlighterJSRAW">Transformers.js</code> to execute the model on the CPU. Depending on your environment, other execution backends may also be available.</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">progress_callback</code>: receives updates while the model files are being downloaded and loaded. Instead of displaying numerous progress messages, we pass the overall download percentage to our <code data-enlighter-language="python" class="EnlighterJSRAW">renderOverallProgress()</code> helper, which renders a clean progress bar in the terminal.</li>
</ul>



<p>Once the model has been downloaded, subsequent executions become much faster because <code data-enlighter-language="python" class="EnlighterJSRAW">Transformers.js</code> reuses the locally cached files.</p>



<h3 class="wp-block-heading">Building the Multimodal Prompt</h3>



<p>With both the processor and model loaded, the next step is defining the conversation that will be sent to Gemma 4.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="83" data-enlighter-title="Running Gemma 4 Locally: Ollama, llama.cpp, MLX, and More" data-enlighter-group="43">// 3. Prompt
log("3/5", "Building chat prompt ...");
const messages = [
 {
   role: "user",
   content: [
     { type: "image" },
     { type: "audio" },
     {
       type: "text",
       text: "Describe this image in detail and transcribe this audio verbatim.",
     },
   ],
 },
];
</pre>



<p>Just like the Python Transformers library, <code data-enlighter-language="python" class="EnlighterJSRAW">Transformers.js</code> represents conversations as a list of chat messages.</p>



<p>Here, the user message contains <strong>3 different modalities</strong>:</p>



<ul class="wp-block-list">
<li>an image</li>



<li>an audio clip</li>



<li>a text instruction</li>
</ul>



<p>The text prompt asks Gemma 4 to perform 2 tasks simultaneously:</p>



<ul class="wp-block-list">
<li>describe the contents of the image</li>



<li>transcribe the accompanying audio</li>
</ul>



<p>Notice that the image and audio are represented using placeholder objects. The actual image and audio data will be loaded and attached in the next step.</p>



<p>Next, we convert these messages into the format expected by Gemma 4.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="98" data-enlighter-title="Running Gemma 4 Locally: Ollama, llama.cpp, MLX, and More" data-enlighter-group="44">const prompt = processor.apply_chat_template(messages, {
 enable_thinking: false,
 add_generation_prompt: true,
});
success("3/5", "Prompt ready");
</pre>



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">apply_chat_template()</code> method formats the conversation according to Gemma 4&#8217;s chat template.</p>



<p>Here:</p>



<ul class="wp-block-list">
<li><code data-enlighter-language="python" class="EnlighterJSRAW">enable_thinking: false</code>: disables the model&#8217;s thinking mode so that only the final response is generated.</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">add_generation_prompt: true</code>: appends the appropriate assistant generation token, indicating where the model should begin generating its response.</li>
</ul>



<p>Using the model&#8217;s built-in chat template ensures that prompts follow the exact conversational format expected during training.</p>



<h3 class="wp-block-heading">Loading and Processing the Inputs</h3>



<p>Next, we load the image and audio that will be provided to the model.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="103" data-enlighter-title="Running Gemma 4 Locally: Ollama, llama.cpp, MLX, and More" data-enlighter-group="45">// 4. Inputs
log("4/5", "Fetching image and audio, then processing inputs ...");
t = Date.now();

const imageUrl = "https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/artemis.jpeg";
const audioUrl = "https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav";
</pre>



<p>For this example, both inputs are hosted remotely and downloaded at runtime.</p>



<p>We first load the image.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="109" data-enlighter-title="Running Gemma 4 Locally: Ollama, llama.cpp, MLX, and More" data-enlighter-group="46">log("4/5", `  Image → ${imageUrl}`);
const image = await load_image(imageUrl);
success("4/5", "  Image loaded");
</pre>



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">load_image()</code> helper downloads the image and prepares it for the processor.</p>



<p>Next, we load the audio.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="112" data-enlighter-title="Running Gemma 4 Locally: Ollama, llama.cpp, MLX, and More" data-enlighter-group="47">log("4/5", `  Audio → ${audioUrl}`);
const audio = await loadAudioNode(audioUrl);
success("4/5", `  Audio loaded — ${audio.length} samples @ 16kHz`);
</pre>



<p>As discussed earlier, <code data-enlighter-language="python" class="EnlighterJSRAW">loadAudioNode()</code> downloads the WAV file, converts it to <strong>32-bit floating-point samples</strong>, resamples it to <strong>16 kHz</strong>, and returns a <code data-enlighter-language="python" class="EnlighterJSRAW">Float32Array</code> containing the waveform.</p>



<p>With both inputs available, we can prepare the model inputs.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="115" data-enlighter-title="Running Gemma 4 Locally: Ollama, llama.cpp, MLX, and More" data-enlighter-group="48">const inputs = await processor(prompt, image, audio, { add_special_tokens: false });
success("4/5", `Inputs ready ${elapsed(t)}`);
</pre>



<p>The processor combines the formatted prompt, image, and audio into a single set of tensors suitable for Gemma 4.</p>



<p>Notice that all 3 modalities are processed together through a single API call. This is one of the advantages of <code data-enlighter-language="python" class="EnlighterJSRAW">Transformers.js</code>, where the same processor handles text, images, and audio without requiring separate preprocessing pipelines.</p>



<h3 class="wp-block-heading">Running Inference</h3>



<p>With the inputs prepared, we can finally generate a response.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="117" data-enlighter-title="Running Gemma 4 Locally: Ollama, llama.cpp, MLX, and More" data-enlighter-group="49">// 5. Generate
log("5/5", "Running inference (CPU can be slow — please wait) ...");
warn("Token generation will stream below as it completes:\n");
t = Date.now();

let tokenCount = 0;
const outputs = await model.generate({
 ...inputs,
 max_new_tokens: 512,
 do_sample: false,
 streamer: new TextStreamer(processor.tokenizer, {
   skip_prompt: true,
   skip_special_tokens: false,
   callback_function: (text) => {
     tokenCount++;
     process.stdout.write(text);
   },
 }),
});

process.stdout.write("\n\n");
success("5/5", `Generation done — ${tokenCount} tokens ${elapsed(t)}`);
</pre>



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">generate()</code> method performs autoregressive text generation using the prepared multimodal inputs.</p>



<p>Some of the most important parameters are:</p>



<ul class="wp-block-list">
<li><code data-enlighter-language="python" class="EnlighterJSRAW">max_new_tokens: 512</code>: limits the maximum length of the generated response.</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">do_sample: false</code>: disables random sampling, producing deterministic outputs for identical inputs.</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">streamer</code>: enables token streaming so that text appears in the terminal as soon as it is generated.</li>
</ul>



<p>Without a streamer, the program would wait until generation finishes before displaying the complete response. By using <code data-enlighter-language="python" class="EnlighterJSRAW">TextStreamer</code>, users receive immediate feedback as Gemma 4 produces each token, resulting in a much more interactive experience.</p>



<h3 class="wp-block-heading">Decoding the Generated Output</h3>



<p>The output returned by <code data-enlighter-language="python" class="EnlighterJSRAW">generate()</code> consists of token IDs rather than human-readable text.</p>



<p>To convert those tokens back into natural language, we decode the generated sequence.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="139" data-enlighter-title="Running Gemma 4 Locally: Ollama, llama.cpp, MLX, and More" data-enlighter-group="50">// Final decoded output
const decoded = processor.batch_decode(
 outputs.slice(null, [inputs.input_ids.dims.at(-1), null]),
 { skip_special_tokens: true },
);

console.log(`\n${BOLD}── Final Output ──────────────────────────────────${RESET}`);
console.log(decoded[0]);
console.log(`${BOLD}──────────────────────────────────────────────────${RESET}\n`);
</pre>



<p>Here, we first remove the original prompt tokens, keeping only the newly generated portion of the sequence. We then call <code data-enlighter-language="python" class="EnlighterJSRAW">batch_decode()</code> to transform the token IDs into readable text while removing any special control tokens.</p>



<p>Finally, we print the generated response to the terminal.</p>



<p>At this point, Gemma 4 has successfully processed the text prompt, image, and audio inputs, producing a unified multimodal response, all from a single JavaScript application running locally through <code data-enlighter-language="python" class="EnlighterJSRAW">Transformers.js</code>.</p>



<h3 class="wp-block-heading">Output</h3>



<p>In your terminal, run <code data-enlighter-language="python" class="EnlighterJSRAW">node index.mjs</code> to run inference using Gemma 4 and <code data-enlighter-language="python" class="EnlighterJSRAW">Transformers.js</code>.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/07/image-63-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="732" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-63-1024x732.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54742"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-63-1024x732.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-63-1024x732.png?size=126x90&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-63-1024x732.png?size=252x180&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-63-1024x732.png?size=378x270&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-63-1024x732.png?size=504x360&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-63-1024x732.png?size=630x450&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 30:</strong> Running Inference using Gemma 4 and <code>Transformers.js</code> (source: author)</figcaption></figure></div>


<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Choosing-Right-Runtime-Running-Gemma-4-Locally"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Choosing-Right-Runtime-Running-Gemma-4-Locally">Choosing the Right Runtime for Running Gemma 4 Locally</a></h2>



<p>Throughout this lesson, we have explored five different ways to run Gemma 4 locally. While each runtime supports local inference, they target different workflows and use cases. The right choice depends on your goals, preferred development environment, and hardware.</p>



<h3 class="wp-block-heading">Choose Ollama if…</h3>



<p>Use <code data-enlighter-language="python" class="EnlighterJSRAW">Ollama</code> when you want the quickest way to get started with Gemma 4.</p>



<p>It is ideal for developers who:</p>



<ul class="wp-block-list">
<li>want a simple installation process</li>



<li>prefer a command-line interface with minimal configuration</li>



<li>need an OpenAI-compatible API for existing applications</li>



<li>want to experiment with local models in just a few commands</li>
</ul>



<p>For most developers getting started with local LLMs, <code data-enlighter-language="python" class="EnlighterJSRAW">Ollama</code> is the easiest recommendation.</p>



<h3 class="wp-block-heading">Choose llama.cpp if…</h3>



<p>Use <code data-enlighter-language="python" class="EnlighterJSRAW">llama.cpp</code> when you need maximum control and performance.</p>



<p>It is a good fit if you:</p>



<ul class="wp-block-list">
<li>want to work directly with <code data-enlighter-language="python" class="EnlighterJSRAW">GGUF</code> models</li>



<li>need fine-grained control over inference settings</li>



<li>plan to optimize CPU or GPU performance</li>



<li>want to build custom local inference pipelines</li>
</ul>



<p>Although it requires more setup than <code data-enlighter-language="python" class="EnlighterJSRAW">Ollama</code> or <code data-enlighter-language="python" class="EnlighterJSRAW">LM Studio</code>, <code data-enlighter-language="python" class="EnlighterJSRAW">llama.cpp</code> offers the greatest flexibility.</p>



<h3 class="wp-block-heading">Choose MLX if…</h3>



<p>Use <code data-enlighter-language="python" class="EnlighterJSRAW">MLX</code> if you are working on an Apple Silicon Mac.</p>



<p>It is particularly useful when you:</p>



<ul class="wp-block-list">
<li>own an M-series Mac</li>



<li>want native Apple Silicon performance</li>



<li>need efficient multimodal inference</li>



<li>prefer using an OpenAI-compatible local server</li>
</ul>



<p>For Apple users, <code data-enlighter-language="python" class="EnlighterJSRAW">MLX</code> typically provides the best performance with the least amount of configuration.</p>



<h3 class="wp-block-heading">Choose LM Studio if…</h3>



<p>Use <code data-enlighter-language="python" class="EnlighterJSRAW">LM Studio</code> when you prefer a graphical user interface over the command line.</p>



<p>It is well suited for users who:</p>



<ul class="wp-block-list">
<li>want to download and manage models visually</li>



<li>prefer chatting with models through a desktop application</li>



<li>need a local API server without compiling or configuring runtimes</li>



<li>are new to local AI and want the simplest desktop experience</li>
</ul>



<p><code data-enlighter-language="python" class="EnlighterJSRAW">LM Studio</code> is an excellent choice for beginners or anyone who prefers a GUI-based workflow.</p>



<h3 class="wp-block-heading">Choose Transformers.js if…</h3>



<p>Use <code data-enlighter-language="python" class="EnlighterJSRAW">Transformers.js</code> when you are building JavaScript applications.</p>



<p>It is the best option if you:</p>



<ul class="wp-block-list">
<li>develop with <code data-enlighter-language="python" class="EnlighterJSRAW">Node.js</code></li>



<li>want to perform inference without Python</li>



<li>need to integrate Gemma 4 directly into a JavaScript project</li>



<li>plan to eventually deploy models inside the browser</li>
</ul>



<p>Since <code data-enlighter-language="python" class="EnlighterJSRAW">Transformers.js</code> powers both <code data-enlighter-language="python" class="EnlighterJSRAW">Node.js</code> and browser-based inference, it provides a natural path from local development to fully client-side AI applications.</p>



<h3 class="wp-block-heading">At a Glance</h3>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/07/image-64.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="352" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-64-1024x352.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54743"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-64-1024x352.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-64-1024x352.png?size=126x43&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-64-1024x352.png?size=252x87&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-64-1024x352.png?size=378x130&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-64-1024x352.png?size=504x173&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-64-1024x352.png?size=630x217&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Table 1:</strong> Recommended Gemma 4 Runtime by Use Case (source: author)</figcaption></figure></div>


<p>Ultimately, there is no single &#8220;best&#8221; runtime. Each excels in different scenarios. If you are just getting started, <code data-enlighter-language="python" class="EnlighterJSRAW">Ollama</code> or <code data-enlighter-language="python" class="EnlighterJSRAW">LM Studio</code> are excellent entry points. If you need maximum flexibility, <code data-enlighter-language="python" class="EnlighterJSRAW">llama.cpp</code> is hard to beat. Apple Silicon users should strongly consider <code data-enlighter-language="python" class="EnlighterJSRAW">MLX</code>, while JavaScript developers will likely feel most at home with <code data-enlighter-language="python" class="EnlighterJSRAW">Transformers.js</code>.</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<div id="pitch" style="padding: 40px; width: 100%; background-color: #F4F6FA;">
	<h3>What's next? We recommend <a target="_blank" href="https://pyimagesearch.com/pyimagesearch-university/?utm_source=blogPost&utm_medium=bottomBanner&utm_campaign=What%27s%20next%3F%20I%20recommend">PyImageSearch University</a>.</h3>

	<script src="https://fast.wistia.com/embed/medias/kno0cmko2z.jsonp" async></script><script src="https://fast.wistia.com/assets/external/E-v1.js" async></script><div class="wistia_responsive_padding" style="padding:56.25% 0 0 0;position:relative;"><div class="wistia_responsive_wrapper" style="height:100%;left:0;position:absolute;top:0;width:100%;"><div class="wistia_embed wistia_async_kno0cmko2z videoFoam=true" style="height:100%;position:relative;width:100%"><div class="wistia_swatch" style="height:100%;left:0;opacity:0;overflow:hidden;position:absolute;top:0;transition:opacity 200ms;width:100%;"><img decoding="async" src="https://fast.wistia.com/embed/medias/kno0cmko2z/swatch" style="filter:blur(5px);height:100%;object-fit:contain;width:100%;" alt="" aria-hidden="true" onload="this.parentNode.style.opacity=1;" /></div></div></div></div>

	<div style="margin-top: 32px; margin-bottom: 32px; ">
		<strong>Course information:</strong><br/>
		120+ total classes • 115+ hours hours of on-demand code walkthrough videos • Last updated: August 2026<br/>
		<span style="color: #169FE6;">★★★★★</span> 4.84 (128 Ratings) • 16,000+ Students Enrolled
	</div>

	<p><strong>I strongly believe that if you had the right teacher you could <em>master</em> computer vision and deep learning.</strong></p>

	<p>Do you think learning computer vision and deep learning has to be time-consuming, overwhelming, and complicated? Or has to involve complex mathematics and equations? Or requires a degree in computer science?</p>

	<p>That’s <em>not</em> the case.</p>

	<p>All you need to master computer vision and deep learning is for someone to explain things to you in <em>simple, intuitive</em> terms. <em>And that’s exactly what I do</em>. My mission is to change education and how complex Artificial Intelligence topics are taught.</p>

	<p>If you're serious about learning computer vision, your next stop should be PyImageSearch University, the most comprehensive computer vision, deep learning, and OpenCV course online today. Here you’ll learn how to <em>successfully</em> and <em>confidently</em> apply computer vision to your work, research, and projects. Join me in computer vision mastery.</p>

	<p><strong>Inside PyImageSearch University you'll find:</strong></p>

	<ul style="margin-left: 0px;">
		<li style="list-style: none;">&check; <strong>120+ courses</strong> on essential computer vision, deep learning, and OpenCV topics</li>
		<li style="list-style: none;">&check; <strong>94+ Certificates</strong> of Completion</li>
		<li style="list-style: none;">&check; <strong>115+ hours hours</strong> of on-demand video</li>
		<li style="list-style: none;">&check; <strong>Brand new courses released <em>regularly</em></strong>, ensuring you can keep up with state-of-the-art techniques</li>
		<li style="list-style: none;">&check; <strong>Pre-configured Jupyter Notebooks in Google Colab</strong></li>
		<li style="list-style: none;">&check; Run all code examples in your web browser — works on Windows, macOS, and Linux (no dev environment configuration required!)</li>
		<li style="list-style: none;">&check; Access to <strong>centralized code repos for <em>all</em> 540+ tutorials</strong> on PyImageSearch</li>
		<li style="list-style: none;">&check; <strong> Easy one-click downloads</strong> for code, datasets, pre-trained models, etc.</li>
		<li style="list-style: none;">&check; <strong>Access</strong> on mobile, laptop, desktop, etc.</li>
	</ul>

	<p style="text-align: center;">
		<a target="_blank" class="button link" href="https://pyimagesearch.com/pyimagesearch-university/?utm_source=blogPost&utm_medium=bottomBanner&utm_campaign=What%27s%20next%3F%20I%20recommend" style="background-color: #6DC713; border-bottom: none;">Click here to join PyImageSearch University</a>
	</p>
</div>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Summary"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Summary">Summary</a></h2>



<p>In this lesson, we explored 5 ways to run Gemma 4 locally, each designed to support a different development workflow.</p>



<p>We started with <code data-enlighter-language="python" class="EnlighterJSRAW">Ollama</code>, the quickest way to download models, launch local inference, and expose an OpenAI-compatible API using just a few commands. We then moved to <code data-enlighter-language="python" class="EnlighterJSRAW">llama.cpp</code>, where we built the runtime from source, downloaded <code data-enlighter-language="python" class="EnlighterJSRAW">GGUF</code> models, enabled hardware acceleration, and launched both command-line and API-based inference.</p>



<p>Next, we explored <code data-enlighter-language="python" class="EnlighterJSRAW">MLX</code>, Apple&#8217;s machine learning framework for Apple Silicon, and used <code data-enlighter-language="python" class="EnlighterJSRAW">MLX-VLM</code> to perform multimodal inference while exposing an OpenAI-compatible server. We then looked at <code data-enlighter-language="python" class="EnlighterJSRAW">LM Studio</code>, which provides a user-friendly graphical interface for downloading, managing, and interacting with Gemma 4 without requiring any command-line configuration.</p>



<p>Finally, we stepped into the JavaScript ecosystem with <code data-enlighter-language="python" class="EnlighterJSRAW">Transformers.js</code>, demonstrating how to load an ONNX version of Gemma 4, process text, images, and audio, and perform multimodal inference entirely from a <code data-enlighter-language="python" class="EnlighterJSRAW">Node.js</code> application without relying on Python.</p>



<p>As we have seen throughout this lesson, there is no single &#8220;best&#8221; way to run Gemma 4. The ideal runtime depends on your workflow, hardware, and application requirements. <code data-enlighter-language="python" class="EnlighterJSRAW">Ollama</code> offers the fastest path to getting started, <code data-enlighter-language="python" class="EnlighterJSRAW">llama.cpp</code> delivers maximum flexibility and performance, <code data-enlighter-language="python" class="EnlighterJSRAW">MLX</code> is an excellent choice for Apple Silicon devices, <code data-enlighter-language="python" class="EnlighterJSRAW">LM Studio</code> provides an intuitive desktop experience, and <code data-enlighter-language="python" class="EnlighterJSRAW">Transformers.js</code> enables JavaScript developers to integrate Gemma 4 directly into their applications.</p>



<p>While all of these approaches run Gemma 4 locally, they still execute as traditional desktop or server-side applications. But what if we could eliminate even that requirement and run Gemma 4 entirely inside a web browser?</p>



<p>In the next lesson, we will build on the <code data-enlighter-language="python" class="EnlighterJSRAW">Transformers.js</code> foundation introduced here and take the next step by running Gemma 4 directly in the browser. We will learn how to load <code data-enlighter-language="python" class="EnlighterJSRAW">ONNX</code> models with <code data-enlighter-language="python" class="EnlighterJSRAW">Transformers.js</code>, leverage browser technologies such as <code data-enlighter-language="python" class="EnlighterJSRAW">WebGPU</code> and <code data-enlighter-language="python" class="EnlighterJSRAW">WebAssembly</code> for local inference, and build fully client-side multimodal AI applications that require no Python backend or dedicated inference server.</p>



<p>See you in the next lesson!</p>



<h3 class="wp-block-heading">Citation Information</h3>



<p><strong>Thakur, P</strong><strong>. </strong>“Running Gemma 4 Locally: Ollama, llama.cpp, MLX, and More,” <em>PyImageSearch</em>, S. Huot, G. Kudriavtsev,and A. Sharma, eds., 2026, <a href="https://pyimg.co/1rpad" target="_blank" rel="noreferrer noopener">https://pyimg.co/1rpad</a> </p>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="classic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="Running Gemma 4 Locally: Ollama, llama.cpp, MLX, and More" data-enlighter-group="51">@incollection{Thakur_2026_running-gemma-4-locally-ollama-llama-cpp-mlx,
  author = {Piyush Thakur},
  title = {{Running Gemma 4 Locally: Ollama, llama.cpp, MLX, and More}},
  booktitle = {PyImageSearch},
  editor = {Susan Huot and Georgii Kudriavtsev and Aditya Sharma},
  year = {2026},
  url = {https://pyimg.co/1rpad},
}
</pre>



<p><strong>To download the source code to this post (and be notified when future tutorials are published here on PyImageSearch), </strong><em><strong>simply enter your email address in the form below!</strong></em></p>



<div id="download-the-code" class="post-cta-wrap">
<div class="gpd-post-cta">
	<div class="gpd-post-cta-content">
		

			<div class="gpd-post-cta-top">
				<div class="gpd-post-cta-top-image"><img decoding="async" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2020/01/cta-source-guide-1.png?lossy=2&strip=1&webp=1" alt="" srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2020/01/cta-source-guide-1.png?lossy=2&strip=1&webp=1 410w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2020/01/cta-source-guide-1.png?size=126x174&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2020/01/cta-source-guide-1.png?size=252x348&lossy=2&strip=1&webp=1 252w" sizes="(max-width: 410px) 100vw, 410px" /></div>
				
				<div class="gpd-post-cta-top-title"><h4>Download the Source Code and FREE 17-page Resource Guide</h4></div>
				<div class="gpd-post-cta-top-desc"><p>Enter your email address below to get a .zip of the code and a <strong>FREE 17-page Resource Guide on Computer Vision, OpenCV, and Deep Learning.</strong> Inside you'll find my hand-picked tutorials, books, courses, and libraries to help you master CV and DL!</p></div>


			</div>

			<div class="gpd-post-cta-bottom">
				<form id="footer-cta-code" class="footer-cta" action="https://www.getdrip.com/forms/4130035/submissions" method="post" target="blank" data-drip-embedded-form="4130035">
					<input name="fields[email]" type="email" value="" placeholder="Your email address" class="form-control" />

					<button type="submit">Download the code!</button>

					<div style="display: none;" aria-hidden="true"><label for="website">Website</label><br /><input type="text" id="website" name="website" tabindex="-1" autocomplete="false" value="" /></div>
				</form>
			</div>


		
	</div>

</div>
</div>
<p>The post <a rel="nofollow" href="https://pyimagesearch.com/2026/07/20/running-gemma-4-locally-ollama-llama-cpp-mlx-and-more/">Running Gemma 4 Locally: Ollama, llama.cpp, MLX, and More</a> appeared first on <a rel="nofollow" href="https://pyimagesearch.com">PyImageSearch</a>.</p>
]]></content:encoded>
					
		
		<enclosure url="https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav" length="1015" type="audio/wav" />

			</item>
		<item>
		<title>Building Multimodal AI Applications with Gemma 4 and Transformers</title>
		<link>https://pyimagesearch.com/2026/07/12/building-multimodal-ai-applications-with-gemma-4-and-transformers/</link>
		
		<dc:creator><![CDATA[Piyush Thakur]]></dc:creator>
		<pubDate>Sun, 12 Jul 2026 17:23:23 +0000</pubDate>
				<category><![CDATA[AI & Deep Learning]]></category>
		<category><![CDATA[Computer Vision]]></category>
		<category><![CDATA[Generative AI]]></category>
		<category><![CDATA[Large Language Models]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[audio understanding]]></category>
		<category><![CDATA[computer vision]]></category>
		<category><![CDATA[function calling]]></category>
		<category><![CDATA[gemma 4]]></category>
		<category><![CDATA[generative ai]]></category>
		<category><![CDATA[google deepmind]]></category>
		<category><![CDATA[hugging face]]></category>
		<category><![CDATA[image captioning]]></category>
		<category><![CDATA[multimodal ai]]></category>
		<category><![CDATA[multimodal applications]]></category>
		<category><![CDATA[multimodal inference]]></category>
		<category><![CDATA[multimodal llm]]></category>
		<category><![CDATA[object detection]]></category>
		<category><![CDATA[screenshot to code]]></category>
		<category><![CDATA[transformers]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[video understanding]]></category>
		<category><![CDATA[vision language model]]></category>
		<category><![CDATA[vlm]]></category>
		<guid isPermaLink="false">https://pyimagesearch.com/?p=54522</guid>

					<description><![CDATA[<p>Table of Contents Building Multimodal AI Applications with Gemma 4 and Transformers Configuring Your Development Environment Installing Python Dependencies and Importing Gemma 4 Multimodal Libraries Loading the Gemma 4 Multimodal Model with Hugging Face Transformers Screenshot-to-Code Generation with Gemma 4&#8230;</p>
<p>The post <a rel="nofollow" href="https://pyimagesearch.com/2026/07/12/building-multimodal-ai-applications-with-gemma-4-and-transformers/">Building Multimodal AI Applications with Gemma 4 and Transformers</a> appeared first on <a rel="nofollow" href="https://pyimagesearch.com">PyImageSearch</a>.</p>
]]></description>
										<content:encoded><![CDATA[<div class="yoast-breadcrumbs"><span><span><a href="https://pyimagesearch.com/">Home</a></span></div>


<script src="https://fast.wistia.com/embed/medias/u9zvmlmsf9.jsonp" async></script><script src="https://fast.wistia.com/assets/external/E-v1.js" async></script><div class="wistia_responsive_padding" style="padding:56.25% 0 0 0;position:relative;"><div class="wistia_responsive_wrapper" style="height:100%;left:0;position:absolute;top:0;width:100%;"><div class="wistia_embed wistia_async_u9zvmlmsf9 seo=true videoFoam=true" style="height:100%;position:relative;width:100%"><div class="wistia_swatch" style="height:100%;left:0;opacity:0;overflow:hidden;position:absolute;top:0;transition:opacity 200ms;width:100%;"><img decoding="async" src="https://fast.wistia.com/embed/medias/u9zvmlmsf9/swatch" style="filter:blur(5px);height:100%;object-fit:contain;width:100%;" alt="" aria-hidden="true" onload="this.parentNode.style.opacity=1;" /></div></div></div></div>



<div class="toc">
<hr class="TOC"/>
<p class="has-large-font-size"><strong>Table of Contents</strong></p>
<ul>
    <li id="TOC-h1-Building-Multimodal-AI-Applications-Gemma-4-Transformers"><a rel="noopener" target="_blank" href="#h1-Building-Multimodal-AI-Applications-Gemma-4-Transformers">Building Multimodal AI Applications with Gemma 4 and Transformers</a></li>

    <li id="TOC-h2-Configuring-Development-Environment"><a rel="noopener" target="_blank" href="#h2-Configuring-Development-Environment">Configuring Your Development Environment</a></li>

    <li id="TOC-h2-Installing-Python-Dependencies-Importing-Gemma-4-Multimodal-Libraries"><a rel="noopener" target="_blank" href="#h2-Installing-Python-Dependencies-Importing-Gemma-4-Multimodal-Libraries">Installing Python Dependencies and Importing Gemma 4 Multimodal Libraries</a></li>

    <li id="TOC-h2-Loading-Gemma-4-Multimodal-Model-Hugging-Face-Transformers"><a rel="noopener" target="_blank" href="#h2-Loading-Gemma-4-Multimodal-Model-Hugging-Face-Transformers">Loading the Gemma 4 Multimodal Model with Hugging Face Transformers</a></li>

    <li id="TOC-h2-Screenshot-to-Code-Generation-Gemma-4-Vision-Language-AI"><a rel="noopener" target="_blank" href="#h2-Screenshot-to-Code-Generation-Gemma-4-Vision-Language-AI">Screenshot-to-Code Generation with Gemma 4 Vision-Language AI</a></li>

    <li id="TOC-h2-Video-Understanding-Multimodal-Reasoning-Gemma-4"><a rel="noopener" target="_blank" href="#h2-Video-Understanding-Multimodal-Reasoning-Gemma-4">Video Understanding and Multimodal Reasoning with Gemma 4</a></li>

    <li id="TOC-h2-Multimodal-Function-Calling-Gemma-4"><a rel="noopener" target="_blank" href="#h2-Multimodal-Function-Calling-Gemma-4">Multimodal Function Calling with Gemma 4</a></li>

    <li id="TOC-h2-Object-Detection-Visual-Grounding-Gemma-4"><a rel="noopener" target="_blank" href="#h2-Object-Detection-Visual-Grounding-Gemma-4">Object Detection and Visual Grounding with Gemma 4</a></li>

    <li id="TOC-h2-Image-Captioning-Gemma-4-Vision-Language-Models"><a rel="noopener" target="_blank" href="#h2-Image-Captioning-Gemma-4-Vision-Language-Models">Image Captioning with Gemma 4 Vision-Language Models</a></li>

    <li id="TOC-h2-Audio-Understanding-Gemma-4"><a rel="noopener" target="_blank" href="#h2-Audio-Understanding-Gemma-4">Audio Understanding with Gemma 4</a></li>

    <li id="TOC-h2-Summary"><a rel="noopener" target="_blank" href="#h2-Summary">Summary</a></li>
    <ul>
        <li id="TOC-h3-Citation-Information"><a rel="noopener" target="_blank" href="#h3-Citation-Information">Citation Information</a></li>
    </ul>
</ul>
</div>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h1-Building-Multimodal-AI-Applications-Gemma-4-Transformers"/>



<h2 class="wp-block-heading"><a href="#TOC-h1-Building-Multimodal-AI-Applications-Gemma-4-Transformers">Building Multimodal AI Applications with Gemma 4 and Transformers</a></h2>



<p>In the first part of this series, we explored the architecture behind Gemma 4: the interleaved attention design, Mixture-of-Experts routing, multimodal encoders, Per-Layer Embeddings, and the engineering decisions that allow the model family to scale from smartphones to large GPU servers. We also looked at the different variants, hardware requirements, benchmarks, and the reasoning capabilities that make Gemma 4 one of the most compelling open-weight model releases today.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://pyimagesearch.com/wp-content/uploads/2026/07/build-multimodal-ai-apps-w-gemma-4-transformers-featured-v2.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="940" height="780" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/build-multimodal-ai-apps-w-gemma-4-transformers-featured-v2.png?lossy=2&strip=1&webp=1" alt="build-multimodal-ai-apps-w-gemma-4-transformers-featured-v2.png" class="wp-image-54547"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/build-multimodal-ai-apps-w-gemma-4-transformers-featured-v2.png?size=126x105&lossy=2&strip=1&webp=1 126w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/build-multimodal-ai-apps-w-gemma-4-transformers-featured-v2-300x249.png?lossy=2&strip=1&webp=1 300w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/build-multimodal-ai-apps-w-gemma-4-transformers-featured-v2.png?size=378x314&lossy=2&strip=1&webp=1 378w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/build-multimodal-ai-apps-w-gemma-4-transformers-featured-v2.png?size=504x418&lossy=2&strip=1&webp=1 504w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/build-multimodal-ai-apps-w-gemma-4-transformers-featured-v2.png?size=630x523&lossy=2&strip=1&webp=1 630w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/build-multimodal-ai-apps-w-gemma-4-transformers-featured-v2-768x637.png?lossy=2&strip=1&webp=1 768w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/build-multimodal-ai-apps-w-gemma-4-transformers-featured-v2.png?lossy=2&strip=1&webp=1 940w" sizes="(max-width: 940px) 100vw, 940px" /></a></figure></div>


<p>But architecture alone does not tell the full story.</p>



<p>The real question for most developers is simple: how do we actually use Gemma 4 in practice?</p>



<p>That is what this second part focuses on. Instead of discussing theory, we will build directly with the model using <a href="https://github.com/huggingface/transformers" target="_blank" rel="noreferrer noopener">Hugging Face Transformers</a>. We will see how Gemma 4 handles images, videos, audio, structured tool calling, object detection, screenshot-to-code generation, and multimodal reasoning, all from a single unified interface.</p>



<p>One of the most interesting things about Gemma 4 is that the workflow stays surprisingly consistent across tasks. Whether we are passing a webpage screenshot, an audio clip, or a video file, the overall pipeline barely changes:</p>



<ul class="wp-block-list">
<li>Define the multimodal message.</li>



<li>Process it using the Gemma processor.</li>



<li>Generate outputs from the model.</li>



<li>Decode and parse the response.</li>
</ul>



<p>Once this pattern becomes familiar, building multimodal applications starts feeling much more approachable.</p>



<p>In this lesson, we will go section by section through the notebook and explain not just <em>what</em> the code is doing, but <em>why </em>each step matters. Along the way, we will also connect the implementation back to the architectural ideas from Part 1, showing how concepts (e.g., multimodal encoders, thinking mode, and structured outputs) appear in real inference pipelines.</p>



<p>This lesson is the 2nd in a 5-part series on <strong>Google DeepMind’s Gemma 4</strong>:</p>



<ol class="wp-block-list">
<li><em><strong><a href="https://pyimg.co/uqxzw" target="_blank" rel="noreferrer noopener">Google DeepMind’s Gemma 4: MoE, Efficiency Tricks, and Benchmarks</a></strong></em> </li>



<li><em><strong><a href="https://pyimg.co/09dks" target="_blank" rel="noreferrer noopener">Building Multimodal AI Applications with Gemma 4 and Transformers</a></strong></em> <strong>(this tutorial)</strong></li>



<li><em>Lesson 3</em></li>



<li><em>Lesson 4</em></li>



<li><em>Lesson 5</em></li>
</ol>



<p><strong>To learn how to </strong><strong>build multimodal applications with Gemma 4</strong><strong>, </strong><em><strong>just keep reading.</strong></em></p>



<div id="pyi-source-code-block" class="source-code-wrap"><div class="gpd-source-code">
    <div class="gpd-source-code-content">
        <img decoding="async" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2020/01/source-code-icon.png?lossy=2&strip=1&webp=1" alt="">
        <h4>Looking for the source code to this post?</h4>
                    <a href="#download-the-code" class="pyis-cta-modal-open-modal">Jump Right To The Downloads Section <svg class="svg-icon arrow-right" width="12" height="12" aria-hidden="true" role="img" focusable="false" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M6.8125 0.1875C6.875 0.125 6.96875 0.09375 7.09375 0.09375C7.1875 0.09375 7.28125 0.125 7.34375 0.1875L13.875 6.75C13.9375 6.8125 14 6.90625 14 7C14 7.125 13.9375 7.1875 13.875 7.25L7.34375 13.8125C7.28125 13.875 7.1875 13.9062 7.09375 13.9062C6.96875 13.9062 6.875 13.875 6.8125 13.8125L6.1875 13.1875C6.125 13.125 6.09375 13.0625 6.09375 12.9375C6.09375 12.8438 6.125 12.75 6.1875 12.6562L11.0312 7.8125H0.375C0.25 7.8125 0.15625 7.78125 0.09375 7.71875C0.03125 7.65625 0 7.5625 0 7.4375V6.5625C0 6.46875 0.03125 6.375 0.09375 6.3125C0.15625 6.25 0.25 6.1875 0.375 6.1875H11.0312L6.1875 1.34375C6.125 1.28125 6.09375 1.1875 6.09375 1.0625C6.09375 0.96875 6.125 0.875 6.1875 0.8125L6.8125 0.1875Z" fill="#169FE6"></path></svg></a>
            </div>
</div>
</div>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p>Would you like immediate access to 3,457 images curated and labeled with hand gestures to train, explore, and experiment with &#8230; for free? Head over to <a href="https://universe.roboflow.com/isl/az-6mqow?ref=pyimagesearch" target="_blank" rel="noreferrer noopener">Roboflow</a> and get a free account to grab these hand gesture images. </p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Configuring-Development-Environment"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Configuring-Development-Environment">Configuring Your Development Environment</a></h2>



<p>To follow this guide, you need to have the following libraries installed on your system.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Building Multimodal AI Applications with Gemma 4 and Transformers" data-enlighter-group="1">!pip install -q -U transformers
</pre>



<p>This command installs the latest version of the <code data-enlighter-language="python" class="EnlighterJSRAW">transformers</code> library.</p>



<p>Here:</p>



<ul class="wp-block-list">
<li><code data-enlighter-language="python" class="EnlighterJSRAW">-U</code> upgrades the package to the newest available version</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">-q</code> enables quiet mode to reduce unnecessary installation logs</li>
</ul>



<p>Using the latest version is important because Gemma 4 support, multimodal processors, and newer generation features are included in recent releases of the library.</p>



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">transformers</code> package gives us access to:</p>



<ul class="wp-block-list">
<li>Pretrained Gemma 4 checkpoints</li>



<li>Multimodal processors</li>



<li>Tokenization utilities</li>



<li>Chat templates</li>



<li>Text generation APIs</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<!-- wp:paragraph -->
<h3>Need Help Configuring Your Development Environment?</h3>
<!-- /wp:paragraph -->

<!-- wp:image {"align":"center","id":18137,"sizeSlug":"large","linkDestination":"custom"} -->
<figure class="wp-block-image aligncenter size-large"><a href="https://pyimagesearch.com/pyimagesearch-university/" target="_blank" rel="noreferrer noopener"><img decoding="async" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2021/01/pyimagesearch_plus_jupyter.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-18137" srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2021/01/pyimagesearch_plus_jupyter.png?lossy=2&strip=1&webp=1 500w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2021/01/pyimagesearch_plus_jupyter.png?size=126x84&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2021/01/pyimagesearch_plus_jupyter.png?size=252x168&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2021/01/pyimagesearch_plus_jupyter.png?size=378x253&lossy=2&strip=1&webp=1 378w" sizes="(max-width: 500px) 100vw, 500px" /></a><figcaption>Having trouble configuring your development environment? Want access to pre-configured Jupyter Notebooks running on Google Colab? Be sure to join <a href="https://pyimagesearch.com/pyimagesearch-university/" target="_blank" rel="noreferrer noopener" aria-label=" (opens in a new tab)">PyImageSearch University</a> — you will be up and running with this tutorial in a matter of minutes. </figcaption></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>All that said, are you:</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li>Short on time?</li><li>Learning on your employer’s administratively locked system?</li><li>Wanting to skip the hassle of fighting with the command line, package managers, and virtual environments?</li><li><strong>Ready to run the code immediately on your Windows, macOS, or Linux system?</strong></li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>Then join <a href="https://pyimagesearch.com/pyimagesearch-university/" target="_blank">PyImageSearch University</a> today!</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><strong>Gain access to Jupyter Notebooks for this tutorial and other PyImageSearch guides pre-configured to run on Google Colab’s ecosystem right in your web browser!</strong> No installation required.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>And best of all, these Jupyter Notebooks will run on Windows, macOS, and Linux!</p>
<!-- /wp:paragraph -->



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Installing-Python-Dependencies-Importing-Gemma-4-Multimodal-Libraries"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Installing-Python-Dependencies-Importing-Gemma-4-Multimodal-Libraries">Installing Python Dependencies and Importing Gemma 4 Multimodal Libraries</a></h2>



<p>After configuring the environment, the next step is importing all the required libraries. These imports provide everything needed for loading Gemma 4, processing multimodal inputs, generating outputs, and visualizing results.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Building Multimodal AI Applications with Gemma 4 and Transformers" data-enlighter-group="3">import re
import json
import torch
import matplotlib.pyplot as plt
import matplotlib.patches as patches

from PIL import Image
from transformers.image_utils import load_image
from transformers import AutoModelForMultimodalLM, AutoProcessor
</pre>



<p>We first import Python’s built-in <code data-enlighter-language="python" class="EnlighterJSRAW">re</code> and <code data-enlighter-language="python" class="EnlighterJSRAW">json</code> libraries. The <code data-enlighter-language="python" class="EnlighterJSRAW">re</code> library is used for regular expression operations. Later in the lesson, we use it while parsing structured outputs such as bounding box predictions returned by the model.</p>



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">json</code> library helps us work with JSON responses generated by Gemma 4. This becomes especially useful for tasks (e.g., object detection and function calling), where the model produces structured outputs instead of plain text.</p>



<p>Next, we import <code data-enlighter-language="python" class="EnlighterJSRAW">PyTorch</code>. <code data-enlighter-language="python" class="EnlighterJSRAW">PyTorch</code> is the deep learning framework powering the model inference pipeline. Hugging Face Transformers internally relies on PyTorch tensors for:</p>



<ul class="wp-block-list">
<li>Token representations</li>



<li>Model weights</li>



<li>GPU computation</li>



<li>Generation operations</li>
</ul>



<p>Almost every operation inside Gemma 4 inference eventually runs through PyTorch.</p>



<p>We then import <code data-enlighter-language="python" class="EnlighterJSRAW">Matplotlib</code> utilities. These libraries are used for visualization. In the object detection section later in the lesson, we will draw predicted bounding boxes on images using rectangle patches.</p>



<p>Next, we import <code data-enlighter-language="python" class="EnlighterJSRAW">PIL</code>. <code data-enlighter-language="python" class="EnlighterJSRAW">PIL</code> (Python Imaging Library) is widely used for image loading and manipulation in Python applications. It helps us work with image files before sending them into the model.</p>



<p>We also import <code data-enlighter-language="python" class="EnlighterJSRAW">load_image</code>. This utility simplifies image loading directly from URLs or local paths. Instead of manually downloading and preprocessing images, we can load them with a single function call.</p>



<p>Finally, we import the 2 most important components from Transformers.</p>



<p><code data-enlighter-language="python" class="EnlighterJSRAW">AutoModelForMultimodalLM</code> loads the Gemma 4 multimodal model itself. Since Gemma 4 can process text, images, video, and audio, we use the multimodal model interface instead of a text-only causal language model.</p>



<p><code data-enlighter-language="python" class="EnlighterJSRAW">AutoProcessor</code> handles preprocessing for all supported modalities. It prepares:</p>



<ul class="wp-block-list">
<li>Text tokens</li>



<li>Image embeddings</li>



<li>Audio features</li>



<li>Video inputs</li>



<li>Chat templates</li>
</ul>



<p>into the format expected by Gemma 4.</p>



<p>Together, these imports form the foundation for the rest of the lesson. Once these libraries are loaded, we are ready to initialize the model and begin multimodal inference.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Loading-Gemma-4-Multimodal-Model-Hugging-Face-Transformers"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Loading-Gemma-4-Multimodal-Model-Hugging-Face-Transformers">Loading the Gemma 4 Multimodal Model with Hugging Face Transformers</a></h2>



<p>Now that the environment and dependencies are ready, we can load the Gemma 4 model and its processor.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Building Multimodal AI Applications with Gemma 4 and Transformers" data-enlighter-group="5">model_id = "google/gemma-4-E2B-it"
model = AutoModelForMultimodalLM.from_pretrained(model_id, device_map="auto")
processor = AutoProcessor.from_pretrained(model_id)
</pre>



<p>We first define the model checkpoint: <code data-enlighter-language="python" class="EnlighterJSRAW">google/gemma-4-E2B-it</code>.</p>



<p>Here, we are using the instruction-tuned <code data-enlighter-language="python" class="EnlighterJSRAW">Gemma-4-E2B-it</code> variant. The <code data-enlighter-language="python" class="EnlighterJSRAW">it</code> suffix stands for <em>instruction tuned</em>, meaning the model has been optimized for conversational and task-following behavior.</p>



<p>The Gemma 4 <code data-enlighter-language="python" class="EnlighterJSRAW">E2B</code> model is also one of the smaller Gemma 4 variants, making it practical for experimentation and multimodal inference without requiring extremely large GPU memory. As discussed in the first part of this series, the E-series models are specifically designed for efficient deployment while still supporting text, image, video, and audio understanding. </p>



<p>Next, we load the model itself. The <code data-enlighter-language="python" class="EnlighterJSRAW">from_pretrained()</code> method downloads the pretrained weights directly from Hugging Face and initializes the model architecture automatically. </p>



<p>The important argument here is: <code data-enlighter-language="python" class="EnlighterJSRAW">device_map="auto"</code>. This tells Transformers to automatically decide where the model should be loaded:</p>



<ul class="wp-block-list">
<li>GPU if CUDA is available</li>



<li>CPU otherwise</li>
</ul>



<p>For larger models, this can also distribute layers across multiple GPUs automatically. In our case, it simplifies deployment because we do not need to manually move tensors or model weights between devices.</p>



<p>Finally, we load the processor. The processor is responsible for preparing multimodal inputs before they are passed into Gemma 4.</p>



<p>This includes:</p>



<ul class="wp-block-list">
<li>Tokenizing text</li>



<li>Processing images</li>



<li>Handling audio inputs</li>



<li>Formatting video data</li>



<li>Applying the correct chat template</li>
</ul>



<p>One of the biggest advantages of the processor API is consistency. Whether we send text, images, video, or audio into the model, the processor converts everything into the exact format expected by Gemma 4 internally.</p>



<p>At this point, both the model and processor are fully initialized, and we are ready to begin multimodal inference tasks.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Screenshot-to-Code-Generation-Gemma-4-Vision-Language-AI"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Screenshot-to-Code-Generation-Gemma-4-Vision-Language-AI">Screenshot-to-Code Generation with Gemma 4 Vision-Language AI</a></h2>



<p>One of the most impressive capabilities of Gemma 4 is multimodal code generation. Instead of giving the model only text prompts, we can provide an image of a webpage and ask it to generate the corresponding HTML code. </p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/07/image-7-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="621" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-7-1024x621.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54551"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-7-1024x621.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-7-1024x621.png?size=126x76&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-7-1024x621.png?size=252x153&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-7-1024x621.png?size=378x229&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-7-1024x621.png?size=504x306&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-7-1024x621.png?size=630x382&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 1:</strong> Website Screenshot (source: <a href="https://zerda.academy/en/blog/landing-page-a-powerful-tool-in-marketing/" target="_blank" rel="noreferrer noopener">Internet</a>)</figcaption></figure></div>


<p>We begin by defining the multimodal conversation input:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Building Multimodal AI Applications with Gemma 4 and Transformers" data-enlighter-group="7">messages = [
   {
       "role": "user",
       "content": [
           {
               "type": "image",
               "image": "https://github.com/PyImageSearch/assets/blob/main/images/landing-page-1.png?raw=true",
           },
           {"type": "text", "text": "Write HTML code for this page."},
       ],
   }
]
</pre>



<p>Here, the input follows a chat-style structure. Each message contains:</p>



<ul class="wp-block-list">
<li>A <code data-enlighter-language="python" class="EnlighterJSRAW">role</code></li>



<li>A <code data-enlighter-language="python" class="EnlighterJSRAW">content</code> field</li>
</ul>



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">content</code> itself is a list because Gemma 4 supports multiple modalities within the same conversation turn.</p>



<p>The first content item is the webpage screenshot. This tells the processor that the input modality is an image. Instead of manually downloading and preprocessing the image ourselves, we simply provide the URL.</p>



<p>The second content item is the text instruction. This prompt guides the model toward the task we want it to perform.</p>



<p>Together, the image and text become a unified multimodal input. Gemma 4 processes both inputs simultaneously, allowing it to reason about the webpage layout visually while generating HTML code as output.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Building Multimodal AI Applications with Gemma 4 and Transformers" data-enlighter-group="9">inputs = processor.apply_chat_template(
   messages,
   tokenize=True,
   return_dict=True,
   return_tensors="pt",
   add_generation_prompt=True,
   enable_thinking=True,
).to(model.device)
</pre>



<p>Next, we prepare the inputs using the processor. This is one of the most important steps in the entire workflow.</p>



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">apply_chat_template()</code> function converts the multimodal conversation into the exact format expected by Gemma 4 internally.</p>



<p>Let us break down the major arguments.</p>



<ul class="wp-block-list">
<li><code data-enlighter-language="python" class="EnlighterJSRAW">tokenize=True</code>: converts the processed input into tokens that the model can understand</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">return_tensors="pt"</code>: tells the processor to return PyTorch tensors instead of Python lists</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">return_dict=True</code>: returns a structured dictionary containing all required tensors instead of returning only token IDs</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">add_generation_prompt=True</code>: appends the assistant generation marker so the model knows it should begin generating a response</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">enable_thinking=True</code>: activates Gemma 4’s thinking mode. As discussed in Part 1, thinking mode encourages the model to internally reason through the problem before producing the final answer.</li>
</ul>



<p>Finally, we move all tensors onto the same device as the model. This ensures inference runs correctly on either CPU or GPU.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Building Multimodal AI Applications with Gemma 4 and Transformers" data-enlighter-group="11">output = model.generate(**inputs, max_new_tokens=4000)
</pre>



<p>Once the inputs are ready, we generate the output. The <code data-enlighter-language="python" class="EnlighterJSRAW">generate()</code> function performs autoregressive decoding and produces the model response token by token. <code data-enlighter-language="python" class="EnlighterJSRAW">max_new_tokens=4000</code> sets the maximum generation length. Since HTML generation can produce large outputs, we allow a relatively high token budget.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Building Multimodal AI Applications with Gemma 4 and Transformers" data-enlighter-group="13">input_len = inputs.input_ids.shape[-1]
generated_text_ids = output[0][input_len:]
generated_text = processor.decode(generated_text_ids, skip_special_tokens=True)
</pre>



<p>Next, we extract only the generated portion of the response. This step is necessary because the generated output contains:</p>



<ul class="wp-block-list">
<li>The original input tokens</li>



<li>The newly generated tokens</li>
</ul>



<p>We remove the input portion and keep only the generated response. We then decode the generated token IDs back into readable text. The <code data-enlighter-language="python" class="EnlighterJSRAW">skip_special_tokens=True</code> argument removes internal formatting tokens that are not useful for display.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Building Multimodal AI Applications with Gemma 4 and Transformers" data-enlighter-group="15">result = processor.parse_response(generated_text)

print(result["content"])
</pre>



<p>Next, we parse the model response. This converts the raw generated text into a cleaner structured format. Finally, we print the generated HTML output.</p>



<p><strong>Output</strong></p>



<p>At this stage, Gemma 4 produces HTML code that attempts to recreate the webpage shown in the screenshot.</p>



<p>This example demonstrates one of the most exciting aspects of multimodal language models: the ability to translate visual layouts directly into working code. Instead of treating images and programming as separate domains, Gemma 4 combines visual understanding and code generation into a single inference pipeline.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Building Multimodal AI Applications with Gemma 4 and Transformers" data-enlighter-group="17">thought
Here's a thinking process that leads to the suggested HTML code:
1.  **Analyze the Request:** The user wants HTML code for the provided image (a website screenshot/design).
2.  **Deconstruct the Image (Identify Key Components &amp; Structure):**
    *   **Header/Navigation Bar:**
        *   Logo: "YOURLOGO" (Top left).
        *   Navigation Links: "Home," "Company," "Services," "Contact."
        *   Icon: Search/Magnifying glass (Top right).
    *   **Hero Section/Main Content Area:**
        *   *Visual Element (Left/Center):* A stylized illustration of a woman celebrating, surrounded by stars, planets, and dots.
        *   *Text/Headline (Right):*
            *   Headline: "Creative Ideas" (Large, orange/bold).
            *   Subheadline/Tagline: "A Studio based in New York, US."
            *   Body Text: "Solutions of design in modern era, consectetur adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat." (Placeholder text).
        *   *Call to Action (CTA):* A button labeled "SUBSCRIBE" (Dark/Maroon).
        *   *Social Media Icons:* Facebook, Instagram, Twitter (Small icons below the CTA).
...
...
</pre>



<p>We can see that Gemma 4 not only understands the webpage visually, but also reasons through its structure before generating the final code. The model identifies components such as the navigation bar, hero section, buttons, and social icons, and then converts them into structured HTML and CSS.</p>



<p>Interestingly, the output also includes responsive styling, layout organization, practical implementation notes, and even a dedicated section explaining how to use the generated code. We followed the same instructions provided by Gemma 4 to run the generated HTML and CSS files, and the resulting webpage closely matched the original design shown in the input image.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/07/image-8-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="576" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-8-1024x576.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54554"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-8-1024x576.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-8-1024x576.png?size=126x71&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-8-1024x576.png?size=252x142&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-8-1024x576.png?size=378x213&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-8-1024x576.png?size=504x284&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-8-1024x576.png?size=630x354&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 2:</strong> Generated landing page from the code (source: author)</figcaption></figure></div>


<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Video-Understanding-Multimodal-Reasoning-Gemma-4"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Video-Understanding-Multimodal-Reasoning-Gemma-4">Video Understanding and Multimodal Reasoning with Gemma 4</a></h2>



<p>After testing image understanding and code generation, we can move one step further and evaluate Gemma 4 on video reasoning tasks.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Building Multimodal AI Applications with Gemma 4 and Transformers" data-enlighter-group="19">messages = [
   {
       "role": "user",
       "content": [
           {"type": "video", "url": "https://huggingface.co/datasets/merve/vlm_test_images/resolve/main/concert.mp4"},
           {"type": "text", "text": "What is happening in the video? What is the song about?"},
       ],
   },
]
</pre>



<p>Here, instead of providing an image, we provide a video file as input.</p>



<p>The first content block defines the video source. This tells the processor that the input modality is a video rather than an image or audio clip.</p>



<p>The second content block contains the text instruction. This prompt asks the model to reason about:</p>



<ul class="wp-block-list">
<li>The visual scene</li>



<li>The event taking place</li>



<li>The semantic meaning of the song</li>
</ul>



<p>This is important because the model is not simply captioning individual frames. It is performing multimodal reasoning across both temporal and audio information.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Building Multimodal AI Applications with Gemma 4 and Transformers" data-enlighter-group="21">inputs = processor.apply_chat_template(
   messages,
   tokenize=True,
   return_dict=True,
   return_tensors="pt",
   add_generation_prompt=True,
   load_audio_from_video=True,
).to(model.device)
</pre>



<p>Next, we process the multimodal input. Most of the arguments are similar to the previous example, but there is one important addition here: </p>



<ul class="wp-block-list">
<li><code data-enlighter-language="python" class="EnlighterJSRAW">load_audio_from_video=True</code> flag tells the processor to extract the audio stream from the video alongside the visual frames.</li>
</ul>



<p>As discussed in the first part of this series, the smaller Gemma 4 E-series models support audio understanding in addition to image and text reasoning. </p>



<p>This means the model can jointly analyze:</p>



<ul class="wp-block-list">
<li>Video frames</li>



<li>Speech</li>



<li>Music</li>



<li>Ambient sounds</li>
</ul>



<p>instead of relying only on visual information.</p>



<p>In practice, this allows Gemma 4 to answer richer questions about videos, such as:</p>



<ul class="wp-block-list">
<li>Understanding spoken dialogue</li>



<li>Identifying music genres</li>



<li>Inferring emotional tone</li>



<li>Explaining events happening in the scene</li>
</ul>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Building Multimodal AI Applications with Gemma 4 and Transformers" data-enlighter-group="23">output = model.generate(**inputs, max_new_tokens=200)
</pre>



<p>Once the inputs are prepared, we generate the output. Here, <code data-enlighter-language="python" class="EnlighterJSRAW">max_new_tokens=200</code> limits the response length. Since video descriptions are usually shorter than HTML generation tasks, a smaller token budget is sufficient.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Building Multimodal AI Applications with Gemma 4 and Transformers" data-enlighter-group="25">input_len = inputs.input_ids.shape[-1]
generated_text_ids = output[0][input_len:]
generated_text = processor.decode(generated_text_ids, skip_special_tokens=True)
result = processor.parse_response(generated_text)
</pre>



<p>After generation, we extract only the generated portion of the sequence. Just as before, this removes the original input tokens and keeps only the newly generated response.</p>



<p>Next, we decode the generated tokens back into readable text. We then parse the response into a cleaner structure. </p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Building Multimodal AI Applications with Gemma 4 and Transformers" data-enlighter-group="27">print(result["content"])
</pre>



<p>Finally, we print the generated output.</p>



<p><strong>Output</strong></p>



<p>At this stage, Gemma 4 analyzes the concert video and produces a multimodal interpretation of the scene.</p>



<p>This example highlights an important capability of Gemma 4: unified video understanding. Instead of requiring separate models for:</p>



<ul class="wp-block-list">
<li>Video captioning</li>



<li>Audio transcription</li>



<li>Scene understanding</li>



<li>Semantic reasoning</li>
</ul>



<p>Gemma 4 performs these tasks  inside a single multimodal inference pipeline.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Building Multimodal AI Applications with Gemma 4 and Transformers" data-enlighter-group="29">Based on the video, here is what is happening:
**What is happening in the video?**
The video captures a live concert performance on a large stage. We see a band performing, with musicians playing instruments (guitars, drums, etc.) under bright stage lights and dramatic blue and white lighting, including significant smoke/fog effects. In the foreground, there is a crowd of people watching the show, with several audience members visible from behind. The energy of the performance seems high, as suggested by the lighting and the engagement of the audience.
**What is the song about?**
The provided lyrics are:
> "I'm falling on the street
> From neck to chest
> Could it be that moments
> Another one I want to be is
> In the storm alone
> I've been all alone
> I never want to see
> Oh this nice sad place you was given fate
> I don't want it
</pre>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Multimodal-Function-Calling-Gemma-4"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Multimodal-Function-Calling-Gemma-4">Multimodal Function Calling with Gemma 4</a></h2>



<p>One of the most powerful capabilities introduced in modern language models is function calling. Instead of generating only plain text responses, the model can decide when to invoke external tools and generate structured arguments for them.</p>



<p>In this example, we combine:</p>



<ul class="wp-block-list">
<li>Vision understanding</li>



<li>Reasoning</li>



<li>Tool usage</li>
</ul>



<p>inside a single multimodal workflow.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Building Multimodal AI Applications with Gemma 4 and Transformers" data-enlighter-group="31">WEATHER_TOOL = {
   "type": "function",
   "function": {
       "name": "get_weather",
       "description": "Gets the current weather for a specific location.",
       "parameters": {
           "type": "object",
           "properties": {
               "city": {"type": "string", "description": "The city name"},
           },
           "required": ["city"],
       },
   },
}
tools = [WEATHER_TOOL]
</pre>



<p>We first define a weather tool schema. This structure describes the external tool available to the model. The tool definition contains several important components.</p>



<p>First, we specify the tool type: <code data-enlighter-language="python" class="EnlighterJSRAW">"type": "function"</code> tells Gemma 4 that the tool represents a callable function.</p>



<p>Next, we define the actual function metadata. <code data-enlighter-language="python" class="EnlighterJSRAW">"name": "get_weather"</code> is the function name the model will reference when generating tool calls. We also provide a natural language description. This helps the model understand what the tool does and when it should be used.</p>



<p>Next comes the parameter schema. This follows a JSON-style schema format. Here, the function expects a single required argument:</p>



<ul class="wp-block-list">
<li><code data-enlighter-language="python" class="EnlighterJSRAW">city</code></li>
</ul>



<p>The model will later generate this parameter automatically based on the image and user request. We then place the tool into a list. This allows multiple tools to be passed into the model if needed.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Building Multimodal AI Applications with Gemma 4 and Transformers" data-enlighter-group="33">messages = [
   {"role": "user", "content": [
       {"type": "image", "image": "https://huggingface.co/datasets/merve/vlm_test_images/resolve/main/venice.jpg"},
       {"type": "text", "text": "What is the city in this image? Check the weather there right now."},
   ]},
]
</pre>



<p>Next, we define the multimodal user input.</p>



<p>This input combines:</p>



<ul class="wp-block-list">
<li>An image</li>



<li>A reasoning instruction</li>
</ul>



<p>The image contains a photograph of Venice, while the text prompt asks the model to:</p>



<ul class="wp-block-list">
<li>Identify the city</li>



<li>Use the weather tool for that location</li>
</ul>



<p>This is important because the model must first perform visual reasoning before it can invoke the function correctly.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Building Multimodal AI Applications with Gemma 4 and Transformers" data-enlighter-group="35">inputs = processor.apply_chat_template(
   messages,
   tools=[WEATHER_TOOL],
   tokenize=True,
   return_dict=True,
   return_tensors="pt",
   add_generation_prompt=True,
   enable_thinking=True,
).to(model.device)
</pre>



<p>Next, we prepare the inputs.</p>



<p>The major addition here is: <code data-enlighter-language="python" class="EnlighterJSRAW">tools=[WEATHER_TOOL]</code></p>



<p>This injects the available tool schema directly into the prompt context. Gemma 4 now knows:</p>



<ul class="wp-block-list">
<li>Which tools exist</li>



<li>What each tool does</li>



<li>Which parameters are required</li>
</ul>



<p>We also enable reasoning mode again: <code data-enlighter-language="python" class="EnlighterJSRAW">enable_thinking=True</code></p>



<p>This helps the model reason through the sequence:</p>



<ul class="wp-block-list">
<li>Analyze image</li>



<li>Infer city</li>



<li>Decide tool usage</li>



<li>Generate function arguments</li>
</ul>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Building Multimodal AI Applications with Gemma 4 and Transformers" data-enlighter-group="37">output = model.generate(**inputs, max_new_tokens=1000)
</pre>



<p>After processing the inputs, we generate the output. Since function-calling outputs can include reasoning traces and structured responses, we allow a larger token budget.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Building Multimodal AI Applications with Gemma 4 and Transformers" data-enlighter-group="39">input_len = inputs.input_ids.shape[-1]
generated_text_ids = output[0][input_len:]
generated_text = processor.decode(generated_text_ids, skip_special_tokens=True)
result = processor.parse_response(generated_text)
</pre>



<p>Next, we extract only the generated tokens. We then decode the generated response. After decoding, we parse the structured response.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Building Multimodal AI Applications with Gemma 4 and Transformers" data-enlighter-group="41">print(result["content"])
</pre>



<p>Finally, we print the generated output.</p>



<p><strong>Output</strong></p>



<p>At this stage, Gemma 4 identifies the city from the image and generates a structured tool call for retrieving the weather.</p>



<p>This is the input image:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/07/image-16-scaled.jpeg" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="674" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-16-1024x674.jpeg?lossy=2&strip=1&webp=1" alt="" class="wp-image-54558"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-16-1024x674.jpeg?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-16-1024x674.jpeg?size=126x83&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-16-1024x674.jpeg?size=252x166&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-16-1024x674.jpeg?size=378x249&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-16-1024x674.jpeg?size=504x332&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-16-1024x674.jpeg?size=630x415&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 3:</strong> Input Image (source: <a href="https://huggingface.co/datasets/merve/vlm_test_images/blob/main/venice.jpg" target="_blank" rel="noreferrer noopener">Hugging Face</a>)</figcaption></figure></div>


<p>This is the generated output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Building Multimodal AI Applications with Gemma 4 and Transformers" data-enlighter-group="43">thought
Here's a thinking process to arrive at the desired response:
1.  **Analyze the Request:** The user has provided an image and asked two questions:
    *   "What is the city in this image?"
    *   "Check the weather there right now."
2.  **Analyze the Image:**
    *   The image shows a large, ornate building situated on the water, with boats and other buildings in the background.
    *   The architecture strongly resembles famous Italian landmarks, specifically those found in Venice (bridges, canals, specific facade styles).
    *   The presence of a canal setting is a huge clue.
3.  **Identify the Location (Inference/Knowledge Retrieval):**
    *   The architecture points strongly toward Venice, Italy.
    *   The specific building looks like a prominent structure in Venice (e.g., a church or palace facade).
4.  **Determine the Necessary Tool Call:**
    *   The user wants the weather for the identified city.
    *   The available tool is `get_weather(city: STRING)`.
5.  **Formulate the Plan:**
    *   **Step 1:** State the identified city.
    *   **Step 2:** Call the `get_weather` tool with the identified city.

6.  **Execute Step 1 (Internal Check):** The city is Venice.
7.  **Execute Step 2 (Tool Call Generation):**
    *   Call: `get_weather(city="Venice")`
8.  **Final Output Generation:** Since I need to call a tool, I must output the tool call first. (Self-Correction: I cannot give the weather *yet*; I must request the tool execution.)call:get_weather{city:Venice}
</pre>



<p>This example demonstrates why multimodal function calling is so powerful. The model is no longer limited to passive question answering. Instead, it can:</p>



<ul class="wp-block-list">
<li>Observe visual information</li>



<li>Reason about the task</li>



<li>Select external tools</li>



<li>Generate structured arguments</li>
</ul>



<p>This forms the foundation for agentic AI systems where multimodal models interact with application programming interfaces (APIs), databases, and external applications dynamically.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Object-Detection-Visual-Grounding-Gemma-4"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Object-Detection-Visual-Grounding-Gemma-4">Object Detection and Visual Grounding with Gemma 4</a></h2>



<p>Beyond captioning and reasoning, Gemma 4 can also perform structured visual localization tasks such as object detection and pointing. Instead of generating only natural language descriptions, the model can return bounding box coordinates for objects inside an image.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Building Multimodal AI Applications with Gemma 4 and Transformers" data-enlighter-group="45">image_url = "https://huggingface.co/datasets/merve/vlm_test_images/resolve/main/bird.png"
image = load_image(image_url)
</pre>



<p>We begin by loading the image. Here, <code data-enlighter-language="python" class="EnlighterJSRAW">load_image()</code> downloads the image directly from the URL and converts it into a format suitable for further processing.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Building Multimodal AI Applications with Gemma 4 and Transformers" data-enlighter-group="47">def resize_to_48_multiple(image):
   w, h = image.size
   new_w = (w // 48) * 48
   new_h = (h // 48) * 48
   return image.crop((0, 0, new_w, new_h))
</pre>



<p>Next, we define a preprocessing helper function. This function adjusts the image dimensions so both height and width become multiples of <code data-enlighter-language="python" class="EnlighterJSRAW">48</code>.</p>



<p>We first extract the original image dimensions. Next, we compute the nearest lower multiples of <code data-enlighter-language="python" class="EnlighterJSRAW">48</code>. The <code data-enlighter-language="python" class="EnlighterJSRAW">//</code> operator performs integer division. This effectively rounds the dimensions downward to the nearest valid multiple.</p>



<p>Finally, we crop the image. This preprocessing step helps ensure compatibility with the vision encoder and patch processing pipeline used internally by Gemma 4. Since transformer-based vision models often process images in fixed patch sizes, maintaining aligned dimensions simplifies inference.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Building Multimodal AI Applications with Gemma 4 and Transformers" data-enlighter-group="49">def inputs_for_object_detection(image, what_object):
   messages = [
       {
           "role": "user", "content": [
               {"type": "image", "image": image},
               {"type": "text", "text": f"What's the bounding box for the {what_object} in the image?"}
           ]
       }
   ]

   inputs = processor.apply_chat_template(
       messages,
       tokenize=True,
       add_generation_prompt=True,
       return_dict=True,
       return_tensors="pt",
       enable_thinking=False,
   )

   return inputs.to(model.device)
</pre>



<p>Next, we define the function that prepares the object detection prompt. This function takes:</p>



<ul class="wp-block-list">
<li>The input image</li>



<li>The target object name</li>
</ul>



<p>and constructs the multimodal request.</p>



<p>Inside the function, we first define the chat-style message. The image is passed directly as part of the multimodal input.</p>



<p>The text prompt dynamically inserts the target object name using an f-string. For example, if:</p>



<p><code data-enlighter-language="python" class="EnlighterJSRAW">what_object = "bird"</code></p>



<p>the final prompt becomes:</p>



<p><code data-enlighter-language="python" class="EnlighterJSRAW">"What's the bounding box for the bird in the image?"</code></p>



<p>This allows the same pipeline to work for many different object categories without changing the core logic.</p>



<p>Next, we process the multimodal request. Most of the arguments are familiar from earlier examples, but one important detail here is: <code data-enlighter-language="python" class="EnlighterJSRAW">enable_thinking=False</code></p>



<p>Unlike reasoning-heavy tasks (e.g., code generation or function calling), object detection is primarily a localization task. Disabling thinking mode helps keep the output concise and focused on structured bounding box predictions instead of extended reasoning traces.</p>



<p>The processor then:</p>



<ul class="wp-block-list">
<li>Tokenizes the text prompt</li>



<li>Encodes the image</li>



<li>Applies the correct chat template</li>



<li>Converts everything into PyTorch tensors</li>
</ul>



<p>Finally, we move the tensors onto the same device as the model.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Building Multimodal AI Applications with Gemma 4 and Transformers" data-enlighter-group="51">def extract_json(text: str):
   text = text.strip()

   text = re.sub(r"^```(?:json)?\s*", "", text)
   text = re.sub(r"\s*```$", "", text)

   # Try direct parse first
   try:
       return json.loads(text)
   except json.JSONDecodeError:
       pass

   # Fallback: extract first JSON object or array
   match = re.search(r'(\{.*\}|\[.*\])', text, re.DOTALL)
   if match:
       candidate = match.group(1)
       return json.loads(candidate)

   raise ValueError("No valid JSON found")
</pre>



<p>After preparing the object detection inputs, the next step is running inference, extracting the structured bounding box predictions, and visualizing the detected object on the image.</p>



<p>We first define a helper function for parsing the model response.</p>



<p>The generated output from Gemma 4 is usually returned as text, even when it contains structured JSON. This function cleans and extracts the JSON portion safely.</p>



<p>We first remove unnecessary whitespace. Next, we remove markdown-style code fences if they exist.</p>



<p>Sometimes models return outputs such as:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Building Multimodal AI Applications with Gemma 4 and Transformers" data-enlighter-group="53">[
 {
   "box_2d": [...]
 }
]
</pre>



<p>These regular expressions remove the surrounding Markdown formatting so the remaining content becomes valid JSON.</p>



<p>Next, we attempt direct JSON parsing. If the response is already valid JSON, this step succeeds immediately.</p>



<p>However, model outputs are not always perfectly formatted. Sometimes, additional explanation text appears before or after the JSON block. To handle that, we add a fallback mechanism. This searches for the first JSON object <code data-enlighter-language="python" class="EnlighterJSRAW">{}</code> or JSON array <code data-enlighter-language="python" class="EnlighterJSRAW">[]</code> inside the generated response.</p>



<p>If a <code data-enlighter-language="python" class="EnlighterJSRAW">match</code> is found: we extract and parse only the JSON portion.</p>



<p>Finally, if no valid JSON is detected, the function raises an error.</p>



<p>This helper function is important because structured outputs from multimodal models can sometimes contain extra formatting or reasoning traces. Robust parsing makes downstream processing much more reliable.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Building Multimodal AI Applications with Gemma 4 and Transformers" data-enlighter-group="55">def detect_object(image_url, what_object):
   image = load_image(image_url)
   image = resize_to_48_multiple(image)
   inputs = inputs_for_object_detection(image, what_object)
   input_len = inputs["input_ids"].shape[-1]
   generated_outputs = model.generate(**inputs, max_new_tokens=1000, do_sample=False)
   generated = processor.decode(generated_outputs[0, input_len:])
   parsed_json = extract_json(generated)[0]
   return parsed_json
</pre>



<p>Next, we define the main object detection function. This function performs the complete detection pipeline.</p>



<p>We first load and preprocess the image. Next, we prepare the detection inputs. We then compute the input sequence length. This helps us later separate the generated response from the original prompt tokens.</p>



<p>Next comes inference. Here:</p>



<ul class="wp-block-list">
<li><code data-enlighter-language="python" class="EnlighterJSRAW">max_new_tokens=1000</code>: sets the generation limit</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">do_sample=False</code>: enables deterministic decoding</li>
</ul>



<p>Deterministic decoding is useful here because object detection requires stable structured outputs rather than creative variations.</p>



<p>Next, we decode only the generated portion. We then extract the structured JSON response.</p>



<p>The model typically returns a list of detections, so <code data-enlighter-language="python" class="EnlighterJSRAW">[0]</code> selects the first detection result.</p>



<p>Finally, we return the structured detection dictionary.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Building Multimodal AI Applications with Gemma 4 and Transformers" data-enlighter-group="57">def draw_pascal_voc_boxes(i, image, box, label, resize_shape=(1000,1000)):
   dpi = 72
   width, height = image.size
   fig, ax = plt.subplots(1, figsize=[width/dpi, height/dpi], tight_layout={'pad':0})

   ax.imshow(image)

   ymin, xmin, ymax, xmax = box
   re_h, re_w = resize_shape if resize_shape is not None else (height, width)
   xmin = (xmin / re_w) * width
   ymin = (ymin/ re_h) * height
   xmax = (xmax / re_w) * width
   ymax = (ymax/ re_h) * height

   w = xmax - xmin
   h = ymax - ymin

   rect = patches.Rectangle(
       (xmin, ymin),
       w,
       h,
       linewidth=10,
       edgecolor="green",
       facecolor="none"
   )
   ax.add_patch(rect)

   if label is not None:
       ax.text(xmin, ymin-25, label, fontsize=24, bbox=dict(facecolor="yellow", alpha=0.5))

   plt.axis("off")
   plt.savefig(f"boxes_{i}.png")
   plt.close(fig)
   display(fig)
</pre>



<p>Next, we define the visualization function. This function draws the predicted bounding box on top of the image.</p>



<p>We first create a Matplotlib figure. Then we display the image. Next, we unpack the bounding box coordinates.</p>



<p>Gemma 4 returns normalized coordinates relative to a <code data-enlighter-language="python" class="EnlighterJSRAW">1000 × 1000</code> coordinate grid. We therefore rescale them back to the original image dimensions.</p>



<p>We then compute the bounding box width and height. Next, we create the rectangle overlay. This draws a green bounding box around the detected object. The rectangle is then added onto the image. If a label exists, we also display the object name.</p>



<p>Finally, we save and display the result.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Building Multimodal AI Applications with Gemma 4 and Transformers" data-enlighter-group="59">def display_detected_object(image_url, what_object):
   image = load_image(image_url)
   image = resize_to_48_multiple(image)
   detection = detect_object(image_url, what_object)
   box = detection["box_2d"]
   label = detection.get("label", f"{what_object}")
   draw_pascal_voc_boxes("1000", image, box, label)
</pre>



<p>Next, we define a helper wrapper function. This combines:</p>



<ul class="wp-block-list">
<li>Image loading</li>



<li>Detection</li>



<li>Visualization</li>
</ul>



<p>into one simple pipeline.</p>



<p>We first run object detection. Then extract the returned bounding box and label.</p>



<p>Finally, we visualize the prediction.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Building Multimodal AI Applications with Gemma 4 and Transformers" data-enlighter-group="61">display_detected_object("https://huggingface.co/datasets/merve/vlm_test_images/resolve/main/bird.png", "bird")</pre>



<p>We can now run the complete pipeline.</p>



<p><strong>Output</strong></p>



<p>At this stage, Gemma 4 identifies the bird in the image, predicts the bounding box coordinates, and overlays the detection visually.</p>



<p>This is the input image:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://pyimagesearch.com/wp-content/uploads/2026/07/image-9.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="732" height="490" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-9.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54562"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-9.png?size=126x84&lossy=2&strip=1&webp=1 126w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-9-300x201.png?lossy=2&strip=1&webp=1 300w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-9.png?size=378x253&lossy=2&strip=1&webp=1 378w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-9.png?size=504x337&lossy=2&strip=1&webp=1 504w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-9.png?size=630x422&lossy=2&strip=1&webp=1 630w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-9.png?lossy=2&strip=1&webp=1 732w" sizes="(max-width: 732px) 100vw, 732px" /></a><figcaption class="wp-element-caption"><strong>Figure 4: </strong>Input Image (source: <a href="https://huggingface.co/datasets/merve/vlm_test_images/blob/main/bird.png" target="_blank" rel="noreferrer noopener">Hugging Face</a>)</figcaption></figure></div>


<p>This is the output image:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://pyimagesearch.com/wp-content/uploads/2026/07/image-10.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="726" height="479" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-10.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54564"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-10.png?size=126x83&lossy=2&strip=1&webp=1 126w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-10-300x198.png?lossy=2&strip=1&webp=1 300w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-10.png?size=378x249&lossy=2&strip=1&webp=1 378w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-10.png?size=504x333&lossy=2&strip=1&webp=1 504w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-10.png?size=630x416&lossy=2&strip=1&webp=1 630w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-10.png?lossy=2&strip=1&webp=1 726w" sizes="(max-width: 726px) 100vw, 726px" /></a><figcaption class="wp-element-caption"><strong>Figure 5:</strong> Detected Object (source: author)</figcaption></figure></div>


<p>This example demonstrates that Gemma 4 is not limited to text generation or captioning. It can also produce structured spatial predictions, enabling workflows such as:</p>



<ul class="wp-block-list">
<li>Object localization</li>



<li>Visual grounding</li>



<li>UI element detection</li>



<li>Document understanding</li>



<li>Interactive visual reasoning</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Image-Captioning-Gemma-4-Vision-Language-Models"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Image-Captioning-Gemma-4-Vision-Language-Models">Image Captioning with Gemma 4 Vision-Language Models</a></h2>



<p>Image captioning is one of the most fundamental multimodal tasks for vision-language models. In this example, we ask Gemma 4 to observe an image and generate a detailed natural language description of the scene. </p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Building Multimodal AI Applications with Gemma 4 and Transformers" data-enlighter-group="63">messages = [
   {
       "role": "user",
       "content": [
           {"type": "image", "url": "https://huggingface.co/datasets/merve/vlm_test_images/resolve/main/mosque.jpg"},
           {"type": "text", "text": "Write single detailed caption for this image."},
       ],
   },
]
</pre>



<p>We first define the multimodal input message. The input contains 2 parts:</p>



<ul class="wp-block-list">
<li>An image</li>



<li>A text instruction</li>
</ul>



<p>The image block specifies the image URL. This tells the processor to load the image and prepare it for the vision encoder inside Gemma 4.</p>



<p>Next, we provide the captioning instruction. The wording of the prompt matters here. Since we request a <em>single detailed caption</em>, the model focuses on generating one coherent descriptive sentence instead of multiple fragmented observations.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Building Multimodal AI Applications with Gemma 4 and Transformers" data-enlighter-group="65">inputs = processor.apply_chat_template(
   messages,
   tokenize=True,
   return_dict=True,
   return_tensors="pt",
   add_generation_prompt=True,
).to(model.device)
</pre>



<p>Next, we process the multimodal input.</p>



<p>This step converts the image and text into the structured format expected by Gemma 4.</p>



<p>The processor internally handles:</p>



<ul class="wp-block-list">
<li>Image preprocessing</li>



<li>Tokenization</li>



<li>Prompt formatting</li>



<li>Tensor creation</li>
</ul>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Building Multimodal AI Applications with Gemma 4 and Transformers" data-enlighter-group="67">output = model.generate(**inputs, max_new_tokens=512)
</pre>



<p>After preprocessing, we generate the caption. Here, <code data-enlighter-language="python" class="EnlighterJSRAW">max_new_tokens=512</code> sets the maximum response length. Captioning tasks generally require fewer tokens than HTML generation or reasoning-heavy workflows, but we still allow enough space for detailed descriptions.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Building Multimodal AI Applications with Gemma 4 and Transformers" data-enlighter-group="69">input_len = inputs.input_ids.shape[-1]
generated_text_ids = output[0][input_len:]
generated_text = processor.decode(generated_text_ids, skip_special_tokens=True)
result = processor.parse_response(generated_text)
</pre>



<p>Next, we isolate the generated response. This removes the original prompt tokens and keeps only the newly generated caption. We then decode the generated tokens into readable text. The response is then parsed into a cleaner structure.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Building Multimodal AI Applications with Gemma 4 and Transformers" data-enlighter-group="71">print(result["content"])
</pre>



<p>Finally, we print the generated caption.</p>



<p><strong>Output</strong></p>



<p>At this stage, Gemma 4 analyzes the image and generates a detailed description of the mosque scene.</p>



<p>This is the input image:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/07/image-17-scaled.jpeg" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="667" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-17-1024x667.jpeg?lossy=2&strip=1&webp=1" alt="" class="wp-image-54569"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-17-1024x667.jpeg?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-17-1024x667.jpeg?size=126x82&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-17-1024x667.jpeg?size=252x164&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-17-1024x667.jpeg?size=378x246&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-17-1024x667.jpeg?size=504x328&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-17-1024x667.jpeg?size=630x410&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 6:</strong> Input Image (source: <a href="https://huggingface.co/datasets/merve/vlm_test_images/blob/main/mosque.jpg" target="_blank" rel="noreferrer noopener">Hugging Face</a>)</figcaption></figure></div>


<p>This is the generated output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Building Multimodal AI Applications with Gemma 4 and Transformers" data-enlighter-group="73">A bustling outdoor scene features a grand, domed building, likely a historical or religious structure, surrounded by lush greenery, palm trees, and pedestrians walking along a paved walkway. The sky is bright blue with some white clouds, suggesting pleasant weather. In the background, taller minarets are visible, adding to the architectural grandeur of the location. The foreground shows a metal railing and a crowd of people, indicating a popular public space.
</pre>



<p>Although captioning appears simpler than function calling or video understanding, it is still a strong test of multimodal reasoning. The model must:</p>



<ul class="wp-block-list">
<li>Identify objects</li>



<li>Understand spatial relationships</li>



<li>Infer scene context</li>



<li>Convert visual information into fluent language</li>
</ul>



<p>This example also highlights the consistency of the Gemma 4 workflow. Whether we perform:</p>



<ul class="wp-block-list">
<li>Screenshot-to-code generation</li>



<li>Video reasoning</li>



<li>Function calling</li>



<li>Captioning</li>
</ul>



<p>the overall inference pipeline remains nearly identical. Only the input modality and prompt change.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Audio-Understanding-Gemma-4"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Audio-Understanding-Gemma-4">Audio Understanding with Gemma 4</a></h2>



<p>One of the most interesting capabilities of the Gemma 4 E-series models is native audio understanding. Instead of relying on a separate speech recognition model, Gemma 4 can directly process audio inputs and reason about them inside the same multimodal pipeline.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Building Multimodal AI Applications with Gemma 4 and Transformers" data-enlighter-group="75">messages = [
   {
       "role": "user",
       "content": [
           {"type": "audio", "url": "https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/winning_call.mp3"},
           {"type": "text", "text": "Can you describe this audio in detail?"},
       ],
   },
]
</pre>



<p>We begin by defining the multimodal input.</p>



<p>The first content block provides the audio input. This tells the processor that the modality is audio rather than image or video.</p>



<p>The second content block contains the text instruction. This prompt asks the model to analyze and explain the audio content in natural language.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Building Multimodal AI Applications with Gemma 4 and Transformers" data-enlighter-group="77">inputs = processor.apply_chat_template(
   messages,
   tokenize=True,
   return_dict=True,
   return_tensors="pt",
   add_generation_prompt=True,
).to(model.device)
</pre>



<p>Next, we process the multimodal input. This step converts the audio and text into tensors that Gemma 4 can process internally.</p>



<p>As discussed in the first part of this series, the E2B and E4B variants include a dedicated audio encoder. The processor handles the conversion of raw audio into the representation expected by this encoder automatically. </p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Building Multimodal AI Applications with Gemma 4 and Transformers" data-enlighter-group="79">output = model.generate(
   **inputs,
   max_new_tokens=1000,
   do_sample=False,
)
</pre>



<p>After preprocessing, we generate the response.</p>



<p>Here, <code data-enlighter-language="python" class="EnlighterJSRAW">max_new_tokens=1000</code> defines the maximum output length for the generated response.</p>



<p>We also use <code data-enlighter-language="python" class="EnlighterJSRAW">do_sample=False</code>. This disables sampling and makes generation deterministic. Instead of producing varied outputs each time, the model selects the most likely token at every step. For descriptive tasks (e.g., audio understanding), deterministic decoding often produces more stable and reproducible results.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Building Multimodal AI Applications with Gemma 4 and Transformers" data-enlighter-group="81">print(processor.decode(output[0], skip_special_tokens=True))
</pre>



<p>Finally, we decode and print the generated response.</p>



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">decode()</code> function converts token IDs back into readable text, while <code data-enlighter-language="python" class="EnlighterJSRAW">skip_special_tokens=True</code> removes internal formatting tokens.</p>



<p><strong>Output</strong></p>



<p>At this stage, Gemma 4 analyzes the audio clip and generates a detailed natural language description of what it hears.</p>



<p>This is the generated output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Building Multimodal AI Applications with Gemma 4 and Transformers" data-enlighter-group="83">user
Can you describe this audio in detail?
model
Okay, here's a detailed description of the audio you provided:
**Overall Impression:**
The audio is a lively, energetic, and enthusiastic sports commentary, likely from a baseball game. The tone is excited, building anticipation and celebrating a significant moment.
**Specific Details:**
* **Soundscape:** The audio features the sounds of a live sports broadcast. This includes the voice of a commentator, likely with some background noise of a stadium or crowd, though the focus is clearly on the commentary.
* **Commentary Style:** The commentary is fast-paced, dynamic, and uses typical sports jargon and exclamations. The delivery is high-energy and passionate, reflecting the excitement of the game.
* **Key Phrases and Content:**
    * **"And the O1 pitcher on the way to Edgar Martinez swung on the line."**: This sets the scene, indicating a specific play involving a pitcher and a batter.
    * **"Here comes Joey! Here's Ginger in third base!"**: These are calls to action, identifying players and their positions.
    * **"They've got a way to win!"**: This conveys a sense of hope and determination.
    * **"The problem of plate will be late the manner is glaring the fans for the American League championship!"**: This is a more complex sentence, likely referring to a strategic situation and the importance of the championship.
    * **"I don't believe it!"**: An expression of surprise or disbelief, adding to the excitement.
    * **"And just continues my old time!"**: This suggests a continuation of a successful or exciting sequence of events.
* **Emotional Tone:** The tone is overwhelmingly positive, excited, and celebratory. There's a palpable sense of anticipation and triumph.
**In Summary:**
The audio is a segment of a high-energy baseball game broadcast. It captures a moment of intense action, featuring dynamic commentary that builds excitement and highlights the stakes of a championship game. The commentator's enthusiasm is infectious and effectively conveys the thrill of the moment.
</pre>



<p>This example highlights an important direction in multimodal AI systems. Traditionally, tasks such as the following:</p>



<ul class="wp-block-list">
<li>Speech recognition</li>



<li>Audio captioning</li>



<li>Sound event detection</li>



<li>Spoken question answering</li>
</ul>



<p>often required separate specialized models.</p>



<p>Gemma 4 instead handles these tasks within a unified multimodal framework, allowing text, images, video, and audio to all flow through the same inference pipeline.</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<div id="pitch" style="padding: 40px; width: 100%; background-color: #F4F6FA;">
	<h3>What's next? We recommend <a target="_blank" href="https://pyimagesearch.com/pyimagesearch-university/?utm_source=blogPost&utm_medium=bottomBanner&utm_campaign=What%27s%20next%3F%20I%20recommend">PyImageSearch University</a>.</h3>

	<script src="https://fast.wistia.com/embed/medias/kno0cmko2z.jsonp" async></script><script src="https://fast.wistia.com/assets/external/E-v1.js" async></script><div class="wistia_responsive_padding" style="padding:56.25% 0 0 0;position:relative;"><div class="wistia_responsive_wrapper" style="height:100%;left:0;position:absolute;top:0;width:100%;"><div class="wistia_embed wistia_async_kno0cmko2z videoFoam=true" style="height:100%;position:relative;width:100%"><div class="wistia_swatch" style="height:100%;left:0;opacity:0;overflow:hidden;position:absolute;top:0;transition:opacity 200ms;width:100%;"><img decoding="async" src="https://fast.wistia.com/embed/medias/kno0cmko2z/swatch" style="filter:blur(5px);height:100%;object-fit:contain;width:100%;" alt="" aria-hidden="true" onload="this.parentNode.style.opacity=1;" /></div></div></div></div>

	<div style="margin-top: 32px; margin-bottom: 32px; ">
		<strong>Course information:</strong><br/>
		120+ total classes • 115+ hours hours of on-demand code walkthrough videos • Last updated: August 2026<br/>
		<span style="color: #169FE6;">★★★★★</span> 4.84 (128 Ratings) • 16,000+ Students Enrolled
	</div>

	<p><strong>I strongly believe that if you had the right teacher you could <em>master</em> computer vision and deep learning.</strong></p>

	<p>Do you think learning computer vision and deep learning has to be time-consuming, overwhelming, and complicated? Or has to involve complex mathematics and equations? Or requires a degree in computer science?</p>

	<p>That’s <em>not</em> the case.</p>

	<p>All you need to master computer vision and deep learning is for someone to explain things to you in <em>simple, intuitive</em> terms. <em>And that’s exactly what I do</em>. My mission is to change education and how complex Artificial Intelligence topics are taught.</p>

	<p>If you're serious about learning computer vision, your next stop should be PyImageSearch University, the most comprehensive computer vision, deep learning, and OpenCV course online today. Here you’ll learn how to <em>successfully</em> and <em>confidently</em> apply computer vision to your work, research, and projects. Join me in computer vision mastery.</p>

	<p><strong>Inside PyImageSearch University you'll find:</strong></p>

	<ul style="margin-left: 0px;">
		<li style="list-style: none;">&check; <strong>120+ courses</strong> on essential computer vision, deep learning, and OpenCV topics</li>
		<li style="list-style: none;">&check; <strong>94+ Certificates</strong> of Completion</li>
		<li style="list-style: none;">&check; <strong>115+ hours hours</strong> of on-demand video</li>
		<li style="list-style: none;">&check; <strong>Brand new courses released <em>regularly</em></strong>, ensuring you can keep up with state-of-the-art techniques</li>
		<li style="list-style: none;">&check; <strong>Pre-configured Jupyter Notebooks in Google Colab</strong></li>
		<li style="list-style: none;">&check; Run all code examples in your web browser — works on Windows, macOS, and Linux (no dev environment configuration required!)</li>
		<li style="list-style: none;">&check; Access to <strong>centralized code repos for <em>all</em> 540+ tutorials</strong> on PyImageSearch</li>
		<li style="list-style: none;">&check; <strong> Easy one-click downloads</strong> for code, datasets, pre-trained models, etc.</li>
		<li style="list-style: none;">&check; <strong>Access</strong> on mobile, laptop, desktop, etc.</li>
	</ul>

	<p style="text-align: center;">
		<a target="_blank" class="button link" href="https://pyimagesearch.com/pyimagesearch-university/?utm_source=blogPost&utm_medium=bottomBanner&utm_campaign=What%27s%20next%3F%20I%20recommend" style="background-color: #6DC713; border-bottom: none;">Click here to join PyImageSearch University</a>
	</p>
</div>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Summary"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Summary">Summary</a></h2>



<p>In this lesson, we explored how to build multimodal applications using Gemma 4 and Hugging Face Transformers. Starting from environment setup and model loading, we walked through several real-world multimodal workflows (e.g., including screenshot-to-code generation, video understanding, multimodal function calling, image captioning, audio understanding, and object detection).</p>



<p>One of the biggest takeaways from Gemma 4 is the consistency of its inference pipeline. Whether the input is text, images, video, or audio, the overall workflow remains nearly identical:</p>



<ul class="wp-block-list">
<li>Define the multimodal conversation</li>



<li>Process the inputs using the processor</li>



<li>Run generation</li>



<li>Decode and parse the outputs</li>
</ul>



<p>This unified design makes multimodal development significantly simpler.</p>



<p>We also saw that Gemma 4 is not limited to conversational AI. It can generate HTML from screenshots, reason over videos, invoke external tools, localize objects with bounding boxes, and understand audio, all inside a single multimodal framework. Together, these capabilities make Gemma 4 a powerful foundation for building next-generation agentic and multimodal AI systems.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Citation-Information"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Citation-Information">Citation Information</a></h3>



<p><strong>Thakur, P. </strong>“Building Multimodal AI Applications with Gemma 4 and Transformers,” <em>PyImageSearch</em>, S. Huot, G. Kudriavtsev, and A. Sharma, eds., 2026, <a href="https://pyimg.co/09dks" target="_blank" rel="noreferrer noopener">https://pyimg.co/09dks</a></p>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="classic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="Building Multimodal AI Applications with Gemma 4 and Transformers" data-enlighter-group="85">@incollection{Thakur_2026_build-multimodal-ai-apps-w-gemma-4-transformers,
  author = {Piyush Thakur},
  title = {{Building Multimodal AI Applications with Gemma 4 and Transformers}},
  booktitle = {PyImageSearch},
  editor = {Susan Huot and Georgii Kudriavtsev and Aditya Sharma},
  year = {2026},
  url = {https://pyimg.co/09dks},
}
</pre>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p><strong>To download the source code to this post (and be notified when future tutorials are published here on PyImageSearch), </strong><em><strong>simply enter your email address in the form below!</strong></em></p>



<div id="download-the-code" class="post-cta-wrap">
<div class="gpd-post-cta">
	<div class="gpd-post-cta-content">
		

			<div class="gpd-post-cta-top">
				<div class="gpd-post-cta-top-image"><img decoding="async" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2020/01/cta-source-guide-1.png?lossy=2&strip=1&webp=1" alt="" srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2020/01/cta-source-guide-1.png?lossy=2&strip=1&webp=1 410w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2020/01/cta-source-guide-1.png?size=126x174&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2020/01/cta-source-guide-1.png?size=252x348&lossy=2&strip=1&webp=1 252w" sizes="(max-width: 410px) 100vw, 410px" /></div>
				
				<div class="gpd-post-cta-top-title"><h4>Download the Source Code and FREE 17-page Resource Guide</h4></div>
				<div class="gpd-post-cta-top-desc"><p>Enter your email address below to get a .zip of the code and a <strong>FREE 17-page Resource Guide on Computer Vision, OpenCV, and Deep Learning.</strong> Inside you'll find my hand-picked tutorials, books, courses, and libraries to help you master CV and DL!</p></div>


			</div>

			<div class="gpd-post-cta-bottom">
				<form id="footer-cta-code" class="footer-cta" action="https://www.getdrip.com/forms/4130035/submissions" method="post" target="blank" data-drip-embedded-form="4130035">
					<input name="fields[email]" type="email" value="" placeholder="Your email address" class="form-control" />

					<button type="submit">Download the code!</button>

					<div style="display: none;" aria-hidden="true"><label for="website">Website</label><br /><input type="text" id="website" name="website" tabindex="-1" autocomplete="false" value="" /></div>
				</form>
			</div>


		
	</div>

</div>
</div>
<p>The post <a rel="nofollow" href="https://pyimagesearch.com/2026/07/12/building-multimodal-ai-applications-with-gemma-4-and-transformers/">Building Multimodal AI Applications with Gemma 4 and Transformers</a> appeared first on <a rel="nofollow" href="https://pyimagesearch.com">PyImageSearch</a>.</p>
]]></content:encoded>
					
		
		<enclosure url="https://huggingface.co/datasets/merve/vlm_test_images/resolve/main/concert.mp4" length="1034" type="video/mp4" />
<enclosure url="https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/winning_call.mp3" length="1057" type="audio/mpeg" />

			</item>
		<item>
		<title>Building a Multimodal Chatbot with Qwen3-VL Instruct and Thinking Models</title>
		<link>https://pyimagesearch.com/2026/07/06/building-a-multimodal-chatbot-with-qwen3-vl-instruct-and-thinking-models/</link>
		
		<dc:creator><![CDATA[Puneet Mangla]]></dc:creator>
		<pubDate>Mon, 06 Jul 2026 12:45:00 +0000</pubDate>
				<category><![CDATA[Chatbot]]></category>
		<category><![CDATA[Gradio]]></category>
		<category><![CDATA[Qwen3 VL]]></category>
		<category><![CDATA[Qwen3-VL]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[chatbot]]></category>
		<category><![CDATA[gradio]]></category>
		<category><![CDATA[qwen3 vl]]></category>
		<category><![CDATA[qwen3-vl]]></category>
		<category><![CDATA[tutorial]]></category>
		<guid isPermaLink="false">https://pyimagesearch.com/?p=54465</guid>

					<description><![CDATA[<p>Table of Contents Building a Multimodal Chatbot with Qwen3-VL Instruct and Thinking Models Qwen3-VL Vision-Language Model: Architecture, Training, and Capabilities Qwen3-VL Architecture Overview: SigLIP2 Vision Encoder and Multimodal Transformer Design Training Pipeline: Multimodal Pretraining with Image-Text and Video-Text Data Performance&#8230;</p>
<p>The post <a rel="nofollow" href="https://pyimagesearch.com/2026/07/06/building-a-multimodal-chatbot-with-qwen3-vl-instruct-and-thinking-models/">Building a Multimodal Chatbot with Qwen3-VL Instruct and Thinking Models</a> appeared first on <a rel="nofollow" href="https://pyimagesearch.com">PyImageSearch</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<hr class="wp-block-separator has-alpha-channel-opacity"/>


<div class="yoast-breadcrumbs"><span><span><a href="https://pyimagesearch.com/">Home</a></span></div>


<div class="toc">
<hr class="TOC"/>
<p class="has-large-font-size"><strong>Table of Contents</strong></p>
<ul>
    <li id="TOC-h1-Building-Multimodal-Chatbot-Qwen3-VL-Instruct-Thinking-Models"><a rel="noopener" target="_blank" href="#h1-Building-Multimodal-Chatbot-Qwen3-VL-Instruct-Thinking-Models">Building a Multimodal Chatbot with Qwen3-VL Instruct and Thinking Models</a></li>

    <li id="TOC-h2-Qwen3-VL-Vision-Language-Model-Architecture-Training-Capabilities"><a rel="noopener" target="_blank" href="#h2-Qwen3-VL-Vision-Language-Model-Architecture-Training-Capabilities">Qwen3-VL Vision-Language Model: Architecture, Training, and Capabilities</a></li>
    <ul>
        <li id="TOC-h3-Qwen3-VL-Architecture-Overview-SigLIP2-Vision-Encoder-Multimodal-Transformer-Design"><a rel="noopener" target="_blank" href="#h3-Qwen3-VL-Architecture-Overview-SigLIP2-Vision-Encoder-Multimodal-Transformer-Design">Qwen3-VL Architecture Overview: SigLIP2 Vision Encoder and Multimodal Transformer Design</a></li>
        <li id="TOC-h3-Training-Pipeline-Multimodal-Pretraining-Image-Text-Video-Text-Data"><a rel="noopener" target="_blank" href="#h3-Training-Pipeline-Multimodal-Pretraining-Image-Text-Video-Text-Data">Training Pipeline: Multimodal Pretraining with Image-Text and Video-Text Data</a></li>
        <li id="TOC-h3-Performance-Benchmarks-Image-Video-Multi-Image-Reasoning-Evaluation"><a rel="noopener" target="_blank" href="#h3-Performance-Benchmarks-Image-Video-Multi-Image-Reasoning-Evaluation">Performance Benchmarks: Image, Video, and Multi-Image Reasoning Evaluation</a></li>
    </ul>

    <li id="TOC-h2-Implementation-Building-Multimodal-Chatbot-Qwen3-VL-Gradio"><a rel="noopener" target="_blank" href="#h2-Implementation-Building-Multimodal-Chatbot-Qwen3-VL-Gradio">Implementation: Building a Multimodal Chatbot with Qwen3-VL and Gradio</a></li>
    <ul>
        <li id="TOC-h3-Step-1-Installing-Dependencies-Qwen3-VL-Multimodal-Processing-PyTorch-Transformers-Gradio"><a rel="noopener" target="_blank" href="#h3-Step-1-Installing-Dependencies-Qwen3-VL-Multimodal-Processing-PyTorch-Transformers-Gradio">Step 1: Installing Dependencies for Qwen3-VL and Multimodal Processing (PyTorch, Transformers, Gradio)</a></li>
        <li id="TOC-h3-Step-2-Importing-Required-Libraries"><a rel="noopener" target="_blank" href="#h3-Step-2-Importing-Required-Libraries">Step 2: Importing Required Libraries</a></li>
        <li id="TOC-h3-Step-3-Initializing-Qwen3-VL-Instruct-Thinking-Image-Text-to-Text-Pipelines"><a rel="noopener" target="_blank" href="#h3-Step-3-Initializing-Qwen3-VL-Instruct-Thinking-Image-Text-to-Text-Pipelines">Step 3: Initializing Qwen3-VL Instruct and Thinking Image-Text-to-Text Pipelines</a></li>
        <li id="TOC-h3-Step-4-Testing-Multimodal-Conversations-Image-Uploads-Text-Prompts"><a rel="noopener" target="_blank" href="#h3-Step-4-Testing-Multimodal-Conversations-Image-Uploads-Text-Prompts">Step 4: Testing Multimodal Conversations with Image Uploads and Text Prompts</a></li>
        <li id="TOC-h3-Step-5-Building-Gradio-Multimodal-Chat-Interface-Image-Input-Support"><a rel="noopener" target="_blank" href="#h3-Step-5-Building-Gradio-Multimodal-Chat-Interface-Image-Input-Support">Step 5: Building a Gradio Multimodal Chat Interface with Image Input Support</a></li>
        <li id="TOC-h3-Step-6-Launching-Qwen3-VL-Multimodal-Chatbot-Application"><a rel="noopener" target="_blank" href="#h3-Step-6-Launching-Qwen3-VL-Multimodal-Chatbot-Application">Step 6: Launching the Qwen3-VL Multimodal Chatbot Application</a></li>
    </ul>

    <li id="TOC-h2-Multimodal-Chatbot-Results-Instruct-Mode-vs-Thinking-Mode-Analysis"><a rel="noopener" target="_blank" href="#h2-Multimodal-Chatbot-Results-Instruct-Mode-vs-Thinking-Mode-Analysis">Multimodal Chatbot Results: Instruct Mode vs Thinking Mode Analysis</a></li>

    <li id="TOC-h2-Summary"><a rel="noopener" target="_blank" href="#h2-Summary">Summary</a></li>
    <ul>
        <li id="TOC-h3-Citation-Information"><a rel="noopener" target="_blank" href="#h3-Citation-Information">Citation Information</a></li>
    </ul>
</ul>
</div>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h1-Building-Multimodal-Chatbot-Qwen3-VL-Instruct-Thinking-Models"/>



<h2 class="wp-block-heading"><a href="#TOC-h1-Building-Multimodal-Chatbot-Qwen3-VL-Instruct-Thinking-Models">Building a Multimodal Chatbot with Qwen3-VL Instruct and Thinking Models</a></h2>



<p>In the previous lesson, we explored the power of Qwen3’s text-only models for building intelligent chatbots capable of deep reasoning. However, the real world is fundamentally multimodal: humans do not just communicate through text; we perceive and interact with the world through vision and other sensory inputs. The ability to understand and reason about visual information alongside text represents a crucial step toward more capable and human-like AI systems. This is where Qwen3-VL (Vision-Language) enters the picture, bringing state-of-the-art multimodal understanding to the open-source community.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://pyimagesearch.com/wp-content/uploads/2026/07/building-multimodal-chatbot-qwen3-vl-instruct-thinking-models-featured.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="940" height="780" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/building-multimodal-chatbot-qwen3-vl-instruct-thinking-models-featured.png?lossy=2&strip=1&webp=1" alt="building-multimodal-chatbot-qwen3-vl-instruct-thinking-models-featured.png" class="wp-image-54481"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/building-multimodal-chatbot-qwen3-vl-instruct-thinking-models-featured.png?size=126x105&lossy=2&strip=1&webp=1 126w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/building-multimodal-chatbot-qwen3-vl-instruct-thinking-models-featured-300x249.png?lossy=2&strip=1&webp=1 300w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/building-multimodal-chatbot-qwen3-vl-instruct-thinking-models-featured.png?size=378x314&lossy=2&strip=1&webp=1 378w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/building-multimodal-chatbot-qwen3-vl-instruct-thinking-models-featured.png?size=504x418&lossy=2&strip=1&webp=1 504w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/building-multimodal-chatbot-qwen3-vl-instruct-thinking-models-featured.png?size=630x523&lossy=2&strip=1&webp=1 630w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/building-multimodal-chatbot-qwen3-vl-instruct-thinking-models-featured-768x637.png?lossy=2&strip=1&webp=1 768w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/building-multimodal-chatbot-qwen3-vl-instruct-thinking-models-featured.png?lossy=2&strip=1&webp=1 940w" sizes="(max-width: 940px) 100vw, 940px" /></a></figure></div>


<p>Qwen3-VL represents a significant advancement in vision-language models, building upon the robust foundations of the Qwen3 architecture while adding sophisticated visual understanding capabilities. Like its text-only counterpart, Qwen3-VL features both Instruct and Thinking variants, enabling users to choose between fast, direct responses and deep, step-by-step reasoning for complex visual understanding tasks. </p>



<p>The model can process and understand images alongside text queries, making it invaluable for applications (e.g., visual question answering, image captioning, complex scene understanding, and multi-image reasoning). Whether you are analyzing medical images, interpreting charts and diagrams, or building assistive technologies for visually impaired users, Qwen3-VL provides the foundational capabilities needed for production-ready multimodal systems.</p>



<p>In this lesson, we extend our chatbot from Lesson 1 by integrating Qwen3-VL’s vision-language capabilities. We will learn how to handle multimodal inputs where users can upload images alongside their text queries, and the chatbot will respond with contextually appropriate answers that demonstrate understanding of both modalities. Through practical implementation using the Hugging Face Transformers library and Gradio, we will build an interactive web interface that seamlessly processes image-text pairs.</p>



<p>The Thinking mode will reveal the model’s visual reasoning process, showing how it analyzes images step-by-step before arriving at conclusions. By the end of this lesson, you will have a fully functional multimodal chatbot that can engage in sophisticated conversations about visual content, laying the groundwork for even more advanced capabilities we will add in subsequent lessons.</p>



<p>This lesson is the 2nd in a 4-part series on <strong>Building with Qwen3 Models</strong>:</p>



<ol class="wp-block-list">
<li><em><strong><a href="https://pyimg.co/o0x9h" target="_blank" rel="noreferrer noopener">Building an Intelligent Chatbot with </a></strong></em><em><strong><a href="https://pyimg.co/o0x9h" target="_blank" rel="noreferrer noopener">Qwen3</a></strong></em><em><strong><a href="https://pyimg.co/o0x9h" target="_blank" rel="noreferrer noopener"> Instruct and Thinking Models</a></strong></em></li>



<li><em><strong><a href="https://pyimg.co/jf6oe" target="_blank" rel="noreferrer noopener">Building a Multimodal Chatbot with Qwen3-VL Instruct and Thinking Models</a></strong></em><strong> (this tutorial)</strong></li>



<li><em>Lesson 3</em></li>



<li><em>Lesson 4</em></li>
</ol>



<p><strong>To learn about Qwen3 and build intelligent applications from scratch, </strong><em><strong>just keep reading</strong></em><strong>.</strong></p>



<div id="pyi-source-code-block" class="source-code-wrap"><div class="gpd-source-code">
    <div class="gpd-source-code-content">
        <img decoding="async" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2020/01/source-code-icon.png?lossy=2&strip=1&webp=1" alt="">
        <h4>Looking for the source code to this post?</h4>
                    <a href="#download-the-code" class="pyis-cta-modal-open-modal">Jump Right To The Downloads Section <svg class="svg-icon arrow-right" width="12" height="12" aria-hidden="true" role="img" focusable="false" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M6.8125 0.1875C6.875 0.125 6.96875 0.09375 7.09375 0.09375C7.1875 0.09375 7.28125 0.125 7.34375 0.1875L13.875 6.75C13.9375 6.8125 14 6.90625 14 7C14 7.125 13.9375 7.1875 13.875 7.25L7.34375 13.8125C7.28125 13.875 7.1875 13.9062 7.09375 13.9062C6.96875 13.9062 6.875 13.875 6.8125 13.8125L6.1875 13.1875C6.125 13.125 6.09375 13.0625 6.09375 12.9375C6.09375 12.8438 6.125 12.75 6.1875 12.6562L11.0312 7.8125H0.375C0.25 7.8125 0.15625 7.78125 0.09375 7.71875C0.03125 7.65625 0 7.5625 0 7.4375V6.5625C0 6.46875 0.03125 6.375 0.09375 6.3125C0.15625 6.25 0.25 6.1875 0.375 6.1875H11.0312L6.1875 1.34375C6.125 1.28125 6.09375 1.1875 6.09375 1.0625C6.09375 0.96875 6.125 0.875 6.1875 0.8125L6.8125 0.1875Z" fill="#169FE6"></path></svg></a>
            </div>
</div>
</div>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Qwen3-VL-Vision-Language-Model-Architecture-Training-Capabilities"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Qwen3-VL-Vision-Language-Model-Architecture-Training-Capabilities">Qwen3-VL Vision-Language Model: Architecture, Training, and Capabilities</a></h2>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Qwen3-VL-Architecture-Overview-SigLIP2-Vision-Encoder-Multimodal-Transformer-Design"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Qwen3-VL-Architecture-Overview-SigLIP2-Vision-Encoder-Multimodal-Transformer-Design">Qwen3-VL Architecture Overview: SigLIP2 Vision Encoder and Multimodal Transformer Design</a></h3>



<p>Qwen3-VL (<strong>Figure 1</strong>) builds upon the Qwen3 language model architecture by integrating a powerful vision encoder capable of processing both static images and dynamic video content. The model employs a vision encoder initialized from SigLIP2-SO-400M, containing approximately 543 million parameters specifically dedicated to visual understanding. </p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/07/image-7-scaled.jpeg" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="588" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-7-1024x588.jpeg?lossy=2&strip=1&webp=1" alt="" class="wp-image-54483"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-7-1024x588.jpeg?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-7-1024x588.jpeg?size=126x72&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-7-1024x588.jpeg?size=252x145&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-7-1024x588.jpeg?size=378x217&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-7-1024x588.jpeg?size=504x289&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-7-1024x588.jpeg?size=630x362&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 1: </strong>The Qwen3-VL architecture (source: <a href="https://arxiv.org/abs/2511.21631" target="_blank" rel="noreferrer noopener">Bai et al., 2025, Qwen Team</a>).</figcaption></figure></div>


<p>This vision encoder is trained on a carefully curated mixture of image and video data, ensuring strong performance across both image understanding tasks and video comprehension scenarios. The integration of vision and language modalities is achieved through an elegant architectural design that preserves the reasoning capabilities of the base language model while adding rich visual understanding.</p>



<p>The Qwen3-VL series offers multiple model sizes to accommodate different computational budgets and application requirements. The lineup includes compact models (e.g., Qwen3-VL-2B) designed for edge deployment and resource-constrained environments, mid-size variants (e.g., Qwen3-VL-4B and Qwen3-VL-8B) that balance performance and efficiency, and larger models up to Qwen3-VL-14B that push the boundaries of multimodal understanding.</p>



<p>Each model variant maintains the same architectural principles but scales the number of layers, attention heads, and hidden dimensions to achieve different capacity levels. All variants support extended context lengths, with smaller models handling 32K tokens and larger models supporting up to 128K tokens, enabling them to process long documents with multiple images or extended video sequences.</p>



<p>A key innovation in Qwen3-VL is the Time-aligned Multimodal Rotary Position Embedding (TM-RoPE), which extends the traditional Multimodal RoPE (M-RoPE) by incorporating explicit temporal information. TM-RoPE factorizes the conventional rotary position embedding into three distinct dimensions: temporal, height, and width. This design enables the model to effectively capture both fine-grained local temporal variations and long-range dependencies across video frames. </p>



<p>For text inputs, the three components share identical position identifiers, making TM-RoPE equivalent to one-dimensional RoPE. For images, a constant temporal ID is assigned to all visual tokens while their spatial positions determine the height and width IDs. For video, each frame receives a monotonically increasing temporal ID adjusted based on actual timestamps, ensuring consistent temporal resolution of 80 milliseconds per ID. This sophisticated positional encoding scheme enables seamless integration of information across diverse modalities.</p>



<p>The vision encoder processes visual inputs by first converting them into a format suitable for the transformer architecture. For images, the encoder divides the input into patches and projects these patches into the model’s hidden dimension. For videos, frames are sampled at a dynamic frame rate to preserve video information while aligning with audio sampling rates in multimodal scenarios. The vision encoder outputs a sequence of visual tokens that are then concatenated with text tokens and processed by the unified transformer backbone. This design allows the model to attend to both visual and textual information jointly, enabling rich cross-modal reasoning. The model can identify objects, understand spatial relationships, read text within images through OCR capabilities, interpret charts and diagrams, and reason about sequences of events in videos.</p>



<p>Both Qwen3-VL-Instruct and Qwen3-VL-Thinking variants are available, mirroring the dual-mode capability of the text-only models. The Instruct variant provides fast, direct responses to visual questions, making it ideal for applications requiring low latency (e.g., real-time image analysis or interactive user interfaces). </p>



<p>The Thinking variant generates explicit reasoning traces that reveal the model’s step-by-step visual analysis process. When presented with a complex image, the Thinking model verbalizes its observations, identifies relevant details, makes connections between visual elements, and systematically works toward a conclusion. This transparency is invaluable for applications requiring explainable AI, educational tools where understanding the reasoning process is important, and debugging or improving system performance.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Training-Pipeline-Multimodal-Pretraining-Image-Text-Video-Text-Data"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Training-Pipeline-Multimodal-Pretraining-Image-Text-Video-Text-Data">Training Pipeline: Multimodal Pretraining with Image-Text and Video-Text Data</a></h3>



<p>The training of Qwen3-VL follows a 4-stage approach (<strong>Table 1</strong>) that builds visual understanding capabilities on top of the strong language foundation established during Qwen3’s pretraining. The training corpus includes diverse sources of image-text pairs and video-text sequences, covering a wide range of domains, styles, and complexity levels.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://pyimagesearch.com/wp-content/uploads/2026/07/image-2.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1001" height="175" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-2.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54508"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-2.png?size=126x22&lossy=2&strip=1&webp=1 126w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-2-300x52.png?lossy=2&strip=1&webp=1 300w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-2.png?size=378x66&lossy=2&strip=1&webp=1 378w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-2.png?size=504x88&lossy=2&strip=1&webp=1 504w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-2.png?size=630x110&lossy=2&strip=1&webp=1 630w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-2-768x134.png?lossy=2&strip=1&webp=1 768w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-2.png?lossy=2&strip=1&webp=1 1001w" sizes="(max-width: 1001px) 100vw, 1001px" /></a><figcaption class="wp-element-caption"><strong>Table 1: </strong>Training setup and hyperparameters across Qwen3-VL training stages (source: <a href="https://arxiv.org/abs/2511.21631" target="_blank" rel="noreferrer noopener">Bai et al., 2025, Qwen Team</a>).</figcaption></figure></div>


<p>The data encompasses natural images from everyday scenarios, professional photography, scientific charts and diagrams, screenshots of user interfaces, medical imagery, satellite imagery, artwork and historical photographs, and video sequences capturing dynamic events and actions. This diversity ensures the model develops robust visual understanding that generalizes well to novel scenarios.</p>



<p>The pretraining stage for Qwen3-VL employs a combination of objectives designed to align visual and textual representations. The primary training objective uses a contrastive learning approach similar to CLIP, where the model learns to associate images with their corresponding textual descriptions by maximizing the similarity between matching image-text pairs while minimizing similarity between non-matching pairs. </p>



<p>Additionally, the model is trained on image captioning tasks where it must generate descriptive text given an image, and visual question answering tasks where it must answer questions about image content. These complementary objectives encourage the model to develop both discriminative abilities (understanding what an image depicts) and generative abilities (producing accurate descriptions and responses).</p>



<p>A critical aspect of Qwen3-VL’s training is the integration of visual and language data at an early stage. Rather than training vision and language components separately and then attempting to bridge them, Qwen3-VL employs joint training from the beginning. This approach enables the model to learn shared representations that naturally capture cross-modal relationships. </p>



<p>The training data is carefully balanced to include both unimodal tasks (pure text or pure image understanding) and cross-modal tasks (image-text reasoning, visual question answering). This balance prevents modality-specific performance degradation (a common issue where improving one modality comes at the cost of another) and ensures the model maintains strong capabilities across all input types.</p>



<p>The vision encoder undergoes specialized training to extract meaningful features from images and videos. For static images, the encoder learns to identify salient objects, understand spatial relationships, recognize text through OCR, interpret abstract concepts like emotions or art styles, and extract information from specialized content (e.g., charts, graphs, and diagrams). </p>



<p>For video understanding, the encoder is trained to track objects across frames, understand temporal relationships and event sequences, recognize actions and activities, and maintain consistent object identity throughout clips. This comprehensive training regimen produces visual representations that are rich, detailed, and optimized for downstream reasoning tasks.</p>



<p>Post-training for Qwen3-VL follows a similar philosophy to the text-only models, with instruction tuning and reinforcement learning adapted for multimodal scenarios. The instruction tuning phase uses high-quality human-annotated image-text conversations where the model learns to follow user instructions that reference visual content. </p>



<p>These instructions span diverse task types (e.g., describing images in varying levels of detail, answering specific questions about image content, comparing multiple images, performing visual reasoning and inference, extracting structured information from images, and generating creative content inspired by images). The Thinking variant receives additional training on reasoning traces that explicitly verbalize the visual analysis process, teaching the model to describe what it observes, explain why certain observations are relevant, and show how visual evidence supports its conclusions.</p>



<p>Reinforcement learning fine-tuning (RLHF) further refines the model’s behavior based on human preferences. For multimodal tasks, this involves collecting feedback on the quality, accuracy, and relevance of responses to visual queries. </p>



<p>The model learns to prioritize responses that accurately describe visual content, provide helpful and relevant information, demonstrate appropriate levels of detail based on the query, acknowledge when visual information is ambiguous or unclear, and maintain consistency between visual observations and textual reasoning. For smaller Qwen3-VL models, knowledge distillation from larger variants transfers both visual understanding and reasoning capabilities, enabling compact models to achieve impressive performance despite their reduced parameter count.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Performance-Benchmarks-Image-Video-Multi-Image-Reasoning-Evaluation"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Performance-Benchmarks-Image-Video-Multi-Image-Reasoning-Evaluation">Performance Benchmarks: Image, Video, and Multi-Image Reasoning Evaluation</a></h3>



<p>Qwen3-VL demonstrates strong performance across a comprehensive suite of vision-language benchmarks, positioning it as a competitive open-source multimodal model. The model excels in traditional image understanding tasks (e.g., image classification, object detection, and visual question answering), while also showing strong capabilities in more challenging scenarios (e.g., multi-image reasoning, video understanding, and complex visual reasoning). </p>



<p>Across flagship benchmarks for evaluating vision-language models, Qwen3-VL consistently achieves results that rival or surpass much larger proprietary models, demonstrating the effectiveness of its architectural innovations and training methodology.</p>



<p>On general vision-language benchmarks, Qwen3-VL shows strong capabilities across multiple evaluation dimensions. For visual question answering tasks, the model demonstrates strong performance on datasets (e.g., ERQA and RealWorldQA) that require it to answer diverse questions about image content, ranging from simple object recognition to complex reasoning about relationships and attributes. On image captioning benchmarks (e.g., COCO and NoCaps), Qwen3-VL generates accurate, detailed, and fluent descriptions that capture both the main subjects and subtle details in images. </p>



<p>The model’s optical character recognition (OCR) capabilities are particularly strong (<strong>Figure 2</strong>), enabling it to accurately extract and understand text embedded within images across various fonts, layouts, and contexts.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://pyimagesearch.com/wp-content/uploads/2026/07/image-9.jpeg" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="999" height="562" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-9.jpeg?lossy=2&strip=1&webp=1" alt="" class="wp-image-54489"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-9.jpeg?size=126x71&lossy=2&strip=1&webp=1 126w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-9-300x169.jpeg?lossy=2&strip=1&webp=1 300w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-9.jpeg?size=378x213&lossy=2&strip=1&webp=1 378w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-9.jpeg?size=504x284&lossy=2&strip=1&webp=1 504w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-9.jpeg?size=630x354&lossy=2&strip=1&webp=1 630w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-9-768x432.jpeg?lossy=2&strip=1&webp=1 768w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-9.jpeg?lossy=2&strip=1&webp=1 999w" sizes="(max-width: 999px) 100vw, 999px" /></a><figcaption class="wp-element-caption"><strong>Figure 2: </strong>Multilingual OCR performance of Qwen3-VL on a self-built test set (source: <a href="https://arxiv.org/abs/2511.21631" target="_blank" rel="noreferrer noopener">Bai et al., 2025, Qwen Team</a>).</figcaption></figure></div>


<p>Multi-image reasoning represents a particularly challenging category where models must integrate information across multiple images to answer questions or perform comparisons. Qwen3-VL excels at these tasks, demonstrating the ability to identify similarities and differences between images, track objects or concepts across a sequence of images, aggregate information from multiple sources, and reason about relationships between distinct visual inputs. </p>



<p>This capability is crucial for applications (e.g., analyzing time-series imagery, comparing before-and-after scenarios, or understanding narratives told through image sequences). The model’s performance on benchmarks specifically designed to test multi-image understanding consistently ranks among the top open-source alternatives.</p>



<p>For video understanding, Qwen3-VL processes sequences of frames to understand temporal dynamics and event structures. The model achieves strong results on video question answering benchmarks where it must comprehend actions, events, and temporal relationships depicted in video clips. </p>



<p>It demonstrates the ability to recognize and track objects throughout videos, understand cause-and-effect relationships between events, identify the sequence and timing of actions, and answer questions requiring temporal reasoning (&#8220;What happened before/after X?&#8221;). The integration of temporal information through TM-RoPE enables the model to maintain coherent understanding across extended video sequences, a capability that distinguishes it from models that treat videos as disconnected frames.</p>



<p>Specialized benchmarks reveal Qwen3-VL’s capabilities in domain-specific tasks. On mathematical and scientific diagram understanding (e.g., charts, graphs, and geometric figures), the model demonstrates the ability to extract numerical information from visualizations, understand mathematical notation and symbols, reason about spatial relationships in geometry problems, and interpret scientific diagrams and schematics. </p>



<p>For document understanding tasks (<strong>Figure 3</strong>), including complex layouts with mixed text and images, Qwen3-VL shows strong performance in extracting information from receipts, invoices, and forms, understanding document structure and hierarchy, reading tables and structured data, and processing multi-page documents with consistent context.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://pyimagesearch.com/wp-content/uploads/2026/07/image-10.jpeg" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="959" height="914" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-10.jpeg?lossy=2&strip=1&webp=1" alt="" class="wp-image-54491"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-10.jpeg?size=126x120&lossy=2&strip=1&webp=1 126w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-10-300x286.jpeg?lossy=2&strip=1&webp=1 300w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-10.jpeg?size=378x360&lossy=2&strip=1&webp=1 378w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-10.jpeg?size=504x480&lossy=2&strip=1&webp=1 504w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-10.jpeg?size=630x600&lossy=2&strip=1&webp=1 630w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-10-768x732.jpeg?lossy=2&strip=1&webp=1 768w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-10.jpeg?lossy=2&strip=1&webp=1 959w" sizes="(max-width: 959px) 100vw, 959px" /></a><figcaption class="wp-element-caption"><strong>Figure 3: </strong>Qwen3-VL performance across image and video understanding benchmarks (source: <a href="https://arxiv.org/abs/2511.21631" target="_blank" rel="noreferrer noopener">Bai et al., 2025, Qwen Team</a>).</figcaption></figure></div>


<p>When comparing Instruct and Thinking variants, the Thinking model demonstrates particular advantages on tasks requiring complex reasoning or multi-step analysis. While the Instruct variant provides faster responses suitable for straightforward queries, the Thinking variant’s explicit reasoning traces lead to improved accuracy on challenging problems. </p>



<p>Users can observe the model systematically analyzing visual information, identifying relevant details, making intermediate inferences, and arriving at well-justified conclusions. This transparency not only improves performance on difficult tasks but also enables debugging, validation, and trust-building in deployment scenarios. </p>



<p>The Thinking variant shows the largest performance improvements over Instruct on tasks involving visual reasoning chains, ambiguous or complex images requiring careful analysis, questions that require synthesizing information from multiple parts of an image, and scenarios where explainability is valued alongside accuracy (<strong>Figure 4</strong>).</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://pyimagesearch.com/wp-content/uploads/2026/07/image-11.jpeg" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="878" height="917" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-11.jpeg?lossy=2&strip=1&webp=1" alt="" class="wp-image-54494"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-11.jpeg?size=126x132&lossy=2&strip=1&webp=1 126w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-11-287x300.jpeg?lossy=2&strip=1&webp=1 287w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-11.jpeg?size=378x395&lossy=2&strip=1&webp=1 378w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-11.jpeg?size=504x526&lossy=2&strip=1&webp=1 504w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-11.jpeg?size=630x658&lossy=2&strip=1&webp=1 630w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-11-768x802.jpeg?lossy=2&strip=1&webp=1 768w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-11.jpeg?lossy=2&strip=1&webp=1 878w" sizes="(max-width: 878px) 100vw, 878px" /></a><figcaption class="wp-element-caption"><strong>Figure 4: </strong>Qwen3-VL-Thinking performance across image and video understanding benchmarks (source: <a href="https://arxiv.org/abs/2511.21631" target="_blank" rel="noreferrer noopener">Bai et al., 2025, Qwen Team</a>).</figcaption></figure></div>


<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Implementation-Building-Multimodal-Chatbot-Qwen3-VL-Gradio"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Implementation-Building-Multimodal-Chatbot-Qwen3-VL-Gradio">Implementation: Building a Multimodal Chatbot with Qwen3-VL and Gradio</a></h2>



<p>Now, let us build on our foundation from Lesson 1 to create a multimodal chatbot that can understand and reason about images alongside text. We will integrate Qwen3-VL models and extend the Gradio interface to support image uploads.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Step-1-Installing-Dependencies-Qwen3-VL-Multimodal-Processing-PyTorch-Transformers-Gradio"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Step-1-Installing-Dependencies-Qwen3-VL-Multimodal-Processing-PyTorch-Transformers-Gradio">Step 1: Installing Dependencies for Qwen3-VL and Multimodal Processing (PyTorch, Transformers, Gradio)</a></h3>



<p>In addition to the packages from Lesson 1, we need a few more libraries for handling images and multimodal processing.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Building a Multimodal Chatbot with Qwen3-VL Instruct and Thinking Models" data-enlighter-group="1">!pip install torch transformers accelerate gradio
!pip install flash-attn --no-build-isolation
!pip install qwen-vl-utils pillow
print("\n✅ Dependencies installed successfully!")
</pre>



<p>On <strong>Lin</strong><strong>e 1</strong>, we install the same core dependencies as Lesson 1: PyTorch, Transformers, Accelerate, and Gradio. On <strong>Line 2</strong>, we include Flash Attention for optimized inference. On <strong>Line 3</strong>, we add 2 new packages: <code data-enlighter-language="python" class="EnlighterJSRAW">qwen-vl-utils</code> provides utilities for processing vision inputs specific to Qwen3-VL models, including helper functions for formatting multimodal conversations, and <code data-enlighter-language="python" class="EnlighterJSRAW">pillow</code> is Python’s standard image-processing library for loading, manipulating, and displaying images. These additional dependencies enable our chatbot to seamlessly handle visual inputs alongside text. On <strong>Line 4</strong>, we print a confirmation message. </p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Step-2-Importing-Required-Libraries"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Step-2-Importing-Required-Libraries">Step 2: Importing Required Libraries</a></h3>



<p>We extend our imports from Lesson 1 to include image processing capabilities.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Building a Multimodal Chatbot with Qwen3-VL Instruct and Thinking Models" data-enlighter-group="2">import torch
from transformers import pipeline
import gradio as gr
from typing import List, Tuple, Optional
from PIL import Image
import requests
from io import BytesIO
from qwen_vl_utils import process_vision_info
from IPython.display import display, Markdown

print(f"PyTorch version: {torch.__version__}")
print(f"CUDA available: {torch.cuda.is_available()}")
if torch.cuda.is_available():
    print(f"CUDA device: {torch.cuda.get_device_name(0)}")
</pre>



<p>On <strong>Lines 1-9</strong>, we import all necessary modules for our multimodal application. Beyond the basic imports from Lesson 1, we add <code data-enlighter-language="python" class="EnlighterJSRAW">Image</code> from PIL for image manipulation, <code data-enlighter-language="python" class="EnlighterJSRAW">requests</code> and <code data-enlighter-language="python" class="EnlighterJSRAW">BytesIO</code> for downloading and handling image data from URLs, and <code data-enlighter-language="python" class="EnlighterJSRAW">process_vision_info</code> from <code data-enlighter-language="python" class="EnlighterJSRAW">qwen_vl_utils</code> for preprocessing vision inputs in the format expected by Qwen3-VL models. The IPython display imports help us visualize images and formatted text in Jupyter notebooks. On <strong>Lines 11-14</strong>, we perform the same environment checks as before to verify PyTorch installation and GPU availability.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Step-3-Initializing-Qwen3-VL-Instruct-Thinking-Image-Text-to-Text-Pipelines"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Step-3-Initializing-Qwen3-VL-Instruct-Thinking-Image-Text-to-Text-Pipelines">Step 3: Initializing Qwen3-VL Instruct and Thinking Image-Text-to-Text Pipelines</a></h3>



<p>Now we initialize the Qwen3-VL pipelines that can process both images and text.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Building a Multimodal Chatbot with Qwen3-VL Instruct and Thinking Models" data-enlighter-group="3">print("=" * 60)
print("Initializing Qwen3-VL-2B-Instruct and Qwen3-VL-2B-Thinking Text Generation Pipelines")
print("=" * 60)

qwen3vl_instruct = pipeline("image-text-to-text", model="Qwen/Qwen3-VL-2B-Instruct")
qwen3vl_thinking = pipeline("image-text-to-text", model="Qwen/Qwen3-VL-2B-Thinking")

print("\n✅ Pipelines initialized successfully!")
</pre>



<p>On <strong>Lines 1-3</strong>, we print informative messages to track initialization progress. On <strong>Lines 5 and 6</strong>, we initialize 2 pipelines using the <code data-enlighter-language="python" class="EnlighterJSRAW">"image-text-to-text"</code> task type instead of <code data-enlighter-language="python" class="EnlighterJSRAW">"text-generation"</code> from Lesson 1. This task type indicates that the pipeline accepts both images and text as input and generates text as output. </p>



<p>We use the Qwen3-VL-2B variants, which offer excellent performance while remaining lightweight enough for efficient inference. The models automatically download from Hugging Face if not cached locally (approximately 4-5 GB each for the 2B parameter versions). These pipelines will handle all the complexity of encoding images, combining them with text, and generating appropriate responses.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Step-4-Testing-Multimodal-Conversations-Image-Uploads-Text-Prompts"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Step-4-Testing-Multimodal-Conversations-Image-Uploads-Text-Prompts">Step 4: Testing Multimodal Conversations with Image Uploads and Text Prompts</a></h3>



<p>Let us test the models with a conversation that includes images to understand their multimodal capabilities.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Building a Multimodal Chatbot with Qwen3-VL Instruct and Thinking Models" data-enlighter-group="4"># Initialize conversation history
conversation = []

# First message with image
img1 = Image.open(BytesIO(requests.get("https://media.istockphoto.com/photos/dogs-playing-picture-id481634156", timeout=10).content))
user_msg_1 = "Describe the image briefly."
conversation.append({"role": "user", "content": [{"type": "text", "text": user_msg_1}, {"type": "image", "image": img1}]})
display(Markdown(f"**User**: {user_msg_1}"))
display(img1)

response_1 = qwen3vl_instruct(conversation, do_sample=False, max_new_tokens=1024, return_full_text=False)
response_1 = response_1[0]['generated_text']
display(Markdown(f"\n**Assistant**: {response_1}\n"))

# Update history
conversation.append({"role": "assistant", "content": [{"type": "text", "text": response_1}]})

# Second message with different image (continuation)
img2 = Image.open(BytesIO(requests.get("https://th.bing.com/th/id/OIP.i7RVdGQWnsiTssgbUeCmsAHaLG", timeout=10).content))
user_msg_2 = "Differentiate between first and second image."
conversation.append({"role": "user", "content": [{"type": "text", "text": user_msg_2}, {"type": "image", "image": img2}]})
display(Markdown(f"**User**: {user_msg_2}"))
display(img2)

response_2 = qwen3vl_thinking(conversation, do_sample=False, max_new_tokens=1024, return_full_text=False)
trace = response_2[0]['generated_text'].split('&lt;/think>')[0]
response_2 = response_2[0]['generated_text'].split('&lt;/think>')[1]
response_2 = (
    "&lt;details>&lt;summary>Show trace&lt;/summary>\n\n"
    "```text\n" + (trace or "").strip() + "\n```\n"
    "&lt;/details>\n\n"
    + (response_2 or "")
)
display(Markdown(f"\nAssistant: {response_2}"))
</pre>



<p>On <strong>Line 2</strong>, we initialize an empty conversation list as before. On <strong>Lines 5-7</strong>, we download an image from a URL using the requests library, load it into a PIL Image object, and create the first user message. Note the new format on <strong>Line 7</strong>: instead of a simple string, the content is now a list containing both text and image dictionaries. This structure allows us to include multiple modalities in a single message. On <strong>Lines 8 and 9</strong>, we display both the text query and the image for visibility.</p>



<p>On <strong>Lines 11-13</strong>, we generate a response using the Instruct model with the same parameters as Lesson 1. The model processes both the text query and the image, generating a description that demonstrates visual understanding. On <strong>Line 16</strong>, we update the conversation history with the assistant’s response, formatting it as a text-type content entry.</p>



<p>On <strong>Lines 19-23</strong>, we introduce a second image and ask a comparative question that requires the model to recall information from the first image while analyzing the second. This tests the model’s ability to maintain visual context across conversation turns. On <strong>Lines 25-33</strong>, we switch to the Thinking model for the response. As in Lesson 1, we parse the thinking trace from the final answer and format it as collapsible HTML. The thinking trace now reveals not just textual reasoning but also how the model analyzes visual information: describing what it observes in each image, identifying key differences, and building toward a coherent comparative answer.</p>



<p><strong>Figure 5 </strong>shows the output of the code snippet above, demonstrating the reasoning capabilities of both models.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/07/image-1-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="618" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-1-1024x618.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54498"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-1-1024x618.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-1-1024x618.png?size=126x76&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-1-1024x618.png?size=252x152&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-1-1024x618.png?size=378x228&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-1-1024x618.png?size=504x304&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-1-1024x618.png?size=630x380&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 5: </strong>Sample conversation using Qwen3-VL-Instruct and Qwen3-VL-Thinking models (source: author).</figcaption></figure></div>


<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Step-5-Building-Gradio-Multimodal-Chat-Interface-Image-Input-Support"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Step-5-Building-Gradio-Multimodal-Chat-Interface-Image-Input-Support">Step 5: Building a Gradio Multimodal Chat Interface with Image Input Support</a></h3>



<p>Now we will build a comprehensive Gradio interface that supports image uploads alongside text input.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Building a Multimodal Chatbot with Qwen3-VL Instruct and Thinking Models" data-enlighter-group="5">import base64

def create_chatbot_interface(chatbot, thinking_chatbot):
    """
    Gradio interface for multimodal chatbot interaction
    """

    def pil_to_base64(img):
        buf = BytesIO()
        img.save(buf, format="PNG")
        return "data:image/png;base64," + base64.b64encode(buf.getvalue()).decode()

    def add_user_message(message: str, image, conversation, history):
        if not message.strip():
            return history, ""
        if history is None:
            history = []
        conversation.append({"role": "user", "content": [{"type": "text", "text": message}]})
        if image is not None:
            conversation.append({"role": "user", "content": [{"type": "image", "image": image}]})

        display_text = message or ""
        if image is not None:
            img_str = pil_to_base64(image)
            display_text += f"\n\n![uploaded image]({img_str})"
        history.append([display_text, None])

        return history, "", None   # show user message immediately
</pre>



<p>On <strong>Line 1</strong>, we import the <code data-enlighter-language="python" class="EnlighterJSRAW">base64</code> module for encoding images as strings. On <strong>Lines 3-6</strong>, we define our main interface function with a docstring explaining its purpose. On <strong>Lines 8-11</strong>, we define a helper function <code data-enlighter-language="python" class="EnlighterJSRAW">pil_to_base64</code> that converts PIL images to base64-encoded strings. This is necessary because we want to display uploaded images directly in the chat history. The function resizes images to 256×256 pixels for efficient display and encodes them as PNG data URLs.</p>



<p>On <strong>Lines 13-28</strong>, we define the <code data-enlighter-language="python" class="EnlighterJSRAW">add_user_message</code> function, which now handles both text and optional image inputs. On <strong>Line</strong><strong>s</strong><strong> 14-17</strong>, we validate that the message is not empty and initialize history if needed. On <strong>Lines 18-20</strong>, we append the text content to the conversation and, if an image is provided, append it as a separate content entry with type <code data-enlighter-language="python" class="EnlighterJSRAW">"image"</code>. </p>



<p>This format matches what Qwen3-VL expects. On <strong>Lines 22-26</strong>, we create a display string for the chat history. If an image was uploaded, we convert it to a base64 data URL and embed it using markdown image syntax, allowing Gradio to render it directly in the chatbot UI. On <strong>Line 28</strong>, we return the updated history, clear the text input, and clear the image input, providing immediate visual feedback.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Building a Multimodal Chatbot with Qwen3-VL Instruct and Thinking Models" data-enlighter-group="6">def chat_function(message: str, conversation, history, model_choice: str):
        try:
            if model_choice == "Thinking":
                response = thinking_chatbot(conversation, do_sample=False, max_new_tokens=1024, return_full_text=False)
                trace = response[0]['generated_text'].split('&lt;/think>')[0]
                response = response[0]['generated_text'].split('&lt;/think>')[1]
                assistant_text = (
                    "&lt;details>&lt;summary>Show thinking trace&lt;/summary>\n\n"
                    "```text\n" + (trace or "").strip() + "\n```\n"
                    "&lt;/details>\n\n"
                    + (response or "")
                )
            else:
                response = chatbot(conversation, do_sample=False, max_new_tokens=1024, return_full_text=False)
                response = response[0]['generated_text']
                assistant_text = response or ""

            conversation.append({"role": "assistant", "content": [{"type": "text", "text": assistant_text}]})
            history[-1][1] = assistant_text
            return history, "", None
        except Exception as e:
            history[-1][1] = f"Exception: {e}"
            return history, "", None
</pre>



<p>On <strong>Lines 1-23</strong>, we define the core chat function that generates responses. The logic is nearly identical to Lesson 1, but now it handles multimodal conversation contexts. On <strong>Lines 3-12</strong>, if Thinking Mode is selected, we generate a response with reasoning traces and format them as collapsible details. On <strong>Lines 13-16</strong>, if Instruct Mode is selected, we generate a direct response. The models automatically process any images in the conversation context without us needing to explicitly pass them again, since the conversation list maintains the complete multimodal history. On <strong>Lines 18-23</strong>, we update the conversation with the assistant’s response and handle any exceptions gracefully.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Building a Multimodal Chatbot with Qwen3-VL Instruct and Thinking Models" data-enlighter-group="7">    with gr.Blocks() as interface:
        gr.Markdown("## 🤖 Qwen3-VL-2B Multimodal Chatbot with Deep Thinking")

        with gr.Row():
            chatbot_ui = gr.Chatbot(scale=4, height=1000)

        with gr.Row():
            msg = gr.Textbox(placeholder="Type your message here...", scale=8)
            image_input = gr.Image(
                label="Upload Image (optional)",
                type="pil",
                scale=1
            )
            send_btn = gr.Button("📤 Send", scale=1)
            stop_btn = gr.Button("⏹️ Stop", scale=1)
            model_selector = gr.Dropdown(
                choices=["Instruct", "Thinking"],
                value="Instruct",
                label="Model selection",
                scale=2
            )

        history_state = gr.State([])
        conversation_state = gr.State([])

        # Step 1: Show user message immediately
        send_btn.click(
            add_user_message,
            inputs=[msg, image_input, conversation_state, history_state],
            outputs=[chatbot_ui, msg, image_input],
        )

        # Step 2: Then process with chatbot
        send_event = send_btn.click(
            chat_function,
            inputs=[msg, conversation_state, history_state, model_selector],
            outputs=[chatbot_ui, msg, image_input],
        )

        stop_btn.click(None, None, None, cancels=[send_event])

    return interface
</pre>



<p>On <strong>Lines 1 and 2</strong>, we create the Gradio interface with an updated title reflecting multimodal capabilities. On <strong>Lines 4 and 5</strong>, we create the chatbot display area. On <strong>Lines 7-21</strong>, we build the input row with several components: a text box for messages (<strong>Line 8</strong>), an image upload widget that accepts PIL images (<strong>Lines 9-13</strong>), send and stop buttons (<strong>Lines 14 and 15</strong>), and a model selector dropdown (<strong>Lines 16-21</strong>). The <code data-enlighter-language="python" class="EnlighterJSRAW">type="pil"</code> parameter on the image input ensures uploaded images are automatically converted to PIL Image objects.</p>



<p>On <strong>Lines 23 and 24</strong>, we initialize state variables for tracking conversation history and display state. On <strong>Lines 27-31</strong>, we configure the send button’s first action to immediately display the user’s message and uploaded image. Note that <code data-enlighter-language="python" class="EnlighterJSRAW">image_input</code> is now included in both inputs and outputs, allowing us to clear it after sending. On <strong>Lines 34-38</strong>, we configure the send button’s second action to process the message with the selected model. On <strong>Line 40</strong>, we wire up the stop button to cancel ongoing generation.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Step-6-Launching-Qwen3-VL-Multimodal-Chatbot-Application"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Step-6-Launching-Qwen3-VL-Multimodal-Chatbot-Application">Step 6: Launching the Qwen3-VL Multimodal Chatbot Application</a></h3>



<p>Finally, we create and launch our multimodal chatbot interface.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Building a Multimodal Chatbot with Qwen3-VL Instruct and Thinking Models" data-enlighter-group="8"># Create the interface
interface = create_chatbot_interface(qwen3vl_instruct, qwen3vl_thinking)
print("✅ Gradio interface created!")

print("Launching Gradio interface...")
print("Access the chatbot at: http://localhost:7860")
print("Press the 'Stop' button in the output to stop the server\n")

interface.launch()
</pre>



<p>On <strong>Line 2</strong>, we instantiate the interface by passing both VL model pipelines to our creation function. On <strong>Lines 5-7</strong>, we print informative messages about accessing the application. On <strong>Line 9</strong>, we launch the Gradio interface on the default port. Users can now interact with a fully multimodal chatbot that understands and reasons about both text and images.</p>



<p>They can upload images individually or alongside text queries, ask questions about uploaded images, request comparisons between multiple images across the conversation, and switch between Instruct and Thinking Modes to see how the model analyzes visual information. The interface provides a seamless, intuitive way to explore Qwen3-VL’s powerful multimodal capabilities.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Multimodal-Chatbot-Results-Instruct-Mode-vs-Thinking-Mode-Analysis"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Multimodal-Chatbot-Results-Instruct-Mode-vs-Thinking-Mode-Analysis">Multimodal Chatbot Results: Instruct Mode vs Thinking Mode Analysis</a></h2>



<p>To illustrate how our chatbot adapts between <strong>Instruct Mode</strong> and <strong>Thinking Mode</strong>, we tested it on 2 different multimodal tasks. Below, we start with the concise instructive response, then show how the same system expands into deeper reasoning when Thinking Mode is enabled.</p>



<p>In <strong>Figure 6</strong>, we tried the chatbot in Instruct Mode, where it delivered a clear and balanced summary: sales across America, EMEA (<strong>Europe, the Middle East, and Africa</strong>), and Asia increased steadily over 4 years, with the strongest growth in Year 4. It also provided exact figures per region and year, but kept the explanation concise enough to avoid overwhelming detail.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/07/image-12-scaled.jpeg" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="643" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-12-1024x643.jpeg?lossy=2&strip=1&webp=1" alt="" class="wp-image-54501"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-12-1024x643.jpeg?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-12-1024x643.jpeg?size=126x79&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-12-1024x643.jpeg?size=252x158&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-12-1024x643.jpeg?size=378x237&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-12-1024x643.jpeg?size=504x316&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-12-1024x643.jpeg?size=630x396&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 6: </strong>Sample conversation with Multimodal Chatbot in Instruct Mode (source: author).</figcaption></figure></div>


<p>This demonstrates how <strong>Instruct Mode</strong> excels at giving <strong>direct, useful insights</strong> from visual inputs, ideal for users who want quick answers.</p>



<p>In <strong>Figure 7, </strong>we uploaded a cartoon-style puzzle showing 2 forest scenes and asked the chatbot to “Spot the difference between both the images. Answer briefly.”</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/07/image-13-scaled.jpeg" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="649" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-13-1024x649.jpeg?lossy=2&strip=1&webp=1" alt="" class="wp-image-54503"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-13-1024x649.jpeg?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-13-1024x649.jpeg?size=126x80&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-13-1024x649.jpeg?size=252x160&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-13-1024x649.jpeg?size=378x240&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-13-1024x649.jpeg?size=504x319&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/07/image-13-1024x649.jpeg?size=630x399&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 7: </strong>Sample conversation with Multimodal Chatbot in Thinking Mode (source: author).</figcaption></figure></div>


<p>In Thinking Mode, the chatbot does not just state the differences; it walks through the reasoning: identifying the animals in each scene, comparing them, and concluding that the bottom image contains a zebra and an orange bird instead of the pink flamingo in the top image.</p>



<p>This shows how Thinking Mode provides step-by-step transparency, making the reasoning process visible and trustworthy.</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<div id="pitch" style="padding: 40px; width: 100%; background-color: #F4F6FA;">
	<h3>What's next? We recommend <a target="_blank" href="https://pyimagesearch.com/pyimagesearch-university/?utm_source=blogPost&utm_medium=bottomBanner&utm_campaign=What%27s%20next%3F%20I%20recommend">PyImageSearch University</a>.</h3>

	<script src="https://fast.wistia.com/embed/medias/kno0cmko2z.jsonp" async></script><script src="https://fast.wistia.com/assets/external/E-v1.js" async></script><div class="wistia_responsive_padding" style="padding:56.25% 0 0 0;position:relative;"><div class="wistia_responsive_wrapper" style="height:100%;left:0;position:absolute;top:0;width:100%;"><div class="wistia_embed wistia_async_kno0cmko2z videoFoam=true" style="height:100%;position:relative;width:100%"><div class="wistia_swatch" style="height:100%;left:0;opacity:0;overflow:hidden;position:absolute;top:0;transition:opacity 200ms;width:100%;"><img decoding="async" src="https://fast.wistia.com/embed/medias/kno0cmko2z/swatch" style="filter:blur(5px);height:100%;object-fit:contain;width:100%;" alt="" aria-hidden="true" onload="this.parentNode.style.opacity=1;" /></div></div></div></div>

	<div style="margin-top: 32px; margin-bottom: 32px; ">
		<strong>Course information:</strong><br/>
		120+ total classes • 115+ hours hours of on-demand code walkthrough videos • Last updated: August 2026<br/>
		<span style="color: #169FE6;">★★★★★</span> 4.84 (128 Ratings) • 16,000+ Students Enrolled
	</div>

	<p><strong>I strongly believe that if you had the right teacher you could <em>master</em> computer vision and deep learning.</strong></p>

	<p>Do you think learning computer vision and deep learning has to be time-consuming, overwhelming, and complicated? Or has to involve complex mathematics and equations? Or requires a degree in computer science?</p>

	<p>That’s <em>not</em> the case.</p>

	<p>All you need to master computer vision and deep learning is for someone to explain things to you in <em>simple, intuitive</em> terms. <em>And that’s exactly what I do</em>. My mission is to change education and how complex Artificial Intelligence topics are taught.</p>

	<p>If you're serious about learning computer vision, your next stop should be PyImageSearch University, the most comprehensive computer vision, deep learning, and OpenCV course online today. Here you’ll learn how to <em>successfully</em> and <em>confidently</em> apply computer vision to your work, research, and projects. Join me in computer vision mastery.</p>

	<p><strong>Inside PyImageSearch University you'll find:</strong></p>

	<ul style="margin-left: 0px;">
		<li style="list-style: none;">&check; <strong>120+ courses</strong> on essential computer vision, deep learning, and OpenCV topics</li>
		<li style="list-style: none;">&check; <strong>94+ Certificates</strong> of Completion</li>
		<li style="list-style: none;">&check; <strong>115+ hours hours</strong> of on-demand video</li>
		<li style="list-style: none;">&check; <strong>Brand new courses released <em>regularly</em></strong>, ensuring you can keep up with state-of-the-art techniques</li>
		<li style="list-style: none;">&check; <strong>Pre-configured Jupyter Notebooks in Google Colab</strong></li>
		<li style="list-style: none;">&check; Run all code examples in your web browser — works on Windows, macOS, and Linux (no dev environment configuration required!)</li>
		<li style="list-style: none;">&check; Access to <strong>centralized code repos for <em>all</em> 540+ tutorials</strong> on PyImageSearch</li>
		<li style="list-style: none;">&check; <strong> Easy one-click downloads</strong> for code, datasets, pre-trained models, etc.</li>
		<li style="list-style: none;">&check; <strong>Access</strong> on mobile, laptop, desktop, etc.</li>
	</ul>

	<p style="text-align: center;">
		<a target="_blank" class="button link" href="https://pyimagesearch.com/pyimagesearch-university/?utm_source=blogPost&utm_medium=bottomBanner&utm_campaign=What%27s%20next%3F%20I%20recommend" style="background-color: #6DC713; border-bottom: none;">Click here to join PyImageSearch University</a>
	</p>
</div>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Summary"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Summary">Summary</a></h2>



<p>Throughout this lesson, we have explored Qwen3-VL and its remarkable multimodal capabilities that enable AI systems to understand and reason about visual information alongside text. We began by understanding the architectural innovations that make Qwen3-VL possible, including the SigLIP2-based vision encoder with 543 million parameters, the sophisticated TM-RoPE positional encoding that seamlessly integrates temporal, height, and width dimensions, and the joint training approach that prevents modality-specific performance degradation. </p>



<p>We learned how the model processes images by dividing them into patches, videos by sampling frames at dynamic rates, and maintains consistent understanding across extended sequences through absolute temporal encoding. The availability of both Instruct and Thinking variants provides flexibility between fast responses and transparent, step-by-step visual reasoning.</p>



<p>We then translated this theoretical knowledge into a practical implementation by extending our chatbot from Lesson 1 with multimodal capabilities. Through hands-on coding, we learned how to install and import additional dependencies for image processing, initialize vision-language pipelines using the &#8220;image-text-to-text&#8221; task type, structure multimodal conversations with content lists containing both text and image entries, and create a Gradio interface that supports image uploads alongside text input. </p>



<p>The implementation demonstrated key patterns for multimodal development: embedding images as base64 strings for display, maintaining visual context across conversation turns, parsing and displaying thinking traces for visual reasoning, and handling the complexity of mixed-modality inputs with clean, modular code. We saw firsthand how the Thinking model verbalizes its visual analysis, describing observations, identifying relevant details, and building toward well-reasoned conclusions.</p>



<p>This lesson represents a crucial step forward in our journey to build a comprehensive AI assistant. We have progressed from text-only interaction to sophisticated multimodal understanding, enabling applications such as visual question answering, image description and captioning, multi-image comparison and analysis, and video understanding through temporal reasoning. </p>



<p>In the next lesson (Lesson 3) of our series, we will add Qwen3-Guard to introduce safety moderation that protects users from harmful content in both text and image inputs. Following that (Lesson 4), we will integrate Qwen3-Embedding to enable retrieval-augmented generation, allowing our chatbot to search through knowledge bases and ground its responses in retrieved information. By combining these components (language understanding, visual reasoning, safety checks, and knowledge retrieval), we are building toward a production-ready multimodal AI assistant that demonstrates the full potential of the Qwen3 ecosystem.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Citation-Information"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Citation-Information">Citation Information</a></h3>



<p><strong>Mangla, P</strong><strong>. </strong>“Building a Multimodal Chatbot with Qwen3-VL Instruct and Thinking Models,” <em>PyImageSearch</em>, S. Huot, A. Sharma, and P. Thakur, eds., 2026, <a href="https://pyimg.co/jf6oe" target="_blank" rel="noreferrer noopener">https://pyimg.co/jf6oe</a> </p>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="classic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="Building a Multimodal Chatbot with Qwen3-VL Instruct and Thinking Models" data-enlighter-group="9">@incollection{Mangla_2026_building-multimodal-chatbot-qwen3-vl-instruct-thinking-models,
  author = {Puneet Mangla},
  title = {{Building a Multimodal Chatbot with Qwen3-VL Instruct and Thinking Models}},
  booktitle = {PyImageSearch},
  editor = {Susan Huot and Aditya Sharma and Piyush Thakur},
  year = {2026},
  url = {https://pyimg.co/jf6oe},
}
</pre>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p><strong>To download the source code to this post (and be notified when future tutorials are published here on PyImageSearch), </strong><em><strong>simply enter your email address in the form below!</strong></em></p>



<div id="download-the-code" class="post-cta-wrap">
<div class="gpd-post-cta">
	<div class="gpd-post-cta-content">
		

			<div class="gpd-post-cta-top">
				<div class="gpd-post-cta-top-image"><img decoding="async" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2020/01/cta-source-guide-1.png?lossy=2&strip=1&webp=1" alt="" srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2020/01/cta-source-guide-1.png?lossy=2&strip=1&webp=1 410w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2020/01/cta-source-guide-1.png?size=126x174&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2020/01/cta-source-guide-1.png?size=252x348&lossy=2&strip=1&webp=1 252w" sizes="(max-width: 410px) 100vw, 410px" /></div>
				
				<div class="gpd-post-cta-top-title"><h4>Download the Source Code and FREE 17-page Resource Guide</h4></div>
				<div class="gpd-post-cta-top-desc"><p>Enter your email address below to get a .zip of the code and a <strong>FREE 17-page Resource Guide on Computer Vision, OpenCV, and Deep Learning.</strong> Inside you'll find my hand-picked tutorials, books, courses, and libraries to help you master CV and DL!</p></div>


			</div>

			<div class="gpd-post-cta-bottom">
				<form id="footer-cta-code" class="footer-cta" action="https://www.getdrip.com/forms/4130035/submissions" method="post" target="blank" data-drip-embedded-form="4130035">
					<input name="fields[email]" type="email" value="" placeholder="Your email address" class="form-control" />

					<button type="submit">Download the code!</button>

					<div style="display: none;" aria-hidden="true"><label for="website">Website</label><br /><input type="text" id="website" name="website" tabindex="-1" autocomplete="false" value="" /></div>
				</form>
			</div>


		
	</div>

</div>
</div>
<p>The post <a rel="nofollow" href="https://pyimagesearch.com/2026/07/06/building-a-multimodal-chatbot-with-qwen3-vl-instruct-and-thinking-models/">Building a Multimodal Chatbot with Qwen3-VL Instruct and Thinking Models</a> appeared first on <a rel="nofollow" href="https://pyimagesearch.com">PyImageSearch</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Building an Intelligent Chatbot with Qwen3 Instruct and Thinking Models</title>
		<link>https://pyimagesearch.com/2026/06/29/building-an-intelligent-chatbot-with-qwen3-instruct-and-thinking-models/</link>
		
		<dc:creator><![CDATA[Puneet Mangla]]></dc:creator>
		<pubDate>Mon, 29 Jun 2026 12:45:00 +0000</pubDate>
				<category><![CDATA[Chatbot]]></category>
		<category><![CDATA[Gradio]]></category>
		<category><![CDATA[Qwen3]]></category>
		<category><![CDATA[Qwen3-32B]]></category>
		<category><![CDATA[Qwen3-4B]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[chatbot]]></category>
		<category><![CDATA[gradio]]></category>
		<category><![CDATA[qwen3]]></category>
		<category><![CDATA[qwen3-32b]]></category>
		<category><![CDATA[qwen3-4b]]></category>
		<category><![CDATA[tutorial]]></category>
		<guid isPermaLink="false">https://pyimagesearch.com/?p=54400</guid>

					<description><![CDATA[<p>Table of Contents Building an Intelligent Chatbot with Qwen3 Instruct and Thinking Models Qwen3 Model Details Qwen3 Model Architecture: Dense Models, MoE Variants, and Dual-Mode Reasoning Qwen3 Training Data and Post-Training Pipeline for Reasoning and Instruction Following Qwen3 Benchmark Performance:&#8230;</p>
<p>The post <a rel="nofollow" href="https://pyimagesearch.com/2026/06/29/building-an-intelligent-chatbot-with-qwen3-instruct-and-thinking-models/">Building an Intelligent Chatbot with Qwen3 Instruct and Thinking Models</a> appeared first on <a rel="nofollow" href="https://pyimagesearch.com">PyImageSearch</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<hr class="wp-block-separator has-alpha-channel-opacity" id="TOC"/>


<div class="yoast-breadcrumbs"><span><span><a href="https://pyimagesearch.com/">Home</a></span></div>


<div class="toc">
<hr class="TOC"/>
<p class="has-large-font-size"><strong>Table of Contents</strong></p>
<ul>
    <li id="TOC-h1-Building-Intelligent-Chatbot-Qwen3-Instruct-Thinking-Models"><a rel="noopener" target="_blank" href="#h1-Building-Intelligent-Chatbot-Qwen3-Instruct-Thinking-Models">Building an Intelligent Chatbot with Qwen3 Instruct and Thinking Models</a></li>

    <li id="TOC-h2-Qwen3-Model-Details"><a rel="noopener" target="_blank" href="#h2-Qwen3-Model-Details">Qwen3 Model Details</a></li>
    <ul>
        <li id="TOC-h3-Qwen3-Model-Architecture-Dense-Models-MoE-Variants-Dual-Mode-Reasoning"><a rel="noopener" target="_blank" href="#h3-Qwen3-Model-Architecture-Dense-Models-MoE-Variants-Dual-Mode-Reasoning">Qwen3 Model Architecture: Dense Models, MoE Variants, and Dual-Mode Reasoning</a></li>
        <li id="TOC-h3-Qwen3-Training-Data-Post-Training-Pipeline-Reasoning-Instruction-Following"><a rel="noopener" target="_blank" href="#h3-Qwen3-Training-Data-Post-Training-Pipeline-Reasoning-Instruction-Following">Qwen3 Training Data and Post-Training Pipeline for Reasoning and Instruction Following</a></li>
        <li id="TOC-h3-Qwen3-Benchmark-Performance-Thinking-Budgets-Reasoning-Coding-STEM-Tasks"><a rel="noopener" target="_blank" href="#h3-Qwen3-Benchmark-Performance-Thinking-Budgets-Reasoning-Coding-STEM-Tasks">Qwen3 Benchmark Performance: Thinking Budgets, Reasoning, Coding, and STEM Tasks</a></li>
    </ul>

    <li id="TOC-h2-Implementation-Building-Deep-Thinking-Chatbot-Qwen3-Gradio"><a rel="noopener" target="_blank" href="#h2-Implementation-Building-Deep-Thinking-Chatbot-Qwen3-Gradio">Implementation: Building a Deep Thinking Chatbot with Qwen3 and Gradio</a></li>
    <ul>
        <li id="TOC-h3-Step-1-Install-Qwen3-Chatbot-Dependencies-PyTorch-Transformers-Gradio"><a rel="noopener" target="_blank" href="#h3-Step-1-Install-Qwen3-Chatbot-Dependencies-PyTorch-Transformers-Gradio">Step 1: Install Qwen3 Chatbot Dependencies with PyTorch, Transformers, and Gradio</a></li>
        <li id="TOC-h3-Step-2-Importing-Required-Libraries"><a rel="noopener" target="_blank" href="#h3-Step-2-Importing-Required-Libraries">Step 2: Importing Required Libraries</a></li>
        <li id="TOC-h3-Step-3-Initialize-Qwen3-Instruct-Qwen3-Thinking-Text-Generation-Pipelines"><a rel="noopener" target="_blank" href="#h3-Step-3-Initialize-Qwen3-Instruct-Qwen3-Thinking-Text-Generation-Pipelines">Step 3: Initialize Qwen3 Instruct and Qwen3 Thinking Text-Generation Pipelines</a></li>
        <li id="TOC-h3-Step-4-Test-Qwen3-Instruct-vs-Thinking-Models-Multi-Turn-Conversation"><a rel="noopener" target="_blank" href="#h3-Step-4-Test-Qwen3-Instruct-vs-Thinking-Models-Multi-Turn-Conversation">Step 4: Test Qwen3 Instruct vs. Thinking Models in a Multi-Turn Conversation</a></li>
        <li id="TOC-h3-Step-5-Creating-Interactive-Gradio-Interface"><a rel="noopener" target="_blank" href="#h3-Step-5-Creating-Interactive-Gradio-Interface">Step 5: Creating the Interactive Gradio Interface</a></li>
        <li id="TOC-h3-Step-6-Launch-Qwen3-Gradio-Chatbot-Application-Locally"><a rel="noopener" target="_blank" href="#h3-Step-6-Launch-Qwen3-Gradio-Chatbot-Application-Locally">Step 6: Launch the Qwen3 Gradio Chatbot Application Locally</a></li>
        <li id="TOC-h3-Sample-Qwen3-Chatbot-Conversations"><a rel="noopener" target="_blank" href="#h3-Sample-Qwen3-Chatbot-Conversations">Sample Qwen3 Chatbot Conversations</a></li>
    </ul>

    <li id="TOC-h2-Summary"><a rel="noopener" target="_blank" href="#h2-Summary">Summary</a></li>
    <ul>
        <li id="TOC-h3-Citation-Information"><a rel="noopener" target="_blank" href="#h3-Citation-Information">Citation Information</a></li>
    </ul>
</ul>
</div>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h1-Building-Intelligent-Chatbot-Qwen3-Instruct-Thinking-Models"/>



<h2 class="wp-block-heading"><a href="#TOC-h1-Building-Intelligent-Chatbot-Qwen3-Instruct-Thinking-Models">Building an Intelligent Chatbot with Qwen3 Instruct and Thinking Models </a></h2>



<p>The landscape of artificial intelligence has witnessed remarkable progress in recent years, with large language models (LLMs) pushing the boundaries of what machines can understand and generate. Among the latest breakthroughs in this field is Qwen3, a comprehensive series of open-weight large language models that achieves state-of-the-art performance across diverse tasks and domains. Qwen3 represents a significant leap forward from its predecessor, Qwen2.5, introducing revolutionary features that fundamentally change how we interact with AI systems.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://pyimagesearch.com/wp-content/uploads/2026/06/building-intelligent-chatbot-qwen3-instruct-thinking-models-featured.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="940" height="780" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/building-intelligent-chatbot-qwen3-instruct-thinking-models-featured.png?lossy=2&strip=1&webp=1" alt="building-intelligent-chatbot-qwen3-instruct-thinking-models-featured.png" class="wp-image-54419"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/building-intelligent-chatbot-qwen3-instruct-thinking-models-featured.png?size=126x105&lossy=2&strip=1&webp=1 126w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/building-intelligent-chatbot-qwen3-instruct-thinking-models-featured-300x249.png?lossy=2&strip=1&webp=1 300w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/building-intelligent-chatbot-qwen3-instruct-thinking-models-featured.png?size=378x314&lossy=2&strip=1&webp=1 378w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/building-intelligent-chatbot-qwen3-instruct-thinking-models-featured.png?size=504x418&lossy=2&strip=1&webp=1 504w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/building-intelligent-chatbot-qwen3-instruct-thinking-models-featured.png?size=630x523&lossy=2&strip=1&webp=1 630w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/building-intelligent-chatbot-qwen3-instruct-thinking-models-featured-768x637.png?lossy=2&strip=1&webp=1 768w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/building-intelligent-chatbot-qwen3-instruct-thinking-models-featured.png?lossy=2&strip=1&webp=1 940w" sizes="(max-width: 940px) 100vw, 940px" /></a></figure></div>


<p>What sets Qwen3 apart is its unique dual-mode architecture that seamlessly integrates both thinking and non-thinking modes within a single model. This innovation eliminates the need to switch between different models for tasks requiring different levels of reasoning, such as moving from Qwen2.5 to QwQ for complex problem-solving. </p>



<p>The thinking mode enables deep, step-by-step reasoning through extended chain-of-thought (CoT) processes, making it ideal for challenging mathematical problems, complex coding tasks, and multi-step reasoning scenarios. Meanwhile, the non-thinking mode provides fast, direct responses for simpler queries where extensive deliberation is not necessary. This flexibility, combined with thinking budgets that allow fine-grained control over computational resources, makes Qwen3 a versatile tool for real-world applications.</p>



<p>In this lesson, we embark on an exciting journey to build an intelligent chatbot that leverages both Qwen3-Instruct and Qwen3-Thinking models. Through hands-on implementation, we will explore how these models can be integrated into a practical application using Gradio, a powerful framework for creating interactive web interfaces. </p>



<p>By the end of this tutorial, you will understand not only the theoretical underpinnings of Qwen3&#8217;s architecture and training methodology but also how to deploy these models in production-ready applications. This lesson serves as the foundation for our multi-part series on building a comprehensive, safe, and multimodal AI assistant using the complete Qwen3 model ecosystem.</p>



<p>This lesson is the 1st in the 4-part series on <strong>Building with Qwen3 Models</strong>:</p>



<ol class="wp-block-list">
<li><em><strong><a href="https://pyimg.co/o0x9h" target="_blank" rel="noreferrer noopener">Building an Intelligent Chatbot with Qwen3 Instruct and Thinking Models</a></strong></em><strong> (this tutorial)</strong></li>



<li><em>Lesson 2</em></li>



<li><em>Lesson 3</em></li>



<li><em>Lesson 4</em></li>
</ol>



<p><strong>To learn about Qwen3 and build intelligent applications from scratch, </strong><em><strong>just keep reading</strong></em><strong>.</strong></p>



<div id="pyi-source-code-block" class="source-code-wrap"><div class="gpd-source-code">
    <div class="gpd-source-code-content">
        <img decoding="async" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2020/01/source-code-icon.png?lossy=2&strip=1&webp=1" alt="">
        <h4>Looking for the source code to this post?</h4>
                    <a href="#download-the-code" class="pyis-cta-modal-open-modal">Jump Right To The Downloads Section <svg class="svg-icon arrow-right" width="12" height="12" aria-hidden="true" role="img" focusable="false" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M6.8125 0.1875C6.875 0.125 6.96875 0.09375 7.09375 0.09375C7.1875 0.09375 7.28125 0.125 7.34375 0.1875L13.875 6.75C13.9375 6.8125 14 6.90625 14 7C14 7.125 13.9375 7.1875 13.875 7.25L7.34375 13.8125C7.28125 13.875 7.1875 13.9062 7.09375 13.9062C6.96875 13.9062 6.875 13.875 6.8125 13.8125L6.1875 13.1875C6.125 13.125 6.09375 13.0625 6.09375 12.9375C6.09375 12.8438 6.125 12.75 6.1875 12.6562L11.0312 7.8125H0.375C0.25 7.8125 0.15625 7.78125 0.09375 7.71875C0.03125 7.65625 0 7.5625 0 7.4375V6.5625C0 6.46875 0.03125 6.375 0.09375 6.3125C0.15625 6.25 0.25 6.1875 0.375 6.1875H11.0312L6.1875 1.34375C6.125 1.28125 6.09375 1.1875 6.09375 1.0625C6.09375 0.96875 6.125 0.875 6.1875 0.8125L6.8125 0.1875Z" fill="#169FE6"></path></svg></a>
            </div>
</div>
</div>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Qwen3-Model-Details"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Qwen3-Model-Details">Qwen3 Model Details </a></h2>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Qwen3-Model-Architecture-Dense-Models-MoE-Variants-Dual-Mode-Reasoning"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Qwen3-Model-Architecture-Dense-Models-MoE-Variants-Dual-Mode-Reasoning">Qwen3 Model Architecture: Dense Models, MoE Variants, and Dual-Mode Reasoning </a></h3>



<p>The Qwen3 series represents a comprehensive family of language models, offering both dense and Mixture-of-Experts (MoE) architectures to accommodate diverse computational requirements and use cases. The lineup includes 6 dense models ranging from the compact Qwen3-0.6B to the substantial Qwen3-32B, alongside two powerful MoE variants: <strong>Qwen3-30B-A3B</strong> and the flagship <strong>Qwen3-235B-A22B</strong>. The flagship model, with its 235 billion total parameters and 22 billion activated parameters per token, demonstrates the perfect balance between high performance and efficient inference through its sparse activation pattern.</p>



<p>The architecture of Qwen3 builds upon proven foundations while introducing critical enhancements for stability and performance. The dense models share core architectural elements with Qwen2.5, including Grouped Query Attention (GQA) for efficient attention computation, SwiGLU activation functions for better gradient flow, Rotary Positional Embeddings (RoPE) for superior position encoding, and RMSNorm with pre-normalization for training stability. However, Qwen3 introduces 2 significant improvements: the removal of QKV-bias that was present in Qwen2, and the introduction of QK-Norm to the attention mechanism, which ensures stable training especially for larger models.</p>



<p>The model variants span a wide range of sizes to meet different deployment scenarios (<strong>Table 1</strong>):</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://pyimagesearch.com/wp-content/uploads/2026/06/image-12.jpeg" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="897" height="260" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-12.jpeg?lossy=2&strip=1&webp=1" alt="" class="wp-image-54421"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-12.jpeg?size=126x37&lossy=2&strip=1&webp=1 126w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-12-300x87.jpeg?lossy=2&strip=1&webp=1 300w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-12.jpeg?size=378x110&lossy=2&strip=1&webp=1 378w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-12.jpeg?size=504x146&lossy=2&strip=1&webp=1 504w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-12.jpeg?size=630x183&lossy=2&strip=1&webp=1 630w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-12-768x223.jpeg?lossy=2&strip=1&webp=1 768w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-12.jpeg?lossy=2&strip=1&webp=1 897w" sizes="(max-width: 897px) 100vw, 897px" /></a><figcaption class="wp-element-caption"><strong>Table 1: </strong>Qwen3 model variants (source: <a href="https://arxiv.org/abs/2505.09388" target="_blank" rel="noreferrer noopener">Yang et al., 2025, Qwen Team</a>).</figcaption></figure></div>


<p>For the MoE models, Qwen3 adopts fine-grained expert segmentation with 128 total experts and 8 activated experts per token. Unlike Qwen2.5-MoE, the new design excludes shared experts and instead employs a global-batch load-balancing loss to encourage expert specialization (<strong>Table 2</strong>). </p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/06/image-13-scaled.jpeg" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="131" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-13-1024x131.jpeg?lossy=2&strip=1&webp=1" alt="" class="wp-image-54423"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-13-1024x131.jpeg?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-13-1024x131.jpeg?size=126x16&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-13-1024x131.jpeg?size=252x32&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-13-1024x131.jpeg?size=378x48&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-13-1024x131.jpeg?size=504x64&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-13-1024x131.jpeg?size=630x81&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Table 2: </strong>Qwen3 MoE (Mixture of Experts) model variants (source: <a href="https://arxiv.org/abs/2505.09388" target="_blank" rel="noreferrer noopener">Yang et al., 2025, Qwen Team</a>).</figcaption></figure></div>


<p>This architectural innovation has yielded substantial improvements in model performance across downstream tasks. The MoE models achieve performance comparable to much larger dense models while using only a fraction of the activated parameters, making them highly cost-effective for training and inference.</p>



<p>All Qwen3 models utilize Qwen&#8217;s tokenizer, which implements byte-level byte-pair encoding (BBPE) with a vocabulary size of 151,669 tokens. This comprehensive vocabulary enables efficient encoding across the 119 languages and dialects supported by Qwen3, from high-resource languages like English and Chinese to low-resource languages and specialized domains. </p>



<p>The combination of architectural innovations, diverse model sizes, and extensive multilingual support makes Qwen3 one of the most versatile and powerful open-source language model families available today.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Qwen3-Training-Data-Post-Training-Pipeline-Reasoning-Instruction-Following"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Qwen3-Training-Data-Post-Training-Pipeline-Reasoning-Instruction-Following">Qwen3 Training Data and Post-Training Pipeline for Reasoning and Instruction Following </a></h3>



<p>The training of Qwen3 represents a massive undertaking in data curation, processing, and model optimization. The pre-training dataset consists of approximately <strong>36 trillion tokens </strong>(double the scale of Qwen2.5) and covers an unprecedented 119 languages and dialects compared to just 29 in the previous version. This expansion includes high-quality content spanning coding, STEM (Science, Technology, Engineering, and Mathematics), reasoning tasks, books, multilingual texts, and synthetic data, ensuring comprehensive knowledge coverage across domains.</p>



<p>To expand the pre-training corpus, the Qwen team employed innovative data augmentation strategies. First, they leveraged the Qwen2.5-VL model to perform text recognition on large volumes of PDF-like documents, extracting trillions of tokens from previously inaccessible sources. The recognized text was then refined using the Qwen2.5 model to improve quality. </p>



<p>Additionally, they employed specialized models (Qwen2.5-Math for mathematical content and Qwen2.5-Coder for code generation) to synthesize trillions of text tokens in various formats, including textbooks, question-answering pairs, instructions, and code snippets across dozens of domains. This synthetic data generation approach allowed for precise control over data quality and diversity.</p>



<p>A key innovation in Qwen3&#8217;s training is the development of a multilingual data annotation system that enhanced both quality and diversity. This system annotated over 30 trillion tokens across multiple dimensions such as educational value, fields, domains, and safety. </p>



<p>Unlike previous studies that optimized data mixture at the source or domain level, Qwen3&#8217;s approach optimized the data mixture at the instance level through extensive ablation experiments on small proxy models with fine-grained data labels. This granular approach to data curation significantly improved the effectiveness of the training process.</p>



<p>The pre-training process follows a carefully designed 3-stage strategy:</p>



<p><strong>Stage 1. General Stage (S1):</strong> All Qwen3 models are trained on over 30 trillion tokens using a sequence length of 4,096 tokens. This stage establishes a strong foundation in language proficiency and general world knowledge across all 119 supported languages and dialects. The models learn fundamental patterns, linguistic structures, and broad knowledge that serves as the basis for more specialized capabilities.</p>



<p><strong>Stage 2. Reasoning Stage (S2):</strong> To enhance reasoning abilities, the training corpus is optimized by increasing the proportion of STEM, coding, reasoning, and synthetic data. Models are further trained on approximately 5 trillion high-quality tokens at a sequence length of 4,096 tokens. The learning rate decay is accelerated during this stage to fine-tune the models&#8217; reasoning capabilities, particularly for complex problem-solving tasks in mathematics, science, and programming.</p>



<p><strong>Stage 3. Long Context Stage:</strong> In the final pre-training stage, high-quality long context corpora are used to extend the context length from 4,096 to 32,768 tokens. The long context corpus includes 75% of text between 16,384 and 32,768 tokens in length, and 25% of text between 4,096 and 16,384 tokens. The base frequency of RoPE is increased from 10,000 to 1,000,000 using the ABF technique, and YARN and Dual Chunk Attention (DCA) techniques are introduced to achieve a 4-fold increase in sequence length capacity during inference, enabling the models to handle documents up to 128K tokens.</p>



<p>Post-training (<strong>Figure 1</strong>) employs a sophisticated multi-stage approach to align the models with human preferences and downstream applications. The first 2 stages focus on developing strong reasoning abilities through long chain-of-thought (CoT) cold-start fine-tuning and reinforcement learning, primarily targeting mathematics and coding tasks.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/06/image-14-scaled.jpeg" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="415" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-14-1024x415.jpeg?lossy=2&strip=1&webp=1" alt="" class="wp-image-54426"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-14-1024x415.jpeg?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-14-1024x415.jpeg?size=126x51&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-14-1024x415.jpeg?size=252x102&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-14-1024x415.jpeg?size=378x153&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-14-1024x415.jpeg?size=504x204&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-14-1024x415.jpeg?size=630x255&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 1: </strong> Post-training pipeline of the Qwen3 series models (source: <a href="https://arxiv.org/abs/2505.09388" target="_blank" rel="noreferrer noopener">Yang et al., 2025, Qwen Team</a>).</figcaption></figure></div>


<p>In the final 2 stages, data with and without reasoning paths are combined into a unified dataset for further fine-tuning, enabling the model to handle both thinking and non-thinking modes effectively. General-domain reinforcement learning is then applied to improve performance across a wide range of downstream tasks.</p>



<p>For smaller models, strong-to-weak distillation leverages both off-policy and on-policy knowledge transfer from larger models, significantly outperforming direct reinforcement learning in both performance and training efficiency.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Qwen3-Benchmark-Performance-Thinking-Budgets-Reasoning-Coding-STEM-Tasks"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Qwen3-Benchmark-Performance-Thinking-Budgets-Reasoning-Coding-STEM-Tasks">Qwen3 Benchmark Performance: Thinking Budgets, Reasoning, Coding, and STEM Tasks </a></h3>



<p>Qwen3 demonstrates exceptional performance across a comprehensive suite of benchmarks, establishing new standards for open-source language models. The flagship model (Qwen3-235B-A22B) consistently outperforms alternatives across most benchmarks (<strong>Table 3</strong>). </p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/06/image-15-scaled.jpeg" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="688" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-15-1024x688.jpeg?lossy=2&strip=1&webp=1" alt="" class="wp-image-54428"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-15-1024x688.jpeg?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-15-1024x688.jpeg?size=126x85&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-15-1024x688.jpeg?size=252x169&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-15-1024x688.jpeg?size=378x254&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-15-1024x688.jpeg?size=504x339&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-15-1024x688.jpeg?size=630x423&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Table 3: </strong>Comparison among Qwen3-235B-A22B-Base and other representative strong open-source baselines (source: <a href="https://arxiv.org/abs/2505.09388" target="_blank" rel="noreferrer noopener">Yang et al., 2025, Qwen Team</a>).</figcaption></figure></div>


<p>When evaluated against DeepSeek-V3-Base, which has approximately three times more parameters (671B vs 235B) and nearly double the activated parameters (37B vs 22B), Qwen3-235B-A22B achieves superior results on 14 out of 15 evaluation benchmarks. This includes substantial advantages on general tasks like MMLU (87.81 vs 87.19), MMLU-Redux (87.40 vs 86.14), and BBH (88.87 vs 86.22), as well as specialized domains such as MATH (71.84 vs 62.62) and EvalPlus coding benchmarks (77.60 vs 63.75).</p>



<p>The performance advantages extend across the entire Qwen3 family. The MoE models demonstrate exceptional efficiency, achieving similar performance to dense models with only 1/5 of the activated parameters. For instance, experimental results show that Qwen3-30B-A3B (with only 3B activated parameters) performs comparably to much larger dense models, while Qwen3-235B-A22B outperforms the Qwen2.5 MoE base models with less than 1/2 of their activated parameters and fewer total parameters.</p>



<p>The dense Qwen3 models also show impressive scaling efficiency. Qwen3-1.7B/4B/8B/14B/32B-Base achieve performance comparable to Qwen2.5-3B/7B/14B/32B/72B-Base, respectively, effectively matching models that are 1.5-2x larger in parameter count (<strong>Table 4</strong>). </p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/06/image-16-scaled.jpeg" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="726" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-16-1024x726.jpeg?lossy=2&strip=1&webp=1" alt="" class="wp-image-54432"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-16-1024x726.jpeg?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-16-1024x726.jpeg?size=126x89&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-16-1024x726.jpeg?size=252x179&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-16-1024x726.jpeg?size=378x268&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-16-1024x726.jpeg?size=504x357&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-16-1024x726.jpeg?size=630x447&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Table 4: </strong>Comparison among Qwen3-32B-Base and other representative strong open-source baselines (source: <a href="https://arxiv.org/abs/2505.09388" target="_blank" rel="noreferrer noopener">Yang et al., 2025, Qwen Team</a>).</figcaption></figure></div>


<p>On STEM, coding, and reasoning benchmarks, Qwen3 dense base models frequently surpass their Qwen2.5 counterparts at higher parameter scales. For example, Qwen3-32B-Base scores 65.54 on MMLU-Pro compared to Qwen2.5-72B-Base&#8217;s 58.07, demonstrating substantial improvements in reasoning capabilities despite having less than half the parameters.</p>



<p>A particularly noteworthy finding is that increasing the thinking budget for thinking tokens leads to consistent improvements in model performance across various tasks (<strong>Figure 2</strong>). This demonstrates the effectiveness of the dual-mode architecture, where users can dynamically control the trade-off between response speed and reasoning depth based on their specific needs. </p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/06/image-17-scaled.jpeg" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="662" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-17-1024x662.jpeg?lossy=2&strip=1&webp=1" alt="" class="wp-image-54434"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-17-1024x662.jpeg?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-17-1024x662.jpeg?size=126x81&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-17-1024x662.jpeg?size=252x163&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-17-1024x662.jpeg?size=378x244&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-17-1024x662.jpeg?size=504x326&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-17-1024x662.jpeg?size=630x407&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 2: </strong>Performance of Qwen3-235B-A22B with respect to the thinking budget (source: <a href="https://arxiv.org/abs/2505.09388" target="_blank" rel="noreferrer noopener">Yang et al., 2025, Qwen Team</a>).</figcaption></figure></div>


<p>The combination of architectural innovations, extensive training data, and sophisticated optimization techniques positions Qwen3 as one of the most capable and efficient open-source language model families available, offering performance competitive with proprietary alternatives while maintaining the benefits of transparency and community-driven development.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Implementation-Building-Deep-Thinking-Chatbot-Qwen3-Gradio"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Implementation-Building-Deep-Thinking-Chatbot-Qwen3-Gradio">Implementation: Building a Deep Thinking Chatbot with Qwen3 and Gradio </a></h2>



<p>Now that we understand the theoretical foundations of Qwen3, let us dive into building a practical chatbot application that leverages both the Instruct and Thinking modes. We will create an interactive web interface using Gradio that allows users to seamlessly switch between fast responses and deep reasoning.</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<!-- wp:paragraph -->
<h3>Need Help Configuring Your Development Environment?</h3>
<!-- /wp:paragraph -->

<!-- wp:image {"align":"center","id":18137,"sizeSlug":"large","linkDestination":"custom"} -->
<figure class="wp-block-image aligncenter size-large"><a href="https://pyimagesearch.com/pyimagesearch-university/" target="_blank" rel="noreferrer noopener"><img decoding="async" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2021/01/pyimagesearch_plus_jupyter.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-18137" srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2021/01/pyimagesearch_plus_jupyter.png?lossy=2&strip=1&webp=1 500w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2021/01/pyimagesearch_plus_jupyter.png?size=126x84&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2021/01/pyimagesearch_plus_jupyter.png?size=252x168&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2021/01/pyimagesearch_plus_jupyter.png?size=378x253&lossy=2&strip=1&webp=1 378w" sizes="(max-width: 500px) 100vw, 500px" /></a><figcaption>Having trouble configuring your development environment? Want access to pre-configured Jupyter Notebooks running on Google Colab? Be sure to join <a href="https://pyimagesearch.com/pyimagesearch-university/" target="_blank" rel="noreferrer noopener" aria-label=" (opens in a new tab)">PyImageSearch University</a> — you will be up and running with this tutorial in a matter of minutes. </figcaption></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>All that said, are you:</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li>Short on time?</li><li>Learning on your employer’s administratively locked system?</li><li>Wanting to skip the hassle of fighting with the command line, package managers, and virtual environments?</li><li><strong>Ready to run the code immediately on your Windows, macOS, or Linux system?</strong></li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>Then join <a href="https://pyimagesearch.com/pyimagesearch-university/" target="_blank">PyImageSearch University</a> today!</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><strong>Gain access to Jupyter Notebooks for this tutorial and other PyImageSearch guides pre-configured to run on Google Colab’s ecosystem right in your web browser!</strong> No installation required.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>And best of all, these Jupyter Notebooks will run on Windows, macOS, and Linux!</p>
<!-- /wp:paragraph -->



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Step-1-Install-Qwen3-Chatbot-Dependencies-PyTorch-Transformers-Gradio"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Step-1-Install-Qwen3-Chatbot-Dependencies-PyTorch-Transformers-Gradio">Step 1: Install Qwen3 Chatbot Dependencies with PyTorch, Transformers, and Gradio </a></h3>



<p>First, we need to install the required Python packages for our chatbot. This includes PyTorch for model inference, Transformers for loading the Qwen3 models, and Gradio for building the web interface.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Building an Intelligent Chatbot with Qwen3 Instruct and Thinking Models" data-enlighter-group="1">!pip install torch transformers accelerate gradio
!pip install flash-attn --no-build-isolation
print("\n✅ Dependencies installed successfully!")
</pre>



<p>On <strong>Lines 1-3</strong>, we install the core dependencies for our chatbot application. The <code data-enlighter-language="python" class="EnlighterJSRAW">torch</code> package provides the deep learning framework for running model inference, while <code data-enlighter-language="python" class="EnlighterJSRAW">transformers</code> from Hugging Face gives us easy access to pre-trained Qwen3 models. </p>



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">accelerate</code> library optimizes model loading and inference across different hardware configurations, and <code data-enlighter-language="python" class="EnlighterJSRAW">gradio</code> enables us to build an interactive web interface with minimal code. We also install <code data-enlighter-language="python" class="EnlighterJSRAW">flash-attn</code> for optimized attention mechanisms that significantly speed up inference, particularly for long sequences. The <code data-enlighter-language="python" class="EnlighterJSRAW">--no-build-isolation</code> flag ensures compatibility with the existing environment.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Step-2-Importing-Required-Libraries"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Step-2-Importing-Required-Libraries">Step 2: Importing Required Libraries </a></h3>



<p>Next, we import the necessary libraries and verify our environment setup.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Building an Intelligent Chatbot with Qwen3 Instruct and Thinking Models" data-enlighter-group="2">import torch
from transformers import pipeline
import gradio as gr
from typing import List, Tuple, Optional
from IPython.display import display, HTML, Markdown

print(f"PyTorch version: {torch.__version__}")
print(f"CUDA available: {torch.cuda.is_available()}")
if torch.cuda.is_available():
    print(f"CUDA device: {torch.cuda.get_device_name(0)}")
</pre>



<p>On <strong>Lines 1-5</strong>, we import the essential modules for our application. The <code data-enlighter-language="python" class="EnlighterJSRAW">torch</code> import provides access to PyTorch functionality, while <code data-enlighter-language="python" class="EnlighterJSRAW">pipeline</code> from transformers simplifies model loading and inference. Gradio (<code data-enlighter-language="python" class="EnlighterJSRAW">gr</code>) will power our web interface, and the typing hints ensure code quality. The IPython display utilities help us render formatted output in Jupyter notebooks. </p>



<p>On <strong>Lines 7-10</strong>, we perform environment checks to verify that PyTorch is properly installed and to confirm whether GPU acceleration is available. If CUDA is available, we also print the GPU device name to ensure we are utilizing hardware acceleration for faster inference.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Step-3-Initialize-Qwen3-Instruct-Qwen3-Thinking-Text-Generation-Pipelines"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Step-3-Initialize-Qwen3-Instruct-Qwen3-Thinking-Text-Generation-Pipelines">Step 3: Initialize Qwen3 Instruct and Qwen3 Thinking Text-Generation Pipelines </a></h3>



<p>Now we create instances of both the Instruct and Thinking model pipelines. The pipeline abstraction from Hugging Face makes it incredibly easy to load and use these models.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Building an Intelligent Chatbot with Qwen3 Instruct and Thinking Models" data-enlighter-group="3">print("=" * 60)
print("Initializing Qwen3-4B-Instruct and Qwen3-4B-Thinking Text Generation Pipelines")
print("=" * 60)

qwen3_instruct = pipeline("text-generation", model="Qwen/Qwen3-4B-Instruct-2507")
qwen3_thinking = pipeline("text-generation", model="Qwen/Qwen3-4B-Thinking-2507")

print("\n✅ Pipelines initialized successfully!")
</pre>



<p>On <strong>Lines 1-3</strong>, we print informative messages to track the initialization process. On <strong>Lines 5 and 6</strong>, we initialize 2 separate pipelines: one for the Instruct model and one for the Thinking model.</p>



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">pipeline</code> function automatically handles model downloading (approximately 8GB for the 4B parameter model), tokenization, and inference setup. We use the Qwen3-4B variants, which offer an excellent balance between performance and resource requirements, making them suitable for a wide range of hardware configurations. The models are automatically downloaded from the Hugging Face model hub if they are not already cached locally.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Step-4-Test-Qwen3-Instruct-vs-Thinking-Models-Multi-Turn-Conversation"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Step-4-Test-Qwen3-Instruct-vs-Thinking-Models-Multi-Turn-Conversation">Step 4: Test Qwen3 Instruct vs. Thinking Models in a Multi-Turn Conversation </a></h3>



<p>Before building the full interface, let us test both models with a simple conversation to understand their behavior.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Building an Intelligent Chatbot with Qwen3 Instruct and Thinking Models" data-enlighter-group="4"># Initialize conversation history
conversation = []

# First message
user_msg_1 = "What is machine learning? Explain shortly."
conversation.append({"role": "user", "content": user_msg_1})
display(Markdown(f"**User**: {user_msg_1}"))

response_1 = qwen3_instruct(conversation, do_sample=False, max_new_tokens=1024, return_full_text=False)
response_1 = response_1[0]['generated_text']
display(Markdown(f"\n**Assistant**: {response_1}\n"))

# Update history
conversation.append({"role": "assistant", "content": response_1})

# Second message (continuation)
user_msg_2 = "Can you give me a simple short example?"
conversation.append({"role": "user", "content": user_msg_2})
display(Markdown(f"**User**: {user_msg_2}"))

response_2 = qwen3_thinking(conversation, do_sample=False, max_new_tokens=1024, return_full_text=False)
trace = response_2[0]['generated_text'].split('&lt;/think>')[0]
response_2 = response_2[0]['generated_text'].split('&lt;/think>')[1]
response_2 = (
    "&lt;details>&lt;summary>Show trace&lt;/summary>\n\n"
    "```text\n" + (trace or "").strip() + "\n```\n"
    "&lt;/details>\n\n"
    + (response_2 or "")
)
display(Markdown(f"\nAssistant: {response_2}"))</pre>



<p>On <strong>Lines 1 and 2</strong>, we initialize an empty conversation list that will store the dialogue history in the format expected by the models. On <strong>Lines 4-7</strong>, we create the first user message asking about machine learning and append it to the conversation with the &#8220;user&#8221; role. </p>



<p>On <strong>Lines 9 and 10</strong>, we use the Instruct model to generate a response with <code data-enlighter-language="python" class="EnlighterJSRAW">do_sample=False</code> for deterministic output and <code data-enlighter-language="python" class="EnlighterJSRAW">max_new_tokens=1024</code> to limit response length. The <code data-enlighter-language="python" class="EnlighterJSRAW">return_full_text=False</code> parameter ensures we only get the newly generated text, not the entire prompt.</p>



<p>On <strong>Lines 13-18</strong>, we update the conversation history with the assistant&#8217;s response and then add a follow-up question. This demonstrates how the models maintain context across multiple turns. On <strong>Line 21</strong>, we switch to the Thinking model for the second response, which generates output with explicit reasoning traces. </p>



<p>On <strong>Lines 22-2</strong><strong>9</strong>, we parse the model&#8217;s output to separate the thinking process (enclosed in <code data-enlighter-language="python" class="EnlighterJSRAW">&lt;think&gt;</code> tags) from the final answer. We format this as collapsible HTML details, allowing users to optionally view the model&#8217;s step-by-step reasoning process. This separation showcases the key difference between Instruct and Thinking modes: while Instruct provides direct answers, Thinking reveals its internal reasoning process.</p>



<p><strong>Figure 3 </strong>shows the output of the above code snippet, demonstrating the reasoning capabilities of both models.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/06/image-18-scaled.jpeg" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="424" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-18-1024x424.jpeg?lossy=2&strip=1&webp=1" alt="" class="wp-image-54437"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-18-1024x424.jpeg?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-18-1024x424.jpeg?size=126x52&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-18-1024x424.jpeg?size=252x104&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-18-1024x424.jpeg?size=378x157&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-18-1024x424.jpeg?size=504x209&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-18-1024x424.jpeg?size=630x261&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 3: </strong>Sample conversation using Qwen3-4B Instruct and Thinking models (source: image by the author).</figcaption></figure></div>


<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Step-5-Creating-Interactive-Gradio-Interface"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Step-5-Creating-Interactive-Gradio-Interface">Step 5: Creating the Interactive Gradio Interface </a></h3>



<p>Now we will build a comprehensive web interface that allows users to interact with both models through a clean, intuitive chat interface.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Building an Intelligent Chatbot with Qwen3 Instruct and Thinking Models" data-enlighter-group="6">def create_chatbot_interface(chatbot, thinking_chatbot):
    """
    Gradio interface for chatbot interaction
    """

    def add_user_message(message: str, conversation, history):
        if not message.strip():
            return history, ""
        if history is None:
            history = []
        conversation.append({"role": "user", "content": message})
        history.append([message, None])
        return history, ""   # show user message immediately

    def chat_function(message: str, conversation, history, model_choice: str):
        try:
            if model_choice == "Thinking":
                response = thinking_chatbot(conversation, do_sample=False, max_new_tokens=1024, return_full_text=False)
                trace = response[0]['generated_text'].split('&lt;/think>')[0]
                response = response[0]['generated_text'].split('&lt;/think>')[1]
                assistant_text = (
                    "&lt;details>&lt;summary>Show thinking trace&lt;/summary>\n\n"
                    "```text\n" + (trace or "").strip() + "\n```\n"
                    "&lt;/details>\n\n"
                    + (response or "")
                )
            else:
                response = chatbot(conversation, do_sample=False, max_new_tokens=1024, return_full_text=False)
                response = response[0]['generated_text']
                assistant_text = response or ""

            conversation.append({"role": "assistant", "content": assistant_text})
            history[-1][1] = assistant_text
            return history, ""
        except Exception as e:
            history[-1][1] = f"Exception: {e}"
            return history, ""
</pre>



<p>On <strong>Lines 1-4</strong>, we define the main function that creates our chatbot interface, taking both the Instruct and Thinking model pipelines as parameters. On <strong>Lines 6-13</strong>, we define <code data-enlighter-language="python" class="EnlighterJSRAW">add_user_message</code>, a helper function that handles user input. It validates that the message is not empty, initializes the history if needed, and appends the user&#8217;s message to both the conversation state and the display history. The function returns the updated history with the user&#8217;s message immediately visible, providing responsive feedback.</p>



<p>On <strong>Lines 15-37</strong>, we define the <code data-enlighter-language="python" class="EnlighterJSRAW">chat_function</code> that processes messages and generates responses. The function first checks the <code data-enlighter-language="python" class="EnlighterJSRAW">model_choice</code> parameter to determine which model to use. On <strong>Lines 17-26</strong>, if &#8220;Thinking&#8221; mode is selected, we generate a response using the thinking model and parse out the reasoning trace, formatting it as collapsible HTML for optional viewing. </p>



<p>On <strong>Lines 27-30</strong>, if &#8220;Instruct&#8221; mode is selected, we generate a straightforward response without thinking traces. On <strong>Lines 32-37</strong>, we update the conversation history with the assistant&#8217;s response and handle any exceptions gracefully by displaying error messages.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Building an Intelligent Chatbot with Qwen3 Instruct and Thinking Models" data-enlighter-group="7"> with gr.Blocks() as interface:
        gr.Markdown("## 🤖 Qwen3-4B Chatbot with Deep Thinking")

        with gr.Row():
            chatbot_ui = gr.Chatbot(scale=4)

        with gr.Row():
            msg = gr.Textbox(placeholder="Type your message here...", scale=8)
            send_btn = gr.Button("📤 Send", scale=1)
            stop_btn = gr.Button("⏹️ Stop", scale=1)
            model_selector = gr.Dropdown(
                choices=["Instruct", "Thinking"],
                value="Instruct",
                label="Model selection",
                scale=2
            )

        history_state = gr.State([])
        conversation_state = gr.State([])

        # Step 1: Show user message immediately
        send_btn.click(
            add_user_message,
            inputs=[msg, conversation_state, history_state],
            outputs=[chatbot_ui, msg],
        )

        # Step 2: Then process with chatbot
        send_event = send_btn.click(
            chat_function,
            inputs=[msg, conversation_state, history_state, model_selector],
            outputs=[chatbot_ui, msg],
        )

        stop_btn.click(None, None, None, cancels=[send_event])

    return interface
</pre>



<p>On <strong>Lines 1</strong><strong> and </strong><strong>2</strong>, we use Gradio&#8217;s <code data-enlighter-language="python" class="EnlighterJSRAW">Blocks</code> API to create a custom layout, starting with a markdown header. On <strong>Lines 4</strong><strong> and </strong><strong>5</strong>, we create the main chatbot display area with <code data-enlighter-language="python" class="EnlighterJSRAW">scale=4</code> to give it more screen space. On <strong>Lines 7-16</strong>, we build the input row containing a text box for user messages, send and stop buttons, and a dropdown menu for model selection. The scaling parameters control the relative widths of these elements for an optimal layout.</p>



<p>On <strong>Lines 18</strong><strong> and </strong><strong>19</strong>, we initialize 2 state variables: <code data-enlighter-language="python" class="EnlighterJSRAW">history_state</code> for the chat display and <code data-enlighter-language="python" class="EnlighterJSRAW">conversation_state</code> for the full conversation context needed by the models. On <strong>Lines 21-26</strong>, we configure the send button&#8217;s first action to immediately display the user&#8217;s message, providing instant feedback. </p>



<p>On <strong>Lines 28-33</strong>, we configure the send button&#8217;s second action to process the message with the selected model and generate a response. The <code data-enlighter-language="python" class="EnlighterJSRAW">send_event</code> variable captures this event so we can cancel it if needed. On <strong>Line 35</strong>, we wire up the stop button to cancel ongoing generation, giving users control over long-running requests.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Step-6-Launch-Qwen3-Gradio-Chatbot-Application-Locally"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Step-6-Launch-Qwen3-Gradio-Chatbot-Application-Locally">Step 6: Launch the Qwen3 Gradio Chatbot Application Locally </a></h3>



<p>Finally, we create the interface instance and launch the web application.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Building an Intelligent Chatbot with Qwen3 Instruct and Thinking Models" data-enlighter-group="8"># Create the interface
interface = create_chatbot_interface(qwen3_instruct, qwen3_thinking)
print("✅ Gradio interface created!")

print("Launching Gradio interface...")
print("Access the chatbot at: http://localhost:7860")
print("Press the 'Stop' button in the output to stop the server\n")

interface.launch()
</pre>



<p>On <strong>Lines 2 and 3</strong>, we instantiate our chatbot interface by calling <code data-enlighter-language="python" class="EnlighterJSRAW">create_chatbot_interface</code> with both model pipelines and confirm successful creation. On <strong>Lines 5-7</strong>, we print informative messages about how to access the application.</p>



<p>On <strong>Line 9</strong>, we launch the Gradio interface, which starts a local web server on port <code data-enlighter-language="python" class="EnlighterJSRAW">7860</code>. The interface automatically opens in a new browser tab (or provides a link if running in certain environments). Users can now interact with both Qwen3-Instruct and Qwen3-Thinking models through an intuitive chat interface, seamlessly switching between fast responses and deep reasoning as needed.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Sample-Qwen3-Chatbot-Conversations"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Sample-Qwen3-Chatbot-Conversations">Sample Qwen3 Chatbot Conversations </a></h3>



<p>To demonstrate how our chatbot blends <strong>instructional clarity</strong> with <strong>deep reasoning</strong>, we have included three example interactions below. These showcase how the model responds in both normal and “Thinking Mode,” which users can toggle to reveal step-by-step logic and internal traceability.</p>



<p>In <strong>Figure 4</strong>, the chatbot responds to a basic science question: <em>“Explain photosynthesis in simple terms.”</em> What is notable here is the clarity and structure of the explanation. The model breaks the process into 4 intuitive steps: sunlight absorption, carbon dioxide intake, water uptake, and glucose production. It then concludes with a simplified chemical equation and adds a metaphor (“a natural kitchen”) to make the concept more relatable. This reflects the model’s <strong>instructional capability</strong>: concise, clear, and beginner-friendly.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/06/image-19-scaled.jpeg" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="635" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-19-1024x635.jpeg?lossy=2&strip=1&webp=1" alt="" class="wp-image-54440"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-19-1024x635.jpeg?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-19-1024x635.jpeg?size=126x78&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-19-1024x635.jpeg?size=252x156&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-19-1024x635.jpeg?size=378x234&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-19-1024x635.jpeg?size=504x313&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-19-1024x635.jpeg?size=630x391&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 4: </strong>Qwen3-4B Chatbot Instruct Capability (source: image by the author).</figcaption></figure></div>


<p><strong>Figure 5 </strong>shows the chatbot solving a math problem in <strong>Thinking Mode</strong>. Here, the chatbot first reveals its internal reasoning trace: a step-by-step breakdown of how it arrived at the answer. It recalls the formula, substitutes values, performs intermediate calculations, and even reflects on whether to include units. This traceability is key: it shows how the model thinks, not just what it knows. For users who want transparency, learning support, or deeper trust, this mode is invaluable.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/06/image-20-scaled.jpeg" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="525" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-20-1024x525.jpeg?lossy=2&strip=1&webp=1" alt="" class="wp-image-54441"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-20-1024x525.jpeg?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-20-1024x525.jpeg?size=126x65&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-20-1024x525.jpeg?size=252x129&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-20-1024x525.jpeg?size=378x194&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-20-1024x525.jpeg?size=504x258&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-20-1024x525.jpeg?size=630x323&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 5: </strong>Qwen3-4B Chatbot Thinking Trace (source: image by the author).</figcaption></figure></div>


<p>Finally, in <strong>Figure 6</strong>, the chatbot provides the correct formula and numerical result, but also distinguishes between the <strong>exact answer</strong> (49π) and the <strong>approximate value</strong> (153.94). This demonstrates its ability to handle both symbolic and numeric reasoning. </p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/06/image-21-scaled.jpeg" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="632" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-21-1024x632.jpeg?lossy=2&strip=1&webp=1" alt="" class="wp-image-54443"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-21-1024x632.jpeg?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-21-1024x632.jpeg?size=126x78&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-21-1024x632.jpeg?size=252x156&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-21-1024x632.jpeg?size=378x233&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-21-1024x632.jpeg?size=504x311&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-21-1024x632.jpeg?size=630x389&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 6: </strong>Qwen3-4B Chatbot Thinking Capability (source: image by the author).</figcaption></figure></div>


<hr class="wp-block-separator has-alpha-channel-opacity"/>



<div id="pitch" style="padding: 40px; width: 100%; background-color: #F4F6FA;">
	<h3>What's next? We recommend <a target="_blank" href="https://pyimagesearch.com/pyimagesearch-university/?utm_source=blogPost&utm_medium=bottomBanner&utm_campaign=What%27s%20next%3F%20I%20recommend">PyImageSearch University</a>.</h3>

	<script src="https://fast.wistia.com/embed/medias/kno0cmko2z.jsonp" async></script><script src="https://fast.wistia.com/assets/external/E-v1.js" async></script><div class="wistia_responsive_padding" style="padding:56.25% 0 0 0;position:relative;"><div class="wistia_responsive_wrapper" style="height:100%;left:0;position:absolute;top:0;width:100%;"><div class="wistia_embed wistia_async_kno0cmko2z videoFoam=true" style="height:100%;position:relative;width:100%"><div class="wistia_swatch" style="height:100%;left:0;opacity:0;overflow:hidden;position:absolute;top:0;transition:opacity 200ms;width:100%;"><img decoding="async" src="https://fast.wistia.com/embed/medias/kno0cmko2z/swatch" style="filter:blur(5px);height:100%;object-fit:contain;width:100%;" alt="" aria-hidden="true" onload="this.parentNode.style.opacity=1;" /></div></div></div></div>

	<div style="margin-top: 32px; margin-bottom: 32px; ">
		<strong>Course information:</strong><br/>
		120+ total classes • 115+ hours hours of on-demand code walkthrough videos • Last updated: August 2026<br/>
		<span style="color: #169FE6;">★★★★★</span> 4.84 (128 Ratings) • 16,000+ Students Enrolled
	</div>

	<p><strong>I strongly believe that if you had the right teacher you could <em>master</em> computer vision and deep learning.</strong></p>

	<p>Do you think learning computer vision and deep learning has to be time-consuming, overwhelming, and complicated? Or has to involve complex mathematics and equations? Or requires a degree in computer science?</p>

	<p>That’s <em>not</em> the case.</p>

	<p>All you need to master computer vision and deep learning is for someone to explain things to you in <em>simple, intuitive</em> terms. <em>And that’s exactly what I do</em>. My mission is to change education and how complex Artificial Intelligence topics are taught.</p>

	<p>If you're serious about learning computer vision, your next stop should be PyImageSearch University, the most comprehensive computer vision, deep learning, and OpenCV course online today. Here you’ll learn how to <em>successfully</em> and <em>confidently</em> apply computer vision to your work, research, and projects. Join me in computer vision mastery.</p>

	<p><strong>Inside PyImageSearch University you'll find:</strong></p>

	<ul style="margin-left: 0px;">
		<li style="list-style: none;">&check; <strong>120+ courses</strong> on essential computer vision, deep learning, and OpenCV topics</li>
		<li style="list-style: none;">&check; <strong>94+ Certificates</strong> of Completion</li>
		<li style="list-style: none;">&check; <strong>115+ hours hours</strong> of on-demand video</li>
		<li style="list-style: none;">&check; <strong>Brand new courses released <em>regularly</em></strong>, ensuring you can keep up with state-of-the-art techniques</li>
		<li style="list-style: none;">&check; <strong>Pre-configured Jupyter Notebooks in Google Colab</strong></li>
		<li style="list-style: none;">&check; Run all code examples in your web browser — works on Windows, macOS, and Linux (no dev environment configuration required!)</li>
		<li style="list-style: none;">&check; Access to <strong>centralized code repos for <em>all</em> 540+ tutorials</strong> on PyImageSearch</li>
		<li style="list-style: none;">&check; <strong> Easy one-click downloads</strong> for code, datasets, pre-trained models, etc.</li>
		<li style="list-style: none;">&check; <strong>Access</strong> on mobile, laptop, desktop, etc.</li>
	</ul>

	<p style="text-align: center;">
		<a target="_blank" class="button link" href="https://pyimagesearch.com/pyimagesearch-university/?utm_source=blogPost&utm_medium=bottomBanner&utm_campaign=What%27s%20next%3F%20I%20recommend" style="background-color: #6DC713; border-bottom: none;">Click here to join PyImageSearch University</a>
	</p>
</div>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Summary"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Summary">Summary </a></h2>



<p>Throughout this lesson, we have explored the groundbreaking Qwen3 model series and its unique dual-mode architecture that revolutionizes how we interact with large language models. We began by understanding the comprehensive model family, from the compact 0.6B parameter variant to the flagship 235B parameter MoE model, each designed to meet different computational requirements and use cases. The architectural innovations (including QK-Norm for training stability, fine-grained expert segmentation in MoE models, and support for 119 languages) demonstrate Qwen3&#8217;s position at the forefront of open-source language models. </p>



<p>The 3-stage training process, encompassing general knowledge acquisition, reasoning enhancement, and long-context capability development, produces models that excel across diverse benchmarks while maintaining efficiency through sparse activation patterns.</p>



<p>We then translated this theoretical knowledge into practical implementation by building a functional deep-thinking chatbot. Through hands-on coding, we learned how to set up the development environment, initialize both Instruct and Thinking model pipelines, and create an interactive web interface using Gradio. The implementation showcased key differences between the two modes: Instruct provides fast, direct responses ideal for straightforward queries, while Thinking reveals its step-by-step reasoning process, making it invaluable for complex problem-solving tasks. </p>



<p>We implemented features like conversation history management, dynamic model switching, and collapsible thinking traces, demonstrating best practices for building user-friendly AI applications. The modular code structure we developed provides a solid foundation that can be extended with additional features such as system prompts, temperature controls, or multi-user support.</p>



<p>This lesson serves as the cornerstone of our series on building a comprehensive, safe, and multimodal AI assistant. In the upcoming lessons, we will expand on this foundation by integrating Qwen3-VL for visual understanding (Lesson 2), adding Qwen3-Guard for safety moderation (Lesson 3), and incorporating Qwen3-Embedding for retrieval-augmented generation (Lesson 4). Each addition will transform our basic chatbot into an increasingly sophisticated system capable of understanding images, ensuring safe interactions, and retrieving relevant information from knowledge bases. </p>



<p>The skills and patterns established in this lesson (from pipeline initialization to interface design) will be reused and extended throughout the series. By the end of the complete series, we will have built a production-ready multimodal AI assistant that demonstrates the full potential of the Qwen3 ecosystem. This assistant will combine state-of-the-art language understanding, visual processing, safety guarantees, and knowledge retrieval in a single cohesive application that showcases the power of modern open-source AI.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Citation-Information"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Citation-Information">Citation Information </a></h3>



<p><strong>Mangla, P</strong><strong>. </strong>“Building an Intelligent Chatbot with Qwen3 Instruct and Thinking Models,” <em>PyImageSearch</em>, S. Huot, A. Sharma, and P. Thakur, eds., 2026, <a href="https://pyimg.co/o0x9h" target="_blank" rel="noreferrer noopener">https://pyimg.co/o0x9h</a> </p>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="classic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="Building an Intelligent Chatbot with Qwen3 Instruct and Thinking Models" data-enlighter-group="9">@incollection{Mangla_2026_building-intelligent-chatbot-qwen3-instruct-thinking-models,
  author = {Puneet Mangla},
  title = {{Building an Intelligent Chatbot with Qwen3 Instruct and Thinking Models}},
  booktitle = {PyImageSearch},
  editor = {Susan Huot and Aditya Sharma and Piyush Thakur},
  year = {2026},
  url = {https://pyimg.co/o0x9h},
}
</pre>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p><strong>To download the source code to this post (and be notified when future tutorials are published here on PyImageSearch), </strong><em><strong>simply enter your email address in the form below!</strong></em></p>



<div id="download-the-code" class="post-cta-wrap">
<div class="gpd-post-cta">
	<div class="gpd-post-cta-content">
		

			<div class="gpd-post-cta-top">
				<div class="gpd-post-cta-top-image"><img decoding="async" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2020/01/cta-source-guide-1.png?lossy=2&strip=1&webp=1" alt="" srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2020/01/cta-source-guide-1.png?lossy=2&strip=1&webp=1 410w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2020/01/cta-source-guide-1.png?size=126x174&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2020/01/cta-source-guide-1.png?size=252x348&lossy=2&strip=1&webp=1 252w" sizes="(max-width: 410px) 100vw, 410px" /></div>
				
				<div class="gpd-post-cta-top-title"><h4>Download the Source Code and FREE 17-page Resource Guide</h4></div>
				<div class="gpd-post-cta-top-desc"><p>Enter your email address below to get a .zip of the code and a <strong>FREE 17-page Resource Guide on Computer Vision, OpenCV, and Deep Learning.</strong> Inside you'll find my hand-picked tutorials, books, courses, and libraries to help you master CV and DL!</p></div>


			</div>

			<div class="gpd-post-cta-bottom">
				<form id="footer-cta-code" class="footer-cta" action="https://www.getdrip.com/forms/4130035/submissions" method="post" target="blank" data-drip-embedded-form="4130035">
					<input name="fields[email]" type="email" value="" placeholder="Your email address" class="form-control" />

					<button type="submit">Download the code!</button>

					<div style="display: none;" aria-hidden="true"><label for="website">Website</label><br /><input type="text" id="website" name="website" tabindex="-1" autocomplete="false" value="" /></div>
				</form>
			</div>


		
	</div>

</div>
</div>
<p>The post <a rel="nofollow" href="https://pyimagesearch.com/2026/06/29/building-an-intelligent-chatbot-with-qwen3-instruct-and-thinking-models/">Building an Intelligent Chatbot with Qwen3 Instruct and Thinking Models</a> appeared first on <a rel="nofollow" href="https://pyimagesearch.com">PyImageSearch</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Google DeepMind&#8217;s Gemma 4: MoE, Efficiency Tricks, and Benchmarks</title>
		<link>https://pyimagesearch.com/2026/06/22/google-deepminds-gemma-4-moe-efficiency-tricks-and-benchmarks/</link>
		
		<dc:creator><![CDATA[Piyush Thakur]]></dc:creator>
		<pubDate>Mon, 22 Jun 2026 12:45:00 +0000</pubDate>
				<category><![CDATA[Artificial Intelligence]]></category>
		<category><![CDATA[Generative AI]]></category>
		<category><![CDATA[Large Language Models]]></category>
		<category><![CDATA[Multimodal AI]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[agentic ai]]></category>
		<category><![CDATA[audio encoder]]></category>
		<category><![CDATA[function calling]]></category>
		<category><![CDATA[gemma 4]]></category>
		<category><![CDATA[google deepmind]]></category>
		<category><![CDATA[grouped query attention]]></category>
		<category><![CDATA[hugging face transformers]]></category>
		<category><![CDATA[kv cache]]></category>
		<category><![CDATA[large language models]]></category>
		<category><![CDATA[llm architecture]]></category>
		<category><![CDATA[long context]]></category>
		<category><![CDATA[mixture of experts]]></category>
		<category><![CDATA[model benchmarks]]></category>
		<category><![CDATA[model optimization]]></category>
		<category><![CDATA[moe model]]></category>
		<category><![CDATA[multimodal ai]]></category>
		<category><![CDATA[open weight models]]></category>
		<category><![CDATA[RoPE]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[vision transformer]]></category>
		<guid isPermaLink="false">https://pyimagesearch.com/?p=54330</guid>

					<description><![CDATA[<p>Table of Contents Google DeepMind’s Gemma 4: MoE, Efficiency Tricks, and Benchmarks Gemma 4 Model Family Overview: E2B, E4B, 31B, and MoE 26B A4B Gemma 4 Capabilities: Reasoning, Multimodal AI, and Thinking Mode Gemma 4 Thinking Mode: Chain-of-Thought Reasoning Explained&#8230;</p>
<p>The post <a rel="nofollow" href="https://pyimagesearch.com/2026/06/22/google-deepminds-gemma-4-moe-efficiency-tricks-and-benchmarks/">Google DeepMind&#8217;s Gemma 4: MoE, Efficiency Tricks, and Benchmarks</a> appeared first on <a rel="nofollow" href="https://pyimagesearch.com">PyImageSearch</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<hr class="wp-block-separator has-alpha-channel-opacity" id="TOC"/>


<div class="yoast-breadcrumbs"><span><span><a href="https://pyimagesearch.com/">Home</a></span></div>


<div class="toc">
<hr class="TOC"/>
<p class="has-large-font-size"><strong>Table of Contents</strong></p>
<ul>
    <li id="TOC-h1-Google-DeepMind-Gemma-4-MoE-Efficiency-Tricks-Benchmarks"><a rel="noopener" target="_blank" href="#h1-Google-DeepMind-Gemma-4-MoE-Efficiency-Tricks-Benchmarks">Google DeepMind’s Gemma 4: MoE, Efficiency Tricks, and Benchmarks</a></li>

    <li id="TOC-h2-Gemma-4-Model-Family-Overview-E2B-E4B-31B-MoE-26B-A4B"><a rel="noopener" target="_blank" href="#h2-Gemma-4-Model-Family-Overview-E2B-E4B-31B-MoE-26B-A4B">Gemma 4 Model Family Overview: E2B, E4B, 31B, and MoE 26B A4B</a></li>

    <li id="TOC-h2-Gemma-4-Capabilities-Reasoning-Multimodal-AI-Thinking-Mode"><a rel="noopener" target="_blank" href="#h2-Gemma-4-Capabilities-Reasoning-Multimodal-AI-Thinking-Mode">Gemma 4 Capabilities: Reasoning, Multimodal AI, and Thinking Mode</a></li>
    <ul>
        <li id="TOC-h3-Gemma-4-Thinking-Mode-Chain-of-Thought-Reasoning-Explained"><a rel="noopener" target="_blank" href="#h3-Gemma-4-Thinking-Mode-Chain-of-Thought-Reasoning-Explained">Gemma 4 Thinking Mode: Chain-of-Thought Reasoning Explained</a></li>
        <li id="TOC-h3-Image-Understanding-Object-Detection-OCR-GUI-Navigation"><a rel="noopener" target="_blank" href="#h3-Image-Understanding-Object-Detection-OCR-GUI-Navigation">Image Understanding: Object Detection, OCR, and GUI Navigation</a></li>
        <li id="TOC-h3-Gemma-4-Code-Generation-Images-UI-Reconstruction-Vision-to-Code"><a rel="noopener" target="_blank" href="#h3-Gemma-4-Code-Generation-Images-UI-Reconstruction-Vision-to-Code">Gemma 4 Code Generation from Images: UI Reconstruction and Vision-to-Code</a></li>
        <li id="TOC-h3-Gemma-4-Video-Understanding-Multimodal-Temporal-Reasoning"><a rel="noopener" target="_blank" href="#h3-Gemma-4-Video-Understanding-Multimodal-Temporal-Reasoning">Gemma 4 Video Understanding: Multimodal Temporal Reasoning</a></li>
        <li id="TOC-h3-Gemma-4-Audio-AI-Speech-Recognition-Translation-Audio-QA"><a rel="noopener" target="_blank" href="#h3-Gemma-4-Audio-AI-Speech-Recognition-Translation-Audio-QA">Gemma 4 Audio AI: Speech Recognition, Translation, and Audio Q&amp;A</a></li>
        <li id="TOC-h3-Gemma-4-Function-Calling-Tool-Use-Agentic-AI-Workflows"><a rel="noopener" target="_blank" href="#h3-Gemma-4-Function-Calling-Tool-Use-Agentic-AI-Workflows">Gemma 4 Function Calling: Tool Use and Agentic AI Workflows</a></li>
        <li id="TOC-h3-Gemma-4-System-Prompts-Instruction-Control-Chat-Behavior"><a rel="noopener" target="_blank" href="#h3-Gemma-4-System-Prompts-Instruction-Control-Chat-Behavior">Gemma 4 System Prompts: Instruction Control and Chat Behavior</a></li>
    </ul>

    <li id="TOC-h2-Gemma-4-Architecture-Overview-Shared-Transformer-Design-Principles"><a rel="noopener" target="_blank" href="#h2-Gemma-4-Architecture-Overview-Shared-Transformer-Design-Principles">Gemma 4 Architecture Overview: Shared Transformer Design Principles</a></li>
    <ul>
        <li id="TOC-h3-Gemma-4-Attention-Mechanism-Local-Global-Interleaved-Attention-Explained"><a rel="noopener" target="_blank" href="#h3-Gemma-4-Attention-Mechanism-Local-Global-Interleaved-Attention-Explained">Gemma 4 Attention Mechanism: Local + Global Interleaved Attention Explained</a></li>
        <li id="TOC-h3-Gemma-4-Efficiency-Tricks-GQA-K-V-Caching-Memory-Optimization"><a rel="noopener" target="_blank" href="#h3-Gemma-4-Efficiency-Tricks-GQA-K-V-Caching-Memory-Optimization">Gemma 4 Efficiency Tricks: GQA, K=V Caching, and Memory Optimization</a></li>
        <li id="TOC-h3-Gemma-4-Vision-Encoder-ViT-Based-Image-Processing-Architecture"><a rel="noopener" target="_blank" href="#h3-Gemma-4-Vision-Encoder-ViT-Based-Image-Processing-Architecture">Gemma 4 Vision Encoder: ViT-Based Image Processing Architecture</a></li>
    </ul>

    <li id="TOC-h2-Gemma-4-Architecture-Variants-Dense-vs-MoE-vs-On-Device-Models"><a rel="noopener" target="_blank" href="#h2-Gemma-4-Architecture-Variants-Dense-vs-MoE-vs-On-Device-Models">Gemma 4 Architecture Variants: Dense vs MoE vs On-Device Models</a></li>
    <ul>
        <li id="TOC-h3-Gemma-4-31B-Dense-Baseline"><a rel="noopener" target="_blank" href="#h3-Gemma-4-31B-Dense-Baseline">Gemma 4 31B: The Dense Baseline</a></li>
        <li id="TOC-h3-Gemma-4-26B-A4B-MoE-Sparse-Experts-Efficient-Inference-Explained"><a rel="noopener" target="_blank" href="#h3-Gemma-4-26B-A4B-MoE-Sparse-Experts-Efficient-Inference-Explained">Gemma 4 26B A4B MoE: Sparse Experts and Efficient Inference Explained</a></li>
        <li id="TOC-h3-Gemma-4-E2B-E4B-On-Device-Multimodal-AI-Models-Edge-Deployment"><a rel="noopener" target="_blank" href="#h3-Gemma-4-E2B-E4B-On-Device-Multimodal-AI-Models-Edge-Deployment">Gemma 4 E2B and E4B: On-Device Multimodal AI Models for Edge Deployment</a></li>
    </ul>

    <li id="TOC-h2-Gemma-4-Hardware-Requirements-GPU-VRAM-Inference-Cost-Breakdown"><a rel="noopener" target="_blank" href="#h2-Gemma-4-Hardware-Requirements-GPU-VRAM-Inference-Cost-Breakdown">Gemma 4 Hardware Requirements: GPU VRAM and Inference Cost Breakdown</a></li>

    <li id="TOC-h2-Gemma-4-Benchmarks-LMArena-Elo-Scores-Multimodal-Performance-Results"><a rel="noopener" target="_blank" href="#h2-Gemma-4-Benchmarks-LMArena-Elo-Scores-Multimodal-Performance-Results">Gemma 4 Benchmarks: LMArena Elo Scores and Multimodal Performance Results</a></li>

    <li id="TOC-h2-How-Run-Gemma-4-Transformers-llama-cpp-MLX-Cloud-Deployment-Options"><a rel="noopener" target="_blank" href="#h2-How-Run-Gemma-4-Transformers-llama-cpp-MLX-Cloud-Deployment-Options">How to Run Gemma 4: Transformers, llama.cpp, MLX, and Cloud Deployment Options</a></li>

    <li id="TOC-h2-Fine-Tuning-Gemma-4-LoRA-QLoRA-TRL-Training-Pipeline-Guide"><a rel="noopener" target="_blank" href="#h2-Fine-Tuning-Gemma-4-LoRA-QLoRA-TRL-Training-Pipeline-Guide">Fine-Tuning Gemma 4: LoRA, QLoRA, and TRL Training Pipeline Guide</a></li>

    <li id="TOC-h2-Gemma-4-Prompt-Formatting-Chat-Templates-Multimodal-Input-Structure"><a rel="noopener" target="_blank" href="#h2-Gemma-4-Prompt-Formatting-Chat-Templates-Multimodal-Input-Structure">Gemma 4 Prompt Formatting: Chat Templates and Multimodal Input Structure</a></li>

    <li id="TOC-h2-Which-Gemma-4-Model-Use-E2B-vs-E4B-vs-26B-MoE-vs-31B-Comparison"><a rel="noopener" target="_blank" href="#h2-Which-Gemma-4-Model-Use-E2B-vs-E4B-vs-26B-MoE-vs-31B-Comparison">Which Gemma 4 Model to Use: E2B vs E4B vs 26B MoE vs 31B Comparison</a></li>

    <li id="TOC-h2-Summary"><a rel="noopener" target="_blank" href="#h2-Summary">Summary</a></li>
    <ul>
        <li id="TOC-h3-Citation-Information"><a rel="noopener" target="_blank" href="#h3-Citation-Information">Citation Information</a></li>
    </ul>
</ul>
</div>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h1-Google-DeepMind-Gemma-4-MoE-Efficiency-Tricks-Benchmarks"/>



<h2 class="wp-block-heading"><a href="#TOC-h1-Google-DeepMind-Gemma-4-MoE-Efficiency-Tricks-Benchmarks">Google DeepMind’s Gemma 4: MoE, Efficiency Tricks, and Benchmarks</a></h2>



<p>Google DeepMind&#8217;s <strong><a href="https://deepmind.google/models/gemma/gemma-4/" target="_blank" rel="noreferrer noopener">Gemma 4</a></strong> is one of the most compelling open-weight model releases in recent memory. It&#8217;s not just one model; it is a carefully designed family spanning from tiny on-device variants to a 31-billion-parameter powerhouse, all built with multimodal reasoning, long context, and real deployment constraints in mind. And crucially, these models are released under an Apache 2.0 license, meaning you can use, modify, and deploy them commercially without restriction.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://pyimagesearch.com/wp-content/uploads/2026/06/google-deepminds-gemma-4-moe-efficiency-tricks-benchmarks-featured.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="940" height="780" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/google-deepminds-gemma-4-moe-efficiency-tricks-benchmarks-featured.png?lossy=2&strip=1&webp=1" alt="google-deepminds-gemma-4-moe-efficiency-tricks-benchmarks-featured.png" class="wp-image-54362"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/google-deepminds-gemma-4-moe-efficiency-tricks-benchmarks-featured.png?size=126x105&lossy=2&strip=1&webp=1 126w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/google-deepminds-gemma-4-moe-efficiency-tricks-benchmarks-featured-300x249.png?lossy=2&strip=1&webp=1 300w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/google-deepminds-gemma-4-moe-efficiency-tricks-benchmarks-featured.png?size=378x314&lossy=2&strip=1&webp=1 378w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/google-deepminds-gemma-4-moe-efficiency-tricks-benchmarks-featured.png?size=504x418&lossy=2&strip=1&webp=1 504w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/google-deepminds-gemma-4-moe-efficiency-tricks-benchmarks-featured.png?size=630x523&lossy=2&strip=1&webp=1 630w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/google-deepminds-gemma-4-moe-efficiency-tricks-benchmarks-featured-768x637.png?lossy=2&strip=1&webp=1 768w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/google-deepminds-gemma-4-moe-efficiency-tricks-benchmarks-featured.png?lossy=2&strip=1&webp=1 940w" sizes="(max-width: 940px) 100vw, 940px" /></a></figure></div>


<p>In this post, we will peel back the hood and explain what makes Gemma 4 tick, including the architecture, the clever efficiency tricks, the multimodal capabilities, what hardware you actually need to run these models, and how to get started in code. No prior deep knowledge of transformers required, though some familiarity will help. </p>



<p>Whether you are evaluating Gemma 4 for a production use case, curious about the architecture, or just want to know which variant to reach for, this post has you covered.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/06/image-75-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="839" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-75-1024x839.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54364"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-75-1024x839.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-75-1024x839.png?size=126x103&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-75-1024x839.png?size=252x206&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-75-1024x839.png?size=378x310&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-75-1024x839.png?size=504x413&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-75-1024x839.png?size=630x516&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 1:</strong> Gemma 4 Architecture (source: <a href="https://newsletter.maartengrootendorst.com/p/a-visual-guide-to-gemma-4" target="_blank" rel="noreferrer noopener">Grootendorst, 2026</a>)</figcaption></figure></div>


<p>This lesson is the 1st in a 5-part series on <strong>Google DeepMind&#8217;s Gemma 4</strong>:</p>



<ol class="wp-block-list">
<li><em><strong><a href="https://pyimg.co/uqxzw" target="_blank" rel="noreferrer noopener">Google DeepMind’s Gemma 4: MoE, Efficiency Tricks, and Benchmarks</a></strong></em><strong> (this tutorial)</strong></li>



<li><em>Lesson 2</em></li>



<li><em>Lesson 3</em></li>



<li><em>Lesson 4</em></li>



<li><em>Lesson 5</em></li>
</ol>



<p><strong>To learn </strong><strong>how Gemma 4&#8217;s architecture, Mixture-of-Experts design, multimodal capabilities, and efficiency optimizations work</strong><strong>, </strong><em><strong>just keep reading.</strong></em></p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p>Would you like immediate access to 3,457 images curated and labeled with hand gestures to train, explore, and experiment with &#8230; for free? Head over to <a href="https://universe.roboflow.com/isl/az-6mqow?ref=pyimagesearch" target="_blank" rel="noreferrer noopener">Roboflow</a> and get a free account to grab these hand gesture images. </p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<!-- wp:paragraph -->
<h3>Need Help Configuring Your Development Environment?</h3>
<!-- /wp:paragraph -->

<!-- wp:image {"align":"center","id":18137,"sizeSlug":"large","linkDestination":"custom"} -->
<figure class="wp-block-image aligncenter size-large"><a href="https://pyimagesearch.com/pyimagesearch-university/" target="_blank" rel="noreferrer noopener"><img decoding="async" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2021/01/pyimagesearch_plus_jupyter.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-18137" srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2021/01/pyimagesearch_plus_jupyter.png?lossy=2&strip=1&webp=1 500w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2021/01/pyimagesearch_plus_jupyter.png?size=126x84&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2021/01/pyimagesearch_plus_jupyter.png?size=252x168&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2021/01/pyimagesearch_plus_jupyter.png?size=378x253&lossy=2&strip=1&webp=1 378w" sizes="(max-width: 500px) 100vw, 500px" /></a><figcaption>Having trouble configuring your development environment? Want access to pre-configured Jupyter Notebooks running on Google Colab? Be sure to join <a href="https://pyimagesearch.com/pyimagesearch-university/" target="_blank" rel="noreferrer noopener" aria-label=" (opens in a new tab)">PyImageSearch University</a> — you will be up and running with this tutorial in a matter of minutes. </figcaption></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>All that said, are you:</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li>Short on time?</li><li>Learning on your employer’s administratively locked system?</li><li>Wanting to skip the hassle of fighting with the command line, package managers, and virtual environments?</li><li><strong>Ready to run the code immediately on your Windows, macOS, or Linux system?</strong></li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>Then join <a href="https://pyimagesearch.com/pyimagesearch-university/" target="_blank">PyImageSearch University</a> today!</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><strong>Gain access to Jupyter Notebooks for this tutorial and other PyImageSearch guides pre-configured to run on Google Colab’s ecosystem right in your web browser!</strong> No installation required.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>And best of all, these Jupyter Notebooks will run on Windows, macOS, and Linux!</p>
<!-- /wp:paragraph -->



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Gemma-4-Model-Family-Overview-E2B-E4B-31B-MoE-26B-A4B"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Gemma-4-Model-Family-Overview-E2B-E4B-31B-MoE-26B-A4B">Gemma 4 Model Family Overview: E2B, E4B, 31B, and MoE 26B A4B</a></h2>



<p>Before diving into how these models work, let us first look at the lineup. There are 4 models:</p>



<p><strong>Gemma 4 E2B and E4B</strong><strong>:</strong> The smallest models in the family, designed to run efficiently on-device (think: your phone). The &#8220;E&#8221; stands for <em>effective parameters</em>, a concept we&#8217;ll unpack below. They support text, images, and even audio.</p>



<p><strong>Gemma 4 31B:</strong> A dense 31-billion parameter model. Dense means every parameter participates in every inference pass. Think of it as the &#8220;traditional&#8221; heavyweight.</p>



<p><strong>Gemma 4 26B A4B:</strong> A Mixture-of-Experts model with 26 billion total parameters, but only 4 billion &#8220;active&#8221; during any given computation (inference). The &#8220;A&#8221; stands for <em>active parameters</em>. It runs with the speed of a 4B model despite its much larger knowledge capacity.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/06/image-76-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="423" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-76-1024x423.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54366"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-76-1024x423.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-76-1024x423.png?size=126x52&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-76-1024x423.png?size=252x104&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-76-1024x423.png?size=378x156&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-76-1024x423.png?size=504x208&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-76-1024x423.png?size=630x260&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Table 1:</strong> Gemma 4 Model Family Overview (source: <a href="https://deepmind.google/models/gemma/gemma-4/" target="_blank" rel="noreferrer noopener">Google DeepMind</a>)</figcaption></figure></div>


<p>The lineup spans from phone-friendly to server-grade, so you can pick the right model for your constraints. All 4 models are <strong>multimodal</strong>; they can reason over images alongside text. The 2 smaller models (E2B and E4B) go a step further and also handle <strong>audio</strong>.</p>



<p>Every model ships in both a base (pre-trained) and instruction-tuned (IT) version. The instruction-tuned versions are what most practitioners will want to use for tasks like chat, reasoning, and function-calling.</p>



<p>All 4 models are available on <a href="https://huggingface.co/collections/google/gemma-4" target="_blank" rel="noreferrer noopener">Hugging Face</a>, <a href="https://www.kaggle.com/models/google/gemma-4" target="_blank" rel="noreferrer noopener">Kaggle</a>, <a href="https://ollama.com/library/gemma4" target="_blank" rel="noreferrer noopener">Ollama</a>, <a href="https://lmstudio.ai/models/gemma-4" target="_blank" rel="noreferrer noopener">LM Studio</a>, and <a href="https://hub.docker.com/r/ai/gemma4" target="_blank" rel="noreferrer noopener">Docker</a>. Also, it can run via Transformers, llama.cpp, MLX, and several other popular inference stacks.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Gemma-4-Capabilities-Reasoning-Multimodal-AI-Thinking-Mode"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Gemma-4-Capabilities-Reasoning-Multimodal-AI-Thinking-Mode">Gemma 4 Capabilities: Reasoning, Multimodal AI, and Thinking Mode</a></h2>



<p>Before getting into architecture, it is worth understanding the capabilities these models were trained and evaluated for. The design choices only make sense in that context.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Gemma-4-Thinking-Mode-Chain-of-Thought-Reasoning-Explained"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Gemma-4-Thinking-Mode-Chain-of-Thought-Reasoning-Explained">Gemma 4 Thinking Mode: Chain-of-Thought Reasoning Explained</a></h3>



<p>All Gemma 4 models are designed as capable reasoners with configurable &#8220;thinking mode.&#8221; When enabled, the model produces an internal chain-of-thought before arriving at its final answer, similar in spirit to what you would see with OpenAI&#8217;s o-series or Anthropic&#8217;s extended thinking. This is particularly valuable for math, logic, and multi-step planning tasks.</p>



<p>Thinking can be toggled per-request. In the Transformers API, you enable it by passing <code data-enlighter-language="python" class="EnlighterJSRAW">enable_thinking=True</code> to the <code data-enlighter-language="python" class="EnlighterJSRAW">apply_chat_template</code> call:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Google DeepMind’s Gemma 4: MoE, Efficiency Tricks, and Benchmarks" data-enlighter-group="1">inputs = processor.apply_chat_template(
    messages,
    tokenize=True,
    return_dict=True,
    return_tensors="pt",
    add_generation_prompt=True,
    enable_thinking=True,  # activates chain-of-thought mode
).to(model.device)
</pre>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Image-Understanding-Object-Detection-OCR-GUI-Navigation"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Image-Understanding-Object-Detection-OCR-GUI-Navigation">Image Understanding: Object Detection, OCR, and GUI Navigation</a></h3>



<p>The vision capabilities in Gemma 4 are genuinely impressive, especially for an open-weight model. All 4 model sizes could reliably perform bounding-box detection, returning results natively as structured JSON without any special grammar constraints or prompting tricks.</p>



<p>For example, given a UI screenshot and the prompt &#8220;What&#8217;s the bounding box for the &#8216;submit&#8217; button?&#8221;, the model returns something like:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="json" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Google DeepMind’s Gemma 4: MoE, Efficiency Tricks, and Benchmarks" data-enlighter-group="2">[{"box_2d": [171, 75, 245, 308], "label": "view recipe element"}]
</pre>



<p>The coordinates are normalized to a 1000×1000 grid regardless of the original image dimensions, which makes post-processing straightforward. This makes Gemma 4 a strong candidate for tasks like automated UI testing, document parsing, and robotic process automation.</p>



<p>Image captioning was tested across all 4 sizes and all performed well, accurately capturing details such as the type of bird, the architectural style of background buildings, and whether the scene was indoors or outdoors. Even the tiny E2B model produced detailed and accurate captions.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Gemma-4-Code-Generation-Images-UI-Reconstruction-Vision-to-Code"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Gemma-4-Code-Generation-Images-UI-Reconstruction-Vision-to-Code">Gemma 4 Code Generation from Images: UI Reconstruction and Vision-to-Code</a></h3>



<p>One standout test: When given each model a screenshot of a webpage and asked it to write the HTML to recreate it. With thinking mode enabled and a token budget of 4,000 output tokens, the larger models (26B A4B and 31B) produced near-faithful reproductions. The smaller E4B model held its own remarkably well, while E2B showed the expected drop-off in fidelity.</p>



<p>This capability to understand a visual layout and translate it into working code has real applications for prototyping, design-to-code workflows, and accessibility tooling.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Gemma-4-Video-Understanding-Multimodal-Temporal-Reasoning"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Gemma-4-Video-Understanding-Multimodal-Temporal-Reasoning">Gemma 4 Video Understanding: Multimodal Temporal Reasoning</a></h3>



<p>Gemma 4 can process video input, though capabilities differ by size. The smaller E2B and E4B models accept video <em>with </em>audio, treating it as a combined audio-visual signal. The larger 31B and 26B A4B models accept video <em>without</em> audio because they lack an audio encoder, which we will discuss below.</p>



<p>In informal testing with a live concert video, E4B correctly identified the genre of music, the mood of the song lyrics, and the stage setup and crowd. The 31B model gave a detailed description of the visual elements and even identified a brand visible on a large screen, despite not having access to audio. Neither model had been explicitly fine-tuned on video data; this capability emerged from the multimodal training.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Gemma-4-Audio-AI-Speech-Recognition-Translation-Audio-QA"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Gemma-4-Audio-AI-Speech-Recognition-Translation-Audio-QA">Gemma 4 Audio AI: Speech Recognition, Translation, and Audio Q&amp;A</a></h3>



<p>The E2B and E4B models include a dedicated audio encoder, enabling end-to-end speech understanding. This is novel for an open-weight model at this scale. Practically, it means you can send raw audio (as an MP4 or audio file) and ask the model questions about the audio, with no separate transcription step required.</p>



<p>This is particularly useful for:</p>



<ul class="wp-block-list">
<li>Automatic speech recognition (ASR) in a single-model pipeline</li>



<li>Multilingual audio translation</li>



<li>Video Q&amp;A where both the speech and visuals matter</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Gemma-4-Function-Calling-Tool-Use-Agentic-AI-Workflows"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Gemma-4-Function-Calling-Tool-Use-Agentic-AI-Workflows">Gemma 4 Function Calling: Tool Use and Agentic AI Workflows</a></h3>



<p>Gemma 4 has built-in support for structured function/tool calling, both in text-only and multimodal contexts. This is essential for building agents: systems in which the model needs to decide which tool to invoke, with what arguments, in response to a user request. The fact that this is natively supported (rather than requiring prompt-engineering workarounds) makes Gemma 4 a serious option for agentic workflows running locally or in constrained environments.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Gemma-4-System-Prompts-Instruction-Control-Chat-Behavior"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Gemma-4-System-Prompts-Instruction-Control-Chat-Behavior">Gemma 4 System Prompts: Instruction Control and Chat Behavior</a></h3>



<p>Gemma 4 introduces first-class support for the <code data-enlighter-language="python" class="EnlighterJSRAW">system</code> role in conversations. In prior Gemma versions, system-level instructions had to be blended into the user turn in ad hoc ways. Now the model is trained to recognize and respect a proper system prompt, which makes deploying it inside structured applications (where you want to set tone, persona, or capabilities) significantly cleaner.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Gemma-4-Architecture-Overview-Shared-Transformer-Design-Principles"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Gemma-4-Architecture-Overview-Shared-Transformer-Design-Principles">Gemma 4 Architecture Overview: Shared Transformer Design Principles</a></h2>



<p>Despite their size differences, all Gemma 4 models share the same core architectural DNA. Let us go through each shared component one by one.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Gemma-4-Attention-Mechanism-Local-Global-Interleaved-Attention-Explained"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Gemma-4-Attention-Mechanism-Local-Global-Interleaved-Attention-Explained">Gemma 4 Attention Mechanism: Local + Global Interleaved Attention Explained</a></h3>



<p>To appreciate what Gemma 4 does here, you first need to understand what &#8220;attention&#8221; means in a transformer model.</p>



<p><strong>The classic attention problem:</strong> In a standard transformer, every word in your input looks at every other word to figure out context. This is called <em>full</em> or <em>global</em> attention. It is powerful but brutally expensive because the computation grows with the <em>square</em> of the input length. Double your input length, and you quadruple the cost.</p>



<p><strong>Sliding window attention (local attention):</strong> Imagine reading a book, but instead of remembering every page you&#8217;ve ever read, you can only reference the last 5 pages. That&#8217;s sliding window attention. Each token only attends to the N most recent tokens (a &#8220;window&#8221;), not the entire sequence. This is dramatically cheaper to compute.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/06/image-77-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="529" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-77-1024x529.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54370"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-77-1024x529.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-77-1024x529.png?size=126x65&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-77-1024x529.png?size=252x130&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-77-1024x529.png?size=378x195&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-77-1024x529.png?size=504x260&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-77-1024x529.png?size=630x325&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 2:</strong> Global Attention vs Sliding Window Attention (source: <a href="https://newsletter.maartengrootendorst.com/p/a-visual-guide-to-gemma-4" target="_blank" rel="noreferrer noopener">Grootendorst, 2026</a>)</figcaption></figure></div>


<p>Here is the tradeoff made tangible: say you are generating a response to a long legal document. With a sliding window of 512 tokens, any given token looks only at the 512 tokens before it, rather than the entire 10,000-token document. That saves enormous compute, but risks losing context from early in the document.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/06/image-78-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="263" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-78-1024x263.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54373"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-78-1024x263.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-78-1024x263.png?size=126x32&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-78-1024x263.png?size=252x65&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-78-1024x263.png?size=378x97&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-78-1024x263.png?size=504x129&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-78-1024x263.png?size=630x162&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 3:</strong> Global Attention vs Sliding Window Attention (source: <a href="https://newsletter.maartengrootendorst.com/p/a-visual-guide-to-gemma-4" target="_blank" rel="noreferrer noopener">Grootendorst, 2026</a>)</figcaption></figure></div>


<p><strong>The interleaving solution:</strong> Gemma 4 does not pick one strategy; it alternates between them across layers. Most layers use the efficient sliding window, but every few layers, a full global attention layer kicks in and &#8220;resets&#8221; the context by attending to everything. Think of it like a student who mostly skims through dense reading, but every few chapters pauses to re-read everything they have covered.</p>



<p>In practice, the E2B model uses a 4-local-to-1-global pattern. All other models use a 5:1 ratio. Crucially, Gemma 4 ensures the <em>final</em> layer is always a global attention layer, so the model&#8217;s last word on any sequence is fully informed, a deliberate fix from Gemma 3 where the last layer could end up being local.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/06/image-79-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="813" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-79-1024x813.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54375"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-79-1024x813.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-79-1024x813.png?size=126x100&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-79-1024x813.png?size=252x200&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-79-1024x813.png?size=378x300&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-79-1024x813.png?size=504x400&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-79-1024x813.png?size=630x500&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 4:</strong> Gemma 3 vs Gemma 4 attention mechanism (source: <a href="https://newsletter.maartengrootendorst.com/p/a-visual-guide-to-gemma-4" target="_blank" rel="noreferrer noopener">Grootendorst, 2026</a>)</figcaption></figure></div>


<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Gemma-4-Efficiency-Tricks-GQA-K-V-Caching-Memory-Optimization"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Gemma-4-Efficiency-Tricks-GQA-K-V-Caching-Memory-Optimization">Gemma 4 Efficiency Tricks: GQA, K=V Caching, and Memory Optimization</a></h3>



<p>Even with interleaving, global attention layers are still the most expensive part. Gemma 4 layers on three additional tricks to tame the cost.</p>



<h4 class="wp-block-heading">Grouped Query Attention (GQA)</h4>



<p>In standard multi-head attention, every &#8220;head&#8221; maintains its own set of Key and Value matrices. This creates a large memory footprint because all of these have to be cached during generation (this is called the KV-cache).</p>



<p>GQA is the idea that multiple Query heads can <em>share</em> the same set of Keys and Values. Imagine 8 students all reading from the same textbook instead of each having their own, with the same knowledge and much less paper.</p>



<p>In Gemma 4&#8217;s global attention layers, 8 Query heads share a single KV pair. This dramatically reduces what needs to be stored in the cache, which is especially significant because global attention has to cache the <em>entire</em> context (versus the local attention layers, which only cache a small window).</p>



<p>To compensate for any quality loss from fewer KV heads, Gemma 4 doubles the dimensionality of the Keys, giving each shared Key more expressive capacity.</p>



<h4 class="wp-block-heading">Keys Equal Values (K=V)</h4>



<p>Here&#8217;s an even bolder efficiency move: in global attention layers, Gemma 4 sets the Key and Value matrices to be identical. Instead of storing both K and V separately in cache, you only need to store one. The KV-cache effectively becomes a K-cache for those layers, cutting memory requirements in half at that level.</p>



<p>This sounds like it might hurt quality significantly, but in practice the performance impact turns out to be modest, a good trade for the memory savings.</p>



<h4 class="wp-block-heading">p-RoPE: Smarter Positional Encoding</h4>



<p>To understand this trick, you need to know how transformers track word order. Because attention has no built-in sense of sequence (unlike an RNN), position is injected into embeddings explicitly. The popular method for this is <strong>Rotary Positional Encoding (RoPE)</strong>.</p>



<p><strong>How RoPE works:</strong> Each embedding vector is split into pairs of values. Each pair is thought of as a 2D vector pointing in some direction. RoPE <em>rotates</em> each pair by a position-dependent angle, so earlier words get one rotation, later words get another. By comparing how much two vectors have been rotated, the model can infer their relative distance.</p>



<p>The rotation speeds vary: the first pairs rotate quickly (high frequency) and the last pairs rotate very slowly (low frequency). The high-frequency pairs are great for tracking <em>where</em> a word is. The low-frequency pairs rotate so little that they barely carry positional information at all, making them closer to the raw semantic meaning of the word.</p>



<p>Here is the problem Gemma 4 solves: over very long sequences, even those tiny low-frequency rotations accumulate and start to introduce misleading positional noise into what should be a semantic signal. Think of it like a clock&#8217;s hour hand being used to measure seconds, where the movement is technically there but too small to be meaningful and can cause errors.</p>



<p><strong>p-RoPE</strong> (pruned RoPE) solves this elegantly: apply rotational encoding only to the first <em>p</em> fraction of pairs, and zero out the rest. If p = 0.25, only the top 25% of pairs (the high-frequency, positional ones) get rotation. The low-frequency pairs are left clean, with pure semantic content and no positional noise. This is especially important in global attention, where the context can span tens of thousands of tokens.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Gemma-4-Vision-Encoder-ViT-Based-Image-Processing-Architecture"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Gemma-4-Vision-Encoder-ViT-Based-Image-Processing-Architecture">Gemma 4 Vision Encoder: ViT-Based Image Processing Architecture</a></h3>



<p>All four Gemma 4 models are multimodal, meaning they can reason about images as well as text. To make this work, images need to be converted into a format the language model can process. The component responsible for this is the <strong>Vision Encoder</strong>, built on a Vision Transformer (ViT).</p>



<p><strong>The core idea of a ViT:</strong> Rather than treating an image as a grid of pixels, a ViT slices the image into fixed-size patches (typically 16×16 pixels each) and treats each patch like a &#8220;word token.&#8221; The sequence of patches goes through a transformer, which produces an embedding for each patch capturing its visual content and context.</p>



<h4 class="wp-block-heading">Handling Variable Aspect Ratios with 2D RoPE</h4>



<p>Standard ViTs assume a square input image with a fixed grid of patches. But real-world images come in all shapes (e.g., wide panoramas, tall portraits, and square thumbnails). Forcing every image into a square distorts content and destroys spatial relationships.</p>



<p>Gemma 4 addresses this by using <strong>2D RoPE</strong> for its vision encoder. Instead of encoding patches with a single 1D position (patch 1, patch 2, patch 3, etc.), each patch is given a 2D position: its (row, column) coordinates in the image grid. The patch embedding is split into two halves where one half encodes the horizontal position, and the other encodes the vertical position. This way, a patch in the upper-left corner of a wide landscape and a patch in the upper-left corner of a tall portrait both correctly identify themselves as &#8220;top-left,&#8221; regardless of the total number of patches.</p>



<p>Images are also adaptively resized to maintain the original aspect ratio while ensuring the dimensions are multiples of 16 (the patch size), with padding added where needed.</p>



<h4 class="wp-block-heading">Soft Token Budget: Controlling Variable Resolution</h4>



<p>More patches mean more tokens fed into the language model, which increases computational cost. To give developers control over this, Gemma 4 introduces a <strong>soft token budget</strong>: a configurable cap on how many visual tokens are processed by the LLM.</p>



<p>Here&#8217;s a concrete example. Suppose you set a budget of 280 tokens. The model will resize your image so that the total resulting patches, after pooling every 3×3 patch block into a single embedding, stays within 280. A budget of 1120 tokens lets high-resolution images through with much more visual detail; a budget of 70 tokens dramatically downsamples the image. The right budget depends on your task:</p>



<ul class="wp-block-list">
<li>Describing a photo? 70–140 tokens is probably fine.</li>



<li>Reading a scanned invoice with fine print? You&#8217;d want 560–1120 tokens.</li>



<li>Analyzing consecutive video frames quickly? Lower budgets keep things fast.</li>
</ul>



<h4 class="wp-block-heading">Linear Projection: Bridging Vision and Language</h4>



<p>The patch embeddings produced by the ViT live in a different dimensional space than the word embeddings Gemma 4 was trained on. Feeding mismatched embeddings into the language model would be like asking someone to add meters and kilograms, which makes no sense.</p>



<p>To solve this, a small neural network called a <strong>linear projection</strong> learns to map vision embeddings into the exact dimensional space Gemma 4 expects. This projection is trained alongside the language model so it perfectly aligns the two embedding spaces. A normalization step (RMSNorm) follows the projection to ensure the scale of visual embeddings matches what the transformer layers anticipate.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Gemma-4-Architecture-Variants-Dense-vs-MoE-vs-On-Device-Models"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Gemma-4-Architecture-Variants-Dense-vs-MoE-vs-On-Device-Models">Gemma 4 Architecture Variants: Dense vs MoE vs On-Device Models</a></h2>



<p>Now that you understand what all Gemma 4 models share, let us look at what makes each variant distinctive.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Gemma-4-31B-Dense-Baseline"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Gemma-4-31B-Dense-Baseline">Gemma 4 31B: The Dense Baseline</a></h3>



<p>The 31B model is the most architecturally conventional in the family. It is a <strong>dense transformer</strong>, meaning every parameter is used on every forward pass. Think of it as a large, all-purpose Swiss Army knife: every tool is always there, every tool can always be used.</p>



<p>Its architecture closely follows Gemma 3&#8217;s 27B model in spirit, but applies all the global attention improvements we&#8217;ve described: K=V, 8-query GQA, doubled Key dimensions, and p-RoPE. It has 60 layers (slightly fewer than Gemma 3&#8217;s 27B model with 62 layers) but compensates with a wider hidden dimension, meaning more parameters per layer rather than more layers.</p>



<p>For most inference scenarios that require a powerful, capable model without the complexity of MoE routing, this is the model to reach for.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Gemma-4-26B-A4B-MoE-Sparse-Experts-Efficient-Inference-Explained"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Gemma-4-26B-A4B-MoE-Sparse-Experts-Efficient-Inference-Explained">Gemma 4 26B A4B MoE: Sparse Experts and Efficient Inference Explained</a></h3>



<p>This is where things get architecturally interesting. The 26B A4B model uses a design called <strong>Mixture of Experts (MoE)</strong> to achieve something remarkable: the knowledge capacity of a 26-billion-parameter model at roughly the inference cost of a 4-billion-parameter model.</p>



<h4 class="wp-block-heading">How Mixture of Experts Works</h4>



<p>In a standard (dense) transformer, every layer contains a single large feedforward neural network (FFNN) that processes every token. In a MoE layer, that single FFNN is replaced by a <em>collection</em> of smaller FFNNs called <strong>experts</strong>, plus a lightweight <strong>router</strong> network.</p>



<p>When a token arrives at a MoE layer, here&#8217;s what happens step by step:</p>



<ul class="wp-block-list">
<li>The router examines the token&#8217;s embedding and assigns a probability score to each expert.</li>



<li>The top-scoring experts are selected (in Gemma 4, 8 out of 128 experts are chosen).</li>



<li>Each selected expert processes the token independently and produces an output.</li>



<li>The outputs are weighted by the router&#8217;s probability scores and summed together.</li>
</ul>



<p>This means for any given token, only 8 experts are doing work, while the other 120 are idle. The total number of parameters that get loaded into memory (the &#8220;sparse&#8221; parameters) is 26B. But the number doing active computation (the &#8220;active&#8221; parameters) is only <img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/658/6588c95074f2609674f5fe10ab63f88f-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='\sim' title='\sim' class='latex' />4B. Hence: 26B A4B.</p>



<p>A good analogy: imagine a hospital with 128 specialist doctors, but any given patient only sees 8 of them during their visit. The hospital has the collective knowledge of all 128 doctors, but each consultation only draws on a relevant subset.</p>



<h4 class="wp-block-heading">The Shared Expert</h4>



<p>Gemma 4&#8217;s MoE adds one more element: a <strong>shared expert</strong> that is always activated for every single token, regardless of what the router decides. This expert is three times larger than the other experts.</p>



<p>The intuition is compelling. Some knowledge is universally useful (e.g., grammar, common-sense reasoning, and factual recall) and should always be applied. The shared expert holds this general knowledge. The routed experts hold more specialized knowledge that is selectively engaged depending on the content. This is similar to how you would always use your native language&#8217;s grammar rules (shared expert), but only pull out domain-specific vocabulary when discussing, say, molecular biology (a selected expert).</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Gemma-4-E2B-E4B-On-Device-Multimodal-AI-Models-Edge-Deployment"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Gemma-4-E2B-E4B-On-Device-Multimodal-AI-Models-Edge-Deployment">Gemma 4 E2B and E4B: On-Device Multimodal AI Models for Edge Deployment</a></h3>



<p>These are the smallest and most novel models in the family. They are designed to run on devices with severely limited RAM, with smartphones being the primary target. Two key innovations enable this: <strong>Per-Layer Embeddings</strong> and an <strong>Audio Encoder</strong>.</p>



<h4 class="wp-block-heading">Per-Layer Embeddings (PLE): Teaching Each Layer Its Own Vocabulary</h4>



<p>In a standard transformer, each token is looked up in a single embedding table at the very start. That means one embedding per token, used everywhere. A richer context comes from stacking many transformer layers on top.</p>



<p>Per-Layer Embeddings take a different approach. Each token has not one embedding, but a <em>separate</em> embedding for every layer in the model. Continuing our analogy: instead of greeting a visitor with one name badge, you give them a different badge for each room they will enter, with each badge describing their role in the context of that room&#8217;s purpose.</p>



<p>For the E2B model, this means 262,144 vocabulary tokens × 35 layers × 256 dimensions per layer-embedding. That&#8217;s a large table, but here&#8217;s the key insight: this table lives in <strong>flash storage</strong> (like your phone&#8217;s SSD), not in RAM. RAM is precious and fast; flash is abundant and cheap. During inference, the needed embeddings are fetched from flash memory once at the start, then used at each layer.</p>



<p>At each layer, a gating function decides how to weight the values in the fetched embedding, effectively letting the model emphasize different aspects of a token&#8217;s meaning at different depths. The resulting embedding is projected up to the full model dimension and added into the main processing stream, functioning as a kind of continuous &#8220;reminder&#8221; to each layer of what the original token meant, preventing that meaning from getting diluted as context accumulates.</p>



<p>The &#8220;E&#8221; in E2B means <em>effective parameters</em>, referring to the parameters that actually reside in RAM and do computation. The large layer-embedding table is intentionally excluded from this count because it sits in flash, not in working memory.</p>



<h4 class="wp-block-heading">The Audio Encoder</h4>



<p>The E2B and E4B models go one step further: they accept raw audio as input, enabling tasks like speech recognition, audio translation, and voice-based Q&amp;A.</p>



<p>Audio processing follows a three-stage pipeline before the language model ever sees it:</p>



<p><strong>Stage 1</strong><strong>.</strong><strong> Feature Extraction:</strong> The raw audio waveform is converted into a <strong>mel-spectrogram</strong>, which is a 2D image-like representation where the horizontal axis represents time and the vertical axis represents frequency. This is similar to how sheet music represents music: time flows left to right, and the vertical position tells you the pitch. The mel scale emphasizes frequency ranges the human ear is most sensitive to.</p>



<p><strong>Stage 2</strong><strong>.</strong><strong> Chunking:</strong> The mel-spectrogram is divided into overlapping chunks, turning the continuous audio signal into a structured sequence of frames ready for processing.</p>



<p><strong>Stage 3</strong><strong>.</strong><strong> Downsampling with Convolutions:</strong> Two 2D convolutional layers process and compress these chunks, reducing the sequence length into a manageable number of &#8220;soft tokens&#8221; (continuous, dense embeddings rather than discrete word tokens). This is the audio equivalent of the ViT&#8217;s patch pooling: it reduces a large number of raw signals into a compact, information-rich sequence.</p>



<p>The resulting audio embeddings pass through a <strong>Conformer encoder</strong>, a transformer-style architecture augmented with convolutional modules, which is well-suited for sequential signal data such as audio. The Conformer&#8217;s output is then linearly projected into Gemma 4&#8217;s embedding space, exactly as we saw with the vision encoder.</p>



<p>The beauty of this design is that it&#8217;s modality-agnostic in spirit: whether it&#8217;s a word, an image patch, or an audio chunk, the final product is always a sequence of aligned embeddings that the language model can reason over uniformly.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Gemma-4-Hardware-Requirements-GPU-VRAM-Inference-Cost-Breakdown"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Gemma-4-Hardware-Requirements-GPU-VRAM-Inference-Cost-Breakdown">Gemma 4 Hardware Requirements: GPU VRAM and Inference Cost Breakdown</a></h2>



<p>Understanding memory requirements is critical before committing to a deployment setup. Here are the approximate GPU or TPU memory requirements for running inference at different precision levels.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/06/image-80-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="290" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-80-1024x290.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54378"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-80-1024x290.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-80-1024x290.png?size=126x36&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-80-1024x290.png?size=252x71&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-80-1024x290.png?size=378x107&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-80-1024x290.png?size=504x143&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-80-1024x290.png?size=630x178&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Table 2:</strong> Gemma 4 Hardware Requirements (source: <a href="https://deepmind.google/models/gemma/gemma-4/" target="_blank" rel="noreferrer noopener">Google DeepMind</a>)</figcaption></figure></div>


<p>At full 16-bit precision, the 31B model needs roughly 60 GB of VRAM, which is equivalent to two A100 80GB GPUs or a single H100. But at 4-bit quantization, the same model fits in about 17 GB, which means a single RTX 4090 or A10G becomes viable.</p>



<p>The 26B A4B model is interesting: its full-precision footprint of 48 GB looks large, but because only 4B parameters are active during inference, it runs significantly faster than the 31B despite needing less memory. At 4-bit, it drops to 15.6 GB.</p>



<p>The E2B and E4B models, at 4-bit quantization, fit in 3–5 GB of VRAM, placing them in genuinely on-device territory for modern phones and edge hardware. The E suffix models are especially designed for this: their PLE (Per-Layer Embeddings) tables live in flash storage, so the actual RAM footprint is even smaller than these numbers suggest during full inference runs on mobile devices.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Gemma-4-Benchmarks-LMArena-Elo-Scores-Multimodal-Performance-Results"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Gemma-4-Benchmarks-LMArena-Elo-Scores-Multimodal-Performance-Results">Gemma 4 Benchmarks: LMArena Elo Scores and Multimodal Performance Results</a></h2>



<p>Gemma 4&#8217;s large models set a new bar for what&#8217;s achievable in the open-weight space at this parameter count.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/06/image-81-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="952" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-81-1024x952.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54380"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-81-1024x952.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-81-1024x952.png?size=126x117&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-81-1024x952.png?size=252x234&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-81-1024x952.png?size=378x351&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-81-1024x952.png?size=504x469&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-81-1024x952.png?size=630x586&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 5:</strong> Model Performance vs Size (source: <a href="https://deepmind.google/models/gemma/gemma-4/" target="_blank" rel="noreferrer noopener">Google DeepMind</a>)</figcaption></figure></div>


<p>The 31B dense model achieves an estimated LMArena Elo score of <strong>1,452</strong> on text-only evaluations, placing it competitively with models that are significantly larger. The 26B A4B MoE model reaches <strong>1,441</strong>, which is remarkable given that it uses only 4 billion active parameters. To put that in context: these scores are competitive with several closed-source models from mid-2024.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/06/image-82-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="819" height="1024" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-82-819x1024.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54381"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-82-819x1024.png?lossy=2&strip=1&webp=1 819w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-82-819x1024.png?size=126x158&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-82-819x1024.png?size=252x315&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-82-819x1024.png?size=378x473&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-82-819x1024.png?size=504x630&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-82-819x1024.png?size=630x788&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 819px) 100vw, 819px" /></a><figcaption class="wp-element-caption"><strong>Figure 6:</strong> Arena ELO Score (source: <a href="https://deepmind.google/models/gemma/gemma-4/" target="_blank" rel="noreferrer noopener">Google DeepMind</a>)</figcaption></figure></div>


<p>Multimodal performance follows a similar pattern. Even the vision and audio capabilities were comparable in quality to the text performance, and not degraded by the multimodal conditioning. All model sizes demonstrated strong OCR, object detection, scene description, and audio understanding.</p>



<p>On coding and agentic benchmarks, Gemma 4 shows notable improvements over Gemma 3, partly due to the expanded context window (128K for small models, 256K for large ones), the native function-calling support, and the thinking-mode capability.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/06/image-83-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="834" height="1024" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-83-834x1024.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54384"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-83-834x1024.png?lossy=2&strip=1&webp=1 834w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-83-834x1024.png?size=126x155&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-83-834x1024.png?size=252x309&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-83-834x1024.png?size=378x464&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-83-834x1024.png?size=504x619&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-83-834x1024.png?size=630x774&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 834px) 100vw, 834px" /></a><figcaption class="wp-element-caption"><strong>Table 3:</strong> Benchmark Performance (source: <a href="https://huggingface.co/blog/gemma4" target="_blank" rel="noreferrer noopener">Gemma 4 Hugging Face blog</a>)</figcaption></figure></div>


<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-How-Run-Gemma-4-Transformers-llama-cpp-MLX-Cloud-Deployment-Options"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-How-Run-Gemma-4-Transformers-llama-cpp-MLX-Cloud-Deployment-Options">How to Run Gemma 4: Transformers, llama.cpp, MLX, and Cloud Deployment Options</a></h2>



<p>Google and the community have built Gemma 4 support into virtually every major inference stack. Here&#8217;s a quick summary to help you choose.</p>



<ul class="wp-block-list">
<li><strong><a href="https://github.com/huggingface/transformers" target="_blank" rel="noreferrer noopener">Hugging Face Transformers</a></strong><strong>:</strong> The most fully featured option for Python users. It supports all modalities, thinking mode, function calling, and the full Processor API for handling mixed text/image/audio inputs. It is the best choice for research, fine-tuning, and flexible experimentation.</li>



<li><strong><a href="https://github.com/ggml-org/llama.cpp" target="_blank" rel="noreferrer noopener">Llama.cpp</a></strong><strong>:</strong> Offers highly optimized CPU and GPU inference, particularly valuable if you&#8217;re running on Apple Silicon or hardware without NVIDIA GPUs. Gemma 4 is supported in recent builds, with GGUF quantization enabling the small models to run on consumer hardware.</li>



<li><strong><a href="https://github.com/ml-explore/mlx" target="_blank" rel="noreferrer noopener">MLX</a></strong><strong>:</strong> The framework of choice for Apple Silicon, offering native Metal GPU acceleration. The E2B and E4B models run surprisingly fast on M-series chips via MLX, making on-Mac deployment practical.</li>



<li><strong><a href="https://github.com/huggingface/transformers.js" target="_blank" rel="noreferrer noopener">transformers.js</a></strong>: Enables in-browser inference via WebGPU. Gemma 4&#8217;s small models can run directly in a web browser (no server required), which opens up genuinely private, fully offline applications.</li>



<li><strong><a href="https://github.com/EricLBuehler/mistral.rs" target="_blank" rel="noreferrer noopener">Mistral.rs</a></strong><strong>:</strong> A Rust-based inference engine with strong performance characteristics for production deployments.</li>
</ul>



<p>For cloud production environments, Gemma 4 is available via the Gemini API, Google Cloud&#8217;s Vertex AI, Cloud Run, and GKE with GPU nodes. The Gemini API option is the lowest-friction path for managed serving without infrastructure work.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Fine-Tuning-Gemma-4-LoRA-QLoRA-TRL-Training-Pipeline-Guide"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Fine-Tuning-Gemma-4-LoRA-QLoRA-TRL-Training-Pipeline-Guide">Fine-Tuning Gemma 4: LoRA, QLoRA, and TRL Training Pipeline Guide</a></h2>



<p>One interesting observation from the Hugging Face team: Gemma 4 was difficult to demonstrate through fine-tuning examples <em>because the base instruction-tuned models are already so capable</em>. That said, fine-tuning is well-supported for domain specialization, style adaptation, or building task-specific versions.</p>



<p><strong><a href="https://github.com/huggingface/trl" target="_blank" rel="noreferrer noopener">TRL (Transformer Reinforcement Learning)</a></strong><strong>:</strong> The primary recommended library for supervised fine-tuning. It supports QLoRA (quantized LoRA), which dramatically reduces the memory requirements for fine-tuning, making it possible to fine-tune the 31B model on a machine with two consumer-grade GPUs if combined with 4-bit quantization. Fine-tuning is also supported on Vertex AI via TRL if you&#8217;d prefer a managed training environment.</p>



<p><strong><a href="https://unsloth.ai/docs/new/studio" target="_blank" rel="noreferrer noopener">Unsloth Studio</a></strong><strong>:</strong> A no-code fine-tuning interface for users who want to adapt Gemma 4 without writing training code. It supports Gemma 4 with memory optimizations baked in.</p>



<p>For a full fine-tuning pipeline in code, the key is using QLoRA via Hugging Face&#8217;s <a href="https://github.com/huggingface/peft" target="_blank" rel="noreferrer noopener">peft</a> and <a href="https://github.com/huggingface/trl" target="_blank" rel="noreferrer noopener">trl</a> libraries, targeting the attention and feedforward projection layers. Google also provides official guides for LoRA fine-tuning via Keras, PyTorch, and the Gemma library itself.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Gemma-4-Prompt-Formatting-Chat-Templates-Multimodal-Input-Structure"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Gemma-4-Prompt-Formatting-Chat-Templates-Multimodal-Input-Structure">Gemma 4 Prompt Formatting: Chat Templates and Multimodal Input Structure</a></h2>



<p>Gemma 4 follows a specific chat template that you should be aware of when building applications. The instruction-tuned models expect input in a structured multi-turn format. When using Hugging Face Transformers, always use <code data-enlighter-language="python" class="EnlighterJSRAW">processor.apply_chat_template()</code> rather than constructing prompts manually. This ensures special tokens are correctly inserted and the model receives input in the format it was trained on.</p>



<p>For multimodal inputs, images and audio are passed as dictionary entries alongside text in the message content list:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Google DeepMind’s Gemma 4: MoE, Efficiency Tricks, and Benchmarks" data-enlighter-group="3">messages = [
    {
        "role": "user",
        "content": [
            # For image input:
            {"type": "image", "url": "https://example.com/image.png"},
            # Or for local audio:
            {"type": "audio", "path": "/path/to/audio.mp3"},
            # Text always accompanies the media:
            {"type": "text", "text": "Describe what you see/hear."},
        ],
    }
]
</pre>



<p>For video with audio (E2B and E4B only), pass <code data-enlighter-language="python" class="EnlighterJSRAW">load_audio_from_video=True</code> in the <code data-enlighter-language="python" class="EnlighterJSRAW">apply_chat_template</code> call. For larger models, omit this flag since they do not have an audio encoder.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Which-Gemma-4-Model-Use-E2B-vs-E4B-vs-26B-MoE-vs-31B-Comparison"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Which-Gemma-4-Model-Use-E2B-vs-E4B-vs-26B-MoE-vs-31B-Comparison">Which Gemma 4 Model to Use: E2B vs E4B vs 26B MoE vs 31B Comparison</a></h2>



<p>With 4 variants available, the choice comes down to a few key questions.</p>



<p>If you are <strong>building something that runs on a phone or edge device</strong> with less than 6–8 GB of RAM available for the model, the E2B or E4B are your options, and they are genuinely capable. E4B is worth the extra memory if you are doing audio-visual tasks. At 4-bit quantization, E2B runs in about 3 GB, which fits on most modern Android and iOS devices.</p>



<p>If you are <strong>running on a single GPU</strong> in the 16–24 GB range (RTX 3090, 4090, A10G), the 26B A4B at 4-bit quantization (<img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/fb4/fb4f353ef9a72c24566678c957a5ae9f-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='\approx' title='\approx' class='latex' />15.6 GB) gives you the best intelligence-per-dollar, running at 4B-speed throughput.</p>



<p>If you need <strong>maximum capability</strong> and have the hardware for it (2× A100 or H100), the 31B dense model at BF16 or the 26B A4B at 16-bit precision are both strong choices. The 31B is architecturally simpler; the 26B A4B provides better throughput if you&#8217;re processing high request volumes.</p>



<p>If you are <strong>doing audio tasks</strong> at all, you must use E2B or E4B, since the larger models do not have an audio encoder.</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<div id="pitch" style="padding: 40px; width: 100%; background-color: #F4F6FA;">
	<h3>What's next? We recommend <a target="_blank" href="https://pyimagesearch.com/pyimagesearch-university/?utm_source=blogPost&utm_medium=bottomBanner&utm_campaign=What%27s%20next%3F%20I%20recommend">PyImageSearch University</a>.</h3>

	<script src="https://fast.wistia.com/embed/medias/kno0cmko2z.jsonp" async></script><script src="https://fast.wistia.com/assets/external/E-v1.js" async></script><div class="wistia_responsive_padding" style="padding:56.25% 0 0 0;position:relative;"><div class="wistia_responsive_wrapper" style="height:100%;left:0;position:absolute;top:0;width:100%;"><div class="wistia_embed wistia_async_kno0cmko2z videoFoam=true" style="height:100%;position:relative;width:100%"><div class="wistia_swatch" style="height:100%;left:0;opacity:0;overflow:hidden;position:absolute;top:0;transition:opacity 200ms;width:100%;"><img decoding="async" src="https://fast.wistia.com/embed/medias/kno0cmko2z/swatch" style="filter:blur(5px);height:100%;object-fit:contain;width:100%;" alt="" aria-hidden="true" onload="this.parentNode.style.opacity=1;" /></div></div></div></div>

	<div style="margin-top: 32px; margin-bottom: 32px; ">
		<strong>Course information:</strong><br/>
		120+ total classes • 115+ hours hours of on-demand code walkthrough videos • Last updated: August 2026<br/>
		<span style="color: #169FE6;">★★★★★</span> 4.84 (128 Ratings) • 16,000+ Students Enrolled
	</div>

	<p><strong>I strongly believe that if you had the right teacher you could <em>master</em> computer vision and deep learning.</strong></p>

	<p>Do you think learning computer vision and deep learning has to be time-consuming, overwhelming, and complicated? Or has to involve complex mathematics and equations? Or requires a degree in computer science?</p>

	<p>That’s <em>not</em> the case.</p>

	<p>All you need to master computer vision and deep learning is for someone to explain things to you in <em>simple, intuitive</em> terms. <em>And that’s exactly what I do</em>. My mission is to change education and how complex Artificial Intelligence topics are taught.</p>

	<p>If you're serious about learning computer vision, your next stop should be PyImageSearch University, the most comprehensive computer vision, deep learning, and OpenCV course online today. Here you’ll learn how to <em>successfully</em> and <em>confidently</em> apply computer vision to your work, research, and projects. Join me in computer vision mastery.</p>

	<p><strong>Inside PyImageSearch University you'll find:</strong></p>

	<ul style="margin-left: 0px;">
		<li style="list-style: none;">&check; <strong>120+ courses</strong> on essential computer vision, deep learning, and OpenCV topics</li>
		<li style="list-style: none;">&check; <strong>94+ Certificates</strong> of Completion</li>
		<li style="list-style: none;">&check; <strong>115+ hours hours</strong> of on-demand video</li>
		<li style="list-style: none;">&check; <strong>Brand new courses released <em>regularly</em></strong>, ensuring you can keep up with state-of-the-art techniques</li>
		<li style="list-style: none;">&check; <strong>Pre-configured Jupyter Notebooks in Google Colab</strong></li>
		<li style="list-style: none;">&check; Run all code examples in your web browser — works on Windows, macOS, and Linux (no dev environment configuration required!)</li>
		<li style="list-style: none;">&check; Access to <strong>centralized code repos for <em>all</em> 540+ tutorials</strong> on PyImageSearch</li>
		<li style="list-style: none;">&check; <strong> Easy one-click downloads</strong> for code, datasets, pre-trained models, etc.</li>
		<li style="list-style: none;">&check; <strong>Access</strong> on mobile, laptop, desktop, etc.</li>
	</ul>

	<p style="text-align: center;">
		<a target="_blank" class="button link" href="https://pyimagesearch.com/pyimagesearch-university/?utm_source=blogPost&utm_medium=bottomBanner&utm_campaign=What%27s%20next%3F%20I%20recommend" style="background-color: #6DC713; border-bottom: none;">Click here to join PyImageSearch University</a>
	</p>
</div>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Summary"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Summary">Summary</a></h2>



<p>Gemma 4 is best understood not as a single model but as a thoughtfully tiered family, each member engineered for a specific place in the hardware spectrum, from a smartphone to a data center GPU cluster.</p>



<p>The two small models (E2B and E4B) push the frontier of what is possible on-device by storing large embedding tables in flash memory rather than RAM, and by packing audio understanding alongside vision and text in a package that fits in just a few gigabytes.</p>



<p>The 26B A4B MoE model achieves something that still feels almost counterintuitive: the knowledge depth of a 26-billion-parameter model running at roughly the speed and cost of a 4-billion-parameter model, thanks to sparse expert routing.</p>



<p>The 31B dense model serves as the reliable, architecturally simple heavyweight for applications that need maximum capability without the added complexity of MoE.</p>



<p>Across all variants, Gemma 4 shares a core set of architectural decisions that compound in value: interleaved local-and-global attention tames the cost of long contexts; grouped query attention and the K=V cache trick shrink the memory footprint of those global layers; and pruned positional encoding keeps semantic meaning clean even across hundreds of thousands of tokens.</p>



<p>These are not isolated optimizations; they are a coherent strategy for squeezing frontier-level intelligence into constrained environments.</p>



<p>On the capability side, what sets Gemma 4 apart from prior open-weight releases is the breadth of what works <em>out of the box</em>. Native structured output for object detection, code generation from screenshots, audio Q&amp;A, configurable thinking mode, and function-calling support all come without special prompting tricks or external scaffolding.</p>



<p>The Apache 2.0 license is a major advantage for commercial use, allowing you to deploy, modify, and build on these models without restriction.</p>



<p>If you take one thing away from this post, let it be this: the right way to approach Gemma 4 is not to ask &#8220;which is the best model?&#8221; but rather &#8220;what are my actual constraints — memory, latency, modality, hardware — and which variant is engineered for exactly that?&#8221;</p>



<p>The answer is almost certainly one of these four. The rest of this series will help you put whichever one you choose to work.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Citation-Information"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Citation-Information">Citation Information</a></h3>



<p><strong>Thakur, P. </strong>“Google DeepMind&#8217;s Gemma 4: MoE, Efficiency Tricks, and Benchmarks,” <em>PyImageSearch</em>, S. Huot and A. Sharma, eds., 2026, <a href="https://pyimg.co/uqxzw" target="_blank" rel="noreferrer noopener">https://pyimg.co/uqxzw</a></p>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="classic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="Google DeepMind’s Gemma 4: MoE, Efficiency Tricks, and Benchmarks" data-enlighter-group="4">@incollection{Thakur_2026_google-deepminds-gemma-4-moe-efficiency-tricks-benchmarks,
  author = {Piyush Thakur},
  title = {{Google DeepMind's Gemma 4: MoE, Efficiency Tricks, and Benchmarks}},
  booktitle = {PyImageSearch},
  editor = {Susan Huot and Aditya Sharma},
  year = {2026},
  url = {https://pyimg.co/uqxzw},
}
</pre>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<div id="download-the-code" class="post-cta-wrap">
<div class="gpd-post-cta">
	<div class="gpd-post-cta-content">
		

			<div class="gpd-post-cta-top">
				<div class="gpd-post-cta-top-image"><img decoding="async" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2020/01/cta-source-guide-1.png?lossy=2&strip=1&webp=1" alt="" srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2020/01/cta-source-guide-1.png?lossy=2&strip=1&webp=1 410w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2020/01/cta-source-guide-1.png?size=126x174&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2020/01/cta-source-guide-1.png?size=252x348&lossy=2&strip=1&webp=1 252w" sizes="(max-width: 410px) 100vw, 410px" /></div>
				
				<div class="gpd-post-cta-top-title"><h4>Join the PyImageSearch Newsletter and Grab My FREE 17-page Resource Guide PDF</h4></div>
				<div class="gpd-post-cta-top-desc"><p>Enter your email address below to <strong>join the PyImageSearch Newsletter</strong> and <strong>download my FREE 17-page Resource Guide PDF</strong> on Computer Vision, OpenCV, and Deep Learning.</p></div>


			</div>

			<div class="gpd-post-cta-bottom">
				<form class="footer-cta" action="https://www.getdrip.com/forms/657075648/submissions" method="post" target="_blank" data-drip-embedded-form="657075648">
					<input name="fields[email]" type="email" value="" placeholder="Your email address" class="form-control" />

					<button type="submit">Join the Newsletter!</button>

					<div style="display: none;" aria-hidden="true"><label for="website">Website</label><br /><input type="text" id="website" name="website" tabindex="-1" autocomplete="false" value="" /></div>
				</form>
			</div>


		
	</div>

</div>
</div>
<p>The post <a rel="nofollow" href="https://pyimagesearch.com/2026/06/22/google-deepminds-gemma-4-moe-efficiency-tricks-and-benchmarks/">Google DeepMind&#8217;s Gemma 4: MoE, Efficiency Tricks, and Benchmarks</a> appeared first on <a rel="nofollow" href="https://pyimagesearch.com">PyImageSearch</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>RAG Observability with Langfuse, vLLM, and FAISS</title>
		<link>https://pyimagesearch.com/2026/06/15/rag-observability-with-langfuse-vllm-and-faiss/</link>
		
		<dc:creator><![CDATA[Vikram Singh]]></dc:creator>
		<pubDate>Mon, 15 Jun 2026 12:45:00 +0000</pubDate>
				<category><![CDATA[Langfuse]]></category>
		<category><![CDATA[LLMOps]]></category>
		<category><![CDATA[MLOps]]></category>
		<category><![CDATA[Observability]]></category>
		<category><![CDATA[Retrieval-Augmented Generation]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[Vector Databases]]></category>
		<category><![CDATA[ai observability]]></category>
		<category><![CDATA[faiss]]></category>
		<category><![CDATA[hallucination detection]]></category>
		<category><![CDATA[langfuse]]></category>
		<category><![CDATA[langfuse tracing]]></category>
		<category><![CDATA[llm monitoring]]></category>
		<category><![CDATA[llm observability]]></category>
		<category><![CDATA[local llm]]></category>
		<category><![CDATA[production rag]]></category>
		<category><![CDATA[prompt engineering]]></category>
		<category><![CDATA[rag evaluation]]></category>
		<category><![CDATA[rag metrics]]></category>
		<category><![CDATA[rag observability]]></category>
		<category><![CDATA[rag pipeline]]></category>
		<category><![CDATA[relevancy scoring]]></category>
		<category><![CDATA[retrieval augmented generation]]></category>
		<category><![CDATA[retrieval scoring]]></category>
		<category><![CDATA[sentence transformers]]></category>
		<category><![CDATA[token usage tracking]]></category>
		<category><![CDATA[traced llm]]></category>
		<category><![CDATA[traced retriever]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[vector database]]></category>
		<category><![CDATA[vector search]]></category>
		<category><![CDATA[vllm]]></category>
		<guid isPermaLink="false">https://pyimagesearch.com/?p=54252</guid>

					<description><![CDATA[<p>Table of Contents RAG Observability with Langfuse, vLLM, and FAISS Introduction to Production-Grade RAG and LLM Observability RAG Observability Architecture with Langfuse, vLLM, and FAISS Project Setup Building a Langfuse-Traced Retriever with FAISS Building a Traced LLM Wrapper for vLLM&#8230;</p>
<p>The post <a rel="nofollow" href="https://pyimagesearch.com/2026/06/15/rag-observability-with-langfuse-vllm-and-faiss/">RAG Observability with Langfuse, vLLM, and FAISS</a> appeared first on <a rel="nofollow" href="https://pyimagesearch.com">PyImageSearch</a>.</p>
]]></description>
										<content:encoded><![CDATA[<div class="yoast-breadcrumbs"><span><span><a href="https://pyimagesearch.com/">Home</a></span></div>


<div class="toc">
<hr class="TOC"/>
<p class="has-large-font-size"><strong>Table of Contents</strong></p>
<ul>
    <li id="TOC-h1-RAG-Observability-Langfuse-vLLM-FAISS"><a rel="noopener" target="_blank" href="#h1-RAG-Observability-Langfuse-vLLM-FAISS">RAG Observability with Langfuse, vLLM, and FAISS</a></li>

    <li id="TOC-h2-Introduction-Production-Grade-RAG-LLM-Observability"><a rel="noopener" target="_blank" href="#h2-Introduction-Production-Grade-RAG-LLM-Observability">Introduction to Production-Grade RAG and LLM Observability</a></li>

    <li id="TOC-h2-RAG-Observability-Architecture-Langfuse-vLLM-FAISS"><a rel="noopener" target="_blank" href="#h2-RAG-Observability-Architecture-Langfuse-vLLM-FAISS">RAG Observability Architecture with Langfuse, vLLM, and FAISS</a></li>

    <li id="TOC-h2-Project-Setup"><a rel="noopener" target="_blank" href="#h2-Project-Setup">Project Setup</a></li>

    <li id="TOC-h2-Building-Langfuse-Traced-Retriever-FAISS"><a rel="noopener" target="_blank" href="#h2-Building-Langfuse-Traced-Retriever-FAISS">Building a Langfuse-Traced Retriever with FAISS</a></li>

    <li id="TOC-h2-Building-Traced-LLM-Wrapper-vLLM-Langfuse"><a rel="noopener" target="_blank" href="#h2-Building-Traced-LLM-Wrapper-vLLM-Langfuse">Building a Traced LLM Wrapper for vLLM and Langfuse</a></li>

    <li id="TOC-h2-Building-Fully-Traced-RAG-Pipeline-Langfuse"><a rel="noopener" target="_blank" href="#h2-Building-Fully-Traced-RAG-Pipeline-Langfuse">Building a Fully Traced RAG Pipeline with Langfuse</a></li>

    <li id="TOC-h2-Implementing-LLM-Evaluation-Metrics-Relevancy-Hallucination-Risk"><a rel="noopener" target="_blank" href="#h2-Implementing-LLM-Evaluation-Metrics-Relevancy-Hallucination-Risk">Implementing LLM Evaluation Metrics for RAG: Relevancy and Hallucination Risk</a></li>

    <li id="TOC-h2-Running-Inspecting-RAG-Pipeline-End-to-End"><a rel="noopener" target="_blank" href="#h2-Running-Inspecting-RAG-Pipeline-End-to-End">Running and Inspecting the RAG Pipeline End-to-End</a></li>

    <li id="TOC-h2-Viewing-RAG-Traces-Spans-Scores-Langfuse"><a rel="noopener" target="_blank" href="#h2-Viewing-RAG-Traces-Spans-Scores-Langfuse">Viewing RAG Traces, Spans, and Scores in Langfuse</a></li>

    <li id="TOC-h2-Summary"><a rel="noopener" target="_blank" href="#h2-Summary">Summary</a></li>
</ul>
</div>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h1-RAG-Observability-Langfuse-vLLM-FAISS"/>



<h2 class="wp-block-heading"><a href="#TOC-h1-RAG-Observability-Langfuse-vLLM-FAISS">RAG Observability with Langfuse, vLLM, and FAISS</a></h2>



<p>In this lesson, you will learn how to instrument every step of your Retrieval-Augmented Generation (RAG) pipeline using Langfuse, capture traces across ingestion, retrieval, and generation, and understand exactly how your system behaves under the hood.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://pyimagesearch.com/wp-content/uploads/2026/06/rag-observability-langfuse-vllm-faiss-featured.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="940" height="780" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/rag-observability-langfuse-vllm-faiss-featured.png?lossy=2&strip=1&webp=1" alt="rag-observability-langfuse-vllm-faiss-featured.png" class="wp-image-54313"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/rag-observability-langfuse-vllm-faiss-featured.png?size=126x105&lossy=2&strip=1&webp=1 126w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/rag-observability-langfuse-vllm-faiss-featured-300x249.png?lossy=2&strip=1&webp=1 300w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/rag-observability-langfuse-vllm-faiss-featured.png?size=378x314&lossy=2&strip=1&webp=1 378w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/rag-observability-langfuse-vllm-faiss-featured.png?size=504x418&lossy=2&strip=1&webp=1 504w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/rag-observability-langfuse-vllm-faiss-featured.png?size=630x523&lossy=2&strip=1&webp=1 630w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/rag-observability-langfuse-vllm-faiss-featured-768x637.png?lossy=2&strip=1&webp=1 768w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/rag-observability-langfuse-vllm-faiss-featured.png?lossy=2&strip=1&webp=1 940w" sizes="(max-width: 940px) 100vw, 940px" /></a></figure></div>


<p>You will wire tracing into your retriever and generator, monitor latency and token usage, evaluate quality scores, and run the entire stack with vLLM and FAISS locally so you can experiment freely without any cloud dependencies.</p>



<p>By the end, you will have a fully transparent RAG workflow that you can debug, optimize, and scale with confidence.</p>



<p>This lesson is the last in a 3-part series on <strong>LLM observability with Langfuse</strong>:</p>



<ol class="wp-block-list">
<li><em><strong><a href="https://pyimg.co/tadoh" target="_blank" rel="noreferrer noopener">LLM Observability with Self-Hosted Langfuse and vLLM</a></strong></em></li>



<li><em><strong><a href="https://pyimg.co/24p06" target="_blank" rel="noreferrer noopener">Manual Tracing, Scores, and Evaluation with Langfuse (Self-Hosted)</a></strong></em></li>



<li><em><strong><a href="https://pyimg.co/g20yk" target="_blank" rel="noreferrer noopener">RAG Observability with Langfuse, vLLM, and FAISS</a></strong></em><strong> (this tutorial)</strong></li>
</ol>



<p><strong>To learn how to make your RAG pipeline fully observable with Langfuse, vLLM, and FAISS, </strong><em><strong>just keep reading.</strong></em></p>



<div id="pyi-source-code-block" class="source-code-wrap"><div class="gpd-source-code">
    <div class="gpd-source-code-content">
        <img decoding="async" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2020/01/source-code-icon.png?lossy=2&strip=1&webp=1" alt="">
        <h4>Looking for the source code to this post?</h4>
                    <a href="#download-the-code" class="pyis-cta-modal-open-modal">Jump Right To The Downloads Section <svg class="svg-icon arrow-right" width="12" height="12" aria-hidden="true" role="img" focusable="false" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M6.8125 0.1875C6.875 0.125 6.96875 0.09375 7.09375 0.09375C7.1875 0.09375 7.28125 0.125 7.34375 0.1875L13.875 6.75C13.9375 6.8125 14 6.90625 14 7C14 7.125 13.9375 7.1875 13.875 7.25L7.34375 13.8125C7.28125 13.875 7.1875 13.9062 7.09375 13.9062C6.96875 13.9062 6.875 13.875 6.8125 13.8125L6.1875 13.1875C6.125 13.125 6.09375 13.0625 6.09375 12.9375C6.09375 12.8438 6.125 12.75 6.1875 12.6562L11.0312 7.8125H0.375C0.25 7.8125 0.15625 7.78125 0.09375 7.71875C0.03125 7.65625 0 7.5625 0 7.4375V6.5625C0 6.46875 0.03125 6.375 0.09375 6.3125C0.15625 6.25 0.25 6.1875 0.375 6.1875H11.0312L6.1875 1.34375C6.125 1.28125 6.09375 1.1875 6.09375 1.0625C6.09375 0.96875 6.125 0.875 6.1875 0.8125L6.8125 0.1875Z" fill="#169FE6"></path></svg></a>
            </div>
</div>
</div>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Introduction-Production-Grade-RAG-LLM-Observability"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Introduction-Production-Grade-RAG-LLM-Observability">Introduction to Production-Grade RAG and LLM Observability</a></h2>



<h3 class="wp-block-heading">What Makes a RAG Pipeline Production-Grade</h3>



<p>A RAG pipeline becomes “production-grade’’ only when it consistently delivers correct, stable, and explainable outputs under real-world constraints. In development, it is easy to get an LLM to answer questions using retrieved context. In production, the challenges multiply: retrieval quality varies, embeddings may shift over time, documents evolve, and latency budgets tighten. A production RAG pipeline must remain robust even when the input data is noisy, queries are unpredictable, and traffic is high.</p>



<p>A production-ready RAG system must treat <strong>retrieval as a first-class subsystem</strong>, not a background detail. That means surfacing similarity scores, exposing ranking decisions, understanding how vector search behaves at scale, and ensuring retriever recall stays high across diverse query types. It also requires that the <strong>prompt construction step is deterministic, inspectable, and traceable</strong>, because subtle variations in formatting often change model behavior dramatically.</p>



<p>Beyond these retrieval and prompt concerns, the LLM is also a production component. That means <strong>retry logic, token accounting, consistent latency, predictable throughput, and graceful failure modes</strong>. Production pipelines need clear boundaries between retrieval failures, prompt-generation bugs, and LLM invocation issues. If these concerns remain invisible, debugging becomes guesswork and reliability collapses under load. Production-grade RAG means engineered behavior, not accidental correctness.</p>



<h3 class="wp-block-heading">Why Observability Is Essential for Retrieval-Augmented Systems</h3>



<p>RAG pipelines fail silently. Retrieval may return irrelevant documents, prompting may omit essential context, and the LLM may hallucinate confidently even when grounded context exists. Without observability, it is impossible to diagnose <em>why</em> a particular answer was wrong. Was the embedding model inconsistent? Did FAISS, the vector search library used to retrieve similar documents, return poor matches? Did the prompt formatting break a system instruction? Did the LLM drift or degrade?</p>



<p>Observability solves this by turning the RAG pipeline into a transparent execution graph. Tools like Langfuse give you <strong>hierarchical traces</strong>: one trace for the whole request, and nested spans for retrieval, LLM calls, evaluation, and supporting steps. Each span captures inputs, outputs, metadata, latencies, token usage, and even scoring metrics. With this information, problems become diagnosable:</p>



<ul class="wp-block-list">
<li>Retrieval returned low-relevance documents</li>



<li>Prompt formatting changed unexpectedly</li>



<li>LLM call degraded or hit retry logic</li>



<li>Evaluation metrics began trending downward</li>
</ul>



<p>In other words, observability provides <strong>ground truth for system behavior</strong>. Production RAG must be accountable: decisions should be explainable, errors traceable, and failures measurable. Without observability, shipping RAG to production is equivalent to flying an airplane without instruments; the system might work, but you will not know <em>when</em> or <em>why</em> it stops working.</p>



<h3 class="wp-block-heading">What We Will Build: Traced Retriever, Traced LLM, Full RAG Pipeline, and Evaluation</h3>



<p>In this lesson, you will construct a fully observable, component-wise traced RAG system using <code data-enlighter-language="python" class="EnlighterJSRAW">Langfuse</code>, <code data-enlighter-language="python" class="EnlighterJSRAW">FAISS</code>, <code data-enlighter-language="python" class="EnlighterJSRAW">SentenceTransformers</code>, and <code data-enlighter-language="python" class="EnlighterJSRAW">vLLM</code>. Each part of the pipeline is instrumented for visibility: you will build a <strong>traced retriever</strong> that logs embeddings, index sizes, similarity scores, and ranking. You will build a <strong>traced LLM wrapper</strong> that records prompts, responses, retry attempts, and token usage. These components power a <strong>fully traced RAG pipeline</strong> that captures retrieval, prompt construction, generation, and final evaluation as a single hierarchical execution tree.</p>



<p>You will also implement <strong>automatic RAG output evaluation</strong>, computing relevancy, hallucination risk, and an overall quality score, with each metric logged back to Langfuse dashboards with scoring nodes. This gives you a complete introspection loop: every answer is measured, every metric is recorded, and every decision is traceable through structured spans.</p>



<p>By the end, you will have a <strong>production-grade RAG observability stack</strong>, running locally with:</p>



<ul class="wp-block-list">
<li>A traced retriever</li>



<li>A traced LLM client</li>



<li>A fully instrumented RAG pipeline</li>



<li>Automatic scoring and diagnostics</li>



<li>Local dashboards for analyzing behavior</li>
</ul>



<p>This foundation prepares you for upcoming lessons, where we extend these ideas into multi-step agents and more complex reasoning workflows.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-RAG-Observability-Architecture-Langfuse-vLLM-FAISS"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-RAG-Observability-Architecture-Langfuse-vLLM-FAISS">RAG Observability Architecture with Langfuse, vLLM, and FAISS</a></h2>



<p>A production-grade RAG pipeline is not a single model call. It is an orchestrated system composed of independent but cooperating components: retrieval, prompt assembly, LLM inference, and evaluation. In this section, we break down each subsystem and explain how they interact, why they are separated, and how Langfuse stitches everything together into a fully observable execution graph.</p>



<h3 class="wp-block-heading">Retrieval → Prompt Construction → LLM → Scoring (The Core RAG Loop)</h3>



<p>A well-designed RAG architecture follows a clean, linear flow where each stage has a single responsibility:</p>



<h4 class="wp-block-heading">Retrieval</h4>



<p>The system begins by embedding the user query and searching for relevant documents in a vector index. The retriever returns <em>ranked, scored</em> context items that will guide the LLM. In production, retrieval quality is often the primary bottleneck; if retrieval fails, generation cannot be correct. Therefore, retrieval spans log:</p>



<ul class="wp-block-list">
<li>embeddings used</li>



<li>search distances and converted relevance scores</li>



<li>number of documents returned</li>



<li>FAISS query latencies</li>
</ul>



<p>Your <code data-enlighter-language="python" class="EnlighterJSRAW">TracedRetriever</code> does exactly this in the codebase, generating embeddings, searching the FAISS index, and tracing each step.</p>



<h4 class="wp-block-heading">Prompt Construction</h4>



<p>Next, the system converts retrieved documents into a structured context block and assembles a prompt that the LLM can reliably parse. Prompt construction must be deterministic to avoid instability across runs. The code in <code data-enlighter-language="python" class="EnlighterJSRAW">rag_pipeline.py</code> builds a system message, a user message, and contextual references (<code data-enlighter-language="python" class="EnlighterJSRAW">[1] doc1</code>, <code data-enlighter-language="python" class="EnlighterJSRAW">[2] doc2</code>, etc.). This ensures:</p>



<ul class="wp-block-list">
<li>deterministic ordering</li>



<li>visible context structure</li>



<li>stable interface for downstream evaluation</li>
</ul>



<h4 class="wp-block-heading">LLM Generation</h4>



<p>The prompt is sent to the LLM via an <strong>OpenAI-compatible Completion API</strong>, served by <strong>vLLM</strong> locally. The <code data-enlighter-language="python" class="EnlighterJSRAW">TracedLLMClient</code> wraps this call with:</p>



<ul class="wp-block-list">
<li>retry logic</li>



<li>token usage reporting</li>



<li>error logging</li>



<li>prompt and response capture</li>



<li>metadata annotations</li>
</ul>



<p>This is critical for production reliability because LLM latency, token usage, and intermittent failures must all be observable.</p>



<h4 class="wp-block-heading">Scoring and Evaluation</h4>



<p>Finally, the answer is passed through a lightweight evaluation module (<code data-enlighter-language="python" class="EnlighterJSRAW">evaluation.py</code>). It computes:</p>



<ul class="wp-block-list">
<li>a relevancy score</li>



<li>a hallucination risk score</li>



<li>an overall quality score</li>
</ul>



<p>These metrics are reported back into Langfuse as scoring nodes. Production RAG systems need this because correctness is subjective; evaluation makes correctness measurable.</p>



<p>This 4-step pipeline forms the backbone of every modern retrieval-augmented system.</p>



<h3 class="wp-block-heading">Local Vector Store Using FAISS and SentenceTransformers</h3>



<p>RAG pipelines must remain fast, private, and cost-efficient. This system uses <strong>FAISS</strong> as the vector index and <strong>SentenceTransformers</strong> for embedding models, giving you:</p>



<ul class="wp-block-list">
<li><strong>Zero API cost</strong> (everything is local)</li>



<li><strong>GPU acceleration optional</strong> (FAISS works on CPU just fine)</li>



<li><strong>Deterministic embeddings</strong> (critical for reproducibility)</li>



<li><strong>Config-driven control</strong> over the embedding model and dimensionality</li>
</ul>



<p>The retrieval pipeline is built around the following 3 core mechanisms:</p>



<h4 class="wp-block-heading">Document Embeddings</h4>



<p>Each document is encoded using the local model defined in <code data-enlighter-language="python" class="EnlighterJSRAW">config.yaml</code>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="1">embeddings:
  model: "sentence-transformers/all-MiniLM-L6-v2"
  dimension: 384
</pre>



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">TracedRetriever</code> loads this model and produces <strong>normalized embeddings</strong> for better retrieval precision.</p>



<h4 class="wp-block-heading">FAISS Index</h4>



<p>FAISS stores all document embeddings in a vector index created via:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="2">self.index = faiss.IndexFlatL2(self.dimension)
</pre>



<p><code data-enlighter-language="python" class="EnlighterJSRAW">IndexFlatL2</code> is simple, fast, and perfect for local development, while still appropriate for many production environments.</p>



<h4 class="wp-block-heading">Similarity Search</h4>



<p>Retrieval happens by computing L2 distance and converting those distances into relevance scores, ensuring consistency and interpretability.</p>



<p>You end up with a fully local, high-performance vector store without touching external cloud APIs.</p>



<h3 class="wp-block-heading">vLLM as an OpenAI-Compatible Inference Server</h3>



<p>Instead of relying on OpenAI or Anthropic APIs, your lesson uses <strong>vLLM</strong>, a high-throughput inference engine built for serving LLMs at scale.</p>



<p>Your Docker Compose file runs vLLM either on <strong>GPU (recommended)</strong> or <strong>CPU fallback</strong>, exposing it at:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="3">http://localhost:8000/v1
</pre>



<p>This allows you to call vLLM with the exact same interface as OpenAI:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="4">response = client.chat.completions.create(
    model=self.model,
    messages=messages,
    temperature=temperature,
    max_tokens=max_tokens
)
</pre>



<p>Benefits for production-grade RAG:</p>



<ul class="wp-block-list">
<li><strong>Predictable latency</strong></li>



<li><strong>Full control over model versioning</strong></li>



<li><strong>No external dependencies</strong></li>



<li><strong>High-throughput serving (paged attention)</strong></li>



<li><strong>OpenAI API compatibility</strong> (no code rewrite needed)</li>
</ul>



<p>Your <code data-enlighter-language="python" class="EnlighterJSRAW">TracedLLMClient</code> wraps all of this with Langfuse observability, giving you:</p>



<ul class="wp-block-list">
<li>latency metrics</li>



<li>retry attempts</li>



<li>token usage breakdown</li>



<li>full input/output transparency</li>



<li>error-level spans when inference fails</li>
</ul>



<p>This is how modern enterprises run private LLMs with production reliability.</p>



<h3 class="wp-block-heading">Langfuse for Tracing, Metrics, Evaluation, and Span Hierarchies</h3>



<p>Langfuse is the backbone of observability in this system. Every major component (i.e., embedding, retrieval, generation, and evaluation) becomes a <strong>span</strong> inside a single <strong>root trace</strong>.</p>



<p>A typical trace hierarchy looks like:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="5">rag_pipeline (root)
│
├── retrieve_documents
│   ├── embed_text
│   ├── index_documents (only once)
│   └── retrieve_documents
│
├── llm_completion
│
└── evaluate_rag_output
    ├── evaluate_relevancy
    └── evaluate_hallucination
</pre>



<p>This structure gives you:</p>



<h4 class="wp-block-heading">Full-System Visibility</h4>



<p>Every question generates a complete execution tree revealing:</p>



<ul class="wp-block-list">
<li>what happened</li>



<li>where it happened</li>



<li>how long it took</li>



<li>what went wrong</li>
</ul>



<h4 class="wp-block-heading">End-to-End Metrics</h4>



<ul class="wp-block-list">
<li>token usage</li>



<li>retrieval scores</li>



<li>latency per component</li>



<li>evaluation metrics</li>
</ul>



<h4 class="wp-block-heading">Rich Debugging Context</h4>



<p>Each span stores:</p>



<ul class="wp-block-list">
<li>input messages</li>



<li>embeddings preview</li>



<li>retrieved context</li>



<li>generated outputs</li>



<li>error details</li>
</ul>



<h4 class="wp-block-heading">Continuous Quality Monitoring</h4>



<p>Your evaluation step logs:</p>



<ul class="wp-block-list">
<li>a relevancy score</li>



<li>a hallucination risk</li>



<li>a final pass-or-fail quality metric</li>
</ul>



<p>Langfuse becomes the <em>single pane of glass</em> for understanding your RAG pipeline’s behavior, serving as the missing observability layer that transforms a working prototype into a production-ready system.</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p>Would you like immediate access to 3,457 images curated and labeled with hand gestures to train, explore, and experiment with &#8230; for free? Head over to <a href="https://universe.roboflow.com/isl/az-6mqow?ref=pyimagesearch" target="_blank" rel="noreferrer noopener">Roboflow</a> and get a free account to grab these hand gesture images. </p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Project-Setup"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Project-Setup">Project Setup</a></h2>



<p>Before we write a single line of RAG logic, the foundation must be solid: a clean folder structure, repeatable environment setup, deterministic configuration, and a reliable inference and observability stack. This section walks you through the project layout, how to launch vLLM and Langfuse via Docker Compose, how to install retrieval dependencies (FAISS and SentenceTransformers), and how to configure all components using a single <code data-enlighter-language="python" class="EnlighterJSRAW">config.yaml</code> file.</p>



<h3 class="wp-block-heading">Folder Structure Walkthrough</h3>



<p>Your project is organized for <strong>production clarity</strong>, where each subsystem (RAG, LLM, agent, evaluation, and infrastructure) is isolated in its own module.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="6">project-root/
│
├── configs/
│   └── config.yaml                # Central config: LLM, embeddings, RAG, agent, eval, Langfuse
│
├── data/
│   └── sample_docs.txt            # Example inputs for retrieval
│
├── src/
│   ├── config.py                  # Config loader utilities
│   ├── llm_utils.py               # OpenAI-compatible client initialization
│   ├── llm_client.py              # Traced LLM wrapper (retry + token usage + spans)
│   ├── retriever.py               # FAISS retriever with traced indexing + search
│   ├── evaluation.py              # RAG quality scoring (relevancy + hallucination)
│   ├── rag_pipeline.py            # Full retrieval → prompt → generation → evaluation pipeline
│   ├── agent_orchestration.py     # 3-step traced agent workflow
│   ├── langfuse_instrumentation.py# Bootstraps Langfuse + flush utilities
│
├── docker-compose.yml             # vLLM + Langfuse + Postgres (self-hosted observability)
│
├── requirements.txt               # Python dependencies
│
└── check_rag_health.py            # Full system health check (env, docker, dependencies, files)
</pre>



<p>This layout ensures:</p>



<ul class="wp-block-list">
<li><strong>Decoupled components:</strong> easy for testing and future replacement</li>



<li><strong>Reproducible environment:</strong> config-driven behavior</li>



<li><strong>Portable observability:</strong> one command launches everything</li>



<li><strong>Scalable structure:</strong> supports RAG, agents, and future tools</li>
</ul>



<p>Every file in the <code data-enlighter-language="python" class="EnlighterJSRAW">src/</code> directory corresponds to a runnable pipeline step, and each is instrumented with Langfuse decorators so all activity becomes visible in the dashboard.</p>



<h3 class="wp-block-heading">Starting vLLM and Langfuse Using Docker Compose</h3>



<p>For production-like observability, the system relies on <strong>2 running services</strong>:</p>



<ul class="wp-block-list">
<li><strong>Langfuse:</strong> tracing, metrics, and span visualization</li>



<li><strong>vLLM:</strong> inference engine serving the LLM</li>
</ul>



<p>Both are provided in your <code data-enlighter-language="python" class="EnlighterJSRAW">docker-compose.yml</code>, and both run <strong>locally</strong>, meaning:</p>



<ul class="wp-block-list">
<li>zero cloud dependency</li>



<li>zero per-token cost</li>



<li>repeatable development environment</li>
</ul>



<h4 class="wp-block-heading">Start the entire stack (GPU version)</h4>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="7">docker-compose --profile gpu up -d
</pre>



<h4 class="wp-block-heading">Or start CPU mode</h4>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="8">docker-compose --profile cpu up -d
</pre>



<h4 class="wp-block-heading">Confirm services are running</h4>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="9">docker-compose ps
</pre>



<p>You should see something like:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://pyimagesearch.com/wp-content/uploads/2026/06/image-56.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="734" height="233" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-56.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54283"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-56.png?size=126x40&lossy=2&strip=1&webp=1 126w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-56-300x95.png?lossy=2&strip=1&webp=1 300w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-56.png?size=378x120&lossy=2&strip=1&webp=1 378w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-56.png?size=504x160&lossy=2&strip=1&webp=1 504w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-56.png?size=630x200&lossy=2&strip=1&webp=1 630w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-56.png?lossy=2&strip=1&webp=1 734w" sizes="(max-width: 734px) 100vw, 734px" /></a><figcaption class="wp-element-caption"><strong>Table 1: </strong>Core services with port mappings and health status</figcaption></figure></div>


<h4 class="wp-block-heading">UI access</h4>



<ul class="wp-block-list">
<li><strong>Langfuse dashboard:</strong> <code data-enlighter-language="python" class="EnlighterJSRAW">http://localhost:3000</code></li>



<li><strong>vLLM API:</strong> <code data-enlighter-language="python" class="EnlighterJSRAW">http://localhost:8000/v1</code></li>
</ul>



<h4 class="wp-block-heading">What these services do internally</h4>



<ul class="wp-block-list">
<li><code data-enlighter-language="python" class="EnlighterJSRAW">Langfuse server</code>: stores traces, spans, scoring, and metadata</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">Langfuse worker</code>: processes asynchronous scoring and analytics</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">PostgreSQL</code>: stores trace data</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">vLLM</code>: serves the Llama 2 model loaded at runtime</li>
</ul>



<p>This cluster forms your local, production-grade observability and inference backbone.</p>



<h3 class="wp-block-heading">Installing FAISS and SentenceTransformers</h3>



<p>The retrieval layer requires:</p>



<ul class="wp-block-list">
<li><strong>FAISS:</strong> similarity search</li>



<li><strong>SentenceTransformers:</strong> embedding model</li>
</ul>



<p>These are already declared in your <code data-enlighter-language="python" class="EnlighterJSRAW">requirements.txt</code>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="10">sentence-transformers>=2.2.0
faiss-cpu>=1.7.4
numpy>=1.24.0
</pre>



<p>Install dependencies:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="11">pip install -r requirements.txt
</pre>



<p>After installation, verify FAISS is working:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="12">python -c "import faiss; print(f'FAISS version: {faiss.__version__}')"
</pre>



<p>Verify embedding model loads:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="13">python -c "from sentence_transformers import SentenceTransformer; print(SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2'))"
</pre>



<p>These 2 libraries form the <strong>core retrieval engine</strong>:</p>



<ul class="wp-block-list">
<li><strong>Embeddings:</strong> produced locally (MiniLM)</li>



<li><strong>Retrieval:</strong> performed locally (FAISS <code data-enlighter-language="python" class="EnlighterJSRAW">IndexFlatL2</code>)</li>
</ul>



<p>No external API latency.</p>



<p>No cost.</p>



<p>No vendor lock-in.</p>



<h3 class="wp-block-heading">Configuring config.yaml (LLM, Embeddings, RAG, and Evaluation)</h3>



<p>The <strong>entire</strong> RAG and agent system is configurable from a single <code data-enlighter-language="python" class="EnlighterJSRAW">YAML</code> file:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="14">langfuse:
  host: "http://localhost:3000"
  project_name: "rag-selfhosted"

llm:
  base_url: "http://localhost:8000/v1"
  model: "meta-llama/Llama-2-7b-chat-hf"
  temperature: 0.7
  max_tokens: 300
  max_retries: 2

embeddings:
  model: "sentence-transformers/all-MiniLM-L6-v2"
  dimension: 384

rag:
  top_k: 3

agent:
  max_steps: 3

evaluation:
  enable_scoring: true
  min_quality_score: 0.6
</pre>



<h4 class="wp-block-heading">Key configuration sections</h4>



<h5 class="wp-block-heading">LLM Configuration</h5>



<p>Controls inference behavior:</p>



<ul class="wp-block-list">
<li>model name</li>



<li>sampling temperature</li>



<li>max tokens</li>



<li>retry count</li>



<li>endpoint (<code data-enlighter-language="python" class="EnlighterJSRAW">vLLM</code> server URL)</li>
</ul>



<p>Your <code data-enlighter-language="python" class="EnlighterJSRAW">TracedLLMClient</code> loads these automatically via:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="15">from config import get_llm_config
</pre>



<h5 class="wp-block-heading">Embeddings Configuration</h5>



<p>Controls vector dimension and embedding model, and is consumed by:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="16">from config import get_embeddings_config
</pre>



<h5 class="wp-block-heading">RAG Settings</h5>



<p>Controls retrieval behavior:</p>



<ul class="wp-block-list">
<li><code data-enlighter-language="python" class="EnlighterJSRAW">top_k</code>: results returned from FAISS</li>



<li>used inside: <code data-enlighter-language="python" class="EnlighterJSRAW">TracedRetriever.retrieve()</code></li>
</ul>



<h5 class="wp-block-heading">Agent Settings</h5>



<p>Agent workflows build on top of RAG, controlling:</p>



<ul class="wp-block-list">
<li>max agent steps</li>



<li>model used for intent detection</li>
</ul>



<h5 class="wp-block-heading">Evaluation Configuration</h5>



<p>Defines quality control thresholds:</p>



<ul class="wp-block-list">
<li>relevancy</li>



<li>hallucination risk</li>



<li>minimum acceptable quality</li>
</ul>



<p>Used in:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="17">from config import get_evaluation_config
</pre>



<p>This config-driven system makes your pipeline:</p>



<ul class="wp-block-list">
<li>reproducible</li>



<li>tunable</li>



<li>production-friendly</li>



<li>environment-agnostic</li>
</ul>



<p>Change models or thresholds, and no code changes are required.</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<!-- wp:paragraph -->
<h3>Need Help Configuring Your Development Environment?</h3>
<!-- /wp:paragraph -->

<!-- wp:image {"align":"center","id":18137,"sizeSlug":"large","linkDestination":"custom"} -->
<figure class="wp-block-image aligncenter size-large"><a href="https://pyimagesearch.com/pyimagesearch-university/" target="_blank" rel="noreferrer noopener"><img decoding="async" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2021/01/pyimagesearch_plus_jupyter.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-18137" srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2021/01/pyimagesearch_plus_jupyter.png?lossy=2&strip=1&webp=1 500w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2021/01/pyimagesearch_plus_jupyter.png?size=126x84&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2021/01/pyimagesearch_plus_jupyter.png?size=252x168&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2021/01/pyimagesearch_plus_jupyter.png?size=378x253&lossy=2&strip=1&webp=1 378w" sizes="(max-width: 500px) 100vw, 500px" /></a><figcaption>Having trouble configuring your development environment? Want access to pre-configured Jupyter Notebooks running on Google Colab? Be sure to join <a href="https://pyimagesearch.com/pyimagesearch-university/" target="_blank" rel="noreferrer noopener" aria-label=" (opens in a new tab)">PyImageSearch University</a> — you will be up and running with this tutorial in a matter of minutes. </figcaption></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>All that said, are you:</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li>Short on time?</li><li>Learning on your employer’s administratively locked system?</li><li>Wanting to skip the hassle of fighting with the command line, package managers, and virtual environments?</li><li><strong>Ready to run the code immediately on your Windows, macOS, or Linux system?</strong></li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>Then join <a href="https://pyimagesearch.com/pyimagesearch-university/" target="_blank">PyImageSearch University</a> today!</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><strong>Gain access to Jupyter Notebooks for this tutorial and other PyImageSearch guides pre-configured to run on Google Colab’s ecosystem right in your web browser!</strong> No installation required.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>And best of all, these Jupyter Notebooks will run on Windows, macOS, and Linux!</p>
<!-- /wp:paragraph -->



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Building-Langfuse-Traced-Retriever-FAISS"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Building-Langfuse-Traced-Retriever-FAISS">Building a Langfuse-Traced Retriever with FAISS</a></h2>



<p>The retriever is the beating heart of any RAG pipeline. If retrieval is weak, every downstream component (i.e., prompting, LLM generation, and evaluation) will degrade. In this section, we construct a <em>production-grade retriever</em> built on three pillars: <strong>local embeddings</strong>, <strong>FAISS vector search</strong>, and <strong>Langfuse instrumentation</strong>. The result is a component that is fast, reproducible, fully observable, and cheap to run because it never leaves your machine or calls a cloud API.</p>



<p>Your <code data-enlighter-language="python" class="EnlighterJSRAW">TracedRetriever</code> class in <code data-enlighter-language="python" class="EnlighterJSRAW">src/retriever.py</code> handles 4 responsibilities:</p>



<ul class="wp-block-list">
<li>Load an embedding model</li>



<li>Embed and index documents</li>



<li>Perform similarity-based search</li>



<li>Emit <strong>Langfuse spans</strong> for every step (embedding, indexing, and retrieval)</li>
</ul>



<h3 class="wp-block-heading">Loading and Embedding Documents</h3>



<p>The retriever begins by loading a <strong>local SentenceTransformers model</strong>, which provides dense vector embeddings without any external API calls.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="18">embeddings_config = get_embeddings_config()
model_name = embeddings_config.get("model", "sentence-transformers/all-MiniLM-L6-v2")
self.model = SentenceTransformer(model_name)
</pre>



<h4 class="wp-block-heading">Why local embeddings?</h4>



<ul class="wp-block-list">
<li><strong>No rate limits or API costs</strong> after the local environment is configured </li>



<li><strong>Fast inference</strong> through optimized ONNX or Torch acceleration</li>



<li><strong>Privacy-safe</strong> since no data leaves the environment</li>



<li><strong>Predictable latency</strong>, which is critical in production</li>
</ul>



<h4 class="wp-block-heading">Embedding a document (with tracing)</h4>



<p>Your <code data-enlighter-language="python" class="EnlighterJSRAW">embed()</code> method is wrapped with the Langfuse <code data-enlighter-language="python" class="EnlighterJSRAW">@observe</code> decorator:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="19">@observe(name="embed_text")
def embed(self, text: str) -> np.ndarray:
</pre>



<p>This automatically creates a <em>top-level span</em> called <code data-enlighter-language="python" class="EnlighterJSRAW">embed_text</code> in Langfuse.</p>



<p>Inside the span, you record:</p>



<ul class="wp-block-list">
<li>first 100 characters of the text</li>



<li>embedding dimension</li>
</ul>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="20">langfuse_context.update_current_observation(
    input={"text_preview": text[:100]}
)
</pre>



<p>The embedding call itself:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="21">embedding = self.model.encode([text], normalize_embeddings=True)[0]
</pre>



<p>This normalization step ensures the embeddings have unit length, which stabilizes similarity scoring and produces better retrieval in FAISS L2 spaces.</p>



<p>The span finishes by storing metadata:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="22">langfuse_context.update_current_observation(
    output={"embedding_dim": len(embedding)}
)
</pre>



<p>This is extremely useful later for debugging:</p>



<ul class="wp-block-list">
<li>Did documents produce embeddings with inconsistent lengths?</li>



<li>Are embeddings accidentally empty?</li>



<li>Are overly long texts being passed in?</li>
</ul>



<p>Langfuse gives you full visibility.</p>



<h3 class="wp-block-heading">Creating and Populating a FAISS Index</h3>



<p>After loading the embedding model, the retriever constructs a <strong>FAISS</strong> <code data-enlighter-language="python" class="EnlighterJSRAW">IndexFlatL2</code> index:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="23">self.index = faiss.IndexFlatL2(self.dimension)
</pre>



<p>This index:</p>



<ul class="wp-block-list">
<li>Stores vectors in RAM</li>



<li>Uses <strong>Euclidean distance</strong> (L2) for similarity</li>



<li>Has <em>no training step</em>, making it ideal for small and medium-sized datasets</li>
</ul>



<p>Your retriever keeps an in-memory list of source documents:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="24">self.documents = []
</pre>



<h4 class="wp-block-heading">Indexing documents (with tracing)</h4>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="25">@observe(name="index_documents")
def index_documents(self, documents: List[str]):
</pre>



<p>This span tracks:</p>



<ul class="wp-block-list">
<li>how many documents are being indexed</li>



<li>how many embeddings were added</li>



<li>previews of content for debugging</li>
</ul>



<p>Under the hood:</p>



<ul class="wp-block-list">
<li><strong>Store the raw documents</strong></li>



<li><strong>Embed them in a batch</strong></li>



<li><strong>Add the vectors to FAISS</strong></li>
</ul>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="26">embeddings = self.model.encode(documents, normalize_embeddings=True)
self.index.add(embeddings.astype(np.float32))
</pre>



<p>Because FAISS expects <code data-enlighter-language="python" class="EnlighterJSRAW">float32</code>, the cast is mandatory.</p>



<h4 class="wp-block-heading">Why IndexFlatL2?</h4>



<ul class="wp-block-list">
<li>Simple</li>



<li>Deterministic</li>



<li>Fast for small–medium corpora (&lt; 200k docs)</li>



<li>Plays well with normalized embeddings (MiniLM, BERT, etc.)</li>
</ul>



<p>Your pipeline achieves high throughput without additional libraries or GPUs.</p>



<h3 class="wp-block-heading">Retrieving with Similarity Ranking</h3>



<p>The retrieval process begins with the <code data-enlighter-language="python" class="EnlighterJSRAW">retrieve()</code> method:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="27">@observe(name="retrieve_documents")
def retrieve(self, query: str, top_k: int = None):
</pre>



<p>Langfuse creates a tracing span named <code data-enlighter-language="python" class="EnlighterJSRAW">retrieve_documents</code> for every search operation.</p>



<h4 class="wp-block-heading">Step 1. Embed the query</h4>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="28">query_embedding = self.embed(query).reshape(1, -1)
</pre>



<p>Notice that calling <code data-enlighter-language="python" class="EnlighterJSRAW">self.embed()</code> creates a <em>nested span</em> under the retrieval span in Langfuse.</p>



<p>This nesting hierarchy:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="29">retrieve_documents
    ├── embed_text
</pre>



<p>gives you a complete view of:</p>



<ul class="wp-block-list">
<li>how long embedding took</li>



<li>token count (if embedding model changes)</li>



<li>exact query text</li>
</ul>



<h4 class="wp-block-heading">Step 2. Search the FAISS index</h4>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="30">distances, indices = self.index.search(query_embedding, top_k)
</pre>



<p>FAISS returns:</p>



<ul class="wp-block-list">
<li><code data-enlighter-language="python" class="EnlighterJSRAW">indices</code>: the closest documents</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">distances</code>: L2 distances to each doc</li>
</ul>



<p>You convert distances into similarity scores:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="31">relevance_score = 1.0 / (1.0 + float(distance))
</pre>



<p>This transforms smaller distances into higher scores.</p>



<h4 class="wp-block-heading">Step 3. Format ranked results</h4>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="32">results.append({
    "content": self.documents[idx],
    "score": relevance_score,
    "rank": rank + 1,
    "distance": float(distance)
})
</pre>



<h4 class="wp-block-heading">Step 4. Log retrieval metadata to Langfuse</h4>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="33">langfuse_context.update_current_observation(
    output={
        "result_count": len(results),
        "scores": [r["score"] for r in results],
        "results": [...]
    }
)
</pre>



<p>You even send content previews (200 characters), which appear in the Langfuse UI and make debugging dramatically easier.</p>



<h3 class="wp-block-heading">Adding Langfuse Spans to Indexing and Retrieval Steps</h3>



<p>Langfuse observability is woven into every retrieval path using the <code data-enlighter-language="python" class="EnlighterJSRAW">@observe</code> decorator and metadata updates.</p>



<h4 class="wp-block-heading">Spans you automatically get from your retriever</h4>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://pyimagesearch.com/wp-content/uploads/2026/06/image-57.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="729" height="179" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-57.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54286"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-57.png?size=126x31&lossy=2&strip=1&webp=1 126w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-57-300x74.png?lossy=2&strip=1&webp=1 300w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-57.png?size=378x93&lossy=2&strip=1&webp=1 378w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-57.png?size=504x124&lossy=2&strip=1&webp=1 504w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-57.png?size=630x155&lossy=2&strip=1&webp=1 630w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-57.png?lossy=2&strip=1&webp=1 729w" sizes="(max-width: 729px) 100vw, 729px" /></a><figcaption class="wp-element-caption"><strong>Table 2: </strong>Key instrumented methods and their corresponding Langfuse tracing spans</figcaption></figure></div>


<p>These spans appear under your RAG pipeline trace like:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="34">rag_pipeline
    ├── retrieve_documents
    │       ├── embed_text
    │       └── result metadata
    ├── llm_completion
    ├── evaluate_rag_output
    └── final scoring
</pre>



<h4 class="wp-block-heading">Why this matters in production</h4>



<ul class="wp-block-list">
<li>You can identify whether latency is coming from <strong>embedding</strong>, <strong>FAISS search</strong>, or <strong>LLM inference</strong>.</li>



<li>You can detect mismatches like:
<ul class="wp-block-list">
<li>wrong embedding dimension</li>



<li>missing documents</li>



<li>unnormalized vectors</li>



<li>misconfigured top-k</li>
</ul>
</li>



<li>You get complete end-to-end lineage for every query.</li>



<li>You can monitor retriever performance across time.</li>
</ul>



<p>This is the observability layer that most open-source RAG tutorials <em>never</em> include, but you now have it baked into the core of your retriever.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Building-Traced-LLM-Wrapper-vLLM-Langfuse"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Building-Traced-LLM-Wrapper-vLLM-Langfuse">Building a Traced LLM Wrapper for vLLM and Langfuse</a></h2>



<h3 class="wp-block-heading">OpenAI-Compatible Chat Completions via vLLM</h3>



<p>Your LLM wrapper is split into 2 layers:</p>



<ul class="wp-block-list">
<li>a <strong>low-level OpenAI-compatible client</strong> in <code data-enlighter-language="python" class="EnlighterJSRAW">llm_utils.py</code>, and</li>



<li>a <strong>high-level, Langfuse-traced wrapper</strong> in <code data-enlighter-language="python" class="EnlighterJSRAW">llm_client.py</code>.</li>
</ul>



<p>The low-level client is created in <code data-enlighter-language="python" class="EnlighterJSRAW">get_llm_client()</code>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="35">from openai import OpenAI

def get_llm_client(timeout: int = 60, load_model_from_config: bool = False):
    if os.getenv("OPENAI_BASE_URL") is None:
        print("⚠️  OPENAI_BASE_URL not found in environment. Using default http://localhost:8000/v1")
   
    if os.getenv("OPENAI_API_KEY") is None:
        print("⚠️  OPENAI_API_KEY not set. Using dummy key.")
   
    client = OpenAI(
        base_url=os.getenv("OPENAI_BASE_URL", "http://localhost:8000/v1"),
        api_key=os.getenv("OPENAI_API_KEY", "dummy"),
        timeout=timeout,
    )
    ...
    return client
</pre>



<p>This means that <strong>as long as vLLM is running</strong> behind an OpenAI-compatible server (from <code data-enlighter-language="python" class="EnlighterJSRAW">docker-compose.yml</code> on <code data-enlighter-language="python" class="EnlighterJSRAW">http://localhost:8000/v1</code>), the rest of your code simply calls <code data-enlighter-language="python" class="EnlighterJSRAW">client.chat.completions.create(...)</code> exactly like it would against OpenAI, without any vendor-specific changes.</p>



<p>At the higher level, <code data-enlighter-language="python" class="EnlighterJSRAW">TracedLLMClient</code> in <code data-enlighter-language="python" class="EnlighterJSRAW">src/llm_client.py</code> wraps this client and pulls model configuration from <code data-enlighter-language="python" class="EnlighterJSRAW">configs/config.yaml</code> via <code data-enlighter-language="python" class="EnlighterJSRAW">get_llm_config()</code>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="36">llm:
  base_url: "http://localhost:8000/v1"
  model: "meta-llama/Llama-2-7b-chat-hf"
  temperature: 0.7
  max_tokens: 300
  max_retries: 2
</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="37">class TracedLLMClient:
    def __init__(self, model: str = None, max_retries: int = 2, timeout: int = 60):
        self.client = get_llm_client(timeout=timeout)
        if model is None:
            llm_config = get_llm_config()
            model = llm_config.get("model", "meta-llama/Llama-2-7b-chat-hf")
        self.model = model
        self.max_retries = max_retries
</pre>



<p>The end result: your <strong>RAG and agent code never talks to vLLM directly</strong>; it always goes through <code data-enlighter-language="python" class="EnlighterJSRAW">TracedLLMClient</code>, which is OpenAI-compatible, config-driven, and ready for tracing.</p>



<h3 class="wp-block-heading">Retry Logic and Error Handling</h3>



<p>The core of the wrapper is the <code data-enlighter-language="python" class="EnlighterJSRAW">complete()</code> method:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="38">from langfuse.decorators import observe, langfuse_context

class TracedLLMClient:
    @observe(name="llm_completion")
    def complete(self, messages: List[Dict[str, str]], **kwargs) -> Dict:
        llm_config = get_llm_config()
        temperature = kwargs.get("temperature", llm_config.get("temperature", 0.7))
        max_tokens = kwargs.get("max_tokens", llm_config.get("max_tokens", 300))

        langfuse_context.update_current_observation(
            input={"messages": messages, "model": self.model}
        )

        last_error = None
        for attempt in range(self.max_retries):
            try:
                response = self.client.chat.completions.create(
                    model=self.model,
                    messages=messages,
                    temperature=temperature,
                    max_tokens=max_tokens
                )
                ...
                return {..., "success": True}
            except Exception as e:
                last_error = e
                if attempt &lt; self.max_retries - 1:
                    time.sleep(1)
                    continue

        error_msg = f"LLM call failed after {self.max_retries} attempts: {last_error}"
        langfuse_context.update_current_observation(
            level="ERROR",
            output={"error": error_msg}
        )
        return {"content": None, "error": error_msg, "success": False}
</pre>



<p>A few production-grade details are baked in here:</p>



<ul class="wp-block-list">
<li><strong>Config-driven defaults:</strong> <code data-enlighter-language="python" class="EnlighterJSRAW">temperature</code> and <code data-enlighter-language="python" class="EnlighterJSRAW">max_tokens</code> come from <code data-enlighter-language="python" class="EnlighterJSRAW">config.yaml</code> but can be overridden per-call via kwargs.</li>



<li><strong>Retry loop:</strong> the method tries up to <code data-enlighter-language="python" class="EnlighterJSRAW">self.max_retries</code> times (default 2), with a short <code data-enlighter-language="python" class="EnlighterJSRAW">time.sleep(1)</code> backoff between attempts.</li>



<li><strong>Graceful failure:</strong> if all attempts fail, you get a structured response <code data-enlighter-language="python" class="EnlighterJSRAW">{content: None, error: "...", success: False}</code> instead of a hard crash, and the Langfuse span is explicitly marked as <code data-enlighter-language="python" class="EnlighterJSRAW">"ERROR"</code>.</li>
</ul>



<p>When you call this from <code data-enlighter-language="python" class="EnlighterJSRAW">rag_pipeline.py</code> or <code data-enlighter-language="python" class="EnlighterJSRAW">agent_orchestration.py</code>, you can safely check <code data-enlighter-language="python" class="EnlighterJSRAW">result</code><code data-enlighter-language="python" class="EnlighterJSRAW">["success"]</code> and decide whether to return a fallback answer, propagate the error, or short-circuit the pipeline.</p>



<h3 class="wp-block-heading">Logging Request and Response Payloads</h3>



<p>Because <code data-enlighter-language="python" class="EnlighterJSRAW">TracedLLMClient</code> is decorated with <code data-enlighter-language="python" class="EnlighterJSRAW">@observe(name="llm_completion")</code>, every call automatically becomes a <strong>Langfuse span</strong>, and you manually enrich that span with <strong>inputs and outputs</strong> via <code data-enlighter-language="python" class="EnlighterJSRAW">langfuse_context</code>.</p>



<p>At the start of the call, you log the <strong>request payload</strong>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="39">langfuse_context.update_current_observation(
    input={"messages": messages, "model": self.model}
)
</pre>



<p>This means that in the Langfuse UI you will see:</p>



<ul class="wp-block-list">
<li>the full chat history (messages) you sent to the model</li>



<li>which <strong>model</strong> was used (e.g., <code data-enlighter-language="python" class="EnlighterJSRAW">"meta-llama/Llama-2-7b-chat-hf"</code>)</li>
</ul>



<p>After a successful LLM call, you log the <strong>response content</strong>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="40">content = response.choices[0].message.content

langfuse_context.update_current_observation(
    output={"content": content},
    usage={
        "input": response.usage.prompt_tokens,
        "output": response.usage.completion_tokens,
        "total": response.usage.total_tokens
    },
    metadata={"attempt": attempt + 1}
)
</pre>



<p>So every Langfuse span for <code data-enlighter-language="python" class="EnlighterJSRAW">llm_completion</code> will show:</p>



<ul class="wp-block-list">
<li>the <strong>raw answer text</strong> the model generated</li>



<li>which <strong>attempt</strong> succeeded (first try or retry)</li>



<li>the <strong>token usage</strong> for that call</li>
</ul>



<p>On failure, the wrapper logs the error message instead of content:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="41">langfuse_context.update_current_observation(
    level="ERROR",
    output={"error": error_msg}
)
</pre>



<p>This gives you <strong>debuggable traces</strong> when vLLM is down, you hit timeouts, or your model name is misconfigured.</p>



<h3 class="wp-block-heading">Capturing Token Usage and Metadata in Langfuse</h3>



<p><code data-enlighter-language="python" class="EnlighterJSRAW">vLLM</code> exposes <code data-enlighter-language="python" class="EnlighterJSRAW">response.usage</code> in an OpenAI-like shape, and you forward that directly into Langfuse as part of the span:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="42">langfuse_context.update_current_observation(
    output={"content": content},
    usage={
        "input": response.usage.prompt_tokens,
        "output": response.usage.completion_tokens,
        "total": response.usage.total_tokens
    },
    metadata={"attempt": attempt + 1}
)

return {
    "content": content,
    "usage": response.usage.model_dump(),
    "success": True
}
</pre>



<p>This gives you <strong>2 layers</strong> of observability:</p>



<ul class="wp-block-list">
<li><strong>Inside Langfuse</strong>
<ul class="wp-block-list">
<li>You can filter and inspect spans by <code data-enlighter-language="python" class="EnlighterJSRAW">usage.total</code>, see which prompts are expensive, and spot unusually long generations.</li>



<li>You can correlate token usage with overall RAG or agent traces because <code data-enlighter-language="python" class="EnlighterJSRAW">llm_completion</code> spans sit inside higher-level pipeline spans such as <code data-enlighter-language="python" class="EnlighterJSRAW">rag_pipeline</code> or <code data-enlighter-language="python" class="EnlighterJSRAW">agent_workflow</code>.</li>
</ul>
</li>



<li><strong>Inside your Python code</strong>
<ul class="wp-block-list">
<li>Callers receive <code data-enlighter-language="python" class="EnlighterJSRAW">result["usage"]</code> and can log or aggregate it themselves (e.g., cost dashboards, quotas, or alerting in future lessons).</li>



<li>Because usage is returned as <code data-enlighter-language="python" class="EnlighterJSRAW">response.usage.model_dump()</code>, it is just a normal Python dict you can serialize or send elsewhere.</li>
</ul>
</li>
</ul>



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">metadata={"attempt": attempt + 1}</code> block gives you a clean way to see <strong>how often retries are needed</strong>; if you start seeing a lot of second or third attempts in Langfuse, you know <code data-enlighter-language="python" class="EnlighterJSRAW">vLLM</code> or your infra is becoming unreliable and needs attention.</p>



<h3 class="wp-block-heading">Example: Using the Traced LLM Client</h3>



<p>Your <code data-enlighter-language="python" class="EnlighterJSRAW">__main__ block</code> in <code data-enlighter-language="python" class="EnlighterJSRAW">llm_client.py</code> shows a minimal end-to-end example:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="43">if __name__ == "__main__":
    client = TracedLLMClient()
   
    result = client.complete(
        messages=[
            {"role": "user", "content": "What is RAG in AI?"}
        ]
    )
   
    print(f"Response: {result['content']}")
    print(f"Tokens: {result['usage']['total_tokens']}")
   
    trace_id = langfuse_context.get_current_trace_id()
    langfuse_host = os.getenv("LANGFUSE_HOST", "http://localhost:3000")
    print(f"🔍 View trace: {langfuse_host}/trace/{trace_id}")
</pre>



<p>This script:</p>



<ul class="wp-block-list">
<li>verifies that <code data-enlighter-language="python" class="EnlighterJSRAW">vLLM</code> is responding correctly</li>



<li>verifies that <code data-enlighter-language="python" class="EnlighterJSRAW">Langfuse</code> keys and host are properly configured</li>



<li>gives you a direct URL to the <strong>exact trace</strong> for this LLM call in the <code data-enlighter-language="python" class="EnlighterJSRAW">Langfuse</code> UI</li>
</ul>



<p>In the next sections, you will see this same <code data-enlighter-language="python" class="EnlighterJSRAW">TracedLLMClient</code> reused inside the <strong>RAG pipeline</strong> and <strong>RAG evaluation</strong>, where it becomes just one span in a larger, nested trace tree.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Building-Fully-Traced-RAG-Pipeline-Langfuse"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Building-Fully-Traced-RAG-Pipeline-Langfuse">Building a Fully Traced RAG Pipeline with Langfuse</a></h2>



<h3 class="wp-block-heading">The run_rag_pipeline Orchestrator</h3>



<p>Your full RAG flow is implemented in <code data-enlighter-language="python" class="EnlighterJSRAW">src/rag_pipeline.py</code> as a single orchestrator function:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="44">@observe(name="rag_pipeline")
def run_rag_pipeline(
    question: str,
    retriever: TracedRetriever,
    llm_client: TracedLLMClient,
    top_k: int = 3
) -> Dict:
    ...
</pre>



<p>This one function wires together everything you have built so far: it takes a <strong>user question</strong>, uses the <strong>traced retriever</strong> to find context, calls the <strong>traced LLM client</strong> to generate an answer, and then runs <strong>RAG evaluation</strong> to compute relevancy and hallucination scores. Because it is decorated with <code data-enlighter-language="python" class="EnlighterJSRAW">@observe(name="rag_pipeline")</code>, the entire run shows up in Langfuse as a <strong>top-level trace</strong>, with all retrieval, LLM, and evaluation spans nested underneath.</p>



<h3 class="wp-block-heading">Step 1: Retrieve</h3>



<p>The first step is retrieving documents with your <code data-enlighter-language="python" class="EnlighterJSRAW">TracedRetriever</code>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="45">langfuse_context.update_current_observation(
    input={"question": question, "top_k": top_k}
)

print("Step 1: Retrieving documents...")
docs = retriever.retrieve(query=question, top_k=top_k)

if not docs:
    print("❌ No documents found")
    return {"answer": "No relevant information found.", "success": False}
</pre>



<p>Here is what happens in this step:</p>



<ul class="wp-block-list">
<li>The pipeline span is enriched with the <strong>incoming question</strong> and the <strong>top_k</strong> parameter via <code data-enlighter-language="python" class="EnlighterJSRAW">langfuse_context.update_current_observation</code>.</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">retriever.retrieve(...)</code> is itself decorated with <code data-enlighter-language="python" class="EnlighterJSRAW">@observe(name="retrieve_documents")</code>, so Langfuse automatically creates a <strong>child span</strong> under <code data-enlighter-language="python" class="EnlighterJSRAW">rag_pipeline</code>. Inside that span, you log the query, scores, and content previews.</li>



<li>If the index is empty or nothing is returned, you fail fast with a friendly message and <code data-enlighter-language="python" class="EnlighterJSRAW">success=False</code> instead of trying to prompt the LLM with no context.</li>
</ul>



<p>By the end of Step 1, you have a ranked list of documents such as:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="46">[
    {"content": "...", "score": 0.93, "rank": 1, "distance": 0.12},
    {"content": "...", "score": 0.88, "rank": 2, "distance": 0.18},
    ...
]
</pre>



<p>and their retrieval details are already captured in Langfuse.</p>



<h3 class="wp-block-heading">Step 2: Build Prompt from Retrieved Docs</h3>



<p>Next, you turn those retrieved documents into a single, structured prompt:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="47">print("Step 2: Building prompt...")
context = "\n\n".join([f"[{i+1}] {d['content']}" for i, d in enumerate(docs)])
messages = [
    {"role": "system", "content": "Answer based on the provided context."},
    {"role": "user", "content": f"Context:\n{context}\n\nQuestion: {question}\n\nAnswer:"}
]
</pre>



<p>A few important details:</p>



<ul class="wp-block-list">
<li>Each document is tagged with an index (<code data-enlighter-language="python" class="EnlighterJSRAW">[1]</code>, <code data-enlighter-language="python" class="EnlighterJSRAW">[2]</code>, <code data-enlighter-language="python" class="EnlighterJSRAW">[3]</code>) so it is easy to map parts of the final answer back to specific sources, both as a human and when you are debugging traces.</li>



<li>The <strong>system message</strong> explicitly constrains the model: <em>“Answer based on the provided context.”</em> This is a simple but effective guardrail against hallucinations.</li>



<li>The <strong>user message</strong> includes both the stitched context and the original question, finishing with &#8220;Answer:&#8221; to bias the model toward a direct response.</li>
</ul>



<p>Because messages are later passed into the traced LLM client, the <strong>entire prompt (including context)</strong> is visible inside the <code data-enlighter-language="python" class="EnlighterJSRAW">llm_completion</code> span in Langfuse.</p>



<h3 class="wp-block-heading">Step 3: Generate with vLLM</h3>



<p>You then hand off the prompt to your <code data-enlighter-language="python" class="EnlighterJSRAW">TracedLLMClient</code>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="48">print("Step 3: Generating answer...")
result = llm_client.complete(messages)

if not result["success"]:
    print(f"❌ Generation failed: {result.get('error')}")
    return {"answer": None, "error": result.get("error"), "success": False}

answer = result["content"]
print(f"✅ Answer generated\n")
</pre>



<p>Under the hood:</p>



<ul class="wp-block-list">
<li><code data-enlighter-language="python" class="EnlighterJSRAW">TracedLLMClient.complete()</code> calls <code data-enlighter-language="python" class="EnlighterJSRAW">client.chat.completions.create(...)</code> against the vLLM OpenAI-compatible server (configured via <code data-enlighter-language="python" class="EnlighterJSRAW">OPENAI_BASE_URL</code> and <code data-enlighter-language="python" class="EnlighterJSRAW">OPENAI_API_KEY</code>, with model and temperature from <code data-enlighter-language="python" class="EnlighterJSRAW">config.yaml</code>).</li>



<li>The method is decorated with <code data-enlighter-language="python" class="EnlighterJSRAW">@observe(name="llm_completion")</code>, so a <strong>child span</strong> is created inside the <code data-enlighter-language="python" class="EnlighterJSRAW">rag_pipeline</code> trace.</li>



<li>Inside that span, you log:
<ul class="wp-block-list">
<li>the <strong>messages</strong> and <strong>model</strong> as input</li>



<li>the <strong>generated content</strong> as output</li>



<li>detailed <strong>token usage</strong> (<code data-enlighter-language="python" class="EnlighterJSRAW">prompt_tokens</code>, <code data-enlighter-language="python" class="EnlighterJSRAW">completion_tokens</code>, <code data-enlighter-language="python" class="EnlighterJSRAW">total_tokens</code>) as usage, plus <code data-enlighter-language="python" class="EnlighterJSRAW">metadata={"attempt": ...}</code> indicating which retry succeeded</li>
</ul>
</li>
</ul>



<p>If <code data-enlighter-language="python" class="EnlighterJSRAW">vLLM</code> is down, misconfigured, or times out, the wrapper returns <code data-enlighter-language="python" class="EnlighterJSRAW">{"success": False, "error": ...}</code> and updates the Langfuse span with <code data-enlighter-language="python" class="EnlighterJSRAW">level="ERROR"</code>, so you get a clear red node in the trace instead of a mysterious failure.</p>



<h3 class="wp-block-heading">Step 4: Evaluate Response Quality</h3>



<p>Once you have an answer, you pass everything into the evaluation layer in <code data-enlighter-language="python" class="EnlighterJSRAW">src/evaluation.py</code>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="49">print("Step 4: Evaluating quality...")
evaluation_results = evaluate_rag_output(question, docs, answer)
</pre>



<p><code data-enlighter-language="python" class="EnlighterJSRAW">evaluate_rag_output</code> is itself annotated with <code data-enlighter-language="python" class="EnlighterJSRAW">@observe(name="evaluate_rag_output")</code>, and it calls 2 more traced helpers under the hood:</p>



<ul class="wp-block-list">
<li><code data-enlighter-language="python" class="EnlighterJSRAW">evaluate_relevancy(query, retrieved_docs, answer)</code></li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">evaluate_hallucination_risk(retrieved_docs, answer)</code></li>
</ul>



<p>The process inside <code data-enlighter-language="python" class="EnlighterJSRAW">evaluate_rag_output</code> looks like this:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="50">langfuse_context.update_current_observation(
    input={
        "query": query,
        "doc_count": len(retrieved_docs),
        "answer_length": len(answer)
    }
)

relevancy_score = evaluate_relevancy(query, retrieved_docs, answer)
hallucination_risk = evaluate_hallucination_risk(retrieved_docs, answer)
overall_quality = (relevancy_score + (1.0 - hallucination_risk)) / 2.0

eval_config = get_evaluation_config()
min_quality = eval_config.get("min_quality_score", 0.6)

results = {
    "relevancy_score": relevancy_score,
    "hallucination_risk": hallucination_risk,
    "overall_quality": overall_quality,
    "passed": overall_quality >= min_quality
}
</pre>



<p>In more detail:</p>



<ul class="wp-block-list">
<li><strong>Relevancy scoring</strong> (<code data-enlighter-language="python" class="EnlighterJSRAW">evaluate_relevancy</code>): computes how well the answer overlaps with both the query and the retrieved documents using simple word-level heuristics.</li>



<li><strong>Hallucination risk</strong> (<code data-enlighter-language="python" class="EnlighterJSRAW">evaluate_hallucination_risk</code>): estimates how many of the answer’s content words are grounded in the retrieved documents; low grounding means higher risk.</li>



<li><strong>Overall quality:</strong> is a simple average of <code data-enlighter-language="python" class="EnlighterJSRAW">relevancy</code> and <code data-enlighter-language="python" class="EnlighterJSRAW">1 − hallucination_risk</code>, giving a single number between 0 and 1.</li>



<li>A minimum quality threshold (<code data-enlighter-language="python" class="EnlighterJSRAW">min_quality_score</code>) comes from the <code data-enlighter-language="python" class="EnlighterJSRAW">evaluation</code> section of <code data-enlighter-language="python" class="EnlighterJSRAW">config.yaml</code> and is used to set a <code data-enlighter-language="python" class="EnlighterJSRAW">passed</code> boolean.</li>
</ul>



<p>The function then:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="51">langfuse_context.score_current_observation(
    name="relevancy",
    value=relevancy_score,
    comment="Keyword and document relevance"
)

langfuse_context.score_current_observation(
    name="hallucination_risk",
    value=hallucination_risk,
    comment="Risk of ungrounded claims"
)

langfuse_context.score_current_observation(
    name="overall_quality",
    value=overall_quality,
    comment=f"Combined quality score (threshold: {min_quality})"
)

langfuse_context.update_current_observation(output=results)
</pre>



<p>So you get <strong>3 named scores</strong> on the evaluation span inside Langfuse: <code data-enlighter-language="python" class="EnlighterJSRAW">relevancy</code>, <code data-enlighter-language="python" class="EnlighterJSRAW">hallucination_risk</code>, and <code data-enlighter-language="python" class="EnlighterJSRAW">overall_quality</code>, each with a numeric value and a human-readable comment.</p>



<h3 class="wp-block-heading">Tracing the Entire RAG Pipeline with Nested Spans</h3>



<p>Back in <code data-enlighter-language="python" class="EnlighterJSRAW">run_rag_pipeline</code>, you finalize the top-level observation and return a structured result:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="52">langfuse_context.update_current_observation(
    output={
        "answer": answer,
        "sources_count": len(docs),
        "evaluation": evaluation_results
    }
)

print(f"✅ Evaluation complete")
print(f"  Relevancy: {evaluation_results['relevancy_score']:.2f}")
print(f"  Hallucination Risk: {evaluation_results['hallucination_risk']:.2f}")
print(f"  Overall Quality: {evaluation_results['overall_quality']:.2f}")
print(f"  Passed: {'✅' if evaluation_results['passed'] else '❌'}\n")
</pre>



<p>Then you expose the trace URL:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="53">trace_id = langfuse_context.get_current_trace_id()
langfuse_host = os.getenv("LANGFUSE_HOST", "http://localhost:3000")

print(f"{'='*50}")
print(f"✅ Pipeline Complete")
print(f"🔍 View trace: {langfuse_host}/trace/{trace_id}")
print(f"{'='*50}\n")
</pre>



<p>At this point, a single pipeline run creates a <strong>hierarchy of spans</strong> roughly like this in Langfuse:</p>



<ul class="wp-block-list">
<li><code data-enlighter-language="python" class="EnlighterJSRAW">rag_pipeline</code> (top-level)
<ul class="wp-block-list">
<li><code data-enlighter-language="python" class="EnlighterJSRAW">retrieve_documents</code> (from <code data-enlighter-language="python" class="EnlighterJSRAW">TracedRetriever.retrieve</code>)
<ul class="wp-block-list">
<li><code data-enlighter-language="python" class="EnlighterJSRAW">embed_text</code> (from <code data-enlighter-language="python" class="EnlighterJSRAW">TracedRetriever.embed</code>)</li>
</ul>
</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">llm_completion</code> (from <code data-enlighter-language="python" class="EnlighterJSRAW">TracedLLMClient.complete</code>)</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">evaluate_rag_output</code>
<ul class="wp-block-list">
<li><code data-enlighter-language="python" class="EnlighterJSRAW">evaluate_relevancy</code></li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">evaluate_hallucination</code></li>
</ul>
</li>
</ul>
</li>
</ul>



<p>Each node contains its own <strong>inputs</strong>, <strong>outputs</strong>, <strong>usage</strong>, and <strong>scores</strong>, giving you a complete picture of <strong>where time is spent</strong>, <strong>how the model behaved</strong>, and <strong>whether the final answer passed your quality threshold</strong>.</p>



<h3 class="wp-block-heading">Returned Structure and Downstream Use</h3>



<p>Finally, the function returns a rich Python dictionary :</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="54">return {
    "answer": answer,
    "sources": docs,
    "evaluation": evaluation_results,
    "success": True
}
</pre>



<p>This shape is deliberate:</p>



<ul class="wp-block-list">
<li><code data-enlighter-language="python" class="EnlighterJSRAW">answer</code>: can be rendered in a UI, CLI, or logged for later inspection.</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">sources</code>: lets you show which documents backed the answer (e.g., for “source citations” in a frontend).</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">evaluation</code>: gives your downstream systems a simple way to <strong>gate</strong> responses (e.g., only show answers where <code data-enlighter-language="python" class="EnlighterJSRAW">overall_quality &gt;= 0.7</code>).</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">success</code>: makes it easy to distinguish between “no documents”, “LLM error”, and “normal completion”.</li>
</ul>



<p>Together, this section gives you not just a RAG pipeline, but a <strong>fully traced, quality-scored RAG system</strong> that is ready to plug into dashboards, UIs, or further production hardening.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Implementing-LLM-Evaluation-Metrics-Relevancy-Hallucination-Risk"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Implementing-LLM-Evaluation-Metrics-Relevancy-Hallucination-Risk">Implementing LLM Evaluation Metrics for RAG: Relevancy and Hallucination Risk</a></h2>



<h3 class="wp-block-heading">Relevancy Scoring</h3>



<p>Relevancy is implemented in <code data-enlighter-language="python" class="EnlighterJSRAW">evaluate_relevancy()</code> and answers a simple but crucial question: <strong>“How well does the model’s answer align with the retrieved documents and the user’s query?”</strong></p>



<p>Your scoring function uses a lightweight, keyword-overlap heuristic, which is ideal for debugging and observability without introducing another model dependency. The implementation:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="55">@observe(name="evaluate_relevancy")
def evaluate_relevancy(query: str, retrieved_docs: List[Dict], answer: str) -> float:
    langfuse_context.update_current_observation(
        input={"query": query, "doc_count": len(retrieved_docs), "answer_length": len(answer)}
    )

    query_words = set(query.lower().split())
    answer_words = set(answer.lower().split())

    overlap_with_query = len(answer_words &amp; query_words) / max(len(query_words), 1)

    doc_words = set()
    for doc in retrieved_docs:
        doc_words |= set(doc["content"].lower().split())

    overlap_with_docs = len(answer_words &amp; doc_words) / max(len(answer_words), 1)

    relevancy_score = (overlap_with_query + overlap_with_docs) / 2.0

    langfuse_context.score_current_observation(
        name="relevancy",
        value=relevancy_score,
        comment="Keyword and doc overlap relevance"
    )

    langfuse_context.update_current_observation(output={"relevancy": relevancy_score})
    return relevancy_score
</pre>



<p><strong>What the algorithm evaluates:</strong></p>



<ul class="wp-block-list">
<li><strong>Query–Answer overlap:</strong> Ensures the model is addressing the question.</li>



<li><strong>Document–Answer overlap:</strong> Checks that the model grounds its answer in retrieved context.</li>



<li>The final score is the average of both signals.</li>
</ul>



<p>While simple, this gives you an interpretable, production-friendly metric that appears directly in Langfuse traces.</p>



<h3 class="wp-block-heading">Hallucination Risk Estimation</h3>



<p>Hallucination risk is implemented in <code data-enlighter-language="python" class="EnlighterJSRAW">evaluate_hallucination_risk()</code> and estimates <strong>how much of the answer is unsupported by the retrieved documents</strong>.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="56">@observe(name="evaluate_hallucination")
def evaluate_hallucination_risk(retrieved_docs: List[Dict], answer: str) -> float:
    all_doc_words = set()
    for doc in retrieved_docs:
        all_doc_words |= set(doc["content"].lower().split())

    answer_words = set(answer.lower().split())

    grounding_ratio = len(answer_words &amp; all_doc_words) / max(len(answer_words), 1)
    hallucination_risk = 1.0 - grounding_ratio
</pre>



<p><strong>Interpretation:</strong></p>



<ul class="wp-block-list">
<li>If every important token in the answer appears in the retrieved context, the <strong>hallucination risk is low</strong>.</li>



<li>If the answer relies heavily on tokens not present in any source document, the <strong>hallucination risk is high</strong>.</li>
</ul>



<p>Langfuse logs this as:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="57">langfuse_context.score_current_observation(
    name="hallucination_risk",
    value=hallucination_risk,
    comment="Ungrounded token ratio"
)
</pre>



<p>This trace node helps you immediately visualize how close an answer is to going “off the rails.”</p>



<h3 class="wp-block-heading">Overall Quality Metric</h3>



<p>Your master scoring function <code data-enlighter-language="python" class="EnlighterJSRAW">evaluate_rag_output()</code> combines the 2 metrics:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="58">overall_quality = (relevancy_score + (1.0 - hallucination_risk)) / 2.0
</pre>



<p>This means:</p>



<ul class="wp-block-list">
<li>high relevancy and low hallucination risk indicate <strong>high quality</strong></li>



<li>low relevancy and high hallucination risk indicate <strong>low quality</strong></li>
</ul>



<p><code data-enlighter-language="python" class="EnlighterJSRAW">config.yaml</code> defines the minimum acceptable score:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="59">evaluation:
  min_quality_score: 0.6
</pre>



<p>Then:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="60">passed = overall_quality >= min_quality
</pre>



<p>This allows your downstream systems to treat RAG evaluation like a <strong>gatekeeper</strong>:</p>



<ul class="wp-block-list">
<li><code data-enlighter-language="python" class="EnlighterJSRAW">passed=True</code>: show the answer to the user, store it, or send it downstream</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">passed=False</code>: trigger fallback mode, self-reflection, or agentic repair workflows</li>
</ul>



<p>All 3 metrics (<code data-enlighter-language="python" class="EnlighterJSRAW">relevancy</code>, <code data-enlighter-language="python" class="EnlighterJSRAW">hallucination_risk</code>, and <code data-enlighter-language="python" class="EnlighterJSRAW">overall_quality</code>) are scored and attached to the current Langfuse span.</p>



<h3 class="wp-block-heading">How Langfuse Displays Evaluation and Scoring Nodes</h3>



<p>The evaluation subsystem produces one of the most informative trace segments in Langfuse. A typical structure:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="61">rag_pipeline
 ├── retrieve_documents
 ├── llm_completion
 └── evaluate_rag_output
       ├── relevancy (score)
       ├── hallucination_risk (score)
       ├── overall_quality (score)
</pre>



<p>Each node includes:</p>



<h4 class="wp-block-heading">Inputs</h4>



<ul class="wp-block-list">
<li>user query</li>



<li>document count</li>



<li>answer length</li>
</ul>



<h4 class="wp-block-heading">Outputs</h4>



<ul class="wp-block-list">
<li>numeric scores</li>



<li>pass-or-fail status</li>



<li>evaluation metadata</li>
</ul>



<h4 class="wp-block-heading">Visual Benefits Inside Langfuse</h4>



<ul class="wp-block-list">
<li><strong>Color-coded score nodes</strong> help you spot failing RAG runs instantly.</li>



<li><strong>Timeline alignment</strong> shows you evaluation overhead and where bottlenecks appear.</li>



<li><strong>Nested spans</strong> reveal exactly which part of the pipeline caused a failure.</li>



<li><strong>JSON detail view</strong> allows exporting evaluation metrics for dashboards or analytics.</li>
</ul>



<p>With these evaluation spans, your Langfuse trace evolves from a simple log viewer into a <strong>quality monitoring dashboard for your RAG system</strong>.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Running-Inspecting-RAG-Pipeline-End-to-End"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Running-Inspecting-RAG-Pipeline-End-to-End">Running and Inspecting the RAG Pipeline End-to-End</a></h2>



<h3 class="wp-block-heading">Running rag_pipeline.py End-to-End</h3>



<p>With all components in place (the retriever, the traced LLM wrapper, and the evaluation module), you can now run the complete production-grade RAG pipeline. The script <code data-enlighter-language="python" class="EnlighterJSRAW">rag_pipeline.py</code> orchestrates the entire flow:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="62">python src/rag_pipeline.py
</pre>



<p>This script loads documents, indexes them, retrieves the <code data-enlighter-language="python" class="EnlighterJSRAW">top_k</code> matches, builds a contextual prompt, generates an answer using <code data-enlighter-language="python" class="EnlighterJSRAW">vLLM</code>, evaluates the output quality, and logs every step into <code data-enlighter-language="python" class="EnlighterJSRAW">Langfuse</code>. If all services are running (<code data-enlighter-language="python" class="EnlighterJSRAW">Langfuse</code> UI on port <code data-enlighter-language="python" class="EnlighterJSRAW">3000</code> and <code data-enlighter-language="python" class="EnlighterJSRAW">vLLM</code> on port <code data-enlighter-language="python" class="EnlighterJSRAW">8000</code>), the run completes with a final console message showing the trace URL:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="63">🔍 View trace: http://localhost:3000/trace/&lt;trace_id>
</pre>



<p>This makes it trivial to jump directly into the corresponding trace in your observability dashboard and inspect the entire RAG execution, including nested spans and evaluation scores.</p>



<h3 class="wp-block-heading">Example Trace Outputs</h3>



<p>A successful run produces a hierarchical trace structure in Langfuse that mirrors your pipeline architecture. A typical RAG trace looks like this:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="64">rag_pipeline
 ├── retrieve_documents
 │     ├── embed_text
 │     └── FAISS search metadata
 ├── llm_completion
 │     ├── request payload
 │     ├── response payload
 │     └── token usage
 └── evaluate_rag_output
        ├── relevancy (score)
        ├── hallucination_risk (score)
        └── overall_quality (score)
</pre>



<p>What you will see in the trace:</p>



<h4 class="wp-block-heading">Retrieval metadata</h4>



<ul class="wp-block-list">
<li><code data-enlighter-language="python" class="EnlighterJSRAW">top_k</code> value</li>



<li>query text</li>



<li>relevance scores</li>



<li>FAISS distances</li>



<li>document preview snippets</li>
</ul>



<h4 class="wp-block-heading">LLM generation metadata</h4>



<ul class="wp-block-list">
<li>system and user messages used for prompting</li>



<li>token usage breakdown</li>



<li>retry attempts</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">vLLM</code> latency and response time</li>
</ul>



<h4 class="wp-block-heading">Evaluation metrics</h4>



<ul class="wp-block-list">
<li>numeric relevancy score</li>



<li>hallucination risk estimation</li>



<li>overall quality score</li>



<li>pass-or-fail decision using the threshold in <code data-enlighter-language="python" class="EnlighterJSRAW">config.yaml</code></li>
</ul>



<p>Together, these give you a full audit trail for each RAG run, which is perfect for debugging, monitoring, or offline analysis.</p>



<h3 class="wp-block-heading">Debugging with the Langfuse UI (Span Trees, Scores, and Metadata)</h3>



<p>Langfuse is not just a logger; it acts as a <strong>visual debugger for your entire RAG system</strong>. When you open the trace URL, you will see several powerful debugging tools:</p>



<h4 class="wp-block-heading">Span Tree View</h4>



<p>This hierarchical tree shows the exact execution order and timing of:</p>



<ul class="wp-block-list">
<li>retrieval</li>



<li>embedding</li>



<li>indexing</li>



<li>LLM generation</li>



<li>evaluation steps</li>
</ul>



<p>It helps you detect:</p>



<ul class="wp-block-list">
<li>slow spans (bottlenecks)</li>



<li>failed or retried LLM calls</li>



<li>missing or empty retrieval results</li>
</ul>



<h4 class="wp-block-heading">Scoring Nodes</h4>



<p>Evaluation scores appear as structured nodes:</p>



<ul class="wp-block-list">
<li><code data-enlighter-language="python" class="EnlighterJSRAW">relevancy</code></li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">hallucination_risk</code></li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">overall_quality</code></li>
</ul>



<p>Langfuse color-codes these (green, yellow, and red), making it instantly clear when a RAG answer is degrading in quality.</p>



<h4 class="wp-block-heading">Metadata Panels</h4>



<p>Each span contains:</p>



<ul class="wp-block-list">
<li>input and output payloads</li>



<li>token counts</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">FAISS</code> distances</li>



<li>processed document counts</li>



<li>retry counts</li>



<li>trace-level summaries</li>
</ul>



<p>This makes debugging extremely fast:</p>



<ul class="wp-block-list">
<li>Wrong documents retrieved? Inspect retrieval span input and output.</li>



<li>Unexpected LLM answer? Check the exact prompt in the generation span.</li>



<li>Poor evaluation scores? Expand the scoring spans to see the raw metrics.</li>
</ul>



<p>Because traces are stored locally in your self-hosted Langfuse instance, you get complete transparency without relying on cloud telemetry.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Viewing-RAG-Traces-Spans-Scores-Langfuse"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Viewing-RAG-Traces-Spans-Scores-Langfuse">Viewing RAG Traces, Spans, and Scores in Langfuse</a></h2>



<p>Once your RAG pipeline is running end-to-end, the real magic happens inside Langfuse. This is where retrieval steps, LLM calls, evaluation metrics, token usage, and pipeline-level metadata condense into a single, navigable trace. In this section, you will learn how to interpret that trace, span by span, so you can debug, understand, and improve RAG behavior with production-grade visibility.</p>



<h3 class="wp-block-heading">Understanding Hierarchical Spans (Retrieve → Prompt → Generate → Evaluate)</h3>



<p>Langfuse automatically groups each step of your <code data-enlighter-language="python" class="EnlighterJSRAW">rag_pipeline</code> into a nested hierarchy of spans. A typical RAG trace looks like this:</p>



<ul class="wp-block-list">
<li><code data-enlighter-language="python" class="EnlighterJSRAW">rag_pipeline</code> (root trace)
<ul class="wp-block-list">
<li><code data-enlighter-language="python" class="EnlighterJSRAW">retrieve_documents</code>
<ul class="wp-block-list">
<li><code data-enlighter-language="python" class="EnlighterJSRAW">embed_text</code></li>
</ul>
</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">llm_completion</code></li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">evaluate_rag_output</code>
<ul class="wp-block-list">
<li><code data-enlighter-language="python" class="EnlighterJSRAW">evaluate_relevancy</code></li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">evaluate_hallucination</code></li>
</ul>
</li>



<li>scoring nodes (<code data-enlighter-language="python" class="EnlighterJSRAW">overall_quality</code>, <code data-enlighter-language="python" class="EnlighterJSRAW">relevancy</code>, <code data-enlighter-language="python" class="EnlighterJSRAW">hallucination_risk</code>)</li>
</ul>
</li>
</ul>



<p>This hierarchy corresponds directly to your source code:</p>



<ul class="wp-block-list">
<li><code data-enlighter-language="python" class="EnlighterJSRAW">TracedRetriever.retrieve()</code>: retrieval span</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">TracedLLMClient.complete()</code>: generation span</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">evaluate_rag_output()</code>: evaluation span</li>
</ul>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://pyimagesearch.com/wp-content/uploads/2026/06/image-58.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="888" height="696" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-58.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54288"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-58.png?size=126x99&lossy=2&strip=1&webp=1 126w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-58-300x235.png?lossy=2&strip=1&webp=1 300w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-58.png?size=378x296&lossy=2&strip=1&webp=1 378w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-58.png?size=504x395&lossy=2&strip=1&webp=1 504w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-58.png?size=630x494&lossy=2&strip=1&webp=1 630w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-58-768x602.png?lossy=2&strip=1&webp=1 768w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-58.png?lossy=2&strip=1&webp=1 888w" sizes="(max-width: 888px) 100vw, 888px" /></a><figcaption class="wp-element-caption"><strong>Figure 1:</strong> Hierarchical spans created automatically by the RAG pipeline. Notice Retrieve → Generate → Evaluate structure.</figcaption></figure></div>


<h4 class="wp-block-heading">How to Navigate the Span Tree</h4>



<p>Each span reveals:</p>



<ul class="wp-block-list">
<li>execution time (critical for latency bottlenecks)</li>



<li>inputs and outputs captured via <code data-enlighter-language="python" class="EnlighterJSRAW">langfuse_context.update_current_observation()</code></li>



<li>whether nested operations (e.g., embedding calls) executed successfully</li>



<li>metadata from FAISS search, document previews, and query text</li>
</ul>



<p>Langfuse becomes a timeline and debugger for your RAG system.</p>



<h3 class="wp-block-heading">Inspecting Retrieval: Document Scores and Previews</h3>



<p>The retrieval stage is your first major insight point. The <code data-enlighter-language="python" class="EnlighterJSRAW">retrieve_documents</code> span logs:</p>



<ul class="wp-block-list">
<li>the <strong>query</strong> that was embedded</li>



<li>the <code data-enlighter-language="python" class="EnlighterJSRAW">top_k</code> used for <code data-enlighter-language="python" class="EnlighterJSRAW">FAISS</code> search</li>



<li><strong>distance scores</strong> returned</li>



<li><strong>converted relevancy scores</strong> (your <code data-enlighter-language="python" class="EnlighterJSRAW">1/(1+d)</code> heuristic)</li>



<li><strong>ranked documents</strong> with text previews</li>
</ul>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/06/image-59-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="535" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-59-1024x535.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54290"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-59-1024x535.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-59-1024x535.png?size=126x66&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-59-1024x535.png?size=252x132&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-59-1024x535.png?size=378x197&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-59-1024x535.png?size=504x263&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-59-1024x535.png?size=630x329&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 2:</strong> Retrieval span showing FAISS scores, document previews, and ranked results.</figcaption></figure></div>


<h4 class="wp-block-heading">What to Look For</h4>



<ul class="wp-block-list">
<li><strong>High distances and low scores:</strong> embedding mismatch or poor docs</li>



<li><strong>Same document repeatedly ranking #1:</strong> indexing error</li>



<li><strong>Empty results:</strong> index not built or FAISS dimension mismatch</li>
</ul>



<h4 class="wp-block-heading">Embedded Text Span</h4>



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">embed_text</code> span reveals the preview of text used for embeddings:</p>



<ul class="wp-block-list">
<li>inspect embeddings length</li>



<li>detect empty or malformed documents</li>



<li>verify embeddings model configuration</li>
</ul>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/06/image-60-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="231" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-60-1024x231.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54293"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-60-1024x231.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-60-1024x231.png?size=126x28&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-60-1024x231.png?size=252x57&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-60-1024x231.png?size=378x85&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-60-1024x231.png?size=504x114&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-60-1024x231.png?size=630x142&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 3:</strong> Embedding span showing text preview and output vector dimension.</figcaption></figure></div>


<h3 class="wp-block-heading">Inspecting Prompt Construction (Optional View)</h3>



<p>Prompt creation happens between retrieval and generation. Although you do not create a separate Langfuse span for this step, the <strong>constructed prompt appears inside the LLM span input</strong>.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/06/image-61-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="568" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-61-1024x568.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54295"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-61-1024x568.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-61-1024x568.png?size=126x70&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-61-1024x568.png?size=252x140&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-61-1024x568.png?size=378x210&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-61-1024x568.png?size=504x280&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-61-1024x568.png?size=630x349&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 4:</strong> Prompt passed to vLLM including context numbered <code>[1]</code>, <code>[2]</code>, and <code>[3]</code>.</figcaption></figure></div>


<p>What you verify here:</p>



<ul class="wp-block-list">
<li>context formatting</li>



<li>numbering</li>



<li>whitespace</li>



<li>hallucination-reducing systems instructions</li>
</ul>



<p>This becomes essential when debugging wrong answers.</p>



<h3 class="wp-block-heading">Token Usage and Generation Metadata</h3>



<p>Inside the <code data-enlighter-language="python" class="EnlighterJSRAW">llm_completion</code> span, Langfuse records:</p>



<ul class="wp-block-list">
<li><strong>input tokens</strong></li>



<li><strong>output tokens</strong></li>



<li><strong>total tokens</strong></li>



<li><strong>retry count</strong></li>



<li><strong>model name</strong></li>



<li><strong>latency breakdown</strong></li>



<li><strong>response content</strong></li>
</ul>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/06/image-62-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="555" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-62-1024x555.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54298"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-62-1024x555.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-62-1024x555.png?size=126x68&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-62-1024x555.png?size=252x137&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-62-1024x555.png?size=378x205&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-62-1024x555.png?size=504x273&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-62-1024x555.png?size=630x341&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 5:</strong> LLM span showing the request payload, response payload, token usage, retry-attempt metadata, and timing.</figcaption></figure></div>


<h4 class="wp-block-heading">What to Look For</h4>



<ul class="wp-block-list">
<li><strong>Unusually high input tokens:</strong> prompt too large</li>



<li><strong>High output tokens:</strong> model drifting or verbose</li>



<li><strong>Repeated retries:</strong> <code data-enlighter-language="python" class="EnlighterJSRAW">vLLM</code> throughput issue</li>



<li><strong>Very long latency:</strong> GPU under-provisioned or CPU fallback</li>
</ul>



<h3 class="wp-block-heading">Evaluation Scoring Nodes (Relevancy, Hallucination, and Overall Quality)</h3>



<p>Your evaluation functions (<code data-enlighter-language="python" class="EnlighterJSRAW">evaluate_relevancy</code>, <code data-enlighter-language="python" class="EnlighterJSRAW">evaluate_hallucination_risk</code>, <code data-enlighter-language="python" class="EnlighterJSRAW">evaluate_rag_output</code>) create <strong>3 scoring nodes</strong> inside Langfuse:</p>



<ul class="wp-block-list">
<li><code data-enlighter-language="python" class="EnlighterJSRAW">relevancy</code></li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">hallucination_risk</code></li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">overall_quality</code></li>
</ul>



<p>These appear alongside the evaluation span.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/06/image-63-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="369" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-63-1024x369.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54300"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-63-1024x369.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-63-1024x369.png?size=126x45&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-63-1024x369.png?size=252x91&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-63-1024x369.png?size=378x136&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-63-1024x369.png?size=504x182&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-63-1024x369.png?size=630x227&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 6:</strong> Langfuse scoring nodes: relevancy, hallucination risk, and overall quality.</figcaption></figure></div>


<h4 class="wp-block-heading">How to Interpret Them</h4>



<ul class="wp-block-list">
<li><strong>High relevancy and low hallucination</strong><strong> risk</strong><strong>:</strong> high <code data-enlighter-language="python" class="EnlighterJSRAW">overall_quality</code></li>



<li><strong>Low relevancy and high hallucination</strong><strong> risk</strong><strong>:</strong> RAG failure</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">passed=True</code> means the response met the <code data-enlighter-language="python" class="EnlighterJSRAW">min_quality_score</code> threshold in <code data-enlighter-language="python" class="EnlighterJSRAW">config.yaml</code></li>
</ul>



<h4 class="wp-block-heading">Debugging Failures</h4>



<ul class="wp-block-list">
<li><strong>Relevancy low:</strong> retrieval needs improvement</li>



<li><strong>Hallucination high:</strong> prompt needs grounding</li>



<li><strong>Both low:</strong> LLM ignoring context, bad retrieval, or noisy docs</li>
</ul>



<h3 class="wp-block-heading">Visual Timeline and Performance Profiling</h3>



<p>The timeline view shows exact timings:</p>



<ul class="wp-block-list">
<li>embedding</li>



<li>retrieval</li>



<li>prompt construction</li>



<li>LLM generation</li>



<li>evaluation</li>
</ul>



<p>This allows profiling end-to-end latency.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/06/image-64-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="182" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-64-1024x182.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54302"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-64-1024x182.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-64-1024x182.png?size=126x22&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-64-1024x182.png?size=252x45&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-64-1024x182.png?size=378x67&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-64-1024x182.png?size=504x90&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-64-1024x182.png?size=630x112&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 7:</strong> Timeline visualization showing latency distribution across RAG stages, including embedding, retrieval, LLM generation, and evaluation.</figcaption></figure></div>


<h3 class="wp-block-heading">How Langfuse Helps Production Debugging</h3>



<p>Langfuse tracing helps answer real production questions:</p>



<h4 class="wp-block-heading">“Why was this answer wrong?”</h4>



<p>Open the evaluation spans, review the hallucination score, inspect the prompt, and then inspect the retrieved documents.</p>



<h4 class="wp-block-heading">“Which part is slowing down?”</h4>



<p>Open the timeline and locate the bottleneck, which is often embeddings or the LLM.</p>



<h4 class="wp-block-heading">“Did the LLM actually use the retrieved documents?”</h4>



<p>Compare:</p>



<ul class="wp-block-list">
<li>retrieval previews</li>



<li>answer keywords</li>



<li>relevancy score</li>
</ul>



<h4 class="wp-block-heading">“Why did this query fail?”</h4>



<p>The trace will show:</p>



<ul class="wp-block-list">
<li>empty index</li>



<li>retries</li>



<li>exceptions</li>



<li>malformed inputs</li>



<li>missing environment variables</li>
</ul>



<p>In production, this becomes indispensable.</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<div id="pitch" style="padding: 40px; width: 100%; background-color: #F4F6FA;">
	<h3>What's next? We recommend <a target="_blank" href="https://pyimagesearch.com/pyimagesearch-university/?utm_source=blogPost&utm_medium=bottomBanner&utm_campaign=What%27s%20next%3F%20I%20recommend">PyImageSearch University</a>.</h3>

	<script src="https://fast.wistia.com/embed/medias/kno0cmko2z.jsonp" async></script><script src="https://fast.wistia.com/assets/external/E-v1.js" async></script><div class="wistia_responsive_padding" style="padding:56.25% 0 0 0;position:relative;"><div class="wistia_responsive_wrapper" style="height:100%;left:0;position:absolute;top:0;width:100%;"><div class="wistia_embed wistia_async_kno0cmko2z videoFoam=true" style="height:100%;position:relative;width:100%"><div class="wistia_swatch" style="height:100%;left:0;opacity:0;overflow:hidden;position:absolute;top:0;transition:opacity 200ms;width:100%;"><img decoding="async" src="https://fast.wistia.com/embed/medias/kno0cmko2z/swatch" style="filter:blur(5px);height:100%;object-fit:contain;width:100%;" alt="" aria-hidden="true" onload="this.parentNode.style.opacity=1;" /></div></div></div></div>

	<div style="margin-top: 32px; margin-bottom: 32px; ">
		<strong>Course information:</strong><br/>
		120+ total classes • 115+ hours hours of on-demand code walkthrough videos • Last updated: August 2026<br/>
		<span style="color: #169FE6;">★★★★★</span> 4.84 (128 Ratings) • 16,000+ Students Enrolled
	</div>

	<p><strong>I strongly believe that if you had the right teacher you could <em>master</em> computer vision and deep learning.</strong></p>

	<p>Do you think learning computer vision and deep learning has to be time-consuming, overwhelming, and complicated? Or has to involve complex mathematics and equations? Or requires a degree in computer science?</p>

	<p>That’s <em>not</em> the case.</p>

	<p>All you need to master computer vision and deep learning is for someone to explain things to you in <em>simple, intuitive</em> terms. <em>And that’s exactly what I do</em>. My mission is to change education and how complex Artificial Intelligence topics are taught.</p>

	<p>If you're serious about learning computer vision, your next stop should be PyImageSearch University, the most comprehensive computer vision, deep learning, and OpenCV course online today. Here you’ll learn how to <em>successfully</em> and <em>confidently</em> apply computer vision to your work, research, and projects. Join me in computer vision mastery.</p>

	<p><strong>Inside PyImageSearch University you'll find:</strong></p>

	<ul style="margin-left: 0px;">
		<li style="list-style: none;">&check; <strong>120+ courses</strong> on essential computer vision, deep learning, and OpenCV topics</li>
		<li style="list-style: none;">&check; <strong>94+ Certificates</strong> of Completion</li>
		<li style="list-style: none;">&check; <strong>115+ hours hours</strong> of on-demand video</li>
		<li style="list-style: none;">&check; <strong>Brand new courses released <em>regularly</em></strong>, ensuring you can keep up with state-of-the-art techniques</li>
		<li style="list-style: none;">&check; <strong>Pre-configured Jupyter Notebooks in Google Colab</strong></li>
		<li style="list-style: none;">&check; Run all code examples in your web browser — works on Windows, macOS, and Linux (no dev environment configuration required!)</li>
		<li style="list-style: none;">&check; Access to <strong>centralized code repos for <em>all</em> 540+ tutorials</strong> on PyImageSearch</li>
		<li style="list-style: none;">&check; <strong> Easy one-click downloads</strong> for code, datasets, pre-trained models, etc.</li>
		<li style="list-style: none;">&check; <strong>Access</strong> on mobile, laptop, desktop, etc.</li>
	</ul>

	<p style="text-align: center;">
		<a target="_blank" class="button link" href="https://pyimagesearch.com/pyimagesearch-university/?utm_source=blogPost&utm_medium=bottomBanner&utm_campaign=What%27s%20next%3F%20I%20recommend" style="background-color: #6DC713; border-bottom: none;">Click here to join PyImageSearch University</a>
	</p>
</div>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Summary"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Summary">Summary</a></h2>



<p>In this lesson, you built a fully instrumented, production-grade RAG pipeline and learned how observability transforms retrieval-augmented systems from “black boxes” into transparent, debuggable, measurable workflows. You started by setting up the core infrastructure (self-hosted Langfuse, vLLM for fast local inference, and FAISS and SentenceTransformers for efficient retrieval) and then wired all these components together using a clean, traceable architecture.</p>



<p>With tracing enabled end-to-end, every stage of your RAG pipeline became inspectable: document embedding, FAISS indexing, retrieval scoring, prompt construction, LLM generation, and quality evaluation. You saw how Langfuse automatically visualizes these steps as nested spans, how it captures token usage and metadata for LLM calls, and how your evaluation functions produce relevancy, hallucination risk, and overall-quality scores directly inside the trace.</p>



<p>By running the pipeline and examining the traces, you learned how to debug retrieval quality, diagnose prompt-related issues, inspect model behavior, and identify performance bottlenecks using Langfuse’s hierarchical tree view and timeline profiler. The final result is an observability-first RAG stack: fully local, fast, and transparent, designed exactly the way production systems must operate.</p>



<p>This foundation prepares you for upcoming lessons, where we extend the same tracing principles to <strong>multi-step agents</strong>, adding reasoning chains, intent analysis, and multi-span agent workflows on top of the RAG engine you constructed here.</p>



<h3 class="wp-block-heading">Citation Information</h3>



<p><strong>Singh, V</strong><strong>. </strong>“RAG Observability with Langfuse, vLLM, and FAISS,” <em>PyImageSearch</em>, S. Huot, A. Sharma, and P. Thakur, eds., 2026, <a href="https://pyimg.co/g20yk" target="_blank" rel="noreferrer noopener">https://pyimg.co/g20yk</a> </p>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="classic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="RAG Observability with Langfuse, vLLM, and FAISS" data-enlighter-group="65">@incollection{Singh_2026_rag-observability-langfuse-vllm-faiss,
  author = {Vikram Singh},
  title = {{RAG Observability with Langfuse, vLLM, and FAISS}},
  booktitle = {PyImageSearch},
  editor = {Susan Huot and Aditya Sharma and Piyush Thakur},
  year = {2026},
  url = {https://pyimg.co/g20yk},
}
</pre>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p><strong>To download the source code to this post (and be notified when future tutorials are published here on PyImageSearch), </strong><em><strong>simply enter your email address in the form below!</strong></em></p>



<div id="download-the-code" class="post-cta-wrap">
<div class="gpd-post-cta">
	<div class="gpd-post-cta-content">
		

			<div class="gpd-post-cta-top">
				<div class="gpd-post-cta-top-image"><img decoding="async" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2020/01/cta-source-guide-1.png?lossy=2&strip=1&webp=1" alt="" srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2020/01/cta-source-guide-1.png?lossy=2&strip=1&webp=1 410w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2020/01/cta-source-guide-1.png?size=126x174&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2020/01/cta-source-guide-1.png?size=252x348&lossy=2&strip=1&webp=1 252w" sizes="(max-width: 410px) 100vw, 410px" /></div>
				
				<div class="gpd-post-cta-top-title"><h4>Download the Source Code and FREE 17-page Resource Guide</h4></div>
				<div class="gpd-post-cta-top-desc"><p>Enter your email address below to get a .zip of the code and a <strong>FREE 17-page Resource Guide on Computer Vision, OpenCV, and Deep Learning.</strong> Inside you'll find my hand-picked tutorials, books, courses, and libraries to help you master CV and DL!</p></div>


			</div>

			<div class="gpd-post-cta-bottom">
				<form id="footer-cta-code" class="footer-cta" action="https://www.getdrip.com/forms/4130035/submissions" method="post" target="blank" data-drip-embedded-form="4130035">
					<input name="fields[email]" type="email" value="" placeholder="Your email address" class="form-control" />

					<button type="submit">Download the code!</button>

					<div style="display: none;" aria-hidden="true"><label for="website">Website</label><br /><input type="text" id="website" name="website" tabindex="-1" autocomplete="false" value="" /></div>
				</form>
			</div>


		
	</div>

</div>
</div>
<p>The post <a rel="nofollow" href="https://pyimagesearch.com/2026/06/15/rag-observability-with-langfuse-vllm-and-faiss/">RAG Observability with Langfuse, vLLM, and FAISS</a> appeared first on <a rel="nofollow" href="https://pyimagesearch.com">PyImageSearch</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Run an Apache Airflow DAG with Docker Compose and PostgreSQL</title>
		<link>https://pyimagesearch.com/2026/06/08/run-an-apache-airflow-dag-with-docker-compose-and-postgresql/</link>
		
		<dc:creator><![CDATA[Vikram Singh]]></dc:creator>
		<pubDate>Mon, 08 Jun 2026 12:45:00 +0000</pubDate>
				<category><![CDATA[Apache Airflow]]></category>
		<category><![CDATA[Docker]]></category>
		<category><![CDATA[MLOps]]></category>
		<category><![CDATA[PostgreSQL]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[airflow dag]]></category>
		<category><![CDATA[airflow scheduler]]></category>
		<category><![CDATA[airflow webserver]]></category>
		<category><![CDATA[apache airflow]]></category>
		<category><![CDATA[containerization]]></category>
		<category><![CDATA[data engineering]]></category>
		<category><![CDATA[data pipelines]]></category>
		<category><![CDATA[docker]]></category>
		<category><![CDATA[docker compose]]></category>
		<category><![CDATA[docker volumes]]></category>
		<category><![CDATA[document ingestion]]></category>
		<category><![CDATA[fastapi]]></category>
		<category><![CDATA[mlops]]></category>
		<category><![CDATA[postgresql]]></category>
		<category><![CDATA[pypdf]]></category>
		<category><![CDATA[rag]]></category>
		<category><![CDATA[retrieval augmented generation]]></category>
		<category><![CDATA[sqlalchemy]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[workflow orchestration]]></category>
		<guid isPermaLink="false">https://pyimagesearch.com/?p=54094</guid>

					<description><![CDATA[<p>Table of Contents Run an Apache Airflow DAG with Docker Compose and PostgreSQL Project Structure PDF Parsing and Text Chunking Logic for Airflow DAG Docker Orchestration and Runtime for Airflow and FastAPI Running the Apache Airflow and FastAPI Document Ingestion&#8230;</p>
<p>The post <a rel="nofollow" href="https://pyimagesearch.com/2026/06/08/run-an-apache-airflow-dag-with-docker-compose-and-postgresql/">Run an Apache Airflow DAG with Docker Compose and PostgreSQL</a> appeared first on <a rel="nofollow" href="https://pyimagesearch.com">PyImageSearch</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<hr class="wp-block-separator has-alpha-channel-opacity" id="TOC"/>


<div class="yoast-breadcrumbs"><span><span><a href="https://pyimagesearch.com/">Home</a></span></div>


<div class="toc">
<hr class="TOC"/>
<p class="has-large-font-size"><strong>Table of Contents</strong></p>
<ul>
    <li id="TOC-h1-Run-Apache-Airflow-DAG-Docker-Compose-PostgreSQL"><a rel="noopener" target="_blank" href="#h1-Run-Apache-Airflow-DAG-Docker-Compose-PostgreSQL">Run an Apache Airflow DAG with Docker Compose and PostgreSQL</a></li>

    <li id="TOC-h2-Project-Structure"><a rel="noopener" target="_blank" href="#h2-Project-Structure">Project Structure</a></li>

    <li id="TOC-h2-PDF-Parsing-Text-Chunking-Logic-Airflow-DAG"><a rel="noopener" target="_blank" href="#h2-PDF-Parsing-Text-Chunking-Logic-Airflow-DAG">PDF Parsing and Text Chunking Logic for Airflow DAG</a></li>

    <li id="TOC-h2-Docker-Orchestration-Runtime-Airflow-FastAPI"><a rel="noopener" target="_blank" href="#h2-Docker-Orchestration-Runtime-Airflow-FastAPI">Docker Orchestration and Runtime for Airflow and FastAPI</a></li>

    <li id="TOC-h2-Running-Apache-Airflow-FastAPI-Document-Ingestion-Pipeline"><a rel="noopener" target="_blank" href="#h2-Running-Apache-Airflow-FastAPI-Document-Ingestion-Pipeline">Running the Apache Airflow and FastAPI Document Ingestion Pipeline</a></li>

    <li id="TOC-h2-Triggering-Monitoring-Apache-Airflow-DAGs"><a rel="noopener" target="_blank" href="#h2-Triggering-Monitoring-Apache-Airflow-DAGs">Triggering and Monitoring Apache Airflow DAGs</a></li>

    <li id="TOC-h2-Verifying-Document-Chunk-Data-PostgreSQL"><a rel="noopener" target="_blank" href="#h2-Verifying-Document-Chunk-Data-PostgreSQL">Verifying Document and Chunk Data in PostgreSQL</a></li>

    <li id="TOC-h2-Error-Handling-Failure-Recovery-Airflow-Pipeline"><a rel="noopener" target="_blank" href="#h2-Error-Handling-Failure-Recovery-Airflow-Pipeline">Error Handling and Failure Recovery in Airflow Pipeline</a></li>

    <li id="TOC-h2-Design-Principles-Idempotency-Observability-Reproducibility-Airflow-Pipelines"><a rel="noopener" target="_blank" href="#h2-Design-Principles-Idempotency-Observability-Reproducibility-Airflow-Pipelines">Design Principles: Idempotency, Observability, and Reproducibility in Airflow Pipelines</a></li>

    <li id="TOC-h2-Limits-Apache-Airflow-Machine-Learning-Workloads"><a rel="noopener" target="_blank" href="#h2-Limits-Apache-Airflow-Machine-Learning-Workloads">Limits of Apache Airflow for Machine Learning Workloads</a></li>

    <li id="TOC-h2-Summary"><a rel="noopener" target="_blank" href="#h2-Summary">Summary</a></li>
</ul>
</div>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h1-Run-Apache-Airflow-DAG-Docker-Compose-PostgreSQL"/>



<h2 class="wp-block-heading"><a href="#TOC-h1-Run-Apache-Airflow-DAG-Docker-Compose-PostgreSQL">Run an Apache Airflow DAG with Docker Compose and PostgreSQL</a></h2>



<p>In Lesson 1, we designed a production-grade document ingestion pipeline using FastAPI, Apache Airflow, and PostgreSQL. We defined the data model, built an idempotent 5-task DAG, structured our project for separation of concerns, and established the architectural principles that make the system reliable.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://pyimagesearch.com/wp-content/uploads/2026/06/run-apache-airflow-dag-docker-compose-postgresql-featured.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="940" height="780" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/run-apache-airflow-dag-docker-compose-postgresql-featured.png?lossy=2&strip=1&webp=1" alt="run-apache-airflow-dag-docker-compose-postgresql-featured.png" class="wp-image-54217"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/run-apache-airflow-dag-docker-compose-postgresql-featured.png?size=126x105&lossy=2&strip=1&webp=1 126w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/run-apache-airflow-dag-docker-compose-postgresql-featured-300x249.png?lossy=2&strip=1&webp=1 300w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/run-apache-airflow-dag-docker-compose-postgresql-featured.png?size=378x314&lossy=2&strip=1&webp=1 378w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/run-apache-airflow-dag-docker-compose-postgresql-featured.png?size=504x418&lossy=2&strip=1&webp=1 504w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/run-apache-airflow-dag-docker-compose-postgresql-featured.png?size=630x523&lossy=2&strip=1&webp=1 630w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/run-apache-airflow-dag-docker-compose-postgresql-featured-768x637.png?lossy=2&strip=1&webp=1 768w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/run-apache-airflow-dag-docker-compose-postgresql-featured.png?lossy=2&strip=1&webp=1 940w" sizes="(max-width: 940px) 100vw, 940px" /></a></figure></div>


<p>Now, in Lesson 2, we bring that architecture to life.</p>



<p>In this lesson, you will operationalize the ingestion pipeline by running it inside Docker, uploading real documents, triggering DAG runs, inspecting logs, and validating results directly in PostgreSQL. You will also explore failure scenarios, observability patterns, and the practical limits of using Airflow for ML-style workloads.</p>



<p>By the end of this lesson, you will not only understand how the pipeline works, but how to run it, debug it, monitor it, and reason about its behavior in production.</p>



<p>This lesson is the last in a 2-part series on <strong>building production-grade document ingestion pipelines for RAG systems</strong>:</p>



<ol class="wp-block-list">
<li><em><strong><a href="https://pyimg.co/8b2ey" target="_blank" rel="noreferrer noopener">Apache Airflow Document Ingestion Pipeline for RAG Systems</a></strong></em></li>



<li><em><strong><a href="https://pyimg.co/kxc7e" target="_blank" rel="noreferrer noopener">Run an Apache Airflow DAG with Docker Compose and PostgreSQL</a></strong></em><em><strong>  (this tutorial)</strong></em></li>
</ol>



<p><strong>To learn how to deploy, execute, monitor, and validate a production-ready ingestion pipeline with Apache Airflow, </strong><em><strong>just keep reading.</strong></em></p>



<div id="pyi-source-code-block" class="source-code-wrap"><div class="gpd-source-code">
    <div class="gpd-source-code-content">
        <img decoding="async" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2020/01/source-code-icon.png?lossy=2&strip=1&webp=1" alt="">
        <h4>Looking for the source code to this post?</h4>
                    <a href="#download-the-code" class="pyis-cta-modal-open-modal">Jump Right To The Downloads Section <svg class="svg-icon arrow-right" width="12" height="12" aria-hidden="true" role="img" focusable="false" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M6.8125 0.1875C6.875 0.125 6.96875 0.09375 7.09375 0.09375C7.1875 0.09375 7.28125 0.125 7.34375 0.1875L13.875 6.75C13.9375 6.8125 14 6.90625 14 7C14 7.125 13.9375 7.1875 13.875 7.25L7.34375 13.8125C7.28125 13.875 7.1875 13.9062 7.09375 13.9062C6.96875 13.9062 6.875 13.875 6.8125 13.8125L6.1875 13.1875C6.125 13.125 6.09375 13.0625 6.09375 12.9375C6.09375 12.8438 6.125 12.75 6.1875 12.6562L11.0312 7.8125H0.375C0.25 7.8125 0.15625 7.78125 0.09375 7.71875C0.03125 7.65625 0 7.5625 0 7.4375V6.5625C0 6.46875 0.03125 6.375 0.09375 6.3125C0.15625 6.25 0.25 6.1875 0.375 6.1875H11.0312L6.1875 1.34375C6.125 1.28125 6.09375 1.1875 6.09375 1.0625C6.09375 0.96875 6.125 0.875 6.1875 0.8125L6.8125 0.1875Z" fill="#169FE6"></path></svg></a>
            </div>
</div>
</div>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p>Would you like immediate access to 3,457 images curated and labeled with hand gestures to train, explore, and experiment with &#8230; for free? Head over to <a href="https://universe.roboflow.com/isl/az-6mqow?ref=pyimagesearch" target="_blank" rel="noreferrer noopener">Roboflow</a> and get a free account to grab these hand gesture images. </p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<!-- wp:paragraph -->
<h3>Need Help Configuring Your Development Environment?</h3>
<!-- /wp:paragraph -->

<!-- wp:image {"align":"center","id":18137,"sizeSlug":"large","linkDestination":"custom"} -->
<figure class="wp-block-image aligncenter size-large"><a href="https://pyimagesearch.com/pyimagesearch-university/" target="_blank" rel="noreferrer noopener"><img decoding="async" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2021/01/pyimagesearch_plus_jupyter.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-18137" srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2021/01/pyimagesearch_plus_jupyter.png?lossy=2&strip=1&webp=1 500w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2021/01/pyimagesearch_plus_jupyter.png?size=126x84&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2021/01/pyimagesearch_plus_jupyter.png?size=252x168&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2021/01/pyimagesearch_plus_jupyter.png?size=378x253&lossy=2&strip=1&webp=1 378w" sizes="(max-width: 500px) 100vw, 500px" /></a><figcaption>Having trouble configuring your development environment? Want access to pre-configured Jupyter Notebooks running on Google Colab? Be sure to join <a href="https://pyimagesearch.com/pyimagesearch-university/" target="_blank" rel="noreferrer noopener" aria-label=" (opens in a new tab)">PyImageSearch University</a> — you will be up and running with this tutorial in a matter of minutes. </figcaption></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>All that said, are you:</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li>Short on time?</li><li>Learning on your employer’s administratively locked system?</li><li>Wanting to skip the hassle of fighting with the command line, package managers, and virtual environments?</li><li><strong>Ready to run the code immediately on your Windows, macOS, or Linux system?</strong></li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>Then join <a href="https://pyimagesearch.com/pyimagesearch-university/" target="_blank">PyImageSearch University</a> today!</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><strong>Gain access to Jupyter Notebooks for this tutorial and other PyImageSearch guides pre-configured to run on Google Colab’s ecosystem right in your web browser!</strong> No installation required.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>And best of all, these Jupyter Notebooks will run on Windows, macOS, and Linux!</p>
<!-- /wp:paragraph -->



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Project-Structure"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Project-Structure">Project Structure</a></h2>



<p>In Lesson 1, we focused on architectural boundaries. Now we look at the same structure through a runtime lens: what runs where, and what each container actually executes.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Run an Apache Airflow DAG with Docker Compose and PostgreSQL" data-enlighter-group="2">├── airflow_project/        # Orchestration + runtime layer
│   ├── dags/              # Airflow DAG definitions
│   │   └── ingest_documents_dag.py  # Main DAG: PDF → chunks pipeline
│   │
│   ├── ingestion_service/ # FastAPI REST API for file uploads
│   │   ├── __init__.py
│   │   ├── main.py      # Upload endpoint with deduplication
│   │   └── requirements.txt  # FastAPI + Uvicorn dependencies
│   │
│   ├── docker-compose.yml  # Defines Postgres, Airflow, API services
│   ├── Dockerfile               # Airflow container image
│   ├── Dockerfile.service   # FastAPI service container image
│   └── init-db.sh              # PostgreSQL database initialization script
│
├── shared/      # Reusable business logic (no Airflow deps)
│   ├── data_models/ # Pydantic schemas (API validation layer)
│   │   ├── __init__.py
│   │   └── models.py  # Document, Chunk, PipelineRun schemas
│   │
│   ├── parsing/                # Document processing logic
│   │   ├── __init__.py
│   │   ├── pdf_parser.py # PyPDF text extraction (page-level)
│   │   ├── chunker.py    # Sliding window text chunking
│   │   └── deduplication.py # Content hash comparison utilities
│   │
│   ├── storage/            # Database interaction layer
│   │   ├── __init__.py
│   │   ├── database.py     # SQLAlchemy session management
│   │   └── models.py       # ORM models (tables definition)
│   │
│   ├── utils/               # Low-level helpers
│   │   ├── __init__.py
│   │   ├── hashing.py      # SHA-256 file &amp; text hashing
│   │   └── logging.py      # Structured logging utilities
│   │
│   ├── __init__.py
│   └── requirements.txt  # Shared dependencies (SQLAlchemy, PyPDF, etc.)
</pre>



<p>When you run:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Run an Apache Airflow DAG with Docker Compose and PostgreSQL" data-enlighter-group="3">docker compose up --build
</pre>



<p>This structure turns into 5 running services.</p>



<h3 class="wp-block-heading">What Runs Inside Each Container</h3>



<p><strong>Airflow Webserver </strong><strong>and</strong><strong> Scheduler</strong></p>



<ul class="wp-block-list">
<li>Load DAGs from <code data-enlighter-language="python" class="EnlighterJSRAW">dags/</code></li>



<li>Import parsing and storage logic from <code data-enlighter-language="python" class="EnlighterJSRAW">shared/</code></li>



<li>Connect to PostgreSQL</li>



<li>Read uploaded files from the shared volume</li>
</ul>



<p><strong>Ingestion Service</strong></p>



<ul class="wp-block-list">
<li>Runs <code data-enlighter-language="python" class="EnlighterJSRAW">main.py</code></li>



<li>Accepts PDF uploads</li>



<li>Writes files into <code data-enlighter-language="python" class="EnlighterJSRAW">/tmp/ml_orchestration/uploads</code></li>



<li>Inserts rows into PostgreSQL</li>
</ul>



<p><strong>PostgreSQL</strong></p>



<ul class="wp-block-list">
<li>Stores Airflow metadata</li>



<li>Stores <code data-enlighter-language="python" class="EnlighterJSRAW">documents</code>, <code data-enlighter-language="python" class="EnlighterJSRAW">chunks</code>, and <code data-enlighter-language="python" class="EnlighterJSRAW">pipeline_runs</code></li>
</ul>



<h3 class="wp-block-heading">Why shared/ Is Mounted Everywhere</h3>



<p>Both the Airflow containers and the ingestion service mount the <code data-enlighter-language="python" class="EnlighterJSRAW">shared/</code> directory.</p>



<p>This guarantees:</p>



<ul class="wp-block-list">
<li>The API and DAG use identical parsing logic</li>



<li>Hashing behaves consistently</li>



<li>Database models stay synchronized</li>
</ul>



<p>No duplicated code.</p>



<p>No version drift.</p>



<h3 class="wp-block-heading">The Shared Upload Volume</h3>



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">/tmp/ml_orchestration/uploads</code> volume is mounted into both:</p>



<ul class="wp-block-list">
<li>ingestion-service</li>



<li>airflow containers</li>
</ul>



<p>This is critical.</p>



<p>The API writes files.</p>



<p>Airflow reads the same files directly from disk.</p>



<p>There is no file transfer, no API polling, and no network hop.</p>



<p>This design eliminates an entire class of distributed file consistency problems.</p>



<h3 class="wp-block-heading">Why This Matters in Practice</h3>



<p>At runtime:</p>



<ul class="wp-block-list">
<li>The API handles fast, user-facing work.</li>



<li>Airflow handles scheduled, asynchronous work.</li>



<li>PostgreSQL persists state.</li>



<li>The shared module ensures consistency.</li>



<li>Docker isolates everything into reproducible containers.</li>
</ul>



<p>Lesson 1 taught you how the system is designed.</p>



<p>Lesson 2 shows you how that design behaves when executed.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-PDF-Parsing-Text-Chunking-Logic-Airflow-DAG"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-PDF-Parsing-Text-Chunking-Logic-Airflow-DAG">PDF Parsing and Text Chunking Logic for Airflow DAG</a></h2>



<p>The DAG calls functions like <code data-enlighter-language="python" class="EnlighterJSRAW">parse_pdf()</code> and <code data-enlighter-language="python" class="EnlighterJSRAW">chunk_text()</code>, but these are not defined in the DAG file. They live in <code data-enlighter-language="python" class="EnlighterJSRAW">shared/parsing/</code> where both Airflow and future Argo Workflows can use them. <strong>Figure 1</strong> shows the chunking pipeline.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://pyimagesearch.com/wp-content/uploads/2026/06/image-34.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="624" height="340" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-34.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54140"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-34.png?size=126x69&lossy=2&strip=1&webp=1 126w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-34-300x163.png?lossy=2&strip=1&webp=1 300w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-34.png?size=378x206&lossy=2&strip=1&webp=1 378w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-34.png?size=504x275&lossy=2&strip=1&webp=1 504w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-34.png?lossy=2&strip=1&webp=1 624w" sizes="(max-width: 624px) 100vw, 624px" /></a><figcaption class="wp-element-caption"><strong>Figure 1:</strong> The text chunking pipeline showing PDF extraction, page concatenation, chunking with overlap, and hash-based deduplication.</figcaption></figure></div>


<p>Here is the PDF parsing code from <code data-enlighter-language="python" class="EnlighterJSRAW">shared/parsing/pdf_parser.py</code>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Run an Apache Airflow DAG with Docker Compose and PostgreSQL" data-enlighter-group="4">def parse_pdf(file_path: str) -> List[dict]:
    """
    Parse a PDF file and extract text page by page.
    
    Args:
        file_path: Path to PDF file
        
    Returns:
        List of dictionaries with page_number and text
    """
    logger.info(f"Parsing PDF: {file_path}")
    
    if not os.path.exists(file_path):
        raise FileNotFoundError(f"PDF file not found: {file_path}")
    
    try:
        reader = PdfReader(file_path)
        pages = []
        
        for i, page in enumerate(reader.pages):
            text = page.extract_text()
            metadata = reader.metadata or {}
            
            pages.append({
                'page_number': i + 1,
                'text': text,
                'metadata': {
                    'title': metadata.get('/Title', ''),
                    'author': metadata.get('/Author', ''),
                    'total_pages': len(reader.pages)
                }
            })
        
        logger.info(f"Extracted {len(pages)} pages from PDF")
        return pages
        
    except Exception as e:
        logger.error(f"Failed to parse PDF {file_path}: {str(e)}")
        raise</pre>



<p>This function uses PyPDF&#8217;s <code data-enlighter-language="python" class="EnlighterJSRAW">PdfReader</code> to load the PDF. It iterates over each page, calls <code data-enlighter-language="python" class="EnlighterJSRAW">extract_text()</code>, and bundles the text with page metadata. The result is a list of dictionaries, one per page.</p>



<p>Notice we extract metadata like title and author if available. This can be useful for citations or provenance tracking later. We also include the total page count so downstream tasks know if they have partial data.</p>



<p>The error handling re-raises exceptions after logging. This ensures failures propagate to Airflow where they can trigger retries or mark the document as failed.</p>



<p>Here is the chunking code from <code data-enlighter-language="python" class="EnlighterJSRAW">shared/parsing/chunker.py</code>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Run an Apache Airflow DAG with Docker Compose and PostgreSQL" data-enlighter-group="6">def chunk_text(
    text: str,
    chunk_size: int = 512,
    overlap: int = 50,
    min_chunk_size: int = 100
) -> List[str]:
    """
    Split text into overlapping chunks.
    
    Args:
        text: Input text to chunk
        chunk_size: Target size in words (approximate token proxy)
        overlap: Number of overlapping words between chunks
        min_chunk_size: Minimum chunk size in words (discard smaller)
        
    Returns:
        List of text chunks
    """
    logger.info(f"Chunking text: {len(text)} chars, chunk_size={chunk_size}, overlap={overlap}")
    
    words = text.split()  # Simple whitespace splitting (production would use proper tokenizers)
    chunks = []
    start = 0
    
    while start &lt; len(words):
        end = min(start + chunk_size, len(words))
        chunk_words = words[start:end]
        chunk = ' '.join(chunk_words)
        
        if len(chunk_words) >= min_chunk_size:
            chunks.append(chunk)
        
        start += (chunk_size - overlap)
    
    logger.info(f"Created {len(chunks)} chunks")
    return chunks</pre>



<p>This function uses a sliding window approach — imagine sliding a frame across a long document, capturing a portion of text, then sliding forward while keeping some overlap with the previous frame.</p>



<p>We split the text into words using whitespace (production systems would use proper tokenizers like tiktoken, but whitespace splitting works as a reasonable approximation). We extract a window of <code data-enlighter-language="python" class="EnlighterJSRAW">chunk_size</code> words, join them back into a string, and add to the chunks list. Then we slide the window forward by <code data-enlighter-language="python" class="EnlighterJSRAW">chunk_size - overlap</code> words to create the next chunk.</p>



<p>The overlap is critical for retrieval quality. If an important sentence or concept spans a chunk boundary, the overlap ensures it appears in full within at least one chunk. Without overlap, you might split a key phrase across two chunks and miss it during semantic search.</p>



<p>We also have a <code data-enlighter-language="python" class="EnlighterJSRAW">min_chunk_size</code> parameter. Very small chunks (just a few words) usually lack enough context to be semantically meaningful, so we discard them.</p>



<p>Here is the content hashing code from <code data-enlighter-language="python" class="EnlighterJSRAW">shared/utils/hashing.py</code>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Run an Apache Airflow DAG with Docker Compose and PostgreSQL" data-enlighter-group="8">def hash_content(content: str) -> str:
    """
    Compute SHA-256 hash of text content.
    
    Args:
        content: Text to hash
        
    Returns:
        Hexadecimal hash string
    """
    return hashlib.sha256(content.encode('utf-8')).hexdigest()


def hash_file(file_path: str) -> str:
    """
    Compute SHA-256 hash of file content.
    
    Args:
        file_path: Path to file
        
    Returns:
        Hexadecimal hash string
    """
    hash_obj = hashlib.sha256()
    
    with open(file_path, 'rb') as f:
        for chunk in iter(lambda: f.read(4096), b''):
            hash_obj.update(chunk)
    
    return hash_obj.hexdigest()</pre>



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">hash_content()</code> function encodes text as UTF-8 bytes and computes its SHA-256 hash. The <code data-enlighter-language="python" class="EnlighterJSRAW">hash_file()</code> function reads a file in 4KB chunks (to handle large files without loading them entirely into memory) and computes the cumulative hash.</p>



<p>These hashes are what enable deduplication. Two identical chunks will always produce the same hash, so we can check for existence in the database before inserting.</p>



<p><strong>Why Sharing This Logic Matters</strong></p>



<p>By putting parsing and chunking in <code data-enlighter-language="python" class="EnlighterJSRAW">shared/</code>, we ensure consistency across different orchestration systems. When we introduce Argo Workflows in a future lesson, it will use the exact same <code data-enlighter-language="python" class="EnlighterJSRAW">parse_pdf()</code> and <code data-enlighter-language="python" class="EnlighterJSRAW">chunk_text()</code> functions. This means documents processed by Airflow and documents processed by Argo will have identical chunk boundaries, identical hashes, and identical behavior.</p>



<p>This is critical for systems where you might migrate from one orchestrator to another or run hybrid setups.</p>



<p>Now let&#8217;s see how this all runs in Docker.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Docker-Orchestration-Runtime-Airflow-FastAPI"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Docker-Orchestration-Runtime-Airflow-FastAPI">Docker Orchestration and Runtime for Airflow and FastAPI</a></h2>



<p>We have examined the code. Now let&#8217;s see how Docker brings it all together. <strong>Figure 2</strong> shows the container topology.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/06/image-scaled.jpeg" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="612" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-1024x612.jpeg?lossy=2&strip=1&webp=1" alt="" class="wp-image-54233"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-1024x612.jpeg?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-1024x612.jpeg?size=126x75&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-1024x612.jpeg?size=252x151&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-1024x612.jpeg?size=378x226&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-1024x612.jpeg?size=504x301&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-1024x612.jpeg?size=630x377&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 2:</strong> Docker Compose container topology showing all services, volumes, networks, and inter-container communication paths.</figcaption></figure></div>


<p>Here is the complete <code data-enlighter-language="python" class="EnlighterJSRAW">docker-compose.yml</code>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="yaml" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Run an Apache Airflow DAG with Docker Compose and PostgreSQL" data-enlighter-group="10">version: '3.8'

x-airflow-common:
  &amp;airflow-common
  image: apache/airflow:2.7.3-python3.11
  environment:
    &amp;airflow-common-env
    AIRFLOW__CORE__EXECUTOR: LocalExecutor
    AIRFLOW__DATABASE__SQL_ALCHEMY_CONN: postgresql+psycopg2://airflow:airflow@postgres/airflow
    AIRFLOW__CORE__FERNET_KEY: ''
    AIRFLOW__CORE__DAGS_ARE_PAUSED_AT_CREATION: 'false'
    AIRFLOW__CORE__LOAD_EXAMPLES: 'false'
    AIRFLOW__API__AUTH_BACKENDS: 'airflow.api.auth.backend.basic_auth,airflow.api.auth.backend.session'
    PYTHONPATH: /opt/airflow/shared
    ML_ORCHESTRATION_DB_URI: postgresql://mlops:mlops_password@postgres:5432/ml_orchestration
  volumes:
    - ./dags:/opt/airflow/dags
    - ./logs:/opt/airflow/logs
    - ./plugins:/opt/airflow/plugins
    - ../shared:/opt/airflow/shared
    - /tmp/ml_orchestration/uploads:/tmp/ml_orchestration/uploads
  user: "${AIRFLOW_UID:-50000}:0"
  depends_on:
    &amp;airflow-common-depends-on
    postgres:
      condition: service_healthy

services:
  postgres:
    image: postgres:15
    environment:
      POSTGRES_USER: airflow
      POSTGRES_PASSWORD: airflow
      POSTGRES_DB: airflow
    volumes:
      - postgres-db-volume:/var/lib/postgresql/data
      - ./init-db.sh:/docker-entrypoint-initdb.d/init-db.sh
    healthcheck:
      test: ["CMD", "pg_isready", "-U", "airflow"]
      interval: 10s
      retries: 5
      start_period: 5s
    ports:
      - "5432:5432"

  airflow-webserver:
    &lt;&lt;: *airflow-common
    command: webserver
    ports:
      - "8080:8080"
    healthcheck:
      test: ["CMD", "curl", "--fail", "http://localhost:8080/health"]
      interval: 30s
      timeout: 10s
      retries: 5
      start_period: 30s
    restart: always

  airflow-scheduler:
    &lt;&lt;: *airflow-common
    command: scheduler
    healthcheck:
      test: ["CMD", "curl", "--fail", "http://localhost:8974/health"]
      interval: 30s
      timeout: 10s
      retries: 5
      start_period: 30s
    restart: always

  airflow-init:
    &lt;&lt;: *airflow-common
    entrypoint: /bin/bash
    command:
      - -c
      - |
        airflow db init
        airflow users create \
          --username admin \
          --firstname Admin \
          --lastname User \
          --role Admin \
          --email admin@example.com \
          --password admin
    environment:
      &lt;&lt;: *airflow-common-env
      _AIRFLOW_DB_UPGRADE: 'true'
      _AIRFLOW_WWW_USER_CREATE: 'true'
    user: "0:0"

  ingestion-service:
    build:
      context: .
      dockerfile: Dockerfile.service
    ports:
      - "8000:8000"
    environment:
      ML_ORCHESTRATION_DB_URI: postgresql://mlops:mlops_password@postgres:5432/ml_orchestration
      UPLOAD_DIR: /tmp/ml_orchestration/uploads
    volumes:
      - ./ingestion_service:/app/ingestion_service
      - ../shared:/app/shared
      - /tmp/ml_orchestration/uploads:/tmp/ml_orchestration/uploads
    depends_on:
      postgres:
        condition: service_healthy
    restart: always

volumes:
  postgres-db-volume:
  /tmp/ml_orchestration/uploads:</pre>



<p>Let us break down the key parts.</p>



<p>The x-airflow-common anchor (starting with &amp;) defines configuration shared by all Airflow containers. This is a YAML feature that lets us avoid repeating the same settings. The <code data-enlighter-language="python" class="EnlighterJSRAW">&lt;&lt;: *airflow-common</code> syntax merges that configuration into each service.</p>



<h3 class="wp-block-heading">Environment Variables</h3>



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">AIRFLOW__CORE__EXECUTOR: LocalExecutor</code> runs tasks in separate processes on the same machine (unlike <code data-enlighter-language="python" class="EnlighterJSRAW">SequentialExecutor</code> which runs one task at a time, or <code data-enlighter-language="python" class="EnlighterJSRAW">CeleryExecutor</code> which distributes across workers). Perfect for development and moderate workloads.</p>



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">AIRFLOW__DATABASE__SQL_ALCHEMY_CONN</code> points to the PostgreSQL container using the service name <code data-enlighter-language="python" class="EnlighterJSRAW">postgres</code> as the hostname — Docker Compose automatically creates a network where services can reach each other by name.</p>



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">PYTHONPATH: /opt/airflow/shared</code> adds the shared module to Python&#8217;s import path, allowing the DAG to import from <code data-enlighter-language="python" class="EnlighterJSRAW">shared.storage</code>, <code data-enlighter-language="python" class="EnlighterJSRAW">shared.parsing</code>, etc. Without this, imports would fail.</p>



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">ML_ORCHESTRATION_DB_URI</code> connects to our application database (<code data-enlighter-language="python" class="EnlighterJSRAW">ml_orchestration</code>), which is separate from Airflow&#8217;s metadata database.</p>



<h3 class="wp-block-heading">Volume Configuration</h3>



<p>Volumes mount local directories into containers. The <code data-enlighter-language="python" class="EnlighterJSRAW">./dags:/opt/airflow/dags</code> mapping makes your local DAG files immediately visible to Airflow — edit locally, see changes in the container.</p>



<p>The critical volume is <code data-enlighter-language="python" class="EnlighterJSRAW">/tmp/ml_orchestration/uploads:/tmp/ml_orchestration/uploads</code>, which mounts the same directory into both Airflow and the ingestion service. This shared storage lets Airflow read files the ingestion service writes, eliminating the &#8220;file not found&#8221; errors you would get with isolated containers.</p>



<h3 class="wp-block-heading">Service Definitions</h3>



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">postgres</code> service runs PostgreSQL 15. It uses a volume (<code data-enlighter-language="python" class="EnlighterJSRAW">postgres-db-volume</code>) for persistent storage. Without this volume, restarting the container would erase all data. The <code data-enlighter-language="python" class="EnlighterJSRAW">init-db.sh</code> script is mounted into <code data-enlighter-language="python" class="EnlighterJSRAW">/docker-entrypoint-initdb.d/</code>, which PostgreSQL runs automatically on first startup. This creates the <code data-enlighter-language="python" class="EnlighterJSRAW">ml_orchestration</code> database and <code data-enlighter-language="python" class="EnlighterJSRAW">mlops</code> user.</p>



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">healthcheck</code> tests if PostgreSQL is ready. Other services wait for this health check to pass before starting.</p>



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">airflow-webserver</code> service runs the Airflow UI. It inherits all settings from <code data-enlighter-language="python" class="EnlighterJSRAW">airflow-common</code> and adds a <code data-enlighter-language="python" class="EnlighterJSRAW">webserver</code> command. It exposes port <code data-enlighter-language="python" class="EnlighterJSRAW">8080</code>, which you access in your browser.</p>



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">airflow-scheduler</code> service runs the scheduler, which triggers DAG runs according to the schedule interval. This is the component that wakes up every minute and checks if the DAG should run.</p>



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">airflow-init</code> service is a one-time initialization container. It runs <code data-enlighter-language="python" class="EnlighterJSRAW">airflow db</code> init to create Airflow&#8217;s metadata tables and <code data-enlighter-language="python" class="EnlighterJSRAW">airflow users create</code> to set up the admin user. After this completes, the container exits. You do not interact with it after the first startup.</p>



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">ingestion-service</code> service runs the FastAPI app. It builds from <code data-enlighter-language="python" class="EnlighterJSRAW">Dockerfile.service</code>, which installs dependencies and runs <code data-enlighter-language="python" class="EnlighterJSRAW">uvicorn</code>. It mounts the ingestion service code and shared module. It also mounts the uploads volume so it can write files.</p>



<h3 class="wp-block-heading">Building the Ingestion Service Container</h3>



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">Dockerfile.service</code> defines how the FastAPI container is built. Here is the complete file:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="dockerfile" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Run an Apache Airflow DAG with Docker Compose and PostgreSQL" data-enlighter-group="12"># airflow_project/Dockerfile.service
FROM python:3.11-slim

WORKDIR /app

# Copy shared module first
COPY shared/ /app/shared/
RUN pip install --no-cache-dir -r /app/shared/requirements.txt

# Copy service dependencies
COPY airflow_project/ingestion_service/requirements.txt /app/requirements.txt
RUN pip install --no-cache-dir -r /app/requirements.txt

# Copy service code
COPY airflow_project/ingestion_service/ /app/ingestion_service/

# Set Python path to include shared module
ENV PYTHONPATH="/app:/app/shared"

EXPOSE 8000

CMD ["uvicorn", "ingestion_service.main:app", "--host", "0.0.0.0", "--port", "8000"]</pre>



<p>This Dockerfile uses a multi-layer approach. First, we copy and install the shared module dependencies. This layer is cached and only rebuilt when shared dependencies change. Then we install the service-specific dependencies. Finally, we copy the application code.</p>



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">PYTHONPATH</code> environment variable is critical. It tells Python where to find modules. By including both <code data-enlighter-language="python" class="EnlighterJSRAW">/app</code> and <code data-enlighter-language="python" class="EnlighterJSRAW">/app/shared</code>, we can import from both <code data-enlighter-language="python" class="EnlighterJSRAW">ingestion_service.main</code> and <code data-enlighter-language="python" class="EnlighterJSRAW">shared.storage.models</code> without issues.</p>



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">CMD</code> runs <code data-enlighter-language="python" class="EnlighterJSRAW">uvicorn</code>, the Asynchronous Server Gateway Interface (<code data-enlighter-language="python" class="EnlighterJSRAW">ASGI</code>) server for <code data-enlighter-language="python" class="EnlighterJSRAW">FastAPI</code>. The <code data-enlighter-language="python" class="EnlighterJSRAW">--host 0.0.0.0</code> makes the server accessible from outside the container (necessary for Docker port mapping). The <code data-enlighter-language="python" class="EnlighterJSRAW">--port 8000</code> matches the port we expose in <code data-enlighter-language="python" class="EnlighterJSRAW">docker-compose.yml</code>.</p>



<h3 class="wp-block-heading">Database Initialization Script</h3>



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">init-db.sh</code> script creates the <code data-enlighter-language="python" class="EnlighterJSRAW">ml_orchestration</code> database and <code data-enlighter-language="python" class="EnlighterJSRAW">mlops</code> user when PostgreSQL starts for the first time. Here is the complete script:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Run an Apache Airflow DAG with Docker Compose and PostgreSQL" data-enlighter-group="14">#!/bin/bash
# airflow_project/init-db.sh
set -e

# Create additional database and user for ML orchestration
# This script is idempotent - safe to run multiple times
psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" &lt;&lt;-EOSQL
    -- Create database only if it doesn't exist
    SELECT 'CREATE DATABASE ml_orchestration'
    WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = 'ml_orchestration')\gexec
    
    -- Create user only if it doesn't exist
    DO
    \$\$
    BEGIN
        IF NOT EXISTS (SELECT FROM pg_catalog.pg_user WHERE usename = 'mlops') THEN
            CREATE USER mlops WITH PASSWORD 'mlops_password';
        END IF;
    END
    \$\$;
    
    -- Grant privileges (idempotent operation)
    GRANT ALL PRIVILEGES ON DATABASE ml_orchestration TO mlops;
    
    -- Connect to ml_orchestration and grant schema privileges
    \c ml_orchestration
    GRANT ALL ON SCHEMA public TO mlops;
    ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON TABLES TO mlops;
    ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON SEQUENCES TO mlops;
EOSQL

echo "ML orchestration database setup completed successfully"</pre>



<p>This script demonstrates several important PostgreSQL patterns. The <code data-enlighter-language="python" class="EnlighterJSRAW">set -e</code> command makes the script exit immediately if any command fails, preventing partial setup.</p>



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">SELECT 'CREATE DATABASE ...' WHERE NOT EXISTS ... \gexec</code> pattern creates the database only if it does not already exist. This is idempotent — running the script multiple times produces the same result.</p>



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">DO $$ ... END $$</code> block is a PL/pgSQL anonymous code block that checks if the user exists before creating it. Again, this makes the script safe to rerun.</p>



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">GRANT ALL PRIVILEGES</code> statements give the <code data-enlighter-language="python" class="EnlighterJSRAW">mlops</code> user full access to the <code data-enlighter-language="python" class="EnlighterJSRAW">ml_orchestration</code> database. The <code data-enlighter-language="python" class="EnlighterJSRAW">ALTER DEFAULT PRIVILEGES</code> commands ensure that future tables and sequences created by any user are automatically accessible to <code data-enlighter-language="python" class="EnlighterJSRAW">mlops</code>. This prevents permission errors when Airflow creates tables.</p>



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">\c ml_orchestration</code> command switches the connection to the newly created database so we can grant schema-level privileges.</p>



<p>This initialization script runs automatically because docker-compose mounts it into <code data-enlighter-language="python" class="EnlighterJSRAW">/docker-entrypoint-initdb.d/</code>. PostgreSQL executes all scripts in that directory on first startup.</p>



<p><strong>Why This Structure Works</strong></p>



<p>This setup gives us isolated, reproducible environments. Everything runs in containers. There is no &#8220;works on my machine&#8221; problem. The same <code data-enlighter-language="python" class="EnlighterJSRAW">docker-compose.yml</code> runs identically on macOS, Linux, and Windows (with Docker Desktop).</p>



<p>The shared uploads volume is the key to inter-service communication. Both Airflow and the ingestion service see the same files. Airflow does not need to call the ingestion API to get files; it just reads from the shared directory.</p>



<p>The dependency management (<code data-enlighter-language="python" class="EnlighterJSRAW">depends_on</code> with health checks) ensures services start in the correct order. PostgreSQL must be ready before Airflow tries to connect.</p>



<p>Now let&#8217;s see how to run this system from scratch.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Running-Apache-Airflow-FastAPI-Document-Ingestion-Pipeline"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Running-Apache-Airflow-FastAPI-Document-Ingestion-Pipeline">Running the Apache Airflow and FastAPI Document Ingestion Pipeline</a></h2>



<p>To start the system, open a terminal, navigate to <code data-enlighter-language="python" class="EnlighterJSRAW">airflow_project/</code>, and run:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Run an Apache Airflow DAG with Docker Compose and PostgreSQL" data-enlighter-group="16">docker compose up --build</pre>



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">--build</code> flag ensures Docker rebuilds images if you changed any code. Docker will pull images, build containers, and start all services. You will see logs streaming from all 5 containers.</p>



<p>After about 30 seconds, you should see messages such as the following:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Run an Apache Airflow DAG with Docker Compose and PostgreSQL" data-enlighter-group="18">airflow-init-1         | Admin user admin created
airflow-webserver-1    | Listening at http://0.0.0.0:8080
airflow-scheduler-1    | Starting the scheduler
ingestion-service-1    | INFO:     Uvicorn running on http://0.0.0.0:8000
postgres-1             | database system is ready to accept connections</pre>



<p>This means all services are up and healthy.</p>



<h3 class="wp-block-heading">Verify the Setup</h3>



<p>Open your browser and go to:</p>



<ul class="wp-block-list">
<li><strong>Airflow UI:</strong> <code data-enlighter-language="python" class="EnlighterJSRAW">http://localhost:8080</code></li>



<li><strong>Ingestion API Docs:</strong> <code data-enlighter-language="python" class="EnlighterJSRAW">http://localhost:8000/docs</code></li>
</ul>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/06/image-36-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="254" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-36-1024x254.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54157"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-36-1024x254.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-36-1024x254.png?size=126x31&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-36-1024x254.png?size=252x63&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-36-1024x254.png?size=378x94&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-36-1024x254.png?size=504x125&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-36-1024x254.png?size=630x156&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 3:</strong> The Airflow login screen. Use username <code>admin</code> and password <code>admin</code>.</figcaption></figure></div>


<p>Log into Airflow with username <code data-enlighter-language="python" class="EnlighterJSRAW">admin</code> and password <code data-enlighter-language="python" class="EnlighterJSRAW">admin</code>. You should see the DAGs page.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/06/image-37-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="207" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-37-1024x207.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54159"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-37-1024x207.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-37-1024x207.png?size=126x25&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-37-1024x207.png?size=252x51&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-37-1024x207.png?size=378x76&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-37-1024x207.png?size=504x102&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-37-1024x207.png?size=630x127&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 4:</strong> The Airflow DAGs page showing <code>ingest_documents_dag</code> enabled and successfully scheduled every minute.</figcaption></figure></div>


<p>Find the <code data-enlighter-language="python" class="EnlighterJSRAW">ingest_documents_dag</code> row. Make sure the toggle on the left is enabled (blue or green). This allows the scheduler to run the DAG.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/06/image-38-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="437" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-38-1024x437.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54161"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-38-1024x437.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-38-1024x437.png?size=126x54&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-38-1024x437.png?size=252x108&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-38-1024x437.png?size=378x161&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-38-1024x437.png?size=504x215&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-38-1024x437.png?size=630x269&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 5:</strong> The FastAPI Swagger documentation at <code>/docs</code> showing the POST <code>/documents</code> endpoint.</figcaption></figure></div>


<p>Go to <code data-enlighter-language="python" class="EnlighterJSRAW">http://localhost:8000/docs</code>. This is the interactive API documentation powered by Swagger. You should see a green POST box labeled <code data-enlighter-language="python" class="EnlighterJSRAW">/documents</code>.</p>



<p>If all 3 URLs load successfully, your system is running.</p>



<h3 class="wp-block-heading">Stopping the System</h3>



<p>To stop all containers, press <code data-enlighter-language="python" class="EnlighterJSRAW">Ctrl+C</code> in the terminal where <code data-enlighter-language="python" class="EnlighterJSRAW">docker compose up</code> is running. Then run:</p>



<p><code data-enlighter-language="python" class="EnlighterJSRAW">docker compose down</code></p>



<p>This stops and removes containers but preserves volumes (your data persists). If you want to completely reset everything (delete all data), run:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Run an Apache Airflow DAG with Docker Compose and PostgreSQL" data-enlighter-group="20">docker compose down -v</pre>



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">-v</code> flag removes volumes, giving you a fresh start.</p>



<p>Now let us upload a document and trigger the pipeline.</p>



<h3 class="wp-block-heading">Uploading Documents via the API</h3>



<p>The ingestion service exposes a single endpoint: <code data-enlighter-language="python" class="EnlighterJSRAW">POST /documents</code>. You can call it with curl or use the Swagger UI for convenience. Let us use Swagger for this demo.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/06/image-39-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="932" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-39-1024x932.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54167"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-39-1024x932.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-39-1024x932.png?size=126x115&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-39-1024x932.png?size=252x229&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-39-1024x932.png?size=378x344&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-39-1024x932.png?size=504x459&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-39-1024x932.png?size=630x573&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 6:</strong> The Swagger UI with the <code>POST /documents</code> endpoint expanded, showing the <code>"Try it out"</code> button and file upload field.</figcaption></figure></div>


<p>In the Swagger UI (<code>http://localhost:8000/docs</code>), click the green <code data-enlighter-language="python" class="EnlighterJSRAW">POST /documents</code> box to expand it. Click <code>"Try it out"</code> in the top right corner. You should see a file upload field.</p>



<p>Click <code>"Choose File"</code> and select any PDF from your computer. For testing, use a small PDF (a few pages). Click <code>"Execute"</code> to send the request.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/06/image-40-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="836" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-40-1024x836.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54172"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-40-1024x836.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-40-1024x836.png?size=126x103&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-40-1024x836.png?size=252x206&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-40-1024x836.png?size=378x309&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-40-1024x836.png?size=504x411&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-40-1024x836.png?size=630x514&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 7:</strong> The Swagger UI response showing status <code>201 Created</code> with the returned document <code>JSON</code>, including <code>id</code>, <code>filename</code>, <code>status: PENDING</code>, and <code>content_hash</code>.</figcaption></figure></div>


<p>You should receive a <code>201 Created</code> response with <code>JSON</code> similar to the following:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="json" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Run an Apache Airflow DAG with Docker Compose and PostgreSQL" data-enlighter-group="22">{
  "id": 1,
  "filename": "sample.pdf",
  "file_path": "/tmp/ml_orchestration/uploads/1769421678.801241_sample.pdf",
  "content_hash": "a7f3b2c8d9e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2c3d4e5f6a7",
  "file_size": 23456,
  "mime_type": "application/pdf",
  "status": "PENDING",
  "created_at": "2026-01-25T10:30:00",
  "updated_at": "2026-01-25T10:30:00"
}</pre>



<p>The important fields are <code data-enlighter-language="python" class="EnlighterJSRAW">id</code> (<code data-enlighter-language="python" class="EnlighterJSRAW">1</code> in this case) and <code data-enlighter-language="python" class="EnlighterJSRAW">status</code> (<code data-enlighter-language="python" class="EnlighterJSRAW">PENDING</code>). This document is now in the database waiting for Airflow to process it.</p>



<p>If you upload the same file again, you will get a <code data-enlighter-language="python" class="EnlighterJSRAW">409 Conflict</code> error:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="json" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Run an Apache Airflow DAG with Docker Compose and PostgreSQL" data-enlighter-group="24">{
  "detail": "Document already exists with ID 1"
}</pre>



<p>This is the deduplication logic working. The system detected the identical content hash and rejected the duplicate.</p>



<p><strong>Using curl</strong></p>



<p>If you prefer the command line, use <code><code data-enlighter-language="python" class="EnlighterJSRAW">curl</code></code>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Run an Apache Airflow DAG with Docker Compose and PostgreSQL" data-enlighter-group="26">curl -X POST "http://localhost:8000/documents" \
  -H "Content-Type: multipart/form-data" \
  -F "file=@/path/to/your/document.pdf"
</pre>



<p>Replace <code data-enlighter-language="python" class="EnlighterJSRAW">/path/to/your/document.pdf</code> with the actual path to your PDF.</p>



<p>Now that we have a pending document, let&#8217;s see Airflow process it.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Triggering-Monitoring-Apache-Airflow-DAGs"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Triggering-Monitoring-Apache-Airflow-DAGs">Triggering and Monitoring Apache Airflow DAGs</a></h2>



<p>The DAG runs automatically every minute. If you just uploaded a document, wait up to 60 seconds and the scheduler will trigger a run.</p>



<h3 class="wp-block-heading">Manual Trigger (Optional)</h3>



<p>If you do not want to wait, you can manually trigger the DAG. In the Airflow UI, click on <code data-enlighter-language="python" class="EnlighterJSRAW">ingest_documents_dag</code> to open the DAG detail page.</p>



<p>You should see a graph view with your five tasks connected by arrows. On the top right, click the play button (triangle icon) and select &#8220;Trigger DAG&#8221;. This starts an immediate run.</p>



<h3 class="wp-block-heading">Monitoring Execution</h3>



<p>The DAG runs page shows all executions. Click on the latest run (top of the list). The status will progress from &#8220;running&#8221; (yellow) to &#8220;success&#8221; (green) or &#8220;failed&#8221; (red).</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/06/image-41-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="422" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-41-1024x422.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54182"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-41-1024x422.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-41-1024x422.png?size=126x52&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-41-1024x422.png?size=252x104&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-41-1024x422.png?size=378x156&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-41-1024x422.png?size=504x208&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-41-1024x422.png?size=630x260&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 8:</strong> A successful DAG run showing all 5 tasks with green checkmarks.</figcaption></figure></div>


<p>Each task should turn green as it completes. The entire run takes about 10-30 seconds, depending on your <code>PDF</code> size.</p>



<h3 class="wp-block-heading">Viewing Logs</h3>



<p>Click on any task box (e.g., <code data-enlighter-language="python" class="EnlighterJSRAW">parse_documents</code>). A panel appears on the right. Click &#8220;Log&#8221; to see the task output.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/06/image-42-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="401" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-42-1024x401.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54185"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-42-1024x401.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-42-1024x401.png?size=126x49&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-42-1024x401.png?size=252x99&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-42-1024x401.png?size=378x148&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-42-1024x401.png?size=504x197&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-42-1024x401.png?size=630x247&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 9:</strong> Task log for <code>parse_documents</code>, showing PDF parsing, page extraction warnings, and successful completion.</figcaption></figure></div>


<p>You should see log messages similar to the following:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Run an Apache Airflow DAG with Docker Compose and PostgreSQL" data-enlighter-group="27">[2026-01-25, 10:31:00 UTC] {ingest_documents_dag.py:234} INFO - Parsing documents...
[2026-01-25, 10:31:00 UTC] {pdf_parser.py:15} INFO - Parsing PDF: /tmp/ml_orchestration/uploads/1769421678.801241_sample.pdf
[2026-01-25, 10:31:01 UTC] {pdf_parser.py:35} INFO - Extracted 5 pages from PDF
[2026-01-25, 10:31:01 UTC] {ingest_documents_dag.py:250} INFO - Parsed 5 pages from sample.pdf
</pre>



<p>These logs confirm the DAG is working. If a task fails, the log will show the exception and stack trace.</p>



<p>Now let us verify the data was written to the database.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Verifying-Document-Chunk-Data-PostgreSQL"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Verifying-Document-Chunk-Data-PostgreSQL">Verifying Document and Chunk Data in PostgreSQL</a></h2>



<p>The DAG writes to 3 tables: <code data-enlighter-language="python" class="EnlighterJSRAW">documents</code>, <code data-enlighter-language="python" class="EnlighterJSRAW">chunks</code>, and <code data-enlighter-language="python" class="EnlighterJSRAW">pipeline_runs</code>. Let us query them to confirm everything worked.</p>



<h3 class="wp-block-heading">Connect to PostgreSQL</h3>



<p>Open a new terminal and run:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Run an Apache Airflow DAG with Docker Compose and PostgreSQL" data-enlighter-group="28">docker exec -it airflow_project-postgres-1 psql -U mlops -d ml_orchestration
</pre>



<p>This opens a PostgreSQL shell inside the <code data-enlighter-language="python" class="EnlighterJSRAW">postgres</code> container. You are now connected as the <code data-enlighter-language="python" class="EnlighterJSRAW">mlops</code> user to the <code data-enlighter-language="python" class="EnlighterJSRAW">ml_orchestration</code> database.</p>



<h3 class="wp-block-heading">Query Documents</h3>



<pre class="EnlighterJSRAW" data-enlighter-language="sql" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Run an Apache Airflow DAG with Docker Compose and PostgreSQL" data-enlighter-group="29">SELECT id, filename, status, created_at FROM documents;
</pre>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/06/image-43-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="92" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-43-1024x92.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54189"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-43-1024x92.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-43-1024x92.png?size=126x11&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-43-1024x92.png?size=252x23&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-43-1024x92.png?size=378x34&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-43-1024x92.png?size=504x45&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-43-1024x92.png?size=630x57&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 10:</strong> PostgreSQL query results showing the uploaded document with status <code>COMPLETED</code>.</figcaption></figure></div>


<p>You should see your document with <code data-enlighter-language="python" class="EnlighterJSRAW">status = COMPLETED</code>.</p>



<h3 class="wp-block-heading">Query Chunks</h3>



<pre class="EnlighterJSRAW" data-enlighter-language="sql" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Run an Apache Airflow DAG with Docker Compose and PostgreSQL" data-enlighter-group="30">SELECT id, document_id, chunk_index, LENGTH(text) as text_length FROM chunks LIMIT 10;
</pre>



<p>You should see rows similar to the following:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/06/image-44-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="272" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-44-1024x272.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54193"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-44-1024x272.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-44-1024x272.png?size=126x33&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-44-1024x272.png?size=252x67&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-44-1024x272.png?size=378x100&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-44-1024x272.png?size=504x134&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-44-1024x272.png?size=630x167&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 11:</strong> Query results from the <code>chunks</code> table showing generated text chunks with their <code>document_id</code>, <code>chunk_index</code>, and <code>text_length</code>.</figcaption></figure></div>


<p>Each row represents a chunk extracted from the document. The <code data-enlighter-language="python" class="EnlighterJSRAW">chunk_index</code> indicates the order of chunks within the document. The <code data-enlighter-language="python" class="EnlighterJSRAW">text_length</code> column shows the character length of each chunk. Since chunking is performed using a target word count (e.g., <code data-enlighter-language="python" class="EnlighterJSRAW">512</code> words with overlap), the character length varies depending on word size and content structure.</p>



<h3 class="wp-block-heading">Query Pipeline Runs</h3>



<pre class="EnlighterJSRAW" data-enlighter-language="sql" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Run an Apache Airflow DAG with Docker Compose and PostgreSQL" data-enlighter-group="31">SELECT run_id, status, documents_processed, chunks_created FROM pipeline_runs;
</pre>



<p>You should see:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/06/image-45-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="173" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-45-1024x173.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54199"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-45-1024x173.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-45-1024x173.png?size=126x21&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-45-1024x173.png?size=252x43&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-45-1024x173.png?size=378x64&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-45-1024x173.png?size=504x85&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-45-1024x173.png?size=630x106&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 12:</strong> Query results from the <code>pipeline_runs</code> table showing DAG run IDs, status, documents processed, and total chunks created.</figcaption></figure></div>


<p>This shows one DAG run processed one document and created <code data-enlighter-language="python" class="EnlighterJSRAW">23</code> chunks. The <code data-enlighter-language="python" class="EnlighterJSRAW">run_id</code> includes the execution timestamp.</p>



<h3 class="wp-block-heading">Exit PostgreSQL</h3>



<p>Type <code data-enlighter-language="python" class="EnlighterJSRAW">\q</code> and press Enter to exit the PostgreSQL shell.</p>



<p>You have now verified end-to-end functionality. A document was uploaded, parsed, chunked, validated, and marked complete. The data is in the database and ready for the next stage (embeddings).</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Error-Handling-Failure-Recovery-Airflow-Pipeline"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Error-Handling-Failure-Recovery-Airflow-Pipeline">Error Handling and Failure Recovery in Airflow Pipeline</a></h2>



<p>Let us walk through a real failure scenario to understand how the system handles errors.</p>



<p><strong>Scenario: A user uploads a corrupted PDF</strong></p>



<ul class="wp-block-list">
<li><strong>Upload Phase:</strong> The ingestion service receives the file, computes its hash, and saves it to <code data-enlighter-language="python" class="EnlighterJSRAW">/tmp/ml_orchestration/uploads/</code>. The file is inserted into the database with <code data-enlighter-language="python" class="EnlighterJSRAW">status=PENDING</code>. The API returns <code data-enlighter-language="python" class="EnlighterJSRAW">201 Created</code>. Everything looks normal.</li>



<li><strong>Processing Phase:</strong> One minute later, the Airflow scheduler triggers the DAG. The <code data-enlighter-language="python" class="EnlighterJSRAW">fetch_documents</code> task finds the corrupted PDF in the <code data-enlighter-language="python" class="EnlighterJSRAW">PENDING</code> state and adds its ID to the processing list.</li>



<li><strong>Parse Failure:</strong> The <code data-enlighter-language="python" class="EnlighterJSRAW">parse_documents</code> task retrieves the file path and calls <code data-enlighter-language="python" class="EnlighterJSRAW">parse_pdf()</code>. PyPDF attempts to read the file, encounters corrupted data, and raises a <code data-enlighter-language="python" class="EnlighterJSRAW">PdfReadError</code>. The exception is caught in the try-except block.</li>



<li><strong>Error Handling:</strong> Instead of letting the exception crash the entire task, we log the error, update the document&#8217;s status to <code data-enlighter-language="python" class="EnlighterJSRAW">FAILED</code>, commit the transaction, and continue processing the next document in the batch. Other valid PDFs in the same batch proceed normally.</li>



<li><strong>Observability:</strong> The task completes successfully (from Airflow&#8217;s perspective), but logs show which specific document failed and why. The failed document remains in the database with <code data-enlighter-language="python" class="EnlighterJSRAW">status=FAILED</code> and no chunks. You can query for failed documents and investigate.</li>



<li><strong>Recovery:</strong> Once you fix the corrupted PDF (or replace it), you can manually reset its status back to <code data-enlighter-language="python" class="EnlighterJSRAW">PENDING</code>. The next DAG run will pick it up and try again.</li>
</ul>



<p>This granular failure handling is why production systems use orchestrators. One bad file does not bring down the entire pipeline. You get observability into what failed, why it failed, and can fix issues incrementally.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Design-Principles-Idempotency-Observability-Reproducibility-Airflow-Pipelines"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Design-Principles-Idempotency-Observability-Reproducibility-Airflow-Pipelines">Design Principles: Idempotency, Observability, and Reproducibility in Airflow Pipelines</a></h2>



<p>This architecture demonstrates several important principles for production ML systems.</p>



<h3 class="wp-block-heading">Separation of Concerns</h3>



<p>We separated ingestion from processing. The FastAPI service accepts uploads quickly and returns. It does not block while parsing PDFs or chunking text. Users get fast feedback. Heavy processing happens asynchronously in Airflow.</p>



<p>This separation also means we can scale components independently. If upload traffic spikes, we can run more ingestion service replicas. If processing lags, we can add more Airflow workers.</p>



<h3 class="wp-block-heading">Idempotency</h3>



<p>Every task in the DAG is idempotent. You can rerun the DAG multiple times on the same documents without creating duplicates or corrupting data. This is essential for retries and recovery.</p>



<p>We achieve idempotency through:</p>



<ul class="wp-block-list">
<li><strong>Content hashing:</strong> Documents with the same content hash are recognized as duplicates.</li>



<li><strong>Existence checks:</strong> Before creating chunks, we check if they already exist.</li>



<li><strong>File-based XCom</strong><strong>:</strong> Parsing results are written to files. If a task reruns, it checks for existing files first.</li>



<li><strong>Status tracking:</strong> Documents have a <code data-enlighter-language="python" class="EnlighterJSRAW">status</code> field that prevents reprocessing completed items.</li>
</ul>



<h3 class="wp-block-heading">Observability</h3>



<p>Every operation logs its progress. You can see exactly what the system is doing at any moment. Task logs show which documents were parsed, how many chunks were created, and which operations failed.</p>



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">pipeline_runs</code> table provides metrics over time. You can query it to answer questions like &#8220;How many documents did we process last week?&#8221; or &#8220;What is our average chunk count per document?&#8221;</p>



<h3 class="wp-block-heading">Reproducibility</h3>



<p>The entire system is defined in code and configuration files. There are no manual setup steps beyond <code data-enlighter-language="python" class="EnlighterJSRAW">docker compose up</code>. Anyone can clone the repository and run the same system.</p>



<p>The shared module ensures parsing and chunking logic is consistent. Documents processed today will have the same chunk boundaries as documents processed next month.</p>



<p><strong>Failure Handling</strong></p>



<p>The DAG does not abort if one document fails. It marks that document as <code data-enlighter-language="python" class="EnlighterJSRAW">FAILED</code> and continues with others. This prevents one corrupted PDF from blocking an entire batch.</p>



<p>Airflow&#8217;s retry mechanism automatically retries failed tasks. If a transient error (network timeout, database deadlock) causes a failure, the task will retry up to 3 times before giving up.</p>



<h3 class="wp-block-heading">Data Provenance</h3>



<p>We track where every chunk came from. The <code data-enlighter-language="python" class="EnlighterJSRAW">chunk.document_id</code> and <code data-enlighter-language="python" class="EnlighterJSRAW">chunk.chunk_index</code> fields let us trace any chunk back to its source document and position. The <code data-enlighter-language="python" class="EnlighterJSRAW">pipeline_runs</code> table records when and how documents were processed.</p>



<p>This is critical for debugging, auditing, and explaining model behavior. If your RAG system returns an incorrect answer, you can trace it back to the source chunk, the document it came from, and the DAG run that processed it.</p>



<p>Now let&#8217;s discuss the limits of this approach.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Limits-Apache-Airflow-Machine-Learning-Workloads"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Limits-Apache-Airflow-Machine-Learning-Workloads">Limits of Apache Airflow for Machine Learning Workloads</a></h2>



<p>Airflow excels at orchestrating data pipelines, but it has limits for ML workloads.</p>



<h3 class="wp-block-heading">No GPU Support</h3>



<p>Airflow tasks run in Python processes on CPU. If you want to generate embeddings using a transformer model, you need GPU acceleration. Airflow does not provide native GPU scheduling.</p>



<p>You could work around this by calling an external service (like a separate embedding API), but that adds complexity and latency.</p>



<h3 class="wp-block-heading">Heavy Computation</h3>



<p>Embedding generation for thousands of chunks can take minutes or hours. Airflow is not designed for long-running, compute-intensive tasks. Tasks that run for hours can clog the scheduler and make the UI sluggish.</p>



<h3 class="wp-block-heading">Parallelism</h3>



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">LocalExecutor</code> runs tasks in parallel on a single machine. If you have 100 documents to process, Airflow will process them sequentially or in small batches limited by your CPU cores.</p>



<p>For true parallelism across multiple machines, you need the <code data-enlighter-language="python" class="EnlighterJSRAW">CeleryExecutor</code> or <code data-enlighter-language="python" class="EnlighterJSRAW">KubernetesExecutor</code>, which adds complexity.</p>



<h3 class="wp-block-heading">Kubernetes Native Workloads</h3>



<p>If you are running on Kubernetes, Airflow is an additional system to manage. It needs its own deployment, scheduler, database, and monitoring.</p>



<p>Argo Workflows, which we will cover in the next lesson, is Kubernetes-native. It runs as Kubernetes Jobs and integrates directly with Kubernetes features like resource limits, autoscaling, and GPU scheduling.</p>



<h3 class="wp-block-heading">When to Use Apache Airflow</h3>



<p>Airflow is perfect for:</p>



<ul class="wp-block-list">
<li>Data ingestion and ETL (Extract, Transform, Load)</li>



<li>Scheduled batch processing</li>



<li>Orchestrating API calls and database operations</li>



<li>Tasks that run on CPU and do not require GPU</li>



<li>Workflows with moderate parallelism</li>
</ul>



<p>Airflow is not ideal for:</p>



<ul class="wp-block-list">
<li>GPU-accelerated ML training or inference</li>



<li>Massive parallel processing (thousands of tasks)</li>



<li>Real-time or low-latency workloads</li>



<li>Kubernetes-native deployments where you want to avoid managing a separate orchestrator</li>
</ul>



<p>For our RAG pipeline, Airflow handles document ingestion perfectly. It parses PDFs, chunks text, and validates quality. But for the next stage (generating embeddings), we will switch to Argo Workflows, which can run GPU-accelerated tasks on Kubernetes.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://pyimagesearch.com/wp-content/uploads/2026/06/image-46.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="624" height="273" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-46.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-54203"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-46.png?size=126x55&lossy=2&strip=1&webp=1 126w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-46-300x131.png?lossy=2&strip=1&webp=1 300w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-46.png?size=378x165&lossy=2&strip=1&webp=1 378w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-46.png?size=504x221&lossy=2&strip=1&webp=1 504w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/06/image-46.png?lossy=2&strip=1&webp=1 624w" sizes="(max-width: 624px) 100vw, 624px" /></a><figcaption class="wp-element-caption"><strong>Figure 13:</strong> A comparison chart showing <code>Airflow</code> strengths (left column: ETL, scheduled jobs, API orchestration) and <code>Argo</code> strengths (right column: GPU tasks, massive parallelism, Kubernetes-native, DAGs with complex dependencies).</figcaption></figure></div>


<hr class="wp-block-separator has-alpha-channel-opacity"/>



<div id="pitch" style="padding: 40px; width: 100%; background-color: #F4F6FA;">
	<h3>What's next? We recommend <a target="_blank" href="https://pyimagesearch.com/pyimagesearch-university/?utm_source=blogPost&utm_medium=bottomBanner&utm_campaign=What%27s%20next%3F%20I%20recommend">PyImageSearch University</a>.</h3>

	<script src="https://fast.wistia.com/embed/medias/kno0cmko2z.jsonp" async></script><script src="https://fast.wistia.com/assets/external/E-v1.js" async></script><div class="wistia_responsive_padding" style="padding:56.25% 0 0 0;position:relative;"><div class="wistia_responsive_wrapper" style="height:100%;left:0;position:absolute;top:0;width:100%;"><div class="wistia_embed wistia_async_kno0cmko2z videoFoam=true" style="height:100%;position:relative;width:100%"><div class="wistia_swatch" style="height:100%;left:0;opacity:0;overflow:hidden;position:absolute;top:0;transition:opacity 200ms;width:100%;"><img decoding="async" src="https://fast.wistia.com/embed/medias/kno0cmko2z/swatch" style="filter:blur(5px);height:100%;object-fit:contain;width:100%;" alt="" aria-hidden="true" onload="this.parentNode.style.opacity=1;" /></div></div></div></div>

	<div style="margin-top: 32px; margin-bottom: 32px; ">
		<strong>Course information:</strong><br/>
		120+ total classes • 115+ hours hours of on-demand code walkthrough videos • Last updated: August 2026<br/>
		<span style="color: #169FE6;">★★★★★</span> 4.84 (128 Ratings) • 16,000+ Students Enrolled
	</div>

	<p><strong>I strongly believe that if you had the right teacher you could <em>master</em> computer vision and deep learning.</strong></p>

	<p>Do you think learning computer vision and deep learning has to be time-consuming, overwhelming, and complicated? Or has to involve complex mathematics and equations? Or requires a degree in computer science?</p>

	<p>That’s <em>not</em> the case.</p>

	<p>All you need to master computer vision and deep learning is for someone to explain things to you in <em>simple, intuitive</em> terms. <em>And that’s exactly what I do</em>. My mission is to change education and how complex Artificial Intelligence topics are taught.</p>

	<p>If you're serious about learning computer vision, your next stop should be PyImageSearch University, the most comprehensive computer vision, deep learning, and OpenCV course online today. Here you’ll learn how to <em>successfully</em> and <em>confidently</em> apply computer vision to your work, research, and projects. Join me in computer vision mastery.</p>

	<p><strong>Inside PyImageSearch University you'll find:</strong></p>

	<ul style="margin-left: 0px;">
		<li style="list-style: none;">&check; <strong>120+ courses</strong> on essential computer vision, deep learning, and OpenCV topics</li>
		<li style="list-style: none;">&check; <strong>94+ Certificates</strong> of Completion</li>
		<li style="list-style: none;">&check; <strong>115+ hours hours</strong> of on-demand video</li>
		<li style="list-style: none;">&check; <strong>Brand new courses released <em>regularly</em></strong>, ensuring you can keep up with state-of-the-art techniques</li>
		<li style="list-style: none;">&check; <strong>Pre-configured Jupyter Notebooks in Google Colab</strong></li>
		<li style="list-style: none;">&check; Run all code examples in your web browser — works on Windows, macOS, and Linux (no dev environment configuration required!)</li>
		<li style="list-style: none;">&check; Access to <strong>centralized code repos for <em>all</em> 540+ tutorials</strong> on PyImageSearch</li>
		<li style="list-style: none;">&check; <strong> Easy one-click downloads</strong> for code, datasets, pre-trained models, etc.</li>
		<li style="list-style: none;">&check; <strong>Access</strong> on mobile, laptop, desktop, etc.</li>
	</ul>

	<p style="text-align: center;">
		<a target="_blank" class="button link" href="https://pyimagesearch.com/pyimagesearch-university/?utm_source=blogPost&utm_medium=bottomBanner&utm_campaign=What%27s%20next%3F%20I%20recommend" style="background-color: #6DC713; border-bottom: none;">Click here to join PyImageSearch University</a>
	</p>
</div>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Summary"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Summary">Summary</a></h2>



<p>In this lesson, you operationalized the document ingestion architecture built in Lesson 1. You ran the complete system inside Docker, configured environment variables and shared volumes, and verified inter-container communication between FastAPI, Airflow, and PostgreSQL.</p>



<p>You uploaded real PDF documents through the API, triggered DAG executions, monitored task progress in the Airflow UI, inspected logs, and validated results directly in PostgreSQL. You confirmed that documents moved from <code data-enlighter-language="python" class="EnlighterJSRAW">PENDING</code> to <code data-enlighter-language="python" class="EnlighterJSRAW">COMPLETED</code>, chunks were created correctly, and pipeline runs were recorded for observability and auditing.</p>



<p>You also explored real-world failure scenarios, including corrupted PDFs and partial processing failures, and saw how the system isolates errors without blocking the entire pipeline. Through this, you reinforced key production principles: separation of concerns, idempotency, observability, reproducibility, and data provenance.</p>



<p>Finally, you examined the practical limits of Apache Airflow for ML workloads and identified where GPU-based execution and Kubernetes-native systems may be more appropriate.</p>



<p>At this point, you now have a fully runnable, production-style ingestion system that you can extend with embedding generation, vector databases, and Retrieval-Augmented Generation workflows.</p>



<h3 class="wp-block-heading">Citation Information</h3>



<p><strong>Singh, V</strong><strong>. </strong>“Run an Apache Airflow DAG with Docker Compose and PostgreSQL,” <em>PyImageSearch</em>, S. Huot, A. Sharma, and P. Thakur, eds., 2026, <a href="https://pyimg.co/kxc7e" target="_blank" rel="noreferrer noopener">https://pyimg.co/kxc7e</a> </p>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="classic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="Run an Apache Airflow DAG with Docker Compose and PostgreSQL" data-enlighter-group="32">@incollection{Singh_2026_run-apache-airflow-dag-docker-compose-postgresql,
  author = {Vikram Singh},
  title = {{Run an Apache Airflow DAG with Docker Compose and PostgreSQL}},
  booktitle = {PyImageSearch},
  editor = {Susan Huot and Aditya Sharma and Piyush Thakur},
  year = {2026},
  url = {https://pyimg.co/kxc7e},
}
</pre>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p><strong>To download the source code to this post (and be notified when future tutorials are published here on PyImageSearch), </strong><em><strong>simply enter your email address in the form below!</strong></em></p>



<div id="download-the-code" class="post-cta-wrap">
<div class="gpd-post-cta">
	<div class="gpd-post-cta-content">
		

			<div class="gpd-post-cta-top">
				<div class="gpd-post-cta-top-image"><img decoding="async" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2020/01/cta-source-guide-1.png?lossy=2&strip=1&webp=1" alt="" srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2020/01/cta-source-guide-1.png?lossy=2&strip=1&webp=1 410w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2020/01/cta-source-guide-1.png?size=126x174&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2020/01/cta-source-guide-1.png?size=252x348&lossy=2&strip=1&webp=1 252w" sizes="(max-width: 410px) 100vw, 410px" /></div>
				
				<div class="gpd-post-cta-top-title"><h4>Download the Source Code and FREE 17-page Resource Guide</h4></div>
				<div class="gpd-post-cta-top-desc"><p>Enter your email address below to get a .zip of the code and a <strong>FREE 17-page Resource Guide on Computer Vision, OpenCV, and Deep Learning.</strong> Inside you'll find my hand-picked tutorials, books, courses, and libraries to help you master CV and DL!</p></div>


			</div>

			<div class="gpd-post-cta-bottom">
				<form id="footer-cta-code" class="footer-cta" action="https://www.getdrip.com/forms/4130035/submissions" method="post" target="blank" data-drip-embedded-form="4130035">
					<input name="fields[email]" type="email" value="" placeholder="Your email address" class="form-control" />

					<button type="submit">Download the code!</button>

					<div style="display: none;" aria-hidden="true"><label for="website">Website</label><br /><input type="text" id="website" name="website" tabindex="-1" autocomplete="false" value="" /></div>
				</form>
			</div>


		
	</div>

</div>
</div>



<p></p>
<p>The post <a rel="nofollow" href="https://pyimagesearch.com/2026/06/08/run-an-apache-airflow-dag-with-docker-compose-and-postgresql/">Run an Apache Airflow DAG with Docker Compose and PostgreSQL</a> appeared first on <a rel="nofollow" href="https://pyimagesearch.com">PyImageSearch</a>.</p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
