<?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[Online Inference - Medium]]></title>
        <description><![CDATA[A blog about AI. - Medium]]></description>
        <link>https://medium.com/online-inference?source=rss----52acf6e3d9be---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Online Inference - Medium</title>
            <link>https://medium.com/online-inference?source=rss----52acf6e3d9be---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 19:43:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/online-inference" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[CoreWeave AI Object Storage (CAIOS): Optimizing GPU workloads]]></title>
            <link>https://medium.com/online-inference/coreweave-ai-cloud-storage-caios-optimizing-gpu-workloads-d4154285f13c?source=rss----52acf6e3d9be---4</link>
            <guid isPermaLink="false">https://medium.com/p/d4154285f13c</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[cloud-storage]]></category>
            <category><![CDATA[coreweave]]></category>
            <dc:creator><![CDATA[David Davies]]></dc:creator>
            <pubDate>Mon, 14 Sep 2026 16:42:44 GMT</pubDate>
            <atom:updated>2026-09-14T16:42:45.626Z</atom:updated>
            <content:encoded><![CDATA[<p>Match each AI data path to the storage layer built for it. The goal is to keep NVIDIA GPU workloads supplied with datasets, weights, and checkpoints from development through production inference.</p><p>Dense GPU clusters create concentrated storage demand. A distributed training job on 20 eight‑GPU nodes can issue thousands of concurrent read requests while the inter‑GPU fabric handles collective communication. CoreWeave isolates and optimizes these paths through bare‑metal NVIDIA GPU clusters, non‑blocking InfiniBand fabric, managed storage, and Kubernetes‑native operations.</p><p>This overview focuses on the storage decisions that gate data‑loader latency, GPU utilization, checkpoint recovery, and runtime predictability. It covers CoreWeave AI Object Storage (CAIOS), the Local Object Transport Accelerator (LOTA), S3‑compatible object storage, POSIX‑compliant file storage, and node‑local NVMe.</p><p>The result is a direct path from an S3‑based experiment to a production workload that scales without replacing its storage interface.</p><h3>What CoreWeave AI Object Storage includes</h3><p><a href="https://www.coreweave.com/products/storage#object-storage">CoreWeave AI ObjectStorage</a> includes persistent object storage, shared POSIX-compliant storage, and fast local NVMe-backed storage — each serving different AI workload needs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yCeojEhMV1hBOqIw3oL6aQ.jpeg" /></figure><p>CoreWeave AI Object Storage is not one generic disk. It is persistent object storage, shared POSIX‑compliant storage, and temporary NVMe‑backed local storage. Each layer addresses a different access pattern.</p><p>Object storage organizes data into buckets and objects accessed through APIs. It fits large datasets, model weights, checkpoints, embeddings, evaluation results, logs, and other artifacts that do not require conventional filesystem behavior.</p><p>Distributed File Storage provides POSIX semantics. Applications see directories, paths, and familiar filesystem operations through a mounted volume. This fits distributed applications that need shared paths, directory traversal, synchronization between Pods, or libraries written for a conventional filesystem.</p><p>Local Storage is encrypted, NVMe‑backed ephemeral storage on GPU and CPU nodes. It mounts under /mnt/local, and Kubernetes emptyDir volumes use this storage by default. Use it for preprocessing output, temporary shards, caches, logs, and job‑local scratch data. It does not survive Pod deletion or node reboot, so it cannot replace persistent storage.</p><p>The Storage Products page and documentation index provide decision charts and operational guides for bucket creation, object management, authentication, IAM policies, API access, LOTA, and Terraform.</p><p>Pricing is capacity‑based rather than request‑driven. As of September 14, 2026, published CAIOS rates are $0.06 per GB‑month for Hot data, $0.03 for Warm data, and $0.015 for Cold data. Objects move between these tiers automatically based on access. Published pricing lists ingress, egress, transfer, request, retrieval, and IOPS charges as free, but teams should confirm current terms and contractual pricing during architecture review.</p><h3>What CoreWeave AI Object Storage (CAIOS) is</h3><p>CoreWeave AI Object Storage is an exabyte‑scale, S3‑compatible managed object‑storage service optimized for GPU‑intensive AI workloads. CAOIS is a common search variant, but CAIOS is the correct acronym.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LDJXF-ysvwnasJHcuvjsig.png" /></figure><p>S3 compatibility means existing clients, SDKs, and object‑oriented workflows address CAIOS buckets without a rewrite. Supported clients include the AWS CLI, S3cmd, and Boto3. CAIOS requires virtual‑hosted addressing via the CoreWeave endpoint.</p><p>AI teams use CAIOS for training and validation datasets, checkpoint shards, model weights, adapters, embeddings, evaluation outputs, synthetic data, and image, audio, or video collections. Objects can be versioned and protected through organization‑level and bucket‑level access policies.</p><p>For large‑scale training, CAIOS scales aggregate throughput and request handling horizontally. That distinction matters when hundreds or thousands of data‑loader workers read separate objects concurrently. The NVIDIA GPUs do not change the S3 programming model. Their density simply increases the aggregate demand that the storage, networking, and caching layers must sustain.</p><h3>How LOTA reduces latency with local NVMe caching</h3><p>The Local Object Transport Accelerator is a CAIOS proxy installed on GPU and CPU nodes in a CKS cluster. LOTA caches fetched data in distributed, node‑local NVMe storage and accelerates repeated GET requests.</p><p>The request path has four steps:</p><ol><li>An S3‑compatible client sends a request to http:// from inside a CoreWeave cluster.</li><li>LOTA authenticates the request and checks its distributed cache.</li><li>On a cache miss, LOTA fetches the object from CAIOS while streaming it to the requesting application.</li><li>Later requests read the cached data from NVMe near the workload.</li></ol><p>Outside a CoreWeave cluster, clients use the primary https:// endpoint. Switching an internal workload to LOTA generally requires an endpoint change rather than new storage logic.</p><pre>S3compatible client<br> |<br> v<br> cwlota.com<br> |<br> v<br>LOTA distributed cache on CKS nodes<br> | cache hit | cache miss<br> v v<br>Local NVMe CAIOS bucket<br> |<br> v<br>Data loader &gt; NVIDIA GPU workers</pre><p>Cache locality is valuable when workloads reread objects. Multi‑epoch training revisits dataset shards. Evaluation jobs reuse test corpora. Replacement workers reload checkpoints after failure. Inference replicas load the same model weights during scale‑out. LOTA reduces repeated backend reads in each case.</p><p>The default cache contribution is 1 TiB per node, and LOTA uses least‑recently‑used eviction. Teams should stage only the working set needed for the next training or inference phase.</p><h3>Benchmarked throughput and scalability results</h3><p>CAIOS demonstrates scalable throughput in benchmark tests using 20 NVIDIA H200 nodes with high-speed networking in a modern data center.</p><p>CoreWeave published a CAIOS random‑read benchmark using 20 NVIDIA H200 nodes in the US‑WEST‑04A Availability Zone. Each node contained eight H200 GPUs, one NVIDIA BlueField‑3 DPU with dual 100 Gbps storage links, and eight NVIDIA ConnectX‑7 InfiniBand adapters for inter‑GPU communication.</p><p>The benchmark used the open‑source Warp S3 tool. Each node wrote 10,000 objects, each 50 MiB, using 10 MiB parts and 100 concurrent threads. Warp then performed random reads across all 20 nodes for 10 minutes. The test generated I/O from CPUs on H200 compute nodes rather than reading directly into GPU memory, so the reported per‑GPU figure represents node throughput divided across eight GPUs.</p><p>During the first minute, while LOTA populated its cache, aggregate read throughput was approximately 24 GiB/s, or 1.2 GiB/s per node. Once the dataset was cached on local NVMe, aggregate throughput reached 368 GiB/s.</p><p>That cached result translates to:</p><ul><li>18.4 GiB/s per node</li><li>2.3 GiB/s per GPU</li><li>368 GiB/s across 20 nodes and 160 GPUs</li></ul><p>These figures apply to the stated object size, concurrency, hardware, cache state, and test topology. They demonstrate horizontal scaling as more GPU nodes contribute both readers and NVMe‑cache capacity. They should not be treated as a guaranteed result for every object distribution or application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B-yu3uwZf8zU6OWTaZEoWg.png" /></figure><h3>How CAIOS architecture differs from traditional object storage</h3><p>Traditional object storage is durable, API‑accessed infrastructure that usually sits on a remote data path from compute. This design works across many application types, but repeated reads still traverse the object‑storage network path unless another caching layer is introduced.</p><p>CAIOS retains the S3‑compatible interface while adding a data path designed around dense GPU clusters. LOTA integrates distributed NVMe caching into CKS nodes, allowing hot objects to move closer to the workers consuming them. A cache miss still retrieves data from persistent object storage. A cache hit changes the path by serving data through the cluster‑local cache.</p><p>This creates two dimensions of horizontal scale. The first is data throughput: additional nodes add local NVMe resources and read bandwidth. The second is request handling: distributed metadata and cache paths must absorb concurrent requests from many data‑loader workers.</p><p>CAIOS also provides read‑after‑write consistency, versioning, bucket lifecycles, IAM policies, and S3‑compatible operations. The architectural difference is therefore not durability versus speed. It is durable object storage combined with a cluster‑local acceleration layer for AI access patterns.</p><h3>When to use CAIOS, POSIX file storage, or local NVMe</h3><p>Start with the application’s access pattern. Choose object storage for API‑based access to durable artifacts, POSIX storage for shared filesystem semantics, and local NVMe for temporary, node‑local performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HPy3CL0FNwefr5AGXF6i1A.png" /></figure><p>Choose CAIOS for large, immutable, or versioned artifacts shared by distributed workers. Choose Distributed File Storage when software requires mounted paths, directory traversal, file locks, or atomic filesystem operations. Choose local NVMe when data can be recreated and only needs to remain close to one job.</p><p>Before selecting a tier, evaluate object size, reuse frequency, concurrency, required persistence, restart behavior, data locality, cache working‑set size, and security boundaries. Also account for automatic pricing‑tier transitions. Reading or pre‑staging Warm or Cold objects makes them Hot again.</p><h3>Common AI scenarios where CAIOS helps</h3><p>CAIOS accelerates workloads such as multi-epoch training, video processing, dataset sharing, and checkpoint restore for large-scale AI projects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_K4yqvOx428-WBp0wSMJ9w.png" /></figure><p>CAIOS provides the clearest benefit when many workers repeatedly access the same large objects. Examples include multi‑epoch training, multimodal dataset processing, video decoding, synthetic‑data pipelines, evaluation suites, checkpoint restore, and inference‑weight loading.</p><p>For multi‑epoch training, the first pass can populate LOTA while later epochs read cached shards. For a restarted job, pre‑staging the latest checkpoint avoids putting the initial restore entirely on the cold path. In production inference, teams can warm model weights while new Pods initialize, reducing storage‑related cold‑start variance.</p><p>Pre‑staging uses a HeadObject request with the Range: bytes=0‑0 header through http://. LOTA fetches the full object into its distributed NVMe cache without returning the object body to the client. The request counts as object access, so pre‑staged Warm or Cold data returns to the Hot pricing tier.</p><p>For AI applications and agents, faster artifact access shortens deployment rollouts, model‑evaluation loops, adapter loading, and recovery after node replacement. The practical objective is predictable end‑to‑end runtime, not a cache‑hit metric in isolation.</p><h3>A practical adoption path from development to production</h3><p>Start with one representative workload and define a measurable target. Record current dataset‑loading time, first‑epoch duration, checkpoint‑restore time, inference start time, GPU utilization, and total job duration.</p><h4>1 — Create storage credentials.</h4><p>In the Cloud Console, open Access Keys and create a temporary key for development. Production workloads should use Workload Identity Federation and short‑lived credentials instead of storing permanent keys in Pods.</p><p>Expected result: the console displays an Access Key ID and secret that your S3 client can use.</p><h4>2 — Configure access policies.</h4><p>Create an organization policy that permits the required bucket and object operations. Add a bucket policy when you need finer‑grained access for a specific dataset or team. Follow least‑privilege rules rather than granting every principal s3:*.</p><p>Expected result: authorized users can create or access buckets, while an unapproved identity receives an access‑denied response.</p><h4>3 — Create a bucket.</h4><p>In the Cloud Console, open Buckets, select Create Bucket, provide a globally unique lowercase name such as sonia‑model‑artifacts‑01, select an Availability Zone, and create it. AWS CLI, S3cmd, and Boto3 are alternatives.</p><p>Expected result: the new bucket appears in the bucket list. A bucket created through an S3 client can require approximately one minute before DNS caches update.</p><h4>4 — Upload representative data.</h4><p>Use the console or an S3‑compatible client to upload a realistic sample. Include the same object sizes and formats used in production, such as 50 MiB dataset shards, multi‑gigabyte checkpoints, or model‑weight files.</p><p>Expected result: object listings show the expected keys, sizes, and metadata. Download one object and verify its integrity.</p><h4>5 — Validate the primary endpoint.</h4><p>From a development environment outside CoreWeave, configure the client for https:// and virtual‑hosted addressing. Run list, upload, download, and range‑read operations.</p><p>Expected result: the existing S3 workflow completes without application‑level storage changes.</p><h4>6 — Measure LOTA.</h4><p>Run the workload inside CKS and change the endpoint to http://. Read the test dataset once to populate the cache, then repeat the same read pattern. Keep object count, concurrency, compute placement, and application settings constant.</p><p>Expected result: the second run reports a higher cache‑hit rate and, for reuse‑heavy workloads, lower read time. Compare GPU utilization and end‑to‑end job duration, not only storage throughput.</p><h4>7 — Pre‑stage the critical working set.</h4><p>Identify the dataset shards, checkpoint, or weights required at startup. Trigger pre‑staging shortly before launching the workload. A Kubernetes Job can warm the cache and complete before training or inference Pods start.</p><p>Expected result: the first critical read follows the warm‑cache path. Monitor cache capacity and avoid staging more data than the active cluster can hold.</p><h4>8 — Productionize the configuration.</h4><p>Move bucket creation, policies, versioning, lifecycle settings, and storage configuration into Terraform. Add endpoint selection and pre‑staging to the deployment pipeline. Use Grafana storage and LOTA dashboards to watch capacity, usage, cache utilization, and hit rates.</p><p>Expected result: development, staging, and production environments receive repeatable storage configuration through reviewed infrastructure‑as‑code changes.</p><h3>Closting thoughts</h3><p>CAIOS delivers persistent, high-throughput object storage for AI datasets and artifacts, integrating seamlessly with familiar S3-based workflows.</p><p>CAIOS is the CoreWeave storage option for S3‑compatible AI datasets and artifacts that require high‑throughput access from NVIDIA GPU clusters. It provides persistent object storage for datasets, model weights, checkpoints, and evaluation output while retaining familiar S3 clients and workflows.</p><p>LOTA adds the performance path for reuse‑heavy workloads. It caches fetched or pre‑staged objects on distributed local NVMe, reducing latency without replacing the underlying S3 programming model.</p><p>In the published test, CAIOS delivered 368 GiB/s of cached aggregate read throughput across 20 eight‑GPU NVIDIA H200 nodes. That equals 18.4 GiB/s per node and 2.3 GiB/s per GPU under the benchmark’s stated object‑size, concurrency, hardware, and cache conditions.</p><p>Choose storage based on access pattern. Test it with production‑representative data. Pre‑stage hot objects when startup, recovery, or first‑epoch performance sits on the critical path. The next step is to review the CAIOS documentation, benchmark one real training or inference workflow, and engage the CoreWeave team or a storage expert before locking the architecture for production.</p><h3>Sources</h3><ul><li><a href="https://docs.coreweave.com/products/storage">About CoreWeave Storage ‑ CoreWeave Docs</a></li><li><a href="https://coreweave.com/pricing">CoreWeave Cloud Pricing | CoreWeave</a></li><li><a href="https://docs.coreweave.com/products/storage/objectstorage">CoreWeave AI Object Storage</a></li><li><a href="https://docs.coreweave.com/products/storage/objectstorage/improvingperformance/aboutlota">Local Object Transport Accelerator (LOTA) ‑ CoreWeave Docs</a></li><li><a href="https://docs.coreweave.com/products/storage/objectstorage/improvingperformance/prestagecache">Pre‑stage the LOTA cache ‑ CoreWeave Docs</a></li><li><a href="https://www.coreweave.com/blog/benchmarkresultscoreweaveaiobjectstoragedelivers2gbspergputhroughputacrossanynumberofgpus">CoreWeave AI Object Storage Delivers 2+ GB/s per GPU</a></li><li><a href="https://docs.coreweave.com/products/storage/objectstorage/about">About CoreWeave AI Object Storage ‑ CoreWeave Docs</a></li><li><a href="https://docs.coreweave.com/products/storage/objectstorage/buckets/createbucket">Create buckets ‑ CoreWeave Docs</a></li><li><a href="https://docs.coreweave.com/products/storage/objectstorage/useterraformawsprovider">Manage AI Object Storage with Terraform ‑ CoreWeave Docs</a></li><li><a href="https://www.executivebiz.com/articles/leidoscoreweavepartneraidefenseintelligencecloud">Leidos, CoreWeave Team Up on Secure AI for National Security</a></li><li><a href="https://www.coreweave.com/blog/inferencebenchmarkscoreweavesversuspopulargeneralizedcloud">Inference Benchmarks: CoreWeave’s Inference Solution 8 to 10x …</a></li><li><a href="https://www.ciodive.com/news/coreweavegooglecloudcollaborateaitraininginference/818121">CoreWeave, Google Cloud link up for AI training, inference ‑ CIO Dive</a></li><li><a href="https://www.builtinnyc.com/job/capacityplannerii/7185309">CoreWeave ‑ Capacity Planner, Storage ‑ Built In NYC</a></li><li><a href="https://jobs.insightpartners.com/companies/monolithai/jobs/92680025seniorspecialistfieldengineerstorage">Senior Specialist Field Engineer ‑ Storage @ Monolith AI</a></li><li><a href="https://www.builtinnyc.com/job/dcopscostmanager/8964266">Data Center Operations Cost Manager ‑ CoreWeave | Built In NYC</a></li><li><a href="https://www.conductortech.com/coreweave">CoreWeave ‑ Conductor Technologies</a></li><li><a href="https://www.coreweave.com/">CoreWeave: The Essential Cloud for AI</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4154285f13c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/online-inference/coreweave-ai-cloud-storage-caios-optimizing-gpu-workloads-d4154285f13c">CoreWeave AI Object Storage (CAIOS): Optimizing GPU workloads</a> was originally published in <a href="https://medium.com/online-inference">Online Inference</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is an AI factory?]]></title>
            <link>https://medium.com/online-inference/the-ai-factory-explained-7cb61c5e65c7?source=rss----52acf6e3d9be---4</link>
            <guid isPermaLink="false">https://medium.com/p/7cb61c5e65c7</guid>
            <category><![CDATA[data-center]]></category>
            <category><![CDATA[ai-factory]]></category>
            <category><![CDATA[ai-data-center]]></category>
            <dc:creator><![CDATA[David Davies]]></dc:creator>
            <pubDate>Tue, 08 Sep 2026 22:29:45 GMT</pubDate>
            <atom:updated>2026-09-10T16:24:19.921Z</atom:updated>
            <content:encoded><![CDATA[<p>An AI factory turns governed data into production intelligence through a repeatable, measurable production system. It combines accelerated computing, high‑throughput data movement, model operations, and automation so teams can produce tokens, predictions, decisions, and model updates without rebuilding the platform for every project.</p><p>For AI leaders, an AI factory is a technical framework for moving from isolated pilots to deployed systems faster, with fewer infrastructure dead ends. The goal is not to assemble the largest GPU cluster. It is to create a balanced operating model in which data, compute, networking, storage, orchestration, evaluation, serving, and governance work as one production system.</p><p>This distinction affects budget and execution. A cluster can complete a training run while still failing as a shared platform. Data pipelines may starve GPUs. Checkpoints may overload storage. Poor placement may push collectives across oversubscribed links. An inference service may meet average latency while missing its p99 service‑level objective under burst traffic.</p><p>A complete AI factory addresses the entire loop: data ingestion, training, fine‑tuning, evaluation, deployment, inference, feedback, and retraining. Its performance emerges from low‑level kernel behavior, collective communication, topology‑aware scheduling, and resilient operations.</p><p><a href="https://www.coreweave.com/">CoreWeave</a> provides one implementation path for organizations that want these layers together. The platform combines bare‑metal NVIDIA accelerators, non‑blocking InfiniBand networking, NVMe local storage, managed object storage, Kubernetes‑native orchestration, and managed cluster services. The decision remains workload‑driven: start with measurable requirements, identify the limiting layer, and build around it.</p><h3>What an AI factory is, what it produces, and how it differs from a data center</h3><p>An AI factory transforms raw data into valuable AI outputs, unlike a traditional data center.</p><p>An AI factory is a specialized computing and operational system that manages the full AI life cycle at production scale. It converts raw data into structured inputs, model weights, embeddings, tokens, predictions, decisions, automations, and learning signals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m7Ch2GLK0AOK9YGs6JEu5A.png" /></figure><p>Those outputs form a closed loop:</p><pre>Data &gt; Training inputs &gt; Model &gt; Production outputs<br> ^ |<br> | v<br>Curated feedback &lt; Logs, evaluations, outcomes</pre><p>A traditional data center supports mixed workloads, including databases, virtual machines, web applications, file services, and business systems. Its primary concerns include server availability, transaction capacity, storage durability, and network connectivity.</p><p>An AI factory optimizes different constraints. Training depends on accelerator utilization, memory capacity, collective performance, checkpoint speed, and time to convergence. Inference depends on token throughput, time to first token, inter‑token latency, KV‑cache capacity, error rate, and cost per million tokens.</p><p>The factory model connects four organizational capabilities that teams often manage separately:</p><ul><li>Data pipelines collect, normalize, secure, and version inputs.</li><li>Algorithm development converts those inputs into models and evaluation methods.</li><li>Software infrastructure supplies compute, storage, networking, and deployment services.</li><li>Experimentation systems track hypotheses, artifacts, metrics, and promotion decisions.</li></ul><p>An AI factory does not need to be one physical facility. It can be cloud‑hosted, hybrid, on‑premises, sovereign, or distributed across several locations. What defines it is the repeatable production process, not the building around the hardware.</p><h3>Core components and reference architecture</h3><p>The core architecture is balanced. Accelerators execute model operations. CPUs and host memory feed them. Network fabrics synchronize distributed workers. Storage supplies datasets and persists checkpoints. Schedulers place workloads. Serving systems convert models into applications. Security, observability, and governance control the process.</p><p>Use the following operating table during architecture reviews:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*guSDdJGtdZ8k8e7kZMlMbA.png" /></figure><p>An underbuilt storage tier can idle expensive GPUs. An oversubscribed fabric can eliminate the benefit of adding workers. Weak scheduling can strand capacity even when the utilization dashboard reports a full cluster.</p><p>NVIDIA supplies the accelerator and systems foundation commonly used in AI factories. Cisco architectures can support segmentation, switching, security, and application delivery. Supermicro integrates high‑density server and rack designs. CoreWeave provides these infrastructure layers as a cloud platform, including <a href="https://coreweave.com/products/bare-metal">bare‑metal GPU capacity</a>, non‑blocking InfiniBand, <a href="https://coreweave.com/products/coreweave-kubernetes-service">Kubernetes</a>, NVMe storage, <a href="https://coreweave.com/products/storage#object-storage">managed object storage</a>, Mission Control, and <a href="https://coreweave.com/products/sunk/sunk-anywhere">SUNK</a>.</p><h3>Compute substrate: GPUs, CPUs, memory, and topology</h3><p>The GPU selection must match the workload, not a procurement hierarchy. H100 SXM 80GB supports distributed training and demanding inference. H200 141GB provides additional HBM capacity for larger models, longer contexts, larger batches, and larger KV caches. B200 increases the available compute and memory capabilities for dense training and serving. GB200 NVL72 provides a rack‑scale architecture for workloads that need a large, tightly connected accelerator domain.</p><p>HBM is only one constraint. CPU cores must decode records, tokenize text, transform images, and prepare batches quickly enough to feed the accelerators. Host memory must absorb prefetch queues and pinned buffers. PCIe placement, NUMA locality, NIC affinity, NVLink connectivity, NVSwitch domains, power delivery, and cooling all affect usable performance.</p><p>Training introduces several parallelism choices:</p><ul><li>Data parallelism replicates the model and divides batches.</li><li>Tensor parallelism divides individual tensor operations.</li><li>Pipeline parallelism assigns layers to different stages.</li><li>Sequence parallelism divides sequence‑dependent work.</li><li>Expert parallelism distributes mixture‑of‑experts layers.</li></ul><p>Inference shifts the constraint toward residency. Model weights, KV cache, temporary workspaces, and request batches must fit in HBM. Longer contexts and larger batches increase cache pressure. Quantization reduces memory consumption but requires quality validation. Prefill is compute‑heavy, while decode is often memory‑bandwidth‑sensitive.</p><p>For every performance test, record the model, GPU SKU, precision, batch size, sequence length, parallelism, software versions, and topology. A tokens‑per‑second result without these conditions is not a planning metric.</p><h3>Network fabric: Collectives, congestion, and locality</h3><p>Distributed training places networking directly on the model’s critical path. Workers exchange gradients, activations, parameter shards, pipeline messages, and expert‑routing traffic during every step. A slow rank can delay the entire job.</p><p>Inside a server, NVLink and NVSwitch connect GPUs at high bandwidth. Between servers, InfiniBand or Ethernet with RoCE carries collective traffic. GPUDirect RDMA allows network adapters to transfer data to and from GPU memory without routing every byte through host memory.</p><pre>+ Spine switches +<br> | | |<br> +++ +++ Storage<br> | Leaf 1| | Leaf 2| path<br> +++ +++ |<br> | | |<br> +++ +++ Object storage<br> | | | |<br> Node A Node B Node C Node D<br> GPUGPUNIC GPUGPU GPUGPUNIC GPUGPU<br> NVSwitch links NVSwitch links</pre><p>NCCL discovers GPU, NIC, and link topology, then constructs rings or trees for operations such as all‑reduce. Placement determines whether those operations remain inside a fast NVSwitch domain, cross one leaf switch, or traverse multiple network tiers.</p><p>A non‑blocking fabric provides enough cross‑sectional bandwidth for nodes to communicate without planned oversubscription. It does not eliminate congestion caused by simultaneous checkpoints, storage reads, expert exchange, and collective traffic. Rail‑optimized designs, traffic isolation, adaptive routing, and congestion control remain important.</p><p>CoreWeave’s non‑blocking InfiniBand fabric fits large training jobs that require predictable collective performance. Cisco networking can fit at segmentation, security, load‑balancing, and Ethernet‑fabric boundaries. In both cases, topology must be included in scheduling policy rather than treated as an invisible utility.</p><h3>Data and storage layer: Feeding the AI factory</h3><p>Multi-tiered storage supplies the AI factory with diverse data types for processing.</p><p>Storage supplies the factory with training shards, RAG corpora, model checkpoints, embeddings, evaluation sets, logs, and replay data. A practical hierarchy separates durability from locality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kCl8sRAqeb-9IgIBBwItig.png" /></figure><p>Managed object storage holds authoritative datasets, model artifacts, and checkpoints. Local NVMe stages hot shards and temporary files near the workers. A parallel file system may serve workloads requiring shared directories, POSIX semantics, or high‑throughput access from many nodes.</p><pre>Raw sources<br> |<br> v<br>Ingest &gt; Validate &gt; Normalize &gt; Deduplicate &gt; Policy filter<br> | |<br> v v<br>Curated datasets RAG documents<br> | |<br> v v<br>Tokenized shards Embeddings &gt; Vector index<br> | |<br> v v<br>Training &gt; Checkpoints &gt; Model registry &gt; Inference<br> |<br> v<br> Logs &gt; Feedback &gt; New curated data</pre><p>Common failures include small‑file metadata storms, uneven sharding, cold‑cache reads, checkpoint collisions, slow restore paths, stale embeddings, and training sets assembled from inconsistent versions.</p><p>A CoreWeave workflow can keep durable data in managed object storage or CoreWeave AI Object Storage, stage active shards to local NVMe, train on bare‑metal GPUs, and write versioned checkpoints back to object storage. Inference services can load approved models from the same durable tier while retrieval jobs refresh vector indexes independently.</p><p>Test the path before training. Run a representative shard scan, concurrent checkpoint write, and full restore. The expected output is a storage profile showing read throughput, checkpoint duration, request rate, cache hit rate, and restore time under planned concurrency.</p><h3>Control plane: Orchestration, identity, and multi‑team operation</h3><p>Infrastructure becomes a factory when teams can request resources through standard policies instead of manual ticket loops. The control plane handles placement, quota, identity, secrets, images, releases, monitoring, and failure recovery.</p><p>Kubernetes supports long‑running inference services, data jobs, operators, and batch workloads. Slurm remains familiar to research teams that need queue‑based allocation and tightly coupled jobs. SUNK, or Slurm on Kubernetes, preserves Slurm workflows while using Kubernetes as the underlying control plane. Mission Control supports cluster lifecycle operations for CoreWeave environments.</p><p>A shared platform should express workload differences explicitly:</p><pre>trainingJob:<br> gpuClass: H200141GB<br> gpuCount: 64<br> placement: gangscheduled<br> topology: singlefabricdomain<br> priority: researchcritical<br> checkpointTarget: objectstorage<br><br>inferenceService:<br> gpuClass: H100SXM80GB<br> minimumReplicas: 4<br> autoscalingMetric: queuedepth<br> latencySLO: p99<br> priority: production<br>dataPrepJob:<br> cpuClass: highmemory<br> localNVMe: required<br> gpuCount: 0<br> priority: backfill</pre><p>Training requires contiguous allocations and gang scheduling. Inference requires stable capacity, rapid scaling, and latency protection. Data preparation can often backfill unused CPU and storage capacity.</p><p>Multi‑tenancy creates deliberate trade‑offs. Strong isolation improves security but can reduce utilization. Shared pools improve utilization but create contention. Reserved capacity protects critical launches but costs money when idle. The control plane should make these decisions visible through quota, priority classes, chargeback, and queue‑wait reporting.</p><h3>How the AI life cycle runs end to end</h3><p>The AI factory runs a continuous, cyclical process from data ingestion to deployment and improvement.</p><p>An AI factory moves data through a controlled loop: ingest, curate, train, evaluate, fine‑tune, deploy, serve, observe, and improve. Inference, RAG, RAG corpus management, training, fine‑tuning, external‑service integration, and application development become parts of one versioned process.</p><p>Automation connects those parts. Every run should identify its dataset version, code revision, container image, configuration, model parent, evaluation results, approval status, deployment target, and cost. Promotion gates should prevent an unapproved checkpoint from reaching production. Rollback should restore both the model and its serving configuration.</p><p>Digital twins can test the planned workload mix before infrastructure deployment. Teams can simulate topology, power, thermal constraints, queue behavior, node failures, checkpoint traffic, and inference bursts. The resulting capacity model is more useful than sizing the platform from peak GPU demand alone.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NEjD9tulLx8paJo3K5o0mg.png" /></figure><h3>Data ingestion and token production</h3><p>Data ingestion transforms documents, database records, images, logs, code, and business events into governed training examples or model context. The sequence usually includes cleansing, deduplication, schema normalization, policy filtering, labeling, chunking, tokenization, and embedding.</p><pre>Sources &gt; Parsers &gt; Clean records &gt; Policy checks &gt; Curated corpus<br> |<br> +++<br> | |<br> v v<br> Token stream Embedding model<br> | |<br> v v<br> Training Vector index</pre><p>For RAG, corpus management also requires connectors, document parsers, chunking rules, embedding‑model versions, vector‑index configuration, refresh schedules, and access‑control enforcement. Retrieval must preserve source permissions. A user should not gain access to a document merely because its embedding appears near a query.</p><p>Quality failures propagate quickly at factory scale. Duplicate records distort training frequency. Low‑signal content consumes tokens. Personally identifiable information creates exposure. Licensing restrictions may prohibit model training. Stale knowledge bases return outdated context. Unbalanced classes hide poor minority‑class performance.</p><p>Create a dataset acceptance report before scheduling GPU work. Its expected output should include document count, duplicate rate, rejected‑record count, token distribution, language distribution, policy violations, class balance, source age, and dataset version.</p><h3>Training, fine-tuning, and evaluation</h3><p>During training, dataloaders prepare batches, GPUs execute forward passes, losses are calculated, backward passes produce gradients, collectives synchronize workers, optimizers update parameters, and checkpoints persist recoverable state.</p><p>Full pretraining creates a model from a large corpus. Continued pretraining adapts an existing model to a domain. Supervised fine‑tuning teaches task‑specific behavior. LoRA and other adapters update a smaller parameter set. RLHF and DPO optimize behavioral preferences. Evaluation‑only jobs measure quality without changing weights.</p><p>Every run needs reproducibility controls: versioned datasets, fixed seeds where practical, captured software environments, immutable configurations, checkpoint lineage, and documented evaluation gates. A Weights &amp; Biases workflow can initialize the run with () and (), record step‑level metrics through (...), and preserve datasets and checkpoints as Artifacts.</p><p>Leaders should require both quality and system metrics:</p><ul><li>Validation loss, task accuracy, safety scores, and domain‑specific quality</li><li>Convergence rate and tokens processed</li><li>GPU active time and model FLOP utilization</li><li>Dataloader wait and NCCL communication time</li><li>Checkpoint duration and recovery time</li><li>Total GPU‑hours and cost per run</li><li>Time from approved checkpoint to deployment</li></ul><p>The expected output is a promoted model artifact with its dataset lineage, evaluation report, cost, and reproducible run configuration attached.</p><h3>Inference, RAG, agents, and production feedback</h3><p>Inference in the AI factory turns models into real-time outputs with continuous feedback.</p><p>Inference is the production line that turns models into customer‑facing outputs. Requests arrive, prompts are assembled, context is retrieved, models generate tokens, tools execute, policies inspect outputs, and the system records results.</p><p>Continuous batching combines active requests while decode is in progress. Prefill processes input context. Decode generates subsequent tokens. KV‑cache paging moves cache blocks between memory tiers. Speculative decoding uses a smaller model or alternative path to propose tokens. Quantization reduces memory and compute requirements. Admission control rejects or delays work before overload destroys latency for every request.</p><p>RAG adds document retrieval, vector search, reranking, context construction, and citation metadata. Agents add external‑service calls, permissions, state, retries, timeouts, and failure isolation. Scope tool credentials to the action, user, and session.</p><p>Track p50, p95, p99, and p999 latency rather than averages alone. Also measure time to first token, inter‑token latency, tokens per second, tokens per second per GPU, cost per million tokens, error rate, cache hit rate, retrieval quality, tool‑call success, and safety‑filter performance.</p><p>Send inference logs, explicit user feedback, retrieval failures, drift signals, and safety‑evaluation failures back to the data‑curation queue. This closes the factory loop without treating every production interaction as automatically valid training data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kiDUWah96AUqJH3ihwhGvA.png" /></figure><h3>Deep mechanics at kernel, collective, and scheduler layers</h3><p>Factory throughput is determined below the platform dashboard. Kernels decide how tensor operations use compute and memory. Collectives determine how distributed workers communicate. Schedulers decide whether workloads receive the right hardware, topology, and priority.</p><p>These mechanics affect executive outcomes directly. Low kernel efficiency increases cost per token. Stalled collectives extend training time. Fragmented scheduling increases queue wait. Poor checkpoint coordination lengthens recovery. Uncontrolled inference placement produces tail‑latency spikes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U_uSDyCOOnQ3fFvtha3itA.png" /></figure><p>Record model, GPU, precision, batch size, sequence length, parallelism, fabric topology, software versions, and request distribution for every performance investigation.</p><h3>Kernel layer: Tensor cores, attention, and memory pressure</h3><p>Transformer execution consists largely of matrix multiplications, attention, softmax, normalization, activation functions, embedding operations, and optimizer updates. Tensor cores accelerate supported matrix operations using formats such as BF16 and FP8.</p><p>Performance depends on arithmetic intensity. Compute‑heavy kernels can approach the accelerator’s mathematical ceiling. Memory‑bound kernels wait for weights, activations, or cache blocks to move through HBM. Poor fusion writes intermediate tensors to memory and reads them back, increasing traffic without adding useful computation.</p><p>FlashAttention‑style methods reduce attention‑memory movement by processing blocks rather than materializing the full attention matrix. Activation checkpointing saves HBM by recomputing selected activations during the backward pass. Quantization reduces weight and cache size, but quality and kernel support must be tested.</p><pre>GPU HBM<br>++<br>| Model weights |<br>| Activations or checkpointed activation fragments |<br>| Gradients and optimizer states |<br>| KV cache for active inference requests |<br>| Input and output token buffers |<br>| Temporary kernel workspaces |<br>++</pre><p>Small batches may underuse tensor cores. Long contexts can exhaust HBM through attention and KV‑cache growth. Irregular mixture‑of‑experts routing can overload specific experts. Excessive kernel launches increase synchronization overhead.</p><p>Profile before scaling out. Adding GPUs does not fix a workload limited by small kernels, memory traffic, or CPU‑side launch gaps.</p><h3>Collective layer: All-reduce, all-gather, and pipeline bubbles</h3><p>Distributed workloads use different collectives for different parallelism modes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fssxth2m07vMExcz0j-14g.png" /></figure><p>Data parallelism synchronizes gradients. Tensor parallelism exchanges activations within layers. Fully sharded data parallelism reconstructs parameter shards. Pipeline parallelism sends activations between stages. Mixture‑of‑experts models route tokens through all‑to‑all exchanges.</p><p>Overlap communication with backward computation where possible. Too-small bucket sizes create overhead. Buckets that are too large delay overlap. NCCL tuning and topology‑aware rank assignment help collectives use the intended NICs and links.</p><p>The slowest rank determines step completion. Congestion, packet loss, thermal throttling, slow data loading, or a single degraded link can turn one worker into a cluster‑wide straggler. At larger scale, marginal gains diminish as communication consumes more of each step.</p><h3>Scheduler layer: Placement, priority, and utilization</h3><p>Schedulers decide when a job runs and where its GPUs, CPUs, NICs, memory, local disks, and storage bandwidth come from. Gang scheduling starts all distributed workers together. Topology-aware placement keeps workers within suitable NVLink, leaf-switch, or fabric domains. Bin packing reduces fragmentation, while backfill lets short jobs use temporary gaps.</p><p>Training and inference need different policies. Training wants large contiguous allocations, predictable topology, and checkpoint‑aware preemption. Inference wants elasticity, stable minimum capacity, rapid failover, and latency isolation.</p><p>Kubernetes‑native workloads can separate training, serving, and data pools through labels, taints, quotas, and priority classes. SUNK supports Slurm‑oriented teams without creating an entirely separate infrastructure model. Mission Control can manage cluster lifecycle while platform teams enforce standardized images, observability, and recovery practices.</p><p>Poor scheduling produces visible waste:</p><ul><li>Eight free GPUs cannot run an eight‑GPU job because they span incompatible nodes.</li><li>A job crosses slow fabric boundaries and spends more time in collectives.</li><li>Batch work consumes capacity needed for an inference burst.</li><li>Low‑priority experiments block critical retraining.</li><li>Reserved capacity sits idle because backfill policies are absent.</li></ul><p>Track allocation efficiency, queue wait, preemption rate, placement failures, fragmentation, topology locality, and unused reservations.</p><h3>What breaks at scale and how to operate the factory</h3><p>AI factories usually fail through compound bottlenecks rather than one catastrophic component. GPU starvation begins with slow data loading. Metadata storms appear when thousands of workers open millions of small files. Checkpoint storms occur when many jobs write simultaneously. Network incast appears when workers converge on the same service. Stragglers extend every distributed step.</p><p>Other failures include noisy neighbors, quota conflicts, image sprawl, dependency drift, incompatible drivers, and silent data‑quality regressions. Inference adds KV‑cache exhaustion, cold starts, long‑context tail latency, traffic bursts, prompt injection, failed tool calls, and stale RAG indexes.</p><p>Build an operating scorecard with:</p><ul><li>MFU and GPU active time</li><li>Dataloader wait and storage throughput</li><li>NCCL time and collective variance</li><li>Checkpoint duration and restore time</li><li>Queue wait and placement failures</li><li>p99 and p999 inference latency</li><li>Error‑budget consumption</li><li>Cost per training run and per million tokens</li><li>Mean time to detect and recover</li></ul><p>Resilience requires efficient checkpoints, model and configuration rollback, canary releases, shadow traffic, controlled autoscaling, chaos testing, and capacity rehearsals. Digital twins can model node loss, switch congestion, power constraints, and workload bursts before a production event.</p><p>Security belongs in the same operating system. Apply workload identity, network segmentation, scoped secrets, dataset access controls, audit logs, model‑approval workflows, safety evaluation, and geographic or regulatory boundaries.</p><p>The platform team should provide paved roads for standard training and serving patterns. Research teams still need controlled escape hatches for new kernels, models, and schedulers. Standardize repeatable operations, not every experiment.</p><h3>Deployment blueprint, economics, and industry use cases</h3><p>Building an AI factory is an investment sequence, not a single procurement event. Begin with workloads and measurable service objectives. Then size data, compute, fabric, storage, control‑plane capacity, and operational support.</p><p>Deployment models offer different trade‑offs. AI‑SaaS minimizes infrastructure work but provides less control over model internals and placement. A cloud‑hosted AI factory accelerates deployment while retaining control over models, containers, data paths, and capacity. Hybrid designs keep regulated data or latency‑sensitive services on‑premises while using cloud capacity for training. Sovereign platforms emphasize geographic, legal, and operational control. On‑premises factories provide physical control but require teams to manage power, cooling, networking, firmware, capacity, and lifecycle.</p><p>Measure economics through useful output rather than installed hardware. Track tokens per second, cost per token, cost per training run, queue wait, utilization, deployment lead time, engineering hours, and the business outcome generated by the workload.</p><p>CoreWeave can provide dedicated GPU capacity, Kubernetes, non‑blocking InfiniBand, managed object storage, Mission Control, and production engineering support. NVIDIA provides the accelerator and AI software ecosystem. Cisco can support network and security architecture. Supermicro can supply integrated physical systems for organizations building their own facilities.</p><h3>Step-by-step blueprint for building an AI factory</h3><p>A structured blueprint guides the step-by-step construction of a scalable AI factory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G0w6GwCzLpSfv1AIgXFkbw.png" /></figure><p><strong>Step 1: Classify the workloads.</strong></p><p>Create a table covering training, continued pretraining, fine‑tuning, RAG, batch inference, real‑time inference, evaluation, simulation, and data preparation. Record model size, context length, data volume, concurrency, run frequency, geographic needs, and expected growth.</p><p>Expected output: a workload inventory with owners and business priority.</p><p><strong>Step 2: Define service objectives and constraints.</strong></p><p>Specify latency percentiles, quality gates, availability, recovery objectives, security controls, budget, geographic placement, and launch dates. Do not use “fast” or “highly available” as requirements.</p><p>Expected output: an SLO sheet such as p99 under 2 seconds for classification, or a defined time‑to‑first‑token target for generation.</p><p><strong>Step 3: Design the reference architecture.</strong></p><p>Choose GPU classes based on memory, computation, and availability. Define NVLink and network boundaries, storage tiers, checkpoint paths, scheduler policies, inference pools, observability, and identity controls.</p><p>Expected output: a topology diagram and capacity model showing peak and steady‑state demand.</p><p><strong>Step 4: Implement the paved road.</strong></p><p>Create approved Kubernetes or SUNK templates for data preparation, training, evaluation, and serving. Connect object storage, CI/CD, an experiment tracker, a model registry, evaluation gates, secrets, and automated deployment.</p><p>Expected output: one workflow that promotes a versioned dataset into a tracked run, approved model artifact, canary deployment, and rollback‑ready production service.</p><p><strong>Step 5: Run a representative pilot.</strong></p><p>Use production‑sized data shards, expected sequence lengths, realistic request distributions, concurrent checkpoints, and injected failures. Measure every layer instead of testing only model quality.</p><p>Expected output: a baseline covering quality, MFU, throughput, p99 latency, queue wait, recovery time, and cost.</p><p><strong>Step 6: Remove the limiting bottleneck.</strong></p><p>Improve the slowest end‑to‑end layer first. This may require better sharding, NVMe staging, topology‑aware placement, different parallelism, larger inference batches, or revised admission control.</p><p><strong>Step 7: Scale the operating model.</strong></p><p>Publish reusable templates, quotas, support boundaries, chargeback, security controls, and service ownership. Add teams only after the platform can explain capacity allocation and recover predictably.</p><h3>Benefits and industry use cases</h3><p>AI factories provide shared infrastructure and faster time to value across industries.</p><p>A well‑operated AI factory shortens time to value by giving teams repeatable paths from data to deployment. Shared infrastructure improves utilization. Standard templates reduce platform fragmentation. Central lineage and approval gates strengthen governance. Instrumented workloads expose cost per output rather than hiding spending inside cluster totals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-ZOAmM50Uq9a8WDf7BDqWA.png" /></figure><p>The infrastructure profile depends on the use case:</p><ul><li>Enterprise copilots need secure RAG, permission‑aware retrieval, frequent corpus refresh, and predictable interactive latency.</li><li>Customer‑support automation needs burst handling, tool integration, safety controls, and low cost per conversation.</li><li>Fraud detection needs high‑throughput event processing, low latency, class‑imbalance monitoring, and frequent drift evaluation.</li><li>Recommendation systems need massive batch generation, online feature access, and rapid feedback loops.</li><li>Drug discovery and personalized medicine need large training runs, simulation, governed datasets, and reproducible experiments.</li><li>Robotics and autonomous vehicles need high‑throughput simulation, multimodal training, edge deployment, and continuous ingestion of field data.</li><li>Manufacturing optimization needs time‑series ingestion, visual inspection, anomaly detection, and integration with operational systems.</li><li>Sovereign AI needs geographic control, local‑language datasets, strong identity, auditability, and dedicated capacity.</li></ul><p>Generative AI changes the operating model because inference becomes continuous rather than occasional. Token economics, KV‑cache capacity, RAG refresh cycles, safety evaluation, and agent permissions become daily production concerns.</p><p>Not every organization needs to build every layer. The strategic decision is how much specialization and control the business needs, and how much infrastructure operation it is prepared to own.</p><h3>Closing thoughts</h3><p>An AI factory is a specialized production system for repeatedly turning governed data into tokens, predictions, decisions, automations, and improved models. It manages the full AI life cycle rather than treating training, deployment, and inference as disconnected projects.</p><p>That makes it fundamentally different from a traditional data center. An AI factory is optimized for accelerators, HBM capacity, collective communication, high-throughput storage, topology-aware scheduling, model operations, low-latency inference, automation, and closed-loop learning.</p><p>The executive decision should not begin with a generic cloud checklist or a preferred GPU count. Start with workload conditions and operating metrics. Define the model, data volume, context length, latency distribution, quality gates, availability target, security boundary, and budget. Then choose the compute, fabric, storage, orchestration, and operating model that satisfy them as a system.</p><p>CoreWeave provides a complete AI platform for teams that need accelerated computing, high‑performance networking, managed storage, Kubernetes‑native orchestration, lifecycle services, and production engineering support together.</p><p>Map one business‑critical AI workload from source data through production feedback. Measure every handoff. Identify the first layer that limits quality, throughput, latency, recovery, or cost. Use that bottleneck as the first design constraint for your AI factory.</p><h3>Sources</h3><ul><li><a href="https://www.nvidia.com/enus/glossary/aifactory">What is an AI Factory? | NVIDIA Glossary</a></li><li><a href="https://www.f5.com/company/blog/defininganaifactory">What Is an AI Factory? ‑ F5</a></li><li><a href="https://online.hbs.edu/blog/post/aifactory">The AI Factory: What It Is &amp; Its Key Components</a></li><li><a href="https://newsroom.cisco.com/c/r/newsroom/en/us/a/y2026/m08/ciscosecureaifactorynvidiarackscale.html">Cisco Expands Secure AI Factory with NVIDIA for the Rack‑Scale Era</a></li><li><a href="https://www.teradata.com/insights/aiandmachinelearning/whatisanaifactory">What Is an AI Factory? Architecture + Key Components ‑ Teradata</a></li><li><a href="https://nvidianews.nvidia.com/news/navernvidiaandbrookfieldtoexpandkoreasnationalaifactoryinfrastructurebuildout">NAVER, NVIDIA and Brookfield to Expand Korea’s National AI …</a></li><li><a href="https://blogs.nvidia.com/blog/aifactory">AI Factories Are Redefining Data Centers, Enabling Next Era of AI</a></li><li><a href="https://www.eurohpcju.europa.eu/eurohpcjuselectsaifactoryantennasbroadenaifactoriesinitiative20251013_en">EuroHPC JU Selects AI Factory Antennas to Broaden the AI Factories Initiative ‑ The European High Performance Computing Joint Undertaking (EuroHPC JU)</a></li><li><a href="https://blogs.nvidia.com/blog/nvidiaaifactorycompute">NVIDIA AI Factory Compute Is Becoming an Investable Asset Class</a></li><li><a href="https://www.supermicro.com/en/accelerators/nvidia/aifactory">Build AI Factories with Supermicro and NVIDIA</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7cb61c5e65c7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/online-inference/the-ai-factory-explained-7cb61c5e65c7">What is an AI factory?</a> was originally published in <a href="https://medium.com/online-inference">Online Inference</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Serverless inference: How autoscaling powers AI model serving]]></title>
            <link>https://medium.com/online-inference/serverless-inference-how-autoscaling-powers-ai-model-serving-5bb4232b41eb?source=rss----52acf6e3d9be---4</link>
            <guid isPermaLink="false">https://medium.com/p/5bb4232b41eb</guid>
            <category><![CDATA[serverless-architecture]]></category>
            <category><![CDATA[inference]]></category>
            <category><![CDATA[llm-inference]]></category>
            <category><![CDATA[inference-optimization]]></category>
            <dc:creator><![CDATA[David Davies]]></dc:creator>
            <pubDate>Wed, 26 Aug 2026 21:54:47 GMT</pubDate>
            <atom:updated>2026-08-26T21:54:47.796Z</atom:updated>
            <content:encoded><![CDATA[<p>Serverless inference is a cloud execution model in which applications invoke AI and machine‑learning models through an API while the platform allocates, scales, and reclaims compute resources automatically. For AI platform leaders, this can shorten deployment cycles, eliminate idle capacity for bursty workloads, and reduce routine infrastructure management. The engineering challenge is understanding what happens when an endpoint scales from zero, absorbs a burst, or reaches its memory and concurrency limits.</p><p>Serverless inference begins with an invocation contract rather than a server specification. A team supplies a request to an endpoint, and the provider decides where and when the model runs. Capacity can expand with demand and return to zero when requests stop.</p><p>This operating model is valuable for intermittent workloads, evaluation endpoints, prototypes, and product features with a high peak‑to‑average traffic ratio. It is less suitable when models must remain resident in GPU memory, p99 latency must be tightly controlled, or inference depends on topology‑aware communication across multiple GPUs.</p><p>This tutorial examines the complete execution path: scheduler placement, worker startup, artifact loading, GPU‑memory allocation, tokenization, batching, CUDA kernels, collectives, response streaming, and scale‑down. It then provides a repeatable evaluation process for selecting among on‑demand serverless inference, provisioned concurrency, and dedicated GPU infrastructure.</p><h3>What serverless inference means</h3><p>Serverless inference means the platform owns endpoint hosting, routing, autoscaling, health management, and idle‑capacity reclamation. It does not mean that inference runs without servers. Models still consume CPUs, GPUs, memory, storage, and network bandwidth. Those resources are hidden behind a managed API and a provider‑defined execution contract.</p><p>Products such as Amazon SageMaker Serverless Inference support bring‑your‑own‑model endpoints. Other platforms, including Google Vertex AI, DigitalOcean Gradient, Together AI, and Vultr, may offer hosted foundation‑model APIs, custom‑model deployment, or both. Hosted APIs simplify model access. Bring‑your‑own‑model endpoints give teams more control over artifacts and runtime behavior.</p><p>Serverless inference is distinct from:</p><ul><li>Training, which updates model parameters through forward and backward passes.</li><li>Fine‑tuning, which adapts model weights or adapters to a dataset.</li><li>Batch inference, which processes a finite dataset without an interactive response path.</li><li>Asynchronous inference, which queues work and returns results later.</li><li>Always‑on real‑time inference, which keeps configured replicas active continuously.</li></ul><h3>Serverless inference vs server‑based inference</h3><p>Traditional server‑based inference starts with capacity planning. The platform team selects instances, deploys model servers, configures replicas, and maintains enough warm capacity for expected traffic. Serverless inference starts with request, memory, concurrency, and timeout limits. The provider maps those requirements onto shared or isolated workers.</p><pre>Attribute Serverless inference Serverbased inference<br>  <br>Capacity ownership Provider Platform team<br>Scaletozero Usually supported Must be implemented<br>Cold starts Possible Avoided with warm replicas<br>Tuning control Providerconstrained Runtime and hardware control<br>Compliance fit Depends on provider controls Strong isolation is possible<br>Bestfit traffic Bursty or intermittent Steady and predictable<br>Hardware choice Limited or abstracted Explicit CPU and GPU selection<br>Cost model Invocation or duration based Capacityhour based</pre><p>Server‑based serving remains preferable for steady high utilization, specialized CUDA kernels, strict data locality, large models, long‑running generation, and compliance requirements that demand direct infrastructure control.</p><h3>How serverless inference works behind the scenes</h3><p>High-level architecture of a serverless inference endpoint, highlighting the separation between control and data planes.</p><p>A serverless endpoint contains a control plane and a data plane. The control plane manages endpoint configuration, quotas, worker placement, scaling, and health. The data plane authenticates requests, executes the model, and returns or streams results.</p><p>The path looks like this:</p><pre>Client<br> |<br> v<br>API gateway &gt; Authentication and quota checks<br> |<br> v<br>Request router &gt; Telemetry and distributed tracing<br> |<br> v<br>Admission queue<br> |<br> v<br>Scheduler &gt; Warm pool<br> | |<br> | cold allocation | warm assignment<br> v v<br>Runtime worker &lt; Model store<br> |<br> v<br>CPU preprocessing &gt; GPU execution &gt; Postprocessing<br> |<br> v<br> Metrics and traces<br> |<br> v<br>Client &lt; Response stream</pre><p>Cold‑start work can include worker allocation, container image retrieval, runtime initialization, artifact download, checksum validation, GPU context creation, weight transfer, CUDA graph capture, and cache warmup. Serverless changes who manages these operations. It does not remove them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zGgEs5qyeICnGmlagioaFg.png" /></figure><h3>Control plane scheduling and scale-to-zero</h3><p>The scheduler performs admission control, quota validation, placement, bin packing, warm‑pool selection, eviction, and scale‑down. Each worker requires a bounded combination of CPU, host memory, GPU memory, network bandwidth, and execution time.</p><p>This resembles a Tetris‑style packing problem. The scheduler must place differently shaped workloads onto available capacity without violating isolation, locality, or resource limits. A worker with sufficient CPU memory but insufficient GPU VRAM is not a valid placement.</p><p>Scale‑to‑zero removes idle workers after a configured or provider‑controlled interval. The next request must recreate enough of the execution environment to serve traffic. This is slower than assigning work to a warm replica.</p><p>At scale, plan for:</p><ul><li>Thundering‑herd bursts that initialize many workers simultaneously.</li><li>Regional quota exhaustion during correlated demand.</li><li>Model‑store hot spots caused by concurrent artifact downloads.</li><li>Noisy neighbors competing for shared resources.</li><li>Retry amplification when clients resubmit timed‑out requests.</li><li>Starvation when one tenant consumes all endpoint concurrency.</li></ul><p>Multi‑team platforms need per‑tenant quotas, priority classes, fairness policies, and explicit overload behavior. Critical production traffic should not compete equally with experiments.</p><h3>Data plane lifecycle from request to token</h3><p>A typical generative request follows this sequence:</p><ol><li>Authenticate the caller.</li><li>Validate payload size, schema, and token limits.</li><li>Route the request to the endpoint and region.</li><li>Apply quotas and admission control.</li><li>Queue the request if no worker is immediately available.</li><li>Assign or initialize a worker.</li><li>Load the model if it is not already resident.</li><li>Tokenize the input.</li><li>Run the prefill phase over the prompt.</li><li>Run iterative decode operations.</li><li>Detokenize and postprocess the output.</li><li>Serialize or stream the response.</li></ol><p>Streaming endpoints expose time to first token and inter‑token latency. Classifiers, embedding models, and single‑response image models usually expose one total response time.</p><p>Track latency as separate components:</p><pre>Component p50 p95 p99<br>   <br>Gateway and routing measured measured measured<br>Queue time measured measured measured<br>Coldstart time measured measured measured<br>Modelload time measured measured measured<br>Tokenization measured measured measured<br>Prefill measured measured measured<br>Decode measured measured measured<br>Serialization/network measured measured measured<br>Endtoend measured measured measured</pre><p>Test both JSON and binary payloads when serving images, documents, audio, or multimodal inputs. Binary payloads can reduce encoding overhead, but payload‑size and gateway limits still apply.</p><h3>Runtime kernels, batching, and collectives</h3><p>Once a worker is warm, serverless performance follows the same GPU mechanics as dedicated serving. CUDA‑kernel efficiency, memory bandwidth, framework overhead, KV‑cache layout, and batching policy determine throughput and latency.</p><p>Dynamic batching combines requests to improve GPU occupancy. Waiting too long for a larger batch increases queueing latency. Interactive APIs therefore need a bounded batching window, while asynchronous workloads can prioritize throughput.</p><p>Models that exceed one GPU may use tensor parallelism or pipeline parallelism. Tensor‑parallel inference exchanges partial results through operations such as all‑reduce, all‑gather, and reduce‑scatter, commonly through NCCL. Every participant must reach synchronization points, so one delayed GPU can increase p99 latency for the complete group.</p><p>Cross‑GPU bandwidth and placement locality become critical for sharded models. When generic serverless limits no longer fit, dedicated CoreWeave capacity can provide bare‑metal NVIDIA H100 SXM 80GB, H200 141GB, B200, or GB200 NVL72 systems. Non‑blocking InfiniBand and topology‑aware placement support collective‑heavy inference without hiding the underlying network path.</p><h3>Memory and concurrency limits for serverless endpoints</h3><p>Typical memory and concurrency limits imposed on serverless inference endpoints.</p><p>Every serverless inference platform imposes limits. The exact values are provider- and region‑specific and subject to change, so verify the current documentation before selecting a production configuration.</p><p>Amazon SageMaker Serverless Inference exposes MemorySizeInMB for vertical sizing and MaxConcurrency for concurrent invocation capacity. Increasing memory may also affect the CPU resources allocated. It does not imply access to a larger or faster GPU.</p><p>GPU‑oriented services may express limits through GPU VRAM, model size, maximum context length, concurrent sequences, timeout, or tokens generated per request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cb5JiPTZFMaHbKnkYaTrgg.png" /></figure><p>Use this worksheet during provider evaluation:</p><pre>Provider or tier Memory/VRAM Max concurrent Timeout Payload Artifact Scale zero Provisioned<br>       <br>Candidate A verify verify verify verify verify yes/no yes/no<br>Candidate B verify verify verify verify verify yes/no yes/no<br>Candidate C verify verify verify verify verify yes/no yes/no<br>Dedicated GPU pool selected configured custom custom custom optional always warm</pre><p>Do not select limits from defaults alone. Measure the model with realistic context lengths, image sizes, output lengths, and concurrency distributions.</p><h3>How to choose memory for model weights and KV cache</h3><p>Estimate the live memory requirement with:</p><pre>M_total =<br> M_weights<br> + M_runtime<br> + M_activation_buffers<br> + M_CUDA_graphs<br> + M_tokenizer<br> + M_KV_cache<br> + M_safety_headroom</pre><p>For an attention model, a useful KV‑cache approximation is:</p><pre>M_KV_cache =<br> 2<br> x layers<br> x concurrent_sequences<br> x cached_tokens_per_sequence<br> x KV_heads<br> x head_dimension<br> x bytes_per_element</pre><p>The factor of two represents key and value tensors. Grouped‑query and multi‑query attention can reduce this footprint because they use fewer KV heads.</p><p>Production memory use can exceed the estimate because of allocator fragmentation, temporary tensors, padding, variable image shapes, and framework caches. Requests with widely varying context lengths are especially difficult to pack efficiently.</p><p>Test at least three memory settings. Select the smallest configuration that satisfies p99 latency and error‑budget requirements at the target concurrency. More host memory may accelerate loading or provide additional CPU allocation on some platforms, but it will not resolve GPU‑bound decode throughput.</p><h3>How to choose concurrency without collapsing tail latency</h3><p>Concurrency is the number of simultaneous in‑flight requests accepted by an endpoint or execution tier. Provider semantics differ, so determine whether the limit applies per endpoint, worker, model, account, or region.</p><p>Use Little’s law for an initial estimate:</p><pre>Required concurrency ~= arrival rate x average service time</pre><p>If the endpoint receives 20 requests per second and average service time is 0.5 seconds, the starting estimate is 10 concurrent requests. Add controlled headroom, then validate p95 and p99 behavior under bursts.</p><p>Higher concurrency can increase throughput, but it can also increase queue depth, cold starts, KV‑cache usage, memory fragmentation, and scheduler contention. Configure separate controls for:</p><ul><li>Endpoint‑wide concurrency.</li><li>Per‑worker batch size.</li><li>Per‑tenant quotas.</li><li>Maximum prompt and output tokens.</li><li>Client retry count and backoff.</li><li>Queue length and queue age.</li></ul><p>Reject overload early or shed low‑priority traffic. Unlimited queues convert a capacity problem into timeouts and retry storms.</p><h3>On-demand serverless inference vs provisioned concurrency</h3><p>On-demand serverless inference initializes workers as needed, while provisioned concurrency keeps capacity ready for predictable workloads.</p><p>On‑demand serverless inference initializes workers as requests arrive. Provisioned concurrency keeps a configured amount of capacity initialized and ready. Amazon SageMaker Serverless Inference uses this terminology, but the same pattern appears across managed inference services.</p><p>Provisioned concurrency lowers cold‑start exposure but creates an idle‑cost floor. It also requires capacity schedules or scaling policies. Neither mode provides unlimited throughput.</p><pre>Workload trait Recommended tier<br> <br>Long idle periods Ondemand<br>Cold starts acceptable Ondemand<br>Predictable businesshours traffic Provisioned concurrency<br>Known launch or event spike Provisioned concurrency<br>Strict interactive p99 Provisioned or dedicated<br>Steady high utilization Dedicated GPU<br>Large resident model Dedicated GPU<br>MultiGPU topology requirement Dedicated GPU</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*svZFHw4Z_wG_7HWOaW5eAQ.png" /></figure><h3>Use on-demand when idle time dominates</h3><p>On‑demand endpoints fit internal tools, prototypes, evaluation endpoints, document enrichment, low‑volume product features, and asynchronous AI jobs. They reduce or eliminate idle compute charges when traffic stops.</p><p>The trade‑off is latency variance. The first request after an idle period may pay for worker startup and model loading. Concurrent first requests may trigger multiple cold workers.</p><p>Configure client timeouts around measured cold‑start distributions. Use exponential backoff with jitter, idempotency keys, and a fallback experience for interactive applications. Do not place an untested on‑demand endpoint directly in a latency‑critical user path.</p><p>For evaluation workloads, on‑demand serving is often effective because the endpoint can disappear between test runs while retaining a stable API contract.</p><h3>Use provisioned concurrency when p99 latency is contractual</h3><p>Provisioned concurrency maintains initialized workers for predictable demand. Suitable workloads include customer‑facing copilots, launch events, business‑hours applications, periodic document‑processing arrivals, and known traffic spikes.</p><p>Where supported, use schedule‑based scaling before known peaks and metric‑based scaling for sustained unexpected demand. Begin warming capacity before traffic arrives because model loading can take longer than the scaling interval.</p><p>Provisioned concurrency still has limits. Requests can queue when all warm workers are occupied. Downstream databases, vector stores, safety services, and API gateways can also throttle.</p><p>Treat warm capacity as the first serving layer, not an unlimited buffer. Define an overflow policy that either scales additional workers, queues bounded work, redirects to a lower‑cost model, or rejects low‑priority requests.</p><h3>Cost, scalability, and infrastructure trade‑offs</h3><p>Serverless inference reduces node management, routine autoscaling work, and idle capacity for bursty models. It can also accelerate deployment because teams use a standard endpoint contract instead of requesting clusters.</p><p>Its cost depends on more than invocation count. Relevant variables include memory allocation, execution duration, model‑loading time, provisioned concurrency, payload transfer, retries, artifact storage, and observability.</p><p>Use an adaptable model:</p><pre>Serverless cost =<br> successful_requests x invocation_charge<br> + total_billed_duration x configured_resource_rate<br> + provisioned_capacity_time x provisioned_rate<br> + storage<br> + data_transfer<br> + observability<br> + failed_and_retried_request_cost<br><br>Dedicated cost =<br> GPU_hours x GPU_hourly_rate<br> + CPU_and_memory<br> + storage<br> + network<br> + platform_operations</pre><p>Compare cost per successful request or cost per million generated tokens. Listed invocation price alone hides retries, failures, and unused provisioned capacity.</p><h3>When serverless inference is cheaper than dedicated GPUs</h3><p>The favorable serverless envelope has low average utilization, a high peak‑to‑average ratio, short requests, small artifacts, and flexible p99 objectives. Long idle windows make scale‑to‑zero economically meaningful.</p><p>Strong candidates include:</p><ul><li>Document classification.</li><li>Sporadic embedding generation.</li><li>Content moderation.</li><li>Routing and intent models.</li><li>Prototype APIs.</li><li>Low‑frequency feature extraction.</li></ul><p>Measure effective utilization as useful execution time divided by available capacity time. Also include platform toil. Moving patching, node replacement, and routine scaling to the provider can lower operational cost even when raw compute pricing is similar.</p><p>Cold starts can reverse the result if model initialization consumes a large share of billed duration. Calculate cost per successful response after timeouts and retries, not merely cost per invocation attempt.</p><h3>When dedicated GPU infrastructure wins</h3><p>Dedicated GPUs become attractive at steady high QPS, strict p99 latency, long‑running generation, or model sizes that require continuous residency. LLM economics depend on tokens per second, GPU occupancy, batch formation, KV‑cache efficiency, and collective communication.</p><p>A dedicated CoreWeave deployment can use Kubernetes‑native orchestration with bare‑metal H100 SXM 80GB, H200 141GB, B200, or GB200 NVL72 capacity. NVMe local storage can accelerate artifact staging. Non‑blocking InfiniBand supports sharded inference whose all‑reduce and all‑gather traffic would otherwise dominate latency.</p><p>Serverless and dedicated capacity can coexist. Keep experimental and low‑volume models on serverless endpoints, then move sustained workloads to pinned GPU pools.</p><p>Avoid packaging dead ends. A prototype API should use the same model artifact, identity model, telemetry schema, health checks, and rollout controls expected in production.</p><h3>Best-fit use cases and what breaks at scale</h3><p>Serverless inference is strongest when traffic is unpredictable, execution is bounded, and the platform can standardize deployment behind an API. It is weakest when models require continuous residency, specialized kernels, topology‑aware collectives, or large local caches.</p><p>Candidate workloads include text classification, embeddings, image generation, moderation, extraction, experimentation, tenant‑isolated APIs, and model evaluation. Classify each workload by traffic distribution, model footprint, latency tolerance, and operational maturity.</p><p>Serverless does not eliminate capacity engineering. Queues, quotas, artifact distribution, memory fragmentation, and retries still determine system behavior. Load testing must include sudden bursts rather than only gradual traffic ramps.</p><h3>Use cases where serverless inference is most advantageous</h3><p>Serverless inference is ideal for intermittent AI features, document classification, moderation, and developer sandboxes.</p><p>Strong fits include intermittent AI features, sporadic embeddings, document classification, moderation, routing models, evaluation jobs, and developer sandboxes. Image generation is a conditional fit when users can tolerate startup and generation latency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KwfSN15p3-A70h80X4NySg.png" /></figure><p>Serverless also lets platform teams support many small engineering groups without reserving a GPU for every experiment. A multi‑tenant design can provide:</p><ul><li>Per‑team endpoints.</li><li>Isolated quotas.</li><li>Cost attribution and chargeback.</li><li>Approved model catalogs.</li><li>Fast rollback to a previous artifact.</li><li>Expiration policies for unused endpoints.</li></ul><p>Managed model APIs and bring‑your‑own‑model endpoints solve different problems. Managed APIs minimize operational work. Bring‑your‑own‑model services support custom weights and packaging but expose more runtime constraints.</p><h3>Failure modes platform teams must plan for</h3><p>A product launch, synchronized cron job, or recovery from an outage can release thousands of requests at once. Every request may compete for worker allocation and artifact loading.</p><p>Large images and model artifacts introduce additional bottlenecks: object‑storage hot spots, slow container pulls, checksum validation, cache eviction, and exhausted local disks.</p><p>GPU‑specific failures include out‑of‑memory errors, KV‑cache fragmentation, batch‑shape variance, kernel‑launch overhead, and collective stalls. API failures include retry storms, inconsistent timeouts, incorrect rate limits, missing idempotency, and interrupted token streams.</p><p>Mitigations include:</p><ul><li>Warm pools or provisioned concurrency.</li><li>Staggered scheduled jobs.</li><li>Prompt and output‑token caps.</li><li>Request‑shape classes.</li><li>Circuit breakers.</li><li>Priority queues.</li><li>Exponential backoff with jitter.</li><li>Regional failover.</li><li>Bounded queues and explicit overload responses.</li></ul><h3>Step-by-step evaluation and deployment blueprint</h3><p>A serverless rollout should begin as a controlled experiment and end as a repeatable platform path. Use the same artifact and traffic replay to compare on‑demand, provisioned concurrency, and dedicated GPU serving.</p><ol><li><strong>Profile the model.</strong> Record artifact size, parameter precision, host‑memory use, GPU‑memory use, startup time, supported payloads, context limit, and expected output length. Expected output: a model profile with weight footprint, peak live memory, and initialization stages.</li><li><strong>Define SLOs. </strong>Specify p50, p95, and p99 latency, time to first token, throughput, error rate, availability, and maximum queue age. Expected output: separate SLO tiers for experiments, internal services, and customer‑facing production.</li><li><strong>Capture representative payloads.</strong> Sample short, median, and worst‑case prompts, images, documents, and output lengths. Remove or protect sensitive data. Expected output: a replay set that reflects request‑size and arrival‑rate distributions.</li><li><strong>Design the configuration matrix.</strong> Vary memory, concurrency, batch size, precision, context length, payload format, and warm state.</li><li><strong>Run cold and warm benchmarks separately.</strong> Force idle periods for cold‑start tests. Run sustained traffic for warm tests. Do not combine them into one average.</li><li><strong>Model cost.</strong> Calculate cost per successful request and cost per million tokens, including retries, storage, transfer, and provisioned capacity.</li><li><strong>Roll out gradually. </strong>Start with internal callers, then a small production percentage. Set concurrency and token caps before increasing traffic.</li><li><strong>Review saturation behavior.</strong> Increase load until queue time, throttling, errors, or p99 latency violates the SLO. Record the first bottleneck.</li><li><strong>Select the serving tier.</strong> Keep bursty workloads on‑demand. Add provisioned concurrency for predictable peaks. Move steady, large, or topology‑sensitive models to dedicated GPUs.</li></ol><h3>Build the benchmark matrix</h3><p>Vary one control at a time so each result has a defensible cause. Test JSON and binary payloads for multimodal inputs, and record both cold and warm states.</p><pre>ID Memory Concurrency Batch Context State p50 p95 p99 Throughput Errors Cold starts Cost/request<br>            <br>A1 low 4 1 short cold<br>A2 low 4 1 short warm<br>B1 medium 8 4 medium cold<br>B2 medium 8 4 medium warm<br>C1 high 16 8 long cold<br>C2 high 16 8 long warm</pre><p>For generative models, add time to first token, output tokens per second, and concurrent sequences. For classifiers, record requests per second and batch‑processing time.</p><p>The expected pattern is not necessarily that larger configurations always win. Increased concurrency may improve throughput while degrading p99. Additional memory may shorten model loading without changing GPU decode speed.</p><h3>Production path on a purpose‑built AI cloud</h3><p>Serverless inference can be one tier within a broader CoreWeave AI platform. Store versioned artifacts in managed object storage. Use a consistent container and model‑server contract. Deploy bursty versions through a serverless‑style API, then pin high‑volume models to dedicated Kubernetes GPU pools.</p><p>Mission Control can manage cluster lifecycle. NVMe local storage can stage large artifacts near workers. Multi‑GPU services can use non‑blocking InfiniBand when tensor‑parallel collectives require predictable bandwidth.</p><p>A dedicated deployment can mirror the serverless contract:</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br> name: textgenerationv1<br> labels:<br> servingtier: dedicated<br> model: textgenerationv1<br>spec:<br> replicas: 2<br> selector:<br> matchLabels:<br> app: textgenerationv1<br> template:<br> metadata:<br> labels:<br> app: textgenerationv1<br> accelerator: h100sxm80gb<br> spec:<br> containers:<br>  name: modelserver<br> image: registry.example/modelserver:v1<br> env:<br>  name: MODEL_URI<br> value: object://models/textgeneration/v1<br>  name: MAX_CONCURRENT_SEQUENCES<br> value: &quot;32&quot;<br> readinessProbe:<br> httpGet:<br> path: /ready<br> port: 8080<br> livenessProbe:<br> httpGet:<br> path: /health<br> port: 8080<br> resources:<br> limits:<br> nvidia.com/gpu: &quot;1&quot;</pre><p>Keep packaging, identity, telemetry, governance, and CI/CD consistent across tiers. That lets teams graduate from prototypes to dedicated capacity without having to rewrite the serving stack.</p><h3>Observability, governance, and operating model</h3><p>Observability and metrics are vital for managing serverless inference endpoints at scale.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7QDZjQ1tG88MhxvsPGQ11A.png" /></figure><p>Serverless reduces server administration, not platform accountability. Alice still owns reliability, governance, cost attribution, and the developer experience.</p><p>Collect these metrics:</p><ul><li>Cold‑start count and duration.</li><li>Queue time and queue age.</li><li>Model‑load time.</li><li>p50, p95, and p99 latency.</li><li>Time to first token and tokens per second.</li><li>Active and queued concurrency.</li><li>CPU, host‑memory, and GPU‑memory use.</li><li>Throttles, retries, and error rate.</li><li>Cost per endpoint, model, team, and tenant.</li></ul><p>Tracing should connect the API gateway, router, scheduler, worker, model server, object store, and downstream dependencies. Assign one request identifier across the complete path, including streamed responses.</p><p>Governance controls should cover model‑registry approval, artifact provenance, access policies, tenant quotas, audit logs, data retention, rollout approval, and rollback. Publish paved paths with predefined SLO tiers and cost ceilings. Engineers should receive self‑service deployment without receiving unbounded concurrency or spend.</p><h3>Closing thoughts</h3><p>Serverless inference is API‑based model serving in which a provider automatically allocates and scales infrastructure, potentially to zero. It hides server administration, but it does not remove constraints imposed by memory, queueing, model‑loading time, GPU kernels, network topology, or concurrency.</p><p>Use on‑demand serverless inference for intermittent workloads that tolerate cold starts. Use provisioned concurrency for predictable bursts and stricter p99 targets. Use dedicated GPUs for steady traffic, continuously resident models, long‑running generation, or topology‑sensitive multi‑GPU inference.</p><p>A purpose‑built AI cloud can combine a serverless‑style developer experience with Kubernetes‑native controls, managed storage, and dedicated GPU capacity. Before standardizing any serving tier, benchmark the same model artifact with realistic payloads, cold starts, bursts, retries, and saturation conditions.</p><h3>Sources</h3><ul><li><a href="https://docs.aws.amazon.com/sagemaker/latest/dg/serverlessendpoints.html">Deploy models with Amazon SageMaker Serverless Inference</a></li><li><a href="https://aws.amazon.com/blogs/machinelearning/introducingtheamazonsagemakerserverlessinferencebenchmarkingtoolkit">Introducing the Amazon SageMaker Serverless Inference Benchmarking Toolkit | Artificial Intelligence</a></li><li><a href="https://arxiv.org/abs/2401.14351">[2401.14351] ServerlessLLM: Low‑Latency Serverless Inference for Large Language Models</a></li><li><a href="https://huggingface.co/learn/cookbook/en/enterprise_hub_serverless_inference_api">Serverless Inference API ‑ Hugging Face</a></li><li><a href="https://www.usenix.org/conference/atc22/presentation/lijie">Tetris: Memory‑efficient Serverless Inference through Tensor Sharing</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5bb4232b41eb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/online-inference/serverless-inference-how-autoscaling-powers-ai-model-serving-5bb4232b41eb">Serverless inference: How autoscaling powers AI model serving</a> was originally published in <a href="https://medium.com/online-inference">Online Inference</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RAG evaluation metrics]]></title>
            <link>https://medium.com/online-inference/rag-evaluation-metrics-cec13e8f2932?source=rss----52acf6e3d9be---4</link>
            <guid isPermaLink="false">https://medium.com/p/cec13e8f2932</guid>
            <category><![CDATA[agentic-rag]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[rag-evaluation]]></category>
            <category><![CDATA[rag-evaluation-metrics]]></category>
            <dc:creator><![CDATA[David Davies]]></dc:creator>
            <pubDate>Mon, 24 Aug 2026 23:20:46 GMT</pubDate>
            <atom:updated>2026-08-24T23:20:46.550Z</atom:updated>
            <content:encoded><![CDATA[<p>RAG evaluation metrics assess two interrelated behaviors: whether a system retrieves the relevant external evidence and whether the LLM turns that evidence into accurate, grounded, and safe answers. Separating these signals lets an AI engineer distinguish search failures from generation failures, rather than debugging a single, opaque answer‑quality score.</p><p>A Retrieval‑Augmented Generation pipeline has at least two independently fallible components. The retriever can miss relevant documents, rank weak passages above useful ones, or return stale content. The generator can ignore good evidence, misinterpret it, or introduce unsupported claims. A single end‑to‑end score cannot reliably tell Sonia which component to change.</p><p>RAG evaluation metrics measure how well a system retrieves external knowledge and uses it to produce grounded, useful answers. They add evidence‑oriented measurements to familiar generation‑quality measurements. Retrieval metrics examine document coverage and ranking. Generation metrics examine whether the response addresses the query, uses the retrieved evidence faithfully, and satisfies application‑specific requirements.</p><p>Regular LLM evaluation metrics are insufficient because RAG quality depends on more than the prompt and model. Chunk boundaries, embedding models, lexical search, metadata filters, rerankers, top‑K settings, corpus freshness, document permissions, and context assembly can all change the result. The same LLM and prompt can produce different answers when any of these inputs change. A practical evaluation program therefore needs several layers:</p><ul><li>A minimum diagnostic set based on the RAG Triad</li><li>Retriever metrics such as Precision@K, Recall@K, MRR, and nDCG</li><li>Generator metrics such as faithfulness, answer relevance, and factual correctness</li><li>Per‑example traces and failure inspection</li><li>Versioned datasets, prompts, scorers, corpora, and pipeline configurations</li><li>Production monitoring for quality, latency, cost, and drift The goal is not to maximize every metric. It is to create measurements that identify the next engineering action.</li></ul><h3>The mechanism: from query to context to answer</h3><p>A RAG system is a chain of operations rather than one model call. A typical request follows this execution path:</p><ol><li>Receive the user query and session context.</li><li>Rewrite or decompose the query when needed.</li><li>Run embedding‑based, lexical, or hybrid search.</li><li>Retrieve candidate documents or chunks.</li><li>Apply metadata and permission filters.</li><li>Rerank the candidates.</li><li>Select and assemble the final context.</li><li>Construct the model prompt.</li><li>Generate an answer.</li><li>Add citations, validate the format, or run safety checks.</li><li>Return the final response.</li></ol><p>Each stage needs an inspection artifact or metric. Query rewriting can be checked for intent preservation. Retrieval can be scored with recall and precision. Reranking can be measured with nDCG or MRR. Context assembly can be checked for truncation and duplicated chunks. Generation can be scored on faithfulness, relevance, completeness, and adherence to format.</p><p>Traces should capture the user input, rewritten queries, retrieved chunk IDs, raw retrieval scores, reranking scores, document versions, assembled context, prompt version, model parameters, tool calls, output, latency, token usage, and scorer results. Without this record, a regression may be visible but not reproducible.</p><p>Consider two responses that both receive an answer‑correctness score of zero. In the first case, the relevant document was never retrieved. In the second, the exact evidence was present, but the model ignored it. The first case calls for work on corpus coverage, embeddings, filters, or query rewriting. The second calls for changes to the prompt, model, or decoding. Evaluation design should preserve that distinction.</p><h3>How RAG metrics differ from regular LLM evaluation metrics</h3><p>Regular LLM evaluation asks whether an output is useful, correct, coherent, or similar to a reference answer. RAG evaluation asks additional questions: did the system retrieve the necessary evidence, rank it well, place it in the prompt, and generate an answer supported by it?</p><p>Generation‑only measurements include:</p><ul><li>Helpfulness and instruction following</li><li>Fluency and coherence</li><li>Exact match</li><li>Semantic similarity</li><li>Style and format adherence</li><li>Safety‑policy compliance</li></ul><p>RAG metrics add:</p><ul><li>Context relevance</li><li>Precision@K and Recall@K</li><li>Context precision and context recall</li><li>MRR and nDCG</li><li>Context‑entity recall</li><li>Groundedness or faithfulness</li><li>Citation support and citation accuracy</li></ul><p>Traditional NLP metrics such as BLEU and ROUGE measure lexical overlap with a reference. They can be useful for tightly constrained responses, but they do not establish that an answer is grounded. An unsupported answer can have high overlap, while a correct paraphrase can have low overlap. Embedding similarity handles paraphrases better but can still assign a high score to a semantically related answer containing a critical factual error.</p><p>RAG evaluation must also account for dynamic knowledge. Documents are updated, deleted, or hidden by changing permissions. Chunking and document IDs change. Approximate nearest‑neighbor search can introduce variability in retrieval. Consequently, an old reference answer may no longer describe the current system’s correct behavior.</p><p>End‑to‑end answer quality remains important because users experience the final response, not the intermediate metrics. It should not, however, be the only score used for root‑cause analysis.</p><h3>The RAG Triad as a practical organizing model</h3><p>The RAG Triad organizes evaluation around three questions:</p><ol><li>Was the retrieved context relevant to the query?</li><li>Was the generated answer grounded in that context?</li><li>Did the answer address the user’s request?</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sx1_3PkS-wOMdGnNwdrusA.png" /></figure><p>These correspond to retrieval quality, evidence use, and user‑facing response quality. Together, they form a compact initial framework that prevents teams from collapsing RAG behavior into one answer score.</p><p>The terminology varies across RAG evaluation frameworks. Context relevance may appear as context precision or contextual relevancy. Groundedness may be called faithfulness. Answer relevance may be called response relevancy. Ragas and other metric libraries use these related concepts while differing in formulas, prompts, and required fields.</p><p>The triad is a minimum diagnostic set rather than a complete production scorecard. A system can have high context relevance, faithfulness, and answer relevance while still exposing restricted documents, citing stale policies, taking 20 seconds to respond, or failing across a multi‑turn session. Add operational, safety, freshness, and task‑specific metrics according to the application’s risks.</p><h3>Context relevance</h3><p>Context relevance measures whether retrieved passages help answer the query. It evaluates the evidence before asking whether the final answer is correct.</p><p>Relevance can be labeled in several ways:</p><ul><li>Human reviewers can grade each chunk as irrelevant, partially relevant, or fully relevant.</li><li>LLM judges can compare a query with each retrieved chunk and return a score and rationale.</li><li>Embedding similarity and lexical overlap can provide inexpensive proxy scores.</li><li>Known relevant document IDs can supply deterministic labels for curated test cases.</li></ul><p>Each method has limitations. Human labels are expensive and can vary between reviewers. LLM judges can be biased by writing style or model familiarity. Embedding similarity can reward topically related passages that do not contain the required facts. Lexical scores can miss paraphrases.</p><p>Context relevance is not context recall. Every retrieved chunk might be relevant while the retrieval set still omits a required policy exception. Inspect low‑scoring examples because they often reveal poor chunk boundaries, incorrect metadata filters, duplicated passages, or reranking errors.</p><h3>Groundedness and faithfulness</h3><p>Groundedness and faithfulness measure whether claims in the generated answer are supported by the retrieved context. This is a claim‑level support test, not a general measure of truth.</p><p>A practical scorer separates the answer into factual claims, finds supporting or contradicting evidence in the supplied context, and aggregates the results. It should distinguish supported claims, unsupported claims, contradicted claims, and non‑factual statements.</p><p>Several edge cases require explicit policy decisions. A model might state a correct fact from pretraining that is absent from the retrieved context. That answer can be factually correct but unfaithful to the RAG evidence. The context itself might contain conflicting or outdated statements. A model might also refuse even though the supplied context contains a complete answer.</p><p>LLM judges can automate claim extraction and support checking, but they should be calibrated against human‑reviewed cases. For legal, medical, financial, or safety‑sensitive workloads, periodically measure agreement between the automated judge and qualified reviewers.</p><h3>Answer relevance</h3><p>Answer relevance measures how directly and completely the final response satisfies the user’s intent. It includes topic alignment, instruction following, requested detail, and output format.</p><p>Relevance differs from correctness. An answer can be directly responsive but factually wrong. It can also be correct yet fail to follow a request for a table, concise summary, or step‑by‑step procedure.</p><p>Common scoring methods include comparison with a reference answer, semantic similarity, rubric‑based LLM judging, and human review. A useful rubric might ask whether the answer addresses every requested sub‑question, avoids unrelated information, and follows the requested format.</p><p>Always interpret answer relevance alongside groundedness. A fluent, direct response should not pass merely because it sounds helpful. If its claims are unsupported by retrieved evidence, the system has not demonstrated reliable RAG behavior.</p><h3>Retrieval metrics: Measuring whether the system found the right evidence</h3><p>Retrieval metrics evaluate the retriever independently from the generator. They let engineers tune chunk size, embedding models, hybrid‑search weights, metadata filters, rerankers, and top‑K without allowing a capable LLM to hide weak retrieval.</p><p>The main metrics serve different purposes:</p><ul><li>Precision@K measures the proportion of retrieved items that are relevant.</li><li>Recall@K measures the number of known relevant items retrieved.</li><li>Hit rate records whether at least one relevant item appears.</li><li>MRR measures how early the first relevant result appears.</li><li>nDCG measures ranking quality with graded relevance.</li><li>Context precision evaluates whether useful chunks appear ahead of less useful chunks.</li><li>Context recall checks whether the retrieved content contains the information needed for the expected answer.</li><li>Context‑entity recall measures coverage of required entities, such as people, products, dates, or account fields.</li></ul><p>Labels can come from known document IDs, human relevance judgments, synthetic question‑document pairs, or LLM‑judged relevance. Each evaluation run should record how the labels were produced.</p><p>Compute retrieval metrics before generation. Otherwise, an LLM might answer from pretraining even though the retriever failed, creating a misleading impression that the pipeline is healthy.</p><h3>Precision@K and context precision</h3><p>Precision@K is the fraction of the top‑K retrieved items that are relevant:</p><pre>Precision@K = relevant items in top K / K</pre><p>If three of five retrieved chunks are relevant, Precision@5 is 0.6. High precision reduces prompt noise, token usage, and the opportunity for irrelevant passages to distract the generator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*164uz8qXKk1N2y6fEDcikg.png" /></figure><p>Context precision is a RAG‑oriented extension that also considers ordering. Retrieving useful passages first receives a better score than placing them after irrelevant passages.</p><p>Precision should not be optimized in isolation. A system that retrieves one highly relevant chunk can have perfect Precision@1 while missing three other documents needed for a complete answer. This becomes important for multi‑hop questions and policies with exceptions.</p><p>Use precision‑oriented metrics when prompt space is constrained, irrelevant context increases hallucination risk, or retrieved passages are expensive to process. Tune K while watching both precision and recall.</p><h3>Recall@K and context recall</h3><p>Recall@K is the fraction of all known relevant items found in the top‑K results:</p><pre>Recall@K = relevant items in top K / all known relevant items</pre><p>If four documents are labeled relevant and the retriever returns three, Recall@K is 0.75. Context recall focuses on information rather than document identity. It asks whether the retrieved text contains the facts required to construct the expected answer.</p><p>Recall is particularly important for support, legal, medical, and internal knowledge‑base applications. Missing an exception, contraindication, or eligibility rule can materially change the response.</p><p>Increasing K often raises recall, but it also adds prompt noise, latency, and token cost. Additional passages can introduce contradictions or push useful evidence beyond the model’s context limit. Evaluate recall across several K values and pair it with precision, latency, and generation faithfulness.</p><h3>MRR, nDCG, and rank‑sensitive metrics</h3><p>Mean reciprocal rank measures where the first relevant result appears. A query with its first relevant result at position 1 receives 1.0. Position 2 receives 0.5, and position 5 receives 0.2. MRR averages this value across queries.</p><p>Normalized discounted cumulative gain, or nDCG, supports graded relevance. A passage containing the complete answer can receive a higher relevance grade than one containing background information. The score rewards placing highly relevant passages near the top.</p><p>Rank matters because earlier chunks are more likely to survive truncation and influence generation. Some prompt templates also place the highest‑ranked evidence first, giving it greater practical weight.</p><p>Use rank‑sensitive metrics when evaluating cross‑encoder rerankers, hybrid search, query expansion, or long‑context pipelines. If a reranker does not improve nDCG on important slices, its added latency may not be justified.</p><h3>Generation metrics: measuring whether the answer used the evidence well</h3><p>Generation metrics evaluate the output after retrieval, context assembly, prompt construction, and decoding. They determine whether good evidence was transformed into a correct and useful response.</p><p>A production scorecard can include:</p><ul><li>Faithfulness or groundedness</li><li>Factual correctness</li><li>Answer relevance</li><li>Completeness</li><li>Coherence</li><li>Refusal correctness</li><li>Citation accuracy and support</li><li>Required‑format adherence</li><li>Tone and policy compliance</li></ul><p>Good retrieval combined with poor generation usually points to the prompt, model choice, decoding settings, context presentation, or conflicting instructions. Poor retrieval combined with a plausible answer can indicate that the model is relying on unsupported prior knowledge.</p><p>Ragas includes common metrics such as response relevancy and faithfulness. Evaluator services such as Patronus AI can support model‑based judging for selected risk criteria. Domain‑specific behavior still requires explicit rubrics and calibration, regardless of the metric provider.</p><p>Generation evaluation can be reference‑based or reference‑free. Most mature RAG evaluation frameworks use both.</p><h3>Reference-based evaluation</h3><p>Reference‑based evaluation compares the generated response with a known answer, gold label, or expected set of facts.</p><p>Possible measurements include:</p><ul><li>Exact match for stable, constrained outputs</li><li>String presence for required wording or identifiers</li><li>Semantic similarity for acceptable paraphrases</li><li>Factual correctness against labeled claims</li><li>Rubric‑based LLM judging against a gold response</li><li>BLEU or ROUGE for tasks where lexical overlap is meaningful</li></ul><p>Reference‑based methods are useful for regression tests, stable FAQs, structured extraction, compliance wording, and questions with clear ground truth. They are often easier to calibrate because evaluators can compare two concrete answers.</p><p>Their limitations become visible in dynamic applications. References are expensive to create and maintain. Many questions have several valid responses. An answer can disagree lexically with the reference while remaining correct. References also drift when the underlying corpus changes.</p><p>Version each reference with the corpus snapshot or document versions from which it was created.</p><h3>Reference-free evaluation</h3><p>Reference‑free evaluation judges an answer against the query, retrieved context, and task rubric without requiring a gold response.</p><p>It can assess:</p><ul><li>Faithfulness to context</li><li>Coverage of information present in context</li><li>Answer relevance</li><li>Tone and structure</li><li>Citation support</li><li>Refusal behavior</li><li>Policy compliance</li></ul><p>This approach is necessary for long‑tail production queries and rapidly changing knowledge bases where writing a reference for every request is impractical. It also supports evaluation directly from sampled production traces.</p><p>The method depends heavily on judge quality and rubric design. A judge cannot detect missing evidence if the provided context is incomplete and the rubric does not ask about completeness. Scores can also vary across evaluator models or prompt versions.</p><p>Calibrate reference‑free scorers with reviewed examples, disagreement analysis, and recurring human audits.</p><h3>Factual correctness versus faithfulness</h3><p>Factual correctness asks whether the claims are true. Faithfulness asks whether the claims are supported by the retrieved context. They are related but not interchangeable.</p><p>The scores can diverge in two important ways:</p><ul><li>A claim can be true but unsupported because the LLM supplied it from pretraining.</li><li>A claim can be faithful to retrieved context that is outdated, incomplete, or wrong.</li></ul><p>Score both when the corpus can contain stale or conflicting information. Factual correctness may require an authoritative reference, trusted database, or separate verification process. Faithfulness can be evaluated directly against the context passed to the model.</p><p>Citation accuracy is useful but does not prove correctness. A citation can point to an irrelevant passage, and a cited source can itself be outdated. Evaluate whether each citation supports the associated claim and whether the source is authoritative and current.</p><h3>How to independently evaluate the retriever and generator</h3><p>Evaluate the two components separately before trusting an end‑to‑end result:</p><ol><li>Run the retriever on a labeled query set without calling the generator.</li><li>Compute document‑level and rank‑sensitive metrics.</li><li>Inspect the returned chunks, scores, filters, and document versions.</li><li>Freeze the retrieved contexts.</li><li>Run one or more generators against exactly those contexts.</li><li>Score faithfulness, answer relevance, completeness, and correctness.</li><li>Compare the component results with end‑to‑end user outcomes.</li></ol><p>Each test row should contain a query, expected relevant document IDs, optional reference answer, required facts, and metadata such as topic, difficulty, source age, language, and user segment.</p><p>Store datasets, prompts, scorer definitions, retriever configurations, and model settings as versioned assets. W&amp;B Weave Traces can record retrieval operations, prompt construction, tool calls, model outputs, and scorer results for each request. Weave Evaluations can then run the same dataset and scorers across different pipeline versions, making it possible to compare a new reranker, prompt, or model without losing per‑example evidence.</p><p>Common patterns include low retrieval recall followed by low faithfulness, or high recall followed by low answer relevance. The first suggests missing evidence and model compensation. The second suggests synthesis or instruction‑following problems.</p><h3>A failure attribution matrix</h3><p>The following matrix converts metric patterns into hypotheses rather than definitive diagnoses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cxNtB-y059aVeAEjHtm5OA.png" /></figure><p>A single metric rarely proves a root cause. Confirm each hypothesis by inspecting traces, retrieved chunks, prompts, outputs, and judge rationales.</p><h3>Worked example: compute RAG metrics on a small eval set</h3><p>A useful RAG eval begins with inspectable examples rather than a dashboard. The following standard‑library Python program defines three support questions, computes Precision@K and Recall@K, and applies a deliberately simple faithfulness stub.</p><p>Save the code as rag_eval.py and run it with python rag_eval.py.</p><pre>import re<br>from statistics import mean<br><br>examples = [<br>{<br> &quot;id&quot;: &quot;support001&quot;,<br> &quot;query&quot;: &quot;How long is a passwordreset link valid?&quot;,<br> &quot;relevant_ids&quot;: [&quot;doc_reset&quot;, &quot;doc_security&quot;],<br> &quot;retrieved_ids&quot;: [&quot;doc_reset&quot;, &quot;doc_billing&quot;, &quot;doc_security&quot;],<br> &quot;context&quot;: [<br> &quot;Passwordreset links expire after 30 minutes.&quot;,<br> &quot;Billing invoices are generated on the first day of each month.&quot;,<br> &quot;Administrators can revoke active passwordreset links.&quot;<br> ],<br> &quot;answer&quot;: (<br> &quot;Passwordreset links expire after 30 minutes. &quot;<br> &quot;Administrators can revoke active passwordreset links.&quot;<br> ),<br> &quot;reference_answer&quot;: (<br> &quot;A passwordreset link expires after 30 minutes and can be &quot;<br> &quot;revoked by an administrator.&quot;<br> ),<br> &quot;tags&quot;: {<br> &quot;topic&quot;: &quot;authentication&quot;,<br> &quot;difficulty&quot;: &quot;easy&quot;,<br> &quot;source_age&quot;: &quot;current&quot;,<br> &quot;intent&quot;: &quot;policy_lookup&quot;<br> }<br> },<br> {<br> &quot;id&quot;: &quot;support002&quot;,<br> &quot;query&quot;: &quot;Where does an approved refund go?&quot;,<br> &quot;relevant_ids&quot;: [&quot;doc_refunds&quot;],<br> &quot;retrieved_ids&quot;: [&quot;doc_shipping&quot;, &quot;doc_refunds&quot;, &quot;doc_returns&quot;],<br> &quot;context&quot;: [<br> &quot;Standard shipping takes three to five business days.&quot;,<br> &quot;Refunds return to the original payment method within five to ten business days.&quot;,<br> &quot;Returned products must include their original accessories.&quot;<br> ],<br> &quot;answer&quot;: (<br> &quot;Refunds return to the original payment method within five &quot;<br> &quot;to ten business days.&quot;<br> ),<br> &quot;reference_answer&quot;: (<br> &quot;Approved refunds are sent to the original payment method.&quot;<br> ),<br> &quot;tags&quot;: {<br> &quot;topic&quot;: &quot;billing&quot;,<br> &quot;difficulty&quot;: &quot;easy&quot;,<br> &quot;source_age&quot;: &quot;current&quot;,<br> &quot;intent&quot;: &quot;policy_lookup&quot;<br> }<br> },<br> {<br> &quot;id&quot;: &quot;support003&quot;,<br> &quot;query&quot;: &quot;Which plans support SAML SSO and SCIM?&quot;,<br> &quot;relevant_ids&quot;: [&quot;doc_sso&quot;, &quot;doc_enterprise&quot;],<br> &quot;retrieved_ids&quot;: [&quot;doc_sso&quot;, &quot;doc_api&quot;, &quot;doc_billing&quot;],<br> &quot;context&quot;: [<br> &quot;SAML SSO is available on Enterprise plans.&quot;,<br> &quot;API keys can be created by workspace administrators.&quot;,<br> &quot;Annual billing is available on Pro and Enterprise plans.&quot;<br> ],<br> &quot;answer&quot;: (<br> &quot;SAML SSO is available on Enterprise plans. &quot;<br> &quot;SCIM is available on all paid plans.&quot;<br> ),<br> &quot;reference_answer&quot;: (<br> &quot;SAML SSO and SCIM are available on Enterprise plans.&quot;<br> ),<br> &quot;tags&quot;: {<br> &quot;topic&quot;: &quot;enterprise_security&quot;,<br> &quot;difficulty&quot;: &quot;medium&quot;,<br> &quot;source_age&quot;: &quot;current&quot;,<br> &quot;intent&quot;: &quot;feature_comparison&quot;<br> }<br> }<br>]<br>def precision_at_k(retrieved_ids, relevant_ids, k):<br> top_k = retrieved_ids[:k]<br> if not top_k:<br> return 0.0<br> relevant_retrieved = set(top_k) &amp; set(relevant_ids)<br> return len(relevant_retrieved) / len(top_k)<br>def recall_at_k(retrieved_ids, relevant_ids, k):<br> if not relevant_ids:<br> return 1.0<br> top_k = retrieved_ids[:k]<br> relevant_retrieved = set(top_k) &amp; set(relevant_ids)<br> return len(relevant_retrieved) / len(set(relevant_ids))<br>def normalize(text):<br> return re.sub(r&quot;\s+&quot;, &quot; &quot;, re.sub(r&quot;[^az09 ]&quot;, &quot;&quot;, text.lower())).strip()<br>def faithfulness_stub(answer, context):<br> &quot;&quot;&quot;<br> Demonstration only.<br> Splits the answer into claims and checks whether each normalized claim<br> appears in the retrieved context. A production scorer should support<br> paraphrases, contradiction detection, and claimlevel reasoning.<br> &quot;&quot;&quot;<br> claims = [<br> claim.strip()<br> for claim in re.split(r&quot;[.!?]+&quot;, answer)<br> if claim.strip()<br> ]<br> normalized_context = normalize(&quot; &quot;.join(context))<br> checks = []<br> for claim in claims:<br> supported = normalize(claim) in normalized_context<br> checks.append({<br> &quot;claim&quot;: claim,<br> &quot;supported&quot;: supported<br> })<br> score = (<br> sum(item[&quot;supported&quot;] for item in checks) / len(checks)<br> if checks else 1.0<br> )<br> unsupported = [<br> item[&quot;claim&quot;] for item in checks if not item[&quot;supported&quot;]<br> ]<br> rationale = (<br> &quot;All claims were found in the retrieved context.&quot;<br> if not unsupported<br> else &quot;Unsupported claims: &quot; + &quot;; &quot;.join(unsupported)<br> )<br> return {<br> &quot;score&quot;: score,<br> &quot;rationale&quot;: rationale,<br> &quot;checks&quot;: checks<br> }<br>results = []<br>for example in examples:<br> precision = precision_at_k(<br> example[&quot;retrieved_ids&quot;],<br> example[&quot;relevant_ids&quot;],<br> k=3<br> )<br> recall = recall_at_k(<br> example[&quot;retrieved_ids&quot;],<br> example[&quot;relevant_ids&quot;],<br> k=3<br> )<br> faithfulness = faithfulness_stub(<br> example[&quot;answer&quot;],<br> example[&quot;context&quot;]<br> )<br> row = {<br> &quot;id&quot;: example[&quot;id&quot;],<br> &quot;precision_at_3&quot;: precision,<br> &quot;recall_at_3&quot;: recall,<br> &quot;faithfulness&quot;: faithfulness[&quot;score&quot;],<br> &quot;rationale&quot;: faithfulness[&quot;rationale&quot;],<br> &quot;tags&quot;: example[&quot;tags&quot;]<br> }<br> results.append(row)<br> print(<br> f&#39;{row[&quot;id&quot;]}: &#39;<br> f&#39;P@3={precision:.2f}, &#39;<br> f&#39;R@3={recall:.2f}, &#39;<br> f&#39;faithfulness={faithfulness[&quot;score&quot;]:.2f}&#39;<br> )<br> print(f&#39; {faithfulness[&quot;rationale&quot;]}&#39;)<br>print(&quot;\nAggregate metrics&quot;)<br>print(f&#39;Precision@3: {mean(r[&quot;precision_at_3&quot;] for r in results):.2f}&#39;)<br>print(f&#39;Recall@3: {mean(r[&quot;recall_at_3&quot;] for r in results):.2f}&#39;)<br>print(f&#39;Faithfulness: {mean(r[&quot;faithfulness&quot;] for r in results):.2f}&#39;)</pre><p>Expected output:</p><pre>support001: P@3=0.67, R@3=1.00, faithfulness=1.00<br> All claims were found in the retrieved context.<br>support002: P@3=0.33, R@3=1.00, faithfulness=1.00<br> All claims were found in the retrieved context.<br>support003: P@3=0.33, R@3=0.50, faithfulness=0.50<br> Unsupported claims: SCIM is available on all paid plans<br><br>Aggregate metrics<br>Precision@3: 0.44<br>Recall@3: 0.83<br>Faithfulness: 0.83</pre><p>The aggregate faithfulness score looks acceptable, but the per‑example result exposes an unsupported security‑related claim. This is why RAG evals need tables and traces, not only averages.</p><h3>Step 1: define an eval dataset</h3><p>Each example should contain enough information to score retrieval and generation independently:</p><ul><li>query: The user request</li><li>relevant_ids: Documents or chunks expected to contain the evidence</li><li>retrieved_ids: Results returned by the tested retriever</li><li>context: Text actually placed in the model prompt</li><li>answer: Generated response</li><li>reference_answer: Optional gold response</li><li>tags: Metadata for slicing and analysis</li></ul><p>Tags such as topic, difficulty, source age, language, customer tier, and user intent make aggregate results actionable. A small drop concentrated in enterprise‑security queries may matter more than a larger drop in low‑risk informational queries.</p><p>Begin with curated or synthetic examples, then replace them with sampled production traces and reviewed user questions. Keep a stable benchmark for regression testing and a changing workload set for current behavior.</p><p>When comparing corpora, retrievers, or prompts over time, store the dataset as a versioned artifact. Record the document snapshot and label‑generation method alongside it.</p><h3>Step 2: implement retrieval metrics</h3><p>The example implements both retrieval metrics with set intersections. Their denominators create different interpretations:</p><pre>Precision@K denominator = number of retrieved items<br>Recall@K denominator = number of known relevant items</pre><p>Precision therefore diagnoses noise. Recall diagnoses missing evidence. The third example retrieves one of two relevant documents, so Recall@3 is 0.5. Because only one of three retrieved documents is relevant, Precision@3 is 0.33.</p><p>Add MRR when the position of the first useful result matters. Add nDCG when passages have graded relevance or when reranking is the main experiment.</p><p>Treat the labels as incomplete observations rather than unquestionable truth. An unjudged document may be useful even if it is not listed in relevant_ids. Review retrieved passages that appear relevant but are counted as false positives, then update the label set or adopt graded relevance.</p><h3>Step 3: implement generation and faithfulness checks</h3><p>The demonstration scorer exposes a useful interface: it returns a numeric score, a rationale, and claim‑level details. Its exact‑string logic is intentionally limited. It will reject valid paraphrases and cannot recognize contradictions.</p><p>A production faithfulness scorer normally performs these operations:</p><ol><li>Extract factual claims from the answer.</li><li>Find evidence related to each claim.</li><li>Classify each claim as supported, unsupported, contradicted, or unverifiable.</li><li>Return an aggregate score and claim‑level rationale.</li><li>Escalate ambiguous or high‑risk cases for review.</li></ol><p>This is often implemented with an LLM judge, a Ragas faithfulness metric, a Patronus AI evaluator, or a custom Weave scorer. Add separate scorers for answer relevance and factual correctness because faithfulness does not measure either one completely.</p><p>With W&amp;B Weave Evaluations, the same scorer set can run across pipeline variants. For example, compare prompt‑v7 with prompt‑v8 while holding the retrieved contexts fixed, then compare retriever‑v3 with retriever‑v4 while holding the generation configuration fixed.</p><h3>Step 4: inspect examples before optimizing averages</h3><p>Average scores can hide an unsafe hallucination, a complete failure for one language, or low recall for a high‑value customer segment. Sort examples by combinations that reveal suspicious behavior:</p><ul><li>Low recall and high answer relevance can indicate unsupported model knowledge.</li><li>High context relevance and low groundedness can indicate prompt or model problems.</li><li>High faithfulness and low completeness can indicate omitted evidence.</li><li>High scores with old sources can indicate reference drift.</li><li>High variance across repeated judge runs can indicate evaluator instability.</li></ul><p>For every failed example, inspect the query, rewritten query, retrieved chunks, ranking scores, assembled prompt, output, judge rationale, latency, and metadata.</p><p>Trace‑based inspection is especially important for agentic pipelines. A final failure may originate in a query‑rewriting tool call several steps before retrieval. Metrics identify which traces deserve attention, while the traces show what happened.</p><h3>Building a RAG evaluation framework that survives real workloads</h3><p>A RAG evaluation framework is the repeatable system connecting datasets, labels, scorers, traces, baselines, pipeline versions, reports, alert thresholds, and human‑review workflows. A metric library is one component of that system.</p><p>The framework should include:</p><ul><li>Versioned evaluation datasets</li><li>Document‑level or chunk‑level relevance labels</li><li>Gold answers or required facts where available</li><li>Reference‑free generation rubrics</li><li>Versioned scorer prompts and evaluator models</li><li>Retriever, prompt, model, and corpus versions</li><li>Per‑example results and aggregate reports</li><li>Slice‑specific regression thresholds</li><li>Production monitors</li><li>Human‑review and label‑correction queues</li></ul><p>Ragas, DeepEval, and similar libraries provide implementations of common RAG metrics. They do not by themselves solve dataset governance, trace storage, experiment comparison, production sampling, or team review.</p><p>A concrete Weave workflow is to trace retrieval and generation operations, create a Weave Dataset from curated rows or production traces, define deterministic and model‑based scorers, and run Weave Evaluations against candidate pipeline versions. The resulting comparison should retain links between each score and its trace so reviewers can inspect low‑scoring calls.</p><p>W&amp;B Models is relevant when retrieval depends on trained components. Store embedding datasets, fine‑tuned rerankers, and corpus snapshots as Artifacts. Track model‑training experiments and register promoted reranker versions so a RAG regression can be connected to the exact model and data change that produced it.</p><p>For lightweight metric logging, a local evaluation can also report aggregates and examples to W&amp;B:</p><pre>import wandb<br>from statistics import mean<br><br>wandb.login()<br>run = wandb.init(<br> project=&quot;ragevaluationmetrics&quot;,<br> job_type=&quot;evaluation&quot;,<br> config={<br> &quot;retriever&quot;: &quot;hybridv3&quot;,<br> &quot;top_k&quot;: 3,<br> &quot;prompt_version&quot;: &quot;supportv7&quot;<br> }<br>)<br>table = wandb.Table(<br> columns=[<br> &quot;example_id&quot;,<br> &quot;precision_at_3&quot;,<br> &quot;recall_at_3&quot;,<br> &quot;faithfulness&quot;,<br> &quot;rationale&quot;<br> ]<br>)<br>for row in results:<br> table.add_data(<br> row[&quot;id&quot;],<br> row[&quot;precision_at_3&quot;],<br> row[&quot;recall_at_3&quot;],<br> row[&quot;faithfulness&quot;],<br> row[&quot;rationale&quot;]<br> )<br>wandb.log({<br> &quot;eval/examples&quot;: table,<br> &quot;eval/precision_at_3&quot;: mean(r[&quot;precision_at_3&quot;] for r in results),<br> &quot;eval/recall_at_3&quot;: mean(r[&quot;recall_at_3&quot;] for r in results),<br> &quot;eval/faithfulness&quot;: mean(r[&quot;faithfulness&quot;] for r in results)<br>})<br>run.finish()</pre><p>Use the resulting table to compare aggregates without losing the individual failures that produced them.</p><h3>Choosing between Ragas, custom scorers, Patronus AI, and Weave</h3><p>Choose tools after identifying failure modes, required labels, risk, and operational constraints.</p><p>Ragas is useful when you need standard RAG metrics such as context precision, context recall, faithfulness, response relevancy, entity recall, or noise sensitivity. It provides reusable metric implementations and avoids rewriting common evaluator logic.</p><p>Custom scorers are necessary when the application has domain rules. Examples include verifying that every legal conclusion has a citation, requiring a support agent to ask for an account identifier, checking a medical response for an escalation statement, or rejecting answers that cite inaccessible documents.</p><p>Patronus AI can support evaluator‑model and policy‑focused judging workflows when external evaluation services fit the application’s security and risk requirements.</p><p>Weave serves as the workflow layer. It records Traces, manages evaluation datasets, executes scorers through Evaluations, compares pipeline versions, and monitors production behavior. It can run custom scorers or metrics supplied by other libraries rather than replacing them.</p><p>Avoid selecting a framework because it has the longest metric list. Begin with concrete failures and the decisions each score must support.</p><h3>Trade-offs in RAG evaluation metrics</h3><p>RAG evaluation involves trade‑offs in both pipeline tuning and evaluation design. The main axes are accuracy vs latency, cost vs throughput, flexibility vs determinism, recall vs precision, and automation vs trust.</p><p>Recall vs precision appears directly in retrieval. Increasing top‑K may recover missing evidence but introduce more irrelevant context. A reranker may improve context precision but add another inference step. Strict faithfulness thresholds may reduce unsupported answers while increasing refusals.</p><p>Automation vs trust appears when replacing human review with LLM judges. Automated judging makes broad coverage possible, but its validity depends on calibration and stable rubrics. High‑risk decisions may still require expert review.</p><p>Set thresholds according to task risk and user impact rather than copying a generic benchmark. A product‑search assistant and a medical‑information system should not use the same tolerance for unsupported claims.</p><p>Evaluation also has a budget. Apply inexpensive deterministic metrics broadly, then reserve expensive evaluators and human review for high‑risk slices, regressions, and ambiguous examples.</p><h3>Accuracy vs latency</h3><p>Larger top‑K values, hybrid retrieval, cross‑encoder reranking, and long‑context prompts can improve answerability while making requests slower. The quality gain should be measured alongside stage‑level latency.</p><p>Separate offline evaluation latency from online serving latency. A multi‑pass judge that takes several seconds may be acceptable in a nightly regression suite but unsuitable for synchronous production scoring.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KrMX3oyljBDVgrVBW4-NIg.png" /></figure><p>Record latency for query rewriting, retrieval, reranking, context assembly, generation, and post‑processing. This shows whether a quality improvement added 20 milliseconds to retrieval or two seconds to reranking.</p><p>Use heavy metrics offline and lighter monitors online. For example, calculate nDCG and claim‑level faithfulness during pre‑release evaluation, while production monitoring tracks empty retrievals, source age, retrieval‑score shifts, latency, and sampled faithfulness.</p><h3>Cost vs throughput</h3><p>LLM‑as‑judge evaluation can require several model calls per example. Claim extraction, evidence matching, contradiction checking, relevance scoring, and rationale generation multiply cost quickly.</p><p>Preserve throughput through:</p><ul><li>Batching evaluator requests</li><li>Caching identical query‑context‑answer combinations</li><li>Sampling production traffic</li><li>Stratifying samples by risk and user segment</li><li>Running deterministic metrics on all examples</li><li>Escalating disagreements to stronger judges</li><li>Reserving human review for ambiguous cases</li></ul><p>Do not optimize solely for inexpensive evaluation. Exact match and embedding similarity can miss subtle factual errors, unsupported qualifiers, or incorrect policy exceptions.</p><p>Use expensive judges for release gates, high‑risk slices, metric disagreements, and examples near decision thresholds. Monitor evaluator cost per pipeline run as a first‑class metric.</p><h3>Flexibility vs determinism</h3><p>Deterministic metrics such as exact match, string presence, document‑ID recall, and schema validation are reproducible but narrow. Flexible LLM judges can score nuanced, open‑ended answers but may vary across runs and model versions.</p><p>Version every part of a flexible evaluator:</p><ul><li>Judge‑model identifier</li><li>Judge prompt</li><li>Rubric text</li><li>Temperature and decoding settings</li><li>Few‑shot calibration examples</li><li>Claim‑segmentation logic</li><li>Aggregation method</li></ul><p>Measure agreement between judges and human reviewers. Also test whether the same evaluator produces stable scores on repeated runs. If the evaluator changes, rerun a calibration set before comparing new results with historical baselines.</p><p>Use deterministic metrics where the requirement can be expressed deterministically. Use flexible judges only for qualities that require interpretation.</p><h3>Challenges and edge cases in RAG evals</h3><p>RAG evaluation is difficult because retrieval and generation interact. A missing passage can cause hallucination, while a strong model can conceal missing retrieval by answering from pretraining. End‑to‑end success alone cannot reveal which behavior occurred.</p><p>Dynamic corpora create further complications. Documents are updated, deleted, renamed, or hidden by new permissions. Chunk IDs change after reprocessing. A previously correct reference may become stale even when the pipeline behaves correctly.</p><p>Evaluation sets should include more than straightforward answerable questions. Add unanswerable queries, conflicting evidence, multi‑hop questions, long documents, noisy context, multilingual requests, multi‑turn sessions, and permission‑sensitive cases. Agentic RAG requires tests for query rewriting, tool selection, and intermediate actions.</p><p>Label incompleteness and judge bias are persistent concerns. LLM judges may favor responses written in their preferred style or overlook domain‑specific errors. Use stress tests, adversarial cases, slice‑based reports, and expert‑reviewed calibration sets rather than relying only on random examples.</p><h3>Dynamic corpora and reference drift</h3><p>Changing documents can invalidate relevance labels, reference answers, and expected citations. A document ID may disappear even though equivalent information now exists in a replacement document.</p><p>Use one of two strategies:</p><ul><li>Pin a corpus snapshot for stable regression testing.</li><li>Refresh labels and references when testing current production behavior.</li></ul><p>Both are necessary in many systems. The pinned benchmark detects behavioral regressions against a controlled environment. The refreshed workload checks whether the application remains correct against current knowledge.</p><p>Store the corpus version, document checksums, chunking configuration, and access‑control state used for every evaluation run. W&amp;B Artifacts or another dataset‑versioning system can preserve this relationship. Without corpus versioning, a team may be unable to determine whether a score changed because of code, data, or labels.</p><h3>Unanswerable and conflicting queries</h3><p>Not every query should produce a direct answer. If the corpus lacks the required evidence, abstention may be the correct behavior.</p><p>Add metrics for:</p><ul><li>Refusal correctness</li><li>Abstention quality</li><li>Clarification‑request quality</li><li>Unsupported‑answer rate</li><li>Citation support</li><li>Confidence calibration</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dz3xagsfP2CwSUux4V0wvw.png" /></figure><p>Conflicting sources require a separate policy. The model may need to cite both positions, prefer the newest authoritative source, or explicitly state that the available evidence conflicts. Selecting one claim with unsupported certainty should fail even if that claim appears in one retrieved passage.</p><p>Include unanswerable and conflict cases in the evaluation dataset. They create the strongest pressure for the model to manufacture a plausible answer and therefore expose weaknesses that ordinary FAQ tests miss.</p><h3>Agentic RAG and tool-use metrics</h3><p>Agentic RAG adds planning, tool selection, query rewriting, repeated retrieval, and follow‑up actions. A final answer score cannot diagnose this execution path.</p><p>Useful metrics include:</p><ul><li>Tool‑call accuracy</li><li>Tool‑call precision, recall, and F1</li><li>Query‑rewrite intent preservation</li><li>Retrieval‑call efficiency</li><li>Step faithfulness</li><li>Task completion</li><li>Correct stopping behavior</li><li>Session‑level consistency</li><li>Recovery from failed tool calls</li></ul><p>Ragas includes metrics for agent and tool‑use scenarios. Weave Traces can record the full path from prompt to retrieval call, intermediate observation, follow‑up tool call, and final output.</p><p>Evaluate both the final state and the path. An agent can reach the correct answer through an unsafe or unnecessarily expensive sequence of actions. Conversely, one failed external call should not count as a reasoning failure if the agent recovers correctly.</p><h3>Monitoring RAG metrics after deployment</h3><p>Offline evals cover known workloads. Production monitoring reveals new query types, corpus drift, changing user behavior, permission failures, latency spikes, and interactions that the test set did not anticipate.</p><p>Useful online signals include:</p><ul><li>Empty retrieval rate</li><li>Retrieved‑document and topic distributions</li><li>Retrieval‑score shifts</li><li>Context‑relevance samples</li><li>Unsupported‑answer rate</li><li>Citation‑support failures</li><li>Source age</li><li>Latency by pipeline stage</li><li>Prompt and completion tokens</li><li>User feedback</li><li>Escalation and abandonment rates</li><li>Refusal and clarification rates</li></ul><p>Sample production traces into a review queue, label representative failures, and add them to versioned evaluation datasets. This keeps regression tests aligned with real use rather than assumptions made before launch.</p><p>W&amp;B Weave Traces can preserve failed requests and their intermediate operations. Weave Monitors can track quality and operational signals, while Evaluations can turn reviewed traces into repeatable tests for candidate fixes.</p><p>Do not automatically run the most expensive LLM judge on every production request unless application risk justifies it. Use stratified sampling, deterministic monitors, and targeted evaluation of high‑risk traffic.</p><h3>When not to use RAG evaluation metrics</h3><p>Do not use RAG‑specific metrics merely because an LLM is present. If there is no fallible retrieval step, or if every request receives a fixed and complete context, standard task metrics are usually clearer.</p><p>Examples include pure text generation, summarization over one supplied document, deterministic database lookup, structured extraction, classification, and tool‑only workflows. These systems may need factuality, format validity, task completion, safety, or latency metrics, but document‑retrieval recall may not describe any meaningful failure.</p><p>RAG metrics can also create false confidence when relevance labels are incomplete, judges are uncalibrated, or the corpus is not versioned. A precise‑looking score does not compensate for an invalid evaluation design.</p><p>Start with simpler task metrics when the primary risk is style, policy compliance, schema validity, user conversion, or another business outcome. Add RAG metrics only when evidence retrieval and grounding are independently fallible components that need diagnosis.</p><h3>Choose metrics that identify the next fix</h3><p>Choose metrics according to the engineering decision they support. A practical baseline is Recall@K, Precision@K or context precision, faithfulness, answer relevance, factual correctness where reliable references exist, and stage‑level latency and cost.</p><p>A useful score should lead to an action. Low recall suggests retrieval or corpus work. High recall with low faithfulness suggests prompt or model work. Good grounding with stale facts suggests corpus‑governance work. High quality with unacceptable latency suggests context, reranking, or serving changes.</p><p>The evaluation framework should connect those scores to traces, inspectable examples, and versioned pipeline changes. That connection makes regressions reproducible and improvements testable.</p><p>Start with a small, slice‑based dataset containing representative, difficult, unanswerable, and conflicting queries. Run retrieval and generation scores separately, inspect the failures, and establish a baseline. Then automate the same datasets, scorers, trace inspection, and regression thresholds in the evaluation platform already used by the team.</p><h3>Sources</h3><ul><li><a href="https://docs.ragas.io/en/stable/concepts/metrics/available_metrics">List of available metrics ‑ Ragas</a></li><li><a href="https://www.evidentlyai.com/llmguide/ragevaluation">A complete guide to RAG evaluation: metrics, testing and best practices</a></li><li><a href="https://www.pinecone.io/learn/series/vectordatabasesinproductionforbusyengineers/ragevaluation">RAG Evaluation: Don’t let customers tell you first | Pinecone</a></li><li><a href="https://deepeval.com/guides/guidesragevaluation">RAG Evaluation | DeepEval ‑ The LLM Evaluation Framework</a></li><li><a href="https://arxiv.org/html/2405.07437v2">Evaluation of Retrieval‑Augmented Generation: A Survey ‑ arXiv</a></li><li><a href="https://www.patronus.ai/llmtesting/ragevaluationmetrics">RAG Evaluation Metrics: Best Practices for Evaluating RAG Systems</a></li><li><a href="https://www.ibm.com/think/architectures/ragcookbook/resultevaluation">Result Evaluation for RAG: Metrics &amp; Best Practices ‑ IBM</a></li><li><a href="https://qdrant.tech/blog/ragevaluationguide">Best Practices in RAG Evaluation: A Comprehensive Guide ‑ Qdrant</a></li><li><a href="https://medium.com/@zilliz_learn/top10ragllmevaluationtoolsyoudontwanttomissa0bfabe9ae19">Top 10 RAG &amp; LLM Evaluation Tools You Don’t Want To Miss | by Zilliz</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cec13e8f2932" width="1" height="1" alt=""><hr><p><a href="https://medium.com/online-inference/rag-evaluation-metrics-cec13e8f2932">RAG evaluation metrics</a> was originally published in <a href="https://medium.com/online-inference">Online Inference</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mixture-of-Experts (MoE): Scaling AI models with smarter routing]]></title>
            <link>https://medium.com/online-inference/mixture-of-experts-moe-scaling-ai-models-with-smarter-routing-df48222f8ff9?source=rss----52acf6e3d9be---4</link>
            <guid isPermaLink="false">https://medium.com/p/df48222f8ff9</guid>
            <category><![CDATA[llm-architecture]]></category>
            <category><![CDATA[llm-optimization]]></category>
            <category><![CDATA[mixture-of-experts]]></category>
            <dc:creator><![CDATA[David Davies]]></dc:creator>
            <pubDate>Sun, 23 Aug 2026 23:05:24 GMT</pubDate>
            <atom:updated>2026-08-23T23:05:24.208Z</atom:updated>
            <content:encoded><![CDATA[<p>Mixture-of-Experts (MoE) divides a large neural network into smaller expert subnetworks, then activates only a few experts for each token. This increases total parameter capacity without applying dense‑model compute to every request, but it shifts significant complexity into routing, memory placement, networking, scheduling, and observability.</p><p>A Mixture-of-Experts architecture routes each token to a small subset of expert networks rather than evaluating every model parameter. For an AI engineer, the practical benefit is straightforward: the model can carry more learned capacity while keeping active parameters and per‑token FLOPs below those of a dense model with the same total parameter count.</p><p>The trade is operational. Every inference request now depends on router decisions, token permutation, expert availability, collective communication, and balanced execution. A model that looks efficient in a FLOP calculation can perform poorly if one expert receives 30 percent of a batch, tokens cross slow network paths, or decode batches are too small for efficient matrix multiplication.</p><h3>What is a Mixture-of-Experts model?</h3><p>A Mixture-of-Experts model contains several expert subnetworks and a learned gating network, also called a router. Modern language models usually preserve dense self‑attention while replacing selected transformer feed‑forward network blocks with sparse MoE layers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ayxt-Rph87mWkaySLUV8jQ.png" /></figure><p>This produces two parameter counts:</p><ul><li>Total parameters include all experts, attention layers, embeddings, routers, and shared components.</li><li>Active parameters include only the shared components and experts selected for a token.</li></ul><p>The distinction matters because total parameters determine weight‑storage requirements, while active parameters more closely determine arithmetic per token. An MoE model can therefore require more GPU memory than a smaller dense model while executing fewer FLOPs than a dense model with an equivalent total parameter count.</p><pre>Property Dense transformer Sparse MoE transformer<br>  <br>FFN execution Every FFN runs per token Topk experts run per token<br>Active parameters Close to total parameters Fraction of total parameters<br>Weight memory All dense weights All experts plus shared weights<br>Routing None Learned tokenlevel routing<br>Communication Tensor/pipeline collectives Adds expert alltoall traffic<br>Latency behavior Relatively predictable Sensitive to routing imbalance<br>Typical failures OOM, kernel or scheduler lag Hot experts, drops, collapse</pre><h3>Dense networks vs sparse MoE layers</h3><p>A dense FFN applies the same matrices to every token. Increasing its hidden dimension increases capacity, compute, and memory together.</p><p>An MoE layer instead evaluates only the selected experts:</p><pre>Token embedding<br> |<br> v<br> Router logits<br> |<br> Topk<br> / \<br>Expert 2 Expert 6<br> \ /<br>Weighted combine<br> |<br> v<br>Residual output</pre><p>Inactive experts perform no matrix multiplication for that token. They must still remain resident in GPU memory, CPU memory, or a sufficiently fast weight‑loading tier. Loading experts from remote storage on demand is generally incompatible with low‑latency decoding.</p><p>For example, a layer with eight experts and top‑2 routing executes two expert FFNs per token, not eight. Attention and other dense components still execute normally, so top‑2 routing does not mean that exactly one‑quarter of the entire model’s FLOPs are active.</p><h3>From early local experts to Switch Transformers and modern language models</h3><p>Robert Jacobs, Michael Jordan, Steven Nowlan, and Geoffrey Hinton introduced adaptive mixtures of local experts in 1991. Their approach trained a gating system to divide a problem among specialized networks. Later conditional‑computation research embedded similar selection mechanisms inside deeper architectures.</p><p>Transformer FFNs became a natural MoE insertion point because they contain much of a transformer’s parameter capacity and process tokens independently. Replacing an FFN with parallel experts can add capacity without making attention sparse or changing the surrounding residual pathway.</p><p>Switch Transformers simplified the design with top‑1 routing. Each token visits one expert, reducing expert compute and communication compared with top‑2 designs. Publicly documented language models such as Mixtral 8x7B use sparse expert layers with top‑2 routing. Related designs also apply expert selection to vision and convolutional networks through Convolutional Mixture of Experts variants.</p><h3>Core components of the MoE architecture</h3><p>An MoE layer has five operational components:</p><ol><li>Expert networks hold most of the layer’s capacity.</li><li>The router produces one score per expert for each token.</li><li>The routing policy selects top‑1, top‑2, or another assignment.</li><li>Capacity controls bound how many tokens each expert accepts.</li><li>The combine operation merges expert outputs into the residual pathway.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ahge2xcO118WcmfDJE_Qxw.png" /></figure><p>Token‑choice routing lets each token select experts. This can optimize model quality but create unpredictable expert loads. Expert‑choice routing lets each expert select a fixed number of tokens. It makes capacity more predictable, although tokens may receive unequal numbers of expert assignments.</p><p>A distributed layer might look like this:</p><pre>GPU 0 GPU 1 GPU 2 GPU 3<br>Shared layers Shared layers Shared layers Shared layers<br>Experts 0,1 Experts 2,3 Experts 4,5 Experts 6,7<br> ^ ^ ^ ^<br> + token alltoall exchange +</pre><h3>Expert networks and specialization</h3><p>Experts are usually independent FFNs with identical tensor shapes and separate weights. A standard expert may contain an up‑projection, an activation, a gated projection, and a down‑projection.</p><p>Specialization emerges from training. Engineers do not normally label one network as the “math expert” and another as the “Python expert.” Experts learn statistical preferences for token patterns, syntax, domains, or contextual features. These preferences can change after fine‑tuning or a shift in traffic distribution.</p><p>Design choices include the expert count, expert hidden dimension, top‑k value, shared experts, and expert replication. Replicating a frequently selected expert can relieve a hot path, but replicas must share consistent weights and routing semantics.</p><p>Placement matters as much as shape. Experts on the same GPU avoid network dispatch. Experts on another GPU require device‑to‑device transfer. Experts on another node add fabric latency, contention, and synchronization risk.</p><h3>Gating network, router logits, and top‑k selection</h3><p>For token state h, a common router computes:</p><pre>logits = Wrouter x h<br>probabilities = softmax(logits)<br>selected = topk(probabilities)<br>output = sum(normalized weight i x expert i(h))</pre><p>The router activates the experts with the largest scores, subject to capacity rules. Top‑1 minimizes expert computation and dispatch volume. Top‑2 often provides a more robust combined representation, but it increases expert FLOPs and communication. Noisy routing adds controlled perturbations during training so that early score differences do not permanently monopolize traffic.</p><p>Routing becomes unstable when logits grow excessively, one expert gains an early advantage, training data is skewed, or fine‑tuning changes token distributions faster than experts adapt. Mixed‑precision router calculations can amplify close‑score errors, so some implementations keep router operations in higher precision than expert GEMMs.</p><h3>Conditional computation, sparsity, and load balancing</h3><p>Conditional computation decouples total model capacity from active per‑token computation. Sparsity appears at several levels:</p><ul><li>Token sparsity means one token activates only top‑k experts.</li><li>Expert sparsity means most experts are inactive for that token.</li><li>Batch sparsity describes the actual expert‑usage distribution across a microbatch.</li></ul><p>Batch sparsity determines runtime efficiency. Even if every token selects two of eight experts, the batch may not distribute evenly. A domain‑specific prompt could route most tokens to two experts, leaving some GPUs overloaded and others idle.</p><p>This makes load balancing a first‑order model and systems requirement. The router that produces the lowest validation loss may not produce the best p99 latency. Production routing must also account for bounded expert capacity, network locality, dispatch size, and the cost of waiting at synchronization barriers.</p><h3>Capacity factors, token dropping, and auxiliary losses</h3><p>Expert capacity defines the maximum tokens accepted by each expert per batch or microbatch:</p><pre>capacity = ceil(capacity factor x token count x topk / expert count)</pre><p>A higher capacity factor reduces overflow but reserves larger buffers, increases padding, and can add memory traffic. A lower factor improves execution regularity but may force the runtime to drop, reroute, or queue overflow tokens.</p><p>Training commonly uses several controls:</p><ul><li>Load‑balancing loss discourages uneven token assignments.</li><li>Importance loss balances aggregate routing probabilities.</li><li>Router Z‑loss limits excessively large router logits.</li><li>Entropy regularization or routing noise prevents premature concentration.</li></ul><p>Test these edge cases explicitly. Dropped tokens can reduce output quality. Padding can erase sparse‑compute savings. Expert collapse can leave much of the model unused. A fine‑tuning dataset dominated by one domain can shift routing toward a few experts. The same collapse can appear only during inference if production traffic differs from the training distribution.</p><h3>Execution mechanics inside an MoE layer</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e1FmWsR2HaISPvkbSUkgGg.png" /></figure><p>An MoE layer is a data‑movement pipeline around expert matrix multiplications. The runtime scores tokens, constructs routing metadata, permutes tokens into expert‑major order, dispatches them to expert owners, executes grouped GEMMs, and reverses the permutation.</p><pre>Tokens<br> |<br> v<br>Router scores<br> |<br> v<br>Topk assignments<br> |<br> v<br>Permutation and packing<br> |<br> v<br>Alltoall dispatch<br> |<br> v<br>Grouped expert GEMM<br> |<br> v<br>Alltoall return<br> |<br> v<br>Inverse permutation<br> |<br> v<br>Weighted combine and residual output</pre><p>Router projection is usually cheap relative to expert FFNs. The expensive systems work comes from sorting, buffer allocation, cross‑GPU movement, padding, synchronization, and fragmented GEMMs.</p><h3>Token dispatch, all‑to‑all collectives, and expert parallelism</h3><p>Expert parallelism keeps each expert’s weights on an owning GPU and moves tokens to that GPU. The dispatch sequence is:</p><ol><li>Compute expert IDs and combine weights.</li><li>Count assignments per local and remote expert.</li><li>Pack token states into contiguous destination buffers.</li><li>Run an all‑to‑all collective.</li><li>Execute local experts.</li><li>Run the return all‑to‑all.</li><li>Restore token order and combine outputs.</li></ol><p>When experts span nodes, non‑blocking InfiniBand fabric and topology locality become critical. Each imbalance in routing becomes an imbalance in network traffic. Small messages reduce link efficiency. Hot experts delay collective completion. Slow nodes become stragglers. Tiny microbatches fragment transfers, while global barriers make otherwise idle GPUs wait for the busiest destination.</p><p>Profile all‑to‑all time separately from expert‑compute time. A lower active‑FLOP count is not useful if collective communication dominates layer latency.</p><h3>Kernel, memory layout, and grouped GEMM behavior</h3><p>Naively launching one GEMM per expert performs poorly when experts receive small or uneven token counts. GPU kernels spend too much time launching, and small matrices fail to occupy enough streaming multiprocessors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oZdx1nl0IAzTFyZJfUvzfg.png" /></figure><p>Production runtimes pack tokens into expert‑major buffers and use grouped GEMM to execute multiple expert operations together. Efficient layouts require aligned dimensions, contiguous ranges, stable offsets, and bounded padding. Ragged assignments complicate every one of these conditions.</p><p>Memory planning must include:</p><ul><li>All resident expert weights.</li><li>Dense attention and embedding weights.</li><li>Routing indices and combine weights.</li><li>Dispatch and return buffers.</li><li>Temporary grouped‑GEMM workspaces.</li><li>Activations during prefill.</li><li>KV cache during autoregressive decoding.</li></ul><p>H100 SXM 80GB is appropriate when weight shards and KV‑cache targets fit with safe headroom. H200 141GB can reduce weight sharding or preserve more memory for KV cache. Evaluate B200 when larger shards or higher‑throughput execution justify a newer GPU generation. Evaluate GB200 NVL72 when rack‑scale NVLink locality matches the model’s expert‑parallel layout. Benchmark the actual runtime rather than inferring latency from peak tensor FLOPs.</p><h3>Scheduler behavior during prefill and decode</h3><p>Prefill processes many prompt tokens concurrently. Large token batches give the runtime enough work to pack expert buffers and amortize collective overhead.</p><p>Decode produces one new token per active sequence at each step. Expert batches become smaller, and latency becomes sensitive to routing skew. Continuous batching helps by combining active sequences, but requests can still converge on the same expert.</p><p>Schedulers can group work by sequence length, expected decode duration, or observed expert pressure. Multi‑tenant systems may need to isolate tenants whose prompts consistently create hot experts.</p><p>At p99, common failures include:</p><ul><li>A popular expert delaying an all‑to‑all barrier.</li><li>Decode batches too small for efficient grouped GEMM.</li><li>KV‑cache allocation fragmenting GPU memory.</li><li>Capacity overflow creating reroutes or queues.</li><li>Backpressure propagating across pipeline stages.</li></ul><p>Measure prefill and decode separately. Aggregate request latency can hide distinct bottlenecks.</p><h3>Scaling trade‑offs and what breaks at scale</h3><p>MoE can be more compute‑efficient than a dense model with comparable total capacity, but it is rarely operationally simpler. It carries all expert weights, introduces router‑training instability, and converts local FFN execution into distributed dispatch.</p><p>Expert collapse occurs when a small group of experts monopolizes assignments. Cold experts receive too little training signal. Router drift appears when fine‑tuning changes assignment patterns. Domain‑skewed production traffic can overload experts that appeared balanced during evaluation. Fine‑tuning may also degrade generalization if a small dataset updates the router more aggressively than the experts.</p><pre>Workload condition MoE compared with dense<br> <br>High batch volume, strong interconnect Often better<br>Large capacity target, bounded active FLOPs Often better<br>Singlenode model with sufficient memory Better or equivalent<br>Small batches and moderate model size Often equivalent<br>Strict singlerequest latency Often worse<br>Weak crossnode networking Worse<br>Limited memory for resident expert weights Worse<br>Unpredictable domainskewed traffic Worse unless carefully controlled</pre><p>MoE is not inherently better than a traditional architecture. It becomes attractive when capacity is the bottleneck, batches amortize routing, memory holds the experts, and the network sustains predictable all‑to‑all traffic.</p><h3>Production deployment workflow for MoE inference</h3><p>Start deployment with routing‑aware profiling rather than total parameter count alone.</p><ol><li>Choose a documented MoE model and runtime. Mixtral 8x7B is a practical validation model because it exposes eight FFN experts with top‑2 routing.</li><li>Measure total weight memory, active parameters, KV‑cache growth, and temporary‑buffer requirements.</li><li>Map experts to GPUs. Begin within one high‑bandwidth node when possible.</li><li>Test all‑to‑all bandwidth and latency using the same node count and message sizes expected in production.</li><li>Deploy the model with explicit GPU‑node placement.</li><li>Load test prompt‑heavy prefill, long decode, burst traffic, and domain‑skewed prompts.</li><li>Record tokens/sec, time to first token, time per output token, p50, p99, drop rate, and per‑expert utilization.</li><li>Tune batch limits, capacity factors, expert placement, and replica count.</li></ol><p>CoreWeave Kubernetes Service provides a Kubernetes‑native path for dedicated serving pools. Store canonical weights in CoreWeave AI Object Storage or persistent model storage, then stage them onto local NVMe before loading the server. Use dedicated H100 SXM 80GB, H200 141GB, B200, or GB200 NVL72 capacity according to weight, KV‑cache, and communication requirements. Keep cross‑node expert traffic on non‑blocking InfiniBand when the serving topology requires expert parallelism.</p><p>Alternative workloads include LLM endpoints, agent backends, multimodal models, domain‑routing systems, Convolutional Mixture-of-Experts for vision, and offline batch inference.</p><h3>Serving topology on CoreWeave: serverless‑style endpoints and dedicated GPU clusters</h3><p>A managed or serverless‑style endpoint fits experimentation, variable traffic, replicated models, and fast API iteration. A large expert‑parallel model usually needs dedicated nodes so the runtime controls expert placement, network locality, capacity, and rolling upgrades.</p><p>A concrete CoreWeave workflow is:</p><ol><li>Upload model weights to managed object storage.</li><li>Create a CoreWeave Kubernetes Service GPU‑node pool.</li><li>Label the selected nodes moe‑pool=h200‑8x.</li><li>Stage weights from persistent storage to local‑NVMe‑backed ephemeral storage.</li><li>Deploy a pinned inference‑runtime image.</li><li>Confirm GPU visibility and model readiness before exposing traffic.</li></ol><p>A minimal scheduling manifest looks like this:</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br> name: mixtralserving<br>spec:<br> replicas: 1<br> selector:<br> matchLabels:<br> app: mixtralserving<br> template:<br> metadata:<br> labels:<br> app: mixtralserving<br> spec:<br> nodeSelector:<br> moepool: h2008x<br> containers:<br>  name: server<br> image: vllm/vllmopenai:latest<br> args:<br>  model<br>  /modelsfast/Mixtral8x7BInstructv0.1<br>  tensorparallelsize<br>  &quot;8&quot;<br> resources:<br> limits:<br> nvidia.com/gpu: &quot;8&quot;<br> volumeMounts:<br>  name: modelstore<br> mountPath: /models<br> readOnly: true<br>  name: localnvme<br> mountPath: /modelsfast<br>  name: sharedmemory<br> mountPath: /dev/shm<br> volumes:<br>  name: modelstore<br> persistentVolumeClaim:<br> claimName: moemodelweights<br>  name: localnvme<br> emptyDir:<br> sizeLimit: 500Gi<br>  name: sharedmemory<br> emptyDir:<br> medium: Memory<br> sizeLimit: 64Gi</pre><p>Add an init container or staging job to copy weights from /models to /models‑fast. Pin the runtime image by digest after validation. For multi‑node expert parallelism, use the runtime&#39;s documented distributed launcher and verify that RDMA traffic follows the intended InfiniBand topology.</p><p>Use Mission Control for dedicated‑cluster lifecycle operations. SUNK is relevant when fine‑tuning, training, or offline evaluation requires Slurm semantics while retaining Kubernetes infrastructure.</p><h3>Observability, SLOs, and capacity planning for hot experts</h3><p>MoE observability must expose routing behavior. Collect these metrics per layer and model replica:</p><ul><li>Tokens assigned to each expert.</li><li>Expert‑capacity utilization and token‑drop rate.</li><li>Router entropy and maximum routing probability.</li><li>Dispatch and return all‑to‑all duration.</li><li>Grouped‑GEMM occupancy and execution time.</li><li>GPU memory used by weights, buffers, and KV cache.</li><li>Input and output tokens/sec.</li><li>Time to first token, p50 latency, and p99 latency.</li></ul><p>Partition routing histograms by tenant, prompt class, sequence length, and model version. This identifies traffic skew that cluster‑wide averages conceal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oZdx1nl0IAzTFyZJfUvzfg.png" /></figure><p>Autoscaling is more constrained than dense serving. A new replica may need every expert and a full copy of the shared weights. A partitioned design must instead scale coordinated expert groups without breaking placement assumptions.</p><p>Capacity plans must reserve space for weights, peak KV cache, dispatch buffers, and rolling upgrades. Do not plan at 100 percent GPU‑memory occupancy. An upgrade may briefly require old and new replicas to coexist while both retain complete expert pools.</p><h3>Choosing MoE with production constraints in mind</h3><p>Mixture of experts trades dense computation for routing, memory, and communication complexity. It can provide large total parameter capacity with lower active FLOPs, but only when the runtime keeps expert assignments balanced and data movement under control.</p><p>Choose MoE when the application requires substantial model capacity, has sufficient batch volume to amortize routing, has strong GPU interconnects, and can observe routing dynamics. Avoid it when serving depends on strict single‑request latency, GPU memory is limited, cross‑node networking is weak, or production traffic produces unstable domain skew.</p><p>Before promoting an MoE deployment, validate:</p><ul><li>Active FLOPs and active parameters per token.</li><li>Per‑expert token balance under realistic traffic.</li><li>All‑to‑all time as a percentage of layer latency.</li><li>Prefill and decode p50 and p99 latency.</li><li>Token‑drop and capacity‑overflow rates.</li><li>Weight, buffer, and KV‑cache memory headroom.</li><li>Behavior during node failures and rolling upgrades.</li><li>A repeatable path from endpoint experimentation to dedicated production capacity.</li></ul><p>If sparse activation reduces compute without making memory, networking, scheduling, or p99 latency unmanageable, the MoE architecture delivers the intended production advantage.</p><h3>Sources</h3><ul><li><a href="https://www.ibm.com/think/topics/mixtureofexperts">What is mixture of experts? | IBM</a></li><li><a href="https://huggingface.co/blog/moe">Mixture of Experts Explained ‑ Hugging Face</a></li><li><a href="https://newsletter.maartengrootendorst.com/p/avisualguidetomixtureofexperts">A Visual Guide to Mixture of Experts (MoE)</a></li><li><a href="https://www.nvidia.com/enus/glossary/mixtureofexperts">What Is Mixture of Experts (MoE) and How It Works? | NVIDIA Glossary</a></li><li><a href="https://en.wikipedia.org/wiki/Mixture_of_experts">Mixture of experts ‑ Wikipedia</a></li><li><a href="https://developer.nvidia.com/blog/applyingmixtureofexpertsinllmarchitectures">Applying Mixture of Experts in LLM Architectures ‑ NVIDIA Developer</a></li><li><a href="https://cameronrwolfe.substack.com/p/moellms">Mixture‑of‑Experts (MoE) LLMs ‑ by Cameron R. Wolfe, Ph.D.</a></li><li><a href="https://arxiv.org/abs/2503.07137">[2503.07137] A Comprehensive Survey of Mixture‑of‑Experts ‑ arXiv</a></li><li><a href="https://www.datacamp.com/blog/mixtureofexpertsmoe">What Is Mixture of Experts (MoE)? How It Works, Use Cases &amp; More</a></li><li><a href="https://arxiv.org/html/2503.07137v1">A Comprehensive Survey of Mixture‑of‑Experts: Algorithms, Theory, and Applications</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df48222f8ff9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/online-inference/mixture-of-experts-moe-scaling-ai-models-with-smarter-routing-df48222f8ff9">Mixture-of-Experts (MoE): Scaling AI models with smarter routing</a> was originally published in <a href="https://medium.com/online-inference">Online Inference</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Top AI cloud conferences for 2026/2027]]></title>
            <link>https://medium.com/online-inference/top-ai-cloud-conferences-for-2026-2027-8169077c485f?source=rss----52acf6e3d9be---4</link>
            <guid isPermaLink="false">https://medium.com/p/8169077c485f</guid>
            <category><![CDATA[ai-cloud]]></category>
            <category><![CDATA[ai-conference-2026]]></category>
            <category><![CDATA[ai-conference]]></category>
            <dc:creator><![CDATA[David Davies]]></dc:creator>
            <pubDate>Wed, 19 Aug 2026 21:39:55 GMT</pubDate>
            <atom:updated>2026-08-19T21:39:55.291Z</atom:updated>
            <content:encoded><![CDATA[<p>Major 2026 AI and cloud events range from the infrastructure‑heavy AI Infra Summit to ecosystem conferences centered on Azure, Google Cloud, AWS, cloud‑native platforms, data, and security. This comparison provides CTOs with a production‑oriented approach to allocating travel, training, partner meetings, and technical due diligence.</p><p>Use this comparison to select events based on what your organization must ship: a migration plan, a secure AI platform, an accelerated‑compute strategy, or a production operating model. Brand visibility and keynote scale matter less than access to reusable architectures, technical experts, working labs, and measurable implementation evidence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SDq0NUnvjS501vqgKykEPg.png" /></figure><p>AI content competes with broader cloud‑native tracks | As of August 19, 2026, AI Infra Summit, Fully Connected, Cloud &amp; AI Summit, AWS re:Invent, and KubeCon + CloudNativeCon North America are still ahead. Atlanta Cloud + AI, Google Cloud Next ’26, and the main San Jose NVIDIA GTC have concluded, but several provide recorded content. Event dates, speakers, labs, and agendas can change, so verify the official event page before booking.</p><h3>Comparison axes for evaluating AI cloud conferences</h3><p>Evaluate every event against the same axes: AI workload relevance, infrastructure depth, cloud operations, modernization and migration, governance, observability, security, hands‑on learning, ecosystem partners, and on‑demand access.</p><p>Create a spreadsheet with one row per event and one column per axis. Score each cell from 1 to 5:</p><ol><li>No meaningful roadmap value.</li><li>Limited or introductory coverage.</li><li>Useful sessions or contacts.</li><li>Strong technical coverage with reusable artifacts.</li><li>Directly resolves an architecture or operating‑model decision.</li></ol><p>Weight critical requirements by three, important requirements by two, and optional requirements by one. Multiply each score by its weight and rank the totals. This creates an organization‑specific selection rather than a generic list of the “best” AI cloud conferences.</p><p>Apply these questions during agenda review and speaker meetings:</p><ul><li>Does the architecture use bare‑metal H100 SXM, H200, B200, or GB200 NVL72 systems, or virtualized GPU instances?</li><li>Is the cluster fabric InfiniBand, Ethernet with RoCE, or an oversubscribed network?</li><li>Does orchestration support Kubernetes, Slurm, or both?</li><li>Where do local NVMe, object storage, checkpoints, vector data, and training data reside?</li><li>How does the inference system handle batching, caching, routing, and model failover?</li><li>What SLA applies to compute capacity and managed services?</li><li>Is pricing on‑demand, reserved, committed, or consumption‑based?</li><li>Are benchmarks reported with the model, precision, batch size, sequence length, parallelism, tokens/sec, p99 latency, MFU, and hourly cost?</li></ul><p>Prioritize reusable outputs: reference architectures, migration assessments, lab repositories, policy templates, security checklists, benchmark methods, and operating‑model documents.</p><h3>Side‑by‑side summary of major AI cloud conferences</h3><p>The strongest event depends on the operating question. Infrastructure events expose chip, network, power, and storage trade‑offs. Platform events connect managed services, migration programs, security controls, and partner ecosystems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nw9P8zZTtwrQR_J1q6dTxQ.png" /></figure><p>AI Infra Summit runs September 15‑17 in Santa Clara, with tracks spanning compute, data movement, data and models, physical AI, and AI data centers. It is the strongest option when facilities, accelerators, cluster networking, storage, or token economics drive the purchase.</p><p>Fully Connected 2026 runs September 29 to October 1 at Moscone South in San Francisco. Official materials list three tracks covering AI infrastructure, model training, and agents, plus 30+ breakouts and hands-on labs with CoreWeave and W&amp;B. It is the strongest option when the buying question is production GPU cloud, cluster operations, and the path from training to serving.</p><p>Cloud &amp; AI Summit runs September 30‑October 2 in St. Charles, Missouri. Its 1.5‑hour sessions cover pro code, low code, cloud operations, AI, data and analytics, security, and DevOps across the Microsoft stack. Atlanta Cloud + AI took place May 30 and covered AI applications, model operations, data platforms, Kubernetes, Infrastructure as Code, SRE, AI safety, and professional development.</p><p>Google Cloud Next ’26 content is available on demand, while the next Las Vegas event is planned for April 13‑15, 2027. AWS re:Invent is scheduled for November 30‑December 4, 2026, with labs, workshops, bootcamps, and dedicated security programming. KubeCon + CloudNativeCon North America runs November 9‑12 in Salt Lake City.</p><h3>Best conference choices by technical priority</h3><p>Map the event to the failure mode you need to remove.</p><p>For infrastructure, compute, data centers, and AI workloads, prioritize AI Infra Summit, Fully Connected, NVIDIA GTC, and KubeCon sessions addressing GPU scheduling, distributed training, inference serving, high‑speed networking, storage throughput, cluster lifecycle, and workload orchestration. GTC is particularly useful for accelerator roadmaps and NVIDIA software. Fully Connected is stronger when the problem is operating AI on specialized GPU cloud, including capacity, cost, security, and the training-to-inference loop. KubeCon is stronger when the problem is portable operations across Kubernetes clusters.</p><p>For Azure modernization, select Cloud &amp; AI Summit or another focused Microsoft event. The relevant tracks connect Azure landing zones, Microsoft Fabric, Power BI, Power Platform, Defender, Sentinel, Entra ID, GitHub Actions, Azure DevOps, and governance.</p><p>For hands‑on learning, compare Atlanta Cloud + AI’s practitioner‑led format, Fully Connected labs, Google Cloud Next skills zones, Cloud &amp; AI Summit’s longer sessions, and AWS re:Invent labs. Google Cloud Next is useful for platform‑roadmap direction, partner evaluation, solution demonstrations, and recorded learning. AWS events fit teams evaluating migration programs, IAM, managed AI services, FinOps, cloud security, and enterprise operating models. AWS re:Invent 2026 advertises more than 2,200 sessions, with workshops, labs, chalk talks, and bootcamps among the available formats.</p><p>Alternative selection goals include:</p><ul><li>Procurement due diligence</li><li>Executive alignment</li><li>Platform‑team enablement</li><li>Migration‑office planning</li><li>SRE and incident‑response training</li><li>Security‑architecture review</li><li>Cloud‑partner discovery</li></ul><p>Assign each attendee one goal, three target sessions, five speaker questions, and one required deliverable.</p><h3>Topics and themes to prioritize in the agenda</h3><p>Prioritize application modernization, AI/ML, security, smart analytics, cloud operations, data platforms, observability, reliability, and DevOps. These themes determine whether an AI app survives the transition from demonstration to production.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HtIWIleE2hP-fLb-O3i5KQ.png" /></figure><p>For application modernization, select sessions covering containers, Kubernetes, serverless platforms, microservices, event‑driven systems, platform engineering, GitOps, CI/CD, and Infrastructure as Code. Look for failure modes, migration sequencing, rollback design, and operating‑cost evidence rather than architecture diagrams alone.</p><p>For AI/ML, prioritize AI agents, LLM‑powered applications, prompt engineering, model evaluation, safety, deployment, inference optimization, orchestration, monitoring, and GPU scheduling. Require speakers to explain routing, retries, evaluation gates, capacity management, and cost per request.</p><p>For smart analytics and data readiness, cover Microsoft Fabric, Power BI, SQL Server, Cosmos DB, lakehouse architectures, vector databases, streaming analytics, lineage, governance, and data quality.</p><p>For security, select Zero Trust, IAM, compliance, Defender, Sentinel, Intune, software‑supply‑chain security, prompt‑injection defense, data‑exfiltration controls, and runtime governance.</p><p>Match each theme to the strongest format. Use Fully Connected for production GPU-cloud infrastructure, training, inference, and agent operations. Use Cloud &amp; AI Summit for deep Microsoft sessions, Atlanta Cloud + AI recordings or community resources for practical patterns, Google Cloud skills content for guided exercises, and AWS or dedicated security events for cloud‑scale control design. Google Cloud’s event catalog explicitly organizes material around application modernization, AI/ML, data management, infrastructure, security, and smart analytics.</p><h3>Modernization and migration playbook from conference sessions</h3><p>A conference creates value when it shortens the path from inventory to an approved migration plan. Run this sequence before, during, and after the event:</p><ol><li>Inventory applications, data platforms, AI models, dependencies, compliance boundaries, and current costs.</li><li>Mark each workload as retain, retire, rehost, replatform, refactor, or rebuild.</li><li>Map agenda sessions to unresolved gaps such as container readiness, data quality, GPU capacity, IAM, or observability.</li><li>Attend readiness, assessment, migration, and target‑architecture sessions before product‑launch sessions.</li><li>Capture reference architectures, assessment templates, lab instructions, cost models, and security controls.</li><li>Run at least one lab using a representative application or data flow.</li><li>Convert the findings into a 30‑60‑90 day roadmap.</li></ol><p>Use the Atlanta keynote framework as a practical sequence: align the AI vision with business outcomes, audit the data estate, then design governance that scales across models. This prevents teams from deploying agents against unclassified, low‑quality, or inaccessible data.</p><p>AI‑driven assessments can discover dependencies, identify candidates for containerization, flag security gaps, evaluate data readiness, and model migration costs. Compare five modernization paths: lift‑and‑shift, replatforming to containers, rebuilding with cloud‑native services, adopting serverless inference, and moving analytics to managed data platforms.</p><p>For each path, record operating burden, architectural risk, lock‑in, latency, data locality, compliance, FinOps, reliability, and required skills. If accelerated compute is required, add GPU availability, interconnect topology, orchestration, storage locality, capacity commitments, and engineering‑support models.</p><p>Your 30‑day output should validate assumptions. The 60‑day output should run pilots. The 90‑day output should approve, revise, or reject the target architecture.</p><h3>Governance, observability, and security patterns to evaluate</h3><p>Production AI requires controls spanning prompts, data, models, infrastructure, tools, identities, and human approval paths. Look for architectures that combine policy, telemetry, and incident response.</p><p>Your governance checklist should include:</p><ul><li>A model registry with ownership and approved‑use metadata</li><li>Data lineage from source records to retrieval and model outputs</li><li>Policy as code for deployment, access, and data‑handling rules</li><li>Approval workflows for models, prompts, tools, and production releases</li><li>Evaluation gates covering quality, safety, latency, and cost</li><li>Immutable audit trails for prompts, responses, tool calls, and overrides</li><li>Multi‑model routing with policy‑based fallback</li><li>A centralized control plane for inventory, policy, and evidence</li></ul><p>Require observability across traces, token usage, p50 and p99 latency, GPU utilization, error budgets, cost per request, retrieval quality, drift, prompt events, and safety violations.</p><p>Security sessions should explain Zero Trust, least‑privilege IAM, network segmentation, secrets management, SBOMs, supply‑chain controls, red teaming, prompt‑injection defense, data‑loss prevention, and runtime enforcement.</p><p>Ask every speaker the same five questions: How is policy enforced at runtime? What is logged? How are incidents escalated? How are models, data, prompts, and tool calls audited? Does the pattern work across multiple clouds and models?</p><p>Fully Connected covers infrastructure security, workload isolation, and agent observability. Atlanta Cloud + AI is useful for AI safety and governance. Cloud &amp; AI Summit maps these controls to Defender, Sentinel, Intune, Purview, Entra ID, compliance, and Zero Trust. Google Cloud Next supports platform‑governance evaluation, while AWS re:Invent includes security content throughout the week and focused security deep dives.</p><p>For teams that cannot travel, use Google Cloud Next recordings and AWS on‑demand sessions. Dedicated virtual options include the State of Trust summit on September 16‑17, 2026, and an agentic‑AI security summit on October 28‑29, covering Zero Trust, autonomous systems, governance, and multi‑agent risk.</p><h3>Picking the right AI cloud conference for your roadmap</h3><p>Pick the event that produces evidence your team cannot obtain from a vendor page.</p><ul><li><strong>Pick AI Infra Summit</strong> when accelerators, networking, storage, data movement, data‑center design, and AI economics drive the roadmap.</li><li><strong>Pick Fully Connected</strong> when production AI on specialized GPU cloud, cluster operations, and hands-on labs with the platform team drive the roadmap.</li><li><strong>Pick NVIDIA GTC</strong> when you need NVIDIA architecture, training, inference, AI‑factory, and software‑stack depth.</li><li><strong>Pick Cloud &amp; AI Summit</strong> when Azure operations, Microsoft Fabric, Power Platform, security, governance, and DevOps are the priority.</li><li><strong>Pick Atlanta Cloud + AI</strong> when you want community‑led implementation lessons, AI‑readiness guidance, professional development, and practical multi‑cloud patterns.</li><li><strong>Pick Google Cloud Next</strong> when you need Google Cloud direction, solution demonstrations, partners, skills content, and on‑demand sessions.</li><li><strong>Pick AWS</strong> events when migration, IAM, managed AI services, cloud security, governance, and enterprise‑scale AWS operations dominate the plan.</li><li><strong>Pick KubeCon</strong> when Kubernetes portability, platform engineering, observability, policy, scheduling, and open‑source workload orchestration matter most.</li></ul><p>Prepare questions before arrival. Assign session owners. Collect architecture artifacts. Validate assumptions with speakers and partners. Convert findings into decisions within ten business days.</p><p>Use beginner tracks, leadership sessions, community meetups, Birds of a Feather discussions, and hands‑on labs to develop the engineers who will operate the platform. Community and diversity programs, including women‑in‑tech groups where available, can also expand technical networks and recruiting pipelines.</p><p>Judge success by the outputs: a revised roadmap, updated risk register, reference architectures, migration backlog, security actions, vendor shortlist, and role‑based training plan.</p><h3>Sources</h3><ul><li><a href="https://www.aiinfrasummit.com/faqs">AI Infra Summit 2026 FAQs</a></li><li><a href="https://www.aiinfrasummit.com/conferenceagenda">Agenda ‑ AI Infra Summit 2026</a></li><li><a href="https://www.cloudandaisummit.com/">The Cloud &amp; AI Summit 2026 | Microsoft Azure &amp; AI Conference</a></li><li><a href="https://www.googlecloudevents.com/nextvegas/faq">FAQ: Google Cloud Next 2026</a></li><li><a href="https://aws.amazon.com/events/reinvent/faqs">AWS re:Invent 2026 FAQ ‑ Frequently Asked Questions</a></li><li><a href="https://cloud.google.com/events">Events | Google Cloud</a></li><li><a href="https://atlcloudconf.com/">Atlanta Cloud + AI Conference</a></li><li><a href="https://www.googlecloudevents.com/nextvegas">Google Cloud Next 2026 ‑ Las Vegas Conference</a></li><li><a href="https://cloudsecurityalliance.org/events">Events | Cloud Security Alliance (CSA)</a></li><li><a href="https://aws.amazon.com/events">Cloud Events, Webinars and Conferences ‑ AWS</a></li><li><a href="https://www.googlecloudpresscorner.com/20260701GoogleCloudSummitinAfricaHighlightstheContinentsDigitalTransformationandUnveilsNewAgenticAIandInfrastructureInvestments">Google Cloud Summit in Africa Highlights the Continent’s Digital …</a></li><li><a href="https://aiinfrasummit.com/">AI Infra Summit 2026 | Sep 15‑17, Santa Clara</a></li><li><a href="https://www.microsoft.com/enus/events">Microsoft Events, Webinars, and Conferences</a></li><li><a href="https://www.coreweave.com/fully-connected-2026">Fully Connected 2026 | CoreWeave AI Cloud Conference</a></li><li><a href="https://www.coreweave.com/fully-connected-2026/agenda">Fully Connected 2026 Agenda</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8169077c485f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/online-inference/top-ai-cloud-conferences-for-2026-2027-8169077c485f">Top AI cloud conferences for 2026/2027</a> was originally published in <a href="https://medium.com/online-inference">Online Inference</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is model distillation for LLMs?]]></title>
            <link>https://medium.com/online-inference/model-distillation-for-llms-ea5c0d741682?source=rss----52acf6e3d9be---4</link>
            <guid isPermaLink="false">https://medium.com/p/ea5c0d741682</guid>
            <category><![CDATA[model-distillation]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[transfer-learning]]></category>
            <dc:creator><![CDATA[David Davies]]></dc:creator>
            <pubDate>Thu, 13 Aug 2026 22:18:14 GMT</pubDate>
            <atom:updated>2026-08-14T00:57:07.463Z</atom:updated>
            <content:encoded><![CDATA[<p>Model distillation trains a compact student model to reproduce the useful behavior of a larger teacher model. For LLM workloads, the training signal can include generated responses, token‑level probabilities, preferences, or concise rationales, converting expensive general capability into a model that fits a defined latency, memory, and cost envelope.</p><p>Model distillation for LLMs transfers selected behavior from a high‑capability teacher into a smaller student model. Instead of serving the teacher for every request, the platform runs the expensive model offline to produce training signals, then deploys the student against repeatable production traffic.</p><p>For AI Platform Leaders, the value lies in operations. A smaller Generative LLM can reduce GPU‑memory requirements, support larger inference batches, tighten p99 latency, and relieve capacity bottlenecks. Teams can change the model behind an existing API without rebuilding the orchestration, observability, storage, or governance layers around it. The difficult work extends beyond selecting a teacher and student. Production LLM distillation requires controlled data generation, soft‑label handling, token‑level losses, distributed training, GPU scheduling, high‑throughput storage, evaluation gates, and derivative‑model governance. ^</p><p>Teacher inference stresses batching and KV‑cache capacity. Student training stresses memory management, checkpoint I/O, and collective communication. Distillation is not a universal compression button. It is a workload and data pipeline. It works best when the target traffic is observable, the desired behavior is measurable, and the organization has the right to use the teacher outputs for training.</p><h3>What model distillation is and how the teacher-student setup works</h3><p>The teacher is the high‑capability source of behavior. It might be a fine‑tuned 70B‑parameter model, an ensemble, or an approved hosted model. The student is the deployable target, such as an 8B decoder‑only LLM, an encoder-classifier, or a task‑specific reranker.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jhR9o1ePj4KdB6Wb7QTq8Q.png" /></figure><p>The relationship is controlled behavioral transfer, not parameter cloning. The student usually has a different architecture or parameter count. It learns from examples produced or scored by the teacher.</p><p>Hard labels provide one correct target. A classification label might state that a support ticket belongs to “billing.” Soft labels preserve the teacher’s uncertainty, such as 0.72 billing, 0.20 account access, and 0.08 cancellation. The second signal tells the student which mistakes are semantically close.</p><p>Generative LLM distillation can transfer:</p><ul><li>Prompt‑response behavior</li><li>Instruction following</li><li>Output schemas and formatting</li><li>Domain terminology</li><li>Refusal and escalation behavior</li><li>Tool‑selection patterns</li><li>Reasoning summaries</li><li>Tone and style</li></ul><p>The resulting student may qualify as a derivative model. Its training data, acceptable uses, and redistribution rights can depend on the teacher license, API contract, source prompts, and generated content.</p><h3>Soft labels, logits, and temperature</h3><p>Logits are the unnormalized scores a model produces before softmax converts them into probabilities. Soft labels are the probability distributions derived from those scores.</p><p>Temperature controls their sharpness:</p><pre>teacher_probability = softmax(teacher_logits / T)<br>student_probability = softmax(student_logits / T)</pre><p>A temperature above 1 smooths the distribution. This exposes “dark knowledge”: information about how the teacher ranks incorrect alternatives. A lower temperature makes the highest‑probability target dominate.</p><p>A standard distillation objective combines ground‑truth supervision with teacher imitation:</p><pre>loss =<br> alpha * CE(ground_truth, student_predictions)<br> + (1  alpha) * T^2<br> * KL(teacher_distribution || student_distribution)</pre><p>For an autoregressive student, calculate the KL term over valid output tokens. Mask padding, prompt tokens that should not contribute to the loss, and any redacted rationale spans.</p><pre>++++<br>| Target | Signal | Best fit |<br>++++<br>| Hard label | One class or answer | Classification, extraction |<br>| Soft label | Probability distribution | Calibration, ambiguity |<br>| Sequence response | Generated completion | Generative LLM behavior |<br>| Preference signal | Ranked candidate outputs | Style, safety, alignment |<br>++++</pre><p>Hosted APIs often expose generated text but not logits. In that case, use sequence‑level responses, multiple sampled candidates, confidence scores, or preference judgments.</p><p>Token‑level KL also becomes difficult when teacher and student vocabularies differ. Tokenizer mismatch can split the same text into incompatible units. Alternatives include sequence‑level training, matching probabilities over aligned text spans, or using a shared tokenizer. Recalibrate the student after training because teacher probabilities can drift across model versions and decoding configurations.</p><h3>Generative LLM distillation versus classic model distillation</h3><p>Classic distillation usually transfers a fixed prediction from a classifier. Autoregressive Language Models predict one token at a time, and each generated token changes the context for subsequent predictions.</p><p>That introduces several problems:</p><ul><li>Exposure bias occurs when the student encounters its own imperfect outputs during inference.</li><li>Length bias can reward responses that are too short or unnecessarily verbose.</li><li>Sampling settings change the synthetic dataset.</li><li>Prompt‑template changes can alter teacher behavior.</li><li>Stop‑token errors can produce truncated or runaway generations.</li></ul><p>A Generative LLM teacher can transfer domain vocabulary, formatting, refusal patterns, tool syntax, and reasoning style. The student can be a small decoder‑only LLM for conversational generation, an encoder for classification, a mixture‑of‑experts model for routed specialization, or a reranker that scores retrieved documents.</p><pre>++++++<br>| Use case | Input | Output | Common loss | Deployment |<br>++++++<br>| Classification | Text | Class scores | CE plus KL | Online API |<br>| Retrieval | Querydocument | Relevance score | Ranking loss | Search pipeline |<br>| Generation | Prompt/context | Token sequence | CE, KL, prefs | LLM serving |<br>++++++</pre><p>For generation, evaluate more than final‑answer accuracy. Test schema validity, stop behavior, verbosity, refusal quality, context handling, and performance under the exact prompt templates used in production.</p><h3>The LLM distillation pipeline from data generation to deployment</h3><p>Production distillation begins before the training loop. The platform must select a task, collect representative prompts, run teacher inference, validate the outputs, train the student, evaluate it against real traffic, and promote only the model that satisfies quality and serving requirements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*66CNLCAMPk3S_ly9hdFQGw.png" /></figure><p>Treat teacher generation as offline inference. Precomputing outputs decouples an expensive teacher workload from student training. The labeling pool can run when suitable GPUs are available, while training consumes immutable, versioned dataset partitions.</p><p>Apply these controls before training:</p><ol><li>Deduplicate exact and near‑duplicate prompts.</li><li>Detect PII and proprietary data.</li><li>Version prompts and system instructions.</li><li>Record teacher model and decoding parameters.</li><li>Reject malformed, unsafe, or low‑confidence generations.</li><li>Sample disagreement and low‑confidence regions for human review.</li><li>Freeze evaluation splits before iterative data enrichment.</li></ol><p>The infrastructure maps naturally to separate execution layers. GPU‑inference pools generate labels. Managed object storage holds prompts, responses, logits, and lineage. Local NVMe stages active shards and checkpoints. Kubernetes jobs handle tokenization, filtering, and batch inference. SUNK provides Slurm scheduling semantics for distributed student training on Kubernetes. A model registry controls promotion into serving.</p><h3>Step-by-step workflow for platform teams</h3><p>Use one concrete workload for the first run. For example, distill an approved Llama 3.1 70B Instruct teacher into a Llama 3.1 8B Instruct student for support‑ticket summarization and structured routing.</p><ol><li><strong>Define the serving target.</strong></li></ol><p>Specify input length, output length, quality threshold, p50 and p99 latency, expected concurrency, and cost per 1,000 requests. An example objective might require valid JSON on 99.5 percent of requests and a p99 below 250 ms for a bounded output. Treat these as targets, not assumed results.</p><p><strong>2. Select the teacher and student.</strong></p><p>Choose a teacher with demonstrated quality on the workload and a student large enough to represent the required behavior. Confirm tokenizer compatibility and output‑use rights.</p><p><strong>3. Build versioned prompts.</strong></p><p>Create a fixed system prompt, task template, output schema, and decoding policy. Include adversarial, ambiguous, and long‑context examples.</p><p><strong>4. Run teacher labeling.</strong></p><p>Use H100 SXM 80GB or H200 141GB pools for batch inference. H200 141GB is useful when long prompts and KV‑cache pressure dominate. Separate this pool from latency‑sensitive production serving.</p><p><strong>5. Validate the synthetic targets.</strong></p><p>Check schema validity, refusal behavior, factual consistency, duplicate rates, and disagreement with human labels. Route uncertain examples to reviewers.</p><p><strong>6. Train and track the student.</strong></p><p>Log dataset version, teacher version, loss components, evaluation slices, and checkpoint identifiers with Weights &amp; Biases:</p><pre>import wandb<br><br>wandb.login()<br>run = wandb.init(<br> project=&quot;supportdistillation&quot;,<br> config={<br> &quot;teacher&quot;: &quot;llama3.170binstruct&quot;,<br> &quot;student&quot;: &quot;llama3.18binstruct&quot;,<br> &quot;dataset_version&quot;: &quot;supportv3&quot;,<br> &quot;temperature&quot;: 2.0<br> }<br>)<br>wandb.log({<br> &quot;train/ce_loss&quot;: ce_loss,<br> &quot;train/kl_loss&quot;: kl_loss,<br> &quot;eval/schema_validity&quot;: schema_validity<br>})</pre><p>Store the filtered dataset and accepted checkpoint as W&amp;B Artifacts so a run can be reproduced from immutable inputs.</p><ol><li>Evaluate and compress further.</li></ol><p>Compare the student with the teacher and current production baseline. If quality holds, test quantization and serving‑time batching separately.</p><ol><li>Deploy through shadow and canary stages.</li></ol><p>Mirror traffic without returning student outputs. Then expose a small traffic percentage with automatic rollback thresholds.</p><p>A workload layout can separate policies and failure domains:</p><pre>namespaces:<br> distilllabeling:<br> gpupool: H200141GB<br> scheduling: dynamicbatch<br> output: managedobjectstorage<br><br>distilltraining:<br> scheduler: SUNK<br> topology: multinode<br> checkpointstage: localNVMe<br> distillevaluation:<br> gpupool: H100SXM80GB<br> priority: belowproductionserving<br> input: frozenevaluationartifact</pre><p>The same workflow supports classification, summarization, code assistance, domain chatbots, retrieval reranking, guardrail models, and offline labeling.</p><h3>Data, governance, and derivative model constraints</h3><p>Teacher outputs become training assets. They can create both a derivative dataset and a derivative model, with contractual, licensing, privacy, and redistribution implications.</p><p>Distillation is not automatically legal or illegal. The answer depends on the teacher license, API terms, input‑data rights, intended deployment, and applicable law. Some hosted‑model agreements restrict using outputs to train competing models. Obtain legal review before generating a large dataset. Prefer approved open‑weight teachers when output‑training rights must be explicit.</p><p>Every sample should carry lineage metadata:</p><pre>sample_id<br>source_prompt_id<br>source_dataset<br>teacher_model_and_version<br>system_prompt_version<br>decoding_temperature<br>top_p_and_max_tokens<br>generation_timestamp<br>filter_versions<br>reviewer_decision<br>license_status<br>evaluation_split</pre><p>Scan prompts and outputs for PII, secrets, memorized content, and proprietary material. Synthetic generation does not remove the sensitivity of source data. A teacher can reproduce confidential text or amplify an unsafe pattern present in the prompt.</p><p>Store metadata beside each data partition in managed object storage. Enforce access by namespace, service identity, and environment. Retain immutable manifests for released datasets, and prevent evaluation examples from entering later training runs.</p><h3>Mechanics at scale: kernels, collectives, and schedulers</h3><p>At scale, model distillation is constrained by the interaction among GPUs, storage, networking, and schedulers.</p><p>Teacher inference is sensitive to model‑weight reads, attention memory traffic, batch composition, and KV‑cache growth. Student training adds activation memory, optimizer state, gradient synchronization, and checkpoint traffic. These phases should not share an undifferentiated queue.</p><p>Batching increases throughput but also increases KV‑cache usage. Sequence length expands attention work and activation memory. Activation checkpointing reduces stored activations but recomputes them during the backward pass. Tensor parallelism splits layer computation across GPUs, while pipeline parallelism divides groups of layers and introduces pipeline bubbles.</p><pre>Prompts &gt; Teacher inference &gt; Synthetic partitions<br> |<br> v<br> Filter and validate<br> |<br> v<br>Object storage &gt; NVMe staging &gt; Student GPUs<br> |<br> gradients and collectives<br> |<br> v<br> Checkpoint registry</pre><p>Schedulers must consider requested GPU count, per‑GPU memory, topology, expected duration, and preemption tolerance. Distributed training requires gang scheduling because a partial allocation cannot run the job. Labeling jobs can usually be retried at the partition level.</p><h3>Teacher inference path: batching, KV cache, and storage I/O</h3><p>Teacher labeling reads prompts, tokenizes them, forms batches, performs generation, applies validators, and writes accepted outputs with metadata.</p><p>Prefill processes the input prompt and is dominated by parallel attention and matrix operations. Decode generates tokens sequentially. During decode, every active sequence maintains key‑value tensors for its previous tokens. KV‑cache memory therefore grows with layer count, batch size, sequence length, and KV representation.</p><p>Long‑context examples can fragment batches and force shorter prompts to wait. Use:</p><ul><li>Length bucketing to group similar prompts</li><li>Dynamic batching within a bounded wait window</li><li>Maximum input and output token caps</li><li>Separate queues for long‑context prompts</li><li>Partition‑level retries</li><li>Speculative decoding where the serving stack supports it</li></ul><p>Attention kernels such as FlashAttention reduce unnecessary memory movement by computing attention in tiled operations. Kernel selection, supported precision, head dimensions, and sequence lengths affect effective throughput, so validate the exact model and serving runtime rather than assuming a generic improvement.</p><pre>Managed object storage<br> |<br> v<br>++<br>| Tokenization pool |<br>++<br> |<br> length buckets<br> |<br> v<br>++<br>| Teacher GPU pods |<br>| prefill &gt; decode |<br>++<br> |<br> v<br>++<br>| Schema and safety |<br>| validators |<br>++<br> |<br> v<br>Synthetic dataset partitions</pre><p>Write outputs incrementally. A failed eight‑hour job should retry only missing partitions, not regenerate the full dataset with potentially different stochastic outputs.</p><h3>Student training path: DDP, FSDP, tensor parallelism, and NCCL collectives</h3><p>Student training can combine supervised fine‑tuning, token‑level KL divergence, preference loss, and rationale supervision. The distributed strategy depends on whether model parameters, activations, and optimizer state fit on each GPU.</p><p>Data Distributed Parallel replicates the model and all‑reduces gradients. Fully Sharded Data Parallel shards parameters, gradients, and optimizer state, using all‑gather before computation and reduce‑scatter afterward. Tensor parallelism divides layer operations across GPUs and communicates within each forward and backward pass. Pipeline parallelism places different layer ranges on different devices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a6-y_70jHjsD_qUszXiViQ.png" /></figure><p>Mixture‑of‑experts students add all‑to‑all communication as tokens are routed to experts.</p><pre>++++<br>| Strategy | Good fit | Main communication |<br>++++<br>| Single node | Model and state fit | Local GPU interconnect |<br>| Multinode DDP | Replicas fit per GPU | Gradient allreduce |<br>| FSDP | State exceeds GPU memory | Allgather and reducescatter |<br>| Tensor parallel| Layers do not fit | Perlayer collective operations |<br>++++</pre><p>A non‑blocking InfiniBand fabric helps prevent collective congestion from dominating multi‑node training. Topology‑aware placement keeps participating GPUs on suitable network paths. Local NVMe supports checkpoint staging and fast restart, while durable copies move asynchronously to managed object storage.</p><p>Checkpoint every interval justified by failure risk and write cost. Test checkpoint restoration before a multi‑day run. A checkpoint that exists but cannot restore the optimizer, tokenizer, and scheduler state is not a valid recovery point.</p><h3>Scheduler and cluster controls for production runs</h3><p>Each pipeline stage needs a different policy.</p><p>Teacher labeling benefits from elastic batch workers and partition‑level retries. Student training requires gang‑scheduled nodes with stable topology. Evaluation needs reproducible model and dataset versions. Production inference must retain the highest priority because a labeling backlog should never consume serving capacity.</p><p>Kubernetes‑native orchestration fits services, tokenization, validators, and labeling jobs. SUNK supports distributed training that expects Slurm queues and job semantics while retaining Kubernetes as the underlying control plane. Fair‑share quotas prevent a research run from exhausting the platform allocation.</p><p>Mission Control becomes relevant for repeated production runs by providing cluster‑lifecycle and health visibility. Scheduler state alone cannot identify degraded links, unhealthy nodes, or recurring hardware faults.</p><p>Plan for these failures:</p><ul><li>Partial node failure during a gang‑scheduled job</li><li>Straggler pods delaying all‑reduce</li><li>Corrupt or incomplete checkpoints</li><li>Object‑storage throttling</li><li>Duplicate retries after ambiguous completion</li><li>Retry storms that refill a failing queue</li><li>Preempted workers writing partial partitions</li></ul><p>Use idempotent partition identifiers, bounded exponential backoff, checkpoint checksums, and completion markers. Quarantine repeatedly failing inputs instead of retrying them indefinitely.</p><h3>How distillation compares with fine‑tuning, quantization, pruning, prompting, and caching</h3><p>Fine‑tuning adapts the behavior of an existing model but normally retains its parameter count. Distillation trains a separate, usually smaller or more specialized student.</p><p>Quantization changes numeric representation, such as converting weights from BF16 to lower‑precision formats. Pruning removes weights, channels, heads, layers, or other structures. Prompt engineering changes model behavior without updating parameters. Offline caching precomputes outputs when real‑time generation is unnecessary. Speculative decoding uses a smaller draft model to propose tokens that a larger model verifies.</p><pre>+++++++<br>| Method | Goal | Training | Size change | Accuracy risk | Ops complexity |<br>+++++++<br>| Finetuning | Adapt capability | Yes | Usually none | Medium | Medium |<br>| Distillation | Smaller specialist | Yes | Usually yes | Mediumhigh | High |<br>| Quantization | Lower memory/compute | Maybe | Numeric only | Lowmedium | Medium |<br>| Pruning | Remove structures | Usually | Yes | Mediumhigh | High |<br>| Prompting | Guide behavior | No | None | Low | Low |<br>| Offline caching | Avoid repeated work | No | None | Low | Medium |<br>| Speculative dec. | Accelerate decoding | No | Adds draft | Low | Mediumhigh |<br>+++++++</pre><p>Use prompt engineering when traffic is low, behavior changes frequently, or the base model already meets latency and cost requirements. Use distillation when repeated traffic justifies a governed training and evaluation pipeline.</p><h3>When to combine techniques</h3><p>A common production sequence is:</p><ol><li>Fine‑tune or prompt the teacher for the target domain.</li><li>Generate task‑specific targets.</li><li>Distill into a smaller student.</li><li>Quantize the student if quality remains acceptable.</li><li>Optimize batching, KV‑cache allocation, and serving.</li><li>Cache deterministic or frequently repeated results.</li></ol><p>Pruning is useful when it removes hardware‑exploitable structures. Unstructured sparsity does not automatically improve latency because kernels and accelerators must support the resulting sparse pattern efficiently.</p><p>For nightly document enrichment, offline inference may be simpler than distillation. The organization can run the teacher in batches and cache the results without maintaining a student.</p><p>Do not stack optimizations and assume their quality effects are independent. Measure task quality, calibration, refusal behavior, p50 and p99 latency, tokens per second, GPU memory, and cost per request after every change. A quantized distilled student can pass an aggregate benchmark while regressing on rare entities, structured output, or long‑context requests.</p><h3>Advanced distillation methods for LLMs</h3><p>Basic response imitation may not transfer reasoning, long‑context behavior, or specialized safety boundaries. Advanced methods change the target signal or use multiple sources.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8tQ_-g1TAYTlAWvAtYt4vQ.png" /></figure><p>Context distillation internalizes stable instructions or domain information. Step‑by‑step distillation transfers intermediate supervision. Multi‑teacher methods combine models, heuristics, and human labels. Self‑distillation learns from stronger samples or checkpoints from the same model family. Preference distillation transfers rankings rather than a single answer. Data augmentation expands coverage around difficult skills.</p><p>The method should match the capability and vertical domain. Algorithm design determines how signals are combined. Skill design identifies whether the target is reasoning, extraction, safety, or tool use. Verticalization aligns prompts and evaluations with the deployed domain.</p><p>Richer targets can improve sample efficiency, but they increase storage, leakage risk, generation cost, and training complexity. A narrowly evaluated student can sometimes exceed its teacher on a specific domain because curated data removes irrelevant general behavior and corrects recurring teacher mistakes. That does not imply broader superiority.</p><h3>Context distillation</h3><p>Context distillation trains a student to behave as though stable instructions, examples, policies, or retrieved material were included in every request.</p><pre>Teacher path:<br>Short request + long policy + examples + domain context &gt; Teacher &gt; Answer<br><br>Student path:<br>Short request &gt; Student &gt; Answer<br> stable context moved into weights</pre><p>This can reduce input tokens, prompt‑processing latency, and recurring token cost. It also simplifies application code by removing repeated prompt scaffolding.</p><p>The trade‑off is maintainability. A policy embedded in model weights can become stale. Hidden prompt dependencies are hard to audit, and the student may hallucinate domain facts when the original context would have constrained the answer.</p><p>Keep retrieval and explicit policy checks for fast‑changing, regulated, or auditable knowledge. Distill stable style, terminology, and workflow behavior, but continue injecting current prices, policies, permissions, and customer‑specific records at inference time.</p><p>Version every context bundle used for generation. When the underlying policy changes, rerun the affected evaluation slices before retraining or promoting the student.</p><h3>Step‑by‑step distillation</h3><p>Step‑by‑step distillation trains the student from intermediate reasoning signals as well as final answers. Rationales can show how the teacher decomposes a classification decision, calculation, or multi‑stage workflow.</p><p>This often gives a smaller LLM more supervision per sample. However, unconstrained reasoning traces can contain sensitive information, hallucinated steps, or brittle explanations that sound plausible while leading to the wrong result.</p><p>Safer targets include:</p><ul><li>Concise reasoning summaries</li><li>Verifiable intermediate labels</li><li>Tool‑call traces</li><li>Extracted evidence spans</li><li>Programmatically checked calculations</li><li>Structured plans without private chain‑of‑thought</li></ul><p>The production student does not need to expose its training rationale. It can use rationale supervision during training and return only the answer, evidence, or tool result at inference time.</p><p>Evaluate final‑answer correctness separately from rationale similarity. Otherwise, the student may receive credit for copying the teacher’s wording instead of solving the task. Use independent checks for calculations, code execution, retrieval evidence, and schema validity.</p><h3>Multi‑teacher, self‑distillation, and preference distillation</h3><p>Multi‑teacher distillation combines outputs from multiple LLMs, classifiers, heuristic systems, and human reviewers. This can improve coverage when no single teacher performs well across all slices.</p><p>Resolve conflicts with majority voting, confidence weighting, judge models, weak‑supervision methods, or targeted human review. Record every signal and its weight. A final label without provenance is difficult to debug.</p><p>Self‑distillation uses a model’s own stronger sampled outputs, later checkpoints, or selected candidates to train a smaller or improved version. It can also filter generations by consistency or verified task success.</p><p>Preference distillation uses ranked outputs rather than one accepted response. The student can learn from reward‑model scores, human preferences, or direct preference optimization‑style pairs. This is useful for tone, safety, concision, and instruction‑following behavior that is difficult to express through hard labels.</p><p>Multiple signals can amplify shared bias. Evaluate performance by domain, language, prompt length, customer segment, and safety category. Do not allow a high‑volume but weak teacher to dominate a smaller set of authoritative human labels.</p><h3>Benefits, drawbacks, and what breaks in production</h3><p>Distillation moves work from repeated high‑cost inference into a controlled training pipeline. The primary benefits are lower serving cost, tighter latency, a smaller memory footprint, higher batching capacity, task specialization, and less dependence on the teacher at runtime.</p><p>The drawbacks are equally concrete. The student can inherit teacher errors while losing rare capabilities. It needs a representative dataset, and synthetic outputs can be confidently wrong. Specialization reduces generality. Calibration can drift. Licensing can block otherwise viable data‑generation plans. Aggregate evaluation can hide regressions in long‑tail traffic.</p><p>At scale, failures often originate outside the loss function. Skewed prompt sampling causes blind spots. Long generations create labeling stragglers. Checkpoint accumulation pressures storage. Competing queues delay training or production inference. A seemingly efficient student may regress at p99 because a small set of long requests defeats batching.</p><pre>+++++<br>| Failure mode | Root cause | Symptom | Mitigation |<br>+++++<br>| Hallucination copy | Bad teacher targets | Confident false answers | Verify and filter outputs |<br>| Longtail collapse | Skewed training data | Rareslice regressions | Disagreement sampling |<br>| Calibration drift | Softtarget mismatch | Bad confidence scores | Posttraining calibration |<br>| Queue contention | Shared GPU pool | Missed serving SLA | Priority and quota isolation|<br>| Checkpoint sprawl | Excessive retention | Storage pressure | Lifecycle and promotion rules|<br>| p99 regression | Longsequence outliers | Taillatency spikes | Length caps and split queues|<br>+++++</pre><h3>Benefits and use cases</h3><p>The strongest use cases have stable boundaries, repeated traffic, and measurable quality:</p><ul><li>Support classification: predictable labels and high request volume</li><li>Summarization: repeated format and bounded output</li><li>Structured extraction: schema‑valid results are easy to verify</li><li>Domain chatbots: specialized vocabulary and common workflows</li><li>Code‑review helpers: repeated checks with executable evaluation</li><li>Retrieval reranking: narrow scoring behavior and strict latency targets</li><li>Guardrail models: dedicated classification before or after generation</li><li>Labeling pipelines: offline throughput matters more than interactivity</li></ul><p>Smaller students can fit on fewer or less costly accelerators and may support larger inference batches. Do not estimate the benefit from parameter count alone. Measure tokens per second, GPU memory, p50 and p99 latency, and cost per 1,000 requests under the real sequence‑length distribution.</p><p>Distillation is strongest when production traffic provides a stable, observable target distribution. If prompts, policies, or required capabilities change weekly, the dataset can become stale before the student reaches deployment.</p><h3>Failure modes, evaluation traps, and remediation</h3><p>A distilled student can perform well on synthetic validation data and still fail in production. It may copy teacher hallucinations, lose rare capabilities, overfit a prompt template, miscalibrate confidence, collapse on long context, or fail under distribution shift.</p><p>Common evaluation traps include:</p><ul><li>Using examples seen during teacher prompt development</li><li>Asking the same teacher to grade its student’s outputs</li><li>Reporting averages without long‑tail slices</li><li>Ignoring refusal and safety behavior</li><li>Measuring mean latency but not p99</li><li>Comparing models with different output lengths</li><li>Allowing duplicate synthetic examples across splits</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DSBWaXVMQ6lS6ZGGqgRWLA.png" /></figure><p>Use independent human review and deterministic task checks where possible. Create adversarial sets for malformed input, missing context, conflicting instructions, rare entities, and excessive sequence length.</p><p>Operational edge cases require explicit tests. Tokenizer mismatch can truncate vocabulary or distort KL targets. Teacher‑version changes can silently alter label distributions. Checkpoint formats can become incompatible with a new runtime. Duplicate retries can overweight particular prompts.</p><p>Deploy through shadow traffic and canaries. Define rollback triggers for quality, rejection rate, schema failures, safety violations, p99 latency, and cost. After release, monitor:</p><ul><li>Task‑specific quality</li><li>Input and output drift</li><li>Refusal and rejection rates</li><li>p50 and p99 latency</li><li>Tokens per second</li><li>GPU utilization and memory</li><li>Cost per request</li><li>Distribution of prompt and response lengths</li></ul><h3>Conclusion: designing a distillation platform that survives scale</h3><p>Model distillation transfers useful LLM behavior from a teacher to a smaller student, but its production value depends on pipeline engineering. The model loss is only one component. Label generation, dataset lineage, legal rights, distributed training, scheduling, evaluation, and rollback determine whether the derivative model is deployable.</p><p>Proceed when the task is stable, the teacher provides a strong signal, the organization can legally use the outputs, and the serving SLA is measurable. Require evaluation across quality, calibration, safety, latency, throughput, and cost.</p><p>CoreWeave provides the components needed to operate that workflow without assembling separate infrastructure for each phase. H100 SXM 80GB and H200 141GB pools can run teacher inference and student training. Managed object storage and local NVMe support dataset and checkpoint movement. Kubernetes‑native orchestration handles labeling and evaluation services. SUNK brings Slurm scheduling semantics to distributed training, while high‑performance networking supports collective‑heavy multi‑node runs.</p><p>Treat distillation as a repeatable platform capability, not a one‑off compression experiment. Select one high‑volume task, define its latency and quality targets, run an offline teacher‑labeling job, and compare a governed student deployment with the current serving baseline.</p><h3>Sources</h3><ul><li><a href="https://snorkel.ai/blog/llmdistillationdemystifiedacompleteguide">LLM distillation demystified: a complete guide ‑ Snorkel AI</a></li><li><a href="https://developers.google.com/machinelearning/crashcourse/llm/tuning">LLMs: Fine‑tuning, distillation, and prompt engineering</a></li><li><a href="https://arxiv.org/abs/2402.13116">A Survey on Knowledge Distillation of Large Language Models ‑ arXiv</a></li><li><a href="https://www.datacamp.com/blog/distillationllm">LLM Distillation Explained: Applications, Implementation &amp; More</a></li><li><a href="https://research.google/blog/distillingstepbystepoutperforminglargerlanguagemodelswithlesstrainingdataandsmallermodelsizes">Distilling step‑by‑step: Outperforming larger language models with less training</a></li><li><a href="https://www.exxactcorp.com/blog/deeplearning/whatisllmdistillationvsquantization">What is LLM Distillation vs Quantization | Exxact Blog</a></li><li><a href="https://redis.io/blog/modeldistillationllmguide">Model Distillation for LLMs: Cut Costs &amp; Boost Speed in 2026 ‑ Redis</a></li><li><a href="https://en.wikipedia.org/wiki/Knowledge_distillation">Knowledge distillation ‑ Wikipedia</a></li><li><a href="https://developer.nvidia.com/blog/llmmodelpruningandknowledgedistillationwithnvidianemoframework">LLM Model Pruning and Knowledge Distillation with NVIDIA NeMo Framework | NVIDIA Technical Blog</a></li><li><a href="https://www.ibm.com/think/topics/knowledgedistillation">What is Knowledge distillation? | IBM</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea5c0d741682" width="1" height="1" alt=""><hr><p><a href="https://medium.com/online-inference/model-distillation-for-llms-ea5c0d741682">What is model distillation for LLMs?</a> was originally published in <a href="https://medium.com/online-inference">Online Inference</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLM observability: Tracing, monitoring, and debugging AI applications in production]]></title>
            <link>https://medium.com/online-inference/llm-observability-tracing-monitoring-and-debugging-ai-applications-in-production-bb4e74529256?source=rss----52acf6e3d9be---4</link>
            <guid isPermaLink="false">https://medium.com/p/bb4e74529256</guid>
            <category><![CDATA[llm-evaluation]]></category>
            <category><![CDATA[llmops]]></category>
            <category><![CDATA[llm-evaluation-metrics]]></category>
            <category><![CDATA[llm-observability]]></category>
            <dc:creator><![CDATA[David Davies]]></dc:creator>
            <pubDate>Tue, 11 Aug 2026 02:39:37 GMT</pubDate>
            <atom:updated>2026-08-11T02:39:37.679Z</atom:updated>
            <content:encoded><![CDATA[<p>LLM observability captures traces, logs, metrics, evaluations, and feedback from large‑language‑model applications so teams can explain system behavior, not merely detect incidents. It connects reliability, response quality, safety, cost, and iteration speed through evidence that developers, platform teams, risk reviewers, and business owners can inspect together.</p><p>For an AI leader, LLM observability provides the operating evidence needed to turn LLM and agent experiments into repeatable engineering practices. Instead of asking whether a demonstration looked convincing, teams can measure whether a production workflow completes its task, uses the correct evidence, stays within latency and cost budgets, and follows safety policies.</p><p>This evidence comes from several connected mechanisms:</p><ul><li>LLM tracing records the steps behind each request.</li><li>LLM logging preserves relevant inputs, outputs, errors, and metadata.</li><li>Metrics reveal changes in latency, cost, traffic, and reliability.</li><li>Evaluations measure semantic quality and policy compliance.</li><li>User feedback and expert annotation turn production failures into test cases.</li></ul><p>Dashboards are useful, but they are the presentation layer, not the mechanism. Effective AI observability must connect aggregate signals to request‑level evidence and then feed that evidence back into development.</p><p>This tutorial explains how to define that system, instrument a small retrieval‑augmented‑generation application, and inspect its trace structure. It also covers the trade‑offs and operating‑model decisions an AI leader must make when scaling enterprise LLM applications. Where the workflow requires request tracing, evaluation datasets, scorers, production monitors, or guardrails, W&amp;B Weave provides a concrete implementation path.</p><h3>What LLM observability means and how it differs from traditional monitoring</h3><p>Traditional monitoring tells you that a request was slow, expensive, or unsuccessful. LLM observability adds the causal context behind that outcome, including the prompt, model, retrieved documents, tool calls, intermediate steps, safety checks, and response‑quality signals.</p><p>Conventional services are commonly monitored through uptime, CPU utilization, memory, latency percentiles, request volume, and error rate. Those signals remain necessary for LLM applications, but they cannot tell you whether a fluent response invented a policy or ignored a correct tool result.</p><p>LLM‑specific signals include:</p><ul><li>Prompt, system‑instruction, and response content or hashes</li><li>Prompt and model versions</li><li>Input, output, cached, and reasoning‑token usage</li><li>Retrieved‑document IDs and relevance scores</li><li>Agent‑tool selections, arguments, results, and retries</li><li>Groundedness, hallucination, toxicity, and policy scores</li><li>Refusal appropriateness and citation correctness</li><li>Human‑review and user‑feedback outcomes</li></ul><p>The related terms describe different layers. LLM monitoring tracks predefined metrics and alerts when thresholds are crossed. LLM logging stores individual events and their metadata. LLM tracing connects events into an execution path. LLM debugging uses those signals to locate and correct a problem. AI observability is the broader practice of combining these layers across models, agents, infrastructure, data, and human feedback.</p><p>Monitoring therefore detects symptoms, while observability helps explain causes. A latency alert might reveal that an application exceeded its service‑level objective. The corresponding trace might show that an agent repeated the same tool call five times because a malformed result was treated as retryable.</p><p>Root‑cause analysis is harder than in conventional software because model outputs are non‑deterministic, user inputs are highly variable, context windows are long, and provider‑side model behavior can change. The same code path may return different answers, while different code paths can produce superficially similar answers. Hierarchical traces preserve the context needed to distinguish those cases.</p><h3>Why LLM applications need observability earlier than conventional software</h3><p>LLM applications need observability because many failures look like valid responses. An assistant can return HTTP 200 in two seconds while hallucinating a contractual term, leaking sensitive context, following a prompt‑injection instruction, or consuming ten times the expected tokens.</p><p>Common failure classes include:</p><ul><li>Hallucinations that introduce unsupported claims</li><li>Degraded retrieval that supplies irrelevant, missing, or stale documents</li><li>Prompt injection that overrides application instructions</li><li>Data leakage through prompts, retrieved context, logs, or tool results</li><li>Unsafe or discriminatory content</li><li>Inappropriate refusals that block valid requests</li><li>Latency spikes caused by retrieval, tools, providers, or agent loops</li><li>Token‑cost overruns caused by long contexts or verbose outputs</li><li>Tool calls with unsafe, malformed, or excessive arguments</li><li>Bias or harmful advice in high‑consequence workflows</li></ul><p>These failures often require evidence from several teams. Developers need prompt and trace details. Platform teams need provider, infrastructure, and cost data. Product owners need task‑success and user‑feedback signals. Security and risk reviewers need policy results and audit history.</p><p>A shared observability record prevents each group from reconstructing the incident separately. It also helps Diana prioritize work based on frequency, severity, business impact, and remediation cost.</p><p>The business value is operational rather than cosmetic. Better traces shorten root‑cause analysis. Versioned evaluations reduce repeated regressions. Cost attribution shows which team, workflow, model, or customer segment is driving spend. Audit records help explain what was deployed and how it behaved. Together, these capabilities make it safer to move from a controlled pilot to production traffic.</p><h3>The core mechanism: observe every request as a trace, not a flat log line</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*haADAq8v1Ng3yV1u7kX78A.png" /></figure><p>Tracing an LLM request records each nested step, unlike traditional flat logs.</p><p>The basic unit of LLM observability is the trace. Instead of storing one flat log line for an entire request, a trace records the nested operations that produced the final answer. Each operation is represented as a span with its own inputs, outputs, timing, status, and attributes.</p><p>A useful trace might contain spans for:</p><ol><li>Receiving and validating the request</li><li>Rewriting the user’s query</li><li>Retrieving and reranking documents</li><li>Assembling the prompt</li><li>Calling the model</li><li>Executing tools</li><li>Applying guardrails</li><li>Evaluating the response</li><li>Returning the final result</li></ol><p>The parent‑child relationships matter. If retrieval takes 80 milliseconds and generation takes 2.5 seconds, the trace localizes the latency. If generation receives irrelevant documents, the retrieval span localizes the quality failure. A flat log line cannot reliably preserve these execution boundaries.</p><p>At minimum, capture:</p><ul><li>Request, trace, session, and anonymized‑user identifiers</li><li>Application, prompt, model, provider, and deployment versions</li><li>Input and output hashes, redacted text, or approved full content</li><li>Input, output, cached, and total‑token counts</li><li>Span and end‑to‑end latency</li><li>Estimated or provider‑reported cost</li><li>Retrieved‑document IDs, timestamps, and relevance scores</li><li>Tool names, arguments, results, retry counts, and errors</li><li>Evaluation names, versions, scores, and thresholds</li><li>Environment, region, release, and owning‑team metadata</li></ul><p>Privacy controls must be designed before high‑volume collection begins. Redact sensitive values before export, hash identifiers that do not need to be readable, restrict trace access by role, sample low‑risk traffic, and define retention by data class. Full prompt logging should never become an accidental copy of every confidential document a user can access.</p><p>W&amp;B Weave traces decorated operations and records their inputs, outputs, execution metadata, timing, errors, and nested relationships. Custom attributes can add deployment, tenant, model‑version, or environment context, while input and output post‑processing can remove sensitive content before it is stored.</p><h3>Trace anatomy for RAG and agent systems</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UvG5BzbiF8kRj4KZLuOk5A.png" /></figure><p>A RAG trace shows each operation from input validation to response delivery.</p><p>A useful trace mirrors the application graph. For retrieval‑augmented generation, the tree commonly looks like this:</p><pre>rag_request<br>├── validate_input<br>├── rewrite_query<br>├── create_embedding<br>├── vector_search<br>├── rerank_documents<br>├── assemble_prompt<br>├── generate_answer<br>├── verify_citations<br>└── deliver_response</pre><p>An agent trace has a different shape:</p><pre>agent_request<br>├── load_memory<br>├── plan<br>├── select_tool<br>├── execute_tool<br>│ └── external_service_call<br>├── retry_or_replan<br>├── synthesize_answer<br>├── apply_guardrail<br>└── deliver_response</pre><p>These trees expose edge cases that final‑answer scoring can miss. A correct answer produced from irrelevant retrieval may indicate memorization rather than a healthy RAG path. It should not be treated as proof that retrieval is working. Conversely, an agent might receive a correct tool result and then contradict it during final synthesis. The tool span succeeds, but the synthesis span fails.</p><p>Trace design should therefore distinguish data failures, orchestration failures, model failures, and policy failures. The distinction determines whether the team should update the index, modify the prompt, constrain the agent, switch models, or change a guardrail.</p><p>For organizations already standardizing telemetry through OpenTelemetry, MLflow Tracing provides a conceptually similar mechanism. Its manual tracing decorator captures function inputs, outputs, timing, exceptions, and parent‑child relationships, and its traces can integrate with OpenTelemetry‑compatible infrastructure. This is useful when interoperability is more important than adopting a product‑specific instrumentation layer.</p><h3>The observability stack: logs, traces, metrics, evaluations, and feedback</h3><p>An LLM observability stack is not one data type. Logs preserve raw evidence, traces explain execution paths, metrics expose trends, evaluations measure semantic behavior, and feedback connects production outcomes to the next development cycle.</p><p>A complete stack contains:</p><ul><li>Prompt and response logging with privacy controls</li><li>End‑to‑end traces with nested spans</li><li>Latency and throughput monitoring</li><li>Token and cost attribution</li><li>Reliability and provider‑health metrics</li><li>RAG retrieval and citation diagnostics</li><li>Task‑specific quality evaluation</li><li>Safety and compliance checks</li><li>Dashboards and threshold‑based alerts</li><li>User feedback and expert‑annotation workflows</li><li>Versioned prompts, datasets, scorers, and model configurations</li></ul><p>Each component supports a leadership decision. Latency and quality thresholds define shipping criteria. Cost per successful task informs model and infrastructure budgets. Safety evaluations support risk review. Trace volume and incident patterns reveal whether additional platform or evaluation staffing is needed. Regression coverage shows whether an application is ready for wider deployment.</p><p>The stack should also integrate with existing engineering systems. Look for SDK‑level instrumentation, OpenTelemetry compatibility, CI/CD hooks, data‑warehouse export, annotation workflows, role‑based access controls, and stable identifiers that connect traces to releases and incidents.</p><p>There is no universally best LLM observability tool. W&amp;B Weave fits teams that want tracing, evaluations, prompt experimentation, production monitors, and guardrails connected to their AI‑development workflow. MLflow Tracing fits teams prioritizing open‑source, OpenTelemetry‑compatible instrumentation. Langfuse offers an open‑source, self‑hosted path, while Datadog Agent Observability connects LLM traces to a broader application‑performance‑monitoring environment. Direct OpenTelemetry instrumentation offers control and portability, but the team may need to build evaluation, annotation, and review layers separately.</p><h3>From raw events to decisions: what each signal is for</h3><p>Each signal answers a different question:</p><ul><li>Logs answer, “What was sent, returned, or reported?”</li><li>Traces answer, “How did the system reach this outcome?”</li><li>Metrics answer, “How often does this happen, and how severe is it?”</li><li>Evaluations answer, “Was the behavior good enough for the task?”</li><li>Feedback answers, “How did users or reviewers judge the result?”</li></ul><p>Suppose groundedness declines after a release. Metrics establish the scope. Traces show that a new query‑rewrite prompt removed product identifiers. Logs preserve the rewritten queries. Evaluation scores identify the affected test cases. The team can then roll back the prompt, repair query rewriting, or tune retrieval.</p><p>Other evidence‑driven actions include switching models, reducing context size, adjusting timeout budgets, disabling a failing tool, adding a prompt‑injection guardrail, or creating a new test dataset from production incidents.</p><p>User feedback and expert annotations should attach to the originating trace. That association preserves the request context, retrieved evidence, application version, and model output. Carefully sampled and labeled production traces can then become evaluation cases.</p><p>Production data is not automatically high‑quality evaluation data. Users may misunderstand the task, feedback can be adversarial, and successful outcomes are often underreported. Before adding a trace to a regression set, validate its inputs, expected behavior, risk tier, and annotation quality.</p><h3>Metrics that matter: performance, cost, reliability, and quality</h3><p>Monitor LLM performance, cost, reliability, and quality with targeted metrics.</p><p>LLM monitoring should separate system performance from semantic quality. A fast response may be wrong or unsafe. A correct answer may be too slow or expensive to serve at the required volume.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7ZF6Mqsigs3ofkUL9psMjg.png" /></figure><p>Organize metrics into four groups with different owners and thresholds.</p><ul><li>Performance: Track end‑to‑end latency, model latency, retrieval latency, reranking latency, tool latency, queue time, time to first token, timeout rate, and throughput. Application and platform teams usually own these service‑level indicators.</li><li>Cost: Track input, output, cached, and reasoning tokens; embedding and reranking calls; tool usage; cost per request; cost per successful task; and cost by team, feature, tenant, or product surface. Product and platform leaders should jointly own these budgets.</li><li>Reliability: Track application errors, provider errors, retry rate, fallback rate, provider saturation, tool failure rate, empty retrieval rate, malformed‑output rate, and agent loop depth. Engineering owners need thresholds that distinguish transient provider issues from application defects.</li><li>Semantic quality: Track task success, groundedness, hallucination rate, citation correctness, answer completeness, refusal appropriateness, toxicity, bias indicators, and human‑review outcomes. Product, domain, and risk owners must define acceptable behavior.</li></ul><p>Avoid one combined “health score.” Aggregation can hide unacceptable trade‑offs. A release that improves latency by 20 percent while doubling policy errors should not pass because its average score increased.</p><p>Metrics should be segmented by prompt version, model, provider, language, user cohort, request type, and risk tier. Global averages conceal tail failures. For example, acceptable median latency may coexist with severe timeouts in tool‑using requests, while acceptable overall groundedness may hide poor performance on a newly added product line.</p><h3>How observability evaluates hallucinations, grounding, and response quality</h3><p>LLM quality becomes observable only after the team defines what good means for the task. A support agent might require correct policy use, grounded answers, appropriate escalation, safe refusals, and case resolution. A code assistant might require tests passed, secure dependencies, valid syntax, and adherence to repository conventions.</p><p>Use several evaluation methods together:</p><ul><li>Deterministic checks for schemas, citations, tool arguments, and exact rules</li><li>Reference‑based tests with expected answers or accepted alternatives</li><li>Model‑based scorers for groundedness, relevance, tone, or completeness</li><li>Human review for ambiguous or high‑consequence cases</li><li>Production feedback for real‑world usefulness</li><li>End‑to‑end task outcomes such as resolution or workflow completion</li></ul><p>Hallucination detection can extract claims from an answer and compare them with approved references. Citation verification checks whether cited evidence supports each claim. Retrieval‑overlap checks reveal whether the response uses the retrieved context. Contradiction checks look for conflict between the answer and source material.</p><p>For RAG, separate retrieval failure from generation failure. If the necessary document was not retrieved, changing the generation prompt may not help. If the correct document was retrieved but ignored, the problem is more likely prompt construction, context ordering, model behavior, or final synthesis.</p><p>Safety and compliance checks should cover prompt injection, sensitive‑data leakage, toxic content, policy violations, unsafe tool calls, and inappropriate refusal behavior. Evaluation datasets must be versioned and refreshed with reviewed production cases so release tests represent current traffic and policies.</p><h3>Evaluation edge cases leaders should expect</h3><p>Evaluation failures can be subtler than model failures. An LLM judge can penalize a correct answer, accept a harmful answer, or change its decisions after a model update.</p><p>False positives and negatives are common when answers have multiple valid formulations, when domain language is nuanced, or when the evaluator is weaker in a particular language. Hallucination detection is also difficult when the source of truth is incomplete, contradictory, time‑sensitive, or distributed across several systems.</p><p>Evaluators can drift for several reasons:</p><ul><li>The judge model or provider changes.</li><li>The scorer prompt is revised.</li><li>Retrieval data is updated.</li><li>A policy changes the definition of acceptable behavior.</li><li>New products or user groups introduce unfamiliar cases.</li></ul><p>Treat evaluators as versioned production components. Maintain a gold set reviewed by domain experts, run human spot checks, record scorer and prompt versions, analyze disagreements, and tune thresholds by risk tier. A low‑risk drafting tool can tolerate more evaluator uncertainty than an agent authorized to execute financial operations.</p><p>W&amp;B Weave Evaluations can run the same versioned dataset and scorer set against multiple prompt or model implementations. Function‑based or class‑based scorers produce stored evaluation results, making it possible to compare versions without silently changing the test definition.</p><h3>Worked example: instrument a simple RAG call with tracing and evaluation</h3><p>A small instrumented RAG path is enough to demonstrate the central mechanism. The following exercise creates separate spans for retrieval, prompt assembly, generation, and groundedness scoring.</p><p>The generator is intentionally deterministic, so the example runs without an LLM‑provider API key. After the trace structure works, replace the stub with your preferred client call.</p><p>Create a virtual environment and install Weave:</p><pre>python m venv.venv<br>source.venv/bin/activate<br>pip install upgrade weave<br>wandb login</pre><p>On Windows PowerShell, activate the environment with:</p><pre>.venv\Scripts\Activate.ps1</pre><p>Create a file named rag_observability.py. The example will:</p><ol><li>Initialize a Weave project.</li><li>Retrieve documents from an in‑memory collection.</li><li>Assemble a prompt.</li><li>Generate a deterministic answer.</li><li>Estimate token usage and record latency.</li><li>Score whether the answer is supported by the retrieved text.</li><li>Return a single result containing the operational and quality signals.</li></ol><p>Production code should redact or transform prompts, retrieved text, user identifiers, and model outputs before logging them if they can contain sensitive information.</p><h3>Runnable snippet to make trace structure concrete</h3><p>The trace tree contains one parent request and four child operations. The structure, rather than the toy retrieval or scoring algorithm, is the lesson.</p><pre>import json<br>import re<br>import time<br><br>import weave<br>weave.init(<br> &quot;llmobservabilityrag&quot;,<br> global_attributes={<br> &quot;environment&quot;: &quot;tutorial&quot;,<br> &quot;app_version&quot;: &quot;1.0.0&quot;,<br> },<br>)<br>DOCUMENTS = [<br> {<br> &quot;id&quot;: &quot;refundpolicyv3&quot;,<br> &quot;text&quot;: &quot;Annual plans are refundable within 30 days of purchase.&quot;,<br> },<br> {<br> &quot;id&quot;: &quot;cancellationguidev2&quot;,<br> &quot;text&quot;: &quot;Monthly plans can be canceled at any time before renewal.&quot;,<br> },<br> {<br> &quot;id&quot;: &quot;securityoverviewv1&quot;,<br> &quot;text&quot;: &quot;Enterprise accounts support single signon and audit logs.&quot;,<br> },<br>]<br>STOPWORDS = {<br> &quot;a&quot;, &quot;an&quot;, &quot;and&quot;, &quot;are&quot;, &quot;at&quot;, &quot;be&quot;, &quot;can&quot;, &quot;for&quot;,<br> &quot;is&quot;, &quot;of&quot;, &quot;or&quot;, &quot;the&quot;, &quot;to&quot;, &quot;what&quot;, &quot;within&quot;,<br>}<br>def terms(text: str) &gt; set[str]:<br> words = set(re.findall(r&quot;[az09]+&quot;, text.lower()))<br> return words  STOPWORDS<br>@weave.op(name=&quot;retrieve&quot;, kind=&quot;search&quot;)<br>def retrieve(query: str, k: int = 2) &gt; dict:<br> started = time.perf_counter()<br> ranked = sorted(<br> DOCUMENTS,<br> key=lambda doc: len(terms(query) &amp; terms(doc[&quot;text&quot;])),<br> reverse=True,<br> )<br> return {<br> &quot;documents&quot;: ranked[:k],<br> &quot;latency_ms&quot;: round((time.perf_counter()  started) * 1000, 3),<br> }<br>@weave.op(name=&quot;assemble_prompt&quot;)<br>def assemble_prompt(query: str, documents: list[dict]) &gt; str:<br> context = &quot;\n&quot;.join(<br> f&quot;[{doc[&#39;id&#39;]}] {doc[&#39;text&#39;]}&quot; for doc in documents<br> )<br> return (<br> &quot;Answer only from the supplied context.\n\n&quot;<br> f&quot;Context:\n{context}\n\n&quot;<br> f&quot;Question: {query}&quot;<br> )<br>@weave.op(name=&quot;generate_answer&quot;, kind=&quot;llm&quot;)<br>def generate_answer(<br> prompt: str,<br> retrieved_document_ids: list[str],<br>) &gt; dict:<br> started = time.perf_counter()<br> # Replace this deterministic stub with an LLMclient call.<br> if &quot;Annual plans are refundable within 30 days&quot; in prompt:<br> answer = &quot;Annual plans are refundable within 30 days of purchase.&quot;<br> else:<br> answer = &quot;The supplied context does not contain the answer.&quot;<br> return {<br> &quot;text&quot;: answer,<br> &quot;model&quot;: &quot;deterministicragstubv1&quot;,<br> &quot;retrieved_document_ids&quot;: retrieved_document_ids,<br> &quot;usage&quot;: {<br> &quot;input_tokens_est&quot;: len(prompt.split()),<br> &quot;output_tokens_est&quot;: len(answer.split()),<br> },<br> &quot;latency_ms&quot;: round((time.perf_counter()  started) * 1000, 3),<br> }<br>@weave.op(name=&quot;score_groundedness&quot;)<br>def score_groundedness(<br> answer: str,<br> documents: list[dict],<br>) &gt; dict:<br> answer_terms = terms(answer)<br> evidence_terms = terms(<br> &quot; &quot;.join(doc[&quot;text&quot;] for doc in documents)<br> )<br> supported = len(answer_terms &amp; evidence_terms)<br> score = supported / max(len(answer_terms), 1)<br> return {<br> &quot;groundedness&quot;: round(score, 3),<br> &quot;threshold&quot;: 0.8,<br> &quot;passed&quot;: score &gt;= 0.8,<br> }<br>@weave.op(name=&quot;rag_request&quot;)<br>def ask(query: str) &gt; dict:<br> retrieval = retrieve(query)<br> documents = retrieval[&quot;documents&quot;]<br> document_ids = [doc[&quot;id&quot;] for doc in documents]<br> prompt = assemble_prompt(query, documents)<br> generation = generate_answer(prompt, document_ids)<br> evaluation = score_groundedness(<br> generation[&quot;text&quot;],<br> documents,<br> )<br> return {<br> &quot;query&quot;: query,<br> &quot;retrieved_document_ids&quot;: document_ids,<br> &quot;answer&quot;: generation[&quot;text&quot;],<br> &quot;usage&quot;: generation[&quot;usage&quot;],<br> &quot;retrieval_latency_ms&quot;: retrieval[&quot;latency_ms&quot;],<br> &quot;generation_latency_ms&quot;: generation[&quot;latency_ms&quot;],<br> &quot;groundedness&quot;: evaluation,<br> }<br>with weave.attributes(<br> {<br> &quot;prompt_version&quot;: &quot;ragpromptv1&quot;,<br> &quot;release&quot;: &quot;tutorialrelease1&quot;,<br> &quot;risk_tier&quot;: &quot;low&quot;,<br> }<br>):<br> result = ask(&quot;What is the refund window for annual plans?&quot;)<br>print(json.dumps(result, indent=2))</pre><p>Run it:</p><pre>python rag_observability.py</pre><p>The printed result should include refund‑policy‑v3, the 30‑day answer, token estimates, latency values, and a passing groundedness score. Weave also prints a trace link. Open it and inspect:</p><ol><li>The rag_request parent operation</li><li>The retrieve input, output, document IDs, and timing</li><li>The assembled prompt</li><li>The generation result, model identifier, and token estimates</li><li>The groundedness value and threshold</li><li>The prompt‑version, release, and risk‑tier attributes</li></ol><p>When you replace the stub with a supported provider client, provider instrumentation can capture model calls and available usage metadata inside the same trace. For an OpenTelemetry implementation, preserve the same parent‑child structure using explicit spans and semantic attributes. For MLflow Tracing, replace @ with @ and retain the operation names and metadata schema. The objective is consistent instrumentation shape, not a model‑quality benchmark.</p><h3>Trade‑offs analysis: accuracy vs latency, cost vs throughput, and flexibility vs determinism</h3><p>LLM observability is a design trade‑off, not a free add‑on. Instrumentation and evaluation can improve reliability while adding latency, cost, privacy exposure, and operational complexity.</p><p>Accuracy vs latency appears when teams add retrieval passes, reranking, larger contexts, tool verification, citation checking, or model‑based evaluators. Each step may improve quality, but it extends the critical path. Passive evaluation after a response avoids user‑facing latency, while inline guardrails can block unsafe behavior but must complete before delivery.</p><p>Cost vs throughput affects both the application and observability system. Full prompt logging increases storage. Scoring every response with another large model adds inference cost. Recording every span increases ingestion volume. Sampling lowers cost but can miss rare failures. A practical policy might retain operational metrics for all requests, sample ordinary traces, and preserve full traces for errors, policy failures, unusually expensive calls, and high‑risk workflows.</p><p>Flexibility vs determinism is especially important for agents. Open‑ended agents can adapt their plans and tools to unfamiliar requests, but variable paths are harder to reproduce and govern. Constrained workflows are less flexible, yet easier to test with exact expectations, bounded tool access, and predictable trace shapes.</p><p>Other trade‑offs include:</p><ul><li>Full‑fidelity logging vs privacy and contractual risk</li><li>Real‑time alerting vs noisy, low‑confidence incidents</li><li>Broad executive dashboards vs task‑specific decision metrics</li><li>Long retention vs data‑minimization requirements</li><li>Universal thresholds vs risk‑tier‑specific controls</li></ul><p>Tier observability depth by risk, revenue impact, regulatory exposure, and failure recoverability. A reversible content suggestion does not require the same evidence as a tool call that changes a customer account.</p><h3>Operational design: from isolated experiments to repeatable AI development</h3><p>Integrating observability creates a repeatable, reliable AI development process.</p><p>Observability creates the most value when it becomes part of the development lifecycle. Teams should use the same evidence to compare versions, approve releases, investigate incidents, and build future evaluation cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Z2tpiPxO6y_WDwSyz3qb_w.png" /></figure><p>A repeatable workflow looks like this:</p><ol><li>Developers create prompt, retrieval, model, or agent variants.</li><li>Each variant runs against a versioned evaluation dataset.</li><li>Scorers measure task quality, safety, latency, and cost.</li><li>Developers review aggregate results and representative traces.</li><li>Approved configurations pass release gates.</li><li>Production monitors track operational and semantic regressions.</li><li>Failed traces enter annotation and incident‑review workflows.</li><li>Reviewed failures become new evaluation cases.</li></ol><p>W&amp;B Models and W&amp;B Weave serve different but connected parts of this lifecycle. Use W&amp;B Models Experiments and Sweeps to track training or fine‑tuning runs. Use Artifacts to version datasets, checkpoints, and other workflow inputs or outputs. Use the Registry to govern approved model versions. Use Tables, Workspaces, and Reports to analyze and communicate results.</p><p>Use W&amp;B Weave Traces to inspect application execution, Evaluations and scorers to compare application versions, Playground to test prompts and models, Monitors to score production traffic, and Guardrails when scores must affect application control flow. Traces created inside a W&amp;B run can also be associated with that run, connecting model‑development experiments to downstream application behavior.</p><p>Governance should specify:</p><ul><li>An owner for each application, scorer, dataset, and monitor</li><li>Service‑level objectives for latency, reliability, quality, and cost</li><li>Access controls and approved logging fields</li><li>Trace‑sampling and retention rules</li><li>Required evaluation and review gates</li><li>Prompt, model, scorer, and dataset lineage</li><li>Rollback and incident‑response procedures</li></ul><p>This structure reduces duplicated debugging and makes budget discussions more concrete. Leaders can see whether higher model spend produces better task outcomes, whether a retrieval project reduces failure volume, or whether an agent’s flexibility creates unacceptable operational risk.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YMLgvc7jxnlgZYajgUA1fg.png" /></figure><h3>A practical rollout plan for enterprise LLM observability</h3><p>Roll out LLM observability in clear phases, starting small and expanding strategically.</p><p>Start with one high‑value application where quality, cost, or risk is visible to the business. Do not begin by instrumenting every prototype.</p><p>Phase the rollout:</p><ol><li>Instrument the end‑to‑end request and its major child spans.</li><li>Add latency, token, cost, and reliability metrics.</li><li>Define two or three task‑specific quality evaluations.</li><li>Review traces for failures and high‑cost outliers.</li><li>Add production sampling and monitors.</li><li>Introduce release gates and governance policies.</li><li>Expand the standard to additional applications.</li></ol><p>Application developers should own correct instrumentation and meaningful span boundaries. The AI‑platform team should own shared schemas, integrations, retention policies, and reusable scorers. Risk teams should review safety and compliance signals. Product leaders should define success criteria and acceptable trade‑offs.</p><p>Useful initial policies include redaction of sensitive fields, sampling of routine low‑risk traffic, full tracing of high‑risk failures, versioning of prompts and scorers, and holding a weekly trace‑review session. The review should end with assigned actions, not merely observations.</p><p>The same rollout works for customer‑support agents, internal‑knowledge assistants, code copilots, RAG search, reviewed clinical or legal drafting support, and tool‑using operations agents. Measure progress through fewer unresolved incidents, faster diagnosis, broader regression coverage, clearer cost attribution, and increased release confidence. These are organization‑specific outcomes, so establish a baseline rather than importing an external benchmark.</p><h3>When not to use LLM observability, or when to keep it minimal</h3><p>Do not implement full‑fidelity LLM observability by default. A prototype, short‑lived demonstration, very low‑risk internal tool, or deterministic workflow may not justify complete prompt logging, model‑based evaluation, and production monitors.</p><p>Conventional monitoring may be sufficient when the model performs a simple classification task with deterministic labels and exact tests already cover the behavior. Model‑based scoring may also be wasteful for tiny traffic volumes where manual review is cheaper and more reliable.</p><p>Logging prompts and responses can create unacceptable privacy, security, contractual, or regulatory risk. If redaction, access control, and retention policies are not ready, collect metadata and hashes instead of full content. In some environments, even redacted prompts can reveal sensitive intent or document structure.</p><p>Over‑instrumentation creates its own failure modes. Excessive spans can obscure the operations that matter. Noisy alerts train teams to ignore incidents. Unowned data consumes budget without improving decisions. Instrumentation requirements can also slow developers if every application must satisfy an oversized schema before its risk is understood.</p><p>A minimum viable setup should capture end‑to‑end latency, error rate, token spend, prompt version, model version, and a redacted sample of traces. Add manual review for selected failures. Expand only when a decision, risk, or recurring diagnostic problem requires more evidence.</p><h3>Closting thoughts</h3><p>LLM observability is the operating evidence layer for reliable AI applications. Its value is not the number of dashboards a team creates. Its value is the ability to diagnose causes faster, evaluate changes consistently, control cost, release more safely, and convert production behavior into reusable development evidence.</p><p>Choose one production or near‑production application. Define its trace schema, latency and cost budgets, task‑specific quality measures, privacy policy, and release gates. Instrument the major execution steps, inspect real traces, and confirm that every collected signal supports an owner and a decision.</p><p>For teams that need tracing, evaluations, monitoring, guardrails, and production feedback integrated into the development workflow, W&amp;B Weave provides a concrete implementation path. The operating principle remains tool‑independent: make important AI behavior traceable, measurable, reviewable, and reproducible before scaling it.</p><h3>Sources</h3><ul><li><a href="https://docs.wandb.ai/weave/concepts/whatisweave">What is Weave? ‑ Weights &amp; Biases Documentation</a></li><li><a href="https://docs.wandb.ai/weave/guides/tracking/tracing">Understand Ops, Calls, and Traces ‑ Weights &amp; Biases Documentation</a></li><li><a href="https://mlflow.org/docs/latest/genai/tracing/opentelemetry">OpenTelemetry Integration | MLflow AI Platform</a></li><li><a href="https://docs.wandb.ai/weave/guides/tools/playground">Use the Playground to experiment with prompts ‑ Weights &amp; Biases Documentation</a></li><li><a href="https://docs.wandb.ai/weave/guides/evaluation/scorers">Scoring overview ‑ Weights &amp; Biases Documentation</a></li><li><a href="https://docs.wandb.ai/weave/quickstart">Quickstart: Instrument and trace functions ‑ Weights &amp; Biases Documentation</a></li><li><a href="https://docs.wandb.ai/models">W&amp;B Models ‑ Weights &amp; Biases Documentation</a></li><li><a href="https://mlflow.org/docs/latest/genai/tracing">LLM Tracing and Agent Observability | MLflow AI Platform</a></li><li><a href="https://medium.com/onlineinference/llmobservabilitytoolsmonitoringdebuggingandimprovingaisystems5af769796266">LLM observability tools: Monitoring, debugging, and improving AI …</a></li><li><a href="https://www.truefoundry.com/blog/llmobservabilitytools">10 Best LLM Observability Tools in 2026 ‑ Truefoundry</a></li><li><a href="https://www.langchain.com/resources/llmobservabilitytools">8 LLM Observability Tools to Monitor &amp; Eval AI Agents ‑ LangChain</a></li><li><a href="https://docs.datadoghq.com/llm_observability">Agent Observability ‑ Datadog Docs</a></li><li><a href="https://langfuse.com/docs/observability/overview">LLM Observability &amp; Application Tracing (Open Source) ‑ Langfuse</a></li><li><a href="https://www.patronus.ai/llmtesting/llmobservability">LLM Observability: Tutorial &amp; Best Practices ‑ Patronus AI</a></li><li><a href="https://wandb.ai/onlineinference/genairesearch/reports/AguidetoLLMdebuggingtracingandmonitoringVmlldzoxMzk1MjAyOQ">A guide to LLM debugging, tracing, and monitoring | genai‑research</a></li><li><a href="https://www.datadoghq.com/products/ai/agentobservability">Agent Observability | LLM Observability ‑ Datadog</a></li><li><a href="https://docs.dynatrace.com/docs/observe/dynatraceforaiobservability">AI Observability for generative AI and LLM models with Dynatrace</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb4e74529256" width="1" height="1" alt=""><hr><p><a href="https://medium.com/online-inference/llm-observability-tracing-monitoring-and-debugging-ai-applications-in-production-bb4e74529256">LLM observability: Tracing, monitoring, and debugging AI applications in production</a> was originally published in <a href="https://medium.com/online-inference">Online Inference</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Convert Jupyter Notebook to Python for reproducible ML experiments]]></title>
            <link>https://medium.com/online-inference/convert-jupyter-notebook-to-python-for-reproducible-ml-experiments-6bbc1bca5cf7?source=rss----52acf6e3d9be---4</link>
            <guid isPermaLink="false">https://medium.com/p/6bbc1bca5cf7</guid>
            <category><![CDATA[marimo]]></category>
            <category><![CDATA[jupyter-notebook]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[David Davies]]></dc:creator>
            <pubDate>Thu, 06 Aug 2026 23:00:33 GMT</pubDate>
            <atom:updated>2026-08-06T23:00:33.506Z</atom:updated>
            <content:encoded><![CDATA[<p>To convert a Jupyter Notebook to a standard Python script, the quickest reliable method is jupyter nbconvert — to script notebook.ipynb. For a one-off conversion, use the export command in Jupyter or Visual Studio Code. For ML research, however, generating the file is only the first step. You must also verify that the script preserves the notebook’s state, configuration, execution flow, metrics, and artifacts.</p><h3>Introduction: convert notebooks without losing experiment context</h3><p>The fastest command-line path is:</p><pre>jupyter nbconvert --to script notebook.ipynb</pre><p>This converts the notebook’s code into an executable script with the same base filename. For example, notebook.ipynb becomes notebook.py. If you only need to send a script to a collaborator, exporting from the Jupyter interface can be even easier.</p><p>The practical problem for an ML researcher is not changing the extension. It is moving from interactive exploration to repeatable training, evaluation, and review without manually rewriting working notebook logic. A notebook may depend on variables created several cells earlier, environment variables loaded interactively, a specific working directory, or checkpoints left by a previous run.</p><p>Conversion also changes how the document is represented. Markdown may become comments, outputs are normally omitted, metadata may disappear, and cells execute sequentially rather than according to their recorded execution counts. Parameters that were previously edited in a cell must become explicit configuration if the script will run in CI, on a GPU worker, or through a scheduler.</p><p><a href="https://marimo.io/">Marimo</a> provides another path when notebook-to-script conversion becomes recurring overhead. A Marimo notebook is stored as executable Python, uses reactive dependency-based execution, and can be reviewed in Git without treating JSON as source code. Existing Jupyter notebooks can also be converted with marimo convert notebook.ipynb &gt; notebook.py.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*W4lqfySjVLUFynM79jz1cw.gif" /><figcaption>Marimo</figcaption></figure><h3>What actually changes when.ipynb becomes.py</h3><p>A Jupyter Notebook is a JSON document. At the top level, it contains notebook metadata, format-version fields, and an ordered list of cells. Individual cells can contain code, Markdown, raw text, metadata, execution counts, attachments, and outputs such as text, images, HTML, or other rich media. Kernel and language information commonly appear in notebook metadata.</p><p>A Python script is ordered text. Conversion tools normally traverse the notebook’s cells from top to bottom, emit code-cell source, and either turn Markdown into comments or omit it. Stored outputs are not part of ordinary script execution. Widget state, embedded images, execution history, and frontend-specific metadata generally do not become executable Python.</p><p>This difference exposes hidden state. Consider a notebook whose first cell loads train_df, whose fourth cell modifies it, and whose second cell trains a model. If the researcher ran cells 1, 4, and 2, the displayed metric may be valid for the modified data. The exported script runs cells 1, 2, and 4, producing a different experiment.</p><p>Before conversion, use Jupyter’s restart-and-run-all operation. If that fails or changes the result, the notebook is not yet a trustworthy source for a script.</p><p>For ML work, explicitly check:</p><ul><li>Random seeds for Python, NumPy, PyTorch, JAX, or TensorFlow</li><li>Dataset versions and relative paths</li><li>Train, validation, and test splits</li><li>Model and tokenizer identifiers</li><li>Checkpoint input and output locations</li><li>Device selection and distributed-training settings</li><li>Metric definitions and aggregation behavior</li><li>Evaluation tables, plots, and generated artifacts</li></ul><p>Conversion preserves source text more reliably than it preserves experimental meaning.</p><h3>Fastest command-line method: use nbconvert</h3><p>For most local workflows, nbconvert is the direct answer to “how do I change a Jupyter notebook to a Python file?”</p><pre>jupyter nbconvert --to script path/to/notebook.ipynb</pre><p>The script exporter creates a script appropriate for the notebook’s kernel. For an ipykernel notebook, the result is a .py file. Older posts and configurations may show — to python; use — to script for current workflows.</p><p>If the command is unavailable, install nbconvert in the environment from which you are running Jupyter:</p><pre>python -m pip install nbconvert</pre><p>For Conda environments:</p><pre>conda install nbconvert</pre><p>Then verify the installation:</p><pre>jupyter nbconvert --version</pre><p>If your shell reports jupyter: command not found or jupyter nbconvert not found, confirm that you activated the intended environment. Also compare these paths:</p><pre>which python<br>which jupyter</pre><p>On Windows, use:</p><pre>where python<br>where jupyter</pre><p>The standard exporter may include cell-prompt comments such as # In[3]:. Remove these when generating reviewable or package-ready code:</p><pre>jupyter nbconvert --to script --no-prompt notebook.ipynb</pre><p>The — no-prompt option excludes input and output prompts from converted documents.</p><p>Do not treat successful conversion as proof that the result is a valid standalone program. Notebook magics can remain in translated IPython calls, and hidden dependencies only become visible when the new script starts in a clean process.</p><h3>Step-by-step nbconvert workflow for a single notebook</h3><p>A safe workflow has two phases: generate the script, then prove that it runs without notebook state.</p><ol><li><strong>Activate the notebook’s Python environment.</strong></li></ol><p>For a virtual environment:</p><pre>source.venv/bin/activate</pre><p>On Windows:</p><pre>.venv\Scripts\Activate.ps1</pre><p>For Conda:</p><pre>conda activate model-research</pre><p>Confirm that the interpreter has the expected dependencies:</p><pre>python -c &quot;import torch, pandas; print(torch.__version__)&quot;</pre><p>bash</p><p><strong>2. Convert the notebook.</strong></p><p>From the repository root, run the requested command:</p><pre>jupyter nbconvert --to script --no-prompt experiments/train.ipynb</pre><p>The documented default is to write the converted file in the current working directory. To guarantee that the output is experiments/train.py, specify the output directory:</p><pre>jupyter nbconvert \<br> --to script \<br> --no-prompt \<br> --output-dir experiments \<br> experiments/train.ipynb</pre><p>Expected terminal output resembles:</p><pre>[NbConvertApp] Converting notebook experiments/train.ipynb to script<br>[NbConvertApp] Writing 8421 bytes to experiments/train.py</pre><p>Confirm the file exists:</p><pre>test -f experiments/train.py &amp;&amp; echo &quot;conversion succeeded&quot;</pre><p><strong>3. Run the script from zero state.</strong></p><pre>python experiments/train.py</pre><p>This exposes missing imports, undefined variables, notebook-only magics, implicit display calls, and path assumptions. Run it from the same directory your scheduler or CI runner will use, usually the repository root.</p><p><strong>4. Compare experiment outputs.</strong></p><p>Check more than the final printed accuracy. Compare:</p><ul><li>Training and validation metrics</li><li>Number of processed examples</li><li>Data-split hashes or row counts</li><li>Saved checkpoint names and sizes</li><li>Evaluation-table contents</li><li>Plot data, not only rendered images</li><li>Tracking-run parameters and tags</li></ul><p>Small floating-point differences may be acceptable on GPU hardware. Changes in sample counts, label mappings, or metric definitions are not.</p><p><strong>5. Choose the source of truth.</strong></p><p>If train.ipynb remains canonical, regenerate train.py rather than editing it manually. If train.py becomes canonical, move reusable logic there and reduce the notebook to an exploratory client. Commit both only when the team has a synchronization rule.</p><h3>Export from Jupyter Notebook, JupyterLab, and VS Code</h3><p>For one file, a graphical export is often the easiest way to turn a.ipynb into a.py.</p><p>In Jupyter Notebook or Notebook 7:</p><ol><li>Open the notebook.</li><li>Open the File menu.</li><li>Select the save-and-export command.</li><li>Look for Executable Script, Python Script, or a similarly named option.</li><li>Save the downloaded .py file.</li><li>Run it from a terminal with python filename.py.</li></ol><p>The exact label depends on the Jupyter version, kernel, environment, and available exporters. A Python option normally requires the notebook to use a Python kernel.</p><p>In JupyterLab, open the notebook and inspect the File menu’s export options. Executable Script is a supported export type, although the visible choices depend on the environment’s nbconvert configuration.</p><p>If Notebook 7 does not show a Python export option, create a clean environment and test there:</p><pre>python -m venv export-test<br>source export-test/bin/activate<br>python -m pip install notebook nbconvert ipykernel<br>jupyter notebook</pre><p>Old nbextensions are not required by nbconvert. A missing exporter is more likely to indicate an environment or configuration problem than a need to downgrade to Notebook 6.</p><p>In Visual Studio Code:</p><ol><li>Install the Python and Jupyter extensions.</li><li>Open the .ipynb file.</li><li>Select the notebook conversion or export control, or open the command palette.</li><li>Run Jupyter: Export to Python Script.</li><li>Save the resulting untitled Python file.</li></ol><p>VS Code can preserve cell boundaries as # %% markers, which lets the exported file continue to behave like a cell-based document in supported editors.</p><h3>Convert notebooks programmatically inside Python</h3><p>Conversion does not require a shell command. Use the nbconvert Python API when conversion is part of a build, training-submission, or evaluation pipeline.</p><p>Install the required libraries:</p><pre>python -m pip install nbconvert nbformat</pre><p>Create tools/convert_notebook.py:</p><pre>from pathlib import Path<br><br><br>import nbformat<br>from nbconvert import PythonExporter<br><br><br><br><br>def notebook_to_python(<br> notebook_path: str | Path,<br> output_path: str | Path | None = None,<br>) -&gt; Path:<br> source = Path(notebook_path)<br> destination = (<br> Path(output_path)<br> if output_path is not None<br> else source.with_suffix(&quot;.py&quot;)<br> )<br><br><br> notebook = nbformat.read(source, as_version=4)<br><br><br> exporter = PythonExporter()<br> python_source, resources = exporter.from_notebook_node(notebook)<br><br><br> destination.parent.mkdir(parents=True, exist_ok=True)<br> destination.write_text(python_source, encoding=&quot;utf-8&quot;)<br><br><br> return destination<br><br><br><br><br>if __name__ == &quot;__main__&quot;:<br> result = notebook_to_python(<br> &quot;experiments/train.ipynb&quot;,<br> &quot;generated/train.py&quot;,<br> )<br> print(f&quot;Wrote {result}&quot;)</pre><p>Run it:</p><pre>python tools/convert_notebook.py</pre><p>Expected output:</p><pre>Wrote generated/train.py</pre><p>PythonExporter accepts a notebook node and returns the converted source plus a resources dictionary.</p><p>Use nbformat directly when you need custom filtering. For example, you might omit cells tagged skip-export, exclude interactive diagnostics, or retain only cells tagged training-entrypoint.</p><p>Avoid naive code that loads JSON and joins every source field. On disk, multiline source can have different representations, and meaningful Markdown, metadata, encodings, or cell tags may require deliberate handling. nbformat normalizes these structures.</p><p>Programmatic conversion is particularly useful before submitting jobs. A pipeline can convert the notebook, record the notebook commit and environment lockfile, run a smoke test, and only then send the generated entrypoint to the training system.</p><h3>Convert multiple notebooks in a folder at once</h3><p>To convert every notebook in one directory, pass a shell glob:</p><pre>jupyter nbconvert --to script notebooks/*.ipynb</pre><p>To keep generated files separate from notebook sources, use an output directory:</p><pre>mkdir -p generated<br>jupyter nbconvert \<br> --to script \<br> --no-prompt \<br> --output-dir generated \<br> notebooks/*.ipynb</pre><p>This is safer than writing generated scripts over hand-maintained production files.</p><p>For nested experiment directories on Linux or macOS, use find with null-delimited filenames:</p><pre>find experiments -name &#39;*.ipynb&#39; -print0 |<br>while IFS= read -r -d &#39;&#39; notebook; do<br> jupyter nbconvert \<br> --to script \<br> --no-prompt \<br> --output-dir generated \<br> &quot;$notebook&quot;<br>done</pre><p>Quoting “$notebook” prevents spaces in filenames from being split into separate arguments.</p><p>For cross-platform repositories, use pathlib and subprocess:</p><pre>from pathlib import Path<br>import subprocess<br><br><br>source_root = Path(&quot;experiments&quot;)<br>output_root = Path(&quot;generated&quot;)<br><br><br>for notebook in source_root.rglob(&quot;*.ipynb&quot;):<br> relative_parent = notebook.parent.relative_to(source_root)<br> output_dir = output_root / relative_parent<br> output_dir.mkdir(parents=True, exist_ok=True)<br><br><br> subprocess.run(<br> [<br> &quot;jupyter&quot;,<br> &quot;nbconvert&quot;,<br> &quot;--to&quot;,<br> &quot;script&quot;,<br> &quot;--no-prompt&quot;,<br> &quot;--output-dir&quot;,<br> str(output_dir),<br> str(notebook),<br> ],<br> check=True,<br> )</pre><p>After batch conversion, validate the results:</p><pre>python -m compileall generated<br>ruff check generated</pre><p>Compilation finds syntax errors but does not prove that imports, data, GPUs, credentials, or checkpoints are available. Add lightweight smoke tests that load a small dataset sample, construct the model, run one batch, compute metrics, and write artifacts to a temporary directory.</p><p>Large notebooks and GPU-dependent notebooks may convert successfully while remaining impossible to test on a CPU-only CI runner. Make smoke-test behavior an explicit parameter rather than skipping validation entirely.</p><h3>Convert Python scripts back to notebooks and keep them in sync</h3><p>For round-trip conversion, use a synchronization tool rather than a one-time exporter. Jupytext can convert scripts to notebooks and pair .ipynb files with text representations.</p><p>Install it:</p><pre>python -m pip install jupytext</pre><p>Convert a notebook into a percent-format Python file:</p><pre>jupytext --to py:percent experiments/train.ipynb</pre><p>The resulting script uses explicit cell markers:</p><pre># %% [markdown]<br># Train a baseline classifier.<br><br><br># %%<br>from pathlib import Path<br>import torch<br><br><br># %%<br>seed = 42<br>torch.manual_seed(seed)</pre><p>Convert the script back:</p><pre>jupytext --to notebook experiments/train.py</pre><p>Pair both representations:</p><pre>jupytext --set-formats ipynb,py:percent experiments/train.ipynb</pre><p>Synchronize after changes:</p><pre>jupytext --sync experiments/train.ipynb</pre><p>Jupytext updates paired files and preserves notebook outputs in the .ipynb representation. Its percent format works naturally with editors that recognize # %%, including VS Code and PyCharm.</p><p>Do not depend on jupyter nbconvert — to notebook script.py as a general Python-to-notebook converter. The notebook exporter primarily processes notebook input and applies notebook preprocessors. Jupytext is the clearer tool for arbitrary script round trips.</p><p>Two-way synchronization improves diffs but introduces an authority question. Document whether the .py file, the .ipynb file, or the newest file wins. Marimo avoids this pair by representing the interactive notebook directly as executable Python.</p><h3>Choosing the best conversion tool for each workflow</h3><p>The best conversion tool depends on whether the operation is manual, automated, bidirectional, or part of the repository’s long-term design.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iqo6VwF0JI0LMi6xJfTXIA.png" /></figure><p>For simple automation, use nbconvert. For synchronized notebook and script files, use Jupytext. For a one-off save, use the Jupyter or VS Code interface.</p><p>Free online converters can be convenient, and some report that conversion happens in the browser. Do not upload proprietary model code, credentials, private data samples, unreleased results, or internal storage paths unless you have verified the tool’s implementation and security properties. Local conversion is easy enough that sensitive notebooks rarely justify this risk.</p><p>Use a .py file when the project needs imports, static analysis, testing, packaging, scheduler entrypoints, or clean code review. Use .ipynb when rich outputs and narrative exploration are central. Use paired text notebooks or Python-native notebooks when you need both interaction and reviewable source.</p><p>Common conversion use cases include:</p><ul><li>Production handoff</li><li>CI import and lint checks</li><li>Batch evaluation</li><li>Script-based training submission</li><li>Teaching materials</li><li>Model cards</li><li>Paper-artifact cleanup</li><li>Reproduction packages</li><li>Parameter sweeps</li></ul><p>Marimo is relevant when conversion itself has become part of every experiment. Its notebooks are Python files, execute according to variable dependencies, and can run as scripts without generating a second source representation.</p><h3>Edge cases that make converted scripts fail</h3><p>A generated script can be syntactically valid and still fail as an experiment. IPython magics are a frequent cause.</p><p>Remove %matplotlib inline; scripts do not need inline notebook rendering. For unattended plotting, select a non-interactive backend and save the figure:</p><pre>import matplotlib<br><br><br>matplotlib.use(&quot;Agg&quot;)</pre><p>Replace %cd with explicit path handling. Prefer configuration-based paths over changing the process directory.</p><p>Replace shell escapes:</p><pre>!nvidia-smi</pre><p>with:</p><pre>import subprocess<br><br><br>subprocess.run([&quot;nvidia-smi&quot;], check=True)</pre><p>Replace %%bash cells with a checked subprocess.run() call or move the commands into a dedicated script. Remove %load-ext autoreload and %autoreload; a fresh Python process imports code without notebook module state. Replace !pip install with a dependency file or environment-building step.</p><p>Some exporters translate magics into get_ipython() calls. Running the script with standard Python can then raise NameError, or raw magics can produce SyntaxError. Search before execution:</p><pre>grep -nE &#39;get_ipython|^[[:space:]]*[%!]&#39; experiments/train.py</pre><p>Paths are another common failure. A notebook may have been launched inside experiments/, while the script runs from the repository root or a scheduler workspace. Derive paths from a configured project root, command-line argument, or environment variable.</p><p>ML-specific checks include:</p><ul><li>Set random seeds before constructing datasets or models.</li><li>Make CUDA selection explicit.</li><li>Do not assume GPU index 0 is available.</li><li>Record distributed rank and world size.</li><li>Make checkpoint resumption a parameter.</li><li>Load logging credentials from the environment.</li><li>Verify that dataset mounts are in place before starting expensive training.</li><li>Use unique artifact directories for concurrent jobs.</li></ul><p>Wrap execution in main() and use argument parsing:</p><pre>def main():<br> config = load_config()<br> train(config)<br><br><br><br><br>if __name__ == &quot;__main__&quot;:<br> main()</pre><p>Add a smoke-test mode that uses a tiny data subset, one training batch, one evaluation batch, and a temporary output directory.</p><h3>From exported script to reproducible ML experiment</h3><p>The goal is not merely to produce a .py file. The result should be an entry point another researcher or remote worker can rerun from a clean process.</p><p>Refactor the exported source into this order:</p><ol><li>Standard-library and third-party imports</li><li>Configuration loading</li><li>Logging and experiment-tracking initialization</li><li>Deterministic seed setup</li><li>Dataset and data-loader construction</li><li>Model, optimizer, and scheduler construction</li><li>Checkpoint loading</li><li>Training</li><li>Evaluation</li><li>Artifact and metric persistence</li></ol><p>Move reusable functions into modules:</p><pre>research-repo/<br> configs/<br> baseline.yaml<br> src/<br> data.py<br> models.py<br> training.py<br> evaluation.py<br> experiments/<br> baseline.py<br> tests/<br> test_smoke.py</pre><p>Preserve useful notebook context. Markdown that explains label mappings, metric caveats, excluded examples, or checkpoint provenance should become comments, docstrings, configuration descriptions, or repository documentation. Do not discard the reasoning required to interpret the result.</p><p>Experiment tracking can be added around the stable entrypoint. MLflow, Weights &amp; Biases, custom JSON logs, and artifact stores are all workable options. At minimum, record:</p><ul><li>Git commit</li><li>Configuration</li><li>Package environment</li><li>Dataset version</li><li>Seed</li><li>Hardware and device details</li><li>Metrics</li><li>Checkpoint paths</li><li>Evaluation artifacts</li><li>Exit status</li></ul><p>Scripts commonly move to remote GPU workers, container platforms, or cluster schedulers. Avoid a workflow that requires SSH access, manual command copying, and terminal polling. The notebook or research platform should submit the explicit entry point, capture its configuration, expose logs and status, and return artifact locations.</p><p>For Malik’s workflow, Marimo keeps exploration and executable Python in the same file. It can run near the relevant CPU or GPU environment, while job submission and monitoring can be connected to the surrounding self-hosted compute platform. The important boundary is explicit: interactive analysis prepares a versioned Python program, and remote execution consumes that same program.</p><h3>A practical migration playbook for research repositories</h3><p>Treat a repository with many notebooks as a migration project rather than a file-conversion exercise.</p><ol><li><strong>Inventory notebooks.</strong></li></ol><p>List every notebook and classify it as active experiment, reusable analysis, report, tutorial, obsolete scratch work, or production dependency.</p><pre>find. -name &#39;*.ipynb&#39; -not -path &#39;./.venv/*&#39;</pre><p><strong>2. Mark the source of truth.</strong></p><p>For each active experiment, decide whether .ipynb, generated .py, paired Jupytext files, or Marimo .py notebooks are canonical. Record the decision in the repository documentation.</p><p><strong>3. Convert candidates.</strong></p><p>Use nbconvert for one-way migration or Jupytext when the Jupyter interface must remain active.</p><p><strong>4. Validate clean execution.</strong></p><p>Restart and run the original notebook, execute the generated script from a clean process, and compare metrics, checkpoints, sample counts, and artifact manifests.</p><p><strong>5. Extract shared code.</strong></p><p>Move model definitions, transforms, data loaders, metrics, and evaluators into importable modules. Notebooks and experiment scripts should orchestrate these functions rather than contain divergent copies.</p><p><strong>6. Automate checks.</strong></p><p>A practical CI job can:</p><pre>jjupyter nbconvert --to script --no-prompt notebooks/*.ipynb<br>python -m compileall generated<br>ruff check src generated<br>pytest -m smoke</pre><p>The smoke suite should avoid full GPU training. Test configuration parsing, small data samples, model construction, one forward pass, one optimization step, evaluation, and artifact writing.</p><ol><li>Control versioned outputs.</li></ol><p>Avoid committing large embedded notebook outputs unless they are required research artifacts. Strip transient outputs or keep the text representation canonical. Generated scripts should not be hand-edited unless they have formally replaced the notebook.</p><p>During review, ask whether a reader can identify the parameters, dataset dependencies, metrics, artifact paths, compute requirements, and likely failure modes without replaying an undocumented notebook session. If not, the migration is incomplete.</p><h3>Pick the conversion path that preserves trust</h3><p>Converting a.ipynb to a.py is straightforward. Use jupyter nbconvert — to script notebook.ipynb for the fastest command-line conversion. Use Jupyter or VS Code export for a one-off save, Jupytext for two-way synchronization, the nbconvert Python API for embedded automation, and shell globs or pathlib for folder-wide conversion.</p><p>The primary risk is not a visible conversion error. It is silent loss of context: hidden notebook state, changed execution order, omitted parameters, missing data paths, notebook-only magics, or evaluation logic that depended on manual inspection.</p><p>Always run the generated script in a clean environment. Compare metrics, sample counts, checkpoints, plots, and evaluation artifacts against a restart-and-run-all notebook execution. Then define which file is authoritative so the notebook and script cannot drift unnoticed.</p><p>If converting notebooks is constant overhead, use a workflow where interactive work is already stored as executable Python. Marimo keeps notebooks reviewable in Git, executes dependencies reactively, runs as a Python script, and can be placed close to the compute and job workflows used for training and evaluation.</p><h3>Sources</h3><ul><li><a href="https://docs.marimo.io/">marimo — Documentation for the Reactive Python Notebook — marimo</a></li><li><a href="https://nbformat.readthedocs.io/en/5.2.0/format_description.html">The Notebook file format — nbformat 5.2 documentation</a></li><li><a href="https://nbconvert.readthedocs.io/en/latest/usage.html">Using as a command line tool — nbconvert 7.17.1 documentation</a></li><li><a href="https://nbconvert.readthedocs.io/en/v7.17.0/config_options.html">Configuration options — nbconvert 7.17.0 documentation</a></li><li><a href="https://jupyterlab.readthedocs.io/en/3.6.x/user/export.html">Exporting Notebooks — JupyterLab 3.6.8 documentation</a></li><li><a href="https://code.visualstudio.com/docs/python/jupyter-support-py">Python Interactive window</a></li><li><a href="https://nbconvert.readthedocs.io/en/v7.6.0/api/exporters.html">Exporters — nbconvert 7.6.0 documentation</a></li><li><a href="https://jupytext.readthedocs.io/en/latest/paired-notebooks.html">Paired notebooks</a></li><li><a href="https://stackoverflow.com/questions/17077494/how-do-i-convert-a-ipython-notebook-into-a-python-file-via-commandline">How do I convert a IPython Notebook into a Python file via …</a></li><li><a href="https://discourse.jupyter.org/t/how-do-i-convert-and-save-as-notebooks-as-py-on-notebook-version-7-4-4/37597">How do i convert and save as Notebooks as .py on Notebook Version 7.4.4 — Notebook — Jupyter Community Forum</a></li><li><a href="https://www.runcell.dev/tool/jupyter-to-python">Jupyter to Python Converter (.ipynb → .py) — Free — Runcell</a></li><li><a href="https://stackoverflow.com/questions/62510114/converting-from-py-to-ipynb">python — converting from .py to .ipynb — Stack Overflow</a></li><li><a href="https://mljar.com/blog/convert-jupyter-notebook-python">Convert Jupyter Notebook to Python script in 3 ways — MLJAR Studio</a></li><li><a href="https://towardsdatascience.com/how-to-convert-a-python-jupyter-notebook-into-an-rmarkdown-file-abf826bd36de">How to convert a Python Jupyter notebook into an RMarkdown file</a></li><li><a href="https://jaketae.github.io/blog/jupyter-automation">Using Jupyter Notebook with Jekyll — Jake Tae — GitHub Pages</a></li><li><a href="https://discuss.python.org/t/how-do-you-convert-a-jupyter-notebook-project-into-an-executable/56353">How do you convert a jupyter notebook project into an executable?</a></li><li><a href="https://github.com/zed-industries/zed/discussions/30814">Survival kit for jupyter-notebooks devs in Zed #30814 — GitHub</a></li><li><a href="https://community.wolfram.com/groups/-/m/t/2562963">How to convert Mathematica notebook to Jupyter notebooks and vice versa? — Online Technical Discussion Groups — Wolfram Community</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6bbc1bca5cf7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/online-inference/convert-jupyter-notebook-to-python-for-reproducible-ml-experiments-6bbc1bca5cf7">Convert Jupyter Notebook to Python for reproducible ML experiments</a> was originally published in <a href="https://medium.com/online-inference">Online Inference</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Agentic loops in AI: Governance, feedback, and failure modes at scale]]></title>
            <link>https://medium.com/online-inference/agentic-loops-in-ai-governance-feedback-and-failure-modes-at-scale-f038e32add6c?source=rss----52acf6e3d9be---4</link>
            <guid isPermaLink="false">https://medium.com/p/f038e32add6c</guid>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[agentic-loop]]></category>
            <category><![CDATA[ai-loop]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[David Davies]]></dc:creator>
            <pubDate>Wed, 05 Aug 2026 15:20:58 GMT</pubDate>
            <atom:updated>2026-08-05T16:09:30.786Z</atom:updated>
            <content:encoded><![CDATA[<p>An agentic loop is an autonomous workflow in which an AI model reasons about a goal, acts through tools or APIs, observes the result, and adjusts its next step. Readers will learn how these loops execute, where they fail, and how production systems govern them. The useful property is not autonomy by itself. It is bounded autonomy supported by measurable feedback, explicit permissions, and reliable stopping conditions.</p><p>Unlike a single prompt‑response exchange, an agentic loop repeats a sequence of planning, action, observation, evaluation, and correction. The loop may inspect files, query databases, call services, run tests, request approval, or modify an external system.</p><p>An AI feedback loop is the broader process through which automated or human signals influence later decisions. Human‑in‑the‑loop AI, or HITL, specifically inserts people into that process for validation, correction, approval, or escalation. An agentic loop can use both mechanisms, but they are not interchangeable.</p><p>Production design requires more than prompt engineering. It includes runtime dataflow, workflow scheduling, model‑serving capacity, tool isolation, durable state, reviewer operations, and enterprise‑risk controls.</p><h3>What an agentic loop is in AI</h3><p>An agentic loop is the execution architecture that moves an AI agent from intent to action. It couples planning, tool selection, observation, memory, policy checks, and termination logic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1SLAkaP1I5wUFzgvDCd_Qg.png" /></figure><p>A one‑shot model receives an input and generates an output. An agent maintains state across multiple turns and can change its environment through external tools. For example, a code‑repair agent may read a repository, identify a failing function, edit a file, run tests, inspect the failure, and revise the patch.</p><p>A typical loop contains:</p><p>A user request and explicit task objective A system policy defining permissions and constraints A planner that proposes the next action A tool router that validates structured calls An executor or sandbox that performs the action Short‑term and durable memory An evaluator that scores the result An optional human reviewer for ambiguous or high‑impact decisions</p><p>Agents can be reactive, responding only to requests, or proactive, initiating work from events or schedules. Both forms need explicit goals, scoped permissions, budgets, and termination rules.</p><pre>User request<br> |<br> v<br>Policy and task initialization<br> |<br> v<br>Model planning &gt; Memory retrieval<br> |<br> v<br>Tool request &gt; Permission check<br> | |<br> | denied +&gt; Human escalation<br> v<br>Tool execution<br> |<br> v<br>Observation and evidence<br> |<br> v<br>Automated evaluation<br> |<br> + success &gt; Stop and report<br> |<br> + uncertain &gt; Human review<br> |<br> + retry &gt; Updated plan</pre><h3>Agentic loop vs traditional AI, automation, and HITL</h3><p>The main distinction is control flow. Traditional AI predicts an output. Deterministic automation follows a predefined procedure. Classic HITL routes selected decisions to a person. An agentic loop dynamically selects intermediate actions from goals, context, and observations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H0I1fZWfFKAQqZIc23D-bw.png" /></figure><p>An agentic loop can treat human feedback as one signal among unit tests, policy‑engine results, model critics, retrieval scores, and environment observations. Human review is therefore not necessarily present during every iteration.</p><p>The distinction matters because dynamic tool use introduces failure modes that fixed automation does not. The agent may select an inappropriate tool, carry incorrect state between steps, exceed its authority, or create a chain of individually plausible but collectively harmful actions. Accountability also becomes less obvious when a model chooses the path rather than following a procedure written by an engineer.</p><h3>Why the loop is a governance mechanism</h3><p>A production agentic loop governs which actions may occur before they affect the environment. Human review is not merely a confirmation dialog. It is a runtime state with defined entry conditions, reviewer authority, deadlines, evidence requirements, and recorded outcomes.</p><p>Governance controls commonly include:</p><p>Approval gates before irreversible actions Confidence thresholds for automatic execution Policy checks against structured tool arguments Audit logs covering every state transition Rollback hooks for reversible mutations Reviewer queues organized by risk and expertise Cost, time, and iteration budgets</p><p>Structured oversight is essential in security, finance, healthcare, and infrastructure operations. A plausible but incorrect recommendation is different from an agent automatically quarantining an endpoint, transferring funds, changing a clinical record, or deleting a production resource.</p><p>Without these controls, agents can hallucinate tool names or arguments, expose sensitive data through tool calls, bypass compliance requirements, or compound an early error across later steps. Human reviewers do not need to examine every routine action, but organizations should require approval for decisions whose impact exceeds the agent’s tested authority.</p><h3>The runtime cycle: reason, act, observe, evaluate</h3><p>The reason‑act‑observe‑evaluate cycle is the core runtime path.</p><ol><li>Reason: The model interprets the goal, current state, retrieved context, and previous observations.</li><li>Act: It selects a permitted tool and emits structured arguments.</li><li>Observe: The runtime executes the tool and returns normalized output.</li><li>Evaluate: Automated checks or human reviewers determine whether to stop, retry, correct, or escalate.</li></ol><p>Each iteration consumes model tokens, KV‑cache capacity, scheduler time, memory reads, tool latency, policy decisions, and evaluator calls. Loop count is therefore a production‑cost driver. A task with eight iterations is not one inference request. It may include eight planner calls, several tool invocations, multiple retrieval operations, and final verification.</p><p>Short loops work well for bounded tasks such as fixing a unit test or locating a document. Investigations, research workflows, and multi‑agent systems have longer horizons. They need stricter cost controls because uncertainty and state drift increase with each step.</p><p>Automated feedback may come from unit tests, static analyzers, schema validators, retrieval scores, reward models, policy engines, or independent verifier models.</p><pre>state = initialize_task()<br>allowed_tools = [&quot;read_file&quot;, &quot;edit_patch&quot;, &quot;run_tests&quot;]<br>max_iterations = 8<br><br>for iteration in range(max_iterations):<br> plan = planner(state)<br> if plan.tool not in allowed_tools:<br> return escalate(&quot;Tool is not allowed&quot;, state)<br> if not policy_engine.approve(plan, state):<br> return escalate(&quot;Policy denied action&quot;, state)<br> observation = execute_in_sandbox(plan)<br> state.append(plan, observation)<br> score = evaluator(state)<br> audit_log.write(iteration, plan, observation, score)<br> if score.success and score.confidence &gt;= 0.90:<br> return complete(state)<br> if score.high_impact or score.confidence &lt; 0.50:<br> return escalate(&quot;Human judgment required&quot;, state)<br>return escalate(&quot;Maximum iteration count reached&quot;, state)</pre><h3>The three phases of Claude’s agentic loop</h3><p>A Claude‑style agentic loop can be understood through three phases:</p><ol><li>Reasoning or planning: Claude analyzes the task, available context, constraints, and possible next actions.</li><li>Action through tools: The runtime permits Claude to read a file, search content, execute an approved command, or call another tool.</li><li>Observation and self‑correction: Claude interprets the result, checks whether it supports the goal, and revises its plan.</li></ol><p>Exact product implementations vary, but this abstraction identifies where engineers should attach controls. Prompt and context constraints apply during planning. Allowlists, schemas, credentials, and approval gates apply during action. Tests, validators, and evidence checks apply during observation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x7R2FpvbOxVDZRLhRkLOwA.png" /></figure><p>These phases generalize beyond Claude. The model does not need unrestricted access to work agentically. In fact, narrow tools with strong schemas usually create a more reliable loop than broad shell or network access.</p><h3>How the agentic loop works in Claude Code</h3><p>In Claude Code, the loop becomes visible through repository operations. The agent inspects files, infers developer intent, proposes or applies edits, runs approved commands, reads test output, and revises the patch.</p><p>A typical sequence is:</p><pre>Read issue &gt; Inspect repository &gt; Locate relevant code<br>&gt; Edit bounded files &gt; Run tests &gt; Read failure<br>&gt; Correct patch &gt; Run lint and type checks &gt; Present diff</pre><p>Shell commands, file writes, dependency installations, secrets, and network access need separate permission boundaries. A safe configuration can permit repository reads and test execution while requiring approval for package installation, credential access, network calls, and changes outside the working directory.</p><p>Tests, linters, type checks, and build logs provide automated feedback. They reduce subjective review, but they do not prove that a patch is correct. Tests may be stale or flaky. Stack traces may point at a symptom rather than the cause. Broad refactors can satisfy tests while violating hidden repository conventions.</p><p>The final review should therefore include the diff, changed‑file list, commands executed, test results, and any unresolved assumptions.</p><h3>Dataflow architecture for agents, memory, tools, and feedback</h3><p>A production agentic loop is a distributed system rather than a prompt template. The orchestrator owns task state, retries, budgets, permissions, audit records, and escalation. The model proposes actions but should not control its own authority.</p><pre>Control plane Data plane<br>++ ++<br>| Workflow orchestrator|&gt;| Modelserving endpoint|<br>| Policy engine | ++<br>| State machine | |<br>| Budget manager | v<br>| Human review queue | ++<br>+++ | Tool gateway |<br> | +++<br> v |<br>++ v<br>| Durable task store | ++<br>| Audit and evaluation|&lt;| Sandboxes and APIs |<br>++ ++</pre><p>State generally includes conversation history, scratchpad summaries, durable task records, tool outputs, retrieved documents, embeddings, evaluator scores, and reviewer annotations.</p><p>Ephemeral memory exists only inside the current context window. It disappears when the request ends or the context is truncated. Durable memory persists across tasks and can affect future actions. That makes it more powerful and more dangerous. Durable entries need provenance, retention rules, correction mechanisms, and access controls.</p><p>Models and tools should exchange structured messages rather than unconstrained text:</p><pre>{<br> &quot;tool&quot;: &quot;run_tests&quot;,<br> &quot;arguments&quot;: {<br> &quot;suite&quot;: &quot;tests/unit&quot;,<br> &quot;timeout_seconds&quot;: 300<br> },<br> &quot;task_id&quot;: &quot;repair1042&quot;,<br> &quot;requested_by&quot;: &quot;plannerv3&quot;<br>}</pre><p>Structured records improve validation, replay, policy enforcement, and incident investigation.</p><h3>Automated feedback channels</h3><p>Automated feedback is a machine‑readable signal returned without waiting for a person. Examples include test results, schema validation, retrieval precision, policy decisions, static‑analysis findings, environment state, and verifier‑model scores.</p><p>It works particularly well when success is externally testable:</p><p>Code generation with unit and integration tests Data extraction with typed schemas Recommendation ranking with offline metrics Security triage with enrichment and detection rules Operational tasks with read‑only checks and dry runs</p><p>The main danger is proxy optimization. An agent may satisfy a weak evaluator without satisfying the real objective. It can produce code that passes stale tests, retrieve documents that match keywords but not intent, or optimize recommendation metrics that do not represent user value.</p><p>Research on Agentic Feedback Loop modeling created recommendation and user agents that exchanged recommendations, rationales, and feedback. Across LastFM, Steam, and MovieLens, the paper reported an 11.52% recommendation improvement and a 21.12% user‑simulation improvement over its baselines. Those results support iterative feedback within that experimental setting, but they do not establish equivalent gains for unrelated enterprise workloads.</p><h3>Human feedback channels</h3><p>Human feedback includes expert validation, corrections, annotations, approvals, rejections, red‑team findings, and post‑incident conclusions.</p><p>Humans should enter the loop when:</p><p>Confidence is low Impact is high or irreversible Policy is ambiguous Evaluators disagree The event represents a novel attack or edge case A regulated decision requires accountable review</p><p>Review should use structured rubrics rather than free‑form comments. Capture the decision, severity, confidence, rationale, applicable policy, corrected action, and reviewer role. Periodically measure reviewer agreement and recalibrate ambiguous labels.</p><p>These records can support supervised fine‑tuning, reinforcement learning from human feedback, new evaluation cases, prompt revisions, and policy‑rule updates. The rationale is often more valuable than a simple approval because it explains what the system failed to understand.</p><h3>Step-by-step design for a production agentic loop</h3><p>Building an agentic loop starts with constraints rather than prompts. The target is a bounded workflow with observable state, deterministic permissions, measurable feedback, and clear human escalation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*anstzTboC5NHHG7PvUXh8Q.png" /></figure><p>The following tutorial uses a code‑repair agent that may inspect a Python repository, propose a patch, and run tests. It cannot merge code, modify deployment configuration, access secrets, or connect to the public network.</p><p>The architecture can run on LangGraph, Temporal, Ray, Kubernetes Jobs, or a custom state‑machine service. The same process also applies to SOC triage, data‑pipeline remediation, recommendation simulation, customer‑support routing, and research‑assistant workflows.</p><h3>Step 1: Define task boundaries, policies, and stop conditions</h3><p>Write the task contract before connecting a model to tools. Specify the objective, allowed actions, forbidden actions, required evidence, success criteria, and escalation conditions.</p><pre>task:<br> name: repairpythonunittest<br> objective: produce a minimal patch that fixes the reported failure<br><br>allowed_actions:<br>  read_repository_files<br>  search_repository<br>  write_patch_in_workspace<br>  run_unit_tests<br>  run_linter<br>  run_type_checker<br>forbidden_actions:<br>  merge_code<br>  push_to_remote<br>  read_secrets<br>  access_public_network<br>  modify_deployment_files<br>success:<br>  reported_test_passes<br>  full_unit_suite_passes<br>  linter_passes<br>  changed_files_are_in_scope<br>limits:<br> max_iterations: 8<br> max_runtime_minutes: 20<br> max_model_cost_usd: 3.00<br>escalate_when:<br>  confidence_below_0.50<br>  same_failure_repeats_3_times<br>  dependency_installation_required<br>  security_sensitive_file_detected</pre><p>Enforce these policies in runtime code or policy‑as‑code. A natural‑language instruction such as “do not read secrets” is not an access‑control mechanism.</p><p>Create an audit schema containing the task ID, requesting user, model and prompt versions, retrieved context, tool calls, observations, evaluator scores, state transitions, and reviewer decisions.</p><p>The expected output of this step is a version‑controlled task contract and a test demonstrating that forbidden actions are rejected before execution.</p><h3>Step 2: Connect tools, memory, and execution sandboxes</h3><p>Place a gateway between the model and every tool. The gateway should validate argument schemas, enforce allowlists, inject scoped credentials, record inputs and outputs, and apply timeouts.</p><p>Give each tool a narrow purpose. Prefer read_file(path) and run_unit_tests(target) over unrestricted shell access.</p><p>Use three memory classes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yh-D88nQkte7HsbppnOZDQ.png" /></figure><p>Run code and commands inside an isolated workspace. Disable public networking by default. Mount the repository as a task‑specific copy and expose secrets only through narrowly scoped tool operations.</p><p>Mutation tools need idempotency keys so retries do not duplicate actions. Define compensating operations where possible. A deployment tool might support apply, verify, and rollback; a ticketing tool might store the created ticket ID and return it on retries.</p><p>The expected output is a tool registry showing each tool’s schema, credential scope, timeout, retry policy, side effects, and rollback behavior.</p><h3>Step 3: Add evaluators, human gates, and audit trails</h3><p>Run automated evaluators before human review. For the repair agent, use the reported test, complete unit suite, linter, type checker, changed‑file allowlist, and a patch‑size limit.</p><p>Then map risk and confidence to an action:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AFYmebPbUAwOZ9r-t6Caww.png" /></figure><p>Configure the review form with a decision, severity, rationale, corrected action, and policy label. Give high‑risk queues shorter service‑level targets than routine patch review.</p><p>Store complete traces in an immutable task record. Evaluation platforms such as W&amp;B Weave can capture model calls, tool spans, scores, and annotated examples. Promote useful traces into regression‑evaluation datasets before changing the model, prompt, tool schema, or policy.</p><p>A successful trace should resemble:</p><pre>Task repair1042<br>Iterations: 4<br>Files changed: 1<br>Policy violations: 0<br>Unit tests: passed<br>Lint: passed<br>Type check: passed<br>Evaluator confidence: 0.94<br>Final state: awaiting developer approval</pre><h3>Human‑in‑the‑loop AI in real workflows</h3><p>Deployed workflows rarely choose between complete automation and complete manual review. Routine cases pass through automated checks. Uncertain, novel, regulated, or high‑impact cases go to humans. Both outcomes become feedback for future evaluations and policies.</p><p>Early deployments should route a relatively large sample to reviewers. Teams can reduce that rate after measuring false approvals, false rejections, evaluator disagreement, policy coverage, and drift. Periodic sampling should continue even when confidence is high.</p><p>Agentic AI does not need a person to approve every action. It does need accountable human authority over decisions that exceed the agent’s validated scope.</p><p>Skipping this maturity process creates predictable problems. Review queues become overloaded, reviewers begin rubber‑stamping decisions, automation bias goes unmeasured, and no team owns unusual failures. An escalation rule is not a control if no qualified reviewer is scheduled to receive it.</p><h3>Case pattern: security operations and the CrowdStrike feedback flywheel</h3><p>Security operations demonstrate how automated and expert feedback can share one loop. An AI agent can enrich an alert with process ancestry, endpoint history, identity activity, and threat intelligence. It can generate hypotheses and recommend investigation steps. A SOC analyst or threat hunter then validates intent, identifies tradecraft, and determines severity.</p><p>The operational loop looks like this:</p><pre>Detection &gt; Automated enrichment &gt; Hypothesis generation<br>&gt; Analyst validation &gt; Containment decision<br>&gt; Updated labels and detections &gt; Future triage</pre><p>The CrowdStrike pattern emphasizes expert‑annotated security data and continuous analyst validation. Analysts contribute context that raw event records do not contain, including why an action is suspicious and how it relates to adversary behavior. Their decisions can improve future triage and escalation.</p><p>Governance remains essential. Read‑only enrichment can run automatically. Endpoint containment, account suspension, remediation, or customer‑impacting actions should require explicit approval or a narrowly defined policy threshold with complete audit records.</p><h3>Case pattern: recommendation and user simulation feedback loops</h3><p>Recommendation workflows show that feedback does not always come from a human expert. In Agentic Feedback Loop research, a recommendation agent proposes items and rationales. A user agent responds with preferences and updates its simulated state. The recommendation agent then updates its understanding and tries again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XefRdN6iU0dCPw9lqQByyg.png" /></figure><p>The experiments covered LastFM, Steam, and MovieLens and reported gains in both recommendation performance and user simulation relative to the evaluated baselines.</p><p>This differs from enterprise HITL because a simulated user is another model, not an accountable reviewer. The feedback loop can help test hypotheses and generate offline interactions, but it can also encode assumptions from its prompts, training data, or memory.</p><p>Teams should validate simulated results against held‑out behavioral data and controlled online experiments. They should also monitor popularity bias, position effects, user‑segment performance, and differences between simulated and observed behavior.</p><h3>What breaks at scale: Scheduler, kernels, and collectives</h3><p>At scale, the unit of work is no longer one inference request. One task may expand into dozens of planner calls, tool executions, retrieval operations, evaluator checks, and reviewer pauses.</p><p>Agentic workloads are bursty because loop counts vary. Tool latency is unpredictable. Context grows over time. Human review can pause execution for minutes or hours. Different tasks may require radically different model sizes and sandbox durations.</p><p>Small inefficiencies compound across the loop:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OhTqeofcFe0gl2J2py39EA.png" /></figure><h3>Scheduler pressure, queues, and backpressure</h3><p>The workflow scheduler must control task queues, priority classes, per‑tenant quotas, maximum loop depth, retries, timeouts, and dead‑letter handling.</p><p>Backpressure can originate from rate‑limited APIs, overloaded vector stores, slow sandboxes, model‑serving queues, or human reviewers. The orchestrator should pause or degrade gracefully rather than continue producing work that downstream systems cannot consume.</p><p>Naive retries amplify incidents. If an external API fails, thousands of agents may retry simultaneously. If a tool partially succeeded before timing out, retries may duplicate tickets, payments, deployments, or notifications.</p><p>Use exponential backoff with jitter, idempotency keys, circuit breakers, bounded concurrency, and admission control. Cache immutable observations when safe. Route repeatedly failing tasks to a dead‑letter queue with the complete trace rather than asking the model to attempt increasingly speculative actions.</p><h3>GPU inference kernels, KV cache, and tensor‑parallel collectives</h3><p>At the GPU layer, an agentic loop becomes a chain of inference bursts. Every planning, reflection, summarization, and evaluator step consumes prefill compute, decode capacity, KV cache, and scheduler slots.</p><p>Long accumulated contexts increase prefill latency. Active sessions hold KV‑cache pages, while irregular sequence lengths fragment available capacity. Continuous batching can improve throughput, but large prefill jobs may delay short decode requests unless the serving scheduler separates or prioritizes them.</p><p>When a model spans multiple GPUs, tensor‑parallel execution adds collective communication. Attention and multilayer‑perceptron layers may require all‑reduce or all‑gather operations. Collective latency can gate token generation when communication cannot overlap effectively with compute.</p><p>Use smaller models for classification, routing, summarization, and routine evaluator passes when evaluation shows that they meet accuracy requirements. Reserve larger models for planning, ambiguous cases, and high‑impact decisions.</p><p>Report serving results only with complete conditions: model and model revision, GPU SKU, precision, tensor and pipeline parallelism, batch size, input and output sequence lengths, tokens/sec, time to first token, and p50/p99 inter‑token latency.</p><h3>Infrastructure pattern on Kubernetes‑native GPU clusters</h3><p>A scalable deployment separates model serving from agent control. Run model servers, loop workers, sandboxes, evaluators, policy services, and review applications as independent Kubernetes workloads.</p><p>On CoreWeave, model‑serving pools can use bare‑metal NVIDIA H100 SXM 80GB, H200 141GB, B200, or GB200 NVL72 infrastructure according to model memory and parallelism requirements. Kubernetes‑native orchestration provides workload isolation and independent scaling. Non‑blocking InfiniBand is relevant when sharded inference depends on latency‑sensitive collectives.</p><p>A model‑server scheduling boundary can look like this:</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br> name: plannermodel<br>spec:<br> replicas: 2<br> selector:<br> matchLabels:<br> app: plannermodel<br> template:<br> metadata:<br> labels:<br> app: plannermodel<br> spec:<br> nodeSelector:<br> nvidia.com/gpu.product: NVIDIAH200<br> containers:<br>  name: server<br> image: registry.example.com/agentmodelserver:pinneddigest<br> args:<br>  model=/models/planner<br>  tensorparallelsize=8<br> resources:<br> limits:<br> nvidia.com/gpu: &quot;8&quot;<br> cpu: &quot;64&quot;<br> memory: 512Gi<br> volumeMounts:<br>  name: scratch<br> mountPath: /scratch<br> volumes:<br>  name: scratch<br> emptyDir: {}</pre><p>Validate the GPU label against the cluster’s discovered labels, and pin images and model artifacts by digest. Bind scratch space to NVMe local storage when sandboxes need fast build artifacts or short‑lived tool outputs. Store durable traces, evaluation datasets, and model artifacts in CoreWeave AI Object Storage rather than local pod storage.</p><p>Use SUNK when Slurm‑based red‑team sweeps, batch evaluations, or offline fine‑tuning jobs need to share Kubernetes‑managed GPU capacity. Keep online agent traffic isolated from those batch queues through quotas and priority classes.</p><h3>Risks, edge cases, and accountability controls</h3><p>Trust, transparency, and accountability matter because agent decisions compound. One poisoned observation can alter memory, produce an incorrect plan, trigger a tool, and influence every later step.</p><p>Technical controls include scoped credentials, immutable traces, model‑version pinning, signed tool outputs, red‑team tests, rollback procedures, and strict stop conditions.</p><p>Organizational controls are equally important. Every tool‑owning workflow needs an accountable service owner, a staffed escalation path, and an incident process covering AI‑initiated actions.</p><h3>Trust, transparency, and traceability</h3><p>Trust means calibrated reliance based on measured performance. It does not mean that users find the model’s language persuasive.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t-63iiX1NlMkx0NJntr9lg.jpeg" /></figure><p>An inspectable loop shows which model acted, what evidence it used, which tools it called, what arguments it supplied, which policy permitted the action, what evaluators returned, and whether a person approved an exception.</p><p>Reasoning summaries can help reviewers understand the decision without treating hidden model reasoning as authoritative evidence. Tool results, source records, tests, and policy outcomes are stronger audit artifacts.</p><p>Trace replay should reconstruct the prompt template, model version, retrieved context, tool inputs and outputs, evaluator results, memory updates, and final decision. Pin mutable dependencies or store normalized snapshots where legally permitted.</p><p>Logging creates privacy and security trade‑offs. Prompts may contain personal data, credentials, medical information, source code, or incident details. Redact secrets before persistence, encrypt traces, enforce role‑based access, define retention limits, and separate debugging access from routine application access.</p><h3>Adversarial and operational failure modes</h3><p>Prompt injection can arrive through retrieved documents, web pages, support tickets, emails, logs, or tool responses. Untrusted content may tell the agent to ignore policy, reveal secrets, or call a dangerous tool.</p><p>The runtime must treat observations as data rather than authority. Isolate retrieved content, validate tool responses against schemas, and keep permission decisions outside the model.</p><p>Operational faults create similar risks. Tools can return partial results, time out after committing a change, race with another task, or serve stale cached state. Retries can duplicate side effects. Reviewer queues can fill while tasks continue waiting with outdated evidence.</p><p>Multi‑agent systems add another failure mode. Agents may optimize conflicting goals, repeat each other’s unsupported claims, or interpret agreement as validation. Consensus among models that share context and failure modes is not independent evidence.</p><p>Mitigations include policy‑as‑code, content isolation, signed tool responses, transaction boundaries, idempotency keys, dry‑run modes, quorum review for high‑impact actions, and chaos tests that inject timeouts, malformed outputs, stale data, duplicate events, and unavailable reviewers.</p><h3>Closing thoughts</h3><p>An agentic loop is a runtime and governance architecture, not simply an autonomous chat pattern. It repeatedly combines reasoning, action, observation, evaluation, and correction while maintaining state and interacting with external systems.</p><p>This dynamic behavior distinguishes agentic AI from traditional inference and deterministic automation. Because the agent chooses intermediate actions, it requires stronger permissions, observability, stopping conditions, and accountability.</p><p>Reliable implementations use bounded authority, structured tool contracts, measurable automated feedback, risk‑based human gates, durable audit trails, and rollback‑capable execution. Human‑in‑the‑loop AI should concentrate expert judgment on ambiguous, novel, regulated, or irreversible decisions rather than reviewing every routine step.</p><p>Enterprise adoption ultimately depends on engineering the loop as one system. The model, workflow scheduler, GPU‑serving layer, tool infrastructure, feedback data, reviewer operation, and accountability model must work together. If any one of those layers is unbounded or unowned, autonomy can amplify failures faster than feedback can correct them.</p><h3>Sources</h3><ul><li><a href="https://imerit.ai/resources/blog/the-rise-of-agentic-ai-why-human-in-the-loop-still-matters-una">The Rise of Agentic AI: Why Human‑in‑the‑Loop Still Matters ‑ iMerit</a></li><li><a href="https://arxiv.org/html/2410.20027v2">Agentic Feedback Loop Modeling Improves Recommendation and User Simulation</a></li><li><a href="https://www.crowdstrike.com/en-us/blog/inside-the-human-ai-feedback-loop-powering-crowdstrike-agentic-security">Inside the Human‑AI Feedback Loop Powering Agentic Security</a></li><li><a href="https://www.elementum.ai/blog/human-in-the-loop-agentic-ai">Human‑in‑the‑Loop AI Agents: Deploying Agentic AI With Control</a></li><li><a href="https://www.ibm.com/think/topics/human-in-the-loop">What Is Human In The Loop (HITL)? ‑ IBM</a></li><li><a href="https://cobusgreyling.medium.com/ai-agents-with-human-in-the-loop-f910d0c0384b">AI Agents With Human In The Loop ‑ Cobus Greyling ‑ Medium</a></li><li><a href="https://brooker.co.za/blog/2026/05/18/whats-easy-whats-hard.html">What’s Easy Now? What’s Hard Now? ‑ Marc’s Blog ‑ brooker.co.za</a></li><li><a href="https://medium.com/@tahirbalarabe2/human-in-the-loop-agentic-systems-explained-db9805dbaa86">Human‑in‑the‑Loop Agentic Systems Explained | by Tahir | Medium</a></li><li><a href="https://hai.stanford.edu/ai-definitions/what-is-human-in-the-loop">What is Human‑in‑the‑Loop? ‑ Stanford HAI</a></li><li><a href="https://medium.com/@visrow/agentic-ai-and-human-in-the-loop-a-practical-java-implementation-guide-2026-21cf6d576b70">Agentic AI and Human-in-the-Loop: A Practical Java Implementation Guide [2026]</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f038e32add6c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/online-inference/agentic-loops-in-ai-governance-feedback-and-failure-modes-at-scale-f038e32add6c">Agentic loops in AI: Governance, feedback, and failure modes at scale</a> was originally published in <a href="https://medium.com/online-inference">Online Inference</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>