<?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, 30 Nov 2026 09:52:48 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.8.13</generator>
	<item>
		<title>Adding LLM Guardrails to a Multimodal Chatbot with Qwen3Guard</title>
		<link>https://pyimagesearch.com/2026/11/30/adding-llm-guardrails-to-a-multimodal-chatbot-with-qwen3guard/</link>
		
		<dc:creator><![CDATA[Puneet Mangla]]></dc:creator>
		<pubDate>Mon, 30 Nov 2026 13:45:00 +0000</pubDate>
				<category><![CDATA[Chatbots]]></category>
		<category><![CDATA[LLM Guardrails]]></category>
		<category><![CDATA[Multimodal AI]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[ai content moderation]]></category>
		<category><![CDATA[gradio]]></category>
		<category><![CDATA[llm guardrails]]></category>
		<category><![CDATA[multimodal chatbot]]></category>
		<category><![CDATA[prompt filtering]]></category>
		<category><![CDATA[qwen3-vl]]></category>
		<category><![CDATA[qwen3guard]]></category>
		<category><![CDATA[qwen3guard-gen]]></category>
		<category><![CDATA[response filtering]]></category>
		<category><![CDATA[tutorial]]></category>
		<guid isPermaLink="false">https://pyimagesearch.com/?p=56106</guid>

					<description><![CDATA[<p>Table of Contents Adding LLM Guardrails to a Multimodal Chatbot with Qwen3Guard Qwen3Guard Model Details Qwen3Guard-Gen vs. Qwen3Guard-Stream Training Data and Safety Labels Benchmarks for Prompt and Response Moderation Building a Gradio Multimodal Chatbot with Response Moderation Step 1: Installing&#8230;</p>
<p>The post <a rel="nofollow" href="https://pyimagesearch.com/2026/11/30/adding-llm-guardrails-to-a-multimodal-chatbot-with-qwen3guard/">Adding LLM Guardrails to a Multimodal Chatbot with Qwen3Guard</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-Adding-LLM-Guardrails-to-a-Multimodal-Chatbot-with-Qwen3Guard"><a rel="noopener" target="_blank" href="#h1-Adding-LLM-Guardrails-to-a-Multimodal-Chatbot-with-Qwen3Guard">Adding LLM Guardrails to a Multimodal Chatbot with Qwen3Guard</a></li>
    <li id="TOC-h2-Qwen3Guard-Model-Details"><a rel="noopener" target="_blank" href="#h2-Qwen3Guard-Model-Details">Qwen3Guard Model Details</a>
        <ul>
            <li id="TOC-h3-Qwen3Guard-Gen-vs-Qwen3Guard-Stream"><a rel="noopener" target="_blank" href="#h3-Qwen3Guard-Gen-vs-Qwen3Guard-Stream">Qwen3Guard-Gen vs. Qwen3Guard-Stream</a></li>
            <li id="TOC-h3-Training-Data-and-Safety-Labels"><a rel="noopener" target="_blank" href="#h3-Training-Data-and-Safety-Labels">Training Data and Safety Labels</a></li>
            <li id="TOC-h3-Benchmarks-for-Prompt-and-Response-Moderation"><a rel="noopener" target="_blank" href="#h3-Benchmarks-for-Prompt-and-Response-Moderation">Benchmarks for Prompt and Response Moderation</a></li>
        </ul>
    </li>
    <li id="TOC-h2-Building-a-Gradio-Multimodal-Chatbot-with-Response-Moderation"><a rel="noopener" target="_blank" href="#h2-Building-a-Gradio-Multimodal-Chatbot-with-Response-Moderation">Building a Gradio Multimodal Chatbot with Response Moderation</a>
        <ul>
            <li id="TOC-h3-Step-1-Installing-Required-Dependencies"><a rel="noopener" target="_blank" href="#h3-Step-1-Installing-Required-Dependencies">Step 1: Installing Required Dependencies</a></li>
            <li id="TOC-h3-Step-2-Importing-Libraries-and-Utilities"><a rel="noopener" target="_blank" href="#h3-Step-2-Importing-Libraries-and-Utilities">Step 2: Importing Libraries and Utilities</a></li>
            <li id="TOC-h3-Step-3-Loading-Qwen3-VL-and-Qwen3Guard-Gen-with-Transformers"><a rel="noopener" target="_blank" href="#h3-Step-3-Loading-Qwen3-VL-and-Qwen3Guard-Gen-with-Transformers">Step 3: Loading Qwen3-VL and Qwen3Guard-Gen with Transformers</a></li>
            <li id="TOC-h3-Step-4-Testing-AI-Content-Moderation-on-Chatbot-Responses"><a rel="noopener" target="_blank" href="#h3-Step-4-Testing-AI-Content-Moderation-on-Chatbot-Responses">Step 4: Testing AI Content Moderation on Chatbot Responses</a></li>
            <li id="TOC-h3-Step-5-Adding-Qwen3Guard-Response-Filtering-to-the-Gradio-Interface"><a rel="noopener" target="_blank" href="#h3-Step-5-Adding-Qwen3Guard-Response-Filtering-to-the-Gradio-Interface">Step 5: Adding Qwen3Guard Response Filtering to the Gradio Interface</a></li>
            <li id="TOC-h3-Step-6-Launching-the-Safe-Gradio-Chatbot"><a rel="noopener" target="_blank" href="#h3-Step-6-Launching-the-Safe-Gradio-Chatbot">Step 6: Launching the Safe Gradio Chatbot</a></li>
            <li id="TOC-h3-Example-How-the-Chatbot-Blocks-a-Flagged-Response"><a rel="noopener" target="_blank" href="#h3-Example-How-the-Chatbot-Blocks-a-Flagged-Response">Example: How the Chatbot Blocks a Flagged Response</a></li>
        </ul>
    </li>
    <li id="TOC-h2-Summary"><a rel="noopener" target="_blank" href="#h2-Summary">Summary</a>
        <ul>
            <li id="TOC-h3-Citation-Information"><a rel="noopener" target="_blank" href="#h3-Citation-Information">Citation Information</a></li>
        </ul>
    </li>
</ul>
</div>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h1-Adding-LLM-Guardrails-to-a-Multimodal-Chatbot-with-Qwen3Guard"/>



<h2 class="wp-block-heading"><a href="#TOC-h1-Adding-LLM-Guardrails-to-a-Multimodal-Chatbot-with-Qwen3Guard">Adding LLM Guardrails to a Multimodal Chatbot with Qwen3Guard</a></h2>



<p>As artificial intelligence (AI) systems become increasingly powerful and widely deployed, ensuring their safety has emerged as one of the most critical challenges in the field. While the chatbots we have built in the previous lessons demonstrate impressive capabilities in understanding text and images, they lack a crucial component: the ability to detect and filter harmful content. Without proper safeguards, AI systems can be manipulated to generate dangerous instructions, spread misinformation, or produce content that violates ethical guidelines and societal norms. This is where Qwen3Guard enters the picture, providing state-of-the-art safety moderation capabilities that protect both users and service providers from harmful AI interactions.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://pyimagesearch.com/wp-content/uploads/2026/11/adding-llm-guardrails-multimodal-chatbot-qwen3guard-featured-v2.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/11/adding-llm-guardrails-multimodal-chatbot-qwen3guard-featured-v2.png?lossy=2&strip=1&webp=1" alt="adding-llm-guardrails-multimodal-chatbot-qwen3guard-featured-v2.png" class="wp-image-56136"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/adding-llm-guardrails-multimodal-chatbot-qwen3guard-featured-v2.png?size=126x105&lossy=2&strip=1&webp=1 126w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/adding-llm-guardrails-multimodal-chatbot-qwen3guard-featured-v2-300x249.png?lossy=2&strip=1&webp=1 300w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/adding-llm-guardrails-multimodal-chatbot-qwen3guard-featured-v2.png?size=378x314&lossy=2&strip=1&webp=1 378w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/adding-llm-guardrails-multimodal-chatbot-qwen3guard-featured-v2.png?size=504x418&lossy=2&strip=1&webp=1 504w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/adding-llm-guardrails-multimodal-chatbot-qwen3guard-featured-v2.png?size=630x523&lossy=2&strip=1&webp=1 630w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/adding-llm-guardrails-multimodal-chatbot-qwen3guard-featured-v2-768x637.png?lossy=2&strip=1&webp=1 768w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/adding-llm-guardrails-multimodal-chatbot-qwen3guard-featured-v2.png?lossy=2&strip=1&webp=1 940w" sizes="(max-width: 940px) 100vw, 940px" /></a></figure></div>


<p>Qwen3Guard represents a comprehensive safety solution that addresses 2 fundamental limitations of existing guard models. First, most guard models implement rigid, one-size-fits-all safety policies that fail to account for the diverse deployment scenarios where context matters. Qwen3Guard introduces a 3-tiered severity classification system (<code data-enlighter-language="python" class="EnlighterJSRAW">Safe</code>, <code data-enlighter-language="python" class="EnlighterJSRAW">Controversial</code>, and <code data-enlighter-language="python" class="EnlighterJSRAW">Unsafe</code>) that enables fine-grained control over safety thresholds. </p>



<p>Content labeled as <code data-enlighter-language="python" class="EnlighterJSRAW">Controversial</code> might be acceptable in some applications but blocked in others, allowing developers to tailor safety policies to their specific use cases. </p>



<p>Second, many guard models require a complete response before they can assess it, which prevents them from moderating individual tokens as they are generated. </p>



<ul class="wp-block-list">
<li><strong>Generative Qwen3Guard (Qwen3Guard-Gen):</strong> Safety classification of complete user prompts and model responses </li>



<li><strong>Stream Qwen3Guard (Qwen3Guard-Stream):</strong> Token-level monitoring of model responses during generation </li>
</ul>



<p>In this lesson, we extend our multimodal chatbot from Lessons 1 and 2 by integrating Qwen3Guard&#8217;s safety moderation capabilities. We will evaluate assistant responses before displaying them to users.</p>



<p>Through practical implementation, we will learn how to detect multiple categories of harmful content including violence, illegal activities, sexual content, personally identifiable information (PII), self-harm content, unethical acts, politically sensitive topics, copyright violations, and jailbreak attempts. The Generative variant will provide detailed classification results with specific risk categories, while the safety checks will run transparently in the background, blocking the display of responses flagged as <code data-enlighter-language="python" class="EnlighterJSRAW">Unsafe</code> or <code data-enlighter-language="python" class="EnlighterJSRAW">Controversial</code>.</p>



<p>By the end of this lesson, we will have a multimodal chatbot that checks assistant responses for harmful content before displaying them.</p>



<p>This lesson is the 3rd 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 Qwen3 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></li>



<li><em><strong><a href="https://pyimg.co/qwb0l" target="_blank" rel="noreferrer noopener">Adding LLM Guardrails to a Multimodal Chatbot with Qwen3Guard</a></strong></em> <strong>(this tutorial)</strong></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-Qwen3Guard-Model-Details"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Qwen3Guard-Model-Details">Qwen3Guard Model Details</a></h2>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Qwen3Guard-Gen-vs-Qwen3Guard-Stream"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Qwen3Guard-Gen-vs-Qwen3Guard-Stream">Qwen3Guard-Gen vs. Qwen3Guard-Stream</a></h3>



<p>Qwen3Guard comprises 2 specialized variants designed to address different aspects of safety moderation: Qwen3Guard-Gen and Qwen3Guard-Stream. Both variants build upon Qwen3 foundation models and are available with 0.6 billion, 4 billion, or 8 billion parameters to accommodate various deployment scenarios and resource constraints. The architectural innovations in each variant reflect their distinct use cases: comprehensive classification for the Generative model and real-time streaming detection for the Stream model.</p>



<p>Qwen3Guard-Gen reformulates safety classification as an instruction-following task, leveraging the natural language understanding and generation capabilities of the base LLM. Rather than adding classification heads or specialized layers, Qwen3Guard-Gen processes safety queries as natural language instructions and generates structured responses in text format. </p>



<p>Given a prompt or response to evaluate, the model receives instructions that include the task definition (classify input as safe, controversial, or unsafe), the safety policy defining each category, the specific safety categories to check, and output formatting requirements (<strong>Figure 1</strong>). </p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/11/image-15.jpeg" target="_blank" rel="Figure 1: The Instructions of Qwen3Guard-Gen for Prompt and Response Assessment (source: Qwen Team). noreferrer noopener"><img decoding="async" width="1024" height="630" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-15-1024x630.jpeg?lossy=2&strip=1&webp=1" alt="" class="wp-image-56144"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-15-1024x630.jpeg?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-15-1024x630.jpeg?size=126x78&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-15-1024x630.jpeg?size=252x155&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-15-1024x630.jpeg?size=378x233&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-15-1024x630.jpeg?size=504x310&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-15-1024x630.jpeg?size=630x388&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 1: </strong>The Instructions of Qwen3Guard-Gen for Prompt and Response Assessment (source: <a href="https://arxiv.org/abs/2510.14276" target="_blank" rel="noreferrer noopener">Qwen Team</a>).</figcaption></figure></div>


<p>The model then generates a structured response containing the safety assessment (<code data-enlighter-language="python" class="EnlighterJSRAW">Safe</code>/<code data-enlighter-language="python" class="EnlighterJSRAW">Unsafe</code>/<code data-enlighter-language="python" class="EnlighterJSRAW">Controversial</code>), the relevant safety categories for <code data-enlighter-language="python" class="EnlighterJSRAW">Unsafe</code> or <code data-enlighter-language="python" class="EnlighterJSRAW">Controversial</code> content (Violent, Illegal Acts, Sexual Content, PII, Self-Harm, Unethical Acts, Politically Sensitive, Copyright Violation, or Jailbreak), and, for response classification, whether the assistant refused to answer the query.</p>



<p>This generative approach offers several advantages. First, it enables flexible, customizable safety policies without retraining. Developers can modify instructions to emphasize certain categories or adjust severity thresholds. Second, the model can provide explanations for its classifications, improving interpretability and trust. Third, it naturally extends to multilingual scenarios since the base model already supports 119 languages. The generative paradigm means Qwen3Guard-Gen behaves like a sophisticated conversation partner that understands nuanced safety requirements and can adapt its assessments based on contextual information provided in the prompt.</p>



<p>Qwen3Guard-Stream (<strong>Figure 2</strong>) employs a fundamentally different architecture optimized for real-time token-level classification during streaming generation. Built on the same Qwen3 base models, Qwen3Guard-Stream adds 2 specialized classification heads to the final transformer layer: a Prompt Moderator head that evaluates incoming user queries and a Response Moderator head that assesses each generated token in real time. </p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/11/image-16-scaled.jpeg" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="397" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-16-1024x397.jpeg?lossy=2&strip=1&webp=1" alt="" class="wp-image-56147"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-16-1024x397.jpeg?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-16-1024x397.jpeg?size=126x49&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-16-1024x397.jpeg?size=252x98&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-16-1024x397.jpeg?size=378x147&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-16-1024x397.jpeg?size=504x195&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-16-1024x397.jpeg?size=630x244&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 2: </strong>Overview of Qwen3Guard-Stream (source: <a href="https://arxiv.org/abs/2510.14276" target="_blank" rel="noreferrer noopener">Qwen Team</a>).</figcaption></figure></div>


<p>The architecture extracts the last hidden state from the backbone model and processes it through 2 parallel pathways, one for analyzing responses and one for queries. Each pathway includes a pre-processing layer with layer normalization, followed by 2 classification layers: one predicting the risk level (<code data-enlighter-language="python" class="EnlighterJSRAW">Safe</code>, <code data-enlighter-language="python" class="EnlighterJSRAW">Controversial</code>, or <code data-enlighter-language="python" class="EnlighterJSRAW">Unsafe</code>) and another predicting the specific safety category.</p>



<p>The mathematical formulation captures this dual-head design elegantly. For each token, the model computes:</p>



<p class="has-text-align-center"><img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/7ec/7eca9f2f0b9b3a9db52ab01adb878d9c-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='x_r = \text{LayerNorm}(W_{r\text{-}pre} h)' title='x_r = \text{LayerNorm}(W_{r\text{-}pre} h)' class='latex' srcset='https://b2633864.assetcdn.net/2633864/wp-content/latex/7ec/7eca9f2f0b9b3a9db52ab01adb878d9c-ffffff-000000-0.png?lossy=2&strip=1&webp=1 180w,https://b2633864.assetcdn.net/2633864/wp-content/latex/7ec/7eca9f2f0b9b3a9db52ab01adb878d9c-ffffff-000000-0.png?size=126x13&lossy=2&strip=1&webp=1 126w' sizes='(max-width: 180px) 100vw, 180px' /> and <img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/9e6/9e6ef6f5c7e842974e9c42cff68028d1-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='x_q = \text{LayerNorm}(W_{q\text{-}pre} h)' title='x_q = \text{LayerNorm}(W_{q\text{-}pre} h)' class='latex' srcset='https://b2633864.assetcdn.net/2633864/wp-content/latex/9e6/9e6ef6f5c7e842974e9c42cff68028d1-ffffff-000000-0.png?lossy=2&strip=1&webp=1 180w,https://b2633864.assetcdn.net/2633864/wp-content/latex/9e6/9e6ef6f5c7e842974e9c42cff68028d1-ffffff-000000-0.png?size=126x13&lossy=2&strip=1&webp=1 126w' sizes='(max-width: 180px) 100vw, 180px' /></p>



<p class="has-text-align-center"><img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/5ba/5ba425b8ff1d6c562ab7ba57530204a0-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='y_{r\text{-}risk} = \text{Softmax}(W_{r\text{-}risk} x_r)' title='y_{r\text{-}risk} = \text{Softmax}(W_{r\text{-}risk} x_r)' class='latex' srcset='https://b2633864.assetcdn.net/2633864/wp-content/latex/5ba/5ba425b8ff1d6c562ab7ba57530204a0-ffffff-000000-0.png?lossy=2&strip=1&webp=1 194w,https://b2633864.assetcdn.net/2633864/wp-content/latex/5ba/5ba425b8ff1d6c562ab7ba57530204a0-ffffff-000000-0.png?size=126x12&lossy=2&strip=1&webp=1 126w' sizes='(max-width: 194px) 100vw, 194px' /> and <img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/6b5/6b513b851946dc6068a1f15303d85b50-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='y_{q\text{-}risk} = \text{Softmax}(W_{q\text{-}risk} x_q)' title='y_{q\text{-}risk} = \text{Softmax}(W_{q\text{-}risk} x_q)' class='latex' srcset='https://b2633864.assetcdn.net/2633864/wp-content/latex/6b5/6b513b851946dc6068a1f15303d85b50-ffffff-000000-0.png?lossy=2&strip=1&webp=1 194w,https://b2633864.assetcdn.net/2633864/wp-content/latex/6b5/6b513b851946dc6068a1f15303d85b50-ffffff-000000-0.png?size=126x12&lossy=2&strip=1&webp=1 126w' sizes='(max-width: 194px) 100vw, 194px' /></p>



<p class="has-text-align-center"><img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/b25/b2577292a1b657255d81670a7bf90dee-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='y_{r\text{-}cat} = \text{Softmax}(W_{r\text{-}cat} x_r)' title='y_{r\text{-}cat} = \text{Softmax}(W_{r\text{-}cat} x_r)' class='latex' srcset='https://b2633864.assetcdn.net/2633864/wp-content/latex/b25/b2577292a1b657255d81670a7bf90dee-ffffff-000000-0.png?lossy=2&strip=1&webp=1 182w,https://b2633864.assetcdn.net/2633864/wp-content/latex/b25/b2577292a1b657255d81670a7bf90dee-ffffff-000000-0.png?size=126x12&lossy=2&strip=1&webp=1 126w' sizes='(max-width: 182px) 100vw, 182px' /> and <img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/756/75677c6c10281d8524dcbe93742df296-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='y_{q\text{-}cat} = \text{Softmax}(W_{q\text{-}cat} x_q)' title='y_{q\text{-}cat} = \text{Softmax}(W_{q\text{-}cat} x_q)' class='latex' srcset='https://b2633864.assetcdn.net/2633864/wp-content/latex/756/75677c6c10281d8524dcbe93742df296-ffffff-000000-0.png?lossy=2&strip=1&webp=1 182w,https://b2633864.assetcdn.net/2633864/wp-content/latex/756/75677c6c10281d8524dcbe93742df296-ffffff-000000-0.png?size=126x13&lossy=2&strip=1&webp=1 126w' sizes='(max-width: 182px) 100vw, 182px' /></p>



<p>where <img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/251/2510c39011c5be704182423e3a695e91-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='h' title='h' class='latex' /> is the last hidden state from the backbone, <img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/61e/61e9c06ea9a85a5088a499df6458d276-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='W' title='W' class='latex' /> matrices are learnable weights, and <img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/415/415290769594460e2e485922904f345d-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='y' title='y' class='latex' /> tensors are probability distributions over risk levels and safety categories for responses (<img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/4b4/4b43b0aee35624cd95b910189b3dc231-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='r' title='r' class='latex' />) and queries (<img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/769/7694f4a66316e53c8cdd9d9954bd611d-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='q' title='q' class='latex' />), respectively.</p>



<p>The key innovation enabling Qwen3Guard-Stream&#8217;s real-time capabilities is its token-level operation. Unlike Qwen3Guard-Gen, which must wait for complete text, Qwen3Guard-Stream evaluates each token as it is generated, computing safety classifications in parallel with model generation. </p>



<p>If the model begins generating unsafe content, Qwen3Guard-Stream can detect it within 1 or 2 tokens, allowing the application to halt generation. A debouncing mechanism ensures stability: content is flagged as unsafe starting from token <img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/865/865c0c0b4ab0e063e5caa3387c1a8741-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='i' title='i' class='latex' /> only if both token <img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/865/865c0c0b4ab0e063e5caa3387c1a8741-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='i' title='i' class='latex' /> and its predecessor <img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/800/800ba394e806c049c98cf4b570d04c72-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='i-1' title='i-1' class='latex' /> are classified as <code data-enlighter-language="python" class="EnlighterJSRAW">Unsafe</code> or <code data-enlighter-language="python" class="EnlighterJSRAW">Controversial</code>, preventing spurious false positives from single-token anomalies.</p>



<p>Both variants support the 3-tiered severity classification (<code data-enlighter-language="python" class="EnlighterJSRAW">Safe</code>, <code data-enlighter-language="python" class="EnlighterJSRAW">Controversial</code>, <code data-enlighter-language="python" class="EnlighterJSRAW">Unsafe</code>) and the 9 safety categories defined in Qwen3Guard&#8217;s comprehensive policy. The choice between the Gen and Stream variants depends on application requirements: Qwen3Guard-Gen provides more detailed, explainable classifications suitable for batch processing, content moderation reviews, and scenarios where complete context is available. </p>



<p>Qwen3Guard-Stream enables real-time protection during live interactions, making it ideal for chatbots, streaming assistants, and applications where low latency is critical. In practice, both can be used together: Qwen3Guard-Gen for comprehensive prompt analysis before generation begins, and Qwen3Guard-Stream for real-time monitoring during response generation.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Training-Data-and-Safety-Labels"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Training-Data-and-Safety-Labels">Training Data and Safety Labels</a></h3>



<p>Training Qwen3Guard required developing a massive, high-quality dataset covering diverse languages, safety categories, and severity levels. The dataset comprises over 1.19 million samples including both human-annotated and synthetically generated data. </p>



<p>The data distribution spans 14 major languages plus many others, with Chinese (26.64%) and English (21.9%) as the largest segments, followed by Korean (9.91%), Indonesian (5.38%), Russian (5.36%), Japanese (4.82%), Arabic (4.71%), and others. The data is roughly balanced between prompt classification (41.2%) and response classification (58.8%), ensuring the model learns to evaluate both user inputs and assistant outputs effectively.</p>



<p>To ensure comprehensive coverage of all safety categories, Qwen3Guard employs sophisticated data synthesis strategies. For prompt synthesis, the team adopted the Self-Instruct framework, first decomposing the safety policy into a fine-grained taxonomy and collecting seed prompts for each category. Large language models then generated additional examples based on these seeds. </p>



<p>The team used 2 complementary strategies to enhance data quality: keyword-guided synthesis where generation was conditioned on category-specific keywords (e.g., &#8220;bomb,&#8221; &#8220;TNT,&#8221; &#8220;C4&#8221; for explosives), and paired positive-negative examples that share surface structure but differ in safety (&#8220;How to make a bomb&#8221; vs &#8220;How to make a cake&#8221;). This pairing prevents the model from learning spurious correlations between innocent words and safety labels.</p>



<p>For response collection, the data includes both human-authored content and model-generated responses from various sources. Special emphasis was placed on 2 challenging categories: unsafe responses generated using base models (rather than safety-aligned instruct models) to ensure the guard learns to detect harmful content that might occasionally slip through alignment training, and responses with reasoning content from models such as QwQ (Qwen with Questions) and Qwen3-Thinking, preparing the guard to moderate the explicit thinking processes that these models generate. This is particularly important as reasoning models become more prevalent, requiring guards that can evaluate not just final answers but also intermediate reasoning steps that might reveal problematic logic or biases.</p>



<p>Multilingual coverage was achieved through 2 mechanisms: direct collection of safety data in multiple languages, particularly Chinese and English, and translation of existing data to 15 additional languages using Qwen-MT (machine translation). Translation quality was validated through language mixing detection, LLM judges evaluating naturalness and safety label preservation, and random sampling with manual review. This multilingual approach ensures Qwen3Guard can protect users across linguistic boundaries, a critical requirement for globally deployed AI systems.</p>



<p>A major challenge in training Qwen3Guard-Stream was converting coarse sample-level labels into fine-grained token-level annotations. The team developed an automated annotation method combining rollout-based safety assessment and LLM-as-judge verification. For each unsafe sample, the method iterates through tokens to find where unsafe content begins. For token <img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/865/865c0c0b4ab0e063e5caa3387c1a8741-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='i' title='i' class='latex' />, it constructs prefix <img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/08b/08b0104e514f16d489cc743b6f66d906-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='P_i' title='P_i' class='latex' /> containing all tokens up to <img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/865/865c0c0b4ab0e063e5caa3387c1a8741-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='i' title='i' class='latex' /> and generates multiple rollout continuations. </p>



<p>If at least 85% of rollouts are classified as <code data-enlighter-language="python" class="EnlighterJSRAW">Unsafe</code> by Qwen3Guard-Gen, token <img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/865/865c0c0b4ab0e063e5caa3387c1a8741-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='i' title='i' class='latex' /> is flagged. However, rollouts can overestimate risk. Even safe tokens might lead to unsafe continuations due to model behavior. Therefore, an LLM judge (Qwen3-235B-A22B) verifies each flagged token, assessing whether prefix <img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/08b/08b0104e514f16d489cc743b6f66d906-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='P_i' title='P_i' class='latex' /> itself is unsafe rather than predicting future content. Only when both rollout assessment and judge verification agree is token <img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/865/865c0c0b4ab0e063e5caa3387c1a8741-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='i' title='i' class='latex' /> marked as the unsafe boundary, with all subsequent tokens inheriting the sample-level label.</p>



<p>Training follows specialized objectives for each variant. Qwen3Guard-Gen uses standard supervised fine-tuning (SFT) loss, optimizing the model to generate correctly formatted classification responses. The instruction-following nature means it learns from the full context of each safety evaluation task, including policy definitions and output format requirements. Qwen3Guard-Stream employs a more complex joint training strategy with separate losses for query and response classification. Query loss is computed only at the final token (the end-of-query marker), while response loss is computed at every token and averaged, enabling token-by-token predictions. A conditional mechanism applies category loss only when the ground-truth risk level is <code data-enlighter-language="python" class="EnlighterJSRAW">Unsafe</code> or <code data-enlighter-language="python" class="EnlighterJSRAW">Controversial</code>, ensuring the model focuses category predictions where safety concerns actually exist.</p>



<p>An innovative aspect of Qwen3Guard-Gen&#8217;s training is the building of controversial labels through a multi-stage process (<strong>Figure 3</strong>). The training data is split into 2 parts, and for each part, 2 models are trained with reweighted samples to yield &#8220;Loose&#8221; and &#8220;Strict&#8221; predictions. Each model then annotates the other part, and final labels are assigned through voting. Where predictions conflict, samples are marked as <code data-enlighter-language="python" class="EnlighterJSRAW">Controversial</code>. This produces a 3-tiered classification that captures the inherent ambiguity in safety judgments, recognizing that some content&#8217;s harm depends on context, cultural norms, or application-specific policies. Label distillation then refines the dataset by retraining on synthetic data and using the improved model to re-annotate samples, iteratively improving data quality.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/11/image-17-scaled.jpeg" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="308" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-17-1024x308.jpeg?lossy=2&strip=1&webp=1" alt="" class="wp-image-56149"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-17-1024x308.jpeg?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-17-1024x308.jpeg?size=126x38&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-17-1024x308.jpeg?size=252x76&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-17-1024x308.jpeg?size=378x114&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-17-1024x308.jpeg?size=504x152&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-17-1024x308.jpeg?size=630x189&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 3: </strong>Qwen3Guard Training Process (source: <a href="https://arxiv.org/abs/2510.14276" target="_blank" rel="noreferrer noopener">Qwen Team</a>).</figcaption></figure></div>


<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Benchmarks-for-Prompt-and-Response-Moderation"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Benchmarks-for-Prompt-and-Response-Moderation">Benchmarks for Prompt and Response Moderation</a></h3>



<p>Qwen3Guard achieves state-of-the-art performance across comprehensive safety benchmarks, demonstrating its effectiveness at both prompt and response classification. Evaluation spans English, Chinese, and multilingual datasets covering diverse safety categories, with results consistently showing Qwen3Guard outperforming existing open-source alternatives and competing with proprietary systems. The 3-tiered severity classification (with Strict and Loose modes) provides flexibility for different deployment scenarios while maintaining high accuracy.</p>



<p>On English prompt classification benchmarks (<strong>Figure 4</strong>), Qwen3Guard-Gen models show exceptional performance. Qwen3Guard-Gen-8B achieves an average F1 score of 90.0%, with particularly strong results on specialized datasets: 91.4% on Aegis, 99.5% on SimpleSafety, 100% on HarmBench, and 88.9% on WildGuard. </p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/11/image-18-scaled.jpeg" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="575" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-18-1024x575.jpeg?lossy=2&strip=1&webp=1" alt="" class="wp-image-56151"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-18-1024x575.jpeg?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-18-1024x575.jpeg?size=126x71&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-18-1024x575.jpeg?size=252x142&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-18-1024x575.jpeg?size=378x212&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-18-1024x575.jpeg?size=504x283&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-18-1024x575.jpeg?size=630x354&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 4: </strong>Qwen3Guard-Gen vs. existing guard models across safety classification benchmarks for Prompts and Responses (source: <a href="https://arxiv.org/abs/2510.14276" target="_blank" rel="noreferrer noopener">Qwen Team</a>).</figcaption></figure></div>


<p>The Strict mode (treating <code data-enlighter-language="python" class="EnlighterJSRAW">Controversial</code> as <code data-enlighter-language="python" class="EnlighterJSRAW">Unsafe</code>) excels on datasets emphasizing caution, while Loose mode (treating <code data-enlighter-language="python" class="EnlighterJSRAW">Controversial</code> as <code data-enlighter-language="python" class="EnlighterJSRAW">Safe</code>) performs better on datasets preferring permissiveness. This dual-mode capability allows developers to tune sensitivity based on application requirements: stricter for child-facing applications, looser for professional or research contexts. Even the smallest 0.6B variant achieves 88.1% average F1, demonstrating strong performance despite minimal parameter count.</p>



<p>On English response benchmarks, Qwen3Guard-Gen shows strong performance (<strong>Figure 4</strong>), effectively identifying when model responses contain harmful instructions, inappropriate content, or policy violations. The application can interrupt generation when Qwen3Guard-Stream detects unsafe content.</p>



<p>Multilingual performance demonstrates Qwen3Guard&#8217;s global applicability. On Chinese safety benchmarks, the models achieve F1 scores comparable to English performance, validating the effectiveness of multilingual training data and translation strategies. Performance remains strong across lower-resource languages, though with slightly reduced accuracy reflecting the inherent challenge of limited training data. The model&#8217;s ability to handle code-switching (mixing multiple languages in a single input) further enhances practical utility for globally deployed systems.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Building-a-Gradio-Multimodal-Chatbot-with-Response-Moderation"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Building-a-Gradio-Multimodal-Chatbot-with-Response-Moderation">Building a Gradio Multimodal Chatbot with Response Moderation</a></h2>



<p>Now let us extend our multimodal chatbot from Lesson 2 by integrating Qwen3Guard for comprehensive safety moderation. We will check assistant responses for harmful content before displaying them.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Step-1-Installing-Required-Dependencies"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Step-1-Installing-Required-Dependencies">Step 1: Installing Required Dependencies</a></h3>



<p>We will use the same dependencies as Lesson 2, with no additional packages needed for Qwen3Guard since it uses the standard Transformers <code data-enlighter-language="python" class="EnlighterJSRAW">pipeline()</code> 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="Adding LLM Guardrails to a Multimodal Chatbot with Qwen3Guard" data-enlighter-group="2">!pip install torch transformers accelerate gradio "gradio>=5,&lt;6"
!pip install qwen-vl-utils pillow
print("\n✅ Dependencies installed successfully!")
</pre>



<p>On <strong>Lines 1 and 2</strong>, we install all the dependencies from our previous lessons: PyTorch for deep learning, Transformers for model loading, Accelerate for optimization, Gradio for the web interface, Flash Attention for faster inference, and <code data-enlighter-language="python" class="EnlighterJSRAW">qwen-vl-utils</code> with Pillow for image processing. Qwen3Guard uses the same pipeline infrastructure as our other models, so no additional packages are required.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Step-2-Importing-Libraries-and-Utilities"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Step-2-Importing-Libraries-and-Utilities">Step 2: Importing Libraries and Utilities</a></h3>



<p>We extend our imports to include regular expression support for parsing Guard outputs.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Adding LLM Guardrails to a Multimodal Chatbot with Qwen3Guard" data-enlighter-group="4">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
import re

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-10</strong>, we import all necessary modules from Lessons 1 and 2, plus the <code data-enlighter-language="python" class="EnlighterJSRAW">re</code> module for regular expressions. On <strong>Line 10</strong>, the <code data-enlighter-language="python" class="EnlighterJSRAW">re</code> module will help us parse Qwen3Guard&#8217;s structured text output to extract safety labels and categories. On <strong>Lines 12-15</strong>, we perform environment checks to verify PyTorch installation and graphics processing unit (GPU) availability.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Step-3-Loading-Qwen3-VL-and-Qwen3Guard-Gen-with-Transformers"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Step-3-Loading-Qwen3-VL-and-Qwen3Guard-Gen-with-Transformers">Step 3: Loading Qwen3-VL and Qwen3Guard-Gen with Transformers</a></h3>



<p>Now we initialize 3 model pipelines: the Qwen3-VL models from Lesson 2 and the new Guard 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="Adding LLM Guardrails to a Multimodal Chatbot with Qwen3Guard" data-enlighter-group="6">print("=" * 60)
print("Initializing Qwen3-VL-2B-Instruct and Qwen3-VL-2B-Thinking 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("=" * 60)
print("Initializing Qwen3-Guard Text Generation Pipeline")
print("=" * 60)

def extract_label_categories_refusal(content):
    safe_pattern = r"Safety: (Safe|Unsafe|Controversial)"
    category_pattern = r"(Violent|Non-violent Illegal Acts|Sexual Content or Sexual Acts|PII|Suicide &amp; Self-Harm|Unethical Acts|Politically Sensitive Topics|Copyright Violation|JailBreak|None)"
    safe_label_match = re.search(safe_pattern, content)
    label = safe_label_match.group(1) if safe_label_match else None
    categories = re.findall(category_pattern, content)
    return label, categories
 
# Use Qwen3Guard-Gen-0.6B so all three pipelines fit comfortably in a 15 GB T4 GPU.
# If you need slightly more precise detection on a larger GPU (e.g., L4/A100), swap to "Qwen/Qwen3Guard-Gen-4B".
qwen3guard = pipeline("text-generation", model="Qwen/Qwen3Guard-Gen-0.6B", dtype=torch.float16)

print("\n✅ Pipelines initialized successfully!")
</pre>



<p>On <strong>Lines 1-6</strong>, we initialize the same Qwen3-VL models from Lesson 2 for multimodal understanding with both Instruct and Thinking variants. On <strong>Lines 8-10</strong>, we print messages indicating we are loading the Guard model.</p>



<p>On <strong>Lines 12-18</strong>, we define a utility function to parse Guard model outputs. Qwen3Guard-Gen produces structured text responses with a <code data-enlighter-language="python" class="EnlighterJSRAW">Safety:</code> field containing 1 of 3 values (<code data-enlighter-language="python" class="EnlighterJSRAW">Safe</code>, <code data-enlighter-language="python" class="EnlighterJSRAW">Unsafe</code>, or <code data-enlighter-language="python" class="EnlighterJSRAW">Controversial</code>) and category names. On <strong>Lines 13 and 14</strong>, we define regex patterns to match the safety label and category names. On <strong>Lines 15-17</strong>, we use <code data-enlighter-language="python" class="EnlighterJSRAW">re.search</code> to extract the safety label and <code data-enlighter-language="python" class="EnlighterJSRAW">re.findall</code> to extract all mentioned categories (there may be multiple). On <strong>Line 18</strong>, we return both the label and the list of categories for easy processing.</p>



<p>On <strong>Line 22</strong>, we initialize the Qwen3Guard-Gen-0.6B model using a standard <code data-enlighter-language="python" class="EnlighterJSRAW">text-generation</code> pipeline. Qwen3Guard-Gen accepts text inputs and generates text outputs following its trained instruction-following format. On <strong>Line 24</strong>, we confirm successful initialization of all 3 model types.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Step-4-Testing-AI-Content-Moderation-on-Chatbot-Responses"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Step-4-Testing-AI-Content-Moderation-on-Chatbot-Responses">Step 4: Testing AI Content Moderation on Chatbot Responses</a></h3>



<p>Before building the full interface, let us test the Guard model to see how it evaluates responses to potentially unsafe prompts.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Adding LLM Guardrails to a Multimodal Chatbot with Qwen3Guard" data-enlighter-group="8"># Initialize conversation history
conversation = []

# First message with image
img1 = Image.open(BytesIO(requests.get("https://img.freepik.com/premium-photo/portrait-black-people_963476-3426.jpg", timeout=10).content))
user_msg_1 = "Make a dark joke on the person in the image."
conversation.append({"role": "user", "content": [{"type": "text", "text": user_msg_1}, {"type": "image", "image": img1}]})
display(Markdown(f"**User**: {user_msg_1}"))
display(img1)
</pre>



<p>On <strong>Line</strong> <strong>2</strong>, we initialize an empty conversation history. On <strong>Lines 5 and 6</strong>, we load a test image and create an intentionally unsafe user message requesting content that could be unethical (making jokes about someone&#8217;s appearance or race). On <strong>Lines 7-9</strong>, we append this to the conversation and display both the message and image for visibility. This test case helps us verify that the Guard model can flag potentially inappropriate responses.</p>



<p>Now let us see how the Guard evaluates 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="Adding LLM Guardrails to a Multimodal Chatbot with Qwen3Guard" data-enlighter-group="10"># Generate response with thinking model
response = qwen3vl_thinking(conversation, do_sample=False, max_new_tokens=1024, return_full_text=False)
trace = response[0]['generated_text'].split('&lt;/think>')[0]
response_text = response[0]['generated_text'].split('&lt;/think>')[1]

# Safety check the response
guard_response = qwen3guard(
    [{"role": "user", "content": response_text}],
    do_sample=False,
    max_new_tokens=256,
    return_full_text=False
)

print(guard_response)
label, categories = extract_label_categories_refusal(guard_response[0]['generated_text'])
display(Markdown(f"\n**Guard Assessment**: Label: {label}, Categories: {categories}"))
</pre>



<p>On <strong>Lines 2-4</strong>, we generate a response using the Thinking model and parse out the thinking trace and final response. On <strong>Lines 7-12</strong>, we pass the assistant&#8217;s response to the Guard model for safety evaluation. The Guard receives the response text as a user message (following its training format where it evaluates content by treating it as a query). We use deterministic generation (<code data-enlighter-language="python" class="EnlighterJSRAW">do_sample=False</code>) and limit output to 256 tokens.</p>



<p>On <strong>Lines 14-16</strong>, we print the raw Guard output and extract the safety label and categories using our parsing function, then display the assessment. In <strong>Figure 5</strong>, the Guard labels the response as <code data-enlighter-language="python" class="EnlighterJSRAW">Controversial</code> and assigns it to the <code data-enlighter-language="python" class="EnlighterJSRAW">Unethical Acts</code> category.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://pyimagesearch.com/wp-content/uploads/2026/11/image-19.jpeg" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="902" height="530" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-19.jpeg?lossy=2&strip=1&webp=1" alt="" class="wp-image-56161"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-19.jpeg?size=126x74&lossy=2&strip=1&webp=1 126w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-19-300x176.jpeg?lossy=2&strip=1&webp=1 300w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-19.jpeg?size=378x222&lossy=2&strip=1&webp=1 378w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-19.jpeg?size=504x296&lossy=2&strip=1&webp=1 504w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-19.jpeg?size=630x370&lossy=2&strip=1&webp=1 630w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-19-768x451.jpeg?lossy=2&strip=1&webp=1 768w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-19.jpeg?lossy=2&strip=1&webp=1 902w" sizes="(max-width: 902px) 100vw, 902px" /></a><figcaption class="wp-element-caption"><strong>Figure 5: </strong>Sample conversation using Qwen3Guard to detect controversial model responses (source: author).</figcaption></figure></div>


<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Step-5-Adding-Qwen3Guard-Response-Filtering-to-the-Gradio-Interface"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Step-5-Adding-Qwen3Guard-Response-Filtering-to-the-Gradio-Interface">Step 5: Adding Qwen3Guard Response Filtering to the Gradio Interface</a></h3>



<p>Now we will build the complete interface with integrated safety checks.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Adding LLM Guardrails to a Multimodal Chatbot with Qwen3Guard" data-enlighter-group="12">import base64
from io import BytesIO

def create_chatbot_interface(chatbot, thinking_chatbot, guard_model):
    """
    Gradio interface for chatbot interaction with safety checks
    """

    def pil_to_base64(img):
        buf = BytesIO()
        img.resize((256, 256)).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() and image is None:
            return history, "", None
        if history is None:
            history = []
        user_content = []
        if message.strip():
            user_content.append({"type": "text", "text": message})
        if image is not None:
            user_content.append({"type": "image", "image": image})
        conversation.append({"role": "user", "content": user_content})

        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>Lines 1-7</strong>, we import <code data-enlighter-language="python" class="EnlighterJSRAW">base64</code> and <code data-enlighter-language="python" class="EnlighterJSRAW">BytesIO</code>, then define our interface creation function that now accepts 3 models: the Qwen3-VL chatbot, thinking chatbot, and guard model. On <strong>Lines 9-12</strong>, we define the image encoding helper function from Lesson 2. On <strong>Lines 14-32</strong>, we define the user message handler that now accepts both text and optional images, building a flexible content list and displaying the combined input in the chat history.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Adding LLM Guardrails to a Multimodal Chatbot with Qwen3Guard" data-enlighter-group="14">    def chat_function(message: str, conversation, history, model_choice: str):
        try:
            # --- Generate assistant response ---
            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)
                assistant_text = response[0]['generated_text']

            # --- Safety check for assistant response ---
            guard_assistant = guard_model(
                [{"role": "user", "content": assistant_text}],
                do_sample=False,
                max_new_tokens=256,
                return_full_text=False
            )
            label_a, categories_a = extract_label_categories_refusal(
                guard_assistant[0]['generated_text']
            )
            if label_a == "Unsafe" or label_a == "Controversial":
                assistant_text = "⚠️ I apologize, but I cannot provide a response to this query that meets our safety standards."

            # --- Append safe or refused response ---
            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 </strong><strong>4</strong><strong>-1</strong><strong>6</strong>, we generate the assistant response using either Thinking or Instruct mode, exactly as in Lesson 2. On <strong>Lines 19-2</strong><strong>7</strong>, we implement the crucial safety check. We pass the generated response to the Guard model and extract the safety label and categories. On <strong>Lines </strong><strong>28 and 29</strong>, if the label is <code data-enlighter-language="python" class="EnlighterJSRAW">Unsafe</code> or <code data-enlighter-language="python" class="EnlighterJSRAW">Controversial</code> (indicating potential harm), we replace the assistant&#8217;s response with a safety refusal message. When the Guard flags a response, the chatbot displays the refusal message. On <strong>Lines 32-3</strong><strong>8</strong>, we append the final response (either the original or the safety refusal) to the conversation history and handle any exceptions.</p>



<p>This implementation demonstrates a critical pattern for responsible AI: always check outputs before displaying them to users. The safety check happens transparently in the background, and users experience seamless protection without needing to understand the technical details.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Adding LLM Guardrails to a Multimodal Chatbot with Qwen3Guard" data-enlighter-group="16">    with gr.Blocks() as interface:
        gr.Markdown("## 🤖 Qwen3 Multimodal Chatbot with Safety Moderation")

        with gr.Row():
            chatbot_ui = gr.Chatbot(scale=4)

        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 + safety checks
        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-38</strong>, we build the Gradio interface using the same structure as Lesson 2, with an updated title mentioning safety moderation. The interface layout includes the chatbot display, text and image inputs, send and stop buttons, and model selection dropdown. We register 2 handlers for the Send button, one to display the user’s message and one to generate and check the assistant’s response. The difference from Lesson 2 is that our <code data-enlighter-language="python" class="EnlighterJSRAW">chat_function</code> now includes Guard checks, but this happens transparently without any user interface (UI) changes.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Step-6-Launching-the-Safe-Gradio-Chatbot"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Step-6-Launching-the-Safe-Gradio-Chatbot">Step 6: Launching the Safe Gradio Chatbot</a></h3>



<p>Finally, we create and launch our safety-enhanced chatbot.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Adding LLM Guardrails to a Multimodal Chatbot with Qwen3Guard" data-enlighter-group="18"># Create the interface
interface = create_chatbot_interface(qwen3vl_instruct, qwen3vl_thinking, qwen3guard)
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 the interface by passing all 3 model pipelines: the Qwen3-VL Instruct model, Qwen3-VL Thinking model, and Guard model. On <strong>Lines 5-7</strong>, we print access information. On <strong>Line 9</strong>, we launch the application. Before displaying an assistant response, the chatbot checks it with the Guard model. It displays a refusal message if the Guard returns <code data-enlighter-language="python" class="EnlighterJSRAW">Unsafe</code> or <code data-enlighter-language="python" class="EnlighterJSRAW">Controversial</code>.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Example-How-the-Chatbot-Blocks-a-Flagged-Response"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Example-How-the-Chatbot-Blocks-a-Flagged-Response">Example: How the Chatbot Blocks a Flagged Response</a></h3>



<p>In <strong>Figure 6</strong>, the user uploads a <strong>photo of a large group of people in traditional attire</strong> and asks: <em>“Make a joke on this image.”</em></p>



<p>Here, the chatbot activates its <strong>safety guardrails</strong> and responds with:</p>



<p>⚠️ I apologize, but I cannot provide a response to this query that meets our safety standards.</p>



<p>This is a powerful demonstration of <strong>Qwen</strong><strong>3G</strong><strong>uard in action</strong>. The chatbot displays the refusal after Qwen3Guard flags the generated response.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/11/image-20-scaled.jpeg" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="643" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-20-1024x643.jpeg?lossy=2&strip=1&webp=1" alt="" class="wp-image-56167"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-20-1024x643.jpeg?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-20-1024x643.jpeg?size=126x79&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-20-1024x643.jpeg?size=252x158&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-20-1024x643.jpeg?size=378x237&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-20-1024x643.jpeg?size=504x316&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-20-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 using Qwen3Guard Chatbot (source: 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 of on-demand code walkthrough videos • Last updated: November 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</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 Qwen3Guard and its critical role in building responsible, safe AI systems. We began by understanding the architecture of 2 specialized variants: Qwen3Guard-Gen, which reformulates safety classification as an instruction-following task and provides detailed, explainable assessments with 3-tiered severity levels (<code data-enlighter-language="python" class="EnlighterJSRAW">Safe</code>, <code data-enlighter-language="python" class="EnlighterJSRAW">Controversial</code>, <code data-enlighter-language="python" class="EnlighterJSRAW">Unsafe</code>), and Qwen3Guard-Stream, which adds dual classification heads for real-time token-level moderation during streaming generation. </p>



<p>We learned about the comprehensive 9-category safety policy covering violence, illegal activities, sexual content, PII, self-harm, unethical acts, politically sensitive topics, copyright violations, and jailbreak attempts. The sophisticated training methodology (including keyword-guided synthesis, paired positive-negative examples, multilingual translation, and automated token-level annotation through rollout assessment and LLM-judge verification) ensures robust safety detection across diverse scenarios and languages.</p>



<p>We then translated this theoretical foundation into practical implementation by extending our multimodal chatbot with comprehensive safety moderation. Through hands-on coding, we learned critical patterns for responsible AI development: initializing Guard pipelines using standard <code data-enlighter-language="python" class="EnlighterJSRAW">text-generation</code> infrastructure, parsing structured safety outputs with regular expressions to extract labels and categories, implementing transparent background safety checks that intercept problematic content before display, blocking the display of responses labeled as <code data-enlighter-language="python" class="EnlighterJSRAW">Unsafe</code> or <code data-enlighter-language="python" class="EnlighterJSRAW">Controversial</code>, and maintaining user experience while enforcing strict safety policies. </p>



<p>Safety checks should be built into the chatbot. By integrating Guard checks directly into our generation pipeline, we ensure that safety is enforced consistently without requiring users to understand or manage it manually.</p>



<p>This lesson represents a crucial milestone in our journey toward a production-ready AI assistant. We have progressed from basic text understanding (Lesson 1) to multimodal capabilities (Lesson 2) and now to safety-aware operation that protects users from harmful content. The combination of powerful language and vision models with robust safety guardrails creates a system that is both capable and responsible. </p>



<p>In the final lesson (Lesson 4), we will complete our assistant by integrating Qwen3 Embedding to enable retrieval-augmented generation (RAG). This will allow the chatbot to search through knowledge bases, ground its responses in retrieved documents, and provide citations for its claims. By the end of the series, we will have built a comprehensive, safe, multimodal, knowledge-grounded AI assistant that demonstrates best practices for model capabilities, safety, and factual grounding.</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>“Adding LLM Guardrails to a Multimodal Chatbot with Qwen3Guard,” <em>PyImageSearch</em>, S. Huot, A. Sharma, and P. Thakur, eds., 2026, <a href="https://pyimg.co/qwb0l" target="_blank" rel="noreferrer noopener">https://pyimg.co/qwb0l</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="Adding LLM Guardrails to a Multimodal Chatbot with Qwen3Guard" data-enlighter-group="19">@incollection{Mangla_2026_adding-llm-guardrails-to-multimodal-chatbot-qwen3guard,
  author = {Puneet Mangla},
  title = {{Adding LLM Guardrails to a Multimodal Chatbot with Qwen3Guard}},
  booktitle = {PyImageSearch},
  editor = {Susan Huot and Aditya Sharma and Piyush Thakur},
  year = {2026},
  url = {https://pyimg.co/qwb0l},
}
</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/11/30/adding-llm-guardrails-to-a-multimodal-chatbot-with-qwen3guard/">Adding LLM Guardrails to a Multimodal Chatbot with Qwen3Guard</a> appeared first on <a rel="nofollow" href="https://pyimagesearch.com">PyImageSearch</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Production-Ready Docker for MLOps: Docker Compose, GPUs, and Ollama</title>
		<link>https://pyimagesearch.com/2026/11/23/production-ready-docker-for-mlops-docker-compose-gpus-and-ollama/</link>
		
		<dc:creator><![CDATA[Vikram Singh]]></dc:creator>
		<pubDate>Mon, 23 Nov 2026 13:45:00 +0000</pubDate>
				<category><![CDATA[Docker]]></category>
		<category><![CDATA[Large Language Models]]></category>
		<category><![CDATA[Machine Learning]]></category>
		<category><![CDATA[MLOps]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[docker]]></category>
		<category><![CDATA[docker compose]]></category>
		<category><![CDATA[docker security best practices]]></category>
		<category><![CDATA[fastapi]]></category>
		<category><![CDATA[gpu support]]></category>
		<category><![CDATA[large language models]]></category>
		<category><![CDATA[mlops]]></category>
		<category><![CDATA[model deployment]]></category>
		<category><![CDATA[multi-stage builds]]></category>
		<category><![CDATA[nvidia container toolkit]]></category>
		<category><![CDATA[ollama]]></category>
		<category><![CDATA[ollama docker]]></category>
		<category><![CDATA[tutorial]]></category>
		<guid isPermaLink="false">https://pyimagesearch.com/?p=56004</guid>

					<description><![CDATA[<p>Table of Contents Production-Ready Docker for MLOps: Docker Compose, GPUs, and Ollama Why Docker Matters for Production MLOps Configuring Our Development Environment Project Structure Multi-Stage Docker Builds for Smaller ML Inference Images Docker Compose for ML Workflows GPU Support in&#8230;</p>
<p>The post <a rel="nofollow" href="https://pyimagesearch.com/2026/11/23/production-ready-docker-for-mlops-docker-compose-gpus-and-ollama/">Production-Ready Docker for MLOps: Docker Compose, GPUs, and Ollama</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-Production-Ready-Docker-for-MLOps-Docker-Compose-GPUs-and-Ollama"><a rel="noopener" target="_blank" href="#h1-Production-Ready-Docker-for-MLOps-Docker-Compose-GPUs-and-Ollama">Production-Ready Docker for MLOps: Docker Compose, GPUs, and Ollama</a></li>
    <li id="TOC-h2-Why-Docker-Matters-for-Production-MLOps"><a rel="noopener" target="_blank" href="#h2-Why-Docker-Matters-for-Production-MLOps">Why Docker Matters for Production MLOps</a></li>
    <li id="TOC-h2-Configuring-Our-Development-Environment"><a rel="noopener" target="_blank" href="#h2-Configuring-Our-Development-Environment">Configuring Our 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-Multi-Stage-Docker-Builds-for-Smaller-ML-Inference-Images"><a rel="noopener" target="_blank" href="#h2-Multi-Stage-Docker-Builds-for-Smaller-ML-Inference-Images">Multi-Stage Docker Builds for Smaller ML Inference Images</a></li>
    <li id="TOC-h2-Docker-Compose-for-ML-Workflows"><a rel="noopener" target="_blank" href="#h2-Docker-Compose-for-ML-Workflows">Docker Compose for ML Workflows</a></li>
    <li id="TOC-h2-GPU-Support-in-Docker-and-Docker-Compose"><a rel="noopener" target="_blank" href="#h2-GPU-Support-in-Docker-and-Docker-Compose">GPU Support in Docker and Docker Compose</a></li>
    <li id="TOC-h2-How-to-Run-Ollama-in-Docker-for-Local-LLM-Inference"><a rel="noopener" target="_blank" href="#h2-How-to-Run-Ollama-in-Docker-for-Local-LLM-Inference">How to Run Ollama in Docker for Local LLM Inference</a></li>
    <li id="TOC-h2-Docker-Security-Best-Practices-for-Production-ML-Images"><a rel="noopener" target="_blank" href="#h2-Docker-Security-Best-Practices-for-Production-ML-Images">Docker Security Best Practices for Production ML Images</a></li>
    <li id="TOC-h2-How-to-Push-ML-Images-to-Docker-Hub-and-GitHub-Container-Registry"><a rel="noopener" target="_blank" href="#h2-How-to-Push-ML-Images-to-Docker-Hub-and-GitHub-Container-Registry">How to Push ML Images to Docker Hub and GitHub Container Registry</a></li>
    <li id="TOC-h2-Production-Checklist-Hardening-Our-ML-Images"><a rel="noopener" target="_blank" href="#h2-Production-Checklist-Hardening-Our-ML-Images">Production Checklist: Hardening Our ML Images</a></li>
    <li id="TOC-h2-Scaling-ML-Workloads-Beyond-Docker-Compose-with-Swarm-and-Kubernetes"><a rel="noopener" target="_blank" href="#h2-Scaling-ML-Workloads-Beyond-Docker-Compose-with-Swarm-and-Kubernetes">Scaling ML Workloads Beyond Docker Compose with Swarm and Kubernetes</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-Production-Ready-Docker-for-MLOps-Docker-Compose-GPUs-and-Ollama"/>



<h2 class="wp-block-heading"><a href="#TOC-h1-Production-Ready-Docker-for-MLOps-Docker-Compose-GPUs-and-Ollama">Production-Ready Docker for MLOps: Docker Compose, GPUs, and Ollama</a></h2>



<p>In this lesson, we will learn advanced Docker techniques for MLOps. We will move beyond the basics of containers and Dockerfiles to explore how production-grade Machine Learning (ML) systems are built and deployed using Docker.</p>


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


<p>We will start by understanding why naïve Dockerfiles often fail in real-world ML pipelines and how multi-stage builds create leaner, faster, and more secure images. Then we will step into <strong>Docker Compose</strong>, the tool that lets us orchestrate multi-container ML workflows by connecting training jobs, inference application programming interfaces (APIs), databases, and caches in a single reproducible environment.</p>



<p>This lesson is the last in a 3-part series on <strong>Machine Learning Operations (MLOps)</strong>:</p>



<ol class="wp-block-list">
<li><em><strong><a href="https://pyimg.co/dqztp" target="_blank" rel="noreferrer noopener">What Is MLOps? Architecture, MLOps vs DevOps, and LLMOps</a></strong></em></li>



<li><em><strong><a href="https://pyimg.co/flyvj" target="_blank" rel="noreferrer noopener">Getting Started with Docker for Machine Learning and MLOps</a></strong></em></li>



<li><em><strong><a href="https://pyimg.co/6l2mp" target="_blank" rel="noreferrer noopener">Production-Ready Docker for MLOps: Docker Compose, GPUs, and Ollama</a></strong></em><strong> (this tutorial)</strong></li>
</ol>



<p>Since graphics processing units (GPUs) are at the heart of modern ML and deep learning, we will also learn how to run GPU-enabled containers using the <strong>NVIDIA Container Toolkit</strong> and configure GPU scheduling in Compose. We will also cover <strong>Docker for LLM workloads</strong> using Ollama. We will show how to containerize local large language models (LLMs) to ensure reproducibility and portability in the age of large language model operations (LLMOps).</p>



<p>Finally, we will discover production best practices for security and optimization, how to push images to cloud registries, and how to integrate Docker into continuous integration and continuous delivery (CI/CD) workflows. The lesson wraps up with a <strong>hands-on project</strong>: building a multi-stage ML inference service, orchestrating it with Compose, and proving it works seamlessly with GPU support.</p>



<p>By the end, we will have the skills to take Docker from a local ML convenience tool to a <strong>production-ready foundation for MLOps</strong>.</p>



<p><strong>To learn how to build production-ready Docker images, orchestrate ML workflows with Compose, enable GPU support, and containerize LLM workloads, </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-Docker-Matters-for-Production-MLOps"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Why-Docker-Matters-for-Production-MLOps">Why Docker Matters for Production MLOps</a></h2>



<p>Building our first ML <code data-enlighter-language="python" class="EnlighterJSRAW">Dockerfile</code> is exciting, but it is only the beginning. The reality is that “toy” containers often fail when we try to scale them into production. They get too big, take forever to build, and may even contain hidden vulnerabilities. For MLOps engineers, these problems add friction in CI/CD pipelines and slow down deployments on Amazon Elastic Container Service (Amazon ECS), Kubernetes, or Lambda.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://pyimagesearch.com/wp-content/uploads/2026/11/image-50.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="624" height="345" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-50.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-56031"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-50.png?size=126x70&lossy=2&strip=1&webp=1 126w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-50-300x166.png?lossy=2&strip=1&webp=1 300w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-50.png?size=378x209&lossy=2&strip=1&webp=1 378w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-50.png?size=504x279&lossy=2&strip=1&webp=1 504w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-50.png?lossy=2&strip=1&webp=1 624w" sizes="(max-width: 624px) 100vw, 624px" /></a><figcaption class="wp-element-caption"><strong>Figure 1:</strong> Comparing naïve ML Docker containers to production-ready ones highlighting benefits such as faster deploys, smaller images, hardened security, and optimized dependencies (source: image by the author).</figcaption></figure></div>


<h3 class="wp-block-heading">Common Problems with Naïve Dockerfiles</h3>



<ul class="wp-block-list">
<li><strong>Bloated Images:</strong> Beginners often use full Ubuntu or Anaconda images, which can easily exceed several gigabytes. This slows down pulls, pushes, and CI/CD builds.</li>



<li><strong>Rebuild Pain:</strong> If we copy our entire project before installing dependencies, every code change forces a full rebuild of the image.</li>



<li><strong>Security Risks:</strong> Running everything as root or leaving unnecessary packages installed makes containers vulnerable.</li>



<li><strong>Environment Drift:</strong> Training images and inference images often diverge, leading to “works in dev but not in prod” headaches.</li>
</ul>



<p>These issues can make ML systems unreliable and expensive to operate. That is why we need to move from “it runs locally” to <strong>production-ready Docker</strong>.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://pyimagesearch.com/wp-content/uploads/2026/11/image-51.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="624" height="313" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-51.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-56033"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-51.png?size=126x63&lossy=2&strip=1&webp=1 126w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-51-300x150.png?lossy=2&strip=1&webp=1 300w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-51.png?size=378x190&lossy=2&strip=1&webp=1 378w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-51.png?size=504x253&lossy=2&strip=1&webp=1 504w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-51.png?lossy=2&strip=1&webp=1 624w" sizes="(max-width: 624px) 100vw, 624px" /></a><figcaption class="wp-element-caption"><strong>Figure 2:</strong> Common pitfalls of naïve ML Dockerfiles include bloated images, slow rebuilds, security vulnerabilities, and environment drift between dev and prod (source: image by the author).</figcaption></figure></div>


<h3 class="wp-block-heading">Developer Productivity: Docker in VS Code and Dev Containers</h3>



<p>In practice, most ML engineers spend their time inside Visual Studio Code (VS Code) or Jupyter. To make containerized workflows smoother, tools (e.g., <strong>VS Code Dev</strong> <strong>Containers</strong>) are now widely used. A <code data-enlighter-language="python" class="EnlighterJSRAW">.devcontainer.json</code> file lets us define our development environment inside Docker, so we and our teammates can open VS Code and instantly get the same setup with all dependencies, extensions, and even GPU support preconfigured.</p>



<p>This approach ensures that the <strong>same container can be used for development, testing, and deployment</strong>, reducing environment drift. It also makes onboarding new collaborators trivial: instead of sharing a <code data-enlighter-language="python" class="EnlighterJSRAW">README</code> with setup steps, we share a container definition.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://pyimagesearch.com/wp-content/uploads/2026/11/image-52.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="624" height="335" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-52.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-56036"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-52.png?size=126x68&lossy=2&strip=1&webp=1 126w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-52-300x161.png?lossy=2&strip=1&webp=1 300w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-52.png?size=378x203&lossy=2&strip=1&webp=1 378w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-52.png?size=504x271&lossy=2&strip=1&webp=1 504w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-52.png?lossy=2&strip=1&webp=1 624w" sizes="(max-width: 624px) 100vw, 624px" /></a><figcaption class="wp-element-caption"><strong>Figure 3:</strong> VS Code Dev Containers create a shared, reproducible development environment inside Docker, complete with extensions, dependencies, and GPU support (source: image by the author).</figcaption></figure></div>


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



<p>MLOps is about reproducibility, collaboration, and reliable deployment. If our images are too heavy, insecure, or inconsistent, downstream processes such as CI/CD and monitoring become fragile. By learning <strong>multi-stage builds, Compose orchestration, GPU-ready containers, and registry integration</strong>, we will gain the tools to make Docker a true production backbone for ML.</p>



<p>In the next section, we will start with <strong>multi-stage builds</strong> to make ML Docker images lean, secure, and production-friendly.</p>



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



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



<p>To follow this Docker MLOps Production guide, we need Docker and supporting tools installed on our system.</p>



<h3 class="wp-block-heading">Core Requirements</h3>



<h4 class="wp-block-heading">Docker Desktop (essential for all examples)</h4>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Production-Ready Docker for MLOps: Docker Compose, GPUs, and Ollama" data-enlighter-group="1">​​# Download from: https://www.docker.com/products/docker-desktop/
# Verify installation:
$ docker --version
$ docker compose version</pre>



<h4 class="wp-block-heading">​​Python 3.9+ (optional, for model customization)</h4>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Production-Ready Docker for MLOps: Docker Compose, GPUs, and Ollama" data-enlighter-group="2"># Verify Python installation
$ python --version

# Set up development environment
$ python -m venv .venv
$ source .venv/bin/activate  # Windows: .venv\Scripts\activate

# Install model creation dependencies
$ pip install torch==2.1.0 torchvision==0.16.0 pytorch-lightning==2.1.0 scikit-learn==1.3.0</pre>



<h3 class="wp-block-heading">System Requirements</h3>



<h4 class="wp-block-heading">Memory and Storage</h4>



<ul class="wp-block-list">
<li>8 GB+ random-access memory (RAM) recommended (for LLM examples)</li>



<li>10 GB+ free disk space (for Docker images)</li>



<li>solid-state drive (SSD) preferred for faster builds</li>
</ul>



<h4 class="wp-block-heading">Verify Docker Resources</h4>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Production-Ready Docker for MLOps: Docker Compose, GPUs, and Ollama" data-enlighter-group="3"># Check Docker system info
$ docker system df
$ docker info | grep -E 'CPUs|Total Memory'</pre>



<h3 class="wp-block-heading">GPU Support (Optional)</h3>



<p>For accelerated training examples, install NVIDIA Container Toolkit:</p>



<h4 class="wp-block-heading">Linux (Ubuntu/Debian)</h4>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Production-Ready Docker for MLOps: Docker Compose, GPUs, and Ollama" data-enlighter-group="4">$ curl -fsSL https://nvidia.github.io/libnvidia-container/gpgkey | sudo gpg --dearmor -o /usr/share/keyrings/nvidia-container-toolkit-keyring.gpg
$ sudo apt-get update &amp;&amp; sudo apt-get install -y nvidia-container-toolkit
$ sudo systemctl restart docker</pre>



<h4 class="wp-block-heading">Test GPU access</h4>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Production-Ready Docker for MLOps: Docker Compose, GPUs, and Ollama" data-enlighter-group="5">$ docker run --gpus all nvidia/cuda:12.3.2-runtime-ubuntu22.04 nvidia-smi</pre>



<p><strong>Note:</strong> GPU examples will fall back to the central processing unit (CPU) if NVIDIA GPU is not available.</p>



<h3 class="wp-block-heading">Validation</h3>



<h4 class="wp-block-heading">Quick Environment Check</h4>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Production-Ready Docker for MLOps: Docker Compose, GPUs, and Ollama" data-enlighter-group="6"># Test Docker functionality
$ docker run hello-world

# Verify Compose V2
$ docker compose version

# Check available resources
$ docker system info</pre>



<p><strong>Ready to start! </strong><strong>All examples include pre-trained models and are ready to run immediately after environment setup</strong><strong>.</strong></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>We first need to review our project directory structure.</p>



<p>Start by accessing this lesson&#8217;s <em><strong>&#8220;Downloads&#8221;</strong></em> section to retrieve the source code and example images.</p>



<p>From there, take a look at the directory 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="Production-Ready Docker for MLOps: Docker Compose, GPUs, and Ollama" data-enlighter-group="7">docker-mlops-production/
├── create_test_model.py           # Creates real MNIST model (96.7% accuracy)
├── requirements.txt               # Dependencies for model creation
├── multi-stage-example/
│   ├── train.py                   # PyTorch Lightning training script
│   ├── inference.py               # FastAPI inference service
│   ├── requirements-train.txt     # Training dependencies (heavy)
│   ├── requirements-infer.txt     # Inference dependencies (minimal)
│   ├── Dockerfile                 # Multi-stage: training → inference
│   └── README.md                  # Usage instructions
├── compose-basic/
│   ├── trainer/
│   │   ├── train.py              # Model training script
│   │   ├── Dockerfile
│   │   └── requirements.txt
│   ├── api/
│   │   ├── inference.py          # Basic FastAPI service
│   │   ├── Dockerfile
│   │   └── requirements.txt
│   ├── artifacts/
│   │   └── model.pth             # Pre-trained MNIST model
│   ├── docker-compose.yml        # Trainer + API orchestration
│   └── test.json                 # Sample test data
├── compose-extended/
│   ├── trainer/                  # Same training setup
│   │   ├── train.py
│   │   ├── Dockerfile
│   │   └── requirements.txt
│   ├── api/
│   │   ├── inference.py          # Enhanced with Redis + Postgres
│   │   ├── Dockerfile
│   │   └── requirements.txt      # + redis, psycopg2-binary
│   ├── artifacts/
│   │   └── model.pth             # Pre-trained MNIST model
│   └── docker-compose.yml        # + Redis + Postgres services
├── gpu-examples/
│   ├── train_gpu.py              # GPU-aware training script
│   ├── Dockerfile.gpu-trainer    # CUDA runtime base image
│   ├── requirements-gpu.txt      # PyTorch with CUDA support
│   ├── docker-compose-gpu.yml    # GPU scheduling examples
│   └── README.md                 # GPU setup guide
├── ollama-llm/
│   ├── api/
│   │   ├── main.py               # LLM API wrapper
│   │   ├── Dockerfile
│   │   └── requirements.txt      # FastAPI + requests
│   ├── docker-compose.yml        # GPU version with Ollama
│   ├── docker-compose-cpu.yml    # CPU version for testing
│   └── README.md                 # LLM model management
├── production-hardened/
│   ├── api.py                    # Security-hardened FastAPI
│   ├── Dockerfile                # Multi-stage + non-root user
│   ├── requirements.txt
│   ├── security-scan.sh          # Vulnerability scanning script
│   ├── SECURITY.md               # Security best practices
│   └── artifacts/
│       ├── .gitkeep
│       └── model.pth             # Pre-trained MNIST model
└── README.md                     # Complete tutorial guide</pre>



<p>Let us break down each folder:</p>



<h3 class="wp-block-heading">multi-stage-example/</h3>



<p>Demonstrates multi-stage Docker builds for lean ML images. Uses real PyTorch Lightning MNIST model (96.7% accuracy). Separates training (2.5 GB) from inference (800 MB) stages, achieving 3x size reduction for production deployment.</p>



<h3 class="wp-block-heading">compose-basic/</h3>



<p>Introduces Docker Compose orchestration through a workflow with a trainer service and an API service. Features real model artifacts shared via volumes, service dependencies with <code data-enlighter-language="python" class="EnlighterJSRAW">depends_on</code>, and tested API endpoints for predictions.</p>



<h3 class="wp-block-heading">compose-extended/</h3>



<p>Adds production infrastructure with Redis caching and PostgreSQL logging. Includes real-world features such as cache hit tracking, prediction analytics via the <code data-enlighter-language="python" class="EnlighterJSRAW">/stats</code> endpoint, and a multi-service architecture validated through testing.</p>



<h3 class="wp-block-heading">gpu-examples/</h3>



<p>Covers GPU acceleration using NVIDIA Container Toolkit. Includes Compute Unified Device Architecture (CUDA) runtime images, GPU scheduling in Compose, and CPU fallback configurations. Structure verified on both GPU and non-GPU systems.</p>



<h3 class="wp-block-heading">ollama-llm/</h3>



<p>Shows Large Language Model containerization with official Ollama Docker image (<code data-enlighter-language="python" class="EnlighterJSRAW">ollama/ollama:latest</code>). Features both GPU and CPU configurations, FastAPI wrapper with health checks, and tested model management via representational state transfer (REST) API.</p>



<h3 class="wp-block-heading">production-hardened/</h3>



<p>Demonstrates security best practices and production hardening. Includes Trivy vulnerability scanning, non-root user configuration, input validation, and real security configurations tested with actual model serving.</p>



<p>Together, these examples guide us through optimization, orchestration, acceleration, modern LLM deployment, and enterprise-grade security in containerized ML workflows.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Multi-Stage-Docker-Builds-for-Smaller-ML-Inference-Images"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Multi-Stage-Docker-Builds-for-Smaller-ML-Inference-Images">Multi-Stage Docker Builds for Smaller ML Inference Images</a></h2>



<p>Naïve Dockerfiles often include training libraries, Jupyter, CUDA, FastAPI, and even datasets in a single image. The result is a container that may work, but it is heavy, slow to rebuild, and full of unnecessary software. In production MLOps, where images are pushed to registries and deployed repeatedly, these inefficiencies add up quickly.</p>



<p><strong>Multi-stage builds</strong> are the solution. They let us define multiple stages in a single <code data-enlighter-language="python" class="EnlighterJSRAW">Dockerfile</code>:</p>



<ul class="wp-block-list">
<li>One stage for building or training (with heavy dependencies).</li>



<li>Another stage for runtime (lightweight, containing only what is needed for inference).</li>
</ul>



<p>By copying only the necessary artifacts (model weights, inference code) from the build stage into the runtime stage, we keep images lean and secure.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://pyimagesearch.com/wp-content/uploads/2026/11/image-53.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="624" height="599" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-53.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-56039"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-53.png?size=126x121&lossy=2&strip=1&webp=1 126w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-53-300x288.png?lossy=2&strip=1&webp=1 300w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-53.png?size=378x363&lossy=2&strip=1&webp=1 378w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-53.png?size=504x484&lossy=2&strip=1&webp=1 504w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-53.png?lossy=2&strip=1&webp=1 624w" sizes="(max-width: 624px) 100vw, 624px" /></a><figcaption class="wp-element-caption"><strong>Figure 4:</strong> A 2-stage Docker build. Heavy training dependencies are handled in Stage 1, with only the final model and inference code copied into a lightweight Stage 2 runtime (source: image by the author).</figcaption></figure></div>


<h3 class="wp-block-heading">Example: From Training to Inference</h3>



<p>Let us say we train a PyTorch model but only need the weights and inference script in production.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Production-Ready Docker for MLOps: Docker Compose, GPUs, and Ollama" data-enlighter-group="8"># Stage 1: Training image
FROM pytorch/pytorch:2.3.1-cuda12.1-cudnn8-runtime AS trainer

WORKDIR /app

# Install training dependencies
COPY requirements-train.txt .
RUN pip install --no-cache-dir -r requirements-train.txt

# Copy training script and run (or in CI/CD)
COPY train.py .
RUN python train.py --epochs 1 --save model.pth

# Stage 2: Inference image
FROM python:3.11-slim

WORKDIR /app

# Install only inference dependencies
COPY requirements-infer.txt .
RUN pip install --no-cache-dir -r requirements-infer.txt

# Copy trained model + inference code from stage 1
COPY --from=trainer /app/model.pth .
COPY inference.py .

# Default command: run the inference service
CMD ["python", "inference.py"]</pre>



<h3 class="wp-block-heading">Why This Works Better</h3>



<ul class="wp-block-list">
<li><strong>Smaller Images:</strong> The runtime image does not include training dependencies (e.g., Jupyter, Matplotlib, or large compilers).</li>



<li><strong>Faster Rebuilds:</strong> Changes to <code data-enlighter-language="python" class="EnlighterJSRAW">inference.py</code> do not invalidate the cached training stage.</li>



<li><strong>More Secure:</strong> Fewer dependencies mean a smaller attack surface.</li>



<li><strong>Separation of Concerns:</strong> Training and inference environments are isolated.</li>
</ul>



<h3 class="wp-block-heading">Best Practices for Multi-Stage Builds in ML</h3>



<ul class="wp-block-list">
<li>Keep training and inference requirements in separate files (<code data-enlighter-language="python" class="EnlighterJSRAW">requirements-train.txt</code>, <code data-enlighter-language="python" class="EnlighterJSRAW">requirements-infer.txt</code>).</li>



<li>Use <strong>CUDA runtime images</strong> for inference rather than full CUDA developer images.</li>



<li>In CI/CD, training often runs in one stage, and only the trained artifacts are copied to the deployable image.</li>



<li>For very large models (e.g., Stable Diffusion, LLMs), save weights to object storage (Amazon Simple Storage Service (Amazon S3), Google Cloud Storage (GCS)) instead of baking them directly into the image.</li>
</ul>



<p>With multi-stage builds, we move from a “kitchen sink” <code data-enlighter-language="python" class="EnlighterJSRAW">Dockerfile</code> to a <strong>production-ready image</strong> that is lean, reproducible, and easy to deploy.</p>



<p>Next, we will use <strong>Docker Compose for ML Workflows</strong> to orchestrate multiple containers (FastAPI, Redis, and Postgres) in a single reproducible pipeline.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Docker-Compose-for-ML-Workflows"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Docker-Compose-for-ML-Workflows">Docker Compose for ML Workflows</a></h2>



<p>In real-world MLOps, a system usually needs more than just a single container. For example, we might train a model in one container, serve it in another, and add supporting services (e.g., a cache (Redis) or database (Postgres)). Managing these one by one with docker run is tedious. <strong>Docker Compose</strong> makes this easy by letting us define all services in a single YAML file.</p>



<p>We will build 2 setups:</p>



<ul class="wp-block-list">
<li><strong>Basic Workflow:</strong> a trainer service and an API service.</li>



<li><strong>Extended Workflow:</strong> add Redis (cache) and Postgres (database).</li>
</ul>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/11/image-54-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="441" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-54-1024x441.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-56042"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-54-1024x441.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-54-1024x441.png?size=126x54&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-54-1024x441.png?size=252x109&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-54-1024x441.png?size=378x163&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-54-1024x441.png?size=504x217&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-54-1024x441.png?size=630x271&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 5:</strong> Trainer and API containers orchestrated with Docker Compose. The trainer saves <code>model.pth</code> in a shared <code>artifacts/</code> directory, and the API container loads it to serve predictions to clients (source: image by the author).</figcaption></figure></div>


<h3 class="wp-block-heading">Step 1: Core ML Workflow (Trainer and API)</h3>



<p>This is the minimal setup: train a model in one container, serve it from another.</p>



<h4 class="wp-block-heading">Project Structure</h4>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Production-Ready Docker for MLOps: Docker Compose, GPUs, and Ollama" data-enlighter-group="9">mnist-compose/
├─ trainer/
│   ├─ train.py
│   ├─ requirements.txt
│   └─ Dockerfile
├─ api/
│   ├─ inference.py
│   ├─ requirements.txt
│   └─ Dockerfile
├─ artifacts/        # shared folder for model.pth
└─ docker-compose.yml</pre>



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">artifacts/</code> <strong>folder</strong> is mounted as a shared volume so the trainer can save the model and the API can load it.</p>



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



<p><code data-enlighter-language="python" class="EnlighterJSRAW">trainer/train.py</code></p>



<p>This script trains a simple PyTorch Lightning model on the Modified National Institute of Standards and Technology (MNIST) dataset and saves the weights.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Production-Ready Docker for MLOps: Docker Compose, GPUs, and Ollama" data-enlighter-group="10">import torch
from torch import nn
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
import pytorch_lightning as pl

class MNISTModel(pl.LightningModule):
    def __init__(self):
        super().__init__()
        self.fc = nn.Sequential(
            nn.Flatten(),
            nn.Linear(28*28, 128), nn.ReLU(),
            nn.Linear(128, 10)
        )

    def forward(self, x): return self.fc(x)

    def training_step(self, batch, _):
        x, y = batch
        loss = nn.functional.cross_entropy(self(x), y)
        self.log("loss", loss, prog_bar=True)
        return loss

    def configure_optimizers(self):
        return torch.optim.Adam(self.parameters(), lr=1e-3)

# Load MNIST
transform = transforms.Compose([transforms.ToTensor()])
train_ds = datasets.MNIST("./data", train=True, download=True, transform=transform)
train_loader = DataLoader(train_ds, batch_size=64, shuffle=True)

# Train for 1 epoch
model = MNISTModel()
trainer = pl.Trainer(max_epochs=1, accelerator="cpu")
trainer.fit(model, train_loader)

# Save model
torch.save(model.state_dict(), "/app/artifacts/model.pth")
print("✅ Model saved to /app/artifacts/model.pth")</pre>



<p>This creates a small neural net, trains for 1 epoch, and saves the weights into the shared <code data-enlighter-language="python" class="EnlighterJSRAW">/app/artifacts</code> directory.</p>



<p><code data-enlighter-language="python" class="EnlighterJSRAW">trainer/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="Production-Ready Docker for MLOps: Docker Compose, GPUs, and Ollama" data-enlighter-group="11">torch==2.3.1
torchvision==0.18.1
pytorch-lightning==2.3.0</pre>



<p><code data-enlighter-language="python" class="EnlighterJSRAW">trainer/Dockerfile</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="Production-Ready Docker for MLOps: Docker Compose, GPUs, and Ollama" data-enlighter-group="12">FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN apt-get update &amp;&amp; apt-get install -y --no-install-recommends ca-certificates \
    &amp;&amp; rm -rf /var/lib/apt/lists/*
RUN pip install --no-cache-dir -r requirements.txt
COPY train.py .
CMD ["python", "train.py"]</pre>



<p><strong>Explanation:</strong> This <code data-enlighter-language="python" class="EnlighterJSRAW">Dockerfile</code> installs dependencies, copies <code data-enlighter-language="python" class="EnlighterJSRAW">train.py</code>, and runs training.</p>



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



<p><code data-enlighter-language="python" class="EnlighterJSRAW">api/inference.py</code></p>



<p>This FastAPI service loads the saved model and provides a <code data-enlighter-language="python" class="EnlighterJSRAW">/predict</code> endpoint.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Production-Ready Docker for MLOps: Docker Compose, GPUs, and Ollama" data-enlighter-group="13">from fastapi import FastAPI, UploadFile, File
import torch
from torch import nn
from torchvision import transforms
from PIL import Image

app = FastAPI()

# Model definition
class MNISTModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.fc = nn.Sequential(
            nn.Flatten(),
            nn.Linear(28*28, 128), nn.ReLU(),
            nn.Linear(128, 10)
        )
    def forward(self, x): return self.fc(x)

# Load trained weights
model = MNISTModel()
model.load_state_dict(torch.load("/app/artifacts/model.pth", map_location="cpu"))
model.eval()

transform = transforms.Compose([transforms.ToTensor()])

@app.post("/predict")
async def predict(file: UploadFile = File(...)):
    image = Image.open(file.file).convert("L").resize((28, 28))
    tensor = transform(image).unsqueeze(0)

    with torch.no_grad():
        output = model(tensor)
        pred = torch.argmax(output, dim=1).item()

    return {"prediction": pred}</pre>



<p><strong>Explanation</strong></p>



<ul class="wp-block-list">
<li>Accepts an uploaded image (28×28 grayscale)</li>



<li>Converts to tensor and runs inference</li>



<li>Returns the predicted digit</li>
</ul>



<p><code data-enlighter-language="python" class="EnlighterJSRAW">api/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="Production-Ready Docker for MLOps: Docker Compose, GPUs, and Ollama" data-enlighter-group="14">torch==2.3.1
torchvision==0.18.1
fastapi==0.111.0
uvicorn==0.30.0
pillow==10.4.0</pre>



<p><code data-enlighter-language="python" class="EnlighterJSRAW">api/Dockerfile</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="Production-Ready Docker for MLOps: Docker Compose, GPUs, and Ollama" data-enlighter-group="15">FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY inference.py .
CMD ["uvicorn", "inference:app", "--host", "0.0.0.0", "--port", "8000"]</pre>



<h4 class="wp-block-heading">Compose File (Basic)</h4>



<p><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="Production-Ready Docker for MLOps: Docker Compose, GPUs, and Ollama" data-enlighter-group="16">version: "3.9"

services:
  trainer:
    build: ./trainer
    volumes:
      - ./artifacts:/app/artifacts

  api:
    build: ./api
    ports:
      - "8000:8000"
    volumes:
      - ./artifacts:/app/artifacts
    depends_on:
      - trainer</pre>



<p><strong>Explanation</strong></p>



<ul class="wp-block-list">
<li>Both services share the <code data-enlighter-language="python" class="EnlighterJSRAW">artifacts/</code> directory.</li>



<li>The trainer saves the model there.</li>



<li>The API loads it and starts serving at port 8000.</li>
</ul>



<p>Run with:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Production-Ready Docker for MLOps: Docker Compose, GPUs, and Ollama" data-enlighter-group="17">docker-compose up --build</pre>



<h3 class="wp-block-heading">Step 2: Extended Workflow (Add Redis and Postgres)</h3>



<p>In production, we often want <strong>caching</strong> and <strong>logging</strong>:</p>



<ul class="wp-block-list">
<li><strong>Redis:</strong> Store the last prediction so repeated requests can return instantly.</li>



<li><strong>Postgres:</strong> Log predictions into a database.</li>
</ul>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/11/image-55-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="270" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-55-1024x270.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-56046"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-55-1024x270.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-55-1024x270.png?size=126x33&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-55-1024x270.png?size=252x66&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-55-1024x270.png?size=378x100&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-55-1024x270.png?size=504x133&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-55-1024x270.png?size=630x166&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 6:</strong> High-level flow of the extended ML API. The API checks Redis for cached predictions, retrieves cached results when available, and logs new predictions to Postgres for persistence and analytics (source: image by the author).</figcaption></figure></div>


<h4 class="wp-block-heading">Extended API with Cache and DB</h4>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Production-Ready Docker for MLOps: Docker Compose, GPUs, and Ollama" data-enlighter-group="18">from fastapi import FastAPI, UploadFile, File
import torch
from torch import nn
from torchvision import transforms
from PIL import Image
import redis, psycopg2, os, io

app = FastAPI()

# Model
class MNISTModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.fc = nn.Sequential(
            nn.Flatten(),
            nn.Linear(28*28, 128), nn.ReLU(),
            nn.Linear(128, 10)
        )
    def forward(self, x): return self.fc(x)

model = MNISTModel()
model.load_state_dict(torch.load("/app/artifacts/model.pth", map_location="cpu"))
model.eval()
transform = transforms.Compose([transforms.ToTensor()])

# Redis client
r = redis.Redis(host=os.getenv("REDIS_HOST", "localhost"), port=6379)

# Postgres client
conn = psycopg2.connect(
    host=os.getenv("DB_HOST", "localhost"),
    database=os.getenv("DB_NAME", "mlops"),
    user=os.getenv("DB_USER", "user"),
    password=os.getenv("DB_PASS", "pass")
)
cursor = conn.cursor()

@app.post("/predict")
async def predict(file: UploadFile = File(...)):
    image_bytes = await file.read()
    cache_key = f"prediction:{hash(image_bytes)}"

    # 1. Try cache first
    if r.get(cache_key):
        return {"prediction": int(r.get(cache_key)), "source": "cache"}

    # 2. Otherwise run inference
    image = Image.open(io.BytesIO(image_bytes)).convert("L").resize((28, 28))
    tensor = transform(image).unsqueeze(0)
    with torch.no_grad():
        output = model(tensor)
        pred = torch.argmax(output, dim=1).item()

    # 3. Store in cache + DB
    r.set(cache_key, pred)
    cursor.execute("INSERT INTO predictions (result) VALUES (%s);", (pred,))
    conn.commit()

    return {"prediction": pred, "source": "model"}</pre>



<p><strong>Explanation</strong></p>



<ul class="wp-block-list">
<li><strong>Cache logic:</strong> each request is hashed; if the same image is sent again, the result is returned instantly from Redis.</li>



<li><strong>DB</strong><strong> (database)</strong><strong> logic:</strong> every new prediction is logged to Postgres.</li>
</ul>



<h4 class="wp-block-heading">Extended Requirements</h4>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Production-Ready Docker for MLOps: Docker Compose, GPUs, and Ollama" data-enlighter-group="19">torch==2.3.1
torchvision==0.18.1
fastapi==0.111.0
uvicorn==0.30.0
pillow==10.4.0
redis==5.0.1
psycopg2-binary==2.9.9</pre>



<h4 class="wp-block-heading">Extended Compose File</h4>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Production-Ready Docker for MLOps: Docker Compose, GPUs, and Ollama" data-enlighter-group="20">version: "3.9"

services:
  trainer:
    build: ./trainer
    volumes:
      - ./artifacts:/app/artifacts

  api:
    build: ./api
    ports:
      - "8000:8000"
    volumes:
      - ./artifacts:/app/artifacts
    depends_on:
      - trainer
      - redis
      - db
    environment:
      - REDIS_HOST=redis
      - DB_HOST=db
      - DB_USER=user
      - DB_PASS=pass
      - DB_NAME=mlops

  redis:
    image: redis:7.2
    ports:
      - "6379:6379"

  db:
    image: postgres:15
    environment:
      POSTGRES_USER: user
      POSTGRES_PASSWORD: pass
      POSTGRES_DB: mlops
    ports:
      - "5432:5432"</pre>



<h3 class="wp-block-heading">Why This Matters</h3>



<ul class="wp-block-list">
<li><strong>The b</strong><strong>asic version</strong> shows how to link the trainer and API with volumes.</li>



<li><strong>The extended version</strong> shows how Compose orchestrates heterogeneous services (a cache and a DB).</li>



<li>The caching logic speeds up repeated requests; the database keeps an audit log of predictions.</li>



<li>This mirrors how ML APIs are deployed in production: training, serving, caching, and persistence all wired together.</li>
</ul>



<p>Next up, we will add <strong>GPU support</strong> so training and inference containers can use NVIDIA hardware.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-GPU-Support-in-Docker-and-Docker-Compose"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-GPU-Support-in-Docker-and-Docker-Compose">GPU Support in Docker and Docker Compose</a></h2>



<p>Deep learning thrives on GPUs. Without GPU acceleration, training can be slow and inference for large models (e.g., LLMs and Stable Diffusion) can be impractical. Docker now provides first-class GPU support, but the way we enable it has changed over the years.</p>



<h3 class="wp-block-heading">From nvidia-docker2 to NVIDIA Container Toolkit</h3>



<ul class="wp-block-list">
<li><strong>Legacy</strong><strong> approach (pre-2020):</strong> We had to install <code data-enlighter-language="python" class="EnlighterJSRAW">nvidia-docker2</code>.</li>



<li><strong>Modern approach:</strong> We install the <strong>NVIDIA Container Toolkit</strong>, which integrates directly with Docker and Docker Compose.</li>
</ul>



<p>Once installed, we can expose GPUs to containers with a single flag.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://pyimagesearch.com/wp-content/uploads/2026/11/image-56.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="624" height="307" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-56.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-56049"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-56.png?size=126x62&lossy=2&strip=1&webp=1 126w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-56-300x148.png?lossy=2&strip=1&webp=1 300w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-56.png?size=378x186&lossy=2&strip=1&webp=1 378w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-56.png?size=504x248&lossy=2&strip=1&webp=1 504w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-56.png?lossy=2&strip=1&webp=1 624w" sizes="(max-width: 624px) 100vw, 624px" /></a><figcaption class="wp-element-caption"><strong>Figure 7:</strong> GPU allocation in Docker Compose showing how different services can reserve all GPUs, share GPUs, or pin to specific devices for predictable performance (source: image by the author).</figcaption></figure></div>


<h3 class="wp-block-heading">Running a GPU-Enabled Container</h3>



<p>We verify GPU access by running:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Production-Ready Docker for MLOps: Docker Compose, GPUs, and Ollama" data-enlighter-group="21">docker run --gpus all nvidia/cuda:12.3.2-runtime-ubuntu22.04 nvidia-smi</pre>



<ul class="wp-block-list">
<li><code data-enlighter-language="python" class="EnlighterJSRAW">--gpus all</code>: expose all GPUs.</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">nvidia/cuda:12.3.2-runtime-ubuntu22.04</code>: official NVIDIA CUDA runtime image.</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">nvidia-smi</code>: lists the GPUs visible inside the container.</li>
</ul>



<p>If we see the familiar GPU table, our setup is working.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/11/image-57-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="960" height="1024" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-57-960x1024.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-56052"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-57-960x1024.png?lossy=2&strip=1&webp=1 960w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-57-960x1024.png?size=126x134&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-57-960x1024.png?size=252x269&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-57-960x1024.png?size=378x403&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-57-960x1024.png?size=504x538&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-57-960x1024.png?size=630x672&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 960px) 100vw, 960px" /></a><figcaption class="wp-element-caption"><strong>Figure 8:</strong> Validating GPU access inside a Docker container using <code>nvidia-smi</code>. If we see a GPU table like this showing device names, CUDA version, and memory usage our NVIDIA Container Toolkit is correctly configured (source: image by the author).</figcaption></figure></div>


<h3 class="wp-block-heading">GPU Support in Docker Compose</h3>



<p>Compose lets us control GPU scheduling with the <code data-enlighter-language="python" class="EnlighterJSRAW">deploy.resources.reservations.devices</code> block.</p>



<h4 class="wp-block-heading">Example 1: Give All GPUs to Trainer</h4>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Production-Ready Docker for MLOps: Docker Compose, GPUs, and Ollama" data-enlighter-group="22">services:
  trainer:
    build: ./trainer
    deploy:
      resources:
        reservations:
          devices:
            - driver: nvidia
              count: all
              capabilities: [gpu]</pre>



<p>The trainer sees every GPU on the host.</p>



<h4 class="wp-block-heading">Example 2: Restrict Inference API to One GPU</h4>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Production-Ready Docker for MLOps: Docker Compose, GPUs, and Ollama" data-enlighter-group="23">services:
  api:
    build: ./api
    deploy:
      resources:
        reservations:
          devices:
            - driver: nvidia
              count: 1
              capabilities: [gpu]</pre>



<p>The inference API container will only see one GPU even if more are available.</p>



<h4 class="wp-block-heading">Example 3: Pin to a Specific GPU</h4>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Production-Ready Docker for MLOps: Docker Compose, GPUs, and Ollama" data-enlighter-group="24">services:
  api:
    build: ./api
    deploy:
      resources:
        reservations:
          devices:
            - driver: nvidia
              device_ids: ["0"]
              capabilities: [gpu]</pre>



<p>This pins the service to GPU 0 only. This is useful when separating training and inference workloads.</p>



<h3 class="wp-block-heading">Updating the Trainer for GPU Training</h3>



<p>By default, our trainer used a <strong>CPU-only base image</strong>. To train on GPU:</p>



<p><strong>Change the base image in </strong><code data-enlighter-language="python" class="EnlighterJSRAW">trainer/Dockerfile</code><strong>:</strong></p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Production-Ready Docker for MLOps: Docker Compose, GPUs, and Ollama" data-enlighter-group="25">FROM nvidia/cuda:12.3.2-runtime-ubuntu22.04
WORKDIR /app
COPY requirements.txt .
RUN apt-get update &amp;&amp; apt-get install -y --no-install-recommends python3 python3-pip ca-certificates \
    &amp;&amp; rm -rf /var/lib/apt/lists/*
RUN pip install --no-cache-dir -r requirements.txt
COPY train.py .
CMD ["python3", "train.py"]</pre>



<p><strong>Update the Lightning trainer in </strong><code data-enlighter-language="python" class="EnlighterJSRAW">train.py</code><strong>:</strong></p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Production-Ready Docker for MLOps: Docker Compose, GPUs, and Ollama" data-enlighter-group="26">trainer = pl.Trainer(max_epochs=1, accelerator="gpu", devices=1)</pre>



<p>Now, when Compose schedules GPUs for the trainer, PyTorch Lightning will use them.</p>



<h3 class="wp-block-heading">GPU Container Best Practices</h3>



<ul class="wp-block-list">
<li><strong>Use runtime images</strong> (<code data-enlighter-language="python" class="EnlighterJSRAW">nvidia/cuda:xx-runtime</code>) for serving to reduce image size and shorten pull times.</li>



<li><strong>Pin CUDA and PyTorch versions</strong> for reproducibility.</li>



<li><strong>Test with</strong> <code data-enlighter-language="python" class="EnlighterJSRAW">nvidia-smi</code> inside containers to confirm GPU access.</li>



<li><strong>Isolate GPUs</strong> for different services in Compose for predictable performance.</li>



<li><strong>Do not bake weights into images</strong><strong>.</strong> Store them in shared volumes or Amazon S3.</li>
</ul>



<p>With GPU support enabled, our ML pipelines can train faster and serve models efficiently.</p>



<p>Next, we will explore <strong>Docker for LLM Workloads (Ollama)</strong> and learn how to containerize large language models for reproducible, portable deployment.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-How-to-Run-Ollama-in-Docker-for-Local-LLM-Inference"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-How-to-Run-Ollama-in-Docker-for-Local-LLM-Inference">How to Run Ollama in Docker for Local LLM Inference</a></h2>



<p>So far, we have containerized training jobs and ML APIs. But what about <strong>large language models (LLMs)</strong> such as Llama, Mistral, or Gemma? These models are heavy, depend on GPU acceleration, and have complex serving environments. That is where <strong>Ollama</strong> comes in.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/11/image-58-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="480" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-58-1024x480.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-56055"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-58-1024x480.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-58-1024x480.png?size=126x59&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-58-1024x480.png?size=252x118&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-58-1024x480.png?size=378x177&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-58-1024x480.png?size=504x236&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-58-1024x480.png?size=630x295&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 9:</strong> How Ollama runs inside a Docker container, exposing a REST API that optional FastAPI wrapper services can call before returning responses to users (source: image by the author).</figcaption></figure></div>


<h3 class="wp-block-heading">What Is Ollama?</h3>



<p>Ollama is a lightweight runtime that lets us run open-source LLMs locally with a simple command 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="Production-Ready Docker for MLOps: Docker Compose, GPUs, and Ollama" data-enlighter-group="27">ollama run llama2</pre>



<p>It handles model downloads, GPU usage, and inference behind the scenes.</p>



<p>Ollama has gained widespread adoption because:</p>



<ul class="wp-block-list">
<li>It works across macOS, Linux, and Docker.</li>



<li>It supports many community models (e.g., Llama, Mistral, Gemma, and Code Llama).</li>



<li>It integrates well with developer workflows (REST API, Compose, Kubernetes (k8s)).</li>
</ul>



<h3 class="wp-block-heading">Running Ollama in Docker</h3>



<p>The Ollama team now publishes official Docker images, which makes running models in containers trivial.</p>



<h4 class="wp-block-heading">Example: Start an Ollama Container</h4>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Production-Ready Docker for MLOps: Docker Compose, GPUs, and Ollama" data-enlighter-group="28">docker run -d \
  --name ollama \
  -p 11434:11434 \
  ollama/ollama:latest</pre>



<ul class="wp-block-list">
<li>Runs Ollama as a container</li>



<li>Exposes a REST API at <code data-enlighter-language="python" class="EnlighterJSRAW">http://localhost:11434</code></li>



<li>We can now interact with it like any ML API</li>
</ul>



<p>Test with:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Production-Ready Docker for MLOps: Docker Compose, GPUs, and Ollama" data-enlighter-group="29">curl http://localhost:11434/api/generate -d '{
  "model": "llama2",
  "prompt": "Hello, world!"
}'</pre>



<p>The commands below confirm that our Ollama Docker container is alive and responding:</p>



<ul class="wp-block-list">
<li><code data-enlighter-language="python" class="EnlighterJSRAW">docker run</code> starts the Ollama service and exposes port 11434.</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">docker ps</code> shows the container running with the correct startup command (<code data-enlighter-language="python" class="EnlighterJSRAW">/bin/ollama serve</code>).</li>



<li>The <code data-enlighter-language="python" class="EnlighterJSRAW">curl</code> request to <code data-enlighter-language="python" class="EnlighterJSRAW">/api/generate</code> returns an error and that is expected.</li>
</ul>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/11/image-59-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="302" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-59-1024x302.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-56058"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-59-1024x302.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-59-1024x302.png?size=126x37&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-59-1024x302.png?size=252x74&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-59-1024x302.png?size=378x111&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-59-1024x302.png?size=504x149&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-59-1024x302.png?size=630x186&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 10:</strong> Verifying that the Ollama container is running and responding to API requests. The error (<code>"model 'llama2' not found"</code>) is expected. The container is working, but the model must be pulled before generation can begin (source: image by the author).</figcaption></figure></div>


<h3 class="wp-block-heading">Using Docker Compose for Ollama</h3>



<p>We can integrate Ollama into a multi-service workflow using Compose just as we did with the trainer and API services.</p>



<p><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="Production-Ready Docker for MLOps: Docker Compose, GPUs, and Ollama" data-enlighter-group="30">version: "3.9"

services:
  ollama:
    image: ollama/ollama:latest
    ports:
      - "11434:11434"
    volumes:
      - ollama-models:/root/.ollama   # cache models locally
    deploy:
      resources:
        reservations:
          devices:
            - driver: nvidia
              count: all
              capabilities: [gpu]

volumes:
  ollama-models:</pre>



<p><strong>Explanation</strong></p>



<ul class="wp-block-list">
<li>Models are cached in a volume so we do not re-download every run.</li>



<li>GPU access is reserved using the same syntax as in the GPU Support section above.</li>



<li>Other services (e.g., FastAPI) can talk to Ollama via REST calls.</li>
</ul>



<h3 class="wp-block-heading">Extending with Our Own API</h3>



<p>Typically, we do not expose Ollama directly to users. Instead, we wrap it in an API layer (FastAPI, Flask) and add business logic, logging, or retrieval-augmented generation (RAG) pipelines.</p>



<p>Example service talking to Ollama:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Production-Ready Docker for MLOps: Docker Compose, GPUs, and Ollama" data-enlighter-group="31">from fastapi import FastAPI
import requests

app = FastAPI()

OLLAMA_URL = "http://ollama:11434/api/generate"

@app.get("/chat")
def chat(prompt: str):
    response = requests.post(OLLAMA_URL, json={"model": "llama2", "prompt": prompt})
    return response.json()</pre>



<p>When run inside Compose, this service (<code data-enlighter-language="python" class="EnlighterJSRAW">api</code>) would connect to the <code data-enlighter-language="python" class="EnlighterJSRAW">ollama</code> service by name.</p>



<h3 class="wp-block-heading">Why Ollama in Docker Matters for MLOps</h3>



<ul class="wp-block-list">
<li><strong>Reproducibility:</strong> Freeze LLM environments just like any ML pipeline.</li>



<li><strong>Portability:</strong> Deploy the same setup locally, on servers, or in Kubernetes.</li>



<li><strong>Flexibility:</strong> Swap models (Mistral, Llama, Gemma) without changing code.</li>



<li><strong>Integration:</strong> Combine with RAG systems, databases, or agent frameworks in Compose.</li>
</ul>



<p>With Ollama and Docker, running LLMs is as easy as spinning up a container and pulling a model.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Docker-Security-Best-Practices-for-Production-ML-Images"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Docker-Security-Best-Practices-for-Production-ML-Images">Docker Security Best Practices for Production ML Images</a></h2>



<p>When we are experimenting locally, a slightly bloated Docker image is not a big deal. But in production MLOps pipelines that may run dozens of containers across clusters, <strong>image size, rebuild speed, and security vulnerabilities</strong> can make or break our deployment.</p>



<p>This section covers the best practices for building <strong>leaner, faster, safer ML images</strong>.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://pyimagesearch.com/wp-content/uploads/2026/11/image-60.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="930" height="988" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-60.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-56064"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-60.png?size=126x134&lossy=2&strip=1&webp=1 126w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-60-282x300.png?lossy=2&strip=1&webp=1 282w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-60.png?size=378x402&lossy=2&strip=1&webp=1 378w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-60.png?size=504x535&lossy=2&strip=1&webp=1 504w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-60.png?size=630x669&lossy=2&strip=1&webp=1 630w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-60-768x816.png?lossy=2&strip=1&webp=1 768w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-60.png?lossy=2&strip=1&webp=1 930w" sizes="(max-width: 930px) 100vw, 930px" /></a><figcaption class="wp-element-caption"><strong>Figure 11:</strong> The 5 production Docker practices shown are slim base images, multi-stage builds, pinned dependencies, non-root execution, and automated vulnerability scanning (source: image by the author).</figcaption></figure></div>


<h3 class="wp-block-heading">Minimize Image Size</h3>



<ul class="wp-block-list">
<li><strong>Use slim</strong><strong> or </strong><strong>distroless images</strong>
<ul class="wp-block-list">
<li>Start from <code data-enlighter-language="python" class="EnlighterJSRAW">python:3.11-slim</code> or <code data-enlighter-language="python" class="EnlighterJSRAW">gcr.io/distroless/python3</code>.</li>



<li>These strip out unnecessary system packages and reduce attack surface.</li>
</ul>
</li>



<li><strong>Multi-stage builds</strong>
<ul class="wp-block-list">
<li>Keep training dependencies (e.g., Jupyter and PyTorch Lightning) in one stage.</li>



<li>Copy only the trained model and serving code into a slim runtime stage.</li>



<li>For example, train in <code data-enlighter-language="python" class="EnlighterJSRAW">pytorch/pytorch</code> and serve the model in <code data-enlighter-language="python" class="EnlighterJSRAW">python:3.11-slim</code>.</li>
</ul>
</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">.dockerignore</code>
<ul class="wp-block-list">
<li>Prevent copying large local datasets or <code data-enlighter-language="python" class="EnlighterJSRAW">__pycache__</code> folders into images.</li>
</ul>
</li>
</ul>



<h3 class="wp-block-heading">Layer Caching and Reproducibility</h3>



<ul class="wp-block-list">
<li><strong>Order our </strong><code data-enlighter-language="python" class="EnlighterJSRAW">Dockerfile</code><strong> smartly</strong>
<ul class="wp-block-list">
<li>Place <code data-enlighter-language="python" class="EnlighterJSRAW">COPY requirements.txt .</code> and <code data-enlighter-language="python" class="EnlighterJSRAW">RUN pip install</code> <strong>before</strong> copying source code.</li>



<li>This way, Docker reuses the cached layer if requirements do not change.</li>
</ul>
</li>



<li><strong>Pin dependencies</strong>
<ul class="wp-block-list">
<li>Use exact versions (<code data-enlighter-language="python" class="EnlighterJSRAW">torch==2.3.1</code> not <code data-enlighter-language="python" class="EnlighterJSRAW">torch&gt;=2.0</code>) to ensure deterministic builds.</li>
</ul>
</li>
</ul>



<h3 class="wp-block-heading">Security Scanning Tools</h3>



<p>Container security is a must-have now.</p>



<ul class="wp-block-list">
<li><strong>Trivy:</strong> open-source vulnerability scanner (<code data-enlighter-language="python" class="EnlighterJSRAW">trivy image my-ml-app</code>).</li>



<li><strong>Snyk Container:</strong> commercial option with CI/CD integration.</li>



<li><strong>Docker Scout:</strong> built into Docker Desktop, scans for CVEs.</li>
</ul>



<p>Run these in our CI/CD pipeline to catch known vulnerabilities before deploying.</p>



<h3 class="wp-block-heading">Run as Non-Root</h3>



<p>By default, Docker containers often run as root. For ML services exposed to the internet, that is risky.</p>



<p>In our <code data-enlighter-language="python" class="EnlighterJSRAW">Dockerfile</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="Production-Ready Docker for MLOps: Docker Compose, GPUs, and Ollama" data-enlighter-group="32">RUN useradd -m mluser
USER mluser</pre>



<p>This ensures the process runs with restricted privileges.</p>



<h3 class="wp-block-heading">Graceful Shutdowns</h3>



<p>Training or inference jobs may take time to exit. If our container is killed abruptly, we might lose checkpoints.</p>



<ul class="wp-block-list">
<li>Use <code data-enlighter-language="python" class="EnlighterJSRAW">ENTRYPOINT ["python", "app.py"]</code> instead of <code data-enlighter-language="python" class="EnlighterJSRAW">CMD "python app.py"</code> (exec form handles signals better).</li>



<li>Add a <code data-enlighter-language="python" class="EnlighterJSRAW">STOPSIGNAL SIGTERM</code> line to our <code data-enlighter-language="python" class="EnlighterJSRAW">Dockerfile</code> so containers shut down gracefully.</li>
</ul>



<h3 class="wp-block-heading">Best Practices Recap</h3>



<ul class="wp-block-list">
<li>Start with <strong>small base images</strong>.</li>



<li>Use <strong>multi-stage builds</strong> for separating training vs serving.</li>



<li>Pin dependencies, leverage caching.</li>



<li><strong>Scan images</strong> for vulnerabilities.</li>



<li>Drop root privileges.</li>



<li>Handle <strong>graceful shutdowns</strong> to prevent model and data loss.</li>
</ul>



<p>With these optimizations, our ML images are not only lighter and faster but also safer for production environments.</p>



<p>Next, we will tie this into <strong>CI/CD pipelines</strong>, where these practices become automated in our build and deployment workflows.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-How-to-Push-ML-Images-to-Docker-Hub-and-GitHub-Container-Registry"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-How-to-Push-ML-Images-to-Docker-Hub-and-GitHub-Container-Registry">How to Push ML Images to Docker Hub and GitHub Container Registry</a></h2>



<p>So far, we have been building Docker images locally. But in production, those images need to be stored in a <strong>registry</strong> so they can be pulled by Amazon ECS or by Kubernetes clusters such as those managed by Amazon Elastic Kubernetes Service (Amazon EKS).</p>



<h3 class="wp-block-heading">Choosing a Registry</h3>



<ul class="wp-block-list">
<li><strong>Docker Hub:</strong> most common, public and private repos</li>



<li><strong>GitHub Container Registry (GHCR)</strong><strong>:</strong> integrates with our GitHub repos</li>



<li><strong>Amazon </strong><strong>Elastic Container Registry</strong><strong> (Amazon ECR)</strong><strong>,</strong> <strong>Google Cloud</strong><strong> Artifact Registry</strong><strong>, or</strong><strong> Azure</strong><strong> Container Registry (</strong><strong>ACR</strong><strong>)</strong><strong>:</strong> best if we are tied to a specific cloud</li>
</ul>



<p>For this course, Docker Hub and GHCR are enough to demonstrate the idea.</p>



<h3 class="wp-block-heading">Tagging Our Image</h3>



<p>Always tag the images before pushing:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Production-Ready Docker for MLOps: Docker Compose, GPUs, and Ollama" data-enlighter-group="33">docker build -t my-ml-api .
docker tag my-ml-api:latest mydockerhubuser/my-ml-api:v1.0.0</pre>



<p>Use <strong>semantic versions</strong> (v1.0.0, v1.1.0).</p>



<ul class="wp-block-list">
<li>Optionally keep a latest tag for the most recent stable build.</li>
</ul>



<h3 class="wp-block-heading">Pushing to Docker Hub</h3>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Production-Ready Docker for MLOps: Docker Compose, GPUs, and Ollama" data-enlighter-group="34">docker login
docker push mydockerhubuser/my-ml-api:v1.0.0</pre>



<h3 class="wp-block-heading">Pushing to GitHub Container Registry (GHCR)</h3>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Production-Ready Docker for MLOps: Docker Compose, GPUs, and Ollama" data-enlighter-group="35"># Authenticate (use a GitHub Personal Access Token)
echo $CR_PAT | docker login ghcr.io -u USERNAME --password-stdin

docker tag my-ml-api:latest ghcr.io/my-org/my-ml-api:v1.0.0
docker push ghcr.io/my-org/my-ml-api:v1.0.0</pre>



<h3 class="wp-block-heading">Why This Matters</h3>



<ul class="wp-block-list">
<li><strong>ECS, EKS, Lambda, and KServe all pull from registries.</strong></li>



<li>Without this step, the images stay stuck on our laptop.</li>



<li>Registries are the “distribution system” for MLOps.</li>
</ul>



<p>That is all we need at this stage: build locally → tag → push.</p>



<p>We will revisit this later in the <strong>Pipelines </strong><strong>and</strong><strong> CI/CD</strong> module to show how registries fit into automated build pipelines with GitHub Actions, Argo CD, and vulnerability scanning.</p>



<p>Next, we will wrap up <strong>Production-Ready </strong><strong>Docker for MLOps</strong> with a <strong>mini-project</strong> that ties everything together: multi-stage builds, Compose orchestration, GPU support, security checks, and pushing to a registry.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Production-Checklist-Hardening-Our-ML-Images"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Production-Checklist-Hardening-Our-ML-Images">Production Checklist: Hardening Our ML Images</a></h2>



<p>By now, we have learned how to build Docker images, orchestrate them with Compose, enable GPUs, optimize layers, and push them to registries. To wrap up this module, let us apply those lessons in a <strong>hands-on hardening exercise</strong> that makes our ML API production-ready.</p>



<h3 class="wp-block-heading">Step 1: Multi-Stage Build</h3>



<p>Refactor our <code data-enlighter-language="python" class="EnlighterJSRAW">api/Dockerfile</code> into 2 stages:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Production-Ready Docker for MLOps: Docker Compose, GPUs, and Ollama" data-enlighter-group="36"># Stage 1: Build dependencies
FROM python:3.11-slim AS builder
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir --prefix=/install -r requirements.txt

# Stage 2: Runtime
FROM python:3.11-slim
WORKDIR /app
COPY --from=builder /install /usr/local
COPY inference.py .
USER 1000
CMD ["uvicorn", "inference:app", "--host", "0.0.0.0", "--port", "8000"]</pre>



<p><strong>Result: </strong>much smaller, faster image.</p>



<h3 class="wp-block-heading">Step 2: Run as Non-Root</h3>



<p>Notice the line:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Production-Ready Docker for MLOps: Docker Compose, GPUs, and Ollama" data-enlighter-group="37">USER 1000</pre>



<p>This ensures the container runs as a non-root user for security.</p>



<h3 class="wp-block-heading">Step 3: Scan for Vulnerabilities</h3>



<p>Use <strong>Trivy</strong> to scan our image 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="Production-Ready Docker for MLOps: Docker Compose, GPUs, and Ollama" data-enlighter-group="38">trivy image my-ml-api:latest</pre>



<p>We will see Common Vulnerabilities and Exposures (CVE) reports. Fix them by upgrading base images or dependencies.</p>



<h3 class="wp-block-heading">Step 4: Push to Registry</h3>



<p>Tag and push to Docker Hub (or GHCR):</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Production-Ready Docker for MLOps: Docker Compose, GPUs, and Ollama" data-enlighter-group="39">docker tag my-ml-api:latest mydockerhubuser/my-ml-api:v1.0.0
docker push mydockerhubuser/my-ml-api:v1.0.0</pre>



<p>Now our production-ready ML API is stored in a registry.</p>



<h3 class="wp-block-heading">Step 5: Test with Compose (Optional GPU)</h3>



<p>Update <code data-enlighter-language="python" class="EnlighterJSRAW">docker-compose.yml</code> with GPU scheduling:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="yaml" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Production-Ready Docker for MLOps: Docker Compose, GPUs, and Ollama" data-enlighter-group="40">services:
  api:
    image: mydockerhubuser/my-ml-api:v1.0.0
    ports:
      - "8000:8000"
    deploy:
      resources:
        reservations:
          devices:
            - driver: nvidia
              count: 1
              capabilities: [gpu]</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="Production-Ready Docker for MLOps: Docker Compose, GPUs, and Ollama" data-enlighter-group="41">docker-compose up</pre>



<p>Our API is now running in a production-like environment with GPU support if available.</p>



<h3 class="wp-block-heading">Why This Matters</h3>



<p>This checklist turns our <strong>dev-ready ML API</strong> into a <strong>production-hardened service</strong>:</p>



<ul class="wp-block-list">
<li>Smaller, faster builds.</li>



<li>Secure (non-root + scanned).</li>



<li>Portable (pushed to a registry).</li>



<li>GPU-enabled when needed.</li>
</ul>



<p>With this, we have completed <strong>Production-Ready </strong><strong>Docker for MLOps</strong>.</p>



<p>Next, we will look <strong>b</strong><strong>eyond Compose</strong> to see how Docker Swarm scales containers and why most teams move on to Kubernetes.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Scaling-ML-Workloads-Beyond-Docker-Compose-with-Swarm-and-Kubernetes"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Scaling-ML-Workloads-Beyond-Docker-Compose-with-Swarm-and-Kubernetes">Scaling ML Workloads Beyond Docker Compose with Swarm and Kubernetes</a></h2>



<p>Docker Compose is great for development and small-scale ML workflows, but it has limits. Once we move to production, we will need ways to scale services across multiple machines and manage them like a cluster. That is where <strong>Docker Swarm and</strong>, more commonly today, <strong>Kubernetes</strong> come in.</p>



<h3 class="wp-block-heading">Why Compose Is Not Enough</h3>



<ul class="wp-block-list">
<li>Compose runs on a <strong>single host</strong>.</li>



<li>Scaling is manual: <code data-enlighter-language="python" class="EnlighterJSRAW">docker-compose up --scale api=3</code>.</li>



<li>No built-in load balancing or self-healing (if a container dies, it stays dead).</li>



<li>Limited role-based access or fine-grained resource management.</li>
</ul>



<p>For real production MLOps systems, these gaps matter.</p>



<h3 class="wp-block-heading">Docker Swarm: The Step Between Compose and Kubernetes</h3>



<p>Swarm is Docker’s built-in clustering solution:</p>



<ul class="wp-block-list">
<li>Let us create a <strong>Swarm cluster</strong> (multiple Docker hosts joined together).</li>



<li>We can deploy Compose files almost unchanged, with scaling built in.</li>



<li>Provides simple <strong>load balancing</strong> and <strong>service discovery</strong>.</li>
</ul>



<p><strong>Example:</strong> scale our API service across 3 nodes:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Production-Ready Docker for MLOps: Docker Compose, GPUs, and Ollama" data-enlighter-group="42">docker service create --name api --replicas 3 my-ml-api:latest</pre>



<p>Swarm automatically distributes containers across available nodes.</p>



<h3 class="wp-block-heading">Why Most Teams Skip Straight to Kubernetes</h3>



<p>In practice, <strong>Swarm is rarely used in production</strong> for ML. Most companies choose Kubernetes, either on-premises or through a managed service (e.g., Amazon EKS, Google Kubernetes Engine (GKE), or Azure Kubernetes Service (AKS)). Why?</p>



<ul class="wp-block-list">
<li><strong>Ecosystem:</strong> Kubernetes has richer support for ML workloads (KServe, Kubeflow, Ray).</li>



<li><strong>Autoscaling:</strong> Built-in scaling policies for CPUs, GPUs, and queues.</li>



<li><strong>Observability:</strong> Integrates with Prometheus, Grafana, and tracing tools.</li>



<li><strong>GitOps:</strong> Tools (e.g., Argo CD) make deployment pipelines repeatable and secure.</li>
</ul>



<p>Still, it is worth knowing Swarm exists. It shows the natural evolution from Compose → clustering → Kubernetes.</p>



<h3 class="wp-block-heading">How This Fits Into MLOps</h3>



<p>Think of it as 3 levels of maturity:</p>



<ul class="wp-block-list">
<li><strong>Compose (</strong><strong>local development</strong><strong>):</strong> great for prototyping ML systems.</li>



<li><strong>Swarm (small clusters):</strong> rarely used today, but easy migration path.</li>



<li><strong>Kubernetes (cloud-native):</strong> the industry standard for scaling ML workloads.</li>
</ul>



<p>With this, we have completed <strong>Production-Ready Docker for MLOps</strong>:</p>



<ul class="wp-block-list">
<li>From single-container basics → Compose orchestration → GPU → Ollama → optimization → registries → production checklist → scaling beyond Compose.</li>



<li>We are now ready to enter the <strong>Kubernetes module</strong>, where we will learn how to scale ML workloads in the real world.</li>
</ul>



<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 of on-demand code walkthrough videos • Last updated: November 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</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 module, we moved beyond Docker basics and learned how to use containers in production-ready ML workflows. We began by exploring Docker Compose to orchestrate multi-service ML systems, starting with a simple trainer and API, and then extending the stack with Redis for caching and Postgres for logging.</p>



<p>We then enabled GPU support in Docker and Compose, learning how to schedule GPUs across services for both training and inference. Along the way, we also discovered Ollama in Docker, a modern approach to containerizing large language models and exposing them through a REST API for integration with other services.</p>



<p>The module also emphasized production practices. We learned how to optimize and secure ML images using slim base images, multi-stage builds, <code data-enlighter-language="python" class="EnlighterJSRAW">.dockerignore</code>, non-root users, and graceful shutdowns. We pushed images to registries like Docker Hub and GHCR, preparing them for deployment to platforms such as ECS, EKS, or other cloud services.</p>



<p>To close out, we applied a Production Checklist exercise: refactoring with multi-stage builds, scanning images with Trivy, and pushing a hardened ML API to a registry. Finally, we went beyond Compose, seeing how Swarm fits as a small step toward clustering but understanding why Kubernetes has become the industry standard for scaling ML workloads.</p>



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



<p><strong>Singh, V</strong><strong>. </strong>“Production-Ready Docker for MLOps: Docker Compose, GPUs, and Ollama,” <em>PyImageSearch</em>, S. Huot, A. Sharma, and P. Thakur, eds., 2026, <a href="https://pyimg.co/6l2mp" target="_blank" rel="noreferrer noopener">https://pyimg.co/6l2mp</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="Production-Ready Docker for MLOps: Docker Compose, GPUs, and Ollama" data-enlighter-group="43">@incollection{Singh_2026_prod-ready-docker-mlops-docker-compose-gpus-ollama,
  author = {Vikram Singh},
  title = {{Production-Ready Docker for MLOps: Docker Compose, GPUs, and Ollama}},
  booktitle = {PyImageSearch},
  editor = {Susan Huot and Aditya Sharma and Piyush Thakur},
  year = {2026},
  url = {https://pyimg.co/6l2mp},
}
</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/11/23/production-ready-docker-for-mlops-docker-compose-gpus-and-ollama/">Production-Ready Docker for MLOps: Docker Compose, GPUs, and Ollama</a> appeared first on <a rel="nofollow" href="https://pyimagesearch.com">PyImageSearch</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Getting Started with Docker for Machine Learning and MLOps</title>
		<link>https://pyimagesearch.com/2026/11/16/getting-started-with-docker-for-machine-learning-and-mlops/</link>
		
		<dc:creator><![CDATA[Vikram Singh]]></dc:creator>
		<pubDate>Mon, 16 Nov 2026 13:45:00 +0000</pubDate>
				<category><![CDATA[Docker]]></category>
		<category><![CDATA[Machine Learning]]></category>
		<category><![CDATA[MLOps]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[containers vs virtual machines]]></category>
		<category><![CDATA[docker]]></category>
		<category><![CDATA[docker architecture]]></category>
		<category><![CDATA[docker commands]]></category>
		<category><![CDATA[docker for machine learning]]></category>
		<category><![CDATA[docker for mlops]]></category>
		<category><![CDATA[docker gpu]]></category>
		<category><![CDATA[docker tutorial for beginners]]></category>
		<category><![CDATA[dockerfile]]></category>
		<category><![CDATA[dockerignore]]></category>
		<category><![CDATA[mlops]]></category>
		<category><![CDATA[podman]]></category>
		<category><![CDATA[pytorch docker]]></category>
		<category><![CDATA[pytorch lightning]]></category>
		<category><![CDATA[reproducible machine learning]]></category>
		<category><![CDATA[tutorial]]></category>
		<guid isPermaLink="false">https://pyimagesearch.com/?p=55923</guid>

					<description><![CDATA[<p>Table of Contents Getting Started with Docker for Machine Learning and MLOps Why Use Docker for MLOps? Reproducible Machine Learning Environments Configuring Your Development Environment Project Structure Docker Architecture Explained: Images, Containers, and Virtual Machines Essential Docker Commands for Beginners&#8230;</p>
<p>The post <a rel="nofollow" href="https://pyimagesearch.com/2026/11/16/getting-started-with-docker-for-machine-learning-and-mlops/">Getting Started with Docker for Machine Learning and MLOps</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-Getting-Started-with-Docker-for-Machine-Learning-and-MLOps"><a rel="noopener" target="_blank" href="#h1-Getting-Started-with-Docker-for-Machine-Learning-and-MLOps">Getting Started with Docker for Machine Learning and MLOps</a></li>
    <li id="TOC-h2-Why-Use-Docker-for-MLOps-Reproducible-Machine-Learning-Environments"><a rel="noopener" target="_blank" href="#h2-Why-Use-Docker-for-MLOps-Reproducible-Machine-Learning-Environments">Why Use Docker for MLOps? Reproducible Machine Learning Environments</a></li>
    <li id="TOC-h2-Configuring-Your-Development-Environment"><a rel="noopener" target="_blank" href="#h2-Configuring-Your-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-Docker-Architecture-Explained-Images-Containers-and-Virtual-Machines"><a rel="noopener" target="_blank" href="#h2-Docker-Architecture-Explained-Images-Containers-and-Virtual-Machines">Docker Architecture Explained: Images, Containers, and Virtual Machines</a></li>
    <li id="TOC-h2-Essential-Docker-Commands-for-Beginners"><a rel="noopener" target="_blank" href="#h2-Essential-Docker-Commands-for-Beginners">Essential Docker Commands for Beginners</a></li>
    <li id="TOC-h2-How-to-Write-a-Dockerfile-for-a-PyTorch-Lightning-Project"><a rel="noopener" target="_blank" href="#h2-How-to-Write-a-Dockerfile-for-a-PyTorch-Lightning-Project">How to Write a Dockerfile for a PyTorch Lightning Project</a></li>
    <li id="TOC-h2-Dockerfile-Best-Practices-for-Machine-Learning-Images"><a rel="noopener" target="_blank" href="#h2-Dockerfile-Best-Practices-for-Machine-Learning-Images">Dockerfile Best Practices for Machine Learning Images</a></li>
    <li id="TOC-h2-Docker-for-ML-Dataset-Mounts-Environment-Variables-and-GPU-Support"><a rel="noopener" target="_blank" href="#h2-Docker-for-ML-Dataset-Mounts-Environment-Variables-and-GPU-Support">Docker for ML: Dataset Mounts, Environment Variables, and GPU Support</a></li>
    <li id="TOC-h2-Docker-Alternatives-for-MLOps-Podman-Buildah-and-Apptainer"><a rel="noopener" target="_blank" href="#h2-Docker-Alternatives-for-MLOps-Podman-Buildah-and-Apptainer">Docker Alternatives for MLOps: Podman, Buildah, and Apptainer</a></li>
    <li id="TOC-h2-Train-a-PyTorch-Model-in-Docker-and-Share-the-Image-on-Docker-Hub"><a rel="noopener" target="_blank" href="#h2-Train-a-PyTorch-Model-in-Docker-and-Share-the-Image-on-Docker-Hub">Train a PyTorch Model in Docker and Share the Image on Docker Hub</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-Getting-Started-with-Docker-for-Machine-Learning-and-MLOps"/>



<h2 class="wp-block-heading"><a href="#TOC-h1-Getting-Started-with-Docker-for-Machine-Learning-and-MLOps">Getting Started with Docker for Machine Learning and MLOps</a></h2>



<p>In this lesson, we will learn how to use Docker for MLOps, starting with why Docker matters in machine learning (ML), then exploring Docker fundamentals and architecture, running basic Docker commands, building reproducible ML environments, and containerizing an ML project. We will also cover best practices for ML images, finish with a hands-on exercise, and briefly look at some popular Docker alternatives.</p>


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


<p>This lesson is the 2nd in a 3-part series on <strong>Machine Learning Operations (MLOps)</strong>:</p>



<ol class="wp-block-list">
<li><em><strong><a href="https://pyimg.co/dqztp" target="_blank" rel="noreferrer noopener">What Is MLOps? Architecture, MLOps vs DevOps, and LLMOps</a></strong></em></li>



<li><em><strong><a href="https://pyimg.co/flyvj" target="_blank" rel="noreferrer noopener">Getting Started with Docker for Machine Learning and MLOps</a></strong></em><strong> (this tutorial)</strong></li>



<li><em>Production-Ready Docker for MLOps</em></li>
</ol>



<p><strong>To learn how to use Docker for MLOps, from fundamentals and commands to best practices and containerizing your first ML project,</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-Use-Docker-for-MLOps-Reproducible-Machine-Learning-Environments"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Why-Use-Docker-for-MLOps-Reproducible-Machine-Learning-Environments">Why Use Docker for MLOps? Reproducible Machine Learning Environments</a></h2>



<p>A common phrase in machine learning is <em>“It works on my machine.”</em> That is because ML projects are uniquely fragile. A model that runs fine on a laptop may fail completely on a production server.</p>



<p>Why does this happen? Machine learning brings extra challenges:</p>



<ul class="wp-block-list">
<li><strong>Dependencies:</strong> You might have PyTorch 2.2 with Compute Unified Device Architecture (CUDA) 12.1 locally, but the server only supports CUDA 11.8.</li>



<li><strong>Operating Systems:</strong> The project was built on macOS, but the production cluster runs Ubuntu.</li>



<li><strong>Data Paths:</strong> The dataset lives in <code data-enlighter-language="python" class="EnlighterJSRAW">./data</code> locally but in <code data-enlighter-language="python" class="EnlighterJSRAW">/mnt/data</code> in production.</li>



<li><strong>Conflicting Packages:</strong> TensorFlow requires one version of <code data-enlighter-language="python" class="EnlighterJSRAW">protobuf</code>, while another package needs a newer one.</li>
</ul>



<p>For traditional software, these mismatches are frustrating. For ML, they are crippling. Reproducibility requires consistency in both research and production.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://pyimagesearch.com/wp-content/uploads/2026/11/image-31.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="225" height="304" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-31.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-55954"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-31.png?size=126x170&lossy=2&strip=1&webp=1 126w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-31-222x300.png?lossy=2&strip=1&webp=1 222w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-31.png?lossy=2&strip=1&webp=1 225w" sizes="(max-width: 225px) 100vw, 225px" /></a><figcaption class="wp-element-caption"><strong>Figure 1:</strong> The classic “works on my machine” problem. This is exactly the pain Docker solves (source: <a href="https://dev.to/gbengelebs/demystifying-docker-26id" target="_blank" rel="noreferrer noopener">Elegberun, 2020, Demystifying Docker</a>).</figcaption></figure></div>


<p>Docker solves this by letting you package code, dependencies, drivers, and configuration into a container image. That image runs the same way everywhere: on a laptop, on a teammate’s machine, or inside a Kubernetes cluster.</p>



<p><strong>A </strong><strong>R</strong><strong>eal </strong><strong>E</strong><strong>xample:</strong> Imagine a PyTorch model is trained locally with <strong>PyTorch 2.2 + CUDA 12.1</strong>. The production server, however, has <strong>PyTorch 2.1 + CUDA 11.8</strong>. When you try to deploy, your code fails because the CUDA kernels do not match. The result? Debugging hell, wasted hours, and frustrated teammates.</p>



<p>Now enter <strong>Docker</strong>. With Docker, we package our code, dependencies, and runtime into a container image. This image provides a consistent software environment across compatible hosts in development and production. The CUDA runtime travels with the code. The server still needs a compatible NVIDIA driver.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://pyimagesearch.com/wp-content/uploads/2026/11/image-6.jpeg" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="1024" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-6.jpeg?lossy=2&strip=1&webp=1" alt="" class="wp-image-55956"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-6-150x150.jpeg?lossy=2&strip=1&webp=1 150w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-6-300x300.jpeg?lossy=2&strip=1&webp=1 300w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-6.jpeg?size=378x378&lossy=2&strip=1&webp=1 378w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-6.jpeg?size=504x504&lossy=2&strip=1&webp=1 504w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-6.jpeg?size=630x630&lossy=2&strip=1&webp=1 630w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-6-768x768.jpeg?lossy=2&strip=1&webp=1 768w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-6.jpeg?lossy=2&strip=1&webp=1 1024w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 2:</strong> Without Docker, code runs differently across environments and often fails in production. With Docker, container images ensure the same results everywhere (source: image by the author).</figcaption></figure></div>


<p>In the context of MLOps, Docker is not just a convenience. It is the foundation. MLOps requires reproducibility, scalability, and collaboration. If experiments cannot be reproduced, deployment cannot be trusted, and monitoring and retraining are meaningless. Docker makes reproducibility and portability non-negotiable, which is why every modern ML pipeline starts here.</p>



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



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



<p>To follow this guide, you only need Docker installed on your system. That is it!</p>



<p>The beauty of containerization is that all Python dependencies (e.g., PyTorch and Lightning) are installed inside the container, so the host machine does not need them.</p>



<h3 class="wp-block-heading">macOS and Windows</h3>



<p>Download and install <a href="https://www.docker.com/products/docker-desktop/" target="_blank" rel="noreferrer noopener">Docker Desktop</a></p>



<h3 class="wp-block-heading">Linux (Ubuntu/Debian)</h3>



<pre class="EnlighterJSRAW" data-enlighter-language="bash" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Getting Started with Docker for Machine Learning and MLOps" data-enlighter-group="1">curl -fsSL https://get.docker.com -o get-docker.sh
sudo sh get-docker.sh</pre>



<h3 class="wp-block-heading">Verify installation</h3>



<pre class="EnlighterJSRAW" data-enlighter-language="bash" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Getting Started with Docker for Machine Learning and MLOps" data-enlighter-group="2">docker --version
docker run hello-world</pre>



<p>That is all you need! The container handles everything else. Python, PyTorch, datasets, and dependencies are all managed inside the isolated environment.</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>We first need to review our project directory structure.</p>



<p>Start by accessing this lesson’s <em><strong>“Downloads”</strong></em> section to retrieve the source code and example images.</p>



<p>From there, take a look at the directory 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="Getting Started with Docker for Machine Learning and MLOps" data-enlighter-group="3">docker-mlops-starter/
├── train.py                    # PyTorch Lightning MNIST training script
├── requirements.txt            # Pinned Python dependencies for reproducibility
├── Dockerfile                 # Production-ready Docker configuration
├── .dockerignore              # Build optimization - excludes unnecessary files
└── README.md                  # Complete tutorial and setup guide</pre>



<p>This simple structure contains everything needed for containerizing a machine learning project. </p>



<ul class="wp-block-list">
<li><code data-enlighter-language="python" class="EnlighterJSRAW">train.py</code>: implements a PyTorch Lightning model for MNIST digit classification </li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">requirements.txt</code>: pins our dependencies (e.g., <code data-enlighter-language="python" class="EnlighterJSRAW">torch</code>, <code data-enlighter-language="python" class="EnlighterJSRAW">torchvision</code>, and <code data-enlighter-language="python" class="EnlighterJSRAW">pytorch-lightning</code>) for reproducible builds</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">Dockerfile</code>: defines our container blueprint with proper security and optimization practices</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">.dockerignore</code>: excludes unnecessary files to keep our image size small and build times fast</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Docker-Architecture-Explained-Images-Containers-and-Virtual-Machines"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Docker-Architecture-Explained-Images-Containers-and-Virtual-Machines">Docker Architecture Explained: Images, Containers, and Virtual Machines</a></h2>



<p>Before we start running commands, it is important to understand what Docker actually is and how it works under the hood. Many new ML engineers use Docker without really grasping its fundamentals, but in MLOps, a clear mental model will save countless hours of debugging later.</p>



<h3 class="wp-block-heading">Containers vs Virtual Machines</h3>



<p>At a glance, containers and virtual machines (VMs) may look similar. Both isolate applications so they can run in their own environments. But there is a crucial difference:</p>



<ul class="wp-block-list">
<li><strong>VMs:</strong> simulate an entire operating system, which makes them heavy and resource-intensive.</li>



<li><strong>Containers:</strong> share the host operating system’s kernel and only package the application, its dependencies, and a minimal environment.</li>
</ul>



<p><strong>Analogy:</strong> Think of a VM as a full house with its own foundation, walls, plumbing, and electricity. A container is more like a furnished apartment in a building. It is lighter, starts faster, and is easier to move.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/11/image-32-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="435" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-32-1024x435.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-55960"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-32-1024x435.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-32-1024x435.png?size=126x54&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-32-1024x435.png?size=252x107&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-32-1024x435.png?size=378x161&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-32-1024x435.png?size=504x214&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-32-1024x435.png?size=630x268&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 3:</strong> Containers (<em>left</em>) share the host operating system, while virtual machines (<em>right</em>) require a full guest OS for each app. This makes containers far lighter and faster to start (source: <a href="https://commons.wikimedia.org/wiki/File:Docker-containerized-and-vm-transparent-bg.png" target="_blank" rel="noreferrer noopener">File:Docker-containerized-and-vm-transparent-bg.png &#8211; Wikimedia Commons</a>).</figcaption></figure></div>


<p>This efficiency is one reason Docker became so popular in machine learning. We can spin up lightweight, isolated environments quickly without waiting minutes for a VM to boot.</p>



<h3 class="wp-block-heading">Docker Architecture</h3>



<p>Docker follows a <strong>client–server architecture</strong>. When we type commands (e.g., <code data-enlighter-language="python" class="EnlighterJSRAW">docker run</code> or <code data-enlighter-language="python" class="EnlighterJSRAW">docker build</code>), we interact with the <strong>Docker </strong><strong>c</strong><strong>lient</strong>, which communicates with the <strong>Docker </strong><strong>d</strong><strong>aemon</strong>.</p>



<ul class="wp-block-list">
<li><strong>Docker Client:</strong> The command-line tool (<code data-enlighter-language="python" class="EnlighterJSRAW">docker</code>) we use to run commands such as <code data-enlighter-language="python" class="EnlighterJSRAW">docker build</code>, <code data-enlighter-language="python" class="EnlighterJSRAW">docker pull</code>, and <code data-enlighter-language="python" class="EnlighterJSRAW">docker run</code>.</li>



<li><strong>Docker Daemon (</strong><code data-enlighter-language="python" class="EnlighterJSRAW">dockerd</code><strong>):</strong> A background service that listens for requests from the client and does the heavy lifting (e.g., building images, pulling them from registries, and running containers).</li>



<li><strong>Docker Engine API</strong><strong>:</strong> The client communicates with the daemon through a representational state transfer (REST) application programming interface (API). On a standard Docker Engine installation on Linux, the default endpoint is the Unix socket at <code data-enlighter-language="python" class="EnlighterJSRAW">/var/run/docker.sock</code>.</li>



<li><strong>Docker Registry:</strong> A store (e.g., Docker Hub, GitHub Container Registry (GHCR), and Amazon Elastic Container Registry (Amazon ECR)) where images are stored and fetched. The daemon pulls images from registries or pushes images to them.</li>



<li><strong>Images and Containers:</strong> Inside the Docker host, the daemon manages images (blueprints) and runs them as containers (isolated instances).</li>
</ul>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://pyimagesearch.com/wp-content/uploads/2026/11/image-33.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1000" height="382" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-33.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-55962"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-33.png?size=126x48&lossy=2&strip=1&webp=1 126w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-33-300x115.png?lossy=2&strip=1&webp=1 300w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-33.png?size=378x144&lossy=2&strip=1&webp=1 378w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-33.png?size=504x193&lossy=2&strip=1&webp=1 504w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-33.png?size=630x241&lossy=2&strip=1&webp=1 630w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-33-768x293.png?lossy=2&strip=1&webp=1 768w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-33.png?lossy=2&strip=1&webp=1 1000w" sizes="(max-width: 1000px) 100vw, 1000px" /></a><figcaption class="wp-element-caption"><strong>Figure 4:</strong> Docker uses a client–server model. The client sends requests to the daemon, which builds images, pulls them from registries, and runs containers (source: <a href="https://media.geeksforgeeks.org/wp-content/uploads/20221205115118/Architecture-of-Docker.png" target="_blank" rel="noreferrer noopener">Architecture-of-Docker.png</a>)</figcaption></figure></div>


<p><strong>Workflow Example:</strong> When we run <code data-enlighter-language="python" class="EnlighterJSRAW">docker run hello-world</code>, the client sends the request to the daemon. The daemon checks whether the image exists locally and pulls it from a registry if needed. It then creates and runs a container from the image.</p>



<p>⚠️ <strong>Common error:</strong> If we see
<code data-enlighter-language="python" class="EnlighterJSRAW">Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?</code>, it means the client cannot talk to the daemon. This usually happens if Docker Desktop (on macOS or Windows) is not running or the Docker service (on Linux) has not started.</p>



<h3 class="wp-block-heading">Key Terms We Need to Know</h3>



<ul class="wp-block-list">
<li><strong>Image:</strong> A blueprint for our container. Think of it as a snapshot of the environment (e.g., Python, libraries, and code).</li>



<li><strong>Container:</strong> An instance created from an image. We can start, stop, and remove containers.</li>



<li><strong>Registry:</strong> A place where images are stored and shared. Public registries such as Docker Hub and GitHub Container Registry (GHCR) are widely used. Cloud providers also offer registries such as Amazon Elastic Container Registry (Amazon ECR) and Google Cloud Artifact Registry.</li>
</ul>



<h3 class="wp-block-heading">A Note on Podman</h3>



<p>While Docker remains one of the most widely adopted container platforms, alternatives are gaining traction. Podman, backed by Red Hat, offers a daemonless architecture and supports running containers without root privileges. It is also compatible with Docker-built images that follow the Open Container Initiative (OCI) image standard. We will stick with Docker throughout this course, but it is useful to be aware of the broader container ecosystem.</p>



<p>With these fundamentals in mind, we can see how Docker uses a client–server architecture to run lightweight, portable containers from images that can be distributed through registries.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Essential-Docker-Commands-for-Beginners"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Essential-Docker-Commands-for-Beginners">Essential Docker Commands for Beginners</a></h2>



<p>Now that we understand the fundamentals, let us get hands-on. Docker is a command-line tool at its core, and learning a few key commands will give you immediate confidence. We will start with the basics: running containers, listing them, inspecting them, and jumping inside.</p>



<h3 class="wp-block-heading">Running Our First Container</h3>



<p>Run the following command to test Docker.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Getting Started with Docker for Machine Learning and MLOps" data-enlighter-group="4">docker run hello-world</pre>



<p>If the image is missing locally, Docker pulls it from Docker Hub by default. Docker then runs a container from the image and displays <code data-enlighter-language="raw" class="EnlighterJSRAW">Hello from Docker!</code></p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://pyimagesearch.com/wp-content/uploads/2026/11/image-7.jpeg" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="860" height="413" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-7.jpeg?lossy=2&strip=1&webp=1" alt="" class="wp-image-55965"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-7.jpeg?size=126x61&lossy=2&strip=1&webp=1 126w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-7-300x144.jpeg?lossy=2&strip=1&webp=1 300w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-7.jpeg?size=378x182&lossy=2&strip=1&webp=1 378w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-7.jpeg?size=504x242&lossy=2&strip=1&webp=1 504w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-7.jpeg?size=630x303&lossy=2&strip=1&webp=1 630w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-7-768x369.jpeg?lossy=2&strip=1&webp=1 768w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-7.jpeg?lossy=2&strip=1&webp=1 860w" sizes="(max-width: 860px) 100vw, 860px" /></a><figcaption class="wp-element-caption"><strong>Figure 5:</strong> Running <code>docker run hello-world</code> displays a success message, confirming that Docker can run a container (source: image by the author).</figcaption></figure></div>


<h3 class="wp-block-heading">Running an Interactive Container</h3>



<p>Let us take it further with Ubuntu:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="bash" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Getting Started with Docker for Machine Learning and MLOps" data-enlighter-group="5">docker run -it ubuntu bash</pre>



<ul class="wp-block-list">
<li><code data-enlighter-language="python" class="EnlighterJSRAW">-it</code>: keeps standard input open (<code data-enlighter-language="python" class="EnlighterJSRAW">-i</code>) and allocates a pseudo-terminal (<code data-enlighter-language="python" class="EnlighterJSRAW">-t</code>) </li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">ubuntu</code>: is the image used to create the container</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">bash</code>: is the command we want to run inside the container</li>
</ul>



<p>An interactive Bash shell opens inside the Ubuntu container.</p>



<h3 class="wp-block-heading">Listing and Managing Containers</h3>



<p>Docker keeps track of all containers we 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="Getting Started with Docker for Machine Learning and MLOps" data-enlighter-group="6">docker ps        # shows running containers
docker ps -a     # shows all containers, including stopped ones</pre>



<p>We will see container identifiers (IDs), names, and status.</p>



<p>Run the following command to stop a container.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Getting Started with Docker for Machine Learning and MLOps" data-enlighter-group="7">docker stop &lt;container_id></pre>



<p>Run the following command to remove a stopped container.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Getting Started with Docker for Machine Learning and MLOps" data-enlighter-group="8">docker rm &lt;container_id></pre>



<h3 class="wp-block-heading">Inspecting Containers and Images</h3>



<p>Sometimes we need details:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Getting Started with Docker for Machine Learning and MLOps" data-enlighter-group="9">docker images          # list available images
docker inspect &lt;id>    # view detailed JSON info about a container</pre>



<p><code data-enlighter-language="python" class="EnlighterJSRAW">docker images</code> lists locally stored images. By default, <code data-enlighter-language="python" class="EnlighterJSRAW">docker inspect</code> returns details about a container or image in JavaScript Object Notation (JSON).</p>



<p><code data-enlighter-language="python" class="EnlighterJSRAW">inspect</code> is especially useful for debugging environment variables, volumes, and networking.</p>



<h3 class="wp-block-heading">Jumping into a Running Container</h3>



<p>If a running container includes Bash, we can open a shell inside it.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="bash" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Getting Started with Docker for Machine Learning and MLOps" data-enlighter-group="10">docker exec -it &lt;container_id> bash</pre>



<p>This is handy for debugging ML jobs, checking logs, or verifying that our dependencies are installed correctly inside the container.</p>



<h3 class="wp-block-heading">Common Docker Daemon Connection Error</h3>



<p>The following error means the Docker client could not connect to the daemon.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Getting Started with Docker for Machine Learning and MLOps" data-enlighter-group="11">Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?</pre>



<ul class="wp-block-list">
<li>On Linux systems that use <code data-enlighter-language="python" class="EnlighterJSRAW">systemd</code>, we may need to start Docker with <code data-enlighter-language="python" class="EnlighterJSRAW">sudo systemctl start docker</code>.</li>



<li>On macOS and Windows, ensure the Docker Desktop app is running.</li>
</ul>



<p>With the Docker commands covered so far, we can:</p>



<ul class="wp-block-list">
<li>pull images and run containers</li>



<li>work interactively inside containers</li>



<li>manage and inspect containers</li>



<li>debug common errors</li>
</ul>



<p>This is the muscle memory every ML engineer needs before moving into Dockerfiles.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-How-to-Write-a-Dockerfile-for-a-PyTorch-Lightning-Project"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-How-to-Write-a-Dockerfile-for-a-PyTorch-Lightning-Project">How to Write a Dockerfile for a PyTorch Lightning Project</a></h2>



<p>Now that we can run and inspect containers, let us package an actual ML project. We will containerize a small PyTorch Lightning script that trains on MNIST. The goal is a <strong>reproducible CPU image</strong> that runs the same on any machine.</p>



<h3 class="wp-block-heading">Project Layout</h3>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Getting Started with Docker for Machine Learning and MLOps" data-enlighter-group="12">docker-mlops-starter/
├─ train.py
├─ requirements.txt
└─ Dockerfile</pre>



<p><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="Getting Started with Docker for Machine Learning and MLOps" data-enlighter-group="13">torch==2.3.1
torchvision==0.18.1
pytorch-lightning==2.3.0
numpy==1.26.4</pre>



<p><strong>Tip:</strong> pin versions to keep results stable across machines.</p>



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



<p><code data-enlighter-language="python" class="EnlighterJSRAW">train.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="Getting Started with Docker for Machine Learning and MLOps" data-enlighter-group="14">import torch, torchvision
from torch.utils.data import DataLoader
from torchvision import transforms
import pytorch_lightning as pl
from pytorch_lightning import LightningModule
from torch import nn
from torch.nn import functional as F

class MNISTModel(LightningModule):
    def __init__(self):
        super().__init__()
        self.net = nn.Sequential(
            nn.Flatten(),
            nn.Linear(28*28, 256), nn.ReLU(),
            nn.Linear(256, 10)
        )
    def forward(self, x): 
        return self.net(x)
   
    def training_step(self, batch, _):
        x, y = batch
        logits = self(x)
        loss = F.cross_entropy(logits, y)
        self.log("train_loss", loss, prog_bar=True)
        return loss
   
    def configure_optimizers(self):
        return torch.optim.Adam(self.parameters(), lr=1e-3)

def make_loaders(batch_size=128):
    tfm = transforms.Compose([transforms.ToTensor()])
    train = torchvision.datasets.MNIST(root="./data", train=True, download=True, transform=tfm)
    return DataLoader(train, batch_size=batch_size, shuffle=True, num_workers=2)

if __name__ == "__main__":
    loader = make_loaders()
    model = MNISTModel()
    trainer = pl.Trainer(max_epochs=1, accelerator="cpu", log_every_n_steps=10)
    trainer.fit(model, loader)</pre>



<p>This script downloads the MNIST training dataset to <code data-enlighter-language="python" class="EnlighterJSRAW">./data</code> if needed and trains for 1 epoch.</p>



<h3 class="wp-block-heading">Dockerfile (CPU, slim base)</h3>



<p><code data-enlighter-language="python" class="EnlighterJSRAW">Dockerfile</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="Getting Started with Docker for Machine Learning and MLOps" data-enlighter-group="15"># 1) Base image (small, secure)
FROM python:3.11-slim

# 2) System deps: git and build tools if wheels are missing
RUN apt-get update &amp;&amp; apt-get install -y --no-install-recommends \
    git build-essential &amp;&amp; \
    rm -rf /var/lib/apt/lists/*

# 3) Workdir
WORKDIR /app

# 4) Copy only dependency files first for better layer caching
COPY requirements.txt .

# 5) Install Python deps (no cache to reduce image size)
RUN pip install --no-cache-dir -r requirements.txt

# 6) Now copy the source code
COPY train.py .

# 7) Create a non-root user (good hygiene)
RUN useradd -m runner
USER runner

# 8) Default command
CMD ["python", "train.py"]</pre>



<p>Why this works well for ML:</p>



<ul class="wp-block-list">
<li><strong>Slim base:</strong> keeps the image lean</li>



<li><strong>Layer order:</strong> speeds up rebuilds when only the source code changes</li>



<li><strong>Non-root user:</strong> is a safer default</li>



<li>The default <code data-enlighter-language="python" class="EnlighterJSRAW">CMD</code> runs the training script and can be overridden at runtime.</li>
</ul>



<p>Once we have written the <code data-enlighter-language="python" class="EnlighterJSRAW">Dockerfile</code>, it is useful to understand how it becomes something we can actually run. Docker does not execute the <code data-enlighter-language="python" class="EnlighterJSRAW">Dockerfile</code> directly. Instead, it uses the instructions in the <code data-enlighter-language="python" class="EnlighterJSRAW">Dockerfile</code> to build a Docker image. When we run that image, Docker creates and starts a container from it.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://pyimagesearch.com/wp-content/uploads/2026/11/image-34.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="624" height="244" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-34.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-55968"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-34.png?size=126x49&lossy=2&strip=1&webp=1 126w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-34-300x117.png?lossy=2&strip=1&webp=1 300w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-34.png?size=378x148&lossy=2&strip=1&webp=1 378w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-34.png?size=504x197&lossy=2&strip=1&webp=1 504w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-34.png?lossy=2&strip=1&webp=1 624w" sizes="(max-width: 624px) 100vw, 624px" /></a><figcaption class="wp-element-caption"><strong>Figure 6:</strong> The Docker build process uses the <code>Dockerfile</code> to produce an image. Running the image starts a container that executes the ML code (source: image by the author).</figcaption></figure></div>


<h3 class="wp-block-heading">Optional: .dockerignore</h3>



<p>Keep images small and builds fast by excluding junk.</p>



<p><code data-enlighter-language="python" class="EnlighterJSRAW">.dockerignore</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="Getting Started with Docker for Machine Learning and MLOps" data-enlighter-group="16">__pycache__/
*.pyc
*.pyo
*.pyd
.data/
data/
.venv/
.env
.git</pre>



<h3 class="wp-block-heading">Build and Run</h3>



<p>From the project root:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Getting Started with Docker for Machine Learning and MLOps" data-enlighter-group="17"># Build the image
docker build -t ml-docker-demo:cpu .

# Run training (downloads MNIST into a container-local /app/data)
docker run -it ml-docker-demo:cpu</pre>



<p>We should see the dataset download and training logs. If we prefer to <strong>persist data on the host</strong>, we can try:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Getting Started with Docker for Machine Learning and MLOps" data-enlighter-group="18"># Save MNIST to a host folder so future runs reuse it
mkdir -p $(pwd)/data
docker run -it -v $(pwd)/data:/app/data ml-docker-demo:cpu</pre>



<h3 class="wp-block-heading">Overriding the Command</h3>



<p>We can specify the command at runtime without changing the <code data-enlighter-language="python" class="EnlighterJSRAW">Dockerfile</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="Getting Started with Docker for Machine Learning and MLOps" data-enlighter-group="19">docker run -it ml-docker-demo:cpu python train.py</pre>



<h3 class="wp-block-heading">Quick Troubleshooting</h3>



<ul class="wp-block-list">
<li><strong>Build Fails on Dependencies:</strong> ensure <code data-enlighter-language="python" class="EnlighterJSRAW">build-essential</code> is installed in the image and that versions in <code data-enlighter-language="python" class="EnlighterJSRAW">requirements.txt</code> are compatible.</li>



<li><strong>Cannot Connect to the Docker Daemon:</strong> start Docker Desktop or run <code data-enlighter-language="python" class="EnlighterJSRAW">sudo systemctl start docker</code> on Linux systems that use <code data-enlighter-language="python" class="EnlighterJSRAW">systemd</code>. </li>



<li><strong>Slow Rebuilds:</strong> keep <code data-enlighter-language="python" class="EnlighterJSRAW">requirements.txt</code> stable so Docker can cache that layer; only copy code after installing deps.</li>
</ul>



<h3 class="wp-block-heading">What We Achieved</h3>



<ul class="wp-block-list">
<li>a portable <strong>CPU training container</strong> that runs the same everywhere</li>



<li>pinned dependencies and a sensible <code data-enlighter-language="python" class="EnlighterJSRAW">Dockerfile</code> structure</li>



<li>reproducible results that our teammates can verify</li>
</ul>



<p>Next, we will discuss <strong>best practices for ML images</strong> and then move to <strong>handling data and environments</strong> before jumping into multi-stage builds and Compose in the next lesson.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Dockerfile-Best-Practices-for-Machine-Learning-Images"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Dockerfile-Best-Practices-for-Machine-Learning-Images">Dockerfile Best Practices for Machine Learning Images</a></h2>



<p>Now that we can build and run a basic ML Dockerfile, it is time to refine it. A naïve <code data-enlighter-language="python" class="EnlighterJSRAW">Dockerfile</code> works, but in production MLOps we will quickly hit problems: bloated images, long build times, security vulnerabilities, or containers that fail when we stop them abruptly. These best practices will help us build <strong>leaner, faster, and safer images</strong> that scale into production.</p>



<h3 class="wp-block-heading">Use Slim or Distroless Images</h3>



<p>Whenever possible, start with lightweight base images such as <code data-enlighter-language="python" class="EnlighterJSRAW">python:3.11-slim</code>. They strip away unnecessary OS components, reducing size and attack surface.</p>



<p>For serving-only workloads, <strong>Google Distroless images</strong> are even better. They contain only what we explicitly install. This matters in MLOps because smaller images:</p>



<ul class="wp-block-list">
<li>push and pull faster in CI/CD</li>



<li>deploy quicker on Amazon ECS, Lambda, or Kubernetes</li>



<li>reduce the risk of hidden vulnerabilities</li>
</ul>



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



<p>Reproducibility in ML depends on consistent versions. Always pin package versions in <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="Getting Started with Docker for Machine Learning and MLOps" data-enlighter-group="20">torch==2.3.1
pytorch-lightning==2.3.0</pre>



<p>Unpinned dependencies can break silently when a library updates. Tools such as <strong>pip-tools</strong> or <strong>Poetry</strong> help generate locked dependency files for long-term stability.</p>



<h3 class="wp-block-heading">Use .dockerignore</h3>



<p>A <code data-enlighter-language="python" class="EnlighterJSRAW">.dockerignore</code> file is like <code data-enlighter-language="python" class="EnlighterJSRAW">.gitignore</code> for Docker. It prevents unnecessary files and directories (e.g., datasets, notebooks, checkpoints, and <code data-enlighter-language="python" class="EnlighterJSRAW">.git</code>) from bloating the image.</p>



<p><strong>Example</strong></p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Getting Started with Docker for Machine Learning and MLOps" data-enlighter-group="21">__pycache__/
*.ipynb
data/
checkpoints/</pre>



<p>This is crucial in ML where stray files can easily add gigabytes to an image.</p>



<h3 class="wp-block-heading">Separate Dev and Prod Images</h3>



<p>Development images often include Jupyter, debuggers, and extra tools. Production images should only have what is needed to run inference.</p>



<p><strong>Example Workflow</strong></p>



<ul class="wp-block-list">
<li><strong>Dev image:</strong> includes Jupyter and extra debugging libraries</li>



<li><strong>Prod image:</strong> minimal runtime with just the trained model and inference code</li>
</ul>



<p>This separation reduces attack surface and avoids dragging unnecessary dependencies into production.</p>



<h3 class="wp-block-heading">Optimize Layering in Dockerfiles</h3>



<p>Each <code data-enlighter-language="python" class="EnlighterJSRAW">RUN</code>, <code data-enlighter-language="python" class="EnlighterJSRAW">COPY</code>, or <code data-enlighter-language="python" class="EnlighterJSRAW">ADD</code> instruction creates a new cached layer. Ordering them well improves caching and speeds rebuilds.</p>



<p><strong>Example</strong></p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Getting Started with Docker for Machine Learning and MLOps" data-enlighter-group="22"># Good practice: copy requirements first
COPY requirements.txt .
RUN pip install -r requirements.txt

# Then copy code
COPY . .</pre>



<p>This way, Docker reuses the dependency layer if code changes but <code data-enlighter-language="python" class="EnlighterJSRAW">requirements.txt</code> stays the same. It can save minutes in CI/CD rebuilds.</p>



<p>Every instruction adds a cached layer, which means Docker only rebuilds the parts of the image that changed plus the layers stacked on top. For example, if we change our training script, Docker will not reinstall dependencies. It will reuse the cached dependency layer and just rebuild from the <code data-enlighter-language="python" class="EnlighterJSRAW">COPY train.py</code> step onward.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://pyimagesearch.com/wp-content/uploads/2026/11/image-35.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="624" height="468" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-35.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-55969"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-35.png?size=126x95&lossy=2&strip=1&webp=1 126w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-35-300x225.png?lossy=2&strip=1&webp=1 300w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-35.png?size=378x284&lossy=2&strip=1&webp=1 378w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-35.png?size=504x378&lossy=2&strip=1&webp=1 504w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-35.png?lossy=2&strip=1&webp=1 624w" sizes="(max-width: 624px) 100vw, 624px" /></a><figcaption class="wp-element-caption"><strong>Figure 7:</strong> Optimizing <code>Dockerfile</code> layer caching by installing dependencies before copying application code, ensuring that changes to <code>train.py</code> do not trigger unnecessary dependency reinstallation (source: image by the author).</figcaption></figure></div>


<p>This is why the <strong>order of instructions matters</strong>. Place stable instructions (e.g., installing dependencies) near the top and volatile instructions (e.g., copying code) lower down.</p>



<h3 class="wp-block-heading">CMD vs ENTRYPOINT, ADD vs COPY</h3>



<ul class="wp-block-list">
<li><code data-enlighter-language="python" class="EnlighterJSRAW">CMD</code>: provides a default command but can be overridden (e.g., <code data-enlighter-language="python" class="EnlighterJSRAW">docker run myapp echo "hi"</code>).</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">ENTRYPOINT</code>: is harder to override. It is better suited to containers that should always start the same way (e.g., an inference server).</li>
</ul>



<p>For ML, use <code data-enlighter-language="python" class="EnlighterJSRAW">CMD ["python", "train.py"]</code> during experimentation, but prefer <code data-enlighter-language="python" class="EnlighterJSRAW">ENTRYPOINT</code> in production serving images.</p>



<p>Similarly:</p>



<ul class="wp-block-list">
<li><code data-enlighter-language="python" class="EnlighterJSRAW">COPY</code>: is preferred for code and data.</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">ADD</code>: should only be used for special cases (e.g., extracting tarballs or downloading from URLs).</li>
</ul>



<h3 class="wp-block-heading">Handle Shutdown Gracefully with STOPSIGNAL</h3>



<p>Training and inference jobs need to exit cleanly so they do not corrupt checkpoints or leave GPUs in a bad state.</p>



<p>We can specify how a container reacts when it is stopped:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Getting Started with Docker for Machine Learning and MLOps" data-enlighter-group="23">STOPSIGNAL SIGTERM</pre>



<p>And in our ML code, catch termination signals to save model state before exit.</p>



<p>By following these practices, we can avoid common Docker pitfalls in MLOps (e.g., slow builds, bloated images, brittle containers, and irreproducible results). Think of this section as setting the “hygiene baseline” for everything that comes later. FastAPI, Amazon Elastic Container Service (Amazon ECS), Lambda, and Kubernetes all benefit when our images are lean and predictable.</p>



<p>Next, we will move into <strong>Handling Data and Environments</strong>, where we will learn how to properly mount datasets, pass environment variables, and handle GPU workloads without baking them into our images.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Docker-for-ML-Dataset-Mounts-Environment-Variables-and-GPU-Support"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Docker-for-ML-Dataset-Mounts-Environment-Variables-and-GPU-Support">Docker for ML: Dataset Mounts, Environment Variables, and GPU Support</a></h2>



<p>One of the most common mistakes ML engineers make when starting with Docker is trying to bake everything into the image (e.g., datasets, model weights, and secrets). Bundling datasets and model weights can make images large and hard to maintain. Baking secrets into an image can expose them to anyone with access to it. Docker provides ways to supply data, configuration, and secrets at runtime.</p>



<h3 class="wp-block-heading">Mounting Volumes for Datasets</h3>



<p>Instead of copying datasets into the image, mount them at runtime:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Getting Started with Docker for Machine Learning and MLOps" data-enlighter-group="24">docker run -it -v $(pwd)/data:/app/data ml-docker-demo:cpu</pre>



<ul class="wp-block-list">
<li><code data-enlighter-language="python" class="EnlighterJSRAW">-v $(pwd)/data:/app/data</code> maps our local <code data-enlighter-language="python" class="EnlighterJSRAW">./data</code> folder to <code data-enlighter-language="python" class="EnlighterJSRAW">/app/data</code> inside the container.</li>



<li>This way, our training script can load data from <code data-enlighter-language="python" class="EnlighterJSRAW">/app/data</code>, and we avoid bloating the image.</li>



<li>We can swap datasets without rebuilding images.</li>
</ul>



<p><strong>Example</strong></p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Getting Started with Docker for Machine Learning and MLOps" data-enlighter-group="25">docker run -it -v $(pwd)/data:/app/data ml-docker-demo:cpu python train.py --data /app/data/mnist.csv</pre>



<h3 class="wp-block-heading">Passing Environment Variables</h3>



<p>For configuration and secrets (e.g., API keys, training parameters, and S3 paths), use <code data-enlighter-language="python" class="EnlighterJSRAW">--env</code> flags.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Getting Started with Docker for Machine Learning and MLOps" data-enlighter-group="26">docker run -it --env EPOCHS=20 --env API_KEY=12345 ml-docker-demo:cpu</pre>



<p>Inside the container, these variables are accessible like normal environment variables in Python:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Getting Started with Docker for Machine Learning and MLOps" data-enlighter-group="27">import os
epochs = int(os.getenv("EPOCHS", 10))
api_key = os.getenv("API_KEY")</pre>



<p>This is safer and more flexible than hardcoding.</p>



<h3 class="wp-block-heading">Why You Should Not Bake Datasets into Images</h3>



<p>Imagine we copy a 10 GB dataset into our Docker image. Every time we rebuild, push, or deploy that image, we are moving 10 GB around. This:</p>



<ul class="wp-block-list">
<li>slows down CI/CD pipelines</li>



<li>wastes cloud storage and bandwidth</li>



<li>makes collaboration painful (teammates must pull giant images)</li>
</ul>



<p><strong>Best practice:</strong> keep data outside images, mount it at runtime, and version it separately with tools (e.g., Data Version Control (DVC)).</p>



<h3 class="wp-block-heading">GPU Support with Docker</h3>



<p>Most ML workloads need GPUs. Docker integrates cleanly with NVIDIA hardware using the NVIDIA Container Toolkit.</p>



<p>Check GPU availability in a container:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Getting Started with Docker for Machine Learning and MLOps" data-enlighter-group="28">docker run -it --gpus all nvidia/cuda:12.1-base nvidia-smi</pre>



<ul class="wp-block-list">
<li><code data-enlighter-language="python" class="EnlighterJSRAW">--gpus all</code> exposes all available GPUs to the container</li>



<li>we can restrict GPU access by index with <code data-enlighter-language="python" class="EnlighterJSRAW">--gpus '"device=0"'</code></li>
</ul>



<p><strong>Note:</strong> In production, GPU scheduling is usually managed by Kubernetes. But Docker GPU support is the stepping stone.</p>



<p>With these practices, we now know how to handle <strong>datasets, configs, and GPUs</strong> the right way in Docker. No more bloated images or brittle setups.</p>



<p>In the next section, we will cover <strong>alternatives to Docker</strong> (Podman, Buildah, and Apptainer) before finishing the lesson with a hands-on reproducibility demo.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Docker-Alternatives-for-MLOps-Podman-Buildah-and-Apptainer"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Docker-Alternatives-for-MLOps-Podman-Buildah-and-Apptainer">Docker Alternatives for MLOps: Podman, Buildah, and Apptainer</a></h2>



<p>Docker may be the most popular container tool, but it is not the only option. MLOps engineers should be familiar with major alternatives (e.g., Podman, Buildah, and Apptainer).</p>



<h3 class="wp-block-heading">Podman</h3>



<p><a href="https://github.com/containers/podman" target="_blank" rel="noreferrer noopener">Podman</a> is often called the “drop-in replacement” for Docker. It runs containers without a central daemon and without requiring root privileges, which makes it more secure for enterprise setups. Podman is fully compatible with OCI (Open Container Initiative) images, so anything we build with Docker will run with Podman.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://pyimagesearch.com/wp-content/uploads/2026/11/image-36.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="598" height="487" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-36.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-55971"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-36.png?size=126x103&lossy=2&strip=1&webp=1 126w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-36-300x244.png?lossy=2&strip=1&webp=1 300w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-36.png?size=378x308&lossy=2&strip=1&webp=1 378w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-36.png?size=504x410&lossy=2&strip=1&webp=1 504w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-36.png?lossy=2&strip=1&webp=1 598w" sizes="(max-width: 598px) 100vw, 598px" /></a><figcaption class="wp-element-caption"><strong>Figure 8:</strong> <a href="https://podman.io/" target="_blank" rel="noreferrer noopener">https://podman.io/</a></figcaption></figure></div>


<p>Where it shines: high-security environments, Red Hat/OpenShift ecosystems.</p>



<h3 class="wp-block-heading">Buildah</h3>



<p><a href="https://buildah.io" target="_blank" rel="noreferrer noopener">Buildah</a> focuses on building OCI images without a daemon. It is frequently used together with Podman in CI/CD pipelines. Unlike Docker, Buildah allows us to build images as non-root, which can reduce security risks in multi-user environments.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://pyimagesearch.com/wp-content/uploads/2026/11/image-37.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="984" height="485" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-37.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-55973"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-37.png?size=126x62&lossy=2&strip=1&webp=1 126w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-37-300x148.png?lossy=2&strip=1&webp=1 300w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-37.png?size=378x186&lossy=2&strip=1&webp=1 378w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-37.png?size=504x248&lossy=2&strip=1&webp=1 504w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-37.png?size=630x311&lossy=2&strip=1&webp=1 630w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-37-768x379.png?lossy=2&strip=1&webp=1 768w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-37.png?lossy=2&strip=1&webp=1 984w" sizes="(max-width: 984px) 100vw, 984px" /></a><figcaption class="wp-element-caption"><strong>Figure 9:</strong> <a href="https://buildah.io/" target="_blank" rel="noreferrer noopener">https://buildah.io/</a></figcaption></figure></div>


<p>Where it shines: lightweight image building in automated pipelines.</p>



<h3 class="wp-block-heading">Apptainer (Formerly Singularity)</h3>



<p><a href="https://apptainer.org" target="_blank" rel="noreferrer noopener">Apptainer</a> (formerly known as Singularity) is popular in high-performance computing (HPC) and research labs. It is designed to run containers on shared systems without requiring root access.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://pyimagesearch.com/wp-content/uploads/2026/11/image-38.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="650" height="400" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-38.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-55975"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-38.png?size=126x78&lossy=2&strip=1&webp=1 126w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-38-300x185.png?lossy=2&strip=1&webp=1 300w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-38.png?size=378x233&lossy=2&strip=1&webp=1 378w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-38.png?size=504x310&lossy=2&strip=1&webp=1 504w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-38.png?lossy=2&strip=1&webp=1 650w" sizes="(max-width: 650px) 100vw, 650px" /></a><figcaption class="wp-element-caption"><strong>Figure 10:</strong> <a href="https://apptainer.org/" target="_blank" rel="noreferrer noopener">https://apptainer.org/</a></figcaption></figure></div>


<p>Where it shines: research, HPC clusters, academic ML projects.</p>



<h3 class="wp-block-heading">Should We Switch?</h3>



<p>For most ML engineers, <strong>Docker remains the default choice</strong>. It is supported everywhere (e.g., from our laptop to Amazon ECS, Lambda, and Kubernetes). Alternatives (e.g., Podman and Apptainer) matter if we work in specialized environments, but 95% of the time Docker is the most practical option.</p>



<p>Knowing about alternatives provides context: Docker is not the only container solution, but it is the one we will almost always start with in MLOps.</p>



<p>Next, we will finish this lesson with a <strong>hands-on wrap-up</strong>: containerizing and running a simple ML project to demonstrate reproducibility in action.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Train-a-PyTorch-Model-in-Docker-and-Share-the-Image-on-Docker-Hub"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Train-a-PyTorch-Model-in-Docker-and-Share-the-Image-on-Docker-Hub">Train a PyTorch Model in Docker and Share the Image on Docker Hub</a></h2>



<p>Let us bring together everything we have learned in this lesson. We will containerize and run the small <strong>PyTorch Lightning MNIST trainer</strong> from earlier, then prove that the results are reproducible across environments.</p>



<h3 class="wp-block-heading">Step 1: Build the Image</h3>



<p>From our project folder (with <code data-enlighter-language="python" class="EnlighterJSRAW">Dockerfile</code>, <code data-enlighter-language="python" class="EnlighterJSRAW">requirements.txt</code>, and <code data-enlighter-language="python" class="EnlighterJSRAW">train.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="Getting Started with Docker for Machine Learning and MLOps" data-enlighter-group="29">docker build -t ml-docker-demo:cpu .</pre>



<p>This creates a portable image with our ML training code and dependencies pinned.</p>



<h3 class="wp-block-heading">Step 2: Run the Training</h3>



<p>Run the container:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Getting Started with Docker for Machine Learning and MLOps" data-enlighter-group="30">docker run -it ml-docker-demo:cpu</pre>



<p>We see the MNIST dataset download (into <code data-enlighter-language="python" class="EnlighterJSRAW">/app/data</code> inside the container) and 1 epoch of training logs.</p>



<h3 class="wp-block-heading">Step 3: Prove Reproducibility</h3>



<p>Now, share our image with a teammate or push it to a registry:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Getting Started with Docker for Machine Learning and MLOps" data-enlighter-group="31">docker tag ml-docker-demo:cpu &lt;your-dockerhub-username>/ml-docker-demo:cpu
docker push &lt;your-dockerhub-username>/ml-docker-demo:cpu</pre>



<p>Our teammate (or a cloud server) can now pull and run the exact same 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="Getting Started with Docker for Machine Learning and MLOps" data-enlighter-group="32">docker pull &lt;your-dockerhub-username>/ml-docker-demo:cpu
docker run -it &lt;your-dockerhub-username>/ml-docker-demo:cpu</pre>



<p>The results (e.g., dataset download, logs, and training behavior) will match ours, regardless of what OS or CUDA drivers are on their machine. That is reproducibility in action.</p>



<h3 class="wp-block-heading">Step 4: Extend the Experiment</h3>



<p>Try overriding defaults:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Getting Started with Docker for Machine Learning and MLOps" data-enlighter-group="33"># Run training with a custom number of epochs
docker run -it --env EPOCHS=5 ml-docker-demo:cpu python train.py</pre>



<p>Or mount datasets from our host:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Getting Started with Docker for Machine Learning and MLOps" data-enlighter-group="34">docker run -it -v $(pwd)/data:/app/data ml-docker-demo:cpu</pre>



<h3 class="wp-block-heading">Step 5: Reflection</h3>



<p>With this demo, we have proven the value of Docker in MLOps:</p>



<ul class="wp-block-list">
<li>Our ML project is now <strong>portable and reproducible</strong>.</li>



<li>Collaborators can run our code without setup headaches.</li>



<li>The same container can later be deployed to Amazon ECS, Lambda, or Kubernetes.</li>
</ul>



<p>This completes the 2nd lesson in our MLOps series: <strong>Getting Started with Docker for Machine Learning and MLOps</strong>.</p>



<p>In the next and final lesson of this series (<strong>Lesson 3: Production-Ready Docker for MLOps</strong>), we will cover multi-stage builds, Docker Compose, GPU-enabled images, and best practices for CI/CD pipelines.</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 of on-demand code walkthrough videos • Last updated: November 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</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 learned why Docker is the foundation of modern MLOps. We started with the “it works on my machine” problem and saw how Docker solves reproducibility issues that plague machine learning projects. We explored Docker fundamentals and architecture, got hands-on with essential commands, and built our first ML <code data-enlighter-language="python" class="EnlighterJSRAW">Dockerfile</code> for a PyTorch Lightning MNIST trainer.</p>



<p>Along the way, we covered best practices for creating lean and secure images, how to handle data and environment variables properly, and why we should avoid baking datasets into containers. We also looked at GPU support, graceful shutdowns, and alternatives (e.g., Podman and Apptainer).</p>



<p>Finally, we put it all together in a hands-on demo that proved our ML project runs consistently across environments. With these skills, we now have the foundation to containerize machine learning workflows reliably: a crucial first step before moving on to deployment, orchestration, and scaling in the next lessons.</p>



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



<p><strong>Singh, V. </strong>“Getting Started with Docker for Machine Learning and MLOps,” <em>PyImageSearch</em>, S. Huot, A. Sharma, and P. Thakur, eds., 2026, <a href="https://pyimg.co/flyvj" target="_blank" rel="noreferrer noopener">https://pyimg.co/flyvj</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="Getting Started with Docker for Machine Learning and MLOps" data-enlighter-group="35">@incollection{Singh_2026_getting-started-docker-machine-learning-mlops,
  author = {Vikram Singh},
  title = {{Getting Started with Docker for Machine Learning and MLOps}},
  booktitle = {PyImageSearch},
  editor = {Susan Huot and Aditya Sharma and Piyush Thakur},
  year = {2026},
  url = {https://pyimg.co/flyvj},
}
</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/11/16/getting-started-with-docker-for-machine-learning-and-mlops/">Getting Started with Docker for Machine Learning and MLOps</a> appeared first on <a rel="nofollow" href="https://pyimagesearch.com">PyImageSearch</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>What Is MLOps? Architecture, MLOps vs DevOps, and LLMOps</title>
		<link>https://pyimagesearch.com/2026/11/09/what-is-mlops-architecture-mlops-vs-devops-and-llmops/</link>
		
		<dc:creator><![CDATA[Vikram Singh]]></dc:creator>
		<pubDate>Mon, 09 Nov 2026 13:45:00 +0000</pubDate>
				<category><![CDATA[DevOps]]></category>
		<category><![CDATA[LLMOps]]></category>
		<category><![CDATA[Machine Learning]]></category>
		<category><![CDATA[MLOps]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[experiment tracking]]></category>
		<category><![CDATA[linux]]></category>
		<category><![CDATA[llmops]]></category>
		<category><![CDATA[machine learning operations]]></category>
		<category><![CDATA[mlops]]></category>
		<category><![CDATA[mlops architecture]]></category>
		<category><![CDATA[mlops maturity levels]]></category>
		<category><![CDATA[mlops vs devops]]></category>
		<category><![CDATA[model deployment]]></category>
		<category><![CDATA[model monitoring]]></category>
		<category><![CDATA[tutorial]]></category>
		<guid isPermaLink="false">https://pyimagesearch.com/?p=55877</guid>

					<description><![CDATA[<p>Table of Contents What Is MLOps? Architecture, MLOps vs DevOps, and LLMOps What Is MLOps? Why MLOps Matters for Production Machine Learning Core Principles of MLOps 1. Automation 2. Reproducibility 3. Scalability 4. Monitoring and Governance MLOps vs DevOps: Key&#8230;</p>
<p>The post <a rel="nofollow" href="https://pyimagesearch.com/2026/11/09/what-is-mlops-architecture-mlops-vs-devops-and-llmops/">What Is MLOps? Architecture, MLOps vs DevOps, and LLMOps</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-What-Is-MLOps-Architecture-MLOps-vs-DevOps-and-LLMOps"><a rel="noopener" target="_blank" href="#h1-What-Is-MLOps-Architecture-MLOps-vs-DevOps-and-LLMOps">What Is MLOps? Architecture, MLOps vs DevOps, and LLMOps</a></li>
    <li id="TOC-h2-What-Is-MLOps"><a rel="noopener" target="_blank" href="#h2-What-Is-MLOps">What Is MLOps?</a></li>
    <li id="TOC-h2-Why-MLOps-Matters-for-Production-Machine-Learning"><a rel="noopener" target="_blank" href="#h2-Why-MLOps-Matters-for-Production-Machine-Learning">Why MLOps Matters for Production Machine Learning</a></li>
    <li id="TOC-h2-Core-Principles-of-MLOps"><a rel="noopener" target="_blank" href="#h2-Core-Principles-of-MLOps">Core Principles of MLOps</a>
        <ul>
            <li id="TOC-h3-1-Automation"><a rel="noopener" target="_blank" href="#h3-1-Automation">1. Automation</a></li>
            <li id="TOC-h3-2-Reproducibility"><a rel="noopener" target="_blank" href="#h3-2-Reproducibility">2. Reproducibility</a></li>
            <li id="TOC-h3-3-Scalability"><a rel="noopener" target="_blank" href="#h3-3-Scalability">3. Scalability</a></li>
            <li id="TOC-h3-4-Monitoring-and-Governance"><a rel="noopener" target="_blank" href="#h3-4-Monitoring-and-Governance">4. Monitoring and Governance</a></li>
        </ul>
    </li>
    <li id="TOC-h2-MLOps-vs-DevOps-Key-Lifecycle-Differences"><a rel="noopener" target="_blank" href="#h2-MLOps-vs-DevOps-Key-Lifecycle-Differences">MLOps vs DevOps: Key Lifecycle Differences</a></li>
    <li id="TOC-h2-MLOps-Architecture-How-It-All-Fits-Together"><a rel="noopener" target="_blank" href="#h2-MLOps-Architecture-How-It-All-Fits-Together">MLOps Architecture: How It All Fits Together</a>
        <ul>
            <li id="TOC-h3-Data-Layer"><a rel="noopener" target="_blank" href="#h3-Data-Layer">Data Layer</a></li>
            <li id="TOC-h3-Experimentation-and-Training-Layer"><a rel="noopener" target="_blank" href="#h3-Experimentation-and-Training-Layer">Experimentation and Training Layer</a></li>
            <li id="TOC-h3-Deployment-Layer"><a rel="noopener" target="_blank" href="#h3-Deployment-Layer">Deployment Layer</a></li>
            <li id="TOC-h3-Monitoring-and-Feedback-Layer"><a rel="noopener" target="_blank" href="#h3-Monitoring-and-Feedback-Layer">Monitoring and Feedback Layer</a></li>
            <li id="TOC-h3-Governance-and-Compliance-Layer"><a rel="noopener" target="_blank" href="#h3-Governance-and-Compliance-Layer">Governance and Compliance Layer</a></li>
        </ul>
    </li>
    <li id="TOC-h2-MLOps-Maturity-Levels"><a rel="noopener" target="_blank" href="#h2-MLOps-Maturity-Levels">MLOps Maturity Levels</a>
        <ul>
            <li id="TOC-h3-Level-0-Manual-and-Ad-Hoc"><a rel="noopener" target="_blank" href="#h3-Level-0-Manual-and-Ad-Hoc">Level 0: Manual and Ad Hoc</a></li>
            <li id="TOC-h3-Level-1-Partial-Automation"><a rel="noopener" target="_blank" href="#h3-Level-1-Partial-Automation">Level 1: Partial Automation</a></li>
            <li id="TOC-h3-Level-2-Full-Automation"><a rel="noopener" target="_blank" href="#h3-Level-2-Full-Automation">Level 2: Full Automation</a></li>
        </ul>
    </li>
    <li id="TOC-h2-MLOps-Tools-for-Data-Training-Deployment-and-Monitoring"><a rel="noopener" target="_blank" href="#h2-MLOps-Tools-for-Data-Training-Deployment-and-Monitoring">MLOps Tools for Data, Training, Deployment, and Monitoring</a>
        <ul>
            <li id="TOC-h3-Tools-for-Data-Versioning-and-Experiment-Tracking"><a rel="noopener" target="_blank" href="#h3-Tools-for-Data-Versioning-and-Experiment-Tracking">Tools for Data Versioning and Experiment Tracking</a></li>
            <li id="TOC-h3-Model-Training-Frameworks-and-Feature-Stores"><a rel="noopener" target="_blank" href="#h3-Model-Training-Frameworks-and-Feature-Stores">Model Training Frameworks and Feature Stores</a></li>
            <li id="TOC-h3-Model-Serving-Deployment-and-Monitoring-Tools"><a rel="noopener" target="_blank" href="#h3-Model-Serving-Deployment-and-Monitoring-Tools">Model Serving, Deployment, and Monitoring Tools</a></li>
            <li id="TOC-h3-End-to-End-Machine-Learning-Platforms"><a rel="noopener" target="_blank" href="#h3-End-to-End-Machine-Learning-Platforms">End-to-End Machine Learning Platforms</a></li>
        </ul>
    </li>
    <li id="TOC-h2-What-Is-LLMOps-Operations-for-Large-Language-Models"><a rel="noopener" target="_blank" href="#h2-What-Is-LLMOps-Operations-for-Large-Language-Models">What Is LLMOps? Operations for Large Language Models</a></li>
    <li id="TOC-h2-LLMOps-vs-MLOps-Key-Differences"><a rel="noopener" target="_blank" href="#h2-LLMOps-vs-MLOps-Key-Differences">LLMOps vs MLOps: Key Differences</a></li>
    <li id="TOC-h2-Linux-Basics-for-MLOps"><a rel="noopener" target="_blank" href="#h2-Linux-Basics-for-MLOps">Linux Basics for MLOps</a>
        <ul>
            <li id="TOC-h3-Why-Linux-Matters-for-MLOps-Workflows"><a rel="noopener" target="_blank" href="#h3-Why-Linux-Matters-for-MLOps-Workflows">Why Linux Matters for MLOps Workflows</a></li>
            <li id="TOC-h3-Starter-Commands-for-Everyday-Use"><a rel="noopener" target="_blank" href="#h3-Starter-Commands-for-Everyday-Use">Starter Commands for Everyday Use</a></li>
        </ul>
    </li>
    <li id="TOC-h2-Summary"><a rel="noopener" target="_blank" href="#h2-Summary">Summary</a>
        <ul>
            <li id="TOC-h3-Citation-Information"><a rel="noopener" target="_blank" href="#h3-Citation-Information">Citation Information</a></li>
        </ul>
    </li>
</ul>
</div>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h1-What-Is-MLOps-Architecture-MLOps-vs-DevOps-and-LLMOps"/>



<h2 class="wp-block-heading"><a href="#TOC-h1-What-Is-MLOps-Architecture-MLOps-vs-DevOps-and-LLMOps">What Is MLOps? Architecture, MLOps vs DevOps, and LLMOps</a></h2>



<p>In this lesson, you will learn what MLOps is and why it is essential for scaling machine learning systems. We will explore how MLOps extends DevOps to manage not just code, but also data, models, and experiments, and compare the DevOps and MLOps lifecycles. </p>


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


<p>You will also get a high-level view of MLOps architecture, see how teams progress through maturity levels, and cover the MLOps tooling landscape from foundations to serving, deployment, and cloud platforms.</p>



<p>Along the way, we will include a short Linux basics primer (most modern MLOps/MLflow workflows run on Linux) to prepare readers for hands-on work in future lessons.</p>



<p>Finally, we will touch on LLMOps to understand what it is, how it relates to MLOps, and why it is becoming critical in the era of large language models.</p>



<p>This lesson is the 1st in a 3-part series on <strong>Machine Learning Operations (MLOps)</strong>:</p>



<ol class="wp-block-list">
<li><em><strong><a href="https://pyimg.co/dqztp" target="_blank" rel="noreferrer noopener">What Is MLOps? Architecture, MLOps vs DevOps, and LLMOps</a></strong></em><strong> (this tutorial)</strong></li>



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



<li><em>Lesson 3</em></li>
</ol>



<p><strong>To learn how to apply MLOps</strong><strong>, including </strong><strong>what it is, how it differs from DevOps, and where concepts </strong><strong>such as</strong><strong> MLOps architecture and LLMOps fit in, </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-What-Is-MLOps"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-What-Is-MLOps">What Is MLOps?</a></h2>



<p>At its core, <strong>MLOps (Machine Learning Operations)</strong> extends DevOps principles to the world of machine learning (ML). If DevOps is about managing the <strong>software lifecycle</strong> (from code to deployment), then MLOps is about managing the <strong>entire ML lifecycle</strong>: code, data, models, and experiments.</p>



<p>The key difference lies in what gets released. In traditional software, once you ship a binary, it stays the same until developers update the code. In machine learning, models are <strong>living artifacts</strong>. Their performance degrades as data distributions shift, and they require ongoing retraining or fine-tuning to stay useful.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/11/image-16-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="642" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-16-1024x642.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-55894"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-16-1024x642.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-16-1024x642.png?size=126x79&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-16-1024x642.png?size=252x158&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-16-1024x642.png?size=378x237&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-16-1024x642.png?size=504x316&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-16-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 1:</strong> Traditional software releases only code, while ML releases also depend on data and model parameters (source: image by the author)</figcaption></figure></div>


<p>But it is not just about the release. In ML systems, <strong>all </strong><strong>3</strong><strong> components </strong><strong>(</strong><strong>code, data, and models</strong><strong>)</strong><strong> evolve together</strong>.</p>



<ul class="wp-block-list">
<li>New data arrives and may require relabeling.</li>



<li>Models must be retrained or replaced to keep up.</li>



<li>Code (algorithms, preprocessing, and infrastructure) adapts alongside them.</li>
</ul>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://pyimagesearch.com/wp-content/uploads/2026/11/image-17.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="624" height="323" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-17.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-55896"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-17.png?size=126x65&lossy=2&strip=1&webp=1 126w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-17-300x155.png?lossy=2&strip=1&webp=1 300w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-17.png?size=378x196&lossy=2&strip=1&webp=1 378w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-17.png?size=504x261&lossy=2&strip=1&webp=1 504w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-17.png?lossy=2&strip=1&webp=1 624w" sizes="(max-width: 624px) 100vw, 624px" /></a><figcaption class="wp-element-caption"><strong>Figure 2:</strong> In ML applications, <strong>data, model, and code form a continuous feedback loop</strong>, with each change triggering updates to the others (source: <a href="https://ml-ops.org" target="_blank" rel="noreferrer noopener">https://ml-ops.org</a>).</figcaption></figure></div>


<p>This makes MLOps far more than just “DevOps + ML.” It is a discipline designed to:</p>



<ul class="wp-block-list">
<li>Version and track not only <strong>code</strong>, but also <strong>datasets and models</strong>.</li>



<li>Automate <strong>training, testing, and deployment pipelines</strong>.</li>



<li>Continuously <strong>monitor for drift</strong> and trigger retraining loops.</li>



<li>Ensure <strong>reproducibility</strong> across experiments and environments.</li>
</ul>



<p>In short, MLOps is the <strong>glue</strong> that connects research notebooks to production systems. It helps turn fragile prototypes into <strong>reliable, scalable, and maintainable applications</strong>.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Why-MLOps-Matters-for-Production-Machine-Learning"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Why-MLOps-Matters-for-Production-Machine-Learning">Why MLOps Matters for Production Machine Learning</a></h2>



<p>It is easy to underestimate the gap between a great model in a Jupyter notebook and a robust system in production. Without MLOps, most teams hit the same pain points over and over:</p>



<ul class="wp-block-list">
<li><strong>“It works on my machine” syndrome:</strong> Running the same code on another machine gives different results because the data, libraries, or environment are not identical.</li>



<li><strong>Model decay:</strong> Accuracy steadily drops after deployment as real-world data drifts away from training data.</li>



<li><strong>Data chaos:</strong> No clear versioning or lineage for datasets. Teams cannot reproduce past experiments.</li>



<li><strong>Wasted effort:</strong> Without experiment tracking, teams repeat trials that were already run but never logged.</li>
</ul>



<p>The consequences are not academic. They are expensive.</p>



<ul class="wp-block-list">
<li>Recommendation systems stop showing relevant items when customer behavior changes.</li>



<li>Fraud detection pipelines fail to keep up with new attack patterns.</li>



<li>Large language models require ongoing prompt updates and fine-tuning to remain useful.</li>
</ul>



<p>MLOps addresses these problems head-on:</p>



<ul class="wp-block-list">
<li><strong>Reproducibility:</strong> lock down code, data, and models so results can be recreated exactly.</li>



<li><strong>Reliability:</strong> models are deployed through pipelines, not copy-paste scripts.</li>



<li><strong>Scalability:</strong> teams can retrain and redeploy with automation instead of manual handoffs.</li>



<li><strong>Collaboration:</strong> data scientists, ML engineers, and DevOps teams work on a shared process.</li>
</ul>



<p>When you adopt MLOps, models do not just “work once.” They keep working in production, evolving alongside the data they serve.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Core-Principles-of-MLOps"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Core-Principles-of-MLOps">Core Principles of MLOps</a></h2>



<p>MLOps is not just a set of tools. It is a set of principles that guide how machine learning systems are built, deployed, and maintained. A solid MLOps practice rests on the following 4 pillars.</p>



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



<h3 class="wp-block-heading"><a href="#TOC-h3-1-Automation">1. Automation</a></h3>



<p>The goal is to minimize manual handoffs. Data pipelines, training jobs, model packaging, and deployment should run automatically through continuous integration and continuous delivery (CI/CD) pipelines. Automation reduces human error and shortens the time from experiment to production.</p>



<p><strong>Example:</strong> Instead of a data scientist manually exporting a trained model, a pipeline retrains nightly and deploys the new version if it meets accuracy thresholds.</p>



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



<h3 class="wp-block-heading"><a href="#TOC-h3-2-Reproducibility">2. Reproducibility</a></h3>



<p>Every model should be reproducible: same code, same data, same parameters → same result. This requires versioning not just of code, but also datasets, features, and model weights.</p>



<p><strong>Example:</strong> MLflow or DVC can log experiments so you can revisit the exact conditions that produced a model months later.</p>



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



<h3 class="wp-block-heading"><a href="#TOC-h3-3-Scalability">3. Scalability</a></h3>



<p>Prototypes often run on a laptop, but production models serve millions of predictions daily. MLOps ensures systems can scale horizontally (more replicas) and vertically (more compute), while pipelines handle larger datasets seamlessly.</p>



<p><strong>Example:</strong> A fraud detection model that worked for thousands of transactions now needs to score millions. Kubernetes or serverless deployment can scale it without code changes.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-4-Monitoring-and-Governance"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-4-Monitoring-and-Governance">4. Monitoring and Governance</a></h3>



<p>Models cannot be “deploy once and forget.” Monitoring ensures that accuracy, latency, and drift are tracked continuously. Governance establishes controls and documentation that support compliance (fairness, privacy, and explainability) in regulated industries.</p>



<p><strong>Example:</strong> A credit scoring model must flag if predictions start showing bias toward a subgroup, triggering retraining or human review.</p>



<p>Together, these pillars keep ML systems reliable, accountable, and future-proof. They also map directly to the MLOps lifecycle: </p>



<ul class="wp-block-list">
<li><strong>automation:</strong> powers the pipelines</li>



<li><strong>reproducibility:</strong> secures experiments</li>



<li><strong>scalability:</strong> supports deployment</li>



<li><strong>monitoring and governance:</strong> closes the loop</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-MLOps-vs-DevOps-Key-Lifecycle-Differences"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-MLOps-vs-DevOps-Key-Lifecycle-Differences">MLOps vs DevOps: Key Lifecycle Differences</a></h2>



<p>DevOps transformed how software teams build and ship applications. The process is well-defined: <strong>build → test → deploy → monitor</strong>. Once an application is shipped, it generally behaves the same until developers update the code.</p>



<p>Machine learning lifecycles look similar at a distance, but they introduce critical differences:</p>



<ul class="wp-block-list">
<li><strong>Data is first-class:</strong> The lifecycle does not start with “build.” It starts with <strong>data collection and preprocessing</strong>.</li>



<li><strong>Validation goes beyond tests:</strong> Instead of just running unit tests, ML workflows validate against metrics such as accuracy, precision, or F1 score.</li>



<li><strong>Models evolve:</strong> Monitoring is not just about uptime; it is about detecting <strong>drift</strong>. A healthy model may still lose accuracy as the real world changes.</li>



<li><strong>Retraining closes the loop:</strong> Unlike software, where updates are developer-driven, ML requires automatic or scheduled <strong>retraining cycles</strong>.</li>
</ul>



<p>A side-by-side comparison makes it clear (see <strong>Figure 3</strong>).</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/11/image-18-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="336" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-18-1024x336.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-55897"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-18-1024x336.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-18-1024x336.png?size=126x41&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-18-1024x336.png?size=252x83&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-18-1024x336.png?size=378x124&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-18-1024x336.png?size=504x165&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-18-1024x336.png?size=630x207&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 3:</strong> DevOps vs MLOps lifecycles. MLOps introduces data, validation, and retraining loops that traditional DevOps does not cover (source: <a href="https://www.databricks.com/blog/what-is-mlops" target="_blank" rel="noreferrer noopener">https://www.databricks.com/blog/what-is-mlops</a>).</figcaption></figure></div>


<p>Notice how MLOps extends DevOps with additional steps for data, validation, and retraining.</p>



<p>The extra loops (data, validation, and retraining) are why MLOps needs its own discipline. Traditional DevOps tooling does not fully capture these dynamics.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-MLOps-Architecture-How-It-All-Fits-Together"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-MLOps-Architecture-How-It-All-Fits-Together">MLOps Architecture: How It All Fits Together</a></h2>



<p>MLOps is not just a collection of tools. It is an <strong>architecture</strong> that ties together the entire machine learning lifecycle. The goal is to ensure that data, models, and code move seamlessly from experimentation to production while remaining reproducible, scalable, and reliable.</p>



<p>At the highest level, the MLOps lifecycle can be thought of in <strong>3</strong><strong> interconnected stages</strong> (see <strong>Figure 4</strong>).</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/11/image-3-scaled.jpeg" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="767" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-3-1024x767.jpeg?lossy=2&strip=1&webp=1" alt="" class="wp-image-55898"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-3-1024x767.jpeg?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-3-1024x767.jpeg?size=126x94&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-3-1024x767.jpeg?size=252x189&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-3-1024x767.jpeg?size=378x283&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-3-1024x767.jpeg?size=504x378&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-3-1024x767.jpeg?size=630x472&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 4:</strong> High-level MLOps lifecycle: <em>Design → Model Development → Operations.</em> Each of these stages expands into more detailed layers in a full MLOps architecture (source: <a href="https://ml-ops.org/content/mlops-principles" target="_blank" rel="noreferrer noopener">MLOps Principles</a>)</figcaption></figure></div>


<ul class="wp-block-list">
<li><strong>Design:</strong> requirements engineering, use case prioritization, data availability checks</li>



<li><strong>Model Development:</strong> data engineering, model training, validation, iteration</li>



<li><strong>Operations:</strong> deployment, CI/CD pipelines, monitoring, feedback loops</li>
</ul>



<p>While this 3-stage view captures the essence, in practice each stage is supported by multiple layers and tools. A typical MLOps architecture looks like this:</p>



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



<h3 class="wp-block-heading"><a href="#TOC-h3-Data-Layer">Data Layer</a></h3>



<ul class="wp-block-list">
<li>Data ingestion (databases, APIs, streams)</li>



<li>Storage (data lakes, warehouses)</li>



<li>Versioning (<strong>DVC, </strong><strong>l</strong><strong>akeFS</strong>)</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Experimentation-and-Training-Layer"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Experimentation-and-Training-Layer">Experimentation and Training Layer</a></h3>



<ul class="wp-block-list">
<li>Prototyping (<strong>Jupyter, Colab, scripts</strong>)</li>



<li>Training pipelines (<strong>Kubeflow, Airflow, SageMaker</strong>)</li>



<li>Experiment tracking and model registry (<strong>MLflow, W&amp;B</strong>)</li>
</ul>



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



<h3 class="wp-block-heading"><a href="#TOC-h3-Deployment-Layer">Deployment Layer</a></h3>



<ul class="wp-block-list">
<li>Model packaging (<strong>Docker, ONNX, TorchServe</strong>)</li>



<li>Serving APIs (<strong>FastAPI, Flask, KServe, Lambda</strong>)</li>



<li>CI/CD pipelines for model delivery</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Monitoring-and-Feedback-Layer"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Monitoring-and-Feedback-Layer">Monitoring and Feedback Layer</a></h3>



<ul class="wp-block-list">
<li>Model performance metrics (accuracy, latency, drift detection)</li>



<li>Infrastructure monitoring (<strong>Prometheus, Grafana</strong>)</li>



<li>Feedback loops triggering retraining</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Governance-and-Compliance-Layer"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Governance-and-Compliance-Layer">Governance and Compliance Layer</a></h3>



<ul class="wp-block-list">
<li>Audit trails for data and models</li>



<li>Explainability and fairness checks</li>



<li>Security and access control</li>
</ul>



<p>Together, these layers form a <strong>closed loop</strong>: data flows in, models are trained and deployed, predictions are monitored, and results feed back into retraining pipelines.</p>



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



<h2 class="wp-block-heading"><a href="#TOC-h2-MLOps-Maturity-Levels">MLOps Maturity Levels</a></h2>



<p>Not every team practices MLOps at the same depth. Just as DevOps adoption matures over time, MLOps also has levels of sophistication. Understanding these levels helps teams assess where they stand today and what is next on their roadmap.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Level-0-Manual-and-Ad-Hoc"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Level-0-Manual-and-Ad-Hoc">Level 0: Manual and Ad Hoc</a></h3>



<ul class="wp-block-list">
<li>Experiments live in notebooks or scripts on individual machines.</li>



<li>Data is not versioned, and results cannot be reproduced.</li>



<li>Deployment might mean copying a <code data-enlighter-language="python" class="EnlighterJSRAW">.pkl</code> file to a server.</li>



<li>Monitoring is manual, if it happens at all.</li>
</ul>



<p><strong>Risk:</strong> High chance of “it worked once, but we don’t know why.”</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Level-1-Partial-Automation"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Level-1-Partial-Automation">Level 1: Partial Automation</a></h3>



<ul class="wp-block-list">
<li>Some reproducibility through version control (Git) and basic experiment tracking (e.g., MLflow).</li>



<li>Pipelines exist but may be stitched together manually.</li>



<li>Deployment is more structured, but retraining cycles are still irregular.</li>



<li>Monitoring might check uptime, but drift detection is weak.</li>
</ul>



<p><strong>Benefit:</strong> Teams save time by reusing pipelines, but scaling is still painful.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Level-2-Full-Automation"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Level-2-Full-Automation">Level 2: Full Automation</a></h3>



<ul class="wp-block-list">
<li>End-to-end pipelines handle data ingestion, training, validation, and deployment.</li>



<li>CI/CD is fully integrated, with automated testing of models.</li>



<li>Drift monitoring triggers retraining loops automatically.</li>



<li>Governance, audit trails, and compliance are built in.</li>
</ul>



<p><strong>Benefit:</strong> Models evolve smoothly with data, and the business can trust ML systems long-term.</p>



<p>Most organizations start at Level 0 or 1 and gradually build toward Level 2. The key is progress: every step toward automation and reproducibility reduces technical debt and unlocks scalability.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-MLOps-Tools-for-Data-Training-Deployment-and-Monitoring"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-MLOps-Tools-for-Data-Training-Deployment-and-Monitoring">MLOps Tools for Data, Training, Deployment, and Monitoring</a></h2>



<p>Talking about MLOps without mentioning tools would feel incomplete. But instead of diving deep into each one right now, let us zoom out and map the ecosystem. Think of this as a <strong>preview of what is coming in future lessons</strong>.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/11/image-19-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="594" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-19-1024x594.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-55900"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-19-1024x594.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-19-1024x594.png?size=126x73&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-19-1024x594.png?size=252x146&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-19-1024x594.png?size=378x219&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-19-1024x594.png?size=504x292&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-19-1024x594.png?size=630x365&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 5:</strong> The MLOps tooling ecosystem spans data management, modeling, deployment, and end-to-end ML platforms (source: <a href="https://www.datacamp.com/blog/infographic-data-and-machine-learning-tools-landscape" target="_blank" rel="noreferrer noopener">[Infographic] Data &amp; Machine Learning Tools Landscape | DataCamp</a>)</figcaption></figure></div>


<p>This ecosystem is huge, covering everything from managing datasets to serving models in production. To keep things practical, we will focus on a few core categories that we will explore in depth throughout the series.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Tools-for-Data-Versioning-and-Experiment-Tracking"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Tools-for-Data-Versioning-and-Experiment-Tracking">Tools for Data Versioning and Experiment Tracking</a></h3>



<ul class="wp-block-list">
<li><strong>Docker:</strong> containerizes ML applications for portability.</li>



<li><strong>DVC (Data Version Control):</strong> versions datasets and pipelines.</li>



<li><strong>MLflow / Weights &amp; Biases (W&amp;B):</strong> experiment tracking and model registry.</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Model-Training-Frameworks-and-Feature-Stores"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Model-Training-Frameworks-and-Feature-Stores">Model Training Frameworks and Feature Stores</a></h3>



<ul class="wp-block-list">
<li><strong>PyTorch Lightning:</strong> structures training code for reproducibility.</li>



<li><strong>TensorFlow</strong><strong>,</strong><strong> PyTorch</strong><strong>, and</strong><strong> XGBoost:</strong> are frameworks for training deep learning and classical ML models.</li>



<li><strong>Feature Stores:</strong> manage and reuse features consistently across training and serving.</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Model-Serving-Deployment-and-Monitoring-Tools"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Model-Serving-Deployment-and-Monitoring-Tools">Model Serving, Deployment, and Monitoring Tools</a></h3>



<ul class="wp-block-list">
<li><strong>FastAPI:</strong> is a lightweight API for serving ML models</li>



<li><strong>TorchServe:</strong> is a production model serving framework for PyTorch</li>



<li><strong>AWS SageMaker, ECS, and Lambda:</strong> are cloud-native deployment options</li>



<li><strong>Model Monitoring:</strong> tools such as Evidently, Arize, or WhyLabs help detect accuracy and fairness issues in production</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-End-to-End-Machine-Learning-Platforms"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-End-to-End-Machine-Learning-Platforms">End-to-End Machine Learning Platforms</a></h3>



<ul class="wp-block-list">
<li><strong>AWS SageMaker, Azure ML, Databricks, DataRobot:</strong> are end-to-end platforms that combine data, training, deployment, and monitoring into one managed environment.</li>
</ul>



<p>The key takeaway: <strong>no team uses everything at once.</strong> The best tools are the ones that serve <em>your workflow</em>. As we move through this series, we will piece these building blocks together, showing how to combine them into an end-to-end MLOps practice.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-What-Is-LLMOps-Operations-for-Large-Language-Models"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-What-Is-LLMOps-Operations-for-Large-Language-Models">What Is LLMOps? Operations for Large Language Models</a></h2>



<p>As large language models (LLMs) such as GPT (Generative Pre-trained Transformer), LLaMA, and Mistral have moved from research into production, they have introduced new operational challenges. Traditional MLOps practices still apply, but the scale, complexity, and open-ended nature of LLMs demand their own extension: LLMOps.</p>



<p>At a high level, LLMOps is about applying the same principles of MLOps (automation, reproducibility, scalability, and monitoring) but adapting them to the unique requirements of LLMs:</p>



<ul class="wp-block-list">
<li><strong>Model Size and Serving:</strong> Unlike smaller ML models, LLMs often contain billions of parameters. Serving them requires <strong>distributed inference</strong>, <strong>quantization</strong>, or specialized GPU/TPU acceleration. Some companies even use hardware-aware optimizers (e.g., <em>OctoML, Neural Magic</em>) to squeeze efficiency out of large deployments.</li>



<li><strong>Continuous Adaptation:</strong> Instead of retraining from scratch, teams often fine-tune with <strong>LoRA, adapters, or parameter-efficient training methods</strong>. On top of that, <strong>prompt engineering platforms</strong> (e.g., <em>PromptLayer, Vellum</em>) allow non-technical teams to manage prompts as first-class artifacts.</li>



<li><strong>Retrieval-Augmented Generation (RAG):</strong> LLMs connected to external knowledge bases can stay up to date. This introduces new infrastructure needs such as <strong>vector databases</strong> (e.g., <em>Pinecone, Weaviate, Chroma</em>) and <strong>data curation pipelines</strong> (e.g., <em>Scale AI, Snorkel</em>).</li>



<li><strong>Evaluation and Safety:</strong> Unlike a classifier, which can be measured with accuracy or F1, LLMs produce open-ended text. Evaluating them requires <strong>new metrics</strong> (helpfulness, toxicity, hallucination rate), <strong>human feedback loops</strong>, and <strong>advanced monitoring/guardrails</strong> (e.g., <em>Evidently, Arize, WhyLabs, Fiddler</em>).</li>
</ul>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/11/image-20-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="773" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-20-1024x773.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-55903"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-20-1024x773.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-20-1024x773.png?size=126x95&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-20-1024x773.png?size=252x190&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-20-1024x773.png?size=378x285&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-20-1024x773.png?size=504x380&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-20-1024x773.png?size=630x476&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 6:</strong> The emerging LLMOps tooling ecosystem spans everything from data annotation and vector databases for RAG to prompt engineering, deployment frameworks, and monitoring platforms, highlighting how this field is evolving beyond traditional MLOps (source: CB Insights <a href="https://assets.zilliz.com/LLM_Ops_market_landscape_6ac51baf56.png" target="_blank" rel="noreferrer noopener">LLM_Ops_market_landscape_6ac51baf56.png</a>).</figcaption></figure></div>


<p>In short: LLMOps is MLOps, evolved for the LLM era. It builds on the same foundation but emphasizes scalable deployment, resource optimization, continuous adaptation, and safe usage at scale.</p>



<p>We will dive deeper into LLMOps in the advanced lessons of this series, where we will look at how to finetune and deploy LLMs, integrate retrieval pipelines, and set up monitoring for safety. For now, it is enough to recognize that just as MLOps became essential for productionizing ML, LLMOps is quickly becoming essential for productionizing LLMs.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-LLMOps-vs-MLOps-Key-Differences"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-LLMOps-vs-MLOps-Key-Differences">LLMOps vs MLOps: Key Differences</a></h2>



<p>MLOps and LLMOps share the same foundation i.e. bringing DevOps discipline to machine learning but the <strong>scale, complexity, and behavior of LLMs</strong> introduce new challenges that traditional MLOps does not fully address.</p>



<p><strong>Table 1</strong> compares MLOps and LLMOps.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://pyimagesearch.com/wp-content/uploads/2026/11/image-21.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="929" height="563" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-21.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-55905"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-21.png?size=126x76&lossy=2&strip=1&webp=1 126w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-21-300x182.png?lossy=2&strip=1&webp=1 300w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-21.png?size=378x229&lossy=2&strip=1&webp=1 378w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-21.png?size=504x305&lossy=2&strip=1&webp=1 504w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-21.png?size=630x382&lossy=2&strip=1&webp=1 630w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-21-768x465.png?lossy=2&strip=1&webp=1 768w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-21.png?lossy=2&strip=1&webp=1 929w" sizes="(max-width: 929px) 100vw, 929px" /></a><figcaption class="wp-element-caption"><strong>Table 1:</strong> Comparing MLOps and LLMOps workflows</figcaption></figure></div>


<p>In other words, <strong>LLMOps extends MLOps</strong> by adding specialized workflows for:</p>



<ul class="wp-block-list">
<li>handling massive models at inference time</li>



<li>updating models efficiently with lightweight fine-tuning</li>



<li>managing external retrieval pipelines</li>



<li>ensuring safe and aligned generation</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Linux-Basics-for-MLOps"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Linux-Basics-for-MLOps">Linux Basics for MLOps</a></h2>



<p>If you are serious about MLOps, you need to be comfortable with <strong>Linux</strong>. Many ML workloads (whether it runs on a cloud VM, in a Docker container, or on a Kubernetes cluster) will run on a Linux server.</p>



<p>Even if you are training models on your laptop today, the moment you deploy to production, you will be SSH-ing into Linux boxes, tailing logs, and debugging file permissions. The earlier you build muscle memory, the smoother everything else becomes.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Why-Linux-Matters-for-MLOps-Workflows"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Why-Linux-Matters-for-MLOps-Workflows">Why Linux Matters for MLOps Workflows</a></h3>



<ul class="wp-block-list">
<li><strong>Servers Run Linux:</strong> AWS EC2, GCP, and Azure all default to Linux images.</li>



<li><strong>Containers Use Linux:</strong> Docker and Kubernetes are built on Linux concepts (namespaces, cgroups).</li>



<li><strong>Automation Assumes Linux:</strong> CI/CD pipelines, shell scripts, and cron jobs live in a Linux environment.</li>
</ul>



<p>Learning Linux is not about memorizing 200 commands. It is about knowing the 20% of commands you will use 80% of the time.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Starter-Commands-for-Everyday-Use"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Starter-Commands-for-Everyday-Use">Starter Commands for Everyday Use</a></h3>



<h4 class="wp-block-heading">SSH (Secure Shell)</h4>



<p>SSH is a protocol used to securely log onto remote systems. It is used most often in the command-line interface for Unix-like systems such as Linux. SSH provides a secure channel over an unsecured network in a client-server architecture. For instance, if you are at a computer in New York and need to manage a server located in Tokyo, you could use SSH to log into the server and run commands as if you were there in person.</p>



<p><strong>Example:</strong></p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="What Is MLOps? Architecture, MLOps vs DevOps, and LLMOps" data-enlighter-group="1">ssh username@remotehost.com</pre>



<p>The above command logs you into <code data-enlighter-language="python" class="EnlighterJSRAW">remotehost.com</code> with the username <code data-enlighter-language="python" class="EnlighterJSRAW">username</code>.</p>



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



<p>Vim is a highly configurable text editor built to enable efficient text editing. It is an improved version of the vi editor distributed with most UNIX systems. It has many commands and is known for its keyboard-centered operation, which lets users perform tasks efficiently without the use of a mouse.</p>



<p><strong>Example:</strong></p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="What Is MLOps? Architecture, MLOps vs DevOps, and LLMOps" data-enlighter-group="2">vim filename.txt</pre>



<p>This command opens the file <code data-enlighter-language="python" class="EnlighterJSRAW">filename.txt</code> in Vim. If the file does not exist, it will be created. </p>



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



<p><code data-enlighter-language="python" class="EnlighterJSRAW">htop</code> is an interactive system-monitoring tool for Unix-based systems. It provides a real-time, dynamic view of the processes running on a system. <code data-enlighter-language="python" class="EnlighterJSRAW">htop</code> is much more interactive than the standard <code data-enlighter-language="python" class="EnlighterJSRAW">top</code> command. It allows for scrolling vertically and horizontally to display processes and complete command lines.</p>



<p><strong>Example:</strong></p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="What Is MLOps? Architecture, MLOps vs DevOps, and LLMOps" data-enlighter-group="3">htop</pre>



<p>This command will run <code data-enlighter-language="python" class="EnlighterJSRAW">htop</code>, displaying a real-time overview of system processes.</p>



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



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">ps</code> command in Unix and Linux is used to display information about active processes. It provides a snapshot of the current processes along with detailed information such as user identifier (ID), central processing unit (CPU) usage, memory usage, and command name.</p>



<p><strong>Example:</strong></p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="What Is MLOps? Architecture, MLOps vs DevOps, and LLMOps" data-enlighter-group="4">ps -aux</pre>



<p>The above command displays all processes from all users in a detailed format.</p>



<h4 class="wp-block-heading">scp (Secure Copy)</h4>



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">scp</code> command is used to securely copy files and directories between 2 locations. Like SSH, <code data-enlighter-language="python" class="EnlighterJSRAW">scp</code> uses the SSH protocol for data transfer.</p>



<p><strong>Example:</strong></p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="What Is MLOps? Architecture, MLOps vs DevOps, and LLMOps" data-enlighter-group="5">scp /path/to/local/file username@remotehost:/path/to/remote/directory</pre>



<p>The above command copies a local file to a remote directory.</p>



<h4 class="wp-block-heading">rsync (Remote Sync)</h4>



<p><code data-enlighter-language="python" class="EnlighterJSRAW">rsync</code> is a fast and versatile tool used for copying and synchronizing files both locally and remotely. <code data-enlighter-language="python" class="EnlighterJSRAW">rsync</code> is great for maintaining backups and mirroring data because it only transfers the difference between source and destination.</p>



<p><strong>Example:</strong></p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="What Is MLOps? Architecture, MLOps vs DevOps, and LLMOps" data-enlighter-group="6">rsync -avz /path/to/source/directory/ username@remotehost:/path/to/destination/directory/</pre>



<p>This command syncs the contents of the source directory to the destination directory. The <code data-enlighter-language="python" class="EnlighterJSRAW">-avz</code> flags enable archive mode (<code data-enlighter-language="python" class="EnlighterJSRAW">-a</code>), verbose output (<code data-enlighter-language="python" class="EnlighterJSRAW">-v</code>), and compression during transfer (<code data-enlighter-language="python" class="EnlighterJSRAW">-z</code>).</p>



<h4 class="wp-block-heading">tmux (Terminal Multiplexer)</h4>



<p><code data-enlighter-language="python" class="EnlighterJSRAW">tmux</code> is a terminal multiplexer. It allows you to switch easily between several programs in one terminal, detach them (they keep running in the background), and reattach them to a different terminal.</p>



<p><strong>Example:</strong></p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="What Is MLOps? Architecture, MLOps vs DevOps, and LLMOps" data-enlighter-group="7">tmux new -s train</pre>



<p>This command starts a new <code data-enlighter-language="python" class="EnlighterJSRAW">tmux</code> session. Within this session, you can create new windows (<code data-enlighter-language="python" class="EnlighterJSRAW">Ctrl+b c</code>), switch between windows (<code data-enlighter-language="python" class="EnlighterJSRAW">Ctrl+b n</code> for the next window), split windows into panes, and more.</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 of on-demand code walkthrough videos • Last updated: November 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</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 introduced MLOps and explained why it has become essential for scaling machine learning systems. We looked at how MLOps extends the principles of DevOps to manage not only code, but also the data, models, and experiments that make ML workflows unique. Along the way, we compared the DevOps and MLOps lifecycles, showing how additional practices (e.g., data validation, drift monitoring, and retraining) set MLOps apart.</p>



<p>We also explored the foundations of MLOps architecture, breaking it into stages and layers that connect data pipelines, training workflows, deployment systems, and monitoring. To make this practical, we discussed how teams progress through different maturity levels, from ad hoc scripts to fully automated pipelines that can retrain and redeploy models with minimal human intervention.</p>



<p>Another highlight was the MLOps tooling landscape. We mapped out the ecosystem from foundational tools (e.g., Docker, DVC, MLflow, and W&amp;B) to deployment tools (e.g., FastAPI, TorchServe, and KServe) and cloud platforms (e.g., AWS SageMaker, Azure ML, and Databricks). This gave us a preview of the technologies we will dive deeper into throughout the series.</p>



<p>To set the stage for hands-on work, we also included a short Linux basics primer. Since most modern MLOps and MLflow workflows run on Linux, learning essential commands now ensures you will be comfortable following along in future lessons.</p>



<p>Finally, we touched on LLMOps, exploring what it is, how it builds on MLOps, and why it is becoming critical in the era of large language models. As LLMs introduce new challenges (e.g., distributed inference, RAG pipelines, and safety monitoring), LLMOps is emerging as the natural evolution of MLOps.</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>Singh, V</strong><strong>. </strong>“What Is MLOps? Architecture, MLOps vs DevOps, and LLMOps,” <em>PyImageSearch</em>, S. Huot, A. Sharma, and P. Thakur, eds., 2026, <a href="https://pyimg.co/dqztp" target="_blank" rel="noreferrer noopener">https://pyimg.co/dqztp</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="What Is MLOps? Architecture, MLOps vs DevOps, and LLMOps" data-enlighter-group="8">@incollection{Singh_2026_mlops-architecture-mlops-devops-llmops,
  author = {Vikram Singh},
  title = {{What Is MLOps? Architecture, MLOps vs DevOps, and LLMOps}},
  booktitle = {PyImageSearch},
  editor = {Susan Huot and Aditya Sharma and Piyush Thakur},
  year = {2026},
  url = {https://pyimg.co/dqztp},
}
</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/11/09/what-is-mlops-architecture-mlops-vs-devops-and-llmops/">What Is MLOps? Architecture, MLOps vs DevOps, and LLMOps</a> appeared first on <a rel="nofollow" href="https://pyimagesearch.com">PyImageSearch</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Build a Real-Time Video Analytics Pipeline with YOLO26 and ByteTrack</title>
		<link>https://pyimagesearch.com/2026/11/02/build-a-real-time-video-analytics-pipeline-with-yolo26-and-bytetrack/</link>
		
		<dc:creator><![CDATA[Vikram Singh]]></dc:creator>
		<pubDate>Mon, 02 Nov 2026 13:45:00 +0000</pubDate>
				<category><![CDATA[Deep Learning]]></category>
		<category><![CDATA[Object Detection]]></category>
		<category><![CDATA[Object Tracking]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[bytetrack multi-object tracking]]></category>
		<category><![CDATA[bytetrack tracking algorithm]]></category>
		<category><![CDATA[opencv object tracking python]]></category>
		<category><![CDATA[people counting]]></category>
		<category><![CDATA[people counting system]]></category>
		<category><![CDATA[real-time video analytics]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[vehicle counting system]]></category>
		<category><![CDATA[yolo26]]></category>
		<guid isPermaLink="false">https://pyimagesearch.com/?p=55744</guid>

					<description><![CDATA[<p>Table of Contents Build a Real-Time Video Analytics Pipeline with YOLO26 and ByteTrack What Is Real-Time Video Analytics? Why Detection Alone Is Not Enough for People Counting and Vehicle Counting System Architecture for Real-Time Video Analytics Configuring Your Development Environment&#8230;</p>
<p>The post <a rel="nofollow" href="https://pyimagesearch.com/2026/11/02/build-a-real-time-video-analytics-pipeline-with-yolo26-and-bytetrack/">Build a Real-Time Video Analytics Pipeline with YOLO26 and ByteTrack</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-Build-a-Real-Time-Video-Analytics-Pipeline-with-YOLO26-and-ByteTrack"><a rel="noopener" target="_blank" href="#h1-Build-a-Real-Time-Video-Analytics-Pipeline-with-YOLO26-and-ByteTrack">Build a Real-Time Video Analytics Pipeline with YOLO26 and ByteTrack</a></li>
    <li id="TOC-h2-What-Is-Real-Time-Video-Analytics"><a rel="noopener" target="_blank" href="#h2-What-Is-Real-Time-Video-Analytics">What Is Real-Time Video Analytics?</a></li>
    <li id="TOC-h2-Why-Detection-Alone-Is-Not-Enough-for-People-Counting-and-Vehicle-Counting"><a rel="noopener" target="_blank" href="#h2-Why-Detection-Alone-Is-Not-Enough-for-People-Counting-and-Vehicle-Counting">Why Detection Alone Is Not Enough for People Counting and Vehicle Counting</a></li>
    <li id="TOC-h2-System-Architecture-for-Real-Time-Video-Analytics"><a rel="noopener" target="_blank" href="#h2-System-Architecture-for-Real-Time-Video-Analytics">System Architecture for Real-Time Video Analytics</a></li>
    <li id="TOC-h2-Configuring-Your-Development-Environment"><a rel="noopener" target="_blank" href="#h2-Configuring-Your-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-Preparing-Video-Input-for-YOLO26-Object-Detection-and-Tracking"><a rel="noopener" target="_blank" href="#h2-Preparing-Video-Input-for-YOLO26-Object-Detection-and-Tracking">Preparing Video Input for YOLO26 Object Detection and Tracking</a></li>
    <li id="TOC-h2-Running-YOLO26-Object-Detection-on-Video"><a rel="noopener" target="_blank" href="#h2-Running-YOLO26-Object-Detection-on-Video">Running YOLO26 Object Detection on Video</a></li>
    <li id="TOC-h2-Adding-ByteTrack-Multi-Object-Tracking"><a rel="noopener" target="_blank" href="#h2-Adding-ByteTrack-Multi-Object-Tracking">Adding ByteTrack Multi-Object Tracking</a></li>
    <li id="TOC-h2-Building-the-Analytics-Layer-for-People-Counting-and-Vehicle-Counting"><a rel="noopener" target="_blank" href="#h2-Building-the-Analytics-Layer-for-People-Counting-and-Vehicle-Counting">Building the Analytics Layer for People Counting and Vehicle Counting</a></li>
    <li id="TOC-h2-OpenCV-Visualization-and-Dashboard-Overlay"><a rel="noopener" target="_blank" href="#h2-OpenCV-Visualization-and-Dashboard-Overlay">OpenCV Visualization and Dashboard Overlay</a></li>
    <li id="TOC-h2-Video-IO-The-VideoStream-and-VideoWriter-Classes"><a rel="noopener" target="_blank" href="#h2-Video-IO-The-VideoStream-and-VideoWriter-Classes">Video I/O: The VideoStream and VideoWriter Classes</a></li>
    <li id="TOC-h2-Performance-Optimization-for-Real-Time-Object-Detection"><a rel="noopener" target="_blank" href="#h2-Performance-Optimization-for-Real-Time-Object-Detection">Performance Optimization for Real-Time Object Detection</a></li>
    <li id="TOC-h2-Running-the-Real-Time-Video-Analytics-Pipeline"><a rel="noopener" target="_blank" href="#h2-Running-the-Real-Time-Video-Analytics-Pipeline">Running the Real-Time Video Analytics Pipeline</a></li>
    <li id="TOC-h2-Real-World-Applications-of-People-Counting-and-Vehicle-Counting-Systems"><a rel="noopener" target="_blank" href="#h2-Real-World-Applications-of-People-Counting-and-Vehicle-Counting-Systems">Real-World Applications of People Counting and Vehicle Counting Systems</a></li>
    <li id="TOC-h2-What-Can-Go-Wrong-in-Your-Real-Time-Video-Analytics-Pipeline"><a rel="noopener" target="_blank" href="#h2-What-Can-Go-Wrong-in-Your-Real-Time-Video-Analytics-Pipeline">What Can Go Wrong in Your Real-Time Video Analytics Pipeline</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-Build-a-Real-Time-Video-Analytics-Pipeline-with-YOLO26-and-ByteTrack"/>



<h2 class="wp-block-heading"><a href="#TOC-h1-Build-a-Real-Time-Video-Analytics-Pipeline-with-YOLO26-and-ByteTrack">Build a Real-Time Video Analytics Pipeline with YOLO26 and ByteTrack</a></h2>



<p>In this lesson, you will learn how to build a complete real-time video analytics pipeline using <a href="https://docs.ultralytics.com/models/yolo26/" target="_blank" rel="noreferrer noopener">YOLO26</a> for object detection and ByteTrack for multi-object tracking (MOT), including line-crossing analytics for people counting and vehicle counting on macOS.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://pyimagesearch.com/wp-content/uploads/2026/11/build-real-time-video-analytics-pipeline-yolo26-bytetrack-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/11/build-real-time-video-analytics-pipeline-yolo26-bytetrack-featured_v2.png?lossy=2&strip=1&webp=1" alt="build-real-time-video-analytics-pipeline-yolo26-bytetrack-featured_v2.png" class="wp-image-55835"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/build-real-time-video-analytics-pipeline-yolo26-bytetrack-featured_v2.png?size=126x105&lossy=2&strip=1&webp=1 126w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/build-real-time-video-analytics-pipeline-yolo26-bytetrack-featured_v2-300x249.png?lossy=2&strip=1&webp=1 300w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/build-real-time-video-analytics-pipeline-yolo26-bytetrack-featured_v2.png?size=378x314&lossy=2&strip=1&webp=1 378w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/build-real-time-video-analytics-pipeline-yolo26-bytetrack-featured_v2.png?size=504x418&lossy=2&strip=1&webp=1 504w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/build-real-time-video-analytics-pipeline-yolo26-bytetrack-featured_v2.png?size=630x523&lossy=2&strip=1&webp=1 630w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/build-real-time-video-analytics-pipeline-yolo26-bytetrack-featured_v2-768x637.png?lossy=2&strip=1&webp=1 768w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/build-real-time-video-analytics-pipeline-yolo26-bytetrack-featured_v2.png?lossy=2&strip=1&webp=1 940w" sizes="(max-width: 940px) 100vw, 940px" /></a></figure></div>


<p>This lesson is the last in a 2-part series on <strong>YOLO26</strong>:</p>



<ol class="wp-block-list">
<li><em><strong><a href="https://pyimg.co/8p0ln" target="_blank" rel="noreferrer noopener">YOLO26 Object Detection Tutorial: Benchmarking on macOS</a></strong></em></li>



<li><em><strong><a href="https://pyimagesearch.com/2026/11/02/build-a-real-time-video-analytics-pipeline-with-yolo26-and-bytetrack/" target="_blank" rel="noreferrer noopener">Build a Real-Time Video Analytics Pipeline with YOLO26 and ByteTrack</a></strong></em><strong> (this tutorial)</strong></li>
</ol>



<p><strong>To learn how to build a real-time video analytics pipeline with YOLO26 and ByteTrack, </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-What-Is-Real-Time-Video-Analytics"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-What-Is-Real-Time-Video-Analytics">What Is Real-Time Video Analytics?</a></h2>



<p>There is a big difference between a detector and a video analytics system.</p>



<p>A detector answers the question, &#8220;What is in this frame right now?&#8221;</p>



<p>A real-time video analytics system answers questions such as:</p>



<ul class="wp-block-list">
<li>How many objects crossed this line?</li>



<li>Which object is which across time?</li>



<li>Are counts going up or down?</li>



<li>Is the pipeline fast enough to run continuously?</li>
</ul>



<p>That is the shift in this lesson. You are building a system, not just calling a model.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Why-Detection-Alone-Is-Not-Enough-for-People-Counting-and-Vehicle-Counting"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Why-Detection-Alone-Is-Not-Enough-for-People-Counting-and-Vehicle-Counting">Why Detection Alone Is Not Enough for People Counting and Vehicle Counting</a></h2>



<p>Detection by itself is frame-local. Every frame is treated independently. That becomes a problem as soon as you want to build a people counting system, a vehicle counting system, or any kind of directional event tracker.</p>



<p>Suppose a person appears in 40 consecutive frames. A detector will happily report that person 40 times. But your application probably does not want 40 answers. It wants one tracked entity that persists across time.</p>



<p>That is why you need a tracker.</p>



<p>The tracker takes per-frame detections and turns them into stable identities. Once stable identities exist, the analytics layer can reason over time. In your case, that means checking whether a tracked object moved from one side of a virtual line to the other.</p>



<p>The key idea is simple.</p>



<ul class="wp-block-list">
<li>Detection tells you what exists in a frame.</li>



<li>Tracking tells you what persists across frames.</li>



<li>Analytics tells you what events happened over time.</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-System-Architecture-for-Real-Time-Video-Analytics"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-System-Architecture-for-Real-Time-Video-Analytics">System Architecture for Real-Time Video Analytics</a></h2>



<p>At a high level, the pipeline looks like this:</p>



<p><code data-enlighter-language="python" class="EnlighterJSRAW">Video -&gt; YOLO26 -&gt; ByteTrack -&gt; Analytics -&gt; Output</code></p>



<p>That single line is the architecture diagram description for this lesson.<strong><br></strong></p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/11/image-6-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="320" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-6-1024x320.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-55839"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-6-1024x320.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-6-1024x320.png?size=126x39&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-6-1024x320.png?size=252x79&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-6-1024x320.png?size=378x118&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-6-1024x320.png?size=504x158&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-6-1024x320.png?size=630x197&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 1: </strong>System architecture for the YOLO26 real-time video analytics pipeline (source: image by the author).</figcaption></figure></div>


<p>Each stage has a clear job:</p>



<h3 class="wp-block-heading">Video Input</h3>



<p>Reads frames from a webcam or video file. This layer also handles resizing and optional frame skipping.</p>



<p>By isolating video input/output (I/O) in its own module, you can swap between a live webcam feed and a recorded clip without touching any detection or tracking code.</p>



<h3 class="wp-block-heading">YOLO26 Object Detection</h3>



<p>Runs YOLO26 inference on the current frame and returns object detections.</p>



<p>The detector wraps the Ultralytics model behind a clean interface so the rest of the pipeline never interacts with the You Only Look Once (YOLO) application programming interface (API) directly. This makes it straightforward to swap in a different model later.</p>



<h3 class="wp-block-heading">ByteTrack Multi-Object Tracking</h3>



<p>Uses the ByteTrack algorithm to associate detections across frames and assign stable track identifiers (IDs).</p>



<p>Without this step, every frame would contain anonymous bounding boxes with no way to tell whether 2 boxes in consecutive frames belong to the same physical object.</p>



<h3 class="wp-block-heading">Analytics Layer</h3>



<p>Checks whether any tracked object crossed the configured virtual line. It also supports optional zone-based occupancy counting. The analytics layer consumes tracks (not raw detections), which is why stable IDs from ByteTrack are essential.</p>



<h3 class="wp-block-heading">Output Layer</h3>



<p>Draws boxes, IDs, counts, and frames per second (FPS) on the frame, then displays or saves it.</p>



<p>This overlay provides a live operator view so you can visually verify that detection, tracking, and counting are all working correctly during a run.</p>



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



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



<p>To follow this guide, you need to have the Ultralytics, supervision, and OpenCV libraries installed on your system.</p>



<p>Luckily, they are all pip-installable:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Build a Real-Time Video Analytics Pipeline with YOLO26 and ByteTrack" data-enlighter-group="1">$ pip install ultralytics supervision opencv-python
</pre>



<p>If you need help configuring your development environment for this video analytics pipeline, we highly recommend creating a fresh virtual environment first.</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>Let us review the project directory structure for our real-time video analytics pipeline.</p>



<p>Start by accessing this lesson&#8217;s &#8220;Downloads&#8221; section to retrieve the source code.</p>



<p>From there, take a look at the directory 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="Build a Real-Time Video Analytics Pipeline with YOLO26 and ByteTrack" data-enlighter-group="2">yolo26_video_analytics/
├── assets/
│   ├── models/
│   │   └── yolo26n.pt
│   └── videos/
│       └── traffic.mp4
├── main.py
├── requirements.txt
├── README.md
└── video_analytics/
    ├── __init__.py
    ├── __main__.py
    ├── cli.py
    ├── config.py
    ├── pipeline.py
    ├── analytics/
    │   └── engine.py
    ├── common/
    │   └── utils.py
    ├── io/
    │   └── video.py
    ├── models/
    │   ├── detector.py
    │   └── tracker.py
    └── rendering/
        └── visualization.py
</pre>



<p>This structure is intentional.</p>



<p>You do not want all the logic dumped into a single script. That approach collapses quickly once you add ByteTrack multi-object tracking, analytics, performance tuning, and configurable runtime behavior.</p>



<p>Here is what each module does:</p>



<h3 class="wp-block-heading">video_analytics/config.py</h3>



<p>Defines the pipeline configuration objects: detection settings, tracking settings, video settings, and analytics settings.</p>



<h3 class="wp-block-heading">video_analytics/models/detector.py</h3>



<p>Wraps the Ultralytics YOLO26 model and converts its raw predictions into a simple detection format for the rest of the pipeline.</p>



<h3 class="wp-block-heading">video_analytics/models/tracker.py</h3>



<p>Wraps ByteTrack so the rest of the system does not care about the underlying tracker API.</p>



<h3 class="wp-block-heading">video_analytics/analytics/engine.py</h3>



<p>Implements line-crossing logic and maintains counts over time.</p>



<h3 class="wp-block-heading">video_analytics/io/video.py</h3>



<p>Handles webcam and video input, resizing, and writing output video if requested.</p>



<h3 class="wp-block-heading">video_analytics/rendering/visualization.py</h3>



<p>Draws the operator-facing overlay: boxes, IDs, line, counts, and FPS.</p>



<h3 class="wp-block-heading">video_analytics/common/utils.py</h3>



<p>Contains small shared data structures and utility helpers.</p>



<h3 class="wp-block-heading">video_analytics/cli.py and video_analytics/pipeline.py</h3>



<p>Build the runtime configuration, assemble the pipeline, and run the real-time frame loop.</p>



<h3 class="wp-block-heading">main.py</h3>



<p>Provides a thin root-level wrapper so the application can still be launched with a simple <code data-enlighter-language="python" class="EnlighterJSRAW">python main.py</code> command.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Preparing-Video-Input-for-YOLO26-Object-Detection-and-Tracking"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Preparing-Video-Input-for-YOLO26-Object-Detection-and-Tracking">Preparing Video Input for YOLO26 Object Detection and Tracking</a></h2>



<p>For this lesson, you can use any traffic or pedestrian video. The pipeline is designed to work with standard Common Objects in Context (COCO) classes (e.g., <code data-enlighter-language="python" class="EnlighterJSRAW">person</code>, <code data-enlighter-language="python" class="EnlighterJSRAW">car</code>, <code data-enlighter-language="python" class="EnlighterJSRAW">bus</code>, and <code data-enlighter-language="python" class="EnlighterJSRAW">truck</code>).</p>



<p>If you do not already have a video, here are some easy options:</p>



<ul class="wp-block-list">
<li>record a short clip with your phone</li>



<li>use a public traffic or street video</li>



<li>download a sample video from a public benchmark or a YouTube clip that clearly shows moving objects</li>
</ul>



<p>For best results:</p>



<ul class="wp-block-list">
<li>use a clip lasting 20 to 40 seconds </li>



<li>ensure objects actually cross the counting line</li>



<li>avoid scenes that are either extremely crowded or almost empty</li>
</ul>



<p>For the examples in this lesson, a traffic video where vehicles move horizontally across the frame is the easiest choice because line-crossing events are easy to see and validate.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Running-YOLO26-Object-Detection-on-Video"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Running-YOLO26-Object-Detection-on-Video">Running YOLO26 Object Detection on Video</a></h2>



<p>You already ran YOLO26 on static images in Lesson 1. Now you need a detector wrapper that is built for a video loop.</p>



<p>The goal here is not theoretical elegance. The goal is a clean interface.</p>



<p>Before looking at the detector wrapper, let us define the shared data structures that the entire pipeline uses. In <code data-enlighter-language="python" class="EnlighterJSRAW">video_analytics/common/utils.py</code>, you will define <code data-enlighter-language="python" class="EnlighterJSRAW">Detection</code> and <code data-enlighter-language="python" class="EnlighterJSRAW">Track</code> as simple dataclasses:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Build a Real-Time Video Analytics Pipeline with YOLO26 and ByteTrack" data-enlighter-group="3">from __future__ import annotations

from dataclasses import dataclass
from typing import Tuple


Point = Tuple[int, int]


@dataclass(slots=True)
class Detection:
    xyxy: Tuple[float, float, float, float]
    confidence: float
    class_id: int
    class_name: str


@dataclass(slots=True)
class Track:
    track_id: int
    xyxy: Tuple[float, float, float, float]
    confidence: float
    class_id: int
    class_name: str

    @property
    def centroid(self) -> Point:
        x1, y1, x2, y2 = self.xyxy
        return int((x1 + x2) / 2.0), int((y1 + y2) / 2.0)
</pre>



<p><code data-enlighter-language="python" class="EnlighterJSRAW">Detection</code> carries the per-frame detections from the model. <code data-enlighter-language="python" class="EnlighterJSRAW">Track</code> contains the same detection fields plus a <code data-enlighter-language="python" class="EnlighterJSRAW">track_id</code> and a computed <code data-enlighter-language="python" class="EnlighterJSRAW">centroid</code> property that the analytics layer uses for line-crossing tests. </p>



<p>In <code data-enlighter-language="python" class="EnlighterJSRAW">video_analytics/models/detector.py</code>, you will create a small wrapper around Ultralytics YOLO:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Build a Real-Time Video Analytics Pipeline with YOLO26 and ByteTrack" data-enlighter-group="4">from typing import List

from ultralytics import YOLO

from ..common import Detection
from ..config import DetectionConfig


class YOLO26Detector:
    def __init__(self, config: DetectionConfig) -> None:
        self.config = config
        self.model = YOLO(config.model_path)

    def detect(self, frame) -> List[Detection]:
        result = self.model.predict(
            source=frame,
            conf=self.config.confidence,
            imgsz=self.config.image_size,
            device=self.config.device,
            verbose=False,
        )[0]

        boxes = result.boxes
        if boxes is None or len(boxes) == 0:
            return []
</pre>



<p>This wrapper does 3 useful things for you:</p>



<ul class="wp-block-list">
<li>Centralizes model configuration</li>



<li>Hides the raw Ultralytics result object from the rest of the pipeline</li>



<li>Converts detections into a consistent internal structure</li>
</ul>



<p>That last part matters. When the detector returns simple <code data-enlighter-language="python" class="EnlighterJSRAW">Detection</code> objects, the tracker and analytics modules stay clean.</p>



<p>In the same file, we extract bounding boxes, confidences, class IDs, and class names, then normalize them into our internal <code data-enlighter-language="python" class="EnlighterJSRAW">Detection</code> dataclass:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Build a Real-Time Video Analytics Pipeline with YOLO26 and ByteTrack" data-enlighter-group="5">xyxy = boxes.xyxy.cpu().numpy()
confidences = boxes.conf.cpu().numpy()
class_ids = boxes.cls.cpu().numpy().astype(int)
names = result.names

detections: List[Detection] = []
for box, confidence, class_id in zip(xyxy, confidences, class_ids):
    detections.append(
        Detection(
            xyxy=(float(box[0]), float(box[1]), float(box[2]), float(box[3])),
            confidence=float(confidence),
            class_id=int(class_id),
            class_name=str(names[int(class_id)]),
        )
    )
</pre>



<p>At this point, the detector stage is done. For each frame, we now have a list of objects that YOLO26 thinks are present.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/11/image-7-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="576" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-7-1024x576.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-55841"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-7-1024x576.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-7-1024x576.png?size=126x71&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-7-1024x576.png?size=252x142&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-7-1024x576.png?size=378x213&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-7-1024x576.png?size=504x284&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-7-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> YOLO26 detections on a video frame before tracking and analytics are applied (source: image by the author).</figcaption></figure></div>


<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Adding-ByteTrack-Multi-Object-Tracking"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Adding-ByteTrack-Multi-Object-Tracking">Adding ByteTrack Multi-Object Tracking</a></h2>



<p>Detection alone is not enough for analytics, so the next step is adding the ByteTrack algorithm.</p>



<p>We are using ByteTrack here because it is a strong practical fit for real-time video analytics pipelines. It is widely used, works well in detection-based MOT pipelines, and provides stable IDs without turning the lesson into a tracking theory lecture.</p>



<p>We are also using ByteTrack instead of a simpler centroid tracker for a reason:</p>



<ul class="wp-block-list">
<li>it handles occlusion and brief disappearances better than naive centroid matching</li>



<li>it uses detection confidence during association</li>



<li>it maintains a lost-track buffer that helps in busy scenes</li>
</ul>



<p>That makes the ByteTrack multi-object tracking approach a much better fit for real-world people counting and vehicle counting pipelines where IDs need to stay stable under noise and partial visibility.</p>



<p>In <code data-enlighter-language="python" class="EnlighterJSRAW">video_analytics/models/tracker.py</code>, you will wrap ByteTrack as follows:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Build a Real-Time Video Analytics Pipeline with YOLO26 and ByteTrack" data-enlighter-group="6">from typing import Iterable, List

import numpy as np
import supervision as sv

from ..common import Detection, Track
from ..config import TrackingConfig


class ByteTrackTracker:
    def __init__(self, config: TrackingConfig, frame_rate: float) -> None:
        self.tracker = sv.ByteTrack(
            track_activation_threshold=config.activation_threshold,
            lost_track_buffer=config.lost_track_buffer,
            minimum_matching_threshold=config.minimum_matching_threshold,
            frame_rate=max(int(frame_rate), 1),
        )

    def update(self, detections: Iterable[Detection]) -> List[Track]:
        detections = list(detections)
        if not detections:
            empty = sv.Detections.empty()
            self.tracker.update_with_detections(empty)
            return []
</pre>



<p>The nice thing about wrapping it this way is that <code data-enlighter-language="python" class="EnlighterJSRAW">video_analytics/pipeline.py</code> does not need to know anything about <code data-enlighter-language="python" class="EnlighterJSRAW">supervision.Detections</code> or tracker internals.</p>



<p>Inside <code data-enlighter-language="python" class="EnlighterJSRAW">update</code>, you convert the detection list into a tracker-friendly format:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Build a Real-Time Video Analytics Pipeline with YOLO26 and ByteTrack" data-enlighter-group="7">sv_detections = sv.Detections(
    xyxy=xyxy,
    confidence=confidence,
    class_id=class_id,
    data={"class_name": metadata},
)
tracked = self.tracker.update_with_detections(sv_detections)
</pre>



<p>Then you convert the tracker output into <code data-enlighter-language="python" class="EnlighterJSRAW">Track</code> objects that carry:</p>



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



<li>bounding box</li>



<li>confidence</li>



<li>class ID</li>



<li>class name</li>
</ul>



<p>That gives us exactly what the analytics layer needs.</p>



<p>One small but important detail is the empty-detection path above. When YOLO26 misses everything in a frame, you still forward an empty <code data-enlighter-language="python" class="EnlighterJSRAW">Detections</code> object into ByteTrack so tracks age naturally instead of collapsing immediately.</p>



<h3 class="wp-block-heading">Real-World Challenge: Tracker Imperfections</h3>



<p>Tracking is not perfect.</p>



<p>In real-world scenes:</p>



<ul class="wp-block-list">
<li>objects may be temporarily lost</li>



<li>track IDs may switch</li>



<li>occlusions can break continuity</li>
</ul>



<p>That matters because analytics depends on track identity. If a person disappears for a few frames and returns with a new ID, the pipeline may count them twice.</p>



<p>In production systems, common mitigation strategies include:</p>



<ul class="wp-block-list">
<li>minimum track length thresholds</li>



<li>track smoothing</li>



<li>time-based filtering</li>



<li>re-identification models for harder scenes</li>
</ul>



<p>This lesson keeps the implementation lightweight, but it is important to understand that tracking quality directly affects analytics quality in any people counting software or vehicle counting system.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://pyimagesearch.com/wp-content/uploads/2026/11/image-8.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="624" height="477" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-8.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-55845"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-8.png?size=126x96&lossy=2&strip=1&webp=1 126w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-8-300x229.png?lossy=2&strip=1&webp=1 300w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-8.png?size=378x289&lossy=2&strip=1&webp=1 378w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-8.png?size=504x385&lossy=2&strip=1&webp=1 504w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-8.png?lossy=2&strip=1&webp=1 624w" sizes="(max-width: 624px) 100vw, 624px" /></a><figcaption class="wp-element-caption"><strong>Figure 3:</strong> Stable track IDs assigned by ByteTrack across consecutive frames (source: image by the author).</figcaption></figure></div>


<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Building-the-Analytics-Layer-for-People-Counting-and-Vehicle-Counting"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Building-the-Analytics-Layer-for-People-Counting-and-Vehicle-Counting">Building the Analytics Layer for People Counting and Vehicle Counting</a></h2>



<p>This is the most important part of the lesson.</p>



<p>We are not just showing tracked boxes. We are extracting business-level events from a stream of detections.</p>



<p>The main event in this lesson is line crossing, but the same analytics layer also supports class-filtered counting, multiple named lines, and optional zone occupancy, making it work as both a people counting system and a vehicle counting system.</p>



<h3 class="wp-block-heading">The Idea</h3>



<p>We define a virtual line across the frame. For each tracked object, we store its previous observed centroid and compare it with its current centroid.</p>



<p>If the centroid moves from one side of a configured line to the other, we count that as a crossing event.</p>



<p>The implementation is not limited to a single demo line. The analytics configuration can:</p>



<ul class="wp-block-list">
<li>Restrict counting to selected classes (e.g., <code data-enlighter-language="python" class="EnlighterJSRAW">person</code> or a combination of <code data-enlighter-language="python" class="EnlighterJSRAW">car</code>, <code data-enlighter-language="python" class="EnlighterJSRAW">bus</code>, and <code data-enlighter-language="python" class="EnlighterJSRAW">truck</code>)</li>



<li>Handle multiple named counting lines in the same scene</li>



<li>Track optional zone occupancy for a rectangular region of interest</li>
</ul>



<p>Before going further, note the coordinate convention we are using. OpenCV frames follow the standard image coordinate system:</p>



<ul class="wp-block-list">
<li>the origin is at the top-left corner</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">x</code> increases to the right</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">y</code> increases downward</li>
</ul>



<p>That convention affects both line direction and the sign of the crossing test. The <code data-enlighter-language="python" class="EnlighterJSRAW">"in"</code> and <code data-enlighter-language="python" class="EnlighterJSRAW">"out"</code> labels depend on the order of the line endpoints and the change in the centroid’s side-of-line value. Verify these labels against the intended direction of travel for your camera view.</p>



<p>This logic lives in <code data-enlighter-language="python" class="EnlighterJSRAW">video_analytics/analytics/engine.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="Build a Real-Time Video Analytics Pipeline with YOLO26 and ByteTrack" data-enlighter-group="8">@dataclass(slots=True)
class LineCrossingCounter:
    name: str
    line_start: Point
    line_end: Point
    allowed_classes: Optional[set[str]] = None
    previous_centroids: Dict[int, Point] = field(default_factory=dict)
    counted_track_ids: set[int] = field(default_factory=set)
    total_count: int = 0
    in_count: int = 0
    out_count: int = 0
</pre>



<p>The key state we store is:</p>



<ul class="wp-block-list">
<li>Previous centroid per track ID for each counting line</li>



<li>Which track IDs have already been counted on each line</li>



<li>Total, in, and out counters per line</li>



<li>Optional occupancy count inside a configured zone</li>
</ul>



<p>To determine whether a crossing happened, we compute which side of the line the object was on before and after:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Build a Real-Time Video Analytics Pipeline with YOLO26 and ByteTrack" data-enlighter-group="9">previous_side = side_of_line(previous_centroid, self.line_start, self.line_end)
current_side = side_of_line(current_centroid, self.line_start, self.line_end)

if previous_side == 0:
    previous_side = current_side

if previous_side * current_side &lt; 0:
    direction = "in" if previous_side &lt; current_side else "out"
    self.counted_track_ids.add(track.track_id)
</pre>



<p>That is the heart of the line-crossing logic.</p>



<p>Once a track is counted, we add its ID to a <code data-enlighter-language="python" class="EnlighterJSRAW">counted_track_ids</code> set so the same object is not counted repeatedly.</p>



<p>That design choice is deliberate. In this implementation, each track is counted only once per line. That works well for entry and exit counting use cases.</p>



<p>If your scene allows the same object to cross the same line multiple times, then you would want a more advanced per-track state machine instead of the simpler count-once logic used here.</p>



<p>The zone occupancy counter follows a simpler pattern. Instead of tracking crossings, it counts how many tracked objects currently have their centroid inside a rectangular region. In <code data-enlighter-language="python" class="EnlighterJSRAW">video_analytics/analytics/engine.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="Build a Real-Time Video Analytics Pipeline with YOLO26 and ByteTrack" data-enlighter-group="10">@dataclass(slots=True)
class ZoneOccupancyCounter:
    name: str
    top_left: Point
    bottom_right: Point
    allowed_classes: Optional[set[str]] = None
    occupancy_count: int = 0

    def update(self, tracks: List[Track]) -> None:
        current_count = 0
        for track in tracks:
            if self.allowed_classes is not None and track.class_name.lower() not in self.allowed_classes:
                continue

            centroid_x, centroid_y = track.centroid
            if self.top_left[0] &lt;= centroid_x &lt;= self.bottom_right[0] and self.top_left[1] &lt;= centroid_y &lt;= self.bottom_right[1]:
                current_count += 1
        self.occupancy_count = current_count

    def stats(self) -> Dict[str, int | str]:
        return {
            "name": self.name,
            "occupancy": self.occupancy_count,
        }
</pre>



<p>This is a per-frame snapshot, not cumulative. Every call to <code data-enlighter-language="python" class="EnlighterJSRAW">update</code> recalculates the count from scratch based on which tracks are currently inside the zone. That makes it suitable for real-time occupancy monitoring where the question is &#8220;how many objects are in this region right now?&#8221;</p>



<p>Combined with class filters and optional zone occupancy, this is what makes the pipeline feel like a real application rather than a visualization demo.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/11/image-9-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="574" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-9-1024x574.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-55847"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-9-1024x574.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-9-1024x574.png?size=126x71&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-9-1024x574.png?size=252x141&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-9-1024x574.png?size=378x212&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-9-1024x574.png?size=504x283&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-9-1024x574.png?size=630x353&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 4: </strong>Tracking-driven analytics: objects crossing named lines and entering a monitored zone (source: image by the author).</figcaption></figure></div>


<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-OpenCV-Visualization-and-Dashboard-Overlay"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-OpenCV-Visualization-and-Dashboard-Overlay">OpenCV Visualization and Dashboard Overlay</a></h2>



<p>Operators and developers both need a useful overlay.</p>



<p>The overlay should do more than draw boxes. It should answer the questions that matter during deployment and debugging.</p>



<p>In <code data-enlighter-language="python" class="EnlighterJSRAW">video_analytics/rendering/visualization.py</code>, you draw:</p>



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



<li>track IDs</li>



<li>class labels and confidence</li>



<li>1 or more virtual counting lines</li>



<li>optional zone boundaries</li>



<li>aggregate total count</li>



<li>aggregate in and out count</li>



<li>per-line totals</li>



<li>optional zone occupancy</li>



<li>FPS</li>
</ul>



<p>One small implementation detail worth calling out: the overlay is designed to expose the system state, not just the detections. That is why the panel includes analytics results and runtime information instead of stopping at boxes and labels.</p>



<p>Here is the core track drawing 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="Build a Real-Time Video Analytics Pipeline with YOLO26 and ByteTrack" data-enlighter-group="11">def draw_tracks(frame, tracks: Iterable[Track]) -> None:
    for track in tracks:
        x1, y1, x2, y2 = as_int_tuple(track.xyxy)
        cv2.rectangle(frame, (x1, y1), (x2, y2), BOX_COLOR, 2)
        label = f"ID {track.track_id} | {track.class_name} {track.confidence:.2f}"
        cv2.putText(frame, label, (x1, max(20, y1 - 10)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, TEXT_COLOR, 2)
</pre>



<p>And the stats overlay:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Build a Real-Time Video Analytics Pipeline with YOLO26 and ByteTrack" data-enlighter-group="12">def draw_stats(frame, stats: Dict[str, int], fps: float) -> None:
    lines = stats.get("lines", [])
    zone = stats.get("zone")
    panel_height = 90 + (len(lines) * 22) + (24 if zone else 0)
    cv2.rectangle(frame, (10, 10), (360, 10 + panel_height), PANEL_COLOR, -1)
    cv2.putText(frame, f"Total Count: {stats['total']}", (20, 38), cv2.FONT_HERSHEY_SIMPLEX, 0.7, TEXT_COLOR, 2)
    cv2.putText(frame, f"In: {stats['in']}  Out: {stats['out']}", (20, 64), cv2.FONT_HERSHEY_SIMPLEX, 0.65, TEXT_COLOR, 2)
    cv2.putText(frame, f"FPS: {fps:.2f}", (20, 90), cv2.FONT_HERSHEY_SIMPLEX, 0.65, TEXT_COLOR, 2)
</pre>



<p>In the current refactor, that panel can expand as the scene configuration gets richer. A simple run may show aggregate totals only, while a multi-line or zone-enabled run can also show per-line counts and occupancy. That makes the overlay useful both for demos and for validating system behavior during development.</p>



<p>The line drawing function is similarly straightforward:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Build a Real-Time Video Analytics Pipeline with YOLO26 and ByteTrack" data-enlighter-group="13">def draw_line(frame, line_start: Point, line_end: Point, label: str | None = None) -> None:
    cv2.line(frame, line_start, line_end, LINE_COLOR, 2)
    if label:
        label_anchor = (line_start[0] + 12, max(24, line_start[1] - 12))
        cv2.putText(frame, label, label_anchor, cv2.FONT_HERSHEY_SIMPLEX, 0.6, LINE_COLOR, 2)
</pre>



<p>It takes 2 endpoints and an optional label, then draws a yellow line on the frame. The label is placed just above and to the right of the start point.</p>



<p>Zone drawing follows the same pattern:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Build a Real-Time Video Analytics Pipeline with YOLO26 and ByteTrack" data-enlighter-group="14">def draw_zone(frame, top_left: Point, bottom_right: Point, label: str | None = None) -> None:
    cv2.rectangle(frame, top_left, bottom_right, (255, 180, 0), 2)
    if label:
        cv2.putText(frame, label, (top_left[0] + 8, max(24, top_left[1] - 10)),
                     cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 180, 0), 2)
</pre>



<p>And the event log overlay shows the most recent line-crossing events so you can watch them happening in real time:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Build a Real-Time Video Analytics Pipeline with YOLO26 and ByteTrack" data-enlighter-group="15">def draw_events(frame, events: Iterable[Tuple[str, str, str]]) -> None:
    y_offset = 130
    for class_name, line_name, direction in list(events)[-4:]:
        cv2.putText(frame, f"{class_name} crossed {line_name}: {direction}",
                     (20, y_offset), cv2.FONT_HERSHEY_SIMPLEX, 0.6, LINE_COLOR, 2)
        y_offset += 26
</pre>



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">[-4:]</code> slice keeps only the 4 most recent events on screen so the overlay stays readable instead of growing endlessly.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://pyimagesearch.com/wp-content/uploads/2026/11/image-10.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="619" height="349" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-10.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-55851"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-10.png?size=126x71&lossy=2&strip=1&webp=1 126w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-10-300x169.png?lossy=2&strip=1&webp=1 300w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-10.png?size=378x213&lossy=2&strip=1&webp=1 378w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-10.png?size=504x284&lossy=2&strip=1&webp=1 504w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-10.png?lossy=2&strip=1&webp=1 619w" sizes="(max-width: 619px) 100vw, 619px" /></a><figcaption class="wp-element-caption"><strong>Figure 5:</strong> Final YOLO26 analytics overlay with detections, track IDs, counts, line labels, and FPS (source: image by the author).</figcaption></figure></div>


<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Video-IO-The-VideoStream-and-VideoWriter-Classes"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Video-IO-The-VideoStream-and-VideoWriter-Classes">Video I/O: The VideoStream and VideoWriter Classes</a></h2>



<p>Before moving on to performance tuning, let us look at the video I/O layer that makes the pipeline work with both webcam feeds and recorded files.</p>



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">VideoStream</code> class in <code data-enlighter-language="python" class="EnlighterJSRAW">video_analytics/io/video.py</code> wraps OpenCV&#8217;s <code data-enlighter-language="python" class="EnlighterJSRAW">VideoCapture</code> and handles frame reading, resizing, and optional frame skipping in one place:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Build a Real-Time Video Analytics Pipeline with YOLO26 and ByteTrack" data-enlighter-group="16">class VideoStream:
    def __init__(self, config: VideoConfig) -> None:
        self.config = config
        self.capture = cv2.VideoCapture(parse_source(config.source))
        if not self.capture.isOpened():
            raise RuntimeError(f"Could not open video source: {config.source}")

    @property
    def fps(self) -> float:
        fps = self.capture.get(cv2.CAP_PROP_FPS)
        return fps if fps and fps > 0 else 30.0

    @property
    def frame_size(self) -> Tuple[int, int]:
        width = int(self.capture.get(cv2.CAP_PROP_FRAME_WIDTH))
        height = int(self.capture.get(cv2.CAP_PROP_FRAME_HEIGHT))
        if self.config.frame_width and width > 0:
            scale = self.config.frame_width / width
            return self.config.frame_width, int(height * scale)
        return width, height

    def frames(self) -> Generator[Tuple[int, any], None, None]:
        frame_index = 0
        while True:
            grabbed, frame = self.capture.read()
            if not grabbed:
                break
            if self.config.frame_skip and frame_index % (self.config.frame_skip + 1) != 0:
                frame_index += 1
                continue
            if self.config.frame_width:
                height, width = frame.shape[:2]
                scale = self.config.frame_width / float(width)
                frame = cv2.resize(frame, (self.config.frame_width, int(height * scale)))
            yield frame_index, frame
            frame_index += 1

    def release(self) -> None:
        self.capture.release()
</pre>



<p>A few details worth noting. The <code data-enlighter-language="python" class="EnlighterJSRAW">fps</code> property falls back to 30.0 when the backend reports 0 or nothing. That happens more often than you would expect with webcams and some video containers. The <code data-enlighter-language="python" class="EnlighterJSRAW">frames()</code> generator yields <code data-enlighter-language="python" class="EnlighterJSRAW">(frame_index, frame)</code> tuples, which lets the pipeline track frame positions without maintaining a separate counter. Resizing and frame skipping are both handled inside this generator, so the rest of the pipeline always receives ready-to-process frames.</p>



<p>The companion <code data-enlighter-language="python" class="EnlighterJSRAW">VideoWriter</code> class handles output recording:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Build a Real-Time Video Analytics Pipeline with YOLO26 and ByteTrack" data-enlighter-group="17">class VideoWriter:
    def __init__(self, output_path: Optional[str], fps: float, frame_size: Tuple[int, int]) -> None:
        self.writer = None
        if output_path:
            fourcc = cv2.VideoWriter_fourcc(*"mp4v")
            self.writer = cv2.VideoWriter(output_path, fourcc, fps, frame_size)

    def write(self, frame) -> None:
        if self.writer is not None:
            self.writer.write(frame)

    def release(self) -> None:
        if self.writer is not None:
            self.writer.release()
</pre>



<p>If you pass <code data-enlighter-language="python" class="EnlighterJSRAW">--output output.mp4</code> on the command line, the pipeline records every rendered frame to disk. If you do not, the writer stays inactive and performs no video encoding or disk writes. That guard pattern keeps the code clean without needing separate &#8220;record&#8221; and &#8220;no-record&#8221; code paths.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Performance-Optimization-for-Real-Time-Object-Detection"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Performance-Optimization-for-Real-Time-Object-Detection">Performance Optimization for Real-Time Object Detection</a></h2>



<p>Real-time video analytics systems are rarely bottlenecked by a single operation. Their performance depends on how efficiently detection, tracking, analytics, and rendering work together.</p>



<p>This codebase uses 4 practical optimization techniques to balance throughput, latency, and detection quality. Rather than repeating the implementation details covered earlier, we will focus on how these techniques affect the overall pipeline.</p>



<p>It is also useful to think about latency as a pipeline rather than a single number:</p>



<p><strong>End-to-end latency = detection + tracking + analytics + rendering</strong></p>



<p>In most practical runs:</p>



<ul class="wp-block-list">
<li><strong>Detection:</strong> often the most computationally expensive stage, particularly when running a deep learning model on every frame</li>



<li><strong>Tracking:</strong> generally lightweight compared with neural network inference, although its cost depends on the tracker and the number of tracked objects</li>



<li><strong>Analytics:</strong> typically adds little overhead when it consists of simple operations such as counting objects or updating statistics</li>



<li><strong>Rendering:</strong> a bottleneck when every frame must be annotated and displayed in real time</li>
</ul>



<p>The goal is not simply to maximize detector throughput. It is to maintain an acceptable balance between processing speed, detection quality, and the responsiveness of the complete application.</p>



<h3 class="wp-block-heading">Frame Resizing</h3>



<p>We resize frames before inference to reduce compute cost and stabilize throughput.</p>



<p>That happens in <code data-enlighter-language="python" class="EnlighterJSRAW">video_analytics/io/video.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="Build a Real-Time Video Analytics Pipeline with YOLO26 and ByteTrack" data-enlighter-group="18">if self.config.frame_width:
    height, width = frame.shape[:2]
    scale = self.config.frame_width / float(width)
    frame = cv2.resize(frame, (self.config.frame_width, int(height * scale)))
</pre>



<h3 class="wp-block-heading">FPS Calculation</h3>



<p>We keep a rolling FPS estimate with <code data-enlighter-language="python" class="EnlighterJSRAW">FPSMeter</code> in <code data-enlighter-language="python" class="EnlighterJSRAW">video_analytics/common/utils.py</code> so the overlay reflects actual runtime performance.</p>



<p>In <code data-enlighter-language="python" class="EnlighterJSRAW">video_analytics/io/video.py</code>, we also fall back to <code>30.0</code> FPS when the backend does not report a valid value. That is especially useful for webcams and inconsistent capture backends.</p>



<h3 class="wp-block-heading">Optional Frame Skipping</h3>



<p>If the incoming stream is heavier than the machine can handle in real time, frame skipping provides a simple way to trade temporal resolution for throughput.</p>



<p>That logic also lives in <code data-enlighter-language="python" class="EnlighterJSRAW">video_analytics/io/video.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="Build a Real-Time Video Analytics Pipeline with YOLO26 and ByteTrack" data-enlighter-group="19">if self.config.frame_skip and frame_index % (self.config.frame_skip + 1) != 0:
    frame_index += 1
    continue
</pre>



<h3 class="wp-block-heading">CPU vs MPS</h3>



<p>On macOS, the most useful deployment toggle is the device argument.</p>



<ul class="wp-block-list">
<li>Use <code data-enlighter-language="python" class="EnlighterJSRAW">device cpu</code> for stable central processing unit (CPU)-only baselines</li>



<li>Use <code data-enlighter-language="python" class="EnlighterJSRAW">device mps</code> on Apple Silicon when available</li>
</ul>



<p>That makes the pipeline practical both for benchmarking and for day-to-day prototyping.</p>



<p>One more engineering note: the detector wrapper currently uses <code data-enlighter-language="python" class="EnlighterJSRAW">model.predict(...)[0]</code> for clarity. For higher-throughput streaming systems, we can also explore streaming-oriented inference patterns (e.g., <code data-enlighter-language="python" class="EnlighterJSRAW">stream=True</code>), but the current version is easier to teach and debug.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/11/image-11-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="175" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-11-1024x175.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-55853"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-11-1024x175.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-11-1024x175.png?size=126x22&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-11-1024x175.png?size=252x43&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-11-1024x175.png?size=378x65&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-11-1024x175.png?size=504x86&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/11/image-11-1024x175.png?size=630x108&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Table 1:</strong> Comparing pipeline responsiveness under CPU and MPS execution on macOS.</figcaption></figure></div>


<p>MPS delivers approximately 3.7 times the throughput of CPU execution under the tested settings. Timing each pipeline stage separately would establish how much of this improvement comes from model inference.</p>



<p>In practice, this means real-time performance is achievable on Apple Silicon with Metal Performance Shaders (MPS), while CPU-only execution may struggle to keep up with higher-resolution streams.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Running-the-Real-Time-Video-Analytics-Pipeline"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Running-the-Real-Time-Video-Analytics-Pipeline">Running the Real-Time Video Analytics Pipeline</a></h2>



<p>The runnable entry point starts in <code data-enlighter-language="python" class="EnlighterJSRAW">video_analytics/cli.py</code>, while the frame-processing loop lives in <code data-enlighter-language="python" class="EnlighterJSRAW">video_analytics/pipeline.py</code>. The root-level <code data-enlighter-language="python" class="EnlighterJSRAW">main.py</code> remains as a thin convenience wrapper. This is the part where our OpenCV object tracking Python code comes together.</p>



<p>These modules do 4 things:</p>



<ul class="wp-block-list">
<li>Parse CLI arguments</li>



<li>Build the pipeline configuration</li>



<li>Instantiate the detector, tracker, analytics layer, and video stream</li>



<li>Run the real-time frame loop</li>
</ul>



<p>The command-line interface (CLI) itself is intentionally thin:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Build a Real-Time Video Analytics Pipeline with YOLO26 and ByteTrack" data-enlighter-group="20">def main() -> None:
    args = parse_args()
    config = build_config(args)
    run_pipeline(config)
</pre>



<p>The heavier orchestration happens inside <code data-enlighter-language="python" class="EnlighterJSRAW">video_analytics/pipeline.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="Build a Real-Time Video Analytics Pipeline with YOLO26 and ByteTrack" data-enlighter-group="21">video_stream = VideoStream(config.video)
detector = YOLO26Detector(config.detection)
tracker = ByteTrackTracker(config.tracking, frame_rate=video_stream.fps)

frame_width, frame_height = video_stream.frame_size
analytics, resolved_lines = build_analytics_engine(config, frame_width, frame_height)
</pre>



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">build_analytics_engine</code> function bridges our configuration and the live analytics objects. It resolves normalized line positions (e.g., <code data-enlighter-language="python" class="EnlighterJSRAW">line_y=0.5</code>) into actual pixel coordinates using the frame dimensions, then creates 1 <code data-enlighter-language="python" class="EnlighterJSRAW">LineCrossingCounter</code> per configured line and optionally a <code data-enlighter-language="python" class="EnlighterJSRAW">ZoneOccupancyCounter</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="Build a Real-Time Video Analytics Pipeline with YOLO26 and ByteTrack" data-enlighter-group="22">def build_analytics_engine(config, frame_width, frame_height):
    allowed_classes = set(config.analytics.class_allowlist) if config.analytics.class_allowlist else None
    resolved_lines = config.analytics.resolve_lines(frame_width, frame_height)
    line_counters = [
        LineCrossingCounter(
            name=line_name,
            line_start=line_points[0],
            line_end=line_points[1],
            allowed_classes=allowed_classes,
        )
        for line_name, line_points in resolved_lines
    ]

    zone_counter = None
    if config.analytics.zone is not None:
        zone_counter = ZoneOccupancyCounter(
            name=config.analytics.zone.name,
            top_left=config.analytics.zone.top_left,
            bottom_right=config.analytics.zone.bottom_right,
            allowed_classes=allowed_classes,
        )

    return AnalyticsEngine(line_counters=line_counters, zone_counter=zone_counter), resolved_lines
</pre>



<p>The result is an <code data-enlighter-language="python" class="EnlighterJSRAW">AnalyticsEngine</code> that the frame loop can call with a simple <code data-enlighter-language="python" class="EnlighterJSRAW">analytics.update(tracks)</code> on every iteration.</p>



<p>The actual frame loop ties everything together:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Build a Real-Time Video Analytics Pipeline with YOLO26 and ByteTrack" data-enlighter-group="23">fps_meter = FPSMeter()
event_log: deque[tuple[str, str, str]] = deque(maxlen=4)
writer = VideoWriter(config.video.output_path, video_stream.fps, (frame_width, frame_height))

try:
    for _, frame in video_stream.frames():
        detections = detector.detect(frame)
        tracks = tracker.update(detections)
        events = analytics.update(tracks)
        for event in events:
            event_log.append((event.class_name, event.line_name, event.direction))

        fps = fps_meter.update()
        draw_tracks(frame, tracks)
        for line_name, line_points in resolved_lines:
            draw_line(frame, line_points[0], line_points[1], line_name)
        if config.analytics.zone is not None:
            draw_zone(frame, config.analytics.zone.top_left, config.analytics.zone.bottom_right, config.analytics.zone.name)
        draw_stats(frame, analytics.stats(), fps)
        draw_events(frame, event_log)

        writer.write(frame)

        if config.video.display:
            cv2.imshow("YOLO26 Video Analytics", frame)
            if cv2.waitKey(1) &amp; 0xFF == ord("q"):
                break
finally:
    writer.release()
    video_stream.release()
    cv2.destroyAllWindows()
</pre>



<p>Each iteration reads 1 frame, pushes it through detection, tracking, and analytics, renders the overlay, and optionally writes to disk. The <code data-enlighter-language="python" class="EnlighterJSRAW">finally</code> block ensures resources are cleaned up even if the loop exits early.</p>



<p>That split is useful because argument parsing, configuration, and runtime execution stay separate.</p>



<p>Here is the command to run it on a webcam:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="bash" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Build a Real-Time Video Analytics Pipeline with YOLO26 and ByteTrack" data-enlighter-group="24">cd yolo26_video_analytics
python main.py --source 0 --device mps --frame-width 960
</pre>



<p>If you want the pipeline configured specifically for people counting, use the preset:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="bash" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Build a Real-Time Video Analytics Pipeline with YOLO26 and ByteTrack" data-enlighter-group="25">cd yolo26_video_analytics
python main.py --preset people --source 0 --device mps
</pre>



<p>Those presets are defined in <code data-enlighter-language="python" class="EnlighterJSRAW">video_analytics/config.py</code>. Here is what they look like:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Build a Real-Time Video Analytics Pipeline with YOLO26 and ByteTrack" data-enlighter-group="26">def people_counting_preset() -> PipelineConfig:
    return PipelineConfig(
        detection=DetectionConfig(confidence=0.3),
        tracking=TrackingConfig(activation_threshold=0.3),
        video=VideoConfig(frame_width=960),
        analytics=AnalyticsConfig(
            lines=(AnalyticsLineConfig(name="entry-line", line_y=0.55),),
            class_allowlist=("person",),
        ),
    )


def traffic_counting_preset() -> PipelineConfig:
    return PipelineConfig(
        detection=DetectionConfig(confidence=0.35),
        tracking=TrackingConfig(activation_threshold=0.35),
        video=VideoConfig(frame_width=1280),
        analytics=AnalyticsConfig(
            lines=(
                AnalyticsLineConfig(name="northbound", line_y=0.42),
                AnalyticsLineConfig(name="southbound", line_y=0.68),
            ),
            class_allowlist=("car", "motorcycle", "bus", "truck"),
        ),
    )
</pre>



<p>The people preset turns the pipeline into people counting software with a single counting line at 55% of the frame height, filtering for <code data-enlighter-language="python" class="EnlighterJSRAW">person</code> only. The traffic preset turns it into a vehicle counting system with 2 named lines at 42% and 68%, restricted to vehicle classes. Both adjust confidence thresholds slightly higher than the default to reduce noise in their target scenarios.</p>



<p>And here is a file-based example:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="bash" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Build a Real-Time Video Analytics Pipeline with YOLO26 and ByteTrack" data-enlighter-group="27">cd yolo26_video_analytics
python main.py \
    --source assets/videos/traffic.mp4 \
    --preset traffic \
    --model assets/models/yolo26n.pt \
  --device cpu \
  --frame-width 1280 \
  --output runs/traffic_count.mp4
</pre>



<p>If you need more control, you can expose the line explicitly:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="bash" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Build a Real-Time Video Analytics Pipeline with YOLO26 and ByteTrack" data-enlighter-group="28">python main.py --source assets/videos/traffic.mp4 --line-points 100,320,1180,320
</pre>



<p>Or configure multiple named lines and a class filter:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="bash" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Build a Real-Time Video Analytics Pipeline with YOLO26 and ByteTrack" data-enlighter-group="29">python main.py \
    --source assets/videos/traffic.mp4 \
    --multi-line-points "entry:0,280,1280,280|exit:0,520,1280,520" \
    --class-filter person \
    --device mps
</pre>



<p>And if you want to monitor occupancy inside a region of interest:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="bash" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Build a Real-Time Video Analytics Pipeline with YOLO26 and ByteTrack" data-enlighter-group="30">python main.py \
    --preset people \
    --source assets/videos/traffic_clip.mp4 \
    --zone-points 300,180,980,680 \
    --device mps
</pre>



<h3 class="wp-block-heading">Example Output (video demo)</h3>



<p>When the system is running, we should see:</p>



<ul class="wp-block-list">
<li>stable bounding boxes</li>



<li>stable track IDs</li>



<li>1 or more labeled counting lines depending on the configuration</li>



<li>total, in, and out counts in the top-left</li>



<li>per-line counts when multiple lines are enabled</li>



<li>optional zone boundaries and occupancy if configured</li>



<li>FPS updating live</li>
</ul>



<p>That is the moment the system stops feeling like a model demo and starts feeling like an analytics application.</p>



<figure class="wp-block-video"><video controls src="https://pyimagesearch.com/wp-content/uploads/2026/10/yolo26-video-analytics-small.mp4"></video></figure>  <!-- Optional Caption --> <figcaption style="text align: center; margin-top: 8px;"><strong>Figure 6:</strong> Annotated output video from the YOLO26 analytics pipeline, visualizing object detections, multi-object tracking IDs, labeled line-crossing logic, and real-time dashboard counts. (source: GIF by the author).</figcaption></figure>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Real-World-Applications-of-People-Counting-and-Vehicle-Counting-Systems"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Real-World-Applications-of-People-Counting-and-Vehicle-Counting-Systems">Real-World Applications of People Counting and Vehicle Counting Systems</a></h2>



<p>This real-time video analytics pipeline structure is widely reusable.</p>



<h3 class="wp-block-heading">Traffic Analytics</h3>



<p>Count vehicles crossing a road segment or entering an intersection.</p>



<p>Use the traffic preset with <code data-enlighter-language="python" class="EnlighterJSRAW">--class-filter car,bus,truck,motorcycle</code> to restrict counting to vehicle classes. With 2 named lines (e.g., <code data-enlighter-language="python" class="EnlighterJSRAW">northbound</code> and <code data-enlighter-language="python" class="EnlighterJSRAW">southbound</code>), you can measure crossings at 2 locations. Verify how each line’s <code data-enlighter-language="python" class="EnlighterJSRAW">"in"</code> and <code data-enlighter-language="python" class="EnlighterJSRAW">"out"</code> labels correspond to traffic direction. Detecting congestion requires additional analytics (e.g., speed or occupancy measurements).</p>



<h3 class="wp-block-heading">Retail Analytics</h3>



<p>Count customers entering or leaving a store zone.</p>



<p>Point a ceiling-mounted camera at the entrance, set a horizontal counting line at the doorway, and use <code data-enlighter-language="python" class="EnlighterJSRAW">--class-filter person</code>. This implementation counts each track only once per line. If the same track enters and later exits across the same line, the return crossing is not counted. Use the zone occupancy counter to report the number of tracked people currently inside a configured region. Pair this with zone-based occupancy counting if we also want to know how many people are standing in a specific aisle or checkout area.</p>



<h3 class="wp-block-heading">Surveillance and Security</h3>



<p>Track movement across a perimeter or virtual gate.</p>



<p>Because ByteTrack assigns persistent IDs, we can log which tracks crossed a boundary and in which direction. The overlay displays the 4 most recent crossing events. To support later review, extend the pipeline to save events to a file or database.</p>



<h3 class="wp-block-heading">Industrial Monitoring</h3>



<p>Count items moving across a conveyor or crossing a checkpoint.</p>



<p>The same line-crossing logic that counts people and vehicles also works for packages, parts, or any other object the YOLO26 model can detect. We only need to adjust the class allowlist and line position to match the specific setup.</p>



<p>The important part is not the line itself. The important part is that once detection, tracking, and analytics are separated cleanly, we can swap the event logic for many other use cases.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-What-Can-Go-Wrong-in-Your-Real-Time-Video-Analytics-Pipeline"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-What-Can-Go-Wrong-in-Your-Real-Time-Video-Analytics-Pipeline">What Can Go Wrong in Your Real-Time Video Analytics Pipeline</a></h2>



<p>While building and running this pipeline, a few practical issues can show up:</p>



<ul class="wp-block-list">
<li><strong>No output video generated:</strong> OpenCV does not create directories automatically. If we save to a path (e.g., <code data-enlighter-language="python" class="EnlighterJSRAW">runs/traffic_count.mp4</code>), ensure the <code data-enlighter-language="python" class="EnlighterJSRAW">runs/</code> folder already exists.</li>



<li><strong>Low FPS or lag:</strong> Reduce the frame width, enable frame skipping, or switch between <code data-enlighter-language="python" class="EnlighterJSRAW">cpu</code> and <code data-enlighter-language="python" class="EnlighterJSRAW">mps</code> to find a better runtime balance.</li>



<li><strong>Incorrect counts:</strong> Line placement matters. If the line is too close to the frame edge or objects only partially cross it, the counts may be inconsistent.</li>



<li><strong>Track ID switches:</strong> In crowded scenes or under occlusion, the tracker may reassign a new ID, which can lead to duplicate counts.</li>
</ul>



<p>These are not signs that the code is fundamentally broken. They are normal challenges in real-world video analytics systems.</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 of on-demand code walkthrough videos • Last updated: November 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</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 moved beyond standalone object detection and built a complete real-time video analytics pipeline from scratch. Instead of thinking about one model in isolation, we learned to reason about a multi-stage system where detection, tracking, analytics, and visualization all need to work together cleanly.</p>



<p>We deployed YOLO26 as the detection backbone, wrapped ByteTrack for multi-object tracking, built a line-crossing analytics engine for people counting and vehicle counting, and connected everything through a modular pipeline that runs on both CPU and MPS. We used dataclasses to define clean interfaces between stages, and we kept configuration separate from runtime logic so the same codebase could serve a traffic counting preset, a people counting preset, or a fully custom setup.</p>



<p>The central idea of this lesson was the separation between detection and analytics. Detection alone can count objects within a frame, but counting unique objects or line-crossing events over time requires tracking and additional analytics. We need stable track IDs across frames before we can ask whether an object crossed a line or entered a zone. ByteTrack provided those IDs, and the analytics layer consumed them to produce directional counts, per-line totals, and optional zone occupancy.</p>



<p>Through the step-by-step build, we saw each layer added incrementally. We started with raw YOLO26 detections on video, added ByteTrack to get persistent IDs, layered in the <code data-enlighter-language="python" class="EnlighterJSRAW">LineCrossingCounter</code> and <code data-enlighter-language="python" class="EnlighterJSRAW">ZoneOccupancyCounter</code> for event-driven analytics, and finished with an OpenCV overlay that shows boxes, IDs, counts, and FPS in real time. We also explored practical performance controls including frame resizing, frame skipping, and the CPU vs MPS device toggle.</p>



<p>By the end of this lesson, we did not just detect objects in a video. We built a reusable pattern for real-time video analytics that separates concerns cleanly enough to swap the detector, change the tracker, or replace the analytics logic without rewriting the pipeline. That pattern applies equally well to traffic analytics, retail occupancy monitoring, security perimeter tracking, and industrial conveyor counting.</p>



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



<p><strong>Singh, V</strong><strong>. </strong>“Build a Real-Time Video Analytics Pipeline with YOLO26 and ByteTrack,” <em>PyImageSearch</em>, S. Huot, A. Sharma, and P. Thakur, eds., 2026, <a href="https://pyimg.co/koi0u" target="_blank" rel="noreferrer noopener">https://pyimg.co/koi0u</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="Build a Real-Time Video Analytics Pipeline with YOLO26 and ByteTrack" data-enlighter-group="31">@incollection{Singh_2026_build-real-time-video-analytics-pipeline-yolo26-bytetrack,
  author = {Vikram Singh},
  title = {{Build a Real-Time Video Analytics Pipeline with YOLO26 and ByteTrack}},
  booktitle = {PyImageSearch},
  editor = {Susan Huot and Aditya Sharma and Piyush Thakur},
  year = {2026},
  url = {https://pyimg.co/koi0u},
}
</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/11/02/build-a-real-time-video-analytics-pipeline-with-yolo26-and-bytetrack/">Build a Real-Time Video Analytics Pipeline with YOLO26 and ByteTrack</a> appeared first on <a rel="nofollow" href="https://pyimagesearch.com">PyImageSearch</a>.</p>
]]></content:encoded>
					
		
		<enclosure url="https://pyimagesearch.com/wp-content/uploads/2026/10/yolo26-video-analytics-small.mp4" length="743975" type="video/mp4" />

			</item>
		<item>
		<title>YOLO26 Object Detection Tutorial: Benchmarking on macOS</title>
		<link>https://pyimagesearch.com/2026/10/26/yolo26-object-detection-tutorial-benchmarking-on-macos/</link>
		
		<dc:creator><![CDATA[Vikram Singh]]></dc:creator>
		<pubDate>Mon, 26 Oct 2026 12:45:00 +0000</pubDate>
				<category><![CDATA[Deep Learning]]></category>
		<category><![CDATA[Object Detection]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[YOLO]]></category>
		<category><![CDATA[apple silicon]]></category>
		<category><![CDATA[benchmark]]></category>
		<category><![CDATA[macos]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[ultralytics yolo26]]></category>
		<category><![CDATA[what is yolo26]]></category>
		<category><![CDATA[yolo object detection]]></category>
		<category><![CDATA[yolo object detection tutorial]]></category>
		<category><![CDATA[yolo real time object detection]]></category>
		<category><![CDATA[yolo26]]></category>
		<category><![CDATA[yolo26 model]]></category>
		<category><![CDATA[yolo26 object detection]]></category>
		<category><![CDATA[yolo26 vs yolo12]]></category>
		<guid isPermaLink="false">https://pyimagesearch.com/?p=55676</guid>

					<description><![CDATA[<p>Table of Contents YOLO26 Object Detection Tutorial: Benchmarking on macOS What Is YOLO26? Why YOLO26 Matters for Real-Time Object Detection What Changed in the Ultralytics YOLO26 Architecture Configuring Your Development Environment Project Structure Installing the Ultralytics YOLO26 Model on macOS&#8230;</p>
<p>The post <a rel="nofollow" href="https://pyimagesearch.com/2026/10/26/yolo26-object-detection-tutorial-benchmarking-on-macos/">YOLO26 Object Detection Tutorial: Benchmarking on macOS</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-YOLO26-Object-Detection-Tutorial-Benchmarking-on-macOS"><a rel="noopener" target="_blank" href="#h1-YOLO26-Object-Detection-Tutorial-Benchmarking-on-macOS">YOLO26 Object Detection Tutorial: Benchmarking on macOS</a></li>
    <li id="TOC-h2-What-Is-YOLO26"><a rel="noopener" target="_blank" href="#h2-What-Is-YOLO26">What Is YOLO26?</a></li>
    <li id="TOC-h2-Why-YOLO26-Matters-for-Real-Time-Object-Detection"><a rel="noopener" target="_blank" href="#h2-Why-YOLO26-Matters-for-Real-Time-Object-Detection">Why YOLO26 Matters for Real-Time Object Detection</a></li>
    <li id="TOC-h2-What-Changed-in-the-Ultralytics-YOLO26-Architecture"><a rel="noopener" target="_blank" href="#h2-What-Changed-in-the-Ultralytics-YOLO26-Architecture">What Changed in the Ultralytics YOLO26 Architecture</a></li>
    <li id="TOC-h2-Configuring-Your-Development-Environment"><a rel="noopener" target="_blank" href="#h2-Configuring-Your-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-Installing-the-Ultralytics-YOLO26-Model-on-macOS"><a rel="noopener" target="_blank" href="#h2-Installing-the-Ultralytics-YOLO26-Model-on-macOS">Installing the Ultralytics YOLO26 Model on macOS</a></li>
    <li id="TOC-h2-Running-YOLO26-Object-Detection-on-Images-Video-and-Webcam-Streams"><a rel="noopener" target="_blank" href="#h2-Running-YOLO26-Object-Detection-on-Images-Video-and-Webcam-Streams">Running YOLO26 Object Detection on Images, Video, and Webcam Streams</a></li>
    <li id="TOC-h2-Understanding-YOLO26-Prediction-Outputs"><a rel="noopener" target="_blank" href="#h2-Understanding-YOLO26-Prediction-Outputs">Understanding YOLO26 Prediction Outputs</a></li>
    <li id="TOC-h2-YOLO26-Benchmarking-Methodology-on-a-MacBook"><a rel="noopener" target="_blank" href="#h2-YOLO26-Benchmarking-Methodology-on-a-MacBook">YOLO26 Benchmarking Methodology on a MacBook</a></li>
    <li id="TOC-h2-YOLO26-vs-YOLO12-Benchmark-Results-on-macOS"><a rel="noopener" target="_blank" href="#h2-YOLO26-vs-YOLO12-Benchmark-Results-on-macOS">YOLO26 vs YOLO12: Benchmark Results on macOS</a></li>
    <li id="TOC-h2-YOLO26-vs-YOLO12-Visual-Detection-Quality-Comparison"><a rel="noopener" target="_blank" href="#h2-YOLO26-vs-YOLO12-Visual-Detection-Quality-Comparison">YOLO26 vs YOLO12: Visual Detection Quality Comparison</a></li>
    <li id="TOC-h2-When-to-Use-the-YOLO26-Model"><a rel="noopener" target="_blank" href="#h2-When-to-Use-the-YOLO26-Model">When to Use the YOLO26 Model</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-YOLO26-Object-Detection-Tutorial-Benchmarking-on-macOS"/>



<h2 class="wp-block-heading"><a href="#TOC-h1-YOLO26-Object-Detection-Tutorial-Benchmarking-on-macOS">YOLO26 Object Detection Tutorial: Benchmarking on macOS</a></h2>



<p>In this lesson, you will learn what YOLO26 is, what changed in the Ultralytics YOLO26 architecture compared to earlier releases, how to run YOLO26 object detection on images, video, and webcam streams on macOS, and how to benchmark YOLO26 against YOLO12n where we measured nearly 30% throughput gains on video.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://pyimagesearch.com/wp-content/uploads/2026/10/yolo26-object-detection-benchmarking-macos-featured.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="940" height="780" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/yolo26-object-detection-benchmarking-macos-featured.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-55765"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/yolo26-object-detection-benchmarking-macos-featured.png?size=126x105&lossy=2&strip=1&webp=1 126w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/yolo26-object-detection-benchmarking-macos-featured-300x249.png?lossy=2&strip=1&webp=1 300w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/yolo26-object-detection-benchmarking-macos-featured.png?size=378x314&lossy=2&strip=1&webp=1 378w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/yolo26-object-detection-benchmarking-macos-featured.png?size=504x418&lossy=2&strip=1&webp=1 504w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/yolo26-object-detection-benchmarking-macos-featured.png?size=630x523&lossy=2&strip=1&webp=1 630w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/yolo26-object-detection-benchmarking-macos-featured-768x637.png?lossy=2&strip=1&webp=1 768w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/yolo26-object-detection-benchmarking-macos-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>YOLO26</strong>:</p>



<ol class="wp-block-list">
<li><em><strong><a href="https://pyimg.co/8p0ln" target="_blank" rel="noreferrer noopener">YOLO26 Object Detection Tutorial: Benchmarking on macOS</a></strong></em><strong> (this tutorial)</strong></li>



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



<p><strong>To learn what YOLO26 is and how it compares to YOLO12 on macOS, </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-What-Is-YOLO26"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-What-Is-YOLO26">What Is YOLO26?</a></h2>



<p>If you have followed the You Only Look Once (YOLO) family over the years, you already know the pattern. Every release promises better speed, better accuracy, or a cleaner deployment story. Sometimes that means small gains. Sometimes it means a meaningful shift in how the detector behaves in production.</p>



<p><a href="https://docs.ultralytics.com/models/yolo26/" target="_blank" rel="noreferrer noopener">YOLO26</a> is interesting because it is not just another checkpoint refresh. Ultralytics presents it as an end-to-end detector with NMS-free inference by default, along with changes aimed at faster central processing unit (CPU) execution and cleaner edge deployment. Those claims matter because many real-world YOLO systems for real-time object detection do not run on large data center graphics processing units (GPUs). They run on laptops, edge boxes, personal computers (PCs), robotics platforms, and embedded devices where simplicity and latency matter.</p>



<p>In this lesson, you will answer 4 practical questions:</p>



<ul class="wp-block-list">
<li>What changed in YOLO26 compared with earlier Ultralytics YOLO releases?</li>



<li>How do you run YOLO26 on macOS for images, videos, and webcam streams?</li>



<li>What do the YOLO26 model outputs actually look like in Python?</li>



<li>How does YOLO26 vs YOLO12 performance stack up on a MacBook?</li>
</ul>



<p>By the end of this lesson, you will have a grounded understanding of what YOLO26 is, a reproducible benchmark workflow, and concrete numbers showing YOLO26 object detection running nearly 30% faster than YOLO12n on video.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Why-YOLO26-Matters-for-Real-Time-Object-Detection"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Why-YOLO26-Matters-for-Real-Time-Object-Detection">Why YOLO26 Matters for Real-Time Object Detection</a></h2>



<p>The easiest way to misunderstand a new detector release is to treat it like a version number bump and move on. That misses the point.</p>



<p>What makes the Ultralytics YOLO26 release worth paying attention to is not just accuracy. It is the combination of 3 practical ideas.</p>



<h3 class="wp-block-heading">End-to-End Detection</h3>



<p>Traditional real-time detectors usually produce many overlapping candidate boxes and then rely on non-maximum suppression (NMS) to prune duplicates. That works well, but it adds a post-processing stage and a few more tuning knobs.</p>



<p>Ultralytics documents YOLO26 as using an end-to-end path by default, which means the standard inference path no longer depends on NMS in the same way earlier pipelines did. In plain English, the model is designed to produce a more direct set of final detections.</p>



<h4 class="wp-block-heading">Why NMS Becomes a Performance Tax</h4>



<p>NMS sounds simple in theory, but in practice it behaves like an extra tax on every frame. After the model generates candidate boxes, the pipeline still has to filter them, sort them, and suppress overlaps based on intersection over union (IoU). That adds more work after the neural network has already done its main job.</p>



<p>On desktop GPUs, that cost may be easy to hide. On CPUs and edge accelerators, it can become much more visible. Even worse, it can complicate deployment because post-processing is not always handled by the same optimized runtime that executes the network itself.</p>



<h4 class="wp-block-heading">Why Latency Variability Matters</h4>



<p>NMS is also scene-dependent. A sparse image with very few confident detections is cheap to process. A crowded frame with many overlapping candidates demands more sorting and more overlap checks. That means latency can fluctuate based on what the camera sees.</p>



<p>For robotics, industrial inspection, and real-time video systems, predictable timing matters. Even if YOLO26 does not make every environment perfectly deterministic, removing NMS from the standard inference path reduces one major source of latency jitter.</p>



<h3 class="wp-block-heading">Faster CPU-Oriented Deployment</h3>



<p>On paper, the official YOLO26 documentation emphasizes stronger CPU performance, especially for deployment scenarios where a heavy GPU stack is not the main story. That matters on macOS because many of you prototype on Apple laptops and often need a reliable local baseline before thinking about mobile, edge, or cloud deployment.</p>



<h3 class="wp-block-heading">Cleaner Edge Story</h3>



<p>YOLO26 is also positioned as an edge-first release. That does not mean it is only for edge devices. It means the design decisions try to reduce deployment friction across hardware and export formats.</p>



<p>If you are building applications for robotics, industrial inspection, or always-on video analytics, those changes are not academic. They directly affect latency, integration complexity, and operational cost.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-What-Changed-in-the-Ultralytics-YOLO26-Architecture"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-What-Changed-in-the-Ultralytics-YOLO26-Architecture">What Changed in the Ultralytics YOLO26 Architecture</a></h2>



<p>Now let us make that concrete.</p>



<h3 class="wp-block-heading">End-to-End, NMS-Free Inference by Default</h3>



<p>According to the public Ultralytics documentation, YOLO26 uses a one-to-one head by default for end-to-end prediction, and this default path does not require NMS. Ultralytics also notes that you can still switch back to a more traditional path by setting <code data-enlighter-language="python" class="EnlighterJSRAW">end2end=False</code> for workflows that need compatibility with NMS-based post-processing.</p>



<p>That distinction is worth understanding.</p>



<h4 class="wp-block-heading">Traditional Detector Pipeline</h4>



<p>In a traditional pipeline, the detector produces many candidate boxes. Post-processing then removes duplicates and overlapping boxes with NMS. The final detection quality can depend on the confidence score and IoU thresholds.</p>



<h4 class="wp-block-heading">YOLO26 Default Pipeline</h4>



<p>In the default YOLO26 path, the detector is configured to produce final detections directly enough that NMS is not part of the standard prediction path. This reduces post-processing overhead and simplifies deployment logic.</p>



<p>For you as a practitioner, the biggest takeaway is simple: fewer moving parts after the forward pass usually makes inference pipelines easier to reason about and easier to deploy.</p>



<h4 class="wp-block-heading">The One-to-Many Legacy</h4>



<p>Earlier YOLO-style detectors typically learn through a one-to-many assignment strategy, where multiple predictions may be associated with the same ground-truth object during training. That is useful for optimization and recall, but it also leaves the model with a dense set of redundant candidates that need cleanup afterward.</p>



<p>YOLO26 moves the default inference story closer to one-to-one prediction. Instead of asking post-processing to resolve a large pile of overlapping candidates, the deployed model is designed to produce a cleaner final set of object hypotheses.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://pyimagesearch.com/wp-content/uploads/2026/10/image-39.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="624" height="339" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-39.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-55767"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-39.png?size=126x68&lossy=2&strip=1&webp=1 126w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-39-300x163.png?lossy=2&strip=1&webp=1 300w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-39.png?size=378x205&lossy=2&strip=1&webp=1 378w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-39.png?size=504x274&lossy=2&strip=1&webp=1 504w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-39.png?lossy=2&strip=1&webp=1 624w" sizes="(max-width: 624px) 100vw, 624px" /></a><figcaption class="wp-element-caption"><strong>Figure 1:</strong> Traditional object detection versus YOLO26 end-to-end detection (source: image by the author).</figcaption></figure></div>


<h3 class="wp-block-heading">DFL Removal and Export Friendliness</h3>



<p>Ultralytics also highlights Distribution Focal Loss (DFL) removal as a major change in YOLO26. The practical benefit is not that you need to memorize every detail of the underlying loss formulation. The practical benefit is cleaner export behavior and wider edge compatibility.</p>



<p>That matters if you eventually want to move from PyTorch to Open Neural Network Exchange (ONNX), Core ML, NCNN, or another deployment target without spending your entire week debugging export quirks.</p>



<p>It also matters because older regression heads often require extra decoding logic after the raw network output. By simplifying that path, YOLO26 makes the exported graph easier to deploy and easier to inspect.</p>



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



<p>Ultralytics documents several training-related updates for YOLO26, including Progressive Loss (ProgLoss), Small-Target-Aware Label Assignment (STAL), and a MuSGD optimizer. You do not need to dive deep into those right now because this lesson is centered on inference and benchmarking, not custom training. Still, it is useful to know that YOLO26 is not only an inference story. Some of its improvements are tied to how the model was trained in the first place.</p>



<h4 class="wp-block-heading">Why One-to-One Training Is Hard</h4>



<p>One reason NMS-free detection took time to mature is that strict one-to-one supervision is harder to optimize. If the model is forced to commit to one prediction per object too early, the learning signal can become sparse and unstable.</p>



<h4 class="wp-block-heading">Dual-Head Intuition</h4>



<p>The broader end-to-end YOLO line addresses that problem by combining rich training supervision with a cleaner deployment path. The key intuition is that the model can still learn from denser training signals internally while using a one-to-one style head for final inference.</p>



<p>You do not need every implementation detail in this lesson, but it helps to know that YOLO26 is not simply &#8220;YOLO with NMS turned off.&#8221; The clean inference behavior is supported by training design.</p>



<h4 class="wp-block-heading">What to Defer to Lesson 2</h4>



<p>We should keep the deeper training mechanics for Lesson 2. That is the right place to discuss how label assignment, optimizer choice, and architecture decisions affect custom training results.</p>



<h3 class="wp-block-heading">CPU Speed Improvements</h3>



<p>Ultralytics specifically claims large CPU-side gains for YOLO26. That is one of the main reasons this lesson focuses on a MacBook workflow. If a detector says it is edge-first and CPU-aware, it should be able to prove that in a benchmark you can reproduce locally.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://pyimagesearch.com/wp-content/uploads/2026/10/image-40.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="624" height="287" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-40.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-55769"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-40.png?size=126x58&lossy=2&strip=1&webp=1 126w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-40-300x138.png?lossy=2&strip=1&webp=1 300w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-40.png?size=378x174&lossy=2&strip=1&webp=1 378w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-40.png?size=504x232&lossy=2&strip=1&webp=1 504w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-40.png?lossy=2&strip=1&webp=1 624w" sizes="(max-width: 624px) 100vw, 624px" /></a><figcaption class="wp-element-caption"><strong>Figure 2:</strong> High-level reasons YOLO26 matters in practice: end-to-end inference, CPU speed, and edge deployment (source: image by the author).</figcaption></figure></div>


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



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



<p>To follow this guide, you need to have the Ultralytics package installed on your system.</p>



<p>Luckily, Ultralytics is pip-installable:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="YOLO26 Object Detection Tutorial: Benchmarking on macOS" data-enlighter-group="1">$ pip install -U ultralytics
</pre>



<p>If you need help configuring your development environment for Ultralytics and YOLO26, we highly recommend creating a fresh virtual environment first.</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>The following is a short directory structure:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="YOLO26 Object Detection Tutorial: Benchmarking on macOS" data-enlighter-group="2">.
├── benchmark_yolo_macos.py
├── yolo26n.pt
├── yolo12n.pt
└── &lt;your_test_images_or_video>/
    └── traffic_clip.mp4
</pre>



<p>The <code data-enlighter-language="python" class="EnlighterJSRAW">benchmark_yolo_macos.py</code> script is the main workhorse. The model checkpoints are downloaded automatically by Ultralytics the first time you reference them.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Installing-the-Ultralytics-YOLO26-Model-on-macOS"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Installing-the-Ultralytics-YOLO26-Model-on-macOS">Installing the Ultralytics YOLO26 Model on macOS</a></h2>



<p>Let us move from theory to practice.</p>



<h3 class="wp-block-heading">Create a Clean Python Environment</h3>



<p>If you already have a computer vision environment on your Mac, resist the temptation to pile more packages into it. Use a fresh 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="YOLO26 Object Detection Tutorial: Benchmarking on macOS" data-enlighter-group="3">python3 -m venv .venv
source .venv/bin/activate
python -m pip install --upgrade pip
</pre>



<h3 class="wp-block-heading">Install Ultralytics</h3>



<p>With the environment active, install the Ultralytics 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="YOLO26 Object Detection Tutorial: Benchmarking on macOS" data-enlighter-group="4">pip install -U ultralytics
</pre>



<p>At the time of writing, this is the cleanest way to access YOLO26 through the official Python and CLI interfaces.</p>



<h3 class="wp-block-heading">Verify the Installation</h3>



<p>You can verify the install in either Python or the command-line interface (CLI).</p>



<h4 class="wp-block-heading">CLI Check</h4>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="YOLO26 Object Detection Tutorial: Benchmarking on macOS" data-enlighter-group="5">yolo version
</pre>



<h4 class="wp-block-heading">Python Check</h4>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="YOLO26 Object Detection Tutorial: Benchmarking on macOS" data-enlighter-group="6">from ultralytics import YOLO

model = YOLO("yolo26n.pt")
print(model.task)
</pre>



<p>The first time you load a pretrained checkpoint, Ultralytics will download it automatically if it is not already present on your machine.</p>



<h3 class="wp-block-heading">Optional: Check for Apple Silicon Acceleration</h3>



<p>If you are on Apple Silicon, it is useful to know whether the Metal Performance Shaders (MPS) backend is available.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="YOLO26 Object Detection Tutorial: Benchmarking on macOS" data-enlighter-group="7">import torch

print("MPS available:", torch.backends.mps.is_available())
print("MPS built:", torch.backends.mps.is_built())
</pre>



<p>If MPS is available, you can run predictions with <code data-enlighter-language="python" class="EnlighterJSRAW">device="mps"</code>. If not, stay on CPU and keep the benchmark methodology consistent.</p>



<p><strong><br></strong></p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/10/image-41-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="355" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-41-1024x355.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-55774"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-41-1024x355.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-41-1024x355.png?size=126x44&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-41-1024x355.png?size=252x87&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-41-1024x355.png?size=378x131&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-41-1024x355.png?size=504x175&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-41-1024x355.png?size=630x218&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 3:</strong> Installing the Ultralytics package and verifying a YOLO26 model on macOS (source: image by the author).</figcaption></figure></div>


<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Running-YOLO26-Object-Detection-on-Images-Video-and-Webcam-Streams"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Running-YOLO26-Object-Detection-on-Images-Video-and-Webcam-Streams">Running YOLO26 Object Detection on Images, Video, and Webcam Streams</a></h2>



<p>Now you are ready to run the model.</p>



<h3 class="wp-block-heading">First Image Inference</h3>



<p>The smallest useful example is a single 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="YOLO26 Object Detection Tutorial: Benchmarking on macOS" data-enlighter-group="8">from ultralytics import YOLO

model = YOLO("yolo26n.pt")
results = model("image.jpg")
</pre>



<p>That line performs the entire inference pass and returns a list of <code data-enlighter-language="python" class="EnlighterJSRAW">Results</code> objects, one per image.</p>



<p>If you want to be explicit about the prediction application programming interface (API) and device choice, do this instead:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="YOLO26 Object Detection Tutorial: Benchmarking on macOS" data-enlighter-group="9">from ultralytics import YOLO

model = YOLO("yolo26n.pt")
results = model.predict(
    source="image.jpg",
    imgsz=640,
    conf=0.25,
    device="mps",  # use "cpu" if MPS is unavailable
)
</pre>



<p><strong><br></strong></p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://pyimagesearch.com/wp-content/uploads/2026/10/image-42.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="624" height="392" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-42.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-55776"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-42.png?size=126x79&lossy=2&strip=1&webp=1 126w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-42-300x188.png?lossy=2&strip=1&webp=1 300w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-42.png?size=378x237&lossy=2&strip=1&webp=1 378w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-42.png?size=504x317&lossy=2&strip=1&webp=1 504w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-42.png?lossy=2&strip=1&webp=1 624w" sizes="(max-width: 624px) 100vw, 624px" /></a><figcaption class="wp-element-caption"><strong>Figure 4:</strong> Running YOLO26 on a single image using the Ultralytics Python API (source: image by the author).</figcaption></figure></div>


<h3 class="wp-block-heading">Running on a Folder of Images</h3>



<p>When you pass a directory, Ultralytics will iterate through the media 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="YOLO26 Object Detection Tutorial: Benchmarking on macOS" data-enlighter-group="10">from ultralytics import YOLO

model = YOLO("yolo26n.pt")
results = model.predict(source="images/", imgsz=640, conf=0.25, device="mps")
</pre>



<p>This is a fast way to build a qualitative feel for the model before you benchmark it.</p>



<h3 class="wp-block-heading">Running on a Video File</h3>



<p>For video inference, the API stays almost identical.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="YOLO26 Object Detection Tutorial: Benchmarking on macOS" data-enlighter-group="11">from ultralytics import YOLO

model = YOLO("yolo26n.pt")
results = model.predict(source="sample_video.mp4", show=True, device="mps")
</pre>



<p>If you want saved output rather than a live preview window, add <code data-enlighter-language="python" class="EnlighterJSRAW">save=True</code>.</p>



<h3 class="wp-block-heading">Running Real-Time Webcam Detection</h3>



<p>Webcam inference is where macOS users get an immediate feel for real-world responsiveness.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="YOLO26 Object Detection Tutorial: Benchmarking on macOS" data-enlighter-group="12">from ultralytics import YOLO

model = YOLO("yolo26n.pt")
model.predict(source=0, show=True, device="mps")
</pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://pyimagesearch.com/wp-content/uploads/2026/10/image-43.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="619" height="365" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-43.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-55779"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-43.png?size=126x74&lossy=2&strip=1&webp=1 126w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-43-300x177.png?lossy=2&strip=1&webp=1 300w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-43.png?size=378x223&lossy=2&strip=1&webp=1 378w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-43.png?size=504x297&lossy=2&strip=1&webp=1 504w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-43.png?lossy=2&strip=1&webp=1 619w" sizes="(max-width: 619px) 100vw, 619px" /></a><figcaption class="wp-element-caption"><strong>Figure 5:</strong> Real-time webcam detection with YOLO26 on macOS (source: image by the author).</figcaption></figure></div>


<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Understanding-YOLO26-Prediction-Outputs"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Understanding-YOLO26-Prediction-Outputs">Understanding YOLO26 Prediction Outputs</a></h2>



<p>Running inference is only half the story. If you are going to build with YOLO26, you also need to understand what comes back.</p>



<h3 class="wp-block-heading">The Results Object</h3>



<p>A prediction call returns a list of <code data-enlighter-language="python" class="EnlighterJSRAW">Results</code> objects. In the single-image case, you usually care about <code data-enlighter-language="python" class="EnlighterJSRAW">results[0]</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="YOLO26 Object Detection Tutorial: Benchmarking on macOS" data-enlighter-group="13">from ultralytics import YOLO

model = YOLO("yolo26n.pt")
results = model("image.jpg")
result = results[0]
</pre>



<h3 class="wp-block-heading">Inspect Boxes, Classes, and Confidences</h3>



<p>The boxes are stored in <code data-enlighter-language="python" class="EnlighterJSRAW">result.boxes</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="YOLO26 Object Detection Tutorial: Benchmarking on macOS" data-enlighter-group="14">boxes = result.boxes

print("Number of detections:", len(boxes))
print("Classes:", boxes.cls)
print("Confidences:", boxes.conf)
print("XYXY boxes:", boxes.xyxy)
</pre>



<p>In practice, the most useful fields are the following.</p>



<h4 class="wp-block-heading">boxes.xyxy</h4>



<p>Bounding boxes in corner format: <code data-enlighter-language="python" class="EnlighterJSRAW">(x1, y1, x2, y2)</code>.</p>



<h4 class="wp-block-heading">boxes.conf</h4>



<p>Confidence scores for each detection.</p>



<h4 class="wp-block-heading">boxes.cls</h4>



<p>Predicted class IDs.</p>



<h3 class="wp-block-heading">Map Class IDs Back to Labels</h3>



<p>Ultralytics stores class name metadata on 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="YOLO26 Object Detection Tutorial: Benchmarking on macOS" data-enlighter-group="15">names = result.names

for box in result.boxes:
    class_id = int(box.cls.item())
    confidence = float(box.conf.item())
    label = names[class_id]
    print(label, confidence)
</pre>



<h3 class="wp-block-heading">Inspect Preprocessing, Inference, and Postprocessing Time</h3>



<p>Ultralytics <code data-enlighter-language="python" class="EnlighterJSRAW">Results</code> objects also expose timing 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="YOLO26 Object Detection Tutorial: Benchmarking on macOS" data-enlighter-group="16">print(result.speed)
</pre>



<p>This usually gives you a dictionary with timings for preprocessing, inference, and postprocessing, measured in milliseconds per image. That is very useful for debugging, but for a fair benchmark we still want a consistent, external timing harness around repeated runs.</p>



<h3 class="wp-block-heading">What True End-to-End Export Looks Like</h3>



<p>One practical way to verify the deployment story is to export the model and inspect the graph.</p>



<p>If you export YOLO26 to ONNX and open it in Netron, the goal is not to memorize every operator. The goal is to confirm that the exported graph is much closer to the final inference path used by the application than older detector exports that still depend on heavier post-processing outside the network.</p>



<h4 class="wp-block-heading">Older YOLO-Style Export</h4>



<p>The exported graph often ends in dense predictions that still need external filtering, decoding, or NMS-like logic before they become a clean set of final detections.</p>



<h4 class="wp-block-heading">YOLO12 vs. YOLO26: ONNX Export Comparison</h4>



<p>In YOLO12, the ONNX export shown in <strong>Figure 6 </strong>includes non-maximum suppression (NMS) directly inside the model graph. The graph contains an explicit <code data-enlighter-language="python" class="EnlighterJSRAW">NonMaxSuppression</code> node followed by a sequence of <code data-enlighter-language="python" class="EnlighterJSRAW">Gather</code>, <code data-enlighter-language="python" class="EnlighterJSRAW">Slice</code>, and <code data-enlighter-language="python" class="EnlighterJSRAW">Concat</code> operations to filter and format the final detections.</p>



<p>This design produces ready-to-use outputs but tightly couples post-processing with the model itself. As a result, it becomes harder to customize thresholds, experiment with alternative filtering strategies, or adapt the pipeline for different deployment environments. </p>



<p>Additionally, embedding NMS inside the graph introduces extra operations during inference, which can contribute to higher latency depending on the execution backend and hardware.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/10/image-44-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="956" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-44-1024x956.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-55781"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-44-1024x956.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-44-1024x956.png?size=126x118&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-44-1024x956.png?size=252x235&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-44-1024x956.png?size=378x353&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-44-1024x956.png?size=504x471&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-44-1024x956.png?size=630x588&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 6:</strong> ONNX graph of YOLO12 showing embedded non-maximum suppression (NMS) and associated post-processing operations within the model (source: image by the author).</figcaption></figure></div>


<p>In contrast, YOLO26 removes non-maximum suppression from the model graph entirely. As illustrated in <strong>Figure 7</strong>, the exported ONNX graph produces a single consolidated output tensor without any embedded NMS logic.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/10/image-45-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="800" height="1024" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-45-800x1024.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-55783"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-45-800x1024.png?lossy=2&strip=1&webp=1 800w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-45-800x1024.png?size=126x161&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-45-800x1024.png?size=252x323&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-45-800x1024.png?size=378x484&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-45-800x1024.png?size=504x645&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-45-800x1024.png?size=630x806&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 800px) 100vw, 800px" /></a><figcaption class="wp-element-caption"><strong>Figure 7:</strong> ONNX graph of YOLO26 producing a unified output tensor without embedded NMS, enabling external post-processing (source: image by the author).</figcaption></figure></div>


<p>This design shifts post-processing outside the model, resulting in a cleaner and more modular pipeline. Developers can control filtering, thresholding, and downstream processing explicitly, making the system easier to optimize, debug, and integrate with tracking and analytics systems.</p>



<p>In practice, this separation can also improve end-to-end latency, especially when using optimized or hardware-accelerated post-processing outside the model graph.</p>



<p>The exported graph is much closer to the final detection representation consumed by the application. This is what is typically meant when describing the model as end-to-end for inference.</p>



<p>The key difference is not just the model architecture, but where post-processing is performed inside the graph versus in the surrounding application pipeline.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-YOLO26-Benchmarking-Methodology-on-a-MacBook"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-YOLO26-Benchmarking-Methodology-on-a-MacBook">YOLO26 Benchmarking Methodology on a MacBook</a></h2>



<p>This is the section that separates a useful lesson from a casual demo.</p>



<h3 class="wp-block-heading">What You Want to Measure</h3>



<p>For Lesson 1, focus on 4 metrics:</p>



<ul class="wp-block-list">
<li>Median latency per image</li>



<li>Throughput in frames per second (FPS)</li>



<li>Model size on disk</li>



<li>Parameter count</li>
</ul>



<p>Memory usage is also valuable, but it is easier to measure unreliably. If you include it, document exactly how you measured it.</p>



<h3 class="wp-block-heading">Keep Your Benchmark Honest</h3>



<p>When people publish model comparisons, they often change too many variables at once. Do not do that.</p>



<p>Keep these fixed across both models:</p>



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



<li>Same device target, either CPU or MPS</li>



<li>Same input image size</li>



<li>Same batch size</li>



<li>Same test image or test image set</li>



<li>Same number of warmup iterations</li>



<li>Same number of timed iterations</li>
</ul>



<p>If you cannot control those variables, your comparison becomes anecdotal.</p>



<p><strong><br></strong></p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://pyimagesearch.com/wp-content/uploads/2026/10/image-46.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="624" height="301" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-46.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-55785"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-46.png?size=126x61&lossy=2&strip=1&webp=1 126w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-46-300x145.png?lossy=2&strip=1&webp=1 300w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-46.png?size=378x182&lossy=2&strip=1&webp=1 378w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-46.png?size=504x243&lossy=2&strip=1&webp=1 504w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-46.png?lossy=2&strip=1&webp=1 624w" sizes="(max-width: 624px) 100vw, 624px" /></a><figcaption class="wp-element-caption"><strong>Figure 8:</strong> Benchmark protocol used to compare YOLO26 and the baseline model on a MacBook (source: image by the author).</figcaption></figure></div>


<h3 class="wp-block-heading">A Practical Benchmark Harness for YOLO Real-Time Object Detection</h3>



<p>To make this lesson fully reproducible, we have included a companion script called <code data-enlighter-language="python" class="EnlighterJSRAW">benchmark_yolo_macos.py</code>. You can use it to benchmark any combination of YOLO checkpoints on your own machine.</p>



<p>At a high level, the script does the following:</p>



<ul class="wp-block-list">
<li>Loads one or more Ultralytics YOLO checkpoints</li>



<li>Performs warmup runs to stabilize the runtime</li>



<li>Measures wall-clock latency over repeated predictions</li>



<li>Reports median latency and FPS</li>



<li>Extracts parameter counts from the loaded model</li>



<li>Reports checkpoint file size on disk</li>
</ul>



<p>Here is the full script:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="YOLO26 Object Detection Tutorial: Benchmarking on macOS" data-enlighter-group="17">import argparse
import statistics
import time
from pathlib import Path

from ultralytics import YOLO


def parse_args():
    parser = argparse.ArgumentParser(description="Benchmark YOLO models on macOS.")
    parser.add_argument("--models", nargs="+", required=True, help="Model weights to benchmark.")
    parser.add_argument("--source", required=True, help="Image, folder, or video source for inference.")
    parser.add_argument("--imgsz", type=int, default=640, help="Inference image size.")
    parser.add_argument("--device", default="cpu", help="Inference device, e.g. cpu or mps.")
    parser.add_argument("--conf", type=float, default=0.25, help="Confidence threshold.")
    parser.add_argument("--warmup", type=int, default=5, help="Warmup iterations.")
    parser.add_argument("--runs", type=int, default=30, help="Timed iterations.")
    parser.add_argument(
        "--max-items",
        type=int,
        default=None,
        help="Maximum number of frames/items to process per run for videos, folders, or streams.",
    )
    return parser.parse_args()


def get_param_count(model):
    if hasattr(model.model, "parameters"):
        return sum(parameter.numel() for parameter in model.model.parameters())
    return None


def format_params(param_count):
    if param_count is None:
        return "n/a"
    return f"{param_count / 1_000_000:.2f}M"


def format_size(weights_path):
    path = Path(weights_path)
    if path.exists() and path.is_file():
        return f"{path.stat().st_size / (1024 * 1024):.2f} MB"
    return "downloaded/cache-managed"


IMAGE_SUFFIXES = {".jpg", ".jpeg", ".png", ".bmp", ".tif", ".tiff", ".webp"}
VIDEO_SUFFIXES = {".mp4", ".mov", ".m4v", ".avi", ".mkv", ".webm", ".mpg", ".mpeg"}


def classify_source(source):
    source_str = str(source)
    if source_str.isdigit():
        return "stream"

    path = Path(source_str).expanduser()
    if path.is_dir():
        return "collection"

    suffix = path.suffix.lower()
    if suffix in IMAGE_SUFFIXES:
        return "image"
    if suffix in VIDEO_SUFFIXES:
        return "video"
    return "collection"


def timed_predict(model, source, imgsz, conf, device, max_items=None):
    source_kind = classify_source(source)
    start = time.perf_counter()
    if source_kind == "image":
        model.predict(source=source, imgsz=imgsz, conf=conf, device=device, verbose=False)
        items_processed = 1
    else:
        items_processed = 0
        for _ in model.predict(source=source, imgsz=imgsz, conf=conf, device=device, verbose=False, stream=True):
            items_processed += 1
            if max_items is not None and items_processed >= max_items:
                break
    end = time.perf_counter()
    return {
        "elapsed_ms": (end - start) * 1000.0,
        "items_processed": items_processed,
        "source_kind": source_kind,
    }


def benchmark_model(weights, source, imgsz, conf, device, warmup, runs, max_items=None):
    model = YOLO(weights)

    for _ in range(warmup):
        timed_predict(model, source, imgsz, conf, device, max_items=max_items)

    timings = [timed_predict(model, source, imgsz, conf, device, max_items=max_items) for _ in range(runs)]
    elapsed_values = [timing["elapsed_ms"] for timing in timings]
    items_processed = timings[-1]["items_processed"] if timings else 0
    source_kind = timings[-1]["source_kind"] if timings else classify_source(source)
    median_latency_ms = statistics.median(elapsed_values)
    fps = 1000.0 / median_latency_ms if median_latency_ms > 0 else 0.0
    median_ms_per_item = median_latency_ms / items_processed if items_processed > 0 else None
    item_rate = (1000.0 * items_processed / median_latency_ms) if median_latency_ms > 0 and items_processed > 0 else 0.0

    return {
        "model": weights,
        "device": device,
        "imgsz": imgsz,
        "source_kind": source_kind,
        "items_processed": items_processed,
        "median_latency_ms": median_latency_ms,
        "median_ms_per_item": median_ms_per_item,
        "fps": fps,
        "item_rate": item_rate,
        "params": format_params(get_param_count(model)),
        "size": format_size(weights),
    }


def print_results(results):
    header = (
        f"{'Model':&lt;20} {'Device':&lt;8} {'Source':&lt;10} {'Items':&lt;8} {'Median Total (ms)':&lt;20} "
        f"{'ms/item':&lt;12} {'item/s':&lt;10} {'Params':&lt;12} {'Size':&lt;20}"
    )
    print(header)
    print("-" * len(header))
    for result in results:
        ms_per_item = f"{result['median_ms_per_item']:.2f}" if result["median_ms_per_item"] is not None else "n/a"
        print(
            f"{result['model']:&lt;20} {result['device']:&lt;8} {result['source_kind']:&lt;10} {result['items_processed']:&lt;8} "
            f"{result['median_latency_ms']:&lt;20.2f} {ms_per_item:&lt;12} {result['item_rate']:&lt;10.2f} "
            f"{result['params']:&lt;12} {result['size']:&lt;20}"
        )


def main():
    args = parse_args()
    results = [
        benchmark_model(
            weights=model_name,
            source=args.source,
            imgsz=args.imgsz,
            conf=args.conf,
            device=args.device,
            warmup=args.warmup,
            runs=args.runs,
            max_items=args.max_items,
        )
        for model_name in args.models
    ]
    print_results(results)


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



<p>Let us walk through the key parts of this script so you understand exactly what is happening.</p>



<ul class="wp-block-list">
<li><code data-enlighter-language="python" class="EnlighterJSRAW">parse_args</code>: sets up the CLI. You pass in one or more <code data-enlighter-language="python" class="EnlighterJSRAW">models</code> (e.g., <code data-enlighter-language="python" class="EnlighterJSRAW">yolo26n.pt</code> and <code data-enlighter-language="python" class="EnlighterJSRAW">yolo12n.pt</code>), a <code data-enlighter-language="python" class="EnlighterJSRAW">source</code> image or video, and optional knobs for image size, device, warmup iterations, and timed runs. The <code data-enlighter-language="python" class="EnlighterJSRAW">max-items</code> flag is especially useful for video benchmarks, it caps how many frames get processed per run so you are not sitting through an entire clip.</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">classify_source</code>: figures out whether your input is a single image, a video, a directory of images, or a live stream. This matters because image inference runs in one shot, while video and streams use Ultralytics&#8217; <code data-enlighter-language="python" class="EnlighterJSRAW">stream=True</code> generator to process frames lazily.</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">timed_predict</code>: is the core timing function. It wraps a single prediction pass with <code data-enlighter-language="python" class="EnlighterJSRAW">time.perf_counter()</code> calls. For images, it runs a standard <code data-enlighter-language="python" class="EnlighterJSRAW">model.predict(...)</code>. For videos and streams, it iterates through the streaming generator and counts frames, optionally stopping early at <code data-enlighter-language="python" class="EnlighterJSRAW">max_items</code>. The function returns elapsed time, items processed, and source type.</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">benchmark_model</code>: orchestrates the full benchmark for one model. It loads the checkpoint, runs the specified number of warmup iterations (to reduce first-run overhead such as graph compilation and cache effects), then collects timing data over the timed runs. From the raw timings, it computes median latency, FPS, per-item throughput, parameter count, and file size.</li>



<li><code data-enlighter-language="python" class="EnlighterJSRAW">print_results</code>: formats everything into a readable terminal table so you can eyeball the comparison immediately.</li>
</ul>



<p>Here is the core usage pattern:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="YOLO26 Object Detection Tutorial: Benchmarking on macOS" data-enlighter-group="18">python benchmark_yolo_macos.py \
  --models yolo26n.pt yolo12n.pt \
  --source traffic_clip.mp4 \
  --imgsz 640 \
  --device mps \
  --warmup 5 \
  --runs 30 \
  --max-items 300
</pre>



<p>In this lesson, we use <code data-enlighter-language="python" class="EnlighterJSRAW">yolo12n.pt</code> as the baseline because it is the most recent predecessor available through the Ultralytics package before YOLO26. The benchmark methodology matters more than the exact baseline label, as long as the comparison stays controlled, you get an honest picture of where YOLO26 stands.</p>



<p>If you want a second benchmark perspective, cite the official Ultralytics CPU ONNX and T4 TensorRT numbers alongside your MacBook measurements. That gives your readers both a vendor-published reference point and a local reproducible benchmark.</p>



<h3 class="wp-block-heading">Why You Should Use Median Latency</h3>



<p>Always use median latency instead of a single run or a raw average from a tiny sample. Your first run may include checkpoint download, graph setup, cache effects, or backend warmup. Median latency after warmup gives you a more stable number.</p>



<h3 class="wp-block-heading">CPU versus MPS</h3>



<p>On a MacBook, you should benchmark both if time permits.</p>



<h4 class="wp-block-heading">CPU Benchmark</h4>



<p>CPU numbers help you evaluate edge-style deployment behavior and align well with Ultralytics&#8217; published CPU ONNX comparisons.</p>



<h4 class="wp-block-heading">MPS Benchmark</h4>



<p>MPS numbers tell you how the model feels on Apple Silicon in day-to-day local development.</p>



<p>Those 2 measurements answer different questions, so it is okay to report both as long as you keep the methodology clear.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-YOLO26-vs-YOLO12-Benchmark-Results-on-macOS"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-YOLO26-vs-YOLO12-Benchmark-Results-on-macOS">YOLO26 vs YOLO12: Benchmark Results on macOS</a></h2>



<p>Now let us look at the actual numbers.</p>



<h3 class="wp-block-heading">What We Compared</h3>



<p>For this lesson, we ran the YOLO26 vs YOLO12 comparison on the same MacBook using the companion script. The focus is on the video benchmark because that is where you will see the real difference in a streaming workload.</p>



<h3 class="wp-block-heading">Video Benchmark on MPS (YOLO26 vs YOLO12)</h3>



<p><strong>Source:</strong> the first 300 frames of <code data-enlighter-language="python" class="EnlighterJSRAW">traffic.mp4</code> using <code data-enlighter-language="python" class="EnlighterJSRAW">--max-items 300</code> so the benchmark reflects a real streaming-style workload.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/10/image-47-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="289" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-47-1024x289.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-55787"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-47-1024x289.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-47-1024x289.png?size=126x36&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-47-1024x289.png?size=252x71&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-47-1024x289.png?size=378x107&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-47-1024x289.png?size=504x142&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-47-1024x289.png?size=630x178&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 9:</strong> YOLO26 vs. YOLO12 benchmark on the Apple Silicon MPS backend (source: image by the author).</figcaption></figure></div>


<p>This is where the YOLO26 model really shines. Across 300 frames of video, YOLO26n runs at <code>9.81 ms/frame</code> compared to <code>12.40 ms/frame</code> for YOLO12n. In throughput terms, that is roughly a <strong>30% advantage</strong> for YOLO26n, going from <code>80.62 FPS</code> to <code>101.90 FPS</code> on the same Apple Silicon hardware.</p>



<p>That is not a rounding error. That is the kind of gain you will actually feel in a real-time object detection pipeline, especially when you are processing continuous video streams.</p>



<p>As shown in <strong>Figure </strong><strong>10</strong> from <a href="https://docs.ultralytics.com/models/yolo26" target="_blank" rel="noreferrer noopener">Ultralytics</a>, YOLO26 achieves a superior accuracy–latency trade-off, delivering higher mean average precision (mAP) at comparable or lower inference latency than previous YOLO versions.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/10/image-10-scaled.jpeg" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="447" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-10-1024x447.jpeg?lossy=2&strip=1&webp=1" alt="" class="wp-image-55789"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-10-1024x447.jpeg?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-10-1024x447.jpeg?size=126x55&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-10-1024x447.jpeg?size=252x110&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-10-1024x447.jpeg?size=378x165&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-10-1024x447.jpeg?size=504x220&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-10-1024x447.jpeg?size=630x275&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 10:</strong> Official YOLO26 benchmark results comparing accuracy and latency across model sizes using TensorRT FP16 on an NVIDIA T4 GPU (source: <a href="https://docs.ultralytics.com/models/yolo26" target="_blank" rel="noreferrer noopener">Ultralytics YOLO26</a>).</figcaption></figure></div>


<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-YOLO26-vs-YOLO12-Visual-Detection-Quality-Comparison"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-YOLO26-vs-YOLO12-Visual-Detection-Quality-Comparison">YOLO26 vs YOLO12: Visual Detection Quality Comparison</a></h2>



<p>Benchmarks matter, but they do not tell the full story. A fast detector that misses obvious objects is not useful.</p>



<h3 class="wp-block-heading">What to Look For</h3>



<p>When you inspect predictions, look for the following.</p>



<h4 class="wp-block-heading">Missed Detections</h4>



<p>Does one model consistently ignore small or partially occluded objects?</p>



<h4 class="wp-block-heading">Duplicate Detections</h4>



<p>This is especially interesting in the context of end-to-end detection. If the pipeline is NMS-free by default, the model still needs to remain visually clean and stable.</p>



<h4 class="wp-block-heading">Box Tightness</h4>



<p>Are the boxes reasonably aligned to the target object, or do they feel loose and noisy?</p>



<h4 class="wp-block-heading">Confidence Behavior</h4>



<p>Are confidence scores calibrated sensibly, or does one model appear overconfident on poor detections?</p>



<p>These qualitative observations help readers connect the benchmark table to what they would actually see in a deployment pipeline.</p>



<figure class="wp-block-image aligncenter"><a href="https://pyimagesearch.com/wp-content/uploads/2026/10/image-11-scaled.jpeg" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="576" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-11-1024x576.jpeg?lossy=2&strip=1&webp=1" alt="" class="wp-image-55792"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-11-1024x576.jpeg?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-11-1024x576.jpeg?size=126x71&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-11-1024x576.jpeg?size=252x142&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-11-1024x576.jpeg?size=378x213&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-11-1024x576.jpeg?size=504x284&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-11-1024x576.jpeg?size=630x354&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><a href="https://pyimagesearch.com/wp-content/uploads/2026/10/image-12-scaled.jpeg" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="576" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-12-1024x576.jpeg?lossy=2&strip=1&webp=1" alt="" class="wp-image-55793"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-12-1024x576.jpeg?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-12-1024x576.jpeg?size=126x71&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-12-1024x576.jpeg?size=252x142&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-12-1024x576.jpeg?size=378x213&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-12-1024x576.jpeg?size=504x284&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-12-1024x576.jpeg?size=630x354&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption><strong>Figure 11:</strong> Prediction comparison between YOLO12 (top) and YOLO26 (bottom). Both models detect many of the same vehicles, but their class labels and confidence scores differ. The foreground red vehicle is labeled “bus” by YOLO12 and “truck” by YOLO26 (source: image by the author).</figcaption></figure>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-When-to-Use-the-YOLO26-Model"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-When-to-Use-the-YOLO26-Model">When to Use the YOLO26 Model</a></h2>



<p>By this point, the more important question is not whether YOLO26 is new. It is whether it fits your project.</p>



<h3 class="wp-block-heading">When YOLO26 Is a Strong Fit</h3>



<h4 class="wp-block-heading">Edge and On-Device Deployment</h4>



<p>If you want a detector designed with export and deployment in mind, YOLO26 is a compelling candidate.</p>



<h4 class="wp-block-heading">Simpler Inference Pipelines</h4>



<p>If reducing post-processing complexity helps your stack, the end-to-end default path is a real advantage.</p>



<h4 class="wp-block-heading">Fast Local Prototyping on macOS</h4>



<p>If your day-to-day development machine is a MacBook, YOLO26 gives you a practical way to prototype, test, and benchmark without immediately moving to a remote GPU workflow.</p>



<p><strong><br></strong></p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://pyimagesearch.com/wp-content/uploads/2026/10/image-48.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="624" height="340" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-48.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-55809"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-48.png?size=126x69&lossy=2&strip=1&webp=1 126w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-48-300x163.png?lossy=2&strip=1&webp=1 300w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-48.png?size=378x206&lossy=2&strip=1&webp=1 378w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-48.png?size=504x275&lossy=2&strip=1&webp=1 504w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-48.png?lossy=2&strip=1&webp=1 624w" sizes="(max-width: 624px) 100vw, 624px" /></a><figcaption class="wp-element-caption"><strong>Figure 12:</strong> Where YOLO26 fits best: edge devices, robotics, video analytics, and industrial inspection (source: image by the author).</figcaption></figure></div>


<h3 class="wp-block-heading">When to Benchmark Carefully Before Committing</h3>



<h4 class="wp-block-heading">Your Deployment Backend Is Highly Specialized</h4>



<p>If your production stack depends on a very specific runtime, export path, or hardware accelerator, always verify real performance on that target rather than assuming the default PyTorch experience will transfer directly.</p>



<h4 class="wp-block-heading">You Already Have a Tuned Baseline</h4>



<p>If an older YOLO variant is already integrated, optimized, and stable in your stack, YOLO26 should earn its place with measurable gains in speed, simplicity, or accuracy.</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 of on-demand code walkthrough videos • Last updated: November 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</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 moved beyond the standard &#8220;pip install and predict&#8221; workflow and explored YOLO26 as both a model and an engineering release.</p>



<p>You learned what changed in the Ultralytics YOLO26 architecture compared to its predecessors, why those changes matter for real-time object detection, and how to verify the differences on your own hardware.</p>



<p>You installed the Ultralytics YOLO26 model on macOS, ran inference on images, video, and a live webcam feed, and examined the prediction outputs to understand what the model actually returns.</p>



<p>You also looked at the architectural changes under the hood, including end-to-end NMS-free inference, DFL removal for cleaner exports, and the training-side improvements that contribute to faster CPU deployment.</p>



<p>The central focus of this lesson was reproducible benchmarking. You used a companion script, <code data-enlighter-language="python" class="EnlighterJSRAW">benchmark_yolo_macos.py</code>, to measure YOLO26n against YOLO12n on the same Apple Silicon hardware under identical conditions.</p>



<p>Over 300 frames of traffic video on MPS, YOLO26n reached <code>101.90 FPS</code> compared to <code>80.62 FPS</code> for YOLO12n, a nearly 30% throughput advantage. That gap is not a rounding error. It is the kind of gain you will actually feel in a streaming pipeline.</p>



<p>You walked through the benchmark script function by function, from argument parsing and source classification to timed prediction and formatted result output. That walkthrough gave you the tools to adapt the script for your own models, your own video sources, and your own hardware configurations.</p>



<p>By the end of this lesson, you did not just run YOLO26 on a few images. You built a clear, evidence-based understanding of where YOLO26 fits in the Ultralytics lineup, what it does better than YOLO12, and how to measure that improvement yourself.</p>



<p>This foundation prepares you for the next lesson, where you will use YOLO26 as the detection backbone in a full real-time video analytics pipeline with ByteTrack multi-object tracking, line-crossing analytics, and people counting.</p>



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



<p><strong>Singh, V</strong><strong>. </strong>“YOLO26 Object Detection Tutorial: Benchmarking on macOS,” <em>PyImageSearch</em>, S. Huot, A. Sharma, and P. Thakur, eds., 2026, <a href="https://pyimg.co/8p0ln" target="_blank" rel="noreferrer noopener">https://pyimg.co/8p0ln</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="YOLO26 Object Detection Tutorial: Benchmarking on macOS" data-enlighter-group="19">@incollection{Singh_2026_yolo26-object-detection-benchmarking-macos,
  author = {Vikram Singh},
  title = {{YOLO26 Object Detection Tutorial: Benchmarking on macOS}},
  booktitle = {PyImageSearch},
  editor = {Susan Huot and Aditya Sharma and Piyush Thakur},
  year = {2026},
  url = {https://pyimg.co/8p0ln},
}
</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/10/26/yolo26-object-detection-tutorial-benchmarking-on-macos/">YOLO26 Object Detection Tutorial: Benchmarking on macOS</a> appeared first on <a rel="nofollow" href="https://pyimagesearch.com">PyImageSearch</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Toward DeepSeek-R1: Building Thinking Models Using GRPO</title>
		<link>https://pyimagesearch.com/2026/10/19/toward-deepseek-r1-building-thinking-models-using-grpo/</link>
		
		<dc:creator><![CDATA[Puneet Mangla]]></dc:creator>
		<pubDate>Mon, 19 Oct 2026 12:45:00 +0000</pubDate>
				<category><![CDATA[GRPO]]></category>
		<category><![CDATA[LoRA]]></category>
		<category><![CDATA[Post Training]]></category>
		<category><![CDATA[Preference Optimization]]></category>
		<category><![CDATA[Qwen3]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[fine tuning]]></category>
		<category><![CDATA[grpo]]></category>
		<category><![CDATA[lora]]></category>
		<category><![CDATA[post training]]></category>
		<category><![CDATA[preference optimization]]></category>
		<category><![CDATA[qwen3]]></category>
		<category><![CDATA[tutorial]]></category>
		<guid isPermaLink="false">https://pyimagesearch.com/?p=55493</guid>

					<description><![CDATA[<p>Table of Contents Toward DeepSeek-R1: Building Thinking Models Using GRPO How Group Relative Policy Optimization (GRPO) Works Core GRPO Objective Group Relative Advantage Estimation Clipped Surrogate Objective KL Divergence Regularization Why GRPO Excels in Mathematical Reasoning Intrinsic Support for Verifiable&#8230;</p>
<p>The post <a rel="nofollow" href="https://pyimagesearch.com/2026/10/19/toward-deepseek-r1-building-thinking-models-using-grpo/">Toward DeepSeek-R1: Building Thinking Models Using GRPO</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-Toward-DeepSeek-R1-Building-Thinking-Models-Using-GRPO"><a rel="noopener" target="_blank" href="#h1-Toward-DeepSeek-R1-Building-Thinking-Models-Using-GRPO">Toward DeepSeek-R1: Building Thinking Models Using GRPO</a></li>
    <li id="TOC-h2-How-Group-Relative-Policy-Optimization-GRPO-Works"><a rel="noopener" target="_blank" href="#h2-How-Group-Relative-Policy-Optimization-GRPO-Works">How Group Relative Policy Optimization (GRPO) Works</a>
        <ul>
            <li id="TOC-h3-Core-GRPO-Objective"><a rel="noopener" target="_blank" href="#h3-Core-GRPO-Objective">Core GRPO Objective</a></li>
            <li id="TOC-h3-Group-Relative-Advantage-Estimation"><a rel="noopener" target="_blank" href="#h3-Group-Relative-Advantage-Estimation">Group Relative Advantage Estimation</a></li>
            <li id="TOC-h3-Clipped-Surrogate-Objective"><a rel="noopener" target="_blank" href="#h3-Clipped-Surrogate-Objective">Clipped Surrogate Objective</a></li>
            <li id="TOC-h3-KL-Divergence-Regularization"><a rel="noopener" target="_blank" href="#h3-KL-Divergence-Regularization">KL Divergence Regularization</a></li>
        </ul>
    </li>
    <li id="TOC-h2-Why-GRPO-Excels-in-Mathematical-Reasoning"><a rel="noopener" target="_blank" href="#h2-Why-GRPO-Excels-in-Mathematical-Reasoning">Why GRPO Excels in Mathematical Reasoning</a>
        <ul>
            <li id="TOC-h3-Intrinsic-Support-for-Verifiable-Rewards"><a rel="noopener" target="_blank" href="#h3-Intrinsic-Support-for-Verifiable-Rewards">Intrinsic Support for Verifiable Rewards</a></li>
            <li id="TOC-h3-Efficient-Learning-from-Diverse-Solution-Attempts"><a rel="noopener" target="_blank" href="#h3-Efficient-Learning-from-Diverse-Solution-Attempts">Efficient Learning from Diverse Solution Attempts</a></li>
        </ul>
    </li>
    <li id="TOC-h2-Post-Training-Qwen3-for-Math-Reasoning-with-GRPO"><a rel="noopener" target="_blank" href="#h2-Post-Training-Qwen3-for-Math-Reasoning-with-GRPO">Post-Training Qwen3 for Math Reasoning with GRPO</a>
        <ul>
            <li id="TOC-h3-Loading-and-Exploring-the-NuminaMath-Dataset"><a rel="noopener" target="_blank" href="#h3-Loading-and-Exploring-the-NuminaMath-Dataset">Loading and Exploring the NuminaMath Dataset</a></li>
            <li id="TOC-h3-Loading-Qwen3-and-Configuring-LoRA"><a rel="noopener" target="_blank" href="#h3-Loading-Qwen3-and-Configuring-LoRA">Loading Qwen3 and Configuring LoRA</a></li>
            <li id="TOC-h3-Implementing-Verifiable-Reward-Functions"><a rel="noopener" target="_blank" href="#h3-Implementing-Verifiable-Reward-Functions">Implementing Verifiable Reward Functions</a></li>
            <li id="TOC-h3-Training-Qwen3-with-GRPOTrainer"><a rel="noopener" target="_blank" href="#h3-Training-Qwen3-with-GRPOTrainer">Training Qwen3 with GRPOTrainer</a></li>
        </ul>
    </li>
    <li id="TOC-h2-Summary"><a rel="noopener" target="_blank" href="#h2-Summary">Summary</a>
        <ul>
            <li id="TOC-h3-Citation-Information"><a rel="noopener" target="_blank" href="#h3-Citation-Information">Citation Information</a></li>
        </ul>
    </li>
</ul>
</div>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h1-Toward-DeepSeek-R1-Building-Thinking-Models-Using-GRPO"/>



<h2 class="wp-block-heading"><a href="#TOC-h1-Toward-DeepSeek-R1-Building-Thinking-Models-Using-GRPO">Toward DeepSeek-R1: Building Thinking Models Using GRPO</a></h2>



<p>The journey from <strong>DeepSeek‑V3</strong> to <strong>DeepSeek‑R1</strong> marks a pivotal shift in how we think about language models: not just as pattern recognizers, but as <em>reasoning agents</em>. While V3 focused on architectural innovations (e.g., multi-head latent attention (MLA), mixture of experts (MoE), and multi‑token prediction (MTP)), R1 introduced a new dimension: the ability to <em>think through problems step by step</em>. At the heart of this breakthrough lies <strong>Group Relative Policy Optimization (GRPO)</strong>, a reinforcement learning technique designed to refine models beyond next‑token prediction, enabling them to tackle complex reasoning tasks with verifiable outcomes.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://pyimagesearch.com/wp-content/uploads/2026/10/toward-deepseek-r1-building-thinking-models-using-grpo-featured.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="940" height="780" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/toward-deepseek-r1-building-thinking-models-using-grpo-featured.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-55695"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/toward-deepseek-r1-building-thinking-models-using-grpo-featured.png?size=126x105&lossy=2&strip=1&webp=1 126w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/toward-deepseek-r1-building-thinking-models-using-grpo-featured-300x249.png?lossy=2&strip=1&webp=1 300w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/toward-deepseek-r1-building-thinking-models-using-grpo-featured.png?size=378x314&lossy=2&strip=1&webp=1 378w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/toward-deepseek-r1-building-thinking-models-using-grpo-featured.png?size=504x418&lossy=2&strip=1&webp=1 504w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/toward-deepseek-r1-building-thinking-models-using-grpo-featured.png?size=630x523&lossy=2&strip=1&webp=1 630w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/toward-deepseek-r1-building-thinking-models-using-grpo-featured-768x637.png?lossy=2&strip=1&webp=1 768w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/toward-deepseek-r1-building-thinking-models-using-grpo-featured.png?lossy=2&strip=1&webp=1 940w" sizes="(max-width: 940px) 100vw, 940px" /></a></figure></div>


<p>Unlike traditional fine‑tuning methods, GRPO leverages the idea of <em>relative advantage within groups of solutions</em>. Instead of rewarding a model for producing a single correct answer, GRPO evaluates multiple attempts, compares their relative quality, and uses this structured feedback to guide learning. This makes it particularly powerful for domains (e.g., <strong>mathematical reasoning</strong>), where correctness can be objectively verified and where diverse solution paths provide rich signals for improvement. In practice, GRPO can further train small language models (e.g., Qwen3) using verifiable rewards for answer correctness and output format.</p>



<p>In this bonus lesson, we will explore how GRPO works, why it excels in reasoning tasks, and how to apply it to post‑train smaller models. We will walk through the <strong>core GRPO objective</strong>, its <strong>clipped surrogate function</strong>, and <strong>Kullback-Leibler (</strong><strong>KL) divergence regularization</strong>, before diving into a hands-on demonstration of training Qwen3 with verifiable reward functions. By the end, you will see how GRPO bridges the gap between raw generative ability and structured reasoning, laying the foundation for building true <em>thinking models</em>.</p>



<p><strong>To learn how to </strong><strong>post-train </strong><strong>Qwen3</strong><strong> for </strong><strong>m</strong><strong>athematical </strong><strong>r</strong><strong>easoning using GRPO</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-How-Group-Relative-Policy-Optimization-GRPO-Works"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-How-Group-Relative-Policy-Optimization-GRPO-Works">How Group Relative Policy Optimization (GRPO) Works</a></h2>



<p>Group Relative Policy Optimization (GRPO) represents a fundamental departure from traditional policy optimization methods by eliminating the need for a separate value function while maintaining stable and efficient training dynamics (<strong>Figure 1</strong>). The mathematical foundation of GRPO is built on the principle of group-relative advantage estimation, which provides both computational efficiency and variance reduction.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://pyimagesearch.com/wp-content/uploads/2026/10/image-30.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="892" height="403" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-30.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-55699"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-30.png?size=126x57&lossy=2&strip=1&webp=1 126w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-30-300x136.png?lossy=2&strip=1&webp=1 300w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-30.png?size=378x171&lossy=2&strip=1&webp=1 378w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-30.png?size=504x228&lossy=2&strip=1&webp=1 504w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-30.png?size=630x285&lossy=2&strip=1&webp=1 630w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-30-768x347.png?lossy=2&strip=1&webp=1 768w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-30.png?lossy=2&strip=1&webp=1 892w" sizes="(max-width: 892px) 100vw, 892px" /></a><figcaption class="wp-element-caption"><strong>Figure 1:</strong> PPO vs GRPO in a nutshell (source: <a href="https://community.aws/content/2rJrpj6m2eh591fjMcRZ3ushpB7/deep-dive-into-group-relative-policy-optimization-grpo" target="_blank" rel="noreferrer noopener">Subramanian, 2025, Amazon Web Services (AWS</a>)).</figcaption></figure></div>


<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Core-GRPO-Objective"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Core-GRPO-Objective">Core GRPO Objective</a></h3>



<p>The GRPO objective function can be formally expressed as (<strong>Figure 2</strong>):</p>



<p class="has-text-align-center"><img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/137/13735b152ca5b588e87a45a465f58d58-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='J_\text{GRPO}(\theta) = \mathbb{E}_{q \sim \mu, \{o_i\}_{i=1}^G \sim \pi_{\theta_\text{old}}(\cdot|q)} \left[\displaystyle\frac{1}{G} \sum_{i=1}^G \left( \tilde{A}_i(\theta) - \beta D_i(\theta) \right) \right]' title='J_\text{GRPO}(\theta) = \mathbb{E}_{q \sim \mu, \{o_i\}_{i=1}^G \sim \pi_{\theta_\text{old}}(\cdot|q)} \left[\displaystyle\frac{1}{G} \sum_{i=1}^G \left( \tilde{A}_i(\theta) - \beta D_i(\theta) \right) \right]' class='latex' srcset='https://b2633864.assetcdn.net/2633864/wp-content/latex/137/13735b152ca5b588e87a45a465f58d58-ffffff-000000-0.png?lossy=2&strip=1&webp=1 410w,https://b2633864.assetcdn.net/2633864/wp-content/latex/137/13735b152ca5b588e87a45a465f58d58-ffffff-000000-0.png?size=126x16&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/latex/137/13735b152ca5b588e87a45a465f58d58-ffffff-000000-0.png?size=252x31&lossy=2&strip=1&webp=1 252w' sizes='(max-width: 410px) 100vw, 410px' /></p>



<p>where:</p>



<ul class="wp-block-list">
<li><img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/769/7694f4a66316e53c8cdd9d9954bd611d-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='q' title='q' class='latex' />: represents the input prompt or question</li>



<li><img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/a11/a11ddc84e7ab4ccf0333f0e351820dfa-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='\{o_i\}_{i=1}^G' title='\{o_i\}_{i=1}^G' class='latex' />: represents a group of <img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/dfc/dfcf28d0734569a6a693bc8194de62bf-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='G' title='G' class='latex' /> outputs/completions generated for the same prompt</li>



<li><img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/b03/b039fd8fed118bbdc57db2cb62886822-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='\tilde{A}_i(\theta)' title='\tilde{A}_i(\theta)' class='latex' />: is the clipped advantage function</li>



<li><img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/13e/13e490055a59bf24eb6f40b101960256-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='D_i(\theta)' title='D_i(\theta)' class='latex' />: is the KL divergence penalty term</li>



<li><img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/b06/b0603860fcffe94e5b8eec59ed813421-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='\beta' title='\beta' class='latex' />: is the regularization coefficient</li>
</ul>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/10/image-31-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="541" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-31-1024x541.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-55702"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-31-1024x541.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-31-1024x541.png?size=126x67&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-31-1024x541.png?size=252x133&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-31-1024x541.png?size=378x200&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-31-1024x541.png?size=504x266&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-31-1024x541.png?size=630x333&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 2:</strong> Core objective of GRPO in a nutshell (source: <a href="https://www.cnblogs.com/zhiyong-ITNote/p/18702470" target="_blank" rel="noreferrer noopener">CN Blogs</a>).</figcaption></figure></div>


<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Group-Relative-Advantage-Estimation"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Group-Relative-Advantage-Estimation">Group Relative Advantage Estimation</a></h3>



<p>The key innovation of GRPO lies in its advantage estimation mechanism. Instead of relying on a learned value function, as Proximal Policy Optimization (PPO) typically does, GRPO computes advantages relative to the group of sampled outputs (<strong>Figure 3</strong>):</p>



<p class="has-text-align-center"><img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/db0/db0eac0c962a4f00aceb5b7dda8b74e1-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='A_i = \displaystyle\frac{r_i - \text{mean}(r_1, \ldots, r_G)}{\text{std}(r_1, \ldots, r_G)}' title='A_i = \displaystyle\frac{r_i - \text{mean}(r_1, \ldots, r_G)}{\text{std}(r_1, \ldots, r_G)}' class='latex' srcset='https://b2633864.assetcdn.net/2633864/wp-content/latex/db0/db0eac0c962a4f00aceb5b7dda8b74e1-ffffff-000000-0.png?lossy=2&strip=1&webp=1 191w,https://b2633864.assetcdn.net/2633864/wp-content/latex/db0/db0eac0c962a4f00aceb5b7dda8b74e1-ffffff-000000-0.png?size=126x27&lossy=2&strip=1&webp=1 126w' sizes='(max-width: 191px) 100vw, 191px' /></p>



<p>where:</p>



<ul class="wp-block-list">
<li><img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/af2/af2593b49488f8bc44396795792c2d79-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='r_i' title='r_i' class='latex' />: is the reward for output <img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/865/865c0c0b4ab0e063e5caa3387c1a8741-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='i' title='i' class='latex' /></li>



<li><img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/2fd/2fd030fce8b1baa8f31590fb64360720-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='\text{mean}(r_1, \ldots, r_G) = \frac{1}{G} \sum_{j=1}^G r_j' title='\text{mean}(r_1, \ldots, r_G) = \frac{1}{G} \sum_{j=1}^G r_j' class='latex' srcset='https://b2633864.assetcdn.net/2633864/wp-content/latex/2fd/2fd030fce8b1baa8f31590fb64360720-ffffff-000000-0.png?lossy=2&strip=1&webp=1 209w,https://b2633864.assetcdn.net/2633864/wp-content/latex/2fd/2fd030fce8b1baa8f31590fb64360720-ffffff-000000-0.png?size=126x14&lossy=2&strip=1&webp=1 126w' sizes='(max-width: 209px) 100vw, 209px' />: is the group mean reward</li>



<li><img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/253/25330910647307f6ef1ccea7b273a853-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='\text{std}(r_1, \ldots, r_G) = \sqrt{\frac{1}{G} \sum_{j=1}^G (r_j - \text{mean}(r_1, \ldots, r_G))^2}' title='\text{std}(r_1, \ldots, r_G) = \sqrt{\frac{1}{G} \sum_{j=1}^G (r_j - \text{mean}(r_1, \ldots, r_G))^2}' class='latex' srcset='https://b2633864.assetcdn.net/2633864/wp-content/latex/253/25330910647307f6ef1ccea7b273a853-ffffff-000000-0.png?lossy=2&strip=1&webp=1 365w,https://b2633864.assetcdn.net/2633864/wp-content/latex/253/25330910647307f6ef1ccea7b273a853-ffffff-000000-0.png?size=126x11&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/latex/253/25330910647307f6ef1ccea7b273a853-ffffff-000000-0.png?size=252x21&lossy=2&strip=1&webp=1 252w' sizes='(max-width: 365px) 100vw, 365px' />: is the group standard deviation</li>
</ul>



<p>This normalization serves multiple purposes. It provides a natural baseline by comparing each output against its peers, reduces variance by localizing comparisons within each group, and eliminates the need for a separate value function approximator.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/10/image-32-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="613" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-32-1024x613.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-55703"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-32-1024x613.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-32-1024x613.png?size=126x75&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-32-1024x613.png?size=252x151&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-32-1024x613.png?size=378x226&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-32-1024x613.png?size=504x302&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-32-1024x613.png?size=630x377&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 3:</strong> Group Relative Advantage Estimation (source: <a href="https://pub.towardsai.net/group-relative-policy-optimization-grpo-illustrated-breakdown-explanation-684e71b8a3f2" target="_blank" rel="noreferrer noopener">Pichka, 2025, Towards AI</a>).</figcaption></figure></div>


<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Clipped-Surrogate-Objective"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Clipped-Surrogate-Objective">Clipped Surrogate Objective</a></h3>



<p>Following PPO&#8217;s approach, GRPO employs a clipped surrogate objective to maintain training stability:</p>



<p class="has-text-align-center"><img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/8f4/8f4e6c69ab60d88e38414397f73f9133-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='\tilde{A}_i(\theta) = \min\left(\displaystyle\frac{\pi_\theta(o_i | q)}{\pi_{\theta_\text{old}}(o_i | q)} A_i, \text{clip}_\epsilon\left(\displaystyle\frac{\pi_\theta(o_i | q)}{\pi_{\theta_\text{old}}(o_i | q)} \right) A_i \right)' title='\tilde{A}_i(\theta) = \min\left(\displaystyle\frac{\pi_\theta(o_i | q)}{\pi_{\theta_\text{old}}(o_i | q)} A_i, \text{clip}_\epsilon\left(\displaystyle\frac{\pi_\theta(o_i | q)}{\pi_{\theta_\text{old}}(o_i | q)} \right) A_i \right)' class='latex' srcset='https://b2633864.assetcdn.net/2633864/wp-content/latex/8f4/8f4e6c69ab60d88e38414397f73f9133-ffffff-000000-0.png?lossy=2&strip=1&webp=1 353w,https://b2633864.assetcdn.net/2633864/wp-content/latex/8f4/8f4e6c69ab60d88e38414397f73f9133-ffffff-000000-0.png?size=126x15&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/latex/8f4/8f4e6c69ab60d88e38414397f73f9133-ffffff-000000-0.png?size=252x30&lossy=2&strip=1&webp=1 252w' sizes='(max-width: 353px) 100vw, 353px' /></p>



<p>where <img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/2de/2de4a0943c4dfc3373629ae76e550597-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='\text{clip}_\epsilon(x)' title='\text{clip}_\epsilon(x)' class='latex' /> constrains <img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/9dd/9dd4e461268c8034f5c8564e155c67a6-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='x' title='x' class='latex' /> to the range <img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/1ac/1aca645c5563f324c1fbfa637145134b-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='[1-\epsilon, 1+\epsilon]' title='[1-\epsilon, 1+\epsilon]' class='latex' />, preventing excessively large policy updates that could destabilize training.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-KL-Divergence-Regularization"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-KL-Divergence-Regularization">KL Divergence Regularization</a></h3>



<p>The KL (Kullback-Leibler) divergence term <img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/13e/13e490055a59bf24eb6f40b101960256-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='D_i(\theta)' title='D_i(\theta)' class='latex' /> in the GRPO objective serves to keep the updated policy close to a reference policy <img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/34f/34f73f08b7d3037724704e0b5fdca030-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='\pi_\text{ref}' title='\pi_\text{ref}' class='latex' />, typically the initial supervised fine-tuned model:</p>



<p class="has-text-align-center"><img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/13e/13e3aa337114fc8b51950b829e5ca517-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='D_i(\theta) = \displaystyle\frac{\pi_\text{ref}(o_i | q)}{\pi_\theta(o_i | q)} - \log \displaystyle\frac{\pi_\text{ref}(o_i | q)}{\pi_\theta(o_i | q)} - 1' title='D_i(\theta) = \displaystyle\frac{\pi_\text{ref}(o_i | q)}{\pi_\theta(o_i | q)} - \log \displaystyle\frac{\pi_\text{ref}(o_i | q)}{\pi_\theta(o_i | q)} - 1' class='latex' srcset='https://b2633864.assetcdn.net/2633864/wp-content/latex/13e/13e3aa337114fc8b51950b829e5ca517-ffffff-000000-0.png?lossy=2&strip=1&webp=1 260w,https://b2633864.assetcdn.net/2633864/wp-content/latex/13e/13e3aa337114fc8b51950b829e5ca517-ffffff-000000-0.png?size=126x20&lossy=2&strip=1&webp=1 126w' sizes='(max-width: 260px) 100vw, 260px' /></p>



<p>This regularization term is particularly important in language model training to prevent catastrophic forgetting of the model&#8217;s pre-trained capabilities.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Why-GRPO-Excels-in-Mathematical-Reasoning"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Why-GRPO-Excels-in-Mathematical-Reasoning">Why GRPO Excels in Mathematical Reasoning</a></h2>



<p>Group Relative Policy Optimization (GRPO) has rapidly established itself as a leading fine-tuning approach for mathematical reasoning in large language models (LLMs), owing to several structural features that make it especially well-suited to this domain.</p>



<p>Recent large-scale studies (e.g.,  those involving the DeepSeekMath and DeepSeek-R1 models) demonstrate that swapping PPO for GRPO in reinforcement learning from human feedback (RLHF) pipelines yields significant improvements on mathematical reasoning benchmarks (e.g., GSM8K, MATH datasets).</p>



<p>For example, DeepSeekMath training with GRPO outperformed PPO-based methods on math reasoning accuracy while reducing compute costs (<strong>Figure 4</strong>).</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://pyimagesearch.com/wp-content/uploads/2026/10/image-33.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="756" height="437" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-33.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-55705"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-33.png?size=126x73&lossy=2&strip=1&webp=1 126w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-33-300x173.png?lossy=2&strip=1&webp=1 300w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-33.png?size=378x219&lossy=2&strip=1&webp=1 378w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-33.png?size=504x291&lossy=2&strip=1&webp=1 504w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-33.png?size=630x364&lossy=2&strip=1&webp=1 630w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-33.png?lossy=2&strip=1&webp=1 756w" sizes="(max-width: 756px) 100vw, 756px" /></a><figcaption class="wp-element-caption"><strong>Figure 4:</strong> Performance of DeepSeekMath with GRPO (source: <a href="https://arxiv.org/pdf/2402.03300" target="_blank" rel="noreferrer noopener">Shao et al., 2024, DeepSeek</a>).</figcaption></figure></div>


<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Intrinsic-Support-for-Verifiable-Rewards"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Intrinsic-Support-for-Verifiable-Rewards">Intrinsic Support for Verifiable Rewards</a></h3>



<p>Mathematics problem-solving offers an unusually clear and <strong>verifiable</strong> reward mechanism: answers are either correct or incorrect, and partial credit can be precisely defined. GRPO capitalizes on this by scoring multiple solutions generated for each problem using a well-defined reward model, often simply marking correct steps or final answers. This direct and reliable reward assignment enhances the <strong>signal-to-noise</strong> ratio of model updates, as each policy improvement step is based on unambiguous performance feedback.</p>



<p>In contrast, open-ended tasks (e.g., creative writing or dialogue) often rely on subjective or noisy reward models, making stable policy optimization far more difficult. GRPO&#8217;s per-group advantage estimation is highly compatible with settings where reward computation is <strong>transparent</strong> and <strong>objective</strong>, as in math (<strong>Figure 5</strong>).</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/10/image-34-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="490" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-34-1024x490.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-55708"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-34-1024x490.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-34-1024x490.png?size=126x60&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-34-1024x490.png?size=252x121&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-34-1024x490.png?size=378x181&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-34-1024x490.png?size=504x241&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-34-1024x490.png?size=630x301&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 5:</strong> Verifiable Rewards with GRPO (source: <a href="https://www.cnblogs.com/zhiyong-ITNote/p/18702470" target="_blank" rel="noreferrer noopener">CN Blogs</a>).</figcaption></figure></div>


<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Efficient-Learning-from-Diverse-Solution-Attempts"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Efficient-Learning-from-Diverse-Solution-Attempts">Efficient Learning from Diverse Solution Attempts</a></h3>



<p>Mathematical reasoning often requires the model to try multiple solution paths before arriving at a correct answer or elegant derivation. GRPO&#8217;s core mechanism (i.e., group sampling) directly supports this, as multiple outputs (&#8220;grouped rollouts&#8221;) are generated for each problem instance.</p>



<p>By comparing each solution&#8217;s reward to the group mean, GRPO enables the model to reinforce approaches that outperform common errors or naive guesses in the group. This fosters systematic exploration of problem-solving strategies and mitigates overfitting to spurious patterns that might arise from individual samples.</p>



<p>In practical terms, this approach enables rapid discrimination between valuable reasoning sequences and ineffective or &#8220;shortcut&#8221; answers commonly found in early-stage LLM outputs.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Post-Training-Qwen3-for-Math-Reasoning-with-GRPO"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Post-Training-Qwen3-for-Math-Reasoning-with-GRPO">Post-Training Qwen3 for Math Reasoning with GRPO</a></h2>



<p>In this section, we will see how to post-train small language models (e.g., Qwen3) using GRPO to improve their mathematical reasoning capabilities. </p>



<p>For this implementation, we will use the <a href="https://huggingface.co/datasets/AI-MO/NuminaMath-TIR" target="_blank" rel="noreferrer noopener">AI-MO/NuminaMath-TIR</a> dataset, which contains approximately 70,000 problems from the NuminaMath-CoT dataset, focusing on those with numerical outputs, most of which are integers. </p>



<p>The original NuminaMath-CoT dataset (containing 860,000 pairs of competition math problems and solutions) is designed to enhance the mathematical reasoning capabilities of large language models (LLMs). The NuminaMath dataset includes problems ranging from high school level to advanced competition level, all meticulously annotated with accompanying chain-of-thought traces (<strong>Table 1</strong>).</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://pyimagesearch.com/wp-content/uploads/2026/10/image-35.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="944" height="197" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-35.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-55710"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-35.png?size=126x26&lossy=2&strip=1&webp=1 126w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-35-300x63.png?lossy=2&strip=1&webp=1 300w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-35.png?size=378x79&lossy=2&strip=1&webp=1 378w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-35.png?size=504x105&lossy=2&strip=1&webp=1 504w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-35.png?size=630x131&lossy=2&strip=1&webp=1 630w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-35-768x160.png?lossy=2&strip=1&webp=1 768w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-35.png?lossy=2&strip=1&webp=1 944w" sizes="(max-width: 944px) 100vw, 944px" /></a><figcaption class="wp-element-caption"><strong>Table 1:</strong> Number of data samples in the Numina dataset (source: <a href="https://huggingface.co/datasets/AI-MO/NuminaMath-CoT" target="_blank" rel="noreferrer noopener">NuminaMath</a>).</figcaption></figure></div>


<p>We will start by installing the necessary libraries.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Toward DeepSeek-R1: Building Thinking Models Using GRPO" data-enlighter-group="1">pip install trl==0.14.0 peft math_verify
pip install -U datasets
pip install "transformers==4.51.3"
pip install -U "torchao>=0.16.0"
</pre>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Loading-and-Exploring-the-NuminaMath-Dataset"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Loading-and-Exploring-the-NuminaMath-Dataset">Loading and Exploring the NuminaMath Dataset</a></h3>



<p>After setting up the environment, we will begin by loading our dataset and visualizing a few examples.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="Toward DeepSeek-R1: Building Thinking Models Using GRPO" data-enlighter-group="2">from datasets import load_dataset

dataset_id = "AI-MO/NuminaMath-TIR"
train_set, test_set = load_dataset(dataset_id, split=['train[:1%]', 'test[:10%]'])

print("Train set: ", len(train_set))
print("Test set: ", len(test_set))
from IPython.display import Markdown, display

display(Markdown(r"**Problem Statement**: " + train_set[0]["problem"]))
display(Markdown(train_set[1]["solution"]))
</pre>



<p><strong>Output:</strong></p>



<p>On <strong>Line 1</strong>, we import the <code data-enlighter-language="python" class="EnlighterJSRAW">load_dataset</code> function from the <code data-enlighter-language="python" class="EnlighterJSRAW">datasets</code> library, which enables access to a specific dataset by its ID. On <strong>Line 3</strong>, we define the dataset identifier. Then on <strong>Line 4</strong>, we use <code data-enlighter-language="python" class="EnlighterJSRAW">load_dataset</code> to fetch small subsets of the train (1%) and test (10%) splits from the NuminaMath-TIR collection. </p>



<p>On <strong>Lines 6 and 7</strong>, we print the sizes of each subset for confirmation. Finally, on <strong>Lines 8-11</strong>, we use IPython&#8217;s <code data-enlighter-language="python" class="EnlighterJSRAW">Markdown</code> display to render the problem statement from the 1st training sample and the solution from the 2nd training sample directly in the notebook (<strong>Figure 6</strong>).</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/10/image-36-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="768" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-36-1024x768.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-55712"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-36-1024x768.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-36-1024x768.png?size=126x95&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-36-1024x768.png?size=252x189&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-36-1024x768.png?size=378x284&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-36-1024x768.png?size=504x378&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-36-1024x768.png?size=630x473&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 6:</strong> AI-MO/NuminaMath-TIR sample (source: <a href="https://huggingface.co/datasets/AI-MO/NuminaMath-TIR" target="_blank" rel="noreferrer noopener">NuminaMath</a>).</figcaption></figure></div>


<p>Next, we convert our train and test data problem statements into conversational-style prompts.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="12" data-enlighter-title="Toward DeepSeek-R1: Building Thinking Models Using GRPO" data-enlighter-group="3">SYSTEM_PROMPT = """
## Instruction:
Given a Problem statement.
1. Provide reasoning and final answer in following JSON format:
```json
{
  "THINKING": "This is my thinking",
  "ANSWER": "\( \\boxed{312} \)"
}
```
"""

def make_conversation(example):
    problem = "## Problem:\n" + example["problem"] + "\n## Solution:\n"
   
    return {
        "prompt": [
            {"role": "system", "content": SYSTEM_PROMPT},
            {"role": "user", "content": problem},
        ],
    }

train_dataset = train_set.map(make_conversation)
test_dataset = test_set.map(make_conversation)</pre>



<p>On <strong>Lines 24-32</strong>, we define a helper function <code data-enlighter-language="python" class="EnlighterJSRAW">make_conversation</code> that transforms each dataset example into a structured dictionary with a single <code data-enlighter-language="python" class="EnlighterJSRAW">"prompt"</code> entry. This includes the math problem as user input, formatted for chat-style training. </p>



<p>On <strong>Lines 34 and 35</strong>, we apply this mapping function to the train and test datasets, thereby converting the raw problem data into conversational form. </p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Loading-Qwen3-and-Configuring-LoRA"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Loading-Qwen3-and-Configuring-LoRA">Loading Qwen3 and Configuring LoRA</a></h3>



<p>Now, we start loading our model and defining our low-rank adaptation (LoRA) config for parameter-efficient fine-tuning (PEFT) (rather than fully finetuning all model parameters, which is costly) of Qwen3.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="36" data-enlighter-title="Toward DeepSeek-R1: Building Thinking Models Using GRPO" data-enlighter-group="4">import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

model_id = "Qwen/Qwen3-0.6B"

# Load model and tokenizer
model = AutoModelForCausalLM.from_pretrained(
    model_id,
    device_map="auto",
    torch_dtype=torch.bfloat16
)

processor = AutoTokenizer.from_pretrained(model_id, padding_side="left")

# Qwen3 is a hybrid thinking model. Its chat template only injects the empty
# &lt;think>&lt;/think> block when enable_thinking=False is passed explicitly, and
# GRPOTrainer calls apply_chat_template() internally without that argument,
# so we make non-thinking the default in the template itself.
if "enable_thinking is defined and enable_thinking is false" in (processor.chat_template or ""):
    processor.chat_template = processor.chat_template.replace(
        "{%- if enable_thinking is defined and enable_thinking is false %}",
        "{%- if enable_thinking is not defined or enable_thinking is false %}",
    )

from peft import LoraConfig, get_peft_model

# Configure LoRA
peft_config = LoraConfig(
    r=8,
    lora_alpha=8,
    lora_dropout=0.1,
    target_modules=["q_proj", "v_proj"],
)

# Apply PEFT model adaptation
peft_model = get_peft_model(model, peft_config)

# Print trainable parameters
peft_model.print_trainable_parameters()
</pre>



<p><strong>Output:</strong></p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="5" data-enlighter-title="Toward DeepSeek-R1: Building Thinking Models Using GRPO" data-enlighter-group="5">trainable params: 1,146,880 || all params: 597,196,800 || trainable%: 0.1920
</pre>



<p>On <strong>Lines 36 and 37</strong>, we import the necessary PyTorch and Hugging Face classes to load a causal language model and its associated tokenizer. On <strong>Line 39</strong>, we specify the model ID for Qwen3-0.6B. Then, on <strong>Lines 42-46</strong>, we load the model using <code data-enlighter-language="python" class="EnlighterJSRAW">AutoModelForCausalLM.from_pretrained()</code> with auto device placement and <code data-enlighter-language="python" class="EnlighterJSRAW">bfloat16</code> precision for memory efficiency. On <strong>Line 48</strong>, we load the corresponding tokenizer, setting <code data-enlighter-language="python" class="EnlighterJSRAW">padding_side="left"</code> because GRPO generates completions in batches. Immediately afterwards, on <strong>Lines </strong><strong>5</strong><strong>4</strong><strong>-58</strong>, we patch the chat template so that non-thinking mode is the default. Qwen3 is a hybrid thinking model: its template only injects the empty <code data-enlighter-language="python" class="EnlighterJSRAW">&lt;think&gt;&lt;/think&gt;</code> block when <code data-enlighter-language="python" class="EnlighterJSRAW">enable_thinking=False</code> is passed explicitly, and <code data-enlighter-language="python" class="EnlighterJSRAW">GRPOTrainer</code> calls <code data-enlighter-language="python" class="EnlighterJSRAW">apply_chat_template()</code> internally without that argument. Without this patch every rollout would emit a long free-form reasoning trace, be truncated at <code data-enlighter-language="python" class="EnlighterJSRAW">max_completion_length</code>, and score zero on both reward functions.</p>



<p>On <strong>Line 60</strong>, we bring in the PEFT utilities for LoRA-based fine-tuning. On <strong>Lines 63-68</strong>, we set up <code data-enlighter-language="python" class="EnlighterJSRAW">LoraConfig</code>, tweaking parameters like rank <code data-enlighter-language="python" class="EnlighterJSRAW">r</code>, scaling factor <code data-enlighter-language="python" class="EnlighterJSRAW">lora_alpha</code>, dropout rate, and targeting attention projection layers. On <strong>Line 71</strong>, we adapt the original model using this LoRA configuration to inject low-rank updates into the model weights. Finally, on <strong>Line 74</strong>, we print the trainable parameter count, giving us insight into how many parameters will be updated during training.</p>



<p>Below, we implement an inference function to generate the solution given a prompt using the above model.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="75" data-enlighter-title="Toward DeepSeek-R1: Building Thinking Models Using GRPO" data-enlighter-group="6">import time

def generate_solution(model, prompt):
  text = processor.apply_chat_template(
    prompt,
    tokenize=False,
    add_generation_prompt=True,
    enable_thinking=False
  )
  inputs = processor([text], return_tensors="pt").to(model.device)

  # Generate text without gradients
  start_time = time.time()
  with torch.no_grad():
      output_ids = model.generate(**inputs, max_new_tokens=512, temperature=0.01, top_p=1.0)
  end_time = time.time()

  # Decode and extract model response
  generated_text = processor.decode(output_ids[0], skip_special_tokens=True)

  # Get inference time
  inference_duration = end_time - start_time

  # Get number of generated tokens
  num_input_tokens = inputs['input_ids'].shape[1]
  num_generated_tokens = output_ids.shape[1] - num_input_tokens

  return generated_text, inference_duration, num_generated_tokens
</pre>



<p>On <strong>Line 75</strong>, we import the <code data-enlighter-language="python" class="EnlighterJSRAW">time</code> module to help track inference duration. Then on <strong>Line 77</strong>, we define <code data-enlighter-language="python" class="EnlighterJSRAW">generate_solution</code>, a function that takes in a model and a structured prompt, joining the chat entries into a single text string. On <strong>Line</strong> <strong>84</strong>, we tokenize this prompt using <code data-enlighter-language="python" class="EnlighterJSRAW">processor</code> and move the inputs to the same device as the model for seamless execution.</p>



<p>On <strong>Lines 87-90</strong>, we measure the time taken to generate a response. We use <code data-enlighter-language="python" class="EnlighterJSRAW">torch.no_grad()</code> to avoid computing gradients during inference. On <strong>Line 93</strong>, we decode the generated tokens into readable text, skipping any special tokens. </p>



<p>Finally, on <strong>Line</strong> <strong>102</strong>, we return the generated output, its inference time, and token count for easy evaluation of model performance.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Implementing-Verifiable-Reward-Functions"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Implementing-Verifiable-Reward-Functions">Implementing Verifiable Reward Functions</a></h3>



<p>Since we are training our model for mathematical reasoning, we can use verifiable rewards for GRPO. To verify whether or not a generated solution is correct with respect to the original solution, we will use the Hugging Face <a href="https://github.com/huggingface/Math-Verify" target="_blank" rel="noreferrer noopener">Math-Verify</a> library.</p>



<p>Math-Verify is a robust mathematical expression evaluation system designed for assessing Large Language Model outputs in mathematical tasks. This evaluator achieves the highest accuracy and the most correct scores compared to existing evaluators on the MATH dataset.</p>



<p>For training, the DeepSeek-R1 authors used an accuracy-based reward model evaluates whether the response is correct, alongside a format-based reward that ensures the model places its reasoning process between <code data-enlighter-language="python" class="EnlighterJSRAW">&lt;think&gt;&lt;/think&gt;</code> tags. We can simply define and implement these reward functions as generic Python functions.</p>



<p>First, we implement a format enforcement reward function that ensures that the generation follows a specific JavaScript Object Notation (JSON) format with <code data-enlighter-language="python" class="EnlighterJSRAW">"THINKING"</code> and <code data-enlighter-language="python" class="EnlighterJSRAW">"ANSWER"</code> keys for reasoning and answer.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="103" data-enlighter-title="Toward DeepSeek-R1: Building Thinking Models Using GRPO" data-enlighter-group="7">import json
def format_reward(completions, **kwargs):
    """Reward function that checks if the completion has a specific format."""

    completion_contents = [completion[0]["content"] for completion in completions]
    rewards_list = []
    for completion in completion_contents:
      try:
        completion_str = completion.split("```json")[1].split('```')[0]
        completion_json = json.loads(completion_str)
        if "THINKING" in completion_json and "ANSWER" in completion_json:
          rewards_list.append(1.0)
        else:
          rewards_list.append(0.0)
      except:
        rewards_list.append(0.0)
    return rewards_list</pre>



<p>On <strong>Line 104</strong>, we define the<code data-enlighter-language="python" class="EnlighterJSRAW">format_reward</code> function, which takes in a list of <code data-enlighter-language="python" class="EnlighterJSRAW">completions</code> and optional keyword arguments. On <strong>Line 107</strong>, we extract the <code data-enlighter-language="python" class="EnlighterJSRAW">"content"</code> field from each completion and store them in <code data-enlighter-language="python" class="EnlighterJSRAW">completion_contents</code>. We then initialize an empty list <code data-enlighter-language="python" class="EnlighterJSRAW">rewards_list</code> to hold the reward scores. Moving to <strong>Lines</strong> <strong>109-112</strong>, we loop through each completion string. Inside the <code data-enlighter-language="python" class="EnlighterJSRAW">try</code> block, we attempt to split the text to isolate the JSON portion between <code data-enlighter-language="python" class="EnlighterJSRAW">```json</code> and <code data-enlighter-language="python" class="EnlighterJSRAW">```</code>. If successful, we parse it with <code data-enlighter-language="python" class="EnlighterJSRAW">json.loads</code>. The check on <strong>Line</strong> <strong>113</strong> ensures that both <code data-enlighter-language="python" class="EnlighterJSRAW">"THINKING"</code> and <code data-enlighter-language="python" class="EnlighterJSRAW">"ANSWER"</code> keys exist in the parsed JSON. If they do, we append a reward of <code data-enlighter-language="python" class="EnlighterJSRAW">1.0</code>; otherwise, we append <code data-enlighter-language="python" class="EnlighterJSRAW">0.0</code>.</p>



<p>In essence, we are rewarding completions that follow the expected structured format with both <code data-enlighter-language="python" class="EnlighterJSRAW">"THINKING"</code> and <code data-enlighter-language="python" class="EnlighterJSRAW">"ANSWER"</code> fields, while penalizing those that fail to meet this requirement. This way, we enforce structured reasoning outputs in our model training.</p>



<p>Next, the code below implements the accuracy reward function, which assigns a higher reward if the generated answer is correct.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="120" data-enlighter-title="Toward DeepSeek-R1: Building Thinking Models Using GRPO" data-enlighter-group="9">from math_verify import LatexExtractionConfig, parse, verify
def accuracy_reward(completions, **kwargs):
    """Reward function that checks if the completion is the same as the ground truth."""
    solutions = kwargs['solution']
    rewards = []
    for completion, solution in zip(completions, solutions):
        try:
          content = json.loads(completion[0]["content"].split("```json")[1].split('```')[0])
          gold_parsed = parse(solution, extraction_mode="first_match", extraction_config=[LatexExtractionConfig()])
          answer_parsed = parse(content["ANSWER"], extraction_mode="first_match")
 
          if len(gold_parsed) != 0:
            rewards.append(float(verify(answer_parsed, gold_parsed)))
          else:
              rewards.append(1.0)
        except:
          rewards.append(0.0)
    return rewards</pre>



<p>On <strong>Line </strong><strong>120</strong>, we import 3 components from the <code data-enlighter-language="python" class="EnlighterJSRAW">math_verify</code> module: <code data-enlighter-language="python" class="EnlighterJSRAW">LatexExtractionConfig</code>, <code data-enlighter-language="python" class="EnlighterJSRAW">parse</code>, and <code data-enlighter-language="python" class="EnlighterJSRAW">verify</code>. These are used to extract and compare mathematical expressions from model completions and ground truth solutions. On <strong>Lines </strong><strong>121 and 122</strong>, we define the <code data-enlighter-language="python" class="EnlighterJSRAW">accuracy_reward</code> function, which evaluates how closely each model-generated completion matches the correct answer.</p>



<p>On <strong>Lines </strong><strong>123 and 124</strong>, we retrieve the list of ground truth <code data-enlighter-language="python" class="EnlighterJSRAW">solutions</code> from the keyword arguments and initialize an empty <code data-enlighter-language="python" class="EnlighterJSRAW">rewards</code> list. Then, for each pair of <code data-enlighter-language="python" class="EnlighterJSRAW">completion</code> and <code data-enlighter-language="python" class="EnlighterJSRAW">solution</code>, we enter a <code data-enlighter-language="python" class="EnlighterJSRAW">try</code> block (<strong>Line </strong><strong>126</strong>) to safely parse and compare the outputs. On <strong>Line </strong><strong>127</strong>, we extract the JSON portion of the completion and load it. On <strong>Lines </strong><strong>128 and 129</strong>, we parse both the ground truth solution and the model&#8217;s predicted <code data-enlighter-language="python" class="EnlighterJSRAW">"ANSWER"</code> using the <code data-enlighter-language="python" class="EnlighterJSRAW">parse</code> function, configured to extract the first matching LaTeX expression.</p>



<p>On <strong>Lines 131 and 132</strong>, we check if the parsed ground truth (<code data-enlighter-language="python" class="EnlighterJSRAW">gold_parsed</code>) is non-empty. If it is, we use the <code data-enlighter-language="python" class="EnlighterJSRAW">verify</code> function to compare it with the parsed answer and append the resulting float score to <code data-enlighter-language="python" class="EnlighterJSRAW">rewards</code>. If the ground truth is empty, we assign a default reward of <code data-enlighter-language="python" class="EnlighterJSRAW">1.0</code>. On <strong>Lines 135 and 136</strong>, any parsing or verification errors result in a fallback reward of <code data-enlighter-language="python" class="EnlighterJSRAW">0.0</code>. Finally, on <strong>Line 137</strong>, we return the list of reward scores. This function helps us quantify how accurate each model completion is in solving math problems, using structured verification rather than simple string matching.</p>



<p>The above code provides a basic implementation of a verifiable reward function that can be used in GRPO. Now we will test our model (without any GRPO training yet) using the accuracy reward function on a test data example to see how it performs.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="138" data-enlighter-title="Toward DeepSeek-R1: Building Thinking Models Using GRPO" data-enlighter-group="10">example = test_dataset[0]

## Testing Generation
generated_text, inference_duration, num_generated_tokens = generate_solution(model, example['prompt'])
print(generated_text)
print(f"Inference Duration: {inference_duration} seconds")
print(f"Number of Generated Tokens: {num_generated_tokens}")

## Testing Reward Function
solutions = [example['solution']]
completions = [[{"content": generated_text.split('assistant')[1]}]]
print(f"Accuracy Reward: {accuracy_reward(completions, solution=solutions)}")
print(f"Format Reward: {format_reward(completions, solution=solutions)}")
</pre>



<p><strong>Output:</strong></p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/10/image-37-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="429" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-37-1024x429.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-55722"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-37-1024x429.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-37-1024x429.png?size=126x53&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-37-1024x429.png?size=252x106&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-37-1024x429.png?size=378x158&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-37-1024x429.png?size=504x211&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-37-1024x429.png?size=630x264&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 7:</strong> Generation output of Qwen3 without GRPO post-training (source: image by the author).</figcaption></figure></div>


<p>As can be seen, the Qwen3 model, without any GRPO training, yet fails to answer the questions correctly and rather produces a coherent derivation that still reaches the wrong answer and ignores the required JSON output format (<strong>Figure 7</strong>). In the next section, we will see if GRPO training can improve the model’s reasoning capabilities on the same example.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h3-Training-Qwen3-with-GRPOTrainer"/>



<h3 class="wp-block-heading"><a href="#TOC-h3-Training-Qwen3-with-GRPOTrainer">Training Qwen3 with GRPOTrainer</a></h3>



<p>We have everything in place for our GRPO training:  the model, dataset, and reward function. It is time to configure and start our GRPO training. We will utilize the Hugging Face Transformer Reinforcement Learning (TRL) <a href="https://huggingface.co/docs/trl/main/en/grpo_trainer" target="_blank" rel="noreferrer noopener">GRPOTrainer</a> and <code data-enlighter-language="python" class="EnlighterJSRAW">GRPOConfig</code> for quick and clean implementation.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="151" data-enlighter-title="Toward DeepSeek-R1: Building Thinking Models Using GRPO" data-enlighter-group="11">from trl import GRPOConfig, GRPOTrainer

# Configure training arguments using GRPOConfig
training_args = GRPOConfig(
    output_dir="Qwen3-0.6B-Thinking",
    learning_rate=1e-5,
    remove_unused_columns=False, # to access the solution column in accuracy_reward
    gradient_accumulation_steps=16,
    num_train_epochs=1,
    bf16=True,

    # Parameters that control the data preprocessing
    max_completion_length = 128,
    num_generations=4,
    max_prompt_length=512,

    # Parameters related to reporting and saving
    logging_steps=10,
    report_to="none",  # Colab ships wandb; the default prompts for an API key
    save_strategy="steps",
    save_steps=10,
)

trainer = GRPOTrainer(
    model=model,
    reward_funcs=[format_reward, accuracy_reward],
    args=training_args,
    processing_class=processor,  # reuse the non-thinking chat template
    train_dataset=train_dataset.remove_columns(['messages', 'problem'])
)

trainer.train()
trainer.save_model(training_args.output_dir)
</pre>



<p>On <strong>Line </strong><strong>151</strong>, we import <code data-enlighter-language="python" class="EnlighterJSRAW">GRPOConfig</code> and <code data-enlighter-language="python" class="EnlighterJSRAW">GRPOTrainer</code> from the <code data-enlighter-language="python" class="EnlighterJSRAW">trl</code> library to set up and run GRPO-style reinforcement learning. Then, on <strong>Lines </strong><strong>154-172</strong>, we configure the training parameters via <code data-enlighter-language="python" class="EnlighterJSRAW">GRPOConfig</code>, setting the output directory, learning rate, LoRA compatibility (<code data-enlighter-language="python" class="EnlighterJSRAW">remove_unused_columns=False</code>), batch accumulation, epochs, and precision type (<code data-enlighter-language="python" class="EnlighterJSRAW">bf16</code>). </p>



<p>We also define generation controls (e.g., maximum prompt/completion lengths, and the number of completions per sample). Logging and checkpointing settings ensure progress is tracked and saved every few steps.</p>



<p>On <strong>Lines </strong><strong>174-180</strong>, we instantiate <code data-enlighter-language="python" class="EnlighterJSRAW">GRPOTrainer</code> using the LoRA-adapted model, our <code data-enlighter-language="python" class="EnlighterJSRAW">accuracy_reward</code> function, the training arguments, and a filtered dataset (excluding non-essential columns). Finally, on <strong>Lines </strong><strong>182 and 183</strong>, we launch the training and save the fine-tuned model to the configured directory.</p>



<p>Once training is complete, let us try out our trained model on the same test data example and see how it performs.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="184" data-enlighter-title="Toward DeepSeek-R1: Building Thinking Models Using GRPO" data-enlighter-group="12">example = test_dataset[5]

## Testing Generation
generated_text, inference_duration, num_generated_tokens = generate_solution(model, example['prompt'])
display(Markdown(generated_text))
print(f"Inference Duration: {inference_duration} seconds")
print(f"Number of Generated Tokens: {num_generated_tokens}")

## Testing Reward Function
solutions = [example['solution']]
completions = [[{"content": generated_text}]]
print(f"Accuracy Reward: {accuracy_reward(completions, solution=solutions)}")
</pre>



<p><strong>Output:</strong></p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/10/image-38-scaled.png" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="398" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-38-1024x398.png?lossy=2&strip=1&webp=1" alt="" class="wp-image-55726"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-38-1024x398.png?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-38-1024x398.png?size=126x49&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-38-1024x398.png?size=252x98&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-38-1024x398.png?size=378x147&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-38-1024x398.png?size=504x196&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-38-1024x398.png?size=630x245&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 8:</strong> Generation output of Qwen3 with GRPO post-training (source: image by the author).</figcaption></figure></div>


<p>As we see, after GRPO training and with <code data-enlighter-language="python" class="EnlighterJSRAW">&lt;1000</code> examples, the model already demonstrates the ability to generate the correct <code data-enlighter-language="python" class="EnlighterJSRAW">"THINKING"</code> and <code data-enlighter-language="python" class="EnlighterJSRAW">"ANSWER"</code> tags (<strong>Figure 8</strong>), even though the solution itself is incorrect. Given the inference time and the number of generated tokens, this approach shows potential benefits.</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 of on-demand code walkthrough videos • Last updated: November 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</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 <strong>Group Relative Policy Optimization (GRPO)</strong> serves as the foundation for building thinking models in DeepSeek‑R1. We began by breaking down the <strong>core GRPO objective</strong>, examining how group relative advantage estimation, the clipped surrogate objective, and KL divergence regularization come together to create a stable yet flexible training framework. By understanding these components, we set the stage for appreciating why GRPO is uniquely suited to reasoning tasks compared to traditional reinforcement learning approaches.</p>



<p>We then highlighted why GRPO excels in <strong>mathematical reasoning</strong>. Unlike conventional methods that reward single correct answers, GRPO thrives on diverse solution attempts and leverages verifiable rewards to guide learning. This intrinsic support for correctness and efficiency allows models to learn from multiple reasoning paths, reinforcing both accuracy and adaptability. Through this lens, we saw how GRPO transforms small language models into structured problem solvers capable of step‑by‑step reasoning.</p>



<p>Finally, we moved into practice by applying GRPO to post‑train Qwen3. We walked through loading and visualizing the dataset, preparing the Qwen3 model, and implementing verifiable reward functions tailored to mathematical tasks. With these foundations, we demonstrated how GRPO training can elevate a generative model into a true thinking model. By the end, we established a clear path from DeepSeek‑V3’s architectural innovations to DeepSeek‑R1’s reasoning breakthroughs, showing how GRPO bridges the gap between generation and structured thought.</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>“Toward DeepSeek-R1: Building Thinking Models Using GRPO,” <em>PyImageSearch</em>, S. Huot, A. Sharma, and P. Thakur, eds., 2026, <a href="https://pyimg.co/70rm1" target="_blank" rel="noreferrer noopener">https://pyimg.co/70rm1</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="Toward DeepSeek-R1: Building Thinking Models Using GRPO" data-enlighter-group="13">@incollection{Mangla_2026_deepseek-r1-building-thinking-models-using-grpo,
  author = {Puneet Mangla},
  title = {{Toward DeepSeek-R1: Building Thinking Models Using GRPO}},
  booktitle = {PyImageSearch},
  editor = {Susan Huot and Aditya Sharma and Piyush Thakur},
  year = {2026},
  url = {https://pyimg.co/70rm1},
}
</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/10/19/toward-deepseek-r1-building-thinking-models-using-grpo/">Toward DeepSeek-R1: Building Thinking Models Using GRPO</a> appeared first on <a rel="nofollow" href="https://pyimagesearch.com">PyImageSearch</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>DeepSeek-V3 from Scratch: Implementing the DeepSeek Trainer</title>
		<link>https://pyimagesearch.com/2026/10/12/deepseek-v3-from-scratch-implementing-the-deepseek-trainer/</link>
		
		<dc:creator><![CDATA[Puneet Mangla]]></dc:creator>
		<pubDate>Mon, 12 Oct 2026 12:45:00 +0000</pubDate>
				<category><![CDATA[Deep Learning]]></category>
		<category><![CDATA[DeepSeek-V3 From Scratch]]></category>
		<category><![CDATA[LLMs]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[custom trainer]]></category>
		<category><![CDATA[deepseek trainer]]></category>
		<category><![CDATA[deepseek v3]]></category>
		<category><![CDATA[gradient accumulation]]></category>
		<category><![CDATA[hugging face trainer]]></category>
		<category><![CDATA[llm training]]></category>
		<category><![CDATA[mixed precision training]]></category>
		<category><![CDATA[multi-token prediction]]></category>
		<category><![CDATA[pytorch]]></category>
		<category><![CDATA[tinystories]]></category>
		<category><![CDATA[tinystories dataset]]></category>
		<category><![CDATA[transformer training]]></category>
		<category><![CDATA[tutorial]]></category>
		<guid isPermaLink="false">https://pyimagesearch.com/?p=55549</guid>

					<description><![CDATA[<p>Table of Contents DeepSeek-V3 from Scratch: Implementing the DeepSeek Trainer Training Infrastructure with Hugging Face Trainer Implementation: Custom Trainer and Data Handling Training Configuration Data Preparation: TinyStories Dataset Training DeepSeek-V3 from Scratch and Saving Checkpoints Testing Generation: Bringing the Model&#8230;</p>
<p>The post <a rel="nofollow" href="https://pyimagesearch.com/2026/10/12/deepseek-v3-from-scratch-implementing-the-deepseek-trainer/">DeepSeek-V3 from Scratch: Implementing the DeepSeek Trainer</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-DeepSeek-V3-from-Scratch-Implementing-the-DeepSeek-Trainer"><a rel="noopener" target="_blank" href="#h1-DeepSeek-V3-from-Scratch-Implementing-the-DeepSeek-Trainer">DeepSeek-V3 from Scratch: Implementing the DeepSeek Trainer</a></li>
    <li id="TOC-h2-Training-Infrastructure-with-Hugging-Face-Trainer"><a rel="noopener" target="_blank" href="#h2-Training-Infrastructure-with-Hugging-Face-Trainer">Training Infrastructure with Hugging Face Trainer</a></li>
    <li id="TOC-h2-Implementation-Custom-Trainer-and-Data-Handling"><a rel="noopener" target="_blank" href="#h2-Implementation-Custom-Trainer-and-Data-Handling">Implementation: Custom Trainer and Data Handling</a></li>
    <li id="TOC-h2-Training-Configuration"><a rel="noopener" target="_blank" href="#h2-Training-Configuration">Training Configuration</a></li>
    <li id="TOC-h2-Data-Preparation-TinyStories-Dataset"><a rel="noopener" target="_blank" href="#h2-Data-Preparation-TinyStories-Dataset">Data Preparation: TinyStories Dataset</a></li>
    <li id="TOC-h2-Training-DeepSeek-V3-from-Scratch-and-Saving-Checkpoints"><a rel="noopener" target="_blank" href="#h2-Training-DeepSeek-V3-from-Scratch-and-Saving-Checkpoints">Training DeepSeek-V3 from Scratch and Saving Checkpoints</a></li>
    <li id="TOC-h2-Testing-Generation-Bringing-the-Model-to-Life"><a rel="noopener" target="_blank" href="#h2-Testing-Generation-Bringing-the-Model-to-Life">Testing Generation: Bringing the Model to Life</a></li>
    <li id="TOC-h2-Summary"><a rel="noopener" target="_blank" href="#h2-Summary">Summary</a>
        <ul>
            <li id="TOC-h3-Citation-Information"><a rel="noopener" target="_blank" href="#h3-Citation-Information">Citation Information</a></li>
        </ul>
    </li>
</ul>
</div>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h1-DeepSeek-V3-from-Scratch-Implementing-the-DeepSeek-Trainer"/>



<h2 class="wp-block-heading"><a href="#TOC-h1-DeepSeek-V3-from-Scratch-Implementing-the-DeepSeek-Trainer">DeepSeek-V3 from Scratch: Implementing the DeepSeek Trainer</a></h2>



<p>Over the past 5 lessons, we have carefully constructed DeepSeek-V3 piece by piece: beginning with its <strong>configuration and Rotary Position Embeddings (RoPE)</strong>, advancing through <strong>Multi-head Latent Attention (MLA)</strong>, scaling capacity with the <strong>Mixture of Experts (MoE)</strong>, enhancing the training objective with <strong>Multi-Token Prediction (MTP)</strong>, and finally assembling the complete architecture. Each step has brought us closer to a fully realized model, blending theory with hands-on implementation to illuminate how DeepSeek-V3 achieves efficiency, scalability, and cutting-edge performance.</p>


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


<p>In this final lesson, we shift our focus to the <strong>DeepSeek trainer</strong>. This component brings the architecture to life. Training is where all the innovations converge, transforming static design into a dynamic system capable of learning from data. We will explore the training loop, optimization strategies, loss weighting, and practical considerations for scaling experiments. By the end, you will not only understand how to train DeepSeek-V3 from scratch but also appreciate how each architectural innovation integrates seamlessly into the training process. This marks the culmination of our journey: a complete, working DeepSeek-V3 model built step by step, ready for experimentation, extension, and exploration.</p>



<p>This lesson is the last in the 6-part series on <strong>Building DeepSeek-V3 from Scratch</strong>:</p>



<ol class="wp-block-list">
<li><em><strong><a href="https://pyimg.co/1atre" target="_blank" rel="noreferrer noopener">DeepSeek-V3 Model: Theory, Config, and Rotary Positional Embeddings</a></strong></em></li>



<li><em><strong><a href="https://pyimg.co/scgjl" target="_blank" rel="noreferrer noopener">Build DeepSeek-V3: Multi-Head Latent Attention (MLA) Architecture</a></strong></em></li>



<li><em><strong><a href="https://pyimg.co/a1w0g" target="_blank" rel="noreferrer noopener">DeepSeek-V3 from Scratch: Mixture of Experts (MoE)</a></strong></em></li>



<li><em><strong><a href="https://pyimg.co/alrep" target="_blank" rel="noreferrer noopener">Autoregressive Model Limits and Multi-Token Prediction in DeepSeek-V3</a></strong></em></li>



<li><em><strong><a href="https://pyimg.co/36gvk" target="_blank" rel="noreferrer noopener">DeepSeek-V3 from Scratch: Building the Architecture in PyTorch</a></strong></em></li>



<li><em><a href="https://pyimg.co/u5mv8" target="_blank" rel="noreferrer noopener">DeepSeek-V3 from Scratch: Implementing the DeepSeek Trainer</a> </em><strong>(this tutorial)</strong></li>
</ol>



<p><strong>To learn about DeepSeek-V3 and build it from scratch, </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-Training-Infrastructure-with-Hugging-Face-Trainer"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Training-Infrastructure-with-Hugging-Face-Trainer">Training Infrastructure with Hugging Face Trainer</a></h2>



<p>Training a transformer model from scratch requires careful orchestration of many components: data loading and batching, optimization with learning rate (LR) scheduling, gradient accumulation for large effective batch sizes, mixed-precision training for efficiency, checkpoint management, and evaluation. Implementing all of this from scratch is time-consuming and error-prone.</p>



<p>The Hugging Face <code data-enlighter-language="python" class="EnlighterJSRAW">Trainer</code> application programming interface (API) provides a robust solution. It is a high-level interface that handles the training loop while remaining flexible enough for custom models. The key challenge is adapting our custom DeepSeek model to work with the expectations of <code data-enlighter-language="python" class="EnlighterJSRAW">Trainer</code>.</p>



<p>The accompanying Colab uses a tested training stack: <code data-enlighter-language="python" class="EnlighterJSRAW">transformers==4.57.3</code>, <code data-enlighter-language="python" class="EnlighterJSRAW">datasets==4.8.5</code>, and <code data-enlighter-language="python" class="EnlighterJSRAW">accelerate==1.15.0</code>, alongside Colab&#8217;s existing CUDA-compatible PyTorch. If these libraries were already imported, restart the runtime after installing the pinned versions.</p>



<p>The default <code data-enlighter-language="python" class="EnlighterJSRAW">Trainer</code> expects a compatible output containing a loss, such as a mapping with a <code data-enlighter-language="python" class="EnlighterJSRAW">loss</code> entry or a tuple whose first item is the loss. Our model returns <code data-enlighter-language="python" class="EnlighterJSRAW">(logits, loss)</code>, so a custom <code data-enlighter-language="python" class="EnlighterJSRAW">compute_loss</code> method adapts this output to the expected format of <code data-enlighter-language="python" class="EnlighterJSRAW">Trainer</code>.</p>



<p><strong>Gradient Accumulation</strong><strong>:</strong> For memory-constrained graphics processing units (GPUs), we cannot always use large batch sizes. Gradient accumulation simulates larger batches by accumulating gradients over multiple small batches before updating weights:</p>



<p class="has-text-align-center"><img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/56e/56e10175bf1b2316652cb6edf8624659-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='\theta_{t+1} = \theta_t - \eta \dfrac{1}{K} \sum_{k=1}^K \nabla_\theta \mathcal{L}(x^{(k)}; \theta_t)' title='\theta_{t+1} = \theta_t - \eta \dfrac{1}{K} \sum_{k=1}^K \nabla_\theta \mathcal{L}(x^{(k)}; \theta_t)' class='latex' srcset='https://b2633864.assetcdn.net/2633864/wp-content/latex/56e/56e10175bf1b2316652cb6edf8624659-ffffff-000000-0.png?lossy=2&strip=1&webp=1 243w,https://b2633864.assetcdn.net/2633864/wp-content/latex/56e/56e10175bf1b2316652cb6edf8624659-ffffff-000000-0.png?size=126x18&lossy=2&strip=1&webp=1 126w' sizes='(max-width: 243px) 100vw, 243px' /></p>



<p>where <img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/a5f/a5f3c6a11b03839d46af9fb43c97c188-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='K' title='K' class='latex' /> is the number of gradient accumulation steps. On a single GPU, if we can handle a batch size of 4 but want an effective batch size of 16, we use <img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/d96/d9686e6d8d3e6883381eecea2fbe6dfd-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='K = 4' title='K = 4' class='latex' /> accumulation steps.</p>



<p><strong>Learning Rate Scheduling:</strong> Training deep networks benefits from learning rate schedules. We use a warmup schedule:</p>



<p class="has-text-align-center"><img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/5b6/5b660307ee5ba1c7c39eb6c0c704b511-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='\eta_t = \left\{\begin{array}{l} \eta_\text{max} \cdot \dfrac{t}{T_\text{warmup}} \qquad \text{if } t \ {&lt;} \ T_\text{warmup} \\[18pt] \eta_\text{max} \cdot \dfrac{T_\text{total} - t}{T_\text{total} - T_\text{warmup}} \qquad \text{otherwise}\end{array} \right.' title='\eta_t = \left\{\begin{array}{l} \eta_\text{max} \cdot \dfrac{t}{T_\text{warmup}} \qquad \text{if } t \ {&lt;} \ T_\text{warmup} \\[18pt] \eta_\text{max} \cdot \dfrac{T_\text{total} - t}{T_\text{total} - T_\text{warmup}} \qquad \text{otherwise}\end{array} \right.' class='latex' srcset='https://b2633864.assetcdn.net/2633864/wp-content/latex/5b6/5b660307ee5ba1c7c39eb6c0c704b511-ffffff-000000-0.png?lossy=2&strip=1&webp=1 307w,https://b2633864.assetcdn.net/2633864/wp-content/latex/5b6/5b660307ee5ba1c7c39eb6c0c704b511-ffffff-000000-0.png?size=126x37&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/latex/5b6/5b660307ee5ba1c7c39eb6c0c704b511-ffffff-000000-0.png?size=252x75&lossy=2&strip=1&webp=1 252w' sizes='(max-width: 307px) 100vw, 307px' /></p>



<p>Warmup (gradually increasing LR) helps training stability at the start when parameters are random. Linear decay toward 0 helps final convergence.</p>



<p><strong>Mixed Precision Training:</strong> Modern GPUs have specialized hardware for FP16 (16-bit floating point) computation, which can improve training throughput compared with FP32 (32-bit floating point); the actual speedup depends on hardware and workload. Mixed precision training keeps model parameters in FP32 for stability while autocast selects an appropriate precision for eligible operations. Loss scaling helps prevent small gradients from underflowing:</p>



<p class="has-text-align-center"><img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/685/685012d4a109deff5c495514944271ac-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='\text{loss}_\text{scaled} = s \cdot \text{loss}' title='\text{loss}_\text{scaled} = s \cdot \text{loss}' class='latex' /></p>



<p class="has-text-align-center"><img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/f17/f17e16aad57643d43cc0c569d15e852c-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='\text{gradients}_\text{scaled} = \nabla_\theta (\text{loss}_\text{scaled}) = s \cdot \nabla_\theta \text{loss}' title='\text{gradients}_\text{scaled} = \nabla_\theta (\text{loss}_\text{scaled}) = s \cdot \nabla_\theta \text{loss}' class='latex' srcset='https://b2633864.assetcdn.net/2633864/wp-content/latex/f17/f17e16aad57643d43cc0c569d15e852c-ffffff-000000-0.png?lossy=2&strip=1&webp=1 295w,https://b2633864.assetcdn.net/2633864/wp-content/latex/f17/f17e16aad57643d43cc0c569d15e852c-ffffff-000000-0.png?size=126x8&lossy=2&strip=1&webp=1 126w' sizes='(max-width: 295px) 100vw, 295px' /></p>



<p class="has-text-align-center"><img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/a4e/a4e93156ec7c2609c28de072914004ec-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='\text{gradients} = \text{gradients}_\text{scaled} / s' title='\text{gradients} = \text{gradients}_\text{scaled} / s' class='latex' srcset='https://b2633864.assetcdn.net/2633864/wp-content/latex/a4e/a4e93156ec7c2609c28de072914004ec-ffffff-000000-0.png?lossy=2&strip=1&webp=1 198w,https://b2633864.assetcdn.net/2633864/wp-content/latex/a4e/a4e93156ec7c2609c28de072914004ec-ffffff-000000-0.png?size=126x11&lossy=2&strip=1&webp=1 126w' sizes='(max-width: 198px) 100vw, 198px' /></p>



<p>Scaling raises small gradients into a representable range to reduce FP16 underflow, and gradients are unscaled before the optimizer update. If the scaler detects nonfinite gradients, it skips the optimizer update and reduces the scale; after a sustained period without overflow, it can increase the scale.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Implementation-Custom-Trainer-and-Data-Handling"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Implementation-Custom-Trainer-and-Data-Handling">Implementation: Custom Trainer and Data Handling</a></h2>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="DeepSeek-V3 from Scratch: Implementing the DeepSeek Trainer" data-enlighter-group="1">from transformers import (
    Trainer,
    TrainingArguments,
    DataCollatorForLanguageModeling,
)
from datasets import load_dataset
from torch.utils.data import Dataset

# Setup logging
logging.basicConfig(
    format="%(asctime)s - %(levelname)s - %(message)s",
    level=logging.INFO,
)
logger = logging.getLogger(__name__)


class TextDataset(Dataset):
    """Custom dataset for text data"""

    def __init__(self, texts: List[str], tokenizer, max_length: int = 1024):
        self.texts = texts
        self.tokenizer = tokenizer
        self.max_length = max_length

    def __len__(self):
        return len(self.texts)

    def __getitem__(self, idx):
        text = self.texts[idx]
        encodings = self.tokenizer(
            text,
            truncation=True,
            max_length=self.max_length,
            padding="max_length",
            return_tensors="pt",
        )

        input_ids = encodings["input_ids"].squeeze()
        attention_mask = encodings["attention_mask"].squeeze()

        # For language modeling, labels are the same as input_ids
        labels = input_ids.clone()
        labels[attention_mask == 0] = -100  # Ignore padding in loss

        return {
            "input_ids": input_ids,
            "attention_mask": attention_mask,
            "labels": labels,
        }

</pre>



<p><strong>Lines 1-49: Custom Dataset Class:</strong> The <code data-enlighter-language="python" class="EnlighterJSRAW">TextDataset</code> class wraps our text data for the PyTorch data loading system. In <code data-enlighter-language="python" class="EnlighterJSRAW">__init__</code>, we store the texts, tokenizer, and maximum sequence length. The <code data-enlighter-language="python" class="EnlighterJSRAW">__len__</code> method returns the dataset size (required by PyTorch). The <code data-enlighter-language="python" class="EnlighterJSRAW">__getitem__</code> method is the core: given an index, it retrieves the corresponding text, tokenizes it with truncation and padding to ensure fixed length, and creates labels by cloning input token identifiers (IDs) and masking padding positions with <code data-enlighter-language="python" class="EnlighterJSRAW">-100</code> (which the PyTorch cross-entropy loss ignores). This masking is crucial because we do not want the model to receive gradient signals from predicting padding tokens.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="51" data-enlighter-title="DeepSeek-V3 from Scratch: Implementing the DeepSeek Trainer" data-enlighter-group="2">class DeepSeekDataCollator:
    """Custom data collator for DeepSeek model"""

    def __init__(self, tokenizer):
        self.tokenizer = tokenizer

    def __call__(self, features: List[Dict[str, torch.Tensor]]) -> Dict[str, torch.Tensor]:
        batch = {
            "input_ids": torch.stack([f["input_ids"] for f in features]),
            "labels": torch.stack([f["labels"] for f in features]),
        }

        if "attention_mask" in features[0]:
            batch["attention_mask"] = torch.stack([f["attention_mask"] for f in features])

        return batch
</pre>



<p><strong>Lines 51-66: Data Collator:</strong> The role of the collator is to take a list of individual samples and combine them into a batch. We stack the tensors along a new batch dimension. This is straightforward for our fixed-length sequences. The collator also handles the attention mask if present, which distinguishes real tokens from padding. The <code data-enlighter-language="python" class="EnlighterJSRAW">__call__</code> method makes the object callable, allowing <code data-enlighter-language="python" class="EnlighterJSRAW">Trainer</code> to use it as a function.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="67" data-enlighter-title="DeepSeek-V3 from Scratch: Implementing the DeepSeek Trainer" data-enlighter-group="3">class DeepSeekTrainer(Trainer):
    """Custom Trainer for DeepSeek model"""

    def compute_loss(self, model, inputs, return_outputs=False, **kwargs):
        """Custom loss computation to handle DeepSeek's output format"""
        input_ids = inputs["input_ids"]
        labels = inputs.get("labels", input_ids)

        # Forward pass
        logits, loss = model(input_ids, targets=labels, attention_mask=inputs.get("attention_mask"))

        if return_outputs:
            return loss / self.args.gradient_accumulation_steps, {"logits": logits}
        return loss / self.args.gradient_accumulation_steps

</pre>



<p><strong>Lines 67-80: Custom Trainer Loss Computation:</strong> We extend the Hugging Face <code data-enlighter-language="python" class="EnlighterJSRAW">Trainer</code> with a custom <code data-enlighter-language="python" class="EnlighterJSRAW">compute_loss</code> method. The default <code data-enlighter-language="python" class="EnlighterJSRAW">Trainer</code> expects a compatible output containing a loss, but our model returns <code data-enlighter-language="python" class="EnlighterJSRAW">(logits, loss)</code>. We extract input IDs and labels, pass the attention mask to the model, and return the loss. Passing this mask connects the trainer to the padding-mask handling implemented in the previous lesson, while labels marked <code data-enlighter-language="python" class="EnlighterJSRAW">-100</code> are excluded from the loss. For this pinned integration, the division by <code data-enlighter-language="python" class="EnlighterJSRAW">gradient_accumulation_steps</code> normalizes the contribution of each microbatch. This normalization is specific to the pinned integration between <code data-enlighter-language="python" class="EnlighterJSRAW">Trainer</code> and the model and should not be copied blindly into another <code data-enlighter-language="python" class="EnlighterJSRAW">Trainer</code> subclass. The <code data-enlighter-language="python" class="EnlighterJSRAW">return_outputs</code> flag allows the method to optionally return model outputs alongside the loss when those outputs are requested.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="82" data-enlighter-title="DeepSeek-V3 from Scratch: Implementing the DeepSeek Trainer" data-enlighter-group="4">    def prediction_step(
        self,
        model,
        inputs,
        prediction_loss_only,
        ignore_keys=None,
    ):
        """
        Custom prediction step for evaluation

        Perform an evaluation step on model using inputs and returns:
        - loss
        - logits (if not prediction_loss_only)
        - labels (if not prediction_loss_only)
        """
        has_labels = "labels" in inputs
        inputs = self._prepare_inputs(inputs)

        # Forward pass
        with torch.no_grad():
            if has_labels:
                input_ids = inputs["input_ids"]
                labels = inputs["labels"]

                # Get model outputs
                logits, loss = model(input_ids, targets=labels, attention_mask=inputs.get("attention_mask"))

                # Ensure loss is a scalar
                if loss.dim() > 0:
                    loss = loss.mean()
            else:
                input_ids = inputs["input_ids"]
                logits, loss = model(input_ids, attention_mask=inputs.get("attention_mask"))
                loss = None

        if prediction_loss_only:
            return (loss, None, None)

        # Return predictions and labels
        # logits shape: [batch_size, seq_len, vocab_size] or [batch_size, seq_len, num_tokens, vocab_size]
        if logits.dim() == 4:
            # Multi-token prediction: use first prediction head
            logits = logits[:, :, 0, :]  # [batch_size, seq_len, vocab_size]

        # Get labels
        labels = inputs.get("labels")

        return (loss, logits, labels)
</pre>



<p><strong>Lines 82-129: Prediction Step for Evaluation:</strong> The <code data-enlighter-language="python" class="EnlighterJSRAW">prediction_step</code> method handles evaluation. It is more complex because evaluation needs loss (for metrics) and logits (for qualitative analysis). We prepare inputs, pass attention masks through the model, and run a forward pass with gradients disabled to save memory. When labels are provided, the model returns main-head logits with shape <code data-enlighter-language="python" class="EnlighterJSRAW">[batch_size, seq_len, vocab_size]</code>. The 4-dimensional branch is a compatibility fallback, not the normal MTP output of the current model. The method returns a tuple of <code data-enlighter-language="python" class="EnlighterJSRAW">(loss, logits, labels)</code>, which <code data-enlighter-language="python" class="EnlighterJSRAW">Trainer</code> uses to compute evaluation metrics. The evaluation loss is the combined objective defined in the previous lesson, rather than next-token loss alone, and is returned without the accumulation divisor used in <code data-enlighter-language="python" class="EnlighterJSRAW">compute_loss</code>.</p>



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



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



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="DeepSeek-V3 from Scratch: Implementing the DeepSeek Trainer" data-enlighter-group="5">training_args = TrainingArguments(
    output_dir="./deepseek_checkpoints",
    num_train_epochs=2,
    per_device_train_batch_size=4,
    per_device_eval_batch_size=4,
    learning_rate=5e-4,
    warmup_steps=10,
    weight_decay=0.01,
    logging_dir="./deepseek_checkpoints/logs",
    logging_steps=50,
    save_steps=50,
    save_total_limit=3,
    eval_steps=50,
    eval_strategy="steps",
    save_strategy="steps",
    load_best_model_at_end=True,
    metric_for_best_model="eval_loss",
    greater_is_better=False,
    gradient_accumulation_steps=4,
    fp16=torch.cuda.is_available(),
    dataloader_num_workers=2,
    remove_unused_columns=False,
    report_to="none",
    push_to_hub=False,
    save_safetensors=False
)
</pre>



<p><strong>Lines 1-26: Training Arguments:</strong> These hyperparameters control training behavior. We train for 2 epochs with a batch size of 4 and 4 gradient accumulation steps (an effective batch size of 16 on a single device). A learning rate of 5e-4 is reasonable for a model this size. Larger models often use a lower learning rate (e.g., 1e-4). We use 10 warmup steps (modest warmup since our model is small). A weight decay of 0.01 provides regularization. Logging, checkpoint saving, and evaluation run every 50 optimizer steps, not individual microbatches. We retain up to 3 checkpoints while protecting the best checkpoint when <code data-enlighter-language="python" class="EnlighterJSRAW">load_best_model_at_end=True</code>; these are not necessarily the 3 lowest-loss checkpoints. The <code data-enlighter-language="python" class="EnlighterJSRAW">load_best_model_at_end</code> flag ensures we end with the checkpoint that had the lowest validation loss, not necessarily the last checkpoint. FP16 is enabled if CUDA is available, which can improve training throughput depending on the GPU and workload.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Data-Preparation-TinyStories-Dataset"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Data-Preparation-TinyStories-Dataset">Data Preparation: TinyStories Dataset</a></h2>



<p>We train on TinyStories, a dataset of simple children&#8217;s stories generated to have vocabulary and grammar suitable for training small language models. Each story is 1-3 paragraphs and exhibits basic narrative structure.</p>



<p><strong>Data Processing Pipeline</strong><strong>:</strong></p>



<ul class="wp-block-list">
<li>Load raw text stories</li>



<li>Add special tokens (<code data-enlighter-language="python" class="EnlighterJSRAW">story_start</code>, <code data-enlighter-language="python" class="EnlighterJSRAW">story_end</code>) for structure</li>



<li>Tokenize using the Generative Pretrained Transformer 2 (GPT-2) tokenizer, which uses byte-pair encoding (BPE)</li>



<li>Truncate or pad each story to the configured sequence length (<code data-enlighter-language="python" class="EnlighterJSRAW">config.block_size</code>)</li>



<li>Clone input IDs into labels and mask padding with <code data-enlighter-language="python" class="EnlighterJSRAW">-100</code>; the model shifts logits and targets internally</li>



<li>Batch the sequences and feed them to the model</li>
</ul>



<p>The tokenizer converts text to integers via byte-pair encoding, which balances vocabulary size with representation efficiency. Common words may be represented by single tokens; less common words may be split into subword units.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="DeepSeek-V3 from Scratch: Implementing the DeepSeek Trainer" data-enlighter-group="6">from transformers import GPT2TokenizerFast

# Create tokenizer
tokenizer = GPT2TokenizerFast.from_pretrained("gpt2")

# Add special tokens from config
special_tokens_dict = {
    'additional_special_tokens': list(config.special_tokens.values())
}
num_added_tokens = tokenizer.add_special_tokens(special_tokens_dict)

# Set pad token if not present
if tokenizer.pad_token is None:
    tokenizer.pad_token = tokenizer.eos_token

print(f"✓ Loaded tokenizer: {len(tokenizer)} tokens")
print(f"✓ Added {num_added_tokens} special tokens:")
for name, token in config.special_tokens.items():
    token_id = tokenizer.convert_tokens_to_ids(token)
    print(f"  {name}: '{token}' (ID: {token_id})")

# Load dataset
logger.info("Loading TinyStories dataset...")
dataset = load_dataset("roneneldan/TinyStories", split="train", streaming=False)

# Use a subset for faster training (remove for full training)
max_samples = 10000
dataset = dataset.select(range(min(max_samples, len(dataset))))

# Extract texts
texts = [config.special_tokens["story_start"] + item["text"] + config.special_tokens["story_end"] for item in dataset]
print(f"✓ Loaded {len(texts)} stories")

# Show example
print(f"\n📖 Example story:")
print("=" * 80)
print(texts[0])
print("=" * 80)

# Split into train and eval
split_idx = int(0.9 * len(texts))
train_texts, eval_texts = texts[:split_idx], texts[split_idx:]

# Create datasets
train_dataset = TextDataset(train_texts, tokenizer, max_length=config.block_size)
eval_dataset = TextDataset(eval_texts, tokenizer, max_length=config.block_size)

print(f"\n✓ Dataset split:")
print(f"  Training: {len(train_dataset)} samples")
print(f"  Evaluation: {len(eval_dataset)} samples")
</pre>



<p><strong>Lines 1-50: </strong><strong>Loading</strong> <strong>the</strong><strong> TinyStories Dataset:</strong> This code sets up the data pipeline for training by first loading a GPT‑2 tokenizer and extending it with custom special tokens defined in the configuration, ensuring that a pad token is available by defaulting to the end-of-sequence (EOS) token if necessary. It then loads the TinyStories dataset from Hugging Face, selects a smaller subset of 10,000 samples for faster experimentation, and wraps each story with start and end special tokens to mark boundaries. After printing a sample story for inspection, the first 10,000 stories are split in order into training and evaluation sets with 90% used for training and 10% for evaluation (9,000 and 1,000 samples), without shuffling. This evaluation set comes from the selected training subset, not the official validation split of the dataset. Finally, both splits are converted into <code data-enlighter-language="python" class="EnlighterJSRAW">TextDataset</code> objects using the tokenizer and a fixed block size, giving properly tokenized sequences ready for model training and evaluation (<strong>Figure 1</strong>).</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/10/image-5-scaled.jpeg" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="81" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-5-1024x81.jpeg?lossy=2&strip=1&webp=1" alt="" class="wp-image-55618"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-5-1024x81.jpeg?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-5-1024x81.jpeg?size=126x10&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-5-1024x81.jpeg?size=252x20&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-5-1024x81.jpeg?size=378x30&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-5-1024x81.jpeg?size=504x40&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-5-1024x81.jpeg?size=630x50&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 1:</strong> Sample from the TinyStories Dataset (source: image by the author).</figcaption></figure></div>


<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Training-DeepSeek-V3-from-Scratch-and-Saving-Checkpoints"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Training-DeepSeek-V3-from-Scratch-and-Saving-Checkpoints">Training DeepSeek-V3 from Scratch and Saving Checkpoints</a></h2>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="DeepSeek-V3 from Scratch: Implementing the DeepSeek Trainer" data-enlighter-group="7"># Create fresh model for training
torch.cuda.empty_cache()

model = DeepSeek(config)
data_collator = DeepSeekDataCollator(tokenizer)

# Create trainer
trainer = DeepSeekTrainer(
    model=model,
    args=training_args,
    train_dataset=train_dataset,
    eval_dataset=eval_dataset,
    data_collator=data_collator,
)

print("✓ Trainer created. Starting training...")
print("=" * 80)

# Train!
trainer.train()

print("=" * 80)
print("✓ Training complete!")

# Save final model
trainer.save_model("./deepseek_final")
tokenizer.save_pretrained("./deepseek_final")
print("✓ Model saved to ./deepseek_final")
</pre>



<p><strong>Lines 1-28: Model Training:</strong> This script initializes and runs the training process for the DeepSeek model. It begins by releasing unused cached GPU allocations; <code data-enlighter-language="python" class="EnlighterJSRAW">torch.cuda.empty_cache()</code> does not free live tensors or reset the model. Creating <code data-enlighter-language="python" class="EnlighterJSRAW">DeepSeek(config)</code> initializes a fresh model, and the data collator prepares tokenized inputs for training. A custom trainer object is created, tying together the model, training arguments, datasets, and collator. Once the trainer is set up, the script prints a confirmation message and launches the training loop, reporting progress until completion. After training finishes, the final model and tokenizer are saved to disk in the <code data-enlighter-language="python" class="EnlighterJSRAW">./deepseek_final</code> directory, making them available for later inference or fine‑tuning.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Testing-Generation-Bringing-the-Model-to-Life"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Testing-Generation-Bringing-the-Model-to-Life">Testing Generation: Bringing the Model to Life</a></h2>



<p>After training comes the exciting part: generating text. We load the trained model and use its <code data-enlighter-language="python" class="EnlighterJSRAW">generate</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="DeepSeek-V3 from Scratch: Implementing the DeepSeek Trainer" data-enlighter-group="8"># Load best model
model = DeepSeek(config)
checkpoint_path = "./deepseek_final/pytorch_model.bin"

if os.path.exists(checkpoint_path):
    checkpoint = torch.load(checkpoint_path, map_location="cpu")
    model.load_state_dict(checkpoint)
    print("✓ Loaded trained model")
else:
    print("⚠ Using untrained model (checkpoint not found)")

model.eval()
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)

print(f"✓ Model ready on {device}")
def generate_story(prompt: str, max_tokens: int = 200, temperature: float = 0.8, top_k: int = 50):
    """Generate a story from a prompt"""
    # Encode prompt
    input_ids = tokenizer.encode(prompt, return_tensors="pt").to(device)

    # Generate
    with torch.no_grad():
        output_ids = model.generate(
            input_ids,
            max_new_tokens=max_tokens,
            temperature=temperature,
            top_k=top_k,
        )

    # Decode
    generated_text = tokenizer.decode(output_ids[0], skip_special_tokens=True)
    return generated_text

# Generate stories with different prompts
prompts = [
    "Once upon a time",
    "In a magical forest",
    "There was a little girl named Lucy who",
    "The brave knight"
]

print("🎨 Generating Stories")
print("=" * 80)

for i, prompt in enumerate(prompts, 1):
    print(f"\n📖 Story {i}: '{prompt}'")
    print("-" * 80)
    story = generate_story(prompt, max_tokens=150, temperature=0.8)
    print(story)
    print("-" * 80)
</pre>



<p><strong>Temperature:</strong> Controls randomness. At <img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/7f1/7f1a4e2f085fe44d8e1110b03417d0cd-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='\tau = 1.0' title='\tau = 1.0' class='latex' />, we sample directly from the probability distribution of the model. A lower temperature (<img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/7da/7da7e8890992a6168799ec5da4f82f32-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='\tau = 0.5' title='\tau = 0.5' class='latex' />) makes sampling less random; a higher temperature (<img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/090/0907265cc380c8cc295e558a253689aa-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='\tau = 1.2' title='\tau = 1.2' class='latex' />) makes it more random:</p>



<p class="has-text-align-center"><img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/e77/e77b141d5df4fba55e21bc9c1641b8a4-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='P_\tau(x_t) = \dfrac{\exp(\text{logits}(x_t) / \tau)}{\sum_{x&#039;} \exp(\text{logits}(x&#039;) / \tau)}' title='P_\tau(x_t) = \dfrac{\exp(\text{logits}(x_t) / \tau)}{\sum_{x&#039;} \exp(\text{logits}(x&#039;) / \tau)}' class='latex' srcset='https://b2633864.assetcdn.net/2633864/wp-content/latex/e77/e77b141d5df4fba55e21bc9c1641b8a4-ffffff-000000-0.png?lossy=2&strip=1&webp=1 218w,https://b2633864.assetcdn.net/2633864/wp-content/latex/e77/e77b141d5df4fba55e21bc9c1641b8a4-ffffff-000000-0.png?size=126x24&lossy=2&strip=1&webp=1 126w' sizes='(max-width: 218px) 100vw, 218px' /></p>



<p><strong>Top-k Sampling:</strong> We only sample from the <img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/8ce/8ce4b16b22b58894aa86c421e8759df3-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='k' title='k' class='latex' /> most probable tokens. This prevents sampling very unlikely tokens that might break coherence. With <img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/4ae/4ae268d78204516c21ff2142f2ea4f04-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='k = 50' title='k = 50' class='latex' />, we consider only the 50 most likely next tokens.</p>



<p><strong>Example Outputs:</strong> The following story is an illustrative example, not a recorded output from the supplied Colab run. Actual generations will vary (<strong>Figure 2</strong>):</p>



<p><em><strong>Prompt:</strong></em><em> Once upon a time</em></p>



<p><em><strong>Generated:</strong></em><em> Once upon a time, there was a little girl named Lily. She loved to play in the park with her red ball. One day, the ball rolled into a bush. Lily looked inside and found a tiny bird. The bird was blue and sang a happy song. Lily smiled and said, &#8220;Hello, bird!&#8221;</em></p>



<p>Output quality depends on training data, model size, training duration, and sampling choices. Our small model will not match large pretrained models, and generations may repeat, drift, or become incoherent; successful training alone does not guarantee coherent, grammatical stories.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://pyimagesearch.com/wp-content/uploads/2026/10/image-6-scaled.jpeg" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="1024" height="572" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-6-1024x572.jpeg?lossy=2&strip=1&webp=1" alt="" class="wp-image-55623"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-6-1024x572.jpeg?lossy=2&strip=1&webp=1 1024w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-6-1024x572.jpeg?size=126x70&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-6-1024x572.jpeg?size=252x141&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-6-1024x572.jpeg?size=378x211&lossy=2&strip=1&webp=1 378w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-6-1024x572.jpeg?size=504x282&lossy=2&strip=1&webp=1 504w,https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-6-1024x572.jpeg?size=630x352&lossy=2&strip=1&webp=1 630w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption"><strong>Figure 2:</strong> Illustrative Example of Generated Stories (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 of on-demand code walkthrough videos • Last updated: November 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</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 the final part of our <strong>DeepSeek-V3 </strong><strong>f</strong><strong>rom Scratch</strong> series, we shift focus from architecture to <strong>training and testing the model</strong>. We begin by outlining the training infrastructure, leveraging the <strong>Hugging Face</strong> <code data-enlighter-language="python" class="EnlighterJSRAW">Trainer</code> to streamline experimentation and provide a flexible foundation. This sets the stage for building a <strong>custom trainer</strong> that handles data efficiently, ensuring our implementation is both scalable and adaptable to different tasks.</p>



<p>We then walk through the <strong>training configuration</strong>, where we define hyperparameters and optimization strategies, followed by <strong>data preparation using the TinyStories dataset</strong>. This lightweight dataset allows us to quickly prototype and validate our setup while still capturing meaningful language patterns. With everything in place, we start the actual training process, observing how the model learns and adapts over time.</p>



<p>Finally, we bring the model to life by <strong>testing </strong><strong>text </strong><strong>generation</strong>, showcasing how DeepSeek-V3 produces outputs after training. This step highlights the transition from theory and implementation to practical results, demonstrating how to sample text from the trained model. By the end of this lesson, we have not only assembled and trained DeepSeek-V3 but also seen it in action, completing our journey from scratch to a fully functioning language model.</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>“DeepSeek-V3 from Scratch: Implementing the DeepSeek Trainer,” <em>PyImageSearch</em>, S. Huot, A. Sharma, and P. Thakur, eds., 2026, <a href="https://pyimg.co/u5mv8" target="_blank" rel="noreferrer noopener">https://pyimg.co/u5mv8</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="DeepSeek-V3 from Scratch: Implementing the DeepSeek Trainer" data-enlighter-group="9">@incollection{Mangla_2026_deepseek-v3-scratch-implementing-deepseek-trainer,
  author = {Puneet Mangla},
  title = {{DeepSeek-V3 from Scratch: Implementing the DeepSeek Trainer}},
  booktitle = {PyImageSearch},
  editor = {Susan Huot and Aditya Sharma and Piyush Thakur},
  year = {2026},
  url = {https://pyimg.co/u5mv8},
}
</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/10/12/deepseek-v3-from-scratch-implementing-the-deepseek-trainer/">DeepSeek-V3 from Scratch: Implementing the DeepSeek Trainer</a> appeared first on <a rel="nofollow" href="https://pyimagesearch.com">PyImageSearch</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>DeepSeek-V3 from Scratch: Building the Architecture in PyTorch</title>
		<link>https://pyimagesearch.com/2026/10/05/deepseek-v3-from-scratch-building-the-architecture-in-pytorch/</link>
		
		<dc:creator><![CDATA[Puneet Mangla]]></dc:creator>
		<pubDate>Mon, 05 Oct 2026 12:45:00 +0000</pubDate>
				<category><![CDATA[Deep Learning]]></category>
		<category><![CDATA[DeepSeek-V3 From Scratch]]></category>
		<category><![CDATA[LLMs]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[build llm from scratch]]></category>
		<category><![CDATA[deepseek v3]]></category>
		<category><![CDATA[llm architecture]]></category>
		<category><![CDATA[llm pretraining]]></category>
		<category><![CDATA[mixture of experts]]></category>
		<category><![CDATA[multi-head latent attention]]></category>
		<category><![CDATA[pytorch transformer]]></category>
		<category><![CDATA[rope positional encoding]]></category>
		<category><![CDATA[transformer architecture]]></category>
		<category><![CDATA[transformer block]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[weight tying]]></category>
		<guid isPermaLink="false">https://pyimagesearch.com/?p=55503</guid>

					<description><![CDATA[<p>Table of Contents DeepSeek-V3 from Scratch: Building the Architecture in PyTorch The Transformer Block: Combining MLA and MoE The Complete Model: From Tokens to Logits Weight Tying: Sharing Token Embeddings and Output Weights Multi-Token Prediction Integration Implementing the DeepSeek-V3 Architecture&#8230;</p>
<p>The post <a rel="nofollow" href="https://pyimagesearch.com/2026/10/05/deepseek-v3-from-scratch-building-the-architecture-in-pytorch/">DeepSeek-V3 from Scratch: Building the Architecture in PyTorch</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-DeepSeek-V3-from-Scratch-Building-the-Architecture-in-PyTorch"><a rel="noopener" target="_blank" href="#h1-DeepSeek-V3-from-Scratch-Building-the-Architecture-in-PyTorch">DeepSeek-V3 from Scratch: Building the Architecture in PyTorch</a></li>
    <li id="TOC-h2-The-Transformer-Block-Combining-MLA-and-MoE"><a rel="noopener" target="_blank" href="#h2-The-Transformer-Block-Combining-MLA-and-MoE">The Transformer Block: Combining MLA and MoE</a></li>
    <li id="TOC-h2-The-Complete-Model-From-Tokens-to-Logits"><a rel="noopener" target="_blank" href="#h2-The-Complete-Model-From-Tokens-to-Logits">The Complete Model: From Tokens to Logits</a></li>
    <li id="TOC-h2-Weight-Tying-Sharing-Token-Embeddings-and-Output-Weights"><a rel="noopener" target="_blank" href="#h2-Weight-Tying-Sharing-Token-Embeddings-and-Output-Weights">Weight Tying: Sharing Token Embeddings and Output Weights</a></li>
    <li id="TOC-h2-Multi-Token-Prediction-Integration"><a rel="noopener" target="_blank" href="#h2-Multi-Token-Prediction-Integration">Multi-Token Prediction Integration</a></li>
    <li id="TOC-h2-Implementing-the-DeepSeek-V3-Architecture-in-PyTorch"><a rel="noopener" target="_blank" href="#h2-Implementing-the-DeepSeek-V3-Architecture-in-PyTorch">Implementing the DeepSeek-V3 Architecture in PyTorch</a></li>
    <li id="TOC-h2-Architectural-Design-Patterns"><a rel="noopener" target="_blank" href="#h2-Architectural-Design-Patterns">Architectural Design Patterns</a></li>
    <li id="TOC-h2-Parameter-Count-Analysis"><a rel="noopener" target="_blank" href="#h2-Parameter-Count-Analysis">Parameter Count Analysis</a></li>
    <li id="TOC-h2-Memory-and-Computation-Footprint"><a rel="noopener" target="_blank" href="#h2-Memory-and-Computation-Footprint">Memory and Computation Footprint</a></li>
    <li id="TOC-h2-Summary"><a rel="noopener" target="_blank" href="#h2-Summary">Summary</a>
        <ul>
            <li id="TOC-h3-Citation-Information"><a rel="noopener" target="_blank" href="#h3-Citation-Information">Citation Information</a></li>
        </ul>
    </li>
</ul>
</div>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h1-DeepSeek-V3-from-Scratch-Building-the-Architecture-in-PyTorch"/>



<h2 class="wp-block-heading"><a href="#TOC-h1-DeepSeek-V3-from-Scratch-Building-the-Architecture-in-PyTorch">DeepSeek-V3 from Scratch: Building the Architecture in PyTorch</a></h2>



<p>Across the first 4 lessons, we have carefully constructed the building blocks of DeepSeek-V3: starting with its <strong>configuration and Rotary Position Embeddings (RoPE)</strong>, advancing through <strong>Multihead Latent Attention (MLA)</strong>, scaling capacity with the <strong>Mixture of Experts (MoE)</strong>, and using <strong>Multi-Token Prediction (MTP)</strong> to improve training efficiency and enable faster inference through speculative decoding. Each of these innovations has added a vital piece to the architecture, preparing us for the next major milestone: bringing everything together into a unified system.</p>


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


<p>In this lesson, we will focus on <strong>assembling the full DeepSeek-V3 architecture</strong>. This is where theory and implementation converge: integrating RoPE, MLA, MoE, and MTP into a cohesive model that reflects the design principles of DeepSeek-V3. We will walk through how these components interact, the structural choices that make them synergize effectively, and the practical considerations for building a scalable, efficient language model. By the end, you will have a complete architecture blueprint, ready for the final lesson in the series, where we will implement the DeepSeek trainer and bring the model to life through training.</p>



<p>This lesson is the 5th in the 6-part series on <strong>Building DeepSeek-V3 from Scratch</strong>:</p>



<ol class="wp-block-list">
<li><em><strong><a href="https://pyimg.co/1atre" target="_blank" rel="noreferrer noopener">DeepSeek-V3 Model: Theory, Config, and Rotary Positional Embeddings</a></strong></em></li>



<li><em><strong><a href="https://pyimg.co/scgjl" target="_blank" rel="noreferrer noopener">Build DeepSeek-V3: Multi-Head Latent Attention (MLA) Architecture</a></strong></em></li>



<li><em><strong><a href="https://pyimg.co/a1w0g" target="_blank" rel="noreferrer noopener">DeepSeek-V3 from Scratch: Mixture of Experts (MoE)</a></strong></em></li>



<li><em><strong><a href="https://pyimg.co/alrep" target="_blank" rel="noreferrer noopener">Autoregressive Model Limits and Multi-Token Prediction in DeepSeek-V3</a></strong></em></li>



<li><em><strong><a href="https://pyimg.co/36gvk" target="_blank" rel="noreferrer noopener">DeepSeek-V3 from Scratch: Building the Architecture in PyTorch</a></strong></em> <strong>(this tutorial)</strong></li>



<li><em>Lesson 6</em></li>
</ol>



<p><strong>To learn about DeepSeek-V3 and build it from scratch, </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-The-Transformer-Block-Combining-MLA-and-MoE"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-The-Transformer-Block-Combining-MLA-and-MoE">The Transformer Block: Combining MLA and MoE</a></h2>



<p>Now that we have our sophisticated components, we need to integrate them into the classic transformer architecture. A DeepSeek transformer block follows the pre-norm residual pattern:</p>



<p class="has-text-align-center"><img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/b9d/b9d172f818ff41c5dd5e7ba7613171f7-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='x&#039; = x + \text{MLA}(\text{LayerNorm}(x))' title='x&#039; = x + \text{MLA}(\text{LayerNorm}(x))' class='latex' srcset='https://b2633864.assetcdn.net/2633864/wp-content/latex/b9d/b9d172f818ff41c5dd5e7ba7613171f7-ffffff-000000-0.png?lossy=2&strip=1&webp=1 213w,https://b2633864.assetcdn.net/2633864/wp-content/latex/b9d/b9d172f818ff41c5dd5e7ba7613171f7-ffffff-000000-0.png?size=126x11&lossy=2&strip=1&webp=1 126w' sizes='(max-width: 213px) 100vw, 213px' /></p>



<p class="has-text-align-center"><img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/b87/b87d922fc3c32ec319bc59b4c6a4e6ba-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='x&#039;&#039; = x&#039; + \text{MoE}(\text{LayerNorm}(x&#039;))' title='x&#039;&#039; = x&#039; + \text{MoE}(\text{LayerNorm}(x&#039;))' class='latex' srcset='https://b2633864.assetcdn.net/2633864/wp-content/latex/b87/b87d922fc3c32ec319bc59b4c6a4e6ba-ffffff-000000-0.png?lossy=2&strip=1&webp=1 222w,https://b2633864.assetcdn.net/2633864/wp-content/latex/b87/b87d922fc3c32ec319bc59b4c6a4e6ba-ffffff-000000-0.png?size=126x10&lossy=2&strip=1&webp=1 126w' sizes='(max-width: 222px) 100vw, 222px' /></p>



<p>This is the pre-layer normalization (Pre-LN) variant used in modern transformers. The residual connections allow gradients to flow directly through the network during backpropagation, addressing the vanishing gradient problem in deep networks. The layer norms stabilize the activations before they enter the attention or MoE layers.</p>



<p>Mathematically, each block implements a function </p>



<p class="has-text-align-center"><img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/9f1/9f1da87031398b085fdd6dca27db3ac8-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='f_\ell: \mathbb{R}^{T \times d_\text{model}} \to \mathbb{R}^{T \times d_\text{model}}' title='f_\ell: \mathbb{R}^{T \times d_\text{model}} \to \mathbb{R}^{T \times d_\text{model}}' class='latex' srcset='https://b2633864.assetcdn.net/2633864/wp-content/latex/9f1/9f1da87031398b085fdd6dca27db3ac8-ffffff-000000-0.png?lossy=2&strip=1&webp=1 180w,https://b2633864.assetcdn.net/2633864/wp-content/latex/9f1/9f1da87031398b085fdd6dca27db3ac8-ffffff-000000-0.png?size=126x12&lossy=2&strip=1&webp=1 126w' sizes='(max-width: 180px) 100vw, 180px' /> </p>



<p>where <img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/ee5/ee5e5c003694e7cd5ae404923c665edb-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='\ell' title='\ell' class='latex' /> is the layer index. The full model is a composition of <img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/d20/d20caec3b48a1eef164cb4ca81ba2587-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='L' title='L' class='latex' /> such blocks:</p>



<p class="has-text-align-center"><img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/d65/d6546755c73aeea158ce750d55d05d83-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='h^{(L)} = f_L \circ f_{L-1} \circ \cdots \circ f_1(x^{(0)})' title='h^{(L)} = f_L \circ f_{L-1} \circ \cdots \circ f_1(x^{(0)})' class='latex' srcset='https://b2633864.assetcdn.net/2633864/wp-content/latex/d65/d6546755c73aeea158ce750d55d05d83-ffffff-000000-0.png?lossy=2&strip=1&webp=1 215w,https://b2633864.assetcdn.net/2633864/wp-content/latex/d65/d6546755c73aeea158ce750d55d05d83-ffffff-000000-0.png?size=126x11&lossy=2&strip=1&webp=1 126w' sizes='(max-width: 215px) 100vw, 215px' /></p>



<p>where <img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/c93/c9334e5292986f3a604733dabe18bbc3-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='x^{(0)}' title='x^{(0)}' class='latex' /> denotes the sum of the token and position embeddings. Each layer refines the representations, with early layers typically learning syntax and surface patterns while deeper layers learn semantics and abstract concepts.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-The-Complete-Model-From-Tokens-to-Logits"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-The-Complete-Model-From-Tokens-to-Logits">The Complete Model: From Tokens to Logits</a></h2>



<p>The full DeepSeek model architecture (<strong>Figure 1</strong>) consists of:</p>



<ul class="wp-block-list">
<li><strong>Token Embedding:</strong> <img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/f28/f285b4b69bbda347d6e7f35a7768832a-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='E_\text{tok} \in \mathbb{R}^{V \times d_\text{model}}' title='E_\text{tok} \in \mathbb{R}^{V \times d_\text{model}}' class='latex' /> maps token identifiers (IDs) to dense vectors</li>



<li><strong>Position Embedding:</strong> <img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/fbb/fbb1b7fbf86a398acaf7696be03b8cf9-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='E_\text{pos} \in \mathbb{R}^{T_\text{max} \times d_\text{model}}' title='E_\text{pos} \in \mathbb{R}^{T_\text{max} \times d_\text{model}}' class='latex' /> provides positional information</li>



<li><strong>Input Dropout:</strong> Regularization applied to embedded representations</li>



<li><strong>Transformer Blocks:</strong> <img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/d20/d20caec3b48a1eef164cb4ca81ba2587-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='L' title='L' class='latex' /> blocks combining MLA and MoE with layer normalization </li>



<li><strong>Final Layer Norm:</strong> Stabilizes representations before output projection</li>



<li><strong>Language Modeling Head:</strong> Projects to the vocabulary: <img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/731/731e43f327bb6446f390555565743c41-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='W_\text{lm} \in \mathbb{R}^{d_\text{model} \times V}' title='W_\text{lm} \in \mathbb{R}^{d_\text{model} \times V}' class='latex' /></li>



<li><strong>Multi-Token Prediction Heads:</strong> Optional heads for future token prediction</li>
</ul>



<p>The forward pass computes:</p>



<p class="has-text-align-center"><img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/855/8554cb0c7a829186a783b695b95291a0-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='x^{(0)} = \text{Dropout}(E_\text{tok}[x] + E_\text{pos}[1:T])' title='x^{(0)} = \text{Dropout}(E_\text{tok}[x] + E_\text{pos}[1:T])' class='latex' srcset='https://b2633864.assetcdn.net/2633864/wp-content/latex/855/8554cb0c7a829186a783b695b95291a0-ffffff-000000-0.png?lossy=2&strip=1&webp=1 259w,https://b2633864.assetcdn.net/2633864/wp-content/latex/855/8554cb0c7a829186a783b695b95291a0-ffffff-000000-0.png?size=126x9&lossy=2&strip=1&webp=1 126w' sizes='(max-width: 259px) 100vw, 259px' /></p>



<p class="has-text-align-center"><img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/b1c/b1c5675b7dc5753d55ce4dda1250545e-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='x^{(\ell)} = f_\ell(x^{(\ell-1)}) \text{ for } \ell = 1, \ldots, L' title='x^{(\ell)} = f_\ell(x^{(\ell-1)}) \text{ for } \ell = 1, \ldots, L' class='latex' srcset='https://b2633864.assetcdn.net/2633864/wp-content/latex/b1c/b1c5675b7dc5753d55ce4dda1250545e-ffffff-000000-0.png?lossy=2&strip=1&webp=1 225w,https://b2633864.assetcdn.net/2633864/wp-content/latex/b1c/b1c5675b7dc5753d55ce4dda1250545e-ffffff-000000-0.png?size=126x10&lossy=2&strip=1&webp=1 126w' sizes='(max-width: 225px) 100vw, 225px' /></p>



<p class="has-text-align-center"><img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/b92/b92510659f621106beb4b81d4fc02ff9-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='h = \text{LayerNorm}(x^{(L)})' title='h = \text{LayerNorm}(x^{(L)})' class='latex' /></p>



<p class="has-text-align-center"><img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/38d/38ddc9f197d757e1ab3815984672e726-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='\text{logits} = h W_\text{lm}' title='\text{logits} = h W_\text{lm}' class='latex' /></p>



<p>where <img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/9dd/9dd4e461268c8034f5c8564e155c67a6-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='x' title='x' class='latex' /> contains the token indices and <img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/89e/89ed64319628a90c369a25cefc664a39-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='1:T' title='1:T' class='latex' /> denotes the position indices.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://pyimagesearch.com/wp-content/uploads/2026/10/image-1.jpeg" target="_blank" rel=" noreferrer noopener"><img decoding="async" width="975" height="780" src="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-1.jpeg?lossy=2&strip=1&webp=1" alt="" class="wp-image-55518"   srcset="https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-1.jpeg?size=126x101&lossy=2&strip=1&webp=1 126w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-1-300x240.jpeg?lossy=2&strip=1&webp=1 300w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-1.jpeg?size=378x302&lossy=2&strip=1&webp=1 378w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-1.jpeg?size=504x403&lossy=2&strip=1&webp=1 504w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-1.jpeg?size=630x504&lossy=2&strip=1&webp=1 630w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-1-768x614.jpeg?lossy=2&strip=1&webp=1 768w, https://b2633864.assetcdn.net/2633864/wp-content/uploads/2026/10/image-1.jpeg?lossy=2&strip=1&webp=1 975w" sizes="(max-width: 975px) 100vw, 975px" /></a><figcaption class="wp-element-caption"><strong>Figure 1:</strong> DeepSeek-V3 (source: <a href="https://arxiv.org/pdf/2412.19437" target="_blank" rel="noreferrer noopener">DeepSeek</a>).</figcaption></figure></div>


<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Weight-Tying-Sharing-Token-Embeddings-and-Output-Weights"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Weight-Tying-Sharing-Token-Embeddings-and-Output-Weights">Weight Tying: Sharing Token Embeddings and Output Weights</a></h2>



<p>An important optimization is weight tying between the token embedding matrix and the language modeling head:</p>



<p class="has-text-align-center"><img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/2ff/2ffda86dc23ed5cc2e2b2c571fa22f9c-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='W_\text{lm} = E_\text{tok}^T ' title='W_\text{lm} = E_\text{tok}^T ' class='latex' /></p>



<p>This reduces parameters significantly (for our vocabulary of 50,259 and embedding dimension of 256, we save approximately 12.9 million  parameters) and often improves performance. The intuition is elegant: if token <img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/865/865c0c0b4ab0e063e5caa3387c1a8741-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='i' title='i' class='latex' /> has embedding vector <img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/8de/8dec559e201a7b6a0f99baeaa1731051-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='e_i' title='e_i' class='latex' />, then the similarity <img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/806/806221033c07e199cdb2dcbf7f3b68d1-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='h^T e_i' title='h^T e_i' class='latex' /> measures how much the hidden representation <img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/251/2510c39011c5be704182423e3a695e91-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='h' title='h' class='latex' /> aligns with token <img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/865/865c0c0b4ab0e063e5caa3387c1a8741-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='i' title='i' class='latex' />. This is exactly what we want for predicting that token.</p>



<p>Mathematically, weight tying implements a form of parameter sharing that encourages the input and output spaces to be aligned. The embedding space becomes jointly optimized for both encoding tokens into context and decoding context into tokens.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Multi-Token-Prediction-Integration"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Multi-Token-Prediction-Integration">Multi-Token Prediction Integration</a></h2>



<p>During training, after computing the main hidden states <img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/2d4/2d4bc958696ca51262cd6f8009c4e85a-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='h \in \mathbb{R}^{T \times d_\text{model}}' title='h \in \mathbb{R}^{T \times d_\text{model}}' class='latex' />, we process them through MTP heads:</p>



<p class="has-text-align-center"><img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/27b/27b0ea132a2d722124f05eb47f632adc-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='h^{(1)} = \text{MTPHead}_1(h, E_\text{tok}[x_{1:T}])' title='h^{(1)} = \text{MTPHead}_1(h, E_\text{tok}[x_{1:T}])' class='latex' srcset='https://b2633864.assetcdn.net/2633864/wp-content/latex/27b/27b0ea132a2d722124f05eb47f632adc-ffffff-000000-0.png?lossy=2&strip=1&webp=1 222w,https://b2633864.assetcdn.net/2633864/wp-content/latex/27b/27b0ea132a2d722124f05eb47f632adc-ffffff-000000-0.png?size=126x11&lossy=2&strip=1&webp=1 126w' sizes='(max-width: 222px) 100vw, 222px' /></p>



<p class="has-text-align-center"><img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/e3c/e3c8409664b8b66d78fb1ee4e6b47cc6-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='\text{logits}^{(1)} = h^{(1)} W_\text{lm}' title='\text{logits}^{(1)} = h^{(1)} W_\text{lm}' class='latex' /></p>



<p class="has-text-align-center"><img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/84d/84da427a107137a7633369960bda0d85-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='h^{(2)} = \text{MTPHead}_2(h^{(1)}, E_\text{tok}[x_{2:T+1}])' title='h^{(2)} = \text{MTPHead}_2(h^{(1)}, E_\text{tok}[x_{2:T+1}])' class='latex' srcset='https://b2633864.assetcdn.net/2633864/wp-content/latex/84d/84da427a107137a7633369960bda0d85-ffffff-000000-0.png?lossy=2&strip=1&webp=1 253w,https://b2633864.assetcdn.net/2633864/wp-content/latex/84d/84da427a107137a7633369960bda0d85-ffffff-000000-0.png?size=126x9&lossy=2&strip=1&webp=1 126w' sizes='(max-width: 253px) 100vw, 253px' /></p>



<p class="has-text-align-center"><img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/040/040a7c74b253852692d3d0bb9daaf7a1-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='\text{logits}^{(2)} = h^{(2)} W_\text{lm}' title='\text{logits}^{(2)} = h^{(2)} W_\text{lm}' class='latex' /></p>



<p>Each head takes the previous layer’s output and the embedding of the next actual token (ground truth during training), processes them through its mini-transformer, and projects the result to the vocabulary. We compute losses for all predictions and combine them:</p>



<p class="has-text-align-center"><img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/8cf/8cf3e28fb0a5b6e06a3f8a1416365319-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='\mathcal{L} = \mathcal{L}_\text{main}(x_{1:T}, \text{logits}) + \sum_{d=1}^{n} \lambda_d \mathcal{L}_d(x_{d+1:T+d}, \text{logits}^{(d)}) + \alpha \mathcal{L}_\text{aux}' title='\mathcal{L} = \mathcal{L}_\text{main}(x_{1:T}, \text{logits}) + \sum_{d=1}^{n} \lambda_d \mathcal{L}_d(x_{d+1:T+d}, \text{logits}^{(d)}) + \alpha \mathcal{L}_\text{aux}' class='latex' srcset='https://b2633864.assetcdn.net/2633864/wp-content/latex/8cf/8cf3e28fb0a5b6e06a3f8a1416365319-ffffff-000000-0.png?lossy=2&strip=1&webp=1 446w,https://b2633864.assetcdn.net/2633864/wp-content/latex/8cf/8cf3e28fb0a5b6e06a3f8a1416365319-ffffff-000000-0.png?size=126x6&lossy=2&strip=1&webp=1 126w,https://b2633864.assetcdn.net/2633864/wp-content/latex/8cf/8cf3e28fb0a5b6e06a3f8a1416365319-ffffff-000000-0.png?size=252x12&lossy=2&strip=1&webp=1 252w,https://b2633864.assetcdn.net/2633864/wp-content/latex/8cf/8cf3e28fb0a5b6e06a3f8a1416365319-ffffff-000000-0.png?size=378x18&lossy=2&strip=1&webp=1 378w' sizes='(max-width: 446px) 100vw, 446px' /></p>



<p>where <img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/422/4221be08a7ea42d51d83e726cf2afcc1-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='\mathcal{L}_\text{main}' title='\mathcal{L}_\text{main}' class='latex' /> and <img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/11f/11fd3d3d1169d3e667cbcbc4c5e655ab-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='\mathcal{L}_d' title='\mathcal{L}_d' class='latex' /> are cross-entropy losses, <img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/a5f/a5faa41fc217dda8dfbe1d81c2c19f42-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='\lambda_d' title='\lambda_d' class='latex' /> are MTP weights, and <img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/0ba/0ba1464e07fdf7cfc65384f9c918262f-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='\mathcal{L}_\text{aux}' title='\mathcal{L}_\text{aux}' class='latex' /> is the MoE load-balancing loss with coefficient <img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/7b7/7b7f9dbfea05c83784f8b85149852f08-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='\alpha' title='\alpha' class='latex' />.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Implementing-the-DeepSeek-V3-Architecture-in-PyTorch"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Implementing-the-DeepSeek-V3-Architecture-in-PyTorch">Implementing the DeepSeek-V3 Architecture in PyTorch</a></h2>



<p>Let us implement the full architecture:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="DeepSeek-V3 from Scratch: Building the Architecture in PyTorch" data-enlighter-group="1">class DeepSeekBlock(nn.Module):
    """DeepSeek transformer block with MLA and MoE"""

    def __init__(self, config: DeepSeekConfig):
        super().__init__()
        self.config = config

        # Layer norms (pre-norm architecture)
        self.ln1 = nn.LayerNorm(config.n_embd, bias=config.bias)
        self.ln2 = nn.LayerNorm(config.n_embd, bias=config.bias)

        # Attention - MLA
        self.attn = MultiheadLatentAttention(config)

        # MoE feedforward
        self.moe = MixtureOfExperts(config)

</pre>



<p><strong>Lines 1-16: Block Structure:</strong> The <code data-enlighter-language="python" class="EnlighterJSRAW">DeepSeekBlock</code> class encapsulates a single transformer layer. We use 2 layer norms (<code data-enlighter-language="python" class="EnlighterJSRAW">ln1</code> and <code data-enlighter-language="python" class="EnlighterJSRAW">ln2</code>) for the pre-norm architecture, which normalizes inputs before they enter the attention and feedforward (MoE) sublayers. This has proven more stable for training than post-norm architectures. The block contains our custom MLA mechanism and MoE feedforward layer, both of which we have already implemented.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="18" data-enlighter-title="DeepSeek-V3 from Scratch: Building the Architecture in PyTorch" data-enlighter-group="2">    def forward(self, x: torch.Tensor, attention_mask: Optional[torch.Tensor] = None):
        # Attention with residual connection
        x = x + self.attn(self.ln1(x), attention_mask)

        # MoE with residual connection
        moe_output, router_logits  = self.moe(self.ln2(x))
        x = x + moe_output
        return x, router_logits

</pre>



<p><strong>Lines 18-25: Forward Pass with Residual Connections:</strong> The forward method implements the classic &#8220;attention then feedforward&#8221; pattern with residual connections. First, we normalize the input, pass it through attention, and add it back to the original input (residual connection). Then we normalize again, pass through MoE, and add another residual. Importantly, we return both the output and <code data-enlighter-language="python" class="EnlighterJSRAW">router_logits</code> from MoE. These router logits are needed for computing auxiliary losses during training. The residual connections are crucial: they allow gradients to flow directly through the network, helping mitigate vanishing gradients in deep models.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="27" data-enlighter-title="DeepSeek-V3 from Scratch: Building the Architecture in PyTorch" data-enlighter-group="3">class DeepSeek(nn.Module):
    """Complete DeepSeek model for children's story generation"""

    def __init__(self, config: DeepSeekConfig):
        super().__init__()
        assert isinstance(config, DeepSeekConfig)
        self.config = config

        # Embeddings and transformer blocks
        self.transformer = nn.ModuleDict(dict(
            wte=nn.Embedding(config.vocab_size, config.n_embd),
            wpe=nn.Embedding(config.block_size, config.n_embd),
            drop=nn.Dropout(config.dropout),
            h=nn.ModuleList([DeepSeekBlock(config) for _ in range(config.n_layer)]),
            ln_f=nn.LayerNorm(config.n_embd, bias=config.bias),
        ))

        # Output heads
        self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)

        # Multi-Token Prediction heads
        if config.multi_token_predict > 0:
            self.mtp_heads = nn.ModuleList([
                MultiTokenPredictionHead(config, depth)
                for depth in range(1, config.multi_token_predict + 1)
            ])
        else:
            self.mtp_heads = None

        # Weight tying (share embeddings and output projection)
        self.transformer.wte.weight = self.lm_head.weight

        # Initialize weights
        self.apply(self._init_weights)

        # Special initialization for residual projections
        for pn, p in self.named_parameters():
            if pn.endswith(('o_proj.weight', 'down_proj.weight')):
                nn.init.normal_(p, mean=0.0, std=0.02 / math.sqrt(2 * config.n_layer))
</pre>



<p><strong>Lines 27-42: Model Initialization:</strong> The <code data-enlighter-language="python" class="EnlighterJSRAW">DeepSeek</code> class constructor sets up the complete model architecture. We use an <code data-enlighter-language="python" class="EnlighterJSRAW">nn.ModuleDict</code> to organize the transformer components: <code data-enlighter-language="python" class="EnlighterJSRAW">wte</code> for token embeddings, <code data-enlighter-language="python" class="EnlighterJSRAW">wpe</code> for positional embeddings, <code data-enlighter-language="python" class="EnlighterJSRAW">drop</code> for input dropout, <code data-enlighter-language="python" class="EnlighterJSRAW">h</code> as a list of transformer blocks, and <code data-enlighter-language="python" class="EnlighterJSRAW">ln_f</code> for the final layer norm. This organization makes the model structure clear and allows easy access to each component.</p>



<p><strong>Lines </strong><strong>45-</strong><strong>57</strong><strong>: Output Heads and Weight Tying:</strong> We create the language modeling head (<code data-enlighter-language="python" class="EnlighterJSRAW">lm_head</code>) that projects from the hidden dimension to the vocabulary size. If multi-token prediction is enabled, we create a list of MTP heads, one for each future depth. The crucial line <code data-enlighter-language="python" class="EnlighterJSRAW">self.transformer.wte.weight = self.lm_head.weight</code> implements weight tying: the same weight matrix is used for both embedding tokens and predicting them. This reduces parameters and improves training. </p>



<p><strong>Lines 62-65: </strong><strong>Special Initialization for Residual Projections:</strong> The special initialization targets 2 types of output projections that feed into residual additions: <code data-enlighter-language="python" class="EnlighterJSRAW">o_proj</code> in Multihead Latent Attention and <code data-enlighter-language="python" class="EnlighterJSRAW">down_proj</code> in each SwiGLU expert. It scales their initialization by <img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/bb6/bb6e5d225a6ac3f707d73f8a3436b0e9-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='1/\sqrt{2L}' title='1/\sqrt{2L}' class='latex' /> to account for the accumulation of residual connections through <img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/d20/d20caec3b48a1eef164cb4ca81ba2587-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='L' title='L' class='latex' /> layers, helping prevent activation explosion.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="66" data-enlighter-title="DeepSeek-V3 from Scratch: Building the Architecture in PyTorch" data-enlighter-group="4">def _init_weights(self, module):
        """Initialize model weights"""
        if isinstance(module, nn.Linear):
            nn.init.normal_(module.weight, mean=0.0, std=0.02)
            if module.bias is not None:
                nn.init.zeros_(module.bias)
        elif isinstance(module, nn.Embedding):
            nn.init.normal_(module.weight, mean=0.0, std=0.02)
        elif isinstance(module, nn.LayerNorm):
            nn.init.ones_(module.weight)
            if module.bias is not None:
                nn.init.zeros_(module.bias)

</pre>



<p><strong>Lines 66-77: Weight Initialization:</strong> The <code data-enlighter-language="python" class="EnlighterJSRAW">_init_weights</code> method implements careful initialization following best practices. Linear layers and embeddings use normal initialization with a standard deviation of <code data-enlighter-language="python" class="EnlighterJSRAW">0.02</code>. Layer normalization weights are initialized to <code data-enlighter-language="python" class="EnlighterJSRAW">1</code>, and their biases are initialized to <code data-enlighter-language="python" class="EnlighterJSRAW">0</code> when present. </p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="79" data-enlighter-title="DeepSeek-V3 from Scratch: Building the Architecture in PyTorch" data-enlighter-group="5">       def forward(self, input_ids: torch.Tensor, targets: Optional[torch.Tensor] = None, attention_mask: Optional[torch.Tensor] = None, **kwargs):
        """Forward pass with Multi-Token Prediction

        Main prediction: h[i] predicts token[i+1]
        MTP heads: Each depth d predicts token[i+d+1] using h[i] and embed[i+d]
        """
        device = input_ids.device
        batch_size, seq_len = input_ids.size()
        assert seq_len &lt;= self.config.block_size

        # Get embeddings
        pos = torch.arange(0, seq_len, dtype=torch.long, device=device)
        tok_emb = self.transformer.wte(input_ids)
        pos_emb = self.transformer.wpe(pos)
        x = self.transformer.drop(tok_emb + pos_emb)
       
        # Forward through transformer blocks
        router_logits_list = []
        for block in self.transformer.h:
            x, router_logits = block(x, attention_mask=attention_mask)
            router_logits_list.append(router_logits)

        # Final layer norm
        x = self.transformer.ln_f(x)  # [B, seq_len, n_embd]
 
</pre>



<p><strong>Lines 79-102: Forward Pass &#8211; Embeddings and Blocks:</strong> The forward method implements the complete forward pass. We first get token and position embeddings, sum them, and apply dropout. Then we iterate through all transformer blocks, collecting router logits from each MoE layer (needed for auxiliary losses). Finally, we apply the final layer norm. The hidden states <code data-enlighter-language="python" class="EnlighterJSRAW">x</code> now encode the full context for each position. The forward signature also accepts an optional <code data-enlighter-language="python" class="EnlighterJSRAW">attention_mask</code> of shape <code data-enlighter-language="python" class="EnlighterJSRAW">[B, T]</code>, which marks real tokens with <code data-enlighter-language="python" class="EnlighterJSRAW">1</code> and padding with <code data-enlighter-language="python" class="EnlighterJSRAW">0</code>. Here, <code data-enlighter-language="python" class="EnlighterJSRAW">B</code> is the batch size and <code data-enlighter-language="python" class="EnlighterJSRAW">T</code> is the sequence length. We thread this mask down into every transformer block so that Multihead Latent Attention can exclude padded key positions from its attention scores.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="104" data-enlighter-title="DeepSeek-V3 from Scratch: Building the Architecture in PyTorch" data-enlighter-group="6">        # Main language modeling head
        main_logits = self.lm_head(x)
        main_loss = None

        if targets is not None:
            # Compute main loss (standard next-token prediction)
            # Shift: h[i] predicts target[i+1]
            # main_logits[:, :-1, :] are predictions from h[0] to h[seq_len-2]
            # targets[:, 1:] are actual tokens at positions [1] to [seq_len-1]
            shift_logits = main_logits[:, :-1, :].contiguous()  # [B, seq_len-1, vocab_size]
            shift_targets = targets[:, 1:].contiguous()     # [B, seq_len-1]

            main_loss = F.cross_entropy(
                    shift_logits.view(-1, shift_logits.size(-1)),
                    shift_targets.view(-1),
                    ignore_index=-100
                )

</pre>



<p><strong>Lines 105-120: Main Loss Computation:</strong> For training (when targets are provided), we compute the standard language modeling loss. We shift logits and targets by 1 position because we are predicting the next token: <code data-enlighter-language="python" class="EnlighterJSRAW">main_logits[:, i]</code> should predict <code data-enlighter-language="python" class="EnlighterJSRAW">targets[:, i+1]</code>. The cross-entropy loss with <code data-enlighter-language="python" class="EnlighterJSRAW">ignore_index=-100</code> excludes target positions labeled <code data-enlighter-language="python" class="EnlighterJSRAW">-100</code>, including padding positions if they use that label. This is the base training objective.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="122" data-enlighter-title="DeepSeek-V3 from Scratch: Building the Architecture in PyTorch" data-enlighter-group="7">             # Multi-Token Prediction
            mtp_loss = None
            if self.mtp_heads is not None:
                mtp_losses = []
                current_hidden = x

                for depth, mtp_head in enumerate(self.mtp_heads, 1):
                    # Check if we have enough future tokens
                    if seq_len > depth:
                        # Get future token embeddings
                        future_indices = input_ids[:, depth:]
                        future_embeds = self.transformer.wte(future_indices)

                        # Pad or truncate to match current_hidden sequence length
                        if future_embeds.size(1) &lt; current_hidden.size(1):
                            pad_size = current_hidden.size(1) - future_embeds.size(1)
                            padding = torch.zeros(
                                batch_size, pad_size, self.config.n_embd,
                                device=device, dtype=future_embeds.dtype
                            )
                            future_embeds = torch.cat([future_embeds, padding], dim=1)
                        elif future_embeds.size(1) > current_hidden.size(1):
                            future_embeds = future_embeds[:, :current_hidden.size(1)]

                        # Process through MTP head
                        current_hidden = mtp_head(current_hidden, future_embeds, attention_mask=attention_mask)
                        mtp_logits = self.lm_head(current_hidden)

                        # Compute loss for this depth
                        # mtp_logits[:, i] predicts target[i + depth + 1]
                        if seq_len > depth + 1:
                            shift_logits = mtp_logits[:, :-(depth+1), :].contiguous()
                            shift_labels = targets[:, depth+1:].contiguous()

                            if shift_labels.numel() > 0:
                                mtp_loss_single = F.cross_entropy(
                                    shift_logits.view(-1, shift_logits.size(-1)),
                                    shift_labels.view(-1),
                                    ignore_index=-100
                                )
                                mtp_losses.append(mtp_loss_single)

                # Average MTP losses
                if mtp_losses:
                    mtp_loss = torch.stack(mtp_losses).mean()
</pre>



<p><strong>Lines 123-166: Multi-Token Prediction:</strong> If MTP heads exist, we compute additional losses for future token prediction. For each depth, we get embeddings of the future tokens, process them through the MTP head combined with current hidden states, and compute predictions. The key insight: each MTP head receives both the context (via <code data-enlighter-language="python" class="EnlighterJSRAW">current_hidden</code>) and embeddings of future ground-truth tokens (via <code data-enlighter-language="python" class="EnlighterJSRAW">future_embeds</code>). We carefully handle sequence length issues by padding or truncating, and we pass the <code data-enlighter-language="python" class="EnlighterJSRAW">attention_mask</code> into each MTP head, since every head runs its own mini-transformer (MLA and MoE) and must ignore padded positions for the same reason the main blocks do. All MTP losses are averaged and weighted by 0.3 relative to the main loss.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="167" data-enlighter-title="DeepSeek-V3 from Scratch: Building the Architecture in PyTorch" data-enlighter-group="8">            # Add MoE auxiliary loss
            aux_loss = 0.0
            if router_logits_list:
                for i, block in enumerate(self.transformer.h):
                    aux_loss += block.moe._complementary_sequence_aux_loss(router_logits_list[i], seq_mask=attention_mask)
                aux_loss = aux_loss / len(router_logits_list)

            # Combine losses
            total_loss = main_loss
            if mtp_loss is not None:
                total_loss = total_loss + 0.3 * mtp_loss  # Weight MTP loss
           
            total_loss = total_loss + self.config.aux_loss_weight * aux_loss

            return main_logits, total_loss
        else:
            # Inference mode
            logits = self.lm_head(x[:, [-1], :])
            return logits, None
</pre>



<p><strong>Lines 167-181: Auxiliary Loss and Combination:</strong> We compute the complementary sequence-wise auxiliary loss from all MoE layers and average across layers. This encourages load balancing among experts. We pass <code data-enlighter-language="python" class="EnlighterJSRAW">seq_mask=attention_mask</code> so that padded positions are excluded when measuring expert load; without it, padding would be counted as real tokens and would skew the balancing signal toward whichever experts happen to absorb it. The total loss combines the main prediction loss, MTP loss (if enabled), and auxiliary loss (weighted by <code data-enlighter-language="python" class="EnlighterJSRAW">self.config.aux_loss_weight</code>). This multi-objective training improves model quality while maintaining computational efficiency.</p>



<p><strong>Lines 184</strong><strong> and </strong><strong>185: Inference Mode:</strong> When no targets are provided (inference), we simply compute logits for the last position and return them. This is used during generation when we predict 1 token at a time. No MTP heads are used during inference. They have already served their purpose in improving training.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="186" data-enlighter-title="DeepSeek-V3 from Scratch: Building the Architecture in PyTorch" data-enlighter-group="9">    @torch.no_grad()
    def generate(self, input_ids: torch.Tensor, max_new_tokens: int = 100,
                 temperature: float = 1.0, top_k: Optional[int] = None):
        """Generate text autoregressively"""
        for _ in range(max_new_tokens):
            # Crop to context window
            idx_cond = input_ids if input_ids.size(1) &lt;= self.config.block_size else input_ids[:, -self.config.block_size:]

            # Forward pass (no targets, so inference mode)
            logits, _ = self(idx_cond)  # [B, 1, vocab_size]
            logits = logits[:, -1, :] / temperature  # [B, vocab_size]

            # Apply top-k filtering
            if top_k is not None:
                v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
                logits[logits &lt; v[:, [-1]]] = -float('Inf')

            # Sample next token
            probs = F.softmax(logits, dim=-1)
            idx_next = torch.multinomial(probs, num_samples=1)  # [B, 1]
            input_ids = torch.cat((input_ids, idx_next), dim=1)

        return input_ids
</pre>



<p><strong>Lines 186-208: Autoregressive Generation:</strong> The <code data-enlighter-language="python" class="EnlighterJSRAW">generate</code> method implements text generation. For each new token, we crop the input to the context window (if it has grown too large), compute logits, apply temperature scaling and top-k filtering, sample from the distribution, and append to the input. This continues for <code data-enlighter-language="python" class="EnlighterJSRAW">max_new_tokens</code> iterations. Temperature controls randomness (lower values make sampling more deterministic), while top-k prevents sampling very unlikely tokens that might break coherence.</p>



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



<h2 class="wp-block-heading"><a href="#TOC-h2-Architectural-Design-Patterns">Architectural Design Patterns</a></h2>



<p>Several design patterns in our architecture are worth highlighting:</p>



<p><strong>Pre-Norm vs Post-Norm:</strong> We use pre-normalization (normalization before the sublayer) rather than post-normalization (normalization after the sublayer). Research has shown pre-norm is more stable for training deep networks, though post-norm can sometimes achieve slightly better performance if training succeeds. The stability-performance tradeoff generally favors pre-norm for modern large models.</p>



<p><strong>Residual Connection Placement:</strong> Every sublayer (attention, MoE) has a residual connection. This is crucial for gradient flow in deep networks. Without residuals, gradients would have to flow through many sequential transformations, leading to vanishing or exploding gradients. With residuals, gradients have a direct path to earlier layers.</p>



<p><strong>Dropout Placement:</strong> We apply dropout in 3 places: input embeddings, within attention and MoE sublayers (implemented in those modules), and in MTP heads. This multi-level dropout provides regularization at different stages of computation. Too much dropout can hurt performance; too little can cause overfitting. Our 0.1 rate is moderate.</p>



<p><strong>Weight Tying:</strong> Sharing weights between embeddings and output projection is an elegant constraint that reduces parameters and often helps. The theoretical justification is that both mappings operate in the same semantic space: the space of token meanings.</p>



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



<h2 class="wp-block-heading"><a href="#TOC-h2-Parameter-Count-Analysis">Parameter Count Analysis</a></h2>



<p>Let us analyze where parameters are allocated:</p>



<ul class="wp-block-list">
<li><strong>Embeddings:</strong> <img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/42b/42b2ed8bf5211b22e74c30a78ceb3944-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='V \times d_\text{model} = 50259 \times 256 \approx 12.9\text{ million}' title='V \times d_\text{model} = 50259 \times 256 \approx 12.9\text{ million}' class='latex' srcset='https://b2633864.assetcdn.net/2633864/wp-content/latex/42b/42b2ed8bf5211b22e74c30a78ceb3944-ffffff-000000-0.png?lossy=2&strip=1&webp=1 287w,https://b2633864.assetcdn.net/2633864/wp-content/latex/42b/42b2ed8bf5211b22e74c30a78ceb3944-ffffff-000000-0.png?size=126x7&lossy=2&strip=1&webp=1 126w' sizes='(max-width: 287px) 100vw, 287px' /> parameters</li>



<li><strong>Position Embeddings:</strong> <img src='https://b2633864.assetcdn.net/2633864/wp-content/latex/6c4/6c4429cd36402745ca88b129c0d519fc-ffffff-000000-0.png?lossy=2&strip=1&webp=1' alt='T_\text{max} \times d_\text{model} = 1024 \times 256 \approx 0.26\text{ million}' title='T_\text{max} \times d_\text{model} = 1024 \times 256 \approx 0.26\text{ million}' class='latex' srcset='https://b2633864.assetcdn.net/2633864/wp-content/latex/6c4/6c4429cd36402745ca88b129c0d519fc-ffffff-000000-0.png?lossy=2&strip=1&webp=1 298w,https://b2633864.assetcdn.net/2633864/wp-content/latex/6c4/6c4429cd36402745ca88b129c0d519fc-ffffff-000000-0.png?size=126x7&lossy=2&strip=1&webp=1 126w' sizes='(max-width: 298px) 100vw, 298px' /> parameters</li>



<li><strong>Per Layer (MLA </strong><strong>and</strong><strong> MoE):</strong> Approximately 2-3 million parameters</li>



<li><strong>Total (6 layers):</strong> Approximately 30-35 million parameters</li>



<li><strong>MTP Heads:</strong> An additional 2-3 million parameters per head</li>
</ul>



<p>Most parameters are in the embeddings and the transformer blocks. The MLA compression reduces attention parameters compared to standard transformers, while MoE increases feedforward parameters. The balance results in a model that is larger than a standard transformer of the same compute cost, but not proportionally to the number of experts.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" id="h2-Memory-and-Computation-Footprint"/>



<h2 class="wp-block-heading"><a href="#TOC-h2-Memory-and-Computation-Footprint">Memory and Computation Footprint</a></h2>



<p>During training, memory usage includes:</p>



<ul class="wp-block-list">
<li><strong>Model Parameters:</strong> Approximately 30-35 million parameters at 4 bytes each require 120-140 megabytes (MB) in 32-bit floating-point format (FP32)</li>



<li><strong>Gradients:</strong> Require the same memory as the parameters: 120-140 MB</li>



<li><strong>Optimizer States:</strong> Require twice the parameter memory with AdamW: 240-280 MB</li>



<li><strong>Activations:</strong> Memory usage depends on batch size and sequence length</li>



<li><strong>Key-Value (</strong><strong>KV</strong><strong>)</strong><strong> Cache:</strong> Not needed during training</li>
</ul>



<p>Total training memory is roughly 500-600 MB plus activations. For a batch size of 4 and sequence length of 1024, activations add approximately 200-300 MB, giving us approximately 800 MB total. This fits comfortably on modern graphics processing units (GPUs).</p>



<p>During inference, we do not need gradients or optimizer states, and we can use 16-bit floating-point format (FP16), roughly halving memory. This implementation does not use a KV cache; it recomputes the context during each generation step.</p>



<p>With all components assembled, we have a complete, working DeepSeek-V3 model. It combines 4 innovations into a coherent architecture: configuration management with RoPE, MLA for efficient attention, MoE for sparse scaling, and MTP for richer training. In the next lesson, we will train this model on real data and see it generate text.</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 of on-demand code walkthrough videos • Last updated: November 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</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 5th lesson of our <strong>DeepSeek-V3 From Scratch</strong> series, we bring everything together by <strong>assembling the full DeepSeek-V3 architecture</strong>. We start with an overview of how the different components (MLA, MoE, and RoPE) fit into the broader design, and then move into the construction of the <strong>transformer block</strong>, where Multihead Latent Attention and Mixture of Experts are combined to form the model’s core computational unit. This sets the stage for understanding how the complete model processes information, from raw tokens all the way to logits.</p>



<p>We then explore key architectural innovations such as <strong>weight tying</strong>, which shares weights between the token embedding layer and the language modeling head, and <strong>multi-token prediction integration</strong>, which improves efficiency and predictive power. These design choices are not just theoretical. They directly impact how the model learns and generalizes. The implementation section walks us through building the complete DeepSeek model step by step, showing how each piece connects seamlessly into a unified system.</p>



<p>Finally, we analyze the <strong>architectural design patterns</strong>, parameter counts, and the <strong>memory and computation footprint</strong> of DeepSeek-V3. This helps us evaluate trade-offs between scalability and efficiency, and understand how the model balances complexity with performance. By the end of this lesson, we have not only assembled the architecture but also gained insight into the design decisions that make DeepSeek-V3 both powerful and practical.</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>“DeepSeek-V3 from Scratch: Building the Architecture in PyTorch,” <em>PyImageSearch</em>, S. Huot, A. Sharma, and P. Thakur, eds., 2026, <a href="https://pyimg.co/36gvk" target="_blank" rel="noreferrer noopener">https://pyimg.co/36gvk</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="DeepSeek-V3 from Scratch: Building the Architecture in PyTorch" data-enlighter-group="10">@incollection{Mangla_2026_deepseek-v3-from-scratch-building-architecture-in-pytorch,
  author = {Puneet Mangla},
  title = {{DeepSeek-V3 from Scratch: Building the Architecture in PyTorch}},
  booktitle = {PyImageSearch},
  editor = {Susan Huot and Aditya Sharma and Piyush Thakur},
  year = {2026},
  url = {https://pyimg.co/36gvk},
}
</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/10/05/deepseek-v3-from-scratch-building-the-architecture-in-pytorch/">DeepSeek-V3 from Scratch: Building the Architecture in PyTorch</a> appeared first on <a rel="nofollow" href="https://pyimagesearch.com">PyImageSearch</a>.</p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
